Created
January 16, 2023 01:04
-
-
Save robertcampion/73e056400c8eeb015bd9a41925eb6682 to your computer and use it in GitHub Desktop.
OR-Tools integer linear programming example (Python)
This file contains 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
# code to solve the problem described in https://codereview.stackexchange.com/q/282605/209865 | |
# based on https://developers.google.com/optimization/cp/cp_example | |
from ortools.sat.python import cp_model | |
from itertools import product | |
variable_names = list('abcdef') | |
coefficients = [-42, 75, -30, 80, 25, 50] | |
upper_bound = 150 | |
for v in range(3001): | |
for permutation in product([False, True], repeat=len(variable_names)): | |
print(f'v = {v}, permutation = {permutation}') | |
model = cp_model.CpModel() | |
variables = [model.NewIntVar( | |
1 if is_nonzero else 0, | |
upper_bound if is_nonzero else 0, | |
variable_name) | |
for variable_name, is_nonzero in zip(variable_names, permutation)] | |
model.Add(cp_model.LinearExpr.WeightedSum( | |
variables, coefficients) == - (v + 1)) | |
model.Minimize(cp_model.LinearExpr.Sum(variables)) | |
solver = cp_model.CpSolver() | |
status = solver.Solve(model) | |
if status == cp_model.OPTIMAL: | |
print(f'Minimum sum: {solver.ObjectiveValue()}, ' + | |
', '.join(f'{variable.Name()} = {solver.Value(variable)}' | |
for variable in variables)) | |
elif status == cp_model.INFEASIBLE: | |
print('No solution') | |
else: | |
print(f'Error: status = {status}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment