File size: 12,316 Bytes
079c32c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 |
from typing import Any, Union, List
from collections import namedtuple
from easydict import EasyDict
import gym
import copy
import numpy as np
from overcooked_ai_py.mdp.actions import Action, Direction
from overcooked_ai_py.mdp.overcooked_mdp import PlayerState, OvercookedGridworld, OvercookedState, ObjectState, \
SoupState, Recipe
from overcooked_ai_py.mdp.overcooked_env import OvercookedEnv, DEFAULT_ENV_PARAMS
from ding.envs import BaseEnv
from ding.utils import ENV_REGISTRY, deep_merge_dicts
OvercookEnvTimestep = namedtuple('OvercookEnvTimestep', ['obs', 'reward', 'done', 'info'])
# n, s = Direction.NORTH, Direction.SOUTH
# e, w = Direction.EAST, Direction.WEST
# stay, interact = Action.STAY, Action.INTERACT
# Action.ALL_ACTIONS: [n, s, e, w, stay, interact]
@ENV_REGISTRY.register('overcooked')
class OvercookEnv(BaseEnv):
config = EasyDict(
dict(
env_name="cramped_room",
horizon=400,
concat_obs=False,
action_mask=True,
shape_reward=True,
)
)
def __init__(self, cfg) -> None:
self._cfg = deep_merge_dicts(self.config, cfg)
self._env_name = self._cfg.env_name
self._horizon = self._cfg.horizon
self._concat_obs = self._cfg.concat_obs
self._action_mask = self._cfg.action_mask
self._shape_reward = self._cfg.shape_reward
self.mdp = OvercookedGridworld.from_layout_name(self._env_name)
self.base_env = OvercookedEnv.from_mdp(self.mdp, horizon=self._horizon, info_level=0)
# rightnow overcook environment encoding only support 2 agent game
self.agent_num = 2
self.action_dim = len(Action.ALL_ACTIONS)
self.action_space = gym.spaces.Discrete(len(Action.ALL_ACTIONS))
# set up obs shape
featurize_fn = lambda mdp, state: mdp.lossless_state_encoding(state)
self.featurize_fn = featurize_fn
dummy_mdp = self.base_env.mdp
dummy_state = dummy_mdp.get_standard_start_state()
obs_shape = self.featurize_fn(dummy_mdp, dummy_state)[0].shape # (5, 4, 26)
obs_shape = (obs_shape[-1], *obs_shape[:-1]) # permute channel first
if self._concat_obs:
obs_shape = (obs_shape[0] * 2, *obs_shape[1:])
else:
obs_shape = (2, ) + obs_shape
self.observation_space = gym.spaces.Box(low=0, high=1, shape=obs_shape, dtype=np.int64)
if self._action_mask:
self.observation_space = gym.spaces.Dict(
{
'agent_state': self.observation_space,
'action_mask': gym.spaces.Box(
low=0, high=1, shape=(self.agent_num, self.action_dim), dtype=np.int64
)
}
)
self.reward_space = gym.spaces.Box(low=0, high=100, shape=(1, ), dtype=np.float32)
def seed(self, seed: int, dynamic_seed: bool = True) -> None:
self._seed = seed
self._dynamic_seed = dynamic_seed
np.random.seed(self._seed)
def close(self) -> None:
# Note: the real env instance only has a empty close method, only pas
pass
def random_action(self):
return [self.action_space.sample() for _ in range(self.agent_num)]
def step(self, action):
assert all(self.action_space.contains(a) for a in action), "%r (%s) invalid" % (action, type(action))
agent_action, other_agent_action = [Action.INDEX_TO_ACTION[a] for a in action]
if self.agent_idx == 0:
joint_action = (agent_action, other_agent_action)
else:
joint_action = (other_agent_action, agent_action)
next_state, reward, done, env_info = self.base_env.step(joint_action)
reward = np.array([float(reward)])
self._eval_episode_return += reward
if self._shape_reward:
self._eval_episode_return += sum(env_info['shaped_r_by_agent'])
reward += sum(env_info['shaped_r_by_agent'])
ob_p0, ob_p1 = self.featurize_fn(self.mdp, next_state)
ob_p0, ob_p1 = self.obs_preprocess(ob_p0), self.obs_preprocess(ob_p1)
if self.agent_idx == 0:
both_agents_ob = [ob_p0, ob_p1]
else:
both_agents_ob = [ob_p1, ob_p0]
if self._concat_obs:
both_agents_ob = np.concatenate(both_agents_ob)
else:
both_agents_ob = np.stack(both_agents_ob)
env_info["policy_agent_idx"] = self.agent_idx
env_info["eval_episode_return"] = self._eval_episode_return
env_info["other_agent_env_idx"] = 1 - self.agent_idx
action_mask = self.get_action_mask()
if self._action_mask:
obs = {
"agent_state": both_agents_ob,
# "overcooked_state": self.base_env.state,
"action_mask": action_mask
}
else:
obs = both_agents_ob
return OvercookEnvTimestep(obs, reward, done, env_info)
def obs_preprocess(self, obs):
obs = obs.transpose(2, 0, 1)
return obs
def reset(self):
self.base_env.reset()
self._eval_episode_return = 0
self.mdp = self.base_env.mdp
# random init agent index
self.agent_idx = np.random.choice([0, 1])
ob_p0, ob_p1 = self.featurize_fn(self.mdp, self.base_env.state)
ob_p0, ob_p1 = self.obs_preprocess(ob_p0), self.obs_preprocess(ob_p1)
if self.agent_idx == 0:
both_agents_ob = [ob_p0, ob_p1]
else:
both_agents_ob = [ob_p1, ob_p0]
if self._concat_obs:
both_agents_ob = np.concatenate(both_agents_ob)
else:
both_agents_ob = np.stack(both_agents_ob)
action_mask = self.get_action_mask()
if self._action_mask:
obs = {"agent_state": both_agents_ob, "action_mask": action_mask}
else:
obs = both_agents_ob
return obs
def get_available_actions(self):
return self.mdp.get_actions(self.base_env.state)
def get_action_mask(self):
available_actions = self.get_available_actions()
action_masks = np.zeros((self.agent_num, self.action_dim)).astype(np.int64)
for i in range(self.action_dim):
if Action.INDEX_TO_ACTION[i] in available_actions[0]:
action_masks[0][i] = 1
if Action.INDEX_TO_ACTION[i] in available_actions[1]:
action_masks[1][i] = 1
return action_masks
def __repr__(self):
return "DI-engine Overcooked Env"
@ENV_REGISTRY.register('overcooked_game')
class OvercookGameEnv(BaseEnv):
config = EasyDict(
dict(
env_name="cramped_room",
horizon=400,
concat_obs=False,
action_mask=False,
shape_reward=True,
)
)
def __init__(self, cfg) -> None:
self._cfg = deep_merge_dicts(self.config, cfg)
self._env_name = self._cfg.env_name
self._horizon = self._cfg.horizon
self._concat_obs = self._cfg.concat_obs
self._action_mask = self._cfg.action_mask
self._shape_reward = self._cfg.shape_reward
self.mdp = OvercookedGridworld.from_layout_name(self._env_name)
self.base_env = OvercookedEnv.from_mdp(self.mdp, horizon=self._horizon, info_level=0)
# rightnow overcook environment encoding only support 2 agent game
self.agent_num = 2
self.action_dim = len(Action.ALL_ACTIONS)
self.action_space = gym.spaces.Discrete(len(Action.ALL_ACTIONS))
# set up obs shape
featurize_fn = lambda mdp, state: mdp.lossless_state_encoding(state)
self.featurize_fn = featurize_fn
dummy_mdp = self.base_env.mdp
dummy_state = dummy_mdp.get_standard_start_state()
obs_shape = self.featurize_fn(dummy_mdp, dummy_state)[0].shape # (5, 4, 26)
obs_shape = (obs_shape[-1], *obs_shape[:-1]) # permute channel first
if self._concat_obs:
obs_shape = (obs_shape[0] * 2, *obs_shape[1:])
else:
obs_shape = (2, ) + obs_shape
self.observation_space = gym.spaces.Box(low=0, high=1, shape=obs_shape, dtype=np.int64)
if self._action_mask:
self.observation_space = gym.spaces.Dict(
{
'agent_state': self.observation_space,
'action_mask': gym.spaces.Box(
low=0, high=1, shape=(self.agent_num, self.action_dim), dtype=np.int64
)
}
)
self.reward_space = gym.spaces.Box(low=0, high=100, shape=(1, ), dtype=np.float32)
def seed(self, seed: int, dynamic_seed: bool = True) -> None:
self._seed = seed
self._dynamic_seed = dynamic_seed
np.random.seed(self._seed)
def close(self) -> None:
# Note: the real env instance only has a empty close method, only pass
pass
def random_action(self):
return [self.action_space.sample() for _ in range(self.agent_num)]
def step(self, action):
assert all(self.action_space.contains(a) for a in action), "%r (%s) invalid" % (action, type(action))
agent_action, other_agent_action = [Action.INDEX_TO_ACTION[a] for a in action]
if self.agent_idx == 0:
joint_action = (agent_action, other_agent_action)
else:
joint_action = (other_agent_action, agent_action)
next_state, reward, done, env_info = self.base_env.step(joint_action)
reward = np.array([float(reward)])
self._eval_episode_return += reward
if self._shape_reward:
self._eval_episode_return += sum(env_info['shaped_r_by_agent'])
reward += sum(env_info['shaped_r_by_agent'])
ob_p0, ob_p1 = self.featurize_fn(self.mdp, next_state)
ob_p0, ob_p1 = self.obs_preprocess(ob_p0), self.obs_preprocess(ob_p1)
if self.agent_idx == 0:
both_agents_ob = [ob_p0, ob_p1]
else:
both_agents_ob = [ob_p1, ob_p0]
if self._concat_obs:
both_agents_ob = np.concatenate(both_agents_ob)
else:
both_agents_ob = np.stack(both_agents_ob)
env_info["policy_agent_idx"] = self.agent_idx
env_info["eval_episode_return"] = self._eval_episode_return
env_info["other_agent_env_idx"] = 1 - self.agent_idx
action_mask = self.get_action_mask()
if self._action_mask:
obs = {"agent_state": both_agents_ob, "action_mask": action_mask}
else:
obs = both_agents_ob
return OvercookEnvTimestep(obs, reward, done, env_info)
def obs_preprocess(self, obs):
obs = obs.transpose(2, 0, 1)
return obs
def reset(self):
self.base_env.reset()
self._eval_episode_return = 0
self.mdp = self.base_env.mdp
# random init agent index
self.agent_idx = np.random.choice([0, 1])
#fix init agent index
self.agent_idx = 0
ob_p0, ob_p1 = self.featurize_fn(self.mdp, self.base_env.state)
ob_p0, ob_p1 = self.obs_preprocess(ob_p0), self.obs_preprocess(ob_p1)
if self.agent_idx == 0:
both_agents_ob = [ob_p0, ob_p1]
else:
both_agents_ob = [ob_p1, ob_p0]
if self._concat_obs:
both_agents_ob = np.concatenate(both_agents_ob)
else:
both_agents_ob = np.stack(both_agents_ob)
action_mask = self.get_action_mask()
if self._action_mask:
obs = {"agent_state": both_agents_ob, "action_mask": action_mask}
else:
obs = both_agents_ob
return obs
def get_available_actions(self):
return self.mdp.get_actions(self.base_env.state)
def get_action_mask(self):
available_actions = self.get_available_actions()
action_masks = np.zeros((self.agent_num, self.action_dim)).astype(np.int64)
for i in range(self.action_dim):
if Action.INDEX_TO_ACTION[i] in available_actions[0]:
action_masks[0][i] = 1
if Action.INDEX_TO_ACTION[i] in available_actions[1]:
action_masks[1][i] = 1
return action_masks
def __repr__(self):
return "DI-engine Overcooked GameEnv"
|