sgf_wrapper.py 6.39 KB
Newer Older
Yanhui Liang's avatar
Yanhui Liang committed
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
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Code to extract a series of positions + their next moves from an SGF.

Most of the complexity here is dealing with two features of SGF:
- Stones can be added via "play move" or "add move", the latter being used
  to configure L+D puzzles, but also for initial handicap placement.
- Plays don't necessarily alternate colors; they can be repeated B or W moves
  This feature is used to handle free handicap placement.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import coords
import go
from go import Position, PositionWithContext
import numpy as np
import sgf
import utils

34
SGF_TEMPLATE = '''(;GM[1]FF[4]CA[UTF-8]AP[Minigo_sgfgenerator]RU[{ruleset}]
Yanhui Liang's avatar
Yanhui Liang committed
35
SZ[{boardsize}]KM[{komi}]PW[{white_name}]PB[{black_name}]RE[{result}]
36
{game_moves})'''
Yanhui Liang's avatar
Yanhui Liang committed
37

38
PROGRAM_IDENTIFIER = 'Minigo'
Yanhui Liang's avatar
Yanhui Liang committed
39
40
41


def translate_sgf_move_qs(player_move, q):
42
43
  return '{move}C[{q:.4f}]'.format(
      move=translate_sgf_move(player_move), q=q)
Yanhui Liang's avatar
Yanhui Liang committed
44
45
46
47


def translate_sgf_move(player_move, comment):
  if player_move.color not in (go.BLACK, go.WHITE):
48
49
    raise ValueError(
        'Can\'t translate color {} to sgf'.format(player_move.color))
Yanhui Liang's avatar
Yanhui Liang committed
50
51
52
53
  c = coords.to_sgf(player_move.move)
  color = 'B' if player_move.color == go.BLACK else 'W'
  if comment is not None:
    comment = comment.replace(']', r'\]')
54
    comment_node = 'C[{}]'.format(comment)
Yanhui Liang's avatar
Yanhui Liang committed
55
  else:
56
57
58
59
60
61
62
63
64
    comment_node = ''
  return ';{color}[{coords}]{comment_node}'.format(
      color=color, coords=c, comment_node=comment_node)

  # pylint: disable=unused-argument
  # pylint: disable=unused-variable
def make_sgf(board_size, move_history, result_string, ruleset='Chinese',
             komi=7.5, white_name=PROGRAM_IDENTIFIER,
             black_name=PROGRAM_IDENTIFIER, comments=[]):
Yanhui Liang's avatar
Yanhui Liang committed
65
66
67
68
69
  """Turn a game into SGF.

  Doesn't handle handicap games or positions with incomplete history.

  Args:
70
71
    board_size: the go board size.
    move_history: iterable of PlayerMoves.
Yanhui Liang's avatar
Yanhui Liang committed
72
    result_string: "B+R", "W+0.5", etc.
73
74
75
76
    ruleset: the rule set of go game
    komi: komi score
    white_name: the name of white player
    black_name: the name of black player
Yanhui Liang's avatar
Yanhui Liang committed
77
78
79
80
81
82
83
84
85
86
87
    comments: iterable of string/None. Will be zipped with move_history.
  """
  try:
    # Python 2
    from itertools import izip_longest
    zip_longest = izip_longest
  except ImportError:
    # Python 3
    from itertools import zip_longest

  boardsize = board_size
88
89
  game_moves = ''.join(translate_sgf_move(*z) for z in zip_longest(
      move_history, comments))
Yanhui Liang's avatar
Yanhui Liang committed
90
91
92
93
94
  result = result_string
  return SGF_TEMPLATE.format(**locals())


def sgf_prop(value_list):
95
  """Converts raw sgf library output to sensible value."""
Yanhui Liang's avatar
Yanhui Liang committed
96
97
98
99
100
101
102
103
104
105
106
107
108
  if value_list is None:
    return None
  if len(value_list) == 1:
    return value_list[0]
  else:
    return value_list


def sgf_prop_get(props, key, default):
  return sgf_prop(props.get(key, default))


def handle_node(board_size, pos, node):
109
  """A node can either add B+W stones, play as B, or play as W."""
Yanhui Liang's avatar
Yanhui Liang committed
110
  props = node.properties
111
112
  black_stones_added = [coords.from_sgf(c) for c in props.get('AB', [])]
  white_stones_added = [coords.from_sgf(c) for c in props.get('AW', [])]
Yanhui Liang's avatar
Yanhui Liang committed
113
  if black_stones_added or white_stones_added:
114
    return add_stones(board_size, pos, black_stones_added, white_stones_added)
Yanhui Liang's avatar
Yanhui Liang committed
115
116
117
  # If B/W props are not present, then there is no move. But if it is present
  # and equal to the empty string, then the move was a pass.
  elif 'B' in props:
118
    black_move = coords.from_sgf(props.get('B', [''])[0])
Yanhui Liang's avatar
Yanhui Liang committed
119
120
    return pos.play_move(black_move, color=go.BLACK)
  elif 'W' in props:
121
    white_move = coords.from_sgf(props.get('W', [''])[0])
Yanhui Liang's avatar
Yanhui Liang committed
122
123
124
125
126
    return pos.play_move(white_move, color=go.WHITE)
  else:
    return pos


127
def add_stones(board_size, pos, black_stones_added, white_stones_added):
Yanhui Liang's avatar
Yanhui Liang committed
128
129
130
  working_board = np.copy(pos.board)
  go.place_stones(working_board, go.BLACK, black_stones_added)
  go.place_stones(working_board, go.WHITE, white_stones_added)
131
132
133
  new_position = Position(
      board_size, board=working_board, n=pos.n, komi=pos.komi,
      caps=pos.caps, ko=pos.ko, recent=pos.recent, to_play=pos.to_play)
Yanhui Liang's avatar
Yanhui Liang committed
134
135
136
  return new_position


137
def get_next_move(node):
Yanhui Liang's avatar
Yanhui Liang committed
138
139
  props = node.next.properties
  if 'W' in props:
140
    return coords.from_sgf(props['W'][0])
Yanhui Liang's avatar
Yanhui Liang committed
141
  else:
142
    return coords.from_sgf(props['B'][0])
Yanhui Liang's avatar
Yanhui Liang committed
143
144
145


def maybe_correct_next(pos, next_node):
146
147
  if (('B' in next_node.properties and pos.to_play != go.BLACK) or
      ('W' in next_node.properties and pos.to_play != go.WHITE)):
Yanhui Liang's avatar
Yanhui Liang committed
148
149
150
151
    pos.flip_playerturn(mutate=True)


def replay_sgf(board_size, sgf_contents):
152
  """Wrapper for sgf files.
Yanhui Liang's avatar
Yanhui Liang committed
153
154
155
156
157
158
159
160

  It does NOT return the very final position, as there is no follow up.
  To get the final position, call pwc.position.play_move(pwc.next_move)
  on the last PositionWithContext returned.
  Example usage:
  with open(filename) as f:
    for position_w_context in replay_sgf(f.read()):
      print(position_w_context.position)
161
162
163
164
165
166
167

  Args:
    board_size: the go board size.
    sgf_contents: the content in sgf.

  Yields:
    The go.PositionWithContext instances.
Yanhui Liang's avatar
Yanhui Liang committed
168
169
170
171
  """
  collection = sgf.parse(sgf_contents)
  game = collection.children[0]
  props = game.root.properties
172
  assert int(sgf_prop(props.get('GM', ['1']))) == 1, 'Not a Go SGF!'
Yanhui Liang's avatar
Yanhui Liang committed
173
174

  komi = 0
175
  if props.get('KM') is not None:
Yanhui Liang's avatar
Yanhui Liang committed
176
177
178
    komi = float(sgf_prop(props.get('KM')))
  result = utils.parse_game_result(sgf_prop(props.get('RE')))

179
  pos = Position(board_size, komi=komi)
Yanhui Liang's avatar
Yanhui Liang committed
180
181
182
183
  current_node = game.root
  while pos is not None and current_node.next is not None:
    pos = handle_node(board_size, pos, current_node)
    maybe_correct_next(pos, current_node.next)
184
    next_move = get_next_move(current_node)
Yanhui Liang's avatar
Yanhui Liang committed
185
186
187
188
189
190
191
192
    yield PositionWithContext(pos, next_move, result)
    current_node = current_node.next


def replay_sgf_file(board_size, sgf_file):
  with open(sgf_file) as f:
    for pwc in replay_sgf(board_size, f.read()):
      yield pwc