Beispiel #1
0
    def test_make_sgf(self):
        all_positions = list(replay_sgf(NO_HANDICAP_SGF))
        last_position, _, metadata = all_positions[-1]
        back_to_sgf = make_sgf(
            last_position.recent,
            last_position.score(),
            boardsize=metadata.board_size,
            komi=last_position.komi,
        )
        reconstructed_positions = list(replay_sgf(back_to_sgf))
        last_position2, _, _ = reconstructed_positions[-1]

        self.assertEqualPositions(last_position, last_position2)
    def test_make_sgf(self):
        all_positions = list(replay_sgf(NO_HANDICAP_SGF))
        last_position, _, metadata = all_positions[-1]
        back_to_sgf = make_sgf(
            last_position.recent,
            last_position.score(),
            boardsize=metadata.board_size,
            komi=last_position.komi,
        )
        reconstructed_positions = list(replay_sgf(back_to_sgf))
        last_position2, _, _ = reconstructed_positions[-1]

        self.assertEqualPositions(last_position, last_position2)
    def test_make_sgf(self):
        all_pwcs = list(replay_sgf(NO_HANDICAP_SGF))
        second_last_position, last_move, _ = all_pwcs[-1]
        last_position = second_last_position.play_move(last_move)

        back_to_sgf = make_sgf(
            last_position.recent,
            last_position.score(),
            komi=last_position.komi,
        )
        reconstructed_positions = list(replay_sgf(back_to_sgf))
        second_last_position2, last_move2, _ = reconstructed_positions[-1]
        last_position2 = second_last_position2.play_move(last_move2)

        self.assertEqualPositions(last_position, last_position2)
    def test_make_sgf(self):
        all_pwcs = list(replay_sgf(NO_HANDICAP_SGF))
        second_last_position, last_move, _ = all_pwcs[-1]
        last_position = second_last_position.play_move(last_move)

        back_to_sgf = make_sgf(
            last_position.recent,
            last_position.score(),
            komi=last_position.komi,
        )
        reconstructed_positions = list(replay_sgf(back_to_sgf))
        second_last_position2, last_move2, _ = reconstructed_positions[-1]
        last_position2 = second_last_position2.play_move(last_move2)

        self.assertEqualPositions(last_position, last_position2)
