Esempio n. 1
0
def load():
    tearDown()
    rmg = RMG()#for solvent
    database = RMGDatabase()
    database.loadThermo(os.path.join(settings['database.directory'], 'thermo'))
    database.loadTransport(os.path.join(settings['database.directory'], 'transport'))
    database.loadSolvation(os.path.join(settings['database.directory'], 'solvation'))
Esempio n. 2
0
 def __init__(self, *args, **kwargs):
     super(Input, self).__init__(*args, **kwargs)
     self.rmg = RMG()
     self.folder = os.path.join('rmg', 'tools', 'input')
     self.path = os.path.join(settings.MEDIA_ROOT, self.folder)
     self.loadpath = os.path.join(self.path, 'input_upload.py')
     self.savepath = os.path.join(self.path, 'input.py')
Esempio n. 3
0
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'))
Esempio n. 4
0
def main():
    """
    Driver function that parses command line arguments and passes them to the execute function.
    """
    # Parse the command-line arguments (requires the argparse module)
    args = parse_command_line_arguments()

    # Initialize the logging system (resets the RMG.log file)
    level = logging.INFO
    if args.debug:
        level = 0
    elif args.verbose:
        level = logging.DEBUG
    elif args.quiet:
        level = logging.WARNING

    kwargs = {
            'restart': args.restart,
            'walltime': args.walltime,
            'log': level,
            'kineticsdatastore': args.kineticsdatastore
    }

    initializeLog(level, os.path.join(args.output_directory, 'RMG.log'))

    rmg = RMG(inputFile=args.file, outputDirectory=args.output_directory)

    # Add output listeners:
    rmg.attach(ChemkinWriter(args.output_directory))
    rmg.attach(OutputHTMLWriter(args.output_directory))

    execute(rmg, **kwargs)
def saveRestartFile(path, rmg, delay=0):
    """
    Save a restart file to `path` on disk containing the contents of the
    provided `reactionModel`. The `delay` parameter is a time in seconds; if
    the restart file is not at least that old, the save is aborted. (Use the
    default value of 0 to force the restart file to be saved.)
    """

    # Saving of a restart file is very slow (likely due to all the Quantity objects)
    # Therefore, to save it less frequently, don't bother if the restart file is less than an hour old
    if os.path.exists(path) and time.time() - os.path.getmtime(path) < delay:
        logging.info('Not saving restart file in this iteration.')
        return

    # Pickle the reaction model to the specified file
    # We also compress the restart file to save space (and lower the disk read/write time)
    logging.info('Saving restart file...')

    from rmgpy.rmg.main import RMG
    rmg_restart = RMG()
    rmg_restart.reactionModel = rmg.reactionModel
    rmg_restart.unimolecularReact = rmg.unimolecularReact
    rmg_restart.bimolecularReact = rmg.bimolecularReact
    if rmg.filterReactions:
        rmg_restart.unimolecularThreshold = rmg.unimolecularThreshold
        rmg_restart.bimolecularThreshold = rmg.bimolecularThreshold

    f = open(path, 'wb')
    cPickle.dump(rmg_restart, f, cPickle.HIGHEST_PROTOCOL)
    f.close()
Esempio n. 6
0
    def testGetRingGroupsFromComments(self):
        """
        Test that getRingGroupsFromComments method works for fused polycyclics.
        """
        from rmgpy.thermo.thermoengine import generateThermoData

        # set-up RMG object
        rmg = RMG()

        # load kinetic database and forbidden structures
        rmg.database = RMGDatabase()
        path = os.path.join(settings['database.directory'])

        # forbidden structure loading
        rmg.database.loadThermo(os.path.join(path, 'thermo'))

        smi = 'C12C(C3CCC2C3)C4CCC1C4'  #two norbornane rings fused together
        spc = Species().fromSMILES(smi)

        spc.thermo = generateThermoData(spc)

        thermodb = rmg.database.thermo
        thermodb.getRingGroupsFromComments(spc.thermo)

        import rmgpy.data.rmg
        rmgpy.data.rmg.database = None
