示例#1
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
示例#2
0
class TestExecutionStatsWriter(unittest.TestCase):
    """
    Contains unit tests of the ExecutionStatsWriter.
    """

    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()

    def test_save(self):
        """
        Tests if the statistics output file can be found.
        """
        
        folder = self.rmg.outputDirectory
        
        writer = ExecutionStatsWriter(folder)
        writer.update(self.rmg)

        statsfile = os.path.join(folder,'statistics.xls')

        self.assertTrue(os.path.isfile(statsfile))

    def tearDown(self):
        shutil.rmtree(self.rmg.outputDirectory)
示例#3
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)
示例#4
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'))
示例#5
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')
示例#6
0
class TestExecutionStatsWriter(unittest.TestCase):
    """
    Contains unit tests of the ExecutionStatsWriter.
    """
    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()

    def test_save(self):
        """
        Tests if the statistics output file can be found.
        """

        folder = self.rmg.outputDirectory

        writer = ExecutionStatsWriter(folder)
        writer.update(self.rmg)

        statsfile = os.path.join(folder, 'statistics.xls')

        self.assertTrue(os.path.isfile(statsfile))

    def tearDown(self):
        shutil.rmtree(self.rmg.outputDirectory)
示例#7
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
示例#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)
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)
示例#10
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'
            )
示例#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)
示例#12
0
文件: restart.py 项目: nsm120/RMG-Py
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
    rmg_restart.trimolecularReact = rmg.trimolecularReact
    if rmg.filterReactions:
        rmg_restart.unimolecularThreshold = rmg.unimolecularThreshold
        rmg_restart.bimolecularThreshold = rmg.bimolecularThreshold
        rmg_restart.trimolecularThreshold = rmg.trimolecularThreshold

    f = open(path, 'wb')
    cPickle.dump(rmg_restart, f, cPickle.HIGHEST_PROTOCOL)
    f.close()
示例#13
0
文件: loader.py 项目: alongd/RMG-Py
def loadRMGPyJob(inputFile, chemkinFile=None, speciesDict=None, generateImages=True):
    """
    Load the results of an RMG-Py job generated from the given `inputFile`.
    """
    from rmgpy.rmg.main import RMG
    
    # 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
    if not chemkinFile:
        chemkinFile = os.path.join(os.path.dirname(inputFile), 'chemkin', 'chem.inp')
    if not speciesDict:
        speciesDict = os.path.join(os.path.dirname(inputFile), 'chemkin', 'species_dictionary.txt')
    speciesList, reactionList = loadChemkinFile(chemkinFile, speciesDict)
    
    # Map species in input file to corresponding species in Chemkin file
    speciesDict = {}
    for spec0 in rmg.initialSpecies:
        for species in speciesList:
            if species.isIsomorphic(spec0):
                speciesDict[spec0] = species
                break
            
    # Generate flux pairs for each reaction if needed
    for reaction in reactionList:
        if not reaction.pairs: reaction.generatePairs()
    
    # 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]
        reactionSystem.sensitiveSpecies = [speciesDict[spec] for spec in reactionSystem.sensitiveSpecies]
    
    # Set reaction model to match model loaded from Chemkin file
    rmg.reactionModel.core.species = speciesList
    rmg.reactionModel.core.reactions = reactionList

    # Generate species images
    if generateImages:
        speciesPath = os.path.join(os.path.dirname(inputFile), 'species')
        try:
            os.mkdir(speciesPath)
        except OSError:
            pass
        for species in speciesList:
            path = os.path.join(speciesPath, '{0!s}.png'.format(species))
            if not os.path.exists(path):
                species.molecule[0].draw(str(path))
    
    return rmg
示例#14
0
文件: rmgTest.py 项目: zhedian/RMG-Py
    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)
示例#15
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)
def generate_RMG_model(inputFile, outputDirectory):
    """
    Generate the RMG-Py model NOT containing any non-normal isotopomers.

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

    return rmg
示例#17
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()
示例#18
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
示例#19
0
文件: rmg.py 项目: cainja/RMG-Py
def main():
    # Parse the command-line arguments (requires the argparse module)
    args = parse_command_line_arguments()

    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)
示例#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
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.)
    """
    warnings.warn("The saveRestartFile is no longer supported and may be"
                  " removed in version 2.3.", DeprecationWarning)
    # 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
    rmg_restart.trimolecularReact = rmg.trimolecularReact
    if rmg.filterReactions:
        rmg_restart.unimolecularThreshold = rmg.unimolecularThreshold
        rmg_restart.bimolecularThreshold = rmg.bimolecularThreshold
        rmg_restart.trimolecularThreshold = rmg.trimolecularThreshold
    
    f = open(path, 'wb')
    cPickle.dump(rmg_restart, f, cPickle.HIGHEST_PROTOCOL)
    f.close()
 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')
示例#23
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'))
示例#24
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'))
示例#25
0
 def test_liquidInputReading(self):
     """
     Check if constant concentration condition is well handled. 
     From input file reading to information storage in liquid reactor object.
     """
     rmg = RMG()
     rmg.inputFile = os.path.join('rmgpy', 'solver', 'files', 'liquid_phase_constSPC', 'input.py')
     rmg.initialize()
         
     for index, reactionSystem in enumerate(rmg.reactionSystems):
         self.assertIsNotNone(reactionSystem.constSPCNames,
                              'Reactor should contain constant species name and indices after few steps')
         self.assertIsNotNone(reactionSystem.constSPCIndices,
                              'Reactor should contain constant species indices in the core species array')
         self.assertIs(reactionSystem.constSPCNames[0],
                       rmg.reactionModel.core.species[reactionSystem.constSPCIndices[0]].label,
                       'The constant species name from the reaction model and constantSPCnames should be equal')
示例#26
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
示例#27
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)
示例#28
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
示例#29
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)
示例#30
0
def load():
    """
    A method that is run before each unit test in this class.
    """
    tearDown()
    # 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.loadForbiddenStructures(os.path.join(path, 'forbiddenStructures.py'))
    # kinetics family loading
    rmg.database.loadKinetics(os.path.join(path, 'kinetics'),
                                   kineticsFamilies=[TESTFAMILY],
                                   reactionLibraries=[]
                                   )
示例#31
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)
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,
    }

    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)
示例#33
0
def load():
    """
    A method that is run before each unit test in this class.
    """
    tearDown()
    # 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.loadForbiddenStructures(os.path.join(path, 'forbiddenStructures.py'))
    # kinetics family loading
    rmg.database.loadKinetics(os.path.join(path, 'kinetics'),
                                   kineticsFamilies=[TESTFAMILY],
                                   reactionLibraries=[]
                                   )
示例#34
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)
示例#35
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'))
示例#36
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)
示例#37
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
示例#38
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()
示例#39
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'))
示例#40
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'))
示例#41
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))
示例#42
0
def loadRMGPyJob(inputFile):
    """
    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
    chemkinFile = os.path.join(os.path.dirname(inputFile), 'chemkin', 'chem.inp')
    speciesDict = os.path.join(os.path.dirname(inputFile), 'chemkin', 'species_dictionary.txt')
    speciesList, reactionList = loadChemkinFile(chemkinFile, speciesDict)
    
    # Map species in input file to corresponding species in Chemkin file
    speciesDict = {}
    for spec0 in rmg.initialSpecies:
        for species in speciesList:
            if species.isIsomorphic(spec0):
                speciesDict[spec0] = species
                break
            
    # Generate flux pairs for each reaction if needed
    for reaction in reactionList:
        if not reaction.pairs: reaction.generatePairs()
    
    # 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
示例#43
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
        
    # 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'))
示例#44
0
    def setUpClass(cls):
        """
        A method that is run before each unit test in this class.
        """
        test_family = 'H_Abstraction'

        # set-up RMG object
        rmg = RMG()

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

        # kinetics family loading
        rmg.database.load_kinetics(os.path.join(path, 'kinetics'),
                                   kinetics_families=[test_family],
                                   reaction_libraries=[])
        # load empty forbidden structures to avoid any dependence on forbidden structures
        # for these tests
        for family in rmg.database.kinetics.families.values():
            family.forbidden = ForbiddenStructures()
        rmg.database.forbidden_structures = ForbiddenStructures()
示例#45
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'))
示例#46
0
    def test_liquidInputReading(self):
        """
        Check if constant concentration condition is well handled. 
        From input file reading to information storage in liquid reactor object.
        """
        rmg = RMG()

        ##use the liquid phase example to load every input parameters
        inp = os.path.join("examples","rmg","liquid_phase_constSPC","input.py") #In order to work on every system, use of os.path
        rmg.inputFile = inp

        rmg.initialize()
            
        if rmg.solvent is not None:
            ##call the function to identify indices in the solver
            for index, reactionSystem in enumerate(rmg.reactionSystems):
                    if reactionSystem.constSPCNames is not None: #if no constant species provided do nothing
                        reactionSystem.get_constSPCIndices(rmg.reactionModel.core.species)        
                   
        for index, reactionSystem in enumerate(rmg.reactionSystems):
            self.assertIsNotNone(reactionSystem.constSPCNames,"""this input \"{0} \" contain constant SPC, reactor should contain its name and its indices after few steps""")
            self.assertIsNotNone(reactionSystem.constSPCIndices,"""this input \"{0} \" contain constant SPC, reactor should contain its corresponding indices in the core species array""")
            self.assertIs(reactionSystem.constSPCNames[0],rmg.reactionModel.core.species[reactionSystem.constSPCIndices[0]].label,"The constant species name from reaction model and constantSPCnames has to be equals")            
示例#47
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)
    def setUpClass(cls):
        """
        A method that is run before each unit test in this class.
        """
        TESTFAMILY = 'H_Abstraction'

        # set-up RMG object
        rmg = RMG()

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


        # kinetics family loading
        rmg.database.loadKinetics(os.path.join(path, 'kinetics'),
                                       kineticsFamilies=[TESTFAMILY],
                                       reactionLibraries=[]
                                       )
        #load empty forbidden structures to avoid any dependence on forbidden structures
        #for these tests
        for family in rmg.database.kinetics.families.values():
            family.forbidden = ForbiddenStructures()
        rmg.database.forbiddenStructures = ForbiddenStructures()
示例#49
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)
示例#50
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,
     )
示例#51
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.load_forbidden_structures(
            os.path.join(path, 'forbiddenStructures.py'))
        # kinetics family loading
        self.rmg.database.load_kinetics(os.path.join(path, 'kinetics'),
                                        kinetics_families=TESTFAMILIES,
                                        reaction_libraries=[])
