def execute(inputModelFiles, **kwargs): try: wd = kwargs['wd'] except KeyError: wd = os.getcwd() transport = kwargs['transport'] outputChemkinFile = os.path.join(wd, 'chem.inp') outputSpeciesDictionary = os.path.join(wd, 'species_dictionary.txt') outputTransportFile = os.path.join(wd, 'tran.dat') if transport else None models = get_models_to_merge(inputModelFiles) finalModel = combine_models(models) # Save the merged model to disk saveChemkinFile(outputChemkinFile, finalModel.species, finalModel.reactions) saveSpeciesDictionary(outputSpeciesDictionary, finalModel.species) if transport: saveTransportFile(outputTransportFile, finalModel.species) print 'Merged Chemkin file saved to {0}'.format(outputChemkinFile) print 'Merged species dictionary saved to {0}'.format(outputSpeciesDictionary) if transport: print 'Merged transport file saved to {0}'.format(outputTransportFile)
def runIgnitionReactionSensitivity(runChemkinJob, inputFile, dictionaryFile): """ Supply a runChemkinJob python function which returns the ignition delay with a chemkin file input. This will run finite difference reaction sensitivities and save them to a csv file. """ from rmgpy.chemkin import loadChemkinFile, saveChemkinFile speciesList, reactionList = loadChemkinFile(inputFile, dictionaryPath=dictionaryFile, readComments=False) num_reactions = len(reactionList) factor_high = 1.05 factor_low = 1. / factor_high worksheet = csv.writer(file('ignition_rxn_sensitivity.csv', 'w')) worksheet.writerow([ 'Index', 'Reaction', 'd[ln k]', 'tau_high', 'tau_low', 'd[ln tau]/d[ln k]' ]) print 'Running reaction sensitivity analysis using finite differences...' for index, reaction in enumerate(reactionList): rxn_index = index + 1 rxn_string = reaction.toChemkin(kinetics=False) print 'At reaction {0} of {1}. {2}'.format(rxn_index, num_reactions, rxn_string) reaction.kinetics.changeRate(factor_high) saveChemkinFile('chem_temp.inp', speciesList, reactionList, verbose=False) tau_high = runChemkinJob('chem_temp.inp') reaction.kinetics.changeRate(1. / factor_high) # reset the kinetics reaction.kinetics.changeRate(factor_low) saveChemkinFile('chem_temp.inp', speciesList, reactionList, verbose=False) tau_low = runChemkinJob('chem_temp.inp') reaction.kinetics.changeRate(1. / factor_low) # reset the kinetics if tau_high != 0 and tau_low != 0: sens = numpy.log(tau_high / tau_low) / numpy.log( factor_high / factor_low) else: sens = 0 worksheet.writerow([ rxn_index, rxn_string, numpy.log(factor_high / factor_low), tau_high, tau_low, sens ])
def writeModel(rmg, chemkin_name='chem_reduced.inp'): """ Writes the reduced reaction model to a chemkin compatible files. """ logging.info('Writing reduced model to {}'.format(chemkin_name)) speciesList = rmg.reactionModel.core.species rxnList = rmg.reactionModel.core.reactions path = os.path.join(os.getcwd(), chemkin_name) saveChemkinFile(path, speciesList, rxnList, verbose = True, checkForDuplicates=True)
def execute(inputModelFiles, **kwargs): try: wd = kwargs['wd'] except KeyError: wd = os.getcwd() transport = kwargs['transport'] outputChemkinFile = os.path.join(wd, 'chem.inp') outputSpeciesDictionary = os.path.join(wd, 'species_dictionary.txt') outputTransportFile = os.path.join(wd, 'tran.dat') if transport else None # Load the models to merge models = [] for chemkin, speciesPath, transportPath in inputModelFiles: print 'Loading model #{0:d}...'.format(len(models) + 1) model = ReactionModel() model.species, model.reactions = loadChemkinFile( chemkin, speciesPath, transportPath=transportPath) models.append(model) finalModel = ReactionModel() for i, model in enumerate(models): print 'Ignoring common species and reactions from model #{0:d}...'.format( i + 1) Nspec0 = len(finalModel.species) Nrxn0 = len(finalModel.reactions) finalModel = finalModel.merge(model) Nspec = len(finalModel.species) Nrxn = len(finalModel.reactions) print 'Added {1:d} out of {2:d} ({3:.1f}%) unique species from model #{0:d}.'.format( i + 1, Nspec - Nspec0, len(model.species), (Nspec - Nspec0) * 100. / len(model.species)) print 'Added {1:d} out of {2:d} ({3:.1f}%) unique reactions from model #{0:d}.'.format( i + 1, Nrxn - Nrxn0, len(model.reactions), (Nrxn - Nrxn0) * 100. / len(model.reactions)) print 'The merged model has {0:d} species and {1:d} reactions'.format( len(finalModel.species), len(finalModel.reactions)) # Save the merged model to disk saveChemkinFile(outputChemkinFile, finalModel.species, finalModel.reactions) saveSpeciesDictionary(outputSpeciesDictionary, finalModel.species) if transport: saveTransportFile(outputTransportFile, finalModel.species) print 'Merged Chemkin file saved to {0}'.format(outputChemkinFile) print 'Merged species dictionary saved to {0}'.format( outputSpeciesDictionary) if transport: print 'Merged transport file saved to {0}'.format(outputTransportFile)
def runIgnitionThermoSensitivity(runChemkinJob, inputFile, dictionaryFile): """ Supply a runChemkinJob python function which returns the ignition delay with a chemkin file input. This will run finite difference sensitivities to enthalpies and save them to a csv file. """ from rmgpy.chemkin import loadChemkinFile, saveChemkinFile, getSpeciesIdentifier from rmgpy.quantity import Quantity speciesList, reactionList = loadChemkinFile(inputFile, dictionaryPath=dictionaryFile, readComments=False) num_species = len(speciesList) deltaH = Quantity(0.5, 'kcal/mol').value_si worksheet = csv.writer(file('ignition_thermo_sensitivity.csv', 'w')) worksheet.writerow([ 'Species', 'd[del H] (kcal/mol)', 'tau_high', 'tau_low', 'd[ln tau]/d[del H]' ]) print 'Running thermo sensitivity analysis using finite differences...' for index, species in enumerate(speciesList): species_index = index + 1 species_string = getSpeciesIdentifier(species) print 'At species {0} of {1}. {2}'.format(species_index, num_species, species_string) species.thermo.changeBaseEnthalpy(deltaH) saveChemkinFile('chem_temp.inp', speciesList, reactionList, verbose=False) tau_high = runChemkinJob('chem_temp.inp') species.thermo.changeBaseEnthalpy(-deltaH) # reset the thermo species.thermo.changeBaseEnthalpy(-deltaH) saveChemkinFile('chem_temp.inp', speciesList, reactionList, verbose=False) tau_low = runChemkinJob('chem_temp.inp') species.thermo.changeBaseEnthalpy(deltaH) # reset the kinetics if tau_high != 0 and tau_low != 0: sens = numpy.log(tau_high / tau_low) / (2 * deltaH) else: sens = 0 worksheet.writerow([species_string, '1', tau_high, tau_low, sens])
def writeModel(rmg, chemkin_name='chem_reduced.inp'): """ Writes the reduced reaction model to a chemkin compatible files. """ logging.info('Writing reduced model to {}'.format(chemkin_name)) speciesList = rmg.reactionModel.core.species rxnList = rmg.reactionModel.core.reactions path = os.path.join(os.getcwd(), chemkin_name) saveChemkinFile(path, speciesList, rxnList, verbose=True, checkForDuplicates=True)
def execute(inputModelFiles, **kwargs): try: wd = kwargs['wd'] except KeyError: wd = os.getcwd() transport = kwargs['transport'] outputChemkinFile = os.path.join(wd, 'chem.inp') outputSpeciesDictionary = os.path.join(wd, 'species_dictionary.txt') outputTransportFile = os.path.join(wd, 'tran.dat') if transport else None # Load the models to merge models = [] for chemkin, speciesPath, transportPath in inputModelFiles: print 'Loading model #{0:d}...'.format(len(models)+1) model = ReactionModel() model.species, model.reactions = loadChemkinFile(chemkin, speciesPath, transportPath=transportPath) models.append(model) finalModel = ReactionModel() for i, model in enumerate(models): print 'Ignoring common species and reactions from model #{0:d}...'.format(i+1) Nspec0 = len(finalModel.species) Nrxn0 = len(finalModel.reactions) finalModel = finalModel.merge(model) Nspec = len(finalModel.species) Nrxn = len(finalModel.reactions) print 'Added {1:d} out of {2:d} ({3:.1f}%) unique species from model #{0:d}.'.format(i+1, Nspec - Nspec0, len(model.species), (Nspec - Nspec0) * 100. / len(model.species)) print 'Added {1:d} out of {2:d} ({3:.1f}%) unique reactions from model #{0:d}.'.format(i+1, Nrxn - Nrxn0, len(model.reactions), (Nrxn - Nrxn0) * 100. / len(model.reactions)) print 'The merged model has {0:d} species and {1:d} reactions'.format(len(finalModel.species), len(finalModel.reactions)) # Save the merged model to disk saveChemkinFile(outputChemkinFile, finalModel.species, finalModel.reactions) saveSpeciesDictionary(outputSpeciesDictionary, finalModel.species) if transport: saveTransportFile(outputTransportFile, finalModel.species) print 'Merged Chemkin file saved to {0}'.format(outputChemkinFile) print 'Merged species dictionary saved to {0}'.format(outputSpeciesDictionary) if transport: print 'Merged transport file saved to {0}'.format(outputTransportFile)
def runThermoEstimator(inputFile, library_flag): """ Estimate thermo for a list of species using RMG and the settings chosen inside a thermo input file. """ rmg = RMG() rmg.loadThermoInput(inputFile) rmg.database = RMGDatabase() path = os.path.join(settings['database.directory']) # forbidden structure loading rmg.database.loadThermo(os.path.join(path, 'thermo'), rmg.thermoLibraries, depository=False) if rmg.solvent: rmg.database.loadSolvation(os.path.join(path, 'solvation')) Species.solventData = rmg.database.solvation.getSolventData( rmg.solvent) Species.solventName = rmg.solvent for species in rmg.initialSpecies: submit(species) if library_flag: library = ThermoLibrary(name='Thermo Estimation Library') for species in rmg.initialSpecies: library.loadEntry( index=len(library.entries) + 1, label=species.label, molecule=species.molecule[0].toAdjacencyList(), thermo=species.getThermoData().toThermoData(), shortDesc=species.getThermoData().comment, ) library.save(os.path.join(rmg.outputDirectory, 'ThermoLibrary.py')) # Save the thermo data to chemkin format output files and dictionary, with no reactions saveChemkinFile(os.path.join(rmg.outputDirectory, 'chem_annotated.inp'), species=rmg.initialSpecies, reactions=[]) saveSpeciesDictionary(os.path.join(rmg.outputDirectory, 'species_dictionary.txt'), species=rmg.initialSpecies)
def runIgnitionReactionSensitivity(runChemkinJob, inputFile, dictionaryFile): """ Supply a runChemkinJob python function which returns the ignition delay with a chemkin file input. This will run finite difference reaction sensitivities and save them to a csv file. """ from rmgpy.chemkin import loadChemkinFile, saveChemkinFile speciesList, reactionList = loadChemkinFile(inputFile, dictionaryPath = dictionaryFile, readComments = False) num_reactions = len(reactionList) factor_high = 1.05 factor_low = 1. / factor_high worksheet = csv.writer(file('ignition_rxn_sensitivity.csv', 'w')) worksheet.writerow(['Index', 'Reaction', 'd[ln k]','tau_high','tau_low','d[ln tau]/d[ln k]']) logging.info('Running reaction sensitivity analysis using finite differences...') for index, reaction in enumerate(reactionList): rxn_index = index + 1 rxn_string = reaction.toChemkin(kinetics = False) logging.info('At reaction {0} of {1}. {2}'.format(rxn_index, num_reactions, rxn_string)) reaction.kinetics.changeRate(factor_high) saveChemkinFile('chem_temp.inp', speciesList, reactionList, verbose = False) tau_high = runChemkinJob('chem_temp.inp') reaction.kinetics.changeRate(1./factor_high) # reset the kinetics reaction.kinetics.changeRate(factor_low) saveChemkinFile('chem_temp.inp', speciesList, reactionList, verbose = False) tau_low = runChemkinJob('chem_temp.inp') reaction.kinetics.changeRate(1./factor_low) # reset the kinetics if tau_high != 0 and tau_low != 0: sens = numpy.log(tau_high / tau_low) / numpy.log(factor_high / factor_low) else: sens = 0 worksheet.writerow([rxn_index, rxn_string, numpy.log(factor_high / factor_low), tau_high, tau_low, sens])
def runIgnitionThermoSensitivity(runChemkinJob, inputFile, dictionaryFile): """ Supply a runChemkinJob python function which returns the ignition delay with a chemkin file input. This will run finite difference sensitivities to enthalpies and save them to a csv file. """ from rmgpy.chemkin import loadChemkinFile, saveChemkinFile, getSpeciesIdentifier from rmgpy.quantity import Quantity speciesList, reactionList = loadChemkinFile(inputFile, dictionaryPath = dictionaryFile, readComments = False) num_species = len(speciesList) deltaH = Quantity(0.5, 'kcal/mol').value_si worksheet = csv.writer(file('ignition_thermo_sensitivity.csv', 'w')) worksheet.writerow(['Species', 'd[del H] (kcal/mol)', 'tau_high', 'tau_low', 'd[ln tau]/d[del H]']) logging.info('Running thermo sensitivity analysis using finite differences...') for index, species in enumerate(speciesList): species_index = index + 1 species_string = getSpeciesIdentifier(species) logging.info('At species {0} of {1}. {2}'.format(species_index, num_species, species_string)) species.thermo.changeBaseEnthalpy(deltaH) saveChemkinFile('chem_temp.inp', speciesList, reactionList, verbose = False) tau_high = runChemkinJob('chem_temp.inp') species.thermo.changeBaseEnthalpy(-deltaH) # reset the thermo species.thermo.changeBaseEnthalpy(-deltaH) saveChemkinFile('chem_temp.inp', speciesList, reactionList, verbose = False) tau_low = runChemkinJob('chem_temp.inp') species.thermo.changeBaseEnthalpy(deltaH) # reset the kinetics if tau_high != 0 and tau_low != 0: sens = numpy.log(tau_high / tau_low) / (2 * deltaH) else: sens = 0 worksheet.writerow([species_string, '1', tau_high, tau_low, sens])
def runThermoEstimator(inputFile): """ Estimate thermo for a list of species using RMG and the settings chosen inside a thermo input file. """ rmg = RMG() rmg.loadThermoInput(inputFile) rmg.database = RMGDatabase() path = os.path.join(settings['database.directory']) # forbidden structure loading rmg.database.loadThermo(os.path.join(path, 'thermo'), rmg.thermoLibraries, depository=False) if rmg.solvent: rmg.database.loadSolvation(os.path.join(path, 'solvation')) Species.solventData = rmg.database.solvation.getSolventData(rmg.solvent) Species.solventName = rmg.solvent for species in rmg.initialSpecies: submit(species) # library = ThermoLibrary(name='Thermo Estimation Library') # for spc in rmg.initialSpecies: # library.loadEntry( # index = len(library.entries) + 1, # label = species.label, # molecule = species.molecule[0].toAdjacencyList(), # thermo = species.getThermoData().toThermoData(), # shortDesc = species.getThermoData().comment, # ) # library.save(os.path.join(rmg.outputDirectory,'ThermoLibrary.py')) # Save the thermo data to chemkin format output files and dictionary, with no reactions saveChemkinFile(os.path.join(rmg.outputDirectory, 'chem_annotated.inp'), species=rmg.initialSpecies, reactions=[]) saveSpeciesDictionary(os.path.join(rmg.outputDirectory, 'species_dictionary.txt'), species=rmg.initialSpecies)
for chemkin, speciesPath, transportPath in inputModelFiles: print 'Loading model #{0:d}...'.format(len(models)+1) model = ReactionModel() model.species, model.reactions = loadChemkinFile(chemkin, speciesPath, transportPath=transportPath) models.append(model) allSpecies = [] speciesIndices = [[] for i in range(len(models))] for i, model in enumerate(models): speciesIndices[i] = [] for j, species in enumerate(model.species): for index, species0 in enumerate(allSpecies): if species0.isIsomorphic(species): speciesIndices[i].append(index) break; else: allSpecies.append(species) speciesIndices[i].append(allSpecies.index(species)) # Reassign species names and labels according to the list of all species in all models # We must retain the original thermochemistry for i, model in enumerate(models): for j, species in enumerate(model.species): index = speciesIndices[i][j] species.label = allSpecies[index].label species.index = allSpecies[index].index # Resave the models saveChemkinFile('chem{0}.inp'.format(i+1), model.species, model.reactions) saveSpeciesDictionary('species_dictionary{0}.txt'.format(i+1), model.species) print 'Saving of new models with consistent names is complete!'
) reactionList.append(library_reaction) speciesList = [] index = 0 speciesDict = kineticLibrary.getSpecies( os.path.join(settings["database.directory"], "kinetics", "libraries", libraryName, "dictionary.txt") ) for spec in speciesDict.values(): index = index + 1 species = Species(molecule=spec.molecule) species.getThermoData() species.index = index speciesList.append(species) for reaction in reactionList: for reactant in reaction.reactants: for spec in speciesList: if reactant.isIsomorphic(spec): reactant.index = spec.index spec.label = reactant.label for product in reaction.products: for spec in speciesList: if product.isIsomorphic(spec): product.index = spec.index spec.label = product.label print "Saving the chem.inp and species_dictionary.txt to local directory" saveChemkinFile("chem.inp", speciesList, reactionList) saveSpeciesDictionary("species_dictionary.txt", speciesList)
for i, model in enumerate(models): print 'Ignoring common species and reactions from model #{0:d}...'.format( i + 1) Nspec0 = len(finalModel.species) Nrxn0 = len(finalModel.reactions) finalModel = finalModel.merge(model) Nspec = len(finalModel.species) Nrxn = len(finalModel.reactions) print 'Added {1:d} out of {2:d} ({3:.1f}%) unique species from model #{0:d}.'.format( i + 1, Nspec - Nspec0, len(model.species), (Nspec - Nspec0) * 100. / len(model.species)) print 'Added {1:d} out of {2:d} ({3:.1f}%) unique reactions from model #{0:d}.'.format( i + 1, Nrxn - Nrxn0, len(model.reactions), (Nrxn - Nrxn0) * 100. / len(model.reactions)) print 'The merged model has {0:d} species and {1:d} reactions'.format( len(finalModel.species), len(finalModel.reactions)) # Save the merged model to disk saveChemkinFile(outputChemkinFile, finalModel.species, finalModel.reactions) saveSpeciesDictionary(outputSpeciesDictionary, finalModel.species) if transport: saveTransportFile(outputTransportFile, finalModel.species) print 'Merged Chemkin file saved to {0}'.format(outputChemkinFile) print 'Merged species dictionary saved to {0}'.format( outputSpeciesDictionary) if transport: print 'Merged transport file saved to {0}'.format(outputTransportFile)
# Load the models to merge models = [] for chemkin, speciesDict in zip(args.files[0::2], args.files[1::2]): print 'Loading model #{0:d}...'.format(len(models)+1) model = ReactionModel() model.species, model.reactions = loadChemkinFile(chemkin, speciesDict) models.append(model) finalModel = ReactionModel() for i, model in enumerate(models): print 'Ignoring common species and reactions from model #{0:d}...'.format(i+1) Nspec0 = len(finalModel.species) Nrxn0 = len(finalModel.reactions) finalModel = finalModel.merge(model) Nspec = len(finalModel.species) Nrxn = len(finalModel.reactions) print 'Added {1:d} out of {2:d} ({3:.1f}%) unique species from model #{0:d}.'.format(i+1, Nspec - Nspec0, len(model.species), (Nspec - Nspec0) * 100. / len(model.species)) print 'Added {1:d} out of {2:d} ({3:.1f}%) unique reactions from model #{0:d}.'.format(i+1, Nrxn - Nrxn0, len(model.reactions), (Nrxn - Nrxn0) * 100. / len(model.reactions)) print 'The merged model has {0:d} species and {1:d} reactions'.format(len(finalModel.species), len(finalModel.reactions)) # Save the merged model to disk saveChemkinFile(outputChemkinFile, finalModel.species, finalModel.reactions) saveSpeciesDictionary(outputSpeciesDictionary, finalModel.species) print 'Merged Chemkin file saved to {0}'.format(outputChemkinFile) print 'Merged species dictionary saved to {0}'.format(outputSpeciesDictionary)
def main(): fuelName = 'test' chemFile = 'chem_' + fuelName spcFile = 'spc_' + fuelName + '.txt' outputChemkinFile = chemFile + '_delete_DupThirdBodyRXNs.inp' chemFile += '.inp' model = ReactionModel() model.species, model.reactions = loadChemkinFile(chemFile, spcFile) # Delete redundant third body reactions thirdBodyRXNs = [] deleteRedundantThirdBodyRXNs = [] duplicateEndoRXNs = [] for rxn in model.reactions: if isinstance(rxn.kinetics, ThirdBody): thirdBodyRXNs.append(rxn) for rxnThirdBody in thirdBodyRXNs: for rxnTest in model.reactions: if rxnThirdBody.index != rxnTest.index: if checkSpecificFormThirdBodyRXN(rxnThirdBody, rxnTest): deleteRedundantThirdBodyRXNs.append(rxnTest) # Delete duplicate reactions caused by Intra_R_Add_Endocyclic and Intra_R_Add_Exocyclic # Delete the endo one. for rxn1 in [ rxn for rxn in model.reactions if rxn.duplicate == True and rxn.family == 'Intra_R_Add_Exocyclic' ]: for rxn2 in [ rxn for rxn in model.reactions if rxn.duplicate == True and rxn.family == 'Intra_R_Add_Endocyclic' ]: if rxn1.index != rxn2.index and rxn1.isIsomorphic( rxn2, eitherDirection=True): duplicateEndoRXNs.append(rxn2) rxn1.duplicate = False print '--------------------------------------------' print 'The following {0} redundant third body reactions will be removed from the original model:'.format( len(deleteRedundantThirdBodyRXNs)) for rxn in deleteRedundantThirdBodyRXNs: print rxn print '--------------------------------------------' print 'The following {0} duplicated Intra_R_Add_Endocyclic reactions will be removed from the original model:'.format( len(duplicateEndoRXNs)) for rxn in duplicateEndoRXNs: print rxn print '--------------------------------------------' print 'The original model has {0} rxns'.format(len(model.reactions)) for rxn in deleteRedundantThirdBodyRXNs + duplicateEndoRXNs: model.reactions.remove(rxn) print 'The final model has {0} rxns'.format(len(model.reactions)) print 'Save the final model into chemkin file...' saveChemkinFile(outputChemkinFile, model.species, model.reactions)
reaction.kinetics = entry.data reactionList.append(reaction) speciesList = [] index = 0 speciesDict = kineticLibrary.getSpecies( os.path.join(settings['database.directory'], 'kinetics', 'libraries', libraryName, 'dictionary.txt')) for spec in speciesDict.values(): index = index + 1 species = Species(molecule=spec.molecule) species.generateThermoData(database) species.index = index speciesList.append(species) for reaction in reactionList: for reactant in reaction.reactants: for spec in speciesList: if reactant.isIsomorphic(spec): reactant.index = spec.index spec.label = reactant.label for product in reaction.products: for spec in speciesList: if product.isIsomorphic(spec): product.index = spec.index spec.label = product.label print 'Saving the chem.inp and species_dictionary.txt to local directory' saveChemkinFile('chem.inp', speciesList, reactionList) saveSpeciesDictionary('species_dictionary.txt', speciesList)
reaction.kinetics = entry.data reactionList.append(reaction) speciesList = [] index = 0 for spec in kineticLibrary.getSpecies().values(): index = index + 1 species = Species(molecule = spec.molecule) species.generateThermoData(database) species.index = index speciesList.append(species) for reaction in reactionList: for reactant in reaction.reactants: for spec in speciesList: if reactant.isIsomorphic(spec): reactant.index = spec.index spec.label = reactant.label for product in reaction.products: for spec in speciesList: if product.isIsomorphic(spec): product.index = spec.index spec.label = product.label print 'Saving the chem.inp and species_dictionary.txt to local directory' saveChemkinFile('chem.inp', speciesList, reactionList) saveSpeciesDictionary('species_dictionary.txt', speciesList)