# Cost for triple ts commodity - source - destina ti on
cost = {
( ’ Pencil s ’, ’ D etroit ’ , ’ Boston ’): 10 ,
( ’ Pencil s ’, ’ D etroit ’ , ’New York ’): 20 ,
( ’ Pencil s ’, ’ D etroit ’ , ’ Se attle ’): 60 ,
( ’ Pencil s ’, ’ D enver ’ , ’ Boston ’ ): 40 ,
( ’ Pencil s ’, ’ D enver ’ , ’ New York ’ ): 40 ,
( ’ Pencil s ’, ’ D enver ’ , ’ Sea ttle ’ ): 30 ,
( ’ Pens ’, ’ Det roit ’ , ’ Bo ston ’): 20 ,
( ’ Pens ’, ’ Det roit ’ , ’New York ’): 20 ,
( ’ Pens ’, ’ Det roit ’ , ’ Seat tle ’): 80 ,
( ’ Pens ’, ’ Denver ’, ’ Bos ton ’): 60 ,
( ’ Pens ’, ’ Denver ’, ’ New York ’): 70 ,
( ’ Pens ’, ’ Denver ’, ’ Seatt le ’ ): 30}
# Demand for pairs of commodity - city
inflow = {
( ’ Pencil s ’, ’ D etroit ’ ): 50 ,
( ’ Pencil s ’, ’ D enver ’ ): 60 ,
( ’ Pencil s ’, ’ B oston ’ ): -50 ,
( ’ Pencil s ’, ’ New York ’ ): -50 ,
( ’ Pencil s ’, ’ S eattle ’ ): -10 ,
( ’ Pens ’, ’ Det roit ’ ): 60 ,
( ’ Pens ’, ’ Denver ’): 40 ,
( ’ Pens ’, ’ Boston ’): -40 ,
( ’ Pens ’, ’ New York ’): -30 ,
( ’ Pens ’, ’ Sea ttle ’ ): -30}
# Create op timizat io n model
m = gp . Model (’ netflow ’)
# Create v ar ia bl es
flow = m . add Vars ( commodities , arcs , obj =cost , name = " flow ")
# Arc - capacity c on st raints
m. add Co ns tr s (
( flow . sum ( ’* ’, i , j ) <= capacity [i, j ] for i , j in arcs ), " cap ")
# Eq ui va le nt version using Python l ooping
# for i, j in arcs :
# m. addCons tr ( sum ( flow [h , i , j ] for h in commo di ti es ) <= ca pacity [i , j ],
# " cap [% s , %s]" % (i , j ))
# Flow - co ns ervatio n const ra ints
m. add Co ns tr s (
( flow . sum (h , ’*’, j) + inflow [h , j ] == flow . sum (h, j , ’* ’)
for h in c om modities for j in nodes ) , " node ")
# Alternate ve rsion :
# m. addCons tr s (
# ( gp . quicksum ( flow [h, i , j ] for i, j in arcs . sel ect ( ’* ’ , j )) + infl ow [h , j ] ==
# gp . quicksu m ( flow [h, j , k] for j , k in arcs . sel ect (j, ’* ’))
# for h in co mmodities for j in nodes ) , " node ")
84