Esempio n. 7
0
    def testDuplicateReaction(self):
        """
        Test that the radical addition reaction

        HCJ=O + CH2O = [CH2]OC=O

        present in the reaction library "Methylformate",
        only appears once in the model.

        """

        from rmgpy.reaction import Reaction
        from rmgpy.molecule import Molecule
        folder = os.path.join(os.path.dirname(rmgpy.__file__),'tools/data/generate/duplicates')
        
        inputFile = os.path.join(folder,'input.py')

        rmg = RMG()
        rmg = execute(rmg, inputFile, folder)

        self.assertIsNotNone(rmg)
        
        rxnFlagged = Reaction(reactants=[Molecule(SMILES='[CH]=O'),Molecule(SMILES='C=O')],
                       products=[Molecule(SMILES='[CH2]OC=O')])

        count = 0
        for reaction in rmg.reactionModel.core.reactions:
            if reaction.isIsomorphic(rxnFlagged):
                count += 1

        self.assertEquals(count, 1)

        shutil.rmtree(os.path.join(folder,'pdep'))
Esempio n. 8
0
    def testInitialSpecies(self):
        " Test we can check whether the solvent is listed as one of the initial species in various scenarios "

        # Case 1. when SMILES for solvent is available, the molecular structures of the initial species and the solvent
        # are compared to check whether the solvent is in the initial species list

        # Case 1-1: the solvent water is not in the initialSpecies list, so it raises Exception
        rmg=RMG()
        rmg.initialSpecies = []
        solute = Species(label='n-octane', molecule=[Molecule().fromSMILES('C(CCCCC)CC')])
        rmg.initialSpecies.append(solute)
        rmg.solvent = 'water'
        solventStructure = Species().fromSMILES('O')
        self.assertRaises(Exception, self.database.checkSolventinInitialSpecies, rmg, solventStructure)

        # Case 1-2: the solvent is now octane and it is listed as the initialSpecies. Although the string
        # names of the solute and the solvent are different, because the solvent SMILES is provided,
        # it can identify the 'n-octane' as the solvent
        rmg.solvent = 'octane'
        solventStructure = Species().fromSMILES('CCCCCCCC')
        self.database.checkSolventinInitialSpecies(rmg, solventStructure)
        self.assertTrue(rmg.initialSpecies[0].isSolvent)

        # Case 2: the solvent SMILES is not provided. In this case, it can identify the species as the
        # solvent by looking at the string name.

        # Case 2-1: Since 'n-octane and 'octane' are not equal, it raises Exception
        solventStructure = None
        self.assertRaises(Exception, self.database.checkSolventinInitialSpecies, rmg, solventStructure)

        # Case 2-2: The label 'n-ocatne' is corrected to 'octane', so it is identified as the solvent
        rmg.initialSpecies[0].label = 'octane'
        self.database.checkSolventinInitialSpecies(rmg, solventStructure)
        self.assertTrue(rmg.initialSpecies[0].isSolvent)
Esempio n. 9
0
    def test_liquid_input_reading(self):
        """
        Check if constant concentration condition is well handled. 
        From input file reading to information storage in liquid reactor object.
        """
        rmg = RMG()
        rmg.input_file = os.path.join(os.path.dirname(rmgpy.__file__),
                                      'solver', 'files',
                                      'liquid_phase_constSPC', 'input.py')
        rmg.initialize()

        for index, reactionSystem in enumerate(rmg.reaction_systems):
            self.assertIsNotNone(
                reactionSystem.const_spc_names,
                'Reactor should contain constant species name and indices after few steps'
            )
            self.assertIsNotNone(
                reactionSystem.const_spc_indices,
                'Reactor should contain constant species indices in the core species array'
            )
            self.assertIs(
                reactionSystem.const_spc_names[0],
                rmg.reaction_model.core.species[
                    reactionSystem.const_spc_indices[0]].label,
                'The constant species name from the reaction model and constantSPCnames should be equal'
            )
