In this example, we are going to solve a typical Constraint Optimization problem. In the previous tutorial, we tool a simple example of just one constraint.
Example 1: Maximize the function 2x + 2y + 3z with respect to the following constraints:
| x + 7⁄2 y + 3⁄2 z | ≤ | 25 |
| 3x – 5y + 7z | ≤ | 45 |
| 5x + 2y – 6z | ≤ | 37 |
| x, y, z | ≥ | 0 |
| x, y, z integers | ||
Note: Since we are performing integer optimization, we must make sure the coefficients of the first constraint are all integer. We can achieve this by multiplying through by 2.
So let’s now take the steps
Step 1: Declare the model
# Declare the Model from ortools.sat.python import cp_model model = cp_model.CpModel()
Step 2: Define the variables
# Define the variables num_vars = 3 x = model.NewIntVar(0, 50, 'x') y = model.NewIntVar(0, 50, 'y') z = model.NewIntVar(0, 50, 'z')
Step 3: Create the constraints
# Set up the constraints model.Add(2*x + 7*y + 3*z <= 50) model.Add(3*x - 5*y + 7*z <= 45) model.Add(5*x + 2*y - 6*z <= 37)
Step 4: Define the cost function
# Define the objective function 2x + 2y + 3z model.Maximize(2*x + 2*y + 3*z)
Step 5: Invoke the solver
# Invoke the solver solver = cp_model.CpSolver() status = solver.Solve(model)
Step 6: Display the results
# Display the results if status == cp_model.OPTIMAL: print('Value of objective function: %i' % solver.ObjectiveValue()) print('x = %i' %solver.Value(x)) print('y = %i' %solver.Value(y)) print('z = %i' %solver.Value(z))
The output would be as shown below:
Value of objective function: 35 x = 7 y = 3 z = 5
Complete program is given below:
