-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplay.py
176 lines (154 loc) · 6.66 KB
/
play.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
import sys
from gym.wrappers.monitoring.video_recorder import VideoRecorder
from algorithm.replay_buffer import goal_based_process
from common import get_args
from env_ext import make_env
from envs import register_custom_envs
from mpc import MPCDebugPlot
from policies import Policy, make_policy
class Player:
policy: Policy = None
debug_plot: MPCDebugPlot = None
# debug_plot: MPCDebugPlotSmall = None
mpc_policy = False
def __init__(self, args):
# initialize environment
self.args = args
self.env = make_env(args)
self.info = []
self.test_rollouts = 1
self.mode = args.play_mode
self.policy = make_policy(args)
self.policy.set_envs(envs=[self.env])
if args.play_policy in ['MPCRLPolicy', 'MPCPolicy']:
self.mpc_policy = True
if self.mode == 'plot':
self.sim_length = args.timesteps
self.debug_plot = MPCDebugPlot(args, sim_length=self.sim_length, model=self.policy.model)
# self.debug_plot = MPCDebugPlotSmall(args, sim_length=self.sim_length, model=self.policy.model)
def play(self):
# play policy on env
env = self.env
acc_sum, obs = 0.0, []
err_sum = 0
# seed = 5995
# seed = 1240
# seed = 4014
# seed = 3019
seed = 1144
env.np_random.seed(seed) # TODO remove
for i in range(self.test_rollouts):
env.np_random.seed(seed + i)
print('Seed: ', seed + i)
self.policy.reset()
ob = env.reset()
obs.append(goal_based_process(ob))
if args.play_policy in ['MPCPolicy']:
self.policy.set_sub_goals([ob['desired_goal']])
if self.debug_plot:
info = self.policy.initial_info([ob])[0]
self.debug_plot.createPlot(xinit=info['xinit'], pred_x=info['pred_x'],
pred_u=info['pred_u'], k=0, parameters=info['parameters'], obs=ob)
prev_ob = ob
sim_timestep = 0
for timestep in range(args.timesteps):
# start = time.time()
actions, infos = self.policy.predict(obs=[ob])
action = actions[0]
ob, _, _, env_info = env.step(action)
# end = time.time()
# print('Execution time {}: {}'.format(timestep, end - start))
if self.mpc_policy:
info = infos[0]
# sys.stderr.write("FORCESPRO took {} iterations and {} seconds to solve the problem.\n" \
# .format(info['info'].it, info['info'].solvetime))
mpc_info = info
next_x = mpc_info['next_x']
target_x = mpc_info['target_x']
pred_x = mpc_info['pred_x']
pred_u = mpc_info['pred_u']
parameters = mpc_info['parameters']
if self.debug_plot:
print('t:', sim_timestep)
self.debug_plot.updatePlots(next_x=next_x, target_x=target_x, pred_x=pred_x, pred_u=pred_u,
k=sim_timestep,
parameters=parameters, ob=prev_ob, new_ob=ob)
sim_timestep = sim_timestep + 1
# print('Reward: ', env_info['Rewards'])
# print('MPC flag: ', mpc_info['exitflag'])
if mpc_info['exitflag'] != 1:
print(f"""FORCESPRO error {mpc_info['exitflag']}""")
err_sum += 1
if ob['collision_check']:
sys.stderr.write("Collision on {}")
if self.debug_plot:
self.debug_plot.show()
else:
env.render()
pass
if env_info['Success']:
print('\n Success. Exiting. Time steps: ', timestep)
if self.debug_plot:
self.debug_plot.show()
else:
env.render()
pass
break
if self.debug_plot:
if timestep == args.timesteps - 1:
self.debug_plot.show()
else:
self.debug_plot.draw()
# input('check')
else:
env.render()
pass
else:
env.render()
if env_info['Success']:
print('Success. Exiting. Time steps: ', timestep)
break
prev_ob = ob
print('Collisions: ', env.collisions)
print('Errors: ', err_sum)
def record_video(self, raw_path="myrecord"):
env = self.env
test_col_tolerance = 0
test_rollouts = 30
seed = 3000
env.np_random.seed(seed) # TODO remove
# play policy on env
recorder = VideoRecorder(env.env.env, base_path=raw_path)
recorder.frames_per_sec = 30
acc_sum, obs = 0.0, []
tol_acc_sum = 0.0
for i in range(test_rollouts):
env.np_random.seed(seed + i)
print('Seed: ', seed + i)
self.policy.reset()
ob = env.reset()
env_info = None
print("Rollout {}/{} ...".format(i + 1, test_rollouts))
for timestep in range(self.args.timesteps):
actions, infos = self.policy.predict(obs=[ob])
action = actions[0]
ob, _, _, env_info = env.step(action)
recorder.capture_frame()
if env_info['Success']:
print('Success. Exiting.')
break
acc_sum += env_info['Success']
if env.collisions <= test_col_tolerance:
tol_acc_sum += env_info['Success']
print("... done.")
print('Collisions: ', env.collisions)
print('Success rate: {}'.format(acc_sum / test_rollouts))
print('Success rate (no col): {}'.format(tol_acc_sum / test_rollouts))
recorder.close()
if __name__ == "__main__":
register_custom_envs()
# Call play.py in order to see current policy progress
args = get_args()
player = Player(args)
player.play()
# player.record_video(raw_path="/home/ssc/bachelor-thesis/videos/rollouts_{}_{}".format(args.env, args.play_policy))