Esempio n. 10
0
def setUpModule():
    """
    A method that is run before the class.
    """
    # set-up RMG object and get global rmg object in input.py file
    # so methods can be tested
    global rmg
    rmg = RMG()
    inp.set_global_rmg(rmg)
Esempio n. 11
0
def main():
    # Parse the command-line arguments (requires the argparse module)
    # args = parse_command_line_arguments()
    # AJ: change path to intended input file
    # args = parse_command_line_arguments(["/Users/agnes/Documents/Software/RMG/RMG-Py/examples/rmg/superminimal/input.py"])
    args = parse_command_line_arguments(
        ["./examples/rmg/superminimal/input.py"])

    if args.postprocess:
        print "Postprocessing the profiler statistics (will be appended to RMG.log)"
    else:
        # Initialize the logging system (resets the RMG.log file)
        level = logging.INFO
        if args.debug:
            level = 0
        elif args.verbose:
            level = logging.DEBUG
        elif args.quiet:
            level = logging.WARNING
        initializeLog(level, os.path.join(args.output_directory, 'RMG.log'))

    logging.info(rmgpy.settings.report())

    kwargs = {
        'restart': args.restart,
        'walltime': args.walltime,
        'kineticsdatastore': args.kineticsdatastore
    }

    if args.profile:
        import cProfile
        global_vars = {}
        local_vars = {
            'inputFile': args.file,
            'output_dir': args.output_directory,
            'kwargs': kwargs,
            'RMG': RMG
        }

        command = """rmg = RMG(inputFile=inputFile, outputDirectory=output_dir); rmg.execute(**kwargs)"""

        stats_file = os.path.join(args.output_directory, 'RMG.profile')
        print("Running under cProfile")
        if not args.postprocess:
            # actually run the program!
            cProfile.runctx(command, global_vars, local_vars, stats_file)
        # postprocess the stats
        log_file = os.path.join(args.output_directory, 'RMG.log')
        processProfileStats(stats_file, log_file)
        makeProfileGraph(stats_file)

    else:

        rmg = RMG(inputFile=args.file, outputDirectory=args.output_directory)
        rmg.execute(**kwargs)
Esempio n. 12
0
def main():
    # Parse the command-line arguments (requires the argparse module)
    args = parse_command_line_arguments()

    if args.postprocess:
        logging.info(
            "Postprocessing the profiler statistics (will be appended to RMG.log)"
        )
    else:
        # Initialize the logging system (resets the RMG.log file)
        level = logging.INFO
        if args.debug:
            level = 0
        elif args.verbose:
            level = logging.DEBUG
        elif args.quiet:
            level = logging.WARNING
        initialize_log(level, os.path.join(args.output_directory, 'RMG.log'))

    logging.info(rmgpy.settings.report())

    kwargs = {
        'restart': args.restart,
        'walltime': args.walltime,
        'maxproc': args.maxproc,
        'kineticsdatastore': args.kineticsdatastore
    }

    if args.profile:
        import cProfile
        global_vars = {}
        local_vars = {
            'inputFile': args.file,
            'output_dir': args.output_directory,
            'kwargs': kwargs,
            'RMG': RMG
        }

        command = """rmg = RMG(input_file=inputFile, output_directory=output_dir); rmg.execute(**kwargs)"""

        stats_file = os.path.join(args.output_directory, 'RMG.profile')
        print("Running under cProfile")
        if not args.postprocess:
            # actually run the program!
            cProfile.runctx(command, global_vars, local_vars, stats_file)
        # postprocess the stats
        log_file = os.path.join(args.output_directory, 'RMG.log')
        process_profile_stats(stats_file, log_file)
        make_profile_graph(stats_file)

    else:

        rmg = RMG(input_file=args.file, output_directory=args.output_directory)
        rmg.execute(**kwargs)
