Challenge

Project 1 - Parsing NASA thermodynamic data

Aim:

To write a code in Matlab to parse the NASA thermodynamic data file and then calculate the thermodynamic properties of various gas species.

Objective:

To develop a function that extracts the 14 coefficients and calculates the enthalpy, entropy, and specific heats for all the species in the data file.

Develop a code to calculate the molecular weight of each species and display it in the command window.

To plot the Cp, Enthalpy, and Entropy for the local temperature range (low temperature: high temperature) specific for each species.

To save the plots as images with appropriate names and dump them in separate folders for each species with a suitable name. All of these should be generated automatically.

Theory:

File Parsing:

It is the method of splitting the file or other input into a piece of data that can be easily stored or manipulated. By doing this we are going to split a string into parts and then recognize the parts to convert it into something simpler than a string.

Here in this project, we are going to split the NASA thermodynamic data which is having 53 gas species values in 213 lines. To perform the calculation for thermodynamic properties, we need some sort of co-efficient values and temperature ranges which is available in the NASA file. So, we are going to parse the values which are all needed for our calculation from that file.

Specific Heat:

Specific heat is the amount of heat energy required to raise the temperature of the body per unit of mass. Specific heat is also known as specific heat capacity or mass-specific heat. In SI units, specific heat is the amount of heat in joules required to raise 1 gram of a substance by 1 Kelvin.

Enthalpy:

When a substance changes at constant pressure, enthalpy tells how much heat and work was added or removed from the substance. Enthalpy is similar to energy but not the same. When a substance grows or shrinks, energy is used up or released.

Entropy:

The entropy of an object is a measure of the amount of energy that is unavailable to do work. Entropy is also a measure of the number of possible arrangements of atoms a system can have. In this sense, entropy is the measure of uncertainty or randomness.

Gas Constant:

The gas constant is a physical constant denoted by R and is expressed in terms of units of energy per temperature increment per mole. The gas constant value is equivalent to the Boltzmann constant but expressed as the pressure-volume product instead of energy per increment of temperature per particle.

Molecular Weight:

Molecular weight is a measure of the sum of the atomic weight values of the atoms in a molecule. Molecular weight is used in chemistry to determine stoichiometry in chemical reactions and equations.

Background:

NASA came up with polynomials that can be used to evaluate thermodynamic properties such as Cp, H, and S. They have also documented the coefficients that are required to evaluate these polynomials for 1000+ species.

The thermodynamic properties in terms of the coefficients are given as:

where,

`Cp = Specific Heat (KJ)/(Kg)`

`H = Enthalpy (KJ)`

`S = Entropy (KJ)/(K)`

`R = Universal gas constant = 8.314 (KJ)/(mol.K)`

`T = Temperature (celsius)`

The FIRST 7 coefficients are HIGH-temperature coefficients and the SECOND 7 coefficients are LOW-temperature coefficients.

NASA Thermodynamic File:

THERMO.dat file is a data file containing 14 coefficients for 53 different elements given by NASA. These coefficients are utilized to calculate the specific heat, enthalpy & entropy for a particular element. Each element has its own range of local temperatures. Below a screenshot of the THERMO.dat file is displayed.

We will use the above Specific Heat, Entropy, and Enthalpy as function code in Matlab and used to calculate the above and plot the graph accordingly.

File Parsing is how a piece of file information can be used in a computer program. Read data from external files and databases and include that data in your calculation. For example, if the combustion process is considered during this, these quantities are required to observe how the combustion is going on and how efficient it will be. It eventually allows seeking the scope of improvement in the process. Similarly in the other processes like refrigeration, air conditioning, chemical kinetics, nozzle flow, detonation process, etc, these quantities are widely involved to observe the phenomenon.

1 - Define the function

2 - Create an InputParser object

3 - Add inputs to the scheme.

4 - Set properties to adjust parsing.

5 - Parse the inputs.

6 - Use the inputs in the function.

7 - Calling function.

The program begins with the clear all, close all, and clc commands to free up the command window and the workspace. We will then read the data from the external NASA thermodynamic file using fopen(to open the file) and fgetl(to read the content in the file line by line) commands. The useful header information will be extracted from the file such as global temperature limits. Then we will proceed to extract the individual species data of all the species present in the file using fgetl command to read the file line by line and skip the line not containing any useful data. The data that is to be extracted for all the 53 species mentioned in the file is 14 coefficients(7 for higher temperature and & for lower temperature), species name, and the local temperature limits. This process will be carried out with the help of for loop. Calculation of specific heat, enthalpy, entropy, and molecular weight will be done in separate function files and will be called in the main program. Then we will create plots for specific heat v/s temperature, enthalpy v/s temperature, and entropy v/s temperature for all the 53 species and these 3 plots will be saved in separate folders for each species. After this, we will display the molecular weight of all the species in the command window. The code for the entire program will be written in MATLAB.

Coding Functions:

1. function for specific heat

% Specific heat calculation function
 
function Cp = Specificheat(a1,a2,a3,a4,a5,a8,a9,a10,a11,a12,Temp,R,global_medium_temp)          
% Comparing with global temperature
% If less than global temperature - minimum coefficients are taken
if  Temp <= global_medium_temp
Cp = R*(a8 + (a9*Temp) + (a10*(Temp).^2) + (a11*(Temp).^3) + (a12*(Temp).^4)); 
else
Cp = R*(a1 + (a2*Temp) + (a3*(Temp).^2) + (a4*(Temp).^3) + (a5*(Temp).^4));
% Else maximum coefficients are taken
end

2. function for entropy

% Entropy Calculation function

function S = Entropy_calc(a1,a2,a3,a4,a5,a7,a8,a9,a10,a11,a12,a14,Temp,R,global_medium_temp)         
% Comparing with global temperature
% If less than global temperature - minimum coefficients are taken
 
    if Temp <= global_medium_temp
        S = R.*(a8.*log(Temp) + (a9.*Temp) + (a10*((Temp).^2)/2) + (a11*((Temp).^3)/3) + (a12*((Temp).^4)/4) + a14);
    else
 
% Else - maximum coefficients are taken
        S = R.*(a1.*log(Temp) + (a2.*Temp) + (a3*((Temp).^2)/2) + (a4*((Temp).^3)/3) + (a5*((Temp).^4)/4) + a7);
end

3. function for enthalpy:

% Enthalpy Calculation function

function H = Enthalpy(a1,a2,a3,a4,a5,a6,a8,a9,a10,a11,a12,a13,Temp,R,global_medium_temp)    
% Comparing with global temperature
% If less than global temperature - minimum coefficients are taken
 
       if Temp <= global_medium_temp
        H = R*Temp.*(a8 + ((a9*Temp)/2) + ((a10*(Temp).^2)/3) + ((a11*(Temp).^3)/4) + ((a12*(Temp).^4)/5) +((a13./Temp)));
       else
% Else maximum coefficients are taken 
           
        H = R*Temp.*(a1 + ((a2*Temp)/2) + ((a3*(Temp).^2)/3) + ((a4*(Temp).^3)/4) + ((a5*(Temp).^4)/5) +((a6./Temp)));
end

4. function for molecular weight:

% Molecular Weight Calculation function

function Molecularweight = Molecular_weight(Species_SP)
         % Standard - Atomic Name
         atomic_name = ['H','C','O','N','A'];             
         % Hydrogen, Carbon, Oxygen, Nitrogen, Argon
         
         fprintf('Molecular Weight of ');
         fprintf(Species_SP);
         fprintf(' : ');
         % Standard Atomic Number
         Atomic_Weight = [1.008 12.011 15.999 14.007 39.948];     
         % Starting Range of Molecule           
         Molecularweight = 0;                                   
        
         % Adding Atomic number to obtain particular value
        for i = 1:length(Species_SP)
            for j = 1:length(atomic_name)
                if strcmpi(Species_SP(i),atomic_name(j))
                        Molecularweight = Molecularweight +Atomic_Weight(j);
                    position = j;
                end
            end
            n = str2num(Species_SP(i));
            
            if n>1
            
                Molecularweight = Molecularweight + Atomic_Weight(position)*(n-1);
            
            end
        end
            fprintf('molecular weight %s :',Species_SP);
            fprintf('%d',Molecularweight);
            disp(' ');      
end

5. main program:

