-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcontrol.py
82 lines (64 loc) · 2.26 KB
/
control.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
import argparse
import time
import numpy as np
from gymnasium.wrappers import RecordVideo
from mobrob import get_env, load_policy
from mobrob.utils import BulletVideoRecorder
def simulate(
env_name: str,
policy_name: str,
epochs,
no_gui: bool,
video_path: str,
):
env = get_env(env_name, enable_gui=not no_gui, terminate_on_goal=True)
policy = load_policy(env_name, policy_name)
rewards = []
video_recoder = None
if env_name in ("point", "car", "doggo") and video_path is not None:
env.toggle_render_mode()
env = RecordVideo(env, video_path)
no_gui = (
True # no gui when recording video, this is the limitation of mujoco_py
)
elif env_name in ("drone", "turtlebot3"):
video_recoder = BulletVideoRecorder(env.env.client_id, video_path)
def run():
nonlocal rewards
for _ in range(epochs):
cum_reward = 0
obs, _ = env.reset()
for _ in range(1000):
action, _ = policy.predict(obs, deterministic=True)
obs, r, terminated, _, _ = env.step(action)
if terminated:
obs, _ = env.reset()
cum_reward += r
if not no_gui:
env.render()
if env_name in ("drone", "turtlebot3"):
time.sleep(0.005)
rewards.append(cum_reward)
if video_recoder is not None:
with video_recoder:
run()
else:
run()
print(f"average reward: {np.mean(rewards)}")
print(f"reward stds: {np.std(rewards)}")
print(f"rewards: {rewards}")
if __name__ == "__main__":
args_parser = argparse.ArgumentParser()
args_parser.add_argument("--env-name", type=str, default="point")
args_parser.add_argument("--policy-name", type=str, default="ppo")
args_parser.add_argument("--epochs", type=int, default=5)
args_parser.add_argument("--no-gui", action="store_true", default=False)
args_parser.add_argument("--video-path", type=str, default=None)
args = args_parser.parse_args()
simulate(
env_name=args.env_name,
policy_name=args.policy_name,
epochs=args.epochs,
no_gui=args.no_gui,
video_path=args.video_path,
)