sudoku_solver.py 1.75 KB
Newer Older
1
2
3
4
import os
import urllib.request

import numpy as np
5
import torch
6
from sudoku import SudokuNN
7
from sudoku_data import _basic_sudoku_graph
8
9
10
11
12
13
14
15
16


def solve_sudoku(puzzle):
    """
    Solve sudoku puzzle using RRN.
    :param puzzle: an array-like data with shape [9, 9], blank positions are filled with 0
    :return: a [9, 9] shaped numpy array
    """
    puzzle = np.array(puzzle, dtype=np.long).reshape([-1])
17
    model_path = "ckpt"
18
19
20
    if not os.path.exists(model_path):
        os.mkdir(model_path)

21
    model_filename = os.path.join(model_path, "rrn-sudoku.pkl")
22
    if not os.path.exists(model_filename):
23
24
        print("Downloading model...")
        url = "https://data.dgl.ai/models/rrn-sudoku.pkl"
25
26
        urllib.request.urlretrieve(url, model_filename)

27
28
    model = SudokuNN(num_steps=64, edge_drop=0.0)
    model.load_state_dict(torch.load(model_filename, map_location="cpu"))
29
    model.eval()
30
31
32
33
34
35

    g = _basic_sudoku_graph()
    sudoku_indices = np.arange(0, 81)
    rows = sudoku_indices // 9
    cols = sudoku_indices % 9

36
37
38
39
    g.ndata["row"] = torch.tensor(rows, dtype=torch.long)
    g.ndata["col"] = torch.tensor(cols, dtype=torch.long)
    g.ndata["q"] = torch.tensor(puzzle, dtype=torch.long)
    g.ndata["a"] = torch.tensor(puzzle, dtype=torch.long)
40
41
42
43
44
45

    pred, _ = model(g, False)
    pred = pred.cpu().data.numpy().reshape([9, 9])
    return pred


46
if __name__ == "__main__":
47
48
49
50
51
52
53
54
55
    q = [
        [9, 7, 0, 4, 0, 2, 0, 5, 3],
        [0, 4, 6, 0, 9, 0, 0, 0, 0],
        [0, 0, 8, 6, 0, 1, 4, 0, 7],
        [0, 0, 0, 0, 0, 3, 5, 0, 0],
        [7, 6, 0, 0, 0, 0, 0, 8, 2],
        [0, 0, 2, 8, 0, 0, 0, 0, 0],
        [6, 0, 5, 1, 0, 7, 2, 0, 0],
        [0, 0, 0, 0, 6, 0, 7, 4, 0],
56
        [4, 3, 0, 2, 0, 9, 0, 6, 1],
57
58
59
60
    ]

    answer = solve_sudoku(q)
    print(answer)