问题描述
是否可以(如果可以的话)使用具有条件表达式的目标函数?
Is it possible (and if so how) to use an objective function that has a conditional expression?
从文档中更改示例,我想要一个类似这样的表达式:
Changing the example from the docs, I would like an expression like:
def objective_function(model):
return model.x[0] if model.x[1] < const else model.x[2]
model.Obj = Objective(rule=objective_function, sense=maximize)
这可以像这样直接建模吗?还是我必须考虑某种转换(如果是这样的话,会是什么样子?)?
Can this be modelled directly like this or do I have to consider some sort of transformation (and if so how would this look like)?
只需执行上面的操作,就会显示一条错误消息,例如:
Just executing the above gives an error message like:
Evaluating Pyomo variables in a Boolean context, e.g.
if expression <= 5:
is generally invalid. If you want to obtain the Boolean value of the
expression based on the current variable values, explicitly evaluate the
expression using the value() function:
if value(expression) <= 5:
or
if value(expression <= 5):
我认为这是因为Pyomo认为我想获取一个值,而不是一个带有变量的表达式.
which I think is because Pyomo thinks I'd like to obtain a value, instead of an expression with the variable.
推荐答案
表达该问题的一种方法是使用逻辑析取.您可以查看Pyomo.GDP文档的用法,但是看起来像这样:
One way to formulate that is by using a logical disjunction. You can look into the Pyomo.GDP documentation for usage, but it would look like:
m.helper_var = Var()
m.obj = Objective(expr=m.helper_var)
m.lessthan = Disjunct()
m.lessthan.linker = Constraint(expr=m.helper_var == m.x[0])
m.lessthan.constr = Constraint(expr=m.x[1] < const)
m.greaterthan = Disjunct()
m.greaterthan.linker = Constraint(expr=m.helper_var == m.x[2])
m.greaterthan.constr = Constraint(expr=m.x[1] >= const)
m.lessthanorgreaterthan = Disjunction(expr=[m.lessthan, m.greaterthan])
# some kind of transformation (convex hull or big-M)
您也可以使用互补性约束来表述.
You can also formulate this using complementarity constraints.
这篇关于pyomo和条件目标函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!