Created
June 7, 2021 11:24
-
-
Save phabee/6f494d9b0a7f29484a59fce8d98c0304 to your computer and use it in GitHub Desktop.
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
# source based on code presented here https://developers.google.com/optimization/mip/integer_opt | |
from ortools.linear_solver import pywraplp | |
# example how to solve a linear program having ONLY continuous variables | |
def main(): | |
# Create the mip solver with the SCIP backend. | |
# HINT: GLOP cannot handle integer variables! | |
solver = pywraplp.Solver.CreateSolver('GLOP') | |
infinity = solver.infinity() | |
# x and y are integer non-negative variables. | |
x = solver.NumVar(0.0, infinity, 'x') | |
y = solver.NumVar(0.0, infinity, 'y') | |
print('Number of variables =', solver.NumVariables()) | |
# x + 7 * y <= 17.5. | |
solver.Add(x + 7 * y <= 17.5) | |
# x <= 3.5. | |
solver.Add(x <= 3.5) | |
print('Number of constraints =', solver.NumConstraints()) | |
# Maximize x + 10 * y. | |
solver.Maximize(x + 10 * y) | |
status = solver.Solve() | |
if status == pywraplp.Solver.OPTIMAL: | |
print('Solution:') | |
print('Objective value =', solver.Objective().Value()) | |
print('x =', x.solution_value()) | |
print('y =', y.solution_value()) | |
else: | |
print('The problem does not have an optimal solution.') | |
print('\nAdvanced usage:') | |
print('Problem solved in %f milliseconds' % solver.wall_time()) | |
print('Problem solved in %d iterations' % solver.iterations()) | |
# print('Problem solved in %d branch-and-bound nodes' % solver.nodes()) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment