I'm making a program that reads a .txt file that updates itself when running another program in fortran and creates a real-time animation of the temperature map of a plate, however it's giving an error because fortran keeps updating the file in real time, because in some moments python opens the file before the fortran loop ends and takes an incomplete array which will therefore crash the program. Any idea how to make the two run together?
Follow the code in question below
import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation import time n=100 x = np.linspace(0, 99, num=100) y = np.linspace(0, 99, num=100) X,Y = np.meshgrid(x, y) fig = plt.figure() ax1 = fig.add_subplot(1,1,1) def animate(i): Temp_matrix=np.empty(shape=[0,n]) file = open('Temperature.txt', 'r') for i in range (1,n+1): line = file.readline().strip().split() line=np.float32(line) Temp_matrix=np.append(Temp_matrix,[line],axis=0) fig.clear() CS = plt.contourf(X,Y,Temp_matrix,9) colorb=plt.colorbar(CS) plt.title('Placa 1x1') ani = animation.FuncAnimation(fig, animate, interval=1000) plt.show()
Calculation time is usually longer than recording time, so considering a small file (100×100), I assume you are calculating with the file open:
- Open the file for reading
- compute value
- write value
- close file
In this process, Python probably won't be able to open the file… Or will read the file halfway through, before the calculation is complete.
There are two ways to avoid this:
I suggest reviewing Fortran's own code.
You should store the values in memory and Flush only when complete.
Hope this helps!