-
Notifications
You must be signed in to change notification settings - Fork 18
/
play.py
53 lines (46 loc) · 1.99 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
import torch
from torch import device
import numpy as np
import cv2
from gym import wrappers
from mujoco_py import GlfwContext
GlfwContext(offscreen=True)
from mujoco_py.generated import const
class Play:
def __init__(self, env, agent, max_episode=4):
self.env = env
self.env = wrappers.Monitor(env, "./videos", video_callable=lambda episode_id: True, force=True)
self.max_episode = max_episode
self.agent = agent
self.agent.load_weights()
self.agent.set_to_eval_mode()
self.device = device("cuda" if torch.cuda.is_available() else "cpu")
def evaluate(self):
for _ in range(self.max_episode):
env_dict = self.env.reset()
state = env_dict["observation"]
achieved_goal = env_dict["achieved_goal"]
desired_goal = env_dict["desired_goal"]
while np.linalg.norm(achieved_goal - desired_goal) <= 0.05:
env_dict = self.env.reset()
state = env_dict["observation"]
achieved_goal = env_dict["achieved_goal"]
desired_goal = env_dict["desired_goal"]
done = False
episode_reward = 0
while not done:
action = self.agent.choose_action(state, desired_goal, train_mode=False)
next_env_dict, r, done, _ = self.env.step(action)
next_state = next_env_dict["observation"]
next_desired_goal = next_env_dict["desired_goal"]
episode_reward += r
state = next_state.copy()
desired_goal = next_desired_goal.copy()
I = self.env.render(mode="human") # mode = "rgb_array
# self.env.viewer.cam.type = const.CAMERA_FREE
# self.env.viewer.cam.fixedcamid = 0
# I = cv2.cvtColor(I, cv2.COLOR_RGB2BGR)
# cv2.imshow("I", I)
# cv2.waitKey(2)
print(f"episode_reward:{episode_reward:3.3f}")
self.env.close()