Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Farama Foundation Gymnasium Graph Space

From Leeroopedia
Knowledge Sources
Domains Reinforcement_Learning, Spaces
Last Updated 2026-02-15 03:00 GMT

Overview

Concrete tool for representing graph-structured observations and actions provided by Gymnasium.

Description

The Graph space represents graph information as a series of nodes connected with edges according to an adjacency matrix. Each node has features drawn from a Box or Discrete space, and each edge (optionally) has features drawn from a Box or Discrete space. The connectivity between nodes is represented by edge_links, an integer array of shape (m, 2) indicating which two nodes each of the m edges connects.

Samples from this space are GraphInstance named tuples containing three fields:

  • nodes -- an (n x ...) array of node features
  • edges -- an optional (m x ...) array of edge features (or None)
  • edge_links -- an optional (m x 2) integer array of node index pairs (or None)

The Graph space is not numpy-flattenable (is_np_flattenable returns False), which means it cannot be flattened into a single Box. However, it can be flattened into a Graph with flat node and edge spaces via the flatten / flatten_space utilities.

Usage

Use Graph when the environment observation or action naturally has a variable-size graph structure, such as molecular structures, social networks, road networks, or any domain where entities (nodes) are connected by relationships (edges). It is especially suited for graph neural network (GNN) based agents.

Code Reference

Source Location

Signature

class Graph(Space[GraphInstance]):
    def __init__(
        self,
        node_space: Box | Discrete,
        edge_space: None | Box | Discrete,
        seed: int | np.random.Generator | None = None,
    )

Import

from gymnasium.spaces import Graph, GraphInstance

I/O Contract

Inputs

Name Type Required Description
node_space Box or Discrete Yes Defines the feature space for each node in the graph.
edge_space None, Box, or Discrete Yes Defines the feature space for each edge. Pass None for graphs without edge features.
seed int, np.random.Generator, or None No Optional seed for the random number generator used for sampling.

Outputs

Name Type Description
sample() returns GraphInstance A named tuple with fields nodes (NDArray), edges (NDArray or None), and edge_links (NDArray or None).
contains() returns bool Whether a given GraphInstance is a valid member of this space.

Key Methods

Method Description
sample(mask, probability, num_nodes, num_edges) Generate a random graph. num_nodes defaults to 10; num_edges is randomly chosen between 0 and num_nodes * (num_nodes - 1) if not specified.
contains(x) Check whether a GraphInstance is a valid member of this space, verifying node features, edge features, and edge link indices.
seed(seed) Seed the PRNG for the Graph space and its node/edge subspaces. Accepts None, int, or a tuple of ints.
to_jsonable(sample_n) Convert a batch of GraphInstance samples to a JSON-serializable format.
from_jsonable(sample_n) Convert JSON-serializable data back to a list of GraphInstance objects.

Usage Examples

from gymnasium.spaces import Graph, Box, Discrete

# Graph with continuous 3D node features and discrete edge labels
graph_space = Graph(
    node_space=Box(low=-1.0, high=1.0, shape=(3,)),
    edge_space=Discrete(5),
    seed=42
)

# Sample a graph with 4 nodes and 6 edges
sample = graph_space.sample(num_nodes=4, num_edges=6)
print(sample.nodes.shape)       # (4, 3)
print(sample.edges.shape)       # (6,)
print(sample.edge_links.shape)  # (6, 2)

# Check membership
print(sample in graph_space)    # True

# Graph with no edge features
graph_no_edges = Graph(
    node_space=Discrete(10),
    edge_space=None,
    seed=42
)
sample2 = graph_no_edges.sample(num_nodes=3, num_edges=0)
print(sample2.edges)       # None
print(sample2.edge_links)  # None

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment