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?
What you are trying to achieve is called unmarshalling (or deserialization)
If your variable is a simple number, deserializing it is as easy as int(my_string_var)
. If it looks like the one you linked (where you need function calls in it), there is more work to be done. The lib you're using can also provide some serialization/deserialization feature. Unfortunately for you it seems like pyomo doesn't provide this feature at the moment.
So, now, if you have access to who or what is writing your .txt
files in the first place, consider serializing it into json
(or whatever data-storage format you're the most comfortable with; if you're not comfortable with any, try json
). Then you will now how to deserialize it in your code.
Otherwise, you will have to write a string parser to extract the data from your string and serialize it into python objects. This could be trivial if you're only trying to parse this specific variable, but could also end up being rather challenging if you are trying to deserialize a lot of these variables.