2016-04-27 08:00:58 -07:00
|
|
|
import numpy as np
|
2019-01-30 22:39:55 +01:00
|
|
|
from .space import Space
|
2016-04-27 08:00:58 -07:00
|
|
|
|
2019-01-30 22:39:55 +01:00
|
|
|
|
|
|
|
class Discrete(Space):
|
2021-07-29 02:26:34 +02:00
|
|
|
r"""A discrete space in :math:`\{ 0, 1, \\dots, n-1 \}`.
|
2019-07-12 14:08:54 -07:00
|
|
|
|
2019-03-25 00:42:53 +01:00
|
|
|
Example::
|
2019-07-12 14:08:54 -07:00
|
|
|
|
2019-03-25 00:42:53 +01:00
|
|
|
>>> Discrete(2)
|
2019-07-12 14:08:54 -07:00
|
|
|
|
2016-04-27 08:00:58 -07:00
|
|
|
"""
|
2021-07-29 02:26:34 +02:00
|
|
|
|
2016-05-30 18:07:59 -07:00
|
|
|
def __init__(self, n):
|
2019-03-25 00:42:53 +01:00
|
|
|
assert n >= 0
|
2016-04-27 08:00:58 -07:00
|
|
|
self.n = n
|
2019-02-07 11:29:04 -08:00
|
|
|
super(Discrete, self).__init__((), np.int64)
|
2018-09-24 20:11:03 +02:00
|
|
|
|
2016-04-27 08:00:58 -07:00
|
|
|
def sample(self):
|
2019-01-30 22:39:55 +01:00
|
|
|
return self.np_random.randint(self.n)
|
2018-09-24 20:11:03 +02:00
|
|
|
|
2016-04-27 08:00:58 -07:00
|
|
|
def contains(self, x):
|
2016-04-27 18:31:32 -07:00
|
|
|
if isinstance(x, int):
|
|
|
|
as_int = x
|
2021-07-29 12:42:48 -04:00
|
|
|
elif isinstance(x, (np.generic, np.ndarray)) and (x.dtype.char in np.typecodes["AllInteger"] and x.shape == ()):
|
2016-04-27 18:31:32 -07:00
|
|
|
as_int = int(x)
|
|
|
|
else:
|
|
|
|
return False
|
|
|
|
return as_int >= 0 and as_int < self.n
|
2018-08-27 15:30:47 -07:00
|
|
|
|
2016-04-27 08:00:58 -07:00
|
|
|
def __repr__(self):
|
|
|
|
return "Discrete(%d)" % self.n
|
2018-09-24 20:11:03 +02:00
|
|
|
|
2016-04-27 08:00:58 -07:00
|
|
|
def __eq__(self, other):
|
2019-03-23 23:18:19 -07:00
|
|
|
return isinstance(other, Discrete) and self.n == other.n
|