def read_thermo_lib_by_path(lib_path, thermo_db): """ Read thermo library given its library path Args: lib_path (str): Path to thermo library file thermo_database (ThermoDatabase): RMG thermo database object """ if not os.path.exists(lib_path): logging.error('The library file %s does not exist.' %(lib_path)) return if lib_path not in thermo_db.library_order: lib = ThermoLibrary() try: lib.load(lib_path, ThermoDatabase().local_context, ThermoDatabase().global_context) except: logging.error('The library file %s is not vaild.' % (lib_path)) return else: lib.label = lib_path thermo_db.libraries[lib.label] = lib thermo_db.library_order.append(lib.label) logging.info('Loading thermodynamics library {1} from {0} ...'.format( os.path.split(lib_path)[0], os.path.split(lib_path)[1]),) else: logging.warning('The library %s has already been loaded' %(lib_path))
def load_thermo_lib_by_path(path: str, thermo_db: ThermoDatabase): """ Load thermo library given its path. This is really helpful when the library is not located in the RMG-database. Args: path (str): Path to thermo library file thermo_database (ThermoDatabase): RMG thermo database object """ if not os.path.exists(path): raise ValueError(f'The library file {path} does not exist.') if path not in thermo_db.library_order: lib = ThermoLibrary() try: lib.load(path, ThermoDatabase().local_context, ThermoDatabase().global_context) except: raise ValueError(f'The library file {path} is not vaild.') return else: lib.label = path thermo_db.libraries[lib.label] = lib thermo_db.library_order.append(lib.label) print(f'Loading thermo library {os.path.split(path)[1]} ' f'from {os.path.split(path)[0]} ...') else: print(f'The library {path} has already been loaded')
def import_thermo(thermo_path, kinetic_model, models): local_context = { "ThermoData": ThermoData, "Wilhoit": Wilhoit, "NASAPolynomial": NASAPolynomial, "NASA": NASA, } library = ThermoLibrary(label=kinetic_model.model_name) # NOTE: In order for this feature to run we have to be on "rmg-py/importer" branch, may require reinstall # noqa: E501 library.SKIP_DUPLICATES = True library.load(thermo_path, local_context=local_context) for species_name, entry in library.entries.items(): logger.info(f"Importing Thermo entry for {species_name}") try: species = get_or_create_species(kinetic_model, species_name, [entry.item], models) thermo_data = entry.data poly1, poly2 = thermo_data.polynomials thermo, _ = models.Thermo.objects.get_or_create( species=species, coeffs_poly1=poly1.coeffs.tolist(), coeffs_poly2=poly2.coeffs.tolist(), temp_min_1=poly1.Tmin.value_si, temp_max_1=poly1.Tmax.value_si, temp_min_2=poly2.Tmin.value_si, temp_max_2=poly2.Tmax.value_si, ) thermo_comment = models.ThermoComment.objects.create( kinetic_model=kinetic_model, thermo=thermo) thermo_comment.comment = entry.long_desc or entry.short_desc or thermo_comment.comment thermo.save() thermo_comment.save() except Exception: logger.exception("Failed to import entry")
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) # initialize and load the database as well as any QM settings rmg.loadDatabase() if rmg.quantumMechanics: rmg.quantumMechanics.initialize() # Generate the thermo for all the species and write them to chemkin format as well as # ThermoLibrary format with values for H, S, and Cp's. output = open(os.path.join(rmg.outputDirectory, 'output.txt'),'wb') library = ThermoLibrary(name='Thermo Estimation Library') for species in rmg.initialSpecies: species.generateThermoData(rmg.database, quantumMechanics=rmg.reactionModel.quantumMechanics) library.loadEntry( index = len(library.entries) + 1, label = species.label, molecule = species.molecule[0].toAdjacencyList(), thermo = species.thermo.toThermoData(), shortDesc = species.thermo.comment, ) output.write(writeThermoEntry(species)) output.write('\n') output.close() library.save(os.path.join(rmg.outputDirectory,'ThermoLibrary.py'))
def find_thermo_libs(path): """ This function search for the thermo library based on /thermo/*.py or /libraries/*.py Args: path (str): The path to project directories Returns: thermo_lib_list (list): Entries of the path to thermo libraries """ # Initiate the thermo lib list thermo_lib_list = list() # Walk through the dirs under path for root_p, dirs, _ in os.walk(path): if not dirs: continue # Use ARC folder organization to check thermo library chk_path = os.path.join(root_p, 'thermo') if os.path.isdir(chk_path): # Find the corresponding thermo lib file thermo_lib = glob.glob(os.path.join(chk_path, '*.py'))[0] # Check the lib is valid by loading it if thermo_lib: try: lib = ThermoLibrary() lib.load(thermo_lib, ThermoDatabase().local_context, ThermoDatabase().global_context) except: continue else: thermo_lib_list.append(thermo_lib) logging.info("Find thermo library at {0}".format(thermo_lib)) return thermo_lib_list
def __init__(self, fileStore = None, scratchDirectory = None, ): self.settings = QMSettings() self.settings.fileStore = fileStore self.settings.scratchDirectory = scratchDirectory self.database = ThermoLibrary(name='QM Thermo Library')
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) # initialize and load the database as well as any QM settings rmg.loadDatabase() if rmg.quantumMechanics: rmg.quantumMechanics.initialize() # Generate the thermo for all the species and write them to chemkin format as well as # ThermoLibrary format with values for H, S, and Cp's. output = open(os.path.join(rmg.outputDirectory, 'output.txt'), 'wb') library = ThermoLibrary(name='Thermo Estimation Library') for species in rmg.initialSpecies: species.generateThermoData( rmg.database, quantumMechanics=rmg.reactionModel.quantumMechanics) library.loadEntry( index=len(library.entries) + 1, label=species.label, molecule=species.molecule[0].toAdjacencyList(), thermo=species.thermo.toThermoData(), shortDesc=species.thermo.comment, ) output.write(writeThermoEntry(species)) output.write('\n') output.close() library.save(os.path.join(rmg.outputDirectory, 'ThermoLibrary.py'))
def load_thermo_lib_by_path(path: str, thermo_db: ThermoDatabase, reload: bool = False): """ Load thermo library given its library path and store it into the given RMG ThermoDatabase instance Args: path (str): Path to thermo library file thermo_database (ThermoDatabase): RMG thermo database object reload (bool): Whether to reload the library if this library is in the ThermoDatabase """ lib = ThermoLibrary() try: lib.load(path, ThermoDatabase().local_context, ThermoDatabase().global_context) except FileNotFoundError: print(f'The library file {path} does not exist.') except (SyntaxError, ImportError): print(f'The library file {path} is not valid.') else: if path in thermo_db.library_order and not reload: print(f'The library {path} has already been loaded.') return elif path not in thermo_db.library_order: thermo_db.library_order.append(path) lib.label = path lib.name = path thermo_db.libraries[lib.label] = lib print(f'The thermodynamics library {path} is loaded.')
def save_thermo_lib(species_list, path, name, lib_long_desc): """ Save an RMG thermo library of all species in `species_list` in the supplied `path` `name` is the library's name (or project's name) `long_desc` is a multiline string with level of theory description """ if species_list: lib_path = os.path.join(path, 'thermo', '{0}.py'.format(name)) thermo_library = ThermoLibrary(name=name, longDesc=lib_long_desc) for i, spc in enumerate(species_list): if spc.thermo is not None: spc.long_thermo_description += '\nExternal symmetry: {0}, optical isomers: {1}\n'.format( spc.external_symmetry, spc.optical_isomers) spc.long_thermo_description += '\nGeometry:\n{0}'.format( spc.final_xyz) thermo_library.loadEntry( index=i + 1, label=spc.label, molecule=spc.mol_list[0].toAdjacencyList(), thermo=spc.thermo, shortDesc=spc.thermo.comment, longDesc=spc.long_thermo_description) else: logging.warning( 'Species {0} did not contain any thermo data and was omitted from the thermo' ' library.'.format(str(spc))) thermo_library.save(lib_path)
def save_thermo_lib(species_list, path, name, lib_long_desc): """ Save an RMG thermo library. Args: species_list (list): Entries are Species object instances for which thermo will be saved. path (str): The base folder in which the thermo library will be saved. name (str): The library name. lib_long_desc (str): A multiline string with relevant description. """ if species_list: lib_path = os.path.join(path, f'{name}.py') thermo_library = ThermoLibrary(name=name, long_desc=lib_long_desc) for i, spc in enumerate(species_list): if spc.thermo is not None: long_thermo_description = f'\nSpin multiplicity: {spc.conformer.spin_multiplicity}' \ f'\nExternal symmetry: {spc.molecule[0].symmetry_number}' \ f'\nOptical isomers: {spc.conformer.optical_isomers}\n' xyz = get_str_xyz(spc) if xyz is not None: long_thermo_description += f'\nGeometry:\n{xyz}' thermo_library.load_entry( index=i, label=spc.label, molecule=spc.molecule[0].to_adjacency_list(), thermo=spc.thermo, shortDesc=spc.thermo.comment, longDesc=long_thermo_description) else: logging.warning( f'Species {spc.label} did not contain any thermo data and was omitted from the thermo ' f'library {name}.') thermo_library.save(lib_path)
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 # Generate the thermo for all the species and write them to chemkin format as well as # ThermoLibrary format with values for H, S, and Cp's. output = open(os.path.join(rmg.outputDirectory, 'output.txt'),'wb') library = ThermoLibrary(name='Thermo Estimation Library') for species in rmg.initialSpecies: species.getThermoData(rmg.database) library.loadEntry( index = len(library.entries) + 1, label = species.label, molecule = species.molecule[0].toAdjacencyList(), thermo = species.thermo.toThermoData(), shortDesc = species.thermo.comment, ) output.write(writeThermoEntry(species)) output.write('\n') output.close() library.save(os.path.join(rmg.outputDirectory,'ThermoLibrary.py'))
def __init__(self, software = None, method = 'pm3', fileStore = None, scratchDirectory = None, onlyCyclics = True, maxRadicalNumber = 0, ): self.settings = QMSettings(software = software, method = method, fileStore = fileStore, scratchDirectory = scratchDirectory, onlyCyclics = onlyCyclics, maxRadicalNumber = maxRadicalNumber, ) self.database = ThermoLibrary(name='QM Thermo Library')
def run_thermo_estimator(input_file, library_flag): """ Estimate thermo for a list of species using RMG and the settings chosen inside a thermo input file. """ rmg = RMG() rmg.load_thermo_input(input_file) rmg.database = RMGDatabase() path = os.path.join(settings['database.directory']) # forbidden structure loading rmg.database.load_thermo(os.path.join(path, 'thermo'), rmg.thermo_libraries, depository=False) if rmg.solvent: rmg.database.load_solvation(os.path.join(path, 'solvation')) Species.solvent_data = rmg.database.solvation.get_solvent_data( rmg.solvent) Species.solvent_name = rmg.solvent for species in rmg.initial_species: submit(species) if library_flag: library = ThermoLibrary(name='Thermo Estimation Library') for species in rmg.initial_species: library.load_entry( index=len(library.entries) + 1, label=species.label, molecule=species.molecule[0].to_adjacency_list(), thermo=species.get_thermo_data().to_thermo_data(), shortDesc=species.get_thermo_data().comment, ) library.save(os.path.join(rmg.output_directory, 'ThermoLibrary.py')) # Save the thermo data to chemkin format output files and dictionary, with no reactions save_chemkin_file(os.path.join(rmg.output_directory, 'chem_annotated.inp'), species=rmg.initial_species, reactions=[]) save_species_dictionary(os.path.join(rmg.output_directory, 'species_dictionary.txt'), species=rmg.initial_species)
parser.add_argument('name', metavar='NAME', type=str, nargs=1, help='Name of the chemkin library to be saved') args = parser.parse_args() chemkinPath = args.chemkinPath[0] dictionaryPath = args.dictionaryPath[0] name = args.name[0] speciesList, reactionList = loadChemkinFile(chemkinPath, dictionaryPath) # Make full species identifier the species labels for species in speciesList: species.label = getSpeciesIdentifier(species) species.index = -1 # load thermo library entries thermoLibrary = ThermoLibrary(name=name) for i in range(len(speciesList)): species = speciesList[i] if species.thermo: thermoLibrary.loadEntry(index = i + 1, label = species.label, molecule = species.molecule[0].toAdjacencyList(), thermo = species.thermo, shortDesc = species.thermo.comment ) else: logging.warning('Species {0} did not contain any thermo data and was omitted from the thermo library.'.format(str(species))) # load kinetics library entries kineticsLibrary = KineticsLibrary(name=name) kineticsLibrary.entries = {}
parser.add_argument('outputDirectory', metavar='OUTPUTDIR', type=str, nargs=1, help='The desired output directory for the library files') parser.add_argument('-r', '--removeH', action='store_true', help='remove explicit hydrogens') args = parser.parse_args() chemkinPath = args.chemkinPath[0] dictionaryPath = args.dictionaryPath[0] outputDir = args.outputDirectory[0] removeH = args.removeH print removeH speciesList, reactionList = loadChemkinFile(chemkinPath, dictionaryPath) # load thermo library entries thermoLibrary = ThermoLibrary() for i in range(len(speciesList)): species = speciesList[i] rdkitmol = species.molecule[0].toRDKitMol(removeHs=False) species.molecule = [Molecule().fromRDKitMol(rdkitmol)]#[0].toAdjacencyList(removeH=False) print species.molecule[0].toAdjacencyList(removeH = removeH) if species.thermo: thermoLibrary.loadEntry(index = i + 1, label = species.label, molecule = species.molecule[0].toAdjacencyList(removeH = removeH), thermo = species.thermo, shortDesc = species.thermo.comment ) else: logging.warning('Species {0} did not contain any thermo data and was omitted from the thermo library.'.format(str(species)))
def get_libraries(self): """Get RMG kinetics and thermo libraries""" name = 'kineticsjobs' species_list = list(self.species_dict.values()) reaction_list = list(self.reaction_dict.values()) # remove duplicate species for rxn in reaction_list: for i, rspc in enumerate(rxn.reactants): for spc in species_list: if spc.is_isomorphic(rspc): rxn.reactants[i] = spc break for i, rspc in enumerate(rxn.products): for spc in species_list: if spc.is_isomorphic(rspc): rxn.products[i] = spc break del_inds = [] for i, spc1 in enumerate(species_list): for j, spc2 in enumerate(species_list): if j > i and spc1.is_isomorphic(spc2): del_inds.append(j) for j in sorted(del_inds)[::-1]: del species_list[j] thermo_library = ThermoLibrary(name=name) for i, species in enumerate(species_list): if species.thermo: thermo_library.load_entry( index=i + 1, label=species.label, molecule=species.molecule[0].to_adjacency_list(), thermo=species.thermo, shortDesc=species.thermo.comment) else: logging.warning( 'Species {0} did not contain any thermo data and was omitted from the thermo library.' .format(str(species))) # load kinetics library entries kinetics_library = KineticsLibrary(name=name, auto_generated=True) kinetics_library.entries = {} for i, reaction in enumerate(reaction_list): entry = Entry(index=i + 1, label=reaction.to_labeled_str(), item=reaction, data=reaction.kinetics) if reaction.kinetics is not None: if hasattr(reaction, 'library') and reaction.library: entry.long_desc = 'Originally from reaction library: ' + \ reaction.library + "\n" + reaction.kinetics.comment else: entry.long_desc = reaction.kinetics.comment kinetics_library.entries[i + 1] = entry kinetics_library.label = name return thermo_library, kinetics_library, species_list
import argparse import os from rmgpy.data.thermo import ThermoLibrary if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('inputPath', metavar='INPUT', type=str, nargs=1, help='the input path of the RMG-Java thermo library directory') parser.add_argument('libraryName', metavar='OUTPUT', type=str, nargs=1, help='the libraryName for the RMG-Py format thermo library') args = parser.parse_args() inputPath = args.inputPath[0] libraryName = args.libraryName[0] library = ThermoLibrary() library.loadOld( dictstr = os.path.join(inputPath, 'Dictionary.txt'), treestr = '', libstr = os.path.join(inputPath, 'Library.txt'), numParameters = 12, numLabels = 1, pattern = False, ) library.name = libraryName # Save in Py format library.save(os.path.join('input/thermo/libraries/', libraryName+'.py'))
def getLibraries(self): name = 'kineticsjobs' speciesList = self.speciesDict.values() reactionList = self.reactionDict.values() # remove duplicate species for rxn in reactionList: for i,rspc in enumerate(rxn.reactants): for spc in speciesList: if spc.isIsomorphic(rspc): rxn.reactants[i] = spc break for i,rspc in enumerate(rxn.products): for spc in speciesList: if spc.isIsomorphic(rspc): rxn.products[i] = spc break del_inds = [] for i,spc1 in enumerate(speciesList): for j,spc2 in enumerate(speciesList): if j>i and spc1.isIsomorphic(spc2): del_inds.append(j) for j in sorted(del_inds)[::-1]: del speciesList[j] thermoLibrary = ThermoLibrary(name=name) for i,species in enumerate(speciesList): if species.thermo: thermoLibrary.loadEntry(index = i + 1, label = species.label, molecule = species.molecule[0].toAdjacencyList(), thermo = species.thermo, shortDesc = species.thermo.comment ) else: logging.warning('Species {0} did not contain any thermo data and was omitted from the thermo library.'.format(str(species))) # load kinetics library entries kineticsLibrary = KineticsLibrary(name=name,autoGenerated=True) kineticsLibrary.entries = {} for i,reaction in enumerate(reactionList): entry = Entry( index = i+1, label = reaction.toLabeledStr(), item = reaction, data = reaction.kinetics, ) if reaction.kinetics is not None: if hasattr(reaction,'library') and reaction.library: entry.longDesc = 'Originally from reaction library: ' +\ reaction.library + "\n" + reaction.kinetics.comment else: entry.longDesc = reaction.kinetics.comment kineticsLibrary.entries[i+1] = entry kineticsLibrary.label = name return thermoLibrary,kineticsLibrary,speciesList
help='The path of the RMG dictionary file') parser.add_argument('name', metavar='NAME', type=str, nargs=1, help='Name of the chemkin library to be saved') args = parser.parse_args() chemkin_path = args.chemkin_path[0] dictionary_path = args.dictionary_path[0] name = args.name[0] species_list, reaction_list = load_chemkin_file(chemkin_path, dictionary_path) thermo_library = ThermoLibrary(name=name) for i in range(len(species_list)): species = species_list[i] if species.thermo: thermo_library.load_entry( index=i + 1, label=species.label, molecule=species.molecule[0].to_adjacency_list(), thermo=species.thermo, ) else: logging.warning( """Species {0} did not contain any thermo data and was omitted from the thermo library.""".format(str(species))) # load kinetics library entries
parser.add_argument('chemkinPath', metavar='CHEMKIN', type=str, nargs=1, help='The path of the chemkin file') parser.add_argument('dictionaryPath', metavar='DICTIONARY', type=str, nargs=1, help='The path of the RMG dictionary file') parser.add_argument('name', metavar='NAME', type=str, nargs=1, help='Name of the chemkin library to be saved') args = parser.parse_args() chemkinPath = args.chemkinPath[0] dictionaryPath = args.dictionaryPath[0] name = args.name[0] speciesList, reactionList = loadChemkinFile(chemkinPath, dictionaryPath) # load thermo library entries thermoLibrary = ThermoLibrary() for i in range(len(speciesList)): species = speciesList[i] if species.thermo: thermoLibrary.loadEntry(index = i + 1, label = species.label, molecule = species.molecule[0].toAdjacencyList(), thermo = species.thermo, shortDesc = species.thermo.comment ) else: logging.warning('Species {0} did not contain any thermo data and was omitted from the thermo library.'.format(str(species))) # load kinetics library entries kineticsLibrary = KineticsLibrary() kineticsLibrary.entries = {}
'--removeH', action='store_true', help='remove explicit hydrogens') args = parser.parse_args() chemkinPath = args.chemkinPath[0] dictionaryPath = args.dictionaryPath[0] outputDir = args.outputDirectory[0] removeH = args.removeH print removeH speciesList, reactionList = loadChemkinFile(chemkinPath, dictionaryPath) # load thermo library entries thermoLibrary = ThermoLibrary() for i in range(len(speciesList)): species = speciesList[i] rdkitmol = species.molecule[0].toRDKitMol(removeHs=False) species.molecule = [Molecule().fromRDKitMol(rdkitmol) ] #[0].toAdjacencyList(removeH=False) print species.molecule[0].toAdjacencyList(removeH=removeH) if species.thermo: thermoLibrary.loadEntry( index=i + 1, label=species.label, molecule=species.molecule[0].toAdjacencyList(removeH=removeH), thermo=species.thermo, shortDesc=species.thermo.comment) else: logging.warning(
import argparse import os from rmgpy.data.thermo import ThermoLibrary from rmgpy import settings if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('inputPath', metavar='INPUT', type=str, nargs=1, help='the input path of the RMG-Java thermo library directory') parser.add_argument('libraryName', metavar='OUTPUT', type=str, nargs=1, help='the libraryName for the RMG-Py format thermo library') args = parser.parse_args() inputPath = args.inputPath[0] libraryName = args.libraryName[0] library = ThermoLibrary() library.loadOld( dictstr = os.path.join(inputPath, 'Dictionary.txt'), treestr = '', libstr = os.path.join(inputPath, 'Library.txt'), numParameters = 12, numLabels = 1, pattern = False, ) library.name = libraryName # Save in Py format library.save(os.path.join(settings['database.directory'], 'thermo', 'libraries', libraryName+'.py'))
metavar='INPUT', type=str, nargs=1, help='the input path of the RMG-Java thermo library directory') parser.add_argument( 'libraryName', metavar='OUTPUT', type=str, nargs=1, help='the libraryName for the RMG-Py format thermo library') args = parser.parse_args() inputPath = args.inputPath[0] libraryName = args.libraryName[0] library = ThermoLibrary() library.loadOld( dictstr=os.path.join(inputPath, 'Dictionary.txt'), treestr='', libstr=os.path.join(inputPath, 'Library.txt'), numParameters=12, numLabels=1, pattern=False, ) library.name = libraryName # Save in Py format library.save( os.path.join(settings['database.directory'], 'thermo', 'libraries', libraryName + '.py'))