-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
513 lines (480 loc) · 15.4 KB
/
utils.py
File metadata and controls
513 lines (480 loc) · 15.4 KB
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
from asyncio.mixins import _global_lock
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 terminalCost(X, goal_coord):
'''
Generates terminal cost
for environment
_______________________
returns the terminal cost for every state
'''
q = np.ones(X.shape)*np.inf
# Part A
if len(goal_coord) == 2:
q[goal_coord[0],goal_coord[1]] = 0
# Part B
else:
for n in range(0,len(goal_coord)):
q[goal_coord[n][0],goal_coord[n][1],:,:,:,n,:,:] = 0
return q
def invalidAction_A(x,u,info,walls):
'''
Checks if a combination of
state and action are valid for Part A.
__________________________
returns true if combination is invalid
returns false if combination is valid
'''
# if on border square
if x[0] == info['height']-1 or x[1] == info['height']-1 or x[0]==0 or x[1]==0:
case = True # all border squares are walls in the environments
# if in closed door
elif x[3] == 0 and all([x[0],x[1]] == info['door_pos']):
case = True
# if attempting to pick up key
elif u == 3:
# Has the key already been picked up?
key_x = info['key_pos'][0] # define indices of key as this to make simpler
key_y = info['key_pos'][1]
if x[4] == 1:
case = True
# Adjacent on cardinals
elif [x[0],x[1]] == [key_x,key_y+1]: # below
if x[2] == 1:
case = False # agent is facing up
else:
case = True
elif [x[0],x[1]] == [key_x,key_y-1]: # above
if x[2] == 3:
case = False # agent is facing down
else:
case = True
elif [x[0],x[1]] == [key_x+1,key_y]: # right
if x[2] == 0:
case = False # agent is facing left
else:
case = True
elif [x[0],x[1]] == [key_x-1,key_y]: # left
if x[2] == 2:
case = False # agent is facing right
else:
case = True
# Not adjacent on cardinals
else:
case = True
# if attempting to open door
elif u == 4:
# agent not holding key
if x[4] != 1:
case = True # agent was not holding key and attempted to open door
# door already open
elif x[3] == 1:
case = True # agent tried to open door but was already open
# Adjacent on left (never optimal to open door from right)
elif [x[0],x[1]] == [info['door_pos'][0]-1,info['door_pos'][1]]:
# check if oriented correctly
if x[2] == 2 and info['door_pos'][0] > x[0]:
case = False # agent is facing right and door on right
else:
case = True # agent not facing proper direction
# Not adjacent on cardinals
else:
case = True
# if in a wall
elif [x[0],x[1]] in walls:
case = True
else:
case = False
return case
def invalidAction_B(x,u,info,walls,key_loc,goal_loc):
'''
Checks if a combination of
state and action are valid for Part B.
__________________________
returns true if combination is invalid
returns false if combination is valid
'''
#key_loc = {0:[1,1],1:[2,3],2:[1,6]} for reference
# if on border square
if x[0] == info['height']-1 or x[1] == info['height']-1 or x[0]==0 or x[1]==0:
case = True # all border squares are walls in the environments
# if in door 1 and it is closed
elif x[3] == 0 and [x[0],x[1]] == [4,2]:
case = True
# if in door 2 and it is closed
elif x[4] == 0 and [x[0],x[1]] == [4,5]:
case = True
# if attempting to pick up key
elif u == 3:
key_coords = np.asarray(key_loc[x[6]]) # define indices of key as this to make simpler
agent_coords = np.asarray([x[0],x[1]])
# Has the key already been picked up?
if x[7] == 1:
case = True
# Adjacent on cardinals
elif all(agent_coords == key_coords+[0,1]): # below
if x[2] == 1:
case = False # agent is facing up
else:
case = True
elif all(agent_coords == key_coords+[0,-1]): # above
if x[2] == 3:
case = False # agent is facing down
else:
case = True
elif all(agent_coords == key_coords + [1,0]): # right
if x[2] == 0:
case = False # agent is facing left
else:
case = True
elif all(agent_coords == key_coords + [-1,0]): # left
if x[2] == 2:
case = False # agent is facing right
else:
case = True
# Not adjacent on cardinals
else:
case = True
# if attempting to open door
elif u == 4:
# agent not holding key
if x[7] != 1:
case = True # agent was not holding key and attempted to open a door
# Adjacent on left of door 1 (never optimal to open door from right)
elif [x[0],x[1]] == [3,2]:
# check if door 1 already open
if x[3] == 1:
case = True
# door closed, now check if oriented correctly
elif x[2] == 2:
# check if facing right
case = False # agent is facing right and door on right
else:
case = True # agent not facing proper direction
# Adjacent on left of door 2 (never optimal to open door from right)
elif [x[0],x[1]] == [3,5]:
# check if door 2 already open
if x[4] == 1:
case = True
# door closed, now check if oriented correctly
elif x[2] == 2:
# check if facing right
case = False # agent is facing right and door on right
else:
case = True # agent not facing proper direction
else: # not adjacent to door
case = True
# if in a wall
elif [x[0],x[1]] in walls:
case = True
else:
case = False
return case
def stageCost_A(x,u,info,U,walls):
'''
Assigns cost to action for
combination of current state and
control input.
If action is invalid assings inf,
otherwise assigns associated control
cost from U
________________________________
returns l, the cost of x,u
'''
if invalidAction_A(x,u,info,walls) == True:
# Invalid Action
l = np.inf
else:
# Valid Action
l = U[u]
return l
def stageCost_B(x,u,info,U,walls,key_loc,goal_loc):
'''
Assigns cost to action for
combination of current state and
control input.
If action is invalid assings inf,
otherwise assigns associated control
cost from U
________________________________
returns l, the cost of x,u
'''
if invalidAction_B(x,u,info,walls,key_loc,goal_loc) == True:
# Invalid Action
l = np.inf
else:
# Valid Action
l = U[u]
return l
def motionModel_A(x,u,info,walls):
'''
Alters the state vector
to next state based on control.
If the control would have the
state move to an invalid state,
the state remains the same.
_______________________________
returns x, the altered state
'''
x_p = [x[0],x[1],x[2],x[3],x[4]]
# If invalid action, stay at current state
if invalidAction_A(x,u,info,walls) == True:
# keep state the same
pass
# Already in Goal
elif [x_p[0],x_p[1]] == [info['goal_pos'][0],info['goal_pos'][1]]:
# No reason to move
pass
# Valid Action
else:
# Move Forward
if u == 0:
# Move Left
if x[2] == 0:
x_p[0] = x_p[0] - 1
# Move Up
elif x[2] == 1:
x_p[1] = x_p[1] - 1
# Move Right
elif x[2] == 2:
x_p[0] = x_p[0] + 1
# Move Down
elif x[2] == 3:
x_p[1] = x_p[1] + 1
# Turn Left (counter-clockwise)
elif u == 1:
if x[2] == 0: # decrementing by 1 would be outside index range
x_p[2] = 3
else:
x_p[2] = x_p[2] - 1 # decrement by 1
# Turn Right (clockwise)
elif u == 2:
if x[2] == 3: # incrementing by 1 would be outside index range
x_p[2] = 0
else:
x_p[2] = x_p[2] + 1 # increment by 1
# Pickup Key
elif u == 3:
x_p[4] = 1 # 0 means key is still in env
# Open Door
elif u == 4:
x_p[3] = 1 # 0 is closed door state
# return modified state
return x_p
def motionModel_B(x,u,info,walls,key_loc,goal_loc):
'''
Alters the state vector
to next state based on control.
If the control would have the
state move to an invalid state,
the state remains the same.
_______________________________
returns x, the altered state
'''
x_p = [x[0],x[1],x[2],x[3],x[4],x[5],x[6],x[7]]
# If invalid action, stay at current state
if invalidAction_B(x,u,info,walls,key_loc,goal_loc) == True:
# keep state the same
pass
# already in any of the goal locations
elif [x_p[0],x_p[1]] == [5,1] or [x_p[0],x_p[1]] == [6,3] or [x_p[0],x_p[1]] == [5,6]:
# No reason to move
'''
THIS MIGHT CAUSE PROBLEMS IN SOME SCENARIOS
(if passing through one goal to get to another would be optimal)
'''
pass
# Valid Action
else:
# Move Forward
if u == 0:
# Move Left
if x[2] == 0:
x_p[0] = x_p[0] - 1
# Move Up
elif x[2] == 1:
x_p[1] = x_p[1] - 1
# Move Right
elif x[2] == 2:
x_p[0] = x_p[0] + 1
# Move Down
elif x[2] == 3:
x_p[1] = x_p[1] + 1
# Turn Left (counter-clockwise)
elif u == 1:
if x[2] == 0: # decrementing by 1 would be outside index range
x_p[2] = 3
else:
x_p[2] = x_p[2] - 1 # decrement by 1
# Turn Right (clockwise)
elif u == 2:
if x[2] == 3: # incrementing by 1 would be outside index range
x_p[2] = 0
else:
x_p[2] = x_p[2] + 1 # increment by 1
# Pickup Key
elif u == 3:
x_p[7] = 1 # 0 means key is still in env
# Open Door
elif u == 4:
if x[1] == 2: # next to door 1
x_p[3] = 1 # open door 1
else: # next to door 2
x_p[4] = 1 # open door 2
# return modified state
return x_p
def step_cost(action):
'''
Returns the cost of an associated action
----------------------------------
'''
# Costs dictionary
costs = {
0: 3,
1: 3,
2: 3,
3: 1,
4: 1
}
return costs[action] # 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
}
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])
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