In a previous post on Google’s ortools module in Python I solved the linear optimization problem stated below:
The code written in my previous post can be reduced to fewer lines of code, resulting in lean code. In this post I will share a leaner version of my previous ortools-script.
Again, I start by importing pywraplp from ortools.linear_solver:
from ortools.linear_solver import pywraplp
Next, I create a solver instance (using GLOP solver) and store its reference to a reference handler:
solver = pywraplp.Solver.CreateSolver('linear_programming_examples', 'GLOP')
I now have to declare relevant optimization variables. In this example the optimization variables are x, y and z:
# declare variable x, with lower bound 0 and no upper bound
x = solver.NumVar(0, solver.infinity(), "x")
# declare variable y, with lower bound 0 and no upper bound
y = solver.NumVar(0, solver.infinity(), "y")
# declare variable z, with lower bound 0 and no upper bound
z = solver.NumVar(0, solver.infinity(), "z")
Now I can model the problem by specifying the objective functions and all relevant constraints. In the following lines of code this is realized in a very lean way:
# declare as max. problem and define objective function
solver.Maximize(x+2*y+3*z)
# add constraints
solver.Add(2*x+y+z <= 20)
solver.Add(x+y+z <= 15)
solver.Add(x-y-z >= 0)
<ortools.linear_solver.pywraplp.Constraint; proxy of <Swig Object of type 'operations_research::MPConstraint *' at 0x000001B9AEC956C0> >
The model is now complete and can be solved:
solver.Solve()
The optimal solution for x is outputed below:
print("x_opt: ", x.solution_value())
x_opt: 6.666666666666667
The optimal solution for y is outputed below:
print("y_opt: ", y.solution_value())
y_opt: 0.0
The optimal solution for z is outputed below:
print("z_opt: ", z.solution_value())
z_opt: 6.666666666666667
The optimal objective function value is outputed below:
print("optimal value: " + str(x.solution_value()+2*y.solution_value()+3*z.solution_value()))
optimal value: 26.666666666666668
Data scientist focusing on simulation, optimization and modeling in R, SQL, VBA and Python
Leave a Reply