# Import of the pyomo module
from pyomo.environ import *
 
# Creation of a Concrete Model
model = ConcreteModel()

"""
Explanation: <img src="static/pybofractal.png" alt="Pybonacci" style="width: 200px;"/>
<img src="static/cacheme_logo.png" alt="CAChemE" style="width: 300px;"/>
The Transport Problem

Note: Adapted from https://github.com/Pyomo/PyomoGallery, see LICENSE.BSD

Summary
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.
Problem Statement
The Transport Problem can be formulated mathematically as a linear programming problem using the following model.  
Sets
$I$ = set of canning plants
 $J$ = set of markets
Parameters
$a_i$     = capacity of plant $i$ in cases, $\forall i \in I$ <br />
 $b_j$     = demand at market $j$ in cases, $\forall j \in J$ <br />
 $d_{i,j}$ = distance in thousands of miles, $\forall i \in I, \forall j \in J$ <br />
 $f$       = freight in dollars per case per thousand miles <br />
 $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$
Variables
$x_{i,j}$ = shipment quantities in cases <br />
 z         = total transportation costs in thousands of dollars
Objective
Minimize the total cost of the shipments: <br />
$\min_{x} z = \sum_{i \in I} \sum_{j \in J} c_{i,j} x_{i,j}$
Constraints
Observe supply limit at plant i: <br />
 $\sum_{i \in I} x_{i,j} \leq a_{i}$, $\forall i \in I$
Satisfy demand at market j: <br />
 $\sum_{j \in J} x_{i,j} \geq b_{j}$, $\forall j \in J$
Non-negative transportation quantities <br />
 $x_{i,j} \geq 0$, $\forall i \in I, \forall j \in J$
Pyomo Formulation
Creation of the Model
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:
End of explanation
"""


## 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')

"""
Explanation: Set Definitions
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:
End of explanation
"""


## 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')

"""
Explanation: Parameters
Parameter objects are created specifying the sets over which they are defined and are initialised with either a python dictionary or a scalar:
End of explanation
"""


#  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')

"""
Explanation: 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.
End of explanation
"""


## 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')

"""
Explanation: Variables
Similar to parameters, variables are created specifying their domain(s). For variables we can also specify the upper/lower bounds in the constructor.
Differently from GAMS, we don't need to define the variable that is on the left hand side of the objective function.
End of explanation
"""


## 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')

"""
Explanation: Constrains
At this point, it should not be a surprise that constrains are again defined as model objects with the required information passed as parameter in the constructor function.
End of explanation
"""


def supply_rule(model, i):
    supply = 0.0
    for j in model.j:
        supply += model.x[i,j]
    return supply <= model.a[i]

"""
Explanation: The above code takes 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:
End of explanation
"""


## 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 ;
def objective_rule(model):
    return sum(model.c[i,j]*model.x[i,j] for i in model.i for j in model.j)

model.objective = Objective(rule=objective_rule, sense=minimize, doc='Define objective function')

"""
Explanation: Using list comprehension is however quicker to code and more readable. 
Objective and Solving
The definition of the objective is similar to those of the constrains, except that most solvers require a scalar objective function, hence a unique function, and we can specify the sense (direction) of the optimisation.
End of explanation
"""


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

"""
Explanation: As we are here looping over two distinct sets, we can see how list comprehension really simplifies the code. The objective function could have been written without list comprehension as:
End of explanation
"""


## Display of the output ##
# Display x.l, x.m ;
def pyomo_postprocess(options=None, instance=None, results=None):
    model.x.display()

"""
Explanation: Retrieving the Output
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.
End of explanation
"""


# 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)

"""
Explanation: 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.
Editing and Running the Script
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:
End of explanation
"""


#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Explanation: 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:
End of explanation
"""


!cat transport.py

"""
Explanation: Complete script
Here is the complete script:
End of explanation
"""


!pyomo solve --solver=glpk transport.py

"""
Explanation: Solutions
Running the model lead to the following output:
End of explanation
"""


!cat results.json

"""
Explanation: By default, the optimization results are stored in the file results.json:
End of explanation
"""


