Last active
March 12, 2020 14:48
-
-
Save dboyliao/3ccf4a52a89279aa75262743f350e3e5 to your computer and use it in GitHub Desktop.
Simple ortools example for solving constraint optimization with CP solver
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from ortools.sat.python import cp_model | |
# setup a model which represents the constraint optimization problem | |
model = cp_model.CpModel() | |
# declare variables | |
# x and y are two integer with range of 0 to 2 | |
x = model.NewIntVar(0, 2, 'x') | |
y = model.NewIntVar(0, 2, 'y') | |
# add constraint: x+y <= 1 | |
model.Add(x + y <= 1) | |
# setup the objective function | |
obj = 2*x + y | |
model.Maximize(obj) | |
# solve the optimization problem | |
solver = cp_model.CpSolver() | |
status = solver.Solve(model) | |
if solver.StatusName(status) == 'OPTIMAL': | |
print('x:', solver.Value(x)) | |
print('y:', solver.Value(y)) | |
else: | |
print('no optimal solution') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment