Type cast in spaces families (#2491)

* Type cast for `spaces.Dict`

* Type cast for `spaces.Tuple`

* Type cast for `spaces.Discrete`

* Type cast for `spaces.MultiDiscrete`

* Type cast for `spaces.MultiBinary`
This commit is contained in:
Xuehai Pan
2021-12-16 13:45:37 +08:00
committed by GitHub
parent 180d8ddd5c
commit 18c8b988d4
5 changed files with 29 additions and 16 deletions

View File

@@ -1,3 +1,4 @@
from collections.abc import Sequence
import numpy as np
from .space import Space
@@ -14,9 +15,9 @@ class MultiBinary(Space):
>> self.observation_space.sample()
array([0,1,0,1,0], dtype =int8)
array([0, 1, 0, 1, 0], dtype=int8)
>> self.observation_space = spaces.MultiBinary([3,2])
>> self.observation_space = spaces.MultiBinary([3, 2])
>> self.observation_space.sample()
@@ -27,18 +28,21 @@ class MultiBinary(Space):
"""
def __init__(self, n, seed=None):
self.n = n
if type(n) in [tuple, list, np.ndarray]:
input_n = n
if isinstance(n, (Sequence, np.ndarray)):
self.n = input_n = tuple(int(i) for i in n)
else:
self.n = n = int(n)
input_n = (n,)
assert (np.asarray(input_n) > 0).all(), "n (counts) have to be positive"
super().__init__(input_n, np.int8, seed)
def sample(self):
return self.np_random.integers(low=0, high=2, size=self.n, dtype=self.dtype)
def contains(self, x):
if isinstance(x, list) or isinstance(x, tuple):
if isinstance(x, Sequence):
x = np.array(x) # Promote list to array for contains check
if self.shape != x.shape:
return False