Example #1
0
    def kinetics_checkSiblingsForParents(self, family_name):
        """
        This test checks that siblings in a tree are not actually parent/child
        """
        from rmgpy.data.base import Database

        originalFamily = self.database.kinetics.families[family_name]
        family = Database()
        family.entries = originalFamily.groups.entries
        for nodeName, node in family.entries.iteritems():
            # Some families also construct a 2-level trees for the products
            # (root with all entries down one level) We don't care about this
            # tree as it is not used in searching, so we ignore products
            if node in originalFamily.forwardTemplate.products:
                continue
            for index, child1 in enumerate(node.children):
                for child2 in node.children[index + 1 :]:
                    # Don't check a node against itself
                    if child1 is child2:
                        continue
                    nose.tools.assert_false(
                        family.matchNodeToChild(child1, child2),
                        "In family {0}, node {1} is written as a sibling of {2}, when it is actually a parent.".format(
                            family_name, child1, child2
                        ),
                    )
                    nose.tools.assert_false(
                        family.matchNodeToChild(child2, child1),
                        "In family {0}, node {1} is written as a sibling of {2}, when it is actually a parent.".format(
                            family_name, child2, child1
                        ),
                    )
Example #2
0
 def __init__(self, label='', name='', shortDesc='', longDesc=''):
     Database.__init__(
         self,
         label=label,
         name=name,
         shortDesc=shortDesc,
         longDesc=longDesc)
Example #3
0
    def kinetics_checkChildParentRelationships(self, family_name):
        """
        This test checks that groups' parent-child relationships are correct in the database.
        """
        from rmgpy.data.base import Database
        originalFamily = self.database.kinetics.families[family_name]
        family = Database()
        family.entries = originalFamily.groups.entries
        for nodeName, childNode in family.entries.iteritems():
            #top nodes and product nodes don't have parents by definition, so they get an automatic pass:
            if childNode in originalFamily.groups.top or childNode in originalFamily.forwardTemplate.products:
                continue
            parentNode = childNode.parent
            # Check whether the node has proper parents unless it is the top reactant or product node
            # The parent should be more general than the child
            nose.tools.assert_true(
                family.matchNodeToChild(parentNode, childNode),
                "In {family} family, group {parent} is not a proper parent of its child {child}."
                .format(family=family_name, parent=parentNode, child=nodeName))

            #check that parentNodes which are LogicOr do not have an ancestor that is a Group
            #If it does, then the childNode must also be a child of the ancestor
            if isinstance(parentNode, LogicOr):
                ancestorNode = childNode
                while ancestorNode not in originalFamily.groups.top and isinstance(
                        ancestorNode, LogicOr):
                    ancestorNode = ancestorNode.parent
                if isinstance(ancestorNode, Group):
                    nose.tools.assert_true(
                        family.matchNodeToChild(ancestorNode, childNode),
                        "In {family} family, group {ancestor} is not a proper ancestor of its child {child}."
                        .format(family=family_name,
                                ancestor=ancestorNode,
                                child=nodeName))
Example #4
0
 def kinetics_checkSiblingsForParents(self, family_name):
     """
     This test checks that siblings in a tree are not actually parent/child
     """
     from rmgpy.data.base import Database
     originalFamily = self.database.kinetics.families[family_name]
     family = Database()
     family.entries = originalFamily.groups.entries
     for nodeName, node in family.entries.iteritems():
         #Some families also construct a 2-level trees for the products
         #(root with all entries down one level) We don't care about this
         #tree as it is not used in searching, so we ignore products
         if node in originalFamily.forwardTemplate.products: continue
         for index, child1 in enumerate(node.children):
             for child2 in node.children[index + 1:]:
                 #Don't check a node against itself
                 if child1 is child2: continue
                 nose.tools.assert_false(
                     family.matchNodeToChild(child1, child2),
                     "In family {0}, node {1} is written as a sibling of {2}, when it is actually a parent."
                     .format(family_name, child1, child2))
                 nose.tools.assert_false(
                     family.matchNodeToChild(child2, child1),
                     "In family {0}, node {1} is written as a sibling of {2}, when it is actually a parent."
                     .format(family_name, child2, child1))
Example #5
0
    def kinetics_checkChildParentRelationships(self, family_name):
        """
        This test checks that groups' parent-child relationships are correct in the database.
        """
        from rmgpy.data.base import Database
        originalFamily = self.database.kinetics.families[family_name]
        family = Database()
        family.entries = originalFamily.groups.entries
        for nodeName, childNode in family.entries.iteritems():
            #top nodes and product nodes don't have parents by definition, so they get an automatic pass:
            if childNode in originalFamily.groups.top or childNode in originalFamily.forwardTemplate.products: continue
            parentNode = childNode.parent
            # Check whether the node has proper parents unless it is the top reactant or product node
            # The parent should be more general than the child
            nose.tools.assert_true(family.matchNodeToChild(parentNode, childNode),
                            "In {family} family, group {parent} is not a proper parent of its child {child}.".format(family=family_name, parent=parentNode, child=nodeName))

            #check that parentNodes which are LogicOr do not have an ancestor that is a Group
            #If it does, then the childNode must also be a child of the ancestor
            if isinstance(parentNode, LogicOr):
                ancestorNode = childNode
                while ancestorNode not in originalFamily.groups.top and isinstance(ancestorNode, LogicOr):
                    ancestorNode = ancestorNode.parent
                if isinstance(ancestorNode, Group):
                    nose.tools.assert_true(family.matchNodeToChild(ancestorNode, childNode),
                                    "In {family} family, group {ancestor} is not a proper ancestor of its child {child}.".format(family=family_name, ancestor=ancestorNode, child=nodeName))
Example #6
0
 def load(self, path):
     """
     Load the solute library from the given path
     """
     Database.load(self,
                   path,
                   local_context={'SoluteData': SoluteData},
                   global_context={})
Example #7
0
    def load(self, path, local_context=None, global_context=None):
        import os
        Database.load(self, path, local_context, global_context)
        
        # Load the species in the kinetics library
        # Do not generate resonance structures, since training reactions may be written for a specific resonance form
        speciesDict = self.getSpecies(os.path.join(os.path.dirname(path),'dictionary.txt'), resonance=False)
        # Make sure all of the reactions draw from only this set
        entries = self.entries.values()
        for entry in entries:
            # Create a new reaction per entry
            rxn = entry.item
            rxn_string = entry.label
            # Convert the reactants and products to Species objects using the speciesDict
            reactants, products = rxn_string.split('=')
            reversible = True
            if '<=>' in rxn_string:
                reactants = reactants[:-1]
                products = products[1:]
            elif '=>' in rxn_string:
                products = products[1:]
                reversible = False
            assert reversible == rxn.reversible, "Reaction string reversibility (=>) and entry attribute `reversible` (set to `False`) must agree if reaction is irreversible."

            specificCollider = None
            collider = re.search('\(\+[^\)]+\)',reactants)
            if collider is not None:
                collider = collider.group(0) # save string value rather than the object
                assert collider == re.search('\(\+[^\)]+\)',products).group(0), "Third body colliders in reaction {0} in kinetics library {1} are not identical!".format(rxn_string, self.label)
                extraParenthesis = collider.count('(') -1
                for i in xrange(extraParenthesis):
                    collider += ')' # allow for species like N2(5) or CH2(T)(15) to be read as specific colliders, although currently not implemented in Chemkin. See RMG-Py #1070
                reactants = reactants.replace(collider,'')
                products = products.replace(collider,'')
                if collider.upper().strip() != "(+M)": # the collider is a specific species, not (+M) or (+m)
                    if collider.strip()[2:-1] not in speciesDict: # stripping spaces, '(+' and ')'
                        raise DatabaseError('Collider species {0} in kinetics library {1} is missing from its dictionary.'.format(collider.strip()[2:-1], self.label))
                    specificCollider = speciesDict[collider.strip()[2:-1]]

            for reactant in reactants.split('+'):
                reactant = reactant.strip()
                if reactant not in speciesDict:
                    raise DatabaseError('Species {0} in kinetics depository {1} is missing from its dictionary.'.format(reactant, self.label))
                # Depository reactions should have molecule objects because they are needed in order to descend the
                # tree using `getReactionTemplate()` later, but species objects work because `getReactionTemplate()`
                # will simply pick the first molecule object in `Species().molecule`.
                rxn.reactants.append(speciesDict[reactant])
            for product in products.split('+'):
                product = product.strip()
                if product not in speciesDict:
                    raise DatabaseError('Species {0} in kinetics depository {1} is missing from its dictionary.'.format(product, self.label))
                # Same comment about molecule vs species objects as above.
                rxn.products.append(speciesDict[product])
                
            if not rxn.isBalanced():
                raise DatabaseError('Reaction {0} in kinetics depository {1} was not balanced! Please reformulate.'.format(rxn, self.label))    
Example #8
0
 def __init__(self,
              label='',
              name='',
              solvent=None,
              shortDesc='',
              longDesc=''):
     Database.__init__(self,
                       label=label,
                       name=name,
                       shortDesc=shortDesc,
                       longDesc=longDesc)
Example #9
0
 def __init__(self,
              label='',
              name='',
              short_desc='',
              long_desc='',
              auto_generated=False):
     Database.__init__(self,
                       label=label,
                       name=name,
                       short_desc=short_desc,
                       long_desc=long_desc)
     self.auto_generated = auto_generated
Example #10
0
 def load(self, path, local_context=None, global_context=None):
     Database.load(self, path, local_context, global_context)
     
     # Generate a unique set of the species in the kinetics library
     speciesDict = self.getSpecies()
     # Make sure all of the reactions draw from only this set
     entries = self.entries.values()
     for entry in entries:
         entry.item.reactants = [speciesDict[spec.label] for spec in entry.item.reactants]
         entry.item.products = [speciesDict[spec.label] for spec in entry.item.products]
         
     self.checkForDuplicates()
Example #11
0
    def load(self, path, local_context=None, global_context=None):
        Database.load(self, path, local_context, global_context)

        # Load a unique set of the species in the kinetics library
        speciesDict = self.getSpecies(
            os.path.join(os.path.dirname(path), 'dictionary.txt'))
        # Make sure all of the reactions draw from only this set
        entries = self.entries.values()
        for entry in entries:
            # Create a new reaction per entry
            rxn = entry.item
            rxn_string = entry.label
            # Convert the reactants and products to Species objects using the speciesDict
            reactants, products = rxn_string.split('=')
            reversible = True
            if '<=>' in rxn_string:
                reactants = reactants[:-1]
                products = products[1:]
            elif '=>' in rxn_string:
                products = products[1:]
                reversible = False
            assert reversible == rxn.reversible, "Reaction string reversibility (=>) and entry attribute `reversible` (set to `False`) must agree if reaction is irreversible."
            for reactant in reactants.split('+'):
                reactant = reactant.strip()
                if reactant not in speciesDict:
                    raise DatabaseError(
                        'Species {0} in kinetics library {1} is missing from its dictionary.'
                        .format(reactant, self.label))
                rxn.reactants.append(speciesDict[reactant])
            for product in products.split('+'):
                product = product.strip()
                if product not in speciesDict:
                    raise DatabaseError(
                        'Species {0} in kinetics library {1} is missing from its dictionary.'
                        .format(product, self.label))
                rxn.products.append(speciesDict[product])

            if not rxn.isBalanced():
                raise DatabaseError(
                    'Reaction {0} in kinetics library {1} was not balanced! Please reformulate.'
                    .format(rxn, self.label))

            if len(rxn.reactants) > 3:
                raise DatabaseError(
                    'RMG does not accept reactions with more than 3 reactants in its solver.  Reaction {0} in kinetics library {1} has {2} reactants.'
                    .format(rxn, self.label, len(rxn.reactants)))
            if len(rxn.products) > 3:
                raise DatabaseError(
                    'RMG does not accept reactions with more than 3 products in its solver.  Reaction {0} in kinetics library {1} has {2} reactants.'
                    .format(rxn, self.label, len(rxn.products)))

        self.checkForDuplicates()
Example #12
0
 def __init__(self,
              label='',
              name='',
              solvent=None,
              shortDesc='',
              longDesc='',
              autoGenerated=False):
     Database.__init__(self,
                       label=label,
                       name=name,
                       shortDesc=shortDesc,
                       longDesc=longDesc)
     self.autoGenerated = autoGenerated
Example #13
0
 def __init__(self,
              label='',
              name='',
              solvent=None,
              shortDesc='',
              longDesc='',
              duplicatesChecked=True):
     Database.__init__(self,
                       label=label,
                       name=name,
                       shortDesc=shortDesc,
                       longDesc=longDesc)
     self.duplicatesChecked = duplicatesChecked
Example #14
0
 def kinetics_checkGroupsNonidentical(self, family_name):
     """
     This test checks that the groups are non-identical.
     """
     from rmgpy.data.base import Database
     originalFamily = self.database.kinetics.families[family_name]
     family = Database()
     family.entries = originalFamily.groups.entries
     entriesCopy = copy(family.entries)
     for nodeName, nodeGroup in family.entries.iteritems():
         del entriesCopy[nodeName]
         for nodeNameOther, nodeGroupOther in entriesCopy.iteritems():
             nose.tools.assert_false(family.matchNodeToNode(nodeGroup, nodeGroupOther), "Group {group} in {family} family was found to be identical to group {groupOther}".format(group=nodeName, family=family_name, groupOther=nodeNameOther))
Example #15
0
 def kinetics_checkGroupsNonidentical(self, family_name):
     """
     This test checks that the groups are non-identical.
     """
     from rmgpy.data.base import Database
     originalFamily = self.database.kinetics.families[family_name]
     family = Database()
     family.entries = originalFamily.groups.entries
     entriesCopy = copy(family.entries)
     for nodeName, nodeGroup in family.entries.iteritems():
         del entriesCopy[nodeName]
         for nodeNameOther, nodeGroupOther in entriesCopy.iteritems():
             nose.tools.assert_false(family.matchNodeToNode(nodeGroup, nodeGroupOther), "Group {group} in {family} family was found to be identical to group {groupOther}".format(group=nodeName, family=family_name, groupOther=nodeNameOther))
Example #16
0
    def load(self, path, local_context=None, global_context=None):
        import os

        Database.load(self, path, local_context, global_context)

        # Load the species in the kinetics library
        speciesDict = self.getSpecies(os.path.join(os.path.dirname(path), "dictionary.txt"))
        # Make sure all of the reactions draw from only this set
        entries = self.entries.values()
        for entry in entries:
            # Create a new reaction per entry
            rxn = entry.item
            rxn_string = entry.label
            # Convert the reactants and products to Species objects using the speciesDict
            reactants, products = rxn_string.split("=")
            reversible = True
            if "<=>" in rxn_string:
                reactants = reactants[:-1]
                products = products[1:]
            elif "=>" in rxn_string:
                products = products[1:]
                reversible = False
            assert reversible == rxn.reversible
            for reactant in reactants.split("+"):
                reactant = reactant.strip()
                if reactant not in speciesDict:
                    raise DatabaseError(
                        "Species {0} in kinetics depository {1} is missing from its dictionary.".format(
                            reactant, self.label
                        )
                    )
                # For some reason we need molecule objects in the depository rather than species objects
                rxn.reactants.append(speciesDict[reactant])
            for product in products.split("+"):
                product = product.strip()
                if product not in speciesDict:
                    raise DatabaseError(
                        "Species {0} in kinetics depository {1} is missing from its dictionary.".format(
                            product, self.label
                        )
                    )
                # For some reason we need molecule objects in the depository rather than species objects
                rxn.products.append(speciesDict[product])

            if not rxn.isBalanced():
                raise DatabaseError(
                    "Reaction {0} in kinetics depository {1} was not balanced! Please reformulate.".format(
                        rxn, self.label
                    )
                )
Example #17
0
 def __init__(self,
              entries=None,
              top=None,
              label='',
              name='',
              shortDesc='',
              longDesc='',
              forwardTemplate=None,
              forwardRecipe=None,
              reverseTemplate=None,
              reverseRecipe=None,
              forbidden=None):
     Database.__init__(self, entries, top, label, name, shortDesc, longDesc)
     self.numReactants = 0
Example #18
0
 def __init__(self,
              entries=None,
              top=None,
              label='',
              name='',
              shortDesc='',
              longDesc='',
              forwardTemplate=None,
              forwardRecipe=None,
              reverseTemplate=None,
              reverseRecipe=None,
              forbidden=None
              ):
     Database.__init__(self, entries, top, label, name, shortDesc, longDesc)
     self.numReactants = 0
Example #19
0
 def __init__(self,
              entries=None,
              top=None,
              label='',
              name='',
              short_desc='',
              long_desc='',
              forward_template=None,
              forward_recipe=None,
              reverse_template=None,
              reverse_recipe=None,
              forbidden=None
              ):
     Database.__init__(self, entries, top, label, name, short_desc, long_desc)
     self.num_reactants = 0
Example #20
0
 def __init__(self,
              label='',
              name='',
              short_desc='',
              long_desc='',
              metal=None,
              site=None,
              facet=None):
     Database.__init__(self,
                       label=label,
                       name=name,
                       short_desc=short_desc,
                       long_desc=long_desc,
                       metal=metal,
                       site=site,
                       facet=facet)
Example #21
0
    def load(self, path, local_context=None, global_context=None):
        Database.load(self, path, local_context, global_context)

        # Generate a unique set of the species in the kinetics library
        speciesDict = self.getSpecies()
        # Make sure all of the reactions draw from only this set
        entries = self.entries.values()
        for entry in entries:
            entry.item.reactants = [
                speciesDict[spec.label] for spec in entry.item.reactants
            ]
            entry.item.products = [
                speciesDict[spec.label] for spec in entry.item.products
            ]

        self.checkForDuplicates()
Example #22
0
    def load(self, path, local_context=None, global_context=None):

        Database.load(self, path, local_context, global_context)

        # Load the species in the kinetics library
        speciesDict = self.getSpecies(
            os.path.join(os.path.dirname(path), 'dictionary.txt'))
        # Make sure all of the reactions draw from only this set
        entries = list(self.entries.values())
        for entry in entries:
            # Create a new reaction per entry
            rxn = entry.item
            rxn_string = entry.label
            # Convert the reactants and products to Species objects using the
            # speciesDict
            reactants, products = rxn_string.split('=')
            reversible = True
            if '<=>' in rxn_string:
                reactants = reactants[:-1]
                products = products[1:]
            elif '=>' in rxn_string:
                products = products[1:]
                reversible = False
            assert reversible == rxn.reversible
            for reactant in reactants.split('+'):
                reactant = reactant.strip()
                if reactant not in speciesDict:
                    raise DatabaseError(
                        'RMGSpecies {0} in kinetics depository {1} is missing from its dictionary.'
                        .format(reactant, self.label))
                # For some reason we need molecule objects in the depository
                # rather than species objects
                rxn.reactants.append(speciesDict[reactant])
            for product in products.split('+'):
                product = product.strip()
                if product not in speciesDict:
                    raise DatabaseError(
                        'RMGSpecies {0} in kinetics depository {1} is missing from its dictionary.'
                        .format(product, self.label))
                # For some reason we need molecule objects in the depository
                # rather than species objects
                rxn.products.append(speciesDict[product])

            if not rxn.isBalanced():
                raise DatabaseError(
                    'Reaction {0} in kinetics depository {1} was not balanced! Please reformulate.'
                    .format(rxn, self.label))
Example #23
0
def save_pictures(git_path="", species_path="", overwrite=False):
    """
    Save a folder full of molecule pictures, needed for the pretty dot files.

    Saves them in the results directory, in a subfolder "species_pictures".
    Unless you set overwrite=True, it'll leave alone files that are
    already there.
    """
    dictionary_filename = git_path + "/base/chemkin/species_dictionary.txt"
    specs = Database().get_species(dictionary_filename, resonance=False)

    images_dir = os.path.join(species_path)
    os.makedirs(images_dir, exist_ok=True)
    for name, species in specs.items():
        filepath = os.path.join(images_dir, name + ".png")
        if not overwrite and os.path.exists(filepath):
            continue
        species.molecule[0].draw(filepath)
    def apply_LSRs(self, delta_atomic_adsoprtion_energies):

        self.rmg_spcs = Database().get_species(self.dictionary_filename,
                                               resonance=False)

        for species in self.surf.species():
            rmg_spcs = self.rmg_spcs[species.name]
            self._correct_binding_energy(rmg_spcs,
                                         delta_atomic_adsoprtion_energies,
                                         False)
