我想优化使用 Python 在 EES 软件(工程方程求解器)中编写的外部函数。为了实现这一点,我创建了一个简单的代码,在 EES 和 Python 之间建立连接并执行优化。
代码如下:
from EESConnect import EESConnector
import pyomo.environ as pyo
from pyomo.environ import *
from pyomo.opt import SolverFactory
model = pyo.ConcreteModel()
# Define the decision variable and bound
model.x = pyo.Var(bounds=(-5,5))
x = model.x
# Define the objective function
def my_function(x):
with EESConnector() as ees:
# Load the EES file with the objective function
ees.ees_file_path = 'C:/Users/XX/Desktop/Optimization/Opt.EES'
# Calculate the values of the objective function
func = ees.calculate([x])
return func
# Define the optimization problem
model.obj = pyo.Objective(rule= my_function(x), sense=minimize)
opt = SolverFactory('ipopt', executable='E:/Py/ipopt/bin/ipopt.exe')
opt.solve(model)
print('x=', value(model.x))
但是,上述代码似乎出现故障,因为 Python 似乎需要一个明确的目标函数。该问题似乎源于以下代码行:func = ees.calculate([x])。它卡在那条线上。看起来 Python 试图将“x”放入该函数,但 EES 不接受“x”;它只接受数值。因此,Python 似乎需要访问一个显式函数,但事实并非如此。
我不确定,但似乎我们需要告诉 Python 一个明确的目标函数不可用。相反,我们需要将值输入 EES 软件进行数值计算并检索数值输出。然后我们可以以这种方式进行优化过程。
谁能帮我解决这个问题?