31 TableFactor::TableFactor() {}
37 cardinalities_(potentials.cardinalities_) {
49 double denom = table.
size();
53 denominators_.insert(std::pair<Key, double>(dkey.first, denom));
61 const std::vector<double>&
table) {
64 const uint64_t nnz = std::count_if(table.begin(), table.end(),
68 if (table[
i] != 0) sparse_table.insert(
i) = table[
i];
70 sparse_table.pruned();
71 sparse_table.data().squeeze();
78 std::vector<double> ys;
79 std::istringstream iss(table);
80 std::copy(std::istream_iterator<double>(iss), std::istream_iterator<double>(),
81 std::back_inserter(ys));
87 if (!dynamic_cast<const TableFactor*>(&other)) {
90 const auto&
f(static_cast<const TableFactor&>(other));
100 if (values.find(it->first) != values.end()) {
101 idx += card * values.at(it->first);
112 for (
auto it =
keys_.rbegin(); it !=
keys_.rend(); ++it) {
113 if (values.find(*it) != values.end()) {
114 idx += card * values.at(*it);
139 std::vector<double>
table;
150 if (parent_keys.empty())
return *
this;
155 for (
auto it =
keys_.rbegin(); it !=
keys_.rend(); ++it) {
156 if (parent_assign.find(*it) != parent_assign.end()) {
157 unique += parent_assign.at(*it) * card;
164 std::sort(parent_keys.begin(), parent_keys.end());
166 parent_keys.begin(), parent_keys.end(),
167 std::back_inserter(child_dkeys));
172 child_card *= child_dkey.second;
174 child_sparse_table_.
reserve(child_card);
181 if (parent_unique == unique) {
183 child_sparse_table_.
insert(idx) = it.value();
187 child_sparse_table_.
pruned();
189 return TableFactor(child_dkeys, child_sparse_table_);
197 return (a == 0 || b == 0) ? 0 : (a /
b);
206 cout <<
" ]" << endl;
209 for (
auto&& kv : assignment) {
210 cout <<
"(" <<
formatter(kv.first) <<
", " << kv.second <<
")";
212 cout <<
" | " << it.value() <<
" | " << it.index() << endl;
228 unordered_map<uint64_t, AssignValList> map_f =
229 f.
createMap(contract_dkeys, f_free_dkeys);
232 for (
auto u_dkey : union_dkeys) card *= u_dkey.second;
234 mult_sparse_table.
reserve(card);
238 if (map_f.find(contract_unique) == map_f.end())
continue;
239 for (
auto assignVal : map_f[contract_unique]) {
241 mult_sparse_table.
insert(union_idx) = op(it.value(), assignVal.second);
245 mult_sparse_table.
pruned();
248 return TableFactor(union_dkeys, mult_sparse_table);
257 back_inserter(contract));
267 back_inserter(free));
285 for (
auto it = union_keys.rbegin(); it != union_keys.rend(); it++) {
286 if (f_free.find(it->first) == f_free.end()) {
289 union_idx += f_free.at(it->first) * card;
300 unordered_map<uint64_t, AssignValList> map_f;
307 for (
auto&
key : free)
310 if (map_f.find(unique_rep) == map_f.end()) {
311 map_f[unique_rep] = {make_pair(free_assignments, it.value())};
313 map_f[unique_rep].push_back(make_pair(free_assignments, it.value()));
322 if (dkeys.empty())
return 0;
324 for (
auto it = dkeys.rbegin(); it != dkeys.rend(); it++) {
333 if (assignments.empty())
return 0;
335 for (
auto it = assignments.rbegin(); it != assignments.rend(); it++) {
336 unique_rep += it->second * card;
354 if (nrFrontals >
size()) {
355 throw invalid_argument(
356 "TableFactor::combine: invalid number of frontal " 358 to_string(nrFrontals) +
", nr.keys=" + std::to_string(
size()));
363 for (
auto i = nrFrontals;
i <
keys_.size();
i++) {
373 double new_val = op(combined_table.
coeff(idx), it.value());
374 combined_table.
coeffRef(idx) = new_val;
379 return std::make_shared<TableFactor>(remain_dkeys, combined_table);
385 if (frontalKeys.size() >
size()) {
386 throw invalid_argument(
387 "TableFactor::combine: invalid number of frontal " 389 std::to_string(frontalKeys.size()) +
390 ", nr.keys=" + std::to_string(
size()));
396 if (std::find(frontalKeys.begin(), frontalKeys.end(),
key) ==
408 double new_val = op(combined_table.
coeff(idx), it.value());
409 combined_table.
coeffRef(idx) = new_val;
414 return std::make_shared<TableFactor>(remain_dkeys, combined_table);
426 std::vector<std::pair<Key, size_t>> pairs =
discreteKeys();
428 std::vector<std::pair<Key, size_t>> rpairs(pairs.rbegin(), pairs.rend());
431 std::vector<std::pair<DiscreteValues, double>>
result;
432 for (
const auto& assignment : assignments) {
433 result.emplace_back(assignment,
operator()(assignment));
443 if (std::find(result.begin(), result.end(), dkey) == result.end()) {
444 result.push_back(dkey);
459 ss << keyFormatter(
key) <<
"|";
465 for (
size_t j = 0;
j <
size();
j++) ss <<
":-:|";
473 size_t index = assignment.at(
key);
476 ss << it.value() <<
"|\n";
487 ss <<
"<div>\n<table class='TableFactor'>\n <thead>\n";
492 ss <<
"<th>" << keyFormatter(
key) <<
"</th>";
494 ss <<
"<th>value</th></tr>\n";
497 ss <<
" </thead>\n <tbody>\n";
504 size_t index = assignment.at(
key);
507 ss <<
"<td>" << it.value() <<
"</td>";
510 ss <<
" </tbody>\n</table>\n</div>";
516 const size_t N = maxNrAssignments;
519 vector<pair<Eigen::Index, double>> probabilities;
523 probabilities.emplace_back(it.index(), it.value());
527 if (probabilities.size() <=
N)
return *
this;
530 sort(probabilities.begin(), probabilities.end(),
531 [](
const std::pair<Eigen::Index, double>&
a,
532 const std::pair<Eigen::Index, double>&
b) {
533 return a.second >
b.second;
537 if (probabilities.size() >
N) probabilities.resize(N);
541 pruned_vec.
reserve(probabilities.size());
544 for (
const auto& prob : probabilities) {
545 pruned_vec.insert(prob.first) = prob.second;
TableFactor choose(const DiscreteValues assignments, DiscreteKeys parent_keys) const
Create a TableFactor that is a subset of this TableFactor.
const gtsam::Symbol key('X', 0)
std::string markdown(const KeyFormatter &keyFormatter=DefaultKeyFormatter, const Names &names={}) const override
Render as markdown table.
Scalar & insert(Index row, Index col)
double operator()(const DiscreteValues &values) const override
Evaluate probability distribution, sugar.
static Eigen::SparseVector< double > Convert(const std::vector< double > &table)
std::map< Key, size_t > denominators_
Map of Keys and their denominators used in keyValueForIndex.
std::string html(const KeyFormatter &keyFormatter=DefaultKeyFormatter, const Names &names={}) const override
Render as html table.
Scalar coeff(Index row, Index col) const
DecisionTreeFactor toDecisionTreeFactor() const override
Convert into a decisiontree.
TableFactor apply(const TableFactor &f, Binary op) const
void print(const std::string &s="TableFactor:\, const KeyFormatter &formatter=DefaultKeyFormatter) const override
print
KeyVector keys_
The keys involved in this factor.
double evaluate(const DiscreteValues &values) const
std::shared_ptr< TableFactor > shared_ptr
DiscreteValues findAssignments(const uint64_t idx) const
Find DiscreteValues for corresponding index.
EIGEN_DEVICE_FUNC const LogReturnType log() const
static std::vector< DiscreteValues > CartesianProduct(const DiscreteKeys &keys)
Return a vector of DiscreteValues, one for each possible combination of values.
std::unordered_map< uint64_t, AssignValList > createMap(const DiscreteKeys &contract, const DiscreteKeys &free) const
DiscreteKeys sorted_dkeys_
Sorted DiscreteKeys to use internally.
uint64_t uniqueRep(const DiscreteKeys &keys, const uint64_t idx) const
Create unique representation.
std::vector< std::pair< DiscreteValues, double > > enumerate() const
Enumerate all values into a map from values to double.
const KeyFormatter & formatter
void reserve(Index reserveSize)
bool equals(const DiscreteFactor &other, double tol=1e-9) const override
equality
const SparseView< Derived > pruned(const Scalar &reference=Scalar(0), const RealScalar &epsilon=NumTraits< Scalar >::dummy_precision()) const
std::map< Key, size_t > cardinalities_
Map of Keys and their cardinalities.
double error(const DiscreteValues &values) const
Calculate error for DiscreteValues x, is -log(probability).
size_t cardinality(Key j) const
Eigen::SparseVector< double > sparse_table_
SparseVector of nonzero probabilities.
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 ...
unsigned __int64 uint64_t
DiscreteKeys freeDkeys(const TableFactor &f) const
Return keys in free mode.
Point2(* f)(const Point3 &, OptionalJacobian< 2, 3 >)
DiscreteKeys discreteKeys() const
Return all the discrete keys associated with this factor.
std::function< double(const double, const double)> Binary
std::function< std::string(Key)> KeyFormatter
Typedef for a function to format a key, i.e. to convert it to a string.
TableFactor prune(size_t maxNrAssignments) const
Prune the decision tree of discrete variables.
static std::stringstream ss
std::uint64_t index() const
static double safe_div(const double &a, const double &b)
DiscreteValues::Names Names
Translation table from values to strings.
shared_ptr combine(size_t nrFrontals, Binary op) const
DiscreteKeys unionDkeys(const TableFactor &f) const
Return union of DiscreteKeys in two factors.
TableFactor operator*(const TableFactor &f) const
multiply two TableFactors
static std::string Translate(const Names &names, Key key, size_t index)
Translate an integer index value for given key to a string.
double findValue(const DiscreteValues &values) const
Find value for corresponding DiscreteValues.
const DiscreteValues & discrete() const
Return the discrete values.
std::pair< Key, size_t > DiscreteKey
const KeyVector & keys() const
Access the factor's involved variable keys.
uint64_t unionRep(const DiscreteKeys &keys, const DiscreteValues &assign, const uint64_t idx) const
Create unique representation of union modes.
A thin wrapper around std::set that uses boost's fast_pool_allocator.
std::uint64_t Key
Integer nonlinear key type.
Scalar & coeffRef(Index row, Index col)
DiscreteKeys contractDkeys(const TableFactor &f) const
Return keys in contract mode.
DiscreteKey discreteKey(size_t i) const
Return ith key in keys_ as a DiscreteKey.
DiscreteKeys is a set of keys that can be assembled using the & operator.
bool isApprox(const SparseMatrixBase< OtherDerived > &other, const RealScalar &prec=NumTraits< Scalar >::dummy_precision()) const