1# Copyright 2010 Hakan Kjellerstrand hakank@gmail.com 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14""" 15 16 Set covering in Google CP Solver. 17 18 Example 9.1-2, page 354ff, from 19 Taha 'Operations Research - An Introduction' 20 Minimize the number of security telephones in street 21 corners on a campus. 22 23 Compare with the following models: 24 * MiniZinc: http://www.hakank.org/minizinc/set_covering2.mzn 25 * Comet : http://www.hakank.org/comet/set_covering2.co 26 * ECLiPSe : http://www.hakank.org/eclipse/set_covering2.ecl 27 * SICStus: http://hakank.org/sicstus/set_covering2.pl 28 * Gecode: http://hakank.org/gecode/set_covering2.cpp 29 30 This model was created by Hakan Kjellerstrand (hakank@gmail.com) 31 Also see my other Google CP Solver models: 32 http://www.hakank.org/google_or_tools/ 33 34""" 35from ortools.constraint_solver import pywrapcp 36 37 38def main(unused_argv): 39 40 # Create the solver. 41 solver = pywrapcp.Solver("Set covering") 42 43 # 44 # data 45 # 46 n = 8 # maximum number of corners 47 num_streets = 11 # number of connected streets 48 49 # corners of each street 50 # Note: 1-based (handled below) 51 corner = [[1, 2], [2, 3], [4, 5], [7, 8], [6, 7], [2, 6], [1, 6], [4, 7], 52 [2, 4], [5, 8], [3, 5]] 53 54 # 55 # declare variables 56 # 57 x = [solver.IntVar(0, 1, "x[%i]" % i) for i in range(n)] 58 59 # 60 # constraints 61 # 62 63 # number of telephones, to be minimized 64 z = solver.Sum(x) 65 66 # ensure that all corners are covered 67 for i in range(num_streets): 68 # also, convert to 0-based 69 solver.Add(solver.SumGreaterOrEqual([x[j - 1] for j in corner[i]], 1)) 70 71 objective = solver.Minimize(z, 1) 72 73 # 74 # solution and search 75 # 76 solution = solver.Assignment() 77 solution.Add(x) 78 solution.AddObjective(z) 79 80 collector = solver.LastSolutionCollector(solution) 81 solver.Solve( 82 solver.Phase(x, solver.INT_VAR_DEFAULT, solver.INT_VALUE_DEFAULT), 83 [collector, objective]) 84 85 print("z:", collector.ObjectiveValue(0)) 86 print("x:", [collector.Value(0, x[i]) for i in range(n)]) 87 88 print("failures:", solver.Failures()) 89 print("branches:", solver.Branches()) 90 print("WallTime:", solver.WallTime()) 91 92 93if __name__ == "__main__": 94 main("cp sample") 95