-
Notifications
You must be signed in to change notification settings - Fork 0
/
solver.py
74 lines (53 loc) · 1.92 KB
/
solver.py
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
import z3
from data import users, N, M, G, pooled_score, pooled_score_group
from collections import defaultdict
from random import shuffle
# declare variables
groups = [z3.Int('group_of_' + str(i)) for i in range(N)]
total_pooled = z3.Int('total_pooled')
def build_solver():
o = z3.Optimize()
for g in range(G):
o.add(z3.Sum([z3.If(groups[i] == g, 1, 0) for i in range(N)]) == M)
o.add(total_pooled == z3.Sum([z3.If(groups[i] == groups[j],
pooled_score(users[i], users[j]),
0)
for i in range(N)
for j in range(i + 1, N)]))
o.add(total_pooled >= 0)
o.minimize(total_pooled)
return o
def pull_result(m):
by_group = defaultdict(list)
for i in range(N):
by_group[m[groups[i]].as_long()].append(i)
serialized = [{"name": users[u]["name"],
"team": users[u]["team"],
"last_group": users[u]["last_group"]}
for g in range(G)
for u in by_group[g]]
return serialized
def dump_edn(score, ordered_users):
import edn_format
open("demo/src/shuffle_lunch/data.cljc", "w") \
.write("""(ns shuffle-lunch.data)
(def total-pooled %d)
(def users %s)
(def cardinality %d)""" % (score, edn_format.dumps(ordered_users, keyword_keys=True), M))
mode = 0
if mode == 0:
# dump original
dump_edn(sum([pooled_score_group(g) for g in range(0, N, M)]), users)
elif mode == 1:
# simple shuffle
shuffle(users)
dump_edn(sum([pooled_score_group(g) for g in range(0, N, M)]), users)
elif mode == 2:
# dump shuffled
z3.set_param("smt.random_seed", 10)
#z3.set_option("smt.arith.solver", 1) # for sparse constraints
s = build_solver()
s.set("timeout", 3000)
s.check()
m = s.model()
dump_edn(m[total_pooled].as_long(), pull_result(m))