示例#52
0
    def saveForm(self, posted, form):
        """
        Save form data into input.py file specified by the path.
        """
        # Clean past history
        self.rmg = RMG()

        # Databases
        # self.rmg.databaseDirectory = settings['database.directory']
        self.rmg.thermoLibraries = []
        if posted.thermo_libraries.all():
            self.rmg.thermoLibraries = [item.thermolib.encode() for item in posted.thermo_libraries.all()]
        self.rmg.reactionLibraries = []
        self.rmg.seedMechanisms = []
        if posted.reaction_libraries.all():
            for item in posted.reaction_libraries.all():
                if not item.seedmech and not item.edge:
                    self.rmg.reactionLibraries.append((item.reactionlib.encode(), False))
                elif not item.seedmech:
                    self.rmg.reactionLibraries.append((item.reactionlib.encode(), True))
                else:
                    self.rmg.seedMechanisms.append(item.reactionlib.encode())
        self.rmg.statmechLibraries = []
        self.rmg.kineticsDepositories = "default"
        self.rmg.kineticsFamilies = "default"
        self.rmg.kineticsEstimator = "rate rules"

        # Species
        self.rmg.initialSpecies = []
        speciesDict = {}
        initialMoleFractions = {}
        self.rmg.reactionModel = CoreEdgeReactionModel()
        for item in posted.reactor_species.all():
            structure = Molecule().fromAdjacencyList(item.adjlist.encode())
            spec, isNew = self.rmg.reactionModel.makeNewSpecies(
                structure, label=item.name.encode(), reactive=False if item.inert else True
            )
            self.rmg.initialSpecies.append(spec)
            speciesDict[item.name.encode()] = spec
            initialMoleFractions[spec] = item.molefrac

        # Reactor systems
        self.rmg.reactionSystems = []
        for item in posted.reactor_systems.all():
            T = Quantity(item.temperature, item.temperature_units.encode())
            P = Quantity(item.pressure, item.pressure_units.encode())
            termination = []
            if item.conversion:
                termination.append(TerminationConversion(speciesDict[item.species.encode()], item.conversion))
            termination.append(TerminationTime(Quantity(item.terminationtime, item.time_units.encode())))
            # Sensitivity Analysis
            sensitiveSpecies = []
            if item.sensitivity:
                if isinstance(item.sensitivity.encode(), str):
                    sensitivity = item.sensitivity.encode().split(",").strip()
                for spec in sensitivity:
                    sensitiveSpecies.append(speciesDict[spec])
            system = SimpleReactor(T, P, initialMoleFractions, termination, sensitiveSpecies, item.sensitivityThreshold)
            self.rmg.reactionSystems.append(system)

        # Simulator tolerances
        self.rmg.absoluteTolerance = form.cleaned_data["simulator_atol"]
        self.rmg.relativeTolerance = form.cleaned_data["simulator_rtol"]
        self.rmg.sensitivityAbsoluteTolerance = form.cleaned_data["simulator_sens_atol"]
        self.rmg.sensitivityRelativeTolerance = form.cleaned_data["simulator_sens_rtol"]
        self.rmg.fluxToleranceKeepInEdge = form.cleaned_data["toleranceKeepInEdge"]
        self.rmg.fluxToleranceMoveToCore = form.cleaned_data["toleranceMoveToCore"]
        self.rmg.fluxToleranceInterrupt = form.cleaned_data["toleranceInterruptSimulation"]
        self.rmg.maximumEdgeSpecies = form.cleaned_data["maximumEdgeSpecies"]

        # Pressure Dependence
        pdep = form.cleaned_data["pdep"].encode()
        if pdep != "off":
            self.rmg.pressureDependence = PressureDependenceJob(network=None)
            self.rmg.pressureDependence.method = pdep

            # Process interpolation model
            if form.cleaned_data["interpolation"].encode() == "chebyshev":
                self.rmg.pressureDependence.interpolationModel = (
                    form.cleaned_data["interpolation"].encode(),
                    form.cleaned_data["temp_basis"],
                    form.cleaned_data["p_basis"],
                )
            else:
                self.rmg.pressureDependence.interpolationModel = (form.cleaned_data["interpolation"].encode(),)

            # Temperature and pressure range
            self.rmg.pressureDependence.Tmin = Quantity(
                form.cleaned_data["temp_low"], form.cleaned_data["temprange_units"].encode()
            )
            self.rmg.pressureDependence.Tmax = Quantity(
                form.cleaned_data["temp_high"], form.cleaned_data["temprange_units"].encode()
            )
            self.rmg.pressureDependence.Tcount = form.cleaned_data["temp_interp"]
            self.rmg.pressureDependence.generateTemperatureList()
            self.rmg.pressureDependence.Pmin = Quantity(
                form.cleaned_data["p_low"], form.cleaned_data["prange_units"].encode()
            )
            self.rmg.pressureDependence.Pmax = Quantity(
                form.cleaned_data["p_high"], form.cleaned_data["prange_units"].encode()
            )
            self.rmg.pressureDependence.Pcount = form.cleaned_data["p_interp"]
            self.rmg.pressureDependence.generatePressureList()

            # Process grain size and count
            self.rmg.pressureDependence.grainSize = Quantity(
                form.cleaned_data["maximumGrainSize"], form.cleaned_data["grainsize_units"].encode()
            )
            self.rmg.pressureDependence.grainCount = form.cleaned_data["minimumNumberOfGrains"]

            self.rmg.pressureDependence.maximumAtoms = form.cleaned_data["maximumAtoms"]
        # Additional Options
        self.rmg.units = "si"
        self.rmg.saveRestartPeriod = (
            Quantity(form.cleaned_data["saveRestartPeriod"], form.cleaned_data["saveRestartPeriodUnits"].encode())
            if form.cleaned_data["saveRestartPeriod"]
            else None
        )
        self.rmg.generateOutputHTML = form.cleaned_data["generateOutputHTML"]
        self.rmg.generatePlots = form.cleaned_data["generatePlots"]
        self.rmg.saveSimulationProfiles = form.cleaned_data["saveSimulationProfiles"]
        self.rmg.saveEdgeSpecies = form.cleaned_data["saveEdgeSpecies"]
        self.rmg.verboseComments = form.cleaned_data["verboseComments"]

        # Species Constraints
        speciesConstraints = form.cleaned_data["speciesConstraints"]
        if speciesConstraints == "on":
            allowed = []
            if form.cleaned_data["allowed_inputSpecies"]:
                allowed.append("input species")
            if form.cleaned_data["allowed_seedMechanisms"]:
                allowed.append("seed mechanisms")
            if form.cleaned_data["allowed_reactionLibraries"]:
                allowed.append("reaction libraries")
            self.rmg.speciesConstraints["allowed"] = allowed
            self.rmg.speciesConstraints["maximumCarbonAtoms"] = form.cleaned_data["maximumCarbonAtoms"]
            self.rmg.speciesConstraints["maximumHydrogenAtoms"] = form.cleaned_data["maximumHydrogenAtoms"]
            self.rmg.speciesConstraints["maximumOxygenAtoms"] = form.cleaned_data["maximumOxygenAtoms"]
            self.rmg.speciesConstraints["maximumNitrogenAtoms"] = form.cleaned_data["maximumNitrogenAtoms"]
            self.rmg.speciesConstraints["maximumSiliconAtoms"] = form.cleaned_data["maximumSiliconAtoms"]
            self.rmg.speciesConstraints["maximumSulfurAtoms"] = form.cleaned_data["maximumSulfurAtoms"]
            self.rmg.speciesConstraints["maximumHeavyAtoms"] = form.cleaned_data["maximumHeavyAtoms"]
            self.rmg.speciesConstraints["maximumRadicalElectrons"] = form.cleaned_data["maximumRadicalElectrons"]
            self.rmg.speciesConstraints["allowSingletO2"] = form.cleaned_data["allowSingletO2"]

        # Quantum Calculations
        quantumCalc = form.cleaned_data["quantumCalc"]
        if quantumCalc == "on":
            from rmgpy.qm.main import QMCalculator

            self.rmg.quantumMechanics = QMCalculator(
                software=form.cleaned_data["software"].encode(),
                method=form.cleaned_data["method"].encode(),
                fileStore=form.cleaned_data["fileStore"].encode(),
                scratchDirectory=form.cleaned_data["scratchDirectory"].encode(),
                onlyCyclics=form.cleaned_data["onlyCyclics"],
                maxRadicalNumber=form.cleaned_data["maxRadicalNumber"],
            )

        # Save the input.py file
        self.rmg.saveInput(self.savepath)
