jeudi 5 février 2015

If statement issues in Python

I am trying to use multiple if statements to check a certain condition and then to plot some data using matplotlib in Python. Firstly, I am doing os.walk on a directory to get the list of files and subsequently load them to finally plot and save the figures. Here is my code:



def velocity():
plt.xlabel('$\mathrm{Iterations\/or\/Time}$')
plt.title(r'$\mathrm{Residual\/history}$')
plt.grid(True)
plt.yscale('log')

if 'Ux_0' in lf:
print "Entered"
plt.plot(time_x, value_x, color = 'r', label = 'x-vel')
elif 'Uy_0' in lf:
print "Entered"
plt.plot(time_y, value_y, color = 'b', label = 'y-vel')
elif 'Uz_0' in lf:
print "Entered"
plt.plot(time_z, value_z, color = 'g', label = 'z-vel')

plt.legend()
plt.savefig(os.path.join(plotsDir, 'velocity'), bbox_inches='tight', dpi=100)
plt.close()

return (time_x, value_x, lf)
return (time_y, value_y, lf)
return (time_z, value_z, lf)

for path, dirs, files in os.walk(logsDir, topdown=False):
for lf in files:
if 'Ux_0' in lf:
logFile = os.path.join(path, lf)
data_x = np.loadtxt(logFile)
time_x, value_x = data_x[:,0], data_x[:,1]
(time_x, value_x, lf) = velocity()
if 'Uy_0' in lf:
logFile = os.path.join(path, lf)
data_y = np.loadtxt(logFile)
time_y, value_y = data_y[:,0], data_y[:,1]
(time_y, value_y, lf) = velocity()
if 'Uz_0' in lf:
logFile = os.path.join(path, lf)
data_z = np.loadtxt(logFile)
time_z, value_z = data_z[:,0], data_z[:,1]
(time_z, value_z, lf) = velocity()


The logDir has only three files to begin with and they are Ux_0, Uy_0 and Uz_0. Interestingly, after os.walk when I print lf, I get order of files as Ux_0, Uz_0 and Uy_0. Now, the figure that is generated by the function velocity() has only data from Ux_0 and Uz_0 and not Uy_0. However, in my function if the order of Uy_0 and Uz_0 is reversed such that I have Uz_0 immediately after Ux_0 as shown below, I get all the three plots as desired.



if 'Ux_0' in lf:
print "Entered"
plt.plot(time_x, value_x, color = 'r', label = 'x-vel')
elif 'Uz_0' in lf:
print "Entered"
plt.plot(time_z, value_z, color = 'b', label = 'z-vel')
elif 'Uy_0' in lf:
print "Entered"
plt.plot(time_y, value_y, color = 'g', label = 'y-vel')

plt.legend()
plt.savefig(os.path.join(plotsDir, 'velocity'), bbox_inches='tight', dpi=100)
plt.close()

return (time_x, value_x, lf)
return (time_y, value_y, lf)
return (time_z, value_z, lf)


I am not sure what is causing this.


Aucun commentaire:

Enregistrer un commentaire