问题
I am currently trying to solve this problem. I need to maximize the profit of this company.
That s the code I currently have:
from pyomo.environ import *
from pyomo.opt import *
opt = solvers.SolverFactory("ipopt")
model = ConcreteModel()
model.x1 = Var(within=NonNegativeIntegers)
model.x2 = Var(within=NonNegativeIntegers)
model.y1 = Var(within=NonNegativeIntegers)
model.y2 = Var(within=NonNegativeIntegers)
model.b1 = Var(within=Boolean)
model.b2 = Var(within=Boolean)
model.c1 = Constraint(expr = model.x1 + model.x2 + model.y1 + model.y2 <= 7000)
model.c2 = Constraint(expr = 2*model.x1 + 2*model.x2 + model.y1 + model.y2 <= 10000)
model.c3 = Constraint(expr = model.x1 <= 2000)
model.c4 = Constraint(expr = model.x2 <= 1000)
model.c5 = Constraint(expr = model.y1 <= 2000)
model.c6 = Constraint(expr = model.y2 <= 3000)
model.z = Objective(expr= (150*model.x1 + 180*model.x2*model.b1 + 100*model.y1 + 110*model.y2*model.b2), sense=maximize)
results = opt.solve(model)
This is the code I tried to write for my constraint which is then only using the first slope as long as it does not exceed 2000 products:
def ObjRule(model):
if model.x1 >= 2000:
return model.b1==1
if model.x2 >= 2000:
return model.b2 == 1`
If someone would have a hint, how I could proceed that would be great.
thank you in advance, Patrick
回答1:
In Pyomo, rules are not callbacks sent to a solver. They are called once for each index to obtain a static set of expressions. This set of expressions is what is sent to a solver. Any if-logic you use inside of rules should not involve the values of variables (unless it is based on the initial value of a variable, in which case you would wrap the variable in value() wherever you use it outside of the main expression that is returned).
If you want to model a piecewise function, you need to apply some kind of modeling trick to do so. In some cases this involves introducing discrete variables (see examples for the Piecewise component), in other cases it does not (for instance when maximizing a piecewise function that can be expressed as the min of a finite number of affine functions).
来源:https://stackoverflow.com/questions/40873161/pyomo-constraint-with-if-statements