A DecisionTreeFactor
represents a function over a set of discrete variables, . It is a versatile building block for representing potentials or probabilities in discrete factor graphs.
Internally, it uses an AlgebraicDecisionTree
(ADT) to store the function’s values. This representation can be very efficient, especially for sparse factors where many assignments have the same value (e.g., zero).
DecisionTreeFactor
is the base class for more specialized factors like DiscreteConditional
.
import gtsam
import numpy as np
import graphviz
from gtsam.symbol_shorthand import A, B
Creating a DecisionTreeFactor¶
A factor is defined by its DiscreteKeys
(the variables it depends on) and a table of values. The table specifies the factor’s output for every possible assignment of its variables. The values in the table are ordered such that the last key varies fastest.
# Define keys for two binary variables
KeyA = (A(0), 2)
KeyB = (B(0), 2)
# --- Method 1: From a spec string ---
# The values correspond to assignments (A,B) in the order:
# (0,0), (0,1), (1,0), (1,1)
f1_string = gtsam.DecisionTreeFactor([KeyA, KeyB], "1 2 3 4")
print("--- Factor f1 from string ---")
f1_string.print()
# --- Method 2: From a list of values ---
f2_vector = gtsam.DecisionTreeFactor([KeyA], [0.8, 0.2])
print("\n--- Factor f2 from vector ---")
f2_vector.print()
--- Factor f1 from string ---
DecisionTreeFactor
f[ (a0,2), (b0,2), ]
Choice(b0)
0 Choice(a0)
0 0 Leaf 1
0 1 Leaf 3
1 Choice(a0)
1 0 Leaf 2
1 1 Leaf 4
--- Factor f2 from vector ---
DecisionTreeFactor
f[ (a0,2), ]
Choice(a0)
0 Leaf 0.8
1 Leaf 0.2
Operations on DecisionTreeFactor¶
# --- Evaluate ---
# Get the factor's value for a specific assignment.
assignment = gtsam.DiscreteValues()
assignment[A(0)] = 1
assignment[B(0)] = 0
value = f1_string(assignment)
print(f"Value of f1 at A=1, B=0: {value}")
# --- Multiplication ---
# Multiplying factors corresponds to the product of their functions.
# The resulting factor is over the union of their variables.
# f3(A,B) = f1(A,B) * f2(A)
f3_product = f1_string * f2_vector
print("\n--- Product Factor f3 = f1 * f2 ---")
f3_product
Visualization¶
We can visualize the underlying Algebraic Decision Tree structure. This shows how the factor’s values are stored efficiently. Each path from the root to a leaf corresponds to an assignment, and the leaf holds the value.
graphviz.Source(f1_string.dot())
Rich Display in Jupyter¶
In a notebook, factors are displayed as easy-to-read tables.
f1_string