Exemple #1
0
    def save(self, outputFile):
        """
        Save the results of the kinetics job to the file located
        at `path` on disk.
        """
        reaction = self.reaction

        logging.info("Saving kinetics for {0}...".format(reaction))

        order = len(self.reaction.reactants)
        factor = 1e6 ** (order - 1)

        f = open(outputFile, "a")

        f.write("#   ======= =========== =========== =========== ===============\n")
        f.write("#   Temp.   k (TST)     Tunneling   k (TST+T)   Units\n")
        f.write("#   ======= =========== =========== =========== ===============\n")
        for T in [300, 400, 500, 600, 800, 1000, 1500, 2000]:
            tunneling = reaction.transitionState.tunneling
            reaction.transitionState.tunneling = None
            k0 = reaction.calculateTSTRateCoefficient(T) * factor
            reaction.transitionState.tunneling = tunneling
            k = reaction.calculateTSTRateCoefficient(T) * factor
            tunneling = reaction.transitionState.tunneling
            kappa = k / k0
            f.write("#    {0:4g} K {1:11.3e} {2:11g} {3:11.3e} {4}\n".format(T, k0, kappa, k, self.kunits))
        f.write("#   ======= =========== =========== =========== ===============\n")

        # Reaction path degeneracy is INCLUDED in the kinetics itself!
        string = "kinetics(label={0!r}, kinetics={1!r})".format(reaction.label, reaction.kinetics)
        f.write("{0}\n\n".format(prettify(string)))

        f.close()
Exemple #2
0
    def save(self, outputFile):
        """
        Save the results of the kinetics job to the file located
        at `path` on disk.
        """
        reaction = self.reaction

        logging.info('Saving kinetics for {0}...'.format(reaction))

        order = len(self.reaction.reactants)
        factor = 1e6**(order - 1)

        f = open(outputFile, 'a')

        f.write(
            '#   ======= =========== =========== =========== ===============\n'
        )
        f.write('#   Temp.   k (TST)     Tunneling   k (TST+T)   Units\n')
        f.write(
            '#   ======= =========== =========== =========== ===============\n'
        )
        for T in [300, 400, 500, 600, 800, 1000, 1500, 2000]:
            tunneling = reaction.transitionState.tunneling
            reaction.transitionState.tunneling = None
            k0 = reaction.calculateTSTRateCoefficient(T) * factor
            reaction.transitionState.tunneling = tunneling
            k = reaction.calculateTSTRateCoefficient(T) * factor
            tunneling = reaction.transitionState.tunneling
            kappa = k / k0
            f.write('#    {0:4g} K {1:11.3e} {2:11g} {3:11.3e} {4}\n'.format(
                T, k0, kappa, k, self.kunits))
        f.write(
            '#   ======= =========== =========== =========== ===============\n'
        )

        # Reaction path degeneracy is INCLUDED in the kinetics itself!
        string = 'kinetics(label={0!r}, kinetics={1!r})'.format(
            reaction.label, reaction.kinetics)
        f.write('{0}\n\n'.format(prettify(string)))

        f.close()

        # Also save the result to chem.inp
        f = open(os.path.join(os.path.dirname(outputFile), 'chem.inp'), 'a')

        reaction = self.reaction
        kinetics = reaction.kinetics

        string = '{0!s:51} {1:9.3e} {2:9.3f} {3:9.3f}\n'.format(
            reaction,
            kinetics.A.value_si * factor,
            kinetics.n.value_si,
            kinetics.Ea.value_si / 4184.,
        )

        f.write('{0}\n'.format(string))

        f.close()
Exemple #3
0
    def save(self, outputFile):
        """
        Save the results of the kinetics job to the file located
        at `path` on disk.
        """
        reaction = self.reaction
        
        logging.info('Saving kinetics for {0}...'.format(reaction))
        
        order = len(self.reaction.reactants)
        factor = 1e6 ** (order-1)
        
        f = open(outputFile, 'a')
    
        f.write('#   ======= =========== =========== =========== ===============\n')
        f.write('#   Temp.   k (TST)     Tunneling   k (TST+T)   Units\n')
        f.write('#   ======= =========== =========== =========== ===============\n')
        
        if self.Tlist is None:
            Tlist = [300,400,500,600,800,1000,1500,2000]
        else:
            Tlist =self.Tlist.value_si

        for T in Tlist:  
            tunneling = reaction.transitionState.tunneling
            reaction.transitionState.tunneling = None
            k0 = reaction.calculateTSTRateCoefficient(T) * factor
            reaction.transitionState.tunneling = tunneling
            k = reaction.calculateTSTRateCoefficient(T) * factor
            tunneling = reaction.transitionState.tunneling
            kappa = k / k0
            f.write('#    {0:4g} K {1:11.3e} {2:11g} {3:11.3e} {4}\n'.format(T, k0, kappa, k, self.kunits))
        f.write('#   ======= =========== =========== =========== ===============\n')
        
        # Reaction path degeneracy is INCLUDED in the kinetics itself!
        string = 'kinetics(label={0!r}, kinetics={1!r})'.format(reaction.label, reaction.kinetics)
        f.write('{0}\n\n'.format(prettify(string)))
        
        f.close()
        
        # Also save the result to chem.inp
        f = open(os.path.join(os.path.dirname(outputFile), 'chem.inp'), 'a')
        
        reaction = self.reaction
        kinetics = reaction.kinetics
                
        string = '{0!s:51} {1:9.3e} {2:9.3f} {3:9.3f}\n'.format(
            reaction,
            kinetics.A.value_si * factor,
            kinetics.n.value_si,
            kinetics.Ea.value_si / 4184.,
        )
                
        f.write('{0}\n'.format(string))
            
        f.close()
Exemple #4
0
    def save(self, outputFile):
        """
        Save the results of the thermodynamics job to the file located
        at `path` on disk.
        """
        species = self.species
        logging.info('Saving thermo for {0}...'.format(species.label))

        f = open(outputFile, 'a')

        f.write('# Thermodynamics for {0}:\n'.format(species.label))
        H298 = species.getThermoData().getEnthalpy(298) / 4184.
        S298 = species.getThermoData().getEntropy(298) / 4.184
        f.write(
            '#   Enthalpy of formation (298 K)   = {0:9.3f} kcal/mol\n'.format(
                H298))
        f.write('#   Entropy of formation (298 K)    = {0:9.3f} cal/(mol*K)\n'.
                format(S298))
        f.write(
            '#    =========== =========== =========== =========== ===========\n'
        )
        f.write(
            '#    Temperature Heat cap.   Enthalpy    Entropy     Free energy\n'
        )
        f.write(
            '#    (K)         (cal/mol*K) (kcal/mol)  (cal/mol*K) (kcal/mol)\n'
        )
        f.write(
            '#    =========== =========== =========== =========== ===========\n'
        )
        for T in [300, 400, 500, 600, 800, 1000, 1500, 2000, 2400]:
            Cp = species.getThermoData().getHeatCapacity(T) / 4.184
            H = species.getThermoData().getEnthalpy(T) / 4184.
            S = species.getThermoData().getEntropy(T) / 4.184
            G = species.getThermoData().getFreeEnergy(T) / 4184.
            f.write('#    {0:11g} {1:11.3f} {2:11.3f} {3:11.3f} {4:11.3f}\n'.
                    format(T, Cp, H, S, G))
        f.write(
            '#    =========== =========== =========== =========== ===========\n'
        )

        string = 'thermo(label={0!r}, thermo={1!r})'.format(
            species.label, species.getThermoData())
        f.write('{0}\n\n'.format(prettify(string)))

        f.close()

        f = open(os.path.join(os.path.dirname(outputFile), 'chem.inp'), 'a')
        string = writeThermoEntry(species,
                                  elementCounts=species.props['elementCounts'],
                                  verbose=False)
        f.write(string)
        f.close()
Exemple #5
0
    def save(self, outputFile):
        """
        Save the results of the statistical mechanics job to the file located
        at `path` on disk.
        """

        logging.info(
            'Saving statistical mechanics parameters for {0}...'.format(
                self.species.label))
        f = open(outputFile, 'a')

        numbers = {
            1: 'H',
            6: 'C',
            7: 'N',
            8: 'O',
            14: 'Si',
            15: 'P',
            16: 'S',
            17: 'Cl'
        }

        conformer = self.species.conformer

        coordinates = conformer.coordinates.value_si * 1e10
        number = conformer.number.value_si

        f.write('# Coordinates for {0} (angstroms):\n'.format(
            self.species.label))
        for i in range(coordinates.shape[0]):
            x = coordinates[i, 0] - coordinates[0, 0]
            y = coordinates[i, 1] - coordinates[0, 1]
            z = coordinates[i, 2] - coordinates[0, 2]
            f.write('#   {0} {1:9.4f} {2:9.4f} {3:9.4f}\n'.format(
                numbers[number[i]], x, y, z))

        string = 'conformer(label={0!r}, E0={1!r}, modes={2!r}, spinMultiplicity={3:d}, opticalIsomers={4:d}'.format(
            self.species.label,
            conformer.E0,
            conformer.modes,
            conformer.spinMultiplicity,
            conformer.opticalIsomers,
        )
        try:
            string += ', frequency={0!r}'.format(self.species.frequency)
        except AttributeError:
            pass
        string += ')'

        f.write('{0}\n\n'.format(prettify(string)))

        f.close()
Exemple #6
0
 def save(self, outputFile):
     """
     Save the results of the thermodynamics job to the file located
     at `path` on disk.
     """
     species = self.species
     logging.info('Saving thermo for {0}...'.format(species.label))
     
     f = open(outputFile, 'a')
 
     f.write('# Thermodynamics for {0}:\n'.format(species.label))
     H298 = species.getThermoData().getEnthalpy(298) / 4184.
     S298 = species.getThermoData().getEntropy(298) / 4.184
     f.write('#   Enthalpy of formation (298 K)   = {0:9.3f} kcal/mol\n'.format(H298))
     f.write('#   Entropy of formation (298 K)    = {0:9.3f} cal/(mol*K)\n'.format(S298))
     f.write('#    =========== =========== =========== =========== ===========\n')
     f.write('#    Temperature Heat cap.   Enthalpy    Entropy     Free energy\n')
     f.write('#    (K)         (cal/mol*K) (kcal/mol)  (cal/mol*K) (kcal/mol)\n')
     f.write('#    =========== =========== =========== =========== ===========\n')
     for T in [300,400,500,600,800,1000,1500,2000,2400]:
         Cp = species.getThermoData().getHeatCapacity(T) / 4.184
         H = species.getThermoData().getEnthalpy(T) / 4184.
         S = species.getThermoData().getEntropy(T) / 4.184
         G = species.getThermoData().getFreeEnergy(T) / 4184.
         f.write('#    {0:11g} {1:11.3f} {2:11.3f} {3:11.3f} {4:11.3f}\n'.format(T, Cp, H, S, G))
     f.write('#    =========== =========== =========== =========== ===========\n')
     
     string = 'thermo(label={0!r}, thermo={1!r})'.format(species.label, species.getThermoData())
     f.write('{0}\n\n'.format(prettify(string)))
     
     f.close()
     
     f = open(os.path.join(os.path.dirname(outputFile), 'chem.inp'), 'a')
     if isinstance(species, Species):
         if species.molecule and isinstance(species.molecule[0], Molecule):
             elementCounts = retrieveElementCount(species.molecule[0])
         else:
             try:
                 elementCounts = species.props['elementCounts']
             except KeyError:
                 elementCounts = {'C': 0, 'H': 0}
     else:
         elementCounts = {'C': 0, 'H': 0}
     string = writeThermoEntry(species, elementCounts=elementCounts, verbose=False)
     f.write('{0}\n'.format(string))
     f.close()
Exemple #7
0
 def save(self, outputFile):
     """
     Save the results of the statistical mechanics job to the file located
     at `path` on disk.
     """
     
     logging.info('Saving statistical mechanics parameters for {0}...'.format(self.species.label))
     f = open(outputFile, 'a')
 
     numbers = {1: 'H', 6: 'C', 7: 'N', 8: 'O', 14: 'Si', 15: 'P', 16: 'S', 17: 'Cl'}
     
     conformer = self.species.conformer
         
     coordinates = conformer.coordinates.value_si * 1e10
     number = conformer.number.value_si
     
     f.write('# Coordinates for {0} (angstroms):\n'.format(self.species.label))
     for i in range(coordinates.shape[0]):
         x = coordinates[i,0] - coordinates[0,0]
         y = coordinates[i,1] - coordinates[0,1]
         z = coordinates[i,2] - coordinates[0,2]
         f.write('#   {0} {1:9.4f} {2:9.4f} {3:9.4f}\n'.format(numbers[number[i]], x, y, z))
     
     string = 'conformer(label={0!r}, E0={1!r}, modes={2!r}, spinMultiplicity={3:d}, opticalIsomers={4:d}'.format(
         self.species.label, 
         conformer.E0,
         conformer.modes,
         conformer.spinMultiplicity,
         conformer.opticalIsomers,
     )
     try:
         string += ', frequency={0!r}'.format(self.species.frequency)
     except AttributeError: pass
     string += ')'
     
     f.write('{0}\n\n'.format(prettify(string)))
     
     f.close()
Exemple #8
0
            f.write('#   Enthalpy of formation (298 K)   = {0:9.3f} kcal/mol\n'.format(H298))
            f.write('#   Entropy of formation (298 K)    = {0:9.3f} cal/(mol*K)\n'.format(S298))
            f.write('#    =========== =========== =========== =========== ===========\n')
            f.write('#    Temperature Heat cap.   Enthalpy    Entropy     Free energy\n')
            f.write('#    (K)         (cal/mol*K) (kcal/mol)  (cal/mol*K) (kcal/mol)\n')
            f.write('#    =========== =========== =========== =========== ===========\n')
            for T in T_list:
                Cp = species.getThermoData().getHeatCapacity(T) / 4.184
                H = species.getThermoData().getEnthalpy(T) / 4184.
                S = species.getThermoData().getEntropy(T) / 4.184
                G = species.getThermoData().getFreeEnergy(T) / 4184.
                f.write('#    {0:11g} {1:11.3f} {2:11.3f} {3:11.3f} {4:11.3f}\n'.format(T, Cp, H, S, G))
            f.write('#    =========== =========== =========== =========== ===========\n')

            string = 'thermo(label={0!r}, thermo={1!r})'.format(species.label, species.getThermoData())
            f.write('{0}\n\n'.format(prettify(string)))

            f.close()
        else:
            print ('Species {0} did not contain any thermo data and was omitted from the output file.'.format(str(species)))

    #Convert T_list into an array
    T_list = numpy.asarray(T_list)

    # Plot the thermo properties of each species at the specified T's and save as .pdf files
    for i in range(len(speciesList)):
        species = speciesList[i]
        if species.thermo:

            # Skip this step if matplotlib is not installed
            try:
Exemple #9
0
    def save(self, outputFile):
        """
        Save the results of the thermodynamics job to the file located
        at `path` on disk.
        """
        species = self.species
        logging.info("Saving thermo for {0}...".format(species.label))

        f = open(outputFile, "a")

        f.write("# Thermodynamics for {0}:\n".format(species.label))
        H298 = species.thermo.getEnthalpy(298) / 4184.0
        S298 = species.thermo.getEntropy(298) / 4.184
        f.write("#   Enthalpy of formation (298 K)   = {0:9.3f} kcal/mol\n".format(H298))
        f.write("#   Entropy of formation (298 K)    = {0:9.3f} cal/(mol*K)\n".format(S298))
        f.write("#    =========== =========== =========== =========== ===========\n")
        f.write("#    Temperature Heat cap.   Enthalpy    Entropy     Free energy\n")
        f.write("#    (K)         (cal/mol*K) (kcal/mol)  (cal/mol*K) (kcal/mol)\n")
        f.write("#    =========== =========== =========== =========== ===========\n")
        for T in [300, 400, 500, 600, 800, 1000, 1500, 2000, 2400]:
            Cp = species.thermo.getHeatCapacity(T) / 4.184
            H = species.thermo.getEnthalpy(T) / 4184.0
            S = species.thermo.getEntropy(T) / 4.184
            G = species.thermo.getFreeEnergy(T) / 4184.0
            f.write("#    {0:11g} {1:11.3f} {2:11.3f} {3:11.3f} {4:11.3f}\n".format(T, Cp, H, S, G))
        f.write("#    =========== =========== =========== =========== ===========\n")

        string = "thermo(label={0!r}, thermo={1!r})".format(species.label, species.thermo)
        f.write("{0}\n\n".format(prettify(string)))

        f.close()

        f = open(os.path.join(os.path.dirname(outputFile), "chem.inp"), "w")

        thermo = species.thermo
        if isinstance(thermo, NASA):

            poly_low = thermo.polynomials[0]
            poly_high = thermo.polynomials[1]

            # Determine the number of each type of element in the molecule
            elements = ["C", "H", "N", "O"]
            elementCounts = [0, 0, 0, 0]

            # Remove elements with zero count
            index = 2
            while index < len(elementCounts):
                if elementCounts[index] == 0:
                    del elements[index]
                    del elementCounts[index]
                else:
                    index += 1

            # Line 1
            string = "{0:<16}        ".format(species.label)
            if len(elements) <= 4:
                # Use the original Chemkin syntax for the element counts
                for symbol, count in zip(elements, elementCounts):
                    string += "{0!s:<2}{1:<3d}".format(symbol, count)
                string += "     " * (4 - len(elements))
            else:
                string += "     " * 4
            string += "G{0:<10.3f}{1:<10.3f}{2:<8.2f}      1".format(
                poly_low.Tmin.value_si, poly_high.Tmax.value_si, poly_low.Tmax.value_si
            )
            if len(elements) > 4:
                string += "&\n"
                # Use the new-style Chemkin syntax for the element counts
                # This will only be recognized by Chemkin 4 or later
                for symbol, count in zip(elements, elementCounts):
                    string += "{0!s:<2}{1:<3d}".format(symbol, count)
            string += "\n"

            # Line 2
            string += "{0:< 15.8E}{1:< 15.8E}{2:< 15.8E}{3:< 15.8E}{4:< 15.8E}    2\n".format(
                poly_high.c0, poly_high.c1, poly_high.c2, poly_high.c3, poly_high.c4
            )

            # Line 3
            string += "{0:< 15.8E}{1:< 15.8E}{2:< 15.8E}{3:< 15.8E}{4:< 15.8E}    3\n".format(
                poly_high.c5, poly_high.c6, poly_low.c0, poly_low.c1, poly_low.c2
            )

            # Line 4
            string += "{0:< 15.8E}{1:< 15.8E}{2:< 15.8E}{3:< 15.8E}                   4\n".format(
                poly_low.c3, poly_low.c4, poly_low.c5, poly_low.c6
            )

            f.write(string)

            f.close()
