/
expfw.py
executable file
·346 lines (302 loc) · 11.8 KB
/
expfw.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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
#!/usr/bin/env python
from __future__ import print_function
import os
import sys
from subprocess import Popen, TimeoutExpired
import time
import random
import itertools
def call(*popenargs, timeout=None, **kwargs):
# print("calling {}".format(str(popenargs)))
with Popen(*popenargs, **kwargs) as p:
try:
return p.wait(timeout=timeout)
except:
p.terminate()
p.wait()
raise
class Experiment(object):
NOTDONE = 0
DONE = 1
TIMEOUT = 2
def __init__(self, name, call, group=None):
self.name = name
self.call = call
self.group = group
def parse_log(self, contents):
"""Parse the log file.
Return None if not good, or a dict with the results otherwise.
"""
return None
def get_text(self, res):
"""Given the result of parse_log, return a str representing the main result.
"""
return ""
def get_status(self, filename):
"""Obtain the status of the experiment.
Return a pair:
(Experiment.DONE, res)
(Experiment.TIMEOUT, time)
(Experiment.NOTDONE, None)
"""
if (os.path.isfile(filename)):
try:
with open(filename, 'r') as handle:
res = self.parse_log(handle.read())
if res is not None:
return Experiment.DONE, res
except FileNotFoundError:
return Experiment.NOTDONE, None
timeout_filename = "{}.timeout".format(filename)
if (os.path.isfile(timeout_filename)):
with open(timeout_filename, 'r') as handle:
return Experiment.TIMEOUT, int(handle.read())
return Experiment.NOTDONE, None
def run_experiment(self, timeout, filename):
# remove output and timeout files
if os.path.isfile(filename):
os.unlink(filename)
timeout_filename = "{}.timeout".format(filename)
if os.path.isfile(timeout_filename):
os.unlink(timeout_filename)
# report that we are running the experiment
print("Performing {}... ".format(self.name), end='')
sys.stdout.flush()
try:
with open(filename, 'w+') as out:
call(self.call, stdout=out, stderr=out, timeout=timeout)
except KeyboardInterrupt:
# if CTRL-C was hit, move the file
os.rename(filename, "{}.interrupted".format(filename))
print("interrupted.")
sys.exit()
except OSError:
# OS error (probably missing executable)
print("OS failure. (missing executable?)")
sys.exit()
except TimeoutExpired:
# timeout hit, write current timeout value to timeout file
with open(timeout_filename, 'w') as handle:
handle.write(str(timeout))
print("timeout.")
return Experiment.TIMEOUT, timeout
else:
# experiment finished, either report done or not done...
status, value = self.get_status(filename)
if status == Experiment.DONE:
print("done; {}.".format(self.get_text(value)))
else:
print("not done.")
return status, value
class ExperimentEngine(object):
def __init__(self, **kwargs):
"""Initialize a set of experiments.
Parameters:
- logdir (default "logs")
- timeout (default 1200 seconds)
"""
self.experiments = []
if 'logdir' in kwargs:
self.logdir = kwargs['logdir']
else:
self.logdir = 'logs'
if 'timeout' in kwargs:
self.timeout = int(kwargs['timeout'])
else:
self.timeout = 1200
def todo(self, maxiter=0):
for i in itertools.count():
if maxiter != 0 and i == maxiter:
return
got = False
for e in self.experiments:
logfile = "{}/{}-{}".format(self.logdir, e.name, i)
status, value = e.get_status(logfile)
if status == Experiment.DONE:
got = True
elif status == Experiment.TIMEOUT:
got = True
elif (os.path.isfile(logfile)):
print("{}: not done.".format(e.name))
else:
print("{}: to do.".format(e.name))
if not got:
return
def dry_run(self, maxiter=0):
for i in itertools.count():
if maxiter != 0 and i == maxiter:
return
got = False
for e in self.experiments:
logfile = "{}/{}-{}".format(self.logdir, e.name, i)
status, value = e.get_status(logfile)
if status == Experiment.DONE:
print("{}: {}.".format(e.name, e.get_text(value)))
got = True
elif status == Experiment.TIMEOUT:
print("{}: timeout.".format(e.name))
got = True
elif (os.path.isfile(logfile)):
print("{}: not done.".format(e.name))
if not got:
return
def get_status(self, e, i):
logfile = "{}/{}-{}".format(self.logdir, e.name, i)
status, value = e.get_status(logfile)
return status, value
def get_results(self, maxiter=0):
"""Get all results.
"""
self.results = []
self.timeouts = []
self.notdone = []
for i in itertools.count():
if maxiter != 0 and i == maxiter:
return
results = []
timeouts = []
notdone = []
for e in self.experiments:
status, value = e.get_status("{}/{}-{}".format(self.logdir, e.name, i))
if status == Experiment.DONE:
results.append((e, value))
elif status == Experiment.TIMEOUT:
timeouts.append((e, value))
else:
notdone.append(e)
if len(results) == 0:
return
self.results.append(results)
self.timeouts.append(timeouts)
self.notdone.append(notdone)
def report_group(self, group, maxiter=None):
# create directory
if not os.path.exists(self.logdir):
return
# get experiments...
exps = [x for x in self.experiments if str(x.group) == str(group)]
for i in itertools.count():
if maxiter is not None and maxiter <= i: return
got = False
for e in exps:
logfile = "{}/{}-{}".format(self.logdir, e.name, i)
status, value = e.get_status(logfile)
if status == Experiment.DONE:
print("{}: {}.".format(e.name, e.get_text(value)))
got = True
elif status == Experiment.TIMEOUT:
print("{}: timeout.".format(e.name))
got = True
elif (os.path.isfile(logfile)):
print("{}: not done.".format(e.name))
if not got:
return
def run_group(self, group, maxiter=None):
# create directory
if not os.path.exists(self.logdir):
os.makedirs(self.logdir)
# get experiments...
exps = [x for x in self.experiments if str(x.group) == str(group)]
print("Found {} experiments in group {}".format(len(exps), group))
for i in itertools.count():
if maxiter is not None and maxiter <= i: break
random.shuffle(exps)
for e in exps:
logfile = "{}/{}-{}".format(self.logdir, e.name, i)
status, value = e.get_status(logfile)
if status == Experiment.DONE: continue
if status == Experiment.TIMEOUT and value >= self.timeout: continue
# run experiment
print("It {}: ".format(i), end='')
status, value = e.run_experiment(self.timeout, logfile)
# sleep 1 second to allow OS to swap stuff in or out
time.sleep(1)
def get_groups(self):
return list(set([x.group for x in self.experiments]))
def run_experiments(self, maxiter=None):
"""Run experiments indefinitely.
"""
# create directory
if not os.path.exists(self.logdir):
os.makedirs(self.logdir)
# obtain results so far
self.get_results()
# now move low timeouts to notdone
for i in range(0, len(self.results)):
self.notdone[i] += [x[0] for x in self.timeouts[i] if x[1] < self.timeout]
self.timeouts[i] = [x for x in self.timeouts[i] if x[1] >= self.timeout]
# report current status
n_iterations = len(self.results)
n_successful = sum([len(x) for x in self.results])
n_timeout = sum([len(x) for x in self.timeouts])
n_notdone = n_iterations * len(self.experiments) - n_successful - n_timeout
print("In {} iterations, {} successful, {} timeouts, {} not done.".format(
n_iterations, n_successful, n_timeout, n_notdone))
for i in itertools.count():
if maxiter is not None and maxiter <= i:
break
if i < n_iterations:
todo = self.notdone[i]
self.notdone[i] = []
else:
todo = self.experiments
self.results.append([])
self.timeouts.append([])
self.notdone.append([])
random.shuffle(todo)
while len(todo):
# get next experiment (random)
e = random.choice(todo)
# get all experiments with this group
if getattr(e, 'group', None) is not None:
exps = [x for x in todo if x.group == e.group]
todo = [x for x in todo if x.group != e.group]
else:
exps = [e]
todo.remove(e)
for j, e in enumerate(exps):
# print header
print("It {} ({}/{}): ".format(i, len(self.experiments)-len(todo)-len(exps)+j+1, len(self.experiments)), end='')
# run experiment
filename = "{}/{}-{}".format(self.logdir, e.name, i)
status, value = e.run_experiment(self.timeout, filename)
# store result
if status == Experiment.DONE:
self.results[i] += [(e, value)]
elif status == Experiment.TIMEOUT:
self.timeouts[i] += [(e, value)]
else:
self.notdone[i] += [e]
# sleep 2 seconds to allow OS to swap stuff in or out
time.sleep(2)
print("Iteration {} done.".format(i))
def __iadd__(self, other):
if isinstance(other, Experiment):
self.experiments.append(other)
return self
elif isinstance(other, ExperimentEngine):
self.experiments.extend(other)
return self
elif hasattr(other, '__iter__'):
for item in other:
self += item
return self
else:
return NotImplemented
def online_variance(data):
n = 0
mean = 0
M2 = 0
for x in data:
n = n + 1
delta = x - mean
mean = mean + delta / n
M2 = M2 + delta * (x - mean)
if n < 1:
return n, float('nan'), float('nan')
if n < 2:
return n, mean, float('nan')
variance = M2 / (n - 1)
return n, mean, variance
def fixnan(table):
return [['--' if s.strip() == 'nan' else s for s in row] for row in table]