Пример #1
0
    def plot(self, data):
        """
        Plots data from the simulations from this cantera job.
        Takes data in the format of a list of tuples containing (time, [list of temperature, pressure, and species data]) 
        
        3 plots will be created for each condition:
        - T vs. time
        - P vs. time
        - Maximum 10 species mole fractions vs time
        """
        for i, conditionData in enumerate(data):
            time, dataList = conditionData
            # In RMG, any species with an index of -1 is an inert and should not be plotted
            inertList = [
                species for species in self.speciesList if species.index == -1
            ]

            TData = dataList[0]
            PData = dataList[1]
            speciesData = [
                data for data in dataList if data.species not in inertList
            ]

            # plot
            GenericPlot(xVar=time,
                        yVar=TData).plot('{0}_temperature.png'.format(i + 1))
            GenericPlot(xVar=time,
                        yVar=PData).plot('{0}_pressure.png'.format(i + 1))
            SimulationPlot(xVar=time, yVar=speciesData,
                           ylabel='Mole Fraction').plot(
                               os.path.join(
                                   self.outputDirectory,
                                   '{0}_mole_fractions.png'.format(i + 1)))
Пример #2
0
 def plot(self, data, topSpecies=10, topSensitiveReactions=10):
     """
     Plots data from the simulations from this cantera job.
     Takes data in the format of a list of tuples containing (time, [list of temperature, pressure, and species data]) 
     
     3 plots will be created for each condition:
     - T vs. time
     - P vs. time
     - Maximum species mole fractions (the number of species plotted is based on the `topSpecies` argument)
     
     Reaction sensitivity plots will also be plotted automatically if there were sensitivities evaluated.
     The number of reactions to be plotted is defined by the `topSensitiveReactions` argument.
     
     """
     numCtReactions = len(self.model.reactions())
     for i, conditionData in enumerate(data):
         time, dataList, reactionSensitivityData = conditionData
         # In RMG, any species with an index of -1 is an inert and should not be plotted
         inertList = [species for species in self.speciesList if species.index == -1 ]
         
         TData = dataList[0]
         PData = dataList[1]
         speciesData = [data for data in dataList if data.species not in inertList]
         
         # plot
         GenericPlot(xVar=time, yVar=TData).plot(os.path.join(self.outputDirectory,'{0}_temperature.png'.format(i+1)))
         GenericPlot(xVar=time, yVar=PData).plot(os.path.join(self.outputDirectory,'{0}_pressure.png'.format(i+1)))
         SimulationPlot(xVar=time, yVar=speciesData, numSpecies=topSpecies, ylabel='Mole Fraction').plot(os.path.join(self.outputDirectory,'{0}_mole_fractions.png'.format(i+1)))
         
         for j, species in enumerate(self.sensitiveSpecies):
             ReactionSensitivityPlot(xVar=time, yVar=reactionSensitivityData[j*numCtReactions:(j+1)*numCtReactions], numReactions=topSensitiveReactions).barplot(os.path.join(self.outputDirectory,'{0}_{1}_sensitivity.png'.format(i+1,species.toChemkin())))
Пример #3
0
    def update(self, reaction_system):
        """
        Saves a png with filename referring to:
            - reaction system
            - number of core species
        """

        csv_file = os.path.join(
            self.output_directory, 'solver',
            'simulation_{0}_{1:d}.csv'.format(self.reaction_sys_index + 1,
                                              len(self.core_species)))

        png_file = os.path.join(
            self.output_directory, 'solver',
            'simulation_{0}_{1:d}.png'.format(self.reaction_sys_index + 1,
                                              len(self.core_species)))

        SimulationPlot(csv_file=csv_file, num_species=10,
                       ylabel='Moles').plot(png_file)
Пример #4
0
def plot_profiles(data, topSpecies=10):
    """
    data is tuple:
    (time data, [temperature data, density data, species1 data, species2 data, ...])
    """

    time, data_list = data
    temperature = data_list[0]
    density = data_list[1]
    species_data = [d for d in data_list[2:]
                    if d.index != -1]  # remove unwanted species

    # plot
    GenericPlot(xVar=time, yVar=temperature).plot('temperature.png')
    GenericPlot(xVar=time, yVar=density).plot('density.png')
    SimulationPlot(xVar=time,
                   yVar=species_data,
                   numSpecies=topSpecies,
                   ylabel='Mole Fraction').plot('mole_fractions.png')
