forked from egtaonline/gameanalysis
/
TestbedInterface.py
executable file
·235 lines (190 loc) · 7.51 KB
/
TestbedInterface.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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
#! /usr/bin/env python2.7
from json import loads
from string import join
from copy import deepcopy
import requests
from GameIO import read, read_v3_profile, read_v3_samples_profile, read_v3_players_profile
from Reductions import DPR_profiles
from BasicFunctions import one_line
from RoleSymmetricGame import SampleGame
modifiable_attributes = ["process_memory", "name", "parameter_hash", "active", \
"time_per_sample", "nodes", "samples_per_simulation"]
granularities = ["structure", "summary", "observations", "full"]
class TestbedObject:
def __init__(self, name, obj_type, name_field="", options={}, \
url_options={}, skip_name=False):
self.auth = {'auth_token':"g2LHz1mEtbysFngwLMCz"}
self.url = "http://egtaonline.eecs.umich.edu/api/v3/" + obj_type
data = dict(options)
data.update(self.auth)
ID = name #try treating name as an id
r = requests.get(self.url +"/"+ ID + ".json?" + "&".join([str(k) +"="+ \
str(v) for k,v in url_options.items()]), data=data)
if r.status_code != 200 and not skip_name: #treat name as a name_field
r = requests.get(self.url + ".json", data=data)
if r.status_code == 404:
raise Exception("404 error"+"\n"+r.url+"\n"+r.text)
try:
ID = filter(lambda s: s[name_field] == name, \
loads(r.text)[obj_type])[0]['_id']
except IndexError:
raise Exception("no such "+obj_type[:-1]+": "+name)
self.url += "/" + ID
self.processResponse(r)
def processResponse(self, r):
self.json = r.text
j = loads(r.text)
if isinstance(j, dict):
self.__dict__.update()
elif isinstance(j, list):
map(lambda d: self.__dict__.update(d), j)
else:
raise ValueError(one_line(r.text))
def update(self):
r = requests.get(self.url + ".json", data=self.auth)
self.processResponse(r)
return r.status_code
def __repr__(self):
return join(map(lambda p: one_line(repr(p[0]) + ": " + repr(p[1])), \
self.__dict__.items()), "\n")
class TestbedScheduler(TestbedObject):
def __init__(self, name, scheduler_type="generic"):
TestbedObject.__init__(self, name, scheduler_type+"_schedulers", "name")
def addProfile(self, profile, samples):
data = {'sample_count':samples, 'assignment':str(profile)}
data.update(self.auth)
r = requests.post(self.url + "/add_profile.json", data=data)
return r.status_code
def update(self, **kwds):
assert all((k in modifiable_attributes for k in kwds)), \
"invalid parameter for update"
self.__dict__.update(kwds)
data = {"scheduler":kwds}
data.update(self.auth)
r = requests.put(self.url + ".json", data=data)
return r.status_code
class TestbedSimulator(TestbedObject):
def __init__(self, name):
TestbedObject.__init__(self, name, "simulators", "simulator_fullname")
def updateRoles(self):
r = requests.get(self.url + ".json", data=self.auth)
self.roles = loads(r.text)["roles"]
return r.status_code
def hasRole(self, role):
return any([r["name"] == role for r in self.roles])
def hasStrategy(self, role, strategy):
return self.hasRole(role) and strategy in filter(lambda r: \
r["name"] == role, self.roles)[0]["strategies"]
def addRole(self, role):
data = {"role":role}
data.update(self.auth)
r = requests.post(self.url +"/"+ "add_role.json", data=data)
self.updateRoles()
return r.status_code
def addStrategy(self, role, strategy):
assert self.hasRole(role), "no such role: " + role
data = {"role":role, "strategy":strategy}
data.update(self.auth)
r = requests.post(self.url +"/"+ "add_strategy.json", data=data)
self.updateRoles()
return r.status_code
def removeRole(self, role):
data = {"role":role}
data.update(self.auth)
r = requests.post(self.url +"/"+ "remove_role.json", data=data)
self.updateRoles()
return r.status_code
def removeStrategy(self, role, strategy):
assert self.hasRole(role), "no such role: " + role
data = {"role":role, "strategy":strategy}
data.update(self.auth)
r = requests.post(self.url +"/"+ "remove_strategy.json", data=data)
self.updateRoles()
return r.status_code
class TestbedGame(TestbedObject):
def __init__(self, name, granularity="structure"):
TestbedObject.__init__(self, name, "games", "name", {"granularity": \
granularity})
self.game = read(self.json)
def update(self):
TestbedObject.update(self)
self.game = read(self.json)
class TestbedProfile(TestbedObject):
def __init__(self, ID, granularity="summary"):
TestbedObject.__init__(self, ID, "profiles", url_options= \
{"granularity":granularity}, skip_name=True)
self.granularity = granularity
if self.granularity == "summary":
self.payoffs = read_v3_profile(loads(self.json)[0])
elif self.granularity == "observations":
self.payoffs = read_v3_samples_profile(loads(self.json)[0])
elif self.granularity == "full":
self.payoffs = read_v3_players_profile(loads(self.json)[0])
def update(self):
TestbedObject.update(self)
if self.granularity == "summary":
self.payoffs = read_v3_profile(loads(self.json)[0])
elif self.granularity == "observations":
self.payoffs = read_v3_samples_profile(loads(self.json)[0])
elif self.granularity == "full":
self.payoffs = read_v3_players_profile(loads(self.json)[0])
class DPR_scheduler:
def __init__(self, scheduler_name, game_name, players, samples):
self.TB_scheduler = TestbedScheduler(scheduler_name)
self.TB_game = TestbedGame(game_name)
self.players = {r['name']:p for r,p in zip(self.TB_game.roles, players)}
self.samples = samples
for profile in DPR_profiles(self.TB_game.game, self.players):
self.TB_scheduler.addProfile(profile, self.samples)
def addSamples(self, additional_samples):
self.samples += additional_samples
for profile in DPR_profiles(self.TB_game.game, self.players):
self.TB_scheduler.addProfile(profile, self.samples)
def get_game_data(game_ID):
TB_game = TestbedGame(game_ID, granularity="summary")
GA_game = SampleGame(TB_game.game.roles, TB_game.game.players, \
TB_game.game.strategies)
profile_IDs = [p["_id"] for p in loads(TB_game.json)["profiles"]]
for i,ID in enumerate(profile_IDs):
print i
TB_prof = TestbedProfile(ID, granularity="observations")
GA_game.addProfile(TB_prof.payoffs)
return GA_game
def prep_for_bootstrap(game):
"""
Run this on a credit network game resulting from get_game_data to remove
zeros and ensure that all profiles have the same number of samples.
"""
game.makeArrays()
for p in range(len(game)):
for r in range(len(game.roles)):
for s in range(game.maxStrategies):
if game.counts[p,r,s] > 0:
game.sample_values[p,r,s] = filter(None, \
game.sample_values[p,r,s])
min_len = min(map(len, game.sample_values.flat))
for p in range(len(game)):
for r in range(len(game.roles)):
for s in range(game.maxStrategies):
game.sample_values[p,r,s] = game.sample_values[p,r,s][:min_len]
game.min_samples = game.max_samples = min_len
game.makeArrays()
from argparse import ArgumentParser
def main():
parser = ArgumentParser()
parser.add_argument("scheduler", type=str, help="Name or ID of testbed " +\
"scheduler.")
parser.add_argument("-game", type=str, default="", help="Name or ID of " +\
"testbed scheduler. May be omitted if it's the same as the " +\
"specified scheduler name.")
parser.add_argument("samples", type=int, help="Number of samples to " +\
"schedule for each profile.")
parser.add_argument("players", type=int, nargs="*", help="Number of " +\
"players each reduced-game role should have.")
args = parser.parse_args()
if args.game == "":
args.game = args.scheduler
scheduler = DPR_scheduler(args.scheduler, args.game, args.players, \
args.samples)
if __name__ == "__main__":
main()