Given a single product, p plants and m markets, define the best route between p and m as to minimize transport costs:
$ min \sum_{p}{\sum_{m} {c_{p,m} * x_{p,m}}} $
s.t.
$\sum_{m} x_{p,m} <= a_p $
$\sum_{p} x_{p,m} >= b_m $
You will need to import as a minima the JuMP module. If you wish to specify a solver engine rather than letting JuMP select a suitable one, you will need to import also the module relative to the solver, e.g. Ipopt or GLPK
# Import of the JuMP, GLPK and CSV modules (the latter one just to import the data from a header based table, as in the original trasnport example in GAMS
using JuMP, GLPK, CSV, DataFrames
JuMP doesn't really have a concept of sets, but it uses the native containers available in the core Julia language\Variables, parameters and constraints can be indexed using these containers. While many works with position-based lists, I find more readable using dictionaries instead. So the “sets” are represented as lists, but then everything else is a dictionary with the elements of the list as keys. One note: it seems that Julia/JuMP don't like much the “-” symbol, so I replaced it to “_”.
# Define sets #
# Sets
# i canning plants / seattle, san-diego /
# j markets / new-york, chicago, topeka / ;
plants = ["seattle","san_diego"] # canning plants
markets = ["new_york","chicago","topeka"] # markets
3-element Array{String,1}: "new_york" "chicago" "topeka"
Capacity of plants and demand of markets are directly defined as dictionaries, while the distance is first read as a DataFrame from a white-space separated table and then it is converted in a “(plant, market) ⇒ value” dictionary.
# Define parameters #
# Parameters
# a(i) capacity of plant i in cases
# / seattle 350
# san-diego 600 /
a = Dict( # 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 / ;
b = Dict( # demand at market j in cases
"new_york" => 325,
"chicago" => 300,
"topeka" => 275,
)
Dict{String,Int64} with 3 entries: "chicago" => 300 "new_york" => 325 "topeka" => 275
# 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 ;
d_table = CSV.read(IOBuffer("""
plants new_york chicago topeka
seattle 2.5 1.7 1.8
san_diego 2.5 1.8 1.4
"""), delim=" ", ignorerepeated=true, copycols=true)
plants | new_york | chicago | topeka | |
---|---|---|---|---|
String | Float64 | Float64 | Float64 | |
1 | seattle | 2.5 | 1.7 | 1.8 |
2 | san_diego | 2.5 | 1.8 | 1.4 |
d = Dict( (r[:plants],m) => r[Symbol(m)] for r in eachrow(d_table), m in markets)
# Here we are converting the table in a "(plant, market) => distance" dictionary
# r[:plants]: the first key, row field using a fixed header
# m: the second key
# r[Symbol(m)]: the value, the row field with a dynamic header
# Scalar f freight in dollars per case per thousand miles /90/ ;
f = 90 # freight in dollars per case per thousand miles
# Parameter c(i,j) transport cost in thousands of dollars per case ;
# c(i,j) = f * d(i,j) / 1000 ;
# We first declare an empty dictionary and then we fill it with the values
c = Dict() # transport cost in thousands of dollars per case ;
[ c[p,m] = f * d[p,m] / 1000 for p in plants, m in markets]
2×3 Array{Float64,2}: 0.225 0.153 0.162 0.225 0.162 0.126
Here we declare a JuML optimisation model and we give it a name. This name will be then passed as first argument to all the subsequent operations, like creation of variables, constraints and objective function. We can, if we wish, works with several models at the same time. If we do not specify a solver, we let JuML use a suitable solver for the type of problem. Aside to specify the solver, we can also pass it solver-level options, e.g.: mymodel = Model(solver=IpoptSolver(print_level=0))
# Model declaration (transport model)
trmodel = Model(with_optimizer(GLPK.Optimizer,msg_lev=GLPK.MSG_ON))
# or
# trmodel = Model(with_optimizer(Ipopt.Optimizer,print_level=0)) # would require "using Ipopt" instead of GLPK
Variables can have multiple-dimensions - that is, being indexed under several indexes -, and bounds are given at the same time as their declaration. Differently from GAMS, we don't need to define the variable that is on the left hand side of the objective function.
## Define variables ##
# Variables
# x(i,j) shipment quantities in cases
# z total transportation costs in thousands of dollars ;
# Positive Variable x ;
@variables trmodel begin
x[p in plants, m in markets] >= 0 # shipment quantities in cases
end
As in GAMS, each constraint can actually be a “family” of constraints:
## Define contrains ##
# supply(i) observe supply limit at plant i
# supply(i) .. sum (j, x(i,j)) =l= a(i)
# demand(j) satisfy demand at market j ;
# demand(j) .. sum(i, x(i,j)) =g= b(j);
@constraints trmodel begin
supply[p in plants], # observe supply limit at plant p
sum(x[p,m] for m in markets) <= a[p]
demand[m in markets], # satisfy demand at market m
sum(x[p,m] for p in plants) >= b[m]
end
Contrary to constraints and variables, the objective is always a unique function. Note that it is at this point that we specify the direction of the optimisation.
# Objective
@objective trmodel Min begin
sum(c[p,m]*x[p,m] for p in plants, m in markets)
end
If we wish, we can get the optimisation model printed in a human-readable fashion, so we can check that all is correct.
print(trmodel)
Min 0.225 x[seattle,new_york] + 0.225 x[san_diego,new_york] + 0.153 x[seattle,chicago] + 0.162 x[san_diego,chicago] + 0.162 x[seattle,topeka] + 0.12599999999999997 x[san_diego,topeka] Subject to x[seattle,new_york] + x[san_diego,new_york] ≥ 325.0 x[seattle,chicago] + x[san_diego,chicago] ≥ 300.0 x[seattle,topeka] + x[san_diego,topeka] ≥ 275.0 x[seattle,new_york] + x[seattle,chicago] + x[seattle,topeka] ≤ 350.0 x[san_diego,new_york] + x[san_diego,chicago] + x[san_diego,topeka] ≤ 600.0 x[seattle,new_york] ≥ 0.0 x[seattle,chicago] ≥ 0.0 x[seattle,topeka] ≥ 0.0 x[san_diego,new_york] ≥ 0.0 x[san_diego,chicago] ≥ 0.0 x[san_diego,topeka] ≥ 0.0
It is at this point that the solver is called and the model is passed to the solver engine for its solution. The return value is the status of the optimisation (“:Optimal” if all went fine)
optimize!(trmodel)
0: obj = 0.000000000e+00 inf = 9.000e+02 (3) 4: obj = 1.561500000e+02 inf = 0.000e+00 (0) * 5: obj = 1.536750000e+02 inf = 0.000e+00 (0)
While you can do any fancy output you may wish after you retrieve the optimal value of the variables with getvalue(var_name), you can just println(getvalue(x)) to get a basic output. Notice that you can also easily retrieve the dual value associated to the constraint with getdual(constraint_name).
status = termination_status(trmodel)
if (status == MOI.OPTIMAL) || (status == MOI.LOCALLY_SOLVED)
println("Objective value: ",objective_value(trmodel))
println(value.(x))
println("Shadow prices of supply:")
[println("$p = $(dual(supply[p]))") for p in plants]
println("Shadow prices of demand:")
[println("$m = $(dual(demand[m]))") for m in markets]
else
println("Model didn't solved")
println(status)
end
# Expected result:
# obj= 153.675
#['seattle','new-york'] = 50
#['seattle','chicago'] = 300
#['seattle','topeka'] = 0
#['san-diego','new-york'] = 275
#['san-diego','chicago'] = 0
#['san-diego','topeka'] = 275
Objective value: 153.675 2-dimensional DenseAxisArray{Float64,2,...} with index sets: Dimension 1, ["seattle", "san_diego"] Dimension 2, ["new_york", "chicago", "topeka"] And data, a 2×3 Array{Float64,2}: 50.0 300.0 0.0 275.0 0.0 275.0 Shadow prices of supply: seattle = 0.0 san_diego = 0.0 Shadow prices of demand: new_york = 0.225 chicago = 0.153 topeka = 0.12599999999999997
3-element Array{Nothing,1}: nothing nothing nothing