Пример #5
0
    def compare(self, tol, plot=False):
        """
        Compare the old and new model
        'tol':  average error acceptable between old and new model for variables
        `plot`: if set to True, it will comparison plots of the two models comparing their species.

        Returns a list of variables failed in a list of tuples in the format:
        
        (CanteraCondition, variable label, variableOld, variableNew)

        """
        # Ignore Inerts
        inertList = ['[Ar]','[He]','[N#N]','[Ne]']

        oldConditionData, newConditionData = self.runSimulations()

        conditionsBroken=[]
        variablesFailed=[]
        
        print ''
        print '{0} Comparison'.format(self)
        print '================'
        # Check the species profile observables
        if 'species' in self.observables:
            oldSpeciesDict = getRMGSpeciesFromUserSpecies(self.observables['species'], self.oldSim.speciesList)
            newSpeciesDict = getRMGSpeciesFromUserSpecies(self.observables['species'], self.newSim.speciesList)
        
        # Check state variable observables 
        implementedVariables = ['temperature','pressure']
        if 'variable' in self.observables:
            for item in self.observables['variable']:
                if item.lower() not in implementedVariables:
                    print 'Observable variable {0} not yet implemented'.format(item)
                    
        failHeader='\nThe following observables did not match:\n'
        failHeaderPrinted=False
        for i in range(len(oldConditionData)):
            timeOld, dataListOld = oldConditionData[i]
            timeNew, dataListNew = newConditionData[i]

            # Compare species observables
            if 'species' in self.observables:
                smilesList=[] #This is to make sure we don't have species with duplicate smiles
                multiplicityList=['','(S)','(D)','(T)','(Q)'] #list ot add multiplcity
                for species in self.observables['species']:

                    smiles=species.molecule[0].toSMILES() #For purpose of naming the plot only
                    if smiles in smilesList: smiles=smiles+multiplicityList[species.molecule[0].multiplicity]
                    smilesList.append(smiles)
                    
                    fail = False
                    oldRmgSpecies = oldSpeciesDict[species]
                    newRmgSpecies = newSpeciesDict[species]
                    
                    if oldRmgSpecies:
                        variableOld = next((data for data in dataListOld if data.species == oldRmgSpecies), None)
                    else:
                        print 'No RMG species found for observable species {0} in old model.'.format(smiles)
                        fail = True
                    if newRmgSpecies:
                        variableNew = next((data for data in dataListNew if data.species == newRmgSpecies), None)
                    else:
                        print 'No RMG species found for observable species {0} in new model.'.format(smiles)
                        fail = True
                    
                    if fail is False:
                        if not curvesSimilar(timeOld.data, variableOld.data, timeNew.data, variableNew.data, tol):
                            fail = True
                            
                        # Try plotting only when species are found in both models
                        if plot:
                            oldSpeciesPlot = SimulationPlot(xVar=timeOld, yVar=variableOld)
                            newSpeciesPlot = SimulationPlot(xVar=timeNew, yVar=variableNew)
                            oldSpeciesPlot.comparePlot(newSpeciesPlot,
                                                       title='Observable Species {0} Comparison'.format(smiles),
                                                       ylabel='Mole Fraction',
                                                       filename='condition_{0}_species_{1}.png'.format(i+1,smiles))
                    
                    # Append to failed variables or conditions if this test failed
                    if fail:
                        if not failHeaderPrinted:
                            print failHeader
                            failHeaderPrinted=True
                        if i not in conditionsBroken: conditionsBroken.append(i)
                        print "Observable species {0} varied by more than {1:.3f} on average between old model {2} and \
new model {3} in condition {4:d}.".format(smiles,
                                          tol,
                                           variableOld.label, 
                                           variableNew.label,
                                           i+1)
                        variablesFailed.append((self.conditions[i], smiles, variableOld, variableNew))
                    
            
            # Compare state variable observables
            if 'variable' in self.observables:
                for varName in self.observables['variable']:
                    variableOld = next((data for data in dataListOld if data.label == varName), None)
                    variableNew = next((data for data in dataListNew if data.label == varName), None)
                    if not curvesSimilar(timeOld.data, variableOld.data, timeNew.data, variableNew.data, 0.05):
                        if i not in conditionsBroken: conditionsBroken.append(i)
                        if not failHeaderPrinted:
                            failHeaderPrinted=True
                            print failHeader

                        print "Observable variable {0} varied by more than {1:.3f} on average between old model and \
new model in condition {2:d}.".format(variableOld.label, i+1)
                        variablesFailed.append((self.conditions[i], tol, varName, variableOld, variableNew))
                    
                    if plot:
                        oldVarPlot = GenericPlot(xVar=timeOld, yVar=variableOld)
                        newVarPlot = GenericPlot(xVar=timeNew, yVar=variableNew)
                        oldVarPlot.comparePlot(newSpeciesPlot,
                                                   title='Observable Variable {0} Comparison'.format(varName),
                                                   filename='condition_{0}_variable_{1}.png'.format(i+1, varName))
                        
            # Compare ignition delay observables
            if 'ignitionDelay' in self.observables:
                print 'Ignition delay observable comparison not implemented yet.'
                
                
        if failHeaderPrinted:
            print ''
            print 'The following reaction conditions were had some discrepancies:'
            print ''
            for index in conditionsBroken:
                print "Condition {0:d}:".format(index+1)
                print str(self.conditions[index])
                print ''

            return variablesFailed
        else:
            print ''
            print 'All Observables varied by less than {0:.3f} on average between old model and \
new model in all conditions!'.format(tol)
            print ''
Пример #6
0
    def compare(self, tol, plot=False):
        """
        Compare the old and new model
        'tol':  average error acceptable between old and new model for variables
        `plot`: if set to True, it will comparison plots of the two models comparing their species.

        Returns a list of variables failed in a list of tuples in the format:
        
        (CanteraCondition, variable label, variable_old, variable_new)

        """
        # Ignore Inerts
        inert_list = ['[Ar]', '[He]', '[N#N]', '[Ne]']

        old_condition_data, new_condition_data = self.run_simulations()

        conditions_broken = []
        variables_failed = []

        print('')
        print('{0} Comparison'.format(self))
        print('================')
        # Check the species profile observables
        if 'species' in self.observables:
            old_species_dict = get_rmg_species_from_user_species(self.observables['species'], self.old_sim.species_list)
            new_species_dict = get_rmg_species_from_user_species(self.observables['species'], self.new_sim.species_list)

        # Check state variable observables 
        implemented_variables = ['temperature', 'pressure']
        if 'variable' in self.observables:
            for item in self.observables['variable']:
                if item.lower() not in implemented_variables:
                    print('Observable variable {0} not yet implemented'.format(item))

        fail_header = '\nThe following observables did not match:\n'
        fail_header_printed = False
        for i in range(len(old_condition_data)):
            time_old, data_list_old, reaction_sensitivity_data_old, thermodynamic_sensitivity_data_old = old_condition_data[i]
            time_new, data_list_new, reaction_sensitivity_data_new, thermodynamic_sensitivity_data_new = new_condition_data[i]

            # Compare species observables
            if 'species' in self.observables:
                smiles_list = []  # This is to make sure we don't have species with duplicate smiles
                multiplicity_list = ['', '(S)', '(D)', '(T)', '(Q)']  # list ot add multiplcity
                for species in self.observables['species']:

                    smiles = species.molecule[0].to_smiles()  # For purpose of naming the plot only
                    if smiles in smiles_list: smiles = smiles + multiplicity_list[species.molecule[0].multiplicity]
                    smiles_list.append(smiles)

                    fail = False
                    old_rmg_species = old_species_dict[species]
                    new_rmg_species = new_species_dict[species]

                    if old_rmg_species:
                        variable_old = next((data for data in data_list_old if data.species == old_rmg_species), None)
                    else:
                        print('No RMG species found for observable species {0} in old model.'.format(smiles))
                        fail = True
                    if new_rmg_species:
                        variable_new = next((data for data in data_list_new if data.species == new_rmg_species), None)
                    else:
                        print('No RMG species found for observable species {0} in new model.'.format(smiles))
                        fail = True

                    if fail is False:
                        if not curves_similar(time_old.data, variable_old.data, time_new.data, variable_new.data, tol):
                            fail = True

                        # Try plotting only when species are found in both models
                        if plot:
                            old_species_plot = SimulationPlot(x_var=time_old, y_var=variable_old)
                            new_species_plot = SimulationPlot(x_var=time_new, y_var=variable_new)
                            old_species_plot.compare_plot(new_species_plot,
                                                          title='Observable Species {0} Comparison'.format(smiles),
                                                          ylabel='Mole Fraction',
                                                          filename='condition_{0}_species_{1}.png'.format(i + 1, smiles))

                    # Append to failed variables or conditions if this test failed
                    if fail:
                        if not fail_header_printed:
                            print(fail_header)
                            fail_header_printed = True
                        if i not in conditions_broken:
                            conditions_broken.append(i)
                        print("Observable species {0} varied by more than {1:.3f} on average between old model {2} and "
                              "new model {3} in condition {4:d}.".format(smiles, tol, variable_old.label,
                                                                         variable_new.label, i + 1))
                        variables_failed.append((self.conditions[i], smiles, variable_old, variable_new))

            # Compare state variable observables
            if 'variable' in self.observables:
                for varName in self.observables['variable']:
                    variable_old = next((data for data in data_list_old if data.label == varName), None)
                    variable_new = next((data for data in data_list_new if data.label == varName), None)
                    if not curves_similar(time_old.data, variable_old.data, time_new.data, variable_new.data, 0.05):
                        if i not in conditions_broken:
                            conditions_broken.append(i)
                        if not fail_header_printed:
                            fail_header_printed = True
                            print(fail_header)

                        print("Observable variable {0} varied by more than {1:.3f} on average between old model and "
                              "new model in condition {2:d}.".format(variable_old.label, tol, i + 1))
                        variables_failed.append((self.conditions[i], varName, variable_old, variable_new))

                    if plot:
                        old_var_plot = GenericPlot(x_var=time_old, y_var=variable_old)
                        new_var_plot = GenericPlot(x_var=time_new, y_var=variable_new)
                        old_var_plot.compare_plot(new_var_plot,
                                                  title='Observable Variable {0} Comparison'.format(varName),
                                                  filename='condition_{0}_variable_{1}.png'.format(i + 1, varName))

            # Compare ignition delay observables
            if 'ignitionDelay' in self.observables:
                print('Ignition delay observable comparison not implemented yet.')

        if fail_header_printed:
            print('')
            print('The following reaction conditions were had some discrepancies:')
            print('')
            for index in conditions_broken:
                print("Condition {0:d}:".format(index + 1))
                print(str(self.conditions[index]))
                print('')

            return variables_failed
        else:
            print('')
            print('All Observables varied by less than {0:.3f} on average between old model and '
                  'new model in all conditions!'.format(tol))
            print('')
Пример #7
0
    def plot(self,
             data,
             top_species=10,
             top_sensitive_reactions=10,
             top_sensitive_species=10):
        """
        Plots data from the simulations from this cantera job.
        Takes data in the format of a list of tuples containing (time, [list of temperature, pressure, and species data]) 
        
        3 plots will be created for each condition:
        - T vs. time
        - P vs. time
        - Maximum species mole fractions (the number of species plotted is based on the `top_species` argument)
        
        Reaction sensitivity plots will also be plotted automatically if there were sensitivities evaluated.
        The number of reactions to be plotted is defined by the `top_sensitive_reactions` argument.
        
        """
        num_ct_reactions = len(self.model.reactions())
        num_ct_species = len(self.model.species())
        for i, condition_data in enumerate(data):
            time, data_list, reaction_sensitivity_data, thermodynamic_sensitivity_data = condition_data
            # In RMG, any species with an index of -1 is an inert and should not be plotted
            inert_list = [
                species for species in self.species_list if species.index == -1
            ]

            T_data = data_list[0]
            P_data = data_list[1]
            species_data = [
                data for data in data_list if data.species not in inert_list
            ]

            # plot
            GenericPlot(x_var=time, y_var=T_data).plot(
                os.path.join(self.output_directory,
                             '{0}_temperature.png'.format(i + 1)))
            GenericPlot(x_var=time, y_var=P_data).plot(
                os.path.join(self.output_directory,
                             '{0}_pressure.png'.format(i + 1)))
            SimulationPlot(x_var=time,
                           y_var=species_data,
                           num_species=top_species,
                           ylabel='Mole Fraction').plot(
                               os.path.join(
                                   self.output_directory,
                                   '{0}_mole_fractions.png'.format(i + 1)))

            for j, species in enumerate(self.sensitive_species):
                ReactionSensitivityPlot(
                    x_var=time,
                    y_var=reaction_sensitivity_data[j *
                                                    num_ct_reactions:(j + 1) *
                                                    num_ct_reactions],
                    num_reactions=top_sensitive_reactions).barplot(
                        os.path.join(
                            self.output_directory,
                            '{0}_{1}_reaction_sensitivity.png'.format(
                                i + 1, species.to_chemkin())))
                if self.thermo_SA:
                    ThermoSensitivityPlot(
                        x_var=time,
                        y_var=thermodynamic_sensitivity_data[j *
                                                             num_ct_species:
                                                             (j + 1) *
                                                             num_ct_species] *
                        4184000,
                        xlabel='dln(c)/d(H_i) [(kcal/mol)^-1]',
                        num_species=top_sensitive_species).barplot(
                            os.path.join(
                                self.output_directory,
                                '{0}_{1}_thermo_sensitivity.png'.format(
                                    i + 1, species.to_chemkin())))
