Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

DiscreteKey

DiscreteKey is the equivalent of Key, but for discrete (or hybrid) factors and conditionals. It pairs the underlying GTSAM variable key with its cardinality; Python represents one DiscreteKey as a two-tuple and wraps a sequence of them in DiscreteKeys.

Open In Colab
import gtsam
import numpy as np
from gtsam.symbol_shorthand import M, X
from IPython.display import Markdown, display

Creating discrete keys

The first tuple element is the 64-bit variable key; the second is the number of allowed values. Using gtsam.symbol() makes keys readable without changing their numeric representation.

weather = (gtsam.symbol("W", 0), 3)  # sunny, cloudy, rainy
umbrella = (gtsam.symbol("U", 0), 2)  # no, yes

print("weather key:", gtsam.DefaultKeyFormatter(weather[0]))
print("weather cardinality:", weather[1])

The DiscreteKeys container

DiscreteKeys preserves variable order, which matters when a flat table is mapped to joint assignments. Use push_back(), at(), size(), and empty() to build and inspect it.

keys = gtsam.DiscreteKeys()
keys.push_back(weather)
keys.push_back(umbrella)

print("number of variables:", keys.size())
print("first key/cardinality:", keys.at(0))
keys.print("Model variables")

Enumerating assignments

cartesianProduct() generates one DiscreteValues object for every joint assignment. Here there are 3 × 2 = 6 assignments, in the order implied by DiscreteKeys.

assignments = gtsam.cartesianProduct(keys)
print("joint assignments:", len(assignments))
print(assignments[:2])
assert len(assignments) == weather[1] * umbrella[1]

Source

DiscreteKey.h

AI assistance caveat

AI was used to help draft this documentation, and inaccuracies could be present.