-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathheuristic.py
80 lines (63 loc) · 2.28 KB
/
heuristic.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
'''###########################################
CS221 Final Project: Heuristic Controller Implementation
Authors:
Kongphop Wongpattananukul ([email protected])
Pouya Rezazadeh Kalehbasti ([email protected])
Dong Hee Song ([email protected])
###########################################'''
# import library
import sys, math
import numpy as np
import gym
def heuristic(env, s):
'''Heuristic action for LunarLander-v2 using rule-based'''
# get state from LunarLander-v2 environment
p_x, p_y, v_x, v_y, alpha, omega, left, right = s
# initialize the action as "0:Do Nothing"
a = 0
# if-else/condition-based action
# centering the lander by "1:Fire Left Engine" or "3:Fire Right Engine" from absolute position from center
if p_x > 0.1:
a = 1
elif p_x < -0.1:
a = 3
# stabilize the lander by "1:Fire Left Engine" or "3:Fire Right Engine" from abosolute angle from vertical
if alpha > 0.1:
a = 3
elif alpha < -0.1:
a = 1
# stabilize the lander by "1:Fire Left Engine" or "3:Fire Right Engine" from abosolute angular velocity (positive and negative)
if omega > 0.3:
a = 3
elif omega < -0.3:
a = 1
# reduce vertical velocity of the lander by "1:Fire Main Engine"
if v_y < -0.1:
a = 2
# stop all action when landed as "0:Do Nothing"
if left == 1 or right == 1:
a = 0
return a
def demo_heuristic_lander(env, seed=None, render=False):
for _ in range(1000):
env.seed(seed)
total_reward = 0
steps = 0
s = env.reset()
while True:
a = heuristic(env, s)
s, r, done, info = env.step(a)
total_reward += r
if render:
still_open = env.render()
if still_open == False: break
if steps % 20 == 0 or done:
print("observations:", " ".join(["{:+0.2f}".format(x) for x in s]))
print("step {} total_reward {:+0.2f}".format(steps, total_reward))
steps += 1
if done:
break
return total_reward
if __name__ == '__main__':
env = gym.make('LunarLander-v2')
demo_heuristic_lander(env, render=True)