Class Spaces
Gymnasium's gymnasium.spaces module as one static class (DR-79, DR-86): with using Gym.Spaces;,
Spaces.Discrete(4, seed: 0) reads as spaces.Discrete(4, seed=0) after from gymnasium import
spaces. Each factory builds the class of its name exactly as its constructor does, and the module's
functions are here too: Flatdim(Space), Flatten(Space, object?), FlattenSpace(Space),
Unflatten(Space, object?).
public static class Spaces
- Inheritance
-
Spaces
- Inherited Members
Remarks
The constructors stay the primary way in C# (new Discrete(4)); this class is for code that reads like
Gymnasium's, or that wants one entry point to discover the spaces from. It mirrors the module's
__all__: the ten spaces, GraphInstance and the four flattening functions (Space, the abstract
base, has no factory).
Every space a factory returns is the caller's: an env takes over a space assigned to it (DR-40), anything else is disposed by whoever created it. A composite factory takes ownership of the subspaces it is given, as the constructor does.
Footgun: the class shares its namespace's name. Outside namespace Gym that is harmless; inside namespace
Gym.Spaces the simple name Spaces is this class, and inside any other Gym.* namespace it is
the namespace, so write Gym.Spaces.Spaces.Discrete(4) there, or new Discrete(4).
Reference: gymnasium/spaces/__init__.py.
Methods
Box(NDArray, NDArray, Shape?, DType?, SpaceSeed?)
A box with per-entry bounds: spaces.Box(low_array, high_array, ...); the shape is the arrays' unless shape is given.
public static Box Box(NDArray low, NDArray high, Shape? shape = null, DType? dtype = null, SpaceSeed? seed = null)
Parameters
lowNDArrayThe lower bounds; read, never kept (the box stores a copy in its dtype).
highNDArrayThe upper bounds; read, never kept.
shapeShape?The shape, or null to take the bounds'.
dtypeDTypeThe dtype; null is float32.
seedSpaceSeed?An integer seed, a generator to share, or null.
Returns
- Box
The new space; the caller owns it.
Exceptions
- ValueError
Thrown for shapes that differ, a NaN bound, a bound outside the dtype, an infinite bound of an unsigned or bool dtype, or
low > high.- Error
Thrown when an integer
seedis negative.
Box(NDArray, double, Shape?, DType?, SpaceSeed?)
A box with per-entry lower bounds and a scalar upper bound.
public static Box Box(NDArray low, double high, Shape? shape = null, DType? dtype = null, SpaceSeed? seed = null)
Parameters
lowNDArrayThe lower bounds; read, never kept.
highdoubleThe upper bound of every entry.
shapeShape?The shape, or null to take
low's.dtypeDTypeThe dtype; null is float32.
seedSpaceSeed?An integer seed, a generator to share, or null.
Returns
- Box
The new space; the caller owns it.
Exceptions
- ValueError
Thrown as for the other boxes.
- Error
Thrown when an integer
seedis negative.
Box(double, NDArray, Shape?, DType?, SpaceSeed?)
A box with a scalar lower bound and per-entry upper bounds.
public static Box Box(double low, NDArray high, Shape? shape = null, DType? dtype = null, SpaceSeed? seed = null)
Parameters
lowdoubleThe lower bound of every entry.
highNDArrayThe upper bounds; read, never kept.
shapeShape?The shape, or null to take
high's.dtypeDTypeThe dtype; null is float32.
seedSpaceSeed?An integer seed, a generator to share, or null.
Returns
- Box
The new space; the caller owns it.
Exceptions
- ValueError
Thrown as for the other boxes.
- Error
Thrown when an integer
seedis negative.
Box(double, double, Shape?, DType?, SpaceSeed?)
A box whose every entry lies in [low, high] (scalar bounds): spaces.Box(low, high, shape, dtype, seed).
public static Box Box(double low, double high, Shape? shape = null, DType? dtype = null, SpaceSeed? seed = null)
Parameters
lowdoubleThe lower bound of every entry;
double.NegativeInfinityfor none.highdoubleThe upper bound of every entry;
double.PositiveInfinityfor none.shapeShape?The shape; null is
(1,), as for Gymnasium's scalar bounds.dtypeDTypeThe dtype: integer, floating or bool; null is float32, Gymnasium's default.
seedSpaceSeed?An integer seed, a generator to share, or null for a lazy entropy-seeded one.
Returns
- Box
The new space; the caller owns it.
Exceptions
- ValueError
Thrown for a NaN bound, a bound outside the dtype, an infinite bound of an unsigned or bool dtype,
low > high, or a dtype that is not integer, floating or bool, with Gymnasium's messages.- Error
Thrown when an integer
seedis negative.
Dict(IEnumerable<KeyValuePair<string, Space>>, SpaceSeed?, bool)
A dict space from key and subspace pairs, which keep their order: spaces.Dict([("a", a), ("b", b)]); the
new space owns the subspaces.
public static Dict Dict(IEnumerable<KeyValuePair<string, Space>> spaces, SpaceSeed? seed = null, bool sortKeys = true)
Parameters
spacesIEnumerable<KeyValuePair<string, Space>>The pairs, in order.
seedSpaceSeed?An integer seed (the dict's generator then draws one
int32seed per subspace), a generator to share, or null.sortKeysboolRecorded but not applied: Gymnasium sorts only an unordered mapping.
Returns
- Dict
The new space; the caller owns it.
Exceptions
- TypeError
Thrown for a null subspace.
- ArgumentException
Thrown for a repeated key.
- ArgumentNullException
Thrown when
spacesis null.- Error
Thrown when an integer
seedis negative.
Dict(IReadOnlyDictionary<string, Space>, SpaceSeed?, bool)
A dict space from a mapping: spaces.Dict({"a": a, "b": b}); with sortKeys (Gymnasium's
default) the keys are sorted ordinally. The new space owns the subspaces.
public static Dict Dict(IReadOnlyDictionary<string, Space> spaces, SpaceSeed? seed = null, bool sortKeys = true)
Parameters
spacesIReadOnlyDictionary<string, Space>The mapping.
seedSpaceSeed?An integer seed, a generator to share, or null.
sortKeysboolWhether to sort the keys, Gymnasium's behaviour for an unordered dict.
Returns
- Dict
The new space; the caller owns it.
Exceptions
- TypeError
Thrown for a null subspace.
- ArgumentNullException
Thrown when
spacesis null.- Error
Thrown when an integer
seedis negative.
Discrete(long, SpaceSeed?, long, DType?)
The integers start to start + n - 1: spaces.Discrete(n, seed=seed, start=start, dtype=dtype).
public static Discrete Discrete(long n, SpaceSeed? seed = null, long start = 0, DType? dtype = null)
Parameters
nlongThe number of elements; must be positive.
seedSpaceSeed?An integer seed (the space then samples what Gymnasium's does), a generator to share, or null.
startlongThe smallest element.
dtypeDTypeThe integer dtype of the elements; null is int64, Gymnasium's default. Samples are drawn in it.
Returns
- Discrete
The new space; the caller owns it.
Exceptions
- ValueError
Thrown when
nis not positive.- TypeError
Thrown when
dtypeis not an integer dtype.- OverflowError
Thrown when
norstartdoes not fitdtype.- Error
Thrown when an integer
seedis negative.
Flatdim(Space)
The number of entries a space's elements flatten to: spaces.flatdim(space) (a box's element count, a
discrete space's n, one-hot, a composite's sum).
public static long Flatdim(Space space)
Parameters
spaceSpaceThe space.
Returns
- long
The flattened size.
Exceptions
- ValueError
Thrown for a space that cannot be flattened to an array (a graph, a sequence, or a composite holding one).
- NotImplementedError
Thrown for a custom space flattenable but unknown to the function.
- ArgumentNullException
Thrown when
spaceis null.
Flatten(Space, object?)
An element flattened (spaces.flatten(space, x)): a new flat array for a flattenable space, and the same
structure of flattened parts for a graph, a sequence or a composite holding one.
public static object? Flatten(Space space, object? x)
Parameters
Returns
- object
The flattened element, new and owned by the caller.
Exceptions
- IndexError
Thrown for a discrete value outside the space, or a text longer than
max_length.- KeyError
Thrown for a dict element missing a key, or a character outside a text space's charset.
- ValueError
Thrown for a tuple element of another length than the space.
- TypeError
Thrown for an element of the wrong kind for a dict or text space.
- NotImplementedError
Thrown for a custom space.
- ArgumentNullException
Thrown when
spaceis null.
FlattenSpace(Space)
The space Flatten(Space, object?) maps a space's elements into: spaces.flatten_space(space), a flat box for every flattenable space.
public static Space FlattenSpace(Space space)
Parameters
spaceSpaceThe space.
Returns
- Space
A new space, owned by the caller, unseeded.
Remarks
Footgun: sampling the flattened space is not sampling the original; a flattened discrete space is a 0/1 box whose samples are rarely one-hot.
Exceptions
- NotImplementedError
Thrown for a custom space.
- ArgumentNullException
Thrown when
spaceis null.
Graph(Space, Space?, SpaceSeed?)
Graphs with node and edge features: spaces.Graph(node_space, edge_space, seed=seed); the new space owns both subspaces.
public static Graph Graph(Space nodeSpace, Space? edgeSpace, SpaceSeed? seed = null)
Parameters
nodeSpaceSpaceThe space of one node's features, usually a box or a discrete space.
edgeSpaceSpaceThe space of one edge's features, or null for graphs without edges.
seedSpaceSeed?An integer seed, a generator to share, or null.
Returns
- Graph
The new space; the caller owns it.
Exceptions
GraphInstance(object?, object?, NDArray?)
A graph element from its parts: spaces.GraphInstance(nodes, edges, edge_links); the instance takes ownership of them.
public static GraphInstance GraphInstance(object? nodes, object? edges, NDArray? edgeLinks)
Parameters
nodesobjectThe node features,
(n, ...), one row per node.edgesobjectThe edge features,
(m, ...), or null for a graph without edge features.edgeLinksNDArrayThe
(m, 2)integer array of the node indices each edge connects, or null when there are no edges.
Returns
- GraphInstance
The new instance; the caller owns it, and disposing it releases the parts.
MultiBinary(long, SpaceSeed?)
A flat array of n binary values: spaces.MultiBinary(n).
public static MultiBinary MultiBinary(long n, SpaceSeed? seed = null)
Parameters
nlongThe number of values; must be positive.
seedSpaceSeed?An integer seed, a generator to share, or null.
Returns
- MultiBinary
The new space; the caller owns it.
Exceptions
- ValueError
Thrown when
nis not positive.- Error
Thrown when an integer
seedis negative.
MultiBinary(long[], SpaceSeed?)
Binary arrays of the shape n: spaces.MultiBinary([3, 2]).
public static MultiBinary MultiBinary(long[] n, SpaceSeed? seed = null)
Parameters
nlong[]The shape; every dimension must be positive.
seedSpaceSeed?An integer seed, a generator to share, or null.
Returns
- MultiBinary
The new space; the caller owns it.
Exceptions
- ValueError
Thrown when a dimension is not positive.
- ArgumentNullException
Thrown when
nis null.- Error
Thrown when an integer
seedis negative.
MultiDiscrete(NDArray, DType?, SpaceSeed?, NDArray?)
One discrete choice per entry of an array of any shape, nvec's.
public static MultiDiscrete MultiDiscrete(NDArray nvec, DType? dtype = null, SpaceSeed? seed = null, NDArray? start = null)
Parameters
nvecNDArrayThe counts, any shape; read, never kept (the space stores a copy in its dtype).
dtypeDTypeThe integer dtype; null is int64.
seedSpaceSeed?An integer seed, a generator to share, or null.
startNDArrayThe smallest values, of
nvec's shape, or null for zeros; read, never kept.
Returns
- MultiDiscrete
The new space; the caller owns it.
Exceptions
- ValueError
Thrown for a non-integer dtype, a start of another shape, or a count that is not positive.
- ArgumentNullException
Thrown when
nvecis null.- Error
Thrown when an integer
seedis negative.
MultiDiscrete(long[], DType?, SpaceSeed?, long[]?)
One discrete choice per entry of a flat array: spaces.MultiDiscrete(nvec, dtype, seed, start).
public static MultiDiscrete MultiDiscrete(long[] nvec, DType? dtype = null, SpaceSeed? seed = null, long[]? start = null)
Parameters
nveclong[]The number of choices of each entry; read, never kept.
dtypeDTypeThe integer dtype; null is int64.
seedSpaceSeed?An integer seed, a generator to share, or null.
startlong[]The smallest value of each entry, or null for zeros; read, never kept.
Returns
- MultiDiscrete
The new space; the caller owns it.
Exceptions
- ValueError
Thrown for a non-integer dtype, a start of another length, or a count that is not positive.
- ArgumentNullException
Thrown when
nvecis null.- Error
Thrown when an integer
seedis negative.
OneOf(params Space[])
One element of one of the given subspaces: spaces.OneOf((a, b)); the new space owns them.
public static OneOf OneOf(params Space[] spaces)
Parameters
spacesSpace[]The subspaces, in order; at least one.
Returns
- OneOf
The new space; the caller owns it.
Exceptions
- TypeError
Thrown for a null subspace.
- ValueError
Thrown for no subspaces.
OneOf(IEnumerable<Space>, SpaceSeed?)
One element of one of the subspaces, with its index: spaces.OneOf(spaces, seed=seed); the new space owns the subspaces.
public static OneOf OneOf(IEnumerable<Space> spaces, SpaceSeed? seed = null)
Parameters
spacesIEnumerable<Space>The subspaces, in order; at least one.
seedSpaceSeed?An integer seed, a generator to share, or null.
Returns
- OneOf
The new space; the caller owns it.
Exceptions
- TypeError
Thrown when
spacesor a subspace is null.- ValueError
Thrown for no subspaces.
- Error
Thrown when an integer
seedis negative.
Sequence(Space, SpaceSeed?, bool)
Sequences of any length of a feature space's elements: spaces.Sequence(space, seed=seed, stack=stack); the new space owns the feature space.
public static Sequence Sequence(Space space, SpaceSeed? seed = null, bool stack = false)
Parameters
spaceSpaceThe feature space.
seedSpaceSeed?An integer seed, a generator to share, or null.
stackboolWhether samples are the items stacked into one batch rather than a tuple of them.
Returns
- Sequence
The new space; the caller owns it.
Exceptions
Text(long, ISet<string>, long, SpaceSeed?)
Strings of a set of characters, which is sorted as Gymnasium sorts a frozenset charset.
public static Text Text(long maxLength, ISet<string> charset, long minLength = 1, SpaceSeed? seed = null)
Parameters
maxLengthlongThe longest length, inclusive.
charsetISet<string>The characters; each must be a single code point.
minLengthlongThe shortest length, inclusive.
seedSpaceSeed?An integer seed, a generator to share, or null.
Returns
- Text
The new space; the caller owns it.
Exceptions
- ValueError
Thrown for invalid lengths, or a charset element that is not one character.
- ArgumentNullException
Thrown when
charsetis null.- Error
Thrown when an integer
seedis negative.
Text(long, long, string?, SpaceSeed?)
Strings of a character set, in a length range: spaces.Text(max_length, min_length=1, charset=alphanumeric, seed=seed).
public static Text Text(long maxLength, long minLength = 1, string? charset = null, SpaceSeed? seed = null)
Parameters
maxLengthlongThe longest length, inclusive.
minLengthlongThe shortest length, inclusive; 1 by default, so no empty string.
charsetstringThe characters, in sampling order (duplicates dropped); null is Gymnasium's alphanumeric set.
seedSpaceSeed?An integer seed, a generator to share, or null.
Returns
- Text
The new space; the caller owns it.
Exceptions
- ValueError
Thrown for a negative minimum or a minimum above the maximum.
- Error
Thrown when an integer
seedis negative.
Tuple(params Space[])
The product of the given subspaces: spaces.Tuple((a, b)); the new space owns them.
public static Tuple Tuple(params Space[] spaces)
Parameters
spacesSpace[]The subspaces, in order.
Returns
- Tuple
The new space; the caller owns it.
Exceptions
Tuple(IEnumerable<Space>, SpaceSeed?)
The product of spaces: spaces.Tuple(spaces, seed=seed); the new space owns the subspaces.
public static Tuple Tuple(IEnumerable<Space> spaces, SpaceSeed? seed = null)
Parameters
spacesIEnumerable<Space>The subspaces, in order.
seedSpaceSeed?An integer seed (the tuple's generator then draws one
int32seed per subspace), a generator to share, or null.
Returns
- Tuple
The new space; the caller owns it.
Exceptions
- TypeError
Thrown for a null subspace.
- ArgumentNullException
Thrown when
spacesis null.- Error
Thrown when an integer
seedis negative.
Unflatten(Space, object?)
Reverses Flatten(Space, object?): spaces.unflatten(space, x); the space must be the one the element was flattened with.
public static object? Unflatten(Space space, object? x)
Parameters
Returns
- object
An element of
space, new and owned by the caller.
Exceptions
- ValueError
Thrown for a flattened discrete element with no one-hot entry.
- AssertionError
Thrown for a composite given the wrong flattened form.
- KeyError
Thrown for a non-flattenable dict space's flattened dict missing a key.
- NotImplementedError
Thrown for a custom space.
- ArgumentNullException
Thrown when
spaceis null.