-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparse.py
More file actions
331 lines (240 loc) · 8.24 KB
/
parse.py
File metadata and controls
331 lines (240 loc) · 8.24 KB
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
import pickle
import re
from chess import *
INITIALELO = 1800;
ME = 'spintheblack';
WHITE = 0;
BLACK = 1;
NOTMYMOVE, MYMOVE = (0,1);
class maxvisitor:
def __init__(self):
self.lowest = 0
self.lowestv = ''
def visit(self,node):
if(self.lowest < node.all):
self.lowest = node.all;
self.lowestv = node;
class chessvisitor:
def __init__(self):
self.game = None
def visit(self,node,tree):
""" general visiting method, should be
called by any subclasses' visitXXX method to initialize state
"""
if not self.game:
self.game = Game( node.board )
self.generaltraverse(node,tree);
def generaltraverse(self,node,tree):
""" general DFS traversal, can be
called after visit method to visit all children """
for mv in node.children:
self.game.move( mv )
tree.nodes[self.game].invite(self,tree)
self.game.takeback();
class Node:
def __init__(self, board, props):
self.board = board
self.children = set()
self.all = int(props["MyRating"])
self.gamesplayed = 0
self.gameswon = 0
def __hash__(self):
return self.__str__(self)
def __str__(self):
return self.board
def invelo(self,opp):
"""
get the probability of winning given
the opponents rating """
return 1/(1.0 + pow(10,((opp-self.all)/400.0)))
def updateelo(self,toupdate, win, oppelo):
""" Update the ELO of the current node.
TODO: make K dynamic based on the games played ala USCF ratings """
K = 32
e_me = 1/(1.0 + pow(10,((int(oppelo)-toupdate)/400.0)))
toupdate = toupdate + K*(win-e_me)
return toupdate
def invite(self, visitor, tree):
visitor.visit(self,tree)
def update(self, updateprop):
self.gamesplayed += 1
self.gameswon += updateprop["Result"]
opponentelo = int( updateprop["OppRating"] )
self.all = self.updateelo(self.all, updateprop["Result"], opponentelo)
# for k,v in updateprop.iteritems():
# if k in self.props:
# self.props[k].update(v,updateprop["Result"], opponentelo,myelo)
# else:
# self.props[k] = Property(k,v)
class ChessTree:
DEFAULTMAXNEWPILES = 20
def __init__(self):
self.nodes = {}
self.maxnewpiles = ChessTree.DEFAULTMAXNEWPILES
def getwhiteroot(self):
return self.nodes["rnbqkbnr pppppppp ........ ........ ........ ........ PPPPPPPP RNBQKBNR01"]
def getblackroot(self):
return self.nodes["rnbqkbnr pppppppp ........ ........ ........ ........ PPPPPPPP RNBQKBNR00"]
def getnode(self, hash):
return self.nodes[hash]
def board2state(self,pos, props, whitetomove):
""" Change board representation pos to the state representation
eg. switching the color bit if it is the user's move and we are black """
newpos = "%s%d"%pos
if props["MyColor"] == WHITE:
newpos += "%d"%whitetomove
if props["MyColor"] == BLACK:
blacktomove = (whitetomove+1)%2
newpos += "%d"%blacktomove
return newpos
def walk(self, game,props):
i = 0;
for pos in game.boardstate:
newpos = self.board2state(pos,props,i%2)
print newpos
if newpos in self.nodes:
cur = self.nodes[newpos]
print cur.all
i+=1
def addGame(self, game, props):
prev = None
seen = set()
numnew = 0;
i = 0;
# boardstate is a tuple of (board representation, turn to move)
print props["MyColor"]
for pos in game.boardstate:
statekey = self.board2state(pos,props,i%2)
print statekey
# make sure we don't update the ELO of a repeated position
if statekey in seen:
continue
# if adding new nods, only go as deep as maxnewpiles
if numnew==self.maxnewpiles:
break
numnew+=1;
seen.add(statekey)
cur = None
if statekey in self.nodes:
cur = self.nodes[statekey]
else:
cur = Node(statekey,props)
self.nodes[statekey] = cur
cur.update(props)
if prev:
movetup = game.moves[i-1]
mv = Move("",movetup[0],movetup[1])
prev.children.add( (str(statekey), "%s-%s" % game.moves[i-1]) )
prev = cur
i+=1
class Property:
def __init__(self, name, p=None):
self.name = name;
self.values = dict();
self.values[p] = INITIALELO;
def __hash__(self):
return self.__name__
def init_val(self,v):
self.values[v] = INITIALELO;
def update(self, node, score, opp):
if not self.values.has_key(node):
self.init_val(node);
self.values[node] = updateElo( self.values[node], score, opp)
#class ChildIter:
# def __init__(self,board,moves):
# self.game = Board();
# self.game.set(board);
# mv = [];
# for moves in moves:
# mv.append((board,moves))
# self.moves = mv;
# self.movesi = 0;
#
# def next(self):
# if not (len(self.moves) - self.movesi):
# raise StopIteration
#
# gamep = self.game.clone();
# t = self.moves[self.movesi];
# gamep.move(t[0],t[1]);
#
# out = (self.moves(self.movesi),"%s" % gamep);
# gamep.takeback();
#
# self.movesi = self.movesi + 1;
#
# return out;
class PGNLoader:
def __init__(self):
self.__matcher__ = re.compile("([0-9]*)\\. ([^{} ]*) ([^{} ]*)");
self.__nmatcher__ = re.compile("\\{.*\\}");
def load(self, file):
games = []
lines = file.readlines()
lines[-1] = '['
thisprops = []
thismoves = []
inmoves = False;
for line in lines:
line = line.strip()
# blank line, drop ...
if not len(line):
continue
if line[0] == '[':
if inmoves:
try:
games.append(self.process(thisprops, thismoves));
except KeyboardInterrupt:
print "Bailing...."
return None
except:
print "Skipping..."
inmoves = 0;
thisprops=[];
thismoves=[];
thisprops.append(line);
else:
inmoves = 1;
thismoves.append(line)
return games
def process(self, prop, moves):
print "starting"
game = self.processMoves(moves)
mapping = self.processProp(prop)
print "done"
return (game,mapping)
def processMoves(self, moves):
ml = []
bigline = reduce( lambda x,y: x+" "+y, moves ).strip()
game = Game()
for move in self.__matcher__.findall(bigline):
game.move( move[1] );
if move[2]:
game.move( move[2] );
return game
def processProp(self, prop):
pm = dict();
for p in prop:
p = p.strip("[]");
t = p.split(" ");
pm[t[0]] = t[1].strip("\"");
try:
if( pm["White"] == ME ):
pm["MyColor"] = 0
pm["OppRating"] = pm["BlackElo"]
pm["MyRating"] = pm["WhiteElo"]
elif( pm["Black"] == ME ):
pm["MyColor"] = 1
pm["OppRating"] = pm["WhiteElo"]
pm["MyRating"] = pm["BlackElo"]
res = pm["Result"]
lr = res.split("-");
if( lr[0] == "1/2" ):
lr[0] = lr[1] = 0.5;
pm["Result"] = ( (float(lr[0])- pm["MyColor"] + \
pm["MyColor"] - float(lr[1])) + 1)/2.0;
except:
raise Error, "Missing Property"
return pm
def parseElo(self, whiteElo, whiteName):
pass