A Soft Introduction to Google OR-Tools

Advancedor Academy
Operations Research Bit
2 min readSep 2, 2023

Today we are going to talk about OR-Tools. Google OR-Tools is an acronym for Operations Research.

OR-Tools allows you to solve problems such as assignment, routing, scheduling and planning in different programming languages. For a simple introduction, we will develop a basic linear programming program.

First, we need to install OR-Tools on our computer.

!pip install ortools

I am sharing the formulation we need to model as a screenshot below.

First we need to call the solver to solve the problem.

from ortools.linear_solver import pywraplp

Now we need to define a solver. Then we enter the type to solve as a parameter.

solver = pywraplp.Solver("Maximization", pywraplp.Solver.GLOP_LINEAR_PROGRAMMING)

Now we will define the decision variables. Variables are numeric.

x1 = solver.NumVar(0, solver.infinity(),"x1")
x2 = solver.NumVar(0, solver.infinity(),"x2")

Now we can write the constraints.

solver.Add(x2 <=5)
solver.Add(x1+x2 <=10)
solver.Add(x1-x2 <=2)

Let’s write our objective function. For this we will define a new variable called pop.

pop = solver.NumVar(0, solver.infinity(),"pop")
solver.Add(pop == 3*x1+x2)

Now, we will ask the solver to maximize the variable pop. Let’s code it.

solver.Maximize(pop)
solver.Solve()

After the last command you will see 0 as output. This indicates that the operation is complete.

Now let’s write the code to see the solution value.

pop.SolutionValue()

After running this code, we will see that the value of the objective function is 22.0.

Now let’s see what the values of our decision variables are.

x1.SolutionValue()
x2.SolutionValue()

You will see that our variables are 6.0 and 4.0 respectively.

This article may seem very simple since it is an introductory level article, but in the field of operations research, it is very important to first master the logic of modeling. After simple models, you can move on to models of intermediate and advanced difficulty.

I hope it was useful for people who are thinking about getting into optimization and solving problems with Python. See you in different optimization problems.

References

https://developers.google.com/optimization/introduction/python

--

--