-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
204 lines (181 loc) · 5.77 KB
/
utils.py
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
import os
import numpy as np
import gym
import gym_minigrid
import pickle
import matplotlib.pyplot as plt
import imageio
import random
MF = 0 # Move Forward
TL = 1 # Turn Left
TR = 2 # Turn Right
PK = 3 # Pickup Key
UD = 4 # Unlock Door
def step_cost(action):
# You should implement the stage cost by yourself
# Feel free to use it or not
# ************************************************
return 1 # the cost of action
def step(env, action):
'''
Take Action
----------------------------------
actions:
0 # Move forward (MF)
1 # Turn left (TL)
2 # Turn right (TR)
3 # Pickup the key (PK)
4 # Unlock the door (UD)
'''
actions = {
0: env.actions.forward,
1: env.actions.left,
2: env.actions.right,
3: env.actions.pickup,
4: env.actions.toggle
}
_, _, done, _ = env.step(actions[action])
return step_cost(action), done
def generate_random_env(seed, task):
'''
Generate a random environment for testing
-----------------------------------------
seed:
A Positive Integer,
the same seed always produces the same environment
task:
'MiniGrid-DoorKey-5x5-v0'
'MiniGrid-DoorKey-6x6-v0'
'MiniGrid-DoorKey-8x8-v0'
'''
if seed < 0:
seed = np.random.randint(50)
env = gym.make(task)
env.seed(seed)
env.reset()
return env
def load_env(path):
'''
Load Environments
---------------------------------------------
Returns:
gym-environment, info
'''
with open(path, 'rb') as f:
env = pickle.load(f)
info = {
'height': env.height,
'width': env.width,
'init_agent_pos': env.agent_pos,
'init_agent_dir': env.dir_vec,
'door_pos': [],
'door_open': [],
}
for i in range(env.height):
for j in range(env.width):
if isinstance(env.grid.get(j, i),
gym_minigrid.minigrid.Key):
info['key_pos'] = np.array([j, i])
elif isinstance(env.grid.get(j, i),
gym_minigrid.minigrid.Door):
info['door_pos'] = np.array([j, i])
if env.grid.get(j, i).is_open:
info['door_open'].append(True)
else:
info['door_open'].append(False)
elif isinstance(env.grid.get(j, i),
gym_minigrid.minigrid.Goal):
info['goal_pos'] = np.array([j, i])
return env, info
def load_one_random_env(env_path):
with open(env_path, 'rb') as f:
env = pickle.load(f)
info = {
'height': env.height,
'width': env.width,
'init_agent_pos': env.agent_pos,
'init_agent_dir': env.dir_vec,
'door_pos': [],
'door_open': [],
}
for i in range(env.height):
for j in range(env.width):
if isinstance(env.grid.get(j, i),
gym_minigrid.minigrid.Key):
info['key_pos'] = np.array([j, i])
elif isinstance(env.grid.get(j, i),
gym_minigrid.minigrid.Door):
info['door_pos'].append(np.array([j, i]))
if env.grid.get(j, i).is_open:
info['door_open'].append(True)
else:
info['door_open'].append(False)
elif isinstance(env.grid.get(j, i),
gym_minigrid.minigrid.Goal):
info['goal_pos'] = np.array([j, i])
return env, info
def load_random_env(env_folder):
'''
Load a random DoorKey environment
---------------------------------------------
Returns:
gym-environment, info
'''
env_list = [os.path.join(env_folder, env_file) for env_file in os.listdir(env_folder)]
env_path = random.choice(env_list)
with open(env_path, 'rb') as f:
env = pickle.load(f)
info = {
'height': env.height,
'width': env.width,
'init_agent_pos': env.agent_pos,
'init_agent_dir': env.dir_vec,
'door_pos': [],
'door_open': [],
}
for i in range(env.height):
for j in range(env.width):
if isinstance(env.grid.get(j, i),
gym_minigrid.minigrid.Key):
info['key_pos'] = np.array([j, i])
elif isinstance(env.grid.get(j, i),
gym_minigrid.minigrid.Door):
info['door_pos'].append(np.array([j, i]))
if env.grid.get(j, i).is_open:
info['door_open'].append(True)
else:
info['door_open'].append(False)
elif isinstance(env.grid.get(j, i),
gym_minigrid.minigrid.Goal):
info['goal_pos'] = np.array([j, i])
return env, info, env_path
def save_env(env, path):
with open(path, 'wb') as f:
pickle.dump(env, f)
def plot_env(env):
'''
Plot current environment
----------------------------------
'''
img = env.render('rgb_array', tile_size=32)
plt.figure()
plt.imshow(img)
plt.show()
def draw_gif_from_seq(seq, env, path='./gif/doorkey.gif'):
'''
Save gif with a given action sequence
----------------------------------------
seq:
Action sequence, e.g [0,0,0,0] or [MF, MF, MF, MF]
env:
The doorkey environment
'''
with imageio.get_writer(path, mode='I', duration=0.8) as writer:
img = env.render('rgb_array', tile_size=32)
writer.append_data(img)
for act in seq:
img = env.render('rgb_array', tile_size=32)
step(env, act)
writer.append_data(img)
print('GIF is written to {}'.format(path))
return