Exemple #10
0
    def save(self, outputFile):

        logging.info(
            'Saving pressure dependence results for {0} network...'.format(
                self.network.label))
        f = open(outputFile, 'a')
        f_chemkin = open(os.path.join(os.path.dirname(outputFile), 'chem.inp'),
                         'a')

        Nreac = self.network.Nisom + self.network.Nreac
        Nprod = Nreac + self.network.Nprod
        Tlist = self.Tlist.value_si
        Plist = self.Plist.value_si
        Tcount = Tlist.shape[0]
        Pcount = Plist.shape[0]

        count = 0
        printed_reactions = []  # list of rxns already printed
        for prod in range(Nprod):
            for reac in range(Nreac):
                if reac == prod: continue
                reaction = self.network.netReactions[count]
                count += 1
                # make sure we aren't double counting any reactions
                if not any([reaction.isIsomorphic(other_rxn,checkOnlyLabel=True) \
                            for other_rxn in printed_reactions]):
                    duplicate = False
                    # add reaction to printed reaction
                    printed_reactions.append(reaction)
                else:
                    # comment out the extra reverse reaction
                    duplicate = True

                # write chemkin output.
                string = writeKineticsEntry(reaction,
                                            speciesList=None,
                                            verbose=False,
                                            commented=duplicate)
                f_chemkin.write('{0}\n'.format(string))

                # write to 'output.py'
                kdata = self.K[:, :, prod, reac].copy()
                order = len(reaction.reactants)
                kdata *= 1e6**(order - 1)
                kunits = {
                    1: 's^-1',
                    2: 'cm^3/(mol*s)',
                    3: 'cm^6/(mol^2*s)'
                }[order]

                f.write('#   =========== ')
                f.write('=========== ' * Pcount)
                f.write('\n')
                f.write('#         T \ P ')
                f.write(' '.join(['{0:11.3e}'.format(P * 1e-5)
                                  for P in Plist]))
                f.write('\n')
                f.write('#   =========== ')
                f.write('=========== ' * Pcount)
                f.write('\n')

                for t in range(Tcount):
                    f.write('#   {0:11g}'.format(Tlist[t]))
                    for p in range(Pcount):
                        f.write(' {0:11.3e}'.format(kdata[t, p]))
                    f.write('\n')

                f.write('#   =========== ')
                f.write('=========== ' * Pcount)
                f.write('\n')

                string = 'pdepreaction(reactants={0!r}, products={1!r}, kinetics={2!r})'.format(
                    [reactant.label for reactant in reaction.reactants],
                    [product.label for product in reaction.products],
                    reaction.kinetics,
                )
                pdep_function = '{0}\n\n'.format(prettify(string))
                if duplicate:
                    # add comments to the start of the string
                    pdep_function = '#   ' + pdep_function.replace(
                        '\n', '\n#   ')
                f.write(pdep_function)

        f.close()
        f_chemkin.close()
Exemple #11
0
def saveEntry(f, entry):
    """
    Save an `entry` in the kinetics database by writing a string to
    the given file object `f`.
    """
    from rmgpy.cantherm.output import prettify

    def sortEfficiencies(efficiencies0):
        efficiencies = {}
        for mol, eff in efficiencies0.iteritems():
            if isinstance(mol, str):
                # already in SMILES string format
                smiles = mol
            else:
                smiles = mol.toSMILES()
                
            efficiencies[smiles] = eff
        keys = efficiencies.keys()
        keys.sort()
        return [(key, efficiencies[key]) for key in keys]

    f.write('entry(\n')
    f.write('    index = {0:d},\n'.format(entry.index))
    if entry.label != '':
        f.write('    label = "{0}",\n'.format(entry.label))


    #Entries for kinetic rules, libraries, training reactions
    #and depositories will have an Reaction object for its item
    if isinstance(entry.item, Reaction):
        #Write out additional data if depository or library
        #kinetic rules would have a Group object for its reactants instead of Species
        if isinstance(entry.item.reactants[0], Species):
            # Add degeneracy if the reaction is coming from a depository or kinetics library
            f.write('    degeneracy = {0:.1f},\n'.format(entry.item.degeneracy))
            if entry.item.duplicate:
                f.write('    duplicate = {0!r},\n'.format(entry.item.duplicate))
            if not entry.item.reversible:
                f.write('    reversible = {0!r},\n'.format(entry.item.reversible))
    #Entries for groups with have a group or logicNode for its item
    elif isinstance(entry.item, Group):
        f.write('    group = \n')
        f.write('"""\n')
        f.write(entry.item.toAdjacencyList())
        f.write('""",\n')
    elif isinstance(entry.item, LogicNode):
        f.write('    group = "{0}",\n'.format(entry.item))
    else:
        raise DatabaseError("Encountered unexpected item of type {0} while saving database.".format(entry.item.__class__))

    # Write kinetics
    if isinstance(entry.data, str):
        f.write('    kinetics = "{0}",\n'.format(entry.data))
    elif entry.data is not None:
        efficiencies = None
        if hasattr(entry.data, 'efficiencies'):
            efficiencies = entry.data.efficiencies
            entry.data.efficiencies = dict(sortEfficiencies(entry.data.efficiencies))
        kinetics = prettify(repr(entry.data))
        kinetics = '    kinetics = {0},\n'.format(kinetics.replace('\n', '\n    '))
        f.write(kinetics)
        if hasattr(entry.data, 'efficiencies'):
            entry.data.efficiencies = efficiencies
    else:
        f.write('    kinetics = None,\n')
            
    # Write reference
    if entry.reference is not None:
        reference = entry.reference.toPrettyRepr()
        lines = reference.splitlines()
        f.write('    reference = {0}\n'.format(lines[0]))
        for line in lines[1:-1]:
            f.write('    {0}\n'.format(line))
        f.write('    ),\n'.format(lines[0]))
    
    if entry.referenceType != "":
        f.write('    referenceType = "{0}",\n'.format(entry.referenceType))
    if entry.rank is not None:
        f.write('    rank = {0},\n'.format(entry.rank))
        
    if entry.shortDesc.strip() !='':
        f.write('    shortDesc = u"""')
        try:
            f.write(entry.shortDesc.encode('utf-8'))
        except:
            f.write(entry.shortDesc.strip().encode('ascii', 'ignore')+ "\n")
        f.write('""",\n')
    
    if entry.longDesc.strip() !='':
        f.write('    longDesc = \n')
        f.write('u"""\n')
        try:
            f.write(entry.longDesc.strip().encode('utf-8') + "\n")
        except:
            f.write(entry.longDesc.strip().encode('ascii', 'ignore')+ "\n")
        f.write('""",\n')

    f.write(')\n\n')
Exemple #12
0
    def save(self, outputFile):
        
        logging.info('Saving pressure dependence results for {0}...'.format(self.network))
        
        f = open(outputFile, 'a')
    
        Nreac = self.network.Nisom + self.network.Nreac
        Nprod = Nreac + self.network.Nprod
        Tlist = self.Tlist.value_si
        Plist = self.Plist.value_si
        Tcount = Tlist.shape[0]
        Pcount = Plist.shape[0]
        
        count = 0
        for prod in range(Nprod):
            for reac in range(Nreac):
                if reac == prod: continue
                reaction = self.network.netReactions[count]
                count += 1
                
                kdata = self.K[:,:,prod,reac].copy()
                order = len(reaction.reactants)
                kdata *= 1e6 ** (order-1)
                kunits = {1: 's^-1', 2: 'cm^3/(mol*s)', 3: 'cm^6/(mol^2*s)'}[order]
                
                f.write('#   =========== ')
                f.write('=========== ' * Pcount)
                f.write('\n')
                f.write('#         T \ P ')
                f.write(' '.join(['{0:11.3e}'.format(P*1e-5) for P in Plist]))
                f.write('\n')
                f.write('#   =========== ')
                f.write('=========== ' * Pcount)
                f.write('\n')
                
                for t in range(Tcount):
                    f.write('#   {0:11g}'.format(Tlist[t]))
                    for p in range(Pcount):
                        f.write(' {0:11.3e}'.format(kdata[t,p]))
                    f.write('\n')
                
                f.write('#   =========== ')
                f.write('=========== ' * Pcount)
                f.write('\n')
                
                string = 'pdepreaction(reactants={0!r}, products={1!r}, kinetics={2!r})'.format(
                    [reactant.label for reactant in reaction.reactants],
                    [product.label for product in reaction.products],
                    reaction.kinetics,
                )
                f.write('{0}\n\n'.format(prettify(string)))
        
        f.close()
        
        f = open(os.path.join(os.path.dirname(outputFile), 'chem.inp'), 'w')
        
        count = 0
        for prod in range(Nprod):
            for reac in range(Nreac):
                if reac == prod: continue
                reaction = self.network.netReactions[count]
                kinetics = reaction.kinetics
                count += 1
                
                string = '{0!s}    1.0 0.0 0.0    0.0 0.0 0.0\n'.format(reaction)
                
                if isinstance(kinetics, PDepArrhenius):
                    for P, arrhenius in zip(kinetics.pressures.value_si, kinetics.arrhenius):
                        string += 'PLOG/ {0:<9.3f} {1:<11.3e} {2:<8.2f} {3:<8.2f}/\n'.format(P / 101325.,
                            arrhenius.A.value_si / (arrhenius.T0.value_si ** arrhenius.n) * 1e6 ** (len(reaction.reactants) - 1),
                            arrhenius.n,
                            arrhenius.Ea.value_si / 4184.
                        )
                        
                elif isinstance(kinetics, Chebyshev):
                    coeffs = kinetics.coeffs.value_si.copy()
                    coeffs[0,0] += 6 * (len(reaction.reactants) - 1)
                    string += 'TCHEB/ {0:<9.3f} {1:<9.3f}/\n'.format(kinetics.Tmin.value_si, kinetics.Tmax.value_si)
                    string += 'PCHEB/ {0:<9.3f} {1:<9.3f}/\n'.format(kinetics.Pmin.value_si / 101325., kinetics.Pmax.value_si / 101325.)
                    string += 'CHEB/ {0:d} {1:d}/\n'.format(kinetics.degreeT, kinetics.degreeP)
                    if kinetics.degreeP < 6:
                        for i in range(kinetics.degreeT):
                            string += 'CHEB/'
                            for j in range(kinetics.degreeP):
                                string += ' {0:<12.3e}'.format(coeffs[i,j])
                            string += '/\n'
                    else:
                        coeffs_list = []
                        for i in range(kinetics.degreeT):
                            for j in range(kinetics.degreeP):
                                coeffs_list.append(coeffs[i,j])
                        coeffs_list[0] += 6 * (numReactants - 1)
                        for i in range(len(coeffs_list)):
                            if i % 5 == 0: string += '    CHEB/'
                            string += ' {0:<12.3e}'.format(coeffs_list[i])
                            if i % 5 == 4: string += '/\n'  

                f.write('{0}\n'.format(string))
            
        f.close()
Exemple #13
0
    def save(self, outputFile):
        """
        Save the results of the thermodynamics job to the file located
        at `path` on disk.
        """
        species = self.species
        logging.info('Saving thermo for {0}...'.format(species.label))

        f = open(outputFile, 'a')

        f.write('# Thermodynamics for {0}:\n'.format(species.label))
        H298 = species.thermo.getEnthalpy(298) / 4184.
        S298 = species.thermo.getEntropy(298) / 4.184
        f.write(
            '#   Enthalpy of formation (298 K)   = {0:9.3f} kcal/mol\n'.format(
                H298))
        f.write('#   Entropy of formation (298 K)    = {0:9.3f} cal/(mol*K)\n'.
                format(S298))
        f.write(
            '#    =========== =========== =========== =========== ===========\n'
        )
        f.write(
            '#    Temperature Heat cap.   Enthalpy    Entropy     Free energy\n'
        )
        f.write(
            '#    (K)         (cal/mol*K) (kcal/mol)  (cal/mol*K) (kcal/mol)\n'
        )
        f.write(
            '#    =========== =========== =========== =========== ===========\n'
        )
        for T in [300, 400, 500, 600, 800, 1000, 1500, 2000, 2400]:
            Cp = species.thermo.getHeatCapacity(T) / 4.184
            H = species.thermo.getEnthalpy(T) / 4184.
            S = species.thermo.getEntropy(T) / 4.184
            G = species.thermo.getFreeEnergy(T) / 4184.
            f.write('#    {0:11g} {1:11.3f} {2:11.3f} {3:11.3f} {4:11.3f}\n'.
                    format(T, Cp, H, S, G))
        f.write(
            '#    =========== =========== =========== =========== ===========\n'
        )

        string = 'thermo(label={0!r}, thermo={1!r})'.format(
            species.label, species.thermo)
        f.write('{0}\n\n'.format(prettify(string)))

        f.close()

        f = open(os.path.join(os.path.dirname(outputFile), 'chem.inp'), 'a')

        thermo = species.thermo
        if isinstance(thermo, NASA):

            poly_low = thermo.polynomials[0]
            poly_high = thermo.polynomials[1]

            # Determine the number of each type of element in the molecule
            elements = ['C', 'H', 'N', 'O']
            elementCounts = [0, 0, 0, 0]

            # Remove elements with zero count
            index = 2
            while index < len(elementCounts):
                if elementCounts[index] == 0:
                    del elements[index]
                    del elementCounts[index]
                else:
                    index += 1

            # Line 1
            string = '{0:<16}        '.format(species.label)
            if len(elements) <= 4:
                # Use the original Chemkin syntax for the element counts
                for symbol, count in zip(elements, elementCounts):
                    string += '{0!s:<2}{1:<3d}'.format(symbol, count)
                string += '     ' * (4 - len(elements))
            else:
                string += '     ' * 4
            string += 'G{0:<10.3f}{1:<10.3f}{2:<8.2f}      1'.format(
                poly_low.Tmin.value_si, poly_high.Tmax.value_si,
                poly_low.Tmax.value_si)
            if len(elements) > 4:
                string += '&\n'
                # Use the new-style Chemkin syntax for the element counts
                # This will only be recognized by Chemkin 4 or later
                for symbol, count in zip(elements, elementCounts):
                    string += '{0!s:<2}{1:<3d}'.format(symbol, count)
            string += '\n'

            # Line 2
            string += '{0:< 15.8E}{1:< 15.8E}{2:< 15.8E}{3:< 15.8E}{4:< 15.8E}    2\n'.format(
                poly_high.c0, poly_high.c1, poly_high.c2, poly_high.c3,
                poly_high.c4)

            # Line 3
            string += '{0:< 15.8E}{1:< 15.8E}{2:< 15.8E}{3:< 15.8E}{4:< 15.8E}    3\n'.format(
                poly_high.c5, poly_high.c6, poly_low.c0, poly_low.c1,
                poly_low.c2)

            # Line 4
            string += '{0:< 15.8E}{1:< 15.8E}{2:< 15.8E}{3:< 15.8E}                   4\n'.format(
                poly_low.c3, poly_low.c4, poly_low.c5, poly_low.c6)

            f.write(string)

            f.close()
Exemple #14
0
    def save(self, outputFile):

        logging.info(
            'Saving pressure dependence results for {0} network...'.format(
                self.network.label))
        f = open(outputFile, 'a')

        Nreac = self.network.Nisom + self.network.Nreac
        Nprod = Nreac + self.network.Nprod
        Tlist = self.Tlist.value_si
        Plist = self.Plist.value_si
        Tcount = Tlist.shape[0]
        Pcount = Plist.shape[0]

        count = 0
        for prod in range(Nprod):
            for reac in range(Nreac):
                if reac == prod: continue
                reaction = self.network.netReactions[count]
                count += 1

                kdata = self.K[:, :, prod, reac].copy()
                order = len(reaction.reactants)
                kdata *= 1e6**(order - 1)
                kunits = {
                    1: 's^-1',
                    2: 'cm^3/(mol*s)',
                    3: 'cm^6/(mol^2*s)'
                }[order]

                f.write('#   =========== ')
                f.write('=========== ' * Pcount)
                f.write('\n')
                f.write('#         T \ P ')
                f.write(' '.join(['{0:11.3e}'.format(P * 1e-5)
                                  for P in Plist]))
                f.write('\n')
                f.write('#   =========== ')
                f.write('=========== ' * Pcount)
                f.write('\n')

                for t in range(Tcount):
                    f.write('#   {0:11g}'.format(Tlist[t]))
                    for p in range(Pcount):
                        f.write(' {0:11.3e}'.format(kdata[t, p]))
                    f.write('\n')

                f.write('#   =========== ')
                f.write('=========== ' * Pcount)
                f.write('\n')

                string = 'pdepreaction(reactants={0!r}, products={1!r}, kinetics={2!r})'.format(
                    [reactant.label for reactant in reaction.reactants],
                    [product.label for product in reaction.products],
                    reaction.kinetics,
                )
                f.write('{0}\n\n'.format(prettify(string)))

        f.close()

        f = open(os.path.join(os.path.dirname(outputFile), 'chem.inp'), 'a')

        count = 0
        for prod in range(Nprod):
            for reac in range(Nreac):
                if reac == prod: continue
                reaction = self.network.netReactions[count]
                count += 1
                string = writeKineticsEntry(reaction,
                                            speciesList=None,
                                            verbose=False)
                f.write('{0}\n'.format(string))

        f.close()
Exemple #15
0
    def save(self, outputFile):
        """
        Save the results of the kinetics job to the file located
        at `path` on disk.
        """
        reaction = self.reaction
        
        ks = []
        k0s = []
        k0revs = []
        krevs = []
        
        logging.info('Saving kinetics for {0}...'.format(reaction))
        
        order = len(self.reaction.reactants)
        factor = 1e6 ** (order-1)
        
        f = open(outputFile, 'a')
    
        f.write('#   ======= =========== =========== =========== ===============\n')
        f.write('#   Temp.   k (TST)     Tunneling   k (TST+T)   Units\n')
        f.write('#   ======= =========== =========== =========== ===============\n')
        
        if self.Tlist is None:
            Tlist = [300,400,500,600,800,1000,1500,2000]
        else:
            Tlist =self.Tlist.value_si

        for T in Tlist:  
            tunneling = reaction.transitionState.tunneling
            reaction.transitionState.tunneling = None
            k0 = reaction.calculateTSTRateCoefficient(T) * factor
            reaction.transitionState.tunneling = tunneling
            k = reaction.calculateTSTRateCoefficient(T) * factor
            tunneling = reaction.transitionState.tunneling
            kappa = k / k0
            ks.append(k)
            k0s.append(k0)
            f.write('#    {0:4g} K {1:11.3e} {2:11g} {3:11.3e} {4}\n'.format(T, k0, kappa, k, self.kunits))
        f.write('#   ======= =========== =========== =========== ===============\n')
        f.write('\n\n')
        
        f.write('#   ======= ============ =========== ============ ============= =========\n')
        f.write('#   Temp.    Kc (eq)        Units     krev (TST)   krev (TST+T)   Units\n')
        f.write('#   ======= ============ =========== ============ ============= =========\n')
        
        for n,T in enumerate(Tlist):
            k = ks[n]
            k0 = k0s[n]
            Keq = reaction.getEquilibriumConstant(T)
            k0rev = k0/Keq
            krev =  k/Keq
            k0revs.append(k0rev)
            krevs.append(krev)
            f.write('#    {0:4g} K {1:11.3e}   {2}  {3:11.3e}   {4:11.3e}      {5}\n'.format(T, Keq, self.Kequnits, k0rev, krev, self.krunits))

            
        f.write('#   ======= ============ =========== ============ ============= =========\n')
        f.write('\n\n')
        
        kinetics0rev = Arrhenius().fitToData(Tlist, numpy.array(k0revs), kunits=self.krunits)
        kineticsrev = Arrhenius().fitToData(Tlist, numpy.array(krevs), kunits=self.krunits)
        
        f.write('# krev (TST) = {0} \n'.format(kinetics0rev))
        f.write('# krev (TST+T) = {0} \n\n'.format(kineticsrev))
                
        # Reaction path degeneracy is INCLUDED in the kinetics itself!
        string = 'kinetics(label={0!r}, kinetics={1!r})'.format(reaction.label, reaction.kinetics)
        f.write('{0}\n\n'.format(prettify(string)))
        
        f.close()
        
        # Also save the result to chem.inp
        f = open(os.path.join(os.path.dirname(outputFile), 'chem.inp'), 'a')
        
        reaction = self.reaction
        kinetics = reaction.kinetics
                
        string = '{0!s:51} {1:9.3e} {2:9.3f} {3:9.3f}\n'.format(
            reaction,
            kinetics.A.value_si * factor,
            kinetics.n.value_si,
            kinetics.Ea.value_si / 4184.,
        )
                
        f.write('{0}\n'.format(string))
            
        f.close()
Exemple #16
0
    def save(self, outputFile):
        """
        Save the results of the thermodynamics job to the file located
        at `path` on disk.
        """
        species = self.species
        logging.info('Saving thermo for {0}...'.format(species.label))

        f = open(outputFile, 'a')

        f.write('# Thermodynamics for {0}:\n'.format(species.label))
        H298 = species.getThermoData().getEnthalpy(298) / 4184.
        S298 = species.getThermoData().getEntropy(298) / 4.184
        f.write(
            '#   Enthalpy of formation (298 K)   = {0:9.3f} kcal/mol\n'.format(
                H298))
        f.write('#   Entropy of formation (298 K)    = {0:9.3f} cal/(mol*K)\n'.
                format(S298))
        f.write(
            '#    =========== =========== =========== =========== ===========\n'
        )
        f.write(
            '#    Temperature Heat cap.   Enthalpy    Entropy     Free energy\n'
        )
        f.write(
            '#    (K)         (cal/mol*K) (kcal/mol)  (cal/mol*K) (kcal/mol)\n'
        )
        f.write(
            '#    =========== =========== =========== =========== ===========\n'
        )
        for T in [300, 400, 500, 600, 800, 1000, 1500, 2000, 2400]:
            Cp = species.getThermoData().getHeatCapacity(T) / 4.184
            H = species.getThermoData().getEnthalpy(T) / 4184.
            S = species.getThermoData().getEntropy(T) / 4.184
            G = species.getThermoData().getFreeEnergy(T) / 4184.
            f.write('#    {0:11g} {1:11.3f} {2:11.3f} {3:11.3f} {4:11.3f}\n'.
                    format(T, Cp, H, S, G))
        f.write(
            '#    =========== =========== =========== =========== ===========\n'
        )

        string = 'thermo(label={0!r}, thermo={1!r})'.format(
            species.label, species.getThermoData())
        f.write('{0}\n\n'.format(prettify(string)))

        f.close()
        # write chemkin file
        f = open(os.path.join(os.path.dirname(outputFile), 'chem.inp'), 'a')
        if isinstance(species, Species):
            if species.molecule and isinstance(species.molecule[0], Molecule):
                elementCounts = retrieveElementCount(species.molecule[0])
            else:
                try:
                    elementCounts = species.props['elementCounts']
                except KeyError:
                    elementCounts = {'C': 0, 'H': 0}
        else:
            elementCounts = {'C': 0, 'H': 0}
        string = writeThermoEntry(species,
                                  elementCounts=elementCounts,
                                  verbose=False)
        f.write('{0}\n'.format(string))
        f.close()

        # write species dictionary
        f = open(
            os.path.join(os.path.dirname(outputFile),
                         'species_dictionary.txt'), 'a')
        if isinstance(species, Species):
            if species.molecule and isinstance(species.molecule[0], Molecule):
                f.write(species.molecule[0].toAdjacencyList(
                    removeH=False, label=species.label))
                f.write('\n')
        f.close()
Exemple #17
0
def saveEntry(f, entry):
    """
    Save an `entry` in the kinetics database by writing a string to
    the given file object `f`.
    """
    from rmgpy.cantherm.output import prettify

    def sortEfficiencies(efficiencies0):
        efficiencies = {}
        for mol, eff in efficiencies0.iteritems():
            smiles = mol.toSMILES()
            efficiencies[smiles] = eff
        keys = efficiencies.keys()
        keys.sort()
        return [(key, efficiencies[key]) for key in keys]

    f.write('entry(\n')
    f.write('    index = {0:d},\n'.format(entry.index))
    if entry.label != '':
        f.write('    label = "{0}",\n'.format(entry.label))

    if isinstance(entry.item, Reaction):
        for i, reactant in enumerate(entry.item.reactants):
            if isinstance(reactant, Molecule):
                f.write('    reactant{0:d} = \n'.format(i+1))
                f.write('"""\n')
                f.write(reactant.toAdjacencyList(removeH=True))
                f.write('""",\n')
            elif isinstance(reactant, Species):
                f.write('    reactant{0:d} = \n'.format(i+1))
                f.write('"""\n')
                f.write(reactant.molecule[0].toAdjacencyList(label=reactant.label, removeH=True))
                f.write('""",\n')
            elif isinstance(reactant, Group):
                f.write('    group{0:d} = \n'.format(i+1))
                f.write('"""\n')
                f.write(reactant.toAdjacencyList())
                f.write('""",\n')
            elif isinstance(reactant, LogicNode):
                f.write('    group{0:d} = "{1}",\n'.format(i+1, reactant))
        for i, product in enumerate(entry.item.products):
            if isinstance(product, Molecule):
                f.write('    product{0:d} = \n'.format(i+1))
                f.write('"""\n')
                f.write(product.toAdjacencyList(removeH=True))
                f.write('""",\n')
            elif isinstance(reactant, Species):
                f.write('    product{0:d} = \n'.format(i+1))
                f.write('"""\n')
                f.write(product.molecule[0].toAdjacencyList(label=product.label, removeH=True))
                f.write('""",\n')
        if not isinstance(entry.item.reactants[0], Group) and not isinstance(entry.item.reactants[0], LogicNode):
            f.write('    degeneracy = {0:d},\n'.format(entry.item.degeneracy))
        if entry.item.duplicate: 
            f.write('    duplicate = {0!r},\n'.format(entry.item.duplicate))
        if not entry.item.reversible:
            f.write('    reversible = {0!r},\n'.format(entry.item.reversible))
    elif isinstance(entry.item, Group):
        f.write('    group = \n')
        f.write('"""\n')
        f.write(entry.item.toAdjacencyList())
        f.write('""",\n')
    elif isinstance(entry.item, LogicNode):
        f.write('    group = "{0}",\n'.format(entry.item))
    else:
        raise DatabaseError("Encountered unexpected item of type {0} while saving database.".format(entry.item.__class__))

    # Write kinetics
    if isinstance(entry.data, str):
        f.write('    kinetics = "{0}",\n'.format(entry.data))
    elif entry.data is not None:
        efficiencies = None
        if hasattr(entry.data, 'efficiencies'):
            efficiencies = entry.data.efficiencies
            entry.data.efficiencies = dict(sortEfficiencies(entry.data.efficiencies))
        kinetics = prettify(repr(entry.data))
        kinetics = '    kinetics = {0},\n'.format(kinetics.replace('\n', '\n    '))
        f.write(kinetics)
        if hasattr(entry.data, 'efficiencies'):
            entry.data.efficiencies = efficiencies
    else:
        f.write('    kinetics = None,\n')
            
    # Write reference
    if entry.reference is not None:
        reference = entry.reference.toPrettyRepr()
        lines = reference.splitlines()
        f.write('    reference = {0}\n'.format(lines[0]))
        for line in lines[1:-1]:
            f.write('    {0}\n'.format(line))
        f.write('    ),\n'.format(lines[0]))
    else:
        f.write('    reference = None,\n')
    
    f.write('    referenceType = "{0}",\n'.format(entry.referenceType))
    if entry.rank is not None:
        f.write('    rank = {0},\n'.format(entry.rank))
    f.write('    shortDesc = u"""')
    f.write(entry.shortDesc)
    f.write('""",\n')
    f.write('    longDesc = \n')
    f.write('u"""\n')
    f.write(entry.longDesc.strip() + "\n")
    f.write('""",\n')

    f.write('    history = [\n')
    for time, user, action, description in entry.history:
        f.write('        ("{0}","{1}","{2}","""{3}"""),\n'.format(time, user, action, description))
    f.write('    ],\n')

    f.write(')\n\n')
Exemple #18
0
def saveEntry(f, entry):
    """
    Save an `entry` in the kinetics database by writing a string to
    the given file object `f`.
    """
    from rmgpy.cantherm.output import prettify

    def sortEfficiencies(efficiencies0):
        efficiencies = {}
        for mol, eff in efficiencies0.iteritems():
            if isinstance(mol, str):
                # already in SMILES string format
                smiles = mol
            else:
                smiles = mol.toSMILES()
                
            efficiencies[smiles] = eff
        keys = efficiencies.keys()
        keys.sort()
        return [(key, efficiencies[key]) for key in keys]

    f.write('entry(\n')
    f.write('    index = {0:d},\n'.format(entry.index))
    if entry.label != '':
        f.write('    label = "{0}",\n'.format(entry.label))


    #Entries for kinetic rules, libraries, training reactions
    #and depositories will have an Reaction object for its item
    if isinstance(entry.item, Reaction):
        #Write out additional data if depository or library
        #kinetic rules would have a Group object for its reactants instead of Species
        if isinstance(entry.item.reactants[0], Species):
            # Add degeneracy if the reaction is coming from a depository or kinetics library
            f.write('    degeneracy = {0:.1f},\n'.format(entry.item.degeneracy))
            if entry.item.duplicate:
                f.write('    duplicate = {0!r},\n'.format(entry.item.duplicate))
            if not entry.item.reversible:
                f.write('    reversible = {0!r},\n'.format(entry.item.reversible))
    #Entries for groups with have a group or logicNode for its item
    elif isinstance(entry.item, Group):
        f.write('    group = \n')
        f.write('"""\n')
        f.write(entry.item.toAdjacencyList())
        f.write('""",\n')
    elif isinstance(entry.item, LogicNode):
        f.write('    group = "{0}",\n'.format(entry.item))
    else:
        raise DatabaseError("Encountered unexpected item of type {0} while saving database.".format(entry.item.__class__))

    # Write kinetics
    if isinstance(entry.data, str):
        f.write('    kinetics = "{0}",\n'.format(entry.data))
    elif entry.data is not None:
        efficiencies = None
        if hasattr(entry.data, 'efficiencies'):
            efficiencies = entry.data.efficiencies
            entry.data.efficiencies = dict(sortEfficiencies(entry.data.efficiencies))
        kinetics = prettify(repr(entry.data))
        kinetics = '    kinetics = {0},\n'.format(kinetics.replace('\n', '\n    '))
        f.write(kinetics)
        if hasattr(entry.data, 'efficiencies'):
            entry.data.efficiencies = efficiencies
    else:
        f.write('    kinetics = None,\n')
            
    # Write reference
    if entry.reference is not None:
        reference = entry.reference.toPrettyRepr()
        lines = reference.splitlines()
        f.write('    reference = {0}\n'.format(lines[0]))
        for line in lines[1:-1]:
            f.write('    {0}\n'.format(line))
        f.write('    ),\n'.format(lines[0]))
    
    if entry.referenceType != "":
        f.write('    referenceType = "{0}",\n'.format(entry.referenceType))
    if entry.rank is not None:
        f.write('    rank = {0},\n'.format(entry.rank))
        
    if entry.shortDesc.strip() !='':
        f.write('    shortDesc = u"""')
        try:
            f.write(entry.shortDesc.encode('utf-8'))
        except:
            f.write(entry.shortDesc.strip().encode('ascii', 'ignore')+ "\n")
        f.write('""",\n')
    
    if entry.longDesc.strip() !='':
        f.write('    longDesc = \n')
        f.write('u"""\n')
        try:
            f.write(entry.longDesc.strip().encode('utf-8') + "\n")
        except:
            f.write(entry.longDesc.strip().encode('ascii', 'ignore')+ "\n")
        f.write('""",\n')

    f.write(')\n\n')
Exemple #19
0
    def save(self, outputFile):
        
        logging.info('Saving pressure dependence results for {0} network...'.format(self.network.label))
        f = open(outputFile, 'a')
    
        Nreac = self.network.Nisom + self.network.Nreac
        Nprod = Nreac + self.network.Nprod
        Tlist = self.Tlist.value_si
        Plist = self.Plist.value_si
        Tcount = Tlist.shape[0]
        Pcount = Plist.shape[0]
        
        count = 0
        for prod in range(Nprod):
            for reac in range(Nreac):
                if reac == prod: continue
                reaction = self.network.netReactions[count]
                count += 1
                
                kdata = self.K[:,:,prod,reac].copy()
                order = len(reaction.reactants)
                kdata *= 1e6 ** (order-1)
                kunits = {1: 's^-1', 2: 'cm^3/(mol*s)', 3: 'cm^6/(mol^2*s)'}[order]
                
                f.write('#   =========== ')
                f.write('=========== ' * Pcount)
                f.write('\n')
                f.write('#         T \ P ')
                f.write(' '.join(['{0:11.3e}'.format(P*1e-5) for P in Plist]))
                f.write('\n')
                f.write('#   =========== ')
                f.write('=========== ' * Pcount)
                f.write('\n')
                
                for t in range(Tcount):
                    f.write('#   {0:11g}'.format(Tlist[t]))
                    for p in range(Pcount):
                        f.write(' {0:11.3e}'.format(kdata[t,p]))
                    f.write('\n')
                
                f.write('#   =========== ')
                f.write('=========== ' * Pcount)
                f.write('\n')
                
                string = 'pdepreaction(reactants={0!r}, products={1!r}, kinetics={2!r})'.format(
                    [reactant.label for reactant in reaction.reactants],
                    [product.label for product in reaction.products],
                    reaction.kinetics,
                )
                f.write('{0}\n\n'.format(prettify(string)))
        
        f.close()
        
        f = open(os.path.join(os.path.dirname(outputFile), 'chem.inp'), 'a')
        
        count = 0
        for prod in range(Nprod):
            for reac in range(Nreac):
                if reac == prod: continue
                reaction = self.network.netReactions[count]
                kinetics = reaction.kinetics
                count += 1
                
                string = '{0!s:51} 1.0 0.0 0.0\n'.format(reaction)
                
                if isinstance(kinetics, PDepArrhenius):
                    for P, arrhenius in zip(kinetics.pressures.value_si, kinetics.arrhenius):
                        string += 'PLOG/ {0:<9.3f} {1:<11.3e} {2:<8.2f} {3:<8.2f}/\n'.format(P / 101325.,
                            arrhenius.A.value_si / (arrhenius.T0.value_si ** arrhenius.n.value_si) * 1e6 ** (len(reaction.reactants) - 1),
                            arrhenius.n.value_si,
                            arrhenius.Ea.value_si / 4184.
                        )
                        
                elif isinstance(kinetics, Chebyshev):
                    coeffs = kinetics.coeffs.value_si.copy()
                    coeffs[0,0] += 6 * (len(reaction.reactants) - 1)
                    string += 'TCHEB/ {0:<9.3f} {1:<9.3f}/\n'.format(kinetics.Tmin.value_si, kinetics.Tmax.value_si)
                    string += 'PCHEB/ {0:<9.3f} {1:<9.3f}/\n'.format(kinetics.Pmin.value_si / 101325., kinetics.Pmax.value_si / 101325.)
                    string += 'CHEB/ {0:d} {1:d}/\n'.format(kinetics.degreeT, kinetics.degreeP)
                    if kinetics.degreeP < 6:
                        for i in range(kinetics.degreeT):
                            string += 'CHEB/'
                            for j in range(kinetics.degreeP):
                                string += ' {0:<12.3e}'.format(coeffs[i,j])
                            string += '/\n'
                    else:
                        coeffs_list = []
                        for i in range(kinetics.degreeT):
                            for j in range(kinetics.degreeP):
                                coeffs_list.append(coeffs[i,j])
                        coeffs_list[0] += 6 * (numReactants - 1)
                        for i in range(len(coeffs_list)):
                            if i % 5 == 0: string += '    CHEB/'
                            string += ' {0:<12.3e}'.format(coeffs_list[i])
                            if i % 5 == 4: string += '/\n'  

                f.write('{0}\n'.format(string))
            
        f.close()
Exemple #20
0
    def save(self, outputFile):
        
        logging.info('Saving pressure dependence results for {0} network...'.format(self.network.label))
        f = open(outputFile, 'a')
        f_chemkin = open(os.path.join(os.path.dirname(outputFile), 'chem.inp'), 'a')
    
        Nreac = self.network.Nisom + self.network.Nreac
        Nprod = Nreac + self.network.Nprod
        Tlist = self.Tlist.value_si
        Plist = self.Plist.value_si
        Tcount = Tlist.shape[0]
        Pcount = Plist.shape[0]
        
        count = 0
        printed_reactions = [] # list of rxns already printed
        for prod in range(Nprod):
            for reac in range(Nreac):
                if reac == prod: continue
                reaction = self.network.netReactions[count]
                count += 1
                # make sure we aren't double counting any reactions
                if not any([reaction.isIsomorphic(other_rxn,checkOnlyLabel=True) \
                            for other_rxn in printed_reactions]):
                    duplicate = False
                    # add reaction to printed reaction
                    printed_reactions.append(reaction)
                else:
                    # comment out the extra reverse reaction
                    duplicate = True

                # write chemkin output.
                string = writeKineticsEntry(reaction, speciesList=None, verbose=False, commented = duplicate)
                f_chemkin.write('{0}\n'.format(string))

                # write to 'output.py'
                kdata = self.K[:,:,prod,reac].copy()
                order = len(reaction.reactants)
                kdata *= 1e6 ** (order-1)
                kunits = {1: 's^-1', 2: 'cm^3/(mol*s)', 3: 'cm^6/(mol^2*s)'}[order]
                
                f.write('#   =========== ')
                f.write('=========== ' * Pcount)
                f.write('\n')
                f.write('#         T \ P ')
                f.write(' '.join(['{0:11.3e}'.format(P*1e-5) for P in Plist]))
                f.write('\n')
                f.write('#   =========== ')
                f.write('=========== ' * Pcount)
                f.write('\n')
                
                for t in range(Tcount):
                    f.write('#   {0:11g}'.format(Tlist[t]))
                    for p in range(Pcount):
                        f.write(' {0:11.3e}'.format(kdata[t,p]))
                    f.write('\n')
                
                f.write('#   =========== ')
                f.write('=========== ' * Pcount)
                f.write('\n')
                
                string = 'pdepreaction(reactants={0!r}, products={1!r}, kinetics={2!r})'.format(
                    [reactant.label for reactant in reaction.reactants],
                    [product.label for product in reaction.products],
                    reaction.kinetics,
                )
                pdep_function = '{0}\n\n'.format(prettify(string))
                if duplicate:
                    # add comments to the start of the string
                    pdep_function = '#   ' + pdep_function.replace('\n','\n#   ')
                f.write(pdep_function)

        f.close()
        f_chemkin.close()
Exemple #21
0
    def save(self, outputFile):
        """
        Save the results of the kinetics job to the file located
        at `path` on disk.
        """
        reaction = self.reaction
        
        ks = []
        k0s = []
        k0revs = []
        krevs = []
        
        logging.info('Saving kinetics for {0}...'.format(reaction))
        
        order = len(self.reaction.reactants)
        factor = 1e6 ** (order-1)
        
        f = open(outputFile, 'a')
    
        f.write('#   ======= =========== =========== =========== ===============\n')
        f.write('#   Temp.   k (TST)     Tunneling   k (TST+T)   Units\n')
        f.write('#   ======= =========== =========== =========== ===============\n')
        
        if self.Tlist is None:
            Tlist = numpy.array([300,400,500,600,800,1000,1500,2000])
        else:
            Tlist =self.Tlist.value_si

        for T in Tlist:  
            tunneling = reaction.transitionState.tunneling
            reaction.transitionState.tunneling = None
            k0 = reaction.calculateTSTRateCoefficient(T) * factor
            reaction.transitionState.tunneling = tunneling
            k = reaction.calculateTSTRateCoefficient(T) * factor
            tunneling = reaction.transitionState.tunneling
            kappa = k / k0
            ks.append(k)
            k0s.append(k0)
            f.write('#    {0:4g} K {1:11.3e} {2:11g} {3:11.3e} {4}\n'.format(T, k0, kappa, k, self.kunits))
        f.write('#   ======= =========== =========== =========== ===============\n')
        f.write('\n\n')
        
        f.write('#   ======= ============ =========== ============ ============= =========\n')
        f.write('#   Temp.    Kc (eq)        Units     krev (TST)   krev (TST+T)   Units\n')
        f.write('#   ======= ============ =========== ============ ============= =========\n')
        
        for n,T in enumerate(Tlist):
            k = ks[n]
            k0 = k0s[n]
            Keq = reaction.getEquilibriumConstant(T)
            k0rev = k0/Keq
            krev =  k/Keq
            k0revs.append(k0rev)
            krevs.append(krev)
            f.write('#    {0:4g} K {1:11.3e}   {2}  {3:11.3e}   {4:11.3e}      {5}\n'.format(T, Keq, self.Kequnits, k0rev, krev, self.krunits))

            
        f.write('#   ======= ============ =========== ============ ============= =========\n')
        f.write('\n\n')
        
        kinetics0rev = Arrhenius().fitToData(Tlist, numpy.array(k0revs), kunits=self.krunits)
        kineticsrev = Arrhenius().fitToData(Tlist, numpy.array(krevs), kunits=self.krunits)
        
        f.write('# krev (TST) = {0} \n'.format(kinetics0rev))
        f.write('# krev (TST+T) = {0} \n\n'.format(kineticsrev))
                
        # Reaction path degeneracy is INCLUDED in the kinetics itself!
        string = 'kinetics(label={0!r}, kinetics={1!r})'.format(reaction.label, reaction.kinetics)
        f.write('{0}\n\n'.format(prettify(string)))
        
        f.close()
        
        # Also save the result to chem.inp
        f = open(os.path.join(os.path.dirname(outputFile), 'chem.inp'), 'a')
        
        reaction = self.reaction
        kinetics = reaction.kinetics
                
        string = '{0!s:51} {1:9.3e} {2:9.3f} {3:9.3f}\n'.format(
            reaction,
            kinetics.A.value_si * factor,
            kinetics.n.value_si,
            kinetics.Ea.value_si / 4184.,
        )
                
        f.write('{0}\n'.format(string))
            
        f.close()
Exemple #22
0
def saveEntry(f, entry):
    """
    Save an `entry` in the kinetics database by writing a string to
    the given file object `f`.
    """
    from rmgpy.cantherm.output import prettify

    def sortEfficiencies(efficiencies0):
        efficiencies = {}
        for mol, eff in efficiencies0.iteritems():
            if isinstance(mol, str):
                # already in SMILES string format
                smiles = mol
            else:
                smiles = mol.toSMILES()
                
            efficiencies[smiles] = eff
        keys = efficiencies.keys()
        keys.sort()
        return [(key, efficiencies[key]) for key in keys]

    f.write('entry(\n')
    f.write('    index = {0:d},\n'.format(entry.index))
    if entry.label != '':
        f.write('    label = "{0}",\n'.format(entry.label))

    if isinstance(entry.item, Reaction):
        if entry.label != str(entry.item):
            raise KineticsError("Reactions are now defined solely by their labels, "
                                                "but reaction {0!s} has label {1!r}".format(
                                                 entry.item, entry.label))
#        for i, reactant in enumerate(entry.item.reactants):
#            if isinstance(reactant, Molecule):
#                f.write('    reactant{0:d} = \n'.format(i+1))
#                f.write('"""\n')
#                f.write(reactant.toAdjacencyList(removeH=False))
#                f.write('""",\n')
#            elif isinstance(reactant, Species):
#                f.write('    reactant{0:d} = \n'.format(i+1))
#                f.write('"""\n')
#                f.write(reactant.molecule[0].toAdjacencyList(label=reactant.label, removeH=False))
#                f.write('""",\n')
#        for i, product in enumerate(entry.item.products):
#            if isinstance(product, Molecule):
#                f.write('    product{0:d} = \n'.format(i+1))
#                f.write('"""\n')
#                f.write(product.toAdjacencyList(removeH=False))
#                f.write('""",\n')
#            elif isinstance(reactant, Species):
#                f.write('    product{0:d} = \n'.format(i+1))
#                f.write('"""\n')
#                f.write(product.molecule[0].toAdjacencyList(label=product.label, removeH=False))
#                f.write('""",\n')
        if isinstance(entry.item.reactants[0], Species): 
            # Add degeneracy if the reaction is coming from a depository or kinetics library
            f.write('    degeneracy = {0:d},\n'.format(entry.item.degeneracy))
        if entry.item.duplicate: 
            f.write('    duplicate = {0!r},\n'.format(entry.item.duplicate))
        if not entry.item.reversible:
            f.write('    reversible = {0!r},\n'.format(entry.item.reversible))
    elif isinstance(entry.item, Group):
        f.write('    group = \n')
        f.write('"""\n')
        f.write(entry.item.toAdjacencyList())
        f.write('""",\n')
    elif isinstance(entry.item, LogicNode):
        f.write('    group = "{0}",\n'.format(entry.item))
    else:
        raise DatabaseError("Encountered unexpected item of type {0} while saving database.".format(entry.item.__class__))

    # Write kinetics
    if isinstance(entry.data, str):
        f.write('    kinetics = "{0}",\n'.format(entry.data))
    elif entry.data is not None:
        efficiencies = None
        if hasattr(entry.data, 'efficiencies'):
            efficiencies = entry.data.efficiencies
            entry.data.efficiencies = dict(sortEfficiencies(entry.data.efficiencies))
        kinetics = prettify(repr(entry.data))
        kinetics = '    kinetics = {0},\n'.format(kinetics.replace('\n', '\n    '))
        f.write(kinetics)
        if hasattr(entry.data, 'efficiencies'):
            entry.data.efficiencies = efficiencies
    else:
        f.write('    kinetics = None,\n')
            
    # Write reference
    if entry.reference is not None:
        reference = entry.reference.toPrettyRepr()
        lines = reference.splitlines()
        f.write('    reference = {0}\n'.format(lines[0]))
        for line in lines[1:-1]:
            f.write('    {0}\n'.format(line))
        f.write('    ),\n'.format(lines[0]))
    
    if entry.referenceType != "":
        f.write('    referenceType = "{0}",\n'.format(entry.referenceType))
    if entry.rank is not None:
        f.write('    rank = {0},\n'.format(entry.rank))
        
    if entry.shortDesc.strip() !='':
        f.write('    shortDesc = u"""')
        try:
            f.write(entry.shortDesc.encode('utf-8'))
        except:
            f.write(entry.shortDesc.strip().encode('ascii', 'ignore')+ "\n")
        f.write('""",\n')
    
    if entry.longDesc.strip() !='':
        f.write('    longDesc = \n')
        f.write('u"""\n')
        try:
            f.write(entry.longDesc.strip().encode('utf-8') + "\n")
        except:
            f.write(entry.longDesc.strip().encode('ascii', 'ignore')+ "\n")
        f.write('""",\n')

    f.write(')\n\n')
Exemple #23
0
def saveEntry(f, entry):
    """
    Save an `entry` in the kinetics database by writing a string to
    the given file object `f`.
    """
    from rmgpy.cantherm.output import prettify

    def sortEfficiencies(efficiencies0):
        efficiencies = {}
        for mol, eff in efficiencies0.iteritems():
            if isinstance(mol, str):
                # already in SMILES string format
                smiles = mol
            else:
                smiles = mol.toSMILES()
                
            efficiencies[smiles] = eff
        keys = efficiencies.keys()
        keys.sort()
        return [(key, efficiencies[key]) for key in keys]

    f.write('entry(\n')
    f.write('    index = {0:d},\n'.format(entry.index))
    if entry.label != '':
        f.write('    label = "{0}",\n'.format(entry.label))

    if isinstance(entry.item, Reaction):
        if entry.label != str(entry.item):
            raise KineticsError("Reactions are now defined solely by their labels, "
                                                "but reaction {0!s} has label {1!r}".format(
                                                 entry.item, entry.label))
#        for i, reactant in enumerate(entry.item.reactants):
#            if isinstance(reactant, Molecule):
#                f.write('    reactant{0:d} = \n'.format(i+1))
#                f.write('"""\n')
#                f.write(reactant.toAdjacencyList(removeH=False))
#                f.write('""",\n')
#            elif isinstance(reactant, Species):
#                f.write('    reactant{0:d} = \n'.format(i+1))
#                f.write('"""\n')
#                f.write(reactant.molecule[0].toAdjacencyList(label=reactant.label, removeH=False))
#                f.write('""",\n')
#        for i, product in enumerate(entry.item.products):
#            if isinstance(product, Molecule):
#                f.write('    product{0:d} = \n'.format(i+1))
#                f.write('"""\n')
#                f.write(product.toAdjacencyList(removeH=False))
#                f.write('""",\n')
#            elif isinstance(reactant, Species):
#                f.write('    product{0:d} = \n'.format(i+1))
#                f.write('"""\n')
#                f.write(product.molecule[0].toAdjacencyList(label=product.label, removeH=False))
#                f.write('""",\n')
        if isinstance(entry.item.reactants[0], Species): 
            # Add degeneracy if the reaction is coming from a depository or kinetics library
            f.write('    degeneracy = {0:d},\n'.format(entry.item.degeneracy))
        if entry.item.duplicate: 
            f.write('    duplicate = {0!r},\n'.format(entry.item.duplicate))
        if not entry.item.reversible:
            f.write('    reversible = {0!r},\n'.format(entry.item.reversible))
    elif isinstance(entry.item, Group):
        f.write('    group = \n')
        f.write('"""\n')
        f.write(entry.item.toAdjacencyList())
        f.write('""",\n')
    elif isinstance(entry.item, LogicNode):
        f.write('    group = "{0}",\n'.format(entry.item))
    else:
        raise DatabaseError("Encountered unexpected item of type {0} while saving database.".format(entry.item.__class__))

    # Write kinetics
    if isinstance(entry.data, str):
        f.write('    kinetics = "{0}",\n'.format(entry.data))
    elif entry.data is not None:
        efficiencies = None
        if hasattr(entry.data, 'efficiencies'):
            efficiencies = entry.data.efficiencies
            entry.data.efficiencies = dict(sortEfficiencies(entry.data.efficiencies))
        kinetics = prettify(repr(entry.data))
        kinetics = '    kinetics = {0},\n'.format(kinetics.replace('\n', '\n    '))
        f.write(kinetics)
        if hasattr(entry.data, 'efficiencies'):
            entry.data.efficiencies = efficiencies
    else:
        f.write('    kinetics = None,\n')
            
    # Write reference
    if entry.reference is not None:
        reference = entry.reference.toPrettyRepr()
        lines = reference.splitlines()
        f.write('    reference = {0}\n'.format(lines[0]))
        for line in lines[1:-1]:
            f.write('    {0}\n'.format(line))
        f.write('    ),\n'.format(lines[0]))
    
    if entry.referenceType != "":
        f.write('    referenceType = "{0}",\n'.format(entry.referenceType))
    if entry.rank is not None:
        f.write('    rank = {0},\n'.format(entry.rank))
        
    if entry.shortDesc.strip() !='':
        f.write('    shortDesc = u"""')
        try:
            f.write(entry.shortDesc.encode('utf-8'))
        except:
            f.write(entry.shortDesc.strip().encode('ascii', 'ignore')+ "\n")
        f.write('""",\n')
    
    if entry.longDesc.strip() !='':
        f.write('    longDesc = \n')
        f.write('u"""\n')
        try:
            f.write(entry.longDesc.strip().encode('utf-8') + "\n")
        except:
            f.write(entry.longDesc.strip().encode('ascii', 'ignore')+ "\n")
        f.write('""",\n')

    f.write(')\n\n')
Exemple #24
0
 def save(self, outputFile):
     
     logging.info('Saving pressure dependence results for {0} network...'.format(self.network.label))
     f = open(outputFile, 'a')
 
     Nreac = self.network.Nisom + self.network.Nreac
     Nprod = Nreac + self.network.Nprod
     Tlist = self.Tlist.value_si
     Plist = self.Plist.value_si
     Tcount = Tlist.shape[0]
     Pcount = Plist.shape[0]
     
     count = 0
     for prod in range(Nprod):
         for reac in range(Nreac):
             if reac == prod: continue
             reaction = self.network.netReactions[count]
             count += 1
             
             kdata = self.K[:,:,prod,reac].copy()
             order = len(reaction.reactants)
             kdata *= 1e6 ** (order-1)
             kunits = {1: 's^-1', 2: 'cm^3/(mol*s)', 3: 'cm^6/(mol^2*s)'}[order]
             
             f.write('#   =========== ')
             f.write('=========== ' * Pcount)
             f.write('\n')
             f.write('#         T \ P ')
             f.write(' '.join(['{0:11.3e}'.format(P*1e-5) for P in Plist]))
             f.write('\n')
             f.write('#   =========== ')
             f.write('=========== ' * Pcount)
             f.write('\n')
             
             for t in range(Tcount):
                 f.write('#   {0:11g}'.format(Tlist[t]))
                 for p in range(Pcount):
                     f.write(' {0:11.3e}'.format(kdata[t,p]))
                 f.write('\n')
             
             f.write('#   =========== ')
             f.write('=========== ' * Pcount)
             f.write('\n')
             
             string = 'pdepreaction(reactants={0!r}, products={1!r}, kinetics={2!r})'.format(
                 [reactant.label for reactant in reaction.reactants],
                 [product.label for product in reaction.products],
                 reaction.kinetics,
             )
             f.write('{0}\n\n'.format(prettify(string)))
     
     f.close()
     
     f = open(os.path.join(os.path.dirname(outputFile), 'chem.inp'), 'a')
     
     count = 0
     for prod in range(Nprod):
         for reac in range(Nreac):
             if reac == prod: continue
             reaction = self.network.netReactions[count]
             count += 1
             string = writeKineticsEntry(reaction, speciesList=None, verbose=False)
             f.write('{0}\n'.format(string))
         
     f.close()