diff --git a/examples/python/3_jugs_mip.py b/examples/python/3_jugs_mip.py index 8560811bb7..750678f821 100644 --- a/examples/python/3_jugs_mip.py +++ b/examples/python/3_jugs_mip.py @@ -25,12 +25,14 @@ http://www.hakank.org/google_or_tools/3_jugs_regular This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ import sys from ortools.linear_solver import pywraplp -def main(sol = 'GLPK'): + +def main(sol='GLPK'): # Create the solver. @@ -41,20 +43,19 @@ def main(sol = 'GLPK'): solver = pywraplp.Solver('CoinsGridGLPK', pywraplp.Solver.GLPK_MIXED_INTEGER_PROGRAMMING) else: - # Using CLP - solver = pywraplp.Solver('CoinsGridCLP', - pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING) - + # Using CLP + solver = pywraplp.Solver('CoinsGridCLP', + pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING) # # data # n = 15 - start = 0 # start node + start = 0 # start node end = 14 # end node M = 999 # a large number - nodes = ['8,0,0', # start + nodes = ['8,0,0', # start '5,0,3', '5,3,0', '2,3,3', @@ -88,7 +89,6 @@ def main(sol = 'GLPK'): [M, 1, M, M, M, M, M, M, M, M, M, M, M, M, 1], [M, M, M, M, M, M, M, M, M, M, M, M, M, M, M]] - # # variables # @@ -99,21 +99,20 @@ def main(sol = 'GLPK'): x = {} for i in range(n): for j in range(n): - x[i,j] = solver.IntVar(0, 1, 'x[%i,%i]' % (i, j)) + x[i, j] = solver.IntVar(0, 1, 'x[%i,%i]' % (i, j)) out_flow = [solver.IntVar(0, 1, 'out_flow[%i]' % i) for i in range(n)] in_flow = [solver.IntVar(0, 1, 'in_flow[%i]' % i) for i in range(n)] # length of path, to be minimized - z = solver.Sum([d[i][j]*x[i,j] - for i in range(n) - for j in range(n) if d[i][j] < M]) + z = solver.Sum([d[i][j] * x[i, j] + for i in range(n) + for j in range(n) if d[i][j] < M]) # # constraints # - for i in range(n): if i == start: solver.Add(rhs[i] == 1) @@ -122,28 +121,25 @@ def main(sol = 'GLPK'): else: solver.Add(rhs[i] == 0) - # outflow constraint for i in range(n): - solver.Add(out_flow[i] == solver.Sum([x[i,j] + solver.Add(out_flow[i] == solver.Sum([x[i, j] for j in range(n) if d[i][j] < M])) # inflow constraint for j in range(n): - solver.Add(in_flow[j] == solver.Sum([x[i,j] + solver.Add(in_flow[j] == solver.Sum([x[i, j] for i in range(n) if d[i][j] < M])) # inflow = outflow for i in range(n): - solver.Add(out_flow[i]-in_flow[i] == rhs[i]) - + solver.Add(out_flow[i] - in_flow[i] == rhs[i]) # objective objective = solver.Minimize(z) - # # solution and search # @@ -156,7 +152,7 @@ def main(sol = 'GLPK'): while t != end: print nodes[t], '->', for j in range(n): - if x[t,j].SolutionValue() == 1: + if x[t, j].SolutionValue() == 1: print nodes[j] t = j break diff --git a/examples/python/3_jugs_regular.py b/examples/python/3_jugs_regular.py index a296b42854..ed49e87e07 100644 --- a/examples/python/3_jugs_regular.py +++ b/examples/python/3_jugs_regular.py @@ -43,7 +43,8 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ @@ -70,197 +71,196 @@ from collections import defaultdict # d : transition matrix # q0: initial state # F : accepting states + + def regular(x, Q, S, d, q0, F): - solver = x[0].solver() + solver = x[0].solver() - assert Q > 0, 'regular: "Q" must be greater than zero' - assert S > 0, 'regular: "S" must be greater than zero' + assert Q > 0, 'regular: "Q" must be greater than zero' + assert S > 0, 'regular: "S" must be greater than zero' - # d2 is the same as d, except we add one extra transition for - # each possible input; each extra transition is from state zero - # to state zero. This allows us to continue even if we hit a - # non-accepted input. + # d2 is the same as d, except we add one extra transition for + # each possible input; each extra transition is from state zero + # to state zero. This allows us to continue even if we hit a + # non-accepted input. - # Comet: int d2[0..Q, 1..S] - d2 = [] - for i in range(Q+1): - row = [] - for j in range(S): - if i == 0: - row.append(0) - else: - row.append(d[i-1][j]) - d2.append(row) + # Comet: int d2[0..Q, 1..S] + d2 = [] + for i in range(Q + 1): + row = [] + for j in range(S): + if i == 0: + row.append(0) + else: + row.append(d[i - 1][j]) + d2.append(row) - d2_flatten = [d2[i][j] for i in range(Q+1) for j in range(S)] + d2_flatten = [d2[i][j] for i in range(Q + 1) for j in range(S)] - # If x has index set m..n, then a[m-1] holds the initial state - # (q0), and a[i+1] holds the state we're in after processing - # x[i]. If a[n] is in F, then we succeed (ie. accept the - # string). - x_range = range(0,len(x)) - m = 0 - n = len(x) + # If x has index set m..n, then a[m-1] holds the initial state + # (q0), and a[i+1] holds the state we're in after processing + # x[i]. If a[n] is in F, then we succeed (ie. accept the + # string). + x_range = range(0, len(x)) + m = 0 + n = len(x) - a = [solver.IntVar(0, Q+1, 'a[%i]' % i) for i in range(m, n+1)] - - # Check that the final state is in F - solver.Add(solver.MemberCt(a[-1], F)) - # First state is q0 - solver.Add(a[m] == q0) - for i in x_range: - solver.Add(x[i] >= 1) - solver.Add(x[i] <= S) - - # Determine a[i+1]: a[i+1] == d2[a[i], x[i]] - solver.Add(a[i+1] == solver.Element(d2_flatten, ((a[i])*S)+(x[i]-1))) + a = [solver.IntVar(0, Q + 1, 'a[%i]' % i) for i in range(m, n + 1)] + # Check that the final state is in F + solver.Add(solver.MemberCt(a[-1], F)) + # First state is q0 + solver.Add(a[m] == q0) + for i in x_range: + solver.Add(x[i] >= 1) + solver.Add(x[i] <= S) + # Determine a[i+1]: a[i+1] == d2[a[i], x[i]] + solver.Add( + a[i + 1] == solver.Element(d2_flatten, ((a[i]) * S) + (x[i] - 1))) def main(n): - # Create the solver. - solver = pywrapcp.Solver('3 jugs problem using regular constraint') + # Create the solver. + solver = pywrapcp.Solver('3 jugs problem using regular constraint') - # - # data - # + # + # data + # - # the DFA (for regular) - n_states = 14 - input_max = 15 - initial_state = 1 # 0 is for the failing state - accepting_states = [15] + # the DFA (for regular) + n_states = 14 + input_max = 15 + initial_state = 1 # 0 is for the failing state + accepting_states = [15] - ## - ## Manually crafted DFA - ## (from the adjacency matrix used in the other models) - ## - # transition_fn = [ - # # 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 - # [0, 2, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0], # 1 - # [0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # 2 - # [0, 0, 0, 4, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0], # 3 - # [0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # 4 - # [0, 0, 0, 0, 0, 6, 0, 0, 9, 0, 0, 0, 0, 0, 0], # 5 - # [0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0], # 6 - # [0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0, 0], # 7 - # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15], # 8 - # [0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0], # 9 - # [0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 11, 0, 0, 0, 0], # 10 - # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0], # 11 - # [0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 13, 0, 0], # 12 - # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 0], # 13 - # [0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15], # 14 - # # 15 - # ] + ## + # Manually crafted DFA + # (from the adjacency matrix used in the other models) + ## + # transition_fn = [ + # # 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 + # [0, 2, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0], # 1 + # [0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # 2 + # [0, 0, 0, 4, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0], # 3 + # [0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # 4 + # [0, 0, 0, 0, 0, 6, 0, 0, 9, 0, 0, 0, 0, 0, 0], # 5 + # [0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0], # 6 + # [0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0, 0], # 7 + # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15], # 8 + # [0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0], # 9 + # [0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 11, 0, 0, 0, 0], # 10 + # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0], # 11 + # [0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 13, 0, 0], # 12 + # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 0], # 13 + # [0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15], # 14 + # # 15 + # ] - # - # However, the DFA is easy to create from adjacency lists. - # - states = [ - [2,9], # state 1 - [3], # state 2 - [4, 9], # state 3 - [5], # state 4 - [6,9], # state 5 - [7], # state 6 - [8,9], # state 7 - [15], # state 8 - [10], # state 9 - [11], # state 10 - [12], # state 11 - [13], # state 12 - [14], # state 13 - [15] # state 14 - ] + # + # However, the DFA is easy to create from adjacency lists. + # + states = [ + [2, 9], # state 1 + [3], # state 2 + [4, 9], # state 3 + [5], # state 4 + [6, 9], # state 5 + [7], # state 6 + [8, 9], # state 7 + [15], # state 8 + [10], # state 9 + [11], # state 10 + [12], # state 11 + [13], # state 12 + [14], # state 13 + [15] # state 14 + ] - transition_fn = [] - for i in range(n_states): - row = [] - for j in range(1,input_max+1): - if j in states[i]: - row.append(j) - else: - row.append(0) - transition_fn.append(row) + transition_fn = [] + for i in range(n_states): + row = [] + for j in range(1, input_max + 1): + if j in states[i]: + row.append(j) + else: + row.append(0) + transition_fn.append(row) - # - # The name of the nodes, for printing - # the solution. - # - nodes = [ - '8,0,0', # 1 start - '5,0,3', # 2 - '5,3,0', # 3 - '2,3,3', # 4 - '2,5,1', # 5 - '7,0,1', # 6 - '7,1,0', # 7 - '4,1,3', # 8 - '3,5,0', # 9 - '3,2,3', # 10 - '6,2,0', # 11 - '6,0,2', # 12 - '1,5,2', # 13 - '1,4,3', # 14 - '4,4,0' # 15 goal - ] + # + # The name of the nodes, for printing + # the solution. + # + nodes = [ + '8,0,0', # 1 start + '5,0,3', # 2 + '5,3,0', # 3 + '2,3,3', # 4 + '2,5,1', # 5 + '7,0,1', # 6 + '7,1,0', # 7 + '4,1,3', # 8 + '3,5,0', # 9 + '3,2,3', # 10 + '6,2,0', # 11 + '6,0,2', # 12 + '1,5,2', # 13 + '1,4,3', # 14 + '4,4,0' # 15 goal + ] + # + # declare variables + # + x = [solver.IntVar(1, input_max, 'x[%i]' % i) for i in range(n)] - # - # declare variables - # - x = [solver.IntVar(1, input_max, 'x[%i]'% i) for i in range(n)] + # + # constraints + # + regular(x, n_states, input_max, transition_fn, + initial_state, accepting_states) - # - # constraints - # - regular(x, n_states, input_max, transition_fn, - initial_state, accepting_states) + # + # solution and search + # + db = solver.Phase(x, + solver.INT_VAR_DEFAULT, + solver.INT_VALUE_DEFAULT) + solver.NewSearch(db) - # - # solution and search - # - db = solver.Phase(x, - solver.INT_VAR_DEFAULT, - solver.INT_VALUE_DEFAULT) + num_solutions = 0 + x_val = [] + while solver.NextSolution(): + num_solutions += 1 + x_val = [1] + [x[i].Value() for i in range(n)] + print 'x:', x_val + for i in range(1, n + 1): + print '%s -> %s' % (nodes[x_val[i - 1] - 1], nodes[x_val[i] - 1]) - solver.NewSearch(db) + solver.EndSearch() - num_solutions = 0 - x_val = [] - while solver.NextSolution(): - num_solutions += 1 - x_val = [1] + [x[i].Value() for i in range(n)] - print 'x:', x_val - for i in range(1, n+1): - print '%s -> %s' % (nodes[x_val[i-1]-1], nodes[x_val[i]-1]) + if num_solutions > 0: + print + print 'num_solutions:', num_solutions + print 'failures:', solver.Failures() + print 'branches:', solver.Branches() + print 'WallTime:', solver.WallTime(), 'ms' - solver.EndSearch() - - if num_solutions > 0: - print - print 'num_solutions:', num_solutions - print 'failures:', solver.Failures() - print 'branches:', solver.Branches() - print 'WallTime:', solver.WallTime(), 'ms' - - # return the solution (or an empty array) - return x_val + # return the solution (or an empty array) + return x_val # Search for a minimum solution by increasing # the length of the state array. if __name__ == '__main__': - for n in range(1, 15): - result = main(n) - result_len = len(result) - if result_len: - print '\nFound a solution of length %i:' % result_len, - print result - print - break + for n in range(1, 15): + result = main(n) + result_len = len(result) + if result_len: + print '\nFound a solution of length %i:' % result_len, + print result + print + break diff --git a/examples/python/a_round_of_golf.py b/examples/python/a_round_of_golf.py index a7f55f54f2..8187e6b9f3 100644 --- a/examples/python/a_round_of_golf.py +++ b/examples/python/a_round_of_golf.py @@ -60,107 +60,107 @@ * SICStus : http://hakank.org/sicstus/a_round_of_golf.pl This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ from ortools.constraint_solver import pywrapcp + def main(): - # Create the solver. - solver = pywrapcp.Solver('All interval') + # Create the solver. + solver = pywrapcp.Solver("All interval") - # - # data - # - n = 4 - [Jack, Bill, Paul, Frank] = [i for i in range(n)] + # + # data + # + n = 4 + [Jack, Bill, Paul, Frank] = [i for i in range(n)] - # - # declare variables - # - last_name = [solver.IntVar(0, n-1, 'last_name[%i]' % i) for i in range(n)] - [Green, Clubb, Sands, Carter] = last_name + # + # declare variables + # + last_name = [solver.IntVar(0, n - 1, "last_name[%i]" % i) for i in range(n)] + [Green, Clubb, Sands, Carter] = last_name - job = [solver.IntVar(0, n-1, 'job[%i]' % i) for i in range(n)] - [cook, maintenance_man, clerk, caddy] = job + job = [solver.IntVar(0, n - 1, "job[%i]" % i) for i in range(n)] + [cook, maintenance_man, clerk, caddy] = job - score = [solver.IntVar(70, 85, 'score[%i]' % i) for i in range(n)] + score = [solver.IntVar(70, 85, "score[%i]" % i) for i in range(n)] - # - # constraints - # - solver.Add(solver.AllDifferent(last_name)) - solver.Add(solver.AllDifferent(job)) - solver.Add(solver.AllDifferent(score)) + # + # constraints + # + solver.Add(solver.AllDifferent(last_name)) + solver.Add(solver.AllDifferent(job)) + solver.Add(solver.AllDifferent(score)) - # 1. Bill, who is not the maintenance man, plays golf often and had - # the lowest score of the foursome. - solver.Add(Bill != maintenance_man) - solver.Add(score[Bill] < score[Jack]) - solver.Add(score[Bill] < score[Paul]) - solver.Add(score[Bill] < score[Frank]) + # 1. Bill, who is not the maintenance man, plays golf often and had + # the lowest score of the foursome. + solver.Add(Bill != maintenance_man) + solver.Add(score[Bill] < score[Jack]) + solver.Add(score[Bill] < score[Paul]) + solver.Add(score[Bill] < score[Frank]) - # 2. Mr. Clubb, who isn't Paul, hit several balls into the woods and - # scored ten strokes more than the pro-shop clerk. - solver.Add(Clubb != Paul) - solver.Add(solver.Element(score, Clubb) == solver.Element(score, clerk) + 10) + # 2. Mr. Clubb, who isn't Paul, hit several balls into the woods and + # scored ten strokes more than the pro-shop clerk. + solver.Add(Clubb != Paul) + solver.Add(solver.Element(score, Clubb) == solver.Element(score, clerk) + 10) - # 3. In some order, Frank and the caddy scored four and seven more - # strokes than Mr. Sands. - solver.Add(Frank != caddy) - solver.Add(Frank != Sands) - solver.Add(caddy != Sands) + # 3. In some order, Frank and the caddy scored four and seven more + # strokes than Mr. Sands. + solver.Add(Frank != caddy) + solver.Add(Frank != Sands) + solver.Add(caddy != Sands) - b3_a_1 = solver.IsEqualVar(solver.Element(score, Sands) + 4, \ - score[Frank]) - b3_a_2 = solver.IsEqualVar(solver.Element(score, caddy), \ - solver.Element(score, Sands) + 7) + b3_a_1 = solver.IsEqualVar(solver.Element(score, Sands) + 4, + score[Frank]) + b3_a_2 = solver.IsEqualVar(solver.Element(score, caddy), + solver.Element(score, Sands) + 7) - b3_b_1 = solver.IsEqualVar(solver.Element(score, Sands) + 7, \ - score[Frank]) - b3_b_2 = solver.IsEqualVar(solver.Element(score, caddy), \ - solver.Element(score, Sands) + 4) + b3_b_1 = solver.IsEqualVar(solver.Element(score, Sands) + 7, + score[Frank]) + b3_b_2 = solver.IsEqualVar(solver.Element(score, caddy), + solver.Element(score, Sands) + 4) - solver.Add( (b3_a_1*b3_a_2) + (b3_b_1*b3_b_2) == 1) + solver.Add((b3_a_1 * b3_a_2) + (b3_b_1 * b3_b_2) == 1) + # 4. Mr. Carter thought his score of 78 was one of his better games, + # even though Frank's score was lower. + solver.Add(Frank != Carter) + solver.Add(solver.Element(score, Carter) == 78) + solver.Add(score[Frank] < solver.Element(score, Carter)) - # 4. Mr. Carter thought his score of 78 was one of his better games, - # even though Frank's score was lower. - solver.Add(Frank != Carter) - solver.Add(solver.Element(score,Carter) == 78) - solver.Add(score[Frank] < solver.Element(score,Carter)) + # 5. None of the four scored exactly 81 strokes. + [solver.Add(score[i] != 81) for i in range(n)] - # 5. None of the four scored exactly 81 strokes. - [solver.Add(score[i] != 81) for i in range(n)] + # + # solution and search + # + solution = solver.Assignment() + solution.Add(last_name) + solution.Add(job) + solution.Add(score) + db = solver.Phase(last_name + job + score, + solver.CHOOSE_FIRST_UNBOUND, + solver.INT_VALUE_DEFAULT) - # - # solution and search - # - solution = solver.Assignment() - solution.Add(last_name) - solution.Add(job) - solution.Add(score) + solver.NewSearch(db) + num_solutions = 0 + while solver.NextSolution(): + print "last_name:", [last_name[i].Value() for i in range(n)] + print "job :", [job[i].Value() for i in range(n)] + print "score :", [score[i].Value() for i in range(n)] + num_solutions += 1 + print - db = solver.Phase(last_name + job + score, - solver.CHOOSE_FIRST_UNBOUND, - solver.INT_VALUE_DEFAULT) + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() - solver.NewSearch(db) - num_solutions = 0 - while solver.NextSolution(): - print "last_name:", [last_name[i].Value() for i in range(n)] - print "job :", [job[i].Value() for i in range(n)] - print "score :", [score[i].Value() for i in range(n)] - num_solutions += 1 - print - - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() - -if __name__ == '__main__': - main() +if __name__ == "__main__": + main() diff --git a/examples/python/all_interval.py b/examples/python/all_interval.py index 232be66ab6..c4b30335a7 100644 --- a/examples/python/all_interval.py +++ b/examples/python/all_interval.py @@ -46,68 +46,71 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ -import string, sys +import string +import sys from ortools.constraint_solver import pywrapcp + def main(n=12): - # Create the solver. - solver = pywrapcp.Solver('All interval') + # Create the solver. + solver = pywrapcp.Solver("All interval") - # - # data - # - print "n:", n + # + # data + # + print "n:", n - # - # declare variables - # - x = [solver.IntVar(1, n, 'x[%i]' % i) for i in range(n)] - diffs = [solver.IntVar(1, n-1, 'diffs[%i]' % i) for i in range(n-1)] + # + # declare variables + # + x = [solver.IntVar(1, n, "x[%i]" % i) for i in range(n)] + diffs = [solver.IntVar(1, n - 1, "diffs[%i]" % i) for i in range(n - 1)] - # - # constraints - # - solver.Add(solver.AllDifferent(x)) - solver.Add(solver.AllDifferent(diffs)) + # + # constraints + # + solver.Add(solver.AllDifferent(x)) + solver.Add(solver.AllDifferent(diffs)) - for k in range(n-1): - solver.Add(diffs[k] == abs(x[k+1]-x[k])) + for k in range(n - 1): + solver.Add(diffs[k] == abs(x[k + 1] - x[k])) - # symmetry breaking - solver.Add(x[0] < x[n-1]) - solver.Add(diffs[0] < diffs[1]) + # symmetry breaking + solver.Add(x[0] < x[n - 1]) + solver.Add(diffs[0] < diffs[1]) - # - # solution and search - # - solution = solver.Assignment() - solution.Add(x) - solution.Add(diffs) + # + # solution and search + # + solution = solver.Assignment() + solution.Add(x) + solution.Add(diffs) - db = solver.Phase(x, - solver.CHOOSE_FIRST_UNBOUND, - solver.ASSIGN_MIN_VALUE) + db = solver.Phase(x, + solver.CHOOSE_FIRST_UNBOUND, + solver.ASSIGN_MIN_VALUE) - solver.NewSearch(db) - num_solutions = 0 - while solver.NextSolution(): - print "x:", [x[i].Value() for i in range(n)] - print "diffs:", [diffs[i].Value() for i in range(n-1)] - num_solutions += 1 - print + solver.NewSearch(db) + num_solutions = 0 + while solver.NextSolution(): + print "x:", [x[i].Value() for i in range(n)] + print "diffs:", [diffs[i].Value() for i in range(n - 1)] + num_solutions += 1 + print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() -n=12 -if __name__ == '__main__': - if len(sys.argv) > 1: - n = string.atoi(sys.argv[1]) - main(n) +n = 12 +if __name__ == "__main__": + if len(sys.argv) > 1: + n = string.atoi(sys.argv[1]) + main(n) diff --git a/examples/python/alldifferent_except_0.py b/examples/python/alldifferent_except_0.py index 27ce71d451..6fbef13543 100644 --- a/examples/python/alldifferent_except_0.py +++ b/examples/python/alldifferent_except_0.py @@ -44,13 +44,12 @@ * Zinc: http://hakank.org/minizinc/alldifferent_except_0.zinc This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ - - from ortools.constraint_solver import pywrapcp # @@ -58,65 +57,67 @@ from ortools.constraint_solver import pywrapcp # Thanks to Laurent Perron (Google) for # suggestions of improvements. # + + def alldifferent_except_0(solver, a): - n = len(a) - for i in range(n): - for j in range(i): - solver.Add((a[i] != 0) * (a[j] != 0) <= (a[i] != a[j])) + n = len(a) + for i in range(n): + for j in range(i): + solver.Add((a[i] != 0) * (a[j] != 0) <= (a[i] != a[j])) # more compact version: + + def alldifferent_except_0_b(solver, a): - n = len(a) - [solver.Add((a[i] != 0) * (a[j] != 0) <= (a[i] != a[j])) - for i in range(n) for j in range(i)] - - + n = len(a) + [solver.Add((a[i] != 0) * (a[j] != 0) <= (a[i] != a[j])) + for i in range(n) for j in range(i)] def main(unused_argv): - # Create the solver. - solver = pywrapcp.Solver('Alldifferent except 0') + # Create the solver. + solver = pywrapcp.Solver("Alldifferent except 0") - # data - n = 7 + # data + n = 7 - # declare variables - x = [solver.IntVar(0,n-1, 'x%i' % i) for i in range(n)] - # Number of zeros. - z = solver.Sum([x[i] == 0 for i in range(n)]).VarWithName('z') + # declare variables + x = [solver.IntVar(0, n - 1, "x%i" % i) for i in range(n)] + # Number of zeros. + z = solver.Sum([x[i] == 0 for i in range(n)]).VarWithName("z") - # - # constraints - # - alldifferent_except_0(solver, x) + # + # constraints + # + alldifferent_except_0(solver, x) - # we require 2 0's - solver.Add(z == 2) + # we require 2 0's + solver.Add(z == 2) - # - # solution and search - # - solution = solver.Assignment() - solution.Add([x[i] for i in range(n)]) - solution.Add(z) + # + # solution and search + # + solution = solver.Assignment() + solution.Add([x[i] for i in range(n)]) + solution.Add(z) - collector = solver.AllSolutionCollector(solution) - solver.Solve(solver.Phase([x[i] for i in range(n)], - solver.CHOOSE_FIRST_UNBOUND, - solver.ASSIGN_MIN_VALUE), - [collector]) + collector = solver.AllSolutionCollector(solution) + solver.Solve(solver.Phase([x[i] for i in range(n)], + solver.CHOOSE_FIRST_UNBOUND, + solver.ASSIGN_MIN_VALUE), + [collector]) - num_solutions = collector.SolutionCount() - for s in range(num_solutions): - print "x:", [collector.Value(s, x[i]) for i in range(n)] - print "z:", collector.Value(s, z) - print + num_solutions = collector.SolutionCount() + for s in range(num_solutions): + print "x:", [collector.Value(s, x[i]) for i in range(n)] + print "z:", collector.Value(s, z) + print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() -if __name__ == '__main__': - main("cp sample") +if __name__ == "__main__": + main("cp sample") diff --git a/examples/python/alphametic.py b/examples/python/alphametic.py index f12aaf3de2..dc7c9c9d45 100644 --- a/examples/python/alphametic.py +++ b/examples/python/alphametic.py @@ -40,127 +40,130 @@ * Zinc: http://www.hakank.org/minizinc/alphametic.zinc This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ -import sys, string, re +import sys +import string +import re from ortools.constraint_solver import pywrapcp + def main(problem_str="SEND+MORE=MONEY", base=10): - # Create the solver. - solver = pywrapcp.Solver('Send most money') + # Create the solver. + solver = pywrapcp.Solver("Send most money") - # data - print "\nproblem:", problem_str + # data + print "\nproblem:", problem_str - # convert to array. - problem = re.split("[\s+=]", problem_str) + # convert to array. + problem = re.split("[\s+=]", problem_str) - p_len = len(problem) - print "base:", base + p_len = len(problem) + print "base:", base - # create the lookup table: list of (digit : ix) - a = sorted(set("".join(problem))) - n = len(a) - lookup = dict(zip(a, range(n))) + # create the lookup table: list of (digit : ix) + a = sorted(set("".join(problem))) + n = len(a) + lookup = dict(zip(a, range(n))) - # length of each number - lens = map(len, problem) + # length of each number + lens = map(len, problem) - # - # declare variables - # + # + # declare variables + # - # the digits - x = [solver.IntVar(0, base-1, "x[%i]"%i) for i in range(n)] - # the sums of each number (e.g. the three numbers SEND, MORE, MONEY) - sums = [solver.IntVar(1, 10**(lens[i])-1) for i in range(p_len)] + # the digits + x = [solver.IntVar(0, base - 1, "x[%i]" % i) for i in range(n)] + # the sums of each number (e.g. the three numbers SEND, MORE, MONEY) + sums = [solver.IntVar(1, 10 ** (lens[i]) - 1) for i in range(p_len)] - # - # constraints - # - solver.Add(solver.AllDifferent(x)) + # + # constraints + # + solver.Add(solver.AllDifferent(x)) - ix = 0 + ix = 0 + for prob in problem: + this_len = len(prob) + + # sum all the digits with proper exponents to a number + solver.Add(sums[ix] == solver.Sum( + [(base ** i) * x[lookup[prob[this_len - i - 1]]] for i in range(this_len)[::-1]])) + # leading digits must be > 0 + solver.Add(x[lookup[prob[0]]] > 0) + ix += 1 + + # the last number is the sum of the previous numbers + solver.Add(solver.Sum([sums[i] for i in range(p_len - 1)]) == sums[-1]) + + # + # solution and search + # + solution = solver.Assignment() + solution.Add(x) + solution.Add(sums) + + db = solver.Phase(x, + solver.CHOOSE_FIRST_UNBOUND, + solver.ASSIGN_MIN_VALUE) + + solver.NewSearch(db) + + num_solutions = 0 + while solver.NextSolution(): + num_solutions += 1 + print "\nsolution #%i" % num_solutions + for i in range(n): + print a[i], "=", x[i].Value() + print for prob in problem: - this_len = len(prob) + for p in prob: + print p, + print + print + for prob in problem: + for p in prob: + print x[lookup[p]].Value(), + print - # sum all the digits with proper exponents to a number - solver.Add(sums[ix] == solver.Sum([(base**i)*x[lookup[prob[this_len-i-1]]] - for i in range(this_len)[::-1]])) - # leading digits must be > 0 - solver.Add(x[lookup[prob[0]]] > 0) - ix += 1 + print "sums:", [sums[i].Value() for i in range(p_len)] + print - # the last number is the sum of the previous numbers - solver.Add(solver.Sum([sums[i] for i in range(p_len-1)]) == sums[-1]) - - - # - # solution and search - # - solution = solver.Assignment() - solution.Add(x) - solution.Add(sums) - - db = solver.Phase(x, - solver.CHOOSE_FIRST_UNBOUND, - solver.ASSIGN_MIN_VALUE) - - solver.NewSearch(db) - - num_solutions = 0 - while solver.NextSolution(): - num_solutions += 1 - print "\nsolution #%i" % num_solutions - for i in range(n): - print a[i], "=", x[i].Value() - print - for prob in problem: - for p in prob: - print p, - print - print - for prob in problem: - for p in prob: - print x[lookup[p]].Value(), - print - - print "sums:", [sums[i].Value() for i in range(p_len)] - print - - print "\nnum_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + print "\nnum_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() def test_problems(base=10): - problems = [ - "SEND+MORE=MONEY", - "SEND+MOST=MONEY", - "VINGT+CINQ+CINQ=TRENTE", - "EIN+EIN+EIN+EIN=VIER", - "DONALD+GERALD=ROBERT", - "SATURN+URANUS+NEPTUNE+PLUTO+PLANETS", - "WRONG+WRONG=RIGHT" - ] + problems = [ + "SEND+MORE=MONEY", + "SEND+MOST=MONEY", + "VINGT+CINQ+CINQ=TRENTE", + "EIN+EIN+EIN+EIN=VIER", + "DONALD+GERALD=ROBERT", + "SATURN+URANUS+NEPTUNE+PLUTO+PLANETS", + "WRONG+WRONG=RIGHT" + ] - for p in problems: - main(p, base) + for p in problems: + main(p, base) problem = "SEND+MORE=MONEY" base = 10 -if __name__ == '__main__': - if len(sys.argv) > 1: - problem = sys.argv[1] - if len(sys.argv) > 2: - base = string.atoi(sys.argv[2]) +if __name__ == "__main__": + if len(sys.argv) > 1: + problem = sys.argv[1] + if len(sys.argv) > 2: + base = string.atoi(sys.argv[2]) - if problem == "TEST" or problem == "test": - test_problems(base) - else: - main(problem, base) + if problem == "TEST" or problem == "test": + test_problems(base) + else: + main(problem, base) diff --git a/examples/python/appointments.py b/examples/python/appointments.py index bb78d6abc7..c148646a06 100644 --- a/examples/python/appointments.py +++ b/examples/python/appointments.py @@ -84,7 +84,7 @@ def Select(combinations, loads, max_number_of_workers): # Simple bound. solver.Add(solver.Sum(variables) <= max_number_of_workers) - obj_vars = [solver.IntVar(0, 1000, 'obj_vars[%d]' %i) + obj_vars = [solver.IntVar(0, 1000, 'obj_vars[%d]' % i) for i in range(num_vars)] for i in range(num_vars): solver.Add(obj_vars[i] >= achieved[i] - loads[i]) diff --git a/examples/python/assignment.py b/examples/python/assignment.py index e46ae0077c..ee75d3844f 100644 --- a/examples/python/assignment.py +++ b/examples/python/assignment.py @@ -28,85 +28,88 @@ * SICStus: http://hakank.org/sicstus/assignment.pl This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ from ortools.constraint_solver import pywrapcp def main(cost, rows, cols): - # Create the solver. - solver = pywrapcp.Solver('n-queens') + # Create the solver. + solver = pywrapcp.Solver("n-queens") - # - # data - # + # + # data + # + # declare variables + total_cost = solver.IntVar(0, 100, "total_cost") + x = [] + for i in range(rows): + t = [] + for j in range(cols): + t.append(solver.IntVar(0, 1, "x[%i,%i]" % (i, j))) + x.append(t) + x_flat = [x[i][j] for i in range(rows) for j in range(cols)] - # declare variables - total_cost = solver.IntVar(0, 100, 'total_cost') - x = [] + # + # constraints + # + + # total_cost + solver.Add( + total_cost == solver.Sum( + [solver.ScalProd(x_row, cost_row) for (x_row, cost_row) in zip( + x, cost)])) + + # exacly one assignment per row, all rows must be assigned + [solver.Add(solver.Sum([x[row][j] for j in range(cols)]) == 1) + for row in range(rows)] + + # zero or one assignments per column + [solver.Add(solver.Sum([x[i][col] for i in range(rows)]) <= 1) + for col in range(cols)] + + objective = solver.Minimize(total_cost, 1) + + # + # solution and search + # + solution = solver.Assignment() + solution.Add(x_flat) + solution.Add(total_cost) + + # db: DecisionBuilder + db = solver.Phase(x_flat, + solver.INT_VAR_SIMPLE, + solver.ASSIGN_MIN_VALUE) + + solver.NewSearch(db, [objective]) + num_solutions = 0 + while solver.NextSolution(): + print "total_cost:", total_cost.Value() for i in range(rows): - t = [] - for j in range(cols): - t.append(solver.IntVar(0,1, 'x[%i,%i]'%(i,j))) - x.append(t) - x_flat = [x[i][j] for i in range(rows) for j in range(cols)] - - # - # constraints - # - - # total_cost - solver.Add(total_cost == solver.Sum([solver.ScalProd(x_row, cost_row) for (x_row, cost_row) in zip(x, cost)])) - - - # exacly one assignment per row, all rows must be assigned - [solver.Add(solver.Sum([x[row][j] for j in range(cols)]) == 1) for row in range(rows)] - - # zero or one assignments per column - [solver.Add(solver.Sum([x[i][col] for i in range(rows)]) <= 1) for col in range(cols)] - - objective = solver.Minimize(total_cost, 1) - - # - # solution and search - # - solution = solver.Assignment() - solution.Add(x_flat) - solution.Add(total_cost) - - - # db: DecisionBuilder - db = solver.Phase(x_flat, - solver.INT_VAR_SIMPLE, - solver.ASSIGN_MIN_VALUE) - - solver.NewSearch(db,[objective]) - num_solutions = 0 - while solver.NextSolution(): - print "total_cost:", total_cost.Value() - for i in range(rows): - for j in range(cols): - print x[i][j].Value(), - print - print - - for i in range(rows): - print "Task:",i, - for j in range(cols): - if x[i][j].Value() == 1: - print " is done by ", j - print - - num_solutions += 1 - solver.EndSearch() - + for j in range(cols): + print x[i][j].Value(), + print print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + + for i in range(rows): + print "Task:", i, + for j in range(cols): + if x[i][j].Value() == 1: + print " is done by ", j + print + + num_solutions += 1 + solver.EndSearch() + + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() # Problem instance @@ -114,11 +117,10 @@ def main(cost, rows, cols): # interesting rows = 4 cols = 5 -cost = [[14, 5, 8, 7, 15], - [ 2, 12, 6, 5, 3], - [ 7, 8, 3, 9, 7], - [ 2, 4, 6, 10, 1] - ] +cost = [[14, 5, 8, 7, 15], + [2, 12, 6, 5, 3], + [7, 8, 3, 9, 7], + [2, 4, 6, 10, 1]] -if __name__ == '__main__': - main(cost, rows, cols) +if __name__ == "__main__": + main(cost, rows, cols) diff --git a/examples/python/assignment6_mip.py b/examples/python/assignment6_mip.py index 04be504256..a29ad75b4a 100644 --- a/examples/python/assignment6_mip.py +++ b/examples/python/assignment6_mip.py @@ -37,12 +37,14 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ import sys from ortools.linear_solver import pywraplp -def main(sol = 'GLPK'): + +def main(sol='GLPK'): # Create the solver. @@ -53,10 +55,9 @@ def main(sol = 'GLPK'): solver = pywraplp.Solver('CoinsGridGLPK', pywraplp.Solver.GLPK_MIXED_INTEGER_PROGRAMMING) else: - # Using CLP - solver = pywraplp.Solver('CoinsGridCLP', - pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING) - + # Using CLP + solver = pywraplp.Solver('CoinsGridCLP', + pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING) # # data @@ -80,14 +81,14 @@ def main(sol = 'GLPK'): # # Optimal solution is 76 # """ - c = [[13, 21, 20, 12, 8, 26, 22, 11], - [12, 36, 25, 41, 40, 11, 4, 8], + c = [[13, 21, 20, 12, 8, 26, 22, 11], + [12, 36, 25, 41, 40, 11, 4, 8], [35, 32, 13, 36, 26, 21, 13, 37], - [34, 54, 7, 8, 12, 22, 11, 40], - [21, 6, 45, 18, 24, 34, 12, 48], + [34, 54, 7, 8, 12, 22, 11, 40], + [21, 6, 45, 18, 24, 34, 12, 48], [42, 19, 39, 15, 14, 16, 28, 46], - [16, 34, 38, 3, 34, 40, 22, 24], - [26, 20, 5, 17, 45, 31, 37, 43]] + [16, 34, 38, 3, 34, 40, 22, 24], + [26, 20, 5, 17, 45, 31, 37, 43]] # # variables @@ -101,35 +102,32 @@ def main(sol = 'GLPK'): x = {} for i in range(n): for j in range(n): - x[i,j] = solver.IntVar(0, 1, 'x[%i,%i]' % (i, j)) + x[i, j] = solver.IntVar(0, 1, 'x[%i,%i]' % (i, j)) # total cost, to be minimized - z = solver.Sum([c[i][j]*x[i,j] - for i in I - for j in J]) + z = solver.Sum([c[i][j] * x[i, j] + for i in I + for j in J]) # # constraints # # each agent can perform at most one task for i in I: - solver.Add(solver.Sum([x[i,j] for j in J]) <= 1) + solver.Add(solver.Sum([x[i, j] for j in J]) <= 1) # each task must be assigned exactly to one agent for j in J: - solver.Add(solver.Sum([x[i,j] for i in I]) == 1) - + solver.Add(solver.Sum([x[i, j] for i in I]) == 1) # to which task and what cost is person i assigned (for output in MiniZinc) for i in I: - solver.Add(assigned[i] == solver.Sum([ j*x[i,j] for j in J])) - solver.Add(costs[i] == solver.Sum([c[i][j]*x[i,j] for j in J])) - + solver.Add(assigned[i] == solver.Sum([j * x[i, j] for j in J])) + solver.Add(costs[i] == solver.Sum([c[i][j] * x[i, j] for j in J])) # objective objective = solver.Minimize(z) - # # solution and search # @@ -146,12 +144,10 @@ def main(sol = 'GLPK'): print 'Matrix:' for i in I: for j in J: - print int(x[i,j].SolutionValue()), + print int(x[i, j].SolutionValue()), print print - - print print 'walltime :', solver.WallTime(), 'ms' if sol == 'CBC': diff --git a/examples/python/bacp.py b/examples/python/bacp.py index 290af0ffe2..90b7410838 100644 --- a/examples/python/bacp.py +++ b/examples/python/bacp.py @@ -23,34 +23,35 @@ gflags.DEFINE_string('data', 'python/data/bacp/bacp12.txt', #----------------helper for binpacking posting---------------- + def BinPacking(solver, binvars, weights, loadvars): '''post the load constraint on bins. constraints forall j: loadvars[j] == sum_i (binvars[i] == j) * weights[i]) ''' pack = solver.Pack(binvars, len(loadvars)) - pack.AddWeightedSumEqualVarDimension(weights, loadvars); + pack.AddWeightedSumEqualVarDimension(weights, loadvars) solver.Add(pack) solver.Add(solver.SumEquality(loadvars, sum(weights))) #------------------------------data reading------------------- + def ReadData(filename): - '''Read data from .''' + """Read data from .""" f = open(filename) nb_courses, nb_periods, min_credit, max_credit, nb_prereqs =\ [int(nb) for nb in f.readline().split()] credits = [int(nb) for nb in f.readline().split()] - prereq = [int(nb) for nb in f.readline().split()] - prereq = [(prereq[i * 2],prereq[i * 2 + 1]) for i in range(nb_prereqs)] - return (credits ,nb_periods, prereq) - + prereq = [int(nb) for nb in f.readline().split()] + prereq = [(prereq[i * 2], prereq[i * 2 + 1]) for i in range(nb_prereqs)] + return (credits, nb_periods, prereq) def main(unused_argv): #------------------solver and variable declaration------------- - credits ,nb_periods, prereq = ReadData(FLAGS.data) + credits, nb_periods, prereq = ReadData(FLAGS.data) nb_courses = len(credits) solver = pywrapcp.Solver('Balanced Academic Curriculum Problem') @@ -65,8 +66,8 @@ def main(unused_argv): # Bin Packing. BinPacking(solver, x, credits, load_vars) # Add dependencies. - for i,j in prereq: - solver.Add(x[i] < x[j]) + for i, j in prereq: + solver.Add(x[i] < x[j]) #----------------Objective------------------------------- diff --git a/examples/python/blending.py b/examples/python/blending.py index ef6e738c32..4abebb651e 100644 --- a/examples/python/blending.py +++ b/examples/python/blending.py @@ -19,13 +19,14 @@ From the OPL model blending.mod. This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ import sys from ortools.linear_solver import pywraplp -def main(sol = 'GLPK'): +def main(sol='GLPK'): # Create the solver. @@ -36,10 +37,9 @@ def main(sol = 'GLPK'): solver = pywraplp.Solver('CoinsGridGLPK', pywraplp.Solver.GLPK_MIXED_INTEGER_PROGRAMMING) else: - # Using CLP - solver = pywraplp.Solver('CoinsGridCLP', - pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING) - + # Using CLP + solver = pywraplp.Solver('CoinsGridCLP', + pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING) # # data @@ -54,15 +54,15 @@ def main(sol = 'GLPK'): Ingos = range(NbIngo) CostMetal = [22, 10, 13] - CostRaw = [6, 5] - CostScrap = [ 7, 8] - CostIngo = [9 ] - Low = [0.05, 0.30, 0.60] - Up = [0.10, 0.40, 0.80] - PercRaw = [ [ 0.20, 0.01 ], [ 0.05, 0 ], [ 0.05, 0.30 ] ] - PercScrap = [ [ 0 , 0.01 ], [ 0.60, 0 ], [ 0.40, 0.70 ] ] - PercIngo = [ [ 0.10 ], [ 0.45 ], [ 0.45 ] ] - Alloy = 71 + CostRaw = [6, 5] + CostScrap = [7, 8] + CostIngo = [9] + Low = [0.05, 0.30, 0.60] + Up = [0.10, 0.40, 0.80] + PercRaw = [[0.20, 0.01], [0.05, 0], [0.05, 0.30]] + PercScrap = [[0, 0.01], [0.60, 0], [0.40, 0.70]] + PercIngo = [[0.10], [0.45], [0.45]] + Alloy = 71 # # variables @@ -71,7 +71,7 @@ def main(sol = 'GLPK'): r = [solver.NumVar(0, solver.Infinity(), 'r[%i]' % i) for i in Raws] s = [solver.NumVar(0, solver.Infinity(), 's[%i]' % i) for i in Scraps] ii = [solver.IntVar(0, solver.Infinity(), 'ii[%i]' % i) for i in Ingos] - metal = [solver.NumVar(Low[j]*Alloy, Up[j]*Alloy, 'metal[%i]' % j) + metal = [solver.NumVar(Low[j] * Alloy, Up[j] * Alloy, 'metal[%i]' % j) for j in Metals] z = solver.NumVar(0, solver.Infinity(), 'z') @@ -81,19 +81,17 @@ def main(sol = 'GLPK'): # solver.Add(z == - solver.Sum([CostMetal[i] * p[i] for i in Metals]) + - solver.Sum([CostRaw[i] * r[i] for i in Raws]) + - solver.Sum([CostScrap[i] * s[i] for i in Scraps]) + - solver.Sum([CostIngo[i] * ii[i] for i in Ingos])) - + solver.Sum([CostMetal[i] * p[i] for i in Metals]) + + solver.Sum([CostRaw[i] * r[i] for i in Raws]) + + solver.Sum([CostScrap[i] * s[i] for i in Scraps]) + + solver.Sum([CostIngo[i] * ii[i] for i in Ingos])) for j in Metals: solver.Add( - metal[j] == p[j] + - solver.Sum([PercRaw[j][k] * r[k] for k in Raws]) + - solver.Sum([PercScrap[j][k] * s[k] for k in Scraps]) + - solver.Sum([PercIngo[j][k] * ii[k] for k in Ingos])) - + metal[j] == p[j] + + solver.Sum([PercRaw[j][k] * r[k] for k in Raws]) + + solver.Sum([PercScrap[j][k] * s[k] for k in Scraps]) + + solver.Sum([PercIngo[j][k] * ii[k] for k in Ingos])) solver.Add(solver.Sum(metal) == Alloy) @@ -140,12 +138,12 @@ def main(sol = 'GLPK'): if __name__ == '__main__': - sol = 'GLPK' + sol = 'GLPK' - if len(sys.argv) > 1: - sol = sys.argv[1] - if sol != 'GLPK' and sol != 'CBC': - print 'Solver must be either GLPK or CBC' - sys.exit(1) + if len(sys.argv) > 1: + sol = sys.argv[1] + if sol != 'GLPK' and sol != 'CBC': + print 'Solver must be either GLPK or CBC' + sys.exit(1) - main(sol) + main(sol) diff --git a/examples/python/broken_weights.py b/examples/python/broken_weights.py index 814b8dfd6e..529f4ae402 100644 --- a/examples/python/broken_weights.py +++ b/examples/python/broken_weights.py @@ -44,7 +44,8 @@ * Comet: http://hakank.org/comet/broken_weights.co This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ import sys import string @@ -54,90 +55,89 @@ from ortools.constraint_solver import pywrapcp def main(m=40, n=4): - # Create the solver. - solver = pywrapcp.Solver('Broken weights') + # Create the solver. + solver = pywrapcp.Solver('Broken weights') - # - # data - # - print 'total weight (m):', m - print 'number of pieces (n):', n + # + # data + # + print 'total weight (m):', m + print 'number of pieces (n):', n + print + + # + # variables + # + weights = [solver.IntVar(1, m, 'weights[%i]' % j) for j in range(n)] + x = {} + for i in range(m): + for j in range(n): + x[i, j] = solver.IntVar(-1, 1, 'x[%i,%i]' % (i, j)) + x_flat = [x[i, j] for i in range(m) for j in range(n)] + + # + # constraints + # + + # symmetry breaking + for j in range(1, n): + solver.Add(weights[j - 1] < weights[j]) + + solver.Add(solver.SumEquality(weights, m)) + + # Check that all weights from 1 to 40 can be made. + # + # Since all weights can be on either side + # of the side of the scale we allow either + # -1, 0, or 1 or the weights, assuming that + # -1 is the weights on the left and 1 is on the right. + # + for i in range(m): + solver.Add(i + 1 == solver.Sum([weights[j] * x[i, j] + for j in range(n)])) + + # objective + objective = solver.Minimize(weights[n - 1], 1) + + # + # search and result + # + db = solver.Phase(weights + x_flat, + solver.CHOOSE_FIRST_UNBOUND, + solver.ASSIGN_MIN_VALUE) + + search_log = solver.SearchLog(1) + + solver.NewSearch(db, [objective]) + + num_solutions = 0 + while solver.NextSolution(): + num_solutions += 1 + print 'weights: ', + for w in [weights[j].Value() for j in range(n)]: + print '%3i ' % w, print - - # - # variables - # - weights = [solver.IntVar(1, m, 'weights[%i]' % j) for j in range(n)] - x = {} + print '-' * 30 for i in range(m): - for j in range(n): - x[i,j] = solver.IntVar(-1, 1, 'x[%i,%i]' % (i, j)) - x_flat = [x[i,j] for i in range(m) for j in range(n)] - - # - # constraints - # - - # symmetry breaking - for j in range(1, n): - solver.Add(weights[j-1] < weights[j]) - - solver.Add(solver.SumEquality(weights, m)) - - # Check that all weights from 1 to 40 can be made. - # - # Since all weights can be on either side - # of the side of the scale we allow either - # -1, 0, or 1 or the weights, assuming that - # -1 is the weights on the left and 1 is on the right. - # - for i in range(m): - solver.Add(i+1 == solver.Sum([weights[j]*x[i,j] - for j in range(n)])) - - - # objective - objective = solver.Minimize(weights[n-1], 1) - - # - # search and result - # - db = solver.Phase(weights + x_flat, - solver.CHOOSE_FIRST_UNBOUND, - solver.ASSIGN_MIN_VALUE) - - search_log = solver.SearchLog(1) - - solver.NewSearch(db, [objective]) - - num_solutions = 0 - while solver.NextSolution(): - num_solutions += 1 - print 'weights: ', - for w in [weights[j].Value() for j in range(n)]: - print '%3i ' % w, - print - print '-' * 30 - for i in range(m): - print 'weight %2i:' % (i+1), - for j in range(n): - print '%3i ' % x[i,j].Value(), - print - print + print 'weight %2i:' % (i + 1), + for j in range(n): + print '%3i ' % x[i, j].Value(), + print print - solver.EndSearch() + print + solver.EndSearch() - print 'num_solutions:', num_solutions - print 'failures :', solver.Failures() - print 'branches :', solver.Branches() - print 'WallTime:', solver.WallTime(), 'ms' + print 'num_solutions:', num_solutions + print 'failures :', solver.Failures() + print 'branches :', solver.Branches() + print 'WallTime:', solver.WallTime(), 'ms' m = 40 n = 4 if __name__ == '__main__': - if len(sys.argv) > 1: - m = string.atoi(sys.argv[1]) - if len(sys.argv) > 2: - n = string.atoi(sys.argv[2]) - main(m, n) + if len(sys.argv) > 1: + m = string.atoi(sys.argv[1]) + if len(sys.argv) > 2: + n = string.atoi(sys.argv[2]) + main(m, n) diff --git a/examples/python/bus_schedule.py b/examples/python/bus_schedule.py index 434603a043..f6d28debd2 100644 --- a/examples/python/bus_schedule.py +++ b/examples/python/bus_schedule.py @@ -30,7 +30,8 @@ * SICStus: http://hakank.org/sicstus/bus_schedule.pl This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ @@ -39,78 +40,74 @@ import string from ortools.constraint_solver import pywrapcp - def main(num_buses_check=0): - # Create the solver. - solver = pywrapcp.Solver('Bus scheduling') + # Create the solver. + solver = pywrapcp.Solver("Bus scheduling") - # data - time_slots = 6 - demands = [8, 10, 7, 12, 4, 4] - max_num = sum(demands) + # data + time_slots = 6 + demands = [8, 10, 7, 12, 4, 4] + max_num = sum(demands) - # declare variables - x = [solver.IntVar(0, max_num, "x%i"%i) for i in range(time_slots)] - num_buses = solver.IntVar(0, max_num, 'num_buses') + # declare variables + x = [solver.IntVar(0, max_num, "x%i" % i) for i in range(time_slots)] + num_buses = solver.IntVar(0, max_num, "num_buses") - # - # constraints - # - solver.Add(num_buses == solver.Sum(x)) + # + # constraints + # + solver.Add(num_buses == solver.Sum(x)) - # Meet the demands for this and the next time slot - for i in range(time_slots-1): - solver.Add(x[i]+x[i+1] >= demands[i]) + # Meet the demands for this and the next time slot + for i in range(time_slots - 1): + solver.Add(x[i] + x[i + 1] >= demands[i]) - # The demand "around the clock" - solver.Add(x[time_slots-1] + x[0] == demands[time_slots-1]) + # The demand "around the clock" + solver.Add(x[time_slots - 1] + x[0] == demands[time_slots - 1]) - if num_buses_check > 0: - solver.Add(num_buses == num_buses_check) + if num_buses_check > 0: + solver.Add(num_buses == num_buses_check) - # - # solution and search - # - solution = solver.Assignment() - solution.Add(x) - solution.Add(num_buses) + # + # solution and search + # + solution = solver.Assignment() + solution.Add(x) + solution.Add(num_buses) - collector = solver.AllSolutionCollector(solution) - cargs = [collector] + collector = solver.AllSolutionCollector(solution) + cargs = [collector] - # objective - if num_buses_check == 0: - objective = solver.Minimize(num_buses, 1) - cargs.extend([objective]) + # objective + if num_buses_check == 0: + objective = solver.Minimize(num_buses, 1) + cargs.extend([objective]) + solver.Solve(solver.Phase(x, + solver.CHOOSE_FIRST_UNBOUND, + solver.ASSIGN_MIN_VALUE), + cargs) + num_solutions = collector.SolutionCount() + num_buses_check_value = 0 + for s in range(num_solutions): + print "x:", [collector.Value(s, x[i]) for i in range(len(x))], + num_buses_check_value = collector.Value(s, num_buses) + print " num_buses:", num_buses_check_value + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() + print + if num_buses_check == 0: + return num_buses_check_value - solver.Solve(solver.Phase(x, - solver.CHOOSE_FIRST_UNBOUND, - solver.ASSIGN_MIN_VALUE), - cargs) - - num_solutions = collector.SolutionCount() - num_buses_check_value = 0 - for s in range(num_solutions): - print "x:", [collector.Value(s, x[i]) for i in range(len(x))], - num_buses_check_value = collector.Value(s, num_buses) - print " num_buses:", num_buses_check_value - - print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() - print - if num_buses_check == 0: - return num_buses_check_value - -if __name__ == '__main__': - print "Check for minimun number of buses" - num_buses_check = main() - print "... got ", num_buses_check, "buses" - print "All solutions:" - main(num_buses_check) +if __name__ == "__main__": + print "Check for minimun number of buses" + num_buses_check = main() + print "... got ", num_buses_check, "buses" + print "All solutions:" + main(num_buses_check) diff --git a/examples/python/car.py b/examples/python/car.py index 49606580b6..999cd82e4f 100644 --- a/examples/python/car.py +++ b/examples/python/car.py @@ -26,7 +26,8 @@ * Comet: http://hakank.org/comet/car.co This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ import sys @@ -37,112 +38,110 @@ from ortools.constraint_solver import pywrapcp def main(num_sol=3): - # Create the solver. - solver = pywrapcp.Solver('Car sequence') + # Create the solver. + solver = pywrapcp.Solver("Car sequence") - # - # data - # - nbCars = 6 - nbOptions = 5 - nbSlots = 10 + # + # data + # + nbCars = 6 + nbOptions = 5 + nbSlots = 10 - Cars = range(nbCars) - Options = range(nbOptions) - Slots = range(nbSlots) + Cars = range(nbCars) + Options = range(nbOptions) + Slots = range(nbSlots) - # car 0 1 2 3 4 5 - demand = [1, 1, 2, 2, 2, 2] + # car 0 1 2 3 4 5 + demand = [1, 1, 2, 2, 2, 2] - option = [ - # car 0 1 2 3 4 5 - [ 1, 0, 0, 0, 1, 1], # option 1 - [ 0, 0, 1, 1, 0, 1], # option 2 - [ 1, 0, 0, 0, 1, 0], # option 3 - [ 1, 1, 0, 1, 0, 0], # option 4 - [ 0, 0, 1, 0, 0, 0] # option 5 - ] + option = [ + # car 0 1 2 3 4 5 + [1, 0, 0, 0, 1, 1], # option 1 + [0, 0, 1, 1, 0, 1], # option 2 + [1, 0, 0, 0, 1, 0], # option 3 + [1, 1, 0, 1, 0, 0], # option 4 + [0, 0, 1, 0, 0, 0] # option 5 + ] - capacity = [ - (1,2), - (2,3), - (1,3), - (2,5), - (1,5) - ] + capacity = [ + (1, 2), + (2, 3), + (1, 3), + (2, 5), + (1, 5) + ] - optionDemand = [sum([demand[j]*option[i][j] for j in Cars]) \ - for i in Options] + optionDemand = [sum([demand[j] * option[i][j] for j in Cars]) + for i in Options] - # - # declare variables - # - slot = [solver.IntVar(0, nbCars-1, "slot[%i]" % i) for i in Slots] - setup = {} - for i in Options: - for j in Slots: - setup[(i,j)] = solver.IntVar(0, 1, "setup[%i,%i]" % (i,j)) - setup_flat = [setup[i,j] for i in Options for j in Slots] + # + # declare variables + # + slot = [solver.IntVar(0, nbCars - 1, "slot[%i]" % i) for i in Slots] + setup = {} + for i in Options: + for j in Slots: + setup[(i, j)] = solver.IntVar(0, 1, "setup[%i,%i]" % (i, j)) + setup_flat = [setup[i, j] for i in Options for j in Slots] - # - # constraints - # - for c in Cars: - b = [solver.IsEqualCstVar(slot[s], c) for s in Slots] - solver.Add(solver.Sum(b) == demand[c]) + # + # constraints + # + for c in Cars: + b = [solver.IsEqualCstVar(slot[s], c) for s in Slots] + solver.Add(solver.Sum(b) == demand[c]) + for o in Options: + for s in range(0, nbSlots - capacity[o][1] + 1): + b = [setup[o, j] for j in range(s, s + capacity[o][1] - 1)] + solver.Add(solver.Sum(b) <= capacity[o][0]) + for o in Options: + for s in Slots: + solver.Add(setup[(o, s)] == solver.Element(option[o], slot[s])) + + for o in Options: + for i in range(optionDemand[o]): + s_range = range(0, nbSlots - (i + 1) * capacity[o][1]) + ss = [setup[o, s] for s in s_range] + cc = optionDemand[o] - (i + 1) * capacity[o][0] + if len(ss) > 0 and cc >= 0: + solver.Add(solver.Sum(ss) >= cc) + + # + # search and result + # + db = solver.Phase(slot + setup_flat, + solver.CHOOSE_FIRST_UNBOUND, + solver.ASSIGN_MIN_VALUE) + + solver.NewSearch(db) + num_solutions = 0 + while solver.NextSolution(): + print "slot:%s" % ",".join([str(slot[i].Value()) for i in Slots]) + print "setup:" for o in Options: - for s in range(0, nbSlots-capacity[o][1]+1): - b = [setup[o,j] for j in range(s, s + capacity[o][1]-1)] - solver.Add(solver.Sum(b) <= capacity[o][0]) - - for o in Options: - for s in Slots: - solver.Add(setup[(o,s)] == solver.Element(option[o], slot[s])) - - for o in Options: - for i in range(optionDemand[o]): - s_range = range(0, nbSlots - (i+1) * capacity[o][1]) - ss = [setup[o,s] for s in s_range] - cc = optionDemand[o] - (i+1) * capacity[o][0] - if len(ss) > 0 and cc >= 0: - solver.Add(solver.Sum(ss) >= cc) - - - # - # search and result - # - db = solver.Phase(slot + setup_flat, - solver.CHOOSE_FIRST_UNBOUND, - solver.ASSIGN_MIN_VALUE) - - solver.NewSearch(db) - num_solutions = 0 - while solver.NextSolution(): - print "slot:%s" % ",".join([str(slot[i].Value()) for i in Slots]) - print "setup:" - for o in Options: - print "%i/%i:" % (capacity[o][0], capacity[o][1]), - for s in Slots: - print setup[o,s].Value(), - print - print - num_solutions += 1 - - if num_solutions >= num_sol: - break - - solver.EndSearch() - + print "%i/%i:" % (capacity[o][0], capacity[o][1]), + for s in Slots: + print setup[o, s].Value(), + print print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + num_solutions += 1 + + if num_solutions >= num_sol: + break + + solver.EndSearch() + + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() num_sol = 3 -if __name__ == '__main__': - if len(sys.argv) > 1: - num_sol = string.atoi(sys.argv[1]) - main(num_sol) +if __name__ == "__main__": + if len(sys.argv) > 1: + num_sol = string.atoi(sys.argv[1]) + main(num_sol) diff --git a/examples/python/circuit.py b/examples/python/circuit.py index b34d03308c..b151751397 100644 --- a/examples/python/circuit.py +++ b/examples/python/circuit.py @@ -37,7 +37,8 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ @@ -52,80 +53,81 @@ from ortools.constraint_solver import pywrapcp # Note: This assumes that x is has the domain 0..len(x)-1, # i.e. 0-based. # + + def circuit(solver, x): - n = len(x) - z = [solver.IntVar(0, n-1, 'z%i' % i) for i in range(n)] + n = len(x) + z = [solver.IntVar(0, n - 1, "z%i" % i) for i in range(n)] - solver.Add(solver.AllDifferent(x)) - solver.Add(solver.AllDifferent(z)) + solver.Add(solver.AllDifferent(x)) + solver.Add(solver.AllDifferent(z)) - # put the orbit of x[0] in in z[0..n-1] - solver.Add(z[0] == x[0]) - for i in range(1,n-1): - # The following constraint give the error - # "TypeError: list indices must be integers, not IntVar" - # solver.Add(z[i] == x[z[i-1]]) + # put the orbit of x[0] in in z[0..n-1] + solver.Add(z[0] == x[0]) + for i in range(1, n - 1): + # The following constraint give the error + # "TypeError: list indices must be integers, not IntVar" + # solver.Add(z[i] == x[z[i-1]]) - # solution: use Element instead - solver.Add(z[i] == solver.Element(x,z[i-1])) + # solution: use Element instead + solver.Add(z[i] == solver.Element(x, z[i - 1])) - # - # Note: At least one of the following two constraint must be set. - # - # may not be 0 for i < n-1 - for i in range(1, n-1): - solver.Add(z[i] != 0) + # + # Note: At least one of the following two constraint must be set. + # + # may not be 0 for i < n-1 + for i in range(1, n - 1): + solver.Add(z[i] != 0) - # when i = n-1 it must be 0 - solver.Add(z[n-1] == 0) + # when i = n-1 it must be 0 + solver.Add(z[n - 1] == 0) def main(n=5): - # Create the solver. - solver = pywrapcp.Solver('Send most money') + # Create the solver. + solver = pywrapcp.Solver("Send most money") - # data - print "n:", n + # data + print "n:", n - # declare variables - # Note: domain should be 0..n-1 - x = [solver.IntVar(0,n-1,"x%i"%i) for i in range(n)] + # declare variables + # Note: domain should be 0..n-1 + x = [solver.IntVar(0, n - 1, "x%i" % i) for i in range(n)] + # + # constraints + # + circuit(solver, x) - # - # constraints - # - circuit(solver, x) + # + # solution and search + # + solution = solver.Assignment() + solution.Add(x) - # - # solution and search - # - solution = solver.Assignment() - solution.Add(x) + collector = solver.AllSolutionCollector(solution) - collector = solver.AllSolutionCollector(solution) + solver.Solve(solver.Phase(x, + solver.CHOOSE_FIRST_UNBOUND, + solver.ASSIGN_MIN_VALUE), + [collector]) - solver.Solve(solver.Phase(x, - solver.CHOOSE_FIRST_UNBOUND, - solver.ASSIGN_MIN_VALUE), - [collector]) + num_solutions = collector.SolutionCount() + for s in range(num_solutions): + print "x:", [collector.Value(s, x[i]) for i in range(len(x))] - num_solutions = collector.SolutionCount() - for s in range(num_solutions): - print "x:", [collector.Value(s, x[i]) for i in range(len(x))] - - print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() - print + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() + print n = 5 -if __name__ == '__main__': - if len(sys.argv) > 1: - n=string.atoi(sys.argv[1]) +if __name__ == "__main__": + if len(sys.argv) > 1: + n = string.atoi(sys.argv[1]) - main(n) + main(n) diff --git a/examples/python/coins3.py b/examples/python/coins3.py index 6e59e0af3c..b3feae22cb 100644 --- a/examples/python/coins3.py +++ b/examples/python/coins3.py @@ -34,71 +34,71 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ -import sys, string +import sys +import string from ortools.constraint_solver import pywrapcp def main(): - # Create the solver. - solver = pywrapcp.Solver('Coins') + # Create the solver. + solver = pywrapcp.Solver("Coins") - # - # data - # - n = 6 # number of different coins - variables = [1, 2, 5, 10, 25, 50] + # + # data + # + n = 6 # number of different coins + variables = [1, 2, 5, 10, 25, 50] + # declare variables + x = [solver.IntVar(0, 99, "x%i" % i) for i in range(n)] + num_coins = solver.IntVar(0, 99, "num_coins") - # declare variables - x = [solver.IntVar(0, 99, 'x%i' % i) for i in range(n)] - num_coins = solver.IntVar(0, 99, 'num_coins') + # + # constraints + # - # - # constraints - # + # number of used coins, to be minimized + solver.Add(num_coins == solver.Sum(x)) - # number of used coins, to be minimized - solver.Add(num_coins == solver.Sum(x)) + # Check that all changes from 1 to 99 can be made. + for j in range(1, 100): + tmp = [solver.IntVar(0, 99, "b%i" % i) for i in range(n)] + solver.Add(solver.ScalProd(tmp, variables) == j) + [solver.Add(tmp[i] <= x[i]) for i in range(n)] - # Check that all changes from 1 to 99 can be made. - for j in range(1, 100): - tmp = [solver.IntVar(0, 99, 'b%i'%i) for i in range(n)] - solver.Add(solver.ScalProd(tmp, variables) == j) - [solver.Add(tmp[i] <= x[i]) for i in range(n)] + # objective + objective = solver.Minimize(num_coins, 1) + # + # solution and search + # + solution = solver.Assignment() + solution.Add(x) + solution.Add(num_coins) + solution.AddObjective(num_coins) - # objective - objective = solver.Minimize(num_coins, 1) - - # - # solution and search - # - solution = solver.Assignment() - solution.Add(x) - solution.Add(num_coins) - solution.AddObjective(num_coins) - - db = solver.Phase(x, - solver.CHOOSE_MIN_SIZE_LOWEST_MAX, - solver.ASSIGN_MIN_VALUE) - - solver.NewSearch(db, [objective]) - num_solutions = 0 - while solver.NextSolution(): - print "x: ", [x[i].Value() for i in range(n)] - print "num_coins:", num_coins.Value() - print - num_solutions += 1 - solver.EndSearch() + db = solver.Phase(x, + solver.CHOOSE_MIN_SIZE_LOWEST_MAX, + solver.ASSIGN_MIN_VALUE) + solver.NewSearch(db, [objective]) + num_solutions = 0 + while solver.NextSolution(): + print "x: ", [x[i].Value() for i in range(n)] + print "num_coins:", num_coins.Value() print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + num_solutions += 1 + solver.EndSearch() + + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() -if __name__ == '__main__': - main() +if __name__ == "__main__": + main() diff --git a/examples/python/coins_grid.py b/examples/python/coins_grid.py index a97b925c18..03f1d12d1d 100644 --- a/examples/python/coins_grid.py +++ b/examples/python/coins_grid.py @@ -50,24 +50,26 @@ * JaCoP: http://hakank.org/JaCoP/CoinsGrid.java This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ from ortools.constraint_solver import pywrapcp + def main(unused_argv): # Create the solver. - solver = pywrapcp.Solver('Coins grid') + solver = pywrapcp.Solver("Coins grid") - # data - n = 31 # the grid size - c = 14 # number of coins per row/column + # data + n = 31 # the grid size + c = 14 # number of coins per row/column # (6, 4) - # declare variables + # declare variables x = {} for i in range(n): for j in range(n): - x[(i,j)] = solver.BoolVar('x %i %i' % (i, j)) + x[(i, j)] = solver.BoolVar("x %i %i" % (i, j)) # # constraints @@ -75,8 +77,8 @@ def main(unused_argv): # sum rows/columns == c for i in range(n): - solver.Add(solver.SumEquality([x[(i, j)] for j in range(n)], c)) # sum rows - solver.Add(solver.SumEquality([x[(j, i)] for j in range(n)], c)) # sum cols + solver.Add(solver.SumEquality([x[(i, j)] for j in range(n)], c)) # sum rows + solver.Add(solver.SumEquality([x[(j, i)] for j in range(n)], c)) # sum cols # quadratic horizonal distance var objective_var = solver.Sum([x[(i, j)] * (i - j) * (i - j) @@ -89,14 +91,14 @@ def main(unused_argv): # solution and search # solution = solver.Assignment() - solution.Add([x[(i,j)] for i in range(n) for j in range(n)]) + solution.Add([x[(i, j)] for i in range(n) for j in range(n)]) solution.AddObjective(objective_var) # last solutions collector = solver.LastSolutionCollector(solution) search_log = solver.SearchLog(1000000, objective_var) restart = solver.ConstantRestart(300) - solver.Solve(solver.Phase([x[(i,j)] for i in range(n) for j in range(n)], + solver.Solve(solver.Phase([x[(i, j)] for i in range(n) for j in range(n)], solver.CHOOSE_RANDOM, solver.ASSIGN_MAX_VALUE), [collector, search_log, objective]) @@ -113,5 +115,5 @@ def main(unused_argv): print "WallTime:", solver.WallTime() -if __name__ == '__main__': - main("coin grids") +if __name__ == "__main__": + main("coin grids") diff --git a/examples/python/coins_grid_mip.py b/examples/python/coins_grid_mip.py index fc93882bf7..b57e00e1dd 100644 --- a/examples/python/coins_grid_mip.py +++ b/examples/python/coins_grid_mip.py @@ -37,33 +37,34 @@ and use This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ from ortools.linear_solver import pywraplp + def main(unused_argv): # Create the solver. # using GLPK solver = pywraplp.Solver('CoinsGridGLPK', - pywraplp.Solver.GLPK_MIXED_INTEGER_PROGRAMMING) + pywraplp.Solver.GLPK_MIXED_INTEGER_PROGRAMMING) # Using CLP # solver = pywraplp.Solver('CoinsGridCLP', # pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING) - # data - n = 31 # the grid size - c = 14 # number of coins per row/column + n = 31 # the grid size + c = 14 # number of coins per row/column # declare variables x = {} for i in range(n): for j in range(n): - x[(i,j)] = solver.IntVar(0, 1, 'x[%i,%i]' % (i, j)) + x[(i, j)] = solver.IntVar(0, 1, 'x[%i,%i]' % (i, j)) # # constraints @@ -72,14 +73,14 @@ def main(unused_argv): # sum rows/columns == c for i in range(n): solver.Add(solver.Sum( - [x[(i, j)] for j in range(n)]) == c) # sum rows + [x[(i, j)] for j in range(n)]) == c) # sum rows solver.Add(solver.Sum( - [x[(j, i)] for j in range(n)]) == c) # sum cols + [x[(j, i)] for j in range(n)]) == c) # sum cols # quadratic horizonal distance var objective_var = solver.Sum( - [x[(i, j)] * (i - j) * (i - j) - for i in range(n) for j in range(n)]) + [x[(i, j)] * (i - j) * (i - j) + for i in range(n) for j in range(n)]) # objective objective = solver.Minimize(objective_var) @@ -102,4 +103,4 @@ def main(unused_argv): if __name__ == '__main__': - main("coin grids") + main('coin grids') diff --git a/examples/python/coloring_ip.py b/examples/python/coloring_ip.py index 617e2fcbb7..857d4ff7a1 100644 --- a/examples/python/coloring_ip.py +++ b/examples/python/coloring_ip.py @@ -34,14 +34,15 @@ http://www.hakank.org/minizinc/coloring_ip.mzn This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ import sys from ortools.linear_solver import pywraplp -def main(sol = 'GLPK'): +def main(sol='GLPK'): # Create the solver. @@ -53,8 +54,8 @@ def main(sol = 'GLPK'): pywraplp.Solver.GLPK_MIXED_INTEGER_PROGRAMMING) else: # Using CBC - solver = pywraplp.Solver('CoinsGridCLP', - pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING) + solver = pywraplp.Solver('CoinsGridCLP', + pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING) # # data @@ -78,27 +79,26 @@ def main(sol = 'GLPK'): # http://mat.gsia.cmu.edu/COLOR/instances.html # # Note: 1-based (adjusted below) - E = [[1, 2], - [1, 4], - [1, 7], - [1, 9], - [2, 3], - [2, 6], - [2, 8], - [3, 5], - [3, 7], - [3, 10], - [4, 5], - [4, 6], - [4, 10], - [5, 8], - [5, 9], - [6, 11], - [7, 11], - [8, 11], - [9, 11], - [10, 11]] - + E = [[1, 2], + [1, 4], + [1, 7], + [1, 9], + [2, 3], + [2, 6], + [2, 8], + [3, 5], + [3, 7], + [3, 10], + [4, 5], + [4, 6], + [4, 10], + [5, 8], + [5, 9], + [6, 11], + [7, 11], + [8, 11], + [9, 11], + [10, 11]] # # declare variables @@ -108,8 +108,7 @@ def main(sol = 'GLPK'): x = {} for v in V: for j in range(nc): - x[v,j] = solver.IntVar(0, 1, 'v[%i,%i]' % (v, j)) - + x[v, j] = solver.IntVar(0, 1, 'v[%i,%i]' % (v, j)) # u[c] = 1 means that color c is used, i.e. assigned to some node u = [solver.IntVar(0, 1, 'u[%i]' % i) for i in range(nc)] @@ -117,22 +116,19 @@ def main(sol = 'GLPK'): # number of colors used, to minimize obj = solver.Sum(u) - # # constraints # # each node must be assigned exactly one color for i in V: - solver.Add(solver.Sum([x[i,c] for c in range(nc)]) == 1) + solver.Add(solver.Sum([x[i, c] for c in range(nc)]) == 1) # adjacent nodes cannot be assigned the same color # (and adjust to 0-based) for i in range(num_edges): - for c in range(nc): - solver.Add(x[E[i][0]-1,c] + x[E[i][1]-1,c] <= u[c]) - - + for c in range(nc): + solver.Add(x[E[i][0] - 1, c] + x[E[i][1] - 1, c] <= u[c]) # objective objective = solver.Minimize(obj) @@ -143,23 +139,22 @@ def main(sol = 'GLPK'): solver.Solve() print - print "number of colors:", int(solver.Objective().Value()) - print "colors used:", [int(u[i].SolutionValue()) for i in range(nc)] + print 'number of colors:', int(solver.Objective().Value()) + print 'colors used:', [int(u[i].SolutionValue()) for i in range(nc)] print for v in V: print 'v%i' % v, ' color ', for c in range(nc): - if int(x[v,c].SolutionValue()) == 1: + if int(x[v, c].SolutionValue()) == 1: print c print - print "WallTime:", solver.WallTime() + print 'WallTime:', solver.WallTime() if sol == 'CBC': print 'iterations:', solver.Iterations() - if __name__ == '__main__': sol = 'GLPK' diff --git a/examples/python/combinatorial_auction2.py b/examples/python/combinatorial_auction2.py index 003e73adb6..a8cc840de6 100644 --- a/examples/python/combinatorial_auction2.py +++ b/examples/python/combinatorial_auction2.py @@ -28,84 +28,85 @@ * Gecode: http://hakank.org/gecode/combinatorial_auction.cpp This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ -import sys,string +import sys +import string from collections import * from ortools.constraint_solver import pywrapcp def main(): - # Create the solver. - solver = pywrapcp.Solver('Problem') + # Create the solver. + solver = pywrapcp.Solver("Problem") - # - # data - # - N = 5 + # + # data + # + N = 5 - # the items for each bid - items = [ - [0,1], # A,B - [0,2], # A, C - [1,3], # B,D - [1,2,3], # B,C,D - [0] # A - ] - # collect the bids for each item - items_t = defaultdict(list) + # the items for each bid + items = [ + [0, 1], # A,B + [0, 2], # A, C + [1, 3], # B,D + [1, 2, 3], # B,C,D + [0] # A + ] + # collect the bids for each item + items_t = defaultdict(list) - # [items_t.setdefault(j,[]).append(i) for i in range(N) for j in items[i] ] - # nicer: - [items_t[j].append(i) for i in range(N) for j in items[i] ] + # [items_t.setdefault(j,[]).append(i) for i in range(N) for j in items[i] ] + # nicer: + [items_t[j].append(i) for i in range(N) for j in items[i]] - bid_amount = [10,20,30,40,14] + bid_amount = [10, 20, 30, 40, 14] - # - # declare variables - # - X = [solver.BoolVar("x%i"%i) for i in range(N)] - obj = solver.IntVar(0,100,'obj') + # + # declare variables + # + X = [solver.BoolVar("x%i" % i) for i in range(N)] + obj = solver.IntVar(0, 100, "obj") - # - # constraints - # - solver.Add(obj == solver.ScalProd(X,bid_amount)) - for item in items_t: - solver.Add(solver.Sum([X[bid] for bid in items_t[item]]) <= 1) + # + # constraints + # + solver.Add(obj == solver.ScalProd(X, bid_amount)) + for item in items_t: + solver.Add(solver.Sum([X[bid] for bid in items_t[item]]) <= 1) + # objective + objective = solver.Maximize(obj, 1) - # objective - objective = solver.Maximize(obj, 1) + # + # solution and search + # + solution = solver.Assignment() + solution.Add(X) + solution.Add(obj) - # - # solution and search - # - solution = solver.Assignment() - solution.Add(X) - solution.Add(obj) - - # db: DecisionBuilder - db = solver.Phase(X, - solver.CHOOSE_FIRST_UNBOUND, - solver.ASSIGN_MIN_VALUE) - - solver.NewSearch(db,[objective]) - num_solutions = 0 - while solver.NextSolution(): - print "X:", [X[i].Value() for i in range(N)] - print "obj:", obj.Value() - print - num_solutions += 1 - - solver.EndSearch() + # db: DecisionBuilder + db = solver.Phase(X, + solver.CHOOSE_FIRST_UNBOUND, + solver.ASSIGN_MIN_VALUE) + solver.NewSearch(db, [objective]) + num_solutions = 0 + while solver.NextSolution(): + print "X:", [X[i].Value() for i in range(N)] + print "obj:", obj.Value() print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + num_solutions += 1 -if __name__ == '__main__': - main() + solver.EndSearch() + + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() + +if __name__ == "__main__": + main() diff --git a/examples/python/contiguity_regular.py b/examples/python/contiguity_regular.py index 8959cb76cb..fe0a6452ad 100644 --- a/examples/python/contiguity_regular.py +++ b/examples/python/contiguity_regular.py @@ -1,16 +1,16 @@ # Copyright 2010 Hakan Kjellerstrand hakank@bonetmail.com # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at # -# http://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. """ @@ -22,22 +22,23 @@ From Global Constraint Catalogue http://www.emn.fr/x-info/sdemasse/gccat/Cglobal_contiguity.html ''' - Enforce all variables of the VARIABLES collection to be assigned to 0 or 1. + Enforce all variables of the VARIABLES collection to be assigned to 0 or 1. In addition, all variables assigned to value 1 appear contiguously. - + Example: (<0, 1, 1, 0>) - The global_contiguity constraint holds since the sequence 0 1 1 0 contains + The global_contiguity constraint holds since the sequence 0 1 1 0 contains no more than one group of contiguous 1. ''' - + Compare with the following model: * MiniZinc: http://www.hakank.org/minizinc/contiguity_regular.mzn This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ - + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ + """ from ortools.constraint_solver import pywrapcp @@ -45,7 +46,7 @@ from ortools.constraint_solver import pywrapcp # # Global constraint regular # -# This is a translation of MiniZinc's regular constraint (defined in +# This is a translation of MiniZinc's regular constraint (defined in # lib/zinc/globals.mzn), via the Comet code refered above. # All comments are from the MiniZinc code. # ''' @@ -62,116 +63,116 @@ from ortools.constraint_solver import pywrapcp # d : transition matrix # q0: initial state # F : accepting states + + def regular(x, Q, S, d, q0, F): - solver = x[0].solver() - - assert Q > 0, 'regular: "Q" must be greater than zero' - assert S > 0, 'regular: "S" must be greater than zero' + solver = x[0].solver() - # d2 is the same as d, except we add one extra transition for - # each possible input; each extra transition is from state zero - # to state zero. This allows us to continue even if we hit a - # non-accepted input. - - # Comet: int d2[0..Q, 1..S] - d2 = [] - for i in range(Q+1): - row = [] - for j in range(S): - if i == 0: - row.append(0) - else: - row.append(d[i-1][j]) - d2.append(row) + assert Q > 0, 'regular: "Q" must be greater than zero' + assert S > 0, 'regular: "S" must be greater than zero' - d2_flatten = [d2[i][j] for i in range(Q+1) for j in range(S)] + # d2 is the same as d, except we add one extra transition for + # each possible input; each extra transition is from state zero + # to state zero. This allows us to continue even if we hit a + # non-accepted input. - # If x has index set m..n, then a[m-1] holds the initial state - # (q0), and a[i+1] holds the state we're in after processing - # x[i]. If a[n] is in F, then we succeed (ie. accept the - # string). - x_range = range(0,len(x)) - m = 0 - n = len(x) - - a = [solver.IntVar(0, Q+1, 'a[%i]' % i) for i in range(m, n+1)] - - # Check that the final state is in F - solver.Add(solver.MemberCt(a[-1], F)) - # First state is q0 - solver.Add(a[m] == q0) - for i in x_range: - solver.Add(x[i] >= 1) - solver.Add(x[i] <= S) - - # Determine a[i+1]: a[i+1] == d2[a[i], x[i]] - solver.Add(a[i+1] == solver.Element(d2_flatten, ((a[i])*S)+(x[i]-1))) + # Comet: int d2[0..Q, 1..S] + d2 = [] + for i in range(Q + 1): + row = [] + for j in range(S): + if i == 0: + row.append(0) + else: + row.append(d[i - 1][j]) + d2.append(row) - + d2_flatten = [d2[i][j] for i in range(Q + 1) for j in range(S)] + + # If x has index set m..n, then a[m-1] holds the initial state + # (q0), and a[i+1] holds the state we're in after processing + # x[i]. If a[n] is in F, then we succeed (ie. accept the + # string). + x_range = range(0, len(x)) + m = 0 + n = len(x) + + a = [solver.IntVar(0, Q + 1, 'a[%i]' % i) for i in range(m, n + 1)] + + # Check that the final state is in F + solver.Add(solver.MemberCt(a[-1], F)) + # First state is q0 + solver.Add(a[m] == q0) + for i in x_range: + solver.Add(x[i] >= 1) + solver.Add(x[i] <= S) + + # Determine a[i+1]: a[i+1] == d2[a[i], x[i]] + solver.Add( + a[i + 1] == solver.Element(d2_flatten, ((a[i]) * S) + (x[i] - 1))) def main(): - - # Create the solver. - solver = pywrapcp.Solver('Global contiguity using regular') - # - # data - # - # the DFA (for regular) - n_states = 3 - input_max = 2 - initial_state = 1 # 0 is for the failing state - - # all states are accepting states - accepting_states = [1,2,3] + # Create the solver. + solver = pywrapcp.Solver('Global contiguity using regular') - # The regular expression 0*1*0* - transition_fn = [ - [1,2], # state 1 (start): input 0 -> state 1, input 1 -> state 2 i.e. 0* - [3,2], # state 2: 1* - [3,0], # state 3: 0* - ] + # + # data + # + # the DFA (for regular) + n_states = 3 + input_max = 2 + initial_state = 1 # 0 is for the failing state - n = 7 + # all states are accepting states + accepting_states = [1, 2, 3] - # - # declare variables - # + # The regular expression 0*1*0* + transition_fn = [ + [1, 2], # state 1 (start): input 0 -> state 1, input 1 -> state 2 i.e. 0* + [3, 2], # state 2: 1* + [3, 0], # state 3: 0* + ] - # We use 1..2 and subtract 1 in the solution - reg_input = [solver.IntVar(1, 2, 'x[%i]'% i) for i in range(n)] + n = 7 + # + # declare variables + # - # - # constraints - # - regular(reg_input, n_states, input_max, transition_fn, - initial_state, accepting_states) - - # - # solution and search - # - db = solver.Phase(reg_input, - solver.CHOOSE_FIRST_UNBOUND, - solver.ASSIGN_MIN_VALUE) + # We use 1..2 and subtract 1 in the solution + reg_input = [solver.IntVar(1, 2, 'x[%i]' % i) for i in range(n)] - solver.NewSearch(db) - - num_solutions = 0 - while solver.NextSolution(): - num_solutions += 1 - # Note: here we subract 1 from the solution - print 'reg_input:', [reg_input[i].Value()-1 for i in range(n)] - - solver.EndSearch() - print - print 'num_solutions:', num_solutions - print 'failures:', solver.Failures() - print 'branches:', solver.Branches() - print 'wall_time:', solver.WallTime(), 'ms' + # + # constraints + # + regular(reg_input, n_states, input_max, transition_fn, + initial_state, accepting_states) + + # + # solution and search + # + db = solver.Phase(reg_input, + solver.CHOOSE_FIRST_UNBOUND, + solver.ASSIGN_MIN_VALUE) + + solver.NewSearch(db) + + num_solutions = 0 + while solver.NextSolution(): + num_solutions += 1 + # Note: here we subract 1 from the solution + print 'reg_input:', [reg_input[i].Value() - 1 for i in range(n)] + + solver.EndSearch() + print + print 'num_solutions:', num_solutions + print 'failures:', solver.Failures() + print 'branches:', solver.Branches() + print 'wall_time:', solver.WallTime(), 'ms' if __name__ == '__main__': - main() + main() diff --git a/examples/python/costas_array.py b/examples/python/costas_array.py index 62f62f0bc6..9536c261c1 100644 --- a/examples/python/costas_array.py +++ b/examples/python/costas_array.py @@ -41,10 +41,10 @@ the array, e.g. those listed in http://mathworld.wolfram.com/CostasArray.html - 1 1 (1) - 2 2 (1, 2), (2,1) - 3 4 (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2) - 4 12 (1, 2, 4, 3), (1, 3, 4, 2), (1, 4, 2, 3), (2, 1, 3, 4), + 1 1 (1) + 2 2 (1, 2), (2,1) + 3 4 (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2) + 4 12 (1, 2, 4, 3), (1, 3, 4, 2), (1, 4, 2, 3), (2, 1, 3, 4), (2, 3, 1, 4), (2, 4, 3, 1), (3, 1, 2, 4), (3, 2, 4, 1), (3, 4, 2, 1), (4, 1, 3, 2), (4, 2, 1, 3), (4, 3, 1, 2) .... @@ -57,7 +57,8 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ import sys import string @@ -67,109 +68,105 @@ from ortools.constraint_solver import pywrapcp def main(n=6): - # Create the solver. - solver = pywrapcp.Solver('Costas array') + # Create the solver. + solver = pywrapcp.Solver("Costas array") - # - # data - # - print "n:", n + # + # data + # + print "n:", n - # - # declare variables - # - costas = [solver.IntVar(1, n, "costas[%i]"%i) for i in range(n)] - differences = {} + # + # declare variables + # + costas = [solver.IntVar(1, n, "costas[%i]" % i) for i in range(n)] + differences = {} + for i in range(n): + for j in range(n): + differences[(i, j)] = solver.IntVar(-n + 1, n - 1, + "differences[%i,%i]" % (i, j)) + differences_flat = [differences[i, j] for i in range(n) for j in range(n)] + + # + # constraints + # + + # Fix the values in the lower triangle in the + # difference matrix to -n+1. This removes variants + # of the difference matrix for the the same Costas array. + for i in range(n): + for j in range(i + 1): + solver.Add(differences[i, j] == -n + 1) + + # hakank: All the following constraints are from + # Barry O'Sullivans's original model. + # + solver.Add(solver.AllDifferent(costas)) + + # "How do the positions in the Costas array relate + # to the elements of the distance triangle." + for i in range(n): + for j in range(n): + if i < j: + solver.Add(differences[(i, j)] == costas[j] - costas[j - i - 1]) + + # "All entries in a particular row of the difference + # triangle must be distint." + for i in range(n - 2): + solver.Add(solver.AllDifferent([differences[i, j] + for j in range(n) if j > i])) + + # + # "All the following are redundant - only here to speed up search." + # + + # "We can never place a 'token' in the same row as any other." + for i in range(n): + for j in range(n): + if i < j: + solver.Add(differences[i, j] != 0) + + for k in range(2, n): + for l in range(2, n): + if k < l: + solver.Add(differences[k - 2, l - 1] + + differences[k, l] == + differences[k - 1, l - 1] + + differences[k - 1, l]) + + # + # search and result + # + db = solver.Phase(costas + differences_flat, + solver.CHOOSE_FIRST_UNBOUND, + solver.ASSIGN_MIN_VALUE) + + solver.NewSearch(db) + num_solutions = 0 + while solver.NextSolution(): + print "costas:", [costas[i].Value() for i in range(n)] + print "differences:" for i in range(n): - for j in range(n): - differences[(i,j)] = solver.IntVar(-n+1, n-1, - "differences[%i,%i]"%(i,j)) - differences_flat = [differences[i,j] for i in range(n) for j in range(n) ] - - # - # constraints - # - - # Fix the values in the lower triangle in the - # difference matrix to -n+1. This removes variants - # of the difference matrix for the the same Costas array. - for i in range(n): - for j in range(i+1): - solver.Add(differences[i,j] == -n+1) - - # hakank: All the following constraints are from - # Barry O'Sullivans's original model. - # - solver.Add(solver.AllDifferent(costas)) - - - # "How do the positions in the Costas array relate - # to the elements of the distance triangle." - for i in range(n): - for j in range(n): - if i < j: - solver.Add(differences[(i,j)] == costas[j] - costas[j-i-1]) - - - # "All entries in a particular row of the difference - # triangle must be distint." - for i in range(n-2): - solver.Add(solver.AllDifferent([differences[i,j] - for j in range(n) if j > i])) - - # - # "All the following are redundant - only here to speed up search." - # - - # "We can never place a 'token' in the same row as any other." - for i in range(n): - for j in range(n): - if i < j: - solver.Add(differences[i,j] != 0) - - - for k in range(2,n): - for l in range(2, n): - if k < l: - solver.Add(differences[k-2,l-1] + - differences[k,l] == - differences[k-1,l-1] + - differences[k-1,l]) - - - # - # search and result - # - db = solver.Phase(costas + differences_flat, - solver.CHOOSE_FIRST_UNBOUND, - solver.ASSIGN_MIN_VALUE) - - solver.NewSearch(db) - num_solutions = 0 - while solver.NextSolution(): - print "costas:", [costas[i].Value() for i in range(n)] - print "differences:" - for i in range(n): - for j in range(n): - v = differences[i,j].Value() - if v == -n+1: - print " ", - else: - print "%2d" % v, - print - print - num_solutions += 1 - - solver.EndSearch() - + for j in range(n): + v = differences[i, j].Value() + if v == -n + 1: + print " ", + else: + print "%2d" % v, + print print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + num_solutions += 1 + + solver.EndSearch() + + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() n = 6 -if __name__ == '__main__': - if len(sys.argv) > 1: - n = string.atoi(sys.argv[1]) - main(n) +if __name__ == "__main__": + if len(sys.argv) > 1: + n = string.atoi(sys.argv[1]) + main(n) diff --git a/examples/python/covering_opl.py b/examples/python/covering_opl.py index 00dabb5cc6..68d28993e3 100644 --- a/examples/python/covering_opl.py +++ b/examples/python/covering_opl.py @@ -53,7 +53,8 @@ * SICStus: http://hakank.org/sicstus/covering_opl.pl This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ import sys @@ -64,91 +65,89 @@ from ortools.constraint_solver import pywrapcp def main(): - # Create the solver. - solver = pywrapcp.Solver('Set covering') + # Create the solver. + solver = pywrapcp.Solver("Set covering") - # - # data - # - nb_workers = 32 - Workers = range(nb_workers) - num_tasks = 15 - Tasks = range(num_tasks) + # + # data + # + nb_workers = 32 + Workers = range(nb_workers) + num_tasks = 15 + Tasks = range(num_tasks) - # Which worker is qualified for each task. - # Note: This is 1-based and will be made 0-base below. - Qualified = [ - [ 1, 9, 19, 22, 25, 28, 31 ], - [ 2, 12, 15, 19, 21, 23, 27, 29, 30, 31, 32 ], - [ 3, 10, 19, 24, 26, 30, 32 ], - [ 4, 21, 25, 28, 32 ], - [ 5, 11, 16, 22, 23, 27, 31 ], - [ 6, 20, 24, 26, 30, 32 ], - [ 7, 12, 17, 25, 30, 31 ] , - [ 8, 17, 20, 22, 23 ], - [ 9, 13, 14, 26, 29, 30, 31 ], - [ 10, 21, 25, 31, 32 ], - [ 14, 15, 18, 23, 24, 27, 30, 32 ], - [ 18, 19, 22, 24, 26, 29, 31 ], - [ 11, 20, 25, 28, 30, 32 ], - [ 16, 19, 23, 31 ], - [ 9, 18, 26, 28, 31, 32 ] - ] + # Which worker is qualified for each task. + # Note: This is 1-based and will be made 0-base below. + Qualified = [ + [1, 9, 19, 22, 25, 28, 31], + [2, 12, 15, 19, 21, 23, 27, 29, 30, 31, 32], + [3, 10, 19, 24, 26, 30, 32], + [4, 21, 25, 28, 32], + [5, 11, 16, 22, 23, 27, 31], + [6, 20, 24, 26, 30, 32], + [7, 12, 17, 25, 30, 31], + [8, 17, 20, 22, 23], + [9, 13, 14, 26, 29, 30, 31], + [10, 21, 25, 31, 32], + [14, 15, 18, 23, 24, 27, 30, 32], + [18, 19, 22, 24, 26, 29, 31], + [11, 20, 25, 28, 30, 32], + [16, 19, 23, 31], + [9, 18, 26, 28, 31, 32] + ] - Cost = [1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 8, 9 ] + Cost = [ + 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, + 5, 5, 6, 6, 6, 7, 8, 9] + # + # variables + # + Hire = [solver.IntVar(0, 1, "Hire[%i]" % w) for w in Workers] + total_cost = solver.IntVar(0, nb_workers * sum(Cost), "total_cost") - # - # variables - # - Hire = [solver.IntVar(0, 1, 'Hire[%i]' % w) for w in Workers] - total_cost = solver.IntVar(0, nb_workers*sum(Cost), 'total_cost') + # + # constraints + # + solver.Add(total_cost == solver.ScalProd(Hire, Cost)) - # - # constraints - # - solver.Add(total_cost == solver.ScalProd(Hire, Cost)) + for j in Tasks: + # Sum the cost for hiring the qualified workers + # (also, make 0-base) + b = solver.Sum([Hire[c - 1] for c in Qualified[j]]) + solver.Add(b >= 1) - for j in Tasks: - # Sum the cost for hiring the qualified workers - # (also, make 0-base) - b = solver.Sum([Hire[c-1] for c in Qualified[j]]) - solver.Add(b >= 1) + # objective: Minimize total cost + objective = solver.Minimize(total_cost, 1) + # + # search and result + # + db = solver.Phase(Hire, + solver.CHOOSE_FIRST_UNBOUND, + solver.ASSIGN_MIN_VALUE) + solver.NewSearch(db, [objective]) - # objective: Minimize total cost - objective = solver.Minimize(total_cost, 1) - - # - # search and result - # - db = solver.Phase(Hire, - solver.CHOOSE_FIRST_UNBOUND, - solver.ASSIGN_MIN_VALUE) - - solver.NewSearch(db, [objective]) - - - num_solutions = 0 - while solver.NextSolution(): - num_solutions += 1 - print "Total cost", total_cost.Value() - print "We should hire these workers: ", - for w in Workers: - if Hire[w].Value() == 1: - print w, - print - print - - solver.EndSearch() - + num_solutions = 0 + while solver.NextSolution(): + num_solutions += 1 + print "Total cost", total_cost.Value() + print "We should hire these workers: ", + for w in Workers: + if Hire[w].Value() == 1: + print w, print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + print + + solver.EndSearch() + + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() -if __name__ == '__main__': - main() +if __name__ == "__main__": + main() diff --git a/examples/python/crew.py b/examples/python/crew.py index 10e3632c6e..97299033d1 100644 --- a/examples/python/crew.py +++ b/examples/python/crew.py @@ -35,190 +35,190 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ -import sys, string +import sys +import string from ortools.constraint_solver import pywrapcp + def main(sols=1): - # Create the solver. - solver = pywrapcp.Solver('Crew') + # Create the solver. + solver = pywrapcp.Solver("Crew") - # - # data - # - names = ["Tom", - "David", - "Jeremy", - "Ron", - "Joe", - "Bill", - "Fred", - "Bob", - "Mario", - "Ed", - "Carol", - "Janet", - "Tracy", - "Marilyn", - "Carolyn", - "Cathy", - "Inez", - "Jean", - "Heather", - "Juliet" - ] + # + # data + # + names = ["Tom", + "David", + "Jeremy", + "Ron", + "Joe", + "Bill", + "Fred", + "Bob", + "Mario", + "Ed", + "Carol", + "Janet", + "Tracy", + "Marilyn", + "Carolyn", + "Cathy", + "Inez", + "Jean", + "Heather", + "Juliet"] - num_persons = len(names) # number of persons + num_persons = len(names) # number of persons - attributes = [ - # steward, hostess, french, spanish, german - [1,0,0,0,1], # Tom = 1 - [1,0,0,0,0], # David = 2 - [1,0,0,0,1], # Jeremy = 3 - [1,0,0,0,0], # Ron = 4 - [1,0,0,1,0], # Joe = 5 - [1,0,1,1,0], # Bill = 6 - [1,0,0,1,0], # Fred = 7 - [1,0,0,0,0], # Bob = 8 - [1,0,0,1,1], # Mario = 9 - [1,0,0,0,0], # Ed = 10 - [0,1,0,0,0], # Carol = 11 - [0,1,0,0,0], # Janet = 12 - [0,1,0,0,0], # Tracy = 13 - [0,1,0,1,1], # Marilyn = 14 - [0,1,0,0,0], # Carolyn = 15 - [0,1,0,0,0], # Cathy = 16 - [0,1,1,1,1], # Inez = 17 - [0,1,1,0,0], # Jean = 18 - [0,1,0,1,1], # Heather = 19 - [0,1,1,0,0] # Juliet = 20 - ] + attributes = [ + # steward, hostess, french, spanish, german + [1, 0, 0, 0, 1], # Tom = 1 + [1, 0, 0, 0, 0], # David = 2 + [1, 0, 0, 0, 1], # Jeremy = 3 + [1, 0, 0, 0, 0], # Ron = 4 + [1, 0, 0, 1, 0], # Joe = 5 + [1, 0, 1, 1, 0], # Bill = 6 + [1, 0, 0, 1, 0], # Fred = 7 + [1, 0, 0, 0, 0], # Bob = 8 + [1, 0, 0, 1, 1], # Mario = 9 + [1, 0, 0, 0, 0], # Ed = 10 + [0, 1, 0, 0, 0], # Carol = 11 + [0, 1, 0, 0, 0], # Janet = 12 + [0, 1, 0, 0, 0], # Tracy = 13 + [0, 1, 0, 1, 1], # Marilyn = 14 + [0, 1, 0, 0, 0], # Carolyn = 15 + [0, 1, 0, 0, 0], # Cathy = 16 + [0, 1, 1, 1, 1], # Inez = 17 + [0, 1, 1, 0, 0], # Jean = 18 + [0, 1, 0, 1, 1], # Heather = 19 + [0, 1, 1, 0, 0] # Juliet = 20 + ] - # The columns are in the following order: - # staff : Overall number of cabin crew needed - # stewards : How many stewards are required - # hostesses : How many hostesses are required - # french : How many French speaking employees are required - # spanish : How many Spanish speaking employees are required - # german : How many German speaking employees are required - required_crew = [ - [4,1,1,1,1,1], # Flight 1 - [5,1,1,1,1,1], # Flight 2 - [5,1,1,1,1,1], # .. - [6,2,2,1,1,1], - [7,3,3,1,1,1], - [4,1,1,1,1,1], - [5,1,1,1,1,1], - [6,1,1,1,1,1], - [6,2,2,1,1,1], # ... - [7,3,3,1,1,1] # Flight 10 - ] + # The columns are in the following order: + # staff : Overall number of cabin crew needed + # stewards : How many stewards are required + # hostesses : How many hostesses are required + # french : How many French speaking employees are required + # spanish : How many Spanish speaking employees are required + # german : How many German speaking employees are required + required_crew = [ + [4, 1, 1, 1, 1, 1], # Flight 1 + [5, 1, 1, 1, 1, 1], # Flight 2 + [5, 1, 1, 1, 1, 1], # .. + [6, 2, 2, 1, 1, 1], + [7, 3, 3, 1, 1, 1], + [4, 1, 1, 1, 1, 1], + [5, 1, 1, 1, 1, 1], + [6, 1, 1, 1, 1, 1], + [6, 2, 2, 1, 1, 1], # ... + [7, 3, 3, 1, 1, 1] # Flight 10 + ] - num_flights = len(required_crew) # number of flights + num_flights = len(required_crew) # number of flights - # - # declare variables - # - crew = {} + # + # declare variables + # + crew = {} + for i in range(num_flights): + for j in range(num_persons): + crew[(i, j)] = solver.IntVar(0, 1, "crew[%i,%i]" % (i, j)) + crew_flat = [crew[(i, j)] for i in range(num_flights) + for j in range(num_persons)] + + # number of working persons + num_working = solver.IntVar(1, num_persons, "num_working") + + # + # constraints + # + + # number of working persons + solver.Add(num_working == solver.Sum( + [solver.IsGreaterOrEqualCstVar(solver.Sum([crew[(f, p)] + for f in range(num_flights)]), 1) + for p in range(num_persons)])) + + for f in range(num_flights): + # size of crew + tmp = [crew[(f, i)] for i in range(num_persons)] + solver.Add(solver.Sum(tmp) == required_crew[f][0]) + + # attributes and requirements + for j in range(5): + tmp = [attributes[i][j] * crew[(f, i)] for i in range(num_persons)] + solver.Add(solver.Sum(tmp) >= required_crew[f][j + 1]) + + # after a flight, break for at least two flights + for f in range(num_flights - 2): + for i in range(num_persons): + solver.Add(crew[f, i] + crew[f + 1, i] + crew[f + 2, i] <= 1) + + # extra contraint: all must work at least two of the flights + # for i in range(num_persons): + # [solver.Add(solver.Sum([crew[f,i] for f in range(num_flights)]) >= 2) ] + + # + # solution and search + # + solution = solver.Assignment() + solution.Add(crew_flat) + solution.Add(num_working) + + db = solver.Phase(crew_flat, + solver.CHOOSE_FIRST_UNBOUND, + solver.ASSIGN_MIN_VALUE) + + # + # result + # + solver.NewSearch(db) + num_solutions = 0 + while solver.NextSolution(): + num_solutions += 1 + print "Solution #%i" % num_solutions + print "Number working:", num_working.Value() for i in range(num_flights): - for j in range(num_persons): - crew[(i,j)] = solver.IntVar(0, 1, 'crew[%i,%i]' % (i, j)) - crew_flat = [crew[(i,j)] for i in range(num_flights) for j in range(num_persons)] - - # number of working persons - num_working = solver.IntVar(1, num_persons, 'num_working') - - - # - # constraints - # - - # number of working persons - solver.Add(num_working == solver.Sum( - [solver.IsGreaterOrEqualCstVar(solver.Sum([crew[(f,p)] - for f in range(num_flights)]), 1) - for p in range(num_persons) ]) ) - - for f in range(num_flights): - # size of crew - tmp = [crew[(f,i)] for i in range(num_persons)] - solver.Add(solver.Sum(tmp) == required_crew[f][0]) - - # attributes and requirements - for j in range(5): - tmp = [attributes[i][j]*crew[(f,i)] for i in range(num_persons) ] - solver.Add(solver.Sum(tmp) >= required_crew[f][j+1]) - - - # after a flight, break for at least two flights - for f in range(num_flights-2): - for i in range(num_persons): - solver.Add(crew[f,i] + crew[f+1,i] + crew[f+2,i] <= 1) - - # extra contraint: all must work at least two of the flights - # for i in range(num_persons): - # [solver.Add(solver.Sum([crew[f,i] for f in range(num_flights)]) >= 2) ] - - - # - # solution and search - # - solution = solver.Assignment() - solution.Add(crew_flat) - solution.Add(num_working) - - db = solver.Phase(crew_flat, - solver.CHOOSE_FIRST_UNBOUND, - solver.ASSIGN_MIN_VALUE) - - # - # result - # - solver.NewSearch(db) - num_solutions = 0 - while solver.NextSolution(): - num_solutions += 1 - print "Solution #%i" % num_solutions - print "Number working:", num_working.Value() - for i in range(num_flights): - for j in range(num_persons): - print crew[i,j].Value(), - print - print - - print "Flights:" - for flight in range(num_flights): - print "Flight", flight, "persons:", - for person in range(num_persons): - if crew[flight, person].Value() == 1: - print names[person], - print - print - - print "Crew:" - for person in range(num_persons): - print "%-10s flights" % names[person], - for flight in range(num_flights): - if crew[flight, person].Value() == 1: - print flight, - print - print - - if num_solutions >= sols: - break - solver.EndSearch() - + for j in range(num_persons): + print crew[i, j].Value(), + print print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + + print "Flights:" + for flight in range(num_flights): + print "Flight", flight, "persons:", + for person in range(num_persons): + if crew[flight, person].Value() == 1: + print names[person], + print + print + + print "Crew:" + for person in range(num_persons): + print "%-10s flights" % names[person], + for flight in range(num_flights): + if crew[flight, person].Value() == 1: + print flight, + print + print + + if num_solutions >= sols: + break + solver.EndSearch() + + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() num_solutions_to_show = 1 -if __name__ == '__main__': - if (len(sys.argv) > 1): - num_solutions_to_show = string.atoi(sys.argv[1]) +if __name__ == "__main__": + if (len(sys.argv) > 1): + num_solutions_to_show = string.atoi(sys.argv[1]) - main(num_solutions_to_show) + main(num_solutions_to_show) diff --git a/examples/python/crossword2.py b/examples/python/crossword2.py index 5084123d01..685258ec49 100644 --- a/examples/python/crossword2.py +++ b/examples/python/crossword2.py @@ -39,7 +39,8 @@ that will start at those locations. ''' - The model was inspired by Sebastian Brand's Array Constraint cross word example + The model was inspired by Sebastian Brand's Array Constraint cross word + example http://www.cs.mu.oz.au/~sbrand/project/ac/ http://www.cs.mu.oz.au/~sbrand/project/ac/examples.pl @@ -53,7 +54,8 @@ * Zinc: http://hakank.org/minizinc/crossword2.zinc This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ from google.apputils import app @@ -61,121 +63,141 @@ from ortools.constraint_solver import pywrapcp def main(_): - # Create the solver. - solver = pywrapcp.Solver('Problem') + # Create the solver. + solver = pywrapcp.Solver("Problem") - # - # data - # - alpha = "_abcdefghijklmnopqrstuvwxyz"; - a=1; b=2; c=3; d=4; e=5; f=6; g=7; h=8; i=9; - j=10; k=11; l=12; m=13; n=14; o=15; p=16; - q=17; r=18; s=19; t=20; u=21; v=22; w=23; - x=24; y=25; z=26; + # + # data + # + alpha = "_abcdefghijklmnopqrstuvwxyz" + a = 1 + b = 2 + c = 3 + d = 4 + e = 5 + f = 6 + g = 7 + h = 8 + i = 9 + j = 10 + k = 11 + l = 12 + m = 13 + n = 14 + o = 15 + p = 16 + q = 17 + r = 18 + s = 19 + t = 20 + u = 21 + v = 22 + w = 23 + x = 24 + y = 25 + z = 26 - num_words = 15 - word_len = 5; - AA = [ - [h, o, s, e, s], # HOSES - [l, a, s, e, r], # LASER - [s, a, i, l, s], # SAILS - [s, h, e, e, t], # SHEET - [s, t, e, e, r], # STEER - [h, e, e, l, 0], # HEEL - [h, i, k, e, 0], # HIKE - [k, e, e, l, 0], # KEEL - [k, n, o, t, 0], # KNOT - [l, i, n, e, 0], # LINE - [a, f, t, 0, 0], # AFT - [a, l, e, 0, 0], # ALE - [e, e, l, 0, 0], # EEL - [l, e, e, 0, 0], # LEE - [t, i, e, 0, 0] # TIE - ] + num_words = 15 + word_len = 5 + AA = [ + [h, o, s, e, s], # HOSES + [l, a, s, e, r], # LASER + [s, a, i, l, s], # SAILS + [s, h, e, e, t], # SHEET + [s, t, e, e, r], # STEER + [h, e, e, l, 0], # HEEL + [h, i, k, e, 0], # HIKE + [k, e, e, l, 0], # KEEL + [k, n, o, t, 0], # KNOT + [l, i, n, e, 0], # LINE + [a, f, t, 0, 0], # AFT + [a, l, e, 0, 0], # ALE + [e, e, l, 0, 0], # EEL + [l, e, e, 0, 0], # LEE + [t, i, e, 0, 0] # TIE + ] - num_overlapping = 12 - overlapping = [ - [0, 2, 1, 0], # s - [0, 4, 2, 0], # s + num_overlapping = 12 + overlapping = [ + [0, 2, 1, 0], # s + [0, 4, 2, 0], # s - [3, 1, 1, 2], # i - [3, 2, 4, 0], # k - [3, 3, 2, 2], # e + [3, 1, 1, 2], # i + [3, 2, 4, 0], # k + [3, 3, 2, 2], # e - [6, 0, 1, 3], # l - [6, 1, 4, 1], # e - [6, 2, 2, 3], # e + [6, 0, 1, 3], # l + [6, 1, 4, 1], # e + [6, 2, 2, 3], # e - [7, 0, 5, 1], # l - [7, 2, 1, 4], # s - [7, 3, 4, 2], # e - [7, 4, 2, 4] # r - ] + [7, 0, 5, 1], # l + [7, 2, 1, 4], # s + [7, 3, 4, 2], # e + [7, 4, 2, 4] # r + ] - n = 8 + n = 8 - # declare variables - A = {} - for I in range(num_words): - for J in range(word_len): - A[(I,J)] = solver.IntVar(0,26, 'A(%i,%i)' % (I, J)) + # declare variables + A = {} + for I in range(num_words): + for J in range(word_len): + A[(I, J)] = solver.IntVar(0, 26, "A(%i,%i)" % (I, J)) - A_flat = [A[(I,J)] for I in range(num_words) for J in range(word_len)] - E = [solver.IntVar(0, num_words, "E%i"%I) for I in range(n)] + A_flat = [A[(I, J)] for I in range(num_words) for J in range(word_len)] + E = [solver.IntVar(0, num_words, "E%i" % I) for I in range(n)] + # + # constraints + # + solver.Add(solver.AllDifferent(E)) - # - # constraints - # - solver.Add(solver.AllDifferent(E)) + for I in range(num_words): + for J in range(word_len): + solver.Add(A[(I, J)] == AA[I][J]) - for I in range(num_words): - for J in range(word_len): - solver.Add(A[(I,J)] == AA[I][J]) + for I in range(num_overlapping): + # This is what I would do: + # solver.Add(A[(E[overlapping[I][0]], overlapping[I][1])] == A[(E[overlapping[I][2]], overlapping[I][3])]) - for I in range(num_overlapping): - # This is what I would do: - # solver.Add(A[(E[overlapping[I][0]], overlapping[I][1])] == A[(E[overlapping[I][2]], overlapping[I][3])]) + # But we must use Element explicitly + solver.Add( + solver.Element( + A_flat, E[overlapping[I][0]] * word_len + overlapping[I][1]) == + solver.Element( + A_flat, E[overlapping[I][2]] * word_len + overlapping[I][3])) - # But we must use Element explicitly - solver.Add( - solver.Element(A_flat,E[overlapping[I][0]]*word_len+overlapping[I][1]) - == - solver.Element(A_flat,E[overlapping[I][2]]*word_len+overlapping[I][3])) + # + # solution and search + # + solution = solver.Assignment() + solution.Add(E) + # db: DecisionBuilder + db = solver.Phase(E + A_flat, + solver.INT_VAR_SIMPLE, + solver.ASSIGN_MIN_VALUE) - # - # solution and search - # - solution = solver.Assignment() - solution.Add(E) + solver.NewSearch(db) + num_solutions = 0 + while solver.NextSolution(): + print E + print_solution(A, E, alpha, n, word_len) + num_solutions += 1 + solver.EndSearch() - # db: DecisionBuilder - db = solver.Phase(E + A_flat, - solver.INT_VAR_SIMPLE, - solver.ASSIGN_MIN_VALUE) - - solver.NewSearch(db) - num_solutions = 0 - while solver.NextSolution(): - print E - print_solution(A,E,alpha, n, word_len) - num_solutions += 1 - solver.EndSearch() - - print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() def print_solution(A, E, alpha, n, word_len): - for ee in range(n): - print "%i: (%2i)" % (ee,E[ee].Value()), - print "".join(["%s" % (alpha[A[ee,ii].Value()]) for ii in range(word_len)]) + for ee in range(n): + print "%i: (%2i)" % (ee, E[ee].Value()), + print "".join(["%s" % (alpha[A[ee, ii].Value()]) for ii in range(word_len)]) - -if __name__ == '__main__': +if __name__ == "__main__": app.run() diff --git a/examples/python/crypta.py b/examples/python/crypta.py index 521f515437..8de60489c6 100644 --- a/examples/python/crypta.py +++ b/examples/python/crypta.py @@ -41,7 +41,8 @@ * SICStus: http://hakank.org/sicstus/crypta.pl This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ from ortools.constraint_solver import pywrapcp @@ -49,71 +50,67 @@ from ortools.constraint_solver import pywrapcp def main(): - # Create the solver. - solver = pywrapcp.Solver('Crypta') + # Create the solver. + solver = pywrapcp.Solver("Crypta") - # - # data - # + # + # data + # - # - # variables - # - LD = [solver.IntVar(0, 9, 'LD[%i]' % i) for i in range(0,10)] - A,B,C,D,E,F,G,H,I,J = LD + # + # variables + # + LD = [solver.IntVar(0, 9, "LD[%i]" % i) for i in range(0, 10)] + A, B, C, D, E, F, G, H, I, J = LD - Sr1 = solver.IntVar(0, 1, 'Sr1') - Sr2 = solver.IntVar(0, 1, 'Sr2') + Sr1 = solver.IntVar(0, 1, "Sr1") + Sr2 = solver.IntVar(0, 1, "Sr2") - # - # constraints - # - solver.Add(solver.AllDifferent(LD)) - solver.Add(B >= 1) - solver.Add(D >= 1) - solver.Add(G >= 1) + # + # constraints + # + solver.Add(solver.AllDifferent(LD)) + solver.Add(B >= 1) + solver.Add(D >= 1) + solver.Add(G >= 1) - solver.Add(A+10*E+100*J+1000*B+10000*B+100000*E+1000000*F+ - E+10*J+100*E+1000*F+10000*G+100000*A+1000000*F - == F+10*E+100*E+1000*H+10000*I+100000*F+1000000*B+10000000*Sr1) + solver.Add(A + 10 * E + 100 * J + 1000 * B + 10000 * B + 100000 * E + 1000000 * F + + E + 10 * J + 100 * E + 1000 * F + 10000 * G + 100000 * A + 1000000 * F + == F + 10 * E + 100 * E + 1000 * H + 10000 * I + 100000 * F + 1000000 * B + 10000000 * Sr1) + solver.Add(C + 10 * F + 100 * H + 1000 * A + 10000 * I + 100000 * I + 1000000 * J + + F + 10 * I + 100 * B + 1000 * D + 10000 * I + 100000 * D + 1000000 * C + Sr1 + == J + 10 * F + 100 * A + 1000 * F + 10000 * H + 100000 * D + 1000000 * D + 10000000 * Sr2) - solver.Add(C+10*F+100*H+1000*A+10000*I+100000*I+1000000*J+ - F+10*I+100*B+1000*D+10000*I+100000*D+1000000*C+Sr1 - == J+10*F+100*A+1000*F+10000*H+100000*D+1000000*D+10000000*Sr2) + solver.Add(A + 10 * J + 100 * J + 1000 * I + 10000 * A + 100000 * B + + B + 10 * A + 100 * G + 1000 * F + 10000 * H + 100000 * D + Sr2 + == C + 10 * A + 100 * G + 1000 * E + 10000 * J + 100000 * G) + # + # search and result + # + db = solver.Phase(LD, + solver.INT_VAR_SIMPLE, + solver.INT_VALUE_SIMPLE) - solver.Add(A+10*J+100*J+1000*I+10000*A+100000*B+ - B+10*A+100*G+1000*F+10000*H+100000*D+Sr2 - == C+10*A+100*G+1000*E+10000*J+100000*G) - - - # - # search and result - # - db = solver.Phase(LD, - solver.INT_VAR_SIMPLE, - solver.INT_VALUE_SIMPLE) - - solver.NewSearch(db) - - - num_solutions = 0 - str = "ABCDEFGHIJ" - while solver.NextSolution(): - num_solutions += 1 - for (letter, val) in [(str[i], LD[i].Value()) for i in range(len(LD))]: - print "%s: %i" % (letter, val) - print - - solver.EndSearch() + solver.NewSearch(db) + num_solutions = 0 + str = "ABCDEFGHIJ" + while solver.NextSolution(): + num_solutions += 1 + for (letter, val) in [(str[i], LD[i].Value()) for i in range(len(LD))]: + print "%s: %i" % (letter, val) print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + + solver.EndSearch() + + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() -if __name__ == '__main__': - main() +if __name__ == "__main__": + main() diff --git a/examples/python/crypto.py b/examples/python/crypto.py index d1db3a3ee8..5800aace2d 100644 --- a/examples/python/crypto.py +++ b/examples/python/crypto.py @@ -40,7 +40,8 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ from ortools.constraint_solver import pywrapcp @@ -48,95 +49,91 @@ from ortools.constraint_solver import pywrapcp def main(): - # Create the solver. - solver = pywrapcp.Solver('Crypto problem') + # Create the solver. + solver = pywrapcp.Solver("Crypto problem") - # - # data - # - num_letters = 26 + # + # data + # + num_letters = 26 - BALLET = 45 - CELLO = 43 - CONCERT = 74 - FLUTE = 30 - FUGUE = 50 - GLEE = 66 - JAZZ = 58 - LYRE = 47 - OBOE = 53 - OPERA = 65 - POLKA = 59 - QUARTET = 50 - SAXOPHONE = 134 - SCALE = 51 - SOLO = 37 - SONG = 61 - SOPRANO = 82 - THEME = 72 - VIOLIN = 100 - WALTZ = 34 + BALLET = 45 + CELLO = 43 + CONCERT = 74 + FLUTE = 30 + FUGUE = 50 + GLEE = 66 + JAZZ = 58 + LYRE = 47 + OBOE = 53 + OPERA = 65 + POLKA = 59 + QUARTET = 50 + SAXOPHONE = 134 + SCALE = 51 + SOLO = 37 + SONG = 61 + SOPRANO = 82 + THEME = 72 + VIOLIN = 100 + WALTZ = 34 + # + # variables + # + LD = [solver.IntVar(1, num_letters, "LD[%i]" % i) for i in range(num_letters)] + A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z = LD - # - # variables - # - LD = [solver.IntVar(1, num_letters, 'LD[%i]' % i) for i in range(num_letters)] - A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z = LD + # + # constraints + # + solver.Add(solver.AllDifferent(LD)) + solver.Add(B + A + L + L + E + T == BALLET) + solver.Add(C + E + L + L + O == CELLO) + solver.Add(C + O + N + C + E + R + T == CONCERT) + solver.Add(F + L + U + T + E == FLUTE) + solver.Add(F + U + G + U + E == FUGUE) + solver.Add(G + L + E + E == GLEE) + solver.Add(J + A + Z + Z == JAZZ) + solver.Add(L + Y + R + E == LYRE) + solver.Add(O + B + O + E == OBOE) + solver.Add(O + P + E + R + A == OPERA) + solver.Add(P + O + L + K + A == POLKA) + solver.Add(Q + U + A + R + T + E + T == QUARTET) + solver.Add(S + A + X + O + P + H + O + N + E == SAXOPHONE) + solver.Add(S + C + A + L + E == SCALE) + solver.Add(S + O + L + O == SOLO) + solver.Add(S + O + N + G == SONG) + solver.Add(S + O + P + R + A + N + O == SOPRANO) + solver.Add(T + H + E + M + E == THEME) + solver.Add(V + I + O + L + I + N == VIOLIN) + solver.Add(W + A + L + T + Z == WALTZ) - # - # constraints - # - solver.Add(solver.AllDifferent(LD)) - solver.Add( B + A + L + L + E + T == BALLET) - solver.Add( C + E + L + L + O == CELLO) - solver.Add( C + O + N + C + E + R + T == CONCERT) - solver.Add( F + L + U + T + E == FLUTE) - solver.Add( F + U + G + U + E == FUGUE) - solver.Add( G + L + E + E == GLEE) - solver.Add( J + A + Z + Z == JAZZ) - solver.Add( L + Y + R + E == LYRE) - solver.Add( O + B + O + E == OBOE) - solver.Add( O + P + E + R + A == OPERA) - solver.Add( P + O + L + K + A == POLKA) - solver.Add( Q + U + A + R + T + E + T == QUARTET) - solver.Add(S + A + X + O + P + H + O + N + E == SAXOPHONE) - solver.Add( S + C + A + L + E == SCALE) - solver.Add( S + O + L + O == SOLO) - solver.Add( S + O + N + G == SONG) - solver.Add( S + O + P + R + A + N + O == SOPRANO) - solver.Add( T + H + E + M + E == THEME) - solver.Add( V + I + O + L + I + N == VIOLIN) - solver.Add( W + A + L + T + Z == WALTZ) + # + # search and result + # + db = solver.Phase(LD, + solver.CHOOSE_MIN_SIZE_LOWEST_MIN, + solver.ASSIGN_CENTER_VALUE) + solver.NewSearch(db) - - # - # search and result - # - db = solver.Phase(LD, - solver.CHOOSE_MIN_SIZE_LOWEST_MIN, - solver.ASSIGN_CENTER_VALUE) - - solver.NewSearch(db) - - - num_solutions = 0 - str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - while solver.NextSolution(): - num_solutions += 1 - for (letter, val) in [(str[i], LD[i].Value()) for i in range(num_letters)]: - print "%s: %i" % (letter, val) - print - - solver.EndSearch() - + num_solutions = 0 + str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + while solver.NextSolution(): + num_solutions += 1 + for (letter, val) in [(str[i], LD[i].Value()) for i in range(num_letters)]: + print "%s: %i" % (letter, val) print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + + solver.EndSearch() + + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() -if __name__ == '__main__': - main() +if __name__ == "__main__": + main() diff --git a/examples/python/curious_set_of_integers.py b/examples/python/curious_set_of_integers.py index 437ecae274..3b75f3efcd 100644 --- a/examples/python/curious_set_of_integers.py +++ b/examples/python/curious_set_of_integers.py @@ -56,75 +56,74 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ from ortools.constraint_solver import pywrapcp def decreasing(solver, x): - for i in range(len(x)-1): - solver.Add(x[i] <= x[i+1]) + for i in range(len(x) - 1): + solver.Add(x[i] <= x[i + 1]) + def main(): - # Create the solver. - solver = pywrapcp.Solver('Curious set of integers') + # Create the solver. + solver = pywrapcp.Solver("Curious set of integers") - # - # data - # - n = 5 - max_val = 10000 + # + # data + # + n = 5 + max_val = 10000 - # - # variables - # - x = [solver.IntVar(0, max_val, 'x[%i]' % i) for i in range(n)] + # + # variables + # + x = [solver.IntVar(0, max_val, "x[%i]" % i) for i in range(n)] - # - # constraints - # - solver.Add(solver.AllDifferent(x)) - decreasing(solver, x) + # + # constraints + # + solver.Add(solver.AllDifferent(x)) + decreasing(solver, x) - for i in range(n): - for j in range(n): - if i !=j: - p = solver.IntVar(0, max_val, "p[%i,%i]" % (i,j)) - solver.Add(p*p-1 == (x[i]*x[j])) + for i in range(n): + for j in range(n): + if i != j: + p = solver.IntVar(0, max_val, "p[%i,%i]" % (i, j)) + solver.Add(p * p - 1 == (x[i] * x[j])) + + # This is the original problem: + # Which is the fifth number? + v = [1, 3, 8, 120] + b = [solver.IsMemberVar(x[i], v) for i in range(n)] + solver.Add(solver.Sum(b) == 4) + + # + # search and result + # + db = solver.Phase(x, + solver.CHOOSE_MIN_SIZE_LOWEST_MIN, + solver.ASSIGN_MIN_VALUE) + + solver.NewSearch(db) + + num_solutions = 0 + while solver.NextSolution(): + num_solutions += 1 + print "x:", [x[i].Value() for i in range(n)] + + solver.EndSearch() + + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() - # This is the original problem: - # Which is the fifth number? - v = [1,3,8,120] - b = [solver.IsMemberVar(x[i], v) for i in range(n)] - solver.Add(solver.Sum(b) == 4) - - - # - # search and result - # - db = solver.Phase(x, - solver.CHOOSE_MIN_SIZE_LOWEST_MIN, - solver.ASSIGN_MIN_VALUE) - - solver.NewSearch(db) - - - num_solutions = 0 - while solver.NextSolution(): - num_solutions += 1 - print "x:", [x[i].Value() for i in range(n)] - - solver.EndSearch() - - print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() - - -if __name__ == '__main__': - main() +if __name__ == "__main__": + main() diff --git a/examples/python/debruijn_binary.py b/examples/python/debruijn_binary.py index 628be85558..46382d8371 100644 --- a/examples/python/debruijn_binary.py +++ b/examples/python/debruijn_binary.py @@ -16,8 +16,10 @@ de Bruijn sequences in Google CP Solver. - Implementation of de Bruijn sequences in Minizinc, both 'classical' and 'arbitrary'. - The 'arbitrary' version is when the length of the sequence (m here) is < base**n. + Implementation of de Bruijn sequences in Minizinc, both 'classical' and + 'arbitrary'. + The 'arbitrary' version is when the length of the sequence (m here) is < + base**n. Compare with the the web based programs: @@ -37,158 +39,159 @@ * JaCoP: http://hakank.org/JaCoP/DeBruijn.java This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ -import sys, string +import sys +import string from ortools.constraint_solver import pywrapcp # converts a number (s) <-> an array of numbers (t) in the specific base. + + def toNum(solver, t, s, base): - tlen = len(t) - solver.Add(s == solver.Sum([(base**(tlen-i-1))*t[i] for i in range(tlen)])) + tlen = len(t) + solver.Add( + s == solver.Sum([(base ** (tlen - i - 1)) * t[i] for i in range(tlen)])) def main(base=2, n=3, m=8): - # Create the solver. - solver = pywrapcp.Solver('de Bruijn sequences') + # Create the solver. + solver = pywrapcp.Solver("de Bruijn sequences") - # - # data - # - #base = 2 # the base to use, i.e. the alphabet 0..n-1 - #n = 3 # number of bits to use (n = 4 -> 0..base^n-1 = 0..2^4 -1, i.e. 0..15) - #m = base**n # the length of the sequence. For "arbitrary" de Bruijn sequences + # + # data + # + # base = 2 # the base to use, i.e. the alphabet 0..n-1 + # n = 3 # number of bits to use (n = 4 -> 0..base^n-1 = 0..2^4 -1, i.e. 0..15) + # m = base**n # the length of the sequence. For "arbitrary" de Bruijn + # sequences - # base = 4 - # n = 4 - # m = base**n + # base = 4 + # n = 4 + # m = base**n - ## harder problem - #base = 13 - #n = 4 - #m = 52 + # harder problem + #base = 13 + #n = 4 + #m = 52 + # for n = 4 with different value of base + # base = 2 0.030 seconds 16 failures + # base = 3 0.041 108 + # base = 4 0.070 384 + # base = 5 0.231 1000 + # base = 6 0.736 2160 + # base = 7 2.2 seconds 4116 + # base = 8 6 seconds 7168 + # base = 9 16 seconds 11664 + # base = 10 42 seconds 18000 + # base = 6 + # n = 4 + # m = base**n - # for n = 4 with different value of base - # base = 2 0.030 seconds 16 failures - # base = 3 0.041 108 - # base = 4 0.070 384 - # base = 5 0.231 1000 - # base = 6 0.736 2160 - # base = 7 2.2 seconds 4116 - # base = 8 6 seconds 7168 - # base = 9 16 seconds 11664 - # base = 10 42 seconds 18000 - # base = 6 - # n = 4 - # m = base**n + # if True then ensure that the number of occurrences of 0..base-1 is + # the same (and if m mod base = 0) + check_same_gcc = True - # if True then ensure that the number of occurrences of 0..base-1 is - # the same (and if m mod base = 0) - check_same_gcc = True + print "base: %i n: %i m: %i" % (base, n, m) + if check_same_gcc: + print "Checks gcc" - print "base: %i n: %i m: %i" % (base, n, m) - if check_same_gcc: - print "Checks gcc" + # declare variables + x = [solver.IntVar(0, (base ** n) - 1, "x%i" % i) for i in range(m)] + binary = {} + for i in range(m): + for j in range(n): + binary[(i, j)] = solver.IntVar(0, base - 1, "x_%i_%i" % (i, j)) + bin_code = [solver.IntVar(0, base - 1, "bin_code%i" % i) for i in range(m)] - # declare variables - x = [solver.IntVar(0,(base**n)-1, 'x%i' % i) for i in range(m)] - binary = {} - for i in range(m): - for j in range(n): - binary[(i,j)] = solver.IntVar(0,base-1, 'x_%i_%i' % (i, j)) + # + # constraints + # + #solver.Add(solver.AllDifferent([x[i] for i in range(m)])) + solver.Add(solver.AllDifferent(x)) - bin_code = [solver.IntVar(0,base-1, 'bin_code%i' % i) for i in range(m)] + # converts x <-> binary + for i in range(m): + t = [solver.IntVar(0, base - 1, "t_%i" % j) for j in range(n)] + toNum(solver, t, x[i], base) + for j in range(n): + solver.Add(binary[(i, j)] == t[j]) - # - # constraints - # - #solver.Add(solver.AllDifferent([x[i] for i in range(m)])) - solver.Add(solver.AllDifferent(x)) + # the de Bruijn condition + # the first elements in binary[i] is the same as the last + # elements in binary[i-i] + for i in range(1, m - 1): + for j in range(1, n - 1): + solver.Add(binary[(i - 1, j)] == binary[(i, j - 1)]) - # converts x <-> binary - for i in range(m): - t = [ solver.IntVar(0,base-1, 't_%i' % j) for j in range(n) ] - toNum(solver, t, x[i], base) - for j in range(n): - solver.Add(binary[(i,j)] == t[j]) + # ... and around the corner + for j in range(1, n): + solver.Add(binary[(m - 1, j)] == binary[(0, j - 1)]) + # converts binary -> bin_code + for i in range(m): + solver.Add(bin_code[i] == binary[(i, 0)]) - # the de Bruijn condition - # the first elements in binary[i] is the same as the last - # elements in binary[i-i] - for i in range(1,m-1): - for j in range(1,n-1): - solver.Add(binary[(i-1,j)] == binary[(i,j-1)] ) + # extra: ensure that all the numbers in the de Bruijn sequence + # (bin_code) has the same occurrences (if check_same_gcc is True + # and mathematically possible) + gcc = [solver.IntVar(0, m, "gcc%i" % i) for i in range(base)] + solver.Add(solver.Distribute(bin_code, range(base), gcc)) + if check_same_gcc and m % base == 0: + for i in range(1, base): + solver.Add(gcc[i] == gcc[i - 1]) - # ... and around the corner - for j in range(1,n): - solver.Add(binary[(m-1,j)] == binary[(0,j-1)]) + # + # solution and search + # + solution = solver.Assignment() + solution.Add([x[i] for i in range(m)]) + solution.Add([bin_code[i] for i in range(m)]) + # solution.Add([binary[(i,j)] for i in range(m) for j in range(n)]) + solution.Add([gcc[i] for i in range(base)]) - # converts binary -> bin_code - for i in range(m): - solver.Add(bin_code[i] == binary[(i,0)]) + db = solver.Phase([x[i] for i in range(m)] + [bin_code[i] for i in range(m)], + solver.CHOOSE_MIN_SIZE_LOWEST_MAX, + solver.ASSIGN_MIN_VALUE) - # extra: ensure that all the numbers in the de Bruijn sequence - # (bin_code) has the same occurrences (if check_same_gcc is True - # and mathematically possible) - gcc = [solver.IntVar(0,m,'gcc%i' %i) for i in range(base) ] - solver.Add(solver.Distribute(bin_code, range(base), gcc)) - if check_same_gcc and m % base == 0: - for i in range(1,base): - solver.Add(gcc[i] == gcc[i-1]) + num_solutions = 0 + solver.NewSearch(db) + num_solutions = 0 + while solver.NextSolution(): + num_solutions += 1 + print "\nSolution %i" % num_solutions + print "x:", [x[i].Value() for i in range(m)] + print "gcc:", [gcc[i].Value() for i in range(base)] + print "de Bruijn sequence:", [bin_code[i].Value() for i in range(m)] + # for i in range(m): + # for j in range(n): + # print binary[(i,j)].Value(), + # print + # print + solver.EndSearch() - # - # solution and search - # - solution = solver.Assignment() - solution.Add([x[i] for i in range(m)]) - solution.Add([bin_code[i] for i in range(m)]) - # solution.Add([binary[(i,j)] for i in range(m) for j in range(n)]) - solution.Add([gcc[i] for i in range(base)]) - - - db = solver.Phase([x[i] for i in range(m)] + [bin_code[i] for i in range(m)] , - solver.CHOOSE_MIN_SIZE_LOWEST_MAX, - solver.ASSIGN_MIN_VALUE) - - num_solutions = 0 - solver.NewSearch(db) - num_solutions = 0 - while solver.NextSolution(): - num_solutions += 1 - print "\nSolution %i" % num_solutions - print "x:", [x[i].Value() for i in range(m)] - print "gcc:", [gcc[i].Value() for i in range(base)] - print "de Bruijn sequence:", [bin_code[i].Value() for i in range(m)] - #for i in range(m): - # for j in range(n): - # print binary[(i,j)].Value(), - # print - #print - solver.EndSearch() - - if num_solutions == 0: - print "No solution found" - - print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + if num_solutions == 0: + print "No solution found" + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() base = 2 -n = 3 -m = base**n -if __name__ == '__main__': - if len(sys.argv) > 1: - base = string.atoi(sys.argv[1]) - if len(sys.argv) > 2: - n = string.atoi(sys.argv[2]) - if len(sys.argv) > 3: - m = string.atoi(sys.argv[3]) +n = 3 +m = base ** n +if __name__ == "__main__": + if len(sys.argv) > 1: + base = string.atoi(sys.argv[1]) + if len(sys.argv) > 2: + n = string.atoi(sys.argv[2]) + if len(sys.argv) > 3: + m = string.atoi(sys.argv[3]) - main(base, n, m) + main(base, n, m) diff --git a/examples/python/diet1.py b/examples/python/diet1.py index eea88c5add..827a2df183 100644 --- a/examples/python/diet1.py +++ b/examples/python/diet1.py @@ -41,46 +41,43 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ from ortools.constraint_solver import pywrapcp - def main(unused_argv): # Create the solver. - solver = pywrapcp.Solver('Diet') - + solver = pywrapcp.Solver("Diet") # # data # n = 4 - price = [ 50, 20, 30, 80] # in cents - limits = [500, 6, 10, 8] # requirements for each nutrition type + price = [50, 20, 30, 80] # in cents + limits = [500, 6, 10, 8] # requirements for each nutrition type # nutritions for each product - calories = [400, 200, 150, 500] - chocolate = [3,2,0,0] - sugar = [2,2,4,4] - fat = [2,4,1,5] - + calories = [400, 200, 150, 500] + chocolate = [3, 2, 0, 0] + sugar = [2, 2, 4, 4] + fat = [2, 4, 1, 5] # # declare variables # - x = [solver.IntVar(0, 100, 'x%d' % i) for i in range(n)] - cost = solver.IntVar(0,10000, 'cost') + x = [solver.IntVar(0, 100, "x%d" % i) for i in range(n)] + cost = solver.IntVar(0, 10000, "cost") # # constraints # - solver.Add(solver.Sum([x[i]*calories[i] for i in range(n)]) >= limits[0]) - solver.Add(solver.Sum([x[i]*chocolate[i] for i in range(n)]) >= limits[1]) - solver.Add(solver.Sum([x[i]*sugar[i] for i in range(n)]) >= limits[2]) - solver.Add(solver.Sum([x[i]*fat[i] for i in range(n)]) >= limits[3]) - + solver.Add(solver.Sum([x[i] * calories[i] for i in range(n)]) >= limits[0]) + solver.Add(solver.Sum([x[i] * chocolate[i] for i in range(n)]) >= limits[1]) + solver.Add(solver.Sum([x[i] * sugar[i] for i in range(n)]) >= limits[2]) + solver.Add(solver.Sum([x[i] * fat[i] for i in range(n)]) >= limits[3]) # objective objective = solver.Minimize(cost, 1) @@ -98,12 +95,12 @@ def main(unused_argv): solver.Solve(solver.Phase(x + [cost], solver.INT_VAR_SIMPLE, solver.ASSIGN_MIN_VALUE), - [objective, search_log, collector]) + [objective, search_log, collector]) # get the first (and only) solution print "cost:", collector.ObjectiveValue(0) - print [("abcdefghij"[i],collector.Value(0, x[i])) for i in range(n)] + print [("abcdefghij"[i], collector.Value(0, x[i])) for i in range(n)] print print "failures:", solver.Failures() print "branches:", solver.Branches() @@ -111,5 +108,5 @@ def main(unused_argv): print -if __name__ == '__main__': +if __name__ == "__main__": main("cp sample") diff --git a/examples/python/diet1_b.py b/examples/python/diet1_b.py index 250ed7e5cf..4384993391 100644 --- a/examples/python/diet1_b.py +++ b/examples/python/diet1_b.py @@ -43,45 +43,43 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ from ortools.constraint_solver import pywrapcp - def main(unused_argv): # Create the solver. - solver = pywrapcp.Solver('Diet') - + solver = pywrapcp.Solver("Diet") # # data # n = 4 - price = [ 50, 20, 30, 80] # in cents - limits = [500, 6, 10, 8] # requirements for each nutrition type + price = [50, 20, 30, 80] # in cents + limits = [500, 6, 10, 8] # requirements for each nutrition type # nutritions for each product - calories = [400, 200, 150, 500] - chocolate = [3,2,0,0] - sugar = [2,2,4,4] - fat = [2,4,1,5] - + calories = [400, 200, 150, 500] + chocolate = [3, 2, 0, 0] + sugar = [2, 2, 4, 4] + fat = [2, 4, 1, 5] # # declare variables # - x = [solver.IntVar(0, 100, 'x%d' % i) for i in range(n)] - cost = solver.IntVar(0,10000, 'cost') + x = [solver.IntVar(0, 100, "x%d" % i) for i in range(n)] + cost = solver.IntVar(0, 10000, "cost") # # constraints # - solver.Add(solver.ScalProd(x,calories) >= limits[0]) - solver.Add(solver.ScalProd(x,chocolate) >= limits[1]) - solver.Add(solver.ScalProd(x,sugar) >= limits[2]) - solver.Add(solver.ScalProd(x,fat) >= limits[3]) + solver.Add(solver.ScalProd(x, calories) >= limits[0]) + solver.Add(solver.ScalProd(x, chocolate) >= limits[1]) + solver.Add(solver.ScalProd(x, sugar) >= limits[2]) + solver.Add(solver.ScalProd(x, fat) >= limits[3]) # objective objective = solver.Minimize(cost, 1) @@ -99,7 +97,7 @@ def main(unused_argv): solver.Solve(solver.Phase(x + [cost], solver.INT_VAR_SIMPLE, solver.ASSIGN_MIN_VALUE), - [objective, search_log, collector]) + [objective, search_log, collector]) # get the first (and only) solution print "cost:", collector.ObjectiveValue(0) @@ -111,5 +109,5 @@ def main(unused_argv): print -if __name__ == '__main__': +if __name__ == "__main__": main("cp sample") diff --git a/examples/python/diet1_mip.py b/examples/python/diet1_mip.py index da0b5ef93a..7fb80e1846 100644 --- a/examples/python/diet1_mip.py +++ b/examples/python/diet1_mip.py @@ -32,14 +32,15 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ import sys from ortools.linear_solver import pywraplp -def main(sol = 'GLPK'): +def main(sol='GLPK'): # Create the solver. @@ -51,39 +52,38 @@ def main(sol = 'GLPK'): pywraplp.Solver.GLPK_MIXED_INTEGER_PROGRAMMING) else: # Using CBC - solver = pywraplp.Solver('CoinsGridCLP', - pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING) + solver = pywraplp.Solver('CoinsGridCLP', + pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING) # # data # n = 4 - price = [ 50, 20, 30, 80] # in cents - limits = [500, 6, 10, 8] # requirements for each nutrition type + price = [50, 20, 30, 80] # in cents + limits = [500, 6, 10, 8] # requirements for each nutrition type # nutritions for each product - calories = [400, 200, 150, 500] - chocolate = [3,2,0,0] - sugar = [2,2,4,4] - fat = [2,4,1,5] - + calories = [400, 200, 150, 500] + chocolate = [3, 2, 0, 0] + sugar = [2, 2, 4, 4] + fat = [2, 4, 1, 5] # # declare variables # x = [solver.IntVar(0, 100, 'x%d' % i) for i in range(n)] - cost = solver.Sum([x[i]*price[i] for i in range(n)]) + cost = solver.Sum([x[i] * price[i] for i in range(n)]) # # constraints # - solver.Add(solver.Sum([x[i]*calories[i] + solver.Add(solver.Sum([x[i] * calories[i] for i in range(n)]) >= limits[0]) - solver.Add(solver.Sum([x[i]*chocolate[i] + solver.Add(solver.Sum([x[i] * chocolate[i] for i in range(n)]) >= limits[1]) - solver.Add(solver.Sum([x[i]*sugar[i] + solver.Add(solver.Sum([x[i] * sugar[i] for i in range(n)]) >= limits[2]) - solver.Add(solver.Sum([x[i]*fat[i] + solver.Add(solver.Sum([x[i] * fat[i] for i in range(n)]) >= limits[3]) # objective @@ -94,16 +94,15 @@ def main(sol = 'GLPK'): # solver.Solve() - print "Cost:", solver.Objective().Value() + print 'Cost:', solver.Objective().Value() print [int(x[i].SolutionValue()) for i in range(n)] print - print "WallTime:", solver.WallTime() + print 'WallTime:', solver.WallTime() if sol == 'CBC': print 'iterations:', solver.Iterations() - if __name__ == '__main__': sol = 'GLPK' diff --git a/examples/python/discrete_tomography.py b/examples/python/discrete_tomography.py index 1b769745e2..578cfa74a8 100644 --- a/examples/python/discrete_tomography.py +++ b/examples/python/discrete_tomography.py @@ -51,7 +51,8 @@ * SICStus: http://hakank.org/sicstus/discrete_tomography.pl This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ import sys from ortools.constraint_solver import pywrapcp @@ -59,101 +60,100 @@ from ortools.constraint_solver import pywrapcp def main(row_sums="", col_sums=""): - # Create the solver. - solver = pywrapcp.Solver('n-queens') + # Create the solver. + solver = pywrapcp.Solver("n-queens") - # - # data - # - if row_sums == "": - print "Using default problem instance" - row_sums = [0,0,8,2,6,4,5,3,7,0,0] - col_sums = [0,0,7,1,6,3,4,5,2,7,0,0] + # + # data + # + if row_sums == "": + print "Using default problem instance" + row_sums = [0, 0, 8, 2, 6, 4, 5, 3, 7, 0, 0] + col_sums = [0, 0, 7, 1, 6, 3, 4, 5, 2, 7, 0, 0] + r = len(row_sums) + c = len(col_sums) - r = len(row_sums) - c = len(col_sums) + # declare variables + x = [] + for i in range(r): + t = [] + for j in range(c): + t.append(solver.IntVar(0, 1, "x[%i,%i]" % (i, j))) + x.append(t) + x_flat = [x[i][j] for i in range(r) for j in range(c)] + # + # constraints + # + [solver.Add(solver.Sum([x[i][j] for j in range(c)]) == row_sums[i]) + for i in range(r)] + [solver.Add(solver.Sum([x[i][j] for i in range(r)]) == col_sums[j]) + for j in range(c)] - # declare variables - x = [] - for i in range(r): - t = [] - for j in range(c): - t.append(solver.IntVar(0,1, 'x[%i,%i]'%(i,j))) - x.append(t) - x_flat = [x[i][j] for i in range(r) for j in range(c)] + # + # solution and search + # + solution = solver.Assignment() + solution.Add(x_flat) - # - # constraints - # - [solver.Add(solver.Sum([x[i][j] for j in range(c)]) == row_sums[i]) for i in range(r)] - [solver.Add(solver.Sum([x[i][j] for i in range(r)]) == col_sums[j]) for j in range(c)] - - # - # solution and search - # - solution = solver.Assignment() - solution.Add(x_flat) - - - # db: DecisionBuilder - db = solver.Phase(x_flat, - solver.INT_VAR_SIMPLE, - solver.ASSIGN_MIN_VALUE) - - solver.NewSearch(db) - num_solutions = 0 - while solver.NextSolution(): - print_solution(x, r, c, row_sums, col_sums) - print - - - num_solutions += 1 - solver.EndSearch() + # db: DecisionBuilder + db = solver.Phase(x_flat, + solver.INT_VAR_SIMPLE, + solver.ASSIGN_MIN_VALUE) + solver.NewSearch(db) + num_solutions = 0 + while solver.NextSolution(): + print_solution(x, r, c, row_sums, col_sums) print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + + num_solutions += 1 + solver.EndSearch() + + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() # # Print solution # + + def print_solution(x, rows, cols, row_sums, col_sums): - print " ", + print " ", + for j in range(cols): + print col_sums[j], + print + for i in range(rows): + print row_sums[i], for j in range(cols): - print col_sums[j], - print - for i in range(rows): - print row_sums[i], - for j in range(cols): - if x[i][j].Value() == 1: - print "#", - else: - print ".", - print '' + if x[i][j].Value() == 1: + print "#", + else: + print ".", + print "" # # Read a problem instance from a file # def read_problem(file): - f = open(file, 'r') - row_sums = f.readline() - col_sums = f.readline() - row_sums = [int(r) for r in (row_sums.rstrip()).split(",")] - col_sums = [int(c) for c in (col_sums.rstrip()).split(",")] + f = open(file, "r") + row_sums = f.readline() + col_sums = f.readline() + row_sums = [int(r) for r in (row_sums.rstrip()).split(",")] + col_sums = [int(c) for c in (col_sums.rstrip()).split(",")] - return [row_sums, col_sums] - -if __name__ == '__main__': - if len(sys.argv) > 1: - file = sys.argv[1] - print "Problem instance from", file - [row_sums, col_sums] = read_problem(file) - main(row_sums, col_sums) - else: - main() + return [row_sums, col_sums] +if __name__ == "__main__": + if len(sys.argv) > 1: + file = sys.argv[1] + print "Problem instance from", file + [row_sums, col_sums] = read_problem(file) + main(row_sums, col_sums) + else: + main() diff --git a/examples/python/divisible_by_9_through_1.py b/examples/python/divisible_by_9_through_1.py index f39326fc1a..986b195128 100644 --- a/examples/python/divisible_by_9_through_1.py +++ b/examples/python/divisible_by_9_through_1.py @@ -48,10 +48,12 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ -import string, sys +import string +import sys from ortools.constraint_solver import pywrapcp @@ -65,114 +67,115 @@ from ortools.constraint_solver import pywrapcp # The ECLiPSe source code: # http://www.hakank.org/eclipse/modulo_propagator.ecl # + + def my_mod(solver, x, y, r): - if not isinstance(y, int): - solver.Add(y != 0) + if not isinstance(y, int): + solver.Add(y != 0) - lbx = x.Min() - ubx = x.Max() - ubx_neg = -ubx - lbx_neg = -lbx - min_x = min(lbx, ubx_neg) - max_x = max(ubx, lbx_neg) + lbx = x.Min() + ubx = x.Max() + ubx_neg = -ubx + lbx_neg = -lbx + min_x = min(lbx, ubx_neg) + max_x = max(ubx, lbx_neg) - d = solver.IntVar(max(0,min_x), max_x, 'd') + d = solver.IntVar(max(0, min_x), max_x, "d") - if not isinstance(r, int): - solver.Add(r >= 0) - solver.Add(x*r >= 0) + if not isinstance(r, int): + solver.Add(r >= 0) + solver.Add(x * r >= 0) - if not isinstance(r, int) and not isinstance(r, int): - solver.Add(-abs(y) < r) - solver.Add(r < abs(y)) + if not isinstance(r, int) and not isinstance(r, int): + solver.Add(-abs(y) < r) + solver.Add(r < abs(y)) - solver.Add(min_x <= d) - solver.Add(d <= max_x) - solver.Add(x == y*d+r) + solver.Add(min_x <= d) + solver.Add(d <= max_x) + solver.Add(x == y * d + r) # # converts a number (s) <-> an array of integers (t) in the specific base. # def toNum(solver, t, s, base): - tlen = len(t) - solver.Add(s == solver.Sum([(base**(tlen-i-1))*t[i] for i in range(tlen)])) + tlen = len(t) + solver.Add( + s == solver.Sum([(base ** (tlen - i - 1)) * t[i] for i in range(tlen)])) def main(base=10): - # Create the solver. - solver = pywrapcp.Solver('Divisible by 9 through 1') + # Create the solver. + solver = pywrapcp.Solver("Divisible by 9 through 1") - # data - m = base**(base-1)-1 - n = base - 1 + # data + m = base ** (base - 1) - 1 + n = base - 1 - digits_str = "_0123456789ABCDEFGH" + digits_str = "_0123456789ABCDEFGH" - print "base:", base + print "base:", base - # declare variables + # declare variables - # the digits - x = [solver.IntVar(1, base-1, 'x[%i]' % i) for i in range(n)] + # the digits + x = [solver.IntVar(1, base - 1, "x[%i]" % i) for i in range(n)] - # the numbers, t[0] contains the answer - t = [solver.IntVar(0, m, 't[%i]' % i) for i in range(n)] + # the numbers, t[0] contains the answer + t = [solver.IntVar(0, m, "t[%i]" % i) for i in range(n)] - # - # constraints - # - solver.Add(solver.AllDifferent(x)) + # + # constraints + # + solver.Add(solver.AllDifferent(x)) - for i in range(n): - mm = base-i-1 - toNum(solver, [x[j] for j in range(mm)], t[i], base) - my_mod(solver, t[i], mm, 0) + for i in range(n): + mm = base - i - 1 + toNum(solver, [x[j] for j in range(mm)], t[i], base) + my_mod(solver, t[i], mm, 0) + # + # solution and search + # + solution = solver.Assignment() + solution.Add(x) + solution.Add(t) - # - # solution and search - # - solution = solver.Assignment() - solution.Add(x) - solution.Add(t) + db = solver.Phase(x, + solver.CHOOSE_FIRST_UNBOUND, + solver.ASSIGN_MIN_VALUE) - db = solver.Phase(x, - solver.CHOOSE_FIRST_UNBOUND, - solver.ASSIGN_MIN_VALUE) + solver.NewSearch(db) + num_solutions = 0 + while solver.NextSolution(): + print "x: ", [x[i].Value() for i in range(n)] + print "t: ", [t[i].Value() for i in range(n)] + print "number base 10: %i base %i: %s" % (t[0].Value(), + base, + "".join([digits_str[x[i].Value() + 1] for i in range(n)])) + print + num_solutions += 1 + solver.EndSearch() - - solver.NewSearch(db) - num_solutions = 0 - while solver.NextSolution(): - print "x: ", [x[i].Value() for i in range(n)] - print "t: ", [t[i].Value() for i in range(n)] - print "number base 10: %i base %i: %s" % (t[0].Value(),\ - base, - "".join([digits_str[x[i].Value()+1] for i in range(n)])) - print - num_solutions += 1 - solver.EndSearch() - - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() base = 10 default_base = 10 max_base = 16 -if __name__ == '__main__': - if len(sys.argv) > 1: - base = string.atoi(sys.argv[1]) - if base > max_base: - print "Sorry, max allowed base is %i. Setting base to %i..." % (max_base, default_base) - base = default_base - main(base) +if __name__ == "__main__": + if len(sys.argv) > 1: + base = string.atoi(sys.argv[1]) + if base > max_base: + print "Sorry, max allowed base is %i. Setting base to %i..." % (max_base, default_base) + base = default_base + main(base) - # for base in range(2, 17): - # print - # main(base) + # for base in range(2, 17): + # print + # main(base) diff --git a/examples/python/dudeney.py b/examples/python/dudeney.py index a20ca3429d..ebce207274 100644 --- a/examples/python/dudeney.py +++ b/examples/python/dudeney.py @@ -13,6 +13,7 @@ from ortools.constraint_solver import pywrapcp + def dudeney(n): solver = pywrapcp.Solver('Dudeney') x = [solver.IntVar(range(10), 'x' + str(i)) for i in range(n)] diff --git a/examples/python/einav_puzzle.py b/examples/python/einav_puzzle.py index 3569ee7b89..91185bbaba 100644 --- a/examples/python/einav_puzzle.py +++ b/examples/python/einav_puzzle.py @@ -60,7 +60,8 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ from ortools.constraint_solver import pywrapcp @@ -68,140 +69,138 @@ from ortools.constraint_solver import pywrapcp def main(): - # Create the solver. - solver = pywrapcp.Solver('Einav puzzle') + # Create the solver. + solver = pywrapcp.Solver('Einav puzzle') - # - # data - # + # + # data + # - # small problem - # rows = 3; - # cols = 3; - # data = [ - # [ 33, 30, -10], - # [-16, 19, 9], - # [-17, -12, -14] - # ] + # small problem + # rows = 3; + # cols = 3; + # data = [ + # [ 33, 30, -10], + # [-16, 19, 9], + # [-17, -12, -14] + # ] - # Full problem - rows = 27 - cols = 9 - data = [ - [33,30,10,-6,18,-7,-11,23,-6], - [16,-19,9,-26,-8,-19,-8,-21,-14], - [17,12,-14,31,-30,13,-13,19,16], - [-6,-11,1,17,-12,-4,-7,14,-21], - [18,-31,34,-22,17,-19,20,24,6], - [33,-18,17,-15,31,-5,3,27,-3], - [-18,-20,-18,31,6,4,-2,-12,24], - [27,14,4,-29,-3,5,-29,8,-12], - [-15,-7,-23,23,-9,-8,6,8,-12], - [33,-23,-19,-4,-8,-7,11,-12,31], - [-20,19,-15,-30,11,32,7,14,-5], - [-23,18,-32,-2,-31,-7,8,24,16], - [32,-4,-10,-14,-6,-1,0,23,23], - [25,0,-23,22,12,28,-27,15,4], - [-30,-13,-16,-3,-3,-32,-3,27,-31], - [22,1,26,4,-2,-13,26,17,14], - [-9,-18,3,-20,-27,-32,-11,27,13], - [-17,33,-7,19,-32,13,-31,-2,-24], - [-31,27,-31,-29,15,2,29,-15,33], - [-18,-23,15,28,0,30,-4,12,-32], - [-3,34,27,-25,-18,26,1,34,26], - [-21,-31,-10,-13,-30,-17,-12,-26,31], - [23,-31,-19,21,-17,-10,2,-23,23], - [-3,6,0,-3,-32,0,-10,-25,14], - [-19,9,14,-27,20,15,-5,-27,18], - [11,-6,24,7,-17,26,20,-31,-25], - [-25,4,-16,30,33,23,-4,-4,23] - ] + # Full problem + rows = 27 + cols = 9 + data = [ + [33, 30, 10, -6, 18, -7, -11, 23, -6], + [16, -19, 9, -26, -8, -19, -8, -21, -14], + [17, 12, -14, 31, -30, 13, -13, 19, 16], + [-6, -11, 1, 17, -12, -4, -7, 14, -21], + [18, -31, 34, -22, 17, -19, 20, 24, 6], + [33, -18, 17, -15, 31, -5, 3, 27, -3], + [-18, -20, -18, 31, 6, 4, -2, -12, 24], + [27, 14, 4, -29, -3, 5, -29, 8, -12], + [-15, -7, -23, 23, -9, -8, 6, 8, -12], + [33, -23, -19, -4, -8, -7, 11, -12, 31], + [-20, 19, -15, -30, 11, 32, 7, 14, -5], + [-23, 18, -32, -2, -31, -7, 8, 24, 16], + [32, -4, -10, -14, -6, -1, 0, 23, 23], + [25, 0, -23, 22, 12, 28, -27, 15, 4], + [-30, -13, -16, -3, -3, -32, -3, 27, -31], + [22, 1, 26, 4, -2, -13, 26, 17, 14], + [-9, -18, 3, -20, -27, -32, -11, 27, 13], + [-17, 33, -7, 19, -32, 13, -31, -2, -24], + [-31, 27, -31, -29, 15, 2, 29, -15, 33], + [-18, -23, 15, 28, 0, 30, -4, 12, -32], + [-3, 34, 27, -25, -18, 26, 1, 34, 26], + [-21, -31, -10, -13, -30, -17, -12, -26, 31], + [23, -31, -19, 21, -17, -10, 2, -23, 23], + [-3, 6, 0, -3, -32, 0, -10, -25, 14], + [-19, 9, 14, -27, 20, 15, -5, -27, 18], + [11, -6, 24, 7, -17, 26, 20, -31, -25], + [-25, 4, -16, 30, 33, 23, -4, -4, 23] + ] - - # - # variables - # - x = {} - for i in range(rows): - for j in range(cols): - x[i,j] = solver.IntVar(-100, 100, 'x[%i,%i]' % (i,j)) - - x_flat = [x[i,j] for i in range(rows) for j in range(cols)] - - row_sums = [solver.IntVar(0, 300, 'row_sums(%i)' % i) - for i in range(rows)] - col_sums = [solver.IntVar(0, 300, 'col_sums(%i)' % j) - for j in range(cols)] - - row_signs = [solver.IntVar([-1, 1], 'row_signs(%i)' % i) - for i in range(rows)] - col_signs = [solver.IntVar([-1, 1], 'col_signs(%i)' % j) - for j in range(cols)] - - # total sum: to be minimized - total_sum = solver.IntVar(0, 1000, 'total_sum') - - # - # constraints - # - for i in range(rows): - for j in range(cols): - solver.Add(x[i,j] == data[i][j]*row_signs[i]*col_signs[j]) - - total_sum_a = [data[i][j]*row_signs[i]*col_signs[j] - for i in range(rows) for j in range(cols) ] - solver.Add(total_sum == solver.Sum(total_sum_a)) - - # row sums - for i in range(rows): - s = [row_signs[i]*col_signs[j]*data[i][j] - for j in range(cols)] - solver.Add(row_sums[i] == solver.Sum(s)) - - # column sums + # + # variables + # + x = {} + for i in range(rows): for j in range(cols): - s = [row_signs[i]*col_signs[j]*data[i][j] - for i in range(rows)] - solver.Add(col_sums[j] == solver.Sum(s)) + x[i, j] = solver.IntVar(-100, 100, 'x[%i,%i]' % (i, j)) + x_flat = [x[i, j] for i in range(rows) for j in range(cols)] - # objective - objective = solver.Minimize(total_sum, 1) + row_sums = [solver.IntVar(0, 300, 'row_sums(%i)' % i) + for i in range(rows)] + col_sums = [solver.IntVar(0, 300, 'col_sums(%i)' % j) + for j in range(cols)] - # - # search and result - # - # Note: The order of the variables makes a big difference. - # If row_signs are before col_sign it is much slower. - db = solver.Phase(col_signs + row_signs, - solver.CHOOSE_MIN_SIZE_LOWEST_MIN, - solver.ASSIGN_MAX_VALUE) + row_signs = [solver.IntVar([-1, 1], 'row_signs(%i)' % i) + for i in range(rows)] + col_signs = [solver.IntVar([-1, 1], 'col_signs(%i)' % j) + for j in range(cols)] - solver.NewSearch(db, [objective]) + # total sum: to be minimized + total_sum = solver.IntVar(0, 1000, 'total_sum') - num_solutions = 0 - while solver.NextSolution(): - num_solutions += 1 - print 'total_sum:', total_sum.Value() - print 'row_sums:', [row_sums[i].Value() for i in range(rows)] - print 'col_sums:', [col_sums[j].Value() for j in range(cols)] - print 'row_signs:', [row_signs[i].Value() for i in range(rows)] - print 'col_signs:', [col_signs[j].Value() for j in range(cols)] - print 'x:' - for i in range(rows): - for j in range(cols): - print '%3i' % x[i,j].Value(), - print - print + # + # constraints + # + for i in range(rows): + for j in range(cols): + solver.Add(x[i, j] == data[i][j] * row_signs[i] * col_signs[j]) - solver.EndSearch() + total_sum_a = [data[i][j] * row_signs[i] * col_signs[j] + for i in range(rows) for j in range(cols)] + solver.Add(total_sum == solver.Sum(total_sum_a)) + # row sums + for i in range(rows): + s = [row_signs[i] * col_signs[j] * data[i][j] + for j in range(cols)] + solver.Add(row_sums[i] == solver.Sum(s)) + + # column sums + for j in range(cols): + s = [row_signs[i] * col_signs[j] * data[i][j] + for i in range(rows)] + solver.Add(col_sums[j] == solver.Sum(s)) + + # objective + objective = solver.Minimize(total_sum, 1) + + # + # search and result + # + # Note: The order of the variables makes a big difference. + # If row_signs are before col_sign it is much slower. + db = solver.Phase(col_signs + row_signs, + solver.CHOOSE_MIN_SIZE_LOWEST_MIN, + solver.ASSIGN_MAX_VALUE) + + solver.NewSearch(db, [objective]) + + num_solutions = 0 + while solver.NextSolution(): + num_solutions += 1 + print 'total_sum:', total_sum.Value() + print 'row_sums:', [row_sums[i].Value() for i in range(rows)] + print 'col_sums:', [col_sums[j].Value() for j in range(cols)] + print 'row_signs:', [row_signs[i].Value() for i in range(rows)] + print 'col_signs:', [col_signs[j].Value() for j in range(cols)] + print 'x:' + for i in range(rows): + for j in range(cols): + print '%3i' % x[i, j].Value(), + print print - print 'num_solutions:', num_solutions - print 'failures:', solver.Failures() - print 'branches:', solver.Branches() - print 'WallTime:', solver.WallTime(), 'ms' + + solver.EndSearch() + + print + print 'num_solutions:', num_solutions + print 'failures:', solver.Failures() + print 'branches:', solver.Branches() + print 'WallTime:', solver.WallTime(), 'ms' if __name__ == '__main__': - main() + main() diff --git a/examples/python/einav_puzzle2.py b/examples/python/einav_puzzle2.py index 213daed261..bebecb6e59 100644 --- a/examples/python/einav_puzzle2.py +++ b/examples/python/einav_puzzle2.py @@ -61,7 +61,8 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ from ortools.constraint_solver import pywrapcp @@ -69,131 +70,128 @@ from ortools.constraint_solver import pywrapcp def main(): - # Create the solver. - solver = pywrapcp.Solver('Einav puzzle') + # Create the solver. + solver = pywrapcp.Solver("Einav puzzle") - # - # data - # + # + # data + # + # small problem + # rows = 3; + # cols = 3; + # data = [ + # [ 33, 30, -10], + # [-16, 19, 9], + # [-17, -12, -14] + # ] - # small problem - # rows = 3; - # cols = 3; - # data = [ - # [ 33, 30, -10], - # [-16, 19, 9], - # [-17, -12, -14] - # ] + # Full problem + rows = 27 + cols = 9 + data = [ + [33, 30, 10, -6, 18, -7, -11, 23, -6], + [16, -19, 9, -26, -8, -19, -8, -21, -14], + [17, 12, -14, 31, -30, 13, -13, 19, 16], + [-6, -11, 1, 17, -12, -4, -7, 14, -21], + [18, -31, 34, -22, 17, -19, 20, 24, 6], + [33, -18, 17, -15, 31, -5, 3, 27, -3], + [-18, -20, -18, 31, 6, 4, -2, -12, 24], + [27, 14, 4, -29, -3, 5, -29, 8, -12], + [-15, -7, -23, 23, -9, -8, 6, 8, -12], + [33, -23, -19, -4, -8, -7, 11, -12, 31], + [-20, 19, -15, -30, 11, 32, 7, 14, -5], + [-23, 18, -32, -2, -31, -7, 8, 24, 16], + [32, -4, -10, -14, -6, -1, 0, 23, 23], + [25, 0, -23, 22, 12, 28, -27, 15, 4], + [-30, -13, -16, -3, -3, -32, -3, 27, -31], + [22, 1, 26, 4, -2, -13, 26, 17, 14], + [-9, -18, 3, -20, -27, -32, -11, 27, 13], + [-17, 33, -7, 19, -32, 13, -31, -2, -24], + [-31, 27, -31, -29, 15, 2, 29, -15, 33], + [-18, -23, 15, 28, 0, 30, -4, 12, -32], + [-3, 34, 27, -25, -18, 26, 1, 34, 26], + [-21, -31, -10, -13, -30, -17, -12, -26, 31], + [23, -31, -19, 21, -17, -10, 2, -23, 23], + [-3, 6, 0, -3, -32, 0, -10, -25, 14], + [-19, 9, 14, -27, 20, 15, -5, -27, 18], + [11, -6, 24, 7, -17, 26, 20, -31, -25], + [-25, 4, -16, 30, 33, 23, -4, -4, 23] + ] - # Full problem - rows = 27 - cols = 9 - data = [ - [33,30,10,-6,18,-7,-11,23,-6], - [16,-19,9,-26,-8,-19,-8,-21,-14], - [17,12,-14,31,-30,13,-13,19,16], - [-6,-11,1,17,-12,-4,-7,14,-21], - [18,-31,34,-22,17,-19,20,24,6], - [33,-18,17,-15,31,-5,3,27,-3], - [-18,-20,-18,31,6,4,-2,-12,24], - [27,14,4,-29,-3,5,-29,8,-12], - [-15,-7,-23,23,-9,-8,6,8,-12], - [33,-23,-19,-4,-8,-7,11,-12,31], - [-20,19,-15,-30,11,32,7,14,-5], - [-23,18,-32,-2,-31,-7,8,24,16], - [32,-4,-10,-14,-6,-1,0,23,23], - [25,0,-23,22,12,28,-27,15,4], - [-30,-13,-16,-3,-3,-32,-3,27,-31], - [22,1,26,4,-2,-13,26,17,14], - [-9,-18,3,-20,-27,-32,-11,27,13], - [-17,33,-7,19,-32,13,-31,-2,-24], - [-31,27,-31,-29,15,2,29,-15,33], - [-18,-23,15,28,0,30,-4,12,-32], - [-3,34,27,-25,-18,26,1,34,26], - [-21,-31,-10,-13,-30,-17,-12,-26,31], - [23,-31,-19,21,-17,-10,2,-23,23], - [-3,6,0,-3,-32,0,-10,-25,14], - [-19,9,14,-27,20,15,-5,-27,18], - [11,-6,24,7,-17,26,20,-31,-25], - [-25,4,-16,30,33,23,-4,-4,23] - ] - - - # - # variables - # - x = {} - for i in range(rows): - for j in range(cols): - x[i,j] = solver.IntVar(-100, 100, "x[%i,%i]" % (i,j)) - - x_flat = [x[i,j] for i in range(rows) for j in range(cols)] - - row_signs = [solver.IntVar([-1, 1], "row_signs(%i)" % i) - for i in range(rows)] - col_signs = [solver.IntVar([-1, 1], "col_signs(%i)" % j) - for j in range(cols)] - - # - # constraints - # - for i in range(rows): - for j in range(cols): - solver.Add(x[i, j] == data[i][j] * row_signs[i] * col_signs[j]) - - total_sum = solver.Sum([x[i, j] for i in range(rows) for j in range(cols)]) - - # - # Note: In einav_puzzle.py row_sums and col_sums are decision variables. - # - - # row sums - row_sums = [solver.Sum([x[i, j] for j in range(cols)]).Var() - for i in range(rows)] - # >= 0 - for i in range(rows): - row_sums[i].SetMin(0) - - # column sums - col_sums = [solver.Sum([x[i, j] for i in range(rows)]).Var() - for j in range(cols)] + # + # variables + # + x = {} + for i in range(rows): for j in range(cols): - col_sums[j].SetMin(0) + x[i, j] = solver.IntVar(-100, 100, "x[%i,%i]" % (i, j)) + x_flat = [x[i, j] for i in range(rows) for j in range(cols)] - # objective - objective = solver.Minimize(total_sum, 1) + row_signs = [solver.IntVar([-1, 1], "row_signs(%i)" % i) + for i in range(rows)] + col_signs = [solver.IntVar([-1, 1], "col_signs(%i)" % j) + for j in range(cols)] - # - # search and result - # - db = solver.Phase(col_signs + row_signs, - solver.CHOOSE_MIN_SIZE_LOWEST_MIN, - solver.ASSIGN_MAX_VALUE) + # + # constraints + # + for i in range(rows): + for j in range(cols): + solver.Add(x[i, j] == data[i][j] * row_signs[i] * col_signs[j]) - solver.NewSearch(db, [objective]) + total_sum = solver.Sum([x[i, j] for i in range(rows) for j in range(cols)]) - num_solutions = 0 - while solver.NextSolution(): - num_solutions += 1 - print "Sum =", objective.best() - print "row_sums:", [row_sums[i].Value() for i in range(rows)] - print "col_sums:", [col_sums[j].Value() for j in range(cols)] - for i in range(rows): - for j in range(cols): - print "%3i" % x[i,j].Value(), - print - print + # + # Note: In einav_puzzle.py row_sums and col_sums are decision variables. + # - solver.EndSearch() + # row sums + row_sums = [solver.Sum([x[i, j] for j in range(cols)]).Var() + for i in range(rows)] + # >= 0 + for i in range(rows): + row_sums[i].SetMin(0) + # column sums + col_sums = [solver.Sum([x[i, j] for i in range(rows)]).Var() + for j in range(cols)] + for j in range(cols): + col_sums[j].SetMin(0) + + # objective + objective = solver.Minimize(total_sum, 1) + + # + # search and result + # + db = solver.Phase(col_signs + row_signs, + solver.CHOOSE_MIN_SIZE_LOWEST_MIN, + solver.ASSIGN_MAX_VALUE) + + solver.NewSearch(db, [objective]) + + num_solutions = 0 + while solver.NextSolution(): + num_solutions += 1 + print "Sum =", objective.best() + print "row_sums:", [row_sums[i].Value() for i in range(rows)] + print "col_sums:", [col_sums[j].Value() for j in range(cols)] + for i in range(rows): + for j in range(cols): + print "%3i" % x[i, j].Value(), + print print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + + solver.EndSearch() + + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() -if __name__ == '__main__': - main() +if __name__ == "__main__": + main() diff --git a/examples/python/eq10.py b/examples/python/eq10.py index dbf22f5b41..1d536db5bc 100644 --- a/examples/python/eq10.py +++ b/examples/python/eq10.py @@ -24,7 +24,8 @@ * SICStus: http://hakank.org/sicstus/eq10.pl This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ from ortools.constraint_solver import pywrapcp @@ -32,77 +33,77 @@ from ortools.constraint_solver import pywrapcp def main(): - # Create the solver. - solver = pywrapcp.Solver('Eq 10') + # Create the solver. + solver = pywrapcp.Solver("Eq 10") - # - # data - # - n = 7 + # + # data + # + n = 7 - # - # variables - # - X = [solver.IntVar(0, 10, "X(%i)" % i) for i in range(n)] - X1,X2,X3,X4,X5,X6,X7 = X + # + # variables + # + X = [solver.IntVar(0, 10, "X(%i)" % i) for i in range(n)] + X1, X2, X3, X4, X5, X6, X7 = X - # - # constraints - # - solver.Add(0+98527*X1+34588*X2+5872*X3+59422*X5+65159*X7 - == 1547604+30704*X4+29649*X6) + # + # constraints + # + solver.Add(0 + 98527 * X1 + 34588 * X2 + 5872 * X3 + 59422 * X5 + 65159 * X7 + == 1547604 + 30704 * X4 + 29649 * X6) - solver.Add(0+98957*X2+83634*X3+69966*X4+62038*X5+37164*X6+85413*X7 - == 1823553+93989*X1) + solver.Add( + 0 + 98957 * X2 + 83634 * X3 + 69966 * X4 + 62038 * X5 + 37164 * X6 + 85413 * X7 == 1823553 + 93989 * + X1) - solver.Add(900032+10949*X1+77761*X2+67052*X5 - == 0+80197*X3+61944*X4+92964*X6+44550*X7) + solver.Add(900032 + 10949 * X1 + 77761 * X2 + 67052 * X5 + == 0 + 80197 * X3 + 61944 * X4 + 92964 * X6 + 44550 * X7) - solver.Add(0+73947*X1+84391*X3+81310*X5 - == 1164380+96253*X2+44247*X4+70582*X6+33054*X7) + solver.Add(0 + 73947 * X1 + 84391 * X3 + 81310 * X5 + == 1164380 + 96253 * X2 + 44247 * X4 + 70582 * X6 + 33054 * X7) - solver.Add(0+13057*X3+42253*X4+77527*X5+96552*X7 - == 1185471+60152*X1+21103*X2+97932*X6) + solver.Add(0 + 13057 * X3 + 42253 * X4 + 77527 * X5 + 96552 * X7 + == 1185471 + 60152 * X1 + 21103 * X2 + 97932 * X6) - solver.Add(1394152+66920*X1+55679*X4 - == 0+64234*X2+65337*X3+45581*X5+67707*X6+98038*X7) + solver.Add(1394152 + 66920 * X1 + 55679 * X4 == + 0 + 64234 * X2 + 65337 * X3 + 45581 * X5 + 67707 * X6 + 98038 * X7) - solver.Add(0+68550*X1+27886*X2+31716*X3+73597*X4+38835*X7 - == 279091+88963*X5+76391*X6) + solver.Add(0 + 68550 * X1 + 27886 * X2 + 31716 * X3 + 73597 * X4 + 38835 * X7 + == 279091 + 88963 * X5 + 76391 * X6) - solver.Add(0+76132*X2+71860*X3+22770*X4+68211*X5+78587*X6 - == 480923+48224*X1+82817*X7) + solver.Add(0 + 76132 * X2 + 71860 * X3 + 22770 * X4 + 68211 * X5 + 78587 * X6 + == 480923 + 48224 * X1 + 82817 * X7) - solver.Add(519878+94198*X2+87234*X3+37498*X4 - == 0+71583*X1+25728*X5+25495*X6+70023*X7) + solver.Add(519878 + 94198 * X2 + 87234 * X3 + 37498 * X4 + == 0 + 71583 * X1 + 25728 * X5 + 25495 * X6 + 70023 * X7) - solver.Add(361921+78693*X1+38592*X5+38478*X6 - == 0+94129*X2+43188*X3+82528*X4+69025*X7) + solver.Add(361921 + 78693 * X1 + 38592 * X5 + 38478 * X6 + == 0 + 94129 * X2 + 43188 * X3 + 82528 * X4 + 69025 * X7) + # + # search and result + # + db = solver.Phase(X, + solver.INT_VAR_SIMPLE, + solver.INT_VALUE_SIMPLE) - # - # search and result - # - db = solver.Phase(X, - solver.INT_VAR_SIMPLE, - solver.INT_VALUE_SIMPLE) - - solver.NewSearch(db) - - num_solutions = 0 - while solver.NextSolution(): - num_solutions += 1 - print "X:", [X[i].Value() for i in range(n)] - print - - solver.EndSearch() + solver.NewSearch(db) + num_solutions = 0 + while solver.NextSolution(): + num_solutions += 1 + print "X:", [X[i].Value() for i in range(n)] print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + + solver.EndSearch() + + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() -if __name__ == '__main__': - main() +if __name__ == "__main__": + main() diff --git a/examples/python/eq20.py b/examples/python/eq20.py index 40055d2cae..521cbcb50b 100644 --- a/examples/python/eq20.py +++ b/examples/python/eq20.py @@ -24,7 +24,8 @@ * SICStus: http://hakank.org/sicstus/eq20.pl This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ from ortools.constraint_solver import pywrapcp @@ -32,88 +33,87 @@ from ortools.constraint_solver import pywrapcp def main(): - # Create the solver. - solver = pywrapcp.Solver('Eq 20') + # Create the solver. + solver = pywrapcp.Solver("Eq 20") - # - # data - # - n = 7 + # + # data + # + n = 7 - # - # variables - # - X = [solver.IntVar(0, 10, "X(%i)" % i) for i in range(n)] - X0,X1,X2,X3,X4,X5,X6 = X + # + # variables + # + X = [solver.IntVar(0, 10, "X(%i)" % i) for i in range(n)] + X0, X1, X2, X3, X4, X5, X6 = X - # - # constraints - # - solver.Add(-76706*X0 + 98205*X1 + 23445*X2 + 67921*X3 + 24111*X4 + - -48614*X5 + -41906*X6 == 821228) - solver.Add(87059*X0 + -29101*X1 + -5513*X2 + -21219*X3 + 22128*X4 + - 7276*X5 + 57308*X6 == 22167) - solver.Add(-60113*X0 + 29475*X1 + 34421*X2 + -76870*X3 + 62646*X4 + - 29278*X5 + -15212*X6 == 251591) - solver.Add(49149*X0 + 52871*X1 + -7132*X2 + 56728*X3 + -33576*X4 + - -49530*X5 + -62089*X6 == 146074) - solver.Add(-10343*X0 + 87758*X1 + -11782*X2 + 19346*X3 + 70072*X4 + - -36991*X5 + 44529*X6 == 740061) - solver.Add(85176*X0 + -95332*X1 + -1268*X2 + 57898*X3 + 15883*X4 + - 50547*X5 + 83287*X6 == 373854) - solver.Add(-85698*X0 + 29958*X1 + 57308*X2 + 48789*X3 + -78219*X4 + - 4657*X5 + 34539*X6 == 249912) - solver.Add(-67456*X0 + 84750*X1 + -51553*X2 + 21239*X3 + 81675*X4 + - -99395*X5 + -4254*X6 == 277271) - solver.Add(94016*X0 + -82071*X1 + 35961*X2 + 66597*X3 + -30705*X4 + - -44404*X5 + -38304*X6 == 25334) - solver.Add(-60301*X0 + 31227*X1 + 93951*X2 + 73889*X3 + 81526*X4 + - -72702*X5 + 68026*X6 == 1410723) - solver.Add(-16835*X0 + 47385*X1 + 97715*X2 + -12640*X3 + 69028*X4 + - 76212*X5 + -81102*X6 == 1244857) - solver.Add(-43277*X0 + 43525*X1 + 92298*X2 + 58630*X3 + 92590*X4 + - -9372*X5 + -60227*X6 == 1503588) - solver.Add(-64919*X0 + 80460*X1 + 90840*X2 + -59624*X3 + -75542*X4 + - 25145*X5 + -47935*X6 == 18465) - solver.Add(-45086*X0 + 51830*X1 + -4578*X2 + 96120*X3 + 21231*X4 + - 97919*X5 + 65651*X6 == 1198280) - solver.Add(85268*X0 + 54180*X1 + -18810*X2 + -48219*X3 + 6013*X4 + - 78169*X5 + -79785*X6 == 90614) - solver.Add(8874*X0 + -58412*X1 + 73947*X2 + 17147*X3 + 62335*X4 + - 16005*X5 + 8632*X6 == 752447) - solver.Add(71202*X0 + -11119*X1 + 73017*X2 + -38875*X3 + -14413*X4 + - -29234*X5 + 72370*X6 == 129768) - solver.Add(1671*X0 + -34121*X1 + 10763*X2 + 80609*X3 + 42532*X4 + - 93520*X5 + -33488*X6 == 915683) - solver.Add(51637*X0 + 67761*X1 + 95951*X2 + 3834*X3 + -96722*X4 + - 59190*X5 + 15280*X6 == 533909) - solver.Add(-16105*X0 + 62397*X1 + -6704*X2 + 43340*X3 + 95100*X4 + - -68610*X5 + 58301*X6 == 876370) + # + # constraints + # + solver.Add(-76706 * X0 + 98205 * X1 + 23445 * X2 + 67921 * X3 + 24111 * X4 + + -48614 * X5 + -41906 * X6 == 821228) + solver.Add(87059 * X0 + -29101 * X1 + -5513 * X2 + -21219 * X3 + 22128 * X4 + + 7276 * X5 + 57308 * X6 == 22167) + solver.Add(-60113 * X0 + 29475 * X1 + 34421 * X2 + -76870 * X3 + 62646 * X4 + + 29278 * X5 + -15212 * X6 == 251591) + solver.Add(49149 * X0 + 52871 * X1 + -7132 * X2 + 56728 * X3 + -33576 * X4 + + -49530 * X5 + -62089 * X6 == 146074) + solver.Add(-10343 * X0 + 87758 * X1 + -11782 * X2 + 19346 * X3 + 70072 * X4 + + -36991 * X5 + 44529 * X6 == 740061) + solver.Add(85176 * X0 + -95332 * X1 + -1268 * X2 + 57898 * X3 + 15883 * X4 + + 50547 * X5 + 83287 * X6 == 373854) + solver.Add(-85698 * X0 + 29958 * X1 + 57308 * X2 + 48789 * X3 + -78219 * X4 + + 4657 * X5 + 34539 * X6 == 249912) + solver.Add(-67456 * X0 + 84750 * X1 + -51553 * X2 + 21239 * X3 + 81675 * X4 + + -99395 * X5 + -4254 * X6 == 277271) + solver.Add(94016 * X0 + -82071 * X1 + 35961 * X2 + 66597 * X3 + -30705 * X4 + + -44404 * X5 + -38304 * X6 == 25334) + solver.Add(-60301 * X0 + 31227 * X1 + 93951 * X2 + 73889 * X3 + 81526 * X4 + + -72702 * X5 + 68026 * X6 == 1410723) + solver.Add(-16835 * X0 + 47385 * X1 + 97715 * X2 + -12640 * X3 + 69028 * X4 + + 76212 * X5 + -81102 * X6 == 1244857) + solver.Add(-43277 * X0 + 43525 * X1 + 92298 * X2 + 58630 * X3 + 92590 * X4 + + -9372 * X5 + -60227 * X6 == 1503588) + solver.Add(-64919 * X0 + 80460 * X1 + 90840 * X2 + -59624 * X3 + -75542 * X4 + + 25145 * X5 + -47935 * X6 == 18465) + solver.Add(-45086 * X0 + 51830 * X1 + -4578 * X2 + 96120 * X3 + 21231 * X4 + + 97919 * X5 + 65651 * X6 == 1198280) + solver.Add(85268 * X0 + 54180 * X1 + -18810 * X2 + -48219 * X3 + 6013 * X4 + + 78169 * X5 + -79785 * X6 == 90614) + solver.Add(8874 * X0 + -58412 * X1 + 73947 * X2 + 17147 * X3 + 62335 * X4 + + 16005 * X5 + 8632 * X6 == 752447) + solver.Add(71202 * X0 + -11119 * X1 + 73017 * X2 + -38875 * X3 + -14413 * X4 + + -29234 * X5 + 72370 * X6 == 129768) + solver.Add(1671 * X0 + -34121 * X1 + 10763 * X2 + 80609 * X3 + 42532 * X4 + + 93520 * X5 + -33488 * X6 == 915683) + solver.Add(51637 * X0 + 67761 * X1 + 95951 * X2 + 3834 * X3 + -96722 * X4 + + 59190 * X5 + 15280 * X6 == 533909) + solver.Add(-16105 * X0 + 62397 * X1 + -6704 * X2 + 43340 * X3 + 95100 * X4 + + -68610 * X5 + 58301 * X6 == 876370) + # + # search and result + # + db = solver.Phase(X, + solver.CHOOSE_FIRST_UNBOUND, + solver.ASSIGN_MIN_VALUE) - # - # search and result - # - db = solver.Phase(X, - solver.CHOOSE_FIRST_UNBOUND, - solver.ASSIGN_MIN_VALUE) - - solver.NewSearch(db) - - num_solutions = 0 - while solver.NextSolution(): - num_solutions += 1 - print "X:", [X[i].Value() for i in range(n)] - print - - solver.EndSearch() + solver.NewSearch(db) + num_solutions = 0 + while solver.NextSolution(): + num_solutions += 1 + print "X:", [X[i].Value() for i in range(n)] print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + + solver.EndSearch() + + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() -if __name__ == '__main__': - main() +if __name__ == "__main__": + main() diff --git a/examples/python/fill_a_pix.py b/examples/python/fill_a_pix.py index d85a46759f..7b84aabfb0 100644 --- a/examples/python/fill_a_pix.py +++ b/examples/python/fill_a_pix.py @@ -16,7 +16,8 @@ Fill-a-Pix problem in Google CP Solver. - From http://www.conceptispuzzles.com/index.aspx?uri=puzzle/fill-a-pix/basiclogic + From + http://www.conceptispuzzles.com/index.aspx?uri=puzzle/fill-a-pix/basiclogic ''' Each puzzle consists of a grid containing clues in various places. The object is to reveal a hidden picture by painting the squares around each @@ -47,7 +48,8 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ import sys from ortools.constraint_solver import pywrapcp @@ -58,129 +60,128 @@ from ortools.constraint_solver import pywrapcp default_n = 10 X = -1 default_puzzle = [ - [X,X,X,X,X,X,X,X,0,X], - [X,8,8,X,2,X,0,X,X,X], - [5,X,8,X,X,X,X,X,X,X], - [X,X,X,X,X,2,X,X,X,2], - [1,X,X,X,4,5,6,X,X,X], - [X,0,X,X,X,7,9,X,X,6], - [X,X,X,6,X,X,9,X,X,6], - [X,X,6,6,8,7,8,7,X,5], - [X,4,X,6,6,6,X,6,X,4], - [X,X,X,X,X,X,3,X,X,X] - ] + [X, X, X, X, X, X, X, X, 0, X], + [X, 8, 8, X, 2, X, 0, X, X, X], + [5, X, 8, X, X, X, X, X, X, X], + [X, X, X, X, X, 2, X, X, X, 2], + [1, X, X, X, 4, 5, 6, X, X, X], + [X, 0, X, X, X, 7, 9, X, X, 6], + [X, X, X, 6, X, X, 9, X, X, 6], + [X, X, 6, 6, 8, 7, 8, 7, X, 5], + [X, 4, X, 6, 6, 6, X, 6, X, 4], + [X, X, X, X, X, X, 3, X, X, X] +] def main(puzzle='', n=''): - # Create the solver. - solver = pywrapcp.Solver('Fill-a-Pix') + # Create the solver. + solver = pywrapcp.Solver('Fill-a-Pix') - # - # data - # + # + # data + # - # Set default problem - if puzzle == '': - puzzle = default_puzzle - n = default_n - else: - print 'n:', n + # Set default problem + if puzzle == '': + puzzle = default_puzzle + n = default_n + else: + print 'n:', n - # for the neighbors of 'this' cell - S = [-1,0,1] + # for the neighbors of 'this' cell + S = [-1, 0, 1] - # print problem instance - print 'Problem:' + # print problem instance + print 'Problem:' + for i in range(n): + for j in range(n): + if puzzle[i][j] == X: + sys.stdout.write('.') + else: + sys.stdout.write(str(puzzle[i][j])) + print + print + + # + # declare variables + # + pict = {} + for i in range(n): + for j in range(n): + pict[(i, j)] = solver.IntVar(0, 1, 'pict %i %i' % (i, j)) + + pict_flat = [pict[i, j] for i in range(n) for j in range(n)] + + # + # constraints + # + for i in range(n): + for j in range(n): + if puzzle[i][j] > X: + # this cell is the sum of all the surrounding cells + solver.Add( + puzzle[i][j] == solver.Sum([pict[i + a, j + b] + for a in S for b in S + if i + a >= 0 and + j + b >= 0 and + i + a < n and + j + b < n]) + ) + + # + # solution and search + # + db = solver.Phase(pict_flat, + solver.INT_VAR_DEFAULT, + solver.INT_VALUE_DEFAULT) + + solver.NewSearch(db) + num_solutions = 0 + print 'Solution:' + while solver.NextSolution(): + num_solutions += 1 for i in range(n): - for j in range(n): - if puzzle[i][j] == X: - sys.stdout.write('.') - else: - sys.stdout.write(str(puzzle[i][j])) - print + row = [str(pict[i, j].Value()) for j in range(n)] + for j in range(n): + if row[j] == '0': + row[j] = ' ' + else: + row[j] = '#' + print ''.join(row) print - # - # declare variables - # - pict = {} - for i in range(n): - for j in range(n): - pict[(i,j)] = solver.IntVar(0,1, 'pict %i %i' % (i, j)) - - pict_flat = [pict[i,j] for i in range(n) for j in range(n)] - - # - # constraints - # - for i in range(n): - for j in range(n): - if puzzle[i][j] > X: - # this cell is the sum of all the surrounding cells - solver.Add( - puzzle[i][j] == solver.Sum([pict[i+a,j+b] - for a in S for b in S - if i + a >=0 and - j + b >=0 and - i + a < n and - j + b < n - ]) - ) - - # - # solution and search - # - db = solver.Phase(pict_flat, - solver.INT_VAR_DEFAULT, - solver.INT_VALUE_DEFAULT) - - solver.NewSearch(db) - num_solutions = 0 - print "Solution:" - while solver.NextSolution(): - num_solutions += 1 - for i in range(n): - row = [str(pict[i,j].Value()) for j in range(n)] - for j in range(n): - if row[j] == '0': - row[j] = ' ' - else: - row[j] = '#' - print "".join(row) - print - - print 'num_solutions:', num_solutions - print 'failures:', solver.Failures() - print 'branches:', solver.Branches() - print 'WallTime:', solver.WallTime(), 'ms' + print 'num_solutions:', num_solutions + print 'failures:', solver.Failures() + print 'branches:', solver.Branches() + print 'WallTime:', solver.WallTime(), 'ms' # # Read a problem instance from a file # def read_problem(file): - f = open(file, 'r') - n = int(f.readline()) - puzzle = [] - for i in range(n): - x = f.readline() - row = [0]*n - for j in range(n): - if x[j] == '.': - tmp = -1 - else: - tmp = int(x[j]) - row[j] = tmp - puzzle.append(row) - return [puzzle, n] + f = open(file, 'r') + n = int(f.readline()) + puzzle = [] + for i in range(n): + x = f.readline() + row = [0] * n + for j in range(n): + if x[j] == '.': + tmp = -1 + else: + tmp = int(x[j]) + row[j] = tmp + puzzle.append(row) + return [puzzle, n] if __name__ == '__main__': - if len(sys.argv) > 1: - file = sys.argv[1] - print 'Problem instance from', file - [puzzle, n] = read_problem(file) - main(puzzle, n) - else: - main() + if len(sys.argv) > 1: + file = sys.argv[1] + print 'Problem instance from', file + [puzzle, n] = read_problem(file) + main(puzzle, n) + else: + main() diff --git a/examples/python/furniture_moving.py b/examples/python/furniture_moving.py index 7c5d9a9971..e521387b40 100644 --- a/examples/python/furniture_moving.py +++ b/examples/python/furniture_moving.py @@ -33,9 +33,11 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ -import sys, string +import sys +import string from ortools.constraint_solver import pywrapcp @@ -61,115 +63,113 @@ from ortools.constraint_solver import pywrapcp # def my_cumulative(solver, s, d, r, b): - # tasks = [i for i in range(len(s))] - tasks = [i for i in range(len(s)) if r[i] > 0 and d[i] > 0] - times_min = min([s[i].Min() for i in tasks]) - times_max = max([s[i].Max() + max(d) for i in tasks]) - for t in xrange(times_min, times_max+1): - bb = [] - for i in tasks: - c1 = solver.IsLessOrEqualCstVar(s[i], t) # s[i] <= t - c2 = solver.IsGreaterCstVar(s[i]+d[i], t) # t < s[i] + d[i] - bb.append(c1*c2*r[i]) - solver.Add(solver.Sum(bb) <= b) + # tasks = [i for i in range(len(s))] + tasks = [i for i in range(len(s)) if r[i] > 0 and d[i] > 0] + times_min = min([s[i].Min() for i in tasks]) + times_max = max([s[i].Max() + max(d) for i in tasks]) + for t in xrange(times_min, times_max + 1): + bb = [] + for i in tasks: + c1 = solver.IsLessOrEqualCstVar(s[i], t) # s[i] <= t + c2 = solver.IsGreaterCstVar(s[i] + d[i], t) # t < s[i] + d[i] + bb.append(c1 * c2 * r[i]) + solver.Add(solver.Sum(bb) <= b) - # Somewhat experimental: - # This constraint is needed to contrain the upper limit of b. - if not isinstance(b, int): - solver.Add(b <= sum(r)) + # Somewhat experimental: + # This constraint is needed to contrain the upper limit of b. + if not isinstance(b, int): + solver.Add(b <= sum(r)) def main(): - # Create the solver. - solver = pywrapcp.Solver('Furniture moving') + # Create the solver. + solver = pywrapcp.Solver("Furniture moving") - # - # data - # - n = 4 - duration = [30,10,15,15] - demand = [ 3, 1, 3, 2] - upper_limit = 160 + # + # data + # + n = 4 + duration = [30, 10, 15, 15] + demand = [3, 1, 3, 2] + upper_limit = 160 - # - # declare variables - # - start_times = [solver.IntVar(0, upper_limit, 'start_times[%i]'%i) for i in range(n)] - end_times = [solver.IntVar(0, upper_limit*2, 'end_times[%i]'%i) for i in range(n)] - end_time = solver.IntVar(0, upper_limit*2, 'end_time') + # + # declare variables + # + start_times = [ + solver.IntVar(0, upper_limit, "start_times[%i]" % i) for i in range(n)] + end_times = [ + solver.IntVar(0, upper_limit * 2, "end_times[%i]" % i) for i in range(n)] + end_time = solver.IntVar(0, upper_limit * 2, "end_time") - # number of needed resources, to be minimized - num_resources = solver.IntVar(0, 10, 'num_resources') + # number of needed resources, to be minimized + num_resources = solver.IntVar(0, 10, "num_resources") + # + # constraints + # + for i in range(n): + solver.Add(end_times[i] == start_times[i] + duration[i]) - # - # constraints - # - for i in range(n): - solver.Add(end_times[i] == start_times[i] + duration[i]) + solver.Add(end_time == solver.Max(end_times)) - solver.Add(end_time == solver.Max(end_times)) + my_cumulative(solver, start_times, duration, demand, num_resources) - my_cumulative(solver, start_times, duration, demand, num_resources) + # + # Some extra constraints to play with + # + # all tasks must end within an hour + # solver.Add(end_time <= 60) - # - # Some extra constraints to play with - # + # All tasks should start at time 0 + # for i in range(n): + # solver.Add(start_times[i] == 0) - ## all tasks must end within an hour - # solver.Add(end_time <= 60) + # limitation of the number of people + # solver.Add(num_resources <= 3) - ## All tasks should start at time 0 - # for i in range(n): - # solver.Add(start_times[i] == 0) + # + # objective + # + # objective = solver.Minimize(end_time, 1) + objective = solver.Minimize(num_resources, 1) + # + # solution and search + # + solution = solver.Assignment() + solution.Add(start_times) + solution.Add(end_times) + solution.Add(end_time) + solution.Add(num_resources) - ## limitation of the number of people - # solver.Add(num_resources <= 3) - - - # - # objective - # - # objective = solver.Minimize(end_time, 1) - objective = solver.Minimize(num_resources, 1) - - # - # solution and search - # - solution = solver.Assignment() - solution.Add(start_times) - solution.Add(end_times) - solution.Add(end_time) - solution.Add(num_resources) - - db = solver.Phase(start_times, - solver.CHOOSE_FIRST_UNBOUND, - solver.ASSIGN_MIN_VALUE) - - # - # result - # - solver.NewSearch(db, [objective]) - num_solutions = 0 - while solver.NextSolution(): - num_solutions += 1 - print "num_resources:", num_resources.Value() - print "start_times :", [start_times[i].Value() for i in range(n)] - print "duration :", [duration[i] for i in range(n)] - print "end_times :", [end_times[i].Value() for i in range(n)] - print "end_time :", end_time.Value() - print - - solver.EndSearch() + db = solver.Phase(start_times, + solver.CHOOSE_FIRST_UNBOUND, + solver.ASSIGN_MIN_VALUE) + # + # result + # + solver.NewSearch(db, [objective]) + num_solutions = 0 + while solver.NextSolution(): + num_solutions += 1 + print "num_resources:", num_resources.Value() + print "start_times :", [start_times[i].Value() for i in range(n)] + print "duration :", [duration[i] for i in range(n)] + print "end_times :", [end_times[i].Value() for i in range(n)] + print "end_time :", end_time.Value() print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() -if __name__ == '__main__': - main() + solver.EndSearch() + + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() + +if __name__ == "__main__": + main() diff --git a/examples/python/futoshiki.py b/examples/python/futoshiki.py index 7c52ee0c27..c61b25ede5 100644 --- a/examples/python/futoshiki.py +++ b/examples/python/futoshiki.py @@ -42,7 +42,8 @@ * SICStus: http://hakank.org/sicstus/futoshiki.pl This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ from ortools.constraint_solver import pywrapcp @@ -50,77 +51,72 @@ from ortools.constraint_solver import pywrapcp def main(values, lt): - # Create the solver. - solver = pywrapcp.Solver('Futoshiki problem') + # Create the solver. + solver = pywrapcp.Solver("Futoshiki problem") - # - # data - # - size = len(values) - RANGE = range(size) - NUMQD = range(len(lt)) + # + # data + # + size = len(values) + RANGE = range(size) + NUMQD = range(len(lt)) + # + # variables + # + field = {} + for i in RANGE: + for j in RANGE: + field[i, j] = solver.IntVar(1, size, "field[%i,%i]" % (i, j)) + field_flat = [field[i, j] for i in RANGE for j in RANGE] - # - # variables - # - field = {} - for i in RANGE: - for j in RANGE: - field[i,j] = solver.IntVar(1, size, "field[%i,%i]" % (i,j)) - field_flat = [field[i,j] for i in RANGE for j in RANGE] - - # - # constraints - # - # set initial values - for row in RANGE: - for col in RANGE: - if values[row][col] > 0: - solver.Add(field[row,col] == values[row][col]) - - - # all rows have to be different - for row in RANGE: - solver.Add(solver.AllDifferent([field[row,col] for col in RANGE])) - - - # all columns have to be different + # + # constraints + # + # set initial values + for row in RANGE: for col in RANGE: - solver.Add(solver.AllDifferent([field[row,col] for row in RANGE])) + if values[row][col] > 0: + solver.Add(field[row, col] == values[row][col]) + # all rows have to be different + for row in RANGE: + solver.Add(solver.AllDifferent([field[row, col] for col in RANGE])) - # all < constraints are satisfied - # Also: make 0-based - for i in NUMQD: - solver.Add(field[ lt[i][0]-1, lt[i][1]-1 ] < - field[ lt[i][2]-1, lt[i][3]-1 ] ) + # all columns have to be different + for col in RANGE: + solver.Add(solver.AllDifferent([field[row, col] for row in RANGE])) + # all < constraints are satisfied + # Also: make 0-based + for i in NUMQD: + solver.Add(field[lt[i][0] - 1, lt[i][1] - 1] < + field[lt[i][2] - 1, lt[i][3] - 1]) - # - # search and result - # - db = solver.Phase(field_flat, - solver.CHOOSE_FIRST_UNBOUND, - solver.ASSIGN_MIN_VALUE) + # + # search and result + # + db = solver.Phase(field_flat, + solver.CHOOSE_FIRST_UNBOUND, + solver.ASSIGN_MIN_VALUE) - solver.NewSearch(db) + solver.NewSearch(db) - num_solutions = 0 - while solver.NextSolution(): - num_solutions += 1 - for i in RANGE: - for j in RANGE: - print field[i,j].Value(), - print - print + num_solutions = 0 + while solver.NextSolution(): + num_solutions += 1 + for i in RANGE: + for j in RANGE: + print field[i, j].Value(), + print + print - solver.EndSearch() + solver.EndSearch() - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() # @@ -146,17 +142,17 @@ values1 = [ # [i1,j1, i2,j2] requires that values[i1,j1] < values[i2,j2] # Note: 1-based lt1 = [ - [1,2, 1,1], - [1,4, 1,5], - [2,3, 1,3], - [3,3, 2,3], - [3,4, 2,4], - [2,5, 3,5], - [3,2, 4,2], - [4,4, 4,3], - [5,2, 5,1], - [5,4, 5,3], - [5,5, 4,5]] + [1, 2, 1, 1], + [1, 4, 1, 5], + [2, 3, 1, 3], + [3, 3, 2, 3], + [3, 4, 2, 4], + [2, 5, 3, 5], + [3, 2, 4, 2], + [4, 4, 4, 3], + [5, 2, 5, 1], + [5, 4, 5, 3], + [5, 5, 4, 5]] # @@ -177,17 +173,17 @@ values2 = [ # Note: 1-based lt2 = [ - [1,2, 1,1], - [1,4, 1,3], - [1,5, 1,4], - [4,4, 4,5], - [5,1, 5,2], - [5,2, 5,3] - ] + [1, 2, 1, 1], + [1, 4, 1, 3], + [1, 5, 1, 4], + [4, 4, 4, 5], + [5, 1, 5, 2], + [5, 2, 5, 3] +] -if __name__ == '__main__': - print "Problem 1" - main(values1, lt1) - print "\nProblem 2" - main(values2, lt2) +if __name__ == "__main__": + print "Problem 1" + main(values1, lt1) + print "\nProblem 2" + main(values2, lt2) diff --git a/examples/python/game_theory_taha.py b/examples/python/game_theory_taha.py index 45891747d0..ce18030955 100644 --- a/examples/python/game_theory_taha.py +++ b/examples/python/game_theory_taha.py @@ -21,13 +21,15 @@ From Taha, Operations Research (8'th edition), page 528. This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ import sys from ortools.linear_solver import pywraplp -def main(sol = 'GLPK'): + +def main(sol='GLPK'): # Create the solver. @@ -40,16 +42,13 @@ def main(sol = 'GLPK'): solver = pywraplp.Solver('CoinsGridCLP', pywraplp.Solver.CLP_LINEAR_PROGRAMMING) - # data rows = 3 cols = 3 game = [[3.0, -1.0, -3.0], - [-2.0, 4.0, -1.0], - [-5.0, -6.0, 2.0] - ] - + [-2.0, 4.0, -1.0], + [-5.0, -6.0, 2.0]] # # declare variables @@ -58,13 +57,13 @@ def main(sol = 'GLPK'): # # row player # - x1 = [solver.NumVar(0, 1, 'x1[%i]' % i ) - for i in range(rows)] + x1 = [solver.NumVar(0, 1, 'x1[%i]' % i) + for i in range(rows)] v = solver.NumVar(-2, 2, 'v') for i in range(rows): - solver.Add(v - solver.Sum([x1[j]*game[j][i] for j in range(cols)]) <= 0) + solver.Add(v - solver.Sum([x1[j] * game[j][i] for j in range(cols)]) <= 0) solver.Add(solver.Sum(x1) == 1) @@ -73,7 +72,7 @@ def main(sol = 'GLPK'): solver.Solve() print - print 'row player:'; + print 'row player:' print 'v = ', solver.Objective().Value() print 'Strategies: ' for i in range(rows): @@ -81,17 +80,16 @@ def main(sol = 'GLPK'): print print - # # For column player: # - x2 = [solver.NumVar(0, 1, 'x2[%i]' % i ) - for i in range(cols)] + x2 = [solver.NumVar(0, 1, 'x2[%i]' % i) + for i in range(cols)] v2 = solver.NumVar(-2, 2, 'v2') for i in range(cols): - solver.Add(v2 - solver.Sum([x2[j]*game[i][j] for j in range(rows)]) >= 0) + solver.Add(v2 - solver.Sum([x2[j] * game[i][j] for j in range(rows)]) >= 0) solver.Add(solver.Sum(x2) == 1) @@ -100,14 +98,13 @@ def main(sol = 'GLPK'): solver.Solve() print - print 'column player:'; + print 'column player:' print 'v2 = ', solver.Objective().Value() print 'Strategies: ' for i in range(rows): print x2[i].SolutionValue(), print - print print 'walltime :', solver.WallTime(), 'ms' print 'iterations:', solver.Iterations() diff --git a/examples/python/golomb8.py b/examples/python/golomb8.py index 690d1fbcc9..d49429f1de 100644 --- a/examples/python/golomb8.py +++ b/examples/python/golomb8.py @@ -23,7 +23,6 @@ of the rule. """ - from google.apputils import app import gflags from ortools.constraint_solver import pywrapcp @@ -50,7 +49,7 @@ def main(unused_argv): solver.Add(marks[0] == 0) solver.Add(solver.AllDifferent([marks[j] - marks[i] for i in range(0, size - 1) - for j in range(i +1, size)])) + for j in range(i + 1, size)])) solver.Add(marks[size - 1] - marks[size - 2] > marks[1] - marks[0]) for i in range(0, size - 2): @@ -65,7 +64,7 @@ def main(unused_argv): solver.ASSIGN_MIN_VALUE), [objective, collector]) for i in range(0, collector.SolutionCount()): - obj_value = collector.Value(i, marks[size -1]) + obj_value = collector.Value(i, marks[size - 1]) time = collector.WallTime(i) branches = collector.Branches(i) failures = collector.Failures(i) diff --git a/examples/python/grocery.py b/examples/python/grocery.py index db6e02210f..ff2a82d178 100644 --- a/examples/python/grocery.py +++ b/examples/python/grocery.py @@ -33,7 +33,8 @@ * Zinc: http://hakank.org/minizinc/grocery.zinc This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ import sys @@ -44,51 +45,51 @@ from ortools.constraint_solver import pywrapcp def main(): - # Create the solver. - solver = pywrapcp.Solver('Grocery') + # Create the solver. + solver = pywrapcp.Solver("Grocery") - # - # data - # - n = 4 - c = 711 + # + # data + # + n = 4 + c = 711 - # - # declare variables - # - item = [solver.IntVar(0, c, "item[%i]" % i) for i in range(n)] + # + # declare variables + # + item = [solver.IntVar(0, c, "item[%i]" % i) for i in range(n)] - # - # constraints - # - solver.Add(solver.Sum(item) == c) - solver.Add(reduce(lambda x, y: x * y, item) == c * 100**3) + # + # constraints + # + solver.Add(solver.Sum(item) == c) + solver.Add(reduce(lambda x, y: x * y, item) == c * 100 ** 3) - # symmetry breaking - for i in range(1,n): - solver.Add(item[i-1] < item[i]) + # symmetry breaking + for i in range(1, n): + solver.Add(item[i - 1] < item[i]) - # - # search and result - # - db = solver.Phase(item, - solver.INT_VAR_SIMPLE, - solver.INT_VALUE_SIMPLE) - - solver.NewSearch(db) - num_solutions = 0 - while solver.NextSolution(): - print "item:", [item[i].Value() for i in range(n)] - print - num_solutions += 1 - - solver.EndSearch() + # + # search and result + # + db = solver.Phase(item, + solver.INT_VAR_SIMPLE, + solver.INT_VALUE_SIMPLE) + solver.NewSearch(db) + num_solutions = 0 + while solver.NextSolution(): + print "item:", [item[i].Value() for i in range(n)] print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + num_solutions += 1 -if __name__ == '__main__': - main() + solver.EndSearch() + + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() + +if __name__ == "__main__": + main() diff --git a/examples/python/hidato.py b/examples/python/hidato.py index 4189768c6e..7be074d206 100644 --- a/examples/python/hidato.py +++ b/examples/python/hidato.py @@ -38,7 +38,8 @@ (and more elegant) model: hidato_table.py . This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ from ortools.constraint_solver import pywrapcp @@ -46,22 +47,22 @@ from ortools.constraint_solver import pywrapcp def main(): - # Create the solver. - solver = pywrapcp.Solver('n-queens') + # Create the solver. + solver = pywrapcp.Solver("n-queens") - # - # data - # - # - # Simple problem - # - # r = 3 - # c = r - # puzzle = [ - # [6,0,9], - # [0,2,8], - # [1,0,0] - # ] + # + # data + # + # + # Simple problem + # + # r = 3 + # c = r + # puzzle = [ + # [6,0,9], + # [0,2,8], + # [1,0,0] + # ] # r = 7 @@ -76,34 +77,33 @@ def main(): # [0, 0, 0,14, 0, 0, 0] # ] + # Problems from the book: + # Gyora Bededek: "Hidato: 2000 Pure Logic Puzzles" - # Problems from the book: - # Gyora Bededek: "Hidato: 2000 Pure Logic Puzzles" - - # Problem 1 (Practice) - # r = 5 - # c = r - # puzzle = [ - # [ 0, 0,20, 0, 0], - # [ 0, 0, 0,16,18], - # [22, 0,15, 0, 0], - # [23, 0, 1,14,11], - # [ 0,25, 0, 0,12], - # ] + # Problem 1 (Practice) + # r = 5 + # c = r + # puzzle = [ + # [ 0, 0,20, 0, 0], + # [ 0, 0, 0,16,18], + # [22, 0,15, 0, 0], + # [23, 0, 1,14,11], + # [ 0,25, 0, 0,12], + # ] # # problem 2 (Practice) - r = 5 - c = r - puzzle= [ - [0, 0, 0, 0,14], - [0,18,12, 0, 0], - [0, 0,17, 4, 5], - [0, 0, 7, 0, 0], - [9, 8,25, 1, 0], - ]; + r = 5 + c = r + puzzle = [ + [0, 0, 0, 0, 14], + [0, 18, 12, 0, 0], + [0, 0, 17, 4, 5], + [0, 0, 7, 0, 0], + [9, 8, 25, 1, 0], + ] - # problem 3 (Beginner) + # problem 3 (Beginner) # r = 6 # c = r # puzzle = [ @@ -115,9 +115,8 @@ def main(): # [35,36, 0,10, 0, 0] # ]; - - # Problem 15 (Intermediate) - # Note: This takes very long time to solve... + # Problem 15 (Intermediate) + # Note: This takes very long time to solve... # r = 8 # c = r # puzzle = [ @@ -131,121 +130,111 @@ def main(): # [28,30, 0,35, 0, 0, 0, 0] # ] + print_game(puzzle, r, c) - print_game(puzzle, r,c) + # + # declare variables + # + x = {} + for i in range(r): + for j in range(c): + x[(i, j)] = solver.IntVar(1, r * c, "dice(%i,%i)" % (i, j)) + x_flat = [x[(i, j)] for i in range(r) for j in range(c)] - # - # declare variables - # - x = {} - for i in range(r): - for j in range(c): - x[(i,j)] = solver.IntVar(1,r*c, 'dice(%i,%i)' % (i, j)) - x_flat = [x[(i,j)] for i in range(r) for j in range(c)] + # + # constraints + # + solver.Add(solver.AllDifferent(x_flat)) + # + # Fill in the clues + # + for i in range(r): + for j in range(c): + if puzzle[i][j] > 0: + solver.Add(x[(i, j)] == puzzle[i][j]) + # From the numbers k = 1 to r*c-1, find this position, + # and then the position of k+1 + for k in range(1, r * c): + i = solver.IntVar(0, r) + j = solver.IntVar(0, c) + a = solver.IntVar(-1, 1) + b = solver.IntVar(-1, 1) - # - # constraints - # - solver.Add(solver.AllDifferent(x_flat)) + # 1) First: fix "this" k + # 2) and then find the position of the next value (k+1) + # solver.Add(k == x[(i,j)]) + solver.Add(k == solver.Element(x_flat, i * c + j)) + # solver.Add(k + 1 == x[(i+a,j+b)]) + solver.Add(k + 1 == solver.Element(x_flat, (i + a) * c + (j + b))) - # - # Fill in the clues - # - for i in range(r): - for j in range(c): - if puzzle[i][j] > 0: - solver.Add(x[(i,j)] == puzzle[i][j]) + solver.Add(i + a >= 0) + solver.Add(j + b >= 0) + solver.Add(i + a < r) + solver.Add(j + b < c) + # solver.Add(((a != 0) | (b != 0))) + a_nz = solver.BoolVar() + b_nz = solver.BoolVar() + solver.Add(a_nz == solver.IsDifferentCstVar(a, 0)) + solver.Add(b_nz == solver.IsDifferentCstVar(b, 0)) + solver.Add(a_nz + b_nz >= 1) + # + # solution and search + # + solution = solver.Assignment() + solution.Add(x_flat) - # From the numbers k = 1 to r*c-1, find this position, - # and then the position of k+1 - for k in range(1,r*c): - i = solver.IntVar(0,r) - j = solver.IntVar(0,c) - a = solver.IntVar(-1,1) - b = solver.IntVar(-1,1) - - # 1) First: fix "this" k - # 2) and then find the position of the next value (k+1) - # solver.Add(k == x[(i,j)]) - solver.Add(k == solver.Element(x_flat, i*c+j)) - # solver.Add(k + 1 == x[(i+a,j+b)]) - solver.Add(k + 1 == solver.Element(x_flat, (i+a)*c+(j+b))) - - solver.Add(i+a >= 0) - solver.Add(j+b >= 0) - solver.Add(i+a < r) - solver.Add(j+b < c) - - # solver.Add(((a != 0) | (b != 0))) - a_nz = solver.BoolVar() - b_nz = solver.BoolVar() - solver.Add(a_nz == solver.IsDifferentCstVar(a,0)) - solver.Add(b_nz == solver.IsDifferentCstVar(b,0)) - solver.Add(a_nz + b_nz >= 1) - - - - # - # solution and search - # - solution = solver.Assignment() - solution.Add(x_flat) - - - # db: DecisionBuilder - db = solver.Phase(x_flat, - #solver.INT_VAR_DEFAULT - #solver.INT_VAR_SIMPLE - solver.CHOOSE_FIRST_UNBOUND - # solver.CHOOSE_RANDOM - #solver.CHOOSE_MIN_SIZE_LOWEST_MIN - #solver.CHOOSE_MIN_SIZE_HIGHEST_MIN - #solver.CHOOSE_MIN_SIZE_LOWEST_MAX - #solver.CHOOSE_MIN_SIZE_HIGHEST_MAX - #solver.CHOOSE_PATH - , - # solver.INT_VALUE_DEFAULT - # solver.INT_VALUE_SIMPLE - solver.ASSIGN_MIN_VALUE - #solver.ASSIGN_MAX_VALUE - #solver.ASSIGN_RANDOM_VALUE - #solver.ASSIGN_CENTER_VALUE - ) - - solver.NewSearch(db) - num_solutions = 0 - while solver.NextSolution(): - num_solutions += 1 - print "\nSolution:", num_solutions - print_board(x, r, c) - print - - solver.EndSearch() + # db: DecisionBuilder + db = solver.Phase(x_flat, + # solver.INT_VAR_DEFAULT + # solver.INT_VAR_SIMPLE + # solver.CHOOSE_RANDOM + # solver.CHOOSE_MIN_SIZE_LOWEST_MIN + # solver.CHOOSE_MIN_SIZE_HIGHEST_MIN + # solver.CHOOSE_MIN_SIZE_LOWEST_MAX + # solver.CHOOSE_MIN_SIZE_HIGHEST_MAX + # solver.CHOOSE_PATH + solver.CHOOSE_FIRST_UNBOUND, + # solver.INT_VALUE_DEFAULT + # solver.INT_VALUE_SIMPLE + # solver.ASSIGN_MAX_VALUE + # solver.ASSIGN_RANDOM_VALUE + # solver.ASSIGN_CENTER_VALUE + solver.ASSIGN_MIN_VALUE) + solver.NewSearch(db) + num_solutions = 0 + while solver.NextSolution(): + num_solutions += 1 + print "\nSolution:", num_solutions + print_board(x, r, c) print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + + solver.EndSearch() + + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() def print_board(x, rows, cols): - for i in range(rows): - for j in range(cols): - print "% 2s" % x[i,j].Value(), - print '' + for i in range(rows): + for j in range(cols): + print "% 2s" % x[i, j].Value(), + print "" + def print_game(game, rows, cols): - for i in range(rows): - for j in range(cols): - print "% 2s" % game[i][j], - print '' + for i in range(rows): + for j in range(cols): + print "% 2s" % game[i][j], + print "" - -if __name__ == '__main__': - main() +if __name__ == "__main__": + main() diff --git a/examples/python/hidato_table.py b/examples/python/hidato_table.py index 3e32a1bf23..1921a8e96d 100644 --- a/examples/python/hidato_table.py +++ b/examples/python/hidato_table.py @@ -101,7 +101,7 @@ def Solve(model): [9, 8, 25, 1, 0]] elif model == 5: - # problem 3 (Beginner) + # problem 3 (Beginner) puzzle = [[0, 26, 0, 0, 0, 18], [0, 0, 27, 0, 0, 19], [31, 23, 0, 0, 14, 0], @@ -194,7 +194,7 @@ def PrintMatrix(game): rows = len(game) cols = len(game[0]) for i in range(rows): - line = "" + line = '' for j in range(cols): if game[i][j] == 0: line += ' .' diff --git a/examples/python/jobshop_ft06.py b/examples/python/jobshop_ft06.py index 664cde18af..f553955838 100644 --- a/examples/python/jobshop_ft06.py +++ b/examples/python/jobshop_ft06.py @@ -24,7 +24,6 @@ jobs. This is called the makespan. """ - from google.apputils import app import gflags from ortools.constraint_solver import pywrapcp diff --git a/examples/python/just_forgotten.py b/examples/python/just_forgotten.py index b63ef4d169..d708c7b2cd 100644 --- a/examples/python/just_forgotten.py +++ b/examples/python/just_forgotten.py @@ -42,7 +42,8 @@ * Gecpde: http://hakank.org/gecode/just_forgotten.cpp This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ from ortools.constraint_solver import pywrapcp @@ -50,69 +51,68 @@ from ortools.constraint_solver import pywrapcp def main(): - # Create the solver. - solver = pywrapcp.Solver('Just forgotten') + # Create the solver. + solver = pywrapcp.Solver("Just forgotten") - # - # data - # - rows = 4 - cols = 10 - # The four tries - a = [[9,4,6,2,1,5,7,8,3,0], - [8,6,0,4,3,9,1,2,5,7], - [1,6,4,0,2,9,7,8,5,3], - [6,8,2,4,3,1,9,0,7,5]] + # + # data + # + rows = 4 + cols = 10 + # The four tries + a = [[9, 4, 6, 2, 1, 5, 7, 8, 3, 0], + [8, 6, 0, 4, 3, 9, 1, 2, 5, 7], + [1, 6, 4, 0, 2, 9, 7, 8, 5, 3], + [6, 8, 2, 4, 3, 1, 9, 0, 7, 5]] - # - # variables - # - x = [solver.IntVar(0, 9, "x[%i]" % j) for j in range(cols)] + # + # variables + # + x = [solver.IntVar(0, 9, "x[%i]" % j) for j in range(cols)] - # - # constraints - # - solver.Add(solver.AllDifferent(x)) + # + # constraints + # + solver.Add(solver.AllDifferent(x)) - for r in range(rows): - b = [solver.IsEqualCstVar(x[c], a[r][c]) for c in range(cols)] - solver.Add(solver.Sum(b) == 4) + for r in range(rows): + b = [solver.IsEqualCstVar(x[c], a[r][c]) for c in range(cols)] + solver.Add(solver.Sum(b) == 4) + # + # search and result + # + db = solver.Phase(x, + solver.INT_VAR_SIMPLE, + solver.INT_VALUE_DEFAULT) - # - # search and result - # - db = solver.Phase(x, - solver.INT_VAR_SIMPLE, - solver.INT_VALUE_DEFAULT) + solver.NewSearch(db) - solver.NewSearch(db) - - num_solutions = 0 - while solver.NextSolution(): - num_solutions += 1 - xval = [x[j].Value() for j in range(cols)] - print "Account number:" - for j in range(cols): - print "%i " % xval[j], - print - print "\nThe four tries, where '!' represents a correct digit:" - for i in range(rows): - for j in range(cols): - check = " " - if a[i][j] == xval[j]: - check = "!" - print "%i%s" % (a[i][j], check), - print - print + num_solutions = 0 + while solver.NextSolution(): + num_solutions += 1 + xval = [x[j].Value() for j in range(cols)] + print "Account number:" + for j in range(cols): + print "%i " % xval[j], print + print "\nThe four tries, where '!' represents a correct digit:" + for i in range(rows): + for j in range(cols): + check = " " + if a[i][j] == xval[j]: + check = "!" + print "%i%s" % (a[i][j], check), + print + print + print - solver.EndSearch() + solver.EndSearch() - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() -if __name__ == '__main__': - main() +if __name__ == "__main__": + main() diff --git a/examples/python/kakuro.py b/examples/python/kakuro.py index c7e2b5217a..ad072e77f6 100644 --- a/examples/python/kakuro.py +++ b/examples/python/kakuro.py @@ -52,7 +52,8 @@ * Gecode: http://www.hakank.org/gecode/kenken2.cpp This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ import sys @@ -63,141 +64,140 @@ from ortools.constraint_solver import pywrapcp # Ensure that the sum of the segments # in cc == res # + + def calc(cc, x, res): - solver = x.values()[0].solver() + solver = x.values()[0].solver() - # ensure that the values are positive - for i in cc: - solver.Add(x[i[0]-1, i[1]-1] >= 1) + # ensure that the values are positive + for i in cc: + solver.Add(x[i[0] - 1, i[1] - 1] >= 1) - # sum the numbers - solver.Add(solver.Sum([x[i[0]-1,i[1]-1] for i in cc]) == res) + # sum the numbers + solver.Add(solver.Sum([x[i[0] - 1, i[1] - 1] for i in cc]) == res) def main(): - # Create the solver. - solver = pywrapcp.Solver('Kakuro') + # Create the solver. + solver = pywrapcp.Solver("Kakuro") - # - # data - # + # + # data + # - # size of matrix - n = 7 + # size of matrix + n = 7 - # segments - # [sum, [segments]] - # Note: 1-based - problem = [ - [16, [1,1],[1,2]], - [24, [1,5],[1,6],[1,7]], - [17, [2,1],[2,2]], - [29, [2,4],[2,5],[2,6],[2,7]], - [35, [3,1],[3,2],[3,3],[3,4],[3,5]], - [ 7, [4,2],[4,3]], - [ 8, [4,5],[4,6]], - [16, [5,3],[5,4],[5,5],[5,6],[5,7]], - [21, [6,1],[6,2],[6,3],[6,4]], - [ 5, [6,6],[6,7]], - [ 6, [7,1],[7,2],[7,3]], - [ 3, [7,6],[7,7]], + # segments + # [sum, [segments]] + # Note: 1-based + problem = [ + [16, [1, 1], [1, 2]], + [24, [1, 5], [1, 6], [1, 7]], + [17, [2, 1], [2, 2]], + [29, [2, 4], [2, 5], [2, 6], [2, 7]], + [35, [3, 1], [3, 2], [3, 3], [3, 4], [3, 5]], + [7, [4, 2], [4, 3]], + [8, [4, 5], [4, 6]], + [16, [5, 3], [5, 4], [5, 5], [5, 6], [5, 7]], + [21, [6, 1], [6, 2], [6, 3], [6, 4]], + [5, [6, 6], [6, 7]], + [6, [7, 1], [7, 2], [7, 3]], + [3, [7, 6], [7, 7]], - [23, [1,1],[2,1],[3,1]], - [30, [1,2],[2,2],[3,2],[4,2]], - [27, [1,5],[2,5],[3,5],[4,5],[5,5]], - [12, [1,6],[2,6]], - [16, [1,7],[2,7]], - [17, [2,4],[3,4]], - [15, [3,3],[4,3],[5,3],[6,3],[7,3]], - [12, [4,6],[5,6],[6,6],[7,6]], - [ 7, [5,4],[6,4]], - [ 7, [5,7],[6,7],[7,7]], - [11, [6,1],[7,1]], - [10, [6,2],[7,2]] - ] + [23, [1, 1], [2, 1], [3, 1]], + [30, [1, 2], [2, 2], [3, 2], [4, 2]], + [27, [1, 5], [2, 5], [3, 5], [4, 5], [5, 5]], + [12, [1, 6], [2, 6]], + [16, [1, 7], [2, 7]], + [17, [2, 4], [3, 4]], + [15, [3, 3], [4, 3], [5, 3], [6, 3], [7, 3]], + [12, [4, 6], [5, 6], [6, 6], [7, 6]], + [7, [5, 4], [6, 4]], + [7, [5, 7], [6, 7], [7, 7]], + [11, [6, 1], [7, 1]], + [10, [6, 2], [7, 2]] + ] - num_p = len(problem) + num_p = len(problem) - # The blanks - # Note: 1-based - blanks = [ - [1,3], [1,4], - [2,3], - [3,6], [3,7], - [4,1], [4,4], [4,7], - [5,1], [5,2], - [6,5], - [7,4], [7,5] - ] - num_blanks = len(blanks) + # The blanks + # Note: 1-based + blanks = [ + [1, 3], [1, 4], + [2, 3], + [3, 6], [3, 7], + [4, 1], [4, 4], [4, 7], + [5, 1], [5, 2], + [6, 5], + [7, 4], [7, 5] + ] + num_blanks = len(blanks) - # - # variables - # + # + # variables + # - # the set - x = {} + # the set + x = {} + for i in range(n): + for j in range(n): + x[i, j] = solver.IntVar(0, 9, "x[%i,%i]" % (i, j)) + + x_flat = [x[i, j] for i in range(n) for j in range(n)] + + # + # constraints + # + + # fill the blanks with 0 + for i in range(num_blanks): + solver.Add(x[blanks[i][0] - 1, blanks[i][1] - 1] == 0) + + for i in range(num_p): + segment = problem[i][1::] + res = problem[i][0] + + # sum this segment + calc(segment, x, res) + + # all numbers in this segment must be distinct + segment = [x[p[0] - 1, p[1] - 1] for p in segment] + solver.Add(solver.AllDifferent(segment)) + + # + # search and solution + # + db = solver.Phase(x_flat, + solver.INT_VAR_DEFAULT, + solver.INT_VALUE_DEFAULT) + + solver.NewSearch(db) + + num_solutions = 0 + while solver.NextSolution(): for i in range(n): - for j in range(n): - x[i,j] = solver.IntVar(0, 9, 'x[%i,%i]' % (i,j)) - - x_flat = [x[i,j] for i in range(n) for j in range(n)] - - # - # constraints - # - - # fill the blanks with 0 - for i in range(num_blanks): - solver.Add(x[blanks[i][0]-1,blanks[i][1]-1]==0) - - - for i in range(num_p): - segment = problem[i][1::] - res = problem[i][0] - - # sum this segment - calc(segment, x, res) - - # all numbers in this segment must be distinct - segment = [x[p[0]-1, p[1]-1] for p in segment] - solver.Add(solver.AllDifferent(segment)) - - - - # - # search and solution - # - db = solver.Phase(x_flat, - solver.INT_VAR_DEFAULT, - solver.INT_VALUE_DEFAULT) - - solver.NewSearch(db) - - num_solutions = 0 - while solver.NextSolution(): - for i in range(n): - for j in range(n): - val = x[i,j].Value() - if val > 0: - print val, - else: - print " ", - print - - print - num_solutions += 1 - - solver.EndSearch() + for j in range(n): + val = x[i, j].Value() + if val > 0: + print val, + else: + print " ", + print print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + num_solutions += 1 + + solver.EndSearch() + + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() -if __name__ == '__main__': - main() +if __name__ == "__main__": + main() diff --git a/examples/python/kenken2.py b/examples/python/kenken2.py index b8bc462ea6..1c7dfa0b4c 100644 --- a/examples/python/kenken2.py +++ b/examples/python/kenken2.py @@ -53,7 +53,8 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ import sys @@ -64,141 +65,140 @@ from ortools.constraint_solver import pywrapcp # Ensure that the sum of the segments # in cc == res # + + def calc(cc, x, res): - solver = x.values()[0].solver() + solver = x.values()[0].solver() - if len(cc) == 2: + if len(cc) == 2: - # for two operands there may be - # a lot of variants + # for two operands there may be + # a lot of variants - c00, c01 = cc[0] - c10, c11 = cc[1] - a = x[c00-1, c01-1] - b = x[c10-1, c11-1] + c00, c01 = cc[0] + c10, c11 = cc[1] + a = x[c00 - 1, c01 - 1] + b = x[c10 - 1, c11 - 1] - r1 = solver.IsEqualCstVar(a + b, res) - r2 = solver.IsEqualCstVar(a * b, res) - r3 = solver.IsEqualVar(a * res, b) - r4 = solver.IsEqualVar(b * res, a) - r5 = solver.IsEqualCstVar(a - b, res) - r6 = solver.IsEqualCstVar(b - a, res) - solver.Add(r1+r2+r3+r4+r5+r6 >= 1) + r1 = solver.IsEqualCstVar(a + b, res) + r2 = solver.IsEqualCstVar(a * b, res) + r3 = solver.IsEqualVar(a * res, b) + r4 = solver.IsEqualVar(b * res, a) + r5 = solver.IsEqualCstVar(a - b, res) + r6 = solver.IsEqualCstVar(b - a, res) + solver.Add(r1 + r2 + r3 + r4 + r5 + r6 >= 1) - else: + else: - # res is either sum or product of the segment + # res is either sum or product of the segment - xx = [x[i[0]-1,i[1]-1] for i in cc] + xx = [x[i[0] - 1, i[1] - 1] for i in cc] - # Sum - # # SumEquality don't work: - # this_sum = solver.SumEquality(xx, res) - this_sum = solver.IsEqualCstVar(solver.Sum(xx), res) + # Sum + # # SumEquality don't work: + # this_sum = solver.SumEquality(xx, res) + this_sum = solver.IsEqualCstVar(solver.Sum(xx), res) - # Product - # # Prod (or MakeProd) don't work: - # this_prod = solver.IsEqualCstVar(solver.Prod(xx), res) - this_prod = solver.IsEqualCstVar(reduce(lambda a, b: a*b, xx), res) - solver.Add(this_sum + this_prod >= 1) + # Product + # # Prod (or MakeProd) don't work: + # this_prod = solver.IsEqualCstVar(solver.Prod(xx), res) + this_prod = solver.IsEqualCstVar(reduce(lambda a, b: a * b, xx), res) + solver.Add(this_sum + this_prod >= 1) def main(): - # Create the solver. - solver = pywrapcp.Solver('KenKen') + # Create the solver. + solver = pywrapcp.Solver("KenKen") - # - # data - # + # + # data + # - # size of matrix - n = 6 + # size of matrix + n = 6 + # For a better view of the problem, see + # http://en.wikipedia.org/wiki/File:KenKenProblem.svg - # For a better view of the problem, see - # http://en.wikipedia.org/wiki/File:KenKenProblem.svg + # hints + # [sum, [segments]] + # Note: 1-based + problem = [ + [11, [[1, 1], [2, 1]]], + [2, [[1, 2], [1, 3]]], + [20, [[1, 4], [2, 4]]], + [6, [[1, 5], [1, 6], [2, 6], [3, 6]]], + [3, [[2, 2], [2, 3]]], + [3, [[2, 5], [3, 5]]], + [240, [[3, 1], [3, 2], [4, 1], [4, 2]]], + [6, [[3, 3], [3, 4]]], + [6, [[4, 3], [5, 3]]], + [7, [[4, 4], [5, 4], [5, 5]]], + [30, [[4, 5], [4, 6]]], + [6, [[5, 1], [5, 2]]], + [9, [[5, 6], [6, 6]]], + [8, [[6, 1], [6, 2], [6, 3]]], + [2, [[6, 4], [6, 5]]]] - # hints - # [sum, [segments]] - # Note: 1-based - problem = [ - [ 11, [[1,1], [2,1]]], - [ 2, [[1,2], [1,3]]], - [ 20, [[1,4], [2,4]]], - [ 6, [[1,5], [1,6], [2,6], [3,6]]], - [ 3, [[2,2], [2,3]]], - [ 3, [[2,5], [3,5]]], - [240, [[3,1], [3,2], [4,1], [4,2]]], - [ 6, [[3,3], [3,4]]], - [ 6, [[4,3], [5,3]]], - [ 7, [[4,4], [5,4], [5,5]]], - [ 30, [[4,5], [4,6]]], - [ 6, [[5,1], [5,2]]], - [ 9, [[5,6], [6,6]]], - [ 8, [[6,1], [6,2], [6,3]]], - [ 2, [[6,4], [6,5]]]] + num_p = len(problem) - num_p = len(problem) + # + # variables + # - # - # variables - # + # the set + x = {} + for i in range(n): + for j in range(n): + x[i, j] = solver.IntVar(1, n, "x[%i,%i]" % (i, j)) - # the set - x = {} + x_flat = [x[i, j] for i in range(n) for j in range(n)] + + # + # constraints + # + + # all rows and columns must be unique + for i in range(n): + row = [x[i, j] for j in range(n)] + solver.Add(solver.AllDifferent(row)) + + col = [x[j, i] for j in range(n)] + solver.Add(solver.AllDifferent(col)) + + # calculate the segments + for (res, segment) in problem: + calc(segment, x, res) + + # + # search and solution + # + db = solver.Phase(x_flat, + solver.INT_VAR_DEFAULT, + solver.INT_VALUE_DEFAULT) + + solver.NewSearch(db) + + num_solutions = 0 + while solver.NextSolution(): for i in range(n): - for j in range(n): - x[i,j] = solver.IntVar(1, n, 'x[%i,%i]' % (i,j)) - - x_flat = [x[i,j] for i in range(n) for j in range(n)] - - # - # constraints - # - - # all rows and columns must be unique - for i in range(n): - row = [x[i,j] for j in range(n)] - solver.Add(solver.AllDifferent(row)) - - col = [x[j,i] for j in range(n)] - solver.Add(solver.AllDifferent(col)) - - - # calculate the segments - for (res, segment) in problem: - calc(segment, x, res) - - - # - # search and solution - # - db = solver.Phase(x_flat, - solver.INT_VAR_DEFAULT, - solver.INT_VALUE_DEFAULT) - - solver.NewSearch(db) - - num_solutions = 0 - while solver.NextSolution(): - for i in range(n): - for j in range(n): - print x[i,j].Value(), - print - - print - num_solutions += 1 - - solver.EndSearch() + for j in range(n): + print x[i, j].Value(), + print print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + num_solutions += 1 + + solver.EndSearch() + + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() -if __name__ == '__main__': - main() +if __name__ == "__main__": + main() diff --git a/examples/python/killer_sudoku.py b/examples/python/killer_sudoku.py index 29789b3704..a3d94f1e1c 100644 --- a/examples/python/killer_sudoku.py +++ b/examples/python/killer_sudoku.py @@ -64,7 +64,8 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ import sys @@ -75,128 +76,128 @@ from ortools.constraint_solver import pywrapcp # Ensure that the sum of the segments # in cc == res # + + def calc(cc, x, res): - solver = x.values()[0].solver() - - # sum the numbers - solver.Add(solver.Sum([x[i[0]-1,i[1]-1] for i in cc]) == res) + solver = x.values()[0].solver() + # sum the numbers + solver.Add(solver.Sum([x[i[0] - 1, i[1] - 1] for i in cc]) == res) def main(): - # Create the solver. - solver = pywrapcp.Solver('Killer Sudoku') + # Create the solver. + solver = pywrapcp.Solver("Killer Sudoku") - # - # data - # + # + # data + # - # size of matrix - n = 9 + # size of matrix + n = 9 - # For a better view of the problem, see - # http://en.wikipedia.org/wiki/File:Killersudoku_color.svg + # For a better view of the problem, see + # http://en.wikipedia.org/wiki/File:Killersudoku_color.svg - # hints - # [sum, [segments]] - # Note: 1-based - problem = [ - [ 3, [[1,1], [1,2]]], - [15, [[1,3], [1,4], [1,5]]], - [22, [[1,6], [2,5], [2,6], [3,5]]], - [ 4, [[1,7], [2,7]]], - [16, [[1,8], [2,8]]], - [15, [[1,9], [2,9], [3,9], [4,9]]], - [25, [[2,1], [2,2], [3,1], [3,2]]], - [17, [[2,3], [2,4]]], - [ 9, [[3,3], [3,4], [4,4]]], - [ 8, [[3,6], [4,6],[5,6]]], - [20, [[3,7], [3,8],[4,7]]], - [ 6, [[4,1], [5,1]]], - [14, [[4,2], [4,3]]], - [17, [[4,5], [5,5],[6,5]]], - [17, [[4,8], [5,7],[5,8]]], - [13, [[5,2], [5,3],[6,2]]], - [20, [[5,4], [6,4],[7,4]]], - [12, [[5,9], [6,9]]], - [27, [[6,1], [7,1],[8,1],[9,1]]], - [ 6, [[6,3], [7,2],[7,3]]], - [20, [[6,6], [7,6], [7,7]]], - [ 6, [[6,7], [6,8]]], - [10, [[7,5], [8,4],[8,5],[9,4]]], - [14, [[7,8], [7,9],[8,8],[8,9]]], - [ 8, [[8,2], [9,2]]], - [16, [[8,3], [9,3]]], - [15, [[8,6], [8,7]]], - [13, [[9,5], [9,6],[9,7]]], - [17, [[9,8], [9,9]]]] + # hints + # [sum, [segments]] + # Note: 1-based + problem = [ + [3, [[1, 1], [1, 2]]], + [15, [[1, 3], [1, 4], [1, 5]]], + [22, [[1, 6], [2, 5], [2, 6], [3, 5]]], + [4, [[1, 7], [2, 7]]], + [16, [[1, 8], [2, 8]]], + [15, [[1, 9], [2, 9], [3, 9], [4, 9]]], + [25, [[2, 1], [2, 2], [3, 1], [3, 2]]], + [17, [[2, 3], [2, 4]]], + [9, [[3, 3], [3, 4], [4, 4]]], + [8, [[3, 6], [4, 6], [5, 6]]], + [20, [[3, 7], [3, 8], [4, 7]]], + [6, [[4, 1], [5, 1]]], + [14, [[4, 2], [4, 3]]], + [17, [[4, 5], [5, 5], [6, 5]]], + [17, [[4, 8], [5, 7], [5, 8]]], + [13, [[5, 2], [5, 3], [6, 2]]], + [20, [[5, 4], [6, 4], [7, 4]]], + [12, [[5, 9], [6, 9]]], + [27, [[6, 1], [7, 1], [8, 1], [9, 1]]], + [6, [[6, 3], [7, 2], [7, 3]]], + [20, [[6, 6], [7, 6], [7, 7]]], + [6, [[6, 7], [6, 8]]], + [10, [[7, 5], [8, 4], [8, 5], [9, 4]]], + [14, [[7, 8], [7, 9], [8, 8], [8, 9]]], + [8, [[8, 2], [9, 2]]], + [16, [[8, 3], [9, 3]]], + [15, [[8, 6], [8, 7]]], + [13, [[9, 5], [9, 6], [9, 7]]], + [17, [[9, 8], [9, 9]]]] - # - # variables - # + # + # variables + # - # the set - x = {} + # the set + x = {} + for i in range(n): + for j in range(n): + x[i, j] = solver.IntVar(1, n, "x[%i,%i]" % (i, j)) + + x_flat = [x[i, j] for i in range(n) for j in range(n)] + + # + # constraints + # + + # all rows and columns must be unique + for i in range(n): + row = [x[i, j] for j in range(n)] + solver.Add(solver.AllDifferent(row)) + + col = [x[j, i] for j in range(n)] + solver.Add(solver.AllDifferent(col)) + + # cells + for i in range(2): + for j in range(2): + cell = [x[r, c] + for r in range(i * 3, i * 3 + 3) + for c in range(j * 3, j * 3 + 3)] + solver.Add(solver.AllDifferent(cell)) + + # calculate the segments + for (res, segment) in problem: + calc(segment, x, res) + + # + # search and solution + # + db = solver.Phase(x_flat, + solver.INT_VAR_DEFAULT, + solver.INT_VALUE_DEFAULT) + + solver.NewSearch(db) + + num_solutions = 0 + while solver.NextSolution(): for i in range(n): - for j in range(n): - x[i,j] = solver.IntVar(1, n, 'x[%i,%i]' % (i,j)) - - x_flat = [x[i,j] for i in range(n) for j in range(n)] - - # - # constraints - # - - # all rows and columns must be unique - for i in range(n): - row = [x[i,j] for j in range(n)] - solver.Add(solver.AllDifferent(row)) - - col = [x[j,i] for j in range(n)] - solver.Add(solver.AllDifferent(col)) - - # cells - for i in range(2): - for j in range(2): - cell = [x[r,c] - for r in range(i*3,i*3+3) - for c in range(j*3,j*3+3)] - solver.Add(solver.AllDifferent(cell)); - - # calculate the segments - for (res, segment) in problem: - calc(segment, x, res) - - - # - # search and solution - # - db = solver.Phase(x_flat, - solver.INT_VAR_DEFAULT, - solver.INT_VALUE_DEFAULT) - - solver.NewSearch(db) - - num_solutions = 0 - while solver.NextSolution(): - for i in range(n): - for j in range(n): - print x[i,j].Value(), - print - - print - num_solutions += 1 - - solver.EndSearch() + for j in range(n): + print x[i, j].Value(), + print print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + num_solutions += 1 + + solver.EndSearch() + + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() -if __name__ == '__main__': - main() +if __name__ == "__main__": + main() diff --git a/examples/python/knapsack.py b/examples/python/knapsack.py index 546654373a..96aedf590a 100644 --- a/examples/python/knapsack.py +++ b/examples/python/knapsack.py @@ -15,7 +15,6 @@ """Bi-dimensional knapsack problem.""" - from google.apputils import app import gflags from ortools.algorithms import pywrapknapsack_solver diff --git a/examples/python/knapsack_cp.py b/examples/python/knapsack_cp.py index abe690feb4..8fa5aa946e 100644 --- a/examples/python/knapsack_cp.py +++ b/examples/python/knapsack_cp.py @@ -19,78 +19,76 @@ Simple knapsack problem. This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ from ortools.constraint_solver import pywrapcp -def knapsack(solver, values, weights, n): - z = solver.IntVar(0, 10000) - x = [solver.IntVar(0,1,"x(%i)"%i) for i in range(len(values))] - solver.Add(z >= 0) - solver.Add(z == solver.ScalProd(x, values)) - solver.Add(solver.ScalProd(x, weights) <= n) - return [x, z] +def knapsack(solver, values, weights, n): + z = solver.IntVar(0, 10000) + x = [solver.IntVar(0, 1, "x(%i)" % i) for i in range(len(values))] + solver.Add(z >= 0) + solver.Add(z == solver.ScalProd(x, values)) + solver.Add(solver.ScalProd(x, weights) <= n) + + return [x, z] def main(values, weights, n): - # Create the solver. - solver = pywrapcp.Solver('n-queens') + # Create the solver. + solver = pywrapcp.Solver("n-queens") - # - # data - # - print "values:", values - print "weights:", weights - print "n:", n + # + # data + # + print "values:", values + print "weights:", weights + print "n:", n + print + + # declare variables + + # + # constraints + # + [x, z] = knapsack(solver, values, weights, n) + + # objective + objective = solver.Maximize(z, 1) + + # + # solution and search + # + solution = solver.Assignment() + solution.Add(x) + solution.Add(z) + + # db: DecisionBuilder + db = solver.Phase(x, + solver.CHOOSE_FIRST_UNBOUND, + solver.ASSIGN_MAX_VALUE) + + solver.NewSearch(db, [objective]) + num_solutions = 0 + while solver.NextSolution(): + print "x:", [x[i].Value() for i in range(len(values))] + print "z:", z.Value() print + num_solutions += 1 + solver.EndSearch() - # declare variables + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() - # - # constraints - # - [x, z] = knapsack(solver, values, weights, n) - - - # objective - objective = solver.Maximize(z,1) - - - # - # solution and search - # - solution = solver.Assignment() - solution.Add(x) - solution.Add(z) - - - # db: DecisionBuilder - db = solver.Phase(x, - solver.CHOOSE_FIRST_UNBOUND, - solver.ASSIGN_MAX_VALUE) - - solver.NewSearch(db,[objective]) - num_solutions = 0 - while solver.NextSolution(): - print "x:", [x[i].Value() for i in range(len(values))] - print "z:", z.Value() - print - num_solutions += 1 - solver.EndSearch() - - print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() - - -values = [15, 100, 90, 60, 40, 15, 10, 1, 12, 12, 100] -weights = [ 2, 20, 20, 30, 40, 30, 60, 10, 21, 12, 2] +values = [15, 100, 90, 60, 40, 15, 10, 1, 12, 12, 100] +weights = [2, 20, 20, 30, 40, 30, 60, 10, 21, 12, 2] n = 102 -if __name__ == '__main__': - main( values, weights, n) +if __name__ == "__main__": + main(values, weights, n) diff --git a/examples/python/knapsack_mip.py b/examples/python/knapsack_mip.py index 943ae25014..a544827d55 100644 --- a/examples/python/knapsack_mip.py +++ b/examples/python/knapsack_mip.py @@ -19,12 +19,14 @@ From the OPL model knapsack.mod This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ import sys from ortools.linear_solver import pywraplp -def main(sol = 'GLPK'): + +def main(sol='GLPK'): # Create the solver. @@ -35,10 +37,9 @@ def main(sol = 'GLPK'): solver = pywraplp.Solver('CoinsGridGLPK', pywraplp.Solver.GLPK_MIXED_INTEGER_PROGRAMMING) else: - # Using CLP - solver = pywraplp.Solver('CoinsGridCLP', - pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING) - + # Using CLP + solver = pywraplp.Solver('CoinsGridCLP', + pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING) # # data @@ -48,15 +49,15 @@ def main(sol = 'GLPK'): items = range(nb_items) resources = range(nb_resources) - capacity = [ 18209, 7692, 1333, 924, 26638, 61188, 13360 ] - value = [ 96, 76, 56, 11, 86, 10, 66, 86, 83, 12, 9, 81 ] - use = [[ 19, 1, 10, 1, 1, 14, 152, 11, 1, 1, 1, 1 ], - [ 0, 4, 53, 0, 0, 80, 0, 4, 5, 0, 0, 0 ], - [ 4, 660, 3, 0, 30, 0, 3, 0, 4, 90, 0, 0], - [ 7, 0, 18, 6, 770, 330, 7, 0, 0, 6, 0, 0], - [ 0, 20, 0, 4, 52, 3, 0, 0, 0, 5, 4, 0], - [ 0, 0, 40, 70, 4, 63, 0, 0, 60, 0, 4, 0], - [ 0, 32, 0, 0, 0, 5, 0, 3, 0, 660, 0, 9]] + capacity = [18209, 7692, 1333, 924, 26638, 61188, 13360] + value = [96, 76, 56, 11, 86, 10, 66, 86, 83, 12, 9, 81] + use = [[19, 1, 10, 1, 1, 14, 152, 11, 1, 1, 1, 1], + [0, 4, 53, 0, 0, 80, 0, 4, 5, 0, 0, 0], + [4, 660, 3, 0, 30, 0, 3, 0, 4, 90, 0, 0], + [7, 0, 18, 6, 770, 330, 7, 0, 0, 6, 0, 0], + [0, 20, 0, 4, 52, 3, 0, 0, 0, 5, 4, 0], + [0, 0, 40, 70, 4, 63, 0, 0, 60, 0, 4, 0], + [0, 32, 0, 0, 0, 5, 0, 3, 0, 660, 0, 9]] max_value = max(capacity) @@ -65,7 +66,6 @@ def main(sol = 'GLPK'): # take = [solver.IntVar(0, max_value, 'take[%i]' % j) for j in items] - # total cost, to be maximized z = solver.Sum([value[i] * take[i] for i in items]) @@ -79,7 +79,6 @@ def main(sol = 'GLPK'): # objective objective = solver.Maximize(z) - # # solution and search # @@ -93,7 +92,6 @@ def main(sol = 'GLPK'): print int(take[i].SolutionValue()), print - print print 'walltime :', solver.WallTime(), 'ms' if sol == 'CBC': diff --git a/examples/python/labeled_dice.py b/examples/python/labeled_dice.py index 55caad4c2b..add271afba 100644 --- a/examples/python/labeled_dice.py +++ b/examples/python/labeled_dice.py @@ -44,7 +44,8 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ from ortools.constraint_solver import pywrapcp @@ -52,94 +53,94 @@ from ortools.constraint_solver import pywrapcp def main(): - # Create the solver. - solver = pywrapcp.Solver('Labeled dice') + # Create the solver. + solver = pywrapcp.Solver("Labeled dice") - # - # data - # - n = 4 - m = 24 - A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,Y = range(m) - letters = ["A","B","C","D","E","F","G","H","I","J","K","L","M", - "N","O","P","Q","R","S","T","U","V","W","Y"] + # + # data + # + n = 4 + m = 24 + A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, Y = ( + range(m)) + letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", + "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "Y"] - num_words = 13 - words = [ - [B,U,O,Y], - [C,A,V,E], - [C,E,L,T], - [F,L,U,B], - [F,O,R,K], - [H,E,M,P], - [J,U,D,Y], - [J,U,N,K], - [L,I,M,N], - [Q,U,I,P], - [S,W,A,G], - [V,I,S,A], - [W,I,S,H] - ] + num_words = 13 + words = [ + [B, U, O, Y], + [C, A, V, E], + [C, E, L, T], + [F, L, U, B], + [F, O, R, K], + [H, E, M, P], + [J, U, D, Y], + [J, U, N, K], + [L, I, M, N], + [Q, U, I, P], + [S, W, A, G], + [V, I, S, A], + [W, I, S, H] + ] - # - # declare variables - # - dice = [solver.IntVar(0, n-1, 'dice[%i]'%i) for i in range(m)] + # + # declare variables + # + dice = [solver.IntVar(0, n - 1, "dice[%i]" % i) for i in range(m)] - # - # constraints - # + # + # constraints + # - # the letters in a word must be on a different die + # the letters in a word must be on a different die + for i in range(num_words): + solver.Add(solver.AllDifferent([dice[words[i][j]] for j in range(n)])) + + # there must be exactly 6 letters of each die + for i in range(n): + b = [solver.IsEqualCstVar(dice[j], i) for j in range(m)] + solver.Add(solver.Sum(b) == 6) + + # + # solution and search + # + solution = solver.Assignment() + solution.Add(dice) + + db = solver.Phase(dice, + solver.CHOOSE_FIRST_UNBOUND, + solver.ASSIGN_MIN_VALUE) + + # + # result + # + solver.NewSearch(db) + num_solutions = 0 + while solver.NextSolution(): + num_solutions += 1 + # print "dice:", [(letters[i],dice[i].Value()) for i in range(m)] + for d in range(n): + print "die %i:" % d, + for i in range(m): + if dice[i].Value() == d: + print letters[i], + print + + print "The words with the cube label:" for i in range(num_words): - solver.Add(solver.AllDifferent([dice[words[i][j]] for j in range(n)])) - - # there must be exactly 6 letters of each die - for i in range(n): - b = [solver.IsEqualCstVar(dice[j], i) for j in range(m)] - solver.Add(solver.Sum(b) == 6) - - - # - # solution and search - # - solution = solver.Assignment() - solution.Add(dice) - - db = solver.Phase(dice, - solver.CHOOSE_FIRST_UNBOUND, - solver.ASSIGN_MIN_VALUE) - - # - # result - # - solver.NewSearch(db) - num_solutions = 0 - while solver.NextSolution(): - num_solutions += 1 - # print "dice:", [(letters[i],dice[i].Value()) for i in range(m)] - for d in range(n): - print "die %i:" % d, - for i in range(m): - if dice[i].Value() == d: - print letters[i], - print - - print "The words with the cube label:" - for i in range(num_words): - for j in range(n): - print "%s (%i)" % (letters[words[i][j]], dice[words[i][j]].Value()), - print - - print - - solver.EndSearch() + for j in range(n): + print "%s (%i)" % (letters[words[i][j]], dice[words[i][j]].Value()), + print print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() -if __name__ == '__main__': - main() + solver.EndSearch() + + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() + +if __name__ == "__main__": + main() diff --git a/examples/python/langford.py b/examples/python/langford.py index be649d8fd8..dbe4ae152d 100644 --- a/examples/python/langford.py +++ b/examples/python/langford.py @@ -41,7 +41,8 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ import sys @@ -52,64 +53,63 @@ from ortools.constraint_solver import pywrapcp def main(k=8, num_sol=0): - # Create the solver. - solver = pywrapcp.Solver('Langford') + # Create the solver. + solver = pywrapcp.Solver("Langford") - # - # data - # - print "k:", k - p = range(2*k) + # + # data + # + print "k:", k + p = range(2 * k) - # - # declare variables - # - position = [solver.IntVar(0, 2*k-1, "position[%i]" % i) for i in p] - solution = [solver.IntVar(1, k, "position[%i]" % i) for i in p] + # + # declare variables + # + position = [solver.IntVar(0, 2 * k - 1, "position[%i]" % i) for i in p] + solution = [solver.IntVar(1, k, "position[%i]" % i) for i in p] - # - # constraints - # - solver.Add(solver.AllDifferent(position)) + # + # constraints + # + solver.Add(solver.AllDifferent(position)) - for i in range(1,k+1): - solver.Add(position[i+k-1] == position[i-1] + i+1) - solver.Add(solver.Element(solution, position[i-1]) == i) - solver.Add(solver.Element(solution, position[k+i-1]) == i) + for i in range(1, k + 1): + solver.Add(position[i + k - 1] == position[i - 1] + i + 1) + solver.Add(solver.Element(solution, position[i - 1]) == i) + solver.Add(solver.Element(solution, position[k + i - 1]) == i) - # symmetry breaking - solver.Add(solution[0] < solution[2*k-1]) + # symmetry breaking + solver.Add(solution[0] < solution[2 * k - 1]) + # + # search and result + # + db = solver.Phase(position, + solver.CHOOSE_FIRST_UNBOUND, + solver.ASSIGN_MIN_VALUE) - # - # search and result - # - db = solver.Phase(position, - solver.CHOOSE_FIRST_UNBOUND, - solver.ASSIGN_MIN_VALUE) + solver.NewSearch(db) + num_solutions = 0 + while solver.NextSolution(): + print "solution:", ",".join([str(solution[i].Value()) for i in p]) + num_solutions += 1 + if num_sol > 0 and num_solutions >= num_sol: + break - solver.NewSearch(db) - num_solutions = 0 - while solver.NextSolution(): - print "solution:", ",".join([str(solution[i].Value()) for i in p]) - num_solutions += 1 - if num_sol > 0 and num_solutions >= num_sol: - break + solver.EndSearch() - solver.EndSearch() - - print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() k = 8 num_sol = 0 -if __name__ == '__main__': - if len(sys.argv) > 1: - k = string.atoi(sys.argv[1]) - if len(sys.argv) > 2: - num_sol = string.atoi(sys.argv[2]) +if __name__ == "__main__": + if len(sys.argv) > 1: + k = string.atoi(sys.argv[1]) + if len(sys.argv) > 2: + num_sol = string.atoi(sys.argv[2]) - main(k, num_sol) + main(k, num_sol) diff --git a/examples/python/least_diff.py b/examples/python/least_diff.py index 874e88506e..f48c47e657 100644 --- a/examples/python/least_diff.py +++ b/examples/python/least_diff.py @@ -34,42 +34,44 @@ * Zinc : http://hakank.org/minizinc/least_diff.zinc This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_cp_solver/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_cp_solver/ """ from ortools.constraint_solver import pywrapcp + def main(unused_argv): # Create the solver. - solver = pywrapcp.Solver('Least diff') + solver = pywrapcp.Solver("Least diff") # # declare variables # digits = range(0, 10) - a = solver.IntVar(digits, 'a') - b = solver.IntVar(digits, 'b') - c = solver.IntVar(digits, 'c') - d = solver.IntVar(digits, 'd') - e = solver.IntVar(digits, 'e') + a = solver.IntVar(digits, "a") + b = solver.IntVar(digits, "b") + c = solver.IntVar(digits, "c") + d = solver.IntVar(digits, "d") + e = solver.IntVar(digits, "e") - f = solver.IntVar(digits, 'f') - g = solver.IntVar(digits, 'g') - h = solver.IntVar(digits, 'h') - i = solver.IntVar(digits, 'i') - j = solver.IntVar(digits, 'j') + f = solver.IntVar(digits, "f") + g = solver.IntVar(digits, "g") + h = solver.IntVar(digits, "h") + i = solver.IntVar(digits, "i") + j = solver.IntVar(digits, "j") - letters = [a,b,c,d,e,f,g,h,i,j] + letters = [a, b, c, d, e, f, g, h, i, j] - x = solver.IntVar(range(0,99999), "x") - y = solver.IntVar(range(0,99999), "y") - diff = solver.IntVar(range(0,99999), "y") + x = solver.IntVar(range(0, 99999), "x") + y = solver.IntVar(range(0, 99999), "y") + diff = solver.IntVar(range(0, 99999), "y") # # constraints # - solver.Add(x == 10000*a +1000*b +100*c +10*d + e) - solver.Add(y == 10000*f +1000*g +100*h +10*i + j) + solver.Add(x == 10000 * a + 1000 * b + 100 * c + 10 * d + e) + solver.Add(y == 10000 * f + 1000 * g + 100 * h + 10 * i + j) solver.Add(diff == x - y) solver.Add(diff > 0) solver.Add(solver.AllDifferent(letters)) @@ -91,10 +93,10 @@ def main(unused_argv): search_log = solver.SearchLog(100, diff) # Note: I'm not sure what CHOOSE_PATH do, but it is fast: # find the solution in just 4 steps - solver.Solve(solver.Phase(letters + [x,y,diff], + solver.Solve(solver.Phase(letters + [x, y, diff], solver.CHOOSE_PATH, solver.ASSIGN_MIN_VALUE), - [objective, search_log, collector]) + [objective, search_log, collector]) # get the first (and only) solution @@ -104,7 +106,7 @@ def main(unused_argv): print "x:", xval print "y:", yval print "diff:", diffval - print xval,"-", yval,"=", diffval + print xval, "-", yval, "=", diffval print [("abcdefghij"[i], collector.Value(0, letters[i])) for i in range(10)] print print "failures:", solver.Failures() @@ -112,5 +114,5 @@ def main(unused_argv): print "WallTime:", solver.WallTime() print -if __name__ == '__main__': +if __name__ == "__main__": main("cp sample") diff --git a/examples/python/least_square.py b/examples/python/least_square.py index 67b92da9db..2c8c54740d 100644 --- a/examples/python/least_square.py +++ b/examples/python/least_square.py @@ -22,13 +22,15 @@ page 286f. This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ import sys from ortools.linear_solver import pywraplp -def main(sol = 'GLPK'): + +def main(sol='GLPK'): # Create the solver. @@ -41,40 +43,41 @@ def main(sol = 'GLPK'): solver = pywraplp.Solver('CoinsGridCLP', pywraplp.Solver.CLP_LINEAR_PROGRAMMING) - # data # number of points num = 14 # temperature - t = [20, 30, 80,125,175,225,275,325,360,420,495,540,630,700] + t = [20, 30, 80, 125, 175, 225, 275, 325, 360, 420, 495, 540, 630, 700] # percentage gas - F = [0.0,5.8,14.7,31.6,43.2,58.3,78.4,89.4,96.4,99.1,99.5,99.9,100.0,100.0] + F = [ + 0.0, 5.8, 14.7, 31.6, 43.2, 58.3, 78.4, 89.4, 96.4, 99.1, 99.5, 99.9, + 100.0, 100.0] p = 4 # # declare variables # - a = [solver.NumVar(-100, 100, 'a[%i]' % i ) for i in range(p + 1)] + a = [solver.NumVar(-100, 100, 'a[%i]' % i) for i in range(p + 1)] # to minimize z = solver.Sum([(F[i] - - (sum([a[j]*t[i]**j for j in range(p+1)]))) + (sum([a[j] * t[i] ** j for j in range(p + 1)]))) for i in range(num)]) # # constraints # - solver.Add(solver.Sum([20**i*a[i] for i in range(p+1)]) == 0) + solver.Add(solver.Sum([20 ** i * a[i] for i in range(p + 1)]) == 0) - solver.Add( (a[0] + sum([700.0**j*a[j] - for j in range(1,p+1)])) == 100.0) + solver.Add((a[0] + sum([700.0 ** j * a[j] + for j in range(1, p + 1)])) == 100.0) for i in range(num): - solver.Add(solver.Sum([j*a[j]*t[i]**(j-1) - for j in range(p+1)]) >= 0) + solver.Add(solver.Sum([j * a[j] * t[i] ** (j - 1) + for j in range(p + 1)]) >= 0) objective = solver.Minimize(z) diff --git a/examples/python/lectures.py b/examples/python/lectures.py index dc1150b54f..252639d15b 100644 --- a/examples/python/lectures.py +++ b/examples/python/lectures.py @@ -41,7 +41,8 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ import sys @@ -50,84 +51,83 @@ from ortools.constraint_solver import pywrapcp def main(): - # Create the solver. - solver = pywrapcp.Solver('Lectures') + # Create the solver. + solver = pywrapcp.Solver('Lectures') - # - # data - # + # + # data + # - # - # The schedule requirements: - # lecture a cannot be held at the same time as b - # Note: 1-based - g = [ - [1, 2], - [1, 4], - [3, 5], - [2, 6], - [4, 5], - [5, 6], - [1, 6] - ] + # + # The schedule requirements: + # lecture a cannot be held at the same time as b + # Note: 1-based + g = [ + [1, 2], + [1, 4], + [3, 5], + [2, 6], + [4, 5], + [5, 6], + [1, 6] + ] - # number of nodes - n = 6 + # number of nodes + n = 6 - # number of edges - edges = len(g) + # number of edges + edges = len(g) - # - # declare variables - # - v = [solver.IntVar(0, n-1, 'v[%i]' % i) for i in range(n)] + # + # declare variables + # + v = [solver.IntVar(0, n - 1, 'v[%i]' % i) for i in range(n)] - # maximum color, to minimize - # Note: since Python is 0-based, the - # number of colors is +1 - max_c = solver.IntVar(0, n-1, 'max_c') + # maximum color, to minimize + # Note: since Python is 0-based, the + # number of colors is +1 + max_c = solver.IntVar(0, n - 1, 'max_c') + # + # constraints + # + solver.Add(max_c == solver.Max(v)) - # - # constraints - # - solver.Add(max_c == solver.Max(v)) + # ensure that there are no clashes + # also, adjust to 0-base + for i in range(edges): + solver.Add(v[g[i][0] - 1] != v[g[i][1] - 1]) - # ensure that there are no clashes - # also, adjust to 0-base - for i in range(edges): - solver.Add(v[g[i][0]-1] != v[g[i][1]-1]) + # symmetry breaking: + # - v0 has the color 0, + # - v1 has either color 0 or 1 + solver.Add(v[0] == 0) + solver.Add(v[1] <= 1) - # symmetry breaking: - # - v0 has the color 0, - # - v1 has either color 0 or 1 - solver.Add(v[0] == 0) - solver.Add(v[1] <= 1) + # objective + objective = solver.Minimize(max_c, 1) - # objective - objective = solver.Minimize(max_c, 1) + # + # solution and search + # + db = solver.Phase(v, + solver.CHOOSE_MIN_SIZE_LOWEST_MIN, + solver.ASSIGN_CENTER_VALUE) - # - # solution and search - # - db = solver.Phase(v, - solver.CHOOSE_MIN_SIZE_LOWEST_MIN, - solver.ASSIGN_CENTER_VALUE) + solver.NewSearch(db, [objective]) - solver.NewSearch(db, [objective]) + num_solutions = 0 + while solver.NextSolution(): + num_solutions += 1 + print 'max_c:', max_c.Value() + 1, 'colors' + print 'v:', [v[i].Value() for i in range(n)] + print - num_solutions = 0 - while solver.NextSolution(): - num_solutions += 1 - print 'max_c:', max_c.Value()+1, 'colors' - print 'v:', [v[i].Value() for i in range(n)] - print - - print 'num_solutions:', num_solutions - print 'failures:', solver.Failures() - print 'branches:', solver.Branches() - print 'WallTime:', solver.WallTime(), 'ms' + print 'num_solutions:', num_solutions + print 'failures:', solver.Failures() + print 'branches:', solver.Branches() + print 'WallTime:', solver.WallTime(), 'ms' if __name__ == '__main__': - main() + main() diff --git a/examples/python/linear_assignment_api.py b/examples/python/linear_assignment_api.py index 5db4c6ab10..8f2ebd3845 100644 --- a/examples/python/linear_assignment_api.py +++ b/examples/python/linear_assignment_api.py @@ -19,7 +19,6 @@ """ - from google.apputils import app from ortools.graph import pywrapgraph @@ -36,7 +35,7 @@ def RunAssignmentOn4x4Matrix(): expected_cost = cost[0][3] + cost[1][2] + cost[2][1] + cost[3][0] assignment = pywrapgraph.LinearSumAssignment() - for source in range (0, num_sources): + for source in range(0, num_sources): for target in range(0, num_targets): assignment.AddArcWithCost(source, target, cost[source][target]) diff --git a/examples/python/magic_sequence_distribute.py b/examples/python/magic_sequence_distribute.py index 77b27a6c5c..3b4ffb1f06 100644 --- a/examples/python/magic_sequence_distribute.py +++ b/examples/python/magic_sequence_distribute.py @@ -21,7 +21,6 @@ distribute(). """ - from google.apputils import app import gflags from ortools.constraint_solver import pywrapcp diff --git a/examples/python/magic_square.py b/examples/python/magic_square.py index 2e6c964701..782b7b0799 100644 --- a/examples/python/magic_square.py +++ b/examples/python/magic_square.py @@ -19,88 +19,88 @@ Magic square problem. This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ -import string, sys +import string +import sys from ortools.constraint_solver import pywrapcp def main(n=4): - # Create the solver. - solver = pywrapcp.Solver('n-queens') + # Create the solver. + solver = pywrapcp.Solver("n-queens") - # - # data - # + # + # data + # - # - # declare variables - # - x = {} + # + # declare variables + # + x = {} + for i in range(n): + for j in range(n): + x[(i, j)] = solver.IntVar(1, n * n, "x(%i,%i)" % (i, j)) + x_flat = [x[(i, j)] for i in range(n) for j in range(n)] + + # the sum + # s = ( n * (n*n + 1)) / 2 + s = solver.IntVar(1, n * n * n, "s") + + # + # constraints + # + # solver.Add(s == ( n * (n*n + 1)) / 2) + + solver.Add(solver.AllDifferent(x_flat)) + + [solver.Add(solver.Sum([x[(i, j)] for j in range(n)]) == s) for i in range(n)] + [solver.Add(solver.Sum([x[(i, j)] for i in range(n)]) == s) for j in range(n)] + + solver.Add(solver.Sum([x[(i, i)] for i in range(n)]) == s) # diag 1 + solver.Add(solver.Sum([x[(i, n - i - 1)] for i in range(n)]) == s) # diag 2 + + # symmetry breaking + # solver.Add(x[(0,0)] == 1) + + # + # solution and search + # + solution = solver.Assignment() + solution.Add(x_flat) + solution.Add(s) + + # db: DecisionBuilder + db = solver.Phase(x_flat, + # solver.INT_VAR_DEFAULT, + solver.CHOOSE_FIRST_UNBOUND, + # solver.CHOOSE_MIN_SIZE_LOWEST_MAX, + + # solver.ASSIGN_MIN_VALUE + solver.ASSIGN_CENTER_VALUE) + + solver.NewSearch(db) + num_solutions = 0 + while solver.NextSolution(): + print "s:", s.Value() for i in range(n): - for j in range(n): - x[(i, j)] = solver.IntVar(1, n*n, 'x(%i,%i)' % (i, j)) - x_flat = [x[(i,j)] for i in range(n) for j in range(n)] - - # the sum - # s = ( n * (n*n + 1)) / 2 - s = solver.IntVar(1, n*n*n,'s') - - - # - # constraints - # - # solver.Add(s == ( n * (n*n + 1)) / 2) - - solver.Add(solver.AllDifferent(x_flat)) - - [solver.Add(solver.Sum([x[(i,j)] for j in range(n)]) == s) for i in range(n)] - [solver.Add(solver.Sum([x[(i,j)] for i in range(n)]) == s) for j in range(n)] - - solver.Add(solver.Sum([ x[(i,i)] for i in range(n)]) == s) # diag 1 - solver.Add(solver.Sum([ x[(i,n-i-1)] for i in range(n)]) == s) # diag 2 - - # symmetry breaking - # solver.Add(x[(0,0)] == 1) - - # - # solution and search - # - solution = solver.Assignment() - solution.Add(x_flat) - solution.Add(s) - - # db: DecisionBuilder - db = solver.Phase(x_flat, - #solver.INT_VAR_DEFAULT, - solver.CHOOSE_FIRST_UNBOUND, - #solver.CHOOSE_MIN_SIZE_LOWEST_MAX, - - solver.ASSIGN_CENTER_VALUE - #solver.ASSIGN_MIN_VALUE - ) - - solver.NewSearch(db) - num_solutions = 0 - while solver.NextSolution(): - print "s:", s.Value() - for i in range(n): - for j in range(n): - print "%2i" % x[(i,j)].Value(), - print - - print - num_solutions += 1 - solver.EndSearch() + for j in range(n): + print "%2i" % x[(i, j)].Value(), + print print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + num_solutions += 1 + solver.EndSearch() + + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() n = 4 -if __name__ == '__main__': - if len(sys.argv) > 1: - n = string.atoi(sys.argv[1]) - main(n) +if __name__ == "__main__": + if len(sys.argv) > 1: + n = string.atoi(sys.argv[1]) + main(n) diff --git a/examples/python/magic_square_and_cards.py b/examples/python/magic_square_and_cards.py index a36746341a..e7e1216514 100644 --- a/examples/python/magic_square_and_cards.py +++ b/examples/python/magic_square_and_cards.py @@ -25,90 +25,89 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ -import string, sys +import string +import sys from ortools.constraint_solver import pywrapcp def main(n=3): - # Create the solver. - solver = pywrapcp.Solver('n-queens') + # Create the solver. + solver = pywrapcp.Solver("n-queens") - # - # data - # - # n = 3 + # + # data + # + # n = 3 - # - # declare variables - # - x = {} + # + # declare variables + # + x = {} + for i in range(n): + for j in range(n): + x[(i, j)] = solver.IntVar(1, 13, "x(%i,%i)" % (i, j)) + x_flat = [x[(i, j)] for i in range(n) for j in range(n)] + + s = solver.IntVar(1, 13 * 4, "s") + counts = [solver.IntVar(0, 4, "counts(%i)" % i) for i in range(14)] + + # + # constraints + # + solver.Add(solver.Distribute(x_flat, range(14), counts)) + + # the standard magic square constraints (sans all_different) + [solver.Add(solver.Sum([x[(i, j)] for j in range(n)]) == s) for i in range(n)] + [solver.Add(solver.Sum([x[(i, j)] for i in range(n)]) == s) for j in range(n)] + + solver.Add(solver.Sum([x[(i, i)] for i in range(n)]) == s) # diag 1 + solver.Add(solver.Sum([x[(i, n - i - 1)] for i in range(n)]) == s) # diag 2 + + # redundant constraint + solver.Add(solver.Sum(counts) == n * n) + + # objective + objective = solver.Maximize(s, 1) + + # + # solution and search + # + solution = solver.Assignment() + solution.Add(x_flat) + solution.Add(s) + solution.Add(counts) + + # db: DecisionBuilder + db = solver.Phase(x_flat, + solver.CHOOSE_FIRST_UNBOUND, + solver.ASSIGN_MAX_VALUE) + + solver.NewSearch(db, [objective]) + num_solutions = 0 + while solver.NextSolution(): + print "s:", s.Value() + print "counts:", [counts[i].Value() for i in range(14)] for i in range(n): - for j in range(n): - x[(i, j)] = solver.IntVar(1, 13, 'x(%i,%i)' % (i, j)) - x_flat = [x[(i,j)] for i in range(n) for j in range(n)] - - s = solver.IntVar(1, 13*4,'s') - counts = [solver.IntVar(0,4,"counts(%i)"%i) for i in range(14)] - - # - # constraints - # - solver.Add(solver.Distribute(x_flat, range(14), counts)) - - # the standard magic square constraints (sans all_different) - [solver.Add(solver.Sum([x[(i,j)] for j in range(n)]) == s) for i in range(n)] - [solver.Add(solver.Sum([x[(i,j)] for i in range(n)]) == s) for j in range(n)] - - solver.Add(solver.Sum([ x[(i,i)] for i in range(n)]) == s ) # diag 1 - solver.Add(solver.Sum([ x[(i,n-i-1)] for i in range(n)]) == s) # diag 2 - - # redundant constraint - solver.Add(solver.Sum(counts) == n*n) - - - # objective - objective = solver.Maximize(s,1) - - - # - # solution and search - # - solution = solver.Assignment() - solution.Add(x_flat) - solution.Add(s) - solution.Add(counts) - - - # db: DecisionBuilder - db = solver.Phase(x_flat, - solver.CHOOSE_FIRST_UNBOUND, - solver.ASSIGN_MAX_VALUE) - - solver.NewSearch(db,[objective]) - num_solutions = 0 - while solver.NextSolution(): - print "s:", s.Value() - print "counts:", [counts[i].Value() for i in range(14)] - for i in range(n): - for j in range(n): - print x[(i,j)].Value(), - print - - print - num_solutions += 1 - solver.EndSearch() + for j in range(n): + print x[(i, j)].Value(), + print print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + num_solutions += 1 + solver.EndSearch() + + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() n = 3 -if __name__ == '__main__': - if len(sys.argv) > 1: - n = string.atoi(sys.argv[1]) - main(n) +if __name__ == "__main__": + if len(sys.argv) > 1: + n = string.atoi(sys.argv[1]) + main(n) diff --git a/examples/python/magic_square_mip.py b/examples/python/magic_square_mip.py index 8b08683fe2..26c8330cd2 100644 --- a/examples/python/magic_square_mip.py +++ b/examples/python/magic_square_mip.py @@ -39,7 +39,8 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ import sys from ortools.linear_solver import pywraplp @@ -49,7 +50,9 @@ from ortools.linear_solver import pywraplp # n: size of matrix # use_output_matrix: use the output_matrix # -def main(n = 3, sol = 'GLPK', use_output_matrix = 0): + + +def main(n=3, sol='GLPK', use_output_matrix=0): # Create the solver. @@ -60,21 +63,19 @@ def main(n = 3, sol = 'GLPK', use_output_matrix = 0): solver = pywraplp.Solver('CoinsGridGLPK', pywraplp.Solver.GLPK_MIXED_INTEGER_PROGRAMMING) else: - # Using CLP - solver = pywraplp.Solver('CoinsGridCLP', - pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING) - + # Using CLP + solver = pywraplp.Solver('CoinsGridCLP', + pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING) # # data # print 'n = ', n - # range_n = range(1, n+1) range_n = range(0, n) - N = n*n + N = n * n range_N = range(1, N + 1) # @@ -86,15 +87,15 @@ def main(n = 3, sol = 'GLPK', use_output_matrix = 0): for i in range_n: for j in range_n: for k in range_N: - x[i,j,k] = solver.IntVar(0, 1, 'x[%i,%i,%i]' % (i, j, k)) + x[i, j, k] = solver.IntVar(0, 1, 'x[%i,%i,%i]' % (i, j, k)) - ## For output. Much slower.... + # For output. Much slower.... if use_output_matrix == 1: print 'Using an output matrix' square = {} for i in range_n: for j in range_n: - square[i,j] = solver.IntVar(1, n*n, 'square[%i,%i]' % (i, j)) + square[i, j] = solver.IntVar(1, n * n, 'square[%i,%i]' % (i, j)) # the magic sum s = solver.IntVar(1, n * n * n, 's') @@ -106,41 +107,40 @@ def main(n = 3, sol = 'GLPK', use_output_matrix = 0): # each cell must be assigned exactly one integer for i in range_n: for j in range_n: - solver.Add(solver.Sum([x[i,j,k] for k in range_N]) == 1) + solver.Add(solver.Sum([x[i, j, k] for k in range_N]) == 1) # each integer must be assigned exactly to one cell for k in range_N: - solver.Add(solver.Sum([x[i,j,k] + solver.Add(solver.Sum([x[i, j, k] for i in range_n for j in range_n]) == 1) # # the sum in each row must be the magic sum for i in range_n: - solver.Add(solver.Sum([k * x[i,j,k] - for j in range_n - for k in range_N]) == s) + solver.Add(solver.Sum([k * x[i, j, k] + for j in range_n + for k in range_N]) == s) # # the sum in each column must be the magic sum for j in range_n: - solver.Add(solver.Sum([k * x[i,j,k] - for i in range_n - for k in range_N]) == s) + solver.Add(solver.Sum([k * x[i, j, k] + for i in range_n + for k in range_N]) == s) # # the sum in the diagonal must be the magic sum - solver.Add(solver.Sum([k * x[i,i,k] + solver.Add(solver.Sum([k * x[i, i, k] for i in range_n for k in range_N]) == s) - # # the sum in the co-diagonal must be the magic sum if range_n[0] == 1: - # for range_n = 1..n - solver.Add(solver.Sum([k * x[i,n-i+1,k] - for i in range_n - for k in range_N]) == s) + # for range_n = 1..n + solver.Add(solver.Sum([k * x[i, n - i + 1, k] + for i in range_n + for k in range_N]) == s) else: # for range_n = 0..n-1 - solver.Add(solver.Sum([k * x[i,n-i-1,k] + solver.Add(solver.Sum([k * x[i, n - i - 1, k] for i in range_n for k in range_N]) == s) @@ -148,9 +148,8 @@ def main(n = 3, sol = 'GLPK', use_output_matrix = 0): if use_output_matrix == 1: for i in range_n: for j in range_n: - solver.Add(square[i,j] == - solver.Sum([k * x[i,j,k] for k in range_N])) - + solver.Add(square[i, j] == + solver.Sum([k * x[i, j, k] for k in range_N])) # # solution and search @@ -169,14 +168,14 @@ def main(n = 3, sol = 'GLPK', use_output_matrix = 0): else: for i in range_n: for j in range_n: - print sum([int(k * x[i,j,k].SolutionValue()) for k in range_N]), " ", + print sum([int(k * x[i, j, k].SolutionValue()) for k in range_N]), ' ', print - print "\nx:" + print '\nx:' for i in range_n: for j in range_n: for k in range_N: - print int(x[i,j,k].SolutionValue()), + print int(x[i, j, k].SolutionValue()), print print @@ -186,19 +185,19 @@ def main(n = 3, sol = 'GLPK', use_output_matrix = 0): if __name__ == '__main__': - n = 3 - sol = 'GLPK' - use_output_matrix = 0 - if len(sys.argv) > 1: - n = int(sys.argv[1]) + n = 3 + sol = 'GLPK' + use_output_matrix = 0 + if len(sys.argv) > 1: + n = int(sys.argv[1]) - if len(sys.argv) > 2: - sol = sys.argv[2] - if sol != 'GLPK' and sol != 'CBC': - print 'Solver must be either GLPK or CBC' - sys.exit(1) + if len(sys.argv) > 2: + sol = sys.argv[2] + if sol != 'GLPK' and sol != 'CBC': + print 'Solver must be either GLPK or CBC' + sys.exit(1) - if len(sys.argv) > 3: - use_output_matrix = int(sys.argv[3]) + if len(sys.argv) > 3: + use_output_matrix = int(sys.argv[3]) - main(n, sol, use_output_matrix) + main(n, sol, use_output_matrix) diff --git a/examples/python/map.py b/examples/python/map.py index b444852667..ab1469f085 100644 --- a/examples/python/map.py +++ b/examples/python/map.py @@ -30,79 +30,77 @@ * Zinc: http://hakank.org/minizinc/map.zinc This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ from ortools.constraint_solver import pywrapcp def main(): - # Create the solver. - solver = pywrapcp.Solver('Map coloring') + # Create the solver. + solver = pywrapcp.Solver("Map coloring") - # - # data - # - Belgium = 0 - Denmark = 1 - France = 2 - Germany = 3 - Netherlands = 4 - Luxembourg = 5 + # + # data + # + Belgium = 0 + Denmark = 1 + France = 2 + Germany = 3 + Netherlands = 4 + Luxembourg = 5 - n = 6 - max_num_colors = 4 + n = 6 + max_num_colors = 4 - # declare variables - color = [solver.IntVar(1,max_num_colors, 'x%i' % i) for i in range(n)] + # declare variables + color = [solver.IntVar(1, max_num_colors, "x%i" % i) for i in range(n)] - # - # constraints - # - solver.Add(color[Belgium] == 1) # Symmetry breaking - solver.Add(color[France] != color[Belgium]) - solver.Add(color[France] != color[Luxembourg]) - solver.Add(color[France] != color[Germany]) - solver.Add(color[Luxembourg] != color[Germany]) - solver.Add(color[Luxembourg] != color[Belgium]) - solver.Add(color[Belgium] != color[Netherlands]) - solver.Add(color[Belgium] != color[Germany]) - solver.Add(color[Germany] != color[Netherlands]) - solver.Add(color[Germany] != color[Denmark]) + # + # constraints + # + solver.Add(color[Belgium] == 1) # Symmetry breaking + solver.Add(color[France] != color[Belgium]) + solver.Add(color[France] != color[Luxembourg]) + solver.Add(color[France] != color[Germany]) + solver.Add(color[Luxembourg] != color[Germany]) + solver.Add(color[Luxembourg] != color[Belgium]) + solver.Add(color[Belgium] != color[Netherlands]) + solver.Add(color[Belgium] != color[Germany]) + solver.Add(color[Germany] != color[Netherlands]) + solver.Add(color[Germany] != color[Denmark]) + + # + # solution and search + # + solution = solver.Assignment() + solution.Add([color[i] for i in range(n)]) + + collector = solver.AllSolutionCollector(solution) + # collector = solver.FirstSolutionCollector(solution) + # search_log = solver.SearchLog(100, x[0]) + solver.Solve(solver.Phase([color[i] for i in range(n)], + solver.INT_VAR_SIMPLE, + solver.ASSIGN_MIN_VALUE), + [collector]) + + num_solutions = collector.SolutionCount() + print "num_solutions: ", num_solutions + if num_solutions > 0: + for s in range(num_solutions): + colorval = [collector.Value(s, color[i]) for i in range(n)] + print "color:", colorval + + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() + + else: + print "No solutions found" - - # - # solution and search - # - solution = solver.Assignment() - solution.Add([color[i] for i in range(n)]) - - collector = solver.AllSolutionCollector(solution) - # collector = solver.FirstSolutionCollector(solution) - # search_log = solver.SearchLog(100, x[0]) - solver.Solve(solver.Phase([color[i] for i in range(n)], - solver.INT_VAR_SIMPLE, - solver.ASSIGN_MIN_VALUE), - [collector]) - - - num_solutions = collector.SolutionCount() - print "num_solutions: ", num_solutions - if num_solutions > 0: - for s in range(num_solutions): - colorval = [collector.Value(s, color[i]) for i in range(n)] - print "color:", colorval - - print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() - - else: - print "No solutions found" - - -if __name__ == '__main__': - main() +if __name__ == "__main__": + main() diff --git a/examples/python/marathon2.py b/examples/python/marathon2.py index 9eb0a6dfaa..91718f4b83 100644 --- a/examples/python/marathon2.py +++ b/examples/python/marathon2.py @@ -44,7 +44,8 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ import sys @@ -53,86 +54,82 @@ from ortools.constraint_solver import pywrapcp def main(): - # Create the solver. - solver = pywrapcp.Solver('Marathon') + # Create the solver. + solver = pywrapcp.Solver('Marathon') - # - # data - # - n = 6 + # + # data + # + n = 6 - runners_str = ['Dominique', 'Ignace', 'Naren', - 'Olivier', 'Philippe', 'Pascal'] + runners_str = ['Dominique', 'Ignace', 'Naren', + 'Olivier', 'Philippe', 'Pascal'] - # - # declare variables - # - runners = [solver.IntVar(1, n, 'runners[%i]' % i) for i in range(n)] - Dominique, Ignace, Naren, Olivier, Philippe, Pascal = runners + # + # declare variables + # + runners = [solver.IntVar(1, n, 'runners[%i]' % i) for i in range(n)] + Dominique, Ignace, Naren, Olivier, Philippe, Pascal = runners + # + # constraints + # + solver.Add(solver.AllDifferent(runners)) + # a: Olivier not last + solver.Add(Olivier != n) + # b: Dominique, Pascal and Ignace before Naren and Olivier + solver.Add(Dominique < Naren) + solver.Add(Dominique < Olivier) + solver.Add(Pascal < Naren) + solver.Add(Pascal < Olivier) + solver.Add(Ignace < Naren) + solver.Add(Ignace < Olivier) - # - # constraints - # - solver.Add(solver.AllDifferent(runners)) + # c: Dominique better than third + solver.Add(Dominique < 3) - # a: Olivier not last - solver.Add(Olivier != n) + # d: Philippe is among the first four + solver.Add(Philippe <= 4) - # b: Dominique, Pascal and Ignace before Naren and Olivier - solver.Add(Dominique < Naren) - solver.Add(Dominique < Olivier) - solver.Add(Pascal < Naren) - solver.Add(Pascal < Olivier) - solver.Add(Ignace < Naren) - solver.Add(Ignace < Olivier) + # e: Ignace neither second nor third + solver.Add(Ignace != 2) + solver.Add(Ignace != 3) - # c: Dominique better than third - solver.Add(Dominique < 3) + # f: Pascal three places earlier than Naren + solver.Add(Pascal + 3 == Naren) - # d: Philippe is among the first four - solver.Add(Philippe <= 4) + # g: Neither Ignace nor Dominique on fourth position + solver.Add(Ignace != 4) + solver.Add(Dominique != 4) - # e: Ignace neither second nor third - solver.Add(Ignace != 2) - solver.Add(Ignace != 3) + # + # solution and search + # + db = solver.Phase(runners, + solver.CHOOSE_MIN_SIZE_LOWEST_MIN, + solver.ASSIGN_CENTER_VALUE) - # f: Pascal three places earlier than Naren - solver.Add(Pascal + 3 == Naren) + solver.NewSearch(db) - # g: Neither Ignace nor Dominique on fourth position - solver.Add(Ignace != 4) - solver.Add(Dominique != 4) + num_solutions = 0 + while solver.NextSolution(): + num_solutions += 1 + runners_val = [runners[i].Value() for i in range(n)] + print 'runners:', runners_val + print 'Places:' + for i in range(1, n + 1): + for j in range(n): + if runners_val[j] == i: + print '%i: %s' % (i, runners_str[j]) + print - - # - # solution and search - # - db = solver.Phase(runners, - solver.CHOOSE_MIN_SIZE_LOWEST_MIN, - solver.ASSIGN_CENTER_VALUE) - - solver.NewSearch(db) - - num_solutions = 0 - while solver.NextSolution(): - num_solutions += 1 - runners_val = [runners[i].Value() for i in range(n)] - print 'runners:', runners_val - print "Places:" - for i in range(1, n+1): - for j in range(n): - if runners_val[j] == i: - print "%i: %s" % (i, runners_str[j]) - print - - print 'num_solutions:', num_solutions - print 'failures:', solver.Failures() - print 'branches:', solver.Branches() - print 'WallTime:', solver.WallTime(), 'ms' + print 'num_solutions:', num_solutions + print 'failures:', solver.Failures() + print 'branches:', solver.Branches() + print 'WallTime:', solver.WallTime(), 'ms' if __name__ == '__main__': - main() + main() diff --git a/examples/python/max_flow_taha.py b/examples/python/max_flow_taha.py index 2440646503..ab008eacb3 100644 --- a/examples/python/max_flow_taha.py +++ b/examples/python/max_flow_taha.py @@ -25,108 +25,105 @@ * MiniZinc: http://www.hakank.org/minizinc/max_flow_taha.mzn This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ from ortools.constraint_solver import pywrapcp + def main(): - # Create the solver. - solver = pywrapcp.Solver('Max flow problem, Taha') + # Create the solver. + solver = pywrapcp.Solver('Max flow problem, Taha') - # - # data - # - n = 5 - start = 0 - end = n-1 + # + # data + # + n = 5 + start = 0 + end = n - 1 - nodes = range(n) + nodes = range(n) - # cost matrix - c = [ - [0, 20, 30, 10, 0], - [0, 0, 40, 0, 30], - [0, 0, 0, 10, 20], - [0, 0, 5, 0, 20], - [0, 0, 0, 0, 0] - ] + # cost matrix + c = [ + [0, 20, 30, 10, 0], + [0, 0, 40, 0, 30], + [0, 0, 0, 10, 20], + [0, 0, 5, 0, 20], + [0, 0, 0, 0, 0] + ] + # + # declare variables + # + x = {} + for i in nodes: + for j in nodes: + x[i, j] = solver.IntVar(0, c[i][j], 'x[%i,%i]' % (i, j)) + x_flat = [x[i, j] for i in nodes for j in nodes] + out_flow = [solver.IntVar(0, 10000, 'out_flow[%i]' % i) for i in nodes] + in_flow = [solver.IntVar(0, 10000, 'in_flow[%i]' % i) for i in nodes] - # - # declare variables - # - x = {} + total = solver.IntVar(0, 10000, 'z') + + # + # constraints + # + cost_sum = solver.Sum([x[start, j] for j in nodes if c[start][j] > 0]) + solver.Add(total == cost_sum) + + for i in nodes: + in_flow_sum = solver.Sum([x[j, i] for j in nodes if c[j][i] > 0]) + solver.Add(in_flow[i] == in_flow_sum) + + out_flow_sum = solver.Sum([x[i, j] for j in nodes if c[i][j] > 0]) + solver.Add(out_flow[i] == out_flow_sum) + + # in_flow == out_flow + for i in nodes: + if i != start and i != end: + solver.Add(out_flow[i] - in_flow[i] == 0) + + s1 = [x[i, start] for i in nodes if c[i][start] > 0] + if len(s1) > 0: + solver.Add(solver.Sum([x[i, start] + for i in nodes if c[i][start] > 0] == 0)) + + s2 = [x[end, j] for j in nodes if c[end][j] > 0] + if len(s2) > 0: + solver.Add(solver.Sum([x[end, j] + for j in nodes if c[end][j] > 0]) == 0) + + # objective: maximize total cost + objective = solver.Maximize(total, 1) + + # + # solution and search + # + db = solver.Phase(x_flat, + solver.INT_VAR_DEFAULT, + solver.ASSIGN_MAX_VALUE) + + solver.NewSearch(db, [objective]) + num_solutions = 0 + while solver.NextSolution(): + num_solutions += 1 + print 'total:', total.Value() + print 'in_flow:', [in_flow[i].Value() for i in nodes] + print 'out_flow:', [out_flow[i].Value() for i in nodes] for i in nodes: - for j in nodes: - x[i,j] = solver.IntVar(0, c[i][j], 'x[%i,%i]' % (i, j)) + for j in nodes: + print '%2i' % x[i, j].Value(), + print + print - x_flat = [x[i,j] for i in nodes for j in nodes] - out_flow = [solver.IntVar(0, 10000, 'out_flow[%i]' % i) for i in nodes] - in_flow = [solver.IntVar(0, 10000, 'in_flow[%i]' % i) for i in nodes] - - total = solver.IntVar(0, 10000, 'z') - - # - # constraints - # - cost_sum = solver.Sum([x[start,j] for j in nodes if c[start][j] > 0]) - solver.Add(total == cost_sum) - - for i in nodes: - in_flow_sum = solver.Sum([x[j,i] for j in nodes if c[j][i] > 0]) - solver.Add(in_flow[i] == in_flow_sum) - - out_flow_sum = solver.Sum([x[i,j] for j in nodes if c[i][j] > 0]) - solver.Add(out_flow[i] == out_flow_sum) - - # in_flow == out_flow - for i in nodes: - if i != start and i != end: - solver.Add(out_flow[i] - in_flow[i]==0) - - - s1 = [x[i,start] for i in nodes if c[i][start] > 0] - if len(s1) > 0: - solver.Add(solver.Sum([x[i,start] - for i in nodes if c[i][start] > 0] == 0)) - - s2 = [x[end,j] for j in nodes if c[end][j] > 0] - if len(s2) > 0: - solver.Add(solver.Sum([x[end,j] - for j in nodes if c[end][j] > 0]) == 0) - - - # objective: maximize total cost - objective = solver.Maximize(total, 1) - - - # - # solution and search - # - db = solver.Phase(x_flat, - solver.INT_VAR_DEFAULT, - solver.ASSIGN_MAX_VALUE) - - solver.NewSearch(db, [objective]) - num_solutions = 0 - while solver.NextSolution(): - num_solutions += 1 - print 'total:', total.Value() - print 'in_flow:', [in_flow[i].Value() for i in nodes] - print 'out_flow:', [out_flow[i].Value() for i in nodes] - for i in nodes: - for j in nodes: - print '%2i' % x[i,j].Value(), - print - print - - print 'num_solutions:', num_solutions - print 'failures:', solver.Failures() - print 'branches:', solver.Branches() - print 'WallTime:', solver.WallTime(), 'ms' + print 'num_solutions:', num_solutions + print 'failures:', solver.Failures() + print 'branches:', solver.Branches() + print 'WallTime:', solver.WallTime(), 'ms' if __name__ == '__main__': - main() + main() diff --git a/examples/python/max_flow_winston1.py b/examples/python/max_flow_winston1.py index 54da7735a1..460c9830f9 100644 --- a/examples/python/max_flow_winston1.py +++ b/examples/python/max_flow_winston1.py @@ -25,7 +25,8 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ import sys from ortools.constraint_solver import pywrapcp @@ -33,116 +34,112 @@ from ortools.constraint_solver import pywrapcp def main(): - # Create the solver. - solver = pywrapcp.Solver('Max flow problem, Winston') + # Create the solver. + solver = pywrapcp.Solver('Max flow problem, Winston') - # - # data - # - n = 5 - nodes = range(n) + # + # data + # + n = 5 + nodes = range(n) - # the arcs - # Note: - # This is 1-based to be compatible with other - # implementations. - arcs1 = [ - [1, 2], - [1, 3], - [2, 3], - [2, 4], - [3, 5], - [4, 5], - [5, 1] - ] + # the arcs + # Note: + # This is 1-based to be compatible with other + # implementations. + arcs1 = [ + [1, 2], + [1, 3], + [2, 3], + [2, 4], + [3, 5], + [4, 5], + [5, 1] + ] - # convert arcs to 0-based - arcs = [] - for (a_from, a_to) in arcs1: - a_from -= 1 - a_to -= 1 - arcs.append([a_from, a_to]) + # convert arcs to 0-based + arcs = [] + for (a_from, a_to) in arcs1: + a_from -= 1 + a_to -= 1 + arcs.append([a_from, a_to]) - num_arcs = len(arcs) + num_arcs = len(arcs) - # capacities - cap = [2,3,3,4,2,1,100] + # capacities + cap = [2, 3, 3, 4, 2, 1, 100] - # convert arcs to matrix - # for sanity checking below - mat = {} + # convert arcs to matrix + # for sanity checking below + mat = {} + for i in nodes: + for j in nodes: + c = 0 + for k in range(num_arcs): + if arcs[k][0] == i and arcs[k][1] == j: + c = 1 + mat[i, j] = c + + # + # declare variables + # + flow = {} + for i in nodes: + for j in nodes: + flow[i, j] = solver.IntVar(0, 200, 'flow %i %i' % (i, j)) + + flow_flat = [flow[i, j] for i in nodes for j in nodes] + + z = solver.IntVar(0, 10000, 'z') + + # + # constraints + # + solver.Add(z == flow[n - 1, 0]) + + # capacity of arcs + for i in range(num_arcs): + solver.Add(flow[arcs[i][0], arcs[i][1]] <= cap[i]) + + # inflows == outflows + for i in nodes: + s1 = solver.Sum([flow[arcs[k][0], arcs[k][1]] + for k in range(num_arcs) if arcs[k][1] == i]) + s2 = solver.Sum([flow[arcs[k][0], arcs[k][1]] + for k in range(num_arcs) if arcs[k][0] == i]) + solver.Add(s1 == s2) + + # sanity: just arcs with connections can have a flow + for i in nodes: + for j in nodes: + if mat[i, j] == 0: + solver.Add(flow[i, j] == 0) + + # objective: maximize z + objective = solver.Maximize(z, 1) + + # + # solution and search + # + db = solver.Phase(flow_flat, + solver.INT_VAR_DEFAULT, + solver.INT_VALUE_DEFAULT) + + solver.NewSearch(db, [objective]) + num_solutions = 0 + while solver.NextSolution(): + num_solutions += 1 + print 'z:', z.Value() for i in nodes: - for j in nodes: - c = 0; - for k in range(num_arcs): - if arcs[k][0] == i and arcs[k][1] == j: - c = 1 - mat[i,j] = c + for j in nodes: + print flow[i, j].Value(), + print + print - - # - # declare variables - # - flow = {} - for i in nodes: - for j in nodes: - flow[i,j] = solver.IntVar(0, 200, 'flow %i %i' % (i, j)) - - flow_flat = [flow[i,j] for i in nodes for j in nodes] - - z = solver.IntVar(0, 10000, 'z') - - # - # constraints - # - solver.Add(z == flow[n-1, 0]) - - # capacity of arcs - for i in range(num_arcs): - solver.Add(flow[arcs[i][0], arcs[i][1]] <= cap[i]) - - - # inflows == outflows - for i in nodes: - s1 = solver.Sum([flow[arcs[k][0], arcs[k][1]] - for k in range(num_arcs) if arcs[k][1] == i]) - s2 = solver.Sum([flow[arcs[k][0], arcs[k][1]] - for k in range(num_arcs) if arcs[k][0] == i]) - solver.Add(s1 == s2) - - # sanity: just arcs with connections can have a flow - for i in nodes: - for j in nodes: - if mat[i,j] == 0: - solver.Add(flow[i,j] == 0) - - - # objective: maximize z - objective = solver.Maximize(z, 1) - - - # - # solution and search - # - db = solver.Phase(flow_flat, - solver.INT_VAR_DEFAULT, - solver.INT_VALUE_DEFAULT) - - solver.NewSearch(db, [objective]) - num_solutions = 0 - while solver.NextSolution(): - num_solutions += 1 - print "z:", z.Value() - for i in nodes: - for j in nodes: - print flow[i,j].Value(), - print - print - - print 'num_solutions:', num_solutions - print 'failures:', solver.Failures() - print 'branches:', solver.Branches() - print 'WallTime:', solver.WallTime(), 'ms' + print 'num_solutions:', num_solutions + print 'failures:', solver.Failures() + print 'branches:', solver.Branches() + print 'WallTime:', solver.WallTime(), 'ms' if __name__ == '__main__': - main() + main() diff --git a/examples/python/minesweeper.py b/examples/python/minesweeper.py index 3570c5ae04..634300286e 100644 --- a/examples/python/minesweeper.py +++ b/examples/python/minesweeper.py @@ -60,7 +60,8 @@ * Zinc: http://www.hakank.org/minizinc/minesweeper.zinc This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ import sys from ortools.constraint_solver import pywrapcp @@ -69,173 +70,170 @@ default_r = 8 default_c = 8 X = -1 default_game = [ - [2,3,X,2,2,X,2,1], - [X,X,4,X,X,4,X,2], - [X,X,X,X,X,X,4,X], - [X,5,X,6,X,X,X,2], - [2,X,X,X,5,5,X,2], - [1,3,4,X,X,X,4,X], - [0,1,X,4,X,X,X,3], - [0,1,2,X,2,3,X,2] - ] + [2, 3, X, 2, 2, X, 2, 1], + [X, X, 4, X, X, 4, X, 2], + [X, X, X, X, X, X, 4, X], + [X, 5, X, 6, X, X, X, 2], + [2, X, X, X, 5, 5, X, 2], + [1, 3, 4, X, X, X, 4, X], + [0, 1, X, 4, X, X, X, 3], + [0, 1, 2, X, 2, 3, X, 2] +] def main(game="", r="", c=""): - # Create the solver. - solver = pywrapcp.Solver('Minesweeper') + # Create the solver. + solver = pywrapcp.Solver("Minesweeper") - # - # data - # + # + # data + # - # Set default problem - if game == "": - game = default_game - r = default_r - c = default_c - else: - print "rows:", r, " cols:", c + # Set default problem + if game == "": + game = default_game + r = default_r + c = default_c + else: + print "rows:", r, " cols:", c + # + # Default problem from "Some Minesweeper Configurations",page 3 + # (same as problem instance minesweeper_config3.txt) + # It has 4 solutions + # + # r = 8 + # c = 8 + # X = -1 + # game = [ + # [2,3,X,2,2,X,2,1], + # [X,X,4,X,X,4,X,2], + # [X,X,X,X,X,X,4,X], + # [X,5,X,6,X,X,X,2], + # [2,X,X,X,5,5,X,2], + # [1,3,4,X,X,X,4,X], + # [0,1,X,4,X,X,X,3], + # [0,1,2,X,2,3,X,2] + # ] - # - # Default problem from "Some Minesweeper Configurations",page 3 - # (same as problem instance minesweeper_config3.txt) - # It has 4 solutions - # - # r = 8 - # c = 8 - # X = -1 - # game = [ - # [2,3,X,2,2,X,2,1], - # [X,X,4,X,X,4,X,2], - # [X,X,X,X,X,X,4,X], - # [X,5,X,6,X,X,X,2], - # [2,X,X,X,5,5,X,2], - # [1,3,4,X,X,X,4,X], - # [0,1,X,4,X,X,X,3], - # [0,1,2,X,2,3,X,2] - # ] + S = [-1, 0, 1] # for the neighbors of "this" cell - S = [-1,0,1] # for the neighbors of "this" cell - - # print problem instance - print "Problem:" - for i in range(r): - for j in range(c): - if game[i][j] == X: - print "X", - else: - print game[i][j], - print + # print problem instance + print "Problem:" + for i in range(r): + for j in range(c): + if game[i][j] == X: + print "X", + else: + print game[i][j], print + print + # declare variables + mines = {} + for i in range(r): + for j in range(c): + mines[(i, j)] = solver.IntVar(0, 1, "mines %i %i" % (i, j)) - # declare variables - mines = {} - for i in range(r): + # + # constraints + # + for i in range(r): + for j in range(c): + if game[i][j] >= 0: + solver.Add(mines[i, j] == 0) + # this cell is the sum of all the surrounding cells + solver.Add( + game[i][j] == solver.Sum([mines[i + a, j + b] + for a in S for b in S + if i + a >= 0 and + j + b >= 0 and + i + a < r and + j + b < c]) + ) + if game[i][j] > X: + # This cell cannot be a mine + solver.Add(mines[i, j] == 0) + + # + # solution and search + # + solution = solver.Assignment() + solution.Add([mines[(i, j)] for i in range(r) for j in range(c)]) + + collector = solver.AllSolutionCollector(solution) + solver.Solve(solver.Phase([mines[(i, j)] for i in range(r) for j in range(c)], + solver.INT_VAR_SIMPLE, + solver.ASSIGN_MIN_VALUE), + [collector]) + + num_solutions = collector.SolutionCount() + print "num_solutions: ", num_solutions + if num_solutions > 0: + for s in range(num_solutions): + minesval = [collector.Value(s, mines[(i, j)]) + for i in range(r) for j in range(c)] + for i in range(r): for j in range(c): - mines[(i,j)] = solver.IntVar(0,1, 'mines %i %i' % (i, j)) - - # - # constraints - # - for i in range(r): - for j in range(c): - if game[i][j] >= 0: - solver.Add(mines[i,j] == 0) - # this cell is the sum of all the surrounding cells - solver.Add( - game[i][j] == solver.Sum([mines[i+a,j+b] - for a in S for b in S - if i + a >=0 and - j + b >=0 and - i + a < r and - j + b < c - ]) - ) - if game[i][j] > X: - # This cell cannot be a mine - solver.Add(mines[i,j] == 0) - - # - # solution and search - # - solution = solver.Assignment() - solution.Add([mines[(i,j)] for i in range(r) for j in range(c)]) - - collector = solver.AllSolutionCollector(solution) - solver.Solve(solver.Phase([mines[(i,j)] for i in range(r) for j in range(c)], - solver.INT_VAR_SIMPLE, - solver.ASSIGN_MIN_VALUE), - [collector]) - - num_solutions = collector.SolutionCount() - print "num_solutions: ", num_solutions - if num_solutions > 0: - for s in range(num_solutions): - minesval = [collector.Value(s, mines[(i,j)]) - for i in range(r) for j in range(c)] - for i in range(r): - for j in range(c): - print minesval[i*c+j], - print - print - + print minesval[i * c + j], print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + print - else: - print "No solutions found" + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() + + else: + print "No solutions found" # # Read a problem instance from a file # def read_problem(file): - f = open(file, 'r') - rows = int(f.readline()) - cols = int(f.readline()) - game = [] - for i in range(rows): - x = f.readline() - row = [0]*cols - for j in range(cols): - if x[j] == ".": - tmp = -1 - else: - tmp = int(x[j]) - row[j] = tmp - game.append(row) - return [game, rows, cols] + f = open(file, "r") + rows = int(f.readline()) + cols = int(f.readline()) + game = [] + for i in range(rows): + x = f.readline() + row = [0] * cols + for j in range(cols): + if x[j] == ".": + tmp = -1 + else: + tmp = int(x[j]) + row[j] = tmp + game.append(row) + return [game, rows, cols] # # Print the mines # def print_mines(mines, rows, cols): - for i in range(rows): - for j in range(cols): - print mines[i,j], - print '' + for i in range(rows): + for j in range(cols): + print mines[i, j], + print "" + def print_game(game, rows, cols): - for i in range(rows): - for j in range(cols): - print game[i][j], - print '' + for i in range(rows): + for j in range(cols): + print game[i][j], + print "" - -if __name__ == '__main__': - if len(sys.argv) > 1: - file = sys.argv[1] - print "Problem instance from", file - [game, rows, cols] = read_problem(file) - # print_game(game, rows, cols) - main(game, rows, cols) - else: - main() +if __name__ == "__main__": + if len(sys.argv) > 1: + file = sys.argv[1] + print "Problem instance from", file + [game, rows, cols] = read_problem(file) + # print_game(game, rows, cols) + main(game, rows, cols) + else: + main() diff --git a/examples/python/mr_smith.py b/examples/python/mr_smith.py index 3fe6548272..c5c15cb543 100644 --- a/examples/python/mr_smith.py +++ b/examples/python/mr_smith.py @@ -44,7 +44,8 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ import sys @@ -53,73 +54,70 @@ from ortools.constraint_solver import pywrapcp def main(): - # Create the solver. - solver = pywrapcp.Solver('Mr Smith problem') + # Create the solver. + solver = pywrapcp.Solver('Mr Smith problem') - # - # data - # - n = 5 + # + # data + # + n = 5 + # + # declare variables + # + x = [solver.IntVar(0, 1, 'x[%i]' % i) for i in range(n)] + Mr_Smith, Mrs_Smith, Matt, John, Tim = x - # - # declare variables - # - x = [solver.IntVar(0, 1, 'x[%i]' % i) for i in range(n)] - Mr_Smith, Mrs_Smith, Matt, John, Tim = x + # + # constraints + # + # + # I've kept the MiniZinc constraints for clarity + # and debugging. + # - # - # constraints - # + # If Mr Smith comes then his wife will come too. + # (Mr_Smith -> Mrs_Smith) + solver.Add(Mr_Smith - Mrs_Smith <= 0) - # - # I've kept the MiniZinc constraints for clarity - # and debugging. - # + # At least one of their two sons Matt and John will come. + # (Matt \/ John) + solver.Add(Matt + John >= 1) - # If Mr Smith comes then his wife will come too. - # (Mr_Smith -> Mrs_Smith) - solver.Add(Mr_Smith-Mrs_Smith <= 0) + # Either Mrs Smith or Tim will come but not both. + # bool2int(Mrs_Smith) + bool2int(Tim) = 1 /\ + # (Mrs_Smith xor Tim) + solver.Add(Mrs_Smith + Tim == 1) - # At least one of their two sons Matt and John will come. - # (Matt \/ John) - solver.Add(Matt+John >= 1) + # Either Tim and John will come or neither will come. + # (Tim = John) + solver.Add(Tim == John) - # Either Mrs Smith or Tim will come but not both. - # bool2int(Mrs_Smith) + bool2int(Tim) = 1 /\ - # (Mrs_Smith xor Tim) - solver.Add(Mrs_Smith + Tim == 1) + # If Matt comes /\ then John and his father will also come. + # (Matt -> (John /\ Mr_Smith)) + solver.Add(Matt - (John * Mr_Smith) <= 0) - # Either Tim and John will come or neither will come. - # (Tim = John) - solver.Add(Tim == John) + # + # solution and search + # + db = solver.Phase(x, + solver.INT_VAR_DEFAULT, + solver.INT_VALUE_DEFAULT) - # If Matt comes /\ then John and his father will also come. - # (Matt -> (John /\ Mr_Smith)) - solver.Add(Matt - (John*Mr_Smith) <= 0) + solver.NewSearch(db) + num_solutions = 0 + while solver.NextSolution(): + num_solutions += 1 + print 'x:', [x[i].Value() for i in range(n)] - # - # solution and search - # - db = solver.Phase(x, - solver.INT_VAR_DEFAULT, - solver.INT_VALUE_DEFAULT) - - solver.NewSearch(db) - - num_solutions = 0 - while solver.NextSolution(): - num_solutions += 1 - print 'x:', [x[i].Value() for i in range(n)] - - print - print 'num_solutions:', num_solutions - print 'failures:', solver.Failures() - print 'branches:', solver.Branches() - print 'WallTime:', solver.WallTime(), 'ms' + print + print 'num_solutions:', num_solutions + print 'failures:', solver.Failures() + print 'branches:', solver.Branches() + print 'WallTime:', solver.WallTime(), 'ms' if __name__ == '__main__': - main() + main() diff --git a/examples/python/nonogram_default_search.py b/examples/python/nonogram_default_search.py index 3e59007f02..46b8016d16 100644 --- a/examples/python/nonogram_default_search.py +++ b/examples/python/nonogram_default_search.py @@ -64,7 +64,7 @@ def make_transition_tuples(pattern): # convert pattern to a 0/1 pattern for easy handling of # the states - tmp = [0]; + tmp = [0] c = 0 for pattern_index in range(p_len): tmp.extend([1] * pattern[pattern_index]) @@ -101,6 +101,7 @@ def check_rule(rules, y): initial_state, accepting_states)) + def main(rows, row_rule_len, row_rules, cols, col_rule_len, col_rules): # Create the solver. @@ -139,7 +140,6 @@ def main(rows, row_rule_len, row_rules, cols, col_rule_len, col_rules): for j in range(cols): check_rule(col_rules[j], [board[i, j] for i in range(rows)]) - # # solution and search # @@ -189,34 +189,34 @@ def main(rows, row_rule_len, row_rules, cols, col_rule_len, col_rules): rows = 12 row_rule_len = 3 row_rules = [ - [0,0,2], - [0,1,2], - [0,1,1], - [0,0,2], - [0,0,1], - [0,0,3], - [0,0,3], - [0,2,2], - [0,2,1], - [2,2,1], - [0,2,3], - [0,2,2] - ] + [0, 0, 2], + [0, 1, 2], + [0, 1, 1], + [0, 0, 2], + [0, 0, 1], + [0, 0, 3], + [0, 0, 3], + [0, 2, 2], + [0, 2, 1], + [2, 2, 1], + [0, 2, 3], + [0, 2, 2] +] cols = 10 col_rule_len = 2 col_rules = [ - [2,1], - [1,3], - [2,4], - [3,4], - [0,4], - [0,3], - [0,3], - [0,3], - [0,2], - [0,2] - ] + [2, 1], + [1, 3], + [2, 4], + [3, 4], + [0, 4], + [0, 3], + [0, 3], + [0, 3], + [0, 2], + [0, 2] +] if __name__ == '__main__': diff --git a/examples/python/nonogram_regular.py b/examples/python/nonogram_regular.py index 1dc2353ac5..dbed5a8268 100644 --- a/examples/python/nonogram_regular.py +++ b/examples/python/nonogram_regular.py @@ -49,7 +49,8 @@ to about 1 second' http://www.hakank.org/constraint_programming_blog/2009/03/comet_nonogram_improved_solvin_1.html - * 'Comet: regular constraint, a much faster Nonogram with the regular constraint, + * 'Comet: regular constraint, a much faster Nonogram with the regular + constraint, some OPL models, and more' http://www.hakank.org/constraint_programming_blog/2009/02/comet_regular_constraint_a_muc_1.html @@ -61,7 +62,8 @@ Note: nonogram_create_automaton2.mzn is the preferred model This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ @@ -92,48 +94,49 @@ from ortools.constraint_solver import pywrapcp # F : accepting states def regular(x, Q, S, d, q0, F): - solver = x[0].solver() + solver = x[0].solver() - assert Q > 0, 'regular: "Q" must be greater than zero' - assert S > 0, 'regular: "S" must be greater than zero' + assert Q > 0, 'regular: "Q" must be greater than zero' + assert S > 0, 'regular: "S" must be greater than zero' - # d2 is the same as d, except we add one extra transition for - # each possible input; each extra transition is from state zero - # to state zero. This allows us to continue even if we hit a - # non-accepted input. + # d2 is the same as d, except we add one extra transition for + # each possible input; each extra transition is from state zero + # to state zero. This allows us to continue even if we hit a + # non-accepted input. - # int d2[0..Q, 1..S] - d2 = [] - for i in range(Q+1): - row = [] - for j in range(S): - if i == 0: - row.append(0) - else: - row.append(d[i-1][j]) - d2.append(row) + # int d2[0..Q, 1..S] + d2 = [] + for i in range(Q + 1): + row = [] + for j in range(S): + if i == 0: + row.append(0) + else: + row.append(d[i - 1][j]) + d2.append(row) - d2_flatten = [d2[i][j] for i in range(Q+1) for j in range(S)] + d2_flatten = [d2[i][j] for i in range(Q + 1) for j in range(S)] - # If x has index set m..n, then a[m-1] holds the initial state - # (q0), and a[i+1] holds the state we're in after processing - # x[i]. If a[n] is in F, then we succeed (ie. accept the - # string). - x_range = range(0,len(x)) - m = 0 - n = len(x) + # If x has index set m..n, then a[m-1] holds the initial state + # (q0), and a[i+1] holds the state we're in after processing + # x[i]. If a[n] is in F, then we succeed (ie. accept the + # string). + x_range = range(0, len(x)) + m = 0 + n = len(x) - a = [solver.IntVar(0, Q+1, 'a[%i]' % i) for i in range(m, n+1)] + a = [solver.IntVar(0, Q + 1, 'a[%i]' % i) for i in range(m, n + 1)] - # Check that the final state is in F - solver.Add(solver.MemberCt(a[-1], F)) - # First state is q0 - solver.Add(a[m] == q0) - for i in x_range: - solver.Add(x[i] >= 1) - solver.Add(x[i] <= S) - # Determine a[i+1]: a[i+1] == d2[a[i], x[i]] - solver.Add(a[i+1] == solver.Element(d2_flatten, ((a[i])*S)+(x[i]-1))) + # Check that the final state is in F + solver.Add(solver.MemberCt(a[-1], F)) + # First state is q0 + solver.Add(a[m] == q0) + for i in x_range: + solver.Add(x[i] >= 1) + solver.Add(x[i] <= S) + # Determine a[i+1]: a[i+1] == d2[a[i], x[i]] + solver.Add( + a[i + 1] == solver.Element(d2_flatten, ((a[i]) * S) + (x[i] - 1))) # @@ -142,168 +145,165 @@ def regular(x, Q, S, d, q0, F): # def make_transition_matrix(pattern): - p_len = len(pattern) - num_states = p_len + sum(pattern) + p_len = len(pattern) + num_states = p_len + sum(pattern) - # this is for handling 0-clues. It generates - # just the state 1,2 - if num_states == 0: - num_states = 1 + # this is for handling 0-clues. It generates + # just the state 1,2 + if num_states == 0: + num_states = 1 - t_matrix = [] - for i in range(num_states): - row = [] - for j in range(2): - row.append(0) - t_matrix.append(row) + t_matrix = [] + for i in range(num_states): + row = [] + for j in range(2): + row.append(0) + t_matrix.append(row) - # convert pattern to a 0/1 pattern for easy handling of - # the states - tmp = [0 for i in range(num_states)] - c = 0 - tmp[c] = 0 - for i in range(p_len): - for j in range(pattern[i]): - c += 1 - tmp[c] = 1 - if c < num_states-1: - c += 1 - tmp[c] = 0 + # convert pattern to a 0/1 pattern for easy handling of + # the states + tmp = [0 for i in range(num_states)] + c = 0 + tmp[c] = 0 + for i in range(p_len): + for j in range(pattern[i]): + c += 1 + tmp[c] = 1 + if c < num_states - 1: + c += 1 + tmp[c] = 0 - t_matrix[num_states-1][0] = num_states - t_matrix[num_states-1][1] = 0 + t_matrix[num_states - 1][0] = num_states + t_matrix[num_states - 1][1] = 0 - for i in range(num_states): - if tmp[i] == 0: - t_matrix[i][0] = i+1 - t_matrix[i][1] = i+2 + for i in range(num_states): + if tmp[i] == 0: + t_matrix[i][0] = i + 1 + t_matrix[i][1] = i + 2 + else: + if i < num_states - 1: + if tmp[i + 1] == 1: + t_matrix[i][0] = 0 + t_matrix[i][1] = i + 2 else: - if i < num_states-1: - if tmp[i+1] == 1: - t_matrix[i][0] = 0 - t_matrix[i][1] = i+2 - else: - t_matrix[i][0] = i+2 - t_matrix[i][1] = 0 + t_matrix[i][0] = i + 2 + t_matrix[i][1] = 0 + # print 'The states:' + # for i in range(num_states): + # for j in range(2): + # print t_matrix[i][j], + # print + # print - # print 'The states:' - # for i in range(num_states): - # for j in range(2): - # print t_matrix[i][j], - # print - # print - - return t_matrix + return t_matrix # # check each rule by creating an automaton # and regular # + + def check_rule(rules, y): - solver = y[0].solver() + solver = y[0].solver() - r_len = sum([1 for i in range(len(rules)) if rules[i] > 0]) - rules_tmp = [] - for i in range(len(rules)): - if rules[i] > 0: - rules_tmp.append(rules[i]) + r_len = sum([1 for i in range(len(rules)) if rules[i] > 0]) + rules_tmp = [] + for i in range(len(rules)): + if rules[i] > 0: + rules_tmp.append(rules[i]) - transition_fn = make_transition_matrix(rules_tmp) - n_states = len(transition_fn) - input_max = 2 + transition_fn = make_transition_matrix(rules_tmp) + n_states = len(transition_fn) + input_max = 2 - # Note: we cannot use 0 since it's the failing state - initial_state = 1 - accepting_states = [n_states] # This is the last state - - regular(y, n_states, input_max, transition_fn, - initial_state, accepting_states) + # Note: we cannot use 0 since it's the failing state + initial_state = 1 + accepting_states = [n_states] # This is the last state + regular(y, n_states, input_max, transition_fn, + initial_state, accepting_states) def main(rows, row_rule_len, row_rules, cols, col_rule_len, col_rules): - # Create the solver. - solver = pywrapcp.Solver('Regular test') + # Create the solver. + solver = pywrapcp.Solver('Regular test') - # - # data - # - - # - # variables - # - board = {} - for i in range(rows): - for j in range(cols): - board[i,j] = solver.IntVar(1,2,'board[%i,%i]' % (i,j)) - board_flat = [board[i,j] for i in range(rows) for j in range(cols)] - - # Flattened board for labeling. - # This labeling was inspired by a suggestion from - # Pascal Van Hentenryck about my Comet nonogram model. - board_label = [] - if rows * row_rule_len < cols * col_rule_len: - for i in range(rows): - for j in range(cols): - board_label.append(board[i,j]) - else: - for j in range(cols): - for i in range(rows): - board_label.append(board[i,j]) - - - # - # constraints - # - for i in range(rows): - check_rule([row_rules[i][j] for j in range(row_rule_len)], - [board[i,j] for j in range(cols)]) + # + # data + # + # + # variables + # + board = {} + for i in range(rows): for j in range(cols): - check_rule([col_rules[j][k] for k in range(col_rule_len)], - [board[i,j] for i in range(rows)]) + board[i, j] = solver.IntVar(1, 2, 'board[%i,%i]' % (i, j)) + board_flat = [board[i, j] for i in range(rows) for j in range(cols)] + # Flattened board for labeling. + # This labeling was inspired by a suggestion from + # Pascal Van Hentenryck about my Comet nonogram model. + board_label = [] + if rows * row_rule_len < cols * col_rule_len: + for i in range(rows): + for j in range(cols): + board_label.append(board[i, j]) + else: + for j in range(cols): + for i in range(rows): + board_label.append(board[i, j]) - # - # solution and search - # - db = solver.Phase(board_label, - solver.CHOOSE_FIRST_UNBOUND, - solver.ASSIGN_MIN_VALUE) + # + # constraints + # + for i in range(rows): + check_rule([row_rules[i][j] for j in range(row_rule_len)], + [board[i, j] for j in range(cols)]) - solver.NewSearch(db) + for j in range(cols): + check_rule([col_rules[j][k] for k in range(col_rule_len)], + [board[i, j] for i in range(rows)]) - num_solutions = 0 - while solver.NextSolution(): - print - num_solutions += 1 - for i in range(rows): - row = [board[i,j].Value()-1 for j in range(cols)] - row_pres = [] - for j in row: - if j == 1: - row_pres.append('#') - else: - row_pres.append(' ') - print ' ', ''.join(row_pres) + # + # solution and search + # + db = solver.Phase(board_label, + solver.CHOOSE_FIRST_UNBOUND, + solver.ASSIGN_MIN_VALUE) - print - print ' ', '-' * cols + solver.NewSearch(db) - if num_solutions >= 2: - print '2 solutions is enough...' - break - - solver.EndSearch() + num_solutions = 0 + while solver.NextSolution(): print - print 'num_solutions:', num_solutions - print 'failures:', solver.Failures() - print 'branches:', solver.Branches() - print 'WallTime:', solver.WallTime(), 'ms' + num_solutions += 1 + for i in range(rows): + row = [board[i, j].Value() - 1 for j in range(cols)] + row_pres = [] + for j in row: + if j == 1: + row_pres.append('#') + else: + row_pres.append(' ') + print ' ', ''.join(row_pres) + print + print ' ', '-' * cols + + if num_solutions >= 2: + print '2 solutions is enough...' + break + + solver.EndSearch() + print + print 'num_solutions:', num_solutions + print 'failures:', solver.Failures() + print 'branches:', solver.Branches() + print 'WallTime:', solver.WallTime(), 'ms' # @@ -315,39 +315,39 @@ def main(rows, row_rule_len, row_rules, rows = 12 row_rule_len = 3 row_rules = [ - [0,0,2], - [0,1,2], - [0,1,1], - [0,0,2], - [0,0,1], - [0,0,3], - [0,0,3], - [0,2,2], - [0,2,1], - [2,2,1], - [0,2,3], - [0,2,2] - ] + [0, 0, 2], + [0, 1, 2], + [0, 1, 1], + [0, 0, 2], + [0, 0, 1], + [0, 0, 3], + [0, 0, 3], + [0, 2, 2], + [0, 2, 1], + [2, 2, 1], + [0, 2, 3], + [0, 2, 2] +] cols = 10 col_rule_len = 2 col_rules = [ - [2,1], - [1,3], - [2,4], - [3,4], - [0,4], - [0,3], - [0,3], - [0,3], - [0,2], - [0,2] - ] + [2, 1], + [1, 3], + [2, 4], + [3, 4], + [0, 4], + [0, 3], + [0, 3], + [0, 3], + [0, 2], + [0, 2] +] if __name__ == '__main__': - if len(sys.argv) > 1: - file = sys.argv[1] - execfile(file) - main(rows, row_rule_len, row_rules, - cols, col_rule_len, col_rules) + if len(sys.argv) > 1: + file = sys.argv[1] + execfile(file) + main(rows, row_rule_len, row_rules, + cols, col_rule_len, col_rules) diff --git a/examples/python/nonogram_table.py b/examples/python/nonogram_table.py index ca2381ac16..946023c0ba 100644 --- a/examples/python/nonogram_table.py +++ b/examples/python/nonogram_table.py @@ -49,7 +49,8 @@ to about 1 second' http://www.hakank.org/constraint_programming_blog/2009/03/comet_nonogram_improved_solvin_1.html - * 'Comet: regular constraint, a much faster Nonogram with the regular constraint, + * 'Comet: regular constraint, a much faster Nonogram with the regular + constraint, some OPL models, and more' http://www.hakank.org/constraint_programming_blog/2009/02/comet_regular_constraint_a_muc_1.html @@ -61,7 +62,8 @@ Note: nonogram_create_automaton2.mzn is the preferred model This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ @@ -120,9 +122,9 @@ def regular(x, Q, S, d, q0, F): a = [solver.IntVar(0, Q + 1, 'a[%i]' % i) for i in range(m, n + 1)] - # Check that the final state is in F + # Check that the final state is in F solver.Add(solver.MemberCt(a[-1], F)) - # First state is q0 + # First state is q0 solver.Add(a[m] == q0) for i in x_range: solver.Add(x[i] >= 1) @@ -134,6 +136,8 @@ def regular(x, Q, S, d, q0, F): # Make a transition (automaton) matrix from a # single pattern, e.g. [3,2,1] # + + def make_transition_matrix(pattern): p_len = len(pattern) @@ -160,27 +164,26 @@ def make_transition_matrix(pattern): for j in range(pattern[i]): c += 1 tmp[c] = 1 - if c < num_states-1: + if c < num_states - 1: c += 1 tmp[c] = 0 - t_matrix[num_states-1][0] = num_states - t_matrix[num_states-1][1] = 0 + t_matrix[num_states - 1][0] = num_states + t_matrix[num_states - 1][1] = 0 for i in range(num_states): if tmp[i] == 0: - t_matrix[i][0] = i+1 - t_matrix[i][1] = i+2 + t_matrix[i][0] = i + 1 + t_matrix[i][1] = i + 2 else: - if i < num_states-1: - if tmp[i+1] == 1: + if i < num_states - 1: + if tmp[i + 1] == 1: t_matrix[i][0] = 0 - t_matrix[i][1] = i+2 + t_matrix[i][1] = i + 2 else: - t_matrix[i][0] = i+2 + t_matrix[i][0] = i + 2 t_matrix[i][1] = 0 - # print 'The states:' # for i in range(num_states): # for j in range(2): @@ -194,6 +197,8 @@ def make_transition_matrix(pattern): # check each rule by creating an automaton # and regular # + + def check_rule(rules, y): solver = y[0].solver() @@ -209,13 +214,12 @@ def check_rule(rules, y): # Note: we cannot use 0 since it's the failing state initial_state = 1 - accepting_states = [n_states] # This is the last state + accepting_states = [n_states] # This is the last state regular(y, n_states, input_max, transition_fn, initial_state, accepting_states) - def main(rows, row_rule_len, row_rules, cols, col_rule_len, col_rules): @@ -248,19 +252,17 @@ def main(rows, row_rule_len, row_rules, for i in range(rows): board_label.append(board[i, j]) - # # constraints # for i in range(rows): check_rule([row_rules[i][j] for j in range(row_rule_len)], - [board[i,j] for j in range(cols)]) + [board[i, j] for j in range(cols)]) for j in range(cols): check_rule([col_rules[j][k] for k in range(col_rule_len)], [board[i, j] for i in range(rows)]) - # # solution and search # @@ -299,7 +301,6 @@ def main(rows, row_rule_len, row_rules, print 'WallTime:', solver.WallTime(), 'ms' - # # Default problem # @@ -309,34 +310,34 @@ def main(rows, row_rule_len, row_rules, rows = 12 row_rule_len = 3 row_rules = [ - [0,0,2], - [0,1,2], - [0,1,1], - [0,0,2], - [0,0,1], - [0,0,3], - [0,0,3], - [0,2,2], - [0,2,1], - [2,2,1], - [0,2,3], - [0,2,2] - ] + [0, 0, 2], + [0, 1, 2], + [0, 1, 1], + [0, 0, 2], + [0, 0, 1], + [0, 0, 3], + [0, 0, 3], + [0, 2, 2], + [0, 2, 1], + [2, 2, 1], + [0, 2, 3], + [0, 2, 2] +] cols = 10 col_rule_len = 2 col_rules = [ - [2,1], - [1,3], - [2,4], - [3,4], - [0,4], - [0,3], - [0,3], - [0,3], - [0,2], - [0,2] - ] + [2, 1], + [1, 3], + [2, 4], + [3, 4], + [0, 4], + [0, 3], + [0, 3], + [0, 3], + [0, 2], + [0, 2] +] if __name__ == '__main__': diff --git a/examples/python/nonogram_table2.py b/examples/python/nonogram_table2.py index 1db3495898..78eb641efa 100644 --- a/examples/python/nonogram_table2.py +++ b/examples/python/nonogram_table2.py @@ -49,7 +49,8 @@ to about 1 second' http://www.hakank.org/constraint_programming_blog/2009/03/comet_nonogram_improved_solvin_1.html - * 'Comet: regular constraint, a much faster Nonogram with the regular constraint, + * 'Comet: regular constraint, a much faster Nonogram with the regular + constraint, some OPL models, and more' http://www.hakank.org/constraint_programming_blog/2009/02/comet_regular_constraint_a_muc_1.html @@ -61,7 +62,8 @@ Note: nonogram_create_automaton2.mzn is the preferred model This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ @@ -83,12 +85,12 @@ def make_transition_tuples(pattern): # this is for handling 0-clues. It generates # just the minimal state if num_states == 0: - tuples.Insert3(1, 0, 1); + tuples.Insert3(1, 0, 1) return (tuples, 1) # convert pattern to a 0/1 pattern for easy handling of # the states - tmp = [0]; + tmp = [0] c = 0 for pattern_index in range(p_len): tmp.extend([1] * pattern[pattern_index]) @@ -153,7 +155,6 @@ def main(rows, row_rule_len, row_rules, cols, col_rule_len, col_rules): for i in range(rows): board_label.append(board[i, j]) - # # constraints # @@ -163,7 +164,6 @@ def main(rows, row_rule_len, row_rules, cols, col_rule_len, col_rules): for j in range(cols): check_rule(col_rules[j], [board[i, j] for i in range(rows)]) - # # solution and search # @@ -203,7 +203,6 @@ def main(rows, row_rule_len, row_rules, cols, col_rule_len, col_rules): print 'WallTime:', solver.WallTime(), 'ms' - # # Default problem # @@ -213,34 +212,34 @@ def main(rows, row_rule_len, row_rules, cols, col_rule_len, col_rules): rows = 12 row_rule_len = 3 row_rules = [ - [0,0,2], - [0,1,2], - [0,1,1], - [0,0,2], - [0,0,1], - [0,0,3], - [0,0,3], - [0,2,2], - [0,2,1], - [2,2,1], - [0,2,3], - [0,2,2] - ] + [0, 0, 2], + [0, 1, 2], + [0, 1, 1], + [0, 0, 2], + [0, 0, 1], + [0, 0, 3], + [0, 0, 3], + [0, 2, 2], + [0, 2, 1], + [2, 2, 1], + [0, 2, 3], + [0, 2, 2] +] cols = 10 col_rule_len = 2 col_rules = [ - [2,1], - [1,3], - [2,4], - [3,4], - [0,4], - [0,3], - [0,3], - [0,3], - [0,2], - [0,2] - ] + [2, 1], + [1, 3], + [2, 4], + [3, 4], + [0, 4], + [0, 3], + [0, 3], + [0, 3], + [0, 2], + [0, 2] +] if __name__ == '__main__': diff --git a/examples/python/nontransitive_dice.py b/examples/python/nontransitive_dice.py index d80dee380b..8400954152 100644 --- a/examples/python/nontransitive_dice.py +++ b/examples/python/nontransitive_dice.py @@ -64,144 +64,143 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ import sys import string from ortools.constraint_solver import pywrapcp + def main(m=3, n=6, minimize_val=0): - # Create the solver. - solver = pywrapcp.Solver('Nontransitive dice') + # Create the solver. + solver = pywrapcp.Solver("Nontransitive dice") - # - # data - # - print "number of dice:", m - print "number of sides:", n + # + # data + # + print "number of dice:", m + print "number of sides:", n - # - # declare variables - # + # + # declare variables + # - dice = {} + dice = {} + for i in range(m): + for j in range(n): + dice[(i, j)] = solver.IntVar(1, n * 2, "dice(%i,%i)" % (i, j)) + dice_flat = [dice[(i, j)] for i in range(m) for j in range(n)] + + comp = {} + for i in range(m): + for j in range(2): + comp[(i, j)] = solver.IntVar(0, n * n, "comp(%i,%i)" % (i, j)) + comp_flat = [comp[(i, j)] for i in range(m) for j in range(2)] + + # The following variables are for summaries or objectives + gap = [solver.IntVar(0, n * n, "gap(%i)" % i) for i in range(m)] + gap_sum = solver.IntVar(0, m * n * n, "gap_sum") + + max_val = solver.IntVar(0, n * 2, "max_val") + max_win = solver.IntVar(0, n * n, "max_win") + + # number of occurrences of each value of the dice + counts = [solver.IntVar(0, n * m, "counts(%i)" % i) for i in range(n * 2 + 1)] + + # + # constraints + # + + # number of occurrences for each number + solver.Add(solver.Distribute(dice_flat, range(n * 2 + 1), counts)) + + solver.Add(max_win == solver.Max(comp_flat)) + solver.Add(max_val == solver.Max(dice_flat)) + + # order of the number of each die, lowest first + [solver.Add(dice[(i, j)] <= dice[(i, j + 1)]) + for i in range(m) for j in range(n - 1)] + + # nontransitivity + [comp[i, 0] > comp[i, 1] for i in range(m)], + + # probability gap + [solver.Add(gap[i] == comp[i, 0] - comp[i, 1]) for i in range(m)] + [solver.Add(gap[i] > 0) for i in range(m)] + solver.Add(gap_sum == solver.Sum(gap)) + + # and now we roll... + # Number of wins for [A vs B, B vs A] + for d in range(m): + b1 = [solver.IsGreaterVar(dice[d % m, r1], dice[(d + 1) % m, r2]) + for r1 in range(n) for r2 in range(n)] + solver.Add(comp[d % m, 0] == solver.Sum(b1)) + + b2 = [solver.IsGreaterVar(dice[(d + 1) % m, r1], dice[d % m, r2]) + for r1 in range(n) for r2 in range(n)] + solver.Add(comp[d % m, 1] == solver.Sum(b2)) + + # objective + if minimize_val != 0: + print "Minimizing max_val" + objective = solver.Minimize(max_val, 1) + # other experiments + # objective = solver.Maximize(max_win, 1) + # objective = solver.Maximize(gap_sum, 1) + + # + # solution and search + # + db = solver.Phase(dice_flat + comp_flat, + solver.INT_VAR_DEFAULT, + solver.ASSIGN_MIN_VALUE) + + if minimize_val: + solver.NewSearch(db, [objective]) + else: + solver.NewSearch(db) + + num_solutions = 0 + while solver.NextSolution(): + print "gap_sum:", gap_sum.Value() + print "gap:", [gap[i].Value() for i in range(m)] + print "max_val:", max_val.Value() + print "max_win:", max_win.Value() + print "dice:" for i in range(m): - for j in range(n): - dice[(i,j)] = solver.IntVar(1, n*2, 'dice(%i,%i)' % (i, j)) - dice_flat = [dice[(i,j)] for i in range(m) for j in range(n)] - - comp = {} + for j in range(n): + print dice[(i, j)].Value(), + print + print "comp:" for i in range(m): - for j in range(2): - comp[(i,j)] = solver.IntVar(0, n*n, 'comp(%i,%i)' % (i, j)) - comp_flat = [comp[(i,j)] for i in range(m) for j in range(2)] - - - # The following variables are for summaries or objectives - gap = [solver.IntVar(0, n*n, "gap(%i)"%i) for i in range(m)] - gap_sum = solver.IntVar(0, m*n*n, "gap_sum") - - max_val = solver.IntVar(0, n*2, "max_val") - max_win = solver.IntVar(0, n*n, "max_win") - - # number of occurrences of each value of the dice - counts = [solver.IntVar(0,n*m,"counts(%i)" %i) for i in range(n*2+1)] - - # - # constraints - # - - # number of occurrences for each number - solver.Add(solver.Distribute(dice_flat, range(n*2+1), counts)) - - solver.Add(max_win == solver.Max(comp_flat)) - solver.Add(max_val == solver.Max(dice_flat)) - - # order of the number of each die, lowest first - [ solver.Add(dice[(i,j)] <= dice[(i,j+1)]) - for i in range(m) for j in range(n-1)] - - # nontransitivity - [ comp[i,0] > comp[i,1] for i in range(m)], - - # probability gap - [solver.Add(gap[i] == comp[i,0] - comp[i,1]) for i in range(m)] - [solver.Add(gap[i] > 0) for i in range(m)] - solver.Add(gap_sum == solver.Sum(gap)) - - # and now we roll... - # Number of wins for [A vs B, B vs A] - for d in range(m): - b1 = [solver.IsGreaterVar(dice[d % m, r1], dice[(d+1) % m, r2]) - for r1 in range(n) for r2 in range(n)] - solver.Add(comp[d%m,0] == solver.Sum(b1)) - - b2 = [solver.IsGreaterVar(dice[(d+1) % m, r1], dice[d % m, r2]) - for r1 in range(n) for r2 in range(n)] - solver.Add(comp[d%m,1] == solver.Sum(b2)) - - - # objective - if minimize_val != 0: - print "Minimizing max_val" - objective = solver.Minimize(max_val, 1) - # other experiments - # objective = solver.Maximize(max_win, 1) - # objective = solver.Maximize(gap_sum, 1) - - # - # solution and search - # - db = solver.Phase(dice_flat + comp_flat, - solver.INT_VAR_DEFAULT, - solver.ASSIGN_MIN_VALUE) - - if minimize_val: - solver.NewSearch(db, [objective]) - else: - solver.NewSearch(db) - - num_solutions = 0 - while solver.NextSolution(): - print "gap_sum:", gap_sum.Value() - print "gap:", [gap[i].Value() for i in range(m)] - print "max_val:", max_val.Value() - print "max_win:", max_win.Value() - print "dice:" - for i in range(m): - for j in range(n): - print dice[(i,j)].Value(), - print - print "comp:" - for i in range(m): - for j in range(2): - print comp[(i,j)].Value(), - print - print "counts:", [counts[i].Value() for i in range(n*2+1)] - print - - num_solutions += 1 - - solver.EndSearch() - + for j in range(2): + print comp[(i, j)].Value(), + print + print "counts:", [counts[i].Value() for i in range(n * 2 + 1)] print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + + num_solutions += 1 + + solver.EndSearch() + + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() m = 3 # number of dice n = 6 # number of sides of each die minimize_val = 0 # Minimizing max value (0: no, 1: yes) -if __name__ == '__main__': - if len(sys.argv) > 1: - m = string.atoi(sys.argv[1]) - if len(sys.argv) > 2: - n = string.atoi(sys.argv[2]) - if len(sys.argv) > 3: - minimize_val = string.atoi(sys.argv[3]) - - main(m, n, minimize_val) +if __name__ == "__main__": + if len(sys.argv) > 1: + m = string.atoi(sys.argv[1]) + if len(sys.argv) > 2: + n = string.atoi(sys.argv[2]) + if len(sys.argv) > 3: + minimize_val = string.atoi(sys.argv[3]) + main(m, n, minimize_val) diff --git a/examples/python/nqueens.py b/examples/python/nqueens.py index fe93a961a0..048ca73069 100644 --- a/examples/python/nqueens.py +++ b/examples/python/nqueens.py @@ -19,81 +19,80 @@ N queens problem. This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ from ortools.constraint_solver import pywrapcp def main(n=8): - # Create the solver. - solver = pywrapcp.Solver('n-queens') + # Create the solver. + solver = pywrapcp.Solver("n-queens") - # - # data - # - # n = 8 # size of board (n x n) + # + # data + # + # n = 8 # size of board (n x n) - # declare variables - q = [solver.IntVar(0,n-1, 'x%i' % i) for i in range(n)] + # declare variables + q = [solver.IntVar(0, n - 1, "x%i" % i) for i in range(n)] - # - # constraints - # - solver.Add(solver.AllDifferent(q)) - for i in range(n): - for j in range(i): - solver.Add(q[i] != q[j]) - solver.Add(q[i] + i != q[j] + j) - solver.Add(q[i] - i != q[j] - j) + # + # constraints + # + solver.Add(solver.AllDifferent(q)) + for i in range(n): + for j in range(i): + solver.Add(q[i] != q[j]) + solver.Add(q[i] + i != q[j] + j) + solver.Add(q[i] - i != q[j] - j) - # for i in range(n): - # for j in range(i): - # solver.Add(abs(q[i]-q[j]) != abs(i-j)) + # for i in range(n): + # for j in range(i): + # solver.Add(abs(q[i]-q[j]) != abs(i-j)) - # symmetry breaking - # solver.Add(q[0] == 0) + # symmetry breaking + # solver.Add(q[0] == 0) + # + # solution and search + # + solution = solver.Assignment() + solution.Add([q[i] for i in range(n)]) - # - # solution and search - # - solution = solver.Assignment() - solution.Add([q[i] for i in range(n)]) - - collector = solver.AllSolutionCollector(solution) - # collector = solver.FirstSolutionCollector(solution) - # search_log = solver.SearchLog(100, x[0]) - solver.Solve(solver.Phase([q[i] for i in range(n)], - solver.INT_VAR_SIMPLE, - solver.ASSIGN_MIN_VALUE), - [collector]) - - - num_solutions = collector.SolutionCount() - print "num_solutions: ", num_solutions - if num_solutions > 0: - for s in range(num_solutions): - qval = [collector.Value(s, q[i]) for i in range(n)] - print "q:", qval - for i in range(n): - for j in range(n): - if qval[i] == j: - print "Q", - else: - print "_", - print - print + collector = solver.AllSolutionCollector(solution) + # collector = solver.FirstSolutionCollector(solution) + # search_log = solver.SearchLog(100, x[0]) + solver.Solve(solver.Phase([q[i] for i in range(n)], + solver.INT_VAR_SIMPLE, + solver.ASSIGN_MIN_VALUE), + [collector]) + num_solutions = collector.SolutionCount() + print "num_solutions: ", num_solutions + if num_solutions > 0: + for s in range(num_solutions): + qval = [collector.Value(s, q[i]) for i in range(n)] + print "q:", qval + for i in range(n): + for j in range(n): + if qval[i] == j: + print "Q", + else: + print "_", print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + print - else: - print "No solutions found" + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() + + else: + print "No solutions found" n = 8 -if __name__ == '__main__': - main(n) +if __name__ == "__main__": + main(n) diff --git a/examples/python/nqueens2.py b/examples/python/nqueens2.py index fd9a665ee7..d1fb0995e8 100644 --- a/examples/python/nqueens2.py +++ b/examples/python/nqueens2.py @@ -22,80 +22,80 @@ the solutions. This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ -import sys, string +import sys +import string from ortools.constraint_solver import pywrapcp def main(n=8): - # Create the solver. - solver = pywrapcp.Solver('n-queens') + # Create the solver. + solver = pywrapcp.Solver("n-queens") - # - # data - # - # n = 8 # size of board (n x n) + # + # data + # + # n = 8 # size of board (n x n) - # declare variables - q = [solver.IntVar(0,n-1, 'x%i' % i) for i in range(n)] + # declare variables + q = [solver.IntVar(0, n - 1, "x%i" % i) for i in range(n)] - # - # constraints - # - solver.Add(solver.AllDifferent(q)) + # + # constraints + # + solver.Add(solver.AllDifferent(q)) + for i in range(n): + for j in range(i): + solver.Add(q[i] != q[j]) + solver.Add(q[i] + i != q[j] + j) + solver.Add(q[i] - i != q[j] - j) + + # for i in range(n): + # for j in range(i): + # solver.Add(abs(q[i]-q[j]) != abs(i-j)) + + # symmetry breaking + # solver.Add(q[0] == 0) + + # + # solution and search + # + solution = solver.Assignment() + solution.Add([q[i] for i in range(n)]) + + # db: DecisionBuilder + db = solver.Phase([q[i] for i in range(n)], + # solver.CHOOSE_FIRST_UNBOUND, + solver.CHOOSE_MIN_SIZE_LOWEST_MAX, + solver.ASSIGN_CENTER_VALUE) + + solver.NewSearch(db) + num_solutions = 0 + while solver.NextSolution(): + qval = [q[i].Value() for i in range(n)] + print "q:", qval for i in range(n): - for j in range(i): - solver.Add(q[i] != q[j]) - solver.Add(q[i] + i != q[j] + j) - solver.Add(q[i] - i != q[j] - j) - - # for i in range(n): - # for j in range(i): - # solver.Add(abs(q[i]-q[j]) != abs(i-j)) - - # symmetry breaking - # solver.Add(q[0] == 0) - - - # - # solution and search - # - solution = solver.Assignment() - solution.Add([q[i] for i in range(n)]) - - - # db: DecisionBuilder - db = solver.Phase([q[i] for i in range(n)], - # solver.CHOOSE_FIRST_UNBOUND, - solver.CHOOSE_MIN_SIZE_LOWEST_MAX, - solver.ASSIGN_CENTER_VALUE) - - solver.NewSearch(db) - num_solutions = 0 - while solver.NextSolution(): - qval = [q[i].Value() for i in range(n)] - print "q:", qval - for i in range(n): - for j in range(n): - if qval[i] == j: - print "Q", - else: - print "_", - print - print - num_solutions += 1 - solver.EndSearch() - + for j in range(n): + if qval[i] == j: + print "Q", + else: + print "_", + print print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + num_solutions += 1 + solver.EndSearch() + + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() n = 8 -if __name__ == '__main__': - if len(sys.argv) > 1: - n = string.atoi(sys.argv[1]) - main(n) +if __name__ == "__main__": + if len(sys.argv) > 1: + n = string.atoi(sys.argv[1]) + main(n) diff --git a/examples/python/nqueens3.py b/examples/python/nqueens3.py index ab5411f34e..41560a97d7 100644 --- a/examples/python/nqueens3.py +++ b/examples/python/nqueens3.py @@ -24,89 +24,88 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ -import sys, string +import sys +import string from ortools.constraint_solver import pywrapcp def main(n=8, num_sol=0, print_sol=1): - # Create the solver. - solver = pywrapcp.Solver('n-queens') + # Create the solver. + solver = pywrapcp.Solver("n-queens") - # - # data - # - print "n:", n - print "num_sol:", num_sol - print "print_sol:", print_sol + # + # data + # + print "n:", n + print "num_sol:", num_sol + print "print_sol:", print_sol - # declare variables - q = [solver.IntVar(0,n-1, 'x%i' % i) for i in range(n)] + # declare variables + q = [solver.IntVar(0, n - 1, "x%i" % i) for i in range(n)] - # - # constraints - # - solver.Add(solver.AllDifferent(q)) - solver.Add(solver.AllDifferent([q[i]+i for i in range(n)])) - solver.Add(solver.AllDifferent([q[i]-i for i in range(n)])) + # + # constraints + # + solver.Add(solver.AllDifferent(q)) + solver.Add(solver.AllDifferent([q[i] + i for i in range(n)])) + solver.Add(solver.AllDifferent([q[i] - i for i in range(n)])) + # symmetry breaking + # solver.Add(q[0] == 0) - # symmetry breaking - # solver.Add(q[0] == 0) + # + # search + # + db = solver.Phase(q, + solver.CHOOSE_MIN_SIZE_LOWEST_MAX, + solver.ASSIGN_CENTER_VALUE) - # - # search - # + solver.NewSearch(db) + num_solutions = 0 + while solver.NextSolution(): + if print_sol: + qval = [q[i].Value() for i in range(n)] + print "q:", qval + for i in range(n): + for j in range(n): + if qval[i] == j: + print "Q", + else: + print "_", + print + print + num_solutions += 1 + if num_sol > 0 and num_solutions >= num_sol: + break - db = solver.Phase(q, - solver.CHOOSE_MIN_SIZE_LOWEST_MAX, - solver.ASSIGN_CENTER_VALUE) + solver.EndSearch() - solver.NewSearch(db) - num_solutions = 0 - while solver.NextSolution(): - if print_sol: - qval = [q[i].Value() for i in range(n)] - print "q:", qval - for i in range(n): - for j in range(n): - if qval[i] == j: - print "Q", - else: - print "_", - print - print - num_solutions += 1 - if num_sol > 0 and num_solutions >= num_sol: - break - - solver.EndSearch() - - print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime(), "ms" + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime(), "ms" n = 8 num_sol = 0 print_sol = 1 -if __name__ == '__main__': - if len(sys.argv) > 1: - n = int(sys.argv[1]) - if len(sys.argv) > 2: - num_sol = int(sys.argv[2]) - if len(sys.argv) > 3: - print_sol = int(sys.argv[3]) +if __name__ == "__main__": + if len(sys.argv) > 1: + n = int(sys.argv[1]) + if len(sys.argv) > 2: + num_sol = int(sys.argv[2]) + if len(sys.argv) > 3: + print_sol = int(sys.argv[3]) + main(n, num_sol, print_sol) - main(n, num_sol, print_sol) - - # print_sol = False - # show_all = False - # for n in range(1000,1001): - # print - # main(n, num_sol, print_sol) + # print_sol = False + # show_all = False + # for n in range(1000,1001): + # print + # main(n, num_sol, print_sol) diff --git a/examples/python/nurse_rostering.py b/examples/python/nurse_rostering.py index 477e029783..6a088779cb 100644 --- a/examples/python/nurse_rostering.py +++ b/examples/python/nurse_rostering.py @@ -25,7 +25,8 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ @@ -52,217 +53,214 @@ from collections import defaultdict # d : transition matrix # q0: initial state # F : accepting states + + def regular(x, Q, S, d, q0, F): - solver = x[0].solver() + solver = x[0].solver() - assert Q > 0, 'regular: "Q" must be greater than zero' - assert S > 0, 'regular: "S" must be greater than zero' + assert Q > 0, 'regular: "Q" must be greater than zero' + assert S > 0, 'regular: "S" must be greater than zero' - # d2 is the same as d, except we add one extra transition for - # each possible input; each extra transition is from state zero - # to state zero. This allows us to continue even if we hit a - # non-accepted input. + # d2 is the same as d, except we add one extra transition for + # each possible input; each extra transition is from state zero + # to state zero. This allows us to continue even if we hit a + # non-accepted input. - # Comet: int d2[0..Q, 1..S] - d2 = [] - for i in range(Q+1): - row = [] - for j in range(S): - if i == 0: - row.append(0) - else: - row.append(d[i-1][j]) - d2.append(row) + # Comet: int d2[0..Q, 1..S] + d2 = [] + for i in range(Q + 1): + row = [] + for j in range(S): + if i == 0: + row.append(0) + else: + row.append(d[i - 1][j]) + d2.append(row) - d2_flatten = [d2[i][j] for i in range(Q+1) for j in range(S)] + d2_flatten = [d2[i][j] for i in range(Q + 1) for j in range(S)] - # If x has index set m..n, then a[m-1] holds the initial state - # (q0), and a[i+1] holds the state we're in after processing - # x[i]. If a[n] is in F, then we succeed (ie. accept the - # string). - x_range = range(0,len(x)) - m = 0 - n = len(x) + # If x has index set m..n, then a[m-1] holds the initial state + # (q0), and a[i+1] holds the state we're in after processing + # x[i]. If a[n] is in F, then we succeed (ie. accept the + # string). + x_range = range(0, len(x)) + m = 0 + n = len(x) - a = [solver.IntVar(0, Q+1, 'a[%i]' % i) for i in range(m, n+1)] - - # Check that the final state is in F - solver.Add(solver.MemberCt(a[-1], F)) - # First state is q0 - solver.Add(a[m] == q0) - for i in x_range: - solver.Add(x[i] >= 1) - solver.Add(x[i] <= S) - - # Determine a[i+1]: a[i+1] == d2[a[i], x[i]] - solver.Add(a[i+1] == solver.Element(d2_flatten, ((a[i])*S)+(x[i]-1))) + a = [solver.IntVar(0, Q + 1, 'a[%i]' % i) for i in range(m, n + 1)] + # Check that the final state is in F + solver.Add(solver.MemberCt(a[-1], F)) + # First state is q0 + solver.Add(a[m] == q0) + for i in x_range: + solver.Add(x[i] >= 1) + solver.Add(x[i] <= S) + # Determine a[i+1]: a[i+1] == d2[a[i], x[i]] + solver.Add( + a[i + 1] == solver.Element(d2_flatten, ((a[i]) * S) + (x[i] - 1))) def main(): - # Create the solver. - solver = pywrapcp.Solver('Nurse rostering using regular') + # Create the solver. + solver = pywrapcp.Solver('Nurse rostering using regular') - # - # data - # + # + # data + # - # Note: If you change num_nurses or num_days, - # please also change the constraints - # on nurse_stat and/or day_stat. - num_nurses = 7 - num_days = 14 + # Note: If you change num_nurses or num_days, + # please also change the constraints + # on nurse_stat and/or day_stat. + num_nurses = 7 + num_days = 14 - day_shift = 1 - night_shift = 2 - off_shift = 3 - shifts = [day_shift, night_shift, off_shift] + day_shift = 1 + night_shift = 2 + off_shift = 3 + shifts = [day_shift, night_shift, off_shift] - # the DFA (for regular) - n_states = 6 - input_max = 3 - initial_state = 1 # 0 is for the failing state - accepting_states = [1,2,3,4,5,6] + # the DFA (for regular) + n_states = 6 + input_max = 3 + initial_state = 1 # 0 is for the failing state + accepting_states = [1, 2, 3, 4, 5, 6] - transition_fn = [ - # d,n,o - [2,3,1], # state 1 - [4,4,1], # state 2 - [4,5,1], # state 3 - [6,6,1], # state 4 - [6,0,1], # state 5 - [0,0,1] # state 6 - ] + transition_fn = [ + # d,n,o + [2, 3, 1], # state 1 + [4, 4, 1], # state 2 + [4, 5, 1], # state 3 + [6, 6, 1], # state 4 + [6, 0, 1], # state 5 + [0, 0, 1] # state 6 + ] - days = ['d','n','o'] # for presentation + days = ['d', 'n', 'o'] # for presentation - # - # declare variables - # - x = {} - for i in range(num_nurses): - for j in range(num_days): - x[i,j] = solver.IntVar(shifts, 'x[%i,%i]'% (i,j)) - - x_flat = [x[i,j] for i in range(num_nurses) for j in range(num_days)] - - # summary of the nurses - nurse_stat = [solver.IntVar(0, num_days, 'nurse_stat[%i]'%i) - for i in range(num_nurses)] - - # summary of the shifts per day - day_stat = {} - for i in range(num_days): - for j in shifts: - day_stat[i,j] = solver.IntVar(0, num_nurses, 'day_stat[%i,%i]'% (i,j)) - - day_stat_flat = [day_stat[i,j] for i in range(num_days) for j in shifts] - - - # - # constraints - # - for i in range(num_nurses): - reg_input = [x[i,j] for j in range(num_days)] - regular(reg_input, n_states, input_max, transition_fn, - initial_state, accepting_states) - - # - # Statistics and constraints for each nurse - # - for i in range(num_nurses): - # number of worked days (day or night shift) - b = [solver.IsEqualCstVar(x[i,j], day_shift) + - solver.IsEqualCstVar(x[i,j], night_shift) - for j in range(num_days)] - solver.Add(nurse_stat[i] == solver.Sum(b)) - - # Each nurse must work between 7 and 10 - # days during this period - solver.Add(nurse_stat[i] >= 7) - solver.Add(nurse_stat[i] <= 10) - - - # - # Statistics and constraints for each day - # + # + # declare variables + # + x = {} + for i in range(num_nurses): for j in range(num_days): - for t in shifts: - b = [solver.IsEqualCstVar(x[i,j], t) - for i in range(num_nurses)] - solver.Add(day_stat[j,t] == solver.Sum(b)) + x[i, j] = solver.IntVar(shifts, 'x[%i,%i]' % (i, j)) - # - # Some constraints for this day: - # - # Note: We have a strict requirements of - # the number of shifts. - # Using atleast constraints is much harder - # in this model. - # - if j % 7 == 5 or j % 7 == 6: - # special constraints for the weekends - solver.Add(day_stat[j,day_shift] == 2) - solver.Add(day_stat[j,night_shift] == 1) - solver.Add(day_stat[j,off_shift] == 4 ) - else: - # workdays: + x_flat = [x[i, j] for i in range(num_nurses) for j in range(num_days)] - # - exactly 3 on day shift - solver.Add(day_stat[j,day_shift] == 3) - # - exactly 2 on night - solver.Add(day_stat[j,night_shift] == 2) - # - exactly 1 off duty - solver.Add(day_stat[j,off_shift] == 2 ) + # summary of the nurses + nurse_stat = [solver.IntVar(0, num_days, 'nurse_stat[%i]' % i) + for i in range(num_nurses)] + # summary of the shifts per day + day_stat = {} + for i in range(num_days): + for j in shifts: + day_stat[i, j] = solver.IntVar(0, num_nurses, 'day_stat[%i,%i]' % (i, j)) + + day_stat_flat = [day_stat[i, j] for i in range(num_days) for j in shifts] + + # + # constraints + # + for i in range(num_nurses): + reg_input = [x[i, j] for j in range(num_days)] + regular(reg_input, n_states, input_max, transition_fn, + initial_state, accepting_states) + + # + # Statistics and constraints for each nurse + # + for i in range(num_nurses): + # number of worked days (day or night shift) + b = [solver.IsEqualCstVar(x[i, j], day_shift) + + solver.IsEqualCstVar(x[i, j], night_shift) + for j in range(num_days)] + solver.Add(nurse_stat[i] == solver.Sum(b)) + + # Each nurse must work between 7 and 10 + # days during this period + solver.Add(nurse_stat[i] >= 7) + solver.Add(nurse_stat[i] <= 10) + + # + # Statistics and constraints for each day + # + for j in range(num_days): + for t in shifts: + b = [solver.IsEqualCstVar(x[i, j], t) + for i in range(num_nurses)] + solver.Add(day_stat[j, t] == solver.Sum(b)) # - # solution and search + # Some constraints for this day: # - db = solver.Phase(day_stat_flat + x_flat + nurse_stat, - solver.CHOOSE_FIRST_UNBOUND, - solver.ASSIGN_MIN_VALUE) + # Note: We have a strict requirements of + # the number of shifts. + # Using atleast constraints is much harder + # in this model. + # + if j % 7 == 5 or j % 7 == 6: + # special constraints for the weekends + solver.Add(day_stat[j, day_shift] == 2) + solver.Add(day_stat[j, night_shift] == 1) + solver.Add(day_stat[j, off_shift] == 4) + else: + # workdays: - solver.NewSearch(db) + # - exactly 3 on day shift + solver.Add(day_stat[j, day_shift] == 3) + # - exactly 2 on night + solver.Add(day_stat[j, night_shift] == 2) + # - exactly 1 off duty + solver.Add(day_stat[j, off_shift] == 2) - num_solutions = 0 - while solver.NextSolution(): - num_solutions += 1 + # + # solution and search + # + db = solver.Phase(day_stat_flat + x_flat + nurse_stat, + solver.CHOOSE_FIRST_UNBOUND, + solver.ASSIGN_MIN_VALUE) - for i in range(num_nurses): - print 'Nurse%i: ' % i, - this_day_stat = defaultdict(int) - for j in range(num_days): - d = days[x[i,j].Value()-1] - this_day_stat[d] += 1 - print d, - print ' day_stat:', [(d, this_day_stat[d]) for d in this_day_stat], - print 'total:', nurse_stat[i].Value(), 'workdays' - print + solver.NewSearch(db) - print 'Statistics per day:' - for j in range(num_days): - print 'Day%2i: ' % j, - for t in shifts: - print day_stat[j,t].Value(), - print - print + num_solutions = 0 + while solver.NextSolution(): + num_solutions += 1 - # We just show 2 solutions - if num_solutions >= 2: - break - - - solver.EndSearch() + for i in range(num_nurses): + print 'Nurse%i: ' % i, + this_day_stat = defaultdict(int) + for j in range(num_days): + d = days[x[i, j].Value() - 1] + this_day_stat[d] += 1 + print d, + print ' day_stat:', [(d, this_day_stat[d]) for d in this_day_stat], + print 'total:', nurse_stat[i].Value(), 'workdays' print - print 'num_solutions:', num_solutions - print 'failures:', solver.Failures() - print 'branches:', solver.Branches() - print 'WallTime:', solver.WallTime(), 'ms' + + print 'Statistics per day:' + for j in range(num_days): + print 'Day%2i: ' % j, + for t in shifts: + print day_stat[j, t].Value(), + print + print + + # We just show 2 solutions + if num_solutions >= 2: + break + + solver.EndSearch() + print + print 'num_solutions:', num_solutions + print 'failures:', solver.Failures() + print 'branches:', solver.Branches() + print 'WallTime:', solver.WallTime(), 'ms' if __name__ == '__main__': - main() + main() diff --git a/examples/python/olympic.py b/examples/python/olympic.py index f54decebcf..4a28b3e464 100644 --- a/examples/python/olympic.py +++ b/examples/python/olympic.py @@ -53,64 +53,67 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ import sys from ortools.constraint_solver import pywrapcp + def minus(solver, x, y, z): - solver.Add(z == abs(x - y)) + solver.Add(z == abs(x - y)) + def main(): - # Create the solver. - solver = pywrapcp.Solver('Olympic') + # Create the solver. + solver = pywrapcp.Solver('Olympic') - # - # data - # - n = 10 + # + # data + # + n = 10 - # - # declare variables - # - Vars = [solver.IntVar(1, n, 'Vars[%i]' % i) for i in range(n)] - X1,X2,X3,X4,X5,X6,X7,X8,X9,X10 = Vars + # + # declare variables + # + Vars = [solver.IntVar(1, n, 'Vars[%i]' % i) for i in range(n)] + X1, X2, X3, X4, X5, X6, X7, X8, X9, X10 = Vars - # - # constraints - # - solver.Add(solver.AllDifferent(Vars)) + # + # constraints + # + solver.Add(solver.AllDifferent(Vars)) - solver.Add(X1 == 3) - minus(solver, X2, X3, X1) - minus(solver, X4, X5, X2) - minus(solver, X5, X6, X3) - minus(solver, X7, X8, X4) - minus(solver, X8, X9, X5) - minus(solver, X9, X10, X6) + solver.Add(X1 == 3) + minus(solver, X2, X3, X1) + minus(solver, X4, X5, X2) + minus(solver, X5, X6, X3) + minus(solver, X7, X8, X4) + minus(solver, X8, X9, X5) + minus(solver, X9, X10, X6) - # - # solution and search - # - db = solver.Phase(Vars, - solver.INT_VAR_SIMPLE, - solver.INT_VALUE_DEFAULT) + # + # solution and search + # + db = solver.Phase(Vars, + solver.INT_VAR_SIMPLE, + solver.INT_VALUE_DEFAULT) - solver.NewSearch(db) + solver.NewSearch(db) - num_solutions = 0 - while solver.NextSolution(): - num_solutions += 1 - print 'Vars:', [Vars[i].Value() for i in range(n)] + num_solutions = 0 + while solver.NextSolution(): + num_solutions += 1 + print 'Vars:', [Vars[i].Value() for i in range(n)] - print - print 'num_solutions:', num_solutions - print 'failures:', solver.Failures() - print 'branches:', solver.Branches() - print 'WallTime:', solver.WallTime(), 'ms' + print + print 'num_solutions:', num_solutions + print 'failures:', solver.Failures() + print 'branches:', solver.Branches() + print 'WallTime:', solver.WallTime(), 'ms' if __name__ == '__main__': - main() + main() diff --git a/examples/python/organize_day.py b/examples/python/organize_day.py index e716256801..48f11715d1 100644 --- a/examples/python/organize_day.py +++ b/examples/python/organize_day.py @@ -29,7 +29,8 @@ * Gecode: http://hakank.org/gecode/organize_day.cpp This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ import sys @@ -38,83 +39,84 @@ from ortools.constraint_solver import pywrapcp # # No overlapping of tasks s1 and s2 # + + def no_overlap(solver, s1, d1, s2, d2): - b1 = solver.IsLessOrEqualVar(s1 + d1, s2) # s1 + d1 <= s2 - b2 = solver.IsLessOrEqualVar(s2 + d2, s1) # s2 + d2 <= s1 - solver.Add(b1 + b2 >= 1) + b1 = solver.IsLessOrEqualVar(s1 + d1, s2) # s1 + d1 <= s2 + b2 = solver.IsLessOrEqualVar(s2 + d2, s1) # s2 + d2 <= s1 + solver.Add(b1 + b2 >= 1) def main(): - # Create the solver. - solver = pywrapcp.Solver('Organizing a day') + # Create the solver. + solver = pywrapcp.Solver('Organizing a day') - # - # data - # - n = 4 + # + # data + # + n = 4 - tasks = range(n) - work, mail, shop, bank = tasks - durations = [4,1,2,1] + tasks = range(n) + work, mail, shop, bank = tasks + durations = [4, 1, 2, 1] - # task [i,0] must be finished before task [i,1] - before_tasks = [ - [bank, shop], - [mail, work] - ] + # task [i,0] must be finished before task [i,1] + before_tasks = [ + [bank, shop], + [mail, work] + ] - # the valid times of the day - begin = 9 - end = 17 + # the valid times of the day + begin = 9 + end = 17 - # - # declare variables - # - begins = [solver.IntVar(begin, end, 'begins[%i]% % i') for i in tasks] - ends = [solver.IntVar(begin, end, 'ends[%i]% % i') for i in tasks] + # + # declare variables + # + begins = [solver.IntVar(begin, end, 'begins[%i]% % i') for i in tasks] + ends = [solver.IntVar(begin, end, 'ends[%i]% % i') for i in tasks] - # - # constraints - # - for i in tasks: - solver.Add(ends[i] == begins[i] + durations[i]) + # + # constraints + # + for i in tasks: + solver.Add(ends[i] == begins[i] + durations[i]) - for i in tasks: - for j in tasks: - if i < j: - no_overlap(solver, - begins[i], durations[i], - begins[j], durations[j]) + for i in tasks: + for j in tasks: + if i < j: + no_overlap(solver, + begins[i], durations[i], + begins[j], durations[j]) - # specific constraints - for (before, after) in before_tasks: - solver.Add(ends[before] <= begins[after]) + # specific constraints + for (before, after) in before_tasks: + solver.Add(ends[before] <= begins[after]) - solver.Add(begins[work] >= 11) + solver.Add(begins[work] >= 11) + # + # solution and search + # + db = solver.Phase(begins + ends, + solver.INT_VAR_DEFAULT, + solver.INT_VALUE_DEFAULT) - # - # solution and search - # - db = solver.Phase(begins + ends, - solver.INT_VAR_DEFAULT, - solver.INT_VALUE_DEFAULT) + solver.NewSearch(db) - solver.NewSearch(db) + num_solutions = 0 + while solver.NextSolution(): + num_solutions += 1 + print 'begins:', [begins[i].Value() for i in tasks] + print 'ends:', [ends[i].Value() for i in tasks] + print - num_solutions = 0 - while solver.NextSolution(): - num_solutions += 1 - print 'begins:', [begins[i].Value() for i in tasks] - print 'ends:', [ends[i].Value() for i in tasks] - print - - print 'num_solutions:', num_solutions - print 'failures:', solver.Failures() - print 'branches:', solver.Branches() - print 'WallTime:', solver.WallTime(), 'ms' + print 'num_solutions:', num_solutions + print 'failures:', solver.Failures() + print 'branches:', solver.Branches() + print 'WallTime:', solver.WallTime(), 'ms' if __name__ == '__main__': - main() + main() diff --git a/examples/python/p_median.py b/examples/python/p_median.py index 11eb81b22a..7e5988da90 100644 --- a/examples/python/p_median.py +++ b/examples/python/p_median.py @@ -31,7 +31,8 @@ * Comet: http://hakank.org/comet/p_median.co This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ import sys @@ -40,91 +41,91 @@ from ortools.constraint_solver import pywrapcp def main(): - # Create the solver. - solver = pywrapcp.Solver('P-median problem') + # Create the solver. + solver = pywrapcp.Solver('P-median problem') - # - # data - # - p = 2 + # + # data + # + p = 2 - num_customers = 4 - customers = range(num_customers) - Albert, Bob, Chris, Daniel = customers - num_warehouses = 3 - warehouses = range(num_warehouses) - Santa_Clara, San_Jose, Berkeley = warehouses + num_customers = 4 + customers = range(num_customers) + Albert, Bob, Chris, Daniel = customers + num_warehouses = 3 + warehouses = range(num_warehouses) + Santa_Clara, San_Jose, Berkeley = warehouses - demand = [100,80,80,70] - distance = [ - [ 2, 10, 50], - [ 2, 10, 52], - [50, 60, 3], - [40, 60, 1] - ] + demand = [100, 80, 80, 70] + distance = [ + [2, 10, 50], + [2, 10, 52], + [50, 60, 3], + [40, 60, 1] + ] - # - # declare variables - # - open = [solver.IntVar(warehouses, 'open[%i]% % i') - for w in warehouses] - ship = {} + # + # declare variables + # + open = [solver.IntVar(warehouses, 'open[%i]% % i') + for w in warehouses] + ship = {} + for c in customers: + for w in warehouses: + ship[c, w] = solver.IntVar(0, 1, 'ship[%i,%i]' % (c, w)) + ship_flat = [ship[c, w] + for c in customers + for w in warehouses] + + z = solver.IntVar(0, 1000, 'z') + + # + # constraints + # + z_sum = solver.Sum([demand[c] * distance[c][w] * ship[c, w] + for c in customers + for w in warehouses]) + solver.Add(z == z_sum) + + for c in customers: + s = solver.Sum([ship[c, w] + for w in warehouses]) + solver.Add(s == 1) + + solver.Add(solver.Sum(open) == p) + + for c in customers: + for w in warehouses: + solver.Add(ship[c, w] <= open[w]) + + # objective + objective = solver.Minimize(z, 1) + + # + # solution and search + # + db = solver.Phase(open + ship_flat, + solver.INT_VAR_DEFAULT, + solver.INT_VALUE_DEFAULT) + + solver.NewSearch(db, [objective]) + + num_solutions = 0 + while solver.NextSolution(): + num_solutions += 1 + print 'z:', z.Value() + print 'open:', [open[w].Value() for w in warehouses] for c in customers: - for w in warehouses: - ship[c,w] = solver.IntVar(0, 1,'ship[%i,%i]' % (c,w)) - ship_flat = [ship[c,w] - for c in customers - for w in warehouses] + for w in warehouses: + print ship[c, w].Value(), + print + print - z = solver.IntVar(0, 1000, 'z') - - # - # constraints - # - z_sum = solver.Sum([demand[c]*distance[c][w]*ship[c,w] - for c in customers - for w in warehouses]) - solver.Add(z == z_sum) - - for c in customers: - s = solver.Sum([ship[c,w] - for w in warehouses]) - solver.Add(s == 1) - - solver.Add(solver.Sum(open) == p) - - for c in customers: - for w in warehouses: - solver.Add(ship[c,w] <= open[w]) - - # objective - objective = solver.Minimize(z, 1) - - # - # solution and search - # - db = solver.Phase(open + ship_flat, - solver.INT_VAR_DEFAULT, - solver.INT_VALUE_DEFAULT) - - solver.NewSearch(db, [objective]) - - num_solutions = 0 - while solver.NextSolution(): - num_solutions += 1 - print "z:", z.Value() - print 'open:', [open[w].Value() for w in warehouses] - for c in customers: - for w in warehouses: - print ship[c,w].Value(), - print - print - - print 'num_solutions:', num_solutions - print 'failures:', solver.Failures() - print 'branches:', solver.Branches() - print 'WallTime:', solver.WallTime(), 'ms' + print 'num_solutions:', num_solutions + print 'failures:', solver.Failures() + print 'branches:', solver.Branches() + print 'WallTime:', solver.WallTime(), 'ms' if __name__ == '__main__': - main() + main() diff --git a/examples/python/pandigital_numbers.py b/examples/python/pandigital_numbers.py index 0c29d46e84..73559e0459 100644 --- a/examples/python/pandigital_numbers.py +++ b/examples/python/pandigital_numbers.py @@ -57,110 +57,114 @@ * SICStus : http://hakank.org/sicstus/pandigital_numbers.pl This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ -import string, sys +import string +import sys from ortools.constraint_solver import pywrapcp # # converts a number (s) <-> an array of integers (t) in the specific base. # + + def toNum(solver, t, s, base): - tlen = len(t) - solver.Add(s == solver.Sum([(base**(tlen-i-1))*t[i] for i in range(tlen)])) + tlen = len(t) + solver.Add( + s == solver.Sum([(base ** (tlen - i - 1)) * t[i] for i in range(tlen)])) def main(base=10, start=1, len1=1, len2=4): - # Create the solver. - solver = pywrapcp.Solver('Pandigital numbers') + # Create the solver. + solver = pywrapcp.Solver("Pandigital numbers") - # - # data - # - max_d = base-1 - x_len = max_d + 1 - start - max_num = base**4-1 + # + # data + # + max_d = base - 1 + x_len = max_d + 1 - start + max_num = base ** 4 - 1 - # - # declare variables - # - num1 = solver.IntVar(0, max_num, 'num1') - num2 = solver.IntVar(0, max_num, 'num2') - res = solver.IntVar(0, max_num, 'res') + # + # declare variables + # + num1 = solver.IntVar(0, max_num, "num1") + num2 = solver.IntVar(0, max_num, "num2") + res = solver.IntVar(0, max_num, "res") - x = [solver.IntVar(start, max_d, 'x[%i]' % i) for i in range(x_len)] + x = [solver.IntVar(start, max_d, "x[%i]" % i) for i in range(x_len)] - # - # constraints - # - solver.Add(solver.AllDifferent(x)) + # + # constraints + # + solver.Add(solver.AllDifferent(x)) - toNum(solver, [x[i] for i in range(len1)], num1, base) - toNum(solver, [x[i] for i in range(len1,len1+len2)], num2, base) - toNum(solver, [x[i] for i in range(len1+len2,x_len)], res, base) + toNum(solver, [x[i] for i in range(len1)], num1, base) + toNum(solver, [x[i] for i in range(len1, len1 + len2)], num2, base) + toNum(solver, [x[i] for i in range(len1 + len2, x_len)], res, base) - solver.Add(num1*num2 == res) + solver.Add(num1 * num2 == res) - # no number must start with 0 - solver.Add(x[0] > 0) - solver.Add(x[len1] > 0) - solver.Add(x[len1+len2] > 0) + # no number must start with 0 + solver.Add(x[0] > 0) + solver.Add(x[len1] > 0) + solver.Add(x[len1 + len2] > 0) - # symmetry breaking - solver.Add(num1 < num2) + # symmetry breaking + solver.Add(num1 < num2) - # - # solution and search - # - solution = solver.Assignment() - solution.Add(x) - solution.Add(num1) - solution.Add(num2) - solution.Add(res) + # + # solution and search + # + solution = solver.Assignment() + solution.Add(x) + solution.Add(num1) + solution.Add(num2) + solution.Add(res) - db = solver.Phase(x, - solver.INT_VAR_SIMPLE, - solver.INT_VALUE_DEFAULT) + db = solver.Phase(x, + solver.INT_VAR_SIMPLE, + solver.INT_VALUE_DEFAULT) - solver.NewSearch(db) - num_solutions = 0 - solutions = [] - while solver.NextSolution(): - print_solution([x[i].Value() for i in range(x_len)], len1, len2, x_len) - num_solutions += 1 + solver.NewSearch(db) + num_solutions = 0 + solutions = [] + while solver.NextSolution(): + print_solution([x[i].Value() for i in range(x_len)], len1, len2, x_len) + num_solutions += 1 - solver.EndSearch() + solver.EndSearch() - if 0 and num_solutions > 0: - print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() - print + if 0 and num_solutions > 0: + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() + print - -def print_solution(x,len1,len2,x_len): - print "".join([str(x[i]) for i in range(len1)]), "*", - print "".join([str(x[i]) for i in range(len1,len1+len2)]), "=", - print "".join([str(x[i]) for i in range(len1+len2,x_len)]) +def print_solution(x, len1, len2, x_len): + print "".join([str(x[i]) for i in range(len1)]), "*", + print "".join([str(x[i]) for i in range(len1, len1 + len2)]), "=", + print "".join([str(x[i]) for i in range(len1 + len2, x_len)]) base = 10 start = 1 -if __name__ == '__main__': - if len(sys.argv) > 1: - base = string.atoi(sys.argv[1]) - if len(sys.argv) > 2: - start = string.atoi(sys.argv[2]) +if __name__ == "__main__": + if len(sys.argv) > 1: + base = string.atoi(sys.argv[1]) + if len(sys.argv) > 2: + start = string.atoi(sys.argv[2]) - x_len = base-1 + 1-start - for len1 in range(1+(x_len)): - for len2 in range(1+(x_len)): - if x_len > len1 + len2: - main(base, start, len1, len2) + x_len = base - 1 + 1 - start + for len1 in range(1 + (x_len)): + for len2 in range(1 + (x_len)): + if x_len > len1 + len2: + main(base, start, len1, len2) diff --git a/examples/python/photo_problem.py b/examples/python/photo_problem.py index 8c20598c72..dc4ae463d4 100644 --- a/examples/python/photo_problem.py +++ b/examples/python/photo_problem.py @@ -43,7 +43,8 @@ * SICStus: http://hakank.org/sicstus/photo_problem.pl This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ import sys @@ -54,101 +55,100 @@ from ortools.constraint_solver import pywrapcp def main(show_all_max=0): - # Create the solver. - solver = pywrapcp.Solver('Photo problem') + # Create the solver. + solver = pywrapcp.Solver("Photo problem") - # - # data - # - persons = ["Betty", "Chris", "Donald", "Fred", "Gary", "Mary", "Paul"] - n = len(persons) - preferences = [ - # 0 1 2 3 4 5 6 - # B C D F G M P - [ 0,0,0,0,1,1,0], # Betty 0 - [ 1,0,0,0,1,0,0], # Chris 1 - [ 0,0,0,0,0,0,0], # Donald 2 - [ 0,0,1,0,0,1,0], # Fred 3 - [ 0,0,0,0,0,0,0], # Gary 4 - [ 0,0,0,0,0,0,0], # Mary 5 - [ 0,0,1,1,0,0,0] # Paul 6 - ] + # + # data + # + persons = ["Betty", "Chris", "Donald", "Fred", "Gary", "Mary", "Paul"] + n = len(persons) + preferences = [ + # 0 1 2 3 4 5 6 + # B C D F G M P + [0, 0, 0, 0, 1, 1, 0], # Betty 0 + [1, 0, 0, 0, 1, 0, 0], # Chris 1 + [0, 0, 0, 0, 0, 0, 0], # Donald 2 + [0, 0, 1, 0, 0, 1, 0], # Fred 3 + [0, 0, 0, 0, 0, 0, 0], # Gary 4 + [0, 0, 0, 0, 0, 0, 0], # Mary 5 + [0, 0, 1, 1, 0, 0, 0] # Paul 6 + ] - print """Preferences: + print """Preferences: 1. Betty wants to stand next to Gary and Mary. 2. Chris wants to stand next to Betty and Gary. 3. Fred wants to stand next to Mary and Donald. 4. Paul wants to stand next to Fred and Donald. """ - # - # declare variables - # - positions = [solver.IntVar(0, n-1, "positions[%i]" % i) for i in range(n)] + # + # declare variables + # + positions = [solver.IntVar(0, n - 1, "positions[%i]" % i) for i in range(n)] - # successful preferences - z = solver.IntVar(0, n*n, 'z') + # successful preferences + z = solver.IntVar(0, n * n, "z") - # - # constraints - # - solver.Add(solver.AllDifferent(positions)) + # + # constraints + # + solver.Add(solver.AllDifferent(positions)) - # calculate all the successful preferences - b = [solver.IsEqualCstVar(abs(positions[i]-positions[j]),1) - for i in range(n) for j in range(n) if preferences[i][j] == 1] - solver.Add(z == solver.Sum(b)) + # calculate all the successful preferences + b = [solver.IsEqualCstVar(abs(positions[i] - positions[j]), 1) + for i in range(n) for j in range(n) if preferences[i][j] == 1] + solver.Add(z == solver.Sum(b)) - # - # Symmetry breaking (from the Oz page): - # Fred is somewhere left of Betty - solver.Add(positions[3] < positions[0]) + # + # Symmetry breaking (from the Oz page): + # Fred is somewhere left of Betty + solver.Add(positions[3] < positions[0]) - # objective - objective = solver.Maximize(z, 1) - if show_all_max != 0: - print "Showing all maximum solutions (z == 6).\n" - solver.Add(z == 6) + # objective + objective = solver.Maximize(z, 1) + if show_all_max != 0: + print "Showing all maximum solutions (z == 6).\n" + solver.Add(z == 6) - # - # search and result - # - db = solver.Phase(positions, - solver.CHOOSE_FIRST_UNBOUND, - solver.ASSIGN_MAX_VALUE) + # + # search and result + # + db = solver.Phase(positions, + solver.CHOOSE_FIRST_UNBOUND, + solver.ASSIGN_MAX_VALUE) - if show_all_max == 0: - solver.NewSearch(db, [objective]) - else: - solver.NewSearch(db) + if show_all_max == 0: + solver.NewSearch(db, [objective]) + else: + solver.NewSearch(db) + num_solutions = 0 + while solver.NextSolution(): + print "z:", z.Value() + p = [positions[i].Value() for i in range(n)] - num_solutions = 0 - while solver.NextSolution(): - print "z:", z.Value() - p = [positions[i].Value() for i in range(n)] - - print " ".join([persons[j] - for i in range(n) for j in range(n) if p[j] == i]) - print "Successful preferences:" - for i in range(n): - for j in range(n): - if preferences[i][j] == 1 and abs(p[i]-p[j])==1: - print "\t", persons[i], persons[j] - print - num_solutions += 1 - - solver.EndSearch() - + print " ".join([persons[j] + for i in range(n) for j in range(n) if p[j] == i]) + print "Successful preferences:" + for i in range(n): + for j in range(n): + if preferences[i][j] == 1 and abs(p[i] - p[j]) == 1: + print "\t", persons[i], persons[j] print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + num_solutions += 1 + + solver.EndSearch() + + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() show_all_max = 0 # show all maximal solutions -if __name__ == '__main__': - if len(sys.argv) > 1: - show_all_max = 1 - main(show_all_max) +if __name__ == "__main__": + if len(sys.argv) > 1: + show_all_max = 1 + main(show_all_max) diff --git a/examples/python/place_number_puzzle.py b/examples/python/place_number_puzzle.py index af5652fccc..80490b9802 100644 --- a/examples/python/place_number_puzzle.py +++ b/examples/python/place_number_puzzle.py @@ -36,7 +36,8 @@ * Gecode: http://www.hakank.org/gecode/place_number_puzzle.cpp This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ @@ -44,91 +45,89 @@ import sys import string from ortools.constraint_solver import pywrapcp + def main(): - # Create the solver. - solver = pywrapcp.Solver('Place number') + # Create the solver. + solver = pywrapcp.Solver("Place number") - # data - m = 32 - n = 8 - # Note: this is 1-based for compatibility (and lazyness) - graph = [ - [1,2], - [1,3], - [1,4], - [2,1], - [2,3], - [2,5], - [2,6], - [3,2], - [3,4], - [3,6], - [3,7], - [4,1], - [4,3], - [4,6], - [4,7], - [5,2], - [5,3], - [5,6], - [5,8], - [6,2], - [6,3], - [6,4], - [6,5], - [6,7], - [6,8], - [7,3], - [7,4], - [7,6], - [7,8], - [8,5], - [8,6], - [8,7] - ] + # data + m = 32 + n = 8 + # Note: this is 1-based for compatibility (and lazyness) + graph = [ + [1, 2], + [1, 3], + [1, 4], + [2, 1], + [2, 3], + [2, 5], + [2, 6], + [3, 2], + [3, 4], + [3, 6], + [3, 7], + [4, 1], + [4, 3], + [4, 6], + [4, 7], + [5, 2], + [5, 3], + [5, 6], + [5, 8], + [6, 2], + [6, 3], + [6, 4], + [6, 5], + [6, 7], + [6, 8], + [7, 3], + [7, 4], + [7, 6], + [7, 8], + [8, 5], + [8, 6], + [8, 7] + ] + # declare variables + x = [solver.IntVar(1, n, "x%i" % i) for i in range(n)] - # declare variables - x = [solver.IntVar(1, n, "x%i"%i) for i in range(n)] + # + # constraints + # + solver.Add(solver.AllDifferent(x)) + for i in range(m): + # Note: make 0-based + solver.Add(abs( + x[graph[i][0] - 1] - x[graph[i][1] - 1]) > 1) + # symmetry breaking + solver.Add(x[0] < x[n - 1]) - # - # constraints - # - solver.Add(solver.AllDifferent(x)) - for i in range(m): - # Note: make 0-based - solver.Add( abs( - x[graph[i][0]-1]-x[graph[i][1]-1]) > 1 - ) + # + # solution and search + # + solution = solver.Assignment() + solution.Add(x) - # symmetry breaking - solver.Add(x[0] < x[n-1]) + collector = solver.AllSolutionCollector(solution) - # - # solution and search - # - solution = solver.Assignment() - solution.Add(x) + solver.Solve(solver.Phase(x, + solver.CHOOSE_FIRST_UNBOUND, + solver.ASSIGN_MIN_VALUE), + [collector]) - collector = solver.AllSolutionCollector(solution) + num_solutions = collector.SolutionCount() + for s in range(num_solutions): + print "x:", [collector.Value(s, x[i]) for i in range(len(x))] - solver.Solve(solver.Phase(x, - solver.CHOOSE_FIRST_UNBOUND, - solver.ASSIGN_MIN_VALUE), - [collector]) + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() + print - num_solutions = collector.SolutionCount() - for s in range(num_solutions): - print "x:", [collector.Value(s, x[i]) for i in range(len(x))] - - print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() - print - -if __name__ == '__main__': - main() +if __name__ == "__main__": + main() diff --git a/examples/python/post_office_problem2.py b/examples/python/post_office_problem2.py index 5824c2a62d..d7711cbfe9 100644 --- a/examples/python/post_office_problem2.py +++ b/examples/python/post_office_problem2.py @@ -51,7 +51,8 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ from ortools.constraint_solver import pywrapcp @@ -59,76 +60,73 @@ from ortools.constraint_solver import pywrapcp def main(): - # Create the solver. - solver = pywrapcp.Solver('Post office problem') + # Create the solver. + solver = pywrapcp.Solver('Post office problem') - # - # data - # + # + # data + # - # days 0..6, monday 0 - n = 7 - days = range(n) - need = [17, 13, 15, 19, 14, 16, 11] + # days 0..6, monday 0 + n = 7 + days = range(n) + need = [17, 13, 15, 19, 14, 16, 11] - # Total cost for the 5 day schedule. - # Base cost per day is 100. - # Working saturday is 100 extra - # Working sunday is 200 extra. - cost = [500, 600, 800, 800, 800, 800, 700] + # Total cost for the 5 day schedule. + # Base cost per day is 100. + # Working saturday is 100 extra + # Working sunday is 200 extra. + cost = [500, 600, 800, 800, 800, 800, 700] + # + # variables + # - # - # variables - # + # No. of workers starting at day i + x = [solver.IntVar(0, 100, 'x[%i]' % i) for i in days] - # No. of workers starting at day i - x = [solver.IntVar(0, 100, 'x[%i]'%i) for i in days] + total_cost = solver.IntVar(0, 20000, 'total_cost') + num_workers = solver.IntVar(0, 100, 'num_workers') - total_cost = solver.IntVar(0, 20000, 'total_cost') - num_workers = solver.IntVar(0, 100, 'num_workers') + # + # constraints + # + solver.Add(total_cost == solver.ScalProd(x, cost)) + solver.Add(num_workers == solver.Sum(x)) - # - # constraints - # - solver.Add(total_cost == solver.ScalProd(x, cost)) - solver.Add(num_workers == solver.Sum(x)) + for i in days: + s = solver.Sum([x[j] for j in days + if j != (i + 5) % n and j != (i + 6) % n]) + solver.Add(s >= need[i]) - for i in days: - s = solver.Sum([x[j] for j in days - if j != (i+5) % n and j != (i+6) % n]) - solver.Add(s >= need[i]) + # objective + objective = solver.Minimize(total_cost, 1) - # objective - objective = solver.Minimize(total_cost, 1) + # + # search and result + # + db = solver.Phase(x, + solver.CHOOSE_MIN_SIZE_LOWEST_MIN, + solver.ASSIGN_MIN_VALUE) - # - # search and result - # - db = solver.Phase(x, - solver.CHOOSE_MIN_SIZE_LOWEST_MIN, - solver.ASSIGN_MIN_VALUE - ) + solver.NewSearch(db, [objective]) - solver.NewSearch(db, [objective]) + num_solutions = 0 + while solver.NextSolution(): + num_solutions += 1 + print 'num_workers:', num_workers.Value() + print 'total_cost:', total_cost.Value() + print 'x:', [x[i].Value() for i in days] - num_solutions = 0 + solver.EndSearch() - while solver.NextSolution(): - num_solutions += 1 - print 'num_workers:', num_workers.Value() - print 'total_cost:', total_cost.Value() - print 'x:', [x[i].Value() for i in days] - - solver.EndSearch() - - print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + print + print 'num_solutions:', num_solutions + print 'failures:', solver.Failures() + print 'branches:', solver.Branches() + print 'WallTime:', solver.WallTime() if __name__ == '__main__': - main() + main() diff --git a/examples/python/production.py b/examples/python/production.py index 17e9ab5793..008db70a2f 100644 --- a/examples/python/production.py +++ b/examples/python/production.py @@ -19,13 +19,15 @@ From the OPL model production.mod. This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ import sys from ortools.linear_solver import pywraplp -def main(sol = 'GLPK'): + +def main(sol='GLPK'): # Create the solver. @@ -38,7 +40,6 @@ def main(sol = 'GLPK'): solver = pywraplp.Solver('CoinsGridCLP', pywraplp.Solver.CLP_LINEAR_PROGRAMMING) - # # data # @@ -53,33 +54,34 @@ def main(sol = 'GLPK'): resources = ['flour', 'eggs'] num_resources = len(resources) - consumption = [ [0.5, 0.2], [0.4, 0.4], [0.3, 0.6] ] - capacity = [ 20, 40 ] - demand = [ 100, 200, 300 ] - inside_cost = [0.6, 0.8, 0.3 ] + consumption = [[0.5, 0.2], [0.4, 0.4], [0.3, 0.6]] + capacity = [20, 40] + demand = [100, 200, 300] + inside_cost = [0.6, 0.8, 0.3] outside_cost = [0.8, 0.9, 0.4] # # declare variables # - inside = [solver.NumVar(0, 10000, 'inside[%i]' % p ) + inside = [solver.NumVar(0, 10000, 'inside[%i]' % p) for p in range(num_products)] - outside = [solver.NumVar(0, 10000, 'outside[%i]' % p ) + outside = [solver.NumVar(0, 10000, 'outside[%i]' % p) for p in range(num_products)] # to minimize z = solver.Sum([inside_cost[p] * inside[p] + outside_cost[p] * outside[p] - for p in range(num_products)]) + for p in range(num_products)]) # # constraints # for r in range(num_resources): solver.Add(solver.Sum( - [consumption[p][r]*inside[p] for p in range(num_products)]) <= capacity[r]) + [consumption[p][r] * inside[p] + for p in range(num_products)]) <= capacity[r]) for p in range(num_products): - solver.Add(inside[p] + outside[p] >= demand[p]) + solver.Add(inside[p] + outside[p] >= demand[p]) objective = solver.Minimize(z) @@ -89,8 +91,8 @@ def main(sol = 'GLPK'): print 'z = ', solver.Objective().Value() for p in range(num_products): - print products[p], ': inside:', inside[p].SolutionValue(), '(ReducedCost:', inside[p].ReducedCost(), ')', - print 'outside:', outside[p].SolutionValue(), ' (ReducedCost:', outside[p].ReducedCost(), ')' + print products[p], ': inside:', inside[p].SolutionValue(), '(ReducedCost:', inside[p].ReducedCost(), ')', + print 'outside:', outside[p].SolutionValue(), ' (ReducedCost:', outside[p].ReducedCost(), ')' print diff --git a/examples/python/pyflow_example.py b/examples/python/pyflow_example.py index 8315a7d0e0..8929180844 100644 --- a/examples/python/pyflow_example.py +++ b/examples/python/pyflow_example.py @@ -14,7 +14,6 @@ """MaxFlow and MinCostFlow examples.""" - from google.apputils import app from ortools.graph import pywrapgraph diff --git a/examples/python/quasigroup_completion.py b/examples/python/quasigroup_completion.py index fb497350a1..02f2c2267e 100644 --- a/examples/python/quasigroup_completion.py +++ b/examples/python/quasigroup_completion.py @@ -24,12 +24,15 @@ Ivars Peterson "Completing Latin Squares" http://www.maa.org/mathland/mathtrek_5_8_00.html ''' - Using only the numbers 1, 2, 3, and 4, arrange four sets of these numbers into + Using only the numbers 1, 2, 3, and 4, arrange four sets of these numbers + into a four-by-four array so that no column or row contains the same two numbers. The result is known as a Latin square. ... - The so-called quasigroup completion problem concerns a table that is correctly - but only partially filled in. The question is whether the remaining blanks in + The so-called quasigroup completion problem concerns a table that is + correctly + but only partially filled in. The question is whether the remaining blanks + in the table can be filled in to obtain a complete Latin square (or a proper quasigroup multiplication table). ''' @@ -47,7 +50,8 @@ * Zinc: http://hakank.org/minizinc/quasigroup_completion.zinc This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ import sys @@ -63,153 +67,150 @@ default_puzzle = [ [4, X, X, 2, X], [X, 4, X, X, X], [X, X, 5, X, 1] - ] +] + def main(puzzle="", n=0): - # Create the solver. - solver = pywrapcp.Solver('Quasigroup completion') + # Create the solver. + solver = pywrapcp.Solver("Quasigroup completion") - # - # data - # + # + # data + # - if puzzle == "": - puzzle = default_puzzle - n = default_n + if puzzle == "": + puzzle = default_puzzle + n = default_n - print "Problem:" - print_game(puzzle, n,n) + print "Problem:" + print_game(puzzle, n, n) + # declare variables + x = {} + for i in range(n): + for j in range(n): + x[(i, j)] = solver.IntVar(1, n, "x %i %i" % (i, j)) - # declare variables - x = {} + xflat = [x[(i, j)] for i in range(n) for j in range(n)] + + # + # constraints + # + + # + # set the clues + # + for i in range(n): + for j in range(n): + if puzzle[i][j] > X: + solver.Add(x[i, j] == puzzle[i][j]) + + # + # rows and columns must be different + # + for i in range(n): + solver.Add(solver.AllDifferent([x[i, j] for j in range(n)])) + solver.Add(solver.AllDifferent([x[j, i] for j in range(n)])) + + # + # solution and search + # + solution = solver.Assignment() + solution.Add(xflat) + + # This version prints out the solution directly, and + # don't collect them as solver.FirstSolutionCollector(solution) do + # (db: DecisionBuilder) + db = solver.Phase(xflat, + solver.INT_VAR_SIMPLE, + solver.ASSIGN_MIN_VALUE) + + solver.NewSearch(db) + num_solutions = 0 + while solver.NextSolution(): + num_solutions += 1 + print "Solution %i" % num_solutions + xval = [x[(i, j)].Value() for i in range(n) for j in range(n)] for i in range(n): - for j in range(n): - x[(i,j)] = solver.IntVar(1,n, 'x %i %i' % (i, j)) - - xflat = [x[(i,j)] for i in range(n) for j in range(n)] - - # - # constraints - # - - # - # set the clues - # - for i in range(n): - for j in range(n): - if puzzle[i][j] > X: - solver.Add(x[i,j] == puzzle[i][j]) - - - - # - # rows and columns must be different - # - for i in range(n): - solver.Add(solver.AllDifferent([x[i,j] for j in range(n)])) - solver.Add(solver.AllDifferent([x[j,i] for j in range(n)])) - - # - # solution and search - # - solution = solver.Assignment() - solution.Add(xflat) - - # This version prints out the solution directly, and - # don't collect them as solver.FirstSolutionCollector(solution) do - # (db: DecisionBuilder) - db = solver.Phase(xflat, - solver.INT_VAR_SIMPLE, - solver.ASSIGN_MIN_VALUE) - - solver.NewSearch(db) - num_solutions = 0 - while solver.NextSolution(): - num_solutions += 1 - print "Solution %i" % num_solutions - xval = [x[(i,j)].Value() for i in range(n) for j in range(n)] - for i in range(n): - for j in range(n): - print xval[i*n+j], - print - print - solver.EndSearch() - - if num_solutions == 0: - print "No solutions found" - - # # Note: AllSolution may take very much RAM, hence I choose to - # # show just the first solution. - # # collector = solver.AllSolutionCollector(solution) - # collector = solver.FirstSolutionCollector(solution) - # solver.Solve(solver.Phase([x[(i,j)] for i in range(n) for j in range(n)], - # solver.CHOOSE_FIRST_UNBOUND, - # solver.ASSIGN_MIN_VALUE), - # [collector]) - # - # num_solutions = collector.SolutionCount() - # print "\nnum_solutions: ", num_solutions - # if num_solutions > 0: - # print "\nJust showing the first solution..." - # for s in range(num_solutions): - # xval = [collector.Value(s, x[(i,j)]) for i in range(n) for j in range(n)] - # for i in range(n): - # for j in range(n): - # print xval[i*n+j], - # print - # print - + for j in range(n): + print xval[i * n + j], + print print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + solver.EndSearch() + if num_solutions == 0: + print "No solutions found" + + # # Note: AllSolution may take very much RAM, hence I choose to + # # show just the first solution. + # # collector = solver.AllSolutionCollector(solution) + # collector = solver.FirstSolutionCollector(solution) + # solver.Solve(solver.Phase([x[(i,j)] for i in range(n) for j in range(n)], + # solver.CHOOSE_FIRST_UNBOUND, + # solver.ASSIGN_MIN_VALUE), + # [collector]) + # + # num_solutions = collector.SolutionCount() + # print "\nnum_solutions: ", num_solutions + # if num_solutions > 0: + # print "\nJust showing the first solution..." + # for s in range(num_solutions): + # xval = [collector.Value(s, x[(i,j)]) for i in range(n) for j in range(n)] + # for i in range(n): + # for j in range(n): + # print xval[i*n+j], + # print + # print + + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() # # Read a problem instance from a file # def read_problem(file): - f = open(file, 'r') - n = int(f.readline()) - game = [] - for i in range(n): - x = f.readline() - row_x = (x.rstrip()).split(" ") - row = [0]*n - for j in range(n): - if row_x[j] == ".": - tmp = 0 - else: - tmp = int(row_x[j]) - row[j] = tmp - game.append(row) - return [game, n] + f = open(file, "r") + n = int(f.readline()) + game = [] + for i in range(n): + x = f.readline() + row_x = (x.rstrip()).split(" ") + row = [0] * n + for j in range(n): + if row_x[j] == ".": + tmp = 0 + else: + tmp = int(row_x[j]) + row[j] = tmp + game.append(row) + return [game, n] def print_board(x, rows, cols): - for i in range(rows): - for j in range(cols): - print "% 2s" % x[i,j], - print '' + for i in range(rows): + for j in range(cols): + print "% 2s" % x[i, j], + print "" + def print_game(game, rows, cols): - for i in range(rows): - for j in range(cols): - print "% 2s" % game[i][j], - print '' + for i in range(rows): + for j in range(cols): + print "% 2s" % game[i][j], + print "" +if __name__ == "__main__": -if __name__ == '__main__': - - if len(sys.argv) > 1: - file = sys.argv[1] - print "Problem instance from", file - [game, n] = read_problem(file) - main(game, n) - else: - main() + if len(sys.argv) > 1: + file = sys.argv[1] + print "Problem instance from", file + [game, n] = read_problem(file) + main(game, n) + else: + main() diff --git a/examples/python/rabbit_pheasant.py b/examples/python/rabbit_pheasant.py index c1300d9ba2..49e9146e8b 100644 --- a/examples/python/rabbit_pheasant.py +++ b/examples/python/rabbit_pheasant.py @@ -22,7 +22,6 @@ flavors of constraint programming interfaces. """ - from ortools.constraint_solver import pywrapcp diff --git a/examples/python/regular.py b/examples/python/regular.py index 5612ab5162..af025817e7 100644 --- a/examples/python/regular.py +++ b/examples/python/regular.py @@ -34,7 +34,8 @@ using an array of size 10. This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ @@ -63,50 +64,50 @@ from ortools.constraint_solver import pywrapcp # F : accepting states def regular(x, Q, S, d, q0, F): - solver = x[0].solver() + solver = x[0].solver() - assert Q > 0, 'regular: "Q" must be greater than zero' - assert S > 0, 'regular: "S" must be greater than zero' + assert Q > 0, 'regular: "Q" must be greater than zero' + assert S > 0, 'regular: "S" must be greater than zero' - # d2 is the same as d, except we add one extra transition for - # each possible input; each extra transition is from state zero - # to state zero. This allows us to continue even if we hit a - # non-accepted input. + # d2 is the same as d, except we add one extra transition for + # each possible input; each extra transition is from state zero + # to state zero. This allows us to continue even if we hit a + # non-accepted input. - # int d2[0..Q, 1..S]; - d2 = [] - for i in range(Q+1): - row = [] - for j in range(S): - if i == 0: - row.append(0) - else: - row.append(d[i-1][j]) - d2.append(row) + # int d2[0..Q, 1..S]; + d2 = [] + for i in range(Q + 1): + row = [] + for j in range(S): + if i == 0: + row.append(0) + else: + row.append(d[i - 1][j]) + d2.append(row) - d2_flatten = [d2[i][j] for i in range(Q+1) for j in range(S)] + d2_flatten = [d2[i][j] for i in range(Q + 1) for j in range(S)] - # If x has index set m..n, then a[m-1] holds the initial state - # (q0), and a[i+1] holds the state we're in after processing - # x[i]. If a[n] is in F, then we succeed (ie. accept the - # string). - x_range = range(0,len(x)) - m = 0 - n = len(x) + # If x has index set m..n, then a[m-1] holds the initial state + # (q0), and a[i+1] holds the state we're in after processing + # x[i]. If a[n] is in F, then we succeed (ie. accept the + # string). + x_range = range(0, len(x)) + m = 0 + n = len(x) - a = [solver.IntVar(0, Q+1, 'a[%i]' % i) for i in range(m, n+1)] + a = [solver.IntVar(0, Q + 1, 'a[%i]' % i) for i in range(m, n + 1)] - # Check that the final state is in F - solver.Add(solver.MemberCt(a[-1], F)) - # First state is q0 - solver.Add(a[m] == q0) - for i in x_range: - solver.Add(x[i] >= 1) - solver.Add(x[i] <= S) - - # Determine a[i+1]: a[i+1] == d2[a[i], x[i]] - solver.Add(a[i+1] == solver.Element(d2_flatten, ((a[i])*S)+(x[i]-1))) + # Check that the final state is in F + solver.Add(solver.MemberCt(a[-1], F)) + # First state is q0 + solver.Add(a[m] == q0) + for i in x_range: + solver.Add(x[i] >= 1) + solver.Add(x[i] <= S) + # Determine a[i+1]: a[i+1] == d2[a[i], x[i]] + solver.Add( + a[i + 1] == solver.Element(d2_flatten, ((a[i]) * S) + (x[i] - 1))) # @@ -115,111 +116,110 @@ def regular(x, Q, S, d, q0, F): # def make_transition_matrix(pattern): - p_len = len(pattern) - print 'p_len:', p_len - num_states = p_len + sum(pattern) - print 'num_states:', num_states - t_matrix = [] - for i in range(num_states): - row = [] - for j in range(2): - row.append(0) - t_matrix.append(row) + p_len = len(pattern) + print 'p_len:', p_len + num_states = p_len + sum(pattern) + print 'num_states:', num_states + t_matrix = [] + for i in range(num_states): + row = [] + for j in range(2): + row.append(0) + t_matrix.append(row) - # convert pattern to a 0/1 pattern for easy handling of - # the states - tmp = [0 for i in range(num_states)] - c = 0 - tmp[c] = 0 - for i in range(p_len): - for j in range(pattern[i]): - c += 1 - tmp[c] = 1 - if c < num_states-1: - c += 1 - tmp[c] = 0 - print 'tmp:', tmp + # convert pattern to a 0/1 pattern for easy handling of + # the states + tmp = [0 for i in range(num_states)] + c = 0 + tmp[c] = 0 + for i in range(p_len): + for j in range(pattern[i]): + c += 1 + tmp[c] = 1 + if c < num_states - 1: + c += 1 + tmp[c] = 0 + print 'tmp:', tmp + t_matrix[num_states - 1][0] = num_states + t_matrix[num_states - 1][1] = 0 - t_matrix[num_states-1][0] = num_states - t_matrix[num_states-1][1] = 0 - - for i in range(num_states): - if tmp[i] == 0: - t_matrix[i][0] = i+1 - t_matrix[i][1] = i+2 + for i in range(num_states): + if tmp[i] == 0: + t_matrix[i][0] = i + 1 + t_matrix[i][1] = i + 2 + else: + if i < num_states - 1: + if tmp[i + 1] == 1: + t_matrix[i][0] = 0 + t_matrix[i][1] = i + 2 else: - if i < num_states-1: - if tmp[i+1] == 1: - t_matrix[i][0] = 0 - t_matrix[i][1] = i+2 - else: - t_matrix[i][0] = i+2 - t_matrix[i][1] = 0 + t_matrix[i][0] = i + 2 + t_matrix[i][1] = 0 - print 'The states:' - for i in range(num_states): - for j in range(2): - print t_matrix[i][j], - print + print 'The states:' + for i in range(num_states): + for j in range(2): + print t_matrix[i][j], print + print + + return t_matrix - return t_matrix def main(): - # Create the solver. - solver = pywrapcp.Solver('Regular test') + # Create the solver. + solver = pywrapcp.Solver('Regular test') - # - # data - # + # + # data + # - this_len = 10 - pp = [3,2,1] + this_len = 10 + pp = [3, 2, 1] - transition_fn = make_transition_matrix(pp) - n_states = len(transition_fn) - input_max = 2 + transition_fn = make_transition_matrix(pp) + n_states = len(transition_fn) + input_max = 2 - # Note: we use '1' and '2' (rather than 0 and 1) - # since 0 represents the failing state. - initial_state = 1 + # Note: we use '1' and '2' (rather than 0 and 1) + # since 0 represents the failing state. + initial_state = 1 - accepting_states = [n_states] + accepting_states = [n_states] - # declare variables - reg_input = [solver.IntVar(1, input_max, 'reg_input[%i]' % i) - for i in range(this_len)] + # declare variables + reg_input = [solver.IntVar(1, input_max, 'reg_input[%i]' % i) + for i in range(this_len)] - # - # constraints - # - regular(reg_input, n_states, input_max, transition_fn, - initial_state, accepting_states) + # + # constraints + # + regular(reg_input, n_states, input_max, transition_fn, + initial_state, accepting_states) + # + # solution and search + # + db = solver.Phase(reg_input, + solver.CHOOSE_MIN_SIZE_HIGHEST_MAX, + solver.ASSIGN_MIN_VALUE) - # - # solution and search - # - db = solver.Phase(reg_input, - solver.CHOOSE_MIN_SIZE_HIGHEST_MAX, - solver.ASSIGN_MIN_VALUE) + solver.NewSearch(db) - solver.NewSearch(db) + num_solutions = 0 + while solver.NextSolution(): + print 'reg_input:', [reg_input[i].Value() - 1 for i in range(this_len)] + num_solutions += 1 - num_solutions = 0 - while solver.NextSolution(): - print 'reg_input:', [reg_input[i].Value()-1 for i in range(this_len)] - num_solutions += 1 - - solver.EndSearch() - print - print 'num_solutions:', num_solutions - print 'failures:', solver.Failures() - print 'branches:', solver.Branches() - print 'WallTime:', solver.WallTime(), 'ms' + solver.EndSearch() + print + print 'num_solutions:', num_solutions + print 'failures:', solver.Failures() + print 'branches:', solver.Branches() + print 'WallTime:', solver.WallTime(), 'ms' if __name__ == '__main__': - main() + main() diff --git a/examples/python/regular_table.py b/examples/python/regular_table.py index 122b555d7f..e798316809 100644 --- a/examples/python/regular_table.py +++ b/examples/python/regular_table.py @@ -34,7 +34,8 @@ using an array of size 10. This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ @@ -73,7 +74,7 @@ def regular(x, Q, S, d, q0, F): # to state zero. This allows us to continue even if we hit a # non-accepted input. - d2 = pywrapcp.IntTupleSet(3); + d2 = pywrapcp.IntTupleSet(3) for i in range(Q + 1): for j in range(S): if i == 0: @@ -85,15 +86,15 @@ def regular(x, Q, S, d, q0, F): # (q0), and a[i+1] holds the state we're in after processing # x[i]. If a[n] is in F, then we succeed (ie. accept the # string). - x_range = range(0,len(x)) + x_range = range(0, len(x)) m = 0 n = len(x) - a = [solver.IntVar(0, Q, 'a[%i]' % i) for i in range(m, n+1)] + a = [solver.IntVar(0, Q, 'a[%i]' % i) for i in range(m, n + 1)] - # Check that the final state is in F + # Check that the final state is in F solver.Add(solver.MemberCt(a[-1], F)) - # First state is q0 + # First state is q0 solver.Add(a[m] == q0) for i in x_range: solver.Add(x[i] >= 1) @@ -108,111 +109,110 @@ def regular(x, Q, S, d, q0, F): # def make_transition_matrix(pattern): - p_len = len(pattern) - print 'p_len:', p_len - num_states = p_len + sum(pattern) - print 'num_states:', num_states - t_matrix = [] - for i in range(num_states): - row = [] - for j in range(2): - row.append(0) - t_matrix.append(row) + p_len = len(pattern) + print 'p_len:', p_len + num_states = p_len + sum(pattern) + print 'num_states:', num_states + t_matrix = [] + for i in range(num_states): + row = [] + for j in range(2): + row.append(0) + t_matrix.append(row) - # convert pattern to a 0/1 pattern for easy handling of - # the states - tmp = [0 for i in range(num_states)] - c = 0 - tmp[c] = 0 - for i in range(p_len): - for j in range(pattern[i]): - c += 1 - tmp[c] = 1 - if c < num_states - 1: - c += 1 - tmp[c] = 0 - print 'tmp:', tmp + # convert pattern to a 0/1 pattern for easy handling of + # the states + tmp = [0 for i in range(num_states)] + c = 0 + tmp[c] = 0 + for i in range(p_len): + for j in range(pattern[i]): + c += 1 + tmp[c] = 1 + if c < num_states - 1: + c += 1 + tmp[c] = 0 + print 'tmp:', tmp + t_matrix[num_states - 1][0] = num_states + t_matrix[num_states - 1][1] = 0 - t_matrix[num_states - 1][0] = num_states - t_matrix[num_states - 1][1] = 0 - - for i in range(num_states): - if tmp[i] == 0: - t_matrix[i][0] = i + 1 - t_matrix[i][1] = i + 2 + for i in range(num_states): + if tmp[i] == 0: + t_matrix[i][0] = i + 1 + t_matrix[i][1] = i + 2 + else: + if i < num_states - 1: + if tmp[i + 1] == 1: + t_matrix[i][0] = 0 + t_matrix[i][1] = i + 2 else: - if i < num_states - 1: - if tmp[i+1] == 1: - t_matrix[i][0] = 0 - t_matrix[i][1] = i + 2 - else: - t_matrix[i][0] = i + 2 - t_matrix[i][1] = 0 + t_matrix[i][0] = i + 2 + t_matrix[i][1] = 0 - print 'The states:' - for i in range(num_states): - for j in range(2): - print t_matrix[i][j], - print + print 'The states:' + for i in range(num_states): + for j in range(2): + print t_matrix[i][j], print + print + + return t_matrix - return t_matrix def main(): - # Create the solver. - solver = pywrapcp.Solver('Regular test') + # Create the solver. + solver = pywrapcp.Solver('Regular test') - # - # data - # + # + # data + # - this_len = 10 - pp = [3,2,1] + this_len = 10 + pp = [3, 2, 1] - transition_fn = make_transition_matrix(pp) - n_states = len(transition_fn) - input_max = 2 + transition_fn = make_transition_matrix(pp) + n_states = len(transition_fn) + input_max = 2 - # Note: we use '1' and '2' (rather than 0 and 1) - # since 0 represents the failing state. - initial_state = 1 + # Note: we use '1' and '2' (rather than 0 and 1) + # since 0 represents the failing state. + initial_state = 1 - accepting_states = [n_states] + accepting_states = [n_states] - # declare variables - reg_input = [solver.IntVar(1, input_max, 'reg_input[%i]' % i) - for i in range(this_len)] + # declare variables + reg_input = [solver.IntVar(1, input_max, 'reg_input[%i]' % i) + for i in range(this_len)] - # - # constraints - # - regular(reg_input, n_states, input_max, transition_fn, - initial_state, accepting_states) + # + # constraints + # + regular(reg_input, n_states, input_max, transition_fn, + initial_state, accepting_states) + # + # solution and search + # + db = solver.Phase(reg_input, + solver.CHOOSE_MIN_SIZE_HIGHEST_MAX, + solver.ASSIGN_MIN_VALUE) - # - # solution and search - # - db = solver.Phase(reg_input, - solver.CHOOSE_MIN_SIZE_HIGHEST_MAX, - solver.ASSIGN_MIN_VALUE) + solver.NewSearch(db) - solver.NewSearch(db) + num_solutions = 0 + while solver.NextSolution(): + print 'reg_input:', [reg_input[i].Value() - 1 for i in range(this_len)] + num_solutions += 1 - num_solutions = 0 - while solver.NextSolution(): - print 'reg_input:', [reg_input[i].Value()-1 for i in range(this_len)] - num_solutions += 1 - - solver.EndSearch() - print - print 'num_solutions:', num_solutions - print 'failures:', solver.Failures() - print 'branches:', solver.Branches() - print 'WallTime:', solver.WallTime(), 'ms' + solver.EndSearch() + print + print 'num_solutions:', num_solutions + print 'failures:', solver.Failures() + print 'branches:', solver.Branches() + print 'WallTime:', solver.WallTime(), 'ms' if __name__ == '__main__': - main() + main() diff --git a/examples/python/regular_table2.py b/examples/python/regular_table2.py index 78c228cd94..351f9f36cd 100644 --- a/examples/python/regular_table2.py +++ b/examples/python/regular_table2.py @@ -34,7 +34,8 @@ using an array of size 10. This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ @@ -73,7 +74,7 @@ def regular(x, Q, S, d, q0, F): # to state zero. This allows us to continue even if we hit a # non-accepted input. - d2 = pywrapcp.IntTupleSet(3); + d2 = pywrapcp.IntTupleSet(3) for i in range(Q + 1): for j in range(1, S + 1): if i == 0: @@ -87,113 +88,114 @@ def regular(x, Q, S, d, q0, F): # Make a transition (automaton) matrix from a # single pattern, e.g. [3,2,1] # + + def make_transition_matrix(pattern): - p_len = len(pattern) - print 'p_len:', p_len - num_states = p_len + sum(pattern) - print 'num_states:', num_states - t_matrix = [] - for i in range(num_states): - row = [] - for j in range(2): - row.append(0) - t_matrix.append(row) + p_len = len(pattern) + print 'p_len:', p_len + num_states = p_len + sum(pattern) + print 'num_states:', num_states + t_matrix = [] + for i in range(num_states): + row = [] + for j in range(2): + row.append(0) + t_matrix.append(row) - # convert pattern to a 0/1 pattern for easy handling of - # the states - tmp = [0 for i in range(num_states)] - c = 0 - tmp[c] = 0 - for i in range(p_len): - for j in range(pattern[i]): - c += 1 - tmp[c] = 1 - if c < num_states-1: - c += 1 - tmp[c] = 0 - print 'tmp:', tmp + # convert pattern to a 0/1 pattern for easy handling of + # the states + tmp = [0 for i in range(num_states)] + c = 0 + tmp[c] = 0 + for i in range(p_len): + for j in range(pattern[i]): + c += 1 + tmp[c] = 1 + if c < num_states - 1: + c += 1 + tmp[c] = 0 + print 'tmp:', tmp + t_matrix[num_states - 1][0] = num_states + t_matrix[num_states - 1][1] = 0 - t_matrix[num_states-1][0] = num_states - t_matrix[num_states-1][1] = 0 - - for i in range(num_states): - if tmp[i] == 0: - t_matrix[i][0] = i+1 - t_matrix[i][1] = i+2 + for i in range(num_states): + if tmp[i] == 0: + t_matrix[i][0] = i + 1 + t_matrix[i][1] = i + 2 + else: + if i < num_states - 1: + if tmp[i + 1] == 1: + t_matrix[i][0] = 0 + t_matrix[i][1] = i + 2 else: - if i < num_states-1: - if tmp[i+1] == 1: - t_matrix[i][0] = 0 - t_matrix[i][1] = i+2 - else: - t_matrix[i][0] = i+2 - t_matrix[i][1] = 0 + t_matrix[i][0] = i + 2 + t_matrix[i][1] = 0 - print 'The states:' - for i in range(num_states): - for j in range(2): - print t_matrix[i][j], - print + print 'The states:' + for i in range(num_states): + for j in range(2): + print t_matrix[i][j], print + print + + return t_matrix - return t_matrix def main(): - # Create the solver. - solver = pywrapcp.Solver('Regular test') + # Create the solver. + solver = pywrapcp.Solver('Regular test') - # - # data - # + # + # data + # - this_len = 10 - pp = [3,2,1] + this_len = 10 + pp = [3, 2, 1] - transition_fn = make_transition_matrix(pp) - n_states = len(transition_fn) - input_max = 2 + transition_fn = make_transition_matrix(pp) + n_states = len(transition_fn) + input_max = 2 - # Note: we use '1' and '2' (rather than 0 and 1) - # since 0 represents the failing state. - initial_state = 1 + # Note: we use '1' and '2' (rather than 0 and 1) + # since 0 represents the failing state. + initial_state = 1 - accepting_states = [n_states] + accepting_states = [n_states] - # declare variables - reg_input = [solver.IntVar(1, input_max, 'reg_input[%i]' % i) - for i in range(this_len)] + # declare variables + reg_input = [solver.IntVar(1, input_max, 'reg_input[%i]' % i) + for i in range(this_len)] - # - # constraints - # - regular(reg_input, n_states, input_max, transition_fn, - initial_state, accepting_states) + # + # constraints + # + regular(reg_input, n_states, input_max, transition_fn, + initial_state, accepting_states) + # + # solution and search + # + db = solver.Phase(reg_input, + solver.CHOOSE_MIN_SIZE_HIGHEST_MAX, + solver.ASSIGN_MIN_VALUE) - # - # solution and search - # - db = solver.Phase(reg_input, - solver.CHOOSE_MIN_SIZE_HIGHEST_MAX, - solver.ASSIGN_MIN_VALUE) + solver.NewSearch(db) - solver.NewSearch(db) + num_solutions = 0 + while solver.NextSolution(): + print 'reg_input:', [reg_input[i].Value() - 1 for i in range(this_len)] + num_solutions += 1 - num_solutions = 0 - while solver.NextSolution(): - print 'reg_input:', [reg_input[i].Value()-1 for i in range(this_len)] - num_solutions += 1 - - solver.EndSearch() - print - print 'num_solutions:', num_solutions - print 'failures:', solver.Failures() - print 'branches:', solver.Branches() - print 'WallTime:', solver.WallTime(), 'ms' + solver.EndSearch() + print + print 'num_solutions:', num_solutions + print 'failures:', solver.Failures() + print 'branches:', solver.Branches() + print 'WallTime:', solver.WallTime(), 'ms' if __name__ == '__main__': - main() + main() diff --git a/examples/python/rogo2.py b/examples/python/rogo2.py index fbf99051a9..a852926e40 100644 --- a/examples/python/rogo2.py +++ b/examples/python/rogo2.py @@ -41,129 +41,131 @@ * MiniZinc: http://www.hakank.org/minizinc/rogo2.mzn This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ -import sys, string, re +import sys +import string +import re from ortools.constraint_solver import pywrapcp + def main(problem, rows, cols, max_steps): - # Create the solver. - solver = pywrapcp.Solver('Rogo grid puzzle') + # Create the solver. + solver = pywrapcp.Solver("Rogo grid puzzle") - # - # data - # - W = 0 - B = -1 - print "rows: %i cols: %i max_steps: %i" % (rows, cols, max_steps) + # + # data + # + W = 0 + B = -1 + print "rows: %i cols: %i max_steps: %i" % (rows, cols, max_steps) - problem_flatten = [problem[i][j] for i in range(rows) for j in range(cols)] - max_point = max(problem_flatten) - print "max_point:", max_point - max_sum = sum(problem_flatten) - print "max_sum:", max_sum + problem_flatten = [problem[i][j] for i in range(rows) for j in range(cols)] + max_point = max(problem_flatten) + print "max_point:", max_point + max_sum = sum(problem_flatten) + print "max_sum:", max_sum + print + + # + # declare variables + # + + # the coordinates + x = [solver.IntVar(0, rows - 1, "x[%i]" % i) for i in range(max_steps)] + y = [solver.IntVar(0, cols - 1, "y[%i]" % i) for i in range(max_steps)] + + # the collected points + points = [solver.IntVar(0, max_point, "points[%i]" % i) + for i in range(max_steps)] + + # objective: sum of points in the path + sum_points = solver.IntVar(0, max_sum) + + # + # constraints + # + + # all coordinates must be unique + for s in range(max_steps): + for t in range(s + 1, max_steps): + b1 = solver.IsDifferentVar(x[s], x[t]) + b2 = solver.IsDifferentVar(y[s], y[t]) + solver.Add(b1 + b2 >= 1) + + # calculate the points (to maximize) + for s in range(max_steps): + solver.Add(points[s] == solver.Element(problem_flatten, x[s] * cols + y[s])) + + solver.Add(sum_points == sum(points)) + + # ensure that there are not black cells in + # the path + for s in range(max_steps): + solver.Add(solver.Element(problem_flatten, x[s] * cols + y[s]) != B) + + # get the path + for s in range(max_steps - 1): + solver.Add(abs(x[s] - x[s + 1]) + abs(y[s] - y[s + 1]) == 1) + + # close the path around the corner + solver.Add(abs(x[max_steps - 1] - x[0]) + abs(y[max_steps - 1] - y[0]) == 1) + + # symmetry breaking: the cell with lowest coordinates + # should be in the first step. + for i in range(1, max_steps): + solver.Add(x[0] * cols + y[0] < x[i] * cols + y[i]) + + # symmetry breaking: second step is larger than + # first step + # solver.Add(x[0]*cols+y[0] < x[1]*cols+y[1]) + + # + # objective + # + objective = solver.Maximize(sum_points, 1) + + # + # solution and search + # + # db = solver.Phase(x + y, + # solver.CHOOSE_MIN_SIZE_LOWEST_MIN, + # solver.ASSIGN_MIN_VALUE) + + # Default search + parameters = pywrapcp.DefaultPhaseParameters() + + parameters.heuristic_period = 200000 + # parameters.var_selection_schema = parameters.CHOOSE_MAX_SUM_IMPACT + parameters.var_selection_schema = parameters.CHOOSE_MAX_AVERAGE_IMPACT # <- + # parameters.var_selection_schema = parameters.CHOOSE_MAX_VALUE_IMPACT + + parameters.value_selection_schema = parameters.SELECT_MIN_IMPACT # <- + # parameters.value_selection_schema = parameters.SELECT_MAX_IMPACT + + # parameters.initialization_splits = 10 + + db = solver.DefaultPhase(x + y, parameters) + + solver.NewSearch(db, [objective]) + + num_solutions = 0 + while solver.NextSolution(): + num_solutions += 1 + print "sum_points:", sum_points.Value() + print "adding 1 to coords..." + for s in range(max_steps): + print "%i %i" % (x[s].Value() + 1, y[s].Value() + 1) print - # - # declare variables - # - - # the coordinates - x = [solver.IntVar(0, rows-1, "x[%i]"%i) for i in range(max_steps)] - y = [solver.IntVar(0, cols-1, "y[%i]"%i) for i in range(max_steps)] - - # the collected points - points = [solver.IntVar(0, max_point, "points[%i]"%i) for i in range(max_steps)] - - # objective: sum of points in the path - sum_points = solver.IntVar(0, max_sum) - - # - # constraints - # - - # all coordinates must be unique - for s in range(max_steps): - for t in range(s+1, max_steps): - b1 = solver.IsDifferentVar(x[s], x[t]) - b2 = solver.IsDifferentVar(y[s], y[t]) - solver.Add(b1+b2 >= 1) - - # calculate the points (to maximize) - for s in range(max_steps): - solver.Add(points[s] == solver.Element(problem_flatten, x[s]*cols+y[s])) - - solver.Add(sum_points == sum(points)) - - # ensure that there are not black cells in - # the path - for s in range(max_steps): - solver.Add(solver.Element(problem_flatten, x[s]*cols+y[s]) != B) - - # get the path - for s in range(max_steps-1): - solver.Add(abs(x[s]-x[s+1]) + abs(y[s]-y[s+1]) == 1) - - # close the path around the corner - solver.Add(abs(x[max_steps-1]-x[0]) + abs(y[max_steps-1]-y[0]) == 1) - - - # symmetry breaking: the cell with lowest coordinates - # should be in the first step. - for i in range(1,max_steps): - solver.Add(x[0]*cols+y[0] < x[i]*cols+y[i]) - - # symmetry breaking: second step is larger than - # first step - # solver.Add(x[0]*cols+y[0] < x[1]*cols+y[1]) - - - # - # objective - # - objective = solver.Maximize(sum_points, 1) - - # - # solution and search - # - # db = solver.Phase(x + y, - # solver.CHOOSE_MIN_SIZE_LOWEST_MIN, - # solver.ASSIGN_MIN_VALUE) - - # Default search - parameters = pywrapcp.DefaultPhaseParameters() - - parameters.heuristic_period = 200000 - # parameters.var_selection_schema = parameters.CHOOSE_MAX_SUM_IMPACT - parameters.var_selection_schema = parameters.CHOOSE_MAX_AVERAGE_IMPACT # <- - # parameters.var_selection_schema = parameters.CHOOSE_MAX_VALUE_IMPACT - - parameters.value_selection_schema = parameters.SELECT_MIN_IMPACT # <- - # parameters.value_selection_schema = parameters.SELECT_MAX_IMPACT - - # parameters.initialization_splits = 10 - - db = solver.DefaultPhase(x + y, parameters) - - solver.NewSearch(db, [objective]) - - num_solutions = 0 - while solver.NextSolution(): - num_solutions += 1 - print "sum_points:", sum_points.Value() - print "adding 1 to coords..." - for s in range(max_steps): - print "%i %i" % (x[s].Value()+1,y[s].Value()+1) - print - - print "\nnum_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() - + print "\nnum_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() # Default problem: @@ -185,8 +187,8 @@ problem = [ [W, W, W, W, W, W, B, W, 2], [W, W, 2, B, W, W, W, W, W], [W, W, W, W, 2, W, W, 1, W] - ] -if __name__ == '__main__': - if len(sys.argv) > 1: - execfile(sys.argv[1]) - main(problem, rows, cols, max_steps) +] +if __name__ == "__main__": + if len(sys.argv) > 1: + execfile(sys.argv[1]) + main(problem, rows, cols, max_steps) diff --git a/examples/python/safe_cracking.py b/examples/python/safe_cracking.py index a071438d08..7a44a4fcac 100644 --- a/examples/python/safe_cracking.py +++ b/examples/python/safe_cracking.py @@ -42,7 +42,8 @@ * Gecode: http://hakank.org/gecode/safe_cracking.cpp This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ from ortools.constraint_solver import pywrapcp @@ -50,60 +51,57 @@ from ortools.constraint_solver import pywrapcp def main(): - # Create the solver. - solver = pywrapcp.Solver('Safe cracking puzzle') + # Create the solver. + solver = pywrapcp.Solver('Safe cracking puzzle') - # - # data - # - n = 9 - digits = range(1,n+1) + # + # data + # + n = 9 + digits = range(1, n + 1) - # - # variables - # + # + # variables + # - LD = [solver.IntVar(digits, 'LD[%i]'%i) for i in range(n)] - C1,C2,C3,C4,C5,C6,C7,C8,C9 = LD + LD = [solver.IntVar(digits, 'LD[%i]' % i) for i in range(n)] + C1, C2, C3, C4, C5, C6, C7, C8, C9 = LD - # - # constraints - # - solver.Add(solver.AllDifferent(LD)) + # + # constraints + # + solver.Add(solver.AllDifferent(LD)) - solver.Add(C4 - C6 == C7) - solver.Add(C1 * C2 * C3 == C8 + C9) - solver.Add(C2 + C3 + C6 < C8) - solver.Add(C9 < C8) - for i in range(n): - solver.Add(LD[i] != i+1) + solver.Add(C4 - C6 == C7) + solver.Add(C1 * C2 * C3 == C8 + C9) + solver.Add(C2 + C3 + C6 < C8) + solver.Add(C9 < C8) + for i in range(n): + solver.Add(LD[i] != i + 1) + # + # search and result + # + db = solver.Phase(LD, + solver.INT_VAR_DEFAULT, + solver.INT_VALUE_DEFAULT) - # - # search and result - # - db = solver.Phase(LD, - solver.INT_VAR_DEFAULT, - solver.INT_VALUE_DEFAULT - ) + solver.NewSearch(db) - solver.NewSearch(db) + num_solutions = 0 + while solver.NextSolution(): + num_solutions += 1 + print 'LD:', [LD[i].Value() for i in range(n)] - num_solutions = 0 + solver.EndSearch() - while solver.NextSolution(): - num_solutions += 1 - print 'LD:', [LD[i].Value() for i in range(n)] - - solver.EndSearch() - - print - print 'num_solutions:', num_solutions - print 'failures:', solver.Failures() - print 'branches:', solver.Branches() - print 'WallTime:', solver.WallTime(), 'ms' + print + print 'num_solutions:', num_solutions + print 'failures:', solver.Failures() + print 'branches:', solver.Branches() + print 'WallTime:', solver.WallTime(), 'ms' if __name__ == '__main__': - main() + main() diff --git a/examples/python/scheduling_speakers.py b/examples/python/scheduling_speakers.py index faf3dd1902..2063041abe 100644 --- a/examples/python/scheduling_speakers.py +++ b/examples/python/scheduling_speakers.py @@ -26,7 +26,8 @@ * Gecode: http://hakank.org/gecode/scheduling_speakers.cpp This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ from ortools.constraint_solver import pywrapcp @@ -34,64 +35,61 @@ from ortools.constraint_solver import pywrapcp def main(): - # Create the solver. - solver = pywrapcp.Solver('Scheduling speakers') + # Create the solver. + solver = pywrapcp.Solver('Scheduling speakers') - # - # data - # - n = 6 # number of speakers + # + # data + # + n = 6 # number of speakers - # slots available to speak - available = [ - # Reasoning: - [3,4,5,6], # 2) the only one with 6 after speaker F -> 1 - [3,4], # 5) 3 or 4 - [2,3,4,5], # 3) only with 5 after F -> 1 and A -> 6 - [2,3,4], # 4) only with 2 after C -> 5 and F -> 1 - [3,4], # 5) 3 or 4 - [1,2,3,4,5,6] # 1) the only with 1 - ] + # slots available to speak + available = [ + # Reasoning: + [3, 4, 5, 6], # 2) the only one with 6 after speaker F -> 1 + [3, 4], # 5) 3 or 4 + [2, 3, 4, 5], # 3) only with 5 after F -> 1 and A -> 6 + [2, 3, 4], # 4) only with 2 after C -> 5 and F -> 1 + [3, 4], # 5) 3 or 4 + [1, 2, 3, 4, 5, 6] # 1) the only with 1 + ] - # - # variables - # - x = [solver.IntVar(1, n, 'x[%i]'%i) for i in range(n)] + # + # variables + # + x = [solver.IntVar(1, n, 'x[%i]' % i) for i in range(n)] - # - # constraints - # - solver.Add(solver.AllDifferent(x)) + # + # constraints + # + solver.Add(solver.AllDifferent(x)) - for i in range(n): - solver.Add(solver.MemberCt(x[i], available[i])) + for i in range(n): + solver.Add(solver.MemberCt(x[i], available[i])) + # + # search and result + # + db = solver.Phase(x, + solver.INT_VAR_DEFAULT, + solver.INT_VALUE_DEFAULT) - # - # search and result - # - db = solver.Phase(x, - solver.INT_VAR_DEFAULT, - solver.INT_VALUE_DEFAULT - ) + solver.NewSearch(db) - solver.NewSearch(db) + num_solutions = 0 + while solver.NextSolution(): + num_solutions += 1 + print 'x:', [x[i].Value() for i in range(n)] - num_solutions = 0 + solver.EndSearch() - while solver.NextSolution(): - num_solutions += 1 - print 'x:', [x[i].Value() for i in range(n)] - - solver.EndSearch() - - print - print 'num_solutions:', num_solutions - print 'failures:', solver.Failures() - print 'branches:', solver.Branches() - print 'WallTime:', solver.WallTime(), 'ms' + print + print 'num_solutions:', num_solutions + print 'failures:', solver.Failures() + print 'branches:', solver.Branches() + print 'WallTime:', solver.WallTime(), 'ms' if __name__ == '__main__': - main() + main() diff --git a/examples/python/secret_santa.py b/examples/python/secret_santa.py index 377e1b6268..5b8247e452 100644 --- a/examples/python/secret_santa.py +++ b/examples/python/secret_santa.py @@ -57,7 +57,8 @@ - WallTime: 23735 ms (note: without any printing of the solutions) This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ import sys from ortools.constraint_solver import pywrapcp @@ -65,53 +66,53 @@ from ortools.constraint_solver import pywrapcp def main(): - # Create the solver. - solver = pywrapcp.Solver('Secret Santa problem') + # Create the solver. + solver = pywrapcp.Solver('Secret Santa problem') - # - # data - # - family = [1,1,1,1, 2, 3,3,3,3,3, 4,4] - num_families = max(family) - n = len(family) + # + # data + # + family = [1, 1, 1, 1, 2, 3, 3, 3, 3, 3, 4, 4] + num_families = max(family) + n = len(family) - # - # declare variables - # - x = [solver.IntVar(0, n-1, 'x[%i]' % i) for i in range(n)] + # + # declare variables + # + x = [solver.IntVar(0, n - 1, 'x[%i]' % i) for i in range(n)] - # - # constraints - # - solver.Add(solver.AllDifferent(x)) + # + # constraints + # + solver.Add(solver.AllDifferent(x)) - # Can't be one own's Secret Santa - # Ensure that there are no fix-point in the array - for i in range(n): - solver.Add(x[i] != i) + # Can't be one own's Secret Santa + # Ensure that there are no fix-point in the array + for i in range(n): + solver.Add(x[i] != i) - # No Secret Santa to a person in the same family - for i in range(n): - solver.Add(family[i] != solver.Element(family, x[i])) + # No Secret Santa to a person in the same family + for i in range(n): + solver.Add(family[i] != solver.Element(family, x[i])) - # - # solution and search - # - db = solver.Phase(x, - solver.INT_VAR_SIMPLE, - solver.INT_VALUE_SIMPLE) + # + # solution and search + # + db = solver.Phase(x, + solver.INT_VAR_SIMPLE, + solver.INT_VALUE_SIMPLE) - solver.NewSearch(db) - num_solutions = 0 - while solver.NextSolution(): - num_solutions += 1 - print 'x:', [x[i].Value() for i in range(n)] - print + solver.NewSearch(db) + num_solutions = 0 + while solver.NextSolution(): + num_solutions += 1 + print 'x:', [x[i].Value() for i in range(n)] + print - print 'num_solutions:', num_solutions - print 'failures:', solver.Failures() - print 'branches:', solver.Branches() - print 'WallTime:', solver.WallTime(), 'ms' + print 'num_solutions:', num_solutions + print 'failures:', solver.Failures() + print 'branches:', solver.Branches() + print 'WallTime:', solver.WallTime(), 'ms' if __name__ == '__main__': - main() + main() diff --git a/examples/python/secret_santa2.py b/examples/python/secret_santa2.py index 334b7cf270..bb7339bd83 100644 --- a/examples/python/secret_santa2.py +++ b/examples/python/secret_santa2.py @@ -58,7 +58,8 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ import sys @@ -67,159 +68,154 @@ from ortools.constraint_solver import pywrapcp def main(singe=0): - # Create the solver. - solver = pywrapcp.Solver('Secret Santa problem II') + # Create the solver. + solver = pywrapcp.Solver('Secret Santa problem II') - # - # data - # + # + # data + # - # - # The matrix version of earlier rounds. - # M means that no earlier Santa has been assigned. - # Note: Ryan and Mia has the same recipient for years 3 and 4, - # and Ella and John has for year 4. - # This seems to be caused by modification of - # original data. - # - n_no_single = 8 - M = n_no_single + 1 - rounds_no_single = [ - # N A R M El J L Ev - [0, M, 3, M, 1, 4, M, 2], # Noah - [M, 0, 4, 2, M, 3, M, 1], # Ava - [M, 2, 0, M, 1, M, 3, 4], # Ryan - [M, 1, M, 0, 2, M, 3, 4], # Mia - [M, 4, M, 3, 0, M, 1, 2], # Ella - [1, 4, 3, M, M, 0, 2, M], # John - [M, 3, M, 2, 4, 1, 0, M], # Lily - [4, M, 3, 1, M, 2, M, 0] # Evan - ] + # + # The matrix version of earlier rounds. + # M means that no earlier Santa has been assigned. + # Note: Ryan and Mia has the same recipient for years 3 and 4, + # and Ella and John has for year 4. + # This seems to be caused by modification of + # original data. + # + n_no_single = 8 + M = n_no_single + 1 + rounds_no_single = [ + # N A R M El J L Ev + [0, M, 3, M, 1, 4, M, 2], # Noah + [M, 0, 4, 2, M, 3, M, 1], # Ava + [M, 2, 0, M, 1, M, 3, 4], # Ryan + [M, 1, M, 0, 2, M, 3, 4], # Mia + [M, 4, M, 3, 0, M, 1, 2], # Ella + [1, 4, 3, M, M, 0, 2, M], # John + [M, 3, M, 2, 4, 1, 0, M], # Lily + [4, M, 3, 1, M, 2, M, 0] # Evan + ] - # - # Rounds with a single person (fake data) - # - n_with_single = 9 - M = n_with_single + 1 - rounds_single = [ - # N A R M El J L Ev S - [0, M, 3, M, 1, 4, M, 2, 2], # Noah - [M, 0, 4, 2, M, 3, M, 1, 1], # Ava - [M, 2, 0, M, 1, M, 3, 4, 4], # Ryan - [M, 1, M, 0, 2, M, 3, 4, 3], # Mia - [M, 4, M, 3, 0, M, 1, 2, M], # Ella - [1, 4, 3, M, M, 0, 2, M, M], # John - [M, 3, M, 2, 4, 1, 0, M, M], # Lily - [4, M, 3, 1, M, 2, M, 0, M], # Evan - [1, 2, 3, 4, M, 2, M, M, 0] # Single - ] + # + # Rounds with a single person (fake data) + # + n_with_single = 9 + M = n_with_single + 1 + rounds_single = [ + # N A R M El J L Ev S + [0, M, 3, M, 1, 4, M, 2, 2], # Noah + [M, 0, 4, 2, M, 3, M, 1, 1], # Ava + [M, 2, 0, M, 1, M, 3, 4, 4], # Ryan + [M, 1, M, 0, 2, M, 3, 4, 3], # Mia + [M, 4, M, 3, 0, M, 1, 2, M], # Ella + [1, 4, 3, M, M, 0, 2, M, M], # John + [M, 3, M, 2, 4, 1, 0, M, M], # Lily + [4, M, 3, 1, M, 2, M, 0, M], # Evan + [1, 2, 3, 4, M, 2, M, M, 0] # Single + ] + if single == 1: + n = n_with_single + Noah, Ava, Ryan, Mia, Ella, John, Lily, Evan, Single = range(n) + rounds = rounds_single + else: + n = n_no_single + Noah, Ava, Ryan, Mia, Ella, John, Lily, Evan = range(n) + rounds = rounds_no_single - if single == 1: - n = n_with_single - Noah, Ava, Ryan, Mia, Ella, John, Lily, Evan, Single = range(n) - rounds = rounds_single - else: - n = n_no_single - Noah, Ava, Ryan, Mia, Ella, John, Lily, Evan = range(n) - rounds = rounds_no_single + M = n + 1 - M = n + 1 + persons = ['Noah', 'Ava', 'Ryan', 'Mia', 'Ella', + 'John', 'Lily', 'Evan', 'Single'] - persons = ['Noah', 'Ava', 'Ryan', 'Mia', 'Ella', - 'John', 'Lily', 'Evan', 'Single'] + spouses = [ + Ava, # Noah + Noah, # Ava + Mia, # Rya + Ryan, # Mia + John, # Ella + Ella, # John + Evan, # Lily + Lily, # Evan + -1 # Single has no spouse + ] - spouses = [ - Ava, # Noah - Noah, # Ava - Mia, # Rya - Ryan, # Mia - John, # Ella - Ella, # John - Evan, # Lily - Lily, # Evan - -1 # Single has no spouse - ] + # + # declare variables + # + santas = [solver.IntVar(0, n - 1, 'santas[%i]' % i) + for i in range(n)] + santa_distance = [solver.IntVar(0, M, 'santa_distance[%i]' % i) + for i in range(n)] + # total of 'distance', to maximize + z = solver.IntVar(0, n * n * n, 'z') + # + # constraints + # + solver.Add(solver.AllDifferent(santas)) - # - # declare variables - # - santas = [solver.IntVar(0, n-1, 'santas[%i]' % i) - for i in range(n)] - santa_distance = [solver.IntVar(0, M, 'santa_distance[%i]' % i) - for i in range(n)] + solver.Add(z == solver.Sum(santa_distance)) - # total of 'distance', to maximize - z = solver.IntVar(0, n*n*n, 'z') + # Can't be one own's Secret Santa + # (i.e. ensure that there are no fix-point in the array.) + for i in range(n): + solver.Add(santas[i] != i) - # - # constraints - # - solver.Add(solver.AllDifferent(santas)) + # no Santa for a spouses + for i in range(n): + if spouses[i] > -1: + solver.Add(santas[i] != spouses[i]) - solver.Add(z == solver.Sum(santa_distance)) + # optimize 'distance' to earlier rounds: + for i in range(n): + solver.Add(santa_distance[i] == + solver.Element(rounds[i], santas[i])) - # Can't be one own's Secret Santa - # (i.e. ensure that there are no fix-point in the array.) + # cannot be a Secret Santa for the same person + # two years in a row. + for i in range(n): + for j in range(n): + if rounds[i][j] == 1: + solver.Add(santas[i] != j) + + # objective + objective = solver.Maximize(z, 1) + + # + # solution and search + # + db = solver.Phase(santas, + solver.CHOOSE_MIN_SIZE_LOWEST_MIN, + solver.ASSIGN_CENTER_VALUE) + + solver.NewSearch(db, [objective]) + + num_solutions = 0 + while solver.NextSolution(): + num_solutions += 1 + print 'total distances:', z.Value() + print 'santas:', [santas[i].Value() for i in range(n)] for i in range(n): - solver.Add(santas[i] != i) + print '%s\tis a Santa to %s (distance %i)' % \ + (persons[i], + persons[santas[i].Value()], + santa_distance[i].Value()) + # print 'distance:', [santa_distance[i].Value() + # for i in range(n)] + print - - # no Santa for a spouses - for i in range(n): - if spouses[i] > -1 : - solver.Add(santas[i] != spouses[i]) - - # optimize 'distance' to earlier rounds: - for i in range(n): - solver.Add(santa_distance[i] == - solver.Element(rounds[i], santas[i])) - - - # cannot be a Secret Santa for the same person - # two years in a row. - for i in range(n): - for j in range(n): - if rounds[i][j] == 1: - solver.Add(santas[i] != j) - - # objective - objective = solver.Maximize(z, 1) - - # - # solution and search - # - db = solver.Phase(santas, - solver.CHOOSE_MIN_SIZE_LOWEST_MIN, - solver.ASSIGN_CENTER_VALUE) - - solver.NewSearch(db, [objective]) - - num_solutions = 0 - while solver.NextSolution(): - num_solutions += 1 - print 'total distances:', z.Value() - print 'santas:', [santas[i].Value() for i in range(n)] - for i in range(n): - print '%s\tis a Santa to %s (distance %i)' % \ - (persons[i], - persons[santas[i].Value()], - santa_distance[i].Value()) - # print 'distance:', [santa_distance[i].Value() - # for i in range(n)] - print - - print 'num_solutions:', num_solutions - print 'failures:', solver.Failures() - print 'branches:', solver.Branches() - print 'WallTime:', solver.WallTime(), 'ms' + print 'num_solutions:', num_solutions + print 'failures:', solver.Failures() + print 'branches:', solver.Branches() + print 'WallTime:', solver.WallTime(), 'ms' single = 0 if __name__ == '__main__': - print 'Secret Santas without single' - main(single) - print '\nSecret Santas with single:' - single = 1 - main(single) + print 'Secret Santas without single' + main(single) + print '\nSecret Santas with single:' + single = 1 + main(single) diff --git a/examples/python/send_more_money_any_base.py b/examples/python/send_more_money_any_base.py index 2ba0bd4b79..fcab37b865 100644 --- a/examples/python/send_more_money_any_base.py +++ b/examples/python/send_more_money_any_base.py @@ -38,7 +38,8 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ @@ -46,71 +47,68 @@ import sys import string from ortools.constraint_solver import pywrapcp + def main(base=10): - # Create the solver. - solver = pywrapcp.Solver('Send most money') + # Create the solver. + solver = pywrapcp.Solver('Send most money') - # data - print "base:", base + # data + print 'base:', base - # declare variables - s = solver.IntVar(0,base-1,'s') - e = solver.IntVar(0,base-1,'e') - n = solver.IntVar(0,base-1,'n') - d = solver.IntVar(0,base-1,'d') - m = solver.IntVar(0,base-1,'m') - o = solver.IntVar(0,base-1,'o') - r = solver.IntVar(0,base-1,'r') - y = solver.IntVar(0,base-1,'y') + # declare variables + s = solver.IntVar(0, base - 1, 's') + e = solver.IntVar(0, base - 1, 'e') + n = solver.IntVar(0, base - 1, 'n') + d = solver.IntVar(0, base - 1, 'd') + m = solver.IntVar(0, base - 1, 'm') + o = solver.IntVar(0, base - 1, 'o') + r = solver.IntVar(0, base - 1, 'r') + y = solver.IntVar(0, base - 1, 'y') - x = [s,e,n,d,m,o,r,y] + x = [s, e, n, d, m, o, r, y] + # + # constraints + # + solver.Add(solver.AllDifferent(x)) + solver.Add(s * base ** 3 + e * base ** 2 + n * base + d + + m * base ** 3 + o * base ** 2 + r * base + e == + m * base ** 4 + o * base ** 3 + n * base ** 2 + e * base + y,) + solver.Add(s > 0) + solver.Add(m > 0) + # + # solution and search + # + solution = solver.Assignment() + solution.Add(x) - # - # constraints - # - solver.Add(solver.AllDifferent(x)) - solver.Add( s*base**3 + e*base**2 + n*base + d + - m*base**3 + o*base**2 + r*base + e == - m*base**4 + o*base**3 + n*base**2 + e*base + y, - ) - solver.Add(s > 0) - solver.Add(m > 0) + collector = solver.AllSolutionCollector(solution) + solver.Solve(solver.Phase(x, + solver.CHOOSE_FIRST_UNBOUND, + solver.ASSIGN_MAX_VALUE), + [collector]) - # - # solution and search - # - solution = solver.Assignment() - solution.Add(x) + num_solutions = collector.SolutionCount() + money_val = 0 + for s in range(num_solutions): + print 'x:', [collector.Value(s, x[i]) for i in range(len(x))] - collector = solver.AllSolutionCollector(solution) - - solver.Solve(solver.Phase(x, - solver.CHOOSE_FIRST_UNBOUND, - solver.ASSIGN_MAX_VALUE), - [collector]) - - num_solutions = collector.SolutionCount() - money_val = 0 - for s in range(num_solutions): - print "x:", [collector.Value(s, x[i]) for i in range(len(x))] - - print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() - print + print + print 'num_solutions:', num_solutions + print 'failures:', solver.Failures() + print 'branches:', solver.Branches() + print 'WallTime:', solver.WallTime() + print base = 10 if __name__ == '__main__': - # for base in range(10,30): - # main(base) - if len(sys.argv) > 1: - base=string.atoi(sys.argv[1]) + # for base in range(10,30): + # main(base) + if len(sys.argv) > 1: + base = string.atoi(sys.argv[1]) - main(base) + main(base) diff --git a/examples/python/send_most_money.py b/examples/python/send_most_money.py index 43a7d3e1ec..4ae26e658e 100644 --- a/examples/python/send_most_money.py +++ b/examples/python/send_most_money.py @@ -34,93 +34,90 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ from ortools.constraint_solver import pywrapcp + def main(MONEY=0): - # Create the solver. - solver = pywrapcp.Solver('Send most money') + # Create the solver. + solver = pywrapcp.Solver('Send most money') - # data + # data + # declare variables + s = solver.IntVar(0, 9, 's') + e = solver.IntVar(0, 9, 'e') + n = solver.IntVar(0, 9, 'n') + d = solver.IntVar(0, 9, 'd') + m = solver.IntVar(0, 9, 'm') + o = solver.IntVar(0, 9, 'o') + t = solver.IntVar(0, 9, 't') + y = solver.IntVar(0, 9, 'y') + money = solver.IntVar(0, 100000, 'money') - # declare variables - s = solver.IntVar(0,9,'s') - e = solver.IntVar(0,9,'e') - n = solver.IntVar(0,9,'n') - d = solver.IntVar(0,9,'d') - m = solver.IntVar(0,9,'m') - o = solver.IntVar(0,9,'o') - t = solver.IntVar(0,9,'t') - y = solver.IntVar(0,9,'y') - money = solver.IntVar(0,100000,'money') + x = [s, e, n, d, m, o, t, y] - x = [s,e,n,d,m,o,t,y] + # + # constraints + # + if MONEY > 0: + solver.Add(money == MONEY) + solver.Add(solver.AllDifferent(x)) + solver.Add(money == m * 10000 + o * 1000 + n * 100 + e * 10 + y) + solver.Add(money > 0) + solver.Add(1000 * s + 100 * e + 10 * n + d + + 1000 * m + 100 * o + 10 * s + t == + money) + solver.Add(s > 0) + solver.Add(m > 0) + # + # solution and search + # + solution = solver.Assignment() + solution.Add(x) + solution.Add(money) - # - # constraints - # - if MONEY > 0: - solver.Add(money == MONEY) + collector = solver.AllSolutionCollector(solution) + objective = solver.Maximize(money, 100) + cargs = [collector] + if MONEY == 0: + objective = solver.Maximize(money, 1) + cargs.extend([objective]) - solver.Add(solver.AllDifferent(x)) - solver.Add(money == m*10000 + o*1000 + n*100 + e*10 + y) - solver.Add(money > 0) - solver.Add(1000*s + 100*e + 10*n + d + - 1000*m + 100*o + 10*s + t == - money) - solver.Add(s > 0) - solver.Add(m > 0) + solver.Solve(solver.Phase(x, + solver.CHOOSE_FIRST_UNBOUND, + solver.ASSIGN_MAX_VALUE), + cargs) + num_solutions = collector.SolutionCount() + money_val = 0 + for s in range(num_solutions): + print 'x:', [collector.Value(s, x[i]) for i in range(len(x))] + money_val = collector.Value(s, money) + print 'money:', money_val + print - # - # solution and search - # - solution = solver.Assignment() - solution.Add(x) - solution.Add(money) - - collector = solver.AllSolutionCollector(solution) - objective = solver.Maximize(money, 100) - cargs = [collector] - if MONEY == 0: - objective = solver.Maximize(money, 1) - cargs.extend([objective]) - - solver.Solve(solver.Phase(x, - solver.CHOOSE_FIRST_UNBOUND, - solver.ASSIGN_MAX_VALUE), - cargs) - - num_solutions = collector.SolutionCount() - money_val = 0 - for s in range(num_solutions): - print "x:", [collector.Value(s, x[i]) for i in range(len(x))] - money_val = collector.Value(s, money) - print "money:", money_val - print - - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() - - if MONEY == 0: - return money_val + print 'num_solutions:', num_solutions + print 'failures:', solver.Failures() + print 'branches:', solver.Branches() + print 'WallTime:', solver.WallTime() + if MONEY == 0: + return money_val if __name__ == '__main__': - # First get the maximised MONEY, and then show all solutions for - # this value - print "Minimize money..." - money = main(0) - print "\nCheck all solutions for money=%i" % money - main(money) + # First get the maximised MONEY, and then show all solutions for + # this value + print 'Minimize money...' + money = main(0) + print '\nCheck all solutions for money=%i' % money + main(money) diff --git a/examples/python/sendmore.py b/examples/python/sendmore.py index 8dff4c9272..d6c35e7875 100644 --- a/examples/python/sendmore.py +++ b/examples/python/sendmore.py @@ -20,7 +20,6 @@ Each letter corresponds to one figure and all letters have different values. """ - from google.apputils import app import gflags from ortools.constraint_solver import pywrapcp @@ -44,8 +43,8 @@ def main(unused_argv): letters = [s, e, n, d, m, o, r, y] - solver.Add(1000*s + 100*e + 10*n + d + 1000*m + 100*o + 10*r + e == - 10000*m + 1000*o + 100*n + 10*e + y) + solver.Add(1000 * s + 100 * e + 10 * n + d + 1000 * m + 100 * o + 10 * r + e == + 10000 * m + 1000 * o + 100 * n + 10 * e + y) # pylint: disable=g-explicit-bool-comparison solver.Add(s != 0) diff --git a/examples/python/seseman.py b/examples/python/seseman.py index 47f95d44bd..382d4de142 100644 --- a/examples/python/seseman.py +++ b/examples/python/seseman.py @@ -51,87 +51,89 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ from ortools.constraint_solver import pywrapcp + def main(unused_argv): - # Create the solver. - solver = pywrapcp.Solver('Seseman Convent problem') + # Create the solver. + solver = pywrapcp.Solver("Seseman Convent problem") - # data - n = 3 - border_sum = n*n + # data + n = 3 + border_sum = n * n - # declare variables - total_sum = solver.IntVar(1,n*n*n*n, 'total_sum') - # x[0..n-1,0..n-1] - x = {} + # declare variables + total_sum = solver.IntVar(1, n * n * n * n, "total_sum") + # x[0..n-1,0..n-1] + x = {} + for i in range(n): + for j in range(n): + x[(i, j)] = solver.IntVar(0, n * n, "x %i %i" % (i, j)) + + # + # constraints + # + # zero all middle cells + for i in range(1, n - 1): + for j in range(1, n - 1): + solver.Add(x[(i, j)] == 0) + + # all borders must be >= 1 + for i in range(n): + for j in range(n): + if i == 0 or j == 0 or i == n - 1 or j == n - 1: + solver.Add(x[(i, j)] >= 1) + + # sum the borders (border_sum) + solver.Add(solver.Sum([x[(i, 0)] for i in range(n)]) == border_sum) + solver.Add(solver.Sum([x[(i, n - 1)] for i in range(n)]) == border_sum) + solver.Add(solver.Sum([x[(0, i)] for i in range(n)]) == border_sum) + solver.Add(solver.Sum([x[(n - 1, i)] for i in range(n)]) == border_sum) + + # total + solver.Add( + solver.Sum([x[(i, j)] for i in range(n) for j in range(n)]) == + total_sum) + + # + # solution and search + # + solution = solver.Assignment() + solution.Add([x[(i, j)] for i in range(n) for j in range(n)]) + solution.Add(total_sum) + + # all solutions + collector = solver.AllSolutionCollector(solution) + # search_log = solver.SearchLog(100, total_sum) + solver.Solve(solver.Phase([x[(i, j)] for i in range(n) for j in range(n)], + solver.CHOOSE_PATH, + solver.ASSIGN_MIN_VALUE), + [collector]) + #[collector, search_log]) + + num_solutions = collector.SolutionCount() + # print "x:", x + print "num_solutions:", num_solutions + print + for s in range(num_solutions): + # print [collector.Value(s, x[(i,j)]) + # for i in range(n) for j in range(n)] + print "total_sum:", collector.Value(s, total_sum) for i in range(n): - for j in range(n): - x[(i,j)] = solver.IntVar(0,n*n, 'x %i %i' % (i, j)) - - - # - # constraints - # - # zero all middle cells - for i in range(1,n-1): - for j in range(1,n-1): - solver.Add(x[(i,j)] == 0) - - # all borders must be >= 1 - for i in range(n): - for j in range(n): - if i == 0 or j == 0 or i == n-1 or j == n-1: - solver.Add(x[(i,j)] >= 1) - - - # sum the borders (border_sum) - solver.Add(solver.Sum([x[(i,0)] for i in range(n)]) == border_sum) - solver.Add(solver.Sum([x[(i,n-1)] for i in range(n)]) == border_sum) - solver.Add(solver.Sum([x[(0,i)] for i in range(n)]) == border_sum) - solver.Add(solver.Sum([x[(n-1,i)] for i in range(n)]) == border_sum) - - # total - solver.Add(solver.Sum([x[(i,j)] for i in range(n) for j in range(n)]) == total_sum) - - # - # solution and search - # - solution = solver.Assignment() - solution.Add([x[(i,j)] for i in range(n) for j in range(n)]) - solution.Add(total_sum) - - # all solutions - collector = solver.AllSolutionCollector(solution) - # search_log = solver.SearchLog(100, total_sum) - solver.Solve(solver.Phase([x[(i,j)] for i in range(n) for j in range(n)], - solver.CHOOSE_PATH, - solver.ASSIGN_MIN_VALUE), - [collector]) - #[collector, search_log]) - - num_solutions = collector.SolutionCount() - # print "x:", x - print "num_solutions:", num_solutions + for j in range(n): + print collector.Value(s, x[(i, j)]), + print print - for s in range(num_solutions): - # print [collector.Value(s, x[(i,j)]) - # for i in range(n) for j in range(n)] - print "total_sum:", collector.Value(s, total_sum) - for i in range(n): - for j in range(n): - print collector.Value(s, x[(i,j)]), - print - print - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() - print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() + print "num_solutions:", num_solutions -if __name__ == '__main__': - main("cp sample") +if __name__ == "__main__": + main("cp sample") diff --git a/examples/python/seseman_b.py b/examples/python/seseman_b.py index 21f923f68d..d75daa8d1d 100644 --- a/examples/python/seseman_b.py +++ b/examples/python/seseman_b.py @@ -53,82 +53,83 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ from ortools.constraint_solver import pywrapcp + def main(unused_argv): - # Create the solver. - solver = pywrapcp.Solver('Seseman Convent problem') + # Create the solver. + solver = pywrapcp.Solver("Seseman Convent problem") - # data - n = 3 - border_sum = n*n + # data + n = 3 + border_sum = n * n - # declare variables - total_sum = solver.IntVar(1,n*n*n*n, 'total_sum') - # x[0..n-1,0..n-1] - x = {} + # declare variables + total_sum = solver.IntVar(1, n * n * n * n, "total_sum") + # x[0..n-1,0..n-1] + x = {} + for i in range(n): + for j in range(n): + x[(i, j)] = solver.IntVar(0, n * n, "x %i %i" % (i, j)) + + # + # constraints + # + # zero all middle cells + for i in range(1, n - 1): + for j in range(1, n - 1): + solver.Add(x[(i, j)] == 0) + + # all borders must be >= 1 + for i in range(n): + for j in range(n): + if i == 0 or j == 0 or i == n - 1 or j == n - 1: + solver.Add(x[(i, j)] >= 1) + + # sum the borders (border_sum) + solver.Add(solver.Sum([x[(i, 0)] for i in range(n)]) == border_sum) + solver.Add(solver.Sum([x[(i, n - 1)] for i in range(n)]) == border_sum) + solver.Add(solver.Sum([x[(0, i)] for i in range(n)]) == border_sum) + solver.Add(solver.Sum([x[(n - 1, i)] for i in range(n)]) == border_sum) + + # total + solver.Add( + solver.Sum([x[(i, j)] for i in range(n) for j in range(n)]) == + total_sum) + + # + # solution and search + # + solution = solver.Assignment() + solution.Add([x[(i, j)] for i in range(n) for j in range(n)]) + solution.Add(total_sum) + + db = solver.Phase([x[(i, j)] for i in range(n) for j in range(n)], + solver.CHOOSE_PATH, + solver.ASSIGN_MIN_VALUE) + + solver.NewSearch(db) + + num_solutions = 0 + + while solver.NextSolution(): + num_solutions += 1 + print "total_sum:", total_sum.Value() for i in range(n): - for j in range(n): - x[(i,j)] = solver.IntVar(0,n*n, 'x %i %i' % (i, j)) + for j in range(n): + print x[(i, j)].Value(), + print + print + + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() - # - # constraints - # - # zero all middle cells - for i in range(1,n-1): - for j in range(1,n-1): - solver.Add(x[(i,j)] == 0) - - # all borders must be >= 1 - for i in range(n): - for j in range(n): - if i == 0 or j == 0 or i == n-1 or j == n-1: - solver.Add(x[(i,j)] >= 1) - - - # sum the borders (border_sum) - solver.Add(solver.Sum([x[(i,0)] for i in range(n)]) == border_sum) - solver.Add(solver.Sum([x[(i,n-1)] for i in range(n)]) == border_sum) - solver.Add(solver.Sum([x[(0,i)] for i in range(n)]) == border_sum) - solver.Add(solver.Sum([x[(n-1,i)] for i in range(n)]) == border_sum) - - # total - solver.Add(solver.Sum([x[(i,j)] for i in range(n) for j in range(n)]) == total_sum) - - # - # solution and search - # - solution = solver.Assignment() - solution.Add([x[(i,j)] for i in range(n) for j in range(n)]) - solution.Add(total_sum) - - db = solver.Phase([x[(i,j)] for i in range(n) for j in range(n)], - solver.CHOOSE_PATH, - solver.ASSIGN_MIN_VALUE) - - solver.NewSearch(db) - - num_solutions = 0 - - while solver.NextSolution(): - num_solutions += 1 - print "total_sum:", total_sum.Value() - for i in range(n): - for j in range(n): - print x[(i,j)].Value(), - print - print - - - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() - - -if __name__ == '__main__': - main("cp sample") +if __name__ == "__main__": + main("cp sample") diff --git a/examples/python/set_covering.py b/examples/python/set_covering.py index d9d8d2f6c9..31dc9b1006 100644 --- a/examples/python/set_covering.py +++ b/examples/python/set_covering.py @@ -27,71 +27,73 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ from ortools.constraint_solver import pywrapcp + def main(unused_argv): - # Create the solver. - solver = pywrapcp.Solver('Set covering') + # Create the solver. + solver = pywrapcp.Solver("Set covering") - # - # data - # - min_distance = 15 - num_cities = 6 + # + # data + # + min_distance = 15 + num_cities = 6 - distance = [ - [ 0,10,20,30,30,20], - [10, 0,25,35,20,10], - [20,25, 0,15,30,20], - [30,35,15, 0,15,25], - [30,20,30,15, 0,14], - [20,10,20,25,14, 0] - ] + distance = [ + [0, 10, 20, 30, 30, 20], + [10, 0, 25, 35, 20, 10], + [20, 25, 0, 15, 30, 20], + [30, 35, 15, 0, 15, 25], + [30, 20, 30, 15, 0, 14], + [20, 10, 20, 25, 14, 0] + ] - # - # declare variables - # - x = [solver.IntVar(0,1, 'x[%i]' % i) for i in range(num_cities)] + # + # declare variables + # + x = [solver.IntVar(0, 1, "x[%i]" % i) for i in range(num_cities)] - # - # constraints - # + # + # constraints + # - # objective to minimize - z = solver.Sum(x) + # objective to minimize + z = solver.Sum(x) - # ensure that all cities are covered - for i in range(num_cities): - b = [x[j] for j in range(num_cities) if distance[i][j] <= min_distance] - solver.Add(solver.SumGreaterOrEqual(b, 1)) + # ensure that all cities are covered + for i in range(num_cities): + b = [x[j] for j in range(num_cities) if distance[i][j] <= min_distance] + solver.Add(solver.SumGreaterOrEqual(b, 1)) - objective = solver.Minimize(z, 1) + objective = solver.Minimize(z, 1) - # - # solution and search - # - solution = solver.Assignment() - solution.Add(x) - solution.AddObjective(z) + # + # solution and search + # + solution = solver.Assignment() + solution.Add(x) + solution.AddObjective(z) - collector = solver.LastSolutionCollector(solution) - solver.Solve(solver.Phase(x + [z], - solver.INT_VAR_DEFAULT, - solver.INT_VALUE_DEFAULT), - [collector, objective]) + collector = solver.LastSolutionCollector(solution) + solver.Solve(solver.Phase(x + [z], + solver.INT_VAR_DEFAULT, + solver.INT_VALUE_DEFAULT), + [collector, objective]) - print "z:", collector.ObjectiveValue(0) - print "x:", [collector.Value(0, x[i]) for i in range(num_cities)] + print "z:", collector.ObjectiveValue(0) + print "x:", [collector.Value(0, x[i]) for i in range(num_cities)] - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() -if __name__ == '__main__': - main("cp sample") +if __name__ == "__main__": + main("cp sample") diff --git a/examples/python/set_covering2.py b/examples/python/set_covering2.py index 2830d3ba6d..ff9c5f110c 100644 --- a/examples/python/set_covering2.py +++ b/examples/python/set_covering2.py @@ -29,79 +29,80 @@ * Gecode: http://hakank.org/gecode/set_covering2.cpp This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ from ortools.constraint_solver import pywrapcp + def main(unused_argv): - # Create the solver. - solver = pywrapcp.Solver('Set covering') + # Create the solver. + solver = pywrapcp.Solver("Set covering") - # - # data - # - n = 8 # maximum number of corners - num_streets = 11 # number of connected streets + # + # data + # + n = 8 # maximum number of corners + num_streets = 11 # number of connected streets + + # corners of each street + # Note: 1-based (handled below) + corner = [ + [1, 2], + [2, 3], + [4, 5], + [7, 8], + [6, 7], + [2, 6], + [1, 6], + [4, 7], + [2, 4], + [5, 8], + [3, 5] + ] + + # + # declare variables + # + x = [solver.IntVar(0, 1, "x[%i]" % i) for i in range(n)] + + # + # constraints + # + + # number of telephones, to be minimized + z = solver.Sum(x) + + # ensure that all corners are covered + for i in range(num_streets): + # also, convert to 0-based + solver.Add(solver.SumGreaterOrEqual([x[j - 1] for j in corner[i]], 1)) + + objective = solver.Minimize(z, 1) + + # + # solution and search + # + solution = solver.Assignment() + solution.Add(x) + solution.AddObjective(z) + + collector = solver.LastSolutionCollector(solution) + solver.Solve(solver.Phase(x, + solver.INT_VAR_DEFAULT, + solver.INT_VALUE_DEFAULT), + [collector, objective]) + + print "z:", collector.ObjectiveValue(0) + print "x:", [collector.Value(0, x[i]) for i in range(n)] + + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() - # corners of each street - # Note: 1-based (handled below) - corner = [ - [1,2], - [2,3], - [4,5], - [7,8], - [6,7], - [2,6], - [1,6], - [4,7], - [2,4], - [5,8], - [3,5] - ] - - # - # declare variables - # - x = [solver.IntVar(0, 1, 'x[%i]' % i) for i in range(n)] - - # - # constraints - # - - # number of telephones, to be minimized - z = solver.Sum(x) - - # ensure that all corners are covered - for i in range(num_streets): - # also, convert to 0-based - solver.Add(solver.SumGreaterOrEqual([x[j - 1] for j in corner[i]], 1)) - - objective = solver.Minimize(z, 1) - - # - # solution and search - # - solution = solver.Assignment() - solution.Add(x) - solution.AddObjective(z) - - collector = solver.LastSolutionCollector(solution) - solver.Solve(solver.Phase(x, - solver.INT_VAR_DEFAULT, - solver.INT_VALUE_DEFAULT), - [collector, objective]) - - print "z:", collector.ObjectiveValue(0) - print "x:", [collector.Value(0, x[i]) for i in range(n)] - - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() - - -if __name__ == '__main__': - main("cp sample") +if __name__ == "__main__": + main("cp sample") diff --git a/examples/python/set_covering3.py b/examples/python/set_covering3.py index ffe0423b0a..2a2b43684c 100644 --- a/examples/python/set_covering3.py +++ b/examples/python/set_covering3.py @@ -42,84 +42,85 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ from ortools.constraint_solver import pywrapcp + def main(unused_argv): - # Create the solver. - solver = pywrapcp.Solver('Set covering') + # Create the solver. + solver = pywrapcp.Solver("Set covering") - # - # data - # - num_groups = 6 - num_senators = 10 + # + # data + # + num_groups = 6 + num_senators = 10 - # which group does a senator belong to? - belongs = [ - [1, 1, 1, 1, 1, 0, 0, 0, 0, 0], # 1 southern - [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], # 2 northern - [0, 1, 1, 0, 0, 0, 0, 1, 1, 1], # 3 liberals - [1, 0, 0, 0, 1, 1, 1, 0, 0, 0], # 4 conservative - [0, 0, 1, 1, 1, 1, 1, 0, 1, 0], # 5 democrats - [1, 1, 0, 0, 0, 0, 0, 1, 0, 1] # 6 republicans - ] + # which group does a senator belong to? + belongs = [ + [1, 1, 1, 1, 1, 0, 0, 0, 0, 0], # 1 southern + [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], # 2 northern + [0, 1, 1, 0, 0, 0, 0, 1, 1, 1], # 3 liberals + [1, 0, 0, 0, 1, 1, 1, 0, 0, 0], # 4 conservative + [0, 0, 1, 1, 1, 1, 1, 0, 1, 0], # 5 democrats + [1, 1, 0, 0, 0, 0, 0, 1, 0, 1] # 6 republicans + ] + + # + # declare variables + # + x = [solver.IntVar(0, 1, "x[%i]" % i) for i in range(num_senators)] + + # + # constraints + # + + # number of assigned senators (to minimize) + z = solver.Sum(x) + + # ensure that each group is covered by at least + # one senator + for i in range(num_groups): + solver.Add( + solver.SumGreaterOrEqual([x[j] * belongs[i][j] + for j in range(num_senators)], + 1)) + + objective = solver.Minimize(z, 1) + + # + # solution and search + # + solution = solver.Assignment() + solution.Add(x) + solution.AddObjective(z) + + collector = solver.LastSolutionCollector(solution) + solver.Solve(solver.Phase(x, + solver.INT_VAR_DEFAULT, + solver.INT_VALUE_DEFAULT), + [collector, objective]) + + print "z:", collector.ObjectiveValue(0) + print "x:", [collector.Value(0, x[i]) for i in range(num_senators)] + for j in range(num_senators): + if collector.Value(0, x[j]) == 1: + print "Senator", j + 1, "belongs to these groups:", + for i in range(num_groups): + if belongs[i][j] == 1: + print i + 1, + print + + print + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() - # - # declare variables - # - x = [solver.IntVar(0, 1, 'x[%i]' % i) for i in range(num_senators)] - - # - # constraints - # - - # number of assigned senators (to minimize) - z = solver.Sum(x) - - # ensure that each group is covered by at least - # one senator - for i in range(num_groups): - solver.Add( - solver.SumGreaterOrEqual([x[j]*belongs[i][j] - for j in range(num_senators)], - 1)) - - objective = solver.Minimize(z, 1) - - # - # solution and search - # - solution = solver.Assignment() - solution.Add(x) - solution.AddObjective(z) - - collector = solver.LastSolutionCollector(solution) - solver.Solve(solver.Phase(x, - solver.INT_VAR_DEFAULT, - solver.INT_VALUE_DEFAULT), - [collector, objective]) - - print "z:", collector.ObjectiveValue(0) - print "x:", [collector.Value(0, x[i]) for i in range(num_senators)] - for j in range(num_senators): - if collector.Value(0, x[j]) == 1: - print "Senator", j+1, "belongs to these groups:", - for i in range(num_groups): - if belongs[i][j] == 1: - print i + 1, - print - - print - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() - - -if __name__ == '__main__': - main("cp sample") +if __name__ == "__main__": + main("cp sample") diff --git a/examples/python/set_covering4.py b/examples/python/set_covering4.py index 909c5c8a7c..4eb6f2b291 100644 --- a/examples/python/set_covering4.py +++ b/examples/python/set_covering4.py @@ -62,95 +62,96 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ from ortools.constraint_solver import pywrapcp + def main(set_partition=1): - # Create the solver. - solver = pywrapcp.Solver('Set partition and set covering') + # Create the solver. + solver = pywrapcp.Solver("Set partition and set covering") - # - # data - # - num_alternatives = 10 - num_objects = 8 + # + # data + # + num_alternatives = 10 + num_objects = 8 - # costs for the alternatives - costs = [ 19, 16, 18, 13, 15, 19, 15, 17, 16, 15]; + # costs for the alternatives + costs = [19, 16, 18, 13, 15, 19, 15, 17, 16, 15] - # the alternatives, and their objects - a = [ + # the alternatives, and their objects + a = [ # 1 2 3 4 5 6 7 8 the objects - [1,0,0,0,0,1,0,0], # alternative 1 - [0,1,0,0,0,1,0,1], # alternative 2 - [1,0,0,1,0,0,1,0], # alternative 3 - [0,1,1,0,1,0,0,0], # alternative 4 - [0,1,0,0,1,0,0,0], # alternative 5 - [0,1,1,0,0,0,0,0], # alternative 6 - [0,1,1,1,0,0,0,0], # alternative 7 - [0,0,0,1,1,0,0,1], # alternative 8 - [0,0,1,0,0,1,0,1], # alternative 9 - [1,0,0,0,0,1,1,0] # alternative 10 - ] + [1, 0, 0, 0, 0, 1, 0, 0], # alternative 1 + [0, 1, 0, 0, 0, 1, 0, 1], # alternative 2 + [1, 0, 0, 1, 0, 0, 1, 0], # alternative 3 + [0, 1, 1, 0, 1, 0, 0, 0], # alternative 4 + [0, 1, 0, 0, 1, 0, 0, 0], # alternative 5 + [0, 1, 1, 0, 0, 0, 0, 0], # alternative 6 + [0, 1, 1, 1, 0, 0, 0, 0], # alternative 7 + [0, 0, 0, 1, 1, 0, 0, 1], # alternative 8 + [0, 0, 1, 0, 0, 1, 0, 1], # alternative 9 + [1, 0, 0, 0, 0, 1, 1, 0] # alternative 10 + ] - # - # declare variables - # - x = [solver.IntVar(0, 1, 'x[%i]' % i) for i in range(num_alternatives)] + # + # declare variables + # + x = [solver.IntVar(0, 1, "x[%i]" % i) for i in range(num_alternatives)] - # - # constraints - # + # + # constraints + # - # sum the cost of the choosen alternative, - # to be minimized - z = solver.ScalProd(x,costs) + # sum the cost of the choosen alternative, + # to be minimized + z = solver.ScalProd(x, costs) - # - for j in range(num_objects): - if set_partition == 1: - solver.Add( - solver.SumGreaterOrEqual([x[i] * a[i][j] - for i in range(num_alternatives)], - 1)) - else: - solver.Add( - solver.SumGreaterOrEqual([x[i] * a[i][j] - for i in range(num_alternatives)], - 1)) + # + for j in range(num_objects): + if set_partition == 1: + solver.Add( + solver.SumGreaterOrEqual([x[i] * a[i][j] + for i in range(num_alternatives)], + 1)) + else: + solver.Add( + solver.SumGreaterOrEqual([x[i] * a[i][j] + for i in range(num_alternatives)], + 1)) + + objective = solver.Minimize(z, 1) + + # + # solution and search + # + solution = solver.Assignment() + solution.Add(x) + solution.AddObjective(z) + + collector = solver.LastSolutionCollector(solution) + solver.Solve(solver.Phase([x[i] for i in range(num_alternatives)], + solver.INT_VAR_DEFAULT, + solver.INT_VALUE_DEFAULT), + [collector, objective]) + + print "z:", collector.ObjectiveValue(0) + print "selected alternatives:", [i + 1 for i in range(num_alternatives) + if collector.Value(0, x[i]) == 1] + + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() - objective = solver.Minimize(z, 1) +if __name__ == "__main__": + print "Set partition:" + main(1) - # - # solution and search - # - solution = solver.Assignment() - solution.Add(x) - solution.AddObjective(z) - - collector = solver.LastSolutionCollector(solution) - solver.Solve(solver.Phase([x[i] for i in range(num_alternatives)], - solver.INT_VAR_DEFAULT, - solver.INT_VALUE_DEFAULT), - [collector, objective]) - - print "z:", collector.ObjectiveValue(0) - print "selected alternatives:", [i + 1 for i in range(num_alternatives) - if collector.Value(0, x[i]) == 1] - - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() - - -if __name__ == '__main__': - print "Set partition:" - main(1) - - print "\nSet covering:" - main(0) + print "\nSet covering:" + main(0) diff --git a/examples/python/set_covering_deployment.py b/examples/python/set_covering_deployment.py index 0896a1ab40..63e6cb53ec 100644 --- a/examples/python/set_covering_deployment.py +++ b/examples/python/set_covering_deployment.py @@ -35,110 +35,110 @@ * SICStus : http://hakank.org/sicstus/set_covering_deployment.pl This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ from ortools.constraint_solver import pywrapcp + def main(): - # Create the solver. - solver = pywrapcp.Solver('Set covering deployment') + # Create the solver. + solver = pywrapcp.Solver("Set covering deployment") - # - # data - # + # + # data + # - countries = ["Alexandria", - "Asia Minor", - "Britain", - "Byzantium", - "Gaul", - "Iberia", - "Rome", - "Tunis"] - n = len(countries) + countries = ["Alexandria", + "Asia Minor", + "Britain", + "Byzantium", + "Gaul", + "Iberia", + "Rome", + "Tunis"] + n = len(countries) - # the incidence matrix (neighbours) - mat = [ - [0, 1, 0, 1, 0, 0, 1, 1], - [1, 0, 0, 1, 0, 0, 0, 0], - [0, 0, 0, 0, 1, 1, 0, 0], - [1, 1, 0, 0, 0, 0, 1, 0], - [0, 0, 1, 0, 0, 1, 1, 0], - [0, 0, 1, 0, 1, 0, 1, 1], - [1, 0, 0, 1, 1, 1, 0, 1], - [1, 0, 0, 0, 0, 1, 1, 0] - ] + # the incidence matrix (neighbours) + mat = [ + [0, 1, 0, 1, 0, 0, 1, 1], + [1, 0, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 1, 0, 0], + [1, 1, 0, 0, 0, 0, 1, 0], + [0, 0, 1, 0, 0, 1, 1, 0], + [0, 0, 1, 0, 1, 0, 1, 1], + [1, 0, 0, 1, 1, 1, 0, 1], + [1, 0, 0, 0, 0, 1, 1, 0] + ] + + # + # declare variables + # + + # First army + X = [solver.IntVar(0, 1, "X[%i]" % i) for i in range(n)] + + # Second (reserv) army + Y = [solver.IntVar(0, 1, "Y[%i]" % i) for i in range(n)] + + # + # constraints + # + + # total number of armies + num_armies = solver.Sum([X[i] + Y[i] for i in range(n)]) + + # + # Constraint 1: There is always an army in a city + # (+ maybe a backup) + # Or rather: Is there a backup, there + # must be an an army + # + [solver.Add(X[i] >= Y[i]) for i in range(n)] + + # + # Constraint 2: There should always be an backup army near every city + # + for i in range(n): + neighbors = solver.Sum([Y[j] for j in range(n) if mat[i][j] == 1]) + solver.Add(X[i] + neighbors >= 1) + + objective = solver.Minimize(num_armies, 1) + + # + # solution and search + # + solution = solver.Assignment() + solution.Add(X) + solution.Add(Y) + solution.Add(num_armies) + solution.AddObjective(num_armies) + + collector = solver.LastSolutionCollector(solution) + solver.Solve(solver.Phase(X + Y, + solver.INT_VAR_DEFAULT, + solver.INT_VALUE_DEFAULT), + [collector, objective]) + + print "num_armies:", collector.ObjectiveValue(0) + print "X:", [collector.Value(0, X[i]) for i in range(n)] + print "Y:", [collector.Value(0, Y[i]) for i in range(n)] + + for i in range(n): + if collector.Value(0, X[i]) == 1: + print "army:", countries[i], + if collector.Value(0, Y[i]) == 1: + print "reserv army:", countries[i], " " + print + + print + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() - # - # declare variables - # - - # First army - X = [solver.IntVar(0, 1, 'X[%i]' % i) for i in range(n)] - - # Second (reserv) army - Y = [solver.IntVar(0, 1, 'Y[%i]' % i) for i in range(n)] - - # - # constraints - # - - # total number of armies - num_armies = solver.Sum([X[i] + Y[i] for i in range(n)]) - - # - # Constraint 1: There is always an army in a city - # (+ maybe a backup) - # Or rather: Is there a backup, there - # must be an an army - # - [solver.Add(X[i] >= Y[i]) for i in range(n)] - - # - # Constraint 2: There should always be an backup army near every city - # - for i in range(n): - neighbors = solver.Sum([Y[j] for j in range(n) if mat[i][j] == 1]) - solver.Add(X[i] + neighbors >= 1) - - objective = solver.Minimize(num_armies, 1) - - # - # solution and search - # - solution = solver.Assignment() - solution.Add(X) - solution.Add(Y) - solution.Add(num_armies) - solution.AddObjective(num_armies) - - collector = solver.LastSolutionCollector(solution) - solver.Solve(solver.Phase(X + Y, - solver.INT_VAR_DEFAULT, - solver.INT_VALUE_DEFAULT), - [collector, objective]) - - print "num_armies:", collector.ObjectiveValue(0) - print "X:", [collector.Value(0, X[i]) for i in range(n)] - print "Y:", [collector.Value(0, Y[i]) for i in range(n)] - - for i in range(n): - if collector.Value(0, X[i]) == 1: - print "army:", countries[i], - if collector.Value(0, Y[i]) == 1: - print "reserv army:", countries[i], " " - print - - - print - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() - - -if __name__ == '__main__': - main() +if __name__ == "__main__": + main() diff --git a/examples/python/set_covering_skiena.py b/examples/python/set_covering_skiena.py index 5723f77316..1101341a66 100644 --- a/examples/python/set_covering_skiena.py +++ b/examples/python/set_covering_skiena.py @@ -36,7 +36,8 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ from ortools.constraint_solver import pywrapcp @@ -44,82 +45,79 @@ from ortools.constraint_solver import pywrapcp def main(): - # Create the solver. - solver = pywrapcp.Solver('Set covering Skiena') + # Create the solver. + solver = pywrapcp.Solver('Set covering Skiena') - # - # data - # - num_sets = 7 - num_elements = 12 - belongs = [ + # + # data + # + num_sets = 7 + num_elements = 12 + belongs = [ # 1 2 3 4 5 6 7 8 9 0 1 2 elements - [1,1,0,0,0,0,0,0,0,0,0,0], # Set 1 - [0,1,0,0,0,0,0,1,0,0,0,0], # 2 - [0,0,0,0,1,1,0,0,0,0,0,0], # 3 - [0,0,0,0,0,1,1,0,0,1,1,0], # 4 - [0,0,0,0,0,0,0,0,1,1,0,0], # 5 - [1,1,1,0,1,0,0,0,1,1,1,0], # 6 - [0,0,1,1,0,0,1,1,0,0,1,1] # 7 - ] + [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # Set 1 + [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0], # 2 + [0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0], # 3 + [0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0], # 4 + [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0], # 5 + [1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0], # 6 + [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1] # 7 + ] - # - # variables - # - x = [solver.IntVar(0, 1, 'x[%i]' % i) for i in range(num_sets)] + # + # variables + # + x = [solver.IntVar(0, 1, 'x[%i]' % i) for i in range(num_sets)] - # number of choosen sets - z = solver.IntVar(0, num_sets*2, 'z') + # number of choosen sets + z = solver.IntVar(0, num_sets * 2, 'z') - # total number of elements in the choosen sets - tot_elements = solver.IntVar(0, num_sets*num_elements) + # total number of elements in the choosen sets + tot_elements = solver.IntVar(0, num_sets * num_elements) + # + # constraints + # + solver.Add(z == solver.Sum(x)) - # - # constraints - # - solver.Add(z == solver.Sum(x)) + # all sets must be used + for j in range(num_elements): + s = solver.Sum([belongs[i][j] * x[i] for i in range(num_sets)]) + solver.Add(s >= 1) - # all sets must be used - for j in range(num_elements): - s = solver.Sum([belongs[i][j]*x[i] for i in range(num_sets)]) - solver.Add(s >= 1) + # number of used elements + solver.Add(tot_elements == + solver.Sum([x[i] * belongs[i][j] + for i in range(num_sets) + for j in range(num_elements)])) - # number of used elements - solver.Add(tot_elements == - solver.Sum([x[i]*belongs[i][j] - for i in range(num_sets) - for j in range(num_elements)])) + # objective + objective = solver.Minimize(z, 1) - # objective - objective = solver.Minimize(z, 1) + # + # search and result + # + db = solver.Phase(x, + solver.INT_VAR_DEFAULT, + solver.INT_VALUE_DEFAULT) - # - # search and result - # - db = solver.Phase(x, - solver.INT_VAR_DEFAULT, - solver.INT_VALUE_DEFAULT - ) + solver.NewSearch(db, [objective]) - solver.NewSearch(db, [objective]) + num_solutions = 0 + while solver.NextSolution(): + num_solutions += 1 + print 'z:', z.Value() + print 'tot_elements:', tot_elements.Value() + print 'x:', [x[i].Value() for i in range(num_sets)] + solver.EndSearch() - num_solutions = 0 - while solver.NextSolution(): - num_solutions += 1 - print "z:", z.Value() - print "tot_elements:", tot_elements.Value() - print 'x:', [x[i].Value() for i in range(num_sets)] - - solver.EndSearch() - - print - print 'num_solutions:', num_solutions - print 'failures:', solver.Failures() - print 'branches:', solver.Branches() - print 'WallTime:', solver.WallTime(), 'ms' + print + print 'num_solutions:', num_solutions + print 'failures:', solver.Failures() + print 'branches:', solver.Branches() + print 'WallTime:', solver.WallTime(), 'ms' if __name__ == '__main__': - main() + main() diff --git a/examples/python/set_partition.py b/examples/python/set_partition.py index 3e4db7fb29..954e9169da 100644 --- a/examples/python/set_partition.py +++ b/examples/python/set_partition.py @@ -42,7 +42,8 @@ * SICStus: http://hakank.org/sicstus/set_partition.pl This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ import sys @@ -54,129 +55,125 @@ from ortools.constraint_solver import pywrapcp # Partition the sets (binary matrix representation). # def partition_sets(x, num_sets, n): - solver = x.values()[0].solver() + solver = x.values()[0].solver() + + for i in range(num_sets): + for j in range(num_sets): + if i != j: + b = solver.Sum([x[i, k] * x[j, k] for k in range(n)]) + solver.Add(b == 0) + + # ensure that all integers is in + # (exactly) one partition + b = [x[i, j] for i in range(num_sets) for j in range(n)] + solver.Add(solver.Sum(b) == n) + + +def main(n=16, num_sets=2): + + # Create the solver. + solver = pywrapcp.Solver("Set partition") + + # + # data + # + print "n:", n + print "num_sets:", num_sets + print + + # Check sizes + assert n % num_sets == 0, "Equal sets is not possible." + + # + # variables + # + + # the set + a = {} + for i in range(num_sets): + for j in range(n): + a[i, j] = solver.IntVar(0, 1, "a[%i,%i]" % (i, j)) + + a_flat = [a[i, j] for i in range(num_sets) for j in range(n)] + + # + # constraints + # + + # partition set + partition_sets(a, num_sets, n) + + for i in range(num_sets): + for j in range(i, num_sets): + + # same cardinality + solver.Add(solver.Sum([a[i, k] for k in range(n)]) + == + solver.Sum([a[j, k] for k in range(n)])) + + # same sum + solver.Add(solver.Sum([k * a[i, k] for k in range(n)]) + == + solver.Sum([k * a[j, k] for k in range(n)])) + + # same sum squared + solver.Add(solver.Sum([(k * a[i, k]) * (k * a[i, k]) + for k in range(n)]) + == + solver.Sum([(k * a[j, k]) * (k * a[j, k]) + for k in range(n)])) + + # symmetry breaking for num_sets == 2 + if num_sets == 2: + solver.Add(a[0, 0] == 1) + + # + # search and result + # + db = solver.Phase(a_flat, + solver.INT_VAR_DEFAULT, + solver.INT_VALUE_DEFAULT) + + solver.NewSearch(db) + + num_solutions = 0 + while solver.NextSolution(): + a_val = {} + for i in range(num_sets): + for j in range(n): + a_val[i, j] = a[i, j].Value() + + sq = sum([(j + 1) * a_val[0, j] for j in range(n)]) + print "sums:", sq + sq2 = sum([((j + 1) * a_val[0, j]) ** 2 for j in range(n)]) + print "sums squared:", sq2 for i in range(num_sets): - for j in range(num_sets): - if i != j: - b = solver.Sum([x[i,k]*x[j,k] for k in range(n)]) - solver.Add(b == 0) - - # ensure that all integers is in - # (exactly) one partition - b = [x[i,j] for i in range(num_sets) for j in range(n) ] - solver.Add(solver.Sum(b) == n) - - -def main(n=16,num_sets=2): - - # Create the solver. - solver = pywrapcp.Solver('Set partition') - - # - # data - # - print "n:", n - print "num_sets:", num_sets - print - - # Check sizes - assert n % num_sets == 0, "Equal sets is not possible." - - # - # variables - # - - # the set - a = {} - for i in range(num_sets): + if sum([a_val[i, j] for j in range(n)]): + print i + 1, ":", for j in range(n): - a[i,j] = solver.IntVar(0, 1, 'a[%i,%i]' % (i,j)) - - a_flat = [a[i,j] for i in range(num_sets) for j in range(n)] - - # - # constraints - # - - # partition set - partition_sets(a, num_sets, n) - - for i in range(num_sets): - for j in range(i, num_sets): - - # same cardinality - solver.Add(solver.Sum([a[i,k] for k in range(n)]) - == - solver.Sum([a[j,k] for k in range(n)])) - - # same sum - solver.Add(solver.Sum([k*a[i,k] for k in range(n)]) - == - solver.Sum([k*a[j,k] for k in range(n)])) - - - # same sum squared - solver.Add(solver.Sum([(k*a[i,k])*(k*a[i,k]) - for k in range(n)]) - == - solver.Sum([(k*a[j,k])*(k*a[j,k]) - for k in range(n)])) - - - # symmetry breaking for num_sets == 2 - if num_sets == 2: - solver.Add(a[0,0] == 1) - - - # - # search and result - # - db = solver.Phase(a_flat, - solver.INT_VAR_DEFAULT, - solver.INT_VALUE_DEFAULT) - - solver.NewSearch(db) - - - num_solutions = 0 - while solver.NextSolution(): - a_val = {} - for i in range(num_sets): - for j in range(n): - a_val[i,j] = a[i,j].Value() - - sq = sum([(j+1)*a_val[0,j] for j in range(n)]) - print "sums:", sq - sq2 = sum([((j+1)*a_val[0,j])**2 for j in range(n)]) - print "sums squared:", sq2 - - for i in range(num_sets): - if sum([a_val[i,j] for j in range(n)]): - print i+1, ":", - for j in range(n): - if a_val[i,j] == 1: - print j+1, - print - + if a_val[i, j] == 1: + print j + 1, print - num_solutions += 1 - - solver.EndSearch() print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + num_solutions += 1 + + solver.EndSearch() + + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() n = 16 num_sets = 2 -if __name__ == '__main__': - if len(sys.argv) > 1: - n = int(sys.argv[1]) - if len(sys.argv) > 2: - num_sets = int(sys.argv[2]) +if __name__ == "__main__": + if len(sys.argv) > 1: + n = int(sys.argv[1]) + if len(sys.argv) > 2: + num_sets = int(sys.argv[2]) - main(n, num_sets) + main(n, num_sets) diff --git a/examples/python/sicherman_dice.py b/examples/python/sicherman_dice.py index c4fd893d9b..a0092bb5ef 100644 --- a/examples/python/sicherman_dice.py +++ b/examples/python/sicherman_dice.py @@ -56,7 +56,8 @@ * Gecode: http://hakank.org/gecode/sicherman_dice.cpp This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ import sys from ortools.constraint_solver import pywrapcp @@ -64,79 +65,76 @@ from ortools.constraint_solver import pywrapcp def main(): - # Create the solver. - solver = pywrapcp.Solver('Sicherman dice') + # Create the solver. + solver = pywrapcp.Solver("Sicherman dice") - # - # data - # - n = 6 - m = 10 + # + # data + # + n = 6 + m = 10 - # standard distribution - standard_dist = [1,2,3,4,5,6,5,4,3,2,1] + # standard distribution + standard_dist = [1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1] - # - # declare variables - # + # + # declare variables + # - # the two dice - x1 = [solver.IntVar(0, m,"x1(%i)"%i) for i in range(n)] - x2 = [solver.IntVar(0, m,"x2(%i)"%i) for i in range(n)] + # the two dice + x1 = [solver.IntVar(0, m, "x1(%i)" % i) for i in range(n)] + x2 = [solver.IntVar(0, m, "x2(%i)" % i) for i in range(n)] + # + # constraints + # + # [solver.Add(standard_dist[k] == solver.Sum([x1[i] + x2[j] == k+2 for i in range(n) for j in range(n)])) + # for k in range(len(standard_dist))] + for k in range(len(standard_dist)): + tmp = [solver.BoolVar() for i in range(n) for j in range(n)] + for i in range(n): + for j in range(n): + solver.Add(tmp[i * n + j] == solver.IsEqualCstVar(x1[i] + x2[j], k + 2)) + solver.Add(standard_dist[k] == solver.Sum(tmp)) - # - # constraints - # - # [solver.Add(standard_dist[k] == solver.Sum([x1[i] + x2[j] == k+2 for i in range(n) for j in range(n)])) - # for k in range(len(standard_dist))] - for k in range(len(standard_dist)): - tmp = [solver.BoolVar() for i in range(n) for j in range(n)] - for i in range(n): - for j in range(n): - solver.Add(tmp[i*n+j] == solver.IsEqualCstVar(x1[i] + x2[j],k+2)) - solver.Add(standard_dist[k] == solver.Sum(tmp)) + # symmetry breaking + [solver.Add(x1[i] <= x1[i + 1]) for i in range(n - 1)], + [solver.Add(x2[i] <= x2[i + 1]) for i in range(n - 1)], + [solver.Add(x1[i] <= x2[i]) for i in range(n - 1)], - # symmetry breaking - [solver.Add(x1[i] <= x1[i+1]) for i in range(n-1)], - [solver.Add(x2[i] <= x2[i+1]) for i in range(n-1)], - [solver.Add(x1[i] <= x2[i]) for i in range(n-1)], + # + # solution and search + # + solution = solver.Assignment() + solution.Add(x1) + solution.Add(x2) - # - # solution and search - # - solution = solver.Assignment() - solution.Add(x1) - solution.Add(x2) - - - # db: DecisionBuilder - db = solver.Phase(x1 + x2, - solver.INT_VAR_SIMPLE, - solver.ASSIGN_MIN_VALUE) - - solver.NewSearch(db) - num_solutions = 0 - while solver.NextSolution(): - print "x1:", [x1[i].Value() for i in range(n)] - print "x2:", [x2[i].Value() for i in range(n)] - print - - num_solutions += 1 - solver.EndSearch() + # db: DecisionBuilder + db = solver.Phase(x1 + x2, + solver.INT_VAR_SIMPLE, + solver.ASSIGN_MIN_VALUE) + solver.NewSearch(db) + num_solutions = 0 + while solver.NextSolution(): + print "x1:", [x1[i].Value() for i in range(n)] + print "x2:", [x2[i].Value() for i in range(n)] print - print "num_solutions:", num_solutions, "solver.solutions:", solver.solutions() - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() - print "MemoryUsage:", solver.MemoryUsage() - print "SearchDepth:", solver.SearchDepth() - print "SolveDepth:", solver.SolveDepth() - print "stamp:", solver.stamp() - print "solver", solver + + num_solutions += 1 + solver.EndSearch() + + print + print "num_solutions:", num_solutions, "solver.solutions:", solver.solutions() + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() + print "MemoryUsage:", solver.MemoryUsage() + print "SearchDepth:", solver.SearchDepth() + print "SolveDepth:", solver.SolveDepth() + print "stamp:", solver.stamp() + print "solver", solver -if __name__ == '__main__': - main() - +if __name__ == "__main__": + main() diff --git a/examples/python/simple_meeting.py b/examples/python/simple_meeting.py index ff9134c935..af43d41084 100644 --- a/examples/python/simple_meeting.py +++ b/examples/python/simple_meeting.py @@ -27,7 +27,6 @@ in the meeting and a maximum of non mandatory people are also in the meeting. """ - from google.apputils import app import gflags from ortools.constraint_solver import pywrapcp @@ -134,7 +133,7 @@ def main(unused_argv): disj = solver.DisjunctiveConstraint(calendar, 'room %d calendar' % r) all_rooms_calendars[r] = disj.SequenceVar() solver.Add(disj) - all_rooms_presence[r] = solver.BoolVar('presence of room %d' %r) + all_rooms_presence[r] = solver.BoolVar('presence of room %d' % r) # Objective: maximum number of people. objective = solver.Maximize(people_count, 1) diff --git a/examples/python/ski_assignment.py b/examples/python/ski_assignment.py index 9d55201ad2..b8b2affff7 100644 --- a/examples/python/ski_assignment.py +++ b/examples/python/ski_assignment.py @@ -45,7 +45,8 @@ * Gecode: http://hakank.org/gecode/ski_assignment.cpp This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ import sys @@ -55,69 +56,67 @@ from ortools.constraint_solver import pywrapcp def main(): - # Create the solver. - solver = pywrapcp.Solver('Ski assignment') + # Create the solver. + solver = pywrapcp.Solver('Ski assignment') - # - # data - # - num_skis = 6 - num_skiers = 5 - ski_heights = [1, 2, 5, 7, 13, 21] - skier_heights = [3, 4, 7, 11, 18] + # + # data + # + num_skis = 6 + num_skiers = 5 + ski_heights = [1, 2, 5, 7, 13, 21] + skier_heights = [3, 4, 7, 11, 18] + # + # variables + # - # - # variables - # + # which ski to choose for each skier + x = [solver.IntVar(0, num_skis - 1, 'x[%i]' % i) + for i in range(num_skiers)] + z = solver.IntVar(0, sum(ski_heights), 'z') - # which ski to choose for each skier - x = [solver.IntVar(0, num_skis-1, 'x[%i]' % i) - for i in range(num_skiers)] - z = solver.IntVar(0, sum(ski_heights), 'z') + # + # constraints + # + solver.Add(solver.AllDifferent(x)) - # - # constraints - # - solver.Add(solver.AllDifferent(x)) + z_tmp = [abs(solver.Element(ski_heights, x[i]) - skier_heights[i]) + for i in range(num_skiers)] + solver.Add(z == sum(z_tmp)) - z_tmp = [abs(solver.Element(ski_heights, x[i]) - skier_heights[i]) - for i in range(num_skiers)] - solver.Add(z == sum(z_tmp)) + # objective + objective = solver.Minimize(z, 1) - # objective - objective = solver.Minimize(z, 1) + # + # search and result + # + db = solver.Phase(x, + solver.INT_VAR_DEFAULT, + solver.INT_VALUE_DEFAULT) - # - # search and result - # - db = solver.Phase(x, - solver.INT_VAR_DEFAULT, - solver.INT_VALUE_DEFAULT) - - solver.NewSearch(db, [objective]) - - - num_solutions = 0 - while solver.NextSolution(): - num_solutions += 1 - print 'total differences:', z.Value() - for i in range(num_skiers): - x_val = x[i].Value() - ski_height = ski_heights[x[i].Value()] - diff = ski_height - skier_heights[i] - print 'Skier %i: Ski %i with length %2i (diff: %2i)' %\ - (i, x_val, ski_height, diff ) - print - - solver.EndSearch() + solver.NewSearch(db, [objective]) + num_solutions = 0 + while solver.NextSolution(): + num_solutions += 1 + print 'total differences:', z.Value() + for i in range(num_skiers): + x_val = x[i].Value() + ski_height = ski_heights[x[i].Value()] + diff = ski_height - skier_heights[i] + print 'Skier %i: Ski %i with length %2i (diff: %2i)' %\ + (i, x_val, ski_height, diff) print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + + solver.EndSearch() + + print + print 'num_solutions:', num_solutions + print 'failures:', solver.Failures() + print 'branches:', solver.Branches() + print 'WallTime:', solver.WallTime() if __name__ == '__main__': - main() + main() diff --git a/examples/python/stable_marriage.py b/examples/python/stable_marriage.py index eaaf51e8c0..a529622b75 100644 --- a/examples/python/stable_marriage.py +++ b/examples/python/stable_marriage.py @@ -34,99 +34,105 @@ * SICStus : http://hakank.org/sicstus/stable_marriage.pl This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ -import string, sys +import string +import sys from ortools.constraint_solver import pywrapcp def main(ranks, problem_name): - # Create the solver - solver = pywrapcp.Solver('Stable marriage') + # Create the solver + solver = pywrapcp.Solver("Stable marriage") - # - # data - # - print "Problem name:", problem_name + # + # data + # + print "Problem name:", problem_name - rankMen = ranks["rankMen"] - rankWomen = ranks["rankWomen"] + rankMen = ranks["rankMen"] + rankWomen = ranks["rankWomen"] - n = len(rankMen) + n = len(rankMen) - # - # declare variables - # - wife = [solver.IntVar(0, n-1, 'wife[%i]' % i) for i in range(n)] - husband = [solver.IntVar(0, n-1, 'husband[%i]' % i) for i in range(n)] + # + # declare variables + # + wife = [solver.IntVar(0, n - 1, "wife[%i]" % i) for i in range(n)] + husband = [solver.IntVar(0, n - 1, "husband[%i]" % i) for i in range(n)] - # - # constraints - # + # + # constraints + # - # forall(m in Men) - # cp.post(husband[wife[m]] == m); - for m in range(n): - solver.Add(solver.Element(husband, wife[m]) == m) + # forall(m in Men) + # cp.post(husband[wife[m]] == m); + for m in range(n): + solver.Add(solver.Element(husband, wife[m]) == m) - # forall(w in Women) - # cp.post(wife[husband[w]] == w); - for w in range(n): - solver.Add(solver.Element(wife, husband[w]) == w) + # forall(w in Women) + # cp.post(wife[husband[w]] == w); + for w in range(n): + solver.Add(solver.Element(wife, husband[w]) == w) + # forall(m in Men, o in Women) + # cp.post(rankMen[m,o] < rankMen[m, wife[m]] => rankWomen[o,husband[o]] < + # rankWomen[o,m]); + for m in range(n): + for o in range(n): + b1 = solver.IsGreaterCstVar( + solver.Element(rankMen[m], wife[m]), rankMen[m][o]) + b2 = ( + solver.IsLessCstVar( + solver.Element(rankWomen[o], husband[o]), rankWomen[o][m])) + solver.Add(b1 - b2 <= 0) - # forall(m in Men, o in Women) - # cp.post(rankMen[m,o] < rankMen[m, wife[m]] => rankWomen[o,husband[o]] < rankWomen[o,m]); - for m in range(n): - for o in range(n): - b1 = solver.IsGreaterCstVar(solver.Element(rankMen[m], wife[m]), rankMen[m][o]) - b2 = solver.IsLessCstVar(solver.Element(rankWomen[o], husband[o]), rankWomen[o][m]) - solver.Add(b1-b2<=0) + # forall(w in Women, o in Men) + # cp.post(rankWomen[w,o] < rankWomen[w,husband[w]] => rankMen[o,wife[o]] < + # rankMen[o,w]); + for w in range(n): + for o in range(n): + b1 = solver.IsGreaterCstVar( + solver.Element(rankWomen[w], husband[w]), rankWomen[w][o]) + b2 = solver.IsLessCstVar( + solver.Element(rankMen[o], wife[o]), rankMen[o][w]) + solver.Add(b1 - b2 <= 0) - # forall(w in Women, o in Men) - # cp.post(rankWomen[w,o] < rankWomen[w,husband[w]] => rankMen[o,wife[o]] < rankMen[o,w]); - for w in range(n): - for o in range(n): - b1 = solver.IsGreaterCstVar(solver.Element(rankWomen[w], husband[w]), rankWomen[w][o]) - b2 = solver.IsLessCstVar(solver.Element(rankMen[o], wife[o]), rankMen[o][w]) - solver.Add(b1-b2<=0) + # + # solution and search + # + solution = solver.Assignment() + solution.Add(wife) + solution.Add(husband) + db = solver.Phase(wife + husband, + solver.CHOOSE_FIRST_UNBOUND, + solver.ASSIGN_MIN_VALUE) - # - # solution and search - # - solution = solver.Assignment() - solution.Add(wife) - solution.Add(husband) - - db = solver.Phase(wife + husband, - solver.CHOOSE_FIRST_UNBOUND, - solver.ASSIGN_MIN_VALUE) - - solver.NewSearch(db) - num_solutions = 0 - solutions = [] - while solver.NextSolution(): - # solutions.append([x[i].Value() for i in range(x_len)]) - print "wife : ", [wife[i].Value() for i in range(n)] - print "husband: ", [husband[i].Value() for i in range(n)] - print - num_solutions += 1 - - solver.EndSearch() - - print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() - print "#############" + solver.NewSearch(db) + num_solutions = 0 + solutions = [] + while solver.NextSolution(): + # solutions.append([x[i].Value() for i in range(x_len)]) + print "wife : ", [wife[i].Value() for i in range(n)] + print "husband: ", [husband[i].Value() for i in range(n)] print + num_solutions += 1 + solver.EndSearch() + + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() + print "#############" + print # @@ -134,68 +140,67 @@ def main(ranks, problem_name): # van_hentenryck = { "rankWomen": [ - [1, 2, 4, 3, 5], - [3, 5, 1, 2, 4], - [5, 4, 2, 1, 3], - [1, 3, 5, 4, 2], - [4, 2, 3, 5, 1] + [1, 2, 4, 3, 5], + [3, 5, 1, 2, 4], + [5, 4, 2, 1, 3], + [1, 3, 5, 4, 2], + [4, 2, 3, 5, 1] ], "rankMen": [ - [5, 1, 2, 4, 3], - [4, 1, 3, 2, 5], - [5, 3, 2, 4, 1], - [1, 5, 4, 3, 2], - [4, 3, 2, 1, 5] + [5, 1, 2, 4, 3], + [4, 1, 3, 2, 5], + [5, 3, 2, 4, 1], + [1, 5, 4, 3, 2], + [4, 3, 2, 1, 5] ] - } +} # # Data from MathWorld # http://mathworld.wolfram.com/StableMarriageProblem.html # mathworld = { - "rankWomen" : [ - [3, 1, 5, 2, 8, 7, 6, 9, 4], - [9, 4, 8, 1, 7, 6, 3, 2, 5], - [3, 1, 8, 9, 5, 4, 2, 6, 7], - [8, 7, 5, 3, 2, 6, 4, 9, 1], - [6, 9, 2, 5, 1, 4, 7, 3, 8], - [2, 4, 5, 1, 6, 8, 3, 9, 7], - [9, 3, 8, 2, 7, 5, 4, 6, 1], - [6, 3, 2, 1, 8, 4, 5, 9, 7], - [8, 2, 6, 4, 9, 1, 3, 7, 5]], + "rankWomen": [ + [3, 1, 5, 2, 8, 7, 6, 9, 4], + [9, 4, 8, 1, 7, 6, 3, 2, 5], + [3, 1, 8, 9, 5, 4, 2, 6, 7], + [8, 7, 5, 3, 2, 6, 4, 9, 1], + [6, 9, 2, 5, 1, 4, 7, 3, 8], + [2, 4, 5, 1, 6, 8, 3, 9, 7], + [9, 3, 8, 2, 7, 5, 4, 6, 1], + [6, 3, 2, 1, 8, 4, 5, 9, 7], + [8, 2, 6, 4, 9, 1, 3, 7, 5]], - "rankMen" : [ - [7, 3, 8, 9, 6, 4, 2, 1, 5], - [5, 4, 8, 3, 1, 2, 6, 7, 9], - [4, 8, 3, 9, 7, 5, 6, 1, 2], - [9, 7, 4, 2, 5, 8, 3, 1, 6], - [2, 6, 4, 9, 8, 7, 5, 1, 3], - [2, 7, 8, 6, 5, 3, 4, 1, 9], - [1, 6, 2, 3, 8, 5, 4, 9, 7], - [5, 6, 9, 1, 2, 8, 4, 3, 7], - [6, 1, 4, 7, 5, 8, 3, 9, 2]] - } + "rankMen": [ + [7, 3, 8, 9, 6, 4, 2, 1, 5], + [5, 4, 8, 3, 1, 2, 6, 7, 9], + [4, 8, 3, 9, 7, 5, 6, 1, 2], + [9, 7, 4, 2, 5, 8, 3, 1, 6], + [2, 6, 4, 9, 8, 7, 5, 1, 3], + [2, 7, 8, 6, 5, 3, 4, 1, 9], + [1, 6, 2, 3, 8, 5, 4, 9, 7], + [5, 6, 9, 1, 2, 8, 4, 3, 7], + [6, 1, 4, 7, 5, 8, 3, 9, 2]] +} # # Data from # http://www.csee.wvu.edu/~ksmani/courses/fa01/random/lecnotes/lecture5.pdf # problem3 = { - "rankWomen" : [ - [1,2,3,4], - [4,3,2,1], - [1,2,3,4], - [3,4,1,2]], - - "rankMen" : [ - [1,2,3,4], - [2,1,3,4], - [1,4,3,2], - [4,3,1,2]] - } + "rankWomen": [ + [1, 2, 3, 4], + [4, 3, 2, 1], + [1, 2, 3, 4], + [3, 4, 1, 2]], + "rankMen": [ + [1, 2, 3, 4], + [2, 1, 3, 4], + [1, 4, 3, 2], + [4, 3, 1, 2]] +} # @@ -205,25 +210,25 @@ problem3 = { # problem4 = { "rankWomen": [ - [1,5,4,6,2,3], - [4,1,5,2,6,3], - [6,4,2,1,5,3], - [1,5,2,4,3,6], - [4,2,1,5,6,3], - [2,6,3,5,1,4]], + [1, 5, 4, 6, 2, 3], + [4, 1, 5, 2, 6, 3], + [6, 4, 2, 1, 5, 3], + [1, 5, 2, 4, 3, 6], + [4, 2, 1, 5, 6, 3], + [2, 6, 3, 5, 1, 4]], - "rankMen" : [ - [1,4,2,5,6,3], - [3,4,6,1,5,2], - [1,6,4,2,3,5], - [6,5,3,4,2,1], - [3,1,2,4,5,6], - [2,3,1,6,5,4]] - } + "rankMen": [ + [1, 4, 2, 5, 6, 3], + [3, 4, 6, 1, 5, 2], + [1, 6, 4, 2, 3, 5], + [6, 5, 3, 4, 2, 1], + [3, 1, 2, 4, 5, 6], + [2, 3, 1, 6, 5, 4]] +} -if __name__ == '__main__': - main(van_hentenryck, "Van Hentenryck") - main(mathworld, "MathWorld") - main(problem3, "Problem 3") - main(problem4, "Problem4") +if __name__ == "__main__": + main(van_hentenryck, "Van Hentenryck") + main(mathworld, "MathWorld") + main(problem3, "Problem 3") + main(problem4, "Problem4") diff --git a/examples/python/steel.py b/examples/python/steel.py index 6c068804b8..d10a187fdb 100644 --- a/examples/python/steel.py +++ b/examples/python/steel.py @@ -30,14 +30,15 @@ def BinPacking(solver, binvars, weights, loadvars): constraints forall j: loadvars[j] == sum_i (binvars[i] == j) * weights[i]) ''' pack = solver.Pack(binvars, len(binvars)) - pack.AddWeightedSumEqualVarDimension(weights, loadvars); + pack.AddWeightedSumEqualVarDimension(weights, loadvars) solver.Add(pack) solver.Add(solver.SumEquality(loadvars, sum(weights))) #------------------------------data reading------------------- + def ReadData(filename): - '''Read data from .''' + """Read data from .""" f = open(filename) capacity = [int(nb) for nb in f.readline().split()] capacity.pop(0) @@ -51,7 +52,7 @@ def ReadData(filename): loss = [min(filter(lambda x: x >= c, capacity)) - c for c in range(max_capacity + 1)] color_orders = [filter(lambda o: colors[o] == c, range(nb_slabs)) - for c in range(1, nb_colors + 1)] + for c in range(1, nb_colors + 1)] print 'Solving steel mill with', nb_slabs, 'slabs' return (nb_slabs, capacity, max_capacity, weights, colors, loss, color_orders) @@ -77,11 +78,10 @@ class SteelDecisionBuilder(pywrapcp.PyDecisionBuilder): self.__weights = weights self.__losstab = losstab self.__loads = loads - self.__maxcapa = len(losstab)-1 - + self.__maxcapa = len(losstab) - 1 def Next(self, solver): - var,weight = self.NextVar() + var, weight = self.NextVar() if var: v = self.MaxBound() if v + 1 == var.Min(): @@ -94,41 +94,40 @@ class SteelDecisionBuilder(pywrapcp.PyDecisionBuilder): # try first to place the order in the slab that will induce # the least increase of the loss loads = self.getLoads() - l,v = min((self.__losstab[loads[i]+weight],i) - for i in range(var.Min(),var.Max()+1) - if var.Contains(i) and loads[i]+weight <= self.__maxcapa) + l, v = min((self.__losstab[loads[i] + weight], i) + for i in range(var.Min(), var.Max() + 1) + if var.Contains(i) and loads[i] + weight <= self.__maxcapa) decision = solver.AssignVariableValue(var, v) return decision else: return None def getLoads(self): - load = [0]*len(self.__loads) - for w,x in zip(self.__weights,self.__x): - if x.Bound(): - load[x.Min()] += w - return load - + load = [0] * len(self.__loads) + for w, x in zip(self.__weights, self.__x): + if x.Bound(): + load[x.Min()] += w + return load def MaxBound(self): - ''' returns the max value bound to a variable, -1 if no variables bound''' + """ returns the max value bound to a variable, -1 if no variables bound""" return max([-1] + [self.__x[o].Min() for o in range(self.__nb_slabs) if self.__x[o].Bound()]) def NextVar(self): - ''' mindom size heuristic with tie break on the weights of orders ''' + """ mindom size heuristic with tie break on the weights of orders """ res = [(self.__x[o].Size(), -self.__weights[o], self.__x[o]) for o in range(self.__nb_slabs) if self.__x[o].Size() > 1] if res: res.sort() - return res[0][2],-res[0][1] #returns the order var and its weight + return res[0][2], -res[0][1] # returns the order var and its weight else: return None, None def DebugString(self): - return 'SteelMillDecisionBuilder(' + str(self.__x) + ')' + return 'SteelMillDecisionBuilder(' + str(self.__x) + ')' def main(unused_argv): diff --git a/examples/python/steel_lns.py b/examples/python/steel_lns.py index 7b6bba3367..c65e3325c3 100644 --- a/examples/python/steel_lns.py +++ b/examples/python/steel_lns.py @@ -40,14 +40,15 @@ def BinPacking(solver, binvars, weights, loadvars): constraints forall j: loadvars[j] == sum_i (binvars[i] == j) * weights[i]) ''' pack = solver.Pack(binvars, len(binvars)) - pack.AddWeightedSumEqualVarDimension(weights, loadvars); + pack.AddWeightedSumEqualVarDimension(weights, loadvars) solver.Add(pack) solver.Add(solver.SumEquality(loadvars, sum(weights))) # ---------- data reading ---------- + def ReadData(filename): - '''Read data from .''' + """Read data from .""" f = open(filename) capacity = [int(nb) for nb in f.readline().split()] capacity.pop(0) @@ -61,7 +62,7 @@ def ReadData(filename): loss = [min(filter(lambda x: x >= c, capacity)) - c for c in range(max_capacity + 1)] color_orders = [filter(lambda o: colors[o] == c, range(nb_slabs)) - for c in range(1, nb_colors + 1)] + for c in range(1, nb_colors + 1)] print 'Solving steel mill with', nb_slabs, 'slabs' return (nb_slabs, capacity, max_capacity, weights, colors, loss, color_orders) @@ -87,11 +88,10 @@ class SteelDecisionBuilder(pywrapcp.PyDecisionBuilder): self.__weights = weights self.__loss_array = loss_array self.__loads = loads - self.__max_capacity = len(loss_array)-1 - + self.__max_capacity = len(loss_array) - 1 def Next(self, solver): - var,weight = self.NextVar() + var, weight = self.NextVar() if var: v = self.MaxBound() if v + 1 == var.Min(): @@ -104,10 +104,10 @@ class SteelDecisionBuilder(pywrapcp.PyDecisionBuilder): # try first to place the order in the slab that will induce # the least increase of the loss loads = self.getLoads() - l,v = min((self.__loss_array[loads[i] + weight], i) + l, v = min((self.__loss_array[loads[i] + weight], i) for i in range(var.Min(), var.Max() + 1) - if var.Contains(i) and \ - loads[i] + weight <= self.__max_capacity) + if var.Contains(i) and + loads[i] + weight <= self.__max_capacity) decision = solver.AssignVariableValue(var, v) return decision else: @@ -120,29 +120,29 @@ class SteelDecisionBuilder(pywrapcp.PyDecisionBuilder): load[x.Min()] += w return load - def MaxBound(self): - ''' returns the max value bound to a variable, -1 if no variables bound''' + """ returns the max value bound to a variable, -1 if no variables bound""" return max([-1] + [self.__x[o].Min() for o in range(self.__nb_slabs) if self.__x[o].Bound()]) def NextVar(self): - ''' mindom size heuristic with tie break on the weights of orders ''' + """ mindom size heuristic with tie break on the weights of orders """ res = [(self.__x[o].Size(), -self.__weights[o], self.__x[o]) for o in range(self.__nb_slabs) if self.__x[o].Size() > 1] if res: res.sort() - return (res[0][2], -res[0][1]) #returns the order var and its weight + return (res[0][2], -res[0][1]) # returns the order var and its weight else: return (None, None) def DebugString(self): - return 'SteelMillDecisionBuilder(' + str(self.__x) + ')' + return 'SteelMillDecisionBuilder(' + str(self.__x) + ')' # ----------- LNS Operator ---------- + class SteelRandomLns(object): """Random LNS for Steel.""" diff --git a/examples/python/stigler.py b/examples/python/stigler.py index 4e994f40ac..474a50608b 100644 --- a/examples/python/stigler.py +++ b/examples/python/stigler.py @@ -115,27 +115,27 @@ ''' This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ import sys from ortools.linear_solver import pywraplp -def main(sol = 'GLPK'): +def main(sol="GLPK"): # Create the solver. - print 'Solver: ', sol + print "Solver: ", sol # using GLPK - if sol == 'GLPK': - solver = pywraplp.Solver('CoinsGridGLPK', + if sol == "GLPK": + solver = pywraplp.Solver("CoinsGridGLPK", pywraplp.Solver.GLPK_MIXED_INTEGER_PROGRAMMING) else: - # Using CLP - solver = pywraplp.Solver('CoinsGridCLP', - pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING) - + # Using CLP + solver = pywraplp.Solver("CoinsGridCLP", + pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING) # # data @@ -151,193 +151,190 @@ def main(sol = 'GLPK'): num_nutrients = 9 N = range(num_nutrients) - nutrients = [ - "calories", # Calories, unit = 1000 - "protein", # Protein, unit = grams - "calcium", # Calcium, unit = grams - "iron", # Iron, unit = milligrams - "vitaminA", # Vitamin A, unit = 1000 International Units - "thiamine", # Thiamine, Vit. B1, unit = milligrams - "riboflavin", # Riboflavin, Vit. B2, unit = milligrams - "niacin", # Niacin (Nicotinic Acid), unit = milligrams - "ascorbicAcid" # Ascorbic Acid, Vit. C, unit = milligrams - ] + "calories", # Calories, unit = 1000 + "protein", # Protein, unit = grams + "calcium", # Calcium, unit = grams + "iron", # Iron, unit = milligrams + "vitaminA", # Vitamin A, unit = 1000 International Units + "thiamine", # Thiamine, Vit. B1, unit = milligrams + "riboflavin", # Riboflavin, Vit. B2, unit = milligrams + "niacin", # Niacin (Nicotinic Acid), unit = milligrams + "ascorbicAcid" # Ascorbic Acid, Vit. C, unit = milligrams + ] commodities = [ - ["Wheat Flour (Enriched)", "10 lb."], - ["Macaroni", "1 lb."], - ["Wheat Cereal (Enriched)", "28 oz."], - ["Corn Flakes", "8 oz."], - ["Corn Meal", "1 lb."], - ["Hominy Grits", "24 oz."], - ["Rice", "1 lb."], - ["Rolled Oats", "1 lb."], - ["White Bread (Enriched)", "1 lb."], - ["Whole Wheat Bread", "1 lb."], - ["Rye Bread", "1 lb."], - ["Pound Cake", "1 lb."], - ["Soda Crackers", "1 lb."], - ["Milk", "1 qt."], - ["Evaporated Milk (can)", "14.5 oz."], - ["Butter", "1 lb."], - ["Oleomargarine", "1 lb."], - ["Eggs", "1 doz."], - ["Cheese (Cheddar)", "1 lb."], - ["Cream", "1/2 pt."], - ["Peanut Butter", "1 lb."], - ["Mayonnaise", "1/2 pt."], - ["Crisco", "1 lb."], - ["Lard", "1 lb."], - ["Sirloin Steak", "1 lb."], - ["Round Steak", "1 lb."], - ["Rib Roast", "1 lb."], - ["Chuck Roast", "1 lb."], - ["Plate", "1 lb."], - ["Liver (Beef)", "1 lb."], - ["Leg of Lamb", "1 lb."], - ["Lamb Chops (Rib)", "1 lb."], - ["Pork Chops", "1 lb."], - ["Pork Loin Roast", "1 lb."], - ["Bacon", "1 lb."], - ["Ham - smoked", "1 lb."], - ["Salt Pork", "1 lb."], - ["Roasting Chicken", "1 lb."], - ["Veal Cutlets", "1 lb."], - ["Salmon, Pink (can)", "16 oz."], - ["Apples", "1 lb."], - ["Bananas", "1 lb."], - ["Lemons", "1 doz."], - ["Oranges", "1 doz."], - ["Green Beans", "1 lb."], - ["Cabbage", "1 lb."], - ["Carrots", "1 bunch"], - ["Celery", "1 stalk"], - ["Lettuce", "1 head"], - ["Onions", "1 lb."], - ["Potatoes", "15 lb."], - ["Spinach", "1 lb."], - ["Sweet Potatoes", "1 lb."], - ["Peaches (can)", "No. 2 1/2"], - ["Pears (can)", "No. 2 1/2,"], - ["Pineapple (can)", "No. 2 1/2"], - ["Asparagus (can)", "No. 2"], - ["Grean Beans (can)", "No. 2"], - ["Pork and Beans (can)", "16 oz."], - ["Corn (can)", "No. 2"], - ["Peas (can)", "No. 2"], - ["Tomatoes (can)", "No. 2"], - ["Tomato Soup (can)", "10 1/2 oz."], - ["Peaches, Dried", "1 lb."], - ["Prunes, Dried", "1 lb."], - ["Raisins, Dried", "15 oz."], - ["Peas, Dried", "1 lb."], - ["Lima Beans, Dried", "1 lb."], - ["Navy Beans, Dried", "1 lb."], - ["Coffee", "1 lb."], - ["Tea", "1/4 lb."], - ["Cocoa", "8 oz."], - ["Chocolate", "8 oz."], - ["Sugar", "10 lb."], - ["Corn Sirup", "24 oz."], - ["Molasses", "18 oz."], - ["Strawberry Preserve", "1 lb."] - ] - + ["Wheat Flour (Enriched)", "10 lb."], + ["Macaroni", "1 lb."], + ["Wheat Cereal (Enriched)", "28 oz."], + ["Corn Flakes", "8 oz."], + ["Corn Meal", "1 lb."], + ["Hominy Grits", "24 oz."], + ["Rice", "1 lb."], + ["Rolled Oats", "1 lb."], + ["White Bread (Enriched)", "1 lb."], + ["Whole Wheat Bread", "1 lb."], + ["Rye Bread", "1 lb."], + ["Pound Cake", "1 lb."], + ["Soda Crackers", "1 lb."], + ["Milk", "1 qt."], + ["Evaporated Milk (can)", "14.5 oz."], + ["Butter", "1 lb."], + ["Oleomargarine", "1 lb."], + ["Eggs", "1 doz."], + ["Cheese (Cheddar)", "1 lb."], + ["Cream", "1/2 pt."], + ["Peanut Butter", "1 lb."], + ["Mayonnaise", "1/2 pt."], + ["Crisco", "1 lb."], + ["Lard", "1 lb."], + ["Sirloin Steak", "1 lb."], + ["Round Steak", "1 lb."], + ["Rib Roast", "1 lb."], + ["Chuck Roast", "1 lb."], + ["Plate", "1 lb."], + ["Liver (Beef)", "1 lb."], + ["Leg of Lamb", "1 lb."], + ["Lamb Chops (Rib)", "1 lb."], + ["Pork Chops", "1 lb."], + ["Pork Loin Roast", "1 lb."], + ["Bacon", "1 lb."], + ["Ham - smoked", "1 lb."], + ["Salt Pork", "1 lb."], + ["Roasting Chicken", "1 lb."], + ["Veal Cutlets", "1 lb."], + ["Salmon, Pink (can)", "16 oz."], + ["Apples", "1 lb."], + ["Bananas", "1 lb."], + ["Lemons", "1 doz."], + ["Oranges", "1 doz."], + ["Green Beans", "1 lb."], + ["Cabbage", "1 lb."], + ["Carrots", "1 bunch"], + ["Celery", "1 stalk"], + ["Lettuce", "1 head"], + ["Onions", "1 lb."], + ["Potatoes", "15 lb."], + ["Spinach", "1 lb."], + ["Sweet Potatoes", "1 lb."], + ["Peaches (can)", "No. 2 1/2"], + ["Pears (can)", "No. 2 1/2,"], + ["Pineapple (can)", "No. 2 1/2"], + ["Asparagus (can)", "No. 2"], + ["Grean Beans (can)", "No. 2"], + ["Pork and Beans (can)", "16 oz."], + ["Corn (can)", "No. 2"], + ["Peas (can)", "No. 2"], + ["Tomatoes (can)", "No. 2"], + ["Tomato Soup (can)", "10 1/2 oz."], + ["Peaches, Dried", "1 lb."], + ["Prunes, Dried", "1 lb."], + ["Raisins, Dried", "15 oz."], + ["Peas, Dried", "1 lb."], + ["Lima Beans, Dried", "1 lb."], + ["Navy Beans, Dried", "1 lb."], + ["Coffee", "1 lb."], + ["Tea", "1/4 lb."], + ["Cocoa", "8 oz."], + ["Chocolate", "8 oz."], + ["Sugar", "10 lb."], + ["Corn Sirup", "24 oz."], + ["Molasses", "18 oz."], + ["Strawberry Preserve", "1 lb."] + ] # price and weight are the two first columns data = [ - [36.0, 12600.0, 44.7, 1411.0, 2.0, 365.0, 0.0, 55.4, 33.3, 441.0, 0.0], - [14.1, 3217.0, 11.6, 418.0, 0.7, 54.0, 0.0, 3.2, 1.9, 68.0, 0.0], - [24.2, 3280.0, 11.8, 377.0, 14.4, 175.0, 0.0, 14.4, 8.8, 114.0, 0.0], - [ 7.1, 3194.0, 11.4, 252.0, 0.1, 56.0, 0.0, 13.5, 2.3, 68.0, 0.0], - [ 4.6, 9861.0, 36.0, 897.0, 1.7, 99.0, 30.9, 17.4, 7.9, 106.0, 0.0], - [ 8.5, 8005.0, 28.6, 680.0, 0.8, 80.0, 0.0, 10.6, 1.6, 110.0, 0.0], - [ 7.5, 6048.0, 21.2, 460.0, 0.6, 41.0, 0.0, 2.0, 4.8, 60.0, 0.0], - [ 7.1, 6389.0, 25.3, 907.0, 5.1, 341.0, 0.0, 37.1, 8.9, 64.0, 0.0], - [ 7.9, 5742.0, 15.6, 488.0, 2.5, 115.0, 0.0, 13.8, 8.5, 126.0, 0.0], - [ 9.1, 4985.0, 12.2, 484.0, 2.7, 125.0, 0.0, 13.9, 6.4, 160.0, 0.0], - [ 9.2, 4930.0, 12.4, 439.0, 1.1, 82.0, 0.0, 9.9, 3.0, 66.0, 0.0], - [24.8, 1829.0, 8.0, 130.0, 0.4, 31.0, 18.9, 2.8, 3.0, 17.0, 0.0], - [15.1, 3004.0, 12.5, 288.0, 0.5, 50.0, 0.0, 0.0, 0.0, 0.0, 0.0], - [11.0, 8867.0, 6.1, 310.0, 10.5, 18.0, 16.8, 4.0, 16.0, 7.0, 177.0], - [ 6.7, 6035.0, 8.4, 422.0, 15.1, 9.0, 26.0, 3.0, 23.5, 11.0, 60.0], - [20.8, 1473.0, 10.8, 9.0, 0.2, 3.0, 44.2, 0.0, 0.2, 2.0, 0.0], - [16.1, 2817.0, 20.6, 17.0, 0.6, 6.0, 55.8, 0.2, 0.0, 0.0, 0.0], - [32.6, 1857.0, 2.9, 238.0, 1.0, 52.0, 18.6, 2.8, 6.5, 1.0, 0.0], - [24.2, 1874.0, 7.4, 448.0, 16.4, 19.0, 28.1, 0.8, 10.3, 4.0, 0.0], - [14.1, 1689.0, 3.5, 49.0, 1.7, 3.0, 16.9, 0.6, 2.5, 0.0, 17.0], - [17.9, 2534.0, 15.7, 661.0, 1.0, 48.0, 0.0, 9.6, 8.1, 471.0, 0.0], - [16.7, 1198.0, 8.6, 18.0, 0.2, 8.0, 2.7, 0.4, 0.5, 0.0, 0.0], - [20.3, 2234.0, 20.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], - [ 9.8, 4628.0, 41.7, 0.0, 0.0, 0.0, 0.2, 0.0, 0.5, 5.0, 0.0], - [39.6, 1145.0, 2.9, 166.0, 0.1, 34.0, 0.2, 2.1, 2.9, 69.0, 0.0], - [36.4, 1246.0, 2.2, 214.0, 0.1, 32.0, 0.4, 2.5, 2.4, 87.0, 0.0], - [29.2, 1553.0, 3.4, 213.0, 0.1, 33.0, 0.0, 0.0, 2.0, 0.0, 0.0], - [22.6, 2007.0, 3.6, 309.0, 0.2, 46.0, 0.4, 1.0, 4.0, 120.0, 0.0], - [14.6, 3107.0, 8.5, 404.0, 0.2, 62.0, 0.0, 0.9, 0.0, 0.0, 0.0], - [26.8, 1692.0, 2.2, 333.0, 0.2, 139.0, 169.2, 6.4, 50.8, 316.0, 525.0], - [27.6, 1643.0, 3.1, 245.0, 0.1, 20.0, 0.0, 2.8, 3.0, 86.0, 0.0], - [36.6, 1239.0, 3.3, 140.0, 0.1, 15.0, 0.0, 1.7, 2.7, 54.0, 0.0], - [30.7, 1477.0, 3.5, 196.0, 0.2, 80.0, 0.0, 17.4, 2.7, 60.0, 0.0], - [24.2, 1874.0, 4.4, 249.0, 0.3, 37.0, 0.0, 18.2, 3.6, 79.0, 0.0], - [25.6, 1772.0, 10.4, 152.0, 0.2, 23.0, 0.0, 1.8, 1.8, 71.0, 0.0], - [27.4, 1655.0, 6.7, 212.0, 0.2, 31.0, 0.0, 9.9, 3.3, 50.0, 0.0], - [16.0, 2835.0, 18.8, 164.0, 0.1, 26.0, 0.0, 1.4, 1.8, 0.0, 0.0], - [30.3, 1497.0, 1.8, 184.0, 0.1, 30.0, 0.1, 0.9, 1.8, 68.0, 46.0], - [42.3, 1072.0, 1.7, 156.0, 0.1, 24.0, 0.0, 1.4, 2.4, 57.0, 0.0], - [13.0, 3489.0, 5.8, 705.0, 6.8, 45.0, 3.5, 1.0, 4.9, 209.0, 0.0], - [ 4.4, 9072.0, 5.8, 27.0, 0.5, 36.0, 7.3, 3.6, 2.7, 5.0, 544.0], - [ 6.1, 4982.0, 4.9, 60.0, 0.4, 30.0, 17.4, 2.5, 3.5, 28.0, 498.0], - [26.0, 2380.0, 1.0, 21.0, 0.5, 14.0, 0.0, 0.5, 0.0, 4.0, 952.0], - [30.9, 4439.0, 2.2, 40.0, 1.1, 18.0, 11.1, 3.6, 1.3, 10.0, 1993.0], - [ 7.1, 5750.0, 2.4, 138.0, 3.7, 80.0, 69.0, 4.3, 5.8, 37.0, 862.0], - [ 3.7, 8949.0, 2.6, 125.0, 4.0, 36.0, 7.2, 9.0, 4.5, 26.0, 5369.0], - [ 4.7, 6080.0, 2.7, 73.0, 2.8, 43.0, 188.5, 6.1, 4.3, 89.0, 608.0], - [ 7.3, 3915.0, 0.9, 51.0, 3.0, 23.0, 0.9, 1.4, 1.4, 9.0, 313.0], - [ 8.2, 2247.0, 0.4, 27.0, 1.1, 22.0, 112.4, 1.8, 3.4, 11.0, 449.0], - [ 3.6, 11844.0, 5.8, 166.0, 3.8, 59.0, 16.6, 4.7, 5.9, 21.0, 1184.0], - [34.0, 16810.0, 14.3, 336.0, 1.8, 118.0, 6.7, 29.4, 7.1, 198.0, 2522.0], - [ 8.1, 4592.0, 1.1, 106.0, 0.0, 138.0, 918.4, 5.7, 13.8, 33.0, 2755.0], - [ 5.1, 7649.0, 9.6, 138.0, 2.7, 54.0, 290.7, 8.4, 5.4, 83.0, 1912.0], - [16.8, 4894.0, 3.7, 20.0, 0.4, 10.0, 21.5, 0.5, 1.0, 31.0, 196.0], - [20.4, 4030.0, 3.0, 8.0, 0.3, 8.0, 0.8, 0.8, 0.8, 5.0, 81.0], - [21.3, 3993.0, 2.4, 16.0, 0.4, 8.0, 2.0, 2.8, 0.8, 7.0, 399.0], - [27.7, 1945.0, 0.4, 33.0, 0.3, 12.0, 16.3, 1.4, 2.1, 17.0, 272.0], - [10.0, 5386.0, 1.0, 54.0, 2.0, 65.0, 53.9, 1.6, 4.3, 32.0, 431.0], - [ 7.1, 6389.0, 7.5, 364.0, 4.0, 134.0, 3.5, 8.3, 7.7, 56.0, 0.0], - [10.4, 5452.0, 5.2, 136.0, 0.2, 16.0, 12.0, 1.6, 2.7, 42.0, 218.0], - [13.8, 4109.0, 2.3, 136.0, 0.6, 45.0, 34.9, 4.9, 2.5, 37.0, 370.0], - [ 8.6, 6263.0, 1.3, 63.0, 0.7, 38.0, 53.2, 3.4, 2.5, 36.0, 1253.0], - [ 7.6, 3917.0, 1.6, 71.0, 0.6, 43.0, 57.9, 3.5, 2.4, 67.0, 862.0], - [15.7, 2889.0, 8.5, 87.0, 1.7, 173.0, 86.8, 1.2, 4.3, 55.0, 57.0], - [ 9.0, 4284.0, 12.8, 99.0, 2.5, 154.0, 85.7, 3.9, 4.3, 65.0, 257.0], - [ 9.4, 4524.0, 13.5, 104.0, 2.5, 136.0, 4.5, 6.3, 1.4, 24.0, 136.0], - [ 7.9, 5742.0, 20.0, 1367.0, 4.2, 345.0, 2.9, 28.7, 18.4, 162.0, 0.0], - [ 8.9, 5097.0, 17.4, 1055.0, 3.7, 459.0, 5.1, 26.9, 38.2, 93.0, 0.0], - [ 5.9, 7688.0, 26.9, 1691.0, 11.4, 792.0, 0.0, 38.4, 24.6, 217.0, 0.0], - [22.4, 2025.0, 0.0, 0.0, 0.0, 0.0, 0.0, 4.0, 5.1, 50.0, 0.0], - [17.4, 652.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 2.3, 42.0, 0.0], - [ 8.6, 2637.0, 8.7, 237.0, 3.0, 72.0, 0.0, 2.0, 11.9, 40.0, 0.0], - [16.2, 1400.0, 8.0, 77.0, 1.3, 39.0, 0.0, 0.9, 3.4, 14.0, 0.0], - [51.7, 8773.0, 34.9, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], - [13.7, 4996.0, 14.7, 0.0, 0.5, 74.0, 0.0, 0.0, 0.0, 5.0, 0.0], - [13.6, 3752.0, 9.0, 0.0, 10.3, 244.0, 0.0, 1.9, 7.5, 146.0, 0.0], - [20.5, 2213.0, 6.4, 11.0, 0.4, 7.0, 0.2, 0.2, 0.4, 3.0, 0.0]] + [36.0, 12600.0, 44.7, 1411.0, 2.0, 365.0, 0.0, 55.4, 33.3, 441.0, 0.0], + [14.1, 3217.0, 11.6, 418.0, 0.7, 54.0, 0.0, 3.2, 1.9, 68.0, 0.0], + [24.2, 3280.0, 11.8, 377.0, 14.4, 175.0, 0.0, 14.4, 8.8, 114.0, 0.0], + [7.1, 3194.0, 11.4, 252.0, 0.1, 56.0, 0.0, 13.5, 2.3, 68.0, 0.0], + [4.6, 9861.0, 36.0, 897.0, 1.7, 99.0, 30.9, 17.4, 7.9, 106.0, 0.0], + [8.5, 8005.0, 28.6, 680.0, 0.8, 80.0, 0.0, 10.6, 1.6, 110.0, 0.0], + [7.5, 6048.0, 21.2, 460.0, 0.6, 41.0, 0.0, 2.0, 4.8, 60.0, 0.0], + [7.1, 6389.0, 25.3, 907.0, 5.1, 341.0, 0.0, 37.1, 8.9, 64.0, 0.0], + [7.9, 5742.0, 15.6, 488.0, 2.5, 115.0, 0.0, 13.8, 8.5, 126.0, 0.0], + [9.1, 4985.0, 12.2, 484.0, 2.7, 125.0, 0.0, 13.9, 6.4, 160.0, 0.0], + [9.2, 4930.0, 12.4, 439.0, 1.1, 82.0, 0.0, 9.9, 3.0, 66.0, 0.0], + [24.8, 1829.0, 8.0, 130.0, 0.4, 31.0, 18.9, 2.8, 3.0, 17.0, 0.0], + [15.1, 3004.0, 12.5, 288.0, 0.5, 50.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [11.0, 8867.0, 6.1, 310.0, 10.5, 18.0, 16.8, 4.0, 16.0, 7.0, 177.0], + [6.7, 6035.0, 8.4, 422.0, 15.1, 9.0, 26.0, 3.0, 23.5, 11.0, 60.0], + [20.8, 1473.0, 10.8, 9.0, 0.2, 3.0, 44.2, 0.0, 0.2, 2.0, 0.0], + [16.1, 2817.0, 20.6, 17.0, 0.6, 6.0, 55.8, 0.2, 0.0, 0.0, 0.0], + [32.6, 1857.0, 2.9, 238.0, 1.0, 52.0, 18.6, 2.8, 6.5, 1.0, 0.0], + [24.2, 1874.0, 7.4, 448.0, 16.4, 19.0, 28.1, 0.8, 10.3, 4.0, 0.0], + [14.1, 1689.0, 3.5, 49.0, 1.7, 3.0, 16.9, 0.6, 2.5, 0.0, 17.0], + [17.9, 2534.0, 15.7, 661.0, 1.0, 48.0, 0.0, 9.6, 8.1, 471.0, 0.0], + [16.7, 1198.0, 8.6, 18.0, 0.2, 8.0, 2.7, 0.4, 0.5, 0.0, 0.0], + [20.3, 2234.0, 20.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [9.8, 4628.0, 41.7, 0.0, 0.0, 0.0, 0.2, 0.0, 0.5, 5.0, 0.0], + [39.6, 1145.0, 2.9, 166.0, 0.1, 34.0, 0.2, 2.1, 2.9, 69.0, 0.0], + [36.4, 1246.0, 2.2, 214.0, 0.1, 32.0, 0.4, 2.5, 2.4, 87.0, 0.0], + [29.2, 1553.0, 3.4, 213.0, 0.1, 33.0, 0.0, 0.0, 2.0, 0.0, 0.0], + [22.6, 2007.0, 3.6, 309.0, 0.2, 46.0, 0.4, 1.0, 4.0, 120.0, 0.0], + [14.6, 3107.0, 8.5, 404.0, 0.2, 62.0, 0.0, 0.9, 0.0, 0.0, 0.0], + [26.8, 1692.0, 2.2, 333.0, 0.2, 139.0, 169.2, 6.4, 50.8, 316.0, 525.0], + [27.6, 1643.0, 3.1, 245.0, 0.1, 20.0, 0.0, 2.8, 3.0, 86.0, 0.0], + [36.6, 1239.0, 3.3, 140.0, 0.1, 15.0, 0.0, 1.7, 2.7, 54.0, 0.0], + [30.7, 1477.0, 3.5, 196.0, 0.2, 80.0, 0.0, 17.4, 2.7, 60.0, 0.0], + [24.2, 1874.0, 4.4, 249.0, 0.3, 37.0, 0.0, 18.2, 3.6, 79.0, 0.0], + [25.6, 1772.0, 10.4, 152.0, 0.2, 23.0, 0.0, 1.8, 1.8, 71.0, 0.0], + [27.4, 1655.0, 6.7, 212.0, 0.2, 31.0, 0.0, 9.9, 3.3, 50.0, 0.0], + [16.0, 2835.0, 18.8, 164.0, 0.1, 26.0, 0.0, 1.4, 1.8, 0.0, 0.0], + [30.3, 1497.0, 1.8, 184.0, 0.1, 30.0, 0.1, 0.9, 1.8, 68.0, 46.0], + [42.3, 1072.0, 1.7, 156.0, 0.1, 24.0, 0.0, 1.4, 2.4, 57.0, 0.0], + [13.0, 3489.0, 5.8, 705.0, 6.8, 45.0, 3.5, 1.0, 4.9, 209.0, 0.0], + [4.4, 9072.0, 5.8, 27.0, 0.5, 36.0, 7.3, 3.6, 2.7, 5.0, 544.0], + [6.1, 4982.0, 4.9, 60.0, 0.4, 30.0, 17.4, 2.5, 3.5, 28.0, 498.0], + [26.0, 2380.0, 1.0, 21.0, 0.5, 14.0, 0.0, 0.5, 0.0, 4.0, 952.0], + [30.9, 4439.0, 2.2, 40.0, 1.1, 18.0, 11.1, 3.6, 1.3, 10.0, 1993.0], + [7.1, 5750.0, 2.4, 138.0, 3.7, 80.0, 69.0, 4.3, 5.8, 37.0, 862.0], + [3.7, 8949.0, 2.6, 125.0, 4.0, 36.0, 7.2, 9.0, 4.5, 26.0, 5369.0], + [4.7, 6080.0, 2.7, 73.0, 2.8, 43.0, 188.5, 6.1, 4.3, 89.0, 608.0], + [7.3, 3915.0, 0.9, 51.0, 3.0, 23.0, 0.9, 1.4, 1.4, 9.0, 313.0], + [8.2, 2247.0, 0.4, 27.0, 1.1, 22.0, 112.4, 1.8, 3.4, 11.0, 449.0], + [3.6, 11844.0, 5.8, 166.0, 3.8, 59.0, 16.6, 4.7, 5.9, 21.0, 1184.0], + [34.0, 16810.0, 14.3, 336.0, 1.8, 118.0, 6.7, 29.4, 7.1, 198.0, 2522.0], + [8.1, 4592.0, 1.1, 106.0, 0.0, 138.0, 918.4, 5.7, 13.8, 33.0, 2755.0], + [5.1, 7649.0, 9.6, 138.0, 2.7, 54.0, 290.7, 8.4, 5.4, 83.0, 1912.0], + [16.8, 4894.0, 3.7, 20.0, 0.4, 10.0, 21.5, 0.5, 1.0, 31.0, 196.0], + [20.4, 4030.0, 3.0, 8.0, 0.3, 8.0, 0.8, 0.8, 0.8, 5.0, 81.0], + [21.3, 3993.0, 2.4, 16.0, 0.4, 8.0, 2.0, 2.8, 0.8, 7.0, 399.0], + [27.7, 1945.0, 0.4, 33.0, 0.3, 12.0, 16.3, 1.4, 2.1, 17.0, 272.0], + [10.0, 5386.0, 1.0, 54.0, 2.0, 65.0, 53.9, 1.6, 4.3, 32.0, 431.0], + [7.1, 6389.0, 7.5, 364.0, 4.0, 134.0, 3.5, 8.3, 7.7, 56.0, 0.0], + [10.4, 5452.0, 5.2, 136.0, 0.2, 16.0, 12.0, 1.6, 2.7, 42.0, 218.0], + [13.8, 4109.0, 2.3, 136.0, 0.6, 45.0, 34.9, 4.9, 2.5, 37.0, 370.0], + [8.6, 6263.0, 1.3, 63.0, 0.7, 38.0, 53.2, 3.4, 2.5, 36.0, 1253.0], + [7.6, 3917.0, 1.6, 71.0, 0.6, 43.0, 57.9, 3.5, 2.4, 67.0, 862.0], + [15.7, 2889.0, 8.5, 87.0, 1.7, 173.0, 86.8, 1.2, 4.3, 55.0, 57.0], + [9.0, 4284.0, 12.8, 99.0, 2.5, 154.0, 85.7, 3.9, 4.3, 65.0, 257.0], + [9.4, 4524.0, 13.5, 104.0, 2.5, 136.0, 4.5, 6.3, 1.4, 24.0, 136.0], + [7.9, 5742.0, 20.0, 1367.0, 4.2, 345.0, 2.9, 28.7, 18.4, 162.0, 0.0], + [8.9, 5097.0, 17.4, 1055.0, 3.7, 459.0, 5.1, 26.9, 38.2, 93.0, 0.0], + [5.9, 7688.0, 26.9, 1691.0, 11.4, 792.0, 0.0, 38.4, 24.6, 217.0, 0.0], + [22.4, 2025.0, 0.0, 0.0, 0.0, 0.0, 0.0, 4.0, 5.1, 50.0, 0.0], + [17.4, 652.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 2.3, 42.0, 0.0], + [8.6, 2637.0, 8.7, 237.0, 3.0, 72.0, 0.0, 2.0, 11.9, 40.0, 0.0], + [16.2, 1400.0, 8.0, 77.0, 1.3, 39.0, 0.0, 0.9, 3.4, 14.0, 0.0], + [51.7, 8773.0, 34.9, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [13.7, 4996.0, 14.7, 0.0, 0.5, 74.0, 0.0, 0.0, 0.0, 5.0, 0.0], + [13.6, 3752.0, 9.0, 0.0, 10.3, 244.0, 0.0, 1.9, 7.5, 146.0, 0.0], + [20.5, 2213.0, 6.4, 11.0, 0.4, 7.0, 0.2, 0.2, 0.4, 3.0, 0.0]] # recommended daily allowance for a moderately active man - allowance = [3.0, 70.0, 0.8, 12.0, 5.0, 1.8, 2.7, 18.0, 75.0] - + allowance = [3.0, 70.0, 0.8, 12.0, 5.0, 1.8, 2.7, 18.0, 75.0] # # variables # - x = [solver.NumVar(0, 1000, 'x[%i]' % i) for i in C] - x_cost = [solver.NumVar(0, 1000, 'x_cost[%i]' % i) for i in C] - quant = [solver.NumVar(0, 1000, 'quant[%i]' % i) for i in C] + x = [solver.NumVar(0, 1000, "x[%i]" % i) for i in C] + x_cost = [solver.NumVar(0, 1000, "x_cost[%i]" % i) for i in C] + quant = [solver.NumVar(0, 1000, "quant[%i]" % i) for i in C] # total food bill - total_cost = solver.NumVar(0, 1000, 'total_cost') + total_cost = solver.NumVar(0, 1000, "total_cost") # cost per day, to minimize cost = solver.Sum(x) @@ -345,16 +342,15 @@ def main(sol = 'GLPK'): # # constraints # - solver.Add(total_cost == days * cost) # cost per year + solver.Add(total_cost == days * cost) # cost per year for c in C: - solver.Add(x_cost[c] == days*x[c]) - solver.Add(quant[c] == 100.0*days*x[c] / data[c][0]) + solver.Add(x_cost[c] == days * x[c]) + solver.Add(quant[c] == 100.0 * days * x[c] / data[c][0]) # nutrient balance - for n in range(2, num_nutrients+2): - solver.Add(solver.Sum([data[c][n] * x[c] for c in C]) >= allowance[n-2]) - + for n in range(2, num_nutrients + 2): + solver.Add(solver.Sum([data[c][n] * x[c] for c in C]) >= allowance[n - 2]) objective = solver.Minimize(cost) @@ -365,29 +361,29 @@ def main(sol = 'GLPK'): print - print 'Cost = %0.2f' % solver.Objective().Value() + print "Cost = %0.2f" % solver.Objective().Value() # print 'Cost:', cost.SolutionValue() - print 'Total cost: %0.2f' % total_cost.SolutionValue() + print "Total cost: %0.2f" % total_cost.SolutionValue() print for i in C: if x[i].SolutionValue() > 0: print "%-21s %-11s %0.2f %0.2f" % (commodities[i][0], commodities[i][1], - x_cost[i].SolutionValue(), quant[i].SolutionValue()) + x_cost[i].SolutionValue(), quant[i].SolutionValue()) print - print 'walltime :', solver.WallTime(), 'ms' - if sol == 'CBC': - print 'iterations:', solver.Iterations() + print "walltime :", solver.WallTime(), "ms" + if sol == "CBC": + print "iterations:", solver.Iterations() -if __name__ == '__main__': - sol = 'GLPK' +if __name__ == "__main__": + sol = "GLPK" - if len(sys.argv) > 1: - sol = sys.argv[1] - if sol != 'GLPK' and sol != 'CBC': - print 'Solver must be either GLPK or CBC' - sys.exit(1) + if len(sys.argv) > 1: + sol = sys.argv[1] + if sol != "GLPK" and sol != "CBC": + print "Solver must be either GLPK or CBC" + sys.exit(1) - main(sol) + main(sol) diff --git a/examples/python/strimko2.py b/examples/python/strimko2.py index c4ec4c8911..026bd3dac7 100644 --- a/examples/python/strimko2.py +++ b/examples/python/strimko2.py @@ -48,111 +48,111 @@ import sys from ortools.constraint_solver import pywrapcp -def main(streams="", placed=""): - # Create the solver. - solver = pywrapcp.Solver('Strimko') +def main(streams='', placed=''): - # - # default problem - # - if streams == "": - streams = [ - [1,1,2,2,2,2,2], - [1,1,2,3,3,3,2], - [1,4,1,3,3,5,5], - [4,4,3,1,3,5,5], - [4,6,6,6,7,7,5], - [6,4,6,4,5,5,7], - [6,6,4,7,7,7,7]] + # Create the solver. + solver = pywrapcp.Solver('Strimko') - # Note: This is 1-based - placed = [ - [2,1,1], - [2,3,7], - [2,5,6], - [2,7,4], - [3,2,7], - [3,6,1], - [4,1,4], - [4,7,5], - [5,2,2], - [5,6,6]] + # + # default problem + # + if streams == '': + streams = [ + [1, 1, 2, 2, 2, 2, 2], + [1, 1, 2, 3, 3, 3, 2], + [1, 4, 1, 3, 3, 5, 5], + [4, 4, 3, 1, 3, 5, 5], + [4, 6, 6, 6, 7, 7, 5], + [6, 4, 6, 4, 5, 5, 7], + [6, 6, 4, 7, 7, 7, 7]] - n = len(streams) - num_placed = len(placed) + # Note: This is 1-based + placed = [ + [2, 1, 1], + [2, 3, 7], + [2, 5, 6], + [2, 7, 4], + [3, 2, 7], + [3, 6, 1], + [4, 1, 4], + [4, 7, 5], + [5, 2, 2], + [5, 6, 6]] - print "n:", n + n = len(streams) + num_placed = len(placed) - # - # variables - # + print 'n:', n - x = {} + # + # variables + # + + x = {} + for i in range(n): + for j in range(n): + x[i, j] = solver.IntVar(1, n, 'x[%i,%i]' % (i, j)) + + x_flat = [x[i, j] for i in range(n) for j in range(n)] + + # + # constraints + # + + # all rows and columns must be unique, i.e. a Latin Square + for i in range(n): + row = [x[i, j] for j in range(n)] + solver.Add(solver.AllDifferent(row)) + + col = [x[j, i] for j in range(n)] + solver.Add(solver.AllDifferent(col)) + + # + # streams + # + for s in range(1, n + 1): + tmp = [x[i, j] for i in range(n) for j in range(n) if streams[i][j] == s] + solver.Add(solver.AllDifferent(tmp)) + + # + # placed + # + for i in range(num_placed): + # note: also adjust to 0-based + solver.Add(x[placed[i][0] - 1, placed[i][1] - 1] == placed[i][2]) + + # + # search and solution + # + db = solver.Phase(x_flat, + solver.INT_VAR_DEFAULT, + solver.INT_VALUE_DEFAULT) + + solver.NewSearch(db) + + num_solutions = 0 + while solver.NextSolution(): for i in range(n): - for j in range(n): - x[i,j] = solver.IntVar(1, n, 'x[%i,%i]' % (i,j)) - - x_flat = [x[i,j] for i in range(n) for j in range(n)] - - # - # constraints - # - - # all rows and columns must be unique, i.e. a Latin Square - for i in range(n): - row = [x[i,j] for j in range(n)] - solver.Add(solver.AllDifferent(row)) - - col = [x[j,i] for j in range(n)] - solver.Add(solver.AllDifferent(col)) - - # - # streams - # - for s in range(1, n+1): - tmp = [x[i,j] for i in range(n) for j in range(n) if streams[i][j] == s] - solver.Add(solver.AllDifferent(tmp)) - - # - # placed - # - for i in range(num_placed): - # note: also adjust to 0-based - solver.Add(x[placed[i][0]-1, placed[i][1]-1] == placed[i][2]) - - - # - # search and solution - # - db = solver.Phase(x_flat, - solver.INT_VAR_DEFAULT, - solver.INT_VALUE_DEFAULT) - - solver.NewSearch(db) - - num_solutions = 0 - while solver.NextSolution(): - for i in range(n): - for j in range(n): - print x[i,j].Value(), - print - - print - num_solutions += 1 - - solver.EndSearch() + for j in range(n): + print x[i, j].Value(), + print print - print 'num_solutions:', num_solutions - print 'failures:', solver.Failures() - print 'branches:', solver.Branches() - print 'WallTime:', solver.WallTime(), 'ms' + num_solutions += 1 + + solver.EndSearch() + + print + print 'num_solutions:', num_solutions + print 'failures:', solver.Failures() + print 'branches:', solver.Branches() + print 'WallTime:', solver.WallTime(), 'ms' if __name__ == '__main__': - if len(sys.argv) > 1: - problem_file = sys.argv[1] - execfile(problem_file) - main(streams, placed) - else: - main() + if len(sys.argv) > 1: + problem_file = sys.argv[1] + execfile(problem_file) + main(streams, placed) + else: + main() diff --git a/examples/python/subset_sum.py b/examples/python/subset_sum.py index 28a976535d..2e0750c066 100644 --- a/examples/python/subset_sum.py +++ b/examples/python/subset_sum.py @@ -36,76 +36,76 @@ * SICStus: http://hakank.org/sicstus/subset_sum.pl This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ -import string, sys +import string +import sys from ortools.constraint_solver import pywrapcp def subset_sum(solver, values, total): - n = len(values) - x = [solver.IntVar(0, n) for i in range(n)] - ss = solver.IntVar(0, n) + n = len(values) + x = [solver.IntVar(0, n) for i in range(n)] + ss = solver.IntVar(0, n) + solver.Add(ss == solver.Sum(x)) + solver.Add(total == solver.ScalProd(x, values)) - solver.Add(ss == solver.Sum(x)) - solver.Add(total == solver.ScalProd(x, values)) + return x, ss - return x, ss def main(coins, total): - # Create the solver. - solver = pywrapcp.Solver('n-queens') + # Create the solver. + solver = pywrapcp.Solver("n-queens") - # - # data - # - print "coins:", coins - print "total:", total + # + # data + # + print "coins:", coins + print "total:", total + print + + # + # declare variables + # + + # + # constraints + # + x, ss = subset_sum(solver, coins, total) + + # + # solution and search + # + solution = solver.Assignment() + solution.Add(x) + solution.Add(ss) + + # db: DecisionBuilder + db = solver.Phase(x, + solver.CHOOSE_FIRST_UNBOUND, + solver.ASSIGN_MIN_VALUE) + + solver.NewSearch(db) + num_solutions = 0 + while solver.NextSolution(): + print "ss:", ss.Value() + print "x: ", [x[i].Value() for i in range(len(x))] print + num_solutions += 1 + solver.EndSearch() - # - # declare variables - # - - # - # constraints - # - x, ss = subset_sum(solver, coins, total) - - - # - # solution and search - # - solution = solver.Assignment() - solution.Add(x) - solution.Add(ss) - - # db: DecisionBuilder - db = solver.Phase(x, - solver.CHOOSE_FIRST_UNBOUND, - solver.ASSIGN_MIN_VALUE - ) - - solver.NewSearch(db) - num_solutions = 0 - while solver.NextSolution(): - print "ss:", ss.Value() - print "x: ", [x[i].Value() for i in range(len(x))] - print - num_solutions += 1 - solver.EndSearch() - - print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() coins = [16, 17, 23, 24, 39, 40] total = 100 -if __name__ == '__main__': - if len(sys.argv) > 1: - total = string.atoi(sys.argv[1]) - main(coins, total) +if __name__ == "__main__": + if len(sys.argv) > 1: + total = string.atoi(sys.argv[1]) + main(coins, total) diff --git a/examples/python/sudoku.py b/examples/python/sudoku.py index 08ef25a81a..cbd81b4e09 100644 --- a/examples/python/sudoku.py +++ b/examples/python/sudoku.py @@ -15,7 +15,6 @@ """This model implements a sudoku solver.""" - from google.apputils import app import gflags from ortools.constraint_solver import pywrapcp diff --git a/examples/python/survo_puzzle.py b/examples/python/survo_puzzle.py index 3543441857..7af8611130 100644 --- a/examples/python/survo_puzzle.py +++ b/examples/python/survo_puzzle.py @@ -23,7 +23,8 @@ Survo system which is a general environment for statistical computing and related areas. - In a Survo puzzle the task is to fill an m * n table by integers 1,2,...,m*n so + In a Survo puzzle the task is to fill an m * n table by integers 1,2,...,m*n + so that each of these numbers appears only once and their row and column sums are equal to integers given on the bottom and the right side of the table. Often some of the integers are given readily in the table in order to @@ -56,7 +57,8 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ import sys @@ -65,115 +67,113 @@ from ortools.constraint_solver import pywrapcp def main(r=0, c=0, rowsums=[], colsums=[], game=[]): - # Create the solver. - solver = pywrapcp.Solver('Survo puzzle') + # Create the solver. + solver = pywrapcp.Solver("Survo puzzle") - # - # data - # - if r == 0: - r = 3 - c = 4 - rowsums = [30,18,30] - colsums = [27,16,10,25] - game = [[0, 6, 0, 0], - [8, 0, 0, 0], - [0, 0, 3, 0]] + # + # data + # + if r == 0: + r = 3 + c = 4 + rowsums = [30, 18, 30] + colsums = [27, 16, 10, 25] + game = [[0, 6, 0, 0], + [8, 0, 0, 0], + [0, 0, 3, 0]] - print "r:", r, "c:",c - - - # declare variables - x = {} - for i in range(r): - for j in range(c): - x[(i,j)] = solver.IntVar(1,r*c, 'x %i %i' % (i, j)) - - # - # constraints - # - - # - # set the clues - # - for i in range(r): - for j in range(c): - if game[i][j] > 0: - solver.Add(x[i,j] == game[i][j]) - - - xflat = [x[(i,j)] for i in range(r) for j in range(c)] - solver.Add(solver.AllDifferent(xflat)) - # - # calculate rowsums and colsums - # - for i in range(r): - solver.Add(rowsums[i] == solver.Sum([x[i,j] for j in range(c)])) + print "r:", r, "c:", c + # declare variables + x = {} + for i in range(r): for j in range(c): - solver.Add(colsums[j] == solver.Sum([x[i,j] for i in range(r)])) + x[(i, j)] = solver.IntVar(1, r * c, "x %i %i" % (i, j)) - # - # solution and search - # - solution = solver.Assignment() - solution.Add([x[(i,j)] for i in range(r) for j in range(c)]) + # + # constraints + # - collector = solver.AllSolutionCollector(solution) - solver.Solve(solver.Phase(xflat, - solver.CHOOSE_FIRST_UNBOUND, - solver.ASSIGN_MIN_VALUE), - [collector]) + # + # set the clues + # + for i in range(r): + for j in range(c): + if game[i][j] > 0: + solver.Add(x[i, j] == game[i][j]) - num_solutions = collector.SolutionCount() - print "\nnum_solutions: ", num_solutions - if num_solutions > 0: - for s in range(num_solutions): - xval = [collector.Value(s, x[(i,j)]) - for i in range(r) for j in range(c)] + xflat = [x[(i, j)] for i in range(r) for j in range(c)] + solver.Add(solver.AllDifferent(xflat)) + # + # calculate rowsums and colsums + # + for i in range(r): + solver.Add(rowsums[i] == solver.Sum([x[i, j] for j in range(c)])) - for i in range(r): - for j in range(c): - print "%2i" % (xval[i*c+j]), - print - print + for j in range(c): + solver.Add(colsums[j] == solver.Sum([x[i, j] for i in range(r)])) + # + # solution and search + # + solution = solver.Assignment() + solution.Add([x[(i, j)] for i in range(r) for j in range(c)]) + + collector = solver.AllSolutionCollector(solution) + solver.Solve(solver.Phase(xflat, + solver.CHOOSE_FIRST_UNBOUND, + solver.ASSIGN_MIN_VALUE), + [collector]) + + num_solutions = collector.SolutionCount() + print "\nnum_solutions: ", num_solutions + if num_solutions > 0: + for s in range(num_solutions): + xval = [collector.Value(s, x[(i, j)]) + for i in range(r) for j in range(c)] + + for i in range(r): + for j in range(c): + print "%2i" % (xval[i * c + j]), print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + print - else: - print "No solutions found" + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() + + else: + print "No solutions found" # # Read a problem instance from a file # def read_problem(file): - f = open(file, 'r') - r = int(f.readline()) - c = int(f.readline()) - rowsums = f.readline() - colsums = f.readline() - rowsums = [int(t) for t in (rowsums.rstrip()).split(",")] - colsums = [int(t) for t in (colsums.rstrip()).split(",")] - game = [] - for i in range(r): - x = f.readline() - x = [int(t) for t in (x.rstrip()).split(",")] - row = [0]*c - for j in range(c): - row[j] = int(x[j]) - game.append(row) - return [r, c, rowsums, colsums, game] + f = open(file, "r") + r = int(f.readline()) + c = int(f.readline()) + rowsums = f.readline() + colsums = f.readline() + rowsums = [int(t) for t in (rowsums.rstrip()).split(",")] + colsums = [int(t) for t in (colsums.rstrip()).split(",")] + game = [] + for i in range(r): + x = f.readline() + x = [int(t) for t in (x.rstrip()).split(",")] + row = [0] * c + for j in range(c): + row[j] = int(x[j]) + game.append(row) + return [r, c, rowsums, colsums, game] -if __name__ == '__main__': - if len(sys.argv) > 1: - file = sys.argv[1] - [r, c, rowsums, colsums, game] = read_problem(file) - main(r, c, rowsums, colsums, game) - else: - main() +if __name__ == "__main__": + if len(sys.argv) > 1: + file = sys.argv[1] + [r, c, rowsums, colsums, game] = read_problem(file) + main(r, c, rowsums, colsums, game) + else: + main() diff --git a/examples/python/toNum.py b/examples/python/toNum.py index 19562a7038..783db14d2a 100644 --- a/examples/python/toNum.py +++ b/examples/python/toNum.py @@ -19,67 +19,69 @@ Convert a number <-> array of int in a specific base. This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ - - from ortools.constraint_solver import pywrapcp # # converts a number (s) <-> an array of integers (t) in the specific base. # + + def toNum(solver, t, s, base): - tlen = len(t) - solver.Add(s == solver.Sum([(base**(tlen-i-1))*t[i] for i in range(tlen)])) + tlen = len(t) + solver.Add( + s == solver.Sum([(base ** (tlen - i - 1)) * t[i] for i in range(tlen)])) def main(unused_argv): - # Create the solver. - solver = pywrapcp.Solver('toNum test') + # Create the solver. + solver = pywrapcp.Solver("toNum test") - # data - n = 4 - base = 10 + # data + n = 4 + base = 10 - # declare variables - x = [solver.IntVar(0,n-1, 'x%i' % i) for i in range(n)] - y = solver.IntVar(0,10**n-1, 'y') + # declare variables + x = [solver.IntVar(0, n - 1, "x%i" % i) for i in range(n)] + y = solver.IntVar(0, 10 ** n - 1, "y") - # - # constraints - # - # solver.Add(solver.AllDifferent([x[i] for i in range(n)])) - solver.Add(solver.AllDifferent(x)) - # solver.Add(x[0] > 0) # just for fun + # + # constraints + # + # solver.Add(solver.AllDifferent([x[i] for i in range(n)])) + solver.Add(solver.AllDifferent(x)) + # solver.Add(x[0] > 0) # just for fun - toNum(solver, x, y, base) + toNum(solver, x, y, base) - # - # solution and search - # - solution = solver.Assignment() - solution.Add([x[i] for i in range(n)]) - solution.Add(y) + # + # solution and search + # + solution = solver.Assignment() + solution.Add([x[i] for i in range(n)]) + solution.Add(y) - collector = solver.AllSolutionCollector(solution) - solver.Solve(solver.Phase([x[i] for i in range(n)], - solver.CHOOSE_FIRST_UNBOUND, - solver.ASSIGN_MIN_VALUE), - [collector]) + collector = solver.AllSolutionCollector(solution) + solver.Solve(solver.Phase([x[i] for i in range(n)], + solver.CHOOSE_FIRST_UNBOUND, + solver.ASSIGN_MIN_VALUE), + [collector]) - num_solutions = collector.SolutionCount() - for s in range(num_solutions): - print "x:", [collector.Value(s, x[i]) for i in range(n)] - print "y:", collector.Value(s, y) - print + num_solutions = collector.SolutionCount() + for s in range(num_solutions): + print "x:", [collector.Value(s, x[i]) for i in range(n)] + print "y:", collector.Value(s, y) + print - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() -if __name__ == '__main__': - main("cp sample") +if __name__ == "__main__": + main("cp sample") diff --git a/examples/python/traffic_lights.py b/examples/python/traffic_lights.py index c876fe2ec7..38a2bff057 100644 --- a/examples/python/traffic_lights.py +++ b/examples/python/traffic_lights.py @@ -20,27 +20,36 @@ http://www.cs.st-andrews.ac.uk/~ianm/CSPLib/prob/prob016/index.html ''' Specification: - Consider a four way traffic junction with eight traffic lights. Four of the traffic - lights are for the vehicles and can be represented by the variables V1 to V4 with domains - {r,ry,g,y} (for red, red-yellow, green and yellow). The other four traffic lights are - for the pedestrians and can be represented by the variables P1 to P4 with domains {r,g}. + Consider a four way traffic junction with eight traffic lights. Four of the + traffic + lights are for the vehicles and can be represented by the variables V1 to V4 + with domains + {r,ry,g,y} (for red, red-yellow, green and yellow). The other four traffic + lights are + for the pedestrians and can be represented by the variables P1 to P4 with + domains {r,g}. - The constraints on these variables can be modelled by quaternary constraints on + The constraints on these variables can be modelled by quaternary constraints + on (Vi, Pi, Vj, Pj ) for 1<=i<=4, j=(1+i)mod 4 which allow just the tuples {(r,r,g,g), (ry,r,y,r), (g,g,r,r), (y,r,ry,r)}. It would be interesting to consider other types of junction (e.g. five roads - intersecting) as well as modelling the evolution over time of the traffic light sequence. + intersecting) as well as modelling the evolution over time of the traffic + light sequence. ... Results Only 2^2 out of the 2^12 possible assignments are solutions. (V1,P1,V2,P2,V3,P3,V4,P4) = - {(r,r,g,g,r,r,g,g), (ry,r,y,r,ry,r,y,r), (g,g,r,r,g,g,r,r), (y,r,ry,r,y,r,ry,r)} - [(1,1,3,3,1,1,3,3), ( 2,1,4,1, 2,1,4,1), (3,3,1,1,3,3,1,1), (4,1, 2,1,4,1, 2,1)} + {(r,r,g,g,r,r,g,g), (ry,r,y,r,ry,r,y,r), (g,g,r,r,g,g,r,r), + (y,r,ry,r,y,r,ry,r)} + [(1,1,3,3,1,1,3,3), ( 2,1,4,1, 2,1,4,1), (3,3,1,1,3,3,1,1), (4,1, 2,1,4,1, + 2,1)} - The problem has relative few constraints, but each is very tight. Local propagation + The problem has relative few constraints, but each is very tight. Local + propagation appears to be rather ineffective on this problem. ''' @@ -57,73 +66,74 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ -import string, sys +import string +import sys from ortools.constraint_solver import pywrapcp def main(base=10, start=1, len1=1, len2=4): - # Create the solver. - solver = pywrapcp.Solver('Traffic lights') + # Create the solver. + solver = pywrapcp.Solver("Traffic lights") - # - # data - # - n = 4 - r, ry, g, y = range(n) - lights = ["r", "ry", "g", "y"] + # + # data + # + n = 4 + r, ry, g, y = range(n) + lights = ["r", "ry", "g", "y"] - # The allowed combinations - allowed = pywrapcp.IntTupleSet(4) - allowed.InsertAll([(r,r,g,g), - (ry,r,y,r), - (g,g,r,r), - (y,r,ry,r)]) + # The allowed combinations + allowed = pywrapcp.IntTupleSet(4) + allowed.InsertAll([(r, r, g, g), + (ry, r, y, r), + (g, g, r, r), + (y, r, ry, r)]) + # + # declare variables + # + V = [solver.IntVar(0, n - 1, "V[%i]" % i) for i in range(n)] + P = [solver.IntVar(0, n - 1, "P[%i]" % i) for i in range(n)] - # - # declare variables - # - V = [solver.IntVar(0, n-1, 'V[%i]' % i) for i in range(n)] - P = [solver.IntVar(0, n-1, 'P[%i]' % i) for i in range(n)] + # + # constraints + # + for i in range(n): + for j in range(n): + if j == (1 + i) % n: + solver.Add(solver.AllowedAssignments((V[i], P[i], V[j], P[j]), allowed)) - # - # constraints - # + # + # Search and result + # + db = solver.Phase(V + P, + solver.INT_VAR_SIMPLE, + solver.INT_VALUE_DEFAULT) + + solver.NewSearch(db) + num_solutions = 0 + while solver.NextSolution(): for i in range(n): - for j in range(n): - if j == (1+i) % n: - solver.Add(solver.AllowedAssignments((V[i], P[i], V[j], P[j]), allowed)) - - # - # Search and result - # - db = solver.Phase(V + P, - solver.INT_VAR_SIMPLE, - solver.INT_VALUE_DEFAULT) - - solver.NewSearch(db) - num_solutions = 0 - while solver.NextSolution(): - for i in range(n): - print "%+2s %+2s" % (lights[V[i].Value()], lights[P[i].Value()]), - print - num_solutions += 1 - - solver.EndSearch() - - print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + print "%+2s %+2s" % (lights[V[i].Value()], lights[P[i].Value()]), print + num_solutions += 1 + + solver.EndSearch() + + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() + print -if __name__ == '__main__': - main() +if __name__ == "__main__": + main() diff --git a/examples/python/tsp.py b/examples/python/tsp.py index 2c004419f4..4fc1bfe0ab 100644 --- a/examples/python/tsp.py +++ b/examples/python/tsp.py @@ -25,7 +25,6 @@ """ - import random from google.apputils import app @@ -35,11 +34,11 @@ from ortools.constraint_solver import pywrapcp FLAGS = gflags.FLAGS gflags.DEFINE_integer('tsp_size', 10, - 'Size of Traveling Salesman Problem instance.') + 'Size of Traveling Salesman Problem instance.') gflags.DEFINE_boolean('tsp_use_random_matrix', True, - 'Use random cost matrix.') + 'Use random cost matrix.') gflags.DEFINE_integer('tsp_random_forbidden_connections', 0, - 'Number of random forbidden connections.') + 'Number of random forbidden connections.') gflags.DEFINE_integer('tsp_random_seed', 0, 'Random seed.') gflags.DEFINE_boolean('light_propagation', False, 'Use light propagation') diff --git a/examples/python/volsay.py b/examples/python/volsay.py index f83b90eb1c..c6c98ce5a0 100644 --- a/examples/python/volsay.py +++ b/examples/python/volsay.py @@ -19,24 +19,25 @@ From the OPL model volsay.mod This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ from ortools.linear_solver import pywraplp + def main(unused_argv): # Create the solver. # using GLPK solver = pywraplp.Solver('CoinsGridGLPK', - pywraplp.Solver.GLPK_LINEAR_PROGRAMMING) + pywraplp.Solver.GLPK_LINEAR_PROGRAMMING) # Using CLP # solver = pywraplp.Solver('CoinsGridCLP', # pywraplp.Solver.CLP_LINEAR_PROGRAMMING) - # data # declare variables @@ -52,10 +53,8 @@ def main(unused_argv): # objective objective = solver.Maximize(40 * Gas + 50 * Chloride) - print 'NumConstraints:', solver.NumConstraints() - # # solution and search # @@ -67,4 +66,4 @@ def main(unused_argv): print 'Chloride:', Chloride.SolutionValue(), 'ReducedCost =', Chloride.ReducedCost() if __name__ == '__main__': - main('Volsay') + main('Volsay') diff --git a/examples/python/volsay2.py b/examples/python/volsay2.py index cbe7872b1d..89f2b09a68 100644 --- a/examples/python/volsay2.py +++ b/examples/python/volsay2.py @@ -20,24 +20,25 @@ Using arrays. This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ from ortools.linear_solver import pywraplp + def main(unused_argv): # Create the solver. # using GLPK solver = pywraplp.Solver('CoinsGridGLPK', - pywraplp.Solver.GLPK_LINEAR_PROGRAMMING) + pywraplp.Solver.GLPK_LINEAR_PROGRAMMING) # Using CLP # solver = pywraplp.Solver('CoinsGridCLP', # pywraplp.Solver.CLP_LINEAR_PROGRAMMING) - # data num_products = 2 Gas = 0 @@ -46,7 +47,7 @@ def main(unused_argv): products = ['Gas', 'Chloride'] # declare variables - production = [solver.NumVar(0, 100000, 'production[%i]' % i ) + production = [solver.NumVar(0, 100000, 'production[%i]' % i) for i in range(num_products)] # @@ -58,7 +59,6 @@ def main(unused_argv): # objective objective = solver.Maximize(40 * production[Gas] + 50 * production[Chloride]) - print 'NumConstraints:', solver.NumConstraints() # @@ -69,8 +69,8 @@ def main(unused_argv): print print 'objective = ', solver.Objective().Value() for i in range(num_products): - print products[i], '=', production[i].SolutionValue(), - print 'ReducedCost = ', production[i].ReducedCost() + print products[i], '=', production[i].SolutionValue(), + print 'ReducedCost = ', production[i].ReducedCost() if __name__ == '__main__': - main('Volsay') + main('Volsay') diff --git a/examples/python/volsay3.py b/examples/python/volsay3.py index 781e998b81..e6db791079 100644 --- a/examples/python/volsay3.py +++ b/examples/python/volsay3.py @@ -20,52 +20,51 @@ Using arrays. This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ from ortools.linear_solver import pywraplp + def main(unused_argv): # Create the solver. # using GLPK solver = pywraplp.Solver('CoinsGridGLPK', - pywraplp.Solver.GLPK_LINEAR_PROGRAMMING) + pywraplp.Solver.GLPK_LINEAR_PROGRAMMING) # Using CLP # solver = pywraplp.Solver('CoinsGridCLP', # pywraplp.Solver.CLP_LINEAR_PROGRAMMING) - # data num_products = 2 products = ['Gas', 'Chloride'] components = ['nitrogen', 'hydrogen', 'chlorine'] - demand = [ [1,3,0], [1,4,1]] - profit = [30,40] - stock = [50,180,40] + demand = [[1, 3, 0], [1, 4, 1]] + profit = [30, 40] + stock = [50, 180, 40] # declare variables - production = [solver.NumVar(0, 100000, 'production[%i]' % i ) + production = [solver.NumVar(0, 100000, 'production[%i]' % i) for i in range(num_products)] # # constraints # for c in range(len(components)): - solver.Add(solver.Sum([demand[p][c]*production[p] - for p in range(len(products)) ]) <= stock[c]) - + solver.Add(solver.Sum([demand[p][c] * production[p] + for p in range(len(products))]) <= stock[c]) # objective # Note: there is no support for solver.ScalProd in the LP/IP interface - objective = solver.Maximize(solver.Sum([production[p]*profit[p] + objective = solver.Maximize(solver.Sum([production[p] * profit[p] for p in range(num_products)])) - print 'NumConstraints:', solver.NumConstraints() print 'NumVariables:', solver.NumVariables() print @@ -78,8 +77,8 @@ def main(unused_argv): print print 'objective = ', solver.Objective().Value() for i in range(num_products): - print products[i], '=', production[i].SolutionValue(), - print 'ReducedCost = ', production[i].ReducedCost() + print products[i], '=', production[i].SolutionValue(), + print 'ReducedCost = ', production[i].ReducedCost() print print 'walltime :', solver.WallTime(), 'ms' @@ -87,4 +86,4 @@ def main(unused_argv): if __name__ == '__main__': - main('Volsay') + main('Volsay') diff --git a/examples/python/who_killed_agatha.py b/examples/python/who_killed_agatha.py index 1c8b85c3b2..f67671a137 100644 --- a/examples/python/who_killed_agatha.py +++ b/examples/python/who_killed_agatha.py @@ -14,7 +14,8 @@ """ - Who killed agatha? (The Dreadsbury Mansion Murder Mystery) in Google CP Solver. + Who killed agatha? (The Dreadsbury Mansion Murder Mystery) in Google CP + Solver. This is a standard benchmark for theorem proving. @@ -56,160 +57,159 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ from collections import defaultdict from ortools.constraint_solver import pywrapcp + def var_matrix_array(solver, rows, cols, lb, ub, name): - x = [] - for i in range(rows): - t = [] - for j in range(cols): - t.append(solver.IntVar(lb, ub, '%s[%i,%i]'%(name, i,j))) - x.append(t) - return x + x = [] + for i in range(rows): + t = [] + for j in range(cols): + t.append(solver.IntVar(lb, ub, "%s[%i,%i]" % (name, i, j))) + x.append(t) + return x + def flatten_matrix(solver, m, rows, cols): - return [m[i][j] for i in range(rows) for j in range(cols)] + return [m[i][j] for i in range(rows) for j in range(cols)] def print_flat_matrix(m_flat, rows, cols): - for i in range(rows): - for j in range(cols): - print m_flat[i*cols+j].Value(), - print + for i in range(rows): + for j in range(cols): + print m_flat[i * cols + j].Value(), print + print def main(the_killers): - # Create the solver. - solver = pywrapcp.Solver('Who killed agatha?') + # Create the solver. + solver = pywrapcp.Solver("Who killed agatha?") - # - # data - # - n = 3 - agatha = 0 - butler = 1 - charles = 2 + # + # data + # + n = 3 + agatha = 0 + butler = 1 + charles = 2 - # - # declare variables - # - the_killer = solver.IntVar(0,2, 'the_killer') - the_victim = solver.IntVar(0,2, 'the_victim' ) + # + # declare variables + # + the_killer = solver.IntVar(0, 2, "the_killer") + the_victim = solver.IntVar(0, 2, "the_victim") - hates = var_matrix_array(solver, n, n, 0, 1, 'hates') - richer = var_matrix_array(solver, n, n, 0, 1, 'richer') + hates = var_matrix_array(solver, n, n, 0, 1, "hates") + richer = var_matrix_array(solver, n, n, 0, 1, "richer") - hates_flat = flatten_matrix(solver, hates, n, n) - richer_flat = flatten_matrix(solver, richer, n, n) + hates_flat = flatten_matrix(solver, hates, n, n) + richer_flat = flatten_matrix(solver, richer, n, n) - # - # constraints - # + # + # constraints + # - # Agatha, the butler, and Charles live in Dreadsbury Mansion, and - # are the only ones to live there. + # Agatha, the butler, and Charles live in Dreadsbury Mansion, and + # are the only ones to live there. - # A killer always hates, and is no richer than his victim. - # solver.Add(hates[the_killer, the_victim] == 1) - solver.Add(solver.Element(hates_flat,the_killer*n+the_victim) == 1) + # A killer always hates, and is no richer than his victim. + # solver.Add(hates[the_killer, the_victim] == 1) + solver.Add(solver.Element(hates_flat, the_killer * n + the_victim) == 1) - # solver.Add(richer[the_killer, the_victim] == 0) - solver.Add(solver.Element(richer_flat,the_killer*n+the_victim) == 0) + # solver.Add(richer[the_killer, the_victim] == 0) + solver.Add(solver.Element(richer_flat, the_killer * n + the_victim) == 0) - # define the concept of richer: no one is richer than him-/herself - for i in range(n): - solver.Add(richer[i][i] == 0) + # define the concept of richer: no one is richer than him-/herself + for i in range(n): + solver.Add(richer[i][i] == 0) - # (contd...) if i is richer than j then j is not richer than i - # (i != j) => (richer[i,j] = 1) <=> (richer[j,i] = 0), - for i in range(n): - for j in range(n): - if i != j: - solver.Add((richer[i][j] == 1) == (richer[j][i] == 0)) + # (contd...) if i is richer than j then j is not richer than i + # (i != j) => (richer[i,j] = 1) <=> (richer[j,i] = 0), + for i in range(n): + for j in range(n): + if i != j: + solver.Add((richer[i][j] == 1) == (richer[j][i] == 0)) - # Charles hates noone that Agatha hates. - #forall i : Range . - # (hates[agatha, i] = 1) => (hates[charles, i] = 0), - for i in range(n): - solver.Add((hates[agatha][i]==1) <= (hates[charles][i] == 0)) + # Charles hates noone that Agatha hates. + # forall i : Range . + # (hates[agatha, i] = 1) => (hates[charles, i] = 0), + for i in range(n): + solver.Add((hates[agatha][i] == 1) <= (hates[charles][i] == 0)) - # Agatha hates everybody except the butler. - solver.Add(hates[agatha][charles] == 1) - solver.Add(hates[agatha][agatha] == 1) - solver.Add(hates[agatha][butler] == 0) + # Agatha hates everybody except the butler. + solver.Add(hates[agatha][charles] == 1) + solver.Add(hates[agatha][agatha] == 1) + solver.Add(hates[agatha][butler] == 0) + # The butler hates everyone not richer than Aunt Agatha. + # forall i : Range . + # (richer[i, agatha] = 0) => (hates[butler, i] = 1), + for i in range(n): + solver.Add((richer[i][agatha] == 0) <= (hates[butler][i] == 1)) - # The butler hates everyone not richer than Aunt Agatha. - # forall i : Range . - # (richer[i, agatha] = 0) => (hates[butler, i] = 1), - for i in range(n): - solver.Add((richer[i][agatha]==0) <= (hates[butler][i]==1)) + # The butler hates everyone whom Agatha hates. + # forall i : Range . + # (hates[agatha, i] = 1) => (hates[butler, i] = 1), + for i in range(n): + solver.Add((hates[agatha][i] == 1) <= (hates[butler][i] == 1)) + # Noone hates everyone. + # forall i : Range . + # (sum j : Range . hates[i,j]) <= 2, + for i in range(n): + solver.Add(solver.Sum([hates[i][j] for j in range(n)]) <= 2) - # The butler hates everyone whom Agatha hates. - #forall i : Range . - # (hates[agatha, i] = 1) => (hates[butler, i] = 1), - for i in range(n): - solver.Add((hates[agatha][i]==1) <= (hates[butler][i]==1)) + # Who killed Agatha? + solver.Add(the_victim == agatha) + # + # solution and search + # + solution = solver.Assignment() + solution.Add(the_killer) + solution.Add(the_victim) + solution.Add(hates_flat) + solution.Add(richer_flat) - # Noone hates everyone. - # forall i : Range . - # (sum j : Range . hates[i,j]) <= 2, - for i in range(n): - solver.Add(solver.Sum([hates[i][j] for j in range(n)]) <= 2) - - - # Who killed Agatha? - solver.Add(the_victim == agatha) - - # - # solution and search - # - solution = solver.Assignment() - solution.Add(the_killer) - solution.Add(the_victim) - solution.Add(hates_flat) - solution.Add(richer_flat) - - # db: DecisionBuilder - db = solver.Phase(hates_flat + richer_flat, - solver.CHOOSE_FIRST_UNBOUND, - solver.ASSIGN_MIN_VALUE) - - solver.NewSearch(db) - num_solutions = 0 - while solver.NextSolution(): - print "the_killer:", the_killer.Value() - the_killers[the_killer.Value()] += 1 - print "the_victim:", the_victim.Value() - print "hates:" - print_flat_matrix(hates_flat,n,n) - print "richer:" - print_flat_matrix(richer_flat,n,n) - print - num_solutions += 1 - - solver.EndSearch() + # db: DecisionBuilder + db = solver.Phase(hates_flat + richer_flat, + solver.CHOOSE_FIRST_UNBOUND, + solver.ASSIGN_MIN_VALUE) + solver.NewSearch(db) + num_solutions = 0 + while solver.NextSolution(): + print "the_killer:", the_killer.Value() + the_killers[the_killer.Value()] += 1 + print "the_victim:", the_victim.Value() + print "hates:" + print_flat_matrix(hates_flat, n, n) + print "richer:" + print_flat_matrix(richer_flat, n, n) print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + num_solutions += 1 + + solver.EndSearch() + + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() the_killers = defaultdict(int) p = ["agatha", "butler", "charles"] -if __name__ == '__main__': - main(the_killers) +if __name__ == "__main__": + main(the_killers) - print "\n" - for k in the_killers: - print "the killer %s was choosen in %i solutions" % (p[k], the_killers[k]) + print "\n" + for k in the_killers: + print "the killer %s was choosen in %i solutions" % (p[k], the_killers[k]) diff --git a/examples/python/word_square.py b/examples/python/word_square.py index 9035570f4c..6ef81116bf 100644 --- a/examples/python/word_square.py +++ b/examples/python/word_square.py @@ -35,120 +35,122 @@ * Zinc: http://hakank.org/minizinc/word_square.zinc This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ -import sys, string, re +import sys +import string +import re from ortools.constraint_solver import pywrapcp def main(words, word_len, num_answers=20): - # Create the solver. - solver = pywrapcp.Solver('Problem') + # Create the solver. + solver = pywrapcp.Solver("Problem") - # - # data - # - num_words = len(words) - n = word_len - d, rev = get_dict() + # + # data + # + num_words = len(words) + n = word_len + d, rev = get_dict() + # + # declare variables + # + A = {} + for i in range(num_words): + for j in range(word_len): + A[(i, j)] = solver.IntVar(0, 29, "A(%i,%i)" % (i, j)) - # - # declare variables - # - A = {} - for i in range(num_words): - for j in range(word_len): - A[(i,j)] = solver.IntVar(0,29, 'A(%i,%i)' % (i, j)) + A_flat = [A[(i, j)] for i in range(num_words) for j in range(word_len)] - A_flat = [A[(i,j)] for i in range(num_words) for j in range(word_len)] + E = [solver.IntVar(0, num_words, "E%i" % i) for i in range(n)] - E = [solver.IntVar(0, num_words, "E%i"%i) for i in range(n)] + # + # constraints + # + solver.Add(solver.AllDifferent(E)) - # - # constraints - # - solver.Add(solver.AllDifferent(E)) + # copy the words to a Matrix + for I in range(num_words): + for J in range(word_len): + solver.Add(A[(I, J)] == d[words[I][J]]) - # copy the words to a Matrix - for I in range(num_words): - for J in range(word_len): - solver.Add(A[(I,J)] == d[words[I][J]]) + for i in range(word_len): + for j in range(word_len): + # This is what I would like to do: + # solver.Add(A[(E[i],j)] == A[(E[j],i)]) + # We must use Element explicitly + solver.Add(solver.Element(A_flat, E[i] * word_len + j) == + solver.Element(A_flat, E[j] * word_len + i)) - for i in range(word_len): - for j in range(word_len): - # This is what I would like to do: - # solver.Add(A[(E[i],j)] == A[(E[j],i)]) + # + # solution and search + # + solution = solver.Assignment() + solution.Add(E) - # We must use Element explicitly - solver.Add(solver.Element(A_flat, E[i]*word_len+j) == - solver.Element(A_flat, E[j]*word_len+i)) + # db: DecisionBuilder + db = solver.Phase(E + A_flat, + solver.CHOOSE_FIRST_UNBOUND, + solver.ASSIGN_MIN_VALUE) + solver.NewSearch(db) + num_solutions = 0 + while solver.NextSolution(): + # print E + print_solution(E, words) + num_solutions += 1 - # - # solution and search - # - solution = solver.Assignment() - solution.Add(E) + solver.EndSearch() - # db: DecisionBuilder - db = solver.Phase(E + A_flat, - solver.CHOOSE_FIRST_UNBOUND, - solver.ASSIGN_MIN_VALUE) - - solver.NewSearch(db) - num_solutions = 0 - while solver.NextSolution(): - #print E - print_solution(E,words) - num_solutions += 1 - - solver.EndSearch() - - print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() # # convert a character to integer # def get_dict(): - alpha = "abcdefghijklmnopqrstuvwxyzåäö"; - d = {} - rev = {} - count = 1 - for a in alpha: - d[a] = count - rev[count] = a - count += 1 - return d, rev + alpha = "abcdefghijklmnopqrstuvwxyzåäö" + d = {} + rev = {} + count = 1 + for a in alpha: + d[a] = count + rev[count] = a + count += 1 + return d, rev -def print_solution(E,words): - # print E - for e in E: - print words[e.Value()] - print +def print_solution(E, words): + # print E + for e in E: + print words[e.Value()] + print + def read_words(word_list, word_len, limit): - dict = {} - all_words = [] - count = 0 - words = open(word_list).readlines() - for w in words: - w = string.strip(w).lower() - # if len(w) == word_len and not dict.has_key(w) and not re.search("[^a-zåäö]",w) and count < limit: - # Later note: The limit is not needed anymore with Mistral - if len(w) == word_len and not dict.has_key(w) and not re.search("[^a-zåäö]",w): - dict[w] = 1 - all_words.append(w) - count += 1 - return all_words + dict = {} + all_words = [] + count = 0 + words = open(word_list).readlines() + for w in words: + w = string.strip(w).lower() + # if len(w) == word_len and not dict.has_key(w) and not re.search("[^a-zåäö]",w) and count < limit: + # Later note: The limit is not needed anymore with Mistral + if len(w) == word_len and not dict.has_key(w) and not re.search( + "[^a-zåäö]", w): + dict[w] = 1 + all_words.append(w) + count += 1 + return all_words word_dict = "/usr/share/dict/words" @@ -156,18 +158,18 @@ word_len = 2 limit = 1000000 num_answers = 20 -if __name__ == '__main__': +if __name__ == "__main__": - if len(sys.argv) > 1: - word_dict = sys.argv[1] - if len(sys.argv) > 2: - word_len = int(sys.argv[2]) - if len(sys.argv) > 3: - limit = int(sys.argv[3]) - if len(sys.argv) > 4: - num_answers = int(sys.argv[4]) + if len(sys.argv) > 1: + word_dict = sys.argv[1] + if len(sys.argv) > 2: + word_len = int(sys.argv[2]) + if len(sys.argv) > 3: + limit = int(sys.argv[3]) + if len(sys.argv) > 4: + num_answers = int(sys.argv[4]) - # Note: I have to use a limit, otherwise it seg faults - words = read_words(word_dict, word_len, limit) - print "It was", len(words), "words" - main(words, word_len,num_answers) + # Note: I have to use a limit, otherwise it seg faults + words = read_words(word_dict, word_len, limit) + print "It was", len(words), "words" + main(words, word_len, num_answers) diff --git a/examples/python/xkcd.py b/examples/python/xkcd.py index 5755bebbe0..8e5454183d 100644 --- a/examples/python/xkcd.py +++ b/examples/python/xkcd.py @@ -33,7 +33,8 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_cp_solver/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_cp_solver/ """ from ortools.constraint_solver import pywrapcp @@ -41,71 +42,68 @@ from ortools.constraint_solver import pywrapcp def main(): - # Create the solver. - solver = pywrapcp.Solver('xkcd knapsack') + # Create the solver. + solver = pywrapcp.Solver("xkcd knapsack") - # - # data - # - num_prices = 6 - # for price and total: multiplied by 100 to be able to use integers - price = [215, 275, 335, 355, 420, 580] - total = 1505 + # + # data + # + num_prices = 6 + # for price and total: multiplied by 100 to be able to use integers + price = [215, 275, 335, 355, 420, 580] + total = 1505 - products = ["mixed fruit", "french fries", "side salad", - "host wings", "mozzarella sticks", "samples place"] + products = ["mixed fruit", "french fries", "side salad", + "host wings", "mozzarella sticks", "samples place"] - # declare variables + # declare variables - # how many items of each dish - x = [solver.IntVar(0,10, 'x%i' % i) for i in range(num_prices)] - z = solver.IntVar(0,1505,'z') + # how many items of each dish + x = [solver.IntVar(0, 10, "x%i" % i) for i in range(num_prices)] + z = solver.IntVar(0, 1505, "z") - # - # constraints - # - solver.Add(z == solver.Sum([x[i]*price[i] for i in range(num_prices)] )) - solver.Add(z == total) + # + # constraints + # + solver.Add(z == solver.Sum([x[i] * price[i] for i in range(num_prices)])) + solver.Add(z == total) - # - # solution and search - # - solution = solver.Assignment() - solution.Add([x[i] for i in range(num_prices)]) - solution.Add(z) + # + # solution and search + # + solution = solver.Assignment() + solution.Add([x[i] for i in range(num_prices)]) + solution.Add(z) + + collector = solver.AllSolutionCollector(solution) + # collector = solver.FirstSolutionCollector(solution) + # search_log = solver.SearchLog(100, x[0]) + solver.Solve(solver.Phase([x[i] for i in range(num_prices)], + solver.INT_VAR_SIMPLE, + solver.ASSIGN_MIN_VALUE), + [collector]) + + num_solutions = collector.SolutionCount() + print "num_solutions: ", num_solutions + if num_solutions > 0: + for s in range(num_solutions): + print "z:", collector.Value(s, z) + xval = [collector.Value(s, x[i]) for i in range(num_prices)] + print "x:", xval + for i in range(num_prices): + if xval[i] > 0: + print xval[i], "of", products[i], ":", price[i] / 100.0 + print + + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() + + else: + print "No solutions found" - collector = solver.AllSolutionCollector(solution) - # collector = solver.FirstSolutionCollector(solution) - # search_log = solver.SearchLog(100, x[0]) - solver.Solve(solver.Phase([x[i] for i in range(num_prices)], - solver.INT_VAR_SIMPLE, - solver.ASSIGN_MIN_VALUE), - [collector]) - - - num_solutions = collector.SolutionCount() - print "num_solutions: ", num_solutions - if num_solutions > 0: - for s in range(num_solutions): - print "z:", collector.Value(s, z) - xval = [collector.Value(s, x[i]) for i in range(num_prices)] - print "x:", xval - for i in range(num_prices): - if xval[i] > 0: - print xval[i], "of", products[i], ":", price[i]/100.0 - print - - - print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() - - else: - print "No solutions found" - - -if __name__ == '__main__': - main() +if __name__ == "__main__": + main() diff --git a/examples/python/young_tableaux.py b/examples/python/young_tableaux.py index 36f77ea11b..a5c9d2ec25 100644 --- a/examples/python/young_tableaux.py +++ b/examples/python/young_tableaux.py @@ -57,107 +57,108 @@ * Zinc: http://hakank.org/minizinc/young_tableaux.zinc This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ """ -import sys,string +import sys +import string from ortools.constraint_solver import pywrapcp -def main(n = 5): +def main(n=5): - # Create the solver. - solver = pywrapcp.Solver('Problem') + # Create the solver. + solver = pywrapcp.Solver("Problem") - # - # data - # - print "n:", n + # + # data + # + print "n:", n - # - # declare variables - # - x = {} - for i in range(n): - for j in range(n): - x[(i,j)] = solver.IntVar(1,n+1, 'x(%i,%i)' % (i, j)) - - x_flat = [x[(i,j)] for i in range(n) for j in range(n)] - - # partition structure - p = [solver.IntVar(0,n+1,"p%i"%i) for i in range(n)] - - # - # constraints - # - - # 1..n is used exactly once - for i in range(1,n+1): - solver.Add(solver.Count(x_flat, i, 1)) - - solver.Add(x[(0,0)] == 1) - - # row wise - for i in range(n): - for j in range(1,n): - solver.Add(x[(i,j)] >= x[(i,j-1)]) - - # column wise + # + # declare variables + # + x = {} + for i in range(n): for j in range(n): - for i in range(1,n): - solver.Add(x[(i,j)] >= x[(i-1,j)]) + x[(i, j)] = solver.IntVar(1, n + 1, "x(%i,%i)" % (i, j)) + x_flat = [x[(i, j)] for i in range(n) for j in range(n)] - # calculate the structure (the partition) + # partition structure + p = [solver.IntVar(0, n + 1, "p%i" % i) for i in range(n)] + + # + # constraints + # + + # 1..n is used exactly once + for i in range(1, n + 1): + solver.Add(solver.Count(x_flat, i, 1)) + + solver.Add(x[(0, 0)] == 1) + + # row wise + for i in range(n): + for j in range(1, n): + solver.Add(x[(i, j)] >= x[(i, j - 1)]) + + # column wise + for j in range(n): + for i in range(1, n): + solver.Add(x[(i, j)] >= x[(i - 1, j)]) + + # calculate the structure (the partition) + for i in range(n): + # MiniZinc/Zinc version: + # p[i] == sum(j in 1..n) (bool2int(x[i,j] <= n)) + + b = [solver.IsLessOrEqualCstVar(x[(i, j)], n) for j in range(n)] + solver.Add(p[i] == solver.Sum(b)) + + solver.Add(solver.Sum(p) == n) + + for i in range(1, n): + solver.Add(p[i - 1] >= p[i]) + + # + # solution and search + # + solution = solver.Assignment() + solution.Add(x_flat) + solution.Add(p) + + # db: DecisionBuilder + db = solver.Phase(x_flat + p, + solver.CHOOSE_FIRST_UNBOUND, + solver.ASSIGN_MIN_VALUE) + + solver.NewSearch(db) + num_solutions = 0 + while solver.NextSolution(): + print "p:", [p[i].Value() for i in range(n)] + print "x:" for i in range(n): - # MiniZinc/Zinc version: - # p[i] == sum(j in 1..n) (bool2int(x[i,j] <= n)) - - b = [solver.IsLessOrEqualCstVar(x[(i, j)], n) for j in range(n)] - solver.Add(p[i] == solver.Sum(b)) - - solver.Add(solver.Sum(p) == n) - - for i in range(1,n): - solver.Add(p[i-1] >= p[i]) - - # - # solution and search - # - solution = solver.Assignment() - solution.Add(x_flat) - solution.Add(p) - - # db: DecisionBuilder - db = solver.Phase(x_flat + p, - solver.CHOOSE_FIRST_UNBOUND, - solver.ASSIGN_MIN_VALUE) - - solver.NewSearch(db) - num_solutions = 0 - while solver.NextSolution(): - print "p:", [p[i].Value() for i in range(n)] - print "x:" - for i in range(n): - for j in range(n): - val = x_flat[i*n+j].Value() - if val <= n: - print val, - if p[i].Value() > 0: - print + for j in range(n): + val = x_flat[i * n + j].Value() + if val <= n: + print val, + if p[i].Value() > 0: print - num_solutions += 1 - - solver.EndSearch() - print - print "num_solutions:", num_solutions - print "failures:", solver.Failures() - print "branches:", solver.Branches() - print "WallTime:", solver.WallTime() + num_solutions += 1 -n=5 -if __name__ == '__main__': - if len(sys.argv) > 1: - n = string.atoi(sys.argv[1]) + solver.EndSearch() - main(n) + print + print "num_solutions:", num_solutions + print "failures:", solver.Failures() + print "branches:", solver.Branches() + print "WallTime:", solver.WallTime() + +n = 5 +if __name__ == "__main__": + if len(sys.argv) > 1: + n = string.atoi(sys.argv[1]) + + main(n) diff --git a/examples/python/zebra.py b/examples/python/zebra.py index e61a7ad187..cef16024da 100644 --- a/examples/python/zebra.py +++ b/examples/python/zebra.py @@ -35,7 +35,6 @@ Who owns a zebra and who drinks water? """ - from google.apputils import app import gflags from ortools.constraint_solver import pywrapcp diff --git a/examples/tests/dual_loading.py b/examples/tests/dual_loading.py index 292c4ec5b6..7c24267424 100644 --- a/examples/tests/dual_loading.py +++ b/examples/tests/dual_loading.py @@ -7,5 +7,5 @@ def main(): lp = pywraplp.Solver("test", pywraplp.Solver.CLP_LINEAR_PROGRAMMING) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/examples/tests/issue2.py b/examples/tests/issue2.py index d7c2005f7a..27f5b47bbd 100644 --- a/examples/tests/issue2.py +++ b/examples/tests/issue2.py @@ -2,39 +2,42 @@ from constraint_solver import pywrapcp # Control-C test. Hit Control-C during execution of this program. + def main(): - solver = pywrapcp.Solver('time limit test') - n = 10 - x = [solver.IntVar(1, n, 'x[%i]'%i) for i in range(n)] - solver.Add(solver.AllDifferent(x, True)) + solver = pywrapcp.Solver("time limit test") + n = 10 + x = [solver.IntVar(1, n, "x[%i]" % i) for i in range(n)] + solver.Add(solver.AllDifferent(x, True)) - solution = solver.Assignment() - solution.Add(x) + solution = solver.Assignment() + solution.Add(x) - db = solver.Phase(x, - solver.CHOOSE_FIRST_UNBOUND, - solver.ASSIGN_MIN_VALUE) + db = solver.Phase(x, + solver.CHOOSE_FIRST_UNBOUND, + solver.ASSIGN_MIN_VALUE) - time_limit = 10000 - branch_limit = 100000000 - failures_limit = 100000000 - solutions_limit = 10000000 - limits = solver.Limit(time_limit, branch_limit, failures_limit, solutions_limit, True) + time_limit = 10000 + branch_limit = 100000000 + failures_limit = 100000000 + solutions_limit = 10000000 + limits = ( + solver.Limit( + time_limit, branch_limit, failures_limit, solutions_limit, True)) - search_log = solver.SearchLog(1000) - assignment = solver.Assignment() - assignment.Add(x) - collector = solver.LastSolutionCollector(assignment) - try: - solver.Solve(db, [limits, search_log, collector]) - except KeyboardInterrupt: - print "Control-C caught" + search_log = solver.SearchLog(1000) + assignment = solver.Assignment() + assignment.Add(x) + collector = solver.LastSolutionCollector(assignment) + try: + solver.Solve(db, [limits, search_log, collector]) + except KeyboardInterrupt: + print "Control-C caught" - print - print "failures:", solver.failures() - print "branches:", solver.branches() - print "wall_time:", solver.wall_time() + print + print "failures:", solver.failures() + print "branches:", solver.branches() + print "wall_time:", solver.wall_time() -if __name__ == '__main__': - main() +if __name__ == "__main__": + main() diff --git a/examples/tests/issue3.py b/examples/tests/issue3.py index f9a98b768f..7c7e583013 100644 --- a/examples/tests/issue3.py +++ b/examples/tests/issue3.py @@ -19,51 +19,55 @@ from random import randint #----------------helper for binpacking posting---------------- -def binpacking(cp,binvars,weights,loadvars): - '''post the connstraints forall j: loadvars[j] == sum_i (binvars[i] == j) * weights[i])''' - nbins = len(loadvars) - nitems = len(binvars) - for j in range(nbins): - b = [cp.BoolVar(str(i)) for i in range(nitems)] - for i in range(nitems): - cp.Add(cp.IsEqualCstCt(binvars[i],j,b[i])) - cp.Add(solver.Sum([b[i]*weights[i] for i in range(nitems)]) == l[j]) - cp.Add(solver.Sum(loadvars) == sum(weights)) +def binpacking(cp, binvars, weights, loadvars): + """post the connstraints forall j: loadvars[j] == sum_i (binvars[i] == j) * weights[i])""" + + nbins = len(loadvars) + nitems = len(binvars) + for j in range(nbins): + b = [cp.BoolVar(str(i)) for i in range(nitems)] + for i in range(nitems): + cp.Add(cp.IsEqualCstCt(binvars[i], j, b[i])) + cp.Add(solver.Sum([b[i] * weights[i] for i in range(nitems)]) == l[j]) + cp.Add(solver.Sum(loadvars) == sum(weights)) #------------------------------data reading------------------- maxcapa = 44 weights = [4, 22, 9, 5, 8, 3, 3, 4, 7, 7, 3] -loss = [0, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 1, 0, 2, 1, 0, 0, 0, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 2, 1, 0, 3, 2, 1, 0, 2, 1, 0, 0, 0] +loss = [ + 0, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 1, 0, 2, 1, 0, 0, 0, 0, 2, 1, 0, + 0, 0, 0, 0, 0, 0, 0, 1, 0, 2, 1, 0, 3, 2, 1, 0, 2, 1, 0, 0, 0] nbslab = 11 #------------------solver and variable declaration------------- solver = pywrapcp.Solver('Steel Mill Slab') -x = [solver.IntVar(range(nbslab),'x'+str(i)) for i in range(nbslab)] -l = [solver.IntVar(range(maxcapa),'l'+str(i)) for i in range(nbslab)] -obj = solver.IntVar(range(nbslab*maxcapa),'obj') +x = [solver.IntVar(range(nbslab), 'x' + str(i)) for i in range(nbslab)] +l = [solver.IntVar(range(maxcapa), 'l' + str(i)) for i in range(nbslab)] +obj = solver.IntVar(range(nbslab * maxcapa), 'obj') #-------------------post of the constraints-------------- -binpacking(solver,x,weights[:nbslab],l) -solver.Add(solver.Sum([solver.Element(loss,l[s]) for s in range(nbslab)]) == obj) +binpacking(solver, x, weights[:nbslab], l) +solver.Add(solver.Sum([solver.Element(loss, l[s]) + for s in range(nbslab)]) == obj) sol = [2, 0, 0, 0, 0, 1, 2, 2, 1, 1, 2] #------------start the search and optimization----------- -objective = solver.Minimize(obj,1) +objective = solver.Minimize(obj, 1) db = solver.Phase(x, solver.INT_VAR_DEFAULT, - solver.INT_VALUE_DEFAULT) -#solver.NewSearch(db,[objective]) #segfault if I comment this + solver.INT_VALUE_DEFAULT) +# solver.NewSearch(db,[objective]) #segfault if I comment this while solver.NextSolution(): - print obj,"check:",sum([loss[l[s].Min()] for s in range(nbslab)]) - print l + print obj, 'check:', sum([loss[l[s].Min()] for s in range(nbslab)]) + print l solver.EndSearch() -print "#fails:",solver.failures() -print "time:",solver.wall_time() +print '#fails:', solver.failures() +print 'time:', solver.wall_time() diff --git a/examples/tests/issue4.py b/examples/tests/issue4.py index 431c633339..21dfbc1a0b 100644 --- a/examples/tests/issue4.py +++ b/examples/tests/issue4.py @@ -1,39 +1,42 @@ from constraint_solver import pywrapcp + def main(): - solver = pywrapcp.Solver('time limit test') - n = 10 - x = [solver.IntVar(1, n, 'x[%i]'%i) for i in range(n)] - solver.Add(solver.AllDifferent(x, True)) + solver = pywrapcp.Solver("time limit test") + n = 10 + x = [solver.IntVar(1, n, "x[%i]" % i) for i in range(n)] + solver.Add(solver.AllDifferent(x, True)) - solution = solver.Assignment() - solution.Add(x) + solution = solver.Assignment() + solution.Add(x) - db = solver.Phase(x, - solver.CHOOSE_FIRST_UNBOUND, - solver.ASSIGN_MIN_VALUE) + db = solver.Phase(x, + solver.CHOOSE_FIRST_UNBOUND, + solver.ASSIGN_MIN_VALUE) - time_limit = 10000 - branch_limit = 100000000 - failures_limit = 100000000 - solutions_limit = 10000000 - limits = solver.Limit(time_limit, branch_limit, failures_limit, solutions_limit, True) + time_limit = 10000 + branch_limit = 100000000 + failures_limit = 100000000 + solutions_limit = 10000000 + limits = ( + solver.Limit( + time_limit, branch_limit, failures_limit, solutions_limit, True)) - search_log = solver.SearchLog(1000) + search_log = solver.SearchLog(1000) - solver.NewSearch(db, [limits, search_log]) - num_solutions = 0 - while solver.NextSolution(): - print "x:", [x[i].Value() for i in range(n)] - num_solutions += 1 - solver.EndSearch() + solver.NewSearch(db, [limits, search_log]) + num_solutions = 0 + while solver.NextSolution(): + print "x:", [x[i].Value() for i in range(n)] + num_solutions += 1 + solver.EndSearch() - print - print "num_solutions:", num_solutions - print "failures:", solver.failures() - print "branches:", solver.branches() - print "wall_time:", solver.wall_time() + print + print "num_solutions:", num_solutions + print "failures:", solver.failures() + print "branches:", solver.branches() + print "wall_time:", solver.wall_time() -if __name__ == '__main__': - main() +if __name__ == "__main__": + main() diff --git a/examples/tests/issue5.py b/examples/tests/issue5.py index 8cc7e4706f..17e6a626e6 100644 --- a/examples/tests/issue5.py +++ b/examples/tests/issue5.py @@ -55,7 +55,8 @@ This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) - Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ + Also see my other Google CP Solver models: + http://www.hakank.org/google_or_tools/ ''' from constraint_solver import pywrapcp @@ -63,120 +64,119 @@ from constraint_solver import pywrapcp def main(): - # Create the solver. - solver = pywrapcp.Solver('Einav puzzle') + # Create the solver. + solver = pywrapcp.Solver('Einav puzzle') - # - # data - # + # + # data + # - - # small problem + # small problem # data = [ # [ 33, 30, -10], # [-16, 19, 9], # [-17, -12, -14] # ] - data = [[33, 30, 10, -6, 18, -7, -11, 23, -6], - [16, -19, 9, -26, -8, -19, -8, -21, -14], - [17, 12, -14, 31, -30, 13, -13, 19, 16], - [-6, -11, 1, 17, -12, -4, -7, 14, -21], - [18, -31, 34, -22, 17, -19, 20, 24, 6], - [33, -18, 17, -15, 31, -5, 3, 27, -3], - [-18, -20, -18, 31, 6, 4, -2, -12, 24], - [27, 14, 4, -29, -3, 5, -29, 8, -12], - [-15, -7, -23, 23, -9, -8, 6, 8, -12], - [33, -23, -19, -4, -8, -7, 11, -12, 31], - [-20, 19, -15, -30, 11, 32, 7, 14, -5], - [-23, 18, -32, -2, -31, -7, 8, 24, 16], - [32, -4, -10, -14, -6, -1, 0, 23, 23], - [25, 0, -23, 22, 12, 28, -27, 15, 4], - [-30, -13, -16, -3, -3, -32, -3, 27, -31], - [22, 1, 26, 4, -2, -13, 26, 17, 14], - [-9, -18, 3, -20, -27, -32, -11, 27, 13], - [-17, 33, -7, 19, -32, 13, -31, -2, -24], - [-31, 27, -31, -29, 15, 2, 29, -15, 33], - [-18, -23, 15, 28, 0, 30, -4, 12, -32], - [-3, 34, 27, -25, -18, 26, 1, 34, 26], - [-21, -31, -10, -13, -30, -17, -12, -26, 31], - [23, -31, -19, 21, -17, -10, 2, -23, 23], - [-3, 6, 0, -3, -32, 0, -10, -25, 14], - [-19, 9, 14, -27, 20, 15, -5, -27, 18], - [11, -6, 24, 7, -17, 26, 20, -31, -25], - [-25, 4, -16, 30, 33, 23, -4, -4, 23]] + data = [[33, 30, 10, -6, 18, -7, -11, 23, -6], + [16, -19, 9, -26, -8, -19, -8, -21, -14], + [17, 12, -14, 31, -30, 13, -13, 19, 16], + [-6, -11, 1, 17, -12, -4, -7, 14, -21], + [18, -31, 34, -22, 17, -19, 20, 24, 6], + [33, -18, 17, -15, 31, -5, 3, 27, -3], + [-18, -20, -18, 31, 6, 4, -2, -12, 24], + [27, 14, 4, -29, -3, 5, -29, 8, -12], + [-15, -7, -23, 23, -9, -8, 6, 8, -12], + [33, -23, -19, -4, -8, -7, 11, -12, 31], + [-20, 19, -15, -30, 11, 32, 7, 14, -5], + [-23, 18, -32, -2, -31, -7, 8, 24, 16], + [32, -4, -10, -14, -6, -1, 0, 23, 23], + [25, 0, -23, 22, 12, 28, -27, 15, 4], + [-30, -13, -16, -3, -3, -32, -3, 27, -31], + [22, 1, 26, 4, -2, -13, 26, 17, 14], + [-9, -18, 3, -20, -27, -32, -11, 27, 13], + [-17, 33, -7, 19, -32, 13, -31, -2, -24], + [-31, 27, -31, -29, 15, 2, 29, -15, 33], + [-18, -23, 15, 28, 0, 30, -4, 12, -32], + [-3, 34, 27, -25, -18, 26, 1, 34, 26], + [-21, -31, -10, -13, -30, -17, -12, -26, 31], + [23, -31, -19, 21, -17, -10, 2, -23, 23], + [-3, 6, 0, -3, -32, 0, -10, -25, 14], + [-19, 9, 14, -27, 20, 15, -5, -27, 18], + [11, -6, 24, 7, -17, 26, 20, -31, -25], + [-25, 4, -16, 30, 33, 23, -4, -4, 23]] - rows = len(data) - cols = len(data[0]) + rows = len(data) + cols = len(data[0]) - # - # variables - # - x = {} - for i in range(rows): - for j in range(cols): - x[i, j] = solver.IntVar(-100, 100, 'x[%i,%i]' % (i, j)) - - row_signs = [solver.IntVar([-1, 1], 'row_signs(%i)' % i) - for i in range(rows)] - col_signs = [solver.IntVar([-1, 1], 'col_signs(%i)' % j) - for j in range(cols)] - - # - # constraints - # - for i in range(rows): - for j in range(cols): - solver.Add(x[i, j] == data[i][j] * row_signs[i] * col_signs[j]) - - total_sum = solver.Sum([x[i, j] for i in range(rows) for j in range(cols)]) - - # row sums - row_sums = [solver.Sum([x[i, j] for j in range(cols)]).Var() - for i in range(rows)] - # >= 0 - for i in range(rows): - row_sums[i].SetMin(0) - - # column sums - col_sums = [solver.Sum([x[i, j] for i in range(rows)]).Var() - for j in range(cols)] + # + # variables + # + x = {} + for i in range(rows): for j in range(cols): - col_sums[j].SetMin(0) + x[i, j] = solver.IntVar(-100, 100, 'x[%i,%i]' % (i, j)) - # objective - objective = solver.Minimize(total_sum, 1) + row_signs = [solver.IntVar([-1, 1], 'row_signs(%i)' % i) + for i in range(rows)] + col_signs = [solver.IntVar([-1, 1], 'col_signs(%i)' % j) + for j in range(cols)] - # - # search and result - # - db = solver.Phase(col_signs + row_signs, - solver.CHOOSE_FIRST_UNBOUND, - solver.ASSIGN_MIN_VALUE) + # + # constraints + # + for i in range(rows): + for j in range(cols): + solver.Add(x[i, j] == data[i][j] * row_signs[i] * col_signs[j]) - search_log = solver.SearchLog(100000, total_sum) - solver.NewSearch(db, [objective, search_log]) + total_sum = solver.Sum([x[i, j] for i in range(rows) for j in range(cols)]) - num_solutions = 0 - while solver.NextSolution(): - num_solutions += 1 - print 'Sum =', objective.best() - print 'row_sums:', [row_sums[i].Value() for i in range(rows)] - print 'col_sums:', [col_sums[j].Value() for j in range(cols)] - for i in range(rows): - for j in range(cols): - print x[i,j].Value(), - print - print + # row sums + row_sums = [solver.Sum([x[i, j] for j in range(cols)]).Var() + for i in range(rows)] + # >= 0 + for i in range(rows): + row_sums[i].SetMin(0) - solver.EndSearch() + # column sums + col_sums = [solver.Sum([x[i, j] for i in range(rows)]).Var() + for j in range(cols)] + for j in range(cols): + col_sums[j].SetMin(0) + # objective + objective = solver.Minimize(total_sum, 1) + + # + # search and result + # + db = solver.Phase(col_signs + row_signs, + solver.CHOOSE_FIRST_UNBOUND, + solver.ASSIGN_MIN_VALUE) + + search_log = solver.SearchLog(100000, total_sum) + solver.NewSearch(db, [objective, search_log]) + + num_solutions = 0 + while solver.NextSolution(): + num_solutions += 1 + print 'Sum =', objective.best() + print 'row_sums:', [row_sums[i].Value() for i in range(rows)] + print 'col_sums:', [col_sums[j].Value() for j in range(cols)] + for i in range(rows): + for j in range(cols): + print x[i, j].Value(), + print print - print 'num_solutions:', num_solutions - print 'failures:', solver.failures() - print 'branches:', solver.branches() - print 'wall_time:', solver.wall_time(), 'ms' + + solver.EndSearch() + + print + print 'num_solutions:', num_solutions + print 'failures:', solver.failures() + print 'branches:', solver.branches() + print 'wall_time:', solver.wall_time(), 'ms' if __name__ == '__main__': - main() + main() diff --git a/examples/tests/test_cp_api.py b/examples/tests/test_cp_api.py index e4620f2e7a..8c75da397f 100644 --- a/examples/tests/test_cp_api.py +++ b/examples/tests/test_cp_api.py @@ -10,11 +10,13 @@ def test_member(): ct = x.Member([1, 2, 3, 5]) print(ct) + def test_sparse_var(): solver = pywrapcp.Solver('test sparse') x = solver.IntVar([1, 3, 5], 'x') print(x) + def test_modulo(): solver = pywrapcp.Solver('test modulo') x = solver.IntVar(0, 10, 'x') @@ -22,6 +24,7 @@ def test_modulo(): print(x % 3) print(x % y) + def test_limit(): solver = pywrapcp.Solver('test limit') limit_proto = search_limit_pb2.SearchLimitProto() @@ -31,6 +34,7 @@ def test_limit(): limit = solver.Limit(limit_proto) print limit + def test_export(): solver = pywrapcp.Solver('test export') x = solver.IntVar(1, 10, 'x') @@ -44,6 +48,7 @@ def test_export(): class SearchMonitorTest(pywrapcp.SearchMonitor): + def __init__(self, solver, nexts): pywrapcp.SearchMonitor.__init__(self, solver) self._nexts = nexts @@ -66,6 +71,7 @@ def test_search_monitor(): class DemonTest(pywrapcp.PyDemon): + def __init__(self, x): pywrapcp.Demon.__init__(self) self._x = x @@ -83,6 +89,7 @@ def test_demon(): class ConstraintTest(pywrapcp.PyConstraint): + def __init__(self, solver, x): pywrapcp.Constraint.__init__(self, solver) self._x = x @@ -111,6 +118,7 @@ def test_constraint(): class InitialPropagateDemon(pywrapcp.PyDemon): + def __init__(self, ct): pywrapcp.Demon.__init__(self) self._ct = ct @@ -120,6 +128,7 @@ class InitialPropagateDemon(pywrapcp.PyDemon): class DumbGreaterOrEqualToFive(pywrapcp.PyConstraint): + def __init__(self, solver, x): pywrapcp.Constraint.__init__(self, solver) self._x = x diff --git a/examples/tests/test_lp_api.py b/examples/tests/test_lp_api.py index 9b265c6fbe..fb046cd7d1 100644 --- a/examples/tests/test_lp_api.py +++ b/examples/tests/test_lp_api.py @@ -4,13 +4,15 @@ from ortools.linear_solver import linear_solver2_pb2 import sys import types + def Sum(arg): if type(arg) is types.GeneratorType: arg = [x for x in arg] - sum = 0; + sum = 0 for i in arg: sum += i - print("sum(%s) = %d" % (str(arg), sum)) + print('sum(%s) = %d' % (str(arg), sum)) + def test_sum_no_brackets(): Sum(x for x in range(10) if x % 2 == 0) @@ -31,6 +33,7 @@ model < > """ + def test_proto(): input_proto = linear_solver2_pb2.MPModelRequest() text_format.Merge(text_model, input_proto) @@ -39,7 +42,7 @@ def test_proto(): print input_proto # For now, create the model from the proto by parsing the proto solver.LoadModelFromProto(input_proto.model) - solver.EnableOutput(); + solver.EnableOutput() solver.Solve() # Fill solution solution = linear_solver2_pb2.MPSolutionResponse()