Explanation of Code:

  1. The program begins with clear all, close all, and clc commands to free up the command window and the workspace.
  2. We will then read the data from the external NASA thermodynamic data file using fopen command which is used to open the file and fgetl command which is used to read the content in the file line by line.
  3. After we use the fopen command we will be assigned to the variable called f1. Thus, the fgetl(f1) is the command that acts like a line cursor, which will retrieve the next time while running this command for the second time and so on.
  4. Now, we will be skipping the first 5 lines to enter the pattern of values of the respective gas species. We will be using the for loop command to process the same for all the gas species.
  5. The name of the gas species we will be found using findstr command and for finding out the species we are going to locate the string ‘ ’ which is present in after each species' name.
  6. And then we are going to use A(1:z(1)-1) which tells us the exact location of the species name, using which the name of the gas species is stored in the variable species_name.
  7. The local temperatures for the respective gas species are found similarly using findstr command and we are going to locate the string ‘.’ using which we will find out the values of low temperature, mid-temperature, and high temperature which are assigned to the variables t1, t2, and t3 respectively. But the values we have achieved are string values so we have to change these string values to numeric values using the str2num command.
  8. Now, we are going to extract the co-efficient for the gas species in which the co-efficient locations are in the 2nd row, the next 5 in the 3rd row, and the rest in the 4th row.
  9. We are going to extract these values similarly as we did for finding out the local temperatures by using the findstr and str2num commands and store them in the variables a1 to a14. For extracting we are going to locate the string ‘E’ which is present in each co-efficient value and so it will be followed for all the coefficients values in the same line and then we can proceed to the next lines.
  10. The values from a1 to a7 represent the high-temperature coefficients and the values from a8 to a14 represent the low-temperature coefficients.
  11. Temperature range values from low temperature to high temperature is assigned using the linspace command.
  12. The for loop command is used to calculate the values of specific heat, enthalpy, and entropy, and the if-else command is also used to find out the required values if the temperature is below the mid-temperature or above the mid-temperature.
  13. In order to calculate the molecular weight of the species, we declare the species elements in the form of the cell array. Their atomic mass is declared in the form of an array. Then initially molecular weight is declared as zero.
  14. Now, for loop command is used to detect if there is more than one species in the variable species_name and the respective values of the gas species values are calculated and found.
  15. After the nested for loop, the species_name which is in the form of a string is converted as a number with strdouble command. Then the species_name which is now a number greater than 1, molecular weight is again calculated by having the atomic mass for the current species * n-1
  16. The value of the molecular weight is calculated for the respective gas species and is displayed in the command window.
  17. Now, we are going to create plots that obtain specific heat, enthalpy, and entropy values and save them in the respective species_name folder automatically.
  18. In order to create a new folder with the species_name, we are going to use the mkdir command so that a new folder is created in the main folder. Now, we have to change the current directory from the main folder to the species_name folder so the cd command is used to do the same.
  19. The plots for specific heat vs temperature, enthalpy vs temperature, and entropy vs temperature is plotted and the labeling of the axis and the naming of the title is also done along with the value of molecular weight.
  20. To save the plots in the species_name folder, saveas command is used to save the plots in the current folder. After which to change the current directory to the main folder the oldfolder = cd () command is used.
% Main program
% Reading Data file - NASA Thermodynamic
% Open a file & 'r' Open the file for reading 
f1 = fopen('THERMO.dat','r')
gt=fgetl(f1);

% Obtaing Temperatures - by Reading Header Information
global_temp=fgetl(f1);

% Spliting
t=strsplit(global_temp);

% Converting string cells to numbers using str2num,
global_low_temp=str2num(t{2});
global_medium_temp=str2num(t{3});
global_high_temp=str2num(t{4});

% Temperature range & Gas Constant
    % Temperature Range assumed
Temp=linspace(global_low_temp,global_high_temp,1000);
% Universal Gas Constant J/(mol-K)
    R = 8.314;   
    
% skipping three comment lines in the file
for i = 1:3
    gt=fgetl(f1);
end

 for i = 1:53
gt=fgetl(f1);
A=strsplit(gt,' ');
Species_SP=(A{1})


line_1=fgetl(f1)  ;        
a=strfind(line_1,'E');

% Extracting higher and lower temperature coefficients

% % Extracting FIRST 7 coefficients i.e HIGH-temperature coefficients 
a1=line_1(1:a(1)+3);
a1=str2num(a1);              %1
a2=line_1(a(1)+4:a(2)+3);
a2=str2num(a2) ;             %2
a3=line_1(a(2)+4:a(3)+3);
a3=str2num(a3)  ;            %3
a4=line_1(a(3)+4:a(4)+3);
a4=str2num(a4);              %4
a5=line_1(a(4)+4:a(5)+3);
a5=str2num(a5)  ;            %5

line_2=fgetl(f1);
b=strfind(line_1,'E');;
a6=line_2(1:b(1)+3);
a6=str2num(a6)  ;            %6
a7=line_2(a(1)+4:b(2)+3);
a7=str2num(a7);              %7

 % Extracting SECOND 7 coefficients - LOW-temperature coefficients
a8=line_2(b(2)+4:b(3)+3);         
a8=str2num(a8);              %8
a9=line_2(b(3)+4:b(4)+3);
a9=str2num(a9) ;             %9
a10=line_2(b(4)+4:b(5)+3);
a10=str2num(a10) ;           %10


line_3=fgetl(f1);
c=strfind(line_1,'E');

