-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathrgtuner.py
executable file
·225 lines (194 loc) · 7.76 KB
/
rgtuner.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
#!/usr/bin/env python2
from __future__ import print_function
import os
import multiprocessing
import re
import shutil
import argparse
filesRemaining = []
botScores = {}
import random
from rgkit.run import Runner, Options
from rgkit.settings import settings as default_settings
def make_variants(variable, robot_file, possibilities):
"""Makes variants of the file robot_file with the constant variable
changed for each possibility.
e.g. if the variable is "ELEPHANTS" and the possibilities are [1, 2, 3],
this will find the line
ELEPHANTS = 3
in robobt_file and make a copy of the file for each value in possibilities.
1.py will have ELEPHANTS = 1, 2.py will have ELEPHANTS = 2, etc.
Raises IndexError if the variable name is not found in the file robot_file.
The line assigning the constant variable must be the first line in that
file has the variable name in it.
"""
filenames = []
with open(robot_file, 'r') as f:
lines = f.readlines()
for i, line in enumerate(lines):
if variable in line:
break
assert '=' in line
for p in possibilities:
varandp = variable + str(p)
lines[i] = "%s = %s\n" % (variable, p)
filenames.append(varandp)
with open(varandp, 'w') as pfile:
for line in lines:
pfile.write(line)
return filenames
def get_current_value(variable, robot_file):
"""
Returns the value of the constant variable in the robot file.
This function finds the first line in the file robot_file that has the
variable name in it, and parses the value after the '=' in that line for a
float, returning it.
Raises IndexError if the variable name is not found in the file robot_file.
The line assigning the constant variable must be the first line in that
file has the variable name in it.
"""
with open(robot_file, 'r') as f:
for i, line in enumerate(f):
if variable in line:
break
assert '=' in line
return float(line[line.index('=') + 1:])
def optimize_variable(precisionParam, matchNum, enemies, variable, robot_file, processes):
pool = multiprocessing.Pool(processes)
"""
Creates a bunch of variants of the file robot_file, each with variable
changed, then runs a tournament between the variants to find the best one.
The file robot_fily is modified to contain the best value, and it is
returned.
"""
base_value = get_current_value(variable, robot_file)
precision = precisionParam
while precision >= 0.1:
print('RUNNING WITH BASE VALUE', base_value, \
'PRECISION', precision)
values_to_test = [base_value - precision,
base_value + precision, base_value]
files = make_variants(variable, robot_file, values_to_test)
best_file = run_tourney(matchNum,enemies, files, pool)
best_value = values_to_test[files.index(best_file)]
if best_value == base_value:
precision /= 2.0
print('best value remains', best_value)
print('decreasing precision to', precision)
else:
base_value = best_value
print('new \'best\' value is', best_value)
shutil.copy(make_variants(variable, robot_file, [base_value])[0],
robot_file)
return base_value
def run_match(bot1, bot2):
#rgkit integration
runner = Runner(player_files=(bot1,bot2), options=Options(quiet=4, game_seed=random.randint(0, default_settings.max_seed)))
scores0, scores1 = runner.run()[0]
if scores0 > scores1:
return (scores0, scores1, scores0 - scores1, bot1)
elif scores1 > scores0:
return (scores0, scores1, scores1 - scores0, bot2)
else:
return (scores0, scores1, 0,'tie')
def versus(matchNum,bot1, bot2, pool):
"""Launches a multithreaded comparison between two robot files.
run_match() is run in separate processes, one for each CPU core, until 100
matches are run.
Returns the winner, or 'tie' if there was no winner."""
bot1Score = 0
bot2Score = 0
matches_to_run = matchNum
try:
results = [pool.apply_async(run_match, (bot1, bot2))
for i in xrange(matches_to_run)]
for r in results:
s0, s1, s2, s3 = r.get(timeout=120)
print('battle result:',s3, ' difference:', s2)
bot1Score += s0
bot2Score += s1
#otherwise, it's a tie, but we can ignore it
print('overall:', bot1, bot1Score, ':', bot2Score, bot2)
return bot1Score - bot2Score
except KeyboardInterrupt:
print('user did ctrl+c, ABORT EVERYTHING')
pool.terminate()
for bot in filesRemaining:
os.remove(bot)
raise KeyboardInterrupt()
def run_tourney(matchNum,enemies, botfiles, pool):
"""Runs a tournament between all bot files in botfiles.
Returns the winner of the tournament."""
bestWin = ['', -5000]
scores = {}
for bot1 in botfiles:
filesRemaining.append(bot1)
scores[bot1] = 0
for enemy in enemies:
for bot1 in botfiles:
if bot1 in botScores[enemy] and botScores[enemy][bot1] != 0:
winScore = botScores[enemy][bot1]
print('ALREADY SCORED',str(bot1))
else:
winScore = versus(matchNum,bot1, enemy, pool)
botScores[enemy][bot1] = winScore
while winScore == 0:
print('VERSUS WAS A TIE. RETRYING...')
winScore = versus(matchNum,bot1, enemy, pool)
print('Difference in score:',str(bestWin[1]))
scores[bot1] += winScore
print(scores)
for bot1 in botfiles:
for bot2 in botfiles:
if bot1 != bot2 and scores[bot1] == scores[bot2]:
print("Two bots have same score, finding the winner")
bestWin[1] = versus(matchNum,bot1, bot2, pool)
while bestWin[1] == 0:
print("Wow. Another Tie.")
bestWin[1] = versus(matchNum,bot1, bot2, pool)
if bestWin[1] < 0:
bestWin[0] = bot2
elif bestWin[1] > 0:
bestWin[0] = bot1
else:
print("WTF? Impossible Tie.")
elif scores[bot1] > bestWin[1]:
bestWin[1] = scores[bot1]
bestWin[0] = bot1
for bf in botfiles:
if not bf == bestWin[0]:
print('removing',bf)
os.remove(bf)
filesRemaining.remove(bf)
print('Best Score:',str(bestWin[1]))
return bestWin[0]
def main():
parser = argparse.ArgumentParser(
description="Optimize constant values for robotgame.")
parser.add_argument(
"constant", type=str, help='The constant name to optimize.')
parser.add_argument(
"file", type=str, help='The file of the robot to optimize.')
parser.add_argument(
"enemies", type=str, help='A comma-separated list of the enemy files.')
parser.add_argument(
"-pr", "--precision",
default=8.0,
type=float, help='The precision to start adjusting values at')
parser.add_argument(
"-m", "--matches",
default=100,
type=int, help='The number of matches to run per tourney')
parser.add_argument(
"-p", "--processes",
default=multiprocessing.cpu_count(),
type=int, help='The number of processes to simulate in')
args = vars(parser.parse_args())
eList = args['enemies'].split(',')
for e in eList:
botScores[e] = {}
best_value = optimize_variable(args['precision'],args['matches'],eList,
args['constant'], args['file'], processes=args['processes'])
print(best_value)
if __name__ == '__main__':
main()