Exemplo n.º 1
0
 def extractPatches(self, f):
     mtp = MoveTreeParser(f)
     #print('{} := {}'.format(f.split('/')[-1].split('\\')[-1], mtp.problemType))
     sn = mtp.getSolutionNodes()
     inc = mtp.getIncorrectNodes()
     probtyp = mtp.getProblemType()
     if probtyp == 1 or probtyp == 3:  #Black to live
         probtyp = 1
     elif probtyp == 2 or probtyp == 4:  #White to kill
         probtyp = 2
     else:  #Error should be thrown, but just in case it isn't
         probtyp = 0
     isBTL = (probtyp == 1)
     if not sn.isdisjoint(inc):
         print('NOT DISJOINT')
     paths = mtp.getAllPaths()
     movesConsidered = set()
     for path in paths:
         parent = 0
         start = mtp.start
         #print('START NEW PATH')
         for mid in path:
             move_dict = mtp.formatMove(mtp.moveID[mid])
             saysblack = move_dict['isBlack']  #move_str[0:1]=='B'
             #print('{}''s turn'.format('black' if saysblack else 'white'))
             move_y = move_dict['y']  #ord(move_str[2]) - ord('a')
             move_x = move_dict['x']  #ord(move_str[3]) - ord('a')
             move = Board(start.x, start.y)
             move.white_stones = [x for x in start.white_stones]
             move.black_stones = [y for y in start.black_stones]
             try:
                 move.place_stone(move_x, move_y, saysblack)
                 if (parent, mid) not in movesConsidered:
                     outcome = 0
                     if isBTL == saysblack:
                         #CHECK THIS LOGIC
                         if mid in sn:
                             outcome = 1
                         elif mid in inc:
                             outcome = 0
                         else:
                             raise Exception('Unknown outcome!')
                     else:
                         ''' Assume only moves on incorrect path are correct
                             for the "antagonist" '''
                         if mid in inc:
                             outcome = 1
                         ''' Assume all moves for the "antagonist" are correct '''
                         # outcome = 1
                     self.individualExtraction(start, move,
                                               (move_x, move_y), saysblack,
                                               outcome)
                     movesConsidered.add((parent, mid))
                     # Only train on the first wrong move for the protagonist
                     if outcome == 0 and isBTL == saysblack:
                         break
             except IllegalMove as e:
                 print('{}: ({},{})'.format(e, move_x, move_y))
             parent = mid
             start = move
Exemplo n.º 2
0
    def individualExtraction(self, start, move, movePosition, isblack,
                             outcome):
        if (not isblack):
            newstart = Board(start.x, start.y)
            newstart.black_stones = start.white_stones
            newstart.white_stones = start.black_stones
            start = newstart
            newmove = Board(move.x, move.y)
            newmove.black_stones = move.white_stones
            newmove.white_stones = move.black_stones
            move = newmove

        sparsePatches = SparseDictionaryFeature(start, move, movePosition,
                                                isblack).get_transformed_data(
                                                    4, 'features/')

        if isblack:
            for row in sparsePatches:
                self.fout1a.write(','.join([str(x)
                                            for x in row] + [str(outcome)]))
                self.fout1a.write('\n')

        else:
            for row in sparsePatches:
                self.fout2a.write(','.join([str(x)
                                            for x in row] + [str(outcome)]))
                self.fout2a.write('\n')

        sparsePatches = SparseDictionaryFeature(start, move, movePosition,
                                                isblack).get_transformed_data(
                                                    5, 'features/')

        if isblack:
            for row in sparsePatches:
                self.fout3a.write(','.join([str(x)
                                            for x in row] + [str(outcome)]))
                self.fout3a.write('\n')

        else:
            for row in sparsePatches:
                self.fout4a.write(','.join([str(x)
                                            for x in row] + [str(outcome)]))
                self.fout4a.write('\n')
