I am learning pyomo and working with a toy example, more specifically I would like to understand how to build an expression constraint rule with Pyomo and ultimately convert them into a decorator form - I have the following model that is working and produce the expected output.
from pyomo.environ import *
L = {"s": 3, "j": 5, "f": 8}
B = {"s": 2, "j": 5, "f": 8}
C = {"s": 2, "j": 3, "f": 4}
P = {"s": 3, "j": 5, "f": 7}
limit_b = 325
limit_l = 400
model = ConcreteModel()
model.PACKAGES = Set(initialize=L.keys())
model.x = Var(model.PACKAGES, within=NonNegativeIntegers)
model.value = Objective(
expr=sum((P[i] - C[i]) * model.x[i] for i in model.PACKAGES), sense=maximize
)
model.L_cst = Constraint(
expr=sum(L[i] * model.x[i] for i in model.PACKAGES) <= limit_l
)
model.ballon_cst = Constraint(
expr=sum(B[i] * model.x[i] for i in model.PACKAGES) <= limit_b
)
opt = SolverFactory("cbc")
results = opt.solve(model, tee=True)
model.pprint()
print("Objective value:", model.value())
From this code, I would like to use expressions and pyomo Sets
however I cannot convert the code in the correct way.
from pyomo.environ import *
model = ConcreteModel(name="Profit")
# Define sets
model.k = Set(initialize=["s", "j", "f"], doc="Types of package")
model.b = Set(initialize=[2, 5, 8], doc="B")
model.l = Set(initialize=[3, 5, 8], doc="L")
model.c = Set(initialize=[2, 3, 4], doc="C")
model.p = Set(initialize=[3, 5, 7], doc="P")
limit_B = 325
limit_L = 400
model.x = Var(model.k, within=NonNegativeIntegers)
def obj_rule(model):
return sum((model.p[i] - model.c[i]) * model.x[i] for i in model.k)
model.object = Objective(rule=obj_rule, sense=maximize)
def max_L_per_month_rule(model):
return sum(model.l[i] * model.x[i] for i in model.k) <= limit_L
model.max_L_per_month = Constraint(model, rule=max_L_per_month_rule)
def max_B_per_month_rule(model):
return sum(model.b[i] * model.x[i] for i in model.k) <= limit_B
model.max_B_per_month = Constraint(
model, rule=max_B_per_month_rule
)
opt = SolverFactory("cbc")
results = opt.solve(model, tee=True)
model.pprint()
print("Objective value:", model.value())
Can someone help me and explain the process?
The problem in your constraints is that you are passing the model as the first argument. Positional arguments in Constraint
components are assumed to be indexing sets. Your constraint is not indexed so the correct way to declare it using a rule would be:
model.max_L_per_month = Constraint(rule=max_L_per_month_rule)
I recommend taking a look at the online documentation for examples of declaring constraints using rules and the Pyomo workshop slides for an overview on the decorator notation