This example shows how to use an abstract model where the data is contained in a separate data file and the model is defined using abstract model parameters.

The example is again an "Activity Analysis" problem just like the WYNDOR GLASS CO. example; it is taken from Appendix 3.1 in the 7th edition of Hillier and Lieberman; this section has disappeared in later editions of the book.

A mix of four products is to be produced. The names of the products are contained in index set P and each product yields a profit per unit p. Three machines with corresponding index set M have available production time t. The working time per machine per unit of product is contained in the matrix w.

The task is to determine the product mix x that maximizes total profit.

The actual data is contained in the data file `prod-mix.dat'.

In [1]:
from pyomo.environ import *
from pyomo.opt import *
opt = solvers.SolverFactory("glpk")
In [2]:
model = AbstractModel()

# Products
model.P = Set()
# Machines
model.M = Set()

# Time available on each machine
model.t = Param(model.M, within=PositiveReals)
# Profit for each product
model.p = Param(model.P, within=PositiveReals)
# Work capacity requiment for each machine and each product
model.w = Param(model.M, model.P, within=NonNegativeReals)

# Number of units to be produced for each product
model.x = Var(model.P, within=NonNegativeReals)
In [3]:
# Maximize profit from product mix
def profit_rule(model):
    return sum(model.p[i]*model.x[i] for i in model.P)
model.profit = Objective(rule=profit_rule, sense=maximize)
In [4]:
# Ensure that work can be performed within available capacities
def capacity_rule(model, j):
    return sum(model.w[j,i]*model.x[i] for i in model.P) <= model.t[j]
model.capacity_constraint = Constraint(model.M, rule=capacity_rule)

We turn the abstract model into a concrete instance as follows:

In [5]:
instance = model.create_instance('prod-mix.dat')

Now we solve the instance, not the model.

In [6]:
results = opt.solve(instance)

And we can access the results as before:

In [7]:
instance.x.get_values()
Out[7]:
{'P01': 0.0, 'P02': 10.0, 'P03': 5.0, 'P04': 0.0}
In [8]:
instance.p.extract_values()
Out[8]:
{'P01': 26, 'P02': 35, 'P03': 25, 'P04': 37}
In [9]:
instance.profit.expr()
Out[9]:
475.0