Exemplo n.º 3
0
  def parseStartState(self, gameData):
    boardSizeLocation = gameData.find("SZ")
    sizeString = ''
    counter = 0
    currentChar = gameData[boardSizeLocation + counter + 3]

    '''
    while(currentChar != ']'):
      sizeString += currentChar
      counter += 1
      currentChar = gameData[boardSizeLocation + counter + 3]

    if(sizeString.isdigit()):
      size = int(sizeString)
    else:
      size = 19
    '''

    currentBoard = Board(self.boardDimensions['xMax'] - self.boardDimensions['xMin'] + 1,self.boardDimensions['yMax'] - self.boardDimensions['yMin'] + 1)
    whitePositionLocations = [m.start() for m in re.finditer('AW', gameData)]
    blackPositionLocations = [m.start() for m in re.finditer('AB', gameData)]

    stonePositions = whitePositionLocations + blackPositionLocations
    stonePositions.sort()

    for i in stonePositions:
      isBlack = False
      if i in blackPositionLocations:
        isBlack = not self.flipColors
      if i in whitePositionLocations:
        isBlack = self.flipColors
      counter = 0
      while(True):
        currentChar = gameData[i + counter + 2]
        if (currentChar != '['):
          break
        currentChar = gameData[i + counter + 3]
        y = ord(currentChar) - ord('a') - self.boardDimensions['yMin']
        currentChar = gameData[i + counter + 4]
        x = ord(currentChar) - ord('a') - self.boardDimensions['xMin']
        if isBlack:
            currentBoard.black_stones.append((x,y))
        else:
            currentBoard.white_stones.append((x,y))
        #currentBoard.place_stone(x,y,isBlack)
        counter += 4
    return currentBoard
Exemplo n.º 4
0
 def actOnSolutionStates(self, f):
     mtp = MoveTreeParser(f)
     print('{} := {}'.format(f.split('/')[-1].split('\\')[-1], mtp.problemType))
     sn = mtp.getSolutionStates()
     #print sn
     probtyp = mtp.getProblemType()
     if probtyp == 1 or probtyp == 3: #Black to live
         probtyp = 1
     elif probtyp == 2 or probtyp == 4: #White to kill
         probtyp = 2
     else: #Error should be thrown, but just in case it isn't
         probtyp = 0
     isBTL = (probtyp==1)
     paths = mtp.getSolutionPaths()
     for path in paths:
         parent = 0
         start = mtp.start
         for mid in path:
             move_dict = mtp.formatMove(mtp.moveID[mid])
             saysblack = move_dict['isBlack']
             move_y = move_dict['y']
             move_x = move_dict['x']
             move = Board(start.x, start.y)
             move.white_stones = [x for x in start.white_stones]
             move.black_stones = [y for y in start.black_stones]
             try:
                 move.place_stone(move_x, move_y, saysblack)
                 if isBTL == saysblack:
                     if mid in sn:
                         #DO WHATEVER YOU WANT WITH BOARD: move
                         moveConverted = self.convert_board(move,0,2)
                         print mid
                         print moveConverted
                         print move
                         print move.black_stones
                         print move.white_stones
                         aliveGroups = gold.models.terminalLife.findAliveGroups(move, saysblack)
                         print aliveGroups
             except IllegalMove as e:
                 print('{}: ({},{})'.format(e, move_x, move_y,sys.exc_info()[-1].tb_lineno))
             parent = mid
             start = move
Exemplo n.º 5
0
    def __init__(self, dim_x, dim_y, margin, spaces, board=None):
        self.dim_x = dim_x
        self.dim_y = dim_y
        self.margin = margin
        self.spaces = spaces
        self.ovals = []
        if board == None:
            self.board = Board(spaces, spaces)
        else:
            self.board = board
            self.spaces = max(board.x, board.y)
        self.diam = (float(dim_x) - 2 * float(margin)) / float(self.spaces - 1)
        self.master = Tk()
        self.master.resizable(True, True)
        self.master.configure(bg='#d8af4f')
        #self.board_frame = Frame(width=self.dim_x, height=dim_y, bg='#d8af4f')
        #self.board_frame.pack(side=TOP, fill=BOTH, expand=YES)
        #self.scaler_frame =Frame(width=self.dim_x, height=42, bg='#d8af4f')
        #self.scaler_frame.pack(side=BOTTOM, fill=X, expand=YES)
        self.C = None
        self.drawGrid()
        self.master.rowconfigure(0, weight=1)
        self.master.columnconfigure(0, weight=1)

        def callback(event):
            #[i, j] = self.computeSpace(event.x, event.y)
            self.placeStoneNear(event.x, event.y, 'white')

        def callback2(event):
            #[i, j] = self.computeSpace(event.x, event.y)
            self.placeStoneNear(event.x, event.y, 'black')
            #self.goForWhite(i, j)

        # Left-click for white, right-click for black
        self.C.bind("<Button-1>", callback2)
        self.C.bind("<Button-3>", callback)
