Skip to content

Instantly share code, notes, and snippets.

@AnuragAnalog
Created July 5, 2021 13:02
Show Gist options
  • Save AnuragAnalog/1860dc86a8951af9a23f2e304843d5d3 to your computer and use it in GitHub Desktop.
Save AnuragAnalog/1860dc86a8951af9a23f2e304843d5d3 to your computer and use it in GitHub Desktop.
Getting started with OR tools
# Getting started:
# Python3 installation: python -m pip install --upgrade --user ortools
#
# Optimisation with the OR tool can be done in 5 steps:
# Creating a solver
# Creating a variable (x, y, … etc.)
# Creating linear constraints
# Creating an objective function
# Run the solver
#
# E.g: max z = 8x1 + 11x2 + 6x3 + 4x4
# Such that:
# 5x1 + 7x2 + 0x3 + 3x4 <= 14
# 8x1 + 0x2 + 4x3 + 4x4 <= 12
# 2x1 + 10x2 + 6x3 + 4x4 <= 15
#
# x1, x2, x3, x4 belongs to [0, 1]
#!/usr/bin/python3
from ortools.linear_solver import pywraplp
# Create the linear solver with the GLOP backend.
solver = pywraplp.Solver.CreateSolver('GLOP')
# Create the variables x1 to x4.
x1 = solver.NumVar(0, 1, 'x1')
x2 = solver.NumVar(0, 1, 'x2')
x3 = solver.NumVar(0, 1, 'x3')
x4 = solver.NumVar(0, 1, 'x4')
print('Number of variables =', solver.NumVariables())
# Add a linear constraint, 5x1 + 7x2 + 0x3 + 3x4 <= 14.
ct1 = solver.Constraint(0, 14, 'ct1')
ct1.SetCoefficient(x1, 5)
ct1.SetCoefficient(x2, 7)
ct1.SetCoefficient(x3, 0)
ct1.SetCoefficient(x4, 3)
# Add a linear constraint, 8x1 + 0x2 + 4x3 + 4x4 <= 12.
ct2 = solver.Constraint(0, 12, 'ct2')
ct2.SetCoefficient(x1, 8)
ct2.SetCoefficient(x2, 0)
ct2.SetCoefficient(x3, 4)
ct2.SetCoefficient(x4, 4)
# Add a linear constraint, 2x1 + 10x2 + 6x3 + 4x4 <= 15.
ct3 = solver.Constraint(0, 15, 'ct3')
ct3.SetCoefficient(x1, 2)
ct3.SetCoefficient(x2, 10)
ct3.SetCoefficient(x3, 6)
ct3.SetCoefficient(x4, 4)
print('Number of constraints =', solver.NumConstraints())
# Create the objective function, 8x1 + 11x2 + 6x3 + 4x4.
objective = solver.Objective()
objective.SetCoefficient(x1, 8)
objective.SetCoefficient(x2, 11)
objective.SetCoefficient(x3, 6)
objective.SetCoefficient(x4, 4)
objective.SetMaximization()
solver.Solve()
print('Solution:')
print('Objective value =', objective.Value())
print('x1 =', x1.solution_value())
print('x2 =', x2.solution_value())
print('x3 =', x3.solution_value())
print('x4 =', x4.solution_value())
@AnuragAnalog
Copy link
Author

A Binary Linear Programming Optimization script.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment