2022-05-10 17:18:06 +02:00
|
|
|
"""Implementation of a space that represents the cartesian product of `Discrete` spaces."""
|
2022-05-25 15:28:19 +01:00
|
|
|
from typing import Iterable, List, Optional, Sequence, Tuple, Union
|
2022-03-31 12:50:38 -07:00
|
|
|
|
Cleanup, removal of unmaintained code (#836)
* add dtype to Box
* remove board_game, debugging, safety, parameter_tuning environments
* massive set of breaking changes
- remove python logging module
- _step, _reset, _seed, _close => non underscored method
- remove benchmark and scoring folder
* Improve render("human"), now resizable, closable window.
* get rid of default step and reset in wrappers, so it doesn’t silently fail for people with underscore methods
* CubeCrash unit test environment
* followup fixes
* MemorizeDigits unit test envrionment
* refactored spaces a bit
fixed indentation
disabled test_env_semantics
* fix unit tests
* fixes
* CubeCrash, MemorizeDigits tested
* gym backwards compatibility patch
* gym backwards compatibility, followup fixes
* changelist, add spaces to main namespaces
* undo_logger_setup for backwards compat
* remove configuration.py
2018-01-25 18:20:14 -08:00
|
|
|
import numpy as np
|
2022-03-31 12:50:38 -07:00
|
|
|
|
2021-10-02 08:36:02 +08:00
|
|
|
from gym import logger
|
2022-04-24 17:14:33 +01:00
|
|
|
from gym.spaces.discrete import Discrete
|
|
|
|
from gym.spaces.space import Space
|
|
|
|
from gym.utils import seeding
|
2016-08-14 16:18:28 -04:00
|
|
|
|
2019-01-30 22:39:55 +01:00
|
|
|
|
2022-01-24 23:22:11 +01:00
|
|
|
class MultiDiscrete(Space[np.ndarray]):
|
2022-05-10 17:18:06 +02:00
|
|
|
"""This represents the cartesian product of arbitrary :class:`Discrete` spaces.
|
2022-04-08 03:19:52 +02:00
|
|
|
|
2022-05-10 17:18:06 +02:00
|
|
|
It is useful to represent game controllers or keyboards where each key can be represented as a discrete action space.
|
2022-04-08 03:19:52 +02:00
|
|
|
|
2022-05-10 17:18:06 +02:00
|
|
|
Note:
|
2022-04-06 20:12:55 +01:00
|
|
|
Some environment wrappers assume a value of 0 always represents the NOOP action.
|
2019-03-11 10:58:48 -07:00
|
|
|
|
2022-04-06 20:12:55 +01:00
|
|
|
e.g. Nintendo Game Controller - Can be conceptualized as 3 discrete action spaces:
|
2019-03-11 10:58:48 -07:00
|
|
|
|
2022-04-06 20:12:55 +01:00
|
|
|
1. Arrow Keys: Discrete 5 - NOOP[0], UP[1], RIGHT[2], DOWN[3], LEFT[4] - params: min: 0, max: 4
|
|
|
|
2. Button A: Discrete 2 - NOOP[0], Pressed[1] - params: min: 0, max: 1
|
|
|
|
3. Button B: Discrete 2 - NOOP[0], Pressed[1] - params: min: 0, max: 1
|
2019-03-11 10:58:48 -07:00
|
|
|
|
2022-04-06 20:12:55 +01:00
|
|
|
It can be initialized as ``MultiDiscrete([ 5, 2, 2 ])``
|
2019-03-11 10:58:48 -07:00
|
|
|
|
|
|
|
"""
|
2021-07-29 02:26:34 +02:00
|
|
|
|
2022-04-24 17:14:33 +01:00
|
|
|
def __init__(
|
|
|
|
self,
|
2022-05-25 15:28:19 +01:00
|
|
|
nvec: Union[np.ndarray, List[int]],
|
2022-04-24 17:14:33 +01:00
|
|
|
dtype=np.int64,
|
2022-05-25 15:28:19 +01:00
|
|
|
seed: Optional[Union[int, seeding.RandomNumberGenerator]] = None,
|
2022-04-24 17:14:33 +01:00
|
|
|
):
|
2022-05-10 17:18:06 +02:00
|
|
|
"""Constructor of :class:`MultiDiscrete` space.
|
|
|
|
|
|
|
|
The argument ``nvec`` will determine the number of values each categorical variable can take.
|
|
|
|
|
|
|
|
Although this feature is rarely used, :class:`MultiDiscrete` spaces may also have several axes
|
|
|
|
if ``nvec`` has several axes:
|
|
|
|
|
|
|
|
Example::
|
|
|
|
|
|
|
|
>> d = MultiDiscrete(np.array([[1, 2], [3, 4]]))
|
|
|
|
>> d.sample()
|
|
|
|
array([[0, 0],
|
|
|
|
[2, 3]])
|
|
|
|
|
|
|
|
Args:
|
|
|
|
nvec: vector of counts of each categorical variable. This will usually be a list of integers. However,
|
|
|
|
you may also pass a more complicated numpy array if you'd like the space to have several axes.
|
|
|
|
dtype: This should be some kind of integer type.
|
|
|
|
seed: Optionally, you can use this argument to seed the RNG that is used to sample from the space.
|
Cleanup, removal of unmaintained code (#836)
* add dtype to Box
* remove board_game, debugging, safety, parameter_tuning environments
* massive set of breaking changes
- remove python logging module
- _step, _reset, _seed, _close => non underscored method
- remove benchmark and scoring folder
* Improve render("human"), now resizable, closable window.
* get rid of default step and reset in wrappers, so it doesn’t silently fail for people with underscore methods
* CubeCrash unit test environment
* followup fixes
* MemorizeDigits unit test envrionment
* refactored spaces a bit
fixed indentation
disabled test_env_semantics
* fix unit tests
* fixes
* CubeCrash, MemorizeDigits tested
* gym backwards compatibility patch
* gym backwards compatibility, followup fixes
* changelist, add spaces to main namespaces
* undo_logger_setup for backwards compat
* remove configuration.py
2018-01-25 18:20:14 -08:00
|
|
|
"""
|
2021-12-16 13:45:37 +08:00
|
|
|
self.nvec = np.array(nvec, dtype=dtype, copy=True)
|
|
|
|
assert (self.nvec > 0).all(), "nvec (counts) have to be positive"
|
2019-01-30 22:39:55 +01:00
|
|
|
|
2021-11-14 14:50:23 +01:00
|
|
|
super().__init__(self.nvec.shape, dtype, seed)
|
2018-09-24 20:11:03 +02:00
|
|
|
|
2022-01-24 23:22:11 +01:00
|
|
|
@property
|
2022-05-25 15:28:19 +01:00
|
|
|
def shape(self) -> Tuple[int, ...]:
|
2022-05-10 17:18:06 +02:00
|
|
|
"""Has stricter type than :class:`gym.Space` - never None."""
|
2022-01-24 23:22:11 +01:00
|
|
|
return self._shape # type: ignore
|
|
|
|
|
|
|
|
def sample(self) -> np.ndarray:
|
2022-05-10 17:18:06 +02:00
|
|
|
"""Generates a single random sample this space."""
|
2021-12-08 22:14:15 +01:00
|
|
|
return (self.np_random.random(self.nvec.shape) * self.nvec).astype(self.dtype)
|
2018-09-24 20:11:03 +02:00
|
|
|
|
2022-01-24 23:22:11 +01:00
|
|
|
def contains(self, x) -> bool:
|
2022-05-10 17:18:06 +02:00
|
|
|
"""Return boolean specifying if x is a valid member of this space."""
|
2021-12-16 13:45:37 +08:00
|
|
|
if isinstance(x, Sequence):
|
2019-04-19 14:09:44 -07:00
|
|
|
x = np.array(x) # Promote list to array for contains check
|
2018-12-05 15:54:49 -08:00
|
|
|
# if nvec is uint32 and space dtype is uint32, then 0 <= x < self.nvec guarantees that x
|
|
|
|
# is within correct bounds for space dtype (even though x does not have to be unsigned)
|
2022-01-24 23:22:11 +01:00
|
|
|
return bool(x.shape == self.shape and (0 <= x).all() and (x < self.nvec).all())
|
2018-08-28 10:51:28 -07:00
|
|
|
|
2022-04-08 03:19:52 +02:00
|
|
|
def to_jsonable(self, sample_n: Iterable[np.ndarray]):
|
2022-05-10 17:18:06 +02:00
|
|
|
"""Convert a batch of samples from this space to a JSONable data type."""
|
Cleanup, removal of unmaintained code (#836)
* add dtype to Box
* remove board_game, debugging, safety, parameter_tuning environments
* massive set of breaking changes
- remove python logging module
- _step, _reset, _seed, _close => non underscored method
- remove benchmark and scoring folder
* Improve render("human"), now resizable, closable window.
* get rid of default step and reset in wrappers, so it doesn’t silently fail for people with underscore methods
* CubeCrash unit test environment
* followup fixes
* MemorizeDigits unit test envrionment
* refactored spaces a bit
fixed indentation
disabled test_env_semantics
* fix unit tests
* fixes
* CubeCrash, MemorizeDigits tested
* gym backwards compatibility patch
* gym backwards compatibility, followup fixes
* changelist, add spaces to main namespaces
* undo_logger_setup for backwards compat
* remove configuration.py
2018-01-25 18:20:14 -08:00
|
|
|
return [sample.tolist() for sample in sample_n]
|
2018-09-24 20:11:03 +02:00
|
|
|
|
Cleanup, removal of unmaintained code (#836)
* add dtype to Box
* remove board_game, debugging, safety, parameter_tuning environments
* massive set of breaking changes
- remove python logging module
- _step, _reset, _seed, _close => non underscored method
- remove benchmark and scoring folder
* Improve render("human"), now resizable, closable window.
* get rid of default step and reset in wrappers, so it doesn’t silently fail for people with underscore methods
* CubeCrash unit test environment
* followup fixes
* MemorizeDigits unit test envrionment
* refactored spaces a bit
fixed indentation
disabled test_env_semantics
* fix unit tests
* fixes
* CubeCrash, MemorizeDigits tested
* gym backwards compatibility patch
* gym backwards compatibility, followup fixes
* changelist, add spaces to main namespaces
* undo_logger_setup for backwards compat
* remove configuration.py
2018-01-25 18:20:14 -08:00
|
|
|
def from_jsonable(self, sample_n):
|
2022-05-10 17:18:06 +02:00
|
|
|
"""Convert a JSONable data type to a batch of samples from this space."""
|
Cleanup, removal of unmaintained code (#836)
* add dtype to Box
* remove board_game, debugging, safety, parameter_tuning environments
* massive set of breaking changes
- remove python logging module
- _step, _reset, _seed, _close => non underscored method
- remove benchmark and scoring folder
* Improve render("human"), now resizable, closable window.
* get rid of default step and reset in wrappers, so it doesn’t silently fail for people with underscore methods
* CubeCrash unit test environment
* followup fixes
* MemorizeDigits unit test envrionment
* refactored spaces a bit
fixed indentation
disabled test_env_semantics
* fix unit tests
* fixes
* CubeCrash, MemorizeDigits tested
* gym backwards compatibility patch
* gym backwards compatibility, followup fixes
* changelist, add spaces to main namespaces
* undo_logger_setup for backwards compat
* remove configuration.py
2018-01-25 18:20:14 -08:00
|
|
|
return np.array(sample_n)
|
2018-09-24 20:11:03 +02:00
|
|
|
|
|
|
|
def __repr__(self):
|
2022-05-10 17:18:06 +02:00
|
|
|
"""Gives a string representation of this space."""
|
2021-11-14 14:50:23 +01:00
|
|
|
return f"MultiDiscrete({self.nvec})"
|
2018-09-24 20:11:03 +02:00
|
|
|
|
2021-09-12 00:54:52 +08:00
|
|
|
def __getitem__(self, index):
|
2022-05-10 17:18:06 +02:00
|
|
|
"""Extract a subspace from this ``MultiDiscrete`` space."""
|
2021-09-12 00:54:52 +08:00
|
|
|
nvec = self.nvec[index]
|
|
|
|
if nvec.ndim == 0:
|
|
|
|
subspace = Discrete(nvec)
|
|
|
|
else:
|
2022-04-08 03:19:52 +02:00
|
|
|
subspace = MultiDiscrete(nvec, self.dtype) # type: ignore
|
2021-12-08 22:14:15 +01:00
|
|
|
subspace.np_random.bit_generator.state = self.np_random.bit_generator.state
|
2021-09-12 00:54:52 +08:00
|
|
|
return subspace
|
|
|
|
|
|
|
|
def __len__(self):
|
2022-05-10 17:18:06 +02:00
|
|
|
"""Gives the ``len`` of samples from this space."""
|
2021-09-12 00:54:52 +08:00
|
|
|
if self.nvec.ndim >= 2:
|
2021-10-02 08:36:02 +08:00
|
|
|
logger.warn("Get length of a multi-dimensional MultiDiscrete space.")
|
2021-09-12 00:54:52 +08:00
|
|
|
return len(self.nvec)
|
|
|
|
|
2018-09-24 20:11:03 +02:00
|
|
|
def __eq__(self, other):
|
2022-05-10 17:18:06 +02:00
|
|
|
"""Check whether ``other`` is equivalent to this instance."""
|
2019-03-23 23:18:19 -07:00
|
|
|
return isinstance(other, MultiDiscrete) and np.all(self.nvec == other.nvec)
|