2022-01-24 23:22:11 +01:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2017-09-05 08:49:43 -07:00
|
|
|
from collections import OrderedDict
|
2021-12-16 13:45:37 +08:00
|
|
|
from collections.abc import Mapping, Sequence
|
2022-01-24 23:22:11 +01:00
|
|
|
from typing import Dict as TypingDict
|
2022-04-24 17:14:33 +01:00
|
|
|
from typing import Optional
|
2022-03-31 12:50:38 -07:00
|
|
|
|
2021-09-02 22:15:34 +08:00
|
|
|
import numpy as np
|
2022-03-31 12:50:38 -07:00
|
|
|
|
2022-04-24 17:14:33 +01:00
|
|
|
from gym.spaces.space import Space
|
|
|
|
from gym.utils import seeding
|
2017-09-05 08:49:43 -07:00
|
|
|
|
2019-01-30 22:39:55 +01:00
|
|
|
|
2022-01-24 23:22:11 +01:00
|
|
|
class Dict(Space[TypingDict[str, Space]], Mapping):
|
2017-09-05 08:49:43 -07:00
|
|
|
"""
|
2017-11-05 21:16:46 +03:00
|
|
|
A dictionary of simpler spaces.
|
2017-09-05 08:49:43 -07:00
|
|
|
|
2022-04-06 20:12:55 +01:00
|
|
|
Example usage::
|
|
|
|
|
|
|
|
self.observation_space = spaces.Dict({"position": spaces.Discrete(2), "velocity": spaces.Discrete(3)})
|
|
|
|
|
|
|
|
Example usage [nested]::
|
2022-04-08 03:19:52 +02:00
|
|
|
|
2022-04-06 20:12:55 +01:00
|
|
|
self.nested_observation_space = spaces.Dict({
|
|
|
|
'sensors': spaces.Dict({
|
|
|
|
'position': spaces.Box(low=-100, high=100, shape=(3,)),
|
|
|
|
'velocity': spaces.Box(low=-1, high=1, shape=(3,)),
|
|
|
|
'front_cam': spaces.Tuple((
|
|
|
|
spaces.Box(low=0, high=1, shape=(10, 10, 3)),
|
|
|
|
spaces.Box(low=0, high=1, shape=(10, 10, 3))
|
|
|
|
)),
|
|
|
|
'rear_cam': spaces.Box(low=0, high=1, shape=(10, 10, 3)),
|
|
|
|
}),
|
|
|
|
'ext_controller': spaces.MultiDiscrete((5, 2, 2)),
|
|
|
|
'inner_state':spaces.Dict({
|
|
|
|
'charge': spaces.Discrete(100),
|
|
|
|
'system_checks': spaces.MultiBinary(10),
|
|
|
|
'job_status': spaces.Dict({
|
|
|
|
'task': spaces.Discrete(5),
|
|
|
|
'progress': spaces.Box(low=0, high=100, shape=()),
|
|
|
|
})
|
2017-11-05 21:16:46 +03:00
|
|
|
})
|
|
|
|
})
|
2017-09-05 08:49:43 -07:00
|
|
|
"""
|
2021-07-29 02:26:34 +02:00
|
|
|
|
2022-01-24 23:22:11 +01:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
spaces: dict[str, Space] | None = None,
|
2022-04-24 17:14:33 +01:00
|
|
|
seed: Optional[dict | int | seeding.RandomNumberGenerator] = None,
|
2022-03-14 14:27:03 +00:00
|
|
|
**spaces_kwargs: Space,
|
2022-01-24 23:22:11 +01:00
|
|
|
):
|
2021-07-29 15:39:42 -04:00
|
|
|
assert (spaces is None) or (
|
|
|
|
not spaces_kwargs
|
|
|
|
), "Use either Dict(spaces=dict(...)) or Dict(foo=x, bar=z)"
|
2021-09-13 20:08:01 +02:00
|
|
|
|
2018-12-19 17:53:08 -08:00
|
|
|
if spaces is None:
|
|
|
|
spaces = spaces_kwargs
|
2018-08-27 19:28:32 +02:00
|
|
|
if isinstance(spaces, dict) and not isinstance(spaces, OrderedDict):
|
2021-12-16 13:45:37 +08:00
|
|
|
try:
|
|
|
|
spaces = OrderedDict(sorted(spaces.items()))
|
|
|
|
except TypeError: # raise when sort by different types of keys
|
|
|
|
spaces = OrderedDict(spaces.items())
|
|
|
|
if isinstance(spaces, Sequence):
|
2017-09-06 19:52:26 -07:00
|
|
|
spaces = OrderedDict(spaces)
|
2021-12-16 13:45:37 +08:00
|
|
|
|
|
|
|
assert isinstance(spaces, OrderedDict), "spaces must be a dictionary"
|
|
|
|
|
2017-09-05 08:49:43 -07:00
|
|
|
self.spaces = spaces
|
2019-03-25 02:06:55 +01:00
|
|
|
for space in spaces.values():
|
2021-07-29 15:39:42 -04:00
|
|
|
assert isinstance(
|
|
|
|
space, Space
|
|
|
|
), "Values of the dict should be instances of gym.Space"
|
2021-11-14 14:50:23 +01:00
|
|
|
super().__init__(
|
2022-01-24 23:22:11 +01:00
|
|
|
None, None, seed # type: ignore
|
2021-07-29 15:39:42 -04:00
|
|
|
) # None for shape and dtype, since it'll require special handling
|
2019-01-30 22:39:55 +01:00
|
|
|
|
2022-04-24 17:14:33 +01:00
|
|
|
def seed(self, seed: Optional[dict | int] = None) -> list:
|
2021-09-13 20:08:01 +02:00
|
|
|
seeds = []
|
|
|
|
if isinstance(seed, dict):
|
|
|
|
for key, seed_key in zip(self.spaces, seed):
|
|
|
|
assert key == seed_key, print(
|
|
|
|
"Key value",
|
|
|
|
seed_key,
|
|
|
|
"in passed seed dict did not match key value",
|
|
|
|
key,
|
|
|
|
"in spaces Dict.",
|
|
|
|
)
|
|
|
|
seeds += self.spaces[key].seed(seed[seed_key])
|
|
|
|
elif isinstance(seed, int):
|
|
|
|
seeds = super().seed(seed)
|
|
|
|
try:
|
|
|
|
subseeds = self.np_random.choice(
|
|
|
|
np.iinfo(int).max,
|
|
|
|
size=len(self.spaces),
|
|
|
|
replace=False, # unique subseed for each subspace
|
|
|
|
)
|
|
|
|
except ValueError:
|
|
|
|
subseeds = self.np_random.choice(
|
|
|
|
np.iinfo(int).max,
|
|
|
|
size=len(self.spaces),
|
|
|
|
replace=True, # we get more than INT_MAX subspaces
|
|
|
|
)
|
2021-09-02 22:15:34 +08:00
|
|
|
|
2021-09-13 20:08:01 +02:00
|
|
|
for subspace, subseed in zip(self.spaces.values(), subseeds):
|
|
|
|
seeds.append(subspace.seed(int(subseed))[0])
|
|
|
|
elif seed is None:
|
|
|
|
for space in self.spaces.values():
|
|
|
|
seeds += space.seed(seed)
|
|
|
|
else:
|
|
|
|
raise TypeError("Passed seed not of an expected type: dict or int or None")
|
2021-09-02 22:15:34 +08:00
|
|
|
|
2021-09-13 20:08:01 +02:00
|
|
|
return seeds
|
2017-09-05 08:49:43 -07:00
|
|
|
|
2022-01-24 23:22:11 +01:00
|
|
|
def sample(self) -> dict:
|
2017-09-05 08:49:43 -07:00
|
|
|
return OrderedDict([(k, space.sample()) for k, space in self.spaces.items()])
|
|
|
|
|
2022-01-24 23:22:11 +01:00
|
|
|
def contains(self, x) -> bool:
|
2017-09-05 08:49:43 -07:00
|
|
|
if not isinstance(x, dict) or len(x) != len(self.spaces):
|
|
|
|
return False
|
|
|
|
for k, space in self.spaces.items():
|
|
|
|
if k not in x:
|
|
|
|
return False
|
|
|
|
if not space.contains(x[k]):
|
|
|
|
return False
|
|
|
|
return True
|
|
|
|
|
2019-04-19 23:19:07 +02:00
|
|
|
def __getitem__(self, key):
|
|
|
|
return self.spaces[key]
|
2021-07-29 02:26:34 +02:00
|
|
|
|
2021-09-01 09:09:20 -07:00
|
|
|
def __setitem__(self, key, value):
|
|
|
|
self.spaces[key] = value
|
|
|
|
|
2020-07-11 01:39:21 +02:00
|
|
|
def __iter__(self):
|
2021-11-14 14:50:23 +01:00
|
|
|
yield from self.spaces
|
2019-04-19 23:19:07 +02:00
|
|
|
|
2022-01-24 23:22:11 +01:00
|
|
|
def __len__(self) -> int:
|
2021-07-29 22:29:10 +02:00
|
|
|
return len(self.spaces)
|
|
|
|
|
2022-01-24 23:22:11 +01:00
|
|
|
def __repr__(self) -> str:
|
2021-07-29 15:39:42 -04:00
|
|
|
return (
|
|
|
|
"Dict("
|
|
|
|
+ ", ".join([str(k) + ":" + str(s) for k, s in self.spaces.items()])
|
|
|
|
+ ")"
|
|
|
|
)
|
2017-09-05 08:49:43 -07:00
|
|
|
|
2022-01-24 23:22:11 +01:00
|
|
|
def to_jsonable(self, sample_n: list) -> dict:
|
2017-09-05 08:49:43 -07:00
|
|
|
# serialize as dict-repr of vectors
|
2021-07-29 15:39:42 -04:00
|
|
|
return {
|
|
|
|
key: space.to_jsonable([sample[key] for sample in sample_n])
|
|
|
|
for key, space in self.spaces.items()
|
|
|
|
}
|
2017-09-05 08:49:43 -07:00
|
|
|
|
2022-01-24 23:22:11 +01:00
|
|
|
def from_jsonable(self, sample_n: dict[str, list]) -> list:
|
|
|
|
dict_of_list: dict[str, list] = {}
|
2017-09-05 08:49:43 -07:00
|
|
|
for key, space in self.spaces.items():
|
|
|
|
dict_of_list[key] = space.from_jsonable(sample_n[key])
|
|
|
|
ret = []
|
2022-01-24 23:22:11 +01:00
|
|
|
n_elements = len(next(iter(dict_of_list.values())))
|
|
|
|
for i in range(n_elements):
|
2017-09-05 08:49:43 -07:00
|
|
|
entry = {}
|
|
|
|
for key, value in dict_of_list.items():
|
|
|
|
entry[key] = value[i]
|
|
|
|
ret.append(entry)
|
|
|
|
return ret
|