Skip to content

Instantly share code, notes, and snippets.

@phabee
Created June 7, 2021 12:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phabee/cbdad433adb8940560f845254f830d28 to your computer and use it in GitHub Desktop.
Save phabee/cbdad433adb8940560f845254f830d28 to your computer and use it in GitHub Desktop.
# 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 MIXED integer linear program continuous and integer variables
# and solve it with a gurobi solver installed (or gurobi cloud).
def main():
# Create the mip solver with the SCIP backend.
solver = pywraplp.Solver.CreateSolver('GUROBI_MIP')
infinity = solver.infinity()
# x and y are integer non-negative variables.
x = solver.NumVar(0.0, infinity, 'x')
y = solver.IntVar(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