Esempio n. 13
0
    def test_check_for_existing_species_for_bi_aromatics(self):
        """
        Test RMG check_for_existing_species can correctly check isomorphism for biaromatics.
        In this test, DPP is a species already stored in rmg species_dict, mol_test is a newly
        created molecule which has one kekulized benzene ring and one double_bond-single_bond
        benzene ring.
        """

        rmg_test = RMG()
        rmg_test.reaction_model = CoreEdgeReactionModel()
        DPP = Species().from_smiles('C1=CC=C(C=C1)CCCC1C=CC=CC=1')
        DPP.generate_resonance_structures()
        formula = DPP.molecule[0].get_formula()
        if formula in rmg_test.reaction_model.species_dict:
            rmg_test.reaction_model.species_dict[formula].append(DPP)
        else:
            rmg_test.reaction_model.species_dict[formula] = [DPP]

        mol_test = Molecule().from_adjacency_list(
"""
1     C u0 p0 c0 {2,S} {3,S} {16,S} {17,S}
2     C u0 p0 c0 {1,S} {4,S} {18,S} {19,S}
3     C u0 p0 c0 {1,S} {5,S} {20,S} {21,S}
4     C u0 p0 c0 {2,S} {6,B} {7,B}
5     C u0 p0 c0 {3,S} {8,D} {9,S}
6     C u0 p0 c0 {4,B} {10,B} {22,S}
7     C u0 p0 c0 {4,B} {12,B} {24,S}
8     C u0 p0 c0 {5,D} {14,S} {27,S}
9     C u0 p0 c0 {5,S} {15,D} {28,S}
10    C u0 p0 c0 {6,B} {11,B} {23,S}
11    C u0 p0 c0 {10,B} {12,B} {25,S}
12    C u0 p0 c0 {7,B} {11,B} {26,S}
13    C u0 p0 c0 {14,D} {15,S} {29,S}
14    C u0 p0 c0 {8,S} {13,D} {30,S}
15    C u0 p0 c0 {9,D} {13,S} {31,S}
16    H u0 p0 c0 {1,S}
17    H u0 p0 c0 {1,S}
18    H u0 p0 c0 {2,S}
19    H u0 p0 c0 {2,S}
20    H u0 p0 c0 {3,S}
21    H u0 p0 c0 {3,S}
22    H u0 p0 c0 {6,S}
23    H u0 p0 c0 {10,S}
24    H u0 p0 c0 {7,S}
25    H u0 p0 c0 {11,S}
26    H u0 p0 c0 {12,S}
27    H u0 p0 c0 {8,S}
28    H u0 p0 c0 {9,S}
29    H u0 p0 c0 {13,S}
30    H u0 p0 c0 {14,S}
31    H u0 p0 c0 {15,S}
""")
        spec = rmg_test.reaction_model.check_for_existing_species(mol_test)
        self.assertIsNotNone(spec)
Esempio n. 14
0
    def setUpClass(cls):
        """A function that is run ONCE before all unit tests in this class."""
        cls.testDir = os.path.join(originalPath, 'rmg', 'test_data',
                                   'restartTest')
        cls.outputDir = os.path.join(cls.testDir, 'output_no_filters')
        cls.databaseDirectory = settings['database.directory']

        os.mkdir(cls.outputDir)
        initialize_log(logging.INFO, os.path.join(cls.outputDir, 'RMG.log'))

        cls.rmg = RMG(input_file=os.path.join(cls.testDir,
                                              'restart_no_filters.py'),
                      output_directory=os.path.join(cls.outputDir))
Esempio n. 15
0
    def test(self):
        folder = os.path.join(os.path.dirname(rmgpy.__file__), 'tools/data/generate')

        input_file = os.path.join(folder, 'input.py')

        rmg = RMG(input_file=input_file, output_directory=folder)
        rmg = execute(rmg)

        self.assertIsNotNone(rmg)
        self.assertIsNotNone(rmg.reaction_model.output_species_list)
        self.assertIsNotNone(rmg.reaction_model.output_reaction_list)

        shutil.rmtree(os.path.join(folder, 'pdep'))
