Created
October 28, 2020 18:52
-
-
Save bbenno/870a6391e93bcacfc95f862cd81f5509 to your computer and use it in GitHub Desktop.
ILP
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
#!/usr/bin/python | |
"""linear_program.py: Solves an simple integer linear program. | |
Maximize | |
f(x) = 6x₁ + 4x₂ | |
with | |
x₁, x₂ ∈ ℕ | |
Constraints | |
x₁ + 2x₂ <= 8 | |
3x₁ + x₂ <= 9 | |
""" | |
__author__ = "Benno Bielmeier" | |
__copyright__ = "Copyright 2020, Planet Earth" | |
__license__ = "Unlicense" | |
__version__ = "1.0" | |
from ortools.linear_solver import pywraplp | |
solver = pywraplp.Solver( | |
"simple integer linear program", pywraplp.Solver.GLOP_LINEAR_PROGRAMMING | |
) | |
# variables | |
x1 = solver.NumVar(0, solver.infinity(), "x1") | |
x2 = solver.NumVar(0, solver.infinity(), "x2") | |
# constraints | |
ct1 = solver.Constraint(-solver.infinity(), 8, "constraint 1") | |
ct1.SetCoefficient(x1, 1) | |
ct1.SetCoefficient(x2, 2) | |
ct2 = solver.Constraint(-solver.infinity(), 9, "constraint 2") | |
ct2.SetCoefficient(x1, 3) | |
ct2.SetCoefficient(x2, 1) | |
# objective function | |
objective = solver.Objective() | |
objective.SetCoefficient(x1, 6) | |
objective.SetCoefficient(x2, 4) | |
objective.SetMaximization() | |
solver.Solve() | |
# print solution | |
print("max value = ", objective.Value()) | |
print("x1 = ", x1.solution_value()) | |
print("x2 = ", x2.solution_value()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment