TypeError:无法将值' '视为常量,因为它具有未知的类型'function'

问题描述 投票:0回答:1

Pyomo小组,对于上述错误,我需要帮助。我已经尽力了,但是仍然无法使模型正常工作。以下是我的“目标函数”的公式以及错误消息。谢谢。

## Define Objective ##
def objective_rule(model):
    s1=sum(1000*(model.fmax[j] - model.fmin[j])+ model.cmax[j] - model.cmin[j] for j in model.j)
    s2=sum(model.x[i,k]*model.k*model.t[i] for k in model.k for i in model.i)
    return s1 + 300 * s2
model.objective = Objective(expr=objective_rule, sense=minimize, doc='the objective function')

目标函数之前的所有代码都可以(没有错误)。因此,我将在下面附带的代码下面...可能是引起问题的代码

## Display of the output ##
def pyomo_postprocess(options=None, instance=None, results=None):
    instance.x.display()
    writer = ExcelWriter("Data/output!G5:AJ27.csv")
    df.to_excel(writer,index=False)
    writer.save()

# pyomo command-line
if __name__ == '__main__':
    # This emulates what the pyomo command-line tools does
    from pyomo.opt import SolverFactory
    import pyomo.environ
    instance = model.create_instance()
    instance.pprint()
    opt = solvers.SolverFactory("cplex")
    results = opt.solve(instance, tee=True)
    # sends results to stdout
    instance.solutions.load_from(results)
    print("\nDisplaying Solution\n" + '-' * 60)
    pyomo_postprocess(None, instance, results)

执行程序时,出现下一条错误消息:

ERROR: Constructing component 'objective' from data=None failed:
    TypeError: Cannot treat the value '<function objective_rule at
    0x0000000007C31D08>' as a constant because it has unknown type
    'function'
python optimization error-handling cplex pyomo
1个回答
0
投票

问题是您在Objective组件声明中使用了错误的关键字参数。您应该使用rule而不是expr

model.objective = Objective(rule=objective_rule, sense=minimize, doc='the objective function')

expr关键字通常在您具有非常简单的目标函数表达式并且想要避免编写Python函数以返回目标表达式时使用。您可以像这样使用它:

model.objective = Objective(expr=m.x**2+m.y**2, sense=minimize, doc='the objective function')
© www.soinside.com 2019 - 2024. All rights reserved.