Beispiel #5
0
def analyze_symmetries(sgf_file, dual_network):
    with open(sgf_file) as f:
        sgf_contents = f.read()

    iterator = sgf_wrapper.replay_sgf(sgf_contents)
    differences = []
    stddevs = []

    # For every move in the game, get the corresponding network values for all
    # eight symmetries.
    for i, pwc in enumerate(iterator):
        feats = features.extract_features(pwc.position)
        variants = [symmetries.apply_symmetry_feat(s, feats)
                    for s in symmetries.SYMMETRIES]
        values = dual_network.sess.run(
            dual_network.inference_output['value_output'],
            feed_dict={dual_network.inference_input: variants})

        # Get the difference between the maximum and minimum outputs of the
        # value network over all eight symmetries; also get the standard
        # deviation of the eight values.
        differences.append(max(values) - min(values))
        stddevs.append(np.std(values))

    differences.sort()
    percentiles = [differences[i * len(differences) // 100] for i in range(100)]
    worst = differences[-1]
    avg_stddev = np.mean(stddevs)
    return (percentiles, worst, avg_stddev)
Beispiel #6
0
    def test_replay_position(self):
        sgf_positions = list(replay_sgf(NO_HANDICAP_SGF))
        initial = sgf_positions[0]
        self.assertEqual(initial.metadata.result, 'W+1.5')
        self.assertEqual(initial.metadata.board_size, 9)
        self.assertEqual(initial.position.komi, 6.5)

        final = sgf_positions[-1].position

        # sanity check to ensure we're working with the right position
        final_board = load_board('''
            .OXX.....
            O.OX.X...
            .OOX.....
            OOOOXXXXX
            XOXXOXOOO
            XOOXOO.O.
            XOXXXOOXO
            XXX.XOXXO
            X..XOO.O.
        ''')
        expected_final_position = go.Position(final_board,
                                              n=62,
                                              komi=6.5,
                                              caps=(3, 2),
                                              ko=None,
                                              recent=tuple(),
                                              to_play=go.BLACK)
        self.assertEqualPositions(expected_final_position, final)
        self.assertEqual(final.n, len(final.recent))

        replayed_positions = list(replay_position(final))
        for sgf_pos, replay_pos in zip(sgf_positions, replayed_positions):
            self.assertEqualPositions(sgf_pos.position, replay_pos.position)
    def cmd_loadsgf(self, arguments):
        args = arguments.split()
        if len(args) == 2:
            file_, movenum = args
            movenum = int(movenum)
            print("movenum =", movenum, file=sys.stderr)
        else:
            file_ = args[0]
            movenum = None

        try:
            with open(file_, 'r') as f:
                contents = f.read()
        except:
            raise ValueError("Unreadable file: " + file_)

        try:
            # This is kinda bad, because replay_sgf is already calling
            # 'play move' on its internal position objects, but we really
            # want to advance the engine along with us rather than try to
            # push in some finished Position object.
            for idx, p in enumerate(sgf_wrapper.replay_sgf(contents)):
                print("playing #", idx, p.next_move, file=sys.stderr)
                self._game.play_move(p.next_move)
                if movenum and idx == movenum:
                    break
        except:
            raise
Beispiel #8
0
    def test_replay_position(self):
        sgf_positions = list(sgf_wrapper.replay_sgf(NO_HANDICAP_SGF))
        initial = sgf_positions[0]
        self.assertEqual(initial.result, go.WHITE)

        final = sgf_positions[-1].position.play_move(
            sgf_positions[-1].next_move)

        # sanity check to ensure we're working with the right position
        final_board = test_utils.load_board('''
            .OXX.....
            O.OX.X...
            .OOX.....
            OOOOXXXXX
            XOXXOXOOO
            XOOXOO.O.
            XOXXXOOXO
            XXX.XOXXO
            X..XOO.O.
        ''')
        expected_final_position = go.Position(
            final_board,
            n=62,
            komi=6.5,
            caps=(3, 2),
            ko=None,
            recent=tuple(),
            to_play=go.BLACK
        )
        self.assertEqualPositions(expected_final_position, final)
        self.assertEqual(final.n, len(final.recent))

        replayed_positions = list(go.replay_position(final, 1))
        for sgf_pos, replay_pos in zip(sgf_positions, replayed_positions):
            self.assertEqualPositions(sgf_pos.position, replay_pos.position)
Beispiel #9
0
    def test_replay_position(self):
        sgf_positions = list(sgf_wrapper.replay_sgf(NO_HANDICAP_SGF))
        initial = sgf_positions[0]
        self.assertEqual(initial.result, go.WHITE)

        final = sgf_positions[-1].position.play_move(
            sgf_positions[-1].next_move)

        # sanity check to ensure we're working with the right position
        final_board = test_utils.load_board('''
            .OXX.....
            O.OX.X...
            .OOX.....
            OOOOXXXXX
            XOXXOXOOO
            XOOXOO.O.
            XOXXXOOXO
            XXX.XOXXO
            X..XOO.O.
        ''')
        expected_final_position = go.Position(final_board,
                                              n=62,
                                              komi=6.5,
                                              caps=(3, 2),
                                              ko=None,
                                              recent=tuple(),
                                              to_play=go.BLACK)
        self.assertEqualPositions(expected_final_position, final)
        self.assertEqual(final.n, len(final.recent))

        replayed_positions = list(go.replay_position(final))
        for sgf_pos, replay_pos in zip(sgf_positions, replayed_positions):
            self.assertEqualPositions(sgf_pos.position, replay_pos.position)
Beispiel #10
0
    def cmd_loadsgf(self, arguments):
        args = arguments.split()
        if len(args) == 2:
            file_, movenum = args
            movenum = int(movenum)
            print("movenum =", movenum, file=sys.stderr)
        else:
            file_ = args[0]
            movenum = None

        try:
            with open(file_, 'r') as f:
                contents = f.read()
        except:
            raise ValueError("Unreadable file: " + file_)

        try:
            # This is kinda bad, because replay_sgf is already calling
            # 'play move' on its internal position objects, but we really
            # want to advance the engine along with us rather than try to
            # push in some finished Position object.
            for idx, p in enumerate(sgf_wrapper.replay_sgf(contents)):
                print("playing #", idx, p.next_move, file=sys.stderr)
                self._game.play_move(p.next_move)
                if movenum and idx == movenum:
                    break
        except:
            raise
def predict_move(filename, network, tries_per_move=1, readouts=1000):
  replay = []

  if filename not in REPLAY_CACHE:
    with open(filename) as f:
        text = f.read()
        for position_w_context in sgf_wrapper.replay_sgf(text):
          replay.append(position_w_context)
    REPLAY_CACHE[filename] = replay
  replay = REPLAY_CACHE[filename]


  black_net = network

  player = MCTSPlayer(
        black_net, verbosity=0, two_player_mode=True, num_parallel=4)

  tried = 0
  correct = 0
  move_ratings = []
  for position_w_context in replay:
      if position_w_context.next_move is None:
          continue

      num_correct = 0
      for i in range(tries_per_move):
        move, correct_move, is_correct = predict_position(position_w_context, player, readouts=readouts)
        if is_correct:
          num_correct += 1
      move_ratings.append(num_correct * 1.0 / tries_per_move)
      print('RATING: ', sum(move_ratings) / len(move_ratings))
  return move_ratings
Beispiel #12
0
def main(argv):
    # It takes a couple of seconds to import anything from tensorflow, so only
    # do it if we need to read from GCS.
    path = argv[1]
    if path.startswith('gs://'):
        from tensorflow import gfile
        f = gfile.GFile(path, 'r')
    else:
        f = open(path, 'r')
    contents = f.read()
    f.close()

    # Determine the board size before importing any Minigo libraries because
    # require that the BOARD_SIZE environment variable is set correctly before
    # import.
    m = re.search(r'SZ\[([^]]+)', contents)
    if not m:
        print('Couldn\'t find SZ node, assuming 19x19 board')
        board_size = 19
    else:
        board_size = int(m.group(1))

    # Set the board size and import the Minigo libs.
    os.environ['BOARD_SIZE'] = str(board_size)
    import coords
    import go
    import sgf_wrapper

    # Replay the game.
    for x in sgf_wrapper.replay_sgf(contents):
        to_play = 'B' if x.position.to_play == 1 else 'W'
        print('{}>> {}: {}\n'.format(x.position, to_play,
                                     coords.to_gtp(x.next_move)))
Beispiel #13
0
def get_positions_from_sgf(file):
    try:
        with open(file) as f:
            for position_w_context in replay_sgf(f.read()):
                if position_w_context.is_usable():
                    yield position_w_context
    except:
        return
Beispiel #14
0
 def test_chinese_handicap_handling(self):
   intermediate_board = utils_test.load_board('''
     .........
     .........
     ......X..
     .........
     .........
     .........
     .........
     .........
     .........
   ''')
   intermediate_position = go.Position(
       utils_test.BOARD_SIZE,
       intermediate_board,
       n=1,
       komi=5.5,
       caps=(0, 0),
       recent=(go.PlayerMove(go.BLACK, coords.from_kgs(
           utils_test.BOARD_SIZE, 'G7')),),
       to_play=go.BLACK,
   )
   final_board = utils_test.load_board('''
     ....OX...
     .O.OOX...
     O.O.X.X..
     .OXXX....
     OX...XX..
     .X.XXO...
     X.XOOXXX.
     XXXO.OOX.
     .XOOX.O..
   ''')
   final_position = go.Position(
       utils_test.BOARD_SIZE,
       final_board,
       n=50,
       komi=5.5,
       caps=(7, 2),
       ko=None,
       recent=(
           go.PlayerMove(
               go.WHITE, coords.from_kgs(utils_test.BOARD_SIZE, 'E9')),
           go.PlayerMove(
               go.BLACK, coords.from_kgs(utils_test.BOARD_SIZE, 'F9')),),
       to_play=go.WHITE
   )
   positions_w_context = list(replay_sgf(
       utils_test.BOARD_SIZE, CHINESE_HANDICAP_SGF))
   self.assertEqualPositions(
       intermediate_position, positions_w_context[1].position)
   self.assertEqual(
       positions_w_context[1].next_move, coords.from_kgs(
           utils_test.BOARD_SIZE, 'C3'))
   final_replayed_position = positions_w_context[-1].position.play_move(
       positions_w_context[-1].next_move)
   self.assertEqualPositions(final_position, final_replayed_position)
Beispiel #15
0
def initialize_game(sgf_file, load_file, move=1):
    with open(sgf_file) as f:
        sgf_contents = f.read()
    iterator = sgf_wrapper.replay_sgf(sgf_contents)
    for i in range(move):
        position_w_context = next(iterator)
    player = strategies.MCTSPlayerMixin(dual_net.DualNetwork(load_file))
    player.initialize_game(position_w_context.position)
    return player
Beispiel #16
0
def get_positions_from_sgf(file):     #取得行棋位置
    print("正在处理棋谱文件:%s"%file)
    #auto_play.game().__init__()
    with open(file) as t:                                   #打开一个文件到内存
         ft=replay_sgf(t.read())

         auto_play.game().run(ft,file)                      #自动显示棋谱


    with open(file) as f:                                   #打开一个文件到内存(上面已经打开过 要重新打开)

         for  i,position_w_context in enumerate(replay_sgf(f.read())):   #循环打开棋谱文件,得到棋谱数据 使用枚举得到坐标
             #print("正在处理第%s手"%(i+1))
             #print(position_w_context.next_move)    #sgf坐标 横坐标(从左到右) 从a到s   纵坐标:从上到下a到s    现在使用数字坐标先是纵坐票0到18   后是横从坐票0到18


             if position_w_context.is_usable():
                 yield position_w_context
Beispiel #17
0
 def test_chinese_handicap_handling(self):
     intermediate_board = utils_test.load_board('''
   .........
   .........
   ......X..
   .........
   .........
   .........
   .........
   .........
   .........
 ''')
     intermediate_position = go.Position(
         utils_test.BOARD_SIZE,
         intermediate_board,
         n=1,
         komi=5.5,
         caps=(0, 0),
         recent=(go.PlayerMove(go.BLACK,
                               coords.from_kgs(utils_test.BOARD_SIZE,
                                               'G7')), ),
         to_play=go.BLACK,
     )
     final_board = utils_test.load_board('''
   ....OX...
   .O.OOX...
   O.O.X.X..
   .OXXX....
   OX...XX..
   .X.XXO...
   X.XOOXXX.
   XXXO.OOX.
   .XOOX.O..
 ''')
     final_position = go.Position(
         utils_test.BOARD_SIZE,
         final_board,
         n=50,
         komi=5.5,
         caps=(7, 2),
         ko=None,
         recent=(
             go.PlayerMove(go.WHITE,
                           coords.from_kgs(utils_test.BOARD_SIZE, 'E9')),
             go.PlayerMove(go.BLACK,
                           coords.from_kgs(utils_test.BOARD_SIZE, 'F9')),
         ),
         to_play=go.WHITE)
     positions_w_context = list(
         replay_sgf(utils_test.BOARD_SIZE, CHINESE_HANDICAP_SGF))
     self.assertEqualPositions(intermediate_position,
                               positions_w_context[1].position)
     self.assertEqual(positions_w_context[1].next_move,
                      coords.from_kgs(utils_test.BOARD_SIZE, 'C3'))
     final_replayed_position = positions_w_context[-1].position.play_move(
         positions_w_context[-1].next_move)
     self.assertEqualPositions(final_position, final_replayed_position)
Beispiel #18
0
def initialize_game(sgf_file, load_file, move=1):
    with open(sgf_file) as f:
        sgf_contents = f.read()
    iterator = sgf_wrapper.replay_sgf(sgf_contents)
    for i in range(move):
        position_w_context = next(iterator)
    player = strategies.MCTSPlayerMixin(dual_net.DualNetwork(load_file))
    player.initialize_game(position_w_context.position)
    return player
Beispiel #19
0
 def test_japanese_handicap_handling(self):
     intermediate_board = utils_test.load_board('''
   .........
   .........
   ......X..
   .........
   ....O....
   .........
   ..X......
   .........
   .........
 ''')
     intermediate_position = go.Position(
         utils_test.BOARD_SIZE,
         intermediate_board,
         n=1,
         komi=5.5,
         caps=(0, 0),
         recent=(go.PlayerMove(go.WHITE,
                               coords.from_kgs(utils_test.BOARD_SIZE,
                                               'E5')), ),
         to_play=go.BLACK,
     )
     final_board = utils_test.load_board('''
   .........
   .........
   ......X..
   .........
   ....O....
   .........
   ..XX.....
   .........
   .........
 ''')
     final_position = go.Position(
         utils_test.BOARD_SIZE,
         final_board,
         n=2,
         komi=5.5,
         caps=(0, 0),
         recent=(
             go.PlayerMove(go.WHITE,
                           coords.from_kgs(utils_test.BOARD_SIZE, 'E5')),
             go.PlayerMove(go.BLACK,
                           coords.from_kgs(utils_test.BOARD_SIZE, 'D3')),
         ),
         to_play=go.WHITE,
     )
     positions_w_context = list(
         replay_sgf(utils_test.BOARD_SIZE, JAPANESE_HANDICAP_SGF))
     self.assertEqualPositions(intermediate_position,
                               positions_w_context[1].position)
     final_replayed_position = positions_w_context[-1].position.play_move(
         positions_w_context[-1].next_move)
     self.assertEqualPositions(final_position, final_replayed_position)
Beispiel #20
0
def predict_move(filename, network):
  # Strategies: def initialize_game(self, position=None):

  #filename = '/usr/local/google/home/vbittorf/projects/minigo/benchmark_sgf/prob_0001.sgf'
  replay = []

  with open(filename) as f:
      text = f.read()
      print(text)
      for position_w_context in sgf_wrapper.replay_sgf(text):
        replay.append(position_w_context)

  print(replay)

  # model_path = '/usr/local/google/home/vbittorf/Documents/minigo/rl_pipeline/models/000003-leopard'
  #model_path = '/usr/local/google/home/vbittorf/Documents/minigo/20hour1000game/models/000002-nassau'
  #white_net = dual_net.DualNetwork(model_path)
  #black_net = dual_net.DualNetwork(model_path)

  #print(evaluation.play_match(white_net, black_net, 1, 50, "/tmp/sgf", 0))


  black_net = network

  player = MCTSPlayer(
        black_net, verbosity=0, two_player_mode=True, num_parallel=4)

  readouts = 361 * 10
  tried = 0
  correct = 0
  for position_w_context in replay:
      if position_w_context.next_move is None:
          continue
      player.initialize_game(position_w_context.position)

      current_readouts = player.root.N
      while player.root.N < current_readouts + readouts:
         player.tree_search()


      move = player.pick_move()
      #if player.should_resign():  # Force resign
      #  move = 'R'
      #else:
      #  move = player.suggest_move(position_w_context.position)
      tried += 1
      if move == position_w_context.next_move:
        correct += 1
      player.play_move(move)
      print(player.root.position)
      print(move, position_w_context.next_move)
      return move, position_w_context.next_move, move == position_w_context.next_move
  print('Correct: ', correct * 1.0 / tried)
def predict_move(filename, network):
    # Strategies: def initialize_game(self, position=None):

    #filename = '/usr/local/google/home/vbittorf/projects/minigo/benchmark_sgf/prob_0001.sgf'
    replay = []

    with open(filename) as f:
        text = f.read()
        print(text)
        for position_w_context in sgf_wrapper.replay_sgf(text):
            replay.append(position_w_context)

    print(replay)

    # model_path = '/usr/local/google/home/vbittorf/Documents/minigo/rl_pipeline/models/000003-leopard'
    #model_path = '/usr/local/google/home/vbittorf/Documents/minigo/20hour1000game/models/000002-nassau'
    #white_net = dual_net.DualNetwork(model_path)
    #black_net = dual_net.DualNetwork(model_path)

    #print(evaluation.play_match(white_net, black_net, 1, 50, "/tmp/sgf", 0))

    black_net = network

    player = MCTSPlayer(black_net,
                        verbosity=0,
                        two_player_mode=True,
                        num_parallel=4)

    readouts = 361 * 10
    tried = 0
    correct = 0
    for position_w_context in replay:
        if position_w_context.next_move is None:
            continue
        player.initialize_game(position_w_context.position)

        current_readouts = player.root.N
        while player.root.N < current_readouts + readouts:
            player.tree_search()

        move = player.pick_move()
        # if player.should_resign():  # Force resign
        #  move = 'R'
        # else:
        #  move = player.suggest_move(position_w_context.position)
        tried += 1
        if move == position_w_context.next_move:
            correct += 1
        player.play_move(move)
        print(player.root.position)
        print(move, position_w_context.next_move)
        return move, position_w_context.next_move, move == position_w_context.next_move
    print('Correct: ', correct * 1.0 / tried)
Beispiel #22
0
 def test_japanese_handicap_handling(self):
   intermediate_board = utils_test.load_board('''
     .........
     .........
     ......X..
     .........
     ....O....
     .........
     ..X......
     .........
     .........
   ''')
   intermediate_position = go.Position(
       utils_test.BOARD_SIZE,
       intermediate_board,
       n=1,
       komi=5.5,
       caps=(0, 0),
       recent=(go.PlayerMove(go.WHITE, coords.from_kgs(
           utils_test.BOARD_SIZE, 'E5')),),
       to_play=go.BLACK,
   )
   final_board = utils_test.load_board('''
     .........
     .........
     ......X..
     .........
     ....O....
     .........
     ..XX.....
     .........
     .........
   ''')
   final_position = go.Position(
       utils_test.BOARD_SIZE,
       final_board,
       n=2,
       komi=5.5,
       caps=(0, 0),
       recent=(
           go.PlayerMove(go.WHITE, coords.from_kgs(
               utils_test.BOARD_SIZE, 'E5')),
           go.PlayerMove(go.BLACK, coords.from_kgs(
               utils_test.BOARD_SIZE, 'D3')),),
       to_play=go.WHITE,
   )
   positions_w_context = list(replay_sgf(
       utils_test.BOARD_SIZE, JAPANESE_HANDICAP_SGF))
   self.assertEqualPositions(
       intermediate_position, positions_w_context[1].position)
   final_replayed_position = positions_w_context[-1].position.play_move(
       positions_w_context[-1].next_move)
   self.assertEqualPositions(final_position, final_replayed_position)
Beispiel #23
0
def parse_sgf(sgf_path):
  with open(sgf_path) as f:
    sgf_contents = f.read()

  collection = sgf.parse(sgf_contents)
  game = collection.children[0]
  props = game.root.properties
  assert int(sgf_prop(props.get('GM', ['1']))) == 1, "Not a Go SGF!"

  result = utils.parse_game_result(sgf_prop(props.get('RE')))

  positions, moves = zip(*[(p.position, p.next_move) for p in sgf_wrapper.replay_sgf(sgf_contents)])
  return positions, moves, result, props
Beispiel #24
0
 def test_chinese_handicap_handling(self):
     intermediate_board = load_board('''
         .........
         .........
         ......X..
         .........
         .........
         .........
         .........
         .........
         .........
     ''')
     intermediate_position = go.Position(
         intermediate_board,
         n=1,
         komi=5.5,
         caps=(0, 0),
         recent=(go.PlayerMove(go.BLACK, pc('G7')), ),
         to_play=go.BLACK,
     )
     final_board = load_board('''
         ....OX...
         .O.OOX...
         O.O.X.X..
         .OXXX....
         OX...XX..
         .X.XXO...
         X.XOOXXX.
         XXXO.OOX.
         .XOOX.O..
     ''')
     final_position = go.Position(final_board,
                                  n=50,
                                  komi=5.5,
                                  caps=(7, 2),
                                  ko=None,
                                  recent=(
                                      go.PlayerMove(go.WHITE, pc('E9')),
                                      go.PlayerMove(go.BLACK, pc('F9')),
                                  ),
                                  to_play=go.WHITE)
     positions_w_context = list(replay_sgf(CHINESE_HANDICAP_SGF))
     self.assertEqualPositions(intermediate_position,
                               positions_w_context[1].position)
     self.assertEqual(positions_w_context[1].next_move, pc('C3'))
     self.assertEqualPositions(final_position,
                               positions_w_context[-1].position)
     self.assertFalse(positions_w_context[-1].is_usable())
     self.assertTrue(positions_w_context[-2].is_usable())
Beispiel #25
0
def parse_sgf(sgf_path):
    # TODO(sethtroisi): Replace uses with call to sgf_wrapper.
    with open(sgf_path) as f:
        sgf_contents = f.read()

    collection = sgf.parse(sgf_contents)
    game = collection.children[0]
    props = game.root.properties
    assert int(sgf_prop_get(props, 'GM', '1')) == 1, "Not a Go SGF!"

    result = parse_game_result(sgf_prop_get(props, 'RE', ''))

    positions, moves = zip(*[(p.position, p.next_move)
                             for p in replay_sgf(sgf_contents)])
    return positions, moves, result, props
Beispiel #26
0
    def test_japanese_handicap_handling(self):
        intermediate_board = load_board('''
            .........
            .........
            ......X..
            .........
            ....O....
            .........
            ..X......
            .........
            .........
        ''')
        intermediate_position = go.Position(
            intermediate_board,
            n=1,
            komi=5.5,
            caps=(0, 0),
            recent=(go.PlayerMove(go.WHITE, pc('E5')), ),
            to_play=go.BLACK,
        )
        final_board = load_board('''
            .........
            .........
            ......X..
            .........
            ....O....
            .........
            ..XX.....
            .........
            .........
        ''')
        final_position = go.Position(
            final_board,
            n=2,
            komi=5.5,
            caps=(0, 0),
            recent=(
                go.PlayerMove(go.WHITE, pc('E5')),
                go.PlayerMove(go.BLACK, pc('D3')),
            ),
            to_play=go.WHITE,
        )

        positions_w_context = list(replay_sgf(JAPANESE_HANDICAP_SGF))
        self.assertEqualPositions(intermediate_position,
                                  positions_w_context[1].position)
        self.assertEqualPositions(final_position,
                                  positions_w_context[-1].position)
Beispiel #27
0
    def cmd_loadsgf(self, filename: str, movenum=0):
        try:
            with open(filename, 'r') as f:
                contents = f.read()
        except:
            raise ValueError("Unreadable file: " + filename)

        # This is kinda bad, because replay_sgf is already calling
        # 'play move' on its internal position objects, but we really
        # want to advance the engine along with us rather than try to
        # push in some finished Position object.
        for idx, p in enumerate(sgf_wrapper.replay_sgf(contents)):
            print("playing #", idx, p.next_move, file=sys.stderr)
            self._player.play_move(p.next_move)
            if movenum and idx == movenum:
                break
Beispiel #28
0
 def test_chinese_handicap_handling(self):
     intermediate_board = load_board('''
         .........
         .........
         ......X..
         .........
         .........
         .........
         .........
         .........
         .........
     ''')
     intermediate_position = go.Position(
         intermediate_board,
         n=1,
         komi=5.5,
         caps=(0, 0),
         recent=(go.PlayerMove(go.BLACK, pc('G7')),),
         to_play=go.BLACK,
     )
     final_board = load_board('''
         ....OX...
         .O.OOX...
         O.O.X.X..
         .OXXX....
         OX...XX..
         .X.XXO...
         X.XOOXXX.
         XXXO.OOX.
         .XOOX.O..
     ''')
     final_position = go.Position(
         final_board,
         n=50,
         komi=5.5,
         caps=(7, 2),
         ko=None,
         recent=(go.PlayerMove(go.WHITE, pc('E9')),
                 go.PlayerMove(go.BLACK, pc('F9')),),
         to_play=go.WHITE
     )
     positions_w_context = list(replay_sgf(CHINESE_HANDICAP_SGF))
     self.assertEqualPositions(intermediate_position, positions_w_context[1].position)
     self.assertEqual(positions_w_context[1].next_move, pc('C3'))
     self.assertEqualPositions(final_position, positions_w_context[-1].position)
     self.assertFalse(positions_w_context[-1].is_usable())
     self.assertTrue(positions_w_context[-2].is_usable())
Beispiel #29
0
    def test_japanese_handicap_handling(self):
        intermediate_board = load_board('''
            .........
            .........
            ......X..
            .........
            ....O....
            .........
            ..X......
            .........
            .........
        ''')
        intermediate_position = go.Position(
            intermediate_board,
            n=1,
            komi=5.5,
            caps=(0, 0),
            recent=(go.PlayerMove(go.WHITE, pc('E5')),),
            to_play=go.BLACK,
        )
        final_board = load_board('''
            .........
            .........
            ......X..
            .........
            ....O....
            .........
            ..XX.....
            .........
            .........
        ''')
        final_position = go.Position(
            final_board,
            n=2,
            komi=5.5,
            caps=(0, 0),
            recent=(go.PlayerMove(go.WHITE, pc('E5')),
                    go.PlayerMove(go.BLACK, pc('D3')),),
            to_play=go.WHITE,
        )

        positions_w_context = list(replay_sgf(JAPANESE_HANDICAP_SGF))
        self.assertEqualPositions(intermediate_position, positions_w_context[1].position)
        self.assertEqualPositions(final_position, positions_w_context[-1].position)
Beispiel #30
0
def analyze_symmetries(sgf_file, load_file):
    with open(sgf_file) as f:
        sgf_contents = f.read()
    iterator = sgf_wrapper.replay_sgf(sgf_contents)
    net = dual_net.DualNetwork(load_file)
    for i, pwc in enumerate(iterator):
        if i < 200:
            continue
        feats = features.extract_features(pwc.position)
        variants = [symmetries.apply_symmetry_feat(s, feats) for s in symmetries.SYMMETRIES]
        values = net.sess.run(
            net.inference_output['value_output'],
            feed_dict={net.inference_input['pos_tensor']: variants})
        mean = np.mean(values)
        stdev = np.std(values)
        all_vals = sorted(zip(values, symmetries.SYMMETRIES))

        print("{:3d} {:.3f} +/- {:.3f} min {:.3f} {} max {:.3f} {}".format(
            i, mean, stdev, *all_vals[0], *all_vals[-1]))
Beispiel #31
0
    def cmd_loadsgf(self, filename: str, movenum=0):
        try:
            with open(filename, 'r') as f:
                contents = f.read()
        except:
            raise ValueError("Unreadable file: " + filename)

        # Clear the board before replaying sgf
        # TODO: should this use the sgfs komi?
        self._player.initialize_game(go.Position())

        # This is kinda bad, because replay_sgf is already calling
        # 'play move' on its internal position objects, but we really
        # want to advance the engine along with us rather than try to
        # push in some finished Position object.
        for idx, p in enumerate(sgf_wrapper.replay_sgf(contents)):
            dbg("playing #", idx, p.next_move)
            self._player.play_move(p.next_move)
            if movenum and idx == movenum:
                break
Beispiel #32
0
def analyze_symmetries(sgf_file, load_file):
    with open(sgf_file) as f:
        sgf_contents = f.read()
    iterator = sgf_wrapper.replay_sgf(sgf_contents)
    net = dual_net.DualNetwork(load_file)
    for i, pwc in enumerate(iterator):
        if i < 200:
            continue
        feats = features.extract_features(pwc.position)
        variants = [
            symmetries.apply_symmetry_feat(s, feats)
            for s in symmetries.SYMMETRIES
        ]
        values = net.sess.run(
            net.inference_output['value_output'],
            feed_dict={net.inference_input['pos_tensor']: variants})
        mean = np.mean(values)
        stdev = np.std(values)
        all_vals = sorted(zip(values, symmetries.SYMMETRIES))

        print("{:3d} {:.3f} +/- {:.3f} min {:.3f} {} max {:.3f} {}".format(
            i, mean, stdev, *all_vals[0], *all_vals[-1]))
Beispiel #33
0
    def test_replay_position(self):
        sgf_positions = list(replay_sgf(NO_HANDICAP_SGF))
        initial = sgf_positions[0]
        self.assertEqual(initial.metadata.result, 'W+1.5')
        self.assertEqual(initial.metadata.board_size, 9)
        self.assertEqual(initial.position.komi, 6.5)

        final = sgf_positions[-1].position

        # sanity check to ensure we're working with the right position
        final_board = load_board('''
            .OXX.....
            O.OX.X...
            .OOX.....
            OOOOXXXXX
            XOXXOXOOO
            XOOXOO.O.
            XOXXXOOXO
            XXX.XOXXO
            X..XOO.O.
        ''')
        expected_final_position = go.Position(
            final_board,
            n=62,
            komi=6.5,
            caps=(3, 2),
            ko=None,
            recent=tuple(),
            to_play=go.BLACK
        )
        self.assertEqualPositions(expected_final_position, final)
        self.assertEqual(final.n, len(final.recent))

        replayed_positions = list(replay_position(final))
        for sgf_pos, replay_pos in zip(sgf_positions, replayed_positions):
            self.assertEqualPositions(sgf_pos.position, replay_pos.position)
Beispiel #34
0
def get_positions_from_sgf(file):
    with open(file) as f:
        for position_w_content in replay_sgf(f.read()):
            if position_w_content.is_usable():
                yield position_w_content
Beispiel #35
0
 def test_sgf_props(self):
   sgf_replayer = replay_sgf(utils_test.BOARD_SIZE, CHINESE_HANDICAP_SGF)
   initial = next(sgf_replayer)
   self.assertEqual(initial.result, go.BLACK)
   self.assertEqual(initial.position.komi, 5.5)
Beispiel #36
0
 def test_sgf_props(self):
     sgf_replayer = replay_sgf(utils_test.BOARD_SIZE, CHINESE_HANDICAP_SGF)
     initial = next(sgf_replayer)
     self.assertEqual(initial.result, go.BLACK)
     self.assertEqual(initial.position.komi, 5.5)
 def test_sgf_props(self):
     sgf_replayer = replay_sgf(CHINESE_HANDICAP_SGF)
     initial = next(sgf_replayer)
     self.assertEqual(initial.metadata.result, 'B+39.50')
     self.assertEqual(initial.metadata.board_size, 9)
     self.assertEqual(initial.position.komi, 5.5)
Beispiel #38
0
def parse_sgf(sgf_path):
    with open(sgf_path) as f:
        sgf_contents = f.read()

    return zip(*[(p.position, p.next_move, p.result)
                 for p in sgf_wrapper.replay_sgf(sgf_contents)])
Beispiel #39
0
def get_positions_from_sgf(file):
    with open(file) as f:
        for position_w_context in replay_sgf(f.read()):
            if position_w_context.is_usable():
                yield position_w_context
Beispiel #40
0
 def test_sgf_props(self):
     sgf_replayer = replay_sgf(CHINESE_HANDICAP_SGF)
     initial = next(sgf_replayer)
     self.assertEqual(go.BLACK, initial.result)
     self.assertEqual(5.5, initial.position.komi)
Beispiel #41
0
 def test_sgf_props(self):
     sgf_replayer = replay_sgf(CHINESE_HANDICAP_SGF)
     initial = next(sgf_replayer)
     self.assertEqual(initial.metadata.result, 'B+39.50')
     self.assertEqual(initial.metadata.board_size, 9)
     self.assertEqual(initial.position.komi, 5.5)