Pyomo - Getting started

Pyomo installation: see http://www.pyomo.org/installation

pip install pyomo

In [ ]:
from pyomo.environ import *

Example 1


In [ ]:
model = ConcreteModel(name="Getting started")

model.x = Var(bounds=(-10, 10))

model.obj = Objective(expr=model.x)

model.const_1 = Constraint(expr=model.x >= 5)

# @tail:
opt = SolverFactory('glpk')  # "glpk" or "cbc"

res = opt.solve(model)    # solves and updates instance

model.display()

print()
print("Optimal solution: ", value(model.x))
print("Cost of the optimal solution: ", value(model.obj))
# @:tail

Example 2

$$ \begin{align} \max_{x_1,x_2} & \quad 4 x_1 + 3 x_2 \\ \text{s.t.} & \quad x_1 + x_2 \leq 100 \\ & \quad 2 x_1 + x_2 \leq 150 \\ & \quad 3 x_1 + 4 x_2 \leq 360 \\ & \quad x_1, x_2 \geq 0 \end{align} $$
Optimal total cost is:  350.0

x_1 = 50.
x_2 = 50.

In [ ]:
model = ConcreteModel(name="Getting started")

model.x1 = Var(within=NonNegativeReals)
model.x2 = Var(within=NonNegativeReals)

model.obj = Objective(expr=4. * model.x1 + 3. * model.x2, sense=maximize)

model.ineq_const_1 = Constraint(expr=model.x1 + model.x2 <= 100)
model.ineq_const_2 = Constraint(expr=2. * model.x1 + model.x2 <= 150)
model.ineq_const_3 = Constraint(expr=3. * model.x1 + 4. * model.x2 <= 360)

# @tail:
opt = SolverFactory('glpk')  # "glpk" or "cbc"

results = opt.solve(model)    # solves and updates instance

model.display()

print()
print("Optimal solution: ({}, {})".format(value(model.x1), value(model.x2)))
print("Gain of the optimal solution: ", value(model.obj))
# @:tail