Example #25
0
    def load(self, path, local_context=None, global_context=None):
        Database.load(self, path, local_context, global_context)
        
        # Load a unique set of the species in the kinetics library
        speciesDict = self.getSpecies(os.path.join(os.path.dirname(path),'dictionary.txt'))
        # Make sure all of the reactions draw from only this set
        entries = self.entries.values()
        for entry in entries:
            # Create a new reaction per entry
            rxn = entry.item
            rxn_string = entry.label
            # Convert the reactants and products to Species objects using the speciesDict
            reactants, products = rxn_string.split('=')
            reversible = True
            if '<=>' in rxn_string:
                reactants = reactants[:-1]
                products = products[1:]
            elif '=>' in rxn_string:
                products = products[1:]
                reversible = False
            assert reversible == rxn.reversible, "Reaction string reversibility (=>) and entry attribute `reversible` (set to `False`) must agree if reaction is irreversible."
            for reactant in reactants.split('+'):
                reactant = reactant.strip()
                if reactant not in speciesDict:
                    raise DatabaseError('Species {0} in kinetics library {1} is missing from its dictionary.'.format(reactant, self.label))
                rxn.reactants.append(speciesDict[reactant])
            for product in products.split('+'):
                product = product.strip()
                if product not in speciesDict:
                    raise DatabaseError('Species {0} in kinetics library {1} is missing from its dictionary.'.format(product, self.label))
                rxn.products.append(speciesDict[product])
                
            if not rxn.isBalanced():
                raise DatabaseError('Reaction {0} in kinetics library {1} was not balanced! Please reformulate.'.format(rxn, self.label))    

            if len(rxn.reactants) > 3: 
                raise DatabaseError('RMG does not accept reactions with more than 3 reactants in its solver.  Reaction {0} in kinetics library {1} has {2} reactants.'.format(rxn, self.label, len(rxn.reactants)))
            if len(rxn.products) > 3:
                raise DatabaseError('RMG does not accept reactions with more than 3 products in its solver.  Reaction {0} in kinetics library {1} has {2} reactants.'.format(rxn, self.label, len(rxn.products)))
            

            
        self.checkForDuplicates()
Example #26
0
        self.delEa = delEa
        self.A = A
        self.n = n
        self.Ea_old = Ea_old
        self.Ea_new = Ea_new

    def setParam(self, A, n, Ea):
        self.A = A
        self.n = n
        self.Ea_old = Ea

    def setModEa(self, Ea):
        self.Ea_new = Ea


database = Database()
species_dict = database.getSpecies(
    '/home/slakman.b/Code/mech_C8_EF_paper/V3/RMG_Dictionary.txt')

reaction_list = []
family_list = ['H_Abstraction', 'intra_H_migration']

with open('/home/slakman.b/Code/mech_C8_EF_paper/V3/chem.inp',
          'r') as mech_file:
    for line in mech_file:
        if line.strip().startswith('REACTIONS'): break
    for line in mech_file:
        if line.strip().startswith('!'): break
        if 'H_Abstraction' in line or 'intra_H_migration' in line:
            reaction_list.append(line.strip())
Example #27
0
 def setUp(self):
     """
     A function run before each unit test in this class.
     """
     # Set up a dummy database
     self.database = Database()
Example #28
0
class TestBaseDatabase(unittest.TestCase):
    """
    Contains unit tests for the base class of rmgpy.data.
    """
    def setUp(self):
        """
        A function run before each unit test in this class.
        """
        # Set up a dummy database
        self.database = Database()

    def testMatchNodeToStructure(self):
        """
        Test that the MatchNodeToStructure family works properly.
        """
        entry1 = Entry(item=Group().fromAdjacencyList("""
        1 *3 C  u1 {2,D} {3,S}
        2    C  u0 {1,D}
        3 *5 Cd u0 {1,S} {4,D}
        4    C  u0 {3,D}
        """))

        entry2 = Entry(item=Group().fromAdjacencyList("""
        1 *3 C  u1 {2,D} {3,S}
        2 *5 C  u0 {1,D}
        3    Cd u0 {1,S} {4,D}
        4    C  u0 {3,D}
        """))

        entry3 = Entry(item=Group().fromAdjacencyList("""
        1 *3 C  u1 {2,D} {3,S}
        2    C  u0 {1,D}
        3    Cd u0 {1,S} {4,D}
        4    C  u0 {3,D}
        """))
        # The group should match to itself
        self.assertTrue(
            self.database.matchNodeToStructure(
                entry1, entry1.item, atoms=entry1.item.getLabeledAtoms()))

        # These groups should not match each other
        self.assertFalse(
            self.database.matchNodeToStructure(
                entry1, entry2.item, atoms=entry2.item.getLabeledAtoms()))

        # entry1 contains more labels than entry3, therefore cannot be matched by entry3
        self.assertFalse(
            self.database.matchNodeToStructure(
                entry3, entry1.item, atoms=entry1.item.getLabeledAtoms()))

        # entry3 contains fewer labels than entry1, therefore it can be matched
        self.assertTrue(
            self.database.matchNodeToStructure(
                entry1, entry3.item, atoms=entry3.item.getLabeledAtoms()))

    def testMatchNodeToNode(self):
        """
        Test that nodes can match other nodes.
        """
        entry1 = Entry(item=Group().fromAdjacencyList("""
        1 *1 R!H u1
        """))

        entry2 = Entry(item=Group().fromAdjacencyList("""
        1 *1 Cb u1
        """))
        self.assertTrue(self.database.matchNodeToNode(entry1, entry1))
        self.assertFalse(self.database.matchNodeToNode(entry1, entry2))
