我对优化代码有一个问题。我写的代码应该优化这两个目标,考虑它们的表达式,并产生可以绘制的值。这是我的代码,如下所述。
from pyomo.environ import *
import numpy as np
import pandas as pd
import random
import matplotlib.pyplot as plt
model = ConcreteModel()
st1 = []
st2 = []
rows =10
n = []
for i in range(rows):
rn = random.randint(1,10)
n.append(rn)
print(rn)
model.x1 = Var(within=NonNegativeReals, initialize=rn)
model.x2 = Var(within=NonNegativeReals, initialize=rn)
model.x3 = Var(within=NonNegativeReals, initialize=rn)
model.x4 = Var(within=NonNegativeReals, initialize=rn)
model.f1 = Var()
model.f2 = Var()
model.C_f1 = Constraint(expr= model.f1 == 2 * model.x1 - model.x2 + 4 * model.x3 + model.x4)
model.C_f2 = Constraint(expr= model.f2 == -3 * model.x1 + model.x2 + 2 * model.x3 - 2 * model.x4)
model.O_f1 = Objective(expr= model.f1, sense=maximize)
model.O_f2 = Objective(expr= model.f2, sense=maximize)
model.O_f1.activate()
model.O_f2.deactivate()
solver = SolverFactory('glpk')
solver.solve(model);
print('( x1 , x2 , x3 , x4 ) = ( ' + str(value(model.x1)) + ' , ' + str(value(model.x2)) + ' , ' + str(value(model.x3)) + ' , ' + str(value(model.x4)) + ' )')
st1.append(value(model.f1))
st2.append(value(model.f2))
model.O_f2.activate()
model.O_f1.deactivate()
solver = SolverFactory('glpk')
solver.solve(model);
print('( x1 , x2 , x3 , x4 ) = ( ' + str(value(model.x1)) + ' , ' + str(value(model.x2)) + ' , ' + str(value(model.x3)) + ' , ' + str(value(model.x4)) + ' )')
st1.append(value(model.f1))
st2.append(value(model.f2))
print(n)
print(st1)
print(st2)
plt.scatter(st1, st2)
plt.xlabel('Objective A')
plt.ylabel('Objective B')
plt.show()这就是出现的错误,
7
( x1 , x2 , x3 , x4 ) = ( 7 , 7 , 7 , 7 )
ERROR: evaluating object as numeric value: f1
(object: <class 'pyomo.core.base.var.ScalarVar'>)
No value for uninitialized NumericValue object f1
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-14-c6162a718dc9> in <module>
34
35 print('( x1 , x2 , x3 , x4 ) = ( ' + str(value(model.x1)) + ' , ' +
str(value(model.x2)) + ' , ' + str(value(model.x3)) + ' , ' + str(value(model.x4)) + ' )')
---> 36 st1.append(value(model.f1))
37 st2.append(value(model.f2))
38
pyomo\core\expr\numvalue.pyx in pyomo.core.expr.numvalue.value()
pyomo\core\expr\numvalue.pyx in pyomo.core.expr.numvalue.value()
ValueError: No value for uninitialized NumericValue object f1有没有人可以帮我解决这个问题,给我看看错误,或者帮我找一个替代方案
发布于 2021-09-23 16:19:53
问题是你的模型是无界的。您正在尝试最大化它,并且没有上限约束,因此值可以是无限的。
应始终在解算后首先检查解算器状态,以便在深入研究之前查看所获得的结果。添加以下内容:
result = solver.solve(model);
print(result)https://stackoverflow.com/questions/69301115
复制相似问题