Data Analysis using Python
1. AIM:
To write a script in python which:
- Does data visualizing
- Does compatiblity check
- Does Basic performance Calculations
2. GOVERNING EQUATIONS:
Power output of engine, P = `1/2*area*(r p m)/60` which is in watts. (area in `mm^2`). The area calculated is nothing but the work done. Thus the units of area is also Joules.
Specific Fuel Consumption = `(comsu mption)/(area) * 3600 * 1000` `g/(KW*h)`
3. OBJECTIVES OF THE PROJECT:
Data visualizer:
Script should take column numbers as the input and plot the respective columns as separate images
Each file should be saved by the name of the column
The plot labels should be extracted from the file. If, I request for a plot between column 1 (crank angle) and column 8(volume), then the label information should automatically be extracted and must appear as labels in the plots. No manual data entry.
Compatability check:
Exit gracefully, if a non-compatible file is provided as an input.
Basic performance calculation:
Calculate the area under the P-V diagram. P is in column 2 and V is in column 8.
Calculate the power output of this engine. Assume that RPM is 1500
This engine consumed 20 micro grams of fuel (per 1 stroke cycle). Calculate its specific fuel consumption.
4. PROCEDURAL FLOW OF THE PROJECT:
1. Import required libraries.
2. Define basic functions that we require to plot graphs and plots.
3. Load the engine data file and seperate the column values and assign it to variables.
4. After assigning, To link the column and parameter data, keep the index of both arrays same, i.e corresponding.
5. Take input from user about his choice of plot and call the plotting function to plot the required graph
6. Calculate area under the P-V plot by using numpy trapz and display it.
7. Similarly, using area value which is work done basically, calculate power output.
8. Calculate specific fuel consumption from governing equation.
9. It is also given in objective that you need to plot single parameter graphs. Finally, call the function likewise to plot the same.
5. PYTHON CODE:
import matplotlib.pyplot as plt
import numpy as np
def plot(crank, pressure,parameter,parameter1): #Function for plotting graphs of 2 parameters
plt.figure() #Open a new figure
plt.plot(crank, pressure, linewidth = 2) #Plotting graph between 2 input parameters
plt.xlabel(parameter) #X and Y labelling
plt.ylabel(parameter1)
plt.grid(True)
filename = parameter+parameter1+'.png' #Saving the plot filenameing
plt.savefig(filename)
plt.show()
def single(crank,parameter):
plt.figure()
plt.plot(crank,linewidth = 2)
plt.ylabel(parameter)
plt.xlabel('Iterations')
plt.grid(True)
filename = parameter
plt.savefig(filename)
plt.show()
#Basic initiaization
line_count = 1
consumption = 20*pow(10,-6)
rpm = 1500
#File parsing starts here
for line1 in open('engine_data.out'): #For every line after opening the engine data file
if (line_count == 1): #if the line number is 1
if 'CONVERGE' not in line1: #if CONVERGE words are not present in the first line
print('Invalid CONVERGE file chosen. Please try again!')
exit() #Stop code execution
if (line_count == 2):
a=line1.split() #making array by splitting line 2 for column numbers
if (line_count == 3):
b=line1.split() #making array by spliting line 3 for parameter names
line_count = line_count + 1
list = ['#','column'] #making a known list so we can skip first few words we dont want to add in array
finnum = []
finparam = []
parameter = []
for number in a:
if number in list: #If matching string is found in list array then we are not appending it to the array of column numbers
continue
finnum.append(int(number))
for name in b: #If matching string is found in list array then we are not appending it to the array of parameter name
if name in list:
continue
finparam.append(name)
for name1 in b: #Another for loop which will be only used for plot labels
if name1 in list:
continue
parameter.append(name1)
parameter1 = parameter
linen = 1
for line in open('engine_data.out'): #For every line in the engine data file
if '#' not in line: #for skipping first few lines having # in them
for i in finnum: #for i in column number array
if linen == 6: #only once, empty arrays having name as that of parameter will be created
finparam[i-1] = [] #Column number start from 1, thus for index 0 we need to do i-1
finparam[i-1].append(float(line.split()[i-1]))
linen = linen + 1
total = [] #Total array for combining all the parameter arrays
for i in finnum:
total.append(finparam[i-1])
#taking inputs.
print('Between what parameters you need the graph? \n')
print('crank = 0 \npressure = 1 \nmax_pressure = 2 \nmin_pressure = 3 \ntemperature = 4 \nmax_temp = 5 \nmin_temp = 6 \nvolume = 7 \nmass = 8 \ndensity = 9 \nnteg_hr = 10 \nhr_rate = 11 \ncp = 12 \ncv = 13 \ngamma = 14 \nin_visc = 15 \nyn_visc = 16 \n')
a = input('Enter the number infront of X axis parameter: ')
b = int(a)
c = int(input('Enter the number infront of Y axis parameter: '))
d = int(c)
plotting = plot(total[b],total[d],parameter[b],parameter1[d]) #Calling plot function to plot user-defined parameters
areaa = np.trapz(np.array(total[d]),1000000*np.array(total[b])) #Calculating area under curve using trapz method
print('\n',areaa,'mm^2 is the area under the curve')
power = 0.5*int(areaa)*(rpm/60) #Power calculation
sfc = (consumption/areaa)*3600*1000 #Specific fuel consumption calculation
print(sfc,'is specific fuel consumption g/(KW*h)')
print(power,'watts is the power output of the engine ')
e = input('\n Select a single parameter of which you need the graph? : ')
f = int(e)
singleplot = single(total[f],parameter[f]) #Calling single plot function to plot single parameter against iteration count
Code explanation:
1. We have imported some basic modules needed to run the program.
2. We have created a function named plot which is used for plotting the graph of user defined parameters like volume, pressure etc.
3. The function contains plt functions like plot, label etc and also, the plot is saved by the name of X and Y axis parameter names.
4. Similarly, the next function single() also plots graphs but they are only meant for single parameter. i.e. parameter (Y axis) v/s iteration (X axis). This plot is also saved automatically by the name of its Y axis parameter.
5. Next, we have some basic initialization. Line_count counts how many lines have been scanned uptil now. Also, rpm and fuel consumption values are taken.
6. Now, in order to validate the file, or check if correct file is supplied, we have given if condition.
i. If the word CONVERGE and the symbol # are not present in the first line, the program will stop running. (using exit() command).
ii. Otherwise, the program will proceed. We are splitting line 2 and line 3 for column numbers and parameter names and creating a string array simultaneously.
7. We have created a small list containing '#' and 'column' as string. The purpose is that in previous step, we have created string array and in order to make index same of both arrays, we need to create a new array but exclude # and 'column' string. Thus the use of next for loop.
8. Now the main step is to assign the parameter values to respective parameter arrays. For every line in the engine data file, we first skip lines containing #.
9. Then we run the for loop for all the values in finnum i.e column numbers. Now, as we want to store all values in array, we need to create an array. Creation of array is only 1 time process thus we are running the array creating line only once, i.e on line no. 6.
10. After creating array for all parameters, the line split command splits a single line into number of parts having a space ' ' and it gets appended to the column number currently running in the for loop. Thus after for loop is over, we have assigned all values of parameters into respective parameter arrays.
11. We combine all the individual arrays into a single array called total[] by appending in for loop.
12. Now we ask user to give his input on column values, i.e. What quantities to plot and we use those input numbers as the index in array of total to give output values to the function plot() so that we get the desired plot.
13. Next, we are using trapezoidal rule to calculate the area under the curve which can be called via numpy. we give input parameters as numpy array of the 2 quantities that are plotted.
14. Now, using governing equations, power and specific fuel consumption is calculated.
15. In objective it is also required to plot single parameter plot. That is also done by calling the function defined in initial process.
6. OBSERVATIONS:
Output and Graphs:
File validation:
7. CONCLUSION:
Thus, data has been analyzed and objectives are achieved using the above script.