Esempio n. 16
0
    def setUpClass(cls):
        """
        A method that is run before each unit test in this class.
        """
        # set-up RMG object
        cls.rmg = RMG()

        # load kinetic database and forbidden structures
        cls.rmg.database = RMGDatabase()
        path = os.path.join(settings['database.directory'])

        # forbidden structure loading
        cls.rmg.database.load_thermo(os.path.join(path, 'thermo'))
Esempio n. 17
0
def generate_rmg_model(input_file, output_directory):
    """
    Generate the RMG-Py model NOT containing any non-normal isotopomers.

    Returns created RMG object.
    """
    initialize_log(logging.INFO, os.path.join(output_directory, 'RMG.log'))
    # generate mechanism:
    rmg = RMG(input_file=os.path.abspath(input_file),
              output_directory=os.path.abspath(output_directory))
    rmg.execute()

    return rmg
Esempio n. 18
0
    def setUp(self):
        """
        Set up an RMG object
        """

        folder = os.path.join(os.getcwd(), 'rmgpy/output')
        if not os.path.isdir(folder):
            os.mkdir(folder)

        self.rmg = RMG(outputDirectory=folder)
        self.rmg.reactionModel = CoreEdgeReactionModel()

        self.rmg.saveEverything()
Esempio n. 19
0
    def test(self):
        folder = os.path.join(os.path.dirname(rmgpy.__file__),'tools/data/generate')
        
        inputFile = os.path.join(folder,'input.py')
        
        rmg = RMG()
        rmg = execute(rmg, inputFile, folder)

        self.assertIsNotNone(rmg)
        self.assertIsNotNone(rmg.reactionModel.outputSpeciesList)
        self.assertIsNotNone(rmg.reactionModel.outputReactionList)


        shutil.rmtree(os.path.join(folder,'pdep'))
Esempio n. 20
0
def loadRMGPyJob(inputFile, chemkinFile, speciesDict=None):
    """
    Load the results of an RMG-Py job generated from the given `inputFile`.
    """

    # Load the specified RMG input file
    rmg = RMG()
    rmg.loadInput(inputFile)
    rmg.outputDirectory = os.path.abspath(os.path.dirname(inputFile))

    # Load the final Chemkin model generated by RMG
    speciesList, reactionList = loadChemkinFile(chemkinFile,
                                                speciesDict,
                                                readComments=False)
    assert speciesList, reactionList

    # print 'labels from species in the chemkin file:'
    # for spc in speciesList:
    #     print spc.label

    # Map species in input file to corresponding species in Chemkin file
    speciesDict = {}
    assert rmg.initialSpecies
    # print 'initial species: ', rmg.initialSpecies

    #label of initial species must correspond to the label in the chemkin file WITHOUT parentheses.
    #E.g.: "JP10" not "JP10(1)"
    for spec0 in rmg.initialSpecies:
        for species in speciesList:
            if species.label == spec0.label:
                speciesDict[spec0] = species
                break

    assert speciesDict
    # Replace species in input file with those in Chemkin file
    for reactionSystem in rmg.reactionSystems:
        reactionSystem.initialMoleFractions = dict([
            (speciesDict[spec], frac)
            for spec, frac in reactionSystem.initialMoleFractions.iteritems()
        ])
        for t in reactionSystem.termination:
            if isinstance(t, TerminationConversion):
                t.species = speciesDict[t.species]

    # Set reaction model to match model loaded from Chemkin file
    rmg.reactionModel.core.species = speciesList
    rmg.reactionModel.core.reactions = reactionList

    # print 'core: ', speciesList
    return rmg
Esempio n. 21
0
    def setUpClass(cls):
        """A function that is run ONCE before all unit tests in this class."""
        cls.testDir = os.path.join(originalPath, 'rmg', 'test_data',
                                   'mainTest')
        cls.outputDir = os.path.join(cls.testDir, 'output')
        cls.databaseDirectory = settings['database.directory']

        os.mkdir(os.path.join(cls.testDir, cls.outputDir))

        cls.max_iter = 10

        cls.rmg = RMG(input_file=os.path.join(cls.testDir,
                                              'superminimal_input.py'),
                      output_directory=cls.outputDir)

        cls.rmg.execute(max_iterations=cls.max_iter)
Esempio n. 22
0
 def setUpClass(cls):
     """
     A function run ONCE before all unit tests in this class.
     """
     cls.rmg = RMG()
     rmgpy.rmg.input.rmg = cls.rmg
     rmgpy.rmg.input.generatedSpeciesConstraints(
         maximumCarbonAtoms=2,
         maximumOxygenAtoms=1,
         maximumNitrogenAtoms=1,
         maximumSiliconAtoms=1,
         maximumSulfurAtoms=1,
         maximumHeavyAtoms=3,
         maximumRadicalElectrons=2,
         maximumSingletCarbenes=1,
         maximumCarbeneRadicals=0,
     )
Esempio n. 23
0
    def setUp(self):
        """
        A method that is run before each unit test in this class.
        """
        # set-up RMG object
        self.rmg = RMG()

        # load kinetic database and forbidden structures
        self.rmg.database = RMGDatabase()
        path = os.path.join(settings['database.directory'])

        # forbidden structure loading
        self.rmg.database.loadForbiddenStructures(os.path.join(path, 'forbiddenStructures.py'))
        # kinetics family loading
        self.rmg.database.loadKinetics(os.path.join(path, 'kinetics'),
                                       kineticsFamilies=[TESTFAMILY],
                                       reactionLibraries=[]
                                       )
Esempio n. 24
0
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)
Esempio n. 25
0
def loadRMGPyJob(inputFile, chemkinFile, speciesDict):
    """
    Load the results of an RMG-Py job generated from the given `inputFile`.
    """
    import os.path
    from rmgpy.chemkin import getSpeciesIdentifier, loadChemkinFile
    from rmgpy.rmg.main import RMG
    from rmgpy.solver.base import TerminationTime, TerminationConversion

    # Load the specified RMG input file
    rmg = RMG()
    rmg.loadInput(inputFile)
    rmg.outputDirectory = os.path.abspath(os.path.dirname(inputFile))

    # Load the final Chemkin model generated by RMG
    speciesList, reactionList = loadChemkinFile(chemkinFile,
                                                speciesDict,
                                                readComments=False)

    # Map species in input file to corresponding species in Chemkin file
    speciesDict = {}

    #label of initial species must correspond to the label in the chemkin file WITHOUT parentheses.
    for spec0 in rmg.initialSpecies:
        for species in speciesList:
            if species.label == spec0.label:
                speciesDict[spec0] = species
                break

    # Replace species in input file with those in Chemkin file
    for reactionSystem in rmg.reactionSystems:
        reactionSystem.initialMoleFractions = dict([
            (speciesDict[spec], frac)
            for spec, frac in reactionSystem.initialMoleFractions.iteritems()
        ])
        for t in reactionSystem.termination:
            if isinstance(t, TerminationConversion):
                t.species = speciesDict[t.species]

    # Set reaction model to match model loaded from Chemkin file
    rmg.reactionModel.core.species = speciesList
    rmg.reactionModel.core.reactions = reactionList

    return rmg
Esempio n. 26
0
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)
Esempio n. 27
0
    def createOutput(self):
        """
        Generate output html file from the path containing chemkin and dictionary files.
        """

        import rmgpy.tools.generate_reactions as generate_reactions
        from rmgpy.rmg.main import initializeLog, RMG
        from rmgpy.chemkin import ChemkinWriter
        from rmgpy.rmg.output import OutputHTMLWriter

        inputFile = self.input
        output_directory = self.getDirname()

        rmg = RMG()
        # Add output listeners:
        rmg.attach(ChemkinWriter(output_directory))
        rmg.attach(OutputHTMLWriter(output_directory))

        generate_reactions.execute(rmg, inputFile, output_directory)
