🎉 Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io 🎉
Avatar of Ginoalni

Ginoalni's solution

to SGF Parsing in the Python Track

Published at Apr 13 2021 · 0 comments
Instructions
Test suite
Solution

Parsing a Smart Game Format string.

SGF is a standard format for storing board game files, in particular go.

SGF is a fairly simple format. An SGF file usually contains a single tree of nodes where each node is a property list. The property list contains key value pairs, each key can only occur once but may have multiple values.

An SGF file may look like this:

(;FF[4]C[root]SZ[19];B[aa];W[ab])

This is a tree with three nodes:

  • The top level node has three properties: FF[4] (key = "FF", value = "4"), C[root](key = "C", value = "root") and SZ[19] (key = "SZ", value = "19"). (FF indicates the version of SGF, C is a comment and SZ is the size of the board.)
    • The top level node has a single child which has a single property: B[aa]. (Black plays on the point encoded as "aa", which is the 1-1 point (which is a stupid place to play)).
      • The B[aa] node has a single child which has a single property: W[ab].

As you can imagine an SGF file contains a lot of nodes with a single child, which is why there's a shorthand for it.

SGF can encode variations of play. Go players do a lot of backtracking in their reviews (let's try this, doesn't work, let's try that) and SGF supports variations of play sequences. For example:

(;FF[4](;B[aa];W[ab])(;B[dd];W[ee]))

Here the root node has two variations. The first (which by convention indicates what's actually played) is where black plays on 1-1. Black was sent this file by his teacher who pointed out a more sensible play in the second child of the root node: B[dd] (4-4 point, a very standard opening to take the corner).

A key can have multiple values associated with it. For example:

(;FF[4];AB[aa][ab][ba])

Here AB (add black) is used to add three black stones to the board.

There are a few more complexities to SGF (and parsing in general), which you can mostly ignore. You should assume that the input is encoded in UTF-8, the tests won't contain a charset property, so don't worry about that. Furthermore you may assume that all newlines are unix style (\n, no \r or \r\n will be in the tests) and that no optional whitespace between properties, nodes, etc will be in the tests.

The exercise will have you parse an SGF string and return a tree structure of properties. You do not need to encode knowledge about the data types of properties, just use the rules for the text type everywhere.

Exception messages

Sometimes it is necessary to raise an exception. When you do this, you should include a meaningful error message to indicate what the source of the error is. This makes your code more readable and helps significantly with debugging. Not every exercise will require you to raise an exception, but for those that do, the tests will only pass if you include a message.

To raise a message with an exception, just write it as an argument to the exception type. For example, instead of raise Exception, you should write:

raise Exception("Meaningful message indicating the source of the error")

Running the tests

To run the tests, run pytest sgf_parsing_test.py

Alternatively, you can tell Python to run the pytest module: python -m pytest sgf_parsing_test.py

Common pytest options

  • -v : enable verbose output
  • -x : stop running tests on first failure
  • --ff : run failures from previous test before running other test cases

For other options, see python -m pytest -h

Submitting Exercises

Note that, when trying to submit an exercise, make sure the solution is in the $EXERCISM_WORKSPACE/python/sgf-parsing directory.

You can find your Exercism workspace by running exercism debug and looking for the line that starts with Workspace.

For more detailed information about running tests, code style and linting, please see Running the Tests.

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

sgf_parsing_test.py

import unittest

from sgf_parsing import parse, SgfTree

# Tests adapted from `problem-specifications//canonical-data.json`


class SgfParsingTest(unittest.TestCase):
    def test_empty_input(self):
        input_string = ""
        with self.assertRaisesWithMessage(ValueError):
            parse(input_string)

    def test_tree_with_no_nodes(self):
        input_string = "()"
        with self.assertRaisesWithMessage(ValueError):
            parse(input_string)

    def test_node_without_tree(self):
        input_string = ";"
        with self.assertRaisesWithMessage(ValueError):
            parse(input_string)

    def test_node_without_properties(self):
        input_string = "(;)"
        expected = SgfTree()
        self.assertEqual(parse(input_string), expected)

    def test_single_node_tree(self):
        input_string = "(;A[B])"
        expected = SgfTree(properties={"A": ["B"]})
        self.assertEqual(parse(input_string), expected)

    def test_multiple_properties(self):
        input_string = "(;A[b]C[d])"
        expected = SgfTree(properties={"A": ["b"], "C": ["d"]})
        self.assertEqual(parse(input_string), expected)

    def test_properties_without_delimiter(self):
        input_string = "(;A)"
        with self.assertRaisesWithMessage(ValueError):
            parse(input_string)

    def test_all_lowercase_property(self):
        input_string = "(;a[b])"
        with self.assertRaisesWithMessage(ValueError):
            parse(input_string)

    def test_upper_and_lowercase_property(self):
        input_string = "(;Aa[b])"
        with self.assertRaisesWithMessage(ValueError):
            parse(input_string)

    def test_two_nodes(self):
        input_string = "(;A[B];B[C])"
        expected = SgfTree(properties={"A": ["B"]}, children=[SgfTree({"B": ["C"]})])
        self.assertEqual(parse(input_string), expected)

    def test_two_child_trees(self):
        input_string = "(;A[B](;B[C])(;C[D]))"
        expected = SgfTree(
            properties={"A": ["B"]},
            children=[SgfTree({"B": ["C"]}), SgfTree({"C": ["D"]})],
        )
        self.assertEqual(parse(input_string), expected)

    def test_multiple_property_values(self):
        input_string = "(;A[b][c][d])"
        expected = SgfTree(properties={"A": ["b", "c", "d"]})
        self.assertEqual(parse(input_string), expected)

    def test_escaped_property(self):
        input_string = "(;A[\\]b\nc\nd\t\te \n\\]])"
        expected = SgfTree(properties={"A": ["]b\nc\nd  e \n]"]})
        self.assertEqual(parse(input_string), expected)

    # Utility functions
    def assertRaisesWithMessage(self, exception):
        return self.assertRaisesRegex(exception, r".+")


if __name__ == "__main__":
    unittest.main()
"""To check if SGF string is in correct format"""
import re

non_child_pat = re.compile(r"((?![^\[]*\])[\w,\(,\),;])", re.DOTALL)
match_pat = re.compile(r"^\(;.*\)$", re.DOTALL)

class SgfTree:
    """To compair several SgfTrees"""

    def __init__(self, properties=None, children=None):
        self.properties = properties or {}
        self.children = children or []

    def __eq__(self, other):
        if not isinstance(other, SgfTree):
            return False
        for k, v in self.properties.items():
            if k not in other.properties:
                return False
            if other.properties[k] != v:
                return False
        for k in other.properties.keys():
            if k not in self.properties:
                return False
        if len(self.children) != len(other.children):
            return False
        for a, b in zip(self.children, other.children):
            if a != b:
                return False
        return True

    def __ne__(self, other):
        return not self == other


def parse(input_string):
    def convert(convert_str):
        ls_converted = []
        if not escaped:
            ls_converted[:0] = convert_str
        else:
            ls_converted.append(convert_str)
        return ls_converted

    def sgf_split(to_split):
        tree_prop = []
        tree_child = []
        noc = False  # create a more accurate system
        while not noc:
            to_check_open, to_check_close = short_valid(to_split, "(", ")")
            if to_split == to_split[to_check_open:to_check_close+1]:
                noc = True
            else:
                prop, chi, to_split = splitinto(
                    to_check_open, to_check_close, to_split)
                if prop != "":
                    if not tree_prop:
                        tree_prop.append(prop)
                    else:
                        chi = prop
                if chi != "":
                    tree_child.append(chi)
        while len(to_split) != 0:
            if to_split.count(";") == 1 and not tree_prop:
                tree_prop.append(to_split)
                break
            to_check_open, to_check_close = short_valid(to_split, ";", ";")
            prop, chi, to_split = splitinto(to_check_open, to_check_close, to_split)
            if prop != "":
                tree_prop.append(prop)
            if chi != "":
                tree_child.append(chi)
        return tree_prop, tree_child

    def short_valid(str_to_search, str_open_bracket, str_close_bracket):
        ope = 0
        clos = len(str_to_search)
        for i, char in enumerate(str_to_search):
            if char == str_open_bracket:
                ope = i
            elif char == str_close_bracket and i-1 != ope:
                clos = i
                break
        return ope, clos

    def splitinto(int_bracket_open_start, int_bracket_close, str_to_split):
        if int_bracket_open_start == 0:
            fir = str_to_split[1:int_bracket_close]
            sec = ""
            thir = str_to_split[int_bracket_close+1: len(str_to_split)]
            return fir, sec, thir
        fir = str_to_split[0:int_bracket_open_start]
        sec = str_to_split[int_bracket_open_start+1:int_bracket_close]
        thir = str_to_split[int_bracket_close+1:len(str_to_split)]
        return fir, sec, thir

    def formatco(ls_to_format, is_child=False):
        reschl = []
        respro = {}
        for i, _ in enumerate(ls_to_format):
            ls_to_format[i] = ls_to_format[i].strip("()")
            int_bracket_open_start, int_bracket_close = short_valid(ls_to_format[i], "[", "]")
            if escaped:
                int_bracket_close += 1
            str1, str2, next_str = splitinto(int_bracket_open_start,
                                             int_bracket_close, ls_to_format[i])
            str1 = str1.strip(";")
            str2 = str2.strip(";")
            while next_str != "" and next_str[0] == "[":
                int_bracket_open_start, int_bracket_close = short_valid(next_str, "[", "]")
                next_str2, null, next_str = splitinto(int_bracket_open_start,
                                                      int_bracket_close, next_str)
                del null
                str2 += next_str2
            str2 = convert(str2)
            reschl.append({str1: str2})
            if next_str != "":
                reschl += formatco([next_str], True)
        if is_child:
            return reschl
        for ele in reschl:
            respro.update(ele)
        return respro

    def createchild(ls_children_to_tree):
        ls_child_into_tree = []
        for i, _ in enumerate(ls_children_to_tree):
            ls_child_into_tree.append(SgfTree(ls_children_to_tree[i]))
        return ls_child_into_tree

    def escaped_prop_check(str_to_check_for_escape):
        escaped = False
        str_replaced = str_to_check_for_escape.replace("\t", " ").replace("\\", "")
        if str_to_check_for_escape != str_replaced:
            escaped = True
        return str_replaced, escaped

    def raw_format_check(input_string):
        input_string, escaped = escaped_prop_check(input_string)
        if not match_pat.search(input_string):
            raise ValueError("Invalid Format")
        non_child = "".join(non_child_pat.findall(input_string))
        if True in [True for char in non_child if char.islower() and char.isalpha()] \
            or non_child == input_string:
            raise ValueError("No lowercase letters")
        return input_string, escaped
    
    if input_string == "(;)":
        return SgfTree()
    input_string, escaped = raw_format_check(input_string)
    sgf_split_prop, sgf_split_child = sgf_split(input_string)
    sgf_split_prop = formatco(sgf_split_prop)
    sgf_split_child = formatco(sgf_split_child, True)
    return SgfTree(sgf_split_prop, createchild(sgf_split_child))

Community comments

Find this solution interesting? Ask the author a question to learn more.

Ginoalni's Reflection

Honestly, a bit of a mess, however, I enjoyed creating this.