summaryrefslogtreecommitdiff
path: root/convert_to_sat.py
blob: d538b08a4cdbe8a714f20394a4f20551183e4912 (plain)
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
from z3 import *
import sys


variables = {}
def reachable(graph, node_reachable):
    # check reachability to node_reachable
    clauses = []
    # at least one pebble can be gotted to node_reachble (from config or otherwise)
    clauses.append(1 <= Sum(list(variables[node_reachable]["in"].values())))
    return clauses

def build_model(graph, add_property, node_reachable, config=None, config_count=0):
    clauses = []
    for node in graph["v"]:
        variables[node] = {"out":{}, "in":{}}
    # creat symbolic variables for each edge in/out
    for node in graph["v"]:
        for edge in graph["e"][node]:
            variables[node]["out"][edge] = Int(node+"_out_"+edge)
            variables[edge]["in"][node] = Int(edge+"_in_"+node)
        # add initial pebbles
        variables[node]["in"]["config"] = Int(node+"_in_config")


    if config is not None:
        for node in graph["v"]:
            clauses.append(variables[node]["in"]["config"] == config[node])
    else:
        sum_terms = []
        for node in graph["v"]:
            clauses.append(variables[node]["in"]["config"] >= 0)
            sum_terms.append(variables[node]["in"]["config"])
        clauses.append(Sum(sum_terms) == config_count)

    # make edges linked
    for node in graph["v"]:
        for edge in graph["e"][node]:
            clauses.append(variables[node]["out"][edge] == variables[edge]["in"][node])

    # encode possible moves
    # make sure we don't move too many total from pebble
    for node in graph["v"]:
        sum_out = Sum(list(variables[node]["out"].values()))
        sum_in = Sum(list(variables[node]["in"].values()))
        # The number of pebbles out from a node is no more than half the sum
        # of all pebbles that are moved into a node
        clauses.append( Implies(sum_in % 2 == 0,  sum_out <= (sum_in/2 )) )
        clauses.append( Implies(sum_in % 2 == 1,  sum_out <= ((sum_in-1)/2 )) )
    # make sure each move is a valid amount
    for node in graph["v"]:
        for in_var in variables[node]["in"].values():
            clauses.append(in_var >= 0)
        for out_var in variables[node]["out"].values():
            sum_in = Sum(list(variables[node]["in"].values()))
            clauses.append( 
                    Implies(And(sum_in % 2 == 0, sum_in > 2),
                            And(0 <= out_var, out_var <= (sum_in/2 ))) )
            clauses.append( 
                    Implies(And(sum_in % 2 == 1, sum_in > 2),
                            And(0 <= out_var, out_var <= ((sum_in-1)/2 ))) )

    # encode cycle lemma
    # TODO get all cycles, and remove them?
    for node in graph["v"]:
        # if we along one edge, do not move back along it
        for edge in graph["e"][node]:
            in1 = variables[node]["in"][edge]
            in2 = variables[edge]["in"][node]
            clauses.append(Implies(in1 > 0, in2 == 0))
    clauses += add_property(graph, node_reachable)

    return And(clauses)

def is_sat(f, output=True):
    s = Solver()
    s.add(f)
    if output:
        print(f)
    if s.check() == sat:
        if output:
            print("SAT")
        model = s.model()
        # print(model)
        moves = []
        for key in model:
            if "_in_" in key.name() and 0<model[key].as_long():
                parts = key.name().split("_in_")
                if parts[1] != "config":
                    moves.append(parts[1] + " sends " + str(model[key])+" pebbles to "  +parts[0])
        moves.sort()
        if output:
            print("\n".join(moves))
        return moves
    if output:
        print("UNSAT")
    return None

def test_simple_path():
    config = {
        "a": 4,
        "b": 0,
        "c": 0,
    }
    graph = {
        "v": ["a", "b", "c"],
        "e": {
            "a": ["b"],
            "b": ["a", "c"],
            "c": ["b"],
        },
    }
    node_reachable = "c"
    run_reachable_test_case(graph, config, node_reachable, True)

    config = {
        "a": 3,
        "b": 0,
        "c": 0,
    }
    run_reachable_test_case(graph, config, node_reachable, False)

    config = {
        "a": 5,
        "b": 0,
        "c": 0,
    }
    run_reachable_test_case(graph, config, node_reachable, True)

    config = {
        "a": 2,
        "b": 1,
        "c": 0,
    }
    run_reachable_test_case(graph, config, node_reachable, True)

def test_cycle():
    config = {
        "a": 4,
        "b": 0,
        "c": 0,
        "d": 0,
    }
    graph = {
        "v": ["a", "b", "c", "d"],
        "e": {
            "a": ["b", "d"],
            "b": ["a", "c"],
            "c": ["b", "d"],
            "d": ["a", "c"],
        },
    }
    node_reachable = "c"
    run_reachable_test_case(graph, config, node_reachable, True)

def test_merge():
    #   a
    #  / \
    # b   c
    #  \ /
    #   d
    #   |
    #   e
    graph = {
        "v": ["a", "b", "c", "d", "e"],
        "e": {
            "a": ["b", "c"],
            "b": ["a", "d"],
            "c": ["a", "d"],
            "d": ["b", "c", "e"],
            "e": ["d"],
        },
    }
    node_reachable = "e"
    config = {
        "a": 4,
        "b": 1,
        "c": 1,
        "d": 0,
        "e": 0,
    }
    run_reachable_test_case(graph, config, node_reachable, True)

    config = {
        "a": 4,
        "b": 1,
        "c": 0,
        "d": 0,
        "e": 0,
    }
    run_reachable_test_case(graph, config, node_reachable, False)

def test_lemke():
    #  /-x-\
    # / | | \
    # a-b c d
    # \ \ | /
    #  e--f
    #   \/
    #    v
    graph = {
        "v": ["a", "b", "c", "d", "e", "f", "v", "x"],
        "e": {
            "a": ["b", "e", "x"],
            "b": ["a", "f", "x"],
            "c": ["x", "f"],
            "d": ["x", "f"],
            "e": ["a", "f", "v"],
            "f": ["b", "c", "d", "e", "v"],
            "v": ["e", "f"],
            "x": ["a", "b", "c", "d"],
        },
    }
    config = {
        "a": 0,
        "b": 0,
        "c": 0,
        "d": 0,
        "e": 0,
        "f": 0,
        "v": 0,
        "x": 8,
    }
    run_reachable_test_case(graph, config, "v", True)

    config = {
        "a": 1,
        "b": 1,
        "c": 1,
        "d": 1,
        "e": 0,
        "f": 0,
        "v": 0,
        "x": 4,
    }
    run_reachable_test_case(graph, config, "v", True)
    run_pebbling_number_test_case(graph, 7)

def run_reachable_test_case(graph, config, node_reachable, expected_is_sat):
    variables = {}
    z3_model = build_model(graph, reachable, node_reachable, config=config)
    out = is_sat(z3_model, output=False)
    if (expected_is_sat and not out) or (not expected_is_sat and out):
        print(z3_model)
        print(out)
        print("failed!")

def run_pebbling_number_test_case(graph, count):
    variables = {}
    for node_reachable in graph["v"]:
        # TODO model is wrong, we need to say there is not a configure in
        # which this isn't possible. This is solvability?
        z3_model = build_model(graph, reachable, node_reachable, config_count=count)
        out = is_sat(z3_model, output=False)
        if not out:
            print("failed peb. number: ", count, node_reachable)
        print(out)

def main():
    test_simple_path()
    test_cycle()
    test_merge()
    test_lemke()

if __name__ == '__main__':
    main()