Esempio n. 28
0
    def setUpClass(cls):
        """A function that is run ONCE before all unit tests in this class."""
        cls.testDir = os.path.join(originalPath, 'rmg', 'test_data',
                                   'mainTest')
        cls.outputDir = 'output'
        cls.databaseDirectory = settings['database.directory']

        cls.seedKinetics = os.path.join(cls.databaseDirectory, 'kinetics',
                                        'libraries', 'testSeed')
        cls.seedKineticsEdge = os.path.join(cls.databaseDirectory, 'kinetics',
                                            'libraries', 'testSeed_edge')

        os.mkdir(os.path.join(cls.testDir, cls.outputDir))

        cls.rmg = RMG(input_file=os.path.join(cls.testDir, 'input.py'),
                      output_directory=os.path.join(cls.testDir,
                                                    cls.outputDir))

        cls.rmg.execute()
Esempio n. 29
0
def main():
    """
    Driver function that parses command line arguments and passes them to the execute function.
    """
    # Parse the command-line arguments (requires the argparse module)
    args = parseCommandLineArguments()

    # For output and scratch directories, if they are empty strings, set them
    # to match the input file location
    inputFile = args.file[0]

    inputDirectory = os.path.abspath(os.path.dirname(inputFile))

    if args.output_directory == '':
        args.output_directory = inputDirectory
    if args.scratch_directory == '':
        args.scratch_directory = inputDirectory
    
    # Initialize the logging system (resets the RMG.log file)
    level = logging.INFO
    if args.debug: level = 0
    elif args.verbose: level = logging.DEBUG
    elif args.quiet: level = logging.WARNING

    kwargs = {
            'scratch_directory': args.scratch_directory,
            'restart': args.restart,
            'walltime': args.walltime,
            'log': level,
            'kineticsdatastore': args.kineticsdatastore
    }

    initializeLog(level, os.path.join(args.output_directory,'RMG.log'))

    rmg = RMG(inputFile=inputFile, outputDirectory=args.output_directory)

    # Add output listeners:
    rmg.attach(ChemkinWriter(args.output_directory))
    rmg.attach(OutputHTMLWriter(args.output_directory))

    execute(rmg, **kwargs)
Esempio n. 30
0
    def test_library_reaction_enters_core(self):
        """
        Test that a reaction from a Reaction Library enters the core
        right after the initialization step if all the input species are 
        present in that reaction.
        
        The following reaction from the Methylformate library
        
        HCjO + CH2O <=> Fmoml
        
        should appear in the model if HCjO, CH2O and Fmoml are all used as input species
        """
        from rmgpy.reaction import Reaction
        from rmgpy.molecule import Molecule
        folder = os.path.join(os.path.dirname(rmgpy.__file__),
                              'tools/data/generate/libraryReaction')

        input_file = os.path.join(folder, 'input.py')

        rmg = RMG(input_file=input_file, output_directory=folder)
        rmg = execute(rmg)

        self.assertIsNotNone(rmg)

        # Assert that the flagged reaction occurs
        rxn_flagged = Reaction(
            reactants=[Molecule(smiles='[CH]=O'),
                       Molecule(smiles='C=O')],
            products=[Molecule(smiles='[CH2]OC=O')])

        count = 0
        for reaction in rmg.reaction_model.core.reactions:
            if reaction.is_isomorphic(rxn_flagged):
                count += 1

        self.assertEquals(count, 1)

        # Assert that the core only has 1 reaction
        self.assertEquals(len(rmg.reaction_model.core.reactions), 1)
        shutil.rmtree(os.path.join(folder, 'pdep'))
        os.remove(os.path.join(folder, 'restart_from_seed.py'))