DiscreteFactor is mostly an internal base class; DecisionTreeFactor is probably the class you want to interact with. It defines the common evaluation and structural interface for factors over finite-valued variables, while concrete classes such as DecisionTreeFactor and TableFactor choose how the potentials are stored.
import gtsam
import numpy as np
from gtsam.symbol_shorthand import M, X
from IPython.display import Markdown, displayCreating a concrete factor¶
DiscreteFactor is abstract in Python, so construct one of its wrapped subclasses. A DecisionTreeFactor is convenient for algebra and sparse structure; a TableFactor stores the same potential densely. A discrete key is represented by (key, cardinality).
A = (gtsam.symbol("A", 0), 2)
B = (gtsam.symbol("B", 0), 2)
tree_factor = gtsam.DecisionTreeFactor([A, B], "1 2 3 4")
table_factor = gtsam.TableFactor(tree_factor)
print("number of keys:", table_factor.size())
print("concrete type:", type(table_factor).__name__)Evaluating assignments¶
evaluate() returns the potential for a complete DiscreteValues assignment. errorTree() instead represents negative log-potentials, which is the additive form used by optimizers. The inherited keys(), size(), and empty() methods inspect factor scope.
values = gtsam.DiscreteValues()
values[A[0]] = 1
values[B[0]] = 0
potential = table_factor.evaluate(values)
error = table_factor.error(values)
print("potential:", potential)
print("negative log potential:", error)
assert np.isclose(error, -np.log(potential))Choosing a representation¶
Use DecisionTreeFactor when repeated substructure or zero-valued branches can be compressed. Use TableFactor when dense lookup and predictable memory layout are more important. Algorithms accepting DiscreteFactor can work with either representation.
Source¶
AI assistance caveat¶
AI was used to help draft this documentation, and inaccuracies could be present.