-
Notifications
You must be signed in to change notification settings - Fork 2
/
agents_model.py
218 lines (178 loc) · 8.32 KB
/
agents_model.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
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
import importlib
import pickle
from datetime import datetime
import json
import os
import shutil
from threading import Semaphore
import torch
from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot, pyqtProperty
from policy_nets.base_policy_net import PolicyNet
from train_policy_net import train_policy
from train_reward_net import train_reward
from trainer import TrainingManager
from utils import *
class AgentsModel(QObject):
environment_added = pyqtSignal(str)
environment_deleted = pyqtSignal(str)
agent_added = pyqtSignal(str, str) # TODO cambiare
agent_updated = pyqtSignal(str, str)
agent_deleted = pyqtSignal(str, str) # TODO cambiare
def __init__(self):
super().__init__(parent=None)
self._agents = {}
self.agents_dir = policies_dir()
self.rewards_dir = rewards_dir()
self.games_dir = games_dir()
self.device = auto_device()
self.locks = {}
self.load_from_disk()
def load_from_disk(self):
agents_loaded = 0
envs_loaded = 0
# for each environment in agents_dir
for env in os.listdir(self.agents_dir):
env_dir = os.path.join(self.agents_dir, env)
if not os.path.isdir(env_dir) or env == "__pycache__":
continue
# env is a name (string) of an environment
if env not in self._agents:
self.add_environment(env)
envs_loaded += 1
# for each trained policy (of this type and in this environment)
for trained_policy in os.listdir(env_dir):
trained_policy_dir = os.path.join(env_dir, trained_policy)
if not os.path.isdir(trained_policy_dir):
continue
trained_policy_info = os.path.join(trained_policy_dir, "training.json")
try:
self.add_agent(env, trained_policy)
agents_loaded += 1
except FileNotFoundError:
print("File not found: " + trained_policy_info)
print("loaded {} agents from {} environments".format(agents_loaded, envs_loaded))
if os.path.exists(self.games_dir):
# for each environment in games_dir
for env in os.listdir(self.games_dir):
env_dir = os.path.join(self.games_dir, env)
if not os.path.isdir(env_dir):
continue
self.add_environment(env)
def add_environment(self, environment: str) -> bool:
if environment in self._agents:
return False
self._agents[environment] = {}
self.environment_added.emit(environment)
return True
def delete_environment(self, environment: str) -> bool:
if environment not in self._agents:
return False
self._agents.pop(environment)
shutil.rmtree(os.path.join(self.agents_dir, environment), ignore_errors=True)
shutil.rmtree(os.path.join(self.rewards_dir, environment), ignore_errors=True)
shutil.rmtree(os.path.join(self.games_dir, environment), ignore_errors=True)
self.environment_deleted.emit(environment)
return True
def get_environments(self):
return self._agents.keys()
def create_agent(self, environment: str, games: list):
TrainingManager.train_new_agent(environment, games, self, lambda agent: self.agent_updated.emit(environment, agent.key))
def add_agent(self, environment: str, agent_key: str, agent:PolicyNet=None) -> bool:
if environment not in self._agents:
self.add_environment(environment)
if agent_key in self._agents[environment]:
return False
if agent is None:
agent = self.load_agent(environment, agent_key)
self._agents[environment][agent_key] = agent
self.agent_added.emit(environment, agent_key)
self.locks[agent] = Semaphore(1)
return True
def delete_agent(self, environment: str, agent_key: str) -> bool:
if environment not in self._agents or agent_key not in self._agents[environment]:
return False
if TrainingManager.is_agent_training(environment, agent_key):
TrainingManager.interrupt_training(self, environment, agent_key)
agent = self._agents[environment].pop(agent_key)
shutil.rmtree(agent.folder, ignore_errors=True)
self._delete_agent_games(environment, agent)
self.agent_deleted.emit(environment, agent_key)
return True
def _delete_agent_games(self, environment, agent):
games = agent.games
for game in games:
with open(os.path.join("games", environment, game, "game.json"), 'rt') as file:
j = json.load(file)
if not j["to_delete"]:
continue
if self.game_used_by_some_agent(environment, game):
continue
removing_dir = os.path.join("games", environment, game)
shutil.rmtree(removing_dir, ignore_errors=True)
def game_used_by_some_agent(self, environment, game):
for agent_key in self._agents[environment]:
agent = self._agents[environment][agent_key]
if game in agent.games:
return True
return False
def get_agent(self, environment: str, agent_key: str):
try:
return self._agents[environment][agent_key]
except KeyError:
return None
def read_agent_games(self, environment, reward_key):
trained_reward_info = os.path.join(self.rewards_dir, environment, reward_key, "training.json")
try:
with open(trained_reward_info, 'rt') as file:
j = json.load(file)
return j["games"]
except FileNotFoundError:
print("File not found: " + trained_reward_info)
return None
def load_agent(self, environment: str, agent_key: str, num: int = None):
agent_dir = os.path.join(self.agents_dir, environment, agent_key)
# module_path, _ = policy_net_file.rsplit(".", 1)
# net_module = importlib.import_module(".".join(os.path.split(module_path)))
# reward_net = net_module.get_net(get_input_shape(), get_num_actions(), environment, agent_key, folder=agent_dir).to(self.device)
if num is None:
agent = pickle.load(open(os.path.join(agent_dir, "net.pkl"), "rb")).to(self.device).load_last_checkpoint()
else:
agent = pickle.load(open(os.path.join(agent_dir, "net.pkl"), "rb")).to(self.device).load_checkpoint(num)
return agent
# TODO change
def load_agent_value(self, environment: str, agent_key: str):
trained_agent_dir = os.path.join(self.agents_dir, environment, agent_key)
trained_agent_info = os.path.join(trained_agent_dir, "training.json")
try:
with open(trained_agent_info, 'rt') as file:
j = json.load(file)
j["path"] = trained_agent_dir
try:
j["games"] = self.read_agent_games(environment, j["reward_net_key"])
except KeyError:
j["games"] = []
return j
except FileNotFoundError:
print("File not found: " + trained_agent_info)
return None
def get_agents(self, environment: str):
if environment in self._agents:
return self._agents[environment].keys()
return []
def is_agent_training(self, environment, agent_key):
return TrainingManager.is_agent_training(environment, agent_key)
def resume_agent_training(self, environment, agent_key):
TrainingManager.resume_agent_training(environment, self, self._agents[environment][agent_key], lambda agent: self.agent_updated.emit(environment, agent_key))
def play_agent(self, environment, agent_key):
self.locks[self._agents[environment][agent_key]].release()
self.get_agent(environment, agent_key).play()
self.agent_updated.emit(environment, agent_key)
def pause_agent(self, environment, agent_key):
self.locks[self._agents[environment][agent_key]].acquire()
self.get_agent(environment, agent_key).pause()
self.agent_updated.emit(environment, agent_key)
def get_agent_lock(self, environment, agent_key):
agent = self.get_agent(environment, agent_key)
if agent is None:
return Semaphore(1)
return self.locks[agent]