示例#1
0
def moleculeSearch(request):
    """
    Creates webpage form to display molecule chemgraph upon entering adjacency list, smiles, or inchi, as well as searches for thermochemistry data.
    """
    form = MoleculeSearchForm()
    structure_markup = ""
    molecule = Molecule()
    if request.method == "POST":
        posted = MoleculeSearchForm(request.POST, error_class=DivErrorList)
        initial = request.POST.copy()

        if posted.is_valid():
            adjlist = posted.cleaned_data["species"]
            if adjlist != "":
                molecule.fromAdjacencyList(adjlist)
                structure_markup = getStructureMarkup(molecule)

        form = MoleculeSearchForm(initial, error_class=DivErrorList)

        if "thermo" in request.POST:
            return HttpResponseRedirect(reverse(thermoData, kwargs={"adjlist": adjlist}))

        if "reset" in request.POST:
            form = MoleculeSearchForm()
            structure_markup = ""
            molecule = Molecule()

    return render_to_response(
        "moleculeSearch.html",
        {"structure_markup": structure_markup, "molecule": molecule, "form": form},
        context_instance=RequestContext(request),
    )
示例#2
0
def getAdjacencyList(request, identifier):
    """
    Returns an adjacency list of the species corresponding to `identifier`.
    
    `identifier` should be something recognized by NCI resolver, eg.
    SMILES, InChI, CACTVS, chemical name, etc.
    
    The NCI resolver has some bugs regarding reading SMILES of radicals.
    E.g. it thinks CC[CH] is CCC, so we first try to use the identifier
    directly as a SMILES string, and only pass it through the resolver
    if that does not work. 
    """
    if identifier.strip() == "":
        return HttpResponse("", mimetype="text/plain")
    from rmgpy.molecule import Molecule

    molecule = Molecule()
    try:
        # try using the string as a SMILES directly
        molecule.fromSMILES(str(identifier))
    except IOError:
        # try converting it to a SMILES using the NCI chemical resolver
        url = "http://cactus.nci.nih.gov/chemical/structure/{0}/smiles".format(urllib.quote(identifier))
        try:
            f = urllib2.urlopen(url, timeout=5)
        except urllib2.URLError, e:
            return HttpResponseNotFound(
                "404: Couldn't identify {0}. NCI resolver responded {1} to request for {2}".format(identifier, e, url)
            )
        smiles = f.read()
        molecule.fromSMILES(smiles)
    def test_Intra_R_Add_Exo_scission(self):
        """
        Test that the Intra_R_Add_Exo_scission family, which is its own reverse, returns a properly re-labeled product structure.
        """
        family = self.database.families['Intra_R_Add_Exo_scission']
        reactants = [Molecule().fromAdjacencyList("""
multiplicity 2
1  *3 C u0 p0 c0 {2,S} {8,S} {11,S} {12,S}
2  *2 C u0 p0 c0 {1,S} {3,B} {4,B}
3     C u0 p0 c0 {2,B} {5,B} {13,S}
4     C u0 p0 c0 {2,B} {7,B} {17,S}
5     C u0 p0 c0 {3,B} {6,B} {14,S}
6     C u0 p0 c0 {5,B} {7,B} {15,S}
7     C u0 p0 c0 {4,B} {6,B} {16,S}
8  *1 C u1 p0 c0 {1,S} {9,S} {18,S}
9     C u0 p0 c0 {8,S} {10,T}
10    C u0 p0 c0 {9,T} {19,S}
11    H u0 p0 c0 {1,S}
12    H u0 p0 c0 {1,S}
13    H u0 p0 c0 {3,S}
14    H u0 p0 c0 {5,S}
15    H u0 p0 c0 {6,S}
16    H u0 p0 c0 {7,S}
17    H u0 p0 c0 {4,S}
18    H u0 p0 c0 {8,S}
19    H u0 p0 c0 {10,S}
""")]
        expectedProduct = Molecule().fromAdjacencyList("""
multiplicity 2
1  *3 C u0 p0 c0 {2,S} {8,S} {9,S} {11,S}
2  *2 C u0 p0 c0 {1,S} {3,B} {4,B}
3     C u0 p0 c0 {2,B} {5,B} {12,S}
4     C u0 p0 c0 {2,B} {7,B} {16,S}
5     C u0 p0 c0 {3,B} {6,B} {13,S}
6     C u0 p0 c0 {5,B} {7,B} {14,S}
7     C u0 p0 c0 {4,B} {6,B} {15,S}
8  *1 C u1 p0 c0 {1,S} {17,S} {18,S}
9     C u0 p0 c0 {1,S} {10,T}
10    C u0 p0 c0 {9,T} {19,S}
11    H u0 p0 c0 {1,S}
12    H u0 p0 c0 {3,S}
13    H u0 p0 c0 {5,S}
14    H u0 p0 c0 {6,S}
15    H u0 p0 c0 {7,S}
16    H u0 p0 c0 {4,S}
17    H u0 p0 c0 {8,S}
18    H u0 p0 c0 {8,S}
19    H u0 p0 c0 {10,S}
""")
        products = family.applyRecipe(reactants)

        self.assertEqual(len(products), 1)

        mapping = {}
        for label, atom in expectedProduct.getLabeledAtoms().iteritems():
            mapping[atom] = products[0].getLabeledAtom(label)

        self.assertTrue(expectedProduct.isIsomorphic(products[0], mapping))
示例#4
0
    def testMakeSampleMolecule(self):
        """
        Test the Group.makeSampleMolecule method
        """

        def performSampMoleComparison(adjlist, answer_smiles):
            """
            Creates a sample molecule from the adjlist and returns if it is isomorphic to a molecule created from
            the inputted smiles
            """
            group = Group().fromAdjacencyList(adjlist)
            result = group.makeSampleMolecule()
            return (result.isIsomorphic(Molecule().fromSMILES(answer_smiles)))
########################################################################################################################
        #tests adding implicit atoms
        adjlist = """
1  *1 Cd u0
            """
        answer_smiles = 'C=C'
        self.assertTrue(performSampMoleComparison(adjlist, answer_smiles))

        #test creating implicit benzene atoms
        adjlist2 = """
1  *1 Cbf u0 {2,B}
2     Cbf u0 {1,B}
            """

        group2 = Group().fromAdjacencyList(adjlist2)
        result2 = group2.makeSampleMolecule()
        naphthaleneMolecule = Molecule().fromSMILES('C1=CC=C2C=CC=CC2=C1')
        resonanceList2=naphthaleneMolecule.generateResonanceIsomers()
        self.assertTrue(any([result2.isIsomorphic(x) for x in resonanceList2]))

        #test the creation of a positively charged species
        adjlist = """
1  *1 N5s u0
        """
        answer_smiles = '[NH4+]'
        self.assertTrue(performSampMoleComparison(adjlist, answer_smiles))

        #test the creation of a negatively charged species
        #commented out until new nitrogen atom types added in
#         adjlist = """
# 1  *1 N2s u0
#         """
#         answer_smiles = '[NH2-]'
#         self.assertTrue(performSampMoleComparison(adjlist, answer_smiles))

        #test creation of charged species when some single bonds present
        adjlist = """
1 *2 [N5s,N5d] u0 {2,S} {3,S}
2 *3 R!H       u1 {1,S}
3 *4 H         u0 {1,S}
"""
        answer_smiles = '[NH3+][CH2]'
        self.assertTrue(performSampMoleComparison(adjlist, answer_smiles))
示例#5
0
 def clean_detergent(self):
     """
     Return molecular representation of input detergent structure        """
     try:
         detergent = Molecule()
         detergent.fromAdjacencyList(str(self.cleaned_data['detergent']))
     except Exception, e:
         import traceback
         traceback.print_exc(e)
         raise forms.ValidationError('Invalid SMILES entry.')
示例#6
0
    def compare(self, inchi, mult, u_indices = None):
        u_layer = ','.join([str(i) for i in u_indices]) if u_indices else None

        if u_layer:
            aug_inchi = 'InChI=1/' + inchi  + '/mult' + str(mult) + '/u' + u_layer
        else: 
            aug_inchi = 'InChI=1/' + inchi  + '/mult' + str(mult)

        mol = Molecule()
        mol = fromAugmentedInChI(mol, aug_inchi)
        self.assertEqual(mol.getNumberOfRadicalElectrons(), mult - 1)
        return mol
示例#7
0
 def clean_reactant1(self):
     """
     Custom validation for the reactant1 field to ensure that a valid
     adjacency list has been provided.
     """
     try:
         molecule = Molecule()
         molecule.fromAdjacencyList(str(self.cleaned_data['reactant1']))
     except Exception, e:
         import traceback
         traceback.print_exc(e)
         raise forms.ValidationError('Invalid adjacency list.')
    def test_12_shiftC(self):
        """
        Test that the 1,2_shiftC family, which is its own reverse, returns a properly re-labeled product structure.
        """
        family = self.database.families['1,2_shiftC']
        reactants = [Molecule().fromAdjacencyList("""
multiplicity 2
1  *2 C u0 p0 c0 {2,S} {3,S} {8,S} {9,S}
2  *1 C u0 p0 c0 {1,S} {10,S} {11,S} {12,S}
3  *3 C u1 p0 c0 {1,S} {4,S} {5,S}
4     C u0 p0 c0 {3,S} {6,D} {13,S}
5     C u0 p0 c0 {3,S} {7,D} {14,S}
6     C u0 p0 c0 {4,D} {7,S} {15,S}
7     C u0 p0 c0 {5,D} {6,S} {16,S}
8     H u0 p0 c0 {1,S}
9     H u0 p0 c0 {1,S}
10    H u0 p0 c0 {2,S}
11    H u0 p0 c0 {2,S}
12    H u0 p0 c0 {2,S}
13    H u0 p0 c0 {4,S}
14    H u0 p0 c0 {5,S}
15    H u0 p0 c0 {6,S}
16    H u0 p0 c0 {7,S}
""")]
        expectedProduct = Molecule().fromAdjacencyList("""
multiplicity 2
1  *2 C u0 p0 c0 {2,S} {3,S} {4,S} {7,S}
2  *1 C u0 p0 c0 {1,S} {8,S} {9,S} {10,S}
3     C u0 p0 c0 {1,S} {5,D} {11,S}
4     C u0 p0 c0 {1,S} {6,D} {12,S}
5     C u0 p0 c0 {3,D} {6,S} {13,S}
6     C u0 p0 c0 {4,D} {5,S} {14,S}
7  *3 C u1 p0 c0 {1,S} {15,S} {16,S}
8     H u0 p0 c0 {2,S}
9     H u0 p0 c0 {2,S}
10    H u0 p0 c0 {2,S}
11    H u0 p0 c0 {3,S}
12    H u0 p0 c0 {4,S}
13    H u0 p0 c0 {5,S}
14    H u0 p0 c0 {6,S}
15    H u0 p0 c0 {7,S}
16    H u0 p0 c0 {7,S}
""")
        products = family.applyRecipe(reactants)

        self.assertEqual(len(products), 1)

        mapping = {}
        for label, atom in expectedProduct.getLabeledAtoms().iteritems():
            mapping[atom] = products[0].getLabeledAtom(label)

        self.assertTrue(expectedProduct.isIsomorphic(products[0], mapping))
    def test_Intra_ene_reaction(self):
        """
        Test that the Intra_ene_reaction family, which is its own reverse, returns a properly re-labeled product structure.
        """
        family = self.database.families['Intra_ene_reaction']
        reactants = [Molecule().fromAdjacencyList("""
1  *1 C u0 p0 c0 {2,S} {3,S} {4,S} {10,S}
2  *5 C u0 p0 c0 {1,S} {5,D} {6,S}
3  *2 C u0 p0 c0 {1,S} {7,D} {11,S}
4     C u0 p0 c0 {1,S} {8,D} {12,S}
5  *4 C u0 p0 c0 {2,D} {7,S} {13,S}
6     C u0 p0 c0 {2,S} {9,D} {15,S}
7  *3 C u0 p0 c0 {3,D} {5,S} {14,S}
8     C u0 p0 c0 {4,D} {9,S} {17,S}
9     C u0 p0 c0 {6,D} {8,S} {16,S}
10 *6 H u0 p0 c0 {1,S}
11    H u0 p0 c0 {3,S}
12    H u0 p0 c0 {4,S}
13    H u0 p0 c0 {5,S}
14    H u0 p0 c0 {7,S}
15    H u0 p0 c0 {6,S}
16    H u0 p0 c0 {9,S}
17    H u0 p0 c0 {8,S}
""")]
        expectedProduct = Molecule().fromAdjacencyList("""
1  *2 C u0 p0 c0 {2,D} {3,S} {4,S} 
2  *3 C u0 p0 c0 {1,D} {5,S} {6,S}
3  *1 C u0 p0 c0 {1,S} {7,S} {11,S} {10,S}
4     C u0 p0 c0 {1,S} {8,D} {12,S}
5  *4 C u0 p0 c0 {2,S} {7,D} {13,S}
6     C u0 p0 c0 {2,S} {9,D} {15,S}
7  *5 C u0 p0 c0 {3,S} {5,D} {14,S}
8     C u0 p0 c0 {4,D} {9,S} {17,S}
9     C u0 p0 c0 {6,D} {8,S} {16,S}
10 *6 H u0 p0 c0 {3,S}
11    H u0 p0 c0 {3,S}
12    H u0 p0 c0 {4,S}
13    H u0 p0 c0 {5,S}
14    H u0 p0 c0 {7,S}
15    H u0 p0 c0 {6,S}
16    H u0 p0 c0 {9,S}
17    H u0 p0 c0 {8,S}
""")
        products = family.applyRecipe(reactants)

        self.assertEqual(len(products), 1)

        mapping = {}
        for label, atom in expectedProduct.getLabeledAtoms().iteritems():
            mapping[atom] = products[0].getLabeledAtom(label)

        self.assertTrue(expectedProduct.isIsomorphic(products[0], mapping))
示例#10
0
 def clean_species(self):
         """
         Custom validation for the species field to ensure that a valid adjacency
         list has been provided.
         """
         try:
             adjlist = str(self.cleaned_data['species'])
             if adjlist == '' : return ''
             molecule = Molecule()
             molecule.fromAdjacencyList(str(self.cleaned_data['species']))
         except Exception, e:
             import traceback
             traceback.print_exc(e)
             raise forms.ValidationError('Invalid adjacency list.')
示例#11
0
    def testMakeSampleMolecule(self):
        """
        Test the Group.makeSampleMolecule method
        """

        # result = self.group.makeSampleMolecule()
        # print result.multiplicity
        # self.assertTrue(result.isIsomorphic(Molecule().fromSMILES('OCC')))

        #tests adding implicit atoms
        adjlist1 = """
1  *1 Cd u0
            """

        group1 = Group().fromAdjacencyList(adjlist1)
        result1 = group1.makeSampleMolecule()
        self.assertTrue(result1.isIsomorphic(Molecule().fromSMILES('C=C')))

        #test creating implicit benzene atoms
        adjlist2 = """
1  *1 Cbf u0 {2,B}
2     Cbf u0 {1,B}
            """

        group2 = Group().fromAdjacencyList(adjlist2)
        result2 = group2.makeSampleMolecule()
        naphthaleneMolecule = Molecule().fromSMILES('C1=CC=C2C=CC=CC2=C1')
        resonanceList2=naphthaleneMolecule.generateResonanceIsomers()
        self.assertTrue(any([result2.isIsomorphic(x) for x in resonanceList2]))

        #test the creation of a charged species
        adjlist3 = """
1  *1 N5s u0
        """

        group3 = Group().fromAdjacencyList(adjlist3)
        result3 = group3.makeSampleMolecule()
        self.assertTrue(result3.isIsomorphic(Molecule().fromSMILES('[NH4+]')))

        #test creation of charged species when some single bonds present
        adjlist4 = """
1 *2 [N5s,N5d] u0 {2,S} {3,S}
2 *3 R!H       u1 {1,S}
3 *4 H         u0 {1,S}
"""
        group4 = Group().fromAdjacencyList(adjlist4)
        result4 = group4.makeSampleMolecule()
        self.assertTrue(result4.isIsomorphic(Molecule().fromSMILES('[NH3+][CH2]')))
def getAdjacencyList(request, identifier):
    """
    Returns an adjacency list of the species corresponding to `identifier`.
    
    `identifier` should be something recognized by NCI resolver, eg.
    SMILES, InChI, CACTVS, chemical name, etc.
    
    The NCI resolver has some bugs regarding reading SMILES of radicals.
    E.g. it thinks CC[CH] is CCC, so we first try to use the identifier
    directly as a SMILES string, and only pass it through the resolver
    if that does not work. 
    
    For specific problematic cases, the NCI resolver is bypassed and the SMILES
    is returned from a dictionary of values. For O2, the resolver returns the singlet
    form which is inert in RMG. For oxygen, the resolver returns 'O' as the SMILES, which
    is the SMILES for water.
    """
    from rmgpy.molecule import Molecule
    from rmgpy.exceptions import AtomTypeError
    from ssl import SSLError

    known_names = {
        'o2': '[O][O]',
        'oxygen': '[O][O]',
        'benzyl': '[CH2]c1ccccc1',
        'phenyl': '[c]1ccccc1',
    }

    # Ensure that input is a string
    identifier = str(identifier).strip()

    # Return empty string for empty input
    if identifier == '':
        return HttpResponse('', content_type="text/plain")

    molecule = Molecule()

    # Check if identifier is an InChI string
    if identifier.startswith('InChI=1'):
        try:
            molecule.fromInChI(identifier)
        except AtomTypeError:
            return HttpResponse('Invalid Molecule', status=501)
        except KeyError, e:
            return HttpResponse('Invalid Element: {0!s}'.format(e), status=501)
示例#13
0
def EniSearch(request):
    """
    Creates webpage form to display detergent and deposit structures upon entering smiles as well as returns binding constants
    between the detergent and deposit
    """
    from tools import getAbrahamAB

    if request.method == "POST":
        form = EniSearchForm(request.POST, error_class=DivErrorList)
        if form.is_valid():
            detergent_adjlist = form.cleaned_data["detergent"]
            deposit_adjlist = form.cleaned_data["deposit"]

            detergent = Molecule()
            detergent.fromAdjacencyList(detergent_adjlist)
            detergent_smiles = detergent.toSMILES()
            detergent_structure = getStructureMarkup(detergent)

            deposit = Molecule()
            deposit.fromAdjacencyList(deposit_adjlist)
            deposit_smiles = deposit.toSMILES()
            deposit_structure = getStructureMarkup(deposit)

            detergentA, detergentB = getAbrahamAB(detergent_smiles)
            depositA, depositB = getAbrahamAB(deposit_smiles)

            # Estimating the binding strength assuming the the detergent to be the donor and dirt to be acceptor
            logK_AB = 7.354 * detergentA * depositB
            # Estimating the binding strength assuming the the detergent to be the acceptor and dirt to be donor
            logK_BA = 7.354 * detergentB * depositA

    else:
        detergentA = 0
        detergentB = 0
        depositA = 0
        depositB = 0
        logK_AB = 0
        logK_BA = 0
        form = EniSearchForm()

    return render_to_response(
        "EniSearch.html",
        {
            "detergentA": detergentA,
            "detergentB": detergentB,
            "depositA": depositA,
            "depositB": depositB,
            "logKAB": logK_AB,
            "logKBA": logK_BA,
            "form": form,
        },
        context_instance=RequestContext(request),
    )
    def test_6_membered_central_CC_shift(self):
        """
        Test that the 6_membered_central_C-C_shift family, which is its own reverse, returns a properly re-labeled product structure.
        """
        family = self.database.families['6_membered_central_C-C_shift']
        reactants = [Molecule().fromAdjacencyList("""
1  *3 C u0 p0 c0 {2,S} {3,S} {7,S} {8,S}
2  *4 C u0 p0 c0 {1,S} {4,S} {9,S} {10,S}
3  *2 C u0 p0 c0 {1,S} {5,T}
4  *5 C u0 p0 c0 {2,S} {6,T}
5  *1 C u0 p0 c0 {3,T} {11,S}
6  *6 C u0 p0 c0 {4,T} {12,S}
7     H u0 p0 c0 {1,S}
8     H u0 p0 c0 {1,S}
9     H u0 p0 c0 {2,S}
10    H u0 p0 c0 {2,S}
11    H u0 p0 c0 {5,S}
12    H u0 p0 c0 {6,S}
""")]
        expectedProduct = Molecule().fromAdjacencyList("""
1  *3 C u0 p0 c0 {2,S} {5,D} {7,S}
2  *4 C u0 p0 c0 {1,S} {6,D} {8,S}
3  *1 C u0 p0 c0 {5,D} {9,S} {10,S}
4  *6 C u0 p0 c0 {6,D} {11,S} {12,S}
5  *2 C u0 p0 c0 {1,D} {3,D}
6  *5 C u0 p0 c0 {2,D} {4,D}
7     H u0 p0 c0 {1,S}
8     H u0 p0 c0 {2,S}
9     H u0 p0 c0 {3,S}
10    H u0 p0 c0 {3,S}
11    H u0 p0 c0 {4,S}
12    H u0 p0 c0 {4,S}
""")
        products = family.applyRecipe(reactants)

        self.assertEqual(len(products), 1)

        mapping = {}
        for label, atom in expectedProduct.getLabeledAtoms().iteritems():
            mapping[atom] = products[0].getLabeledAtom(label)

        self.assertTrue(expectedProduct.isIsomorphic(products[0], mapping))
    def test_intra_substitutionS_isomerization(self):
        """
        Test that the intra_substitutionS_isomerization family, which is its own reverse, returns a properly re-labeled product structure.
        """
        family = self.database.families['intra_substitutionS_isomerization']
        reactants = [Molecule().fromAdjacencyList("""
multiplicity 2
1  *2 C u0 p0 c0 {3,S} {4,S} {5,S} {6,S}
2     C u0 p0 c0 {3,S} {7,S} {8,S} {9,S}
3  *3 C u1 p0 c0 {1,S} {2,S} {10,S}
4  *1 S u0 p2 c0 {1,S} {11,S}
5     H u0 p0 c0 {1,S}
6     H u0 p0 c0 {1,S}
7     H u0 p0 c0 {2,S}
8     H u0 p0 c0 {2,S}
9     H u0 p0 c0 {2,S}
10    H u0 p0 c0 {3,S}
11    H u0 p0 c0 {4,S}
""")]
        expectedProduct = Molecule().fromAdjacencyList("""
multiplicity 2
1  *2 C u0 p0 c0 {2,S} {3,S} {4,S} {5,S}
2     C u0 p0 c0 {1,S} {6,S} {7,S} {8,S}
3  *3 C u1 p0 c0 {1,S} {9,S} {10,S}
4  *1 S u0 p2 c0 {1,S} {11,S}
5     H u0 p0 c0 {1,S}
6     H u0 p0 c0 {2,S}
7     H u0 p0 c0 {2,S}
8     H u0 p0 c0 {2,S}
9     H u0 p0 c0 {3,S}
10    H u0 p0 c0 {3,S}
11    H u0 p0 c0 {4,S}
""")
        products = family.applyRecipe(reactants)

        self.assertEqual(len(products), 1)

        mapping = {}
        for label, atom in expectedProduct.getLabeledAtoms().iteritems():
            mapping[atom] = products[0].getLabeledAtom(label)

        self.assertTrue(expectedProduct.isIsomorphic(products[0], mapping))
示例#16
0
 def setUp(self):
     """
     A function run before each unit test in this class.
     """
     self.mol1 = Molecule().fromSMILES('COO=CC=C=CC#C')
     self.mol2 = Molecule().fromSMILES('c1ccccc1')
     self.mol3 = Molecule().fromSMILES('[H]')
     self.mol4 = Molecule().fromSMILES(
                             'O=[Si][Si][Si]=[Si]=[Si][Si]#[Si]SS=S')
     self.mol5 = Molecule().fromSMILES('[N]')
     self.mol6 = Molecule().fromSMILES('[Ar]')
     self.mol7 = Molecule().fromSMILES('[He]')
     self.mol8 = Molecule().fromSMILES('[Ne]')
    def testReactBenzeneBond(self):
        """
        Test that hydrogen addition to benzene (w/ benzene bonds) returns kekulized product.
        """
        family = self.database.families['R_Addition_MultipleBond']
        reactants = [Molecule().fromAdjacencyList("""
1  *1 C u0 p0 c0 {2,B} {6,B} {7,S}
2  *2 C u0 p0 c0 {1,B} {3,B} {8,S}
3     C u0 p0 c0 {2,B} {4,B} {9,S}
4     C u0 p0 c0 {3,B} {5,B} {10,S}
5     C u0 p0 c0 {4,B} {6,B} {11,S}
6     C u0 p0 c0 {1,B} {5,B} {12,S}
7     H u0 p0 c0 {1,S}
8     H u0 p0 c0 {2,S}
9     H u0 p0 c0 {3,S}
10    H u0 p0 c0 {4,S}
11    H u0 p0 c0 {5,S}
12    H u0 p0 c0 {6,S}
"""),
                     Molecule().fromAdjacencyList("1 *3 H u1 p0 c0")]
        expectedProduct = Molecule().fromAdjacencyList("""
multiplicity 2
1  C u0 p0 c0 {2,S} {6,S} {7,S} {13,S}
2  C u1 p0 c0 {1,S} {3,S} {8,S}
3  C u0 p0 c0 {2,S} {4,D} {9,S}
4  C u0 p0 c0 {3,D} {5,S} {10,S}
5  C u0 p0 c0 {4,S} {6,D} {11,S}
6  C u0 p0 c0 {1,S} {5,D} {12,S}
7  H u0 p0 c0 {1,S}
8  H u0 p0 c0 {2,S}
9  H u0 p0 c0 {3,S}
10 H u0 p0 c0 {4,S}
11 H u0 p0 c0 {5,S}
12 H u0 p0 c0 {6,S}
13 H u0 p0 c0 {1,S}
""")
        products = family.applyRecipe(reactants)

        self.assertEqual(len(products), 1)
        self.assertTrue(expectedProduct.isIsomorphic(products[0]))
    def setUp(self):
        """To be run before each test."""
        molecule = Molecule().fromAdjacencyList("""
1  C u0 p0 c0 {2,B} {6,B} {7,S}
2  C u0 p0 c0 {1,B} {3,B} {8,S}
3  C u0 p0 c0 {2,B} {4,B} {9,S}
4  C u0 p0 c0 {3,B} {5,B} {10,S}
5  C u0 p0 c0 {4,B} {6,B} {11,S}
6  C u0 p0 c0 {1,B} {5,B} {12,S}
7  H u0 p0 c0 {1,S}
8  H u0 p0 c0 {2,S}
9  H u0 p0 c0 {3,S}
10 H u0 p0 c0 {4,S}
11 H u0 p0 c0 {5,S}
12 H u0 p0 c0 {6,S}
""")
        bonds = set()
        for atom in molecule.atoms:
            bonds.update(atom.bonds.values())

        ring_atoms, ring_bonds = molecule.getAromaticRings()

        self.aromatic_ring = AromaticRing(ring_atoms[0], set(ring_bonds[0]), bonds - set(ring_bonds[0]))
示例#19
0
文件: base.py 项目: ajalan/RMG-Py
 def loadEntry(self, label, molecule=None, group=None, shortDesc='', longDesc='', history=None):
     """
     Load an entry from the forbidden structures database. This method is
     automatically called during loading of the forbidden structures 
     database.
     """
     assert molecule is not None or group is not None
     assert not (molecule is not None and group is not None)
     if molecule is not None:
         item = Molecule.fromAdjacencyList(molecule)
     elif group is not None:
         if group[0:3].upper() == 'OR{' or group[0:4].upper() == 'AND{' or group[0:7].upper() == 'NOT OR{' or group[0:8].upper() == 'NOT AND{':
             item = makeLogicNode(group)
         else:
             item = Group().fromAdjacencyList(group)
     self.entries[label] = Entry(
         label = label,
         item = item,
         shortDesc = shortDesc,
         longDesc = longDesc.strip(),
         history = history or [],
     )
示例#20
0
    def test_c5h6o2(self):
        adjlist = """
1  C u0 p1 c-1 {5,S} {7,S} {8,S}
2  C u0 p0 c0 {3,D} {4,S} {9,S}
3  C u0 p0 c0 {2,D} {5,S} {10,S}
4  C u0 p0 c0 {2,S} {6,D} {11,S}
5  C u0 p0 c0 {1,S} {3,S} {6,S} {12,S}
6  O u0 p1 c+1 {4,D} {5,S}
7  H u0 p0 c0 {1,S}
8  H u0 p0 c0 {1,S}
9  H u0 p0 c0 {2,S}
10 H u0 p0 c0 {3,S}
11 H u0 p0 c0 {4,S}
12 H u0 p0 c0 {5,S}
        """

        mol = Molecule().from_adjacency_list(adjlist)
        start = mol.atoms[2]
        path = find_butadiene_end_with_charge(start)
        idx_path = [mol.atoms.index(atom) + 1 for atom in path[0::2]]

        expected_idx_path = [3, 2, 4, 6]
        self.assertEquals(idx_path, expected_idx_path)
示例#21
0
    def test_correction_generation(self):
        """Test we can estimate solvation thermochemistry."""
        self.testCases = [
            # solventName, soluteName, soluteSMILES, Hsolv, Gsolv
            ['water', 'acetic acid', 'C(C)(=O)O', -56500, -6700 * 4.184],
            ['water', 'naphthalene', 'C1=CC=CC2=CC=CC=C12', -42800, -2390 * 4.184],
            ['1-octanol', 'octane', 'CCCCCCCC', -40080, -4180 * 4.184],
            ['1-octanol', 'tetrahydrofuran', 'C1CCOC1', -28320, -3930 * 4.184],
            ['benzene', 'toluene', 'C1(=CC=CC=C1)C', -37660, -5320 * 4.184],
            ['benzene', '1,4-dioxane', 'C1COCCO1', -39030, -5210 * 4.184]
        ]

        for solventName, soluteName, smiles, H, G in self.testCases:
            species = Species(molecule=[Molecule(smiles=smiles)])
            solute_data = self.database.get_solute_data(species)
            solvent_data = self.database.get_solvent_data(solventName)
            solvation_correction = self.database.get_solvation_correction(solute_data, solvent_data)
            self.assertAlmostEqual(solvation_correction.enthalpy / 10000., H / 10000., 0,  # 0 decimal place, in 10kJ.
                                   msg="Solvation enthalpy discrepancy ({2:.0f}!={3:.0f}) for {0} in {1}"
                                       "".format(soluteName, solventName, solvation_correction.enthalpy, H))
            self.assertAlmostEqual(solvation_correction.gibbs / 10000., G / 10000., 0,
                                   msg="Solvation Gibbs free energy discrepancy ({2:.0f}!={3:.0f}) for {0} in {1}"
                                       "".format(soluteName, solventName, solvation_correction.gibbs, G))
示例#22
0
 def loadEntry(self,
               index,
               label,
               molecule,
               statmech,
               reference=None,
               referenceType='',
               shortDesc='',
               longDesc='',
               ):
     
     item = Molecule().fromAdjacencyList(molecule)
     
     self.entries[label] = Entry(
         index = index,
         label = label,
         item = item,
         data = statmech,
         reference = reference,
         referenceType = referenceType,
         shortDesc = shortDesc,
         longDesc = longDesc.strip(),
     )
示例#23
0
    def test_14cyclohexadiene(self):
        adjlist = """
1  C u0 p0 c0 {2,D} {6,S} {7,S}
2  C u0 p0 c0 {1,D} {3,S} {8,S}
3  C u0 p0 c0 {2,S} {4,S} {9,S} {10,S}
4  C u0 p0 c0 {3,S} {5,D} {11,S}
5  C u0 p0 c0 {4,D} {6,S} {12,S}
6  C u0 p0 c0 {1,S} {5,S} {13,S} {14,S}
7  H u0 p0 c0 {1,S}
8  H u0 p0 c0 {2,S}
9  H u0 p0 c0 {3,S}
10 H u0 p0 c0 {3,S}
11 H u0 p0 c0 {4,S}
12 H u0 p0 c0 {5,S}
13 H u0 p0 c0 {6,S}
14 H u0 p0 c0 {6,S}
        """

        mol = Molecule().from_adjacency_list(adjlist)  # 1,4-cyclohexadiene

        start, end = mol.atoms[0], mol.atoms[3]
        path = find_butadiene(start, end)
        self.assertIsNone(path)
示例#24
0
    def __init__(self, smiles=None, rmg_molecule=None, index=0):

        self.energy = None
        self.index = index

        if (smiles or rmg_molecule):
            if smiles and rmg_molecule:
                assert rmg_molecule.isIsomorphic(
                    RMGMolecule(SMILES=smiles)
                ), "SMILES string did not match RMG Molecule object"
                self.smiles = smiles
                self.rmg_molecule = rmg_molecule

            elif rmg_molecule:
                self.rmg_molecule = rmg_molecule
                self.smiles = rmg_molecule.toSMILES()

            else:
                self.smiles = smiles
                self.rmg_molecule = RMGMolecule(SMILES=smiles)

            self.rmg_molecule.updateMultiplicity()
            self.get_mols()
            self.get_geometries()
            self._symmetry_number = None

        else:
            self.smiles = None
            self.rmg_molecule = None
            self.rdkit_molecule = None
            self.ase_molecule = None
            self.bonds = []
            self.angles = []
            self.torsions = []
            self.cistrans = []
            self.chiral_centers = []
            self._symmetry_number = None
示例#25
0
文件: thermo.py 项目: olusade/RMG-Py
    def loadEntry(
        self,
        index,
        label,
        molecule,
        thermo,
        reference=None,
        referenceType='',
        shortDesc='',
        longDesc='',
    ):

        molecule = Molecule().fromAdjacencyList(molecule)

        # Internal checks for adding entry to the thermo library
        if label in self.entries.keys():
            raise DatabaseError(
                'Found a duplicate molecule with label {0} in the thermo library.  Please correct your library.'
                .format(label))

        for entry in self.entries.values():
            if molecule.isIsomorphic(entry.item):
                if molecule.multiplicity == entry.item.multiplicity:
                    raise DatabaseError(
                        'Adjacency list and multiplicity of {0} matches that of existing molecule {1} in thermo library.  Please correct your library.'
                        .format(label, entry.label))

        self.entries[label] = Entry(
            index=index,
            label=label,
            item=molecule,
            data=thermo,
            reference=reference,
            referenceType=referenceType,
            shortDesc=shortDesc,
            longDesc=longDesc.strip(),
        )
    def test_is_bond_conjugated_4(self):

        mol_test = Molecule().fromAdjacencyList(
            """1  C u0 p0 c0 {2,D} {8,S} {9,S}
2  C u0 p0 c0 {1,D} {3,S} {10,S}
3  C u0 p0 c0 {2,S} {4,S} {11,S} {12,S}
4  C u0 p0 c0 {3,S} {5,D} {13,S}
5  C u0 p0 c0 {4,D} {6,S} {14,S}
6  C u0 p0 c0 {5,S} {7,D} {15,S}
7  C u0 p0 c0 {6,D} {16,S} {17,S}
8  H u0 p0 c0 {1,S}
9  H u0 p0 c0 {1,S}
10 H u0 p0 c0 {2,S}
11 H u0 p0 c0 {3,S}
12 H u0 p0 c0 {3,S}
13 H u0 p0 c0 {4,S}
14 H u0 p0 c0 {5,S}
15 H u0 p0 c0 {6,S}
16 H u0 p0 c0 {7,S}
17 H u0 p0 c0 {7,S}
""")
        atom0 = mol_test.atoms[0]
        atom1 = mol_test.atoms[1]
        atom2 = mol_test.atoms[2]
        atom3 = mol_test.atoms[3]
        atom4 = mol_test.atoms[4]
        atom5 = mol_test.atoms[5]
        atom6 = mol_test.atoms[6]
        bond01 = atom0.bonds[atom1]
        bond12 = atom1.bonds[atom2]
        bond45 = atom4.bonds[atom5]
        bond56 = atom5.bonds[atom6]

        self.assertFalse(is_bond_conjugated(bond01))
        self.assertFalse(is_bond_conjugated(bond12))
        self.assertTrue(is_bond_conjugated(bond45))
        self.assertTrue(is_bond_conjugated(bond56))
示例#27
0
    def testReactStoreIndices(self):
        """
        Test that reaction generation keeps track of the original species indices.
        """

        indices = {'[OH]': 1, 'CC': 2, '[CH3]': 3}

        # make it bidirectional so that we can look-up indices as well:
        revd = dict([reversed(i) for i in indices.items()])
        indices.update(revd)

        spcA = Species(index=indices['[OH]']).fromSMILES('[OH]')
        spcs = [
            Species(index=indices['CC']).fromSMILES('CC'),
            Species(index=indices['[CH3]']).fromSMILES('[CH3]')
        ]

        reactionList = list(react(spcA, spcs))
        self.assertIsNotNone(reactionList)
        self.assertEquals(len(reactionList), 3)
        for rxn in reactionList:
            for i, reactant in enumerate(rxn.reactants):
                rxn.reactants[i] = Molecule().fromSMILES(indices[reactant])
            self.assertTrue(rxn.isBalanced())
示例#28
0
	def testGetThermoDataMopac(self):
		"""
		Test that getThermoData() works correctly.
		"""
		outputDirectory = os.path.join(self.mop1.settings.fileStore, '..')
		self.mop1.setDefaultOutputDirectory(outputDirectory)
		self.mop2.setDefaultOutputDirectory(outputDirectory)
		self.mop3.setDefaultOutputDirectory(outputDirectory)
		
		mol = Molecule().fromSMILES('C1=CC=C2C=CC=CC2=C1')
		
		fileList = os.listdir(self.mop1.settings.fileStore)
		for fileName in fileList:
			os.remove(os.path.join(self.mop1.settings.fileStore, fileName))
		thermo1 = self.mop1.getThermoData(mol)
		
		fileList = os.listdir(self.mop2.settings.fileStore)
		for fileName in fileList:
			os.remove(os.path.join(self.mop2.settings.fileStore, fileName))
		thermo2 = self.mop2.getThermoData(mol)
		
		fileList = os.listdir(self.mop3.settings.fileStore)
		for fileName in fileList:
			os.remove(os.path.join(self.mop3.settings.fileStore, fileName))
		thermo3 = self.mop3.getThermoData(mol)
			
		self.assertTrue(thermo1.comment.startswith('QM MopacMolPM3'))
		self.assertTrue(thermo2.comment.startswith('QM MopacMolPM6'))
		self.assertTrue(thermo3.comment.startswith('QM MopacMolPM7'))
		
		self.assertAlmostEqual(thermo1.H298.value_si, 169708.0608, 1) # to 1 decimal place
		self.assertAlmostEqual(thermo1.S298.value_si, 334.5007584, 1) # to 1 decimal place
		self.assertAlmostEqual(thermo2.H298.value_si, 167704.4270, 1) # to 1 decimal place
		self.assertAlmostEqual(thermo2.S298.value_si, 338.0999241, 1) # to 1 decimal place
		self.assertAlmostEqual(thermo3.H298.value_si, 166168.8571, 1) # to 1 decimal place
		self.assertAlmostEqual(thermo3.S298.value_si, 336.3330406, 1) # to 1 decimal place
    def test_is_bond_conjugated_3(self):

        mol_test = Molecule().fromAdjacencyList(
            """1  C u0 p0 c0 {2,D} {6,S} {7,S}
2  C u0 p0 c0 {1,D} {3,S} {8,S}
3  C u0 p0 c0 {2,S} {4,D} {9,S}
4  C u0 p0 c0 {3,D} {5,S} {10,S}
5  C u0 p0 c0 {4,S} {6,D} {11,S}
6  C u0 p0 c0 {1,S} {5,D} {12,S}
7  H u0 p0 c0 {1,S}
8  H u0 p0 c0 {2,S}
9  H u0 p0 c0 {3,S}
10 H u0 p0 c0 {4,S}
11 H u0 p0 c0 {5,S}
12 H u0 p0 c0 {6,S}
""")
        atom0 = mol_test.atoms[0]
        atom1 = mol_test.atoms[1]
        atom6 = mol_test.atoms[6]
        bond01 = atom0.bonds[atom1]
        bond06 = atom0.bonds[atom6]

        self.assertTrue(is_bond_conjugated(bond01))
        self.assertFalse(is_bond_conjugated(bond06))
    def test_is_atom_in_rings(self):

        mol_test = Molecule().fromAdjacencyList(
            """1  C u0 p0 c0 {2,S} {11,S} {12,S} {13,S}
2  C u0 p0 c0 {1,S} {3,S} {14,S} {15,S}
3  C u0 p0 c0 {2,S} {4,S} {10,S} {16,S}
4  C u0 p0 c0 {3,S} {5,S} {9,S} {17,S}
5  C u0 p0 c0 {4,S} {6,S} {18,S} {19,S}
6  S u0 p2 c0 {5,S} {7,S}
7  C u0 p0 c0 {6,S} {8,S} {10,S} {20,S}
8  C u0 p0 c0 {7,S} {9,S} {21,S} {22,S}
9  C u0 p0 c0 {4,S} {8,S} {23,S} {24,S}
10 C u0 p0 c0 {3,S} {7,S} {11,S} {25,S}
11 C u0 p0 c0 {1,S} {10,S} {26,S} {27,S}
12 H u0 p0 c0 {1,S}
13 H u0 p0 c0 {1,S}
14 H u0 p0 c0 {2,S}
15 H u0 p0 c0 {2,S}
16 H u0 p0 c0 {3,S}
17 H u0 p0 c0 {4,S}
18 H u0 p0 c0 {5,S}
19 H u0 p0 c0 {5,S}
20 H u0 p0 c0 {7,S}
21 H u0 p0 c0 {8,S}
22 H u0 p0 c0 {8,S}
23 H u0 p0 c0 {9,S}
24 H u0 p0 c0 {9,S}
25 H u0 p0 c0 {10,S}
26 H u0 p0 c0 {11,S}
27 H u0 p0 c0 {11,S}
""")
        atom5 = mol_test.atoms[5]
        atom5_in_rings = is_atom_in_ring(mol_test, atom5)
        expected_atom5_in_rings = [0, 0, 0, 2, 0, 0]

        self.assertEqual(atom5_in_rings, expected_atom5_in_rings)
示例#31
0
 def load_entry(self,
                index,
                label,
                molecule,
                statmech,
                reference=None,
                referenceType='',
                shortDesc='',
                longDesc='',
                ):
     """
     Method for parsing entries in database files.
     Note that these argument names are retained for backward compatibility.
     """
     self.entries[label] = Entry(
         index=index,
         label=label,
         item=Molecule().from_adjacency_list(molecule),
         data=statmech,
         reference=reference,
         reference_type=referenceType,
         short_desc=shortDesc,
         long_desc=longDesc.strip(),
     )
示例#32
0
    def loadEntry(self,
                  index,
                  reactant1=None,
                  reactant2=None,
                  reactant3=None,
                  product1=None,
                  product2=None,
                  product3=None,
                  kinetics=None,
                  degeneracy=1,
                  label='',
                  duplicate=False,
                  reversible=True,
                  reference=None,
                  referenceType='',
                  shortDesc='',
                  longDesc='',
                  rank=None,
                  ):
        
        reactants = [Molecule().fromAdjacencyList(reactant1)]
        if reactant2 is not None: reactants.append(Molecule().fromAdjacencyList(reactant2))
        if reactant3 is not None: reactants.append(Molecule().fromAdjacencyList(reactant3))

        products = [Molecule().fromAdjacencyList(product1)]
        if product2 is not None: products.append(Molecule().fromAdjacencyList(product2))
        if product3 is not None: products.append(Molecule().fromAdjacencyList(product3))
        
        reaction = Reaction(reactants=reactants, products=products, degeneracy=degeneracy, duplicate=duplicate, reversible=reversible)
        
        entry = Entry(
            index = index,
            label = label,
            item = reaction,
            data = kinetics,
            reference = reference,
            referenceType = referenceType,
            shortDesc = shortDesc,
            longDesc = longDesc.strip(),
            rank = rank,
        )
        self.entries['{0:d}:{1}'.format(index,label)] = entry
        return entry
示例#33
0
        def check_isomorphic(conformer):
            """
            Compares whatever is in the log file 'f' 
            to the SMILES of the passed in 'conformer'
            """
            starting_molecule = RMGMolecule(SMILES=conformer.smiles)
            starting_molecule = starting_molecule.toSingleBonds()

            atoms = self.read_log(os.path.join(scratch_dir, f))

            test_molecule = RMGMolecule()
            test_molecule.fromXYZ(atoms.arrays["numbers"],
                                  atoms.arrays["positions"])
            if not starting_molecule.isIsomorphic(test_molecule):
                logging.info(
                    "Output geometry of {} is not isomorphic with input geometry"
                    .format(calc.label))
                return False
            else:
                logging.info("{} was successful and was validated!".format(
                    calc.label))
                return True
                fw.write('{} {}\n'.format(smi,cc_true))'''

sum_list=[]
mol_list={}

with open('134k_withF.csv') as df:
    csvr=csv.reader(df)
    q=0
    for moledata in csvr:
        if q<1:
            q+=1
        elif q>0:
            q+=1
            smi=moledata[0]
            b3lyp_hf=moledata[1]
            mol=Molecule().fromSMILES(smi,backend='rdkit-first')
            mol_list[mol]=b3lyp_hf

with open('trainingset_high_level+TRC+bacfit(source).csv') as csvf:
    csvd=csv.reader(csvf)
    q=0
    i=0
    for line in csvd:
        if q<1:
            q+=1
        elif q>0:
            smi=line[0]
            h_f=line[1]
            source=str(line[2])
            mol=Molecule().fromSMILES(smi,backend='rdkit-first')
            for base_mol in mol_list:
示例#35
0
文件: loader.py 项目: mbprend/RMG-Py
def load_rmg_java_job(input_file, chemkin_file=None, species_dict=None, generate_images=True,
                      use_chemkin_names=False, check_duplicates=True):
    """
    Load the results of an RMG-Java job generated from the given `input_file`.
    """
    warnings.warn("The RMG-Java input is no longer supported and may be" \
                  "removed in version 2.3.", DeprecationWarning)
    from rmgpy.rmg.main import RMG
    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(input_file=input_file)
    rmg.load_rmg_java_input(input_file)
    rmg.output_directory = os.path.abspath(os.path.dirname(input_file))

    # Load the final Chemkin model generated by RMG-Java
    if not chemkin_file:
        chemkin_file = os.path.join(os.path.dirname(input_file), 'chemkin', 'chem.inp')
    if not species_dict:
        species_dict = os.path.join(os.path.dirname(input_file), 'RMG_Dictionary.txt')
    species_list, reaction_list = load_chemkin_file(chemkin_file, species_dict,
                                                    use_chemkin_names=use_chemkin_names,
                                                    check_duplicates=check_duplicates)

    # Bath gas species don't appear in RMG-Java species dictionary, so handle
    # those as a special case
    for species in species_list:
        if species.label == 'Ar':
            species.molecule = [Molecule().from_smiles('[Ar]')]
        elif species.label == 'Ne':
            species.molecule = [Molecule().from_smiles('[Ne]')]
        elif species.label == 'He':
            species.molecule = [Molecule().from_smiles('[He]')]
        elif species.label == 'N2':
            species.molecule = [Molecule().from_smiles('N#N')]

    # Map species in input file to corresponding species in Chemkin file
    species_dict = {}
    for spec0 in rmg.initial_species:
        for species in species_list:
            if species.is_isomorphic(spec0):
                species_dict[spec0] = species
                break

    # Generate flux pairs for each reaction if needed
    for reaction in reaction_list:
        if not reaction.pairs:
            reaction.generate_pairs()

    # Replace species in input file with those in Chemkin file
    for reaction_system in rmg.reaction_systems:
        reaction_system.initial_mole_fractions = dict(
            [(species_dict[spec], frac) for spec, frac in reaction_system.initial_mole_fractions.items()])
        for t in reaction_system.termination:
            if isinstance(t, TerminationConversion):
                if t.species not in list(species_dict.values()):
                    t.species = species_dict[t.species]

    # Set reaction model to match model loaded from Chemkin file
    rmg.reaction_model.core.species = species_list
    rmg.reaction_model.core.reactions = reaction_list

    # RMG-Java doesn't generate species images, so draw them ourselves now
    if generate_images:
        species_path = os.path.join(os.path.dirname(input_file), 'species')
        try:
            os.mkdir(species_path)
        except OSError:
            pass
        for species in species_list:
            path = os.path.join(species_path + '/{0!s}.png'.format(species))
            if not os.path.exists(path):
                species.molecule[0].draw(str(path))

    return rmg
示例#36
0
    def verifyOutputFile(self):
        """
        Check's that an output file exists and was successful.
        
        Returns a boolean flag that states whether a successful MOPAC simulation already exists for the molecule with the 
        given (augmented) InChI Key.
        
        The definition of finding a successful simulation is based on these criteria:
        1) finding an output file with the file name equal to the InChI Key
        2) NOT finding any of the keywords that are denote a calculation failure
        3) finding all the keywords that denote a calculation success.
        4) finding a match between the InChI of the given molecule and the InchI found in the calculation files
        5) checking that the optimized geometry, when connected by single bonds, is isomorphic with self.molecule (converted to single bonds)
        
        If any of the above criteria is not matched, False will be returned.
        If all succeed, then it will return True.
        """
        if not os.path.exists(self.outputFilePath):
            logging.debug("Output file {0} does not (yet) exist.".format(self.outputFilePath))
            return False
    
        InChIMatch=False #flag (1 or 0) indicating whether the InChI in the file matches InChIaug this can only be 1 if InChIFound is also 1
        InChIFound=False #flag (1 or 0) indicating whether an InChI was found in the log file
        
        # Initialize dictionary with "False"s 
        successKeysFound = dict([(key, False) for key in self.successKeys])
        
        with open(self.outputFilePath) as outputFile:
            for line in outputFile:
                line = line.strip()
                
                for element in self.failureKeys: #search for failure keywords
                    if element in line:
                        logging.error("MOPAC output file contains the following error: {0}".format(element) )
                        return False
                
                for element in self.successKeys: #search for success keywords
                    if element in line:
                        successKeysFound[element] = True
                
                if "InChI=" in line:
                    logFileInChI = line #output files should take up to 240 characters of the name in the input file
                    InChIFound = True
                    if self.uniqueIDlong in logFileInChI:
                        InChIMatch = True
                    elif self.uniqueIDlong.startswith(logFileInChI):
                        logging.info("InChI too long to check, but beginning matches so assuming OK.")
                        InChIMatch = True
                    else:
                        logging.warning("InChI in log file ({0}) didn't match that in geometry ({1}).".format(logFileInChI, self.uniqueIDlong))                    
                        # Use only up to first 80 characters to match due to MOPAC bug which deletes 81st character of InChI string
                        if self.uniqueIDlong.startswith(logFileInChI[:80]):
                            logging.warning("but the beginning matches so it's probably just a truncation problem.")
                            InChIMatch = True
        # Check that ALL 'success' keywords were found in the file.
        if not all( successKeysFound.values() ):
            logging.error('Not all of the required keywords for success were found in the output file!')
            return False
        
        if not InChIFound:
            logging.error("No InChI was found in the MOPAC output file {0}".format(self.outputFilePath))
            return False
        
        if not InChIMatch:
            #InChIs do not match (most likely due to limited name length mirrored in log file (240 characters), but possibly due to a collision)
            return self.checkForInChiKeyCollision(logFileInChI) # Not yet implemented!

        # Compare the optimized geometry to the original molecule
        qmData = self.parse()
        cclibMol = Molecule()
        cclibMol.fromXYZ(qmData.atomicNumbers, qmData.atomCoords.value)
        testMol = self.molecule.toSingleBonds()
        if not cclibMol.isIsomorphic(testMol):
            logging.info("Incorrect connectivity for optimized geometry in file {0}".format(self.outputFilePath))
            return False

        logging.info("Successful {1} quantum result in {0}".format(self.outputFilePath, self.__class__.__name__))
        return True
        
        #InChIs do not match (most likely due to limited name length mirrored in log file (240 characters), but possibly due to a collision)
        return self.checkForInChiKeyCollision(logFileInChI) # Not yet implemented!
示例#37
0
from rmgpy.molecule import Molecule
from rmgpy.qm.mopac import Mopac, MopacMolPM3, MopacMolPM6, MopacMolPM7
from rmgpy.exceptions import DependencyError

NO_MOPAC = NO_LICENCE = False
try:
    Mopac().testReady()
except DependencyError as e:
    if "Couldn't find MOPAC executable" in e.message:
        NO_MOPAC = NO_LICENCE = True
    elif 'To install the MOPAC license' in e.message or 'MOPAC_LICENSE' in e.message:
        NO_LICENCE = True
    else:
        raise

mol1 = Molecule().fromSMILES('C1=CC=C2C=CC=CC2=C1')


class TestMopacMolPM3(unittest.TestCase):
    """
    Contains unit tests for the Geometry class.
    """
    @unittest.skipIf(
        NO_MOPAC,
        "MOPAC not found. Try resetting your environment variables if you want to use it."
    )
    @unittest.skipIf(NO_LICENCE,
                     "MOPAC license not installed. Run mopac for instructions")
    def setUp(self):
        """
        A function run before each unit test in this class.
示例#38
0
 def setUp(self):
     """
     A function run before each unit test in this class.
     """
     self.drawer = MoleculeDrawer()
     self.molecule = Molecule(SMILES='CC(=O)CC')
示例#39
0
    def testColliderModel(self):
        """
        Test the solver's ability to simulate a model with collision efficiencies.
        """
        chemFile = os.path.join(os.path.dirname(__file__), 'files',
                                'collider_model', 'chem.inp')
        dictionaryFile = os.path.join(os.path.dirname(__file__), 'files',
                                      'collider_model',
                                      'species_dictionary.txt')
        speciesList, reactionList = loadChemkinFile(chemFile, dictionaryFile)

        smilesDict = {
            'H': '[H]',
            'HO2': '[O]O',
            'O2': '[O][O]',
            'Ar': '[Ar]',
            'N2': 'N#N',
            'CO2': 'O=C=O',
            'CH3': '[CH3]',
            'CH4': 'C'
        }
        speciesDict = {}
        for name, smiles in smilesDict.iteritems():
            mol = Molecule(SMILES=smiles)
            for species in speciesList:
                if species.isIsomorphic(mol):
                    speciesDict[name] = species
                    break

        T = 1000  # K
        P = 10  # Pa
        initialMoleFractions = {
            speciesDict['O2']: 0.5,
            speciesDict['H']: 0.5,
            speciesDict['CO2']: 1.0,
            speciesDict['Ar']: 4.0
        }

        # Initialize the model
        rxnSystem = SimpleReactor(T,
                                  P,
                                  initialMoleFractions=initialMoleFractions,
                                  termination=None)
        rxnSystem.initializeModel(speciesList, reactionList, [], [])

        # Advance to time = 0.1 s
        rxnSystem.advance(0.1)
        # Compare simulated mole fractions with expected mole fractions from CHEMKIN
        simulatedMoleFracs = rxnSystem.y / numpy.sum(rxnSystem.y)
        expectedMoleFracs = numpy.array([
            0.6666667, 0, 0, 0, 0.1666667, 0, 0.08333333, 0.08333333,
            2.466066000000000E-10, 0, 0, 0, 0, 0
        ])
        for i in range(len(simulatedMoleFracs)):
            self.assertAlmostEqual(simulatedMoleFracs[i], expectedMoleFracs[i])

        # Advance to time = 5 s
        rxnSystem.advance(5)
        # Compare simulated mole fractions with expected mole fractions from CHEMKIN
        simulatedMoleFracs = rxnSystem.y / numpy.sum(rxnSystem.y)
        expectedMoleFracs = numpy.array([
            0.6666667, 0, 0, 0, 0.1666667, 0, 0.08333332, 0.08333332,
            1.233033000000000E-08, 0, 0, 0, 0, 0
        ])
        for i in range(len(simulatedMoleFracs)):
            self.assertAlmostEqual(simulatedMoleFracs[i], expectedMoleFracs[i])

        # Try a new set of conditions

        T = 850  # K
        P = 200  # Pa
        initialMoleFractions = {
            speciesDict['O2']: 0.5,
            speciesDict['H']: 1,
            speciesDict['CO2']: 1,
            speciesDict['N2']: 4,
            speciesDict['CH3']: 1
        }

        # Initialize the model
        rxnSystem = SimpleReactor(T,
                                  P,
                                  initialMoleFractions=initialMoleFractions,
                                  termination=None)
        rxnSystem.initializeModel(speciesList, reactionList, [], [])

        # Advance to time = 5 s
        rxnSystem.advance(5)

        # Compare simulated mole fractions with expected mole fractions from CHEMKIN
        simulatedMoleFracs = rxnSystem.y / numpy.sum(rxnSystem.y)
        expectedMoleFracs = numpy.array([
            0, 0, 0, 0.5487241, 0.137181, 0, 0.1083234, 0.0685777,
            1.280687000000000E-05, 0, 0, 0, 0.1083362, 0.02884481
        ])
        for i in range(len(simulatedMoleFracs)):
            self.assertAlmostEqual(simulatedMoleFracs[i], expectedMoleFracs[i])
示例#40
0
def SMARTS(string):
    return Molecule().fromSMARTS(string)
    def test_intra_H_migration(self):
        """
        Test that the intra_H_migration family, which is its own reverse, returns a properly re-labeled product structure.
        """
        family = self.database.families['intra_H_migration']
        reactants = [Molecule().fromAdjacencyList("""
multiplicity 2
1  *2 C u0 p0 c0 {3,S} {11,S} {12,S} {13,S}
2  *4 C u0 p0 c0 {4,S} {5,S} {6,D}
3  *5 C u0 p0 c0 {1,S} {7,D} {14,S}
4  *1 C u1 p0 c0 {2,S} {8,S} {15,S}
5     C u0 p0 c0 {2,S} {10,D} {17,S}
6  *6 C u0 p0 c0 {2,D} {7,S} {19,S}
7  *7 C u0 p0 c0 {3,D} {6,S} {21,S}
8     C u0 p0 c0 {4,S} {9,D} {16,S}
9     C u0 p0 c0 {8,D} {10,S} {20,S}
10    C u0 p0 c0 {5,D} {9,S} {18,S}
11 *3 H u0 p0 c0 {1,S}
12    H u0 p0 c0 {1,S}
13    H u0 p0 c0 {1,S}
14    H u0 p0 c0 {3,S}
15    H u0 p0 c0 {4,S}
16    H u0 p0 c0 {8,S}
17    H u0 p0 c0 {5,S}
18    H u0 p0 c0 {10,S}
19    H u0 p0 c0 {6,S}
20    H u0 p0 c0 {9,S}
21    H u0 p0 c0 {7,S}
""")]
        expectedProduct = Molecule().fromAdjacencyList("""
multiplicity 2
1  *1 C u1 p0 c0 {3,S} {12,S} {13,S}
2  *5 C u0 p0 c0 {4,S} {5,S} {6,D}
3  *4 C u0 p0 c0 {1,S} {7,D} {14,S}
4  *2 C u0 p0 c0 {2,S} {11,S} {8,S} {15,S}
5     C u0 p0 c0 {2,S} {10,D} {17,S}
6  *7 C u0 p0 c0 {2,D} {7,S} {19,S}
7  *6 C u0 p0 c0 {3,D} {6,S} {21,S}
8     C u0 p0 c0 {4,S} {9,D} {16,S}
9     C u0 p0 c0 {8,D} {10,S} {20,S}
10    C u0 p0 c0 {5,D} {9,S} {18,S}
11 *3 H u0 p0 c0 {4,S}
12    H u0 p0 c0 {1,S}
13    H u0 p0 c0 {1,S}
14    H u0 p0 c0 {3,S}
15    H u0 p0 c0 {4,S}
16    H u0 p0 c0 {8,S}
17    H u0 p0 c0 {5,S}
18    H u0 p0 c0 {10,S}
19    H u0 p0 c0 {6,S}
20    H u0 p0 c0 {9,S}
21    H u0 p0 c0 {7,S}
""")
        products = family.applyRecipe(reactants)

        self.assertEqual(len(products), 1)

        mapping = {}
        for label, atom in expectedProduct.getLabeledAtoms().iteritems():
            mapping[atom] = products[0].getLabeledAtom(label)

        self.assertTrue(expectedProduct.isIsomorphic(products[0], mapping))
示例#42
0
文件: thermo.py 项目: jbarlow3/RMG-Py
    def estimateThermoViaGroupAdditivity(self, molecule):
        """
        Return the set of thermodynamic parameters corresponding to a given
        :class:`Molecule` object `molecule` by estimation using the group
        additivity values. If no group additivity values are loaded, a
        :class:`DatabaseError` is raised.
        """
        # For thermo estimation we need the atoms to already be sorted because we
        # iterate over them; if the order changes during the iteration then we
        # will probably not visit the right atoms, and so will get the thermo wrong
        molecule.sortVertices()

        # Create the ThermoData object
        thermoData = ThermoData(
            Tdata = ([300,400,500,600,800,1000,1500],"K"),
            Cpdata = ([0.0,0.0,0.0,0.0,0.0,0.0,0.0],"J/(mol*K)"),
            H298 = (0.0,"kJ/mol"),
            S298 = (0.0,"J/(mol*K)"),
        )

        if sum([atom.radicalElectrons for atom in molecule.atoms]) > 0: # radical species

            # Make a copy of the structure so we don't change the original
            saturatedStruct = molecule.copy(deep=True)

            # Saturate structure by replacing all radicals with bonds to
            # hydrogen atoms
            added = {}
            for atom in saturatedStruct.atoms:
                for i in range(atom.radicalElectrons):
                    H = Atom('H')
                    bond = Bond(atom, H, 'S')
                    saturatedStruct.addAtom(H)
                    saturatedStruct.addBond(bond)
                    if atom not in added:
                        added[atom] = []
                    added[atom].append([H, bond])
                    atom.decrementRadical()

            # Update the atom types of the saturated structure (not sure why
            # this is necessary, because saturating with H shouldn't be
            # changing atom types, but it doesn't hurt anything and is not
            # very expensive, so will do it anyway)
            saturatedStruct.updateConnectivityValues()
            saturatedStruct.sortVertices()
            saturatedStruct.updateAtomTypes()

            # Get thermo estimate for saturated form of structure
            thermoData = self.estimateThermoViaGroupAdditivity(saturatedStruct)
            assert thermoData is not None, "Thermo data of saturated {0} of molecule {1} is None!".format(saturatedStruct, molecule)
            # Undo symmetry number correction for saturated structure
            thermoData.S298.value_si += constants.R * math.log(saturatedStruct.symmetryNumber)

            # For each radical site, get radical correction
            # Only one radical site should be considered at a time; all others
            # should be saturated with hydrogen atoms
            for atom in added:

                # Remove the added hydrogen atoms and bond and restore the radical
                for H, bond in added[atom]:
                    saturatedStruct.removeBond(bond)
                    saturatedStruct.removeAtom(H)
                    atom.incrementRadical()

                saturatedStruct.updateConnectivityValues()
                
                try:
                    self.__addGroupThermoData(thermoData, self.groups['radical'], saturatedStruct, {'*':atom})
                except KeyError:
                    logging.error("Couldn't find in radical thermo database:")
                    logging.error(molecule)
                    logging.error(molecule.toAdjacencyList())
                    raise
                        
                # Re-saturate
                for H, bond in added[atom]:
                    saturatedStruct.addAtom(H)
                    saturatedStruct.addBond(bond)
                    atom.decrementRadical()

                # Subtract the enthalpy of the added hydrogens
                for H, bond in added[atom]:
                    thermoData.H298.value_si -= 52.103 * 4184

            # Correct the entropy for the symmetry number

        else: # non-radical species
            # Generate estimate of thermodynamics
            for atom in molecule.atoms:
                # Iterate over heavy (non-hydrogen) atoms
                if atom.isNonHydrogen():
                    # Get initial thermo estimate from main group database
                    try:
                        self.__addGroupThermoData(thermoData, self.groups['group'], molecule, {'*':atom})
                    except KeyError:
                        logging.error("Couldn't find in main thermo database:")
                        logging.error(molecule)
                        logging.error(molecule.toAdjacencyList())
                        raise
                    # Correct for gauche and 1,5- interactions
                    try:
                        self.__addGroupThermoData(thermoData, self.groups['gauche'], molecule, {'*':atom})
                    except KeyError: pass
                    try:
                        self.__addGroupThermoData(thermoData, self.groups['int15'], molecule, {'*':atom})
                    except KeyError: pass
                    try:
                        self.__addGroupThermoData(thermoData, self.groups['other'], molecule, {'*':atom})
                    except KeyError: pass

            # Do ring corrections separately because we only want to match
            # each ring one time; this doesn't work yet
            rings = molecule.getSmallestSetOfSmallestRings()
            for ring in rings:
                # Make a temporary structure containing only the atoms in the ring
                # NB. if any of the ring corrections depend on ligands not in the ring, they will not be found!
                ringStructure = Molecule()
                newAtoms = dict()
                for atom in ring:
                    newAtoms[atom] = atom.copy()
                    ringStructure.addAtom(newAtoms[atom]) # (addAtom deletes the atom's bonds)
                for atom1 in ring:
                    for atom2 in ring:
                        if molecule.hasBond(atom1, atom2):
                            ringStructure.addBond(Bond(newAtoms[atom1], newAtoms[atom2], atom1.bonds[atom2].order ))

                # Get thermo correction for this ring
                try:
                    self.__addGroupThermoData(thermoData, self.groups['ring'], ringStructure, {})
                except KeyError:
                    logging.error("Couldn't find in ring database:")
                    logging.error(ringStructure)
                    logging.error(ringStructure.toAdjacencyList())
                    raise
                
        # Correct entropy for symmetry number
        molecule.calculateSymmetryNumber()
        thermoData.S298.value_si -= constants.R * math.log(molecule.symmetryNumber)

        return thermoData
示例#43
0
def example():
    """Create a set of sample tables"""

    # In practice, you'd most likely be embedding your HTML tables in
    # a web page template. For demonstration purposes, we'll create a
    # simple page with a few default styles.
    htmlheader = """\
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>Sample table</title>
<style type="text/css">
body { font-family: Helvetica,Arial,FreeSans; }
table.reporttable { border-style: solid; border-width: 1px; }
table.reporttable tr.tr_odd { background-color: #eee; }
table.reporttable tr.tr_even { background-color: #bbb; }
table.reporttable th { background-color: blue; color: white; }
table.reporttable td.cell_bold { font-weight: bold; }
table.reporttable td.cell_money { text-align: right; font-family: monospace; }
</style>
</head>
<body>
"""
    htmlfooter = """\
</body>
</html>"""

    exampletypes = ((PDFTable, 'pdf'), (HTMLTable, 'html'), (SpreadsheetTable, 'xls'))

    #### Example with several row types

#    mainrs = RowSpec(
#        ColumnSpec('foo', 'Column 1', width=1),
#        ColumnSpec('bar', 'Column 2', width=1),
#        ColumnSpec('baz', 'Column 3', width=1),
#        ColumnSpec('qux', 'Column 4', width=4))
#
#    subrow1 = RowSpec(
#        ColumnSpec('subfoo1', 'First wide column', bold=True, span=2, width=2),
#        ColumnSpec('subbar1', 'Second wide column', span=2))
#
#    subrow2 = RowSpec(
#        ColumnSpec('subfoo2', 'A table-wide column', span=4))
#
#    summaryrow = RowSpec(
#        ColumnSpec('junk1', span=2, width=2),
#        ColumnSpec('baz', bold=True, width=1),
#        ColumnSpec('junk2'))
#
#    lines = []
#    lines.append([mainrs({'foo': 1, 'bar': 2, 'baz': 3, 'qux': 'Bar.  ' * 30}),
#                  subrow1({'subfoo1': 'And', 'subbar1': 'another'}),
#                  subrow2({'subfoo2': 'This is a test.  ' * 15}),
#                  subrow2({'subfoo2': 'And another test'})])
#    for i in range(5):
#        lines.append(mainrs({'foo': i, 'bar': 14, 'baz': 15, 'qux': 'extra'}))
#    lines.append(summaryrow({'junk1': None, 'baz': 'Summary!', 'junk2': None}))
#
#    for tableclass, extension in exampletypes:
#        outfile = open('showcase.%s' % extension, 'wb')
#        if tableclass is HTMLTable:
#            outfile.write(htmlheader)
#        outfile.write(tableclass('Sample Table',
#                                 '%s test' % extension.upper(),
#                                 headers=[mainrs, subrow1, subrow2]).render(lines))
#        if tableclass is HTMLTable:
#            outfile.write(htmlfooter)

    #### Converting species dictionary from RMG-Java in bond connectivity
    # format into the smile and 

    import decimal
    import random
    import numpy as np
    import csv
    import itertools
    from rmgpy.molecule import Molecule

    #reading text file of species
    groups= []
    uniquekeys = []
    def isa_group_separator(line):
        return line=='\n'
    
    with open('Species_Dictionary.txt') as f:
        for key,group in itertools.groupby(f,isa_group_separator):
            groups.append(list(group))
            uniquekeys.append(key)
        #print groups , len(groups)
    
    # Since empty lines are appered as seperate lists in the groups lis,
    # this section is removing them from the final list
    groupsb = list()
    for sublist in groups:
        if not any(map(str.strip, sublist)):  # this detects blanks
            continue  # it was blank, so skip it
        if sublist not in groupsb:  # this detects duplicates
            groupsb.append(sublist)
    #print groupsb , len (groupsb)
    
    # remove '\n' from each item in list
    def stripp(x):
        return x.strip('\n')
    
    groupsb=[list(map(stripp,x)) for x in groupsb]
    #print groupsb 

    rows = []
    for index, adjacency_list in enumerate(groupsb, start=1):
        species_name = adjacency_list[0]
        mol = Molecule().fromAdjacencyList('\n'.join(adjacency_list))
        smiles = mol.toSMILES()
        rows.append({'Index': index,
                     'Species': species_name,
                     'SMILES': smiles,
                     'Molecule': mol,
                     })
    print "Made {num} rows".format(num=len(rows))

    invoicerow = RowSpec(ColumnSpec('Index', 'Index #'),
                         ColumnSpec('Species', 'Species Name'),
                         ColumnSpec('SMILES', 'SMILES'),
                         ColumnSpec('Molecule', 'Molecule'),
                         )
    lines = invoicerow.makeall(rows)

    def image(mol):
        from base64 import b64encode
        src = mol._repr_png_()
        encoded = b64encode(src)
        return '<img alt="{name}" src="data:image/png;base64,{data}" />'.format(name=mol.toSMILES(), data=encoded)
    image.htmlsafe = True
    def blank(mol):
        return ''

    for tableclass, extension in exampletypes:
        outfile = open('Species.%s' % extension, 'wb')

        if tableclass is HTMLTable:
            tableclass.castfunctions[Molecule] = image
        else:
            tableclass.castfunctions[Molecule] = blank

        if tableclass is HTMLTable:
            outfile.write(htmlheader)
        outfile.write(tableclass('Species dictionary',
                                 'species list from RMG-java generated mechanism for bio-oil gasification',
                                 headers=invoicerow).render(lines))
        if tableclass is HTMLTable:
            outfile.write(htmlfooter)
def str_to_mol(s):
    if s.startswith('InChI'):
        mol = Molecule().fromInChI(s, backend='rdkit-first')
    else:
        mol = Molecule().fromSMILES(s, backend='rdkit-first')
    return mol
示例#45
0
def InChI(string):
    return Molecule().fromInChI(string)
示例#46
0
    def testSolve(self):
        """
        Test the simple batch reactor with a simple kinetic model. Here we
        choose a kinetic model consisting of the hydrogen abstraction reaction
        CH4 + C2H5 <=> CH3 + C2H6.
        """
        CH4 = Species(
            molecule=[Molecule().fromSMILES("C")],
            thermo=ThermoData(
                Tdata=([300, 400, 500, 600, 800, 1000, 1500], "K"),
                Cpdata=([8.615, 9.687, 10.963, 12.301, 14.841, 16.976,
                         20.528], "cal/(mol*K)"),
                H298=(-17.714, "kcal/mol"),
                S298=(44.472, "cal/(mol*K)")))
        CH3 = Species(molecule=[Molecule().fromSMILES("[CH3]")],
                      thermo=ThermoData(
                          Tdata=([300, 400, 500, 600, 800, 1000, 1500], "K"),
                          Cpdata=([
                              9.397, 10.123, 10.856, 11.571, 12.899, 14.055,
                              16.195
                          ], "cal/(mol*K)"),
                          H298=(9.357, "kcal/mol"),
                          S298=(45.174, "cal/(mol*K)")))
        C2H6 = Species(molecule=[Molecule().fromSMILES("CC")],
                       thermo=ThermoData(
                           Tdata=([300, 400, 500, 600, 800, 1000, 1500], "K"),
                           Cpdata=([
                               12.684, 15.506, 18.326, 20.971, 25.500, 29.016,
                               34.595
                           ], "cal/(mol*K)"),
                           H298=(-19.521, "kcal/mol"),
                           S298=(54.799, "cal/(mol*K)")))
        C2H5 = Species(molecule=[Molecule().fromSMILES("C[CH2]")],
                       thermo=ThermoData(
                           Tdata=([300, 400, 500, 600, 800, 1000, 1500], "K"),
                           Cpdata=([
                               11.635, 13.744, 16.085, 18.246, 21.885, 24.676,
                               29.107
                           ], "cal/(mol*K)"),
                           H298=(29.496, "kcal/mol"),
                           S298=(56.687, "cal/(mol*K)")))

        rxn1 = Reaction(reactants=[C2H6, CH3],
                        products=[C2H5, CH4],
                        kinetics=Arrhenius(A=(686.375 * 6, 'm^3/(mol*s)'),
                                           n=4.40721,
                                           Ea=(7.82799, 'kcal/mol'),
                                           T0=(298.15, 'K')))

        coreSpecies = [CH4, CH3, C2H6, C2H5]
        edgeSpecies = []
        coreReactions = [rxn1]
        edgeReactions = []

        T = 1000
        P = 1.0e5
        rxnSystem = SimpleReactor(T,
                                  P,
                                  initialMoleFractions={
                                      C2H5: 0.1,
                                      CH3: 0.1,
                                      CH4: 0.4,
                                      C2H6: 0.4
                                  },
                                  termination=[])

        rxnSystem.initializeModel(coreSpecies, coreReactions, edgeSpecies,
                                  edgeReactions)

        tlist = numpy.array([10**(i / 10.0) for i in range(-130, -49)],
                            numpy.float64)

        # Integrate to get the solution at each time point
        t = []
        y = []
        reactionRates = []
        speciesRates = []
        for t1 in tlist:
            rxnSystem.advance(t1)
            t.append(rxnSystem.t)
            # You must make a copy of y because it is overwritten by DASSL at
            # each call to advance()
            y.append(rxnSystem.y.copy())
            reactionRates.append(rxnSystem.coreReactionRates.copy())
            speciesRates.append(rxnSystem.coreSpeciesRates.copy())

        # Convert the solution vectors to numpy arrays
        t = numpy.array(t, numpy.float64)
        y = numpy.array(y, numpy.float64)
        reactionRates = numpy.array(reactionRates, numpy.float64)
        speciesRates = numpy.array(speciesRates, numpy.float64)
        V = constants.R * rxnSystem.T.value_si * numpy.sum(
            y) / rxnSystem.P.value_si

        # Check that we're computing the species fluxes correctly
        for i in range(t.shape[0]):
            self.assertAlmostEqual(reactionRates[i, 0],
                                   speciesRates[i, 0],
                                   delta=1e-6 * reactionRates[i, 0])
            self.assertAlmostEqual(reactionRates[i, 0],
                                   -speciesRates[i, 1],
                                   delta=1e-6 * reactionRates[i, 0])
            self.assertAlmostEqual(reactionRates[i, 0],
                                   -speciesRates[i, 2],
                                   delta=1e-6 * reactionRates[i, 0])
            self.assertAlmostEqual(reactionRates[i, 0],
                                   speciesRates[i, 3],
                                   delta=1e-6 * reactionRates[i, 0])

        # Check that we've reached equilibrium
        self.assertAlmostEqual(reactionRates[-1, 0], 0.0, delta=1e-2)

        #######
        # Unit test for the jacobian function:
        # Solve a reaction system and check if the analytical jacobian matches the finite difference jacobian

        H2 = Species(molecule=[Molecule().fromSMILES("[H][H]")],
                     thermo=ThermoData(
                         Tdata=([300, 400, 500, 600, 800, 1000, 1500], "K"),
                         Cpdata=([6.89, 6.97, 6.99, 7.01, 7.08, 7.22,
                                  7.72], "cal/(mol*K)"),
                         H298=(0, "kcal/mol"),
                         S298=(31.23, "cal/(mol*K)")))

        rxnList = []
        rxnList.append(
            Reaction(reactants=[C2H6],
                     products=[CH3, CH3],
                     kinetics=Arrhenius(A=(686.375 * 6, '1/s'),
                                        n=4.40721,
                                        Ea=(7.82799, 'kcal/mol'),
                                        T0=(298.15, 'K'))))
        rxnList.append(
            Reaction(reactants=[CH3, CH3],
                     products=[C2H6],
                     kinetics=Arrhenius(A=(686.375 * 6, 'm^3/(mol*s)'),
                                        n=4.40721,
                                        Ea=(7.82799, 'kcal/mol'),
                                        T0=(298.15, 'K'))))

        rxnList.append(
            Reaction(reactants=[C2H6, CH3],
                     products=[C2H5, CH4],
                     kinetics=Arrhenius(A=(46.375 * 6, 'm^3/(mol*s)'),
                                        n=3.40721,
                                        Ea=(6.82799, 'kcal/mol'),
                                        T0=(298.15, 'K'))))
        rxnList.append(
            Reaction(reactants=[C2H5, CH4],
                     products=[C2H6, CH3],
                     kinetics=Arrhenius(A=(46.375 * 6, 'm^3/(mol*s)'),
                                        n=3.40721,
                                        Ea=(6.82799, 'kcal/mol'),
                                        T0=(298.15, 'K'))))

        rxnList.append(
            Reaction(reactants=[C2H5, CH4],
                     products=[CH3, CH3, CH3],
                     kinetics=Arrhenius(A=(246.375 * 6, 'm^3/(mol*s)'),
                                        n=1.40721,
                                        Ea=(3.82799, 'kcal/mol'),
                                        T0=(298.15, 'K'))))
        rxnList.append(
            Reaction(reactants=[CH3, CH3, CH3],
                     products=[C2H5, CH4],
                     kinetics=Arrhenius(A=(246.375 * 6, 'm^6/(mol^2*s)'),
                                        n=1.40721,
                                        Ea=(3.82799, 'kcal/mol'),
                                        T0=(298.15, 'K'))))  #

        rxnList.append(
            Reaction(reactants=[C2H6, CH3, CH3],
                     products=[C2H5, C2H5, H2],
                     kinetics=Arrhenius(A=(146.375 * 6, 'm^6/(mol^2*s)'),
                                        n=2.40721,
                                        Ea=(8.82799, 'kcal/mol'),
                                        T0=(298.15, 'K'))))
        rxnList.append(
            Reaction(reactants=[C2H5, C2H5, H2],
                     products=[C2H6, CH3, CH3],
                     kinetics=Arrhenius(A=(146.375 * 6, 'm^6/(mol^2*s)'),
                                        n=2.40721,
                                        Ea=(8.82799, 'kcal/mol'),
                                        T0=(298.15, 'K'))))

        rxnList.append(
            Reaction(reactants=[C2H6, C2H6],
                     products=[CH3, CH4, C2H5],
                     kinetics=Arrhenius(A=(1246.375 * 6, 'm^3/(mol*s)'),
                                        n=0.40721,
                                        Ea=(8.82799, 'kcal/mol'),
                                        T0=(298.15, 'K'))))
        rxnList.append(
            Reaction(reactants=[CH3, CH4, C2H5],
                     products=[C2H6, C2H6],
                     kinetics=Arrhenius(A=(46.375 * 6, 'm^6/(mol^2*s)'),
                                        n=0.10721,
                                        Ea=(8.82799, 'kcal/mol'),
                                        T0=(298.15, 'K'))))

        for rxn in rxnList:
            coreSpecies = [CH4, CH3, C2H6, C2H5, H2]
            edgeSpecies = []
            coreReactions = [rxn]

            rxnSystem0 = SimpleReactor(T,
                                       P,
                                       initialMoleFractions={
                                           CH4: 0.2,
                                           CH3: 0.1,
                                           C2H6: 0.35,
                                           C2H5: 0.15,
                                           H2: 0.2
                                       },
                                       termination=[])
            rxnSystem0.initializeModel(coreSpecies, coreReactions, edgeSpecies,
                                       edgeReactions)
            dydt0 = rxnSystem0.residual(0.0, rxnSystem0.y,
                                        numpy.zeros(rxnSystem0.y.shape))[0]
            numCoreSpecies = len(coreSpecies)
            dN = .000001 * sum(rxnSystem0.y)
            dN_array = dN * numpy.eye(numCoreSpecies)

            dydt = []
            for i in range(numCoreSpecies):
                rxnSystem0.y[i] += dN
                dydt.append(
                    rxnSystem0.residual(0.0, rxnSystem0.y,
                                        numpy.zeros(rxnSystem0.y.shape))[0])
                rxnSystem0.y[i] -= dN  # reset y to original y0

            # Let the solver compute the jacobian
            solverJacobian = rxnSystem0.jacobian(0.0, rxnSystem0.y, dydt0, 0.0)
            # Compute the jacobian using finite differences
            jacobian = numpy.zeros((numCoreSpecies, numCoreSpecies))
            for i in range(numCoreSpecies):
                for j in range(numCoreSpecies):
                    jacobian[i, j] = (dydt[j][i] - dydt0[i]) / dN
                    self.assertAlmostEqual(jacobian[i, j],
                                           solverJacobian[i, j],
                                           delta=abs(1e-4 * jacobian[i, j]))

        #print 'Solver jacobian'
        #print solverJacobian
        #print 'Numerical jacobian'
        #print jacobian

        ###
        # Unit test for the compute rate derivative
        rxnList = []
        rxnList.append(
            Reaction(reactants=[C2H6],
                     products=[CH3, CH3],
                     kinetics=Arrhenius(A=(686.375e6, '1/s'),
                                        n=4.40721,
                                        Ea=(7.82799, 'kcal/mol'),
                                        T0=(298.15, 'K'))))
        rxnList.append(
            Reaction(reactants=[C2H6, CH3],
                     products=[C2H5, CH4],
                     kinetics=Arrhenius(A=(46.375 * 6, 'm^3/(mol*s)'),
                                        n=3.40721,
                                        Ea=(6.82799, 'kcal/mol'),
                                        T0=(298.15, 'K'))))
        rxnList.append(
            Reaction(reactants=[C2H6, CH3, CH3],
                     products=[C2H5, C2H5, H2],
                     kinetics=Arrhenius(A=(146.375 * 6, 'm^6/(mol^2*s)'),
                                        n=2.40721,
                                        Ea=(8.82799, 'kcal/mol'),
                                        T0=(298.15, 'K'))))

        coreSpecies = [CH4, CH3, C2H6, C2H5, H2]
        edgeSpecies = []
        coreReactions = rxnList

        rxnSystem0 = SimpleReactor(T,
                                   P,
                                   initialMoleFractions={
                                       CH4: 0.2,
                                       CH3: 0.1,
                                       C2H6: 0.35,
                                       C2H5: 0.15,
                                       H2: 0.2
                                   },
                                   termination=[])
        rxnSystem0.initializeModel(coreSpecies, coreReactions, edgeSpecies,
                                   edgeReactions)
        dfdt0 = rxnSystem0.residual(0.0, rxnSystem0.y,
                                    numpy.zeros(rxnSystem0.y.shape))[0]
        solver_dfdk = rxnSystem0.computeRateDerivative()
        #print 'Solver d(dy/dt)/dk'
        #print solver_dfdk

        integrationTime = 1e-8
        rxnSystem0.termination.append(TerminationTime((integrationTime, 's')))
        rxnSystem0.simulate(coreSpecies, coreReactions, [], [], 0, 1, 0)

        y0 = rxnSystem0.y

        dfdk = numpy.zeros((numCoreSpecies, len(rxnList)))  # d(dy/dt)/dk

        for i in range(len(rxnList)):
            k0 = rxnList[i].getRateCoefficient(T, P)
            rxnList[i].kinetics.A.value_si = rxnList[i].kinetics.A.value_si * (
                1 + 1e-3)
            dk = rxnList[i].getRateCoefficient(T, P) - k0

            rxnSystem = SimpleReactor(T,
                                      P,
                                      initialMoleFractions={
                                          CH4: 0.2,
                                          CH3: 0.1,
                                          C2H6: 0.35,
                                          C2H5: 0.15,
                                          H2: 0.2
                                      },
                                      termination=[])
            rxnSystem.initializeModel(coreSpecies, coreReactions, edgeSpecies,
                                      edgeReactions)

            dfdt = rxnSystem.residual(0.0, rxnSystem.y,
                                      numpy.zeros(rxnSystem.y.shape))[0]
            dfdk[:, i] = (dfdt - dfdt0) / dk

            rxnSystem.termination.append(
                TerminationTime((integrationTime, 's')))
            rxnSystem.simulate(coreSpecies, coreReactions, [], [], 0, 1, 0)

            rxnList[i].kinetics.A.value_si = rxnList[i].kinetics.A.value_si / (
                1 + 1e-3)  # reset A factor

        for i in range(numCoreSpecies):
            for j in range(len(rxnList)):
                self.assertAlmostEqual(dfdk[i, j],
                                       solver_dfdk[i, j],
                                       delta=abs(1e-3 * dfdk[i, j]))
示例#47
0
            
                    
for f in os.listdir(folder):
    f = os.path.join(folder,f)
    stem, ext = os.path.splitext(f)
    if ext != '.thermo':
        continue

    with open(f) as thermofile:
        line = thermofile.readline()
        match = re.match('InChI = "(.*?)(\/mult\d)*"',line)
        if not match: continue
        inchi = match.group(1)
        mult = match.group(2)
        if mult: continue
        mol = Molecule()
        mol.fromInChI(inchi)
        mmol = rmgpy.qm.mopac.MopacMolPM3(mol, settings)
        print mmol.uniqueID, f
        thermo = mmol.loadThermoData()
        if not thermo: continue
        
        assert inchi.startswith('InChI=1S/')
        inchimain = inchi[9:]
        keystart = keydict[inchimain]
        jthermo = thermodict[keystart]
        print mol.toSMILES()
        print inchi
        print keystart
        print thermo
        print jthermo
示例#48
0
################################################################################

if __name__ == '__main__':
    
    # Parse the command-line arguments
    args = parseCommandLineArguments()
    
    # Load RMG dictionary if specified
    moleculeDict = {}
    if args.dictionary is not None:
        f = open(args.dictionary[0])
        adjlist = ''; label = ''
        for line in f:
            if len(line.strip()) == 0:
                if len(adjlist.strip()) > 0:
                    molecule = Molecule()
                    molecule.fromAdjacencyList(adjlist)
                    moleculeDict[label] = molecule
                adjlist = ''; label = ''
            else:
                if len(adjlist.strip()) == 0:
                    label = line.strip()
                adjlist += line
                    
        f.close()
    
    method = None

    for fstr in args.file:

        # Construct CanTherm job from FAME input
示例#49
0
class TestGetAtomType(unittest.TestCase):
    """
    Contains unit tests of the getAtomType() method.
    """
    
    def setUp(self):
        """
        A function run before each unit test in this class.
        """
        self.mol1 = Molecule().fromSMILES('COO=CC=C=CC#C')
        self.mol2 = Molecule().fromSMILES('c1ccccc1')
        self.mol3 = Molecule().fromSMILES('[H]')
        self.mol4 = Molecule().fromSMILES(
                                'O=[Si][Si][Si]=[Si]=[Si][Si]#[Si]SS=S')
        self.mol5 = Molecule().fromSMILES('[N]')
        self.mol6 = Molecule().fromSMILES('[Ar]')
        self.mol7 = Molecule().fromSMILES('[He]')
        self.mol8 = Molecule().fromSMILES('[Ne]')
    
    def testCarbonTypes(self):
        """
        Test that getAtomType() returns appropriate carbon atom types.
        """
        self.assertEqual(getAtomType(self.mol1.atoms[0],
            self.mol1.getBonds(self.mol1.atoms[0])).label, 'Cs')
        self.assertEqual(getAtomType(self.mol1.atoms[4],
            self.mol1.getBonds(self.mol1.atoms[4])).label, 'Cd')
        self.assertEqual(getAtomType(self.mol1.atoms[5],
            self.mol1.getBonds(self.mol1.atoms[5])).label, 'Cdd')
        self.assertEqual(getAtomType(self.mol1.atoms[7],
            self.mol1.getBonds(self.mol1.atoms[7])).label, 'Ct')
        self.assertEqual(getAtomType(self.mol1.atoms[3],
            self.mol1.getBonds(self.mol1.atoms[3])).label, 'CO')
        self.assertEqual(getAtomType(self.mol2.atoms[0],
            self.mol2.getBonds(self.mol2.atoms[0])).label, 'Cb')
    
    def testHydrogenType(self):
        """
        Test that getAtomType() returns the hydrogen atom type.
        """
        self.assertEqual(getAtomType(self.mol3.atoms[0],
            self.mol3.getBonds(self.mol3.atoms[0])).label, 'H')
    
    def testOxygenTypes(self):
        """
        Test that getAtomType() returns appropriate oxygen atom types.
        """
        self.assertEqual(getAtomType(self.mol1.atoms[1],
            self.mol1.getBonds(self.mol1.atoms[1])).label, 'Os')
        self.assertEqual(getAtomType(self.mol1.atoms[2],
            self.mol1.getBonds(self.mol1.atoms[2])).label, 'Od')
    
    def testSiliconTypes(self):
        """
        Test that getAtomType() returns appropriate silicon atom types.
        """
        self.assertEqual(getAtomType(self.mol4.atoms[2],
            self.mol4.getBonds(self.mol4.atoms[2])).label, 'Sis')
        self.assertEqual(getAtomType(self.mol4.atoms[3],
            self.mol4.getBonds(self.mol4.atoms[3])).label, 'Sid')
        self.assertEqual(getAtomType(self.mol4.atoms[4],
            self.mol4.getBonds(self.mol4.atoms[4])).label, 'Sidd')
        self.assertEqual(getAtomType(self.mol4.atoms[6],
            self.mol4.getBonds(self.mol4.atoms[6])).label, 'Sit')
        self.assertEqual(getAtomType(self.mol4.atoms[1],
            self.mol4.getBonds(self.mol4.atoms[1])).label, 'SiO')
    
    def testSulfurTypes(self):
        """
        Test that getAtomType() returns appropriate sulfur atom types.
        """
        self.assertEqual(getAtomType(self.mol4.atoms[8],
            self.mol4.getBonds(self.mol4.atoms[8])).label, 'Ss')
        self.assertEqual(getAtomType(self.mol4.atoms[9],
            self.mol4.getBonds(self.mol4.atoms[9])).label, 'Sd')
    
    def testNoneTypes(self):
        """
        Test that getAtomType() returns appropriate NoneTypes.
        """
        self.assertIsNone(getAtomType(self.mol5.atoms[0],
            self.mol5.getBonds(self.mol5.atoms[0])))
        self.assertIsNone(getAtomType(self.mol6.atoms[0],
            self.mol6.getBonds(self.mol6.atoms[0])))
        self.assertIsNone(getAtomType(self.mol7.atoms[0],
            self.mol7.getBonds(self.mol7.atoms[0])))
        self.assertIsNone(getAtomType(self.mol8.atoms[0],
            self.mol8.getBonds(self.mol8.atoms[0])))
示例#50
0
    def loadEntry(
        self,
        index,
        reactant1,
        product1,
        kinetics,
        reactant2=None,
        reactant3=None,
        product2=None,
        product3=None,
        degeneracy=1,
        label='',
        duplicate=False,
        reversible=True,
        reference=None,
        referenceType='',
        shortDesc='',
        longDesc='',
    ):

        reactants = [
            Species(label=reactant1.strip().splitlines()[0].strip(),
                    molecule=[Molecule().fromAdjacencyList(reactant1)])
        ]
        if reactant2 is not None:
            reactants.append(
                Species(label=reactant2.strip().splitlines()[0].strip(),
                        molecule=[Molecule().fromAdjacencyList(reactant2)]))
        if reactant3 is not None:
            reactants.append(
                Species(label=reactant3.strip().splitlines()[0].strip(),
                        molecule=[Molecule().fromAdjacencyList(reactant3)]))

        products = [
            Species(label=product1.strip().splitlines()[0].strip(),
                    molecule=[Molecule().fromAdjacencyList(product1)])
        ]
        if product2 is not None:
            products.append(
                Species(label=product2.strip().splitlines()[0].strip(),
                        molecule=[Molecule().fromAdjacencyList(product2)]))
        if product3 is not None:
            products.append(
                Species(label=product3.strip().splitlines()[0].strip(),
                        molecule=[Molecule().fromAdjacencyList(product3)]))

        comment = "Reaction and kinetics from {0}.".format(self.label)
        if shortDesc.strip():
            comment += "{0!s}\n".format(shortDesc.strip())
        if longDesc.strip():
            comment += str(re.sub('\s*\n\s*', '\n', longDesc))
        kinetics.comment = comment.strip()

        # Perform mass balance check on the reaction
        rxn = Reaction(reactants=reactants,
                       products=products,
                       degeneracy=degeneracy,
                       duplicate=duplicate,
                       reversible=reversible)
        if not rxn.isBalanced():
            raise DatabaseError(
                'Reaction {0} in kinetics library {1} was not balanced! Please reformulate.'
                .format(rxn, self.label))

        assert index not in self.entries, "Reaction with index {0} already present!".format(
            index)
        self.entries[index] = Entry(
            index=index,
            label=label,
            item=rxn,
            data=kinetics,
            reference=reference,
            referenceType=referenceType,
            shortDesc=shortDesc,
            longDesc=longDesc.strip(),
        )

        # Convert SMILES to Molecule objects in collision efficiencies
        if isinstance(kinetics, PDepKineticsModel):
            efficiencies = {}
            for smiles, eff in kinetics.efficiencies.items():
                if isinstance(smiles, str):
                    efficiencies[Molecule().fromSMILES(smiles)] = eff
            kinetics.efficiencies = efficiencies
示例#51
0
    def verifyOutputFile(self):
        """
        Check's that an output file exists and was successful.
        
        Returns a boolean flag that states whether a successful MOPAC simulation already exists for the molecule with the 
        given (augmented) InChI Key.
        
        The definition of finding a successful simulation is based on these criteria:
        1) finding an output file with the file name equal to the InChI Key
        2) NOT finding any of the keywords that are denote a calculation failure
        3) finding all the keywords that denote a calculation success.
        4) finding a match between the InChI of the given molecule and the InchI found in the calculation files
        5) checking that the optimized geometry, when connected by single bonds, is isomorphic with self.molecule (converted to single bonds)
        
        If any of the above criteria is not matched, False will be returned.
        If all succeed, then it will return True.
        """
        if not os.path.exists(self.outputFilePath):
            logging.debug("Output file {0} does not (yet) exist.".format(
                self.outputFilePath))
            return False

        InChIFound = False  #flag (1 or 0) indicating whether an InChI was found in the log file

        # Initialize dictionary with "False"s
        successKeysFound = dict([(key, False) for key in self.successKeys])

        with open(self.outputFilePath) as outputFile:
            for line in outputFile:
                line = line.strip()

                for element in self.failureKeys:  #search for failure keywords
                    if element in line:
                        logging.error(
                            "MOPAC output file contains the following error: {0}"
                            .format(element))
                        return False

                for element in self.successKeys:  #search for success keywords
                    if element in line:
                        successKeysFound[element] = True

                if "InChI=" in line:
                    logFileInChI = line  #output files should take up to 240 characters of the name in the input file
                    InChIFound = True
                    if self.uniqueIDlong in logFileInChI:
                        pass
                    elif self.uniqueIDlong.startswith(logFileInChI):
                        logging.info(
                            "InChI too long to check, but beginning matches so assuming OK."
                        )

                    else:
                        logging.warning(
                            "InChI in log file ({0}) didn't match that in geometry ({1})."
                            .format(logFileInChI, self.uniqueIDlong))
                        # Use only up to first 80 characters to match due to MOPAC bug which deletes 81st character of InChI string
                        if self.uniqueIDlong.startswith(logFileInChI[:80]):
                            logging.warning(
                                "but the beginning matches so it's probably just a truncation problem."
                            )

        # Check that ALL 'success' keywords were found in the file.
        if not all(successKeysFound.values()):
            logging.error(
                'Not all of the required keywords for success were found in the output file!'
            )
            return False

        if not InChIFound:
            logging.error(
                "No InChI was found in the MOPAC output file {0}".format(
                    self.outputFilePath))
            return False

        # Compare the optimized geometry to the original molecule
        qmData = self.parse()
        cclibMol = Molecule()
        cclibMol.fromXYZ(qmData.atomicNumbers, qmData.atomCoords.value)
        testMol = self.molecule.toSingleBonds()
        if not cclibMol.isIsomorphic(testMol):
            logging.info(
                "Incorrect connectivity for optimized geometry in file {0}".
                format(self.outputFilePath))
            return False

        logging.info("Successful {1} quantum result in {0}".format(
            self.outputFilePath, self.__class__.__name__))
        return True
示例#52
0
    if args.max_energy:
        Emax = float(args.max_energy[0])
        Eunits = str(args.max_energy[1])
        Emax = Energy(Emax, Eunits).value_si
    else:
        Emax = None
    
    # Load RMG dictionary if specified
    moleculeDict = {}
    if args.dictionary is not None:
        f = open(args.dictionary[0])
        adjlist = ''; label = ''
        for line in f:
            if len(line.strip()) == 0:
                if len(adjlist.strip()) > 0:
                    molecule = Molecule()
                    molecule.fromAdjacencyList(adjlist)
                    moleculeDict[label] = molecule
                adjlist = ''; label = ''
            else:
                if len(adjlist.strip()) == 0:
                    label = line.strip()
                adjlist += line
                    
        f.close()
    
    method = None

    for fstr in args.file:

        # Construct CanTherm job from FAME input
示例#53
0
    ]
    possible_labels = [
        '_'.join((joined_r, joined_p)) for joined_r in joined_reactant_orders
        for joined_p in joined_product_orders
    ]

    for reaction in ooh_reactions:
        ooh_reactants, ooh_products = reaction.label.split("_")
        r1, r2 = ooh_reactants.split("+")
        p1, p2 = ooh_products.split("+")
        ooh_smiles = [r1, r2, p1, p2]

        # Creating a dictionary to decode inchikeys into smiles
        inchikey_to_smiles_dict = {}
        for smiles in ooh_smiles:
            inchikey_to_smiles_dict[Molecule(
                SMILES=smiles).toInChIKey()] = smiles

        # Setting the reactant and product labels as the nickname given in the model
        if reaction.label in possible_labels:
            for reactant in reaction.reactants:
                inchi_key = reactant.label.split("-u")[0]
                if not reactant.label in smiles_to_nickname_dict.itervalues():
                    reactant.molecule = [
                        Molecule(SMILES=inchikey_to_smiles_dict[inchi_key])
                    ]
                    reactant.label = smiles_to_nickname_dict[
                        inchikey_to_smiles_dict[inchi_key]]

            for product in reaction.products:
                inchi_key = product.label.split("-u")[0]
                if not product.label in smiles_to_nickname_dict.itervalues():
示例#54
0
def SMILES(string):
    return Molecule().from_smiles(string)
    def testReactBenzeneBond2(self):
        """
        Test that hydrogen addition to phenanthrene (w/ benzene bonds) returns kekulized product.
        """
        family = self.database.families['R_Addition_MultipleBond']
        reactants = [Molecule().fromAdjacencyList("""
1  *1 C u0 p0 c0 {2,B} {3,B} {6,B}
2  *2 C u0 p0 c0 {1,B} {4,B} {9,B}
3     C u0 p0 c0 {1,B} {5,B} {7,B}
4     C u0 p0 c0 {2,B} {8,B} {10,B}
5     C u0 p0 c0 {3,B} {11,B} {17,S}
6     C u0 p0 c0 {1,B} {12,B} {18,S}
7     C u0 p0 c0 {3,B} {8,B} {19,S}
8     C u0 p0 c0 {4,B} {7,B} {20,S}
9     C u0 p0 c0 {2,B} {13,B} {21,S}
10    C u0 p0 c0 {4,B} {14,B} {23,S}
11    C u0 p0 c0 {5,B} {12,B} {15,S}
12    C u0 p0 c0 {6,B} {11,B} {16,S}
13    C u0 p0 c0 {9,B} {14,B} {22,S}
14    C u0 p0 c0 {10,B} {13,B} {24,S}
15    H u0 p0 c0 {11,S}
16    H u0 p0 c0 {12,S}
17    H u0 p0 c0 {5,S}
18    H u0 p0 c0 {6,S}
19    H u0 p0 c0 {7,S}
20    H u0 p0 c0 {8,S}
21    H u0 p0 c0 {9,S}
22    H u0 p0 c0 {13,S}
23    H u0 p0 c0 {10,S}
24    H u0 p0 c0 {14,S}
"""),
                     Molecule().fromAdjacencyList("1 *3 H u1 p0 c0")]
        expectedProduct = Molecule().fromAdjacencyList("""
multiplicity 2
1  *1 C u0 p0 c0 {2,S} {3,S} {5,S} {15,S}
2  *2 C u1 p0 c0 {1,S} {4,S} {8,S}
3     C u0 p0 c0 {1,S} {6,S} {7,D}
4     C u0 p0 c0 {2,S} {9,D} {10,S}
5     C u0 p0 c0 {1,S} {11,D} {16,S}
6     C u0 p0 c0 {3,S} {12,D} {19,S}
7     C u0 p0 c0 {3,D} {9,S} {20,S}
8     C u0 p0 c0 {2,S} {13,D} {22,S}
9     C u0 p0 c0 {4,D} {7,S} {21,S}
10    C u0 p0 c0 {4,S} {14,D} {24,S}
11    C u0 p0 c0 {5,D} {12,S} {18,S}
12    C u0 p0 c0 {6,D} {11,S} {17,S}
13    C u0 p0 c0 {8,D} {14,S} {23,S}
14    C u0 p0 c0 {10,D} {13,S} {25,S}
15 *3 H u0 p0 c0 {1,S}
16    H u0 p0 c0 {5,S}
17    H u0 p0 c0 {12,S}
18    H u0 p0 c0 {11,S}
19    H u0 p0 c0 {6,S}
20    H u0 p0 c0 {7,S}
21    H u0 p0 c0 {9,S}
22    H u0 p0 c0 {8,S}
23    H u0 p0 c0 {13,S}
24    H u0 p0 c0 {10,S}
25    H u0 p0 c0 {14,S}
""")
        products = family.applyRecipe(reactants)

        self.assertEqual(len(products), 1)
        self.assertTrue(expectedProduct.isIsomorphic(products[0]))
示例#56
0
def SMILES(string):
    return Molecule().fromSMILES(string)
示例#57
0
MaxCarbonNumberPerSpecies:     20
MaxOxygenNumberPerSpecies:     20
MaxRadicalNumberPerSpecies:    20
MaxSulfurNumberPerSpecies:     20
MaxSiliconNumberPerSpecies:    20
MaxHeavyAtomNumberPerSpecies: 100
MaxCycleNumberPerSpecies:      20
END

PrimaryThermoLibrary:
Name: RMG-minimal
Location: primaryThermoLibrary
END

""")


    for f in os.listdir(folder):
        f = os.path.join(folder,f)
        stem, ext = os.path.splitext(f)
        if ext != '.thermo':
            continue
        
        data = rmgpy.qm.molecule.loadThermoDataFile(f)
        mol = Molecule().fromAdjacencyList(data['adjacencyList'])
    
        output.write('// {0!s}\n'.format(data['InChI']))
        output.write('// {0!r}\n'.format(data['thermoData']).replace('),','),\n//           '))
        output.write(mol.toSMILES())
        output.write(data['adjacencyList']+'\n')
            
示例#58
0
def adjacencyList(string):
    return Molecule().fromAdjacencyList(string)
示例#59
0
elif os.getenv('LSB_JOBINDEX'):
	i = int(os.getenv('LSB_JOBINDEX'))
else:
	raise Exception("Specify a TS number!")
	
rxnFamiles = ['intra_H_migration', 'R_Addition_MultipleBond', 'H_Abstraction'] 

# Create a python dictionary of the species name and the adjacency list
# from the species dictionary
moleculeDict = {}
f = open('dictionary.txt', 'r')
adjlist = ''; label = ''
for line in f:
	if len(line.strip()) == 0:
		if len(adjlist.strip()) > 0:
			molecule = Molecule()
			molecule.fromAdjacencyList(adjlist, saturateH=True)
			moleculeDict[label] = molecule
		adjlist = ''; label = ''
	else:
		if len(adjlist.strip()) == 0:
			label = line.strip()
		adjlist += line


file_object = open('mechanism.txt', 'r')
mechLines = file_object.readlines()

rxnList = []
gotit = []
for rxnFamily in rxnFamiles: