python - 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?
解决方案
您要实现的目标称为解组(或反序列化)
如果你的变量是一个简单的数字,反序列化它就像int(my_string_var)
. 如果它看起来像您链接的那个(您需要在其中调用函数),那么还有更多工作要做。您使用的库还可以提供一些序列化/反序列化功能。对您来说不幸的是,pyomo 目前似乎不提供此功能。
因此,现在,如果您首先可以访问谁或什么正在编写您的.txt
文件,请考虑将其序列化为json
(或您最熟悉的任何数据存储格式;如果您不熟悉任何格式,请尝试json
)。然后你现在将如何在你的代码中反序列化它。
否则,您将不得不编写一个字符串解析器来从字符串中提取数据并将其序列化为 python 对象。如果您只是试图解析这个特定的变量,这可能是微不足道的,但如果您试图反序列化很多这些变量,这也可能最终变得相当具有挑战性。
推荐阅读
- android - 如何使用 Robolectric 运行具有 LiveData 观察者的片段测试
- javascript - Jade Datatables 不适用于 adminlte
- javascript - 更改背景渐变 onclick
- list - 我正在尝试从列表中创建一个字典,其中第一个值是键,第二个值是值,依此类推
- c - 使用 C 中的 get http 请求和套接字获取 html 页面
- javascript - 如何解决 axios 的承诺
- python - Vue3 / Vuex 更改存储状态不会更新计算道具
- sql - 递归查询以获取所有孩子
- python - 记录错误时的 Loguru 回调函数
- typescript - 使用 webpack 在 typescript 生产构建中删除断言