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 Space Utils

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

Overview

Concrete tool for flattening, unflattening, and transforming Gymnasium space instances and their samples provided by Gymnasium.

Description

The Space Utils module (gymnasium/spaces/utils.py) provides four primary utility functions implemented via Python's functools.singledispatch mechanism. Each function has specialized implementations registered for every built-in Gymnasium space type (Box, Discrete, MultiBinary, MultiDiscrete, Tuple, Dict, Graph, Text, Sequence, OneOf).

The four core functions are:

  • flatdim(space) -- Returns the number of dimensions a flattened equivalent of the space would have. Raises ValueError for non-flattenable spaces (Graph, Sequence).
  • flatten(space, x) -- Flattens a data point from a space into a form suitable for neural networks (typically a 1D numpy array). For Discrete spaces, this produces one-hot encodings. For Graph spaces, it returns a GraphInstance with reshaped arrays.
  • unflatten(space, x) -- Reverses the transformation applied by flatten.
  • flatten_space(space) -- Flattens the space itself (not a sample) into an equivalent flat space, typically a Box.

Additionally, is_space_dtype_shape_equiv(space_1, space_2) checks whether two spaces share a common dtype and shape, used primarily for vector environment compatibility.

Usage

Use these utilities when preparing observations or actions for neural network consumption, converting structured space samples to flat arrays, or checking space compatibility in vectorized environments.

Code Reference

Source Location

Signature

def flatdim(space: Space[Any]) -> int

def flatten(space: Space[T], x: T) -> FlatType

def unflatten(space: Space[T], x: FlatType) -> T

def flatten_space(space: Space[Any]) -> Box | Dict | Sequence | Tuple | Graph

def is_space_dtype_shape_equiv(space_1: Space, space_2: Space) -> bool

Import

from gymnasium.spaces.utils import flatdim, flatten, unflatten, flatten_space

I/O Contract

flatdim

Name Type Required Description
space Space Yes The space to compute the flat dimension of.
Return Type Description
int The total number of dimensions in the flattened space. Raises ValueError for Graph or Sequence spaces.

flatten

Name Type Required Description
space Space Yes The space that defines how x is flattened.
x Matches space type Yes The data point to flatten.
Return Type Description
NDArray, dict, tuple, or GraphInstance Box/MultiBinary: flattened 1D array. Discrete: one-hot array of length n. MultiDiscrete: concatenated one-hot arrays. Tuple/Dict: concatenated array (if flattenable) or nested structure. Graph: GraphInstance with reshaped arrays. Text: integer array of length max_length. Sequence: tuple of flattened items or stacked array. OneOf: array with index prefix followed by padded flat sample.

unflatten

Name Type Required Description
space Space Yes The space used to determine how to unflatten.
x FlatType Yes The flattened data point.
Return Type Description
Matches original space type The reconstructed data point in the original space structure.

flatten_space

Name Type Required Description
space Space Yes The space to flatten.
Return Type Description
Box, Dict, Tuple, Sequence, or Graph A flat equivalent space. Most spaces produce a Box. Graph produces a Graph with flat subspaces. Sequence produces a Sequence with a flat feature space.

Dispatch Table

Space Type flatdim flatten output flatten_space output
Box product of shape 1D array Box with flat bounds
MultiBinary product of shape 1D array Box(0, 1, ...)
Discrete n one-hot array of length n Box(0, 1, (n,))
MultiDiscrete sum(nvec) concatenated one-hot arrays Box(0, 1, (sum(nvec),))
Tuple sum of sub-flatdims concatenated array or tuple Box or Tuple
Dict sum of sub-flatdims concatenated array or dict Box or Dict
Graph raises ValueError GraphInstance with flat arrays Graph with flat subspaces
Text max_length int32 array of character indices Box(0, charset_size, (max_length,))
Sequence raises ValueError tuple of flat items or stacked Sequence with flat feature space
OneOf 1 + max(sub-flatdims) array with [index, padded_flat_sample] Box with combined bounds

Usage Examples

from gymnasium.spaces import Box, Discrete, Dict, Tuple
from gymnasium.spaces.utils import flatdim, flatten, unflatten, flatten_space

# Flat dimension of a Dict space
space = Dict({"position": Discrete(2), "velocity": Discrete(3)})
print(flatdim(space))  # 5

# Flatten a Box sample
box = Box(0, 1, shape=(3, 5))
sample = box.sample()
flat = flatten(box, sample)
print(flat.shape)  # (15,)

# Round-trip flatten/unflatten for Discrete
disc = Discrete(4)
flat_disc = flatten(disc, 2)
print(flat_disc)  # [0, 0, 1, 0]
original = unflatten(disc, flat_disc)
print(original)   # 2

# Flatten a compound space
compound = Tuple((Box(0, 1, shape=(2,)), Discrete(3)))
flat_space = flatten_space(compound)
print(flat_space)  # Box(0.0, 1.0, (5,), float64)

Related Pages

Page Connections

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