Example #29
0
 def __init__(self, label='', name='', short_desc='', long_desc=''):
     Database.__init__(self,
                       label=label,
                       name=name,
                       short_desc=short_desc,
                       long_desc=long_desc)
Example #30
0
 def __init__(self, label='', name='', shortDesc='', longDesc='', recommended=False):
     Database.__init__(self, label=label, name=name, shortDesc=shortDesc, longDesc=longDesc, recommended=recommended)
Example #31
0
 def setUp(self):
     """
     A function run before each unit test in this class.
     """
     # Set up a dummy database
     self.database = Database()
Example #32
0
class TestBaseDatabase(unittest.TestCase):
    """
    Contains unit tests for the base class of rmgpy.data.
    """
    
    
    def setUp(self):
        """
        A function run before each unit test in this class.
        """
        # Set up a dummy database
        self.database = Database()


    def testMatchNodeToStructure(self):
        """
        Test that the MatchNodeToStructure family works properly.
        """
        entry1 = Entry(
            item = Group().fromAdjacencyList(
        """
        1 *3 C  1 {2,D} {3,S}
        2    C  0 {1,D}
        3 *5 Cd 0 {1,S} {4,D}
        4    C  0 {3,D}
        """)
        )        
        
        entry2 = Entry(
            item= Group().fromAdjacencyList(
        """
        1 *3 C  1 {2,D} {3,S}
        2 *5 C  0 {1,D}
        3    Cd 0 {1,S} {4,D}
        4    C  0 {3,D}
        """)
        )
        
        entry3 = Entry(
            item = Group().fromAdjacencyList(
        """
        1 *3 C  1 {2,D} {3,S}
        2    C  0 {1,D}
        3    Cd 0 {1,S} {4,D}
        4    C  0 {3,D}
        """)
        )
        # The group should match to itself
        self.assertTrue(self.database.matchNodeToStructure(entry1,entry1.item,atoms=entry1.item.getLabeledAtoms()))  
        
        # These groups should not match each other
        self.assertFalse(self.database.matchNodeToStructure(entry1,entry2.item,atoms=entry2.item.getLabeledAtoms()))  

        # entry1 contains more labels than entry3, therefore cannot be matched by entry3
        self.assertFalse(self.database.matchNodeToStructure(entry3,entry1.item,atoms=entry1.item.getLabeledAtoms()))

        # entry3 contains fewer labels than entry1, therefore it can be matched
        self.assertTrue(self.database.matchNodeToStructure(entry1,entry3.item,atoms=entry3.item.getLabeledAtoms()))
        
    def testMatchNodeToNode(self):
        """
        Test that nodes can match other nodes.
        """
        entry1 = Entry(
            item = Group().fromAdjacencyList(
        """
        1 *1 R!H 1
        """)
        )        
        
        entry2 = Entry(
            item= Group().fromAdjacencyList(
        """
        1 *1 Cb 1
        """)
        )
        self.assertTrue(self.database.matchNodeToNode(entry1,entry1))
        self.assertFalse(self.database.matchNodeToNode(entry1,entry2))
Example #33
0
"""
Given two chemkin files and species dictionaries, will replace rates in the second
mechanism with the rate in the first.
"""
import sys
import os
from rmgpy import settings
from rmgpy.molecule import Molecule
from rmgpy.species import Species
from rmgpy.reaction import Reaction
from rmgpy.data.rmg import RMGDatabase
from rmgpy.data.base import Database
#########################################################
database = Database()
species_dict_V3 = database.getSpecies(
    '/home/slakman.b/Code/mech/MH_mechs1/prelim_mech_V3/RMG_Dictionary.txt')
species_dict_V4 = database.getSpecies(
    '/home/slakman.b/Code/mech/MH_mechs1/final_mech_V4/RMG_Dictionary.txt')

reaction_list_V3 = []
reaction_list_V4 = []
family_list = ['H_Abstraction', 'intra_H_migration']

with open('/home/slakman.b/Code/mech/MH_mechs1/prelim_mech_V3/chem.inp',
          'r') as mech_file:
    for line in mech_file:
        if line.strip().startswith('REACTIONS'): break
    for line in mech_file:
        if line.strip().startswith('!'): break
        if 'H_Abstraction' in line or 'intra_H_migration' in line:
            reaction_list_V3.append(line.strip())
Example #34
0
 def __init__(self, label='', name='', solvent=None, shortDesc='', longDesc='', autoGenerated=False):
     Database.__init__(self, label=label, name=name, shortDesc=shortDesc, longDesc=longDesc)
     self.autoGenerated=autoGenerated
Example #35
0
    def load(self, path, local_context=None, global_context=None):
        Database.load(self, path, local_context, global_context)

        # Load a unique set of the species in the kinetics library
        speciesDict = self.getSpecies(
            os.path.join(os.path.dirname(path), 'dictionary.txt'))
        # Make sure all of the reactions draw from only this set
        entries = self.entries.values()
        for entry in entries:
            # Create a new reaction per entry
            rxn = entry.item
            rxn_string = entry.label
            # Convert the reactants and products to Species objects using the speciesDict
            reactants, products = rxn_string.split('=>')
            reversible = True
            if '<=>' in rxn_string:
                reactants = reactants[:-1]
                products = products[1:]
            elif '=>' in rxn_string:
                products = products[1:]
                reversible = False
            assert reversible == rxn.reversible, "Reaction string reversibility (=>) and entry attribute `reversible` (set to `False`) must agree if reaction is irreversible."

            collider = re.search('\(\+[^\)]+\)', reactants)
            if collider is not None:
                collider = collider.group(
                    0)  # save string value rather than the object
                assert collider == re.search('\(\+[^\)]+\)',products).group(0), "Third body colliders in reaction {0} in kinetics library {1} are missing" \
                                                                                " from products or are not identical!".format(rxn_string, self.label)
                extraParenthesis = collider.count('(') - 1
                for i in xrange(extraParenthesis):
                    collider += ')'  # allow for species like N2(5) or CH2(T)(15) to be read as specific colliders, although currently not implemented in Chemkin. See RMG-Py #1070
                reactants = reactants.replace(collider, '', 1)
                products = products.replace(collider, '', 1)
                if collider.upper().strip(
                ) != "(+M)":  # the collider is a specific species, not (+M) or (+m)
                    if collider.strip(
                    )[2:
                      -1] not in speciesDict:  # stripping spaces, '(+' and ')'
                        raise DatabaseError(
                            'Collider species {0} in kinetics library {1} is missing from its dictionary.'
                            .format(collider.strip()[2:-1], self.label))
                    rxn.specificCollider = speciesDict[collider.strip()[2:-1]]
            # verify there's no more than one specificCollider:
            collider = re.search('\(\+[^\)]+\)', reactants)
            if collider is not None:
                raise DatabaseError(
                    "Found TWO specific third body colliders, {0} and {1}, in reaction {2} in kinetics library {3), expecting no more than one!"
                    .format(rxn.specificCollider, collider.group(0),
                            rxn_string, self.label))

            for reactant in reactants.split('+'):
                reactant = reactant.strip()
                if reactant not in speciesDict:
                    raise DatabaseError(
                        'Species {0} in kinetics library {1} is missing from its dictionary.'
                        .format(reactant, self.label))
                rxn.reactants.append(speciesDict[reactant])
            for product in products.split('+'):
                product = product.strip()
                if product not in speciesDict:
                    raise DatabaseError(
                        'Species {0} in kinetics library {1} is missing from its dictionary.'
                        .format(product, self.label))
                rxn.products.append(speciesDict[product])

            if not rxn.isBalanced():
                raise DatabaseError(
                    'Reaction {0} in kinetics library {1} was not balanced! Please reformulate.'
                    .format(rxn, self.label))

            if len(rxn.reactants) > 3:
                raise DatabaseError(
                    'RMG does not accept reactions with more than 3 reactants in its solver.  Reaction {0} in kinetics library {1} has {2} reactants.'
                    .format(rxn, self.label, len(rxn.reactants)))
            if len(rxn.products) > 3:
                raise DatabaseError(
                    'RMG does not accept reactions with more than 3 products in its solver.  Reaction {0} in kinetics library {1} has {2} reactants.'
                    .format(rxn, self.label, len(rxn.products)))

        self.checkForDuplicates()
Example #36
0
 def load(self, path):
     """
     Load the metal library from the given path
     """
     Database.load(self, path, local_context={}, global_context={})
Example #37
0
 def __init__(self, label="", name="", shortDesc="", longDesc=""):
     Database.__init__(self, label=label, name=name, shortDesc=shortDesc, longDesc=longDesc)