basic/color.py example

 1# --------------------------------------------------------------------------
 2# Source file provided under Apache License, Version 2.0, January 2004,
 3# http://www.apache.org/licenses/
 4# (c) Copyright IBM Corp. 2015, 2022
 5# --------------------------------------------------------------------------
 6
 7"""
 8The problem involves choosing colors for the countries on a map in
 9such a way that at most four colors (blue, white, yellow, green) are
10used and no neighboring countries are the same color. In this exercise,
11you will find a solution for a map coloring problem with six countries:
12Belgium, Denmark, France, Germany, Luxembourg, and the Netherlands.
13
14Please refer to documentation for appropriate setup of solving configuration.
15"""
16
17from docplex.cp.model import CpoModel
18
19# Create CPO model
20mdl = CpoModel()
21
22# Create model variables containing colors of the countries
23Belgium     = mdl.integer_var(0, 3, "Belgium")
24Denmark     = mdl.integer_var(0, 3, "Denmark")
25France      = mdl.integer_var(0, 3, "France")
26Germany     = mdl.integer_var(0, 3, "Germany")
27Luxembourg  = mdl.integer_var(0, 3, "Luxembourg")
28Netherlands = mdl.integer_var(0, 3, "Netherlands")
29ALL_COUNTRIES = (Belgium, Denmark, France, Germany, Luxembourg, Netherlands)
30        
31# Create constraints
32mdl.add(Belgium != France)
33mdl.add(Belgium != Germany)
34mdl.add(Belgium != Netherlands)
35mdl.add(Belgium != Luxembourg)
36mdl.add(Denmark != Germany)
37mdl.add(France  != Germany)
38mdl.add(France  != Luxembourg)
39mdl.add(Germany != Luxembourg)
40mdl.add(Germany != Netherlands)
41
42# Solve model
43print("\nSolving model....")
44msol = mdl.solve(TimeLimit=10)
45
46if msol:
47    print("Solution status: " + msol.get_solve_status())
48    colors = ("Yellow", "Red", "Green", "Blue")
49    for country in ALL_COUNTRIES:
50        print("   " + country.get_name() + ": " + colors[msol[country]])
51else:
52    print("No solution found")
53
54# Print solver log
55# print("\nSolver log:")
56# print(msol.get_solver_log())