a11=line_3(1:c(1)+3);
a11=str2num(a11);               %11
a12=line_3(c(1)+4:c(2)+3);
a12=str2num(a12);               %12
a13=line_3(c(2)+4:c(3)+3);
a13=str2num(a13);               %13
a14=line_3(c(3)+4:c(4)+3);
a14=str2num(a14);               %14

% Specific heat calculation
    Cp = Specificheat(a1,a2,a3,a4,a5,a8,a9,a10,a11,a12,Temp,R,global_medium_temp);
 
    % Enthalpy calculation
    H = Enthalpy(a1,a2,a3,a4,a5,a6,a8,a9,a10,a11,a12,a13,Temp,R,global_medium_temp);
 
    % Entropy calculation
    S = Entropy_calc(a1,a2,a3,a4,a5,a7,a8,a9,a10,a11,a12,a14,Temp,R,global_medium_temp);

    % Calculating the molecular weight of species
    Molecularweight(i) = Molecular_weight(Species_SP);
    
    % Read & Write Molecular list
     Molecular_list = fopen('Molecular weight.txt','a+');
         fprintf( Molecular_list,'Molecular weight of %s is %d \n',Species_SP,Molecularweight);
         fclose(Molecular_list);

     % plotting(CP,H,S,Temp,Species_SP)
        % Saving as a folder
 
           cur_dir=pwd;
           mkdir(Species_SP);
           cd(Species_SP);
 
        % Plot 1, Specific heat (CP) vs Temperature Range (Temp)
 
        figure(1)
        plot(Temp,Cp,'linewidth',2,'color','r');
        xlabel('Temperature  [K]');
        ylabel('Specific Heat [kJ]');
        title(sprintf('Varying Specific Heat with Temperature Range of %s',Species_SP));
        grid on
        saveas(figure(1),'Specific Heat.jpg');
 
        % Plot 2, Enthalpy (H) vs Temperature Range (Temp)
 
        figure(2)
        plot(Temp,H,'linewidth',2,'color','g');
        xlabel('Temperature [K]');
        ylabel('Enthalpy in [kJ/(mol)]');
        title(sprintf('Varying Enthalpy with Temperature Range of %s',Species_SP));
        grid on
        saveas(figure(2),'Ethalpy.jpg');
 
        % Plot 3, Entropy (S) vs Temperature Range (Temp)
 
        figure(3)
        plot(Temp,S,'linewidth',2,'color','b');
        xlabel('Temperature [K]');
        ylabel('Entropy in [kJ/(mol-K)]');
        title(sprintf('Varying Entropy with Temperature Range of %s',Species_SP));
        grid on
        saveas(figure(3),'Entropy.jpg');
 
        cd(cur_dir);            
 
        % Molecular weight
        
        M = Molecular_weight(Species_SP)
        f2 = fopen('molecular mass','w');
        fprintf('%s n %s n %f n','species','Molecular mass',M)
        fclose(f2)
end

Syntax Used during Coding:

Fopen :

Open a file or obtain information about open files

‘r’ :

Open the file for reading

fgetl

Read line from file

strsplit

Split string or character vector at the specified delimiter

str2num

Convert character array or string to numeric array

strfind

Find one string within another

linspace

Generate linearly spaced vectors

fprintf

Write formatted data to file

pwd

Identify current directory

mkdir

Make new directory

cd

Change working directory

Output:

Molecular Weight of all species :

Results:

Specific Heat, Entropy, and Enthalpy Plots for `O_2`, `N_2`, and `Co_2` species:

1. Plots for `O_2`

a. Variation of Specific heat with the temperature of `O_2`

b. Variation of Entropy with the temperature of `O_2`

c. Variation of Enthalpy with the temperature of `O_2`

2. Plots for `N_2`

a. Variation of Specific heat with the temperature of `N_2`

b. Variation of Entropy with the temperature of `N_2`

c. Variation of Enthalpy with the temperature of `N_2`

3. Plots for `Co_2`

a. Variation of Specific heat with the temperature of `Co_2`

b. Variation of Entropy with the temperature of `Co_2`

c. Variation of Enthalpy with the temperature of `Co_2`

Screenshot of the window where all the folders are saved:

Conclusion:

Therefore, we have successfully parsed the given NASA thermodynamic data file and plotted the graphs of specific heat, enthalpy, and entropy for the respective inputted species name.

References:

  1. https://en.wikipedia.org/wiki/Parsing
  2. https://in.mathworks.com/help/matlab/ref/mkdir.html
  3. https://in.mathworks.com/help/matlab/ref/cd.html
  4. https://in.mathworks.com/help/matlab/ref/saveas.html
Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.