Exemplo n.º 6
0
gameData = currentGame.read()

boardSizeLocation = gameData.find("SZ")
sizeString = ''
counter = 0
currentChar = gameData[boardSizeLocation + counter + 3]
while (currentChar != ']'):
    sizeString += currentChar
    counter += 1
    currentChar = gameData[boardSizeLocation + counter + 3]

if (sizeString.isdigit()):
    size = int(sizeString)

currentBoard = Board(size, size)

whitePositionLocations = [m.start() for m in re.finditer('AW', gameData)]
blackPositionLocations = [m.start() for m in re.finditer('AB', gameData)]

stonePositions = whitePositionLocations + blackPositionLocations
stonePositions.sort()

for i in stonePositions:
    isBlack = False
    if i in blackPositionLocations:
        isBlack = True
    counter = 0
    while (True):
        currentChar = gameData[i + counter + 2]
        if (currentChar != '['):
Exemplo n.º 7
0
 def get_vectors_from_file(self, f):
     mtp = MoveTreeParser(f)
     #print('{} := {}'.format(f.split('/')[-1].split('\\')[-1], mtp.problemType))
     subpaths = f.split('/')
     subfnparts = subpaths[-1].split('\\')
     difficulty = subfnparts[-2]
     fname = subfnparts[-1]
     probId = fname.split('.')[0]
     sn = mtp.getSolutionNodes()
     inc = mtp.getIncorrectNodes()
     probtyp = mtp.getProblemType()
     if probtyp == 1 or probtyp == 3:  #Black to live
         probtyp = 1
     elif probtyp == 2 or probtyp == 4:  #White to kill
         probtyp = 2
     else:  #Error should be thrown, but just in case it isn't
         probtyp = 0
     isBTL = (probtyp == 1)
     if not sn.isdisjoint(inc):
         print('NOT DISJOINT')
     paths = mtp.getAllPaths()
     movesConsidered = set()
     fe = FeatureExtractor()
     vectors = []
     for path in paths:
         parent = 0
         start = mtp.start
         #print('START NEW PATH')
         for i, mid in enumerate(path):
             move_dict = mtp.formatMove(mtp.moveID[mid])
             saysblack = move_dict['isBlack']  #move_str[0:1]=='B'
             #print('{}''s turn'.format('black' if saysblack else 'white'))
             move_y = move_dict['y']  #ord(move_str[2]) - ord('a')
             move_x = move_dict['x']  #ord(move_str[3]) - ord('a')
             move = Board(start.x, start.y)
             move.white_stones = [x for x in start.white_stones]
             move.black_stones = [y for y in start.black_stones]
             try:
                 move.place_stone(move_x, move_y, saysblack)
                 if (parent, mid) not in movesConsidered:
                     features = fe.extract_features(start, move,
                                                    (move_x, move_y),
                                                    saysblack)
                     inSoln = 1 if mid in sn else 0
                     inInc = 1 if mid in inc else 0
                     isTerminal = 1 if i == len(path) - 1 else 0
                     features['_PT'] = probtyp
                     features['_SOLUTION'] = inSoln
                     features['_INC'] = inInc
                     features['_TERM'] = isTerminal
                     features['_PROBID'] = probId
                     features['_DI'] = difficulty
                     features['_MOVE'] = mid
                     features['_PARENT'] = parent
                     movesConsidered.add((parent, mid))
                     vectors.append(features)
             except IllegalMove as e:
                 print('{} ({},{}): {}'.format(fname, move_x, move_y, e))
             parent = mid
             start = move
     return vectors