首页 > 解决方案 > Can I transform string to pyomo variable?

问题描述

I have a .txt file which contains a variable for my model. If I copy and paste the contents of the file in my program as

def Wind_phi_definition(model, i):
         return m.Wind_phi[i] ==-19.995904426195736*Sinc(0.04188790204786391*(0. + m.lammda[i]*180/np.pi))*Sinc(0.08975979010256552*(-65. + m.phi[i]*180/np.pi))
m.Wind_phi_const = Constraint(m.N, rule = Wind_phi_definition)

The code is executed without issue. I want to speed this by making the program read directly from the .txt file.

I have tried to read the variable as

f = open("savedWindXPython.txt", "r")
a=f.readline()
f.close

def Wind_lammda_definition(model, i):
    return m.Wind_phi[i] == a
m.Wind_phi_const = Constraint(m.N, rule = Wind_lammda_definition)

However, an error is returned AttributeError: 'str' object has no attribute 'is_relational'

I understand that this happens because python is reading this as a string and not as a pyomo variable. I have attempted to go arround this problem using exec(a) instead of just a in the definition of m.Wind_phi. However, I still obtain an error, this time it says

'NoneType' object has no attribute 'is_relational'

Is there a way to do what I want to do and define the variable by reading the .txt file isntead of having to copy it's contents by hand?

标签: pythonvariablestextreadlinepyomo

解决方案


您要实现的目标称为组(或反序列化)

如果你的变量是一个简单的数字,反序列化它就像int(my_string_var). 如果它看起来像您链接的那个(您需要在其中调用函数),那么还有更多工作要做。您使用的库还可以提供一些序列化/反序列化功能。对您来说不幸的是,pyomo 目前似乎不提供此功能

因此,现在,如果您首先可以访问谁或什么正在编写您的.txt文件,请考虑将其序列化为json(或您最熟悉的任何数据存储格式;如果您不熟悉任何格式,请尝试json)。然后你现在将如何在你的代码中反序列化它。

否则,您将不得不编写一个字符串解析器来从字符串中提取数据并将其序列化为 python 对象。如果您只是试图解析这个特定的变量,这可能是微不足道的,但如果您试图反序列化很多这些变量,这也可能最终变得相当具有挑战性。


推荐阅读