Пример #8
0
    def compare(self, plot=False):
        """
        Compare the old and new model
        `plot`: if set to True, it will comparison plots of the two models comparing their species.

        Returns a list of variables failed in a list of tuples in the format:
        
        (CanteraCondition, variable label, variableOld, variableNew)

        """
        # Ignore Inerts
        inertList = ['[Ar]','[He]','[N#N]','[Ne]']

        oldConditionData, newConditionData = self.runSimulations()

        conditionsBroken=[]
        variablesFailed=[]
        
        print ''
        print '{0} Comparison'.format(self)
        print '================'
        # Check the species profile observables
        if 'species' in self.observables:
            oldSpeciesDict = getRMGSpeciesFromSMILES(self.observables['species'], self.oldSim.speciesList)
            newSpeciesDict = getRMGSpeciesFromSMILES(self.observables['species'], self.newSim.speciesList)
        
        # Check state variable observables 
        implementedVariables = ['temperature','pressure']
        if 'variable' in self.observables:
            for item in self.observables['variable']:
                if item.lower() not in implementedVariables:
                    print 'Observable variable {0} not yet implemented'.format(item)
                    
        print ''
        print 'The following observables did not match:'
        print ''
        for i in range(len(oldConditionData)):
            timeOld, dataListOld = oldConditionData[i]
            timeNew, dataListNew = newConditionData[i]

            # Compare species observables
            if 'species' in self.observables:
                for smiles in self.observables['species']:
                    
                    fail = False
                    oldRmgSpecies = oldSpeciesDict[smiles]
                    newRmgSpecies = newSpeciesDict[smiles]
                    
                    if oldRmgSpecies:
                        variableOld = next((data for data in dataListOld if data.species == oldRmgSpecies), None)
                    else:
                        print 'No RMG species found for observable species {0} in old model.'.format(smiles)
                        fail = True
                    if newRmgSpecies:
                        variableNew = next((data for data in dataListNew if data.species == newRmgSpecies), None)
                    else:
                        print 'No RMG species found for observable species {0} in new model.'.format(smiles)
                        fail = True
                    
                    if fail is False:
                        if not curvesSimilar(timeOld.data, variableOld.data, timeNew.data, variableNew.data, 0.05):
                            fail = True
                            
                        # Try plotting only when species are found in both models
                        if plot:
                            oldSpeciesPlot = SimulationPlot(xVar=timeOld, yVar=variableOld)
                            newSpeciesPlot = SimulationPlot(xVar=timeNew, yVar=variableNew)
                            oldSpeciesPlot.comparePlot(newSpeciesPlot,
                                                       title='Observable Species {0} Comparison'.format(smiles),
                                                       ylabel='Mole Fraction',
                                                       filename='condition_{0}_species_{1}.png'.format(i+1,smiles))
                    
                    # Append to failed variables or conditions if this test failed
                    if fail:
                        if i not in conditionsBroken: conditionsBroken.append(i)
                        print "Observable species {0} does not match between old model {1} and \
new model {2} in condition {3:d}.".format(smiles,
                                           variableOld.label, 
                                           variableNew.label,
                                           i+1)
                        variablesFailed.append((self.conditions[i], smiles, variableOld, variableNew))
                    
            
            # Compare state variable observables
            if 'variable' in self.observables:
                for varName in self.observables['variable']:
                    variableOld = next((data for data in dataListOld if data.label == varName), None)
                    variableNew = next((data for data in dataListNew if data.label == varName), None)
                    if not curvesSimilar(timeOld.data, variableOld.data, timeNew.data, variableNew.data, 0.05):
                        if i not in conditionsBroken: conditionsBroken.append(i)
                        print "Observable variable {0} does not match between old model and \
new model in condition {1:d}.".format(variableOld.label, i+1)
                        variablesFailed.append((self.conditions[i], varName, variableOld, variableNew))
                    
                    if plot:
                        oldVarPlot = GenericPlot(xVar=timeOld, yVar=variableOld)
                        newVarPlot = GenericPlot(xVar=timeNew, yVar=variableNew)
                        oldVarPlot.comparePlot(newSpeciesPlot,
                                                   title='Observable Variable {0} Comparison'.format(varName),
                                                   filename='condition_{0}_variable_{1}.png'.format(i+1, varName))
                        
            # Compare ignition delay observables
            if 'ignitionDelay' in self.observables:
                print 'Ignition delay observable comparison not implemented yet.'
                
                
        
        print ''
        print 'The following reaction conditions were broken:'
        print ''
        for index in conditionsBroken:
            print "Condition {0:d}:".format(index+1)
            print str(self.conditions[index])
            print ''

        return variablesFailed