Skip to article frontmatterSkip to article content

VariableIndex

A VariableIndex provides an efficient way to look up which factors in a FactorGraph involve a particular variable (Key). It stores, for each variable, a list of the indices of the factors that include that variable.

This structure is often computed internally by GTSAM algorithms (like ordering methods or elimination) but can also be created explicitly if needed, for example, to improve performance when multiple operations need this information.

Open In Colab

import gtsam
from gtsam import VariableIndex, Ordering
# Need a graph type for creation
from gtsam import SymbolicFactorGraph
from gtsam import symbol_shorthand

X = symbol_shorthand.X
L = symbol_shorthand.L

Creating a VariableIndex

A VariableIndex is typically created from an existing FactorGraph.

# Create a simple SymbolicFactorGraph
graph = SymbolicFactorGraph()
graph.push_factor(X(0))           # Factor 0
graph.push_factor(X(0), X(1))     # Factor 1
graph.push_factor(X(1), X(2))     # Factor 2
graph.push_factor(X(0), L(1))     # Factor 3
graph.push_factor(X(1), L(1))     # Factor 4
graph.push_factor(X(1), L(2))     # Factor 5
graph.push_factor(X(2), L(2))     # Factor 6

# Create VariableIndex from the graph
variable_index = VariableIndex(graph)

# Print the index
variable_index.print("VariableIndex: ")
VariableIndex: nEntries = 13, nFactors = 7
var l1: 3 4
var l2: 5 6
var x0: 0 1 3
var x1: 1 2 4 5
var x2: 2 6

Accessing Information

You can query the number of variables, factors, and entries, and look up the factors associated with a specific variable.

print(f"Number of variables (size): {variable_index.size()}")
print(f"Number of factors (nFactors): {variable_index.nFactors()}")
print(f"Number of variable-factor entries (nEntries): {variable_index.nEntries()}")

# Get factors involving a specific variable
factors_x1 = variable_index.at(X(1)) # Returns a FactorIndices (FastVector<size_t>)
print(f"Factors involving x1: {factors_x1}")

# Use key directly
factors_l1 = variable_index.at(L(1))
print(f"Factors involving l1: {factors_l1}")
Number of variables (size): 5
Number of factors (nFactors): 7
Number of variable-factor entries (nEntries): 13
Factors involving x1: [1, 2, 4, 5]
Factors involving l1: [3, 4]

Usage in Algorithms

VariableIndex is primarily used as input to other algorithms, particularly ordering methods like Ordering.Colamd.

# Compute COLAMD ordering directly from the VariableIndex
colamd_ordering = Ordering.Colamd(variable_index)
colamd_ordering.print("COLAMD Ordering from VariableIndex: ")
COLAMD Ordering from VariableIndex: Position 0: l1, x0, x1, l2, x2