1# Copyright 2010 Hakan Kjellerstrand hakank@gmail.com
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14"""
15
16  Set partition problem in Google CP Solver.
17
18  Problem formulation from
19  http://www.koalog.com/resources/samples/PartitionProblem.java.html
20  '''
21   This is a partition problem.
22   Given the set S = {1, 2, ..., n},
23   it consists in finding two sets A and B such that:
24
25     A U B = S,
26     |A| = |B|,
27     sum(A) = sum(B),
28     sum_squares(A) = sum_squares(B)
29
30  '''
31
32  This model uses a binary matrix to represent the sets.
33
34
35  Also, compare with other models which uses var sets:
36  * MiniZinc: http://www.hakank.org/minizinc/set_partition.mzn
37  * Gecode/R: http://www.hakank.org/gecode_r/set_partition.rb
38  * Comet: http://hakank.org/comet/set_partition.co
39  * Gecode: http://hakank.org/gecode/set_partition.cpp
40  * ECLiPSe: http://hakank.org/eclipse/set_partition.ecl
41  * SICStus: http://hakank.org/sicstus/set_partition.pl
42
43  This model was created by Hakan Kjellerstrand (hakank@gmail.com)
44  Also see my other Google CP Solver models:
45  http://www.hakank.org/google_or_tools/
46"""
47import sys
48
49from ortools.constraint_solver import pywrapcp
50
51
52#
53# Partition the sets (binary matrix representation).
54#
55def partition_sets(x, num_sets, n):
56  solver = list(x.values())[0].solver()
57
58  for i in range(num_sets):
59    for j in range(num_sets):
60      if i != j:
61        b = solver.Sum([x[i, k] * x[j, k] for k in range(n)])
62        solver.Add(b == 0)
63
64  # ensure that all integers is in
65  # (exactly) one partition
66  b = [x[i, j] for i in range(num_sets) for j in range(n)]
67  solver.Add(solver.Sum(b) == n)
68
69
70def main(n=16, num_sets=2):
71
72  # Create the solver.
73  solver = pywrapcp.Solver("Set partition")
74
75  #
76  # data
77  #
78  print("n:", n)
79  print("num_sets:", num_sets)
80  print()
81
82  # Check sizes
83  assert n % num_sets == 0, "Equal sets is not possible."
84
85  #
86  # variables
87  #
88
89  # the set
90  a = {}
91  for i in range(num_sets):
92    for j in range(n):
93      a[i, j] = solver.IntVar(0, 1, "a[%i,%i]" % (i, j))
94
95  a_flat = [a[i, j] for i in range(num_sets) for j in range(n)]
96
97  #
98  # constraints
99  #
100
101  # partition set
102  partition_sets(a, num_sets, n)
103
104  for i in range(num_sets):
105    for j in range(i, num_sets):
106
107      # same cardinality
108      solver.Add(
109          solver.Sum([a[i, k] for k in range(n)]) == solver.Sum(
110              [a[j, k] for k in range(n)]))
111
112      # same sum
113      solver.Add(
114          solver.Sum([k * a[i, k] for k in range(n)]) == solver.Sum(
115              [k * a[j, k] for k in range(n)]))
116
117      # same sum squared
118      solver.Add(
119          solver.Sum([(k * a[i, k]) * (k * a[i, k]) for k in range(n)]) ==
120          solver.Sum([(k * a[j, k]) * (k * a[j, k]) for k in range(n)]))
121
122  # symmetry breaking for num_sets == 2
123  if num_sets == 2:
124    solver.Add(a[0, 0] == 1)
125
126  #
127  # search and result
128  #
129  db = solver.Phase(a_flat, solver.INT_VAR_DEFAULT, solver.INT_VALUE_DEFAULT)
130
131  solver.NewSearch(db)
132
133  num_solutions = 0
134  while solver.NextSolution():
135    a_val = {}
136    for i in range(num_sets):
137      for j in range(n):
138        a_val[i, j] = a[i, j].Value()
139
140    sq = sum([(j + 1) * a_val[0, j] for j in range(n)])
141    print("sums:", sq)
142    sq2 = sum([((j + 1) * a_val[0, j])**2 for j in range(n)])
143    print("sums squared:", sq2)
144
145    for i in range(num_sets):
146      if sum([a_val[i, j] for j in range(n)]):
147        print(i + 1, ":", end=" ")
148        for j in range(n):
149          if a_val[i, j] == 1:
150            print(j + 1, end=" ")
151        print()
152
153    print()
154    num_solutions += 1
155
156  solver.EndSearch()
157
158  print()
159  print("num_solutions:", num_solutions)
160  print("failures:", solver.Failures())
161  print("branches:", solver.Branches())
162  print("WallTime:", solver.WallTime())
163
164
165n = 16
166num_sets = 2
167if __name__ == "__main__":
168  if len(sys.argv) > 1:
169    n = int(sys.argv[1])
170  if len(sys.argv) > 2:
171    num_sets = int(sys.argv[2])
172
173  main(n, num_sets)
174