示例#53
0
文件: rmg.py 项目: PengZhang13/RMG-Py
        'restart': args.restart,
        'walltime': args.walltime,
        }

    if args.profile:
        import cProfile, sys, pstats, os
        global_vars = {}
        local_vars = {
            'inputFile': inputFile, 
            'output_dir': output_dir, 
            '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=inputFile, outputDirectory=output_dir)
        rmg.execute(**kwargs)
示例#54
0
    def saveForm(self, posted, form):
        """
        Save form data into input.py file specified by the path.
        """
        # Clean past history
        self.rmg = RMG()
        
        # Databases
        #self.rmg.databaseDirectory = settings['database.directory']
        self.rmg.thermoLibraries  = []
        if posted.thermo_libraries.all():
            self.rmg.thermoLibraries = [item.thermolib.encode() for item in posted.thermo_libraries.all()]
        self.rmg.reactionLibraries = []
        self.rmg.seedMechanisms = []
        if posted.reaction_libraries.all():
            for item in posted.reaction_libraries.all():
                if not item.seedmech and not item.edge:
                    self.rmg.reactionLibraries.append((item.reactionlib.encode(), False))
                elif not item.seedmech:
                    self.rmg.reactionLibraries.append((item.reactionlib.encode(), True))
                else:
                    self.rmg.seedMechanisms.append(item.reactionlib.encode())
        self.rmg.statmechLibraries = []
        self.rmg.kineticsDepositories = ['training']
        self.rmg.kineticsFamilies = ['!Intra_Disproportionation']        
        self.rmg.kineticsEstimator = 'rate rules'
        
        # Species
        self.rmg.initialSpecies = []
        speciesDict = {}
        initialMoleFractions = {}
        self.rmg.reactionModel = CoreEdgeReactionModel()
        for item in posted.reactor_species.all():
            structure = Molecule().fromAdjacencyList(item.adjlist.encode())
            spec, isNew = self.rmg.reactionModel.makeNewSpecies(structure, label = item.name.encode(), reactive = False if item.inert else True)
            self.rmg.initialSpecies.append(spec)
            speciesDict[item.name.encode()] = spec
            initialMoleFractions[spec] = item.molefrac
            
        # Reactor systems
        self.rmg.reactionSystems = []
        for item in posted.reactor_systems.all():
            T = Quantity(item.temperature, item.temperature_units.encode())
            P = Quantity(item.pressure, item.pressure_units.encode())            
            termination = []
            if item.conversion:
                termination.append(TerminationConversion(speciesDict[item.species.encode()], item.conversion))
            termination.append(TerminationTime(Quantity(item.terminationtime, item.time_units.encode())))
            system = SimpleReactor(T, P, initialMoleFractions, termination)
            self.rmg.reactionSystems.append(system)
    
        # Simulator tolerances
        self.rmg.absoluteTolerance = form.cleaned_data['simulator_atol']
        self.rmg.relativeTolerance = form.cleaned_data['simulator_rtol']
        self.rmg.fluxToleranceKeepInEdge = form.cleaned_data['toleranceKeepInEdge']
        self.rmg.fluxToleranceMoveToCore = form.cleaned_data['toleranceMoveToCore']
        self.rmg.fluxToleranceInterrupt = form.cleaned_data['toleranceInterruptSimulation']
        self.rmg.maximumEdgeSpecies = form.cleaned_data['maximumEdgeSpecies']
        
        # Pressure Dependence
        pdep = form.cleaned_data['pdep'].encode()
        if pdep != 'off':
            self.rmg.pressureDependence = PressureDependenceJob(network=None)
            self.rmg.pressureDependence.method = pdep
            # Temperature and pressure range
            self.rmg.pressureDependence.interpolationModel = (form.cleaned_data['interpolation'].encode(), form.cleaned_data['temp_basis'], form.cleaned_data['p_basis'])
            self.rmg.pressureDependence.Tmin = Quantity(form.cleaned_data['temp_low'], form.cleaned_data['temprange_units'].encode())
            self.rmg.pressureDependence.Tmax = Quantity(form.cleaned_data['temp_high'], form.cleaned_data['temprange_units'].encode())
            self.rmg.pressureDependence.Tcount = form.cleaned_data['temp_interp']
            self.rmg.pressureDependence.generateTemperatureList() 
            self.rmg.pressureDependence.Tlist = Quantity(Tlist,"K")
            
            self.rmg.pressureDependence.Pmin = Quantity(form.cleaned_data['p_low'], form.cleaned_data['prange_units'].encode())
            self.rmg.pressureDependence.Pmax = Quantity(form.cleaned_data['p_high'], form.cleaned_data['prange_units'].encode())
            self.rmg.pressureDependence.Pcount = form.cleaned_data['p_interp']
            self.rmg.pressureDependence.generatePressureList()
            self.rmg.pressureDependence.Plist = Quantity(Plist,"Pa")
            
            # Process grain size and count
            self.rmg.pressureDependence.grainSize = Quantity(form.cleaned_data['maximumGrainSize'], form.cleaned_data['grainsize_units'].encode())
            self.rmg.pressureDependence.grainCount = form.cleaned_data['minimumNumberOfGrains']
        
            # Process interpolation model
            self.rmg.pressureDependence.model = interpolation
        
        # Additional Options
        self.rmg.units = 'si' 
        self.rmg.saveRestartPeriod = Quantity(form.cleaned_data['saveRestartPeriod'], form.cleaned_data['saveRestartPeriodUnits'].encode()) if form.cleaned_data['saveRestartPeriod'] else None
        self.rmg.drawMolecules = form.cleaned_data['drawMolecules']
        self.rmg.generatePlots = form.cleaned_data['generatePlots']
        self.rmg.saveSimulationProfiles = form.cleaned_data['saveSimulationProfiles']

        # Save the input.py file        
        self.rmg.saveInput(self.savepath)
示例#55
0
 def __init__(self, *args, **kwargs):
     super(Input, self).__init__(*args, **kwargs)
     self.rmg = RMG()
     self.path = self.getDirname()
     self.loadpath = self.path + '/input_upload.py'
     self.savepath = self.path + '/input.py'
import os
from rmgpy.molecule.molecule import Molecule
from rmgpy.rmg.model import Species
from rmgpy.rmg.model import CoreEdgeReactionModel
from rmgpy.rmg.main import RMG
from rmgpy import settings
from rmgpy.data.rmg import RMGDatabase

rmg = RMG()
rmg.database = RMGDatabase()
path = os.path.join(settings['database.directory'])
rmg.database.loadThermo(os.path.join(path,'thermo'))
	
mol = Molecule().fromSMILES('C1=CC=CC=C1')
tdt = rmg.database.thermo.estimateThermoViaGroupAdditivity(mol)
print tdt.comment
print mol.isAromatic()

spc = Species().fromSMILES('C1=CC=CC=C1')
tdt = rmg.database.thermo.getThermoDataFromGroups(spc)
print tdt.comment
print '\n'
rmg.reactionModel = CoreEdgeReactionModel()
spc, isNew = rmg.reactionModel.makeNewSpecies(mol)
rmg.reactionModel.addSpeciesToEdge(spc)
rmg.initialSpecies = []
rmg.initialSpecies.append(spc)
for species in rmg.initialSpecies:
	#species.generateThermoData(rmg.database, quantumMechanics=rmg.reactionModel.quantumMechanics)
	#print species.thermo.comment
	tdt = rmg.database.thermo.getThermoDataFromGroups(spc)
示例#57
0
class Input(models.Model):
    """
    Model for RMG Input Conditions
    """
        
    def __init__(self, *args, **kwargs):
        super(Input, self).__init__(*args, **kwargs)
        self.rmg = RMG()
        self.path = self.getDirname()
        self.loadpath = self.path + '/input_upload.py'
        self.savepath = self.path + '/input.py'

    def upload_input_to(instance, filename):
        return instance.path + '/input_upload.py'

    input_upload = models.FileField(upload_to=upload_input_to, verbose_name='Input File', blank = True)
    
    # Pressure Dependence
    p_methods=(('off','off',),('modified strong collision','Modified Strong Collision',),('reservoir state','Reservoir State',))
    pdep = models.CharField(max_length = 50, default = 'off', choices = p_methods)
    # Advanced Options for PDep
    # Grain Size
    maximumGrainSize = models.FloatField(blank = True, default = 2, null = True)
    grain_units = (('kcal/mol','kcal/mol',),('kJ/mol','kJ/mol',))
    grainsize_units = models.CharField(max_length = 50, default = 'kcal/mol', choices = grain_units)
    minimumNumberOfGrains = models.PositiveIntegerField(blank = True, default = 200, null = True)
    # P and T Range
    p_low = models.FloatField(blank = True, null = True)
    p_high = models.FloatField(blank = True, null = True)
    prange_units = models.CharField(max_length = 50, default = 'bar', choices=p_units)
    p_interp = models.PositiveIntegerField(blank = True, null = True, default = 5)
    temp_low = models.FloatField(blank = True, null = True)
    temp_high = models.FloatField(blank = True, null = True)
    temprange_units = models.CharField(max_length = 50, default = 'K', choices = temp_units)
    temp_interp = models.PositiveIntegerField(blank = True, null=True, default = 8)
    # Interpolation
    interpolation_choices = (('chebyshev','Chebyshev',),('pdeparrhenius','Pressure Dependent Arrhenius',))
    interpolation = models.CharField(max_length = 50, default = 'chebyshev', choices = interpolation_choices)
    temp_basis = models.PositiveIntegerField(blank = True, default = 6, null = True)
    p_basis = models.PositiveIntegerField(blank = True, default = 4, null = True)

    # Tolerance
    toleranceMoveToCore = models.FloatField(blank=True, null=True)
    toleranceKeepInEdge= models.FloatField(default = 0.0)
    # Tolerance Advanced Options
    toleranceInterruptSimulation = models.FloatField(default = 1.0)
    maximumEdgeSpecies = models.PositiveIntegerField(default = 100000)
    simulator_atol = models.FloatField(default = 1e-16)
    simulator_rtol = models.FloatField(default = 1e-8)
    # Additional Options
    saveRestartPeriod=models.FloatField(blank = True, null=True)
    restartunits = (('second','seconds'),('hour','hours'),('day','days'),('week','weeks'))
    saveRestartPeriodUnits = models.CharField(max_length = 50, default = 'hour', choices = restartunits)
    drawMolecules=models.BooleanField()
    generatePlots=models.BooleanField()
    saveSimulationProfiles = models.BooleanField()


    def getDirname(self):
        """
        Return the absolute path of the directory that the object uses
        to store files.
        """
        return os.path.join(settings.MEDIA_ROOT, 'rmg','tools','input/')

    def createDir(self):
        """
        Create the directory (and any other needed parent directories) that
        the Network uses for storing files.
        """
        try:
            os.makedirs(self.getDirname())
        except OSError:
            # Fail silently on any OS errors
            pass

    def deleteDir(self):
        """
        Clean up everything by deleting the directory
        """
        import shutil
        try:
            shutil.rmtree(self.getDirname())
        except OSError:
            pass
        
    def loadForm(self, path):
        """
        Load input.py file onto form initial data.
        """        
        readInputFile(path, self.rmg)
        
        # Databases
        initial_thermo_libraries = []
        if self.rmg.thermoLibraries:
            for item in self.rmg.thermoLibraries:
                initial_thermo_libraries.append({'thermolib': item})
        
        initial_reaction_libraries = []
        if self.rmg.seedMechanisms:
            for item in self.rmg.seedMechanism:
                initial_reaction_libraries.append({'reactionlib': item, 'seedmech': True, 'edge': False})
        if self.rmg.reactionLibraries:
            for item, edge in self.rmg.reactionLibraries:
                initial_reaction_libraries.append({'reactionlib': item, 'seedmech': False, 'edge': edge})
        
        # Reactor systems
        initial_reactor_systems = []
        for system in self.rmg.reactionSystems:
            temperature = system.T.getValue()
            temperature_units = system.T.units
            pressure = system.P.getValue()
            pressure_units = system.P.units
            initialMoleFractions = system.initialMoleFractions
            for item in system.termination:
                if isinstance(item, TerminationTime):
                    terminationtime = item.time.getValue()
                    time_units = item.time.units
                else:
                    species = item.species.label
                    conversion = item.conversion
            initial_reactor_systems.append({'temperature': temperature, 'temperature_units': temperature_units,
                                            'pressure': pressure, 'pressure_units': pressure_units,
                                            'terminationtime': terminationtime, 'time_units': time_units,
                                            'species': species, 'conversion': conversion})       
        
        # Species
        initial_species = []
        for item in self.rmg.initialSpecies:
            name = item.label
            adjlist = item.molecule[0].toAdjacencyList()
            inert = False if item.reactive else True
            spec, isNew = self.rmg.reactionModel.makeNewSpecies(item.molecule[0], label = item.label, reactive = item.reactive)
            molefrac = initialMoleFractions[spec]
            initial_species.append({'name': name, 'adjlist': adjlist, 
                                    'inert': inert, 'molefrac': molefrac})
            
        # Tolerances
        initial = {}
        initial['simulator_atol'] = self.rmg.absoluteTolerance 
        initial['simulator_rtol'] = self.rmg.relativeTolerance 
        initial['toleranceKeepInEdge'] = self.rmg.fluxToleranceKeepInEdge 
        initial['toleranceMoveToCore']= self.rmg.fluxToleranceMoveToCore
        initial['toleranceInterruptSimulation'] = self.rmg.fluxToleranceInterrupt
        initial['maximumEdgeSpecies'] = self.rmg.maximumEdgeSpecies 
                
        # Pressure Dependence
        if self.rmg.pressureDependence:
            initial['interpolation'] = self.rmg.pressureDependence.model[0]
            initial['temp_basis'] = self.rmg.pressureDependence.model[1]
            initial['p_basis'] = self.rmg.pressureDependence.model[2]
            initial['temp_low'] = self.rmg.pressureDependence.Tmin.getValue()
            initial['temp_high'] = self.rmg.pressureDependence.Tmax.getValue()
            initial['temprange_units'] = self.rmg.pressureDependence.Tmax.units
            initial['temp_interp'] = self.rmg.pressureDependence.Tcount
            initial['p_low'] = self.rmg.pressureDependence.Pmin.getValue()
            initial['p_high'] = self.rmg.pressureDependence.Pmax.getValue()
            initial['prange_units'] = self.rmg.pressureDependence.Pmax.units
            initial['p_interp'] = self.rmg.pressureDepence.Pcount
            
            initial['maximumGrainSize'] = self.rmg.pressureDependence.grainSize.getValue()
            initial['grainsize_units'] = self.rmg.pressureDependence.grainSize.units
            initial['minimumNumberOfGrains'] = self.rmg.pressureDependence.grainCount

        else:
            initial['pdep'] = 'off'    
            
        # Additional Options
        if self.rmg.saveRestartPeriod:
            initial['saveRestartPeriod'] = self.rmg.saveRestartPeriod.getValue()
            initial['saveRestartPeriodUnits'] = self.rmg.saveRestartPeriod.units
        if self.rmg.drawMolecules:
            initial['drawMolecules'] = True
        if self.rmg.generatePlots:
            initial['generatePlots'] = True
        if self.rmg.saveSimulationProfiles:
            initial['saveSimulationProfiles'] = True       
            
        return initial_thermo_libraries, initial_reaction_libraries, initial_reactor_systems, initial_species, initial
        
    def saveForm(self, posted, form):
        """
        Save form data into input.py file specified by the path.
        """
        # Clean past history
        self.rmg = RMG()
        
        # Databases
        #self.rmg.databaseDirectory = settings['database.directory']
        self.rmg.thermoLibraries  = []
        if posted.thermo_libraries.all():
            self.rmg.thermoLibraries = [item.thermolib.encode() for item in posted.thermo_libraries.all()]
        self.rmg.reactionLibraries = []
        self.rmg.seedMechanisms = []
        if posted.reaction_libraries.all():
            for item in posted.reaction_libraries.all():
                if not item.seedmech and not item.edge:
                    self.rmg.reactionLibraries.append((item.reactionlib.encode(), False))
                elif not item.seedmech:
                    self.rmg.reactionLibraries.append((item.reactionlib.encode(), True))
                else:
                    self.rmg.seedMechanisms.append(item.reactionlib.encode())
        self.rmg.statmechLibraries = []
        self.rmg.kineticsDepositories = ['training']
        self.rmg.kineticsFamilies = ['!Intra_Disproportionation']        
        self.rmg.kineticsEstimator = 'rate rules'
        
        # Species
        self.rmg.initialSpecies = []
        speciesDict = {}
        initialMoleFractions = {}
        self.rmg.reactionModel = CoreEdgeReactionModel()
        for item in posted.reactor_species.all():
            structure = Molecule().fromAdjacencyList(item.adjlist.encode())
            spec, isNew = self.rmg.reactionModel.makeNewSpecies(structure, label = item.name.encode(), reactive = False if item.inert else True)
            self.rmg.initialSpecies.append(spec)
            speciesDict[item.name.encode()] = spec
            initialMoleFractions[spec] = item.molefrac
            
        # Reactor systems
        self.rmg.reactionSystems = []
        for item in posted.reactor_systems.all():
            T = Quantity(item.temperature, item.temperature_units.encode())
            P = Quantity(item.pressure, item.pressure_units.encode())            
            termination = []
            if item.conversion:
                termination.append(TerminationConversion(speciesDict[item.species.encode()], item.conversion))
            termination.append(TerminationTime(Quantity(item.terminationtime, item.time_units.encode())))
            system = SimpleReactor(T, P, initialMoleFractions, termination)
            self.rmg.reactionSystems.append(system)
    
        # Simulator tolerances
        self.rmg.absoluteTolerance = form.cleaned_data['simulator_atol']
        self.rmg.relativeTolerance = form.cleaned_data['simulator_rtol']
        self.rmg.fluxToleranceKeepInEdge = form.cleaned_data['toleranceKeepInEdge']
        self.rmg.fluxToleranceMoveToCore = form.cleaned_data['toleranceMoveToCore']
        self.rmg.fluxToleranceInterrupt = form.cleaned_data['toleranceInterruptSimulation']
        self.rmg.maximumEdgeSpecies = form.cleaned_data['maximumEdgeSpecies']
        
        # Pressure Dependence
        pdep = form.cleaned_data['pdep'].encode()
        if pdep != 'off':
            self.rmg.pressureDependence = PressureDependenceJob(network=None)
            self.rmg.pressureDependence.method = pdep
            # Temperature and pressure range
            self.rmg.pressureDependence.interpolationModel = (form.cleaned_data['interpolation'].encode(), form.cleaned_data['temp_basis'], form.cleaned_data['p_basis'])
            self.rmg.pressureDependence.Tmin = Quantity(form.cleaned_data['temp_low'], form.cleaned_data['temprange_units'].encode())
            self.rmg.pressureDependence.Tmax = Quantity(form.cleaned_data['temp_high'], form.cleaned_data['temprange_units'].encode())
            self.rmg.pressureDependence.Tcount = form.cleaned_data['temp_interp']
            self.rmg.pressureDependence.generateTemperatureList() 
            self.rmg.pressureDependence.Tlist = Quantity(Tlist,"K")
            
            self.rmg.pressureDependence.Pmin = Quantity(form.cleaned_data['p_low'], form.cleaned_data['prange_units'].encode())
            self.rmg.pressureDependence.Pmax = Quantity(form.cleaned_data['p_high'], form.cleaned_data['prange_units'].encode())
            self.rmg.pressureDependence.Pcount = form.cleaned_data['p_interp']
            self.rmg.pressureDependence.generatePressureList()
            self.rmg.pressureDependence.Plist = Quantity(Plist,"Pa")
            
            # Process grain size and count
            self.rmg.pressureDependence.grainSize = Quantity(form.cleaned_data['maximumGrainSize'], form.cleaned_data['grainsize_units'].encode())
            self.rmg.pressureDependence.grainCount = form.cleaned_data['minimumNumberOfGrains']
        
            # Process interpolation model
            self.rmg.pressureDependence.model = interpolation
        
        # Additional Options
        self.rmg.units = 'si' 
        self.rmg.saveRestartPeriod = Quantity(form.cleaned_data['saveRestartPeriod'], form.cleaned_data['saveRestartPeriodUnits'].encode()) if form.cleaned_data['saveRestartPeriod'] else None
        self.rmg.drawMolecules = form.cleaned_data['drawMolecules']
        self.rmg.generatePlots = form.cleaned_data['generatePlots']
        self.rmg.saveSimulationProfiles = form.cleaned_data['saveSimulationProfiles']

        # Save the input.py file        
        self.rmg.saveInput(self.savepath)
示例#58
0
def loadRMGJavaJob(inputFile, chemkinFile=None, speciesDict=None):
    """
    Load the results of an RMG-Java job generated from the given `inputFile`.
    """
    
    from rmgpy.molecule import Molecule
    
    # Load the specified RMG-Java input file
    # This implementation only gets the information needed to generate flux diagrams
    rmg = RMG()
    rmg.loadRMGJavaInput(inputFile)
    rmg.outputDirectory = os.path.abspath(os.path.dirname(inputFile))
    
    # Load the final Chemkin model generated by RMG-Java
    if not chemkinFile:
        chemkinFile = os.path.join(os.path.dirname(inputFile), 'chemkin', 'chem.inp')
    if not speciesDict:
        speciesDict = os.path.join(os.path.dirname(inputFile), 'RMG_Dictionary.txt')
    speciesList, reactionList = loadChemkinFile(chemkinFile, speciesDict)
    
    # Bath gas species don't appear in RMG-Java species dictionary, so handle
    # those as a special case
    for species in speciesList:
        if species.label == 'Ar':
            species.molecule = [Molecule().fromSMILES('[Ar]')]
        elif species.label == 'Ne':
            species.molecule = [Molecule().fromSMILES('[Ne]')]
        elif species.label == 'He':
            species.molecule = [Molecule().fromSMILES('[He]')]
        elif species.label == 'N2':
            species.molecule = [Molecule().fromSMILES('N#N')]
    
    # Map species in input file to corresponding species in Chemkin file
    speciesDict = {}
    for spec0 in rmg.initialSpecies:
        for species in speciesList:
            if species.isIsomorphic(spec0):
                speciesDict[spec0] = species
                break
            
    # Generate flux pairs for each reaction if needed
    for reaction in reactionList:
        if not reaction.pairs: reaction.generatePairs()

    # 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):
                if t.species not in speciesDict.values():
                    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
    
    # RMG-Java doesn't generate species images, so draw them ourselves now
    speciesPath = os.path.join(os.path.dirname(inputFile), 'species')
    try:
        os.mkdir(speciesPath)
    except OSError:
        pass
    for species in speciesList:

        path = os.path.join(speciesPath + '/{0!s}.png'.format(species))
        species.molecule[0].draw(str(path))
    
    return rmg
def generate_isotope_model(outputDirectory, rmg0, isotopes, useOriginalReactions = False,
                         kineticIsotopeEffect = None):
    """
    Replace the core species of the rmg model with the parameter list
    of species.

    Generate all reactions between new list of core species.

    Returns created RMG object.
    """
    logging.debug("isotope: called generateIsotopeModel")
    rmg = RMG(inputFile=rmg0.inputFile, outputDirectory=outputDirectory)
    rmg.attach(ChemkinWriter(outputDirectory))

    logging.info("isotope: making the isotope model for with all species")
    initialize_isotope_model(rmg, isotopes)

    if useOriginalReactions:
        logging.info("isotope: finding reactions from the original reactions")
        rxns = generate_isotope_reactions(rmg0.reactionModel.core.reactions, isotopes)
        rmg.reactionModel.processNewReactions(rxns,newSpecies=[])

    else:
        logging.info("isotope: enlarging the isotope model")
        rmg.reactionModel.enlarge(reactEdge=True,
            unimolecularReact=rmg.unimolecularReact,
            bimolecularReact=rmg.bimolecularReact)

    logging.info("isotope: clustering reactions")
    clusters = cluster(rmg.reactionModel.core.reactions)
    logging.info('isotope: fixing the directions of every reaction to a standard')
    for isotopomerRxnList in clusters:
        ensure_reaction_direction(isotopomerRxnList)

    consistent = True
    logging.info("isotope: checking symmetry is consistent among isotopomers")
    for species_list in cluster(rmg.reactionModel.core.species):
        if not ensure_correct_symmetry(species_list):
            logging.info("isotopomers of {} with index {} may have wrong symmetry".format(species_list[0], species_list[0].index))
            consistent = False
    logging.info("isotope: checking that reaction degeneracy is consistent among isotopomers")
    for rxn_list in clusters:
        if not ensure_correct_degeneracies(rxn_list):
            logging.info("isotopomers of {} with index {} may have incorrect degeneracy.".format(rxn_list[0], rxn_list[0].index))
            consistent = False
    if not consistent:
        logging.warning("isotope: non-consistent degeneracy and/or symmetry was detected. This may lead to unrealistic deviations in enrichment. check log for more details")

    if kineticIsotopeEffect:
        logging.info('isotope: modifying reaction rates using kinetic isotope effect method "{0}"'.format(kineticIsotopeEffect))
        if kineticIsotopeEffect == 'simple':
            apply_kinetic_isotope_effect_simple(clusters,rmg.database.kinetics)
        else:
            logging.warning('isotope: kinetic isotope effect {0} is not supported. skipping adding kinetic isotope effects.')
    else:
        logging.info('isotope: not adding kinetic isotope effects since no method was supplied.')
    logging.info("isotope: saving files")
    rmg.saveEverything()

    rmg.finish()

    return rmg