-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathupdate_fingerprints.py
318 lines (264 loc) · 8.61 KB
/
update_fingerprints.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
"""
A script to obtain the Ashlock Fingerprints of all strategies in the Axelrod
library.
This writes a hash of the source code of each strategy to file: db.csv.
If the source code of a strategy changes **or** a new strategy is introduced
then the fingerprint is regenerated for that strategy.
"""
import inspect
import hashlib
import csv
import string
import numpy as np
import matplotlib.pyplot as plt
import axelrod as axl
def hash_strategy(strategy):
"""
Hash the source code of a strategy
"""
try:
source_code = "".join(inspect.getsourcelines(strategy)[0])
except OSError: # Some classes are dynamically created
source_code = "".join(inspect.getsourcelines(strategy.strategy)[0])
hash_object = hashlib.md5(source_code.encode("utf-8"))
hashed_source = hash_object.hexdigest()
return hashed_source
def write_strategy_to_db(strategy, filename="db.csv", fingerprint="Ashlock"):
"""
Write the hash of a strategy to the db
"""
hashed_source = hash_strategy(strategy)
with open(filename, "a") as db:
try:
db.write(
"{},{},{}\n".format(
strategy.original_name, fingerprint, hashed_source
)
)
except AttributeError:
db.write(
"{},{},{}\n".format(strategy.name, fingerprint, hashed_source)
)
def read_db(filename="db.csv"):
"""
Read filename and return a dictionary mapping string names to hash of source
code of a strategy
"""
with open(filename, "r") as db:
csvreader = csv.reader(db)
str_to_hash = {(row[0], row[1]): row[2] for row in csvreader}
return str_to_hash
def create_db(filename="db.csv"):
"""
Creates an empty db.csv file
"""
with open(filename, "w"):
pass
def write_data_to_file(fp, filename):
"""
Write the fingerprint data to a file.
"""
columns = ["x", "y", "score"]
with open(filename, "w") as f:
w = csv.writer(f)
w.writerow(columns)
for key, value in fp.data.items():
w.writerow([key.x, key.y, value])
def obtain_fingerprint(
strategy, turns, repetitions, probe=axl.TitForTat, processes=1
):
"""
Obtain the fingerprint for a given strategy and save the figure to the
assets dir
"""
fp = axl.AshlockFingerprint(strategy, probe)
fp.fingerprint(
turns=turns,
repetitions=repetitions,
progress_bar=False,
processes=processes,
)
plt.figure()
fp.plot()
try:
name = strategy.original_name
except AttributeError:
name = strategy.name
plt.tight_layout()
plt.savefig(
"assets/{}.png".format(format_filename(name)), bbox_inches="tight"
)
write_data_to_file(fp, "assets/{}.csv".format(format_filename(name)))
def obtain_transitive_fingerprint(strategy, turns, repetitions, processes=1):
"""
Obtain the transitive fingerprint
for a given strategy and save the figure to the assets dir
"""
fp = axl.TransitiveFingerprint(strategy, number_of_opponents=30)
fp.fingerprint(
turns=turns,
repetitions=repetitions,
progress_bar=False,
processes=processes,
)
plt.figure()
fp.plot()
try:
name = strategy.original_name
except AttributeError:
name = strategy.name
plt.tight_layout()
plt.savefig(
"assets/transitive_{}.png".format(format_filename(name)),
bbox_inches="tight",
)
np.savetxt(
"assets/transitive_{}.csv".format(format_filename(name)), fp.data
)
def obtain_transitive_fingerprint_v_short(
strategy, turns, repetitions, processes=1
):
"""
Obtain the transitive fingerprint against short run time
for a given strategy and save the figure to the assets dir
"""
short_run_time = [s() for s in axl.short_run_time_strategies]
fp = axl.TransitiveFingerprint(strategy, opponents=short_run_time)
fp.fingerprint(
turns=turns,
repetitions=repetitions,
progress_bar=False,
processes=processes,
)
plt.figure()
fp.plot(display_names=True)
try:
name = strategy.original_name
except AttributeError:
name = strategy.name
plt.tight_layout()
plt.savefig(
"assets/transitive_v_short_{}.png".format(format_filename(name)),
bbox_inches="tight",
)
np.savetxt(
"assets/transitive_v_short_{}.csv".format(format_filename(name)),
fp.data,
)
def format_filename(s):
"""
Take a string and return a valid filename constructed from the string.
Uses a whitelist approach: any characters not present in valid_chars are
removed. Also spaces are replaced with underscores.
Note: this method may produce invalid filenames such as ``, `.` or `..`
When I use this method I prepend a date string like '2009_01_15_19_46_32_'
and append a file extension like '.txt', so I avoid the potential of using
an invalid filename.
Borrowed from https://gist.github.com/seanh/93666
"""
valid_chars = "-_.() {}{}".format(string.ascii_letters, string.digits)
filename = "".join(c for c in s if c in valid_chars)
filename = filename.replace(" ", "_")
return filename
def write_markdown(strategy):
"""
Write a markdown section of a strategy.
"""
try:
name = strategy.original_name
except AttributeError:
name = strategy.name
markdown = """
## {0}

[data (csv)](./assets/{1}.csv)

[data (csv)](./assets/transitive_{1}.csv)

[data (csv)](./assets/transitive_v_short_{1}.csv)
""".format(
name, format_filename(name)
)
return markdown
def main(
turns,
repetitions,
transitive_turns,
transitive_repetitions,
transitive_v_short_turns,
transitive_v_short_repetitions,
processes,
):
"""
Fingerprint all strategies, if a strategy has already been fingerprinted it
does not get rerun.
"""
version = axl.__version__
markdown = """# Ashlock and transitive fingerprints
See:
[axelrod.readthedocs.io/en/latest/tutorials/further_topics/fingerprinting.html#fingerprinting](http://axelrod.readthedocs.io/en/latest/tutorials/further_topics/fingerprinting.html#fingerprinting)
All strategies included from Axelrod version {}.
This README.md file is autogenerated by running:
```
$ python update_fingerprints.py
```
Each individual fingerprint can be obtained by running:
```python
import axelrod as axl
fp = axl.AshlockFingerprint(strategy, probe)
fp.fingerprint(turns={}, repetitions={})
fp.plot()
```
# Axelrod library fingerprints
""".format(
version, turns, repetitions
)
try:
db = read_db()
except FileNotFoundError:
create_db()
db = read_db()
for strategy in axl.short_run_time_strategies:
name = strategy.name
signature = hash_strategy(strategy)
fp = "Ashlock"
if (name, fp) not in db or db[name, fp] != signature:
obtain_fingerprint(
strategy, turns, repetitions, processes=processes
)
write_strategy_to_db(strategy, fingerprint=fp)
fp = "Transitive"
if (name, fp) not in db or db[name, fp] != signature:
obtain_transitive_fingerprint(
strategy,
transitive_turns,
transitive_repetitions,
processes=processes,
)
write_strategy_to_db(strategy, fingerprint=fp)
fp = "Transitive_v_short"
if (name, fp) not in db or db[name, fp] != signature:
obtain_transitive_fingerprint_v_short(
strategy,
transitive_v_short_turns,
transitive_v_short_repetitions,
processes=processes,
)
write_strategy_to_db(strategy, fingerprint=fp)
markdown += write_markdown(strategy)
with open("README.md", "w") as outfile:
outfile.write(markdown)
if __name__ == "__main__":
turns, repetitions = 200, 20
transitive_turns, transitive_repetitions = 200, 20
transitive_v_short_turns, transitive_v_short_repetitions = 200, 20
processes = 20
main(
turns=turns,
repetitions=repetitions,
transitive_turns=transitive_turns,
transitive_repetitions=transitive_repetitions,
transitive_v_short_turns=transitive_v_short_turns,
transitive_v_short_repetitions=transitive_v_short_repetitions,
processes=processes,
)