Note: Adapted from https://github.com/Pyomo/PyomoGallery, see LICENSE.BSD
The goal of the Transport Problem is to select the quantities of an homogeneous good that has several production plants and several punctiform markets as to minimise the transportation costs.
It is the default tutorial for the GAMS language, and GAMS equivalent code is inserted as single-dash comments. The original GAMS code needs slighly different ordering of the commands and it's available at http://www.gams.com/mccarl/trnsport.gms.
The Transport Problem can be formulated mathematically as a linear programming problem using the following model.
$I$ = set of canning plants
$J$ = set of markets
$a_i$ = capacity of plant $i$ in cases, $\forall i \in I$
$b_j$ = demand at market $j$ in cases, $\forall j \in J$
$d_{i,j}$ = distance in thousands of miles, $\forall i \in I, \forall j \in J$
$f$ = freight in dollars per case per thousand miles
$c_{i,j}$ = transport cost in thousands of dollars per case
$c_{i,j}$ is obtained exougenously to the optimisation problem as $c_{i,j} = f \cdot d_{i,j}$, $\forall i \in I, \forall j \in J$
$x_{i,j}$ = shipment quantities in cases
z = total transportation costs in thousands of dollars
Minimize the total cost of the shipments:
$\min_{x} z = \sum_{i \in I} \sum_{j \in J} c_{i,j} x_{i,j}$
Observe supply limit at plant i:
$\sum_{i \in I} x_{i,j} \leq a_{i}$, $\forall i \in I$
Satisfy demand at market j:
$\sum_{j \in J} x_{i,j} \geq b_{j}$, $\forall j \in J$
Non-negative transportation quantities
$x_{i,j} \geq 0$, $\forall i \in I, \forall j \in J$
In pyomo everything is an object. The various components of the model (sets, parameters, variables, constraints, objective..) are all attributes of the main model object while being objects themselves.
There are two type of models in pyomo: A ConcreteModel
is one where all the data is defined at the model creation. We are going to use this type of model in this tutorial. Pyomo however supports also an AbstractModel
, where the model structure is firstly generated and then particular instances of the model are generated with a particular set of data.
The first thing to do in the script is to load the pyomo library and create a new ConcreteModel
object. We have little imagination here, and we call our model "model". You can give it whatever name you want. However, if you give your model an other name, you also need to create a model
object at the end of your script:
In [1]:
# Import of the pyomo module
from pyomo.environ import *
# Creation of a Concrete Model
model = ConcreteModel()
Sets are created as attributes object of the main model objects and all the information is given as parameter in the constructor function. Specifically, we are passing to the constructor the initial elements of the set and a documentation string to keep track on what our set represents:
In [2]:
## Define sets ##
# Sets
# i canning plants / seattle, san-diego /
# j markets / new-york, chicago, topeka / ;
model.i = Set(initialize=['seattle','san-diego'], doc='Canning plans')
model.j = Set(initialize=['new-york','chicago', 'topeka'], doc='Markets')
In [3]:
## Define parameters ##
# Parameters
# a(i) capacity of plant i in cases
# / seattle 350
# san-diego 600 /
# b(j) demand at market j in cases
# / new-york 325
# chicago 300
# topeka 275 / ;
model.a = Param(model.i, initialize={'seattle':350,'san-diego':600}, doc='Capacity of plant i in cases')
model.b = Param(model.j, initialize={'new-york':325,'chicago':300,'topeka':275}, doc='Demand at market j in cases')
# Table d(i,j) distance in thousands of miles
# new-york chicago topeka
# seattle 2.5 1.7 1.8
# san-diego 2.5 1.8 1.4 ;
dtab = {
('seattle', 'new-york') : 2.5,
('seattle', 'chicago') : 1.7,
('seattle', 'topeka') : 1.8,
('san-diego','new-york') : 2.5,
('san-diego','chicago') : 1.8,
('san-diego','topeka') : 1.4,
}
model.d = Param(model.i, model.j, initialize=dtab, doc='Distance in thousands of miles')
# Scalar f freight in dollars per case per thousand miles /90/ ;
model.f = Param(initialize=90, doc='Freight in dollars per case per thousand miles')
A third, powerful way to initialize a parameter is using a user-defined function.
This function will be automatically called by pyomo with any possible (i,j) set. In this case pyomo will actually call c_init()
six times in order to initialize the model.c
parameter.
In [4]:
# Parameter c(i,j) transport cost in thousands of dollars per case ;
# c(i,j) = f * d(i,j) / 1000 ;
def c_init(model, i, j):
return model.f * model.d[i,j] / 1000
model.c = Param(model.i, model.j, initialize=c_init, doc='Transport cost in thousands of dollar per case')
In [5]:
## Define variables ##
# Variables
# x(i,j) shipment quantities in cases
# z total transportation costs in thousands of dollars ;
# Positive Variable x ;
model.x = Var(model.i, model.j, bounds=(0.0,None), doc='Shipment quantities in case')
In [6]:
## Define contrains ##
# supply(i) observe supply limit at plant i
# supply(i) .. sum (j, x(i,j)) =l= a(i)
def supply_rule(model, i):
return sum(model.x[i,j] for j in model.j) <= model.a[i]
model.supply = Constraint(model.i, rule=supply_rule, doc='Observe supply limit at plant i')
# demand(j) satisfy demand at market j ;
# demand(j) .. sum(i, x(i,j)) =g= b(j);
def demand_rule(model, j):
return sum(model.x[i,j] for i in model.i) >= model.b[j]
model.demand = Constraint(model.j, rule=demand_rule, doc='Satisfy demand at market j')
The above code take advantage of list comprehensions, a powerful feature of the python language that provides a concise way to loop over a list. If we take the supply_rule as example, this is actually called two times by pyomo (once for each of the elements of i). Without list comprehensions we would have had to write our function using a for loop, like:
In [7]:
def supply_rule(model, i):
supply = 0.0
for j in model.j:
supply += model.x[i,j]
return supply <= model.a[i]
Using list comprehension is however quicker to code and more readable.
In [8]:
## Define Objective and solve ##
# cost define objective function
# cost .. z =e= sum((i,j), c(i,j)*x(i,j)) ;
# Model transport /all/ ;
# Solve transport using lp minimizing z ;
#
# itertools.product() returns the Cartesian product of two or more iterables
import itertools
def objective_rule(model):
return sum(model.c[i,j]*model.x[i,j] for i, j in itertools.product(model.i, model.j))
model.objective = Objective(rule=objective_rule, sense=minimize, doc='Define objective function')
As we are here looping over two distinct sets, we can see how list comprehension really simplifies the code. The objective function could have being written without list comprehension as:
In [9]:
def objective_rule(model):
obj = 0.0
for ki in model.i:
for kj in model.j:
obj += model.c[ki,kj]*model.x[ki,kj]
return obj
We use the pyomo_postprocess()
function to retrieve the output and do something with it. For example, we could display solution values (see below), plot a graph with matplotlib or save it in a csv file.
This function is called by pyomo after the solver has finished.
In [10]:
## Display of the output ##
# Display x.l, x.m ;
def pyomo_postprocess(options=None, instance=None, results=None):
model.x.display()
We can print model structure information with model.pprint()
(“pprint” stand for “pretty print”).
Results are also by default saved in a results.json
file or, if PyYAML is installed in the system, in results.yml
.
Differently from GAMS, you can use whatever editor environment you wish to code a pyomo script. If you don't need debugging features, a simple text editor like Notepad++ (in windows), gedit or kate (in Linux) will suffice. They already have syntax highlight for python.
If you want advanced features and debugging capabilities you can use a dedicated Python IDE, like e.g. Spyder.
You will normally run the script as pyomo solve –solver=glpk transport.py
. You can output solver specific output adding the option –stream-output
. If you want to run the script as python transport.py
add the following lines at the end:
In [11]:
# This emulates what the pyomo command-line tools does
from pyomo.opt import SolverFactory
import pyomo.environ
opt = SolverFactory("glpk")
results = opt.solve(model)
# sends results to stdout
results.write()
print("\nDisplaying Solution\n" + '-'*60)
pyomo_postprocess(None, None, results)
Finally, if you are very lazy and want to run the script with just ./transport.py
(and you are in Linux) add the following lines at the top:
In [12]:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
In [13]:
!cat transport.py
In [14]:
!pyomo solve --solver=glpk transport.py
By default, the optimization results are stored in the file results.json
:
In [15]:
!cat results.json
This solution shows that the minimum transport costs is attained when 300 cases are sent from the Seattle plant to the Chicago market, 50 cases from Seattle to New-York and 275 cases each are sent from San-Diego plant to New-York and Topeka markets.
The total transport costs will be $153,675.