示例#1
0
def get_gaussian_input(x, template, mult=0):
    """
    Returns Gaussian input file based on a given template.
    """
    if type(x) is str:
        mol = ob.get_mol(x)
    else:
        mol = x
    if mult == 0:
        mult = ob.get_multiplicity(mol)
    charge = ob.get_charge(mol)
    geo = ob.get_geo(mol)
    xyz = ob.get_xyz(mol)
    zmat = ob.get_zmat(mol)
    uniquename = ob.get_inchi_key(mol, mult)
    inp = template.replace("QTC(CHARGE)", str(charge))
    inp = inp.replace("QTC(MULTIPLICITY)", str(mult))
    inp = inp.replace("QTC(UNIQUENAME)", uniquename)
    inp = inp.replace("QTC(ZMAT)", zmat)
    inp = inp.replace("QTC(GEO)", geo)
    inp = inp.replace("QTC(XYZ)", xyz)
    if "QTC(" in inp:
        print("Error in template file:\n" + inp)
        return
    return inp
示例#2
0
def run_molpro(s, exe='molpro', template='molpro_template.txt', mult=None, overwrite=False):
    """
    Runs molpro, returns a string specifying the status of the calculation.
    TODO
    """
    mol = ob.get_mol(s, make3D=True)
    if mult is None:
        mult = ob.get_multiplicity(mol)
    tmp = io.read_file(template)
    inptext = get_input(mol, tmp, mult)
    prefix = ob.get_smiles_filename(s)
    inpfile = prefix + '.nw'
    outfile = prefix + '_nwchem.log'
    command = [exe, inpfile]
    if io.check_file(outfile, timeout=1):
        if overwrite:
            msg = 'Overwriting previous calculation "{0}"\n'.format(io.get_path(outfile))
            run = True
        else:
            msg = 'Skipping calculation, found "{0}"\n'.format(io.get_path(outfile))
            run = False
    else:
        run = True
    if run:
        if not io.check_file(inpfile, timeout=1) or overwrite:
            io.write_file(inptext, inpfile)
        if io.check_file(inpfile, timeout=1):
            msg = io.execute(command,stdoutfile=outfile,merge=True)
            if io.check_file(outfile, timeout=1):
                msg += ' Output file: "{0}"\n'.format(io.get_path(outfile))
        else:
            msg = 'Failed, cannot find input file "{0}"\n'.format(io.get_path(inpfile))
    return msg
示例#3
0
def get_input(x, template,method='CCSD',basis='cc-pvdz'):
    """
    Returns Gaussian input file text (str) based on a given template.
    """
    mol = ob.get_mol(x)
    mult = ob.get_multiplicity(mol)
    nopen = mult - 1
    charge = ob.get_charge(mol)
    formula = ob.get_formula(mol)
    geo = ob.get_geo(mol)
    xyz = ob.get_xyz(mol)
    zmat = ob.get_zmat(mol)
    uniquename = ob.get_inchi_key(mol, mult)
    smilesname = ob.get_smiles_filename(mol)
    inp = template.replace("QTC(CHARGE)", str(charge))
    inp = inp.replace("QTC(MULTIPLICITY)", str(mult))
    inp = inp.replace("QTC(NOPEN)", str(nopen))
    inp = inp.replace("QTC(UNIQUENAME)", uniquename)
    inp = inp.replace("QTC(SMILESNAME)", smilesname)
    inp = inp.replace("QTC(ZMAT)", zmat)
    inp = inp.replace("QTC(GEO)", geo)
    inp = inp.replace("QTC(XYZ)", xyz)
    inp = inp.replace("QTC(FORMULA)", formula)
    inp = inp.replace("QTC(METHOD)", method)
    inp = inp.replace("QTC(BASIS)", basis)
    if "QTC(" in inp:
        print("Error in template file:\n" + inp)
        return
    return inp
示例#4
0
def run_gaussian(s, exe='g09', template='gaussian_template.txt', mult=None, overwrite=False):
    """
    Runs gaussian calculation
    """
    mol = ob.get_mol(s, make3D=True)
    if mult is None:
        mult = ob.get_multiplicity(mol)
    tmp = io.read_file(template)
    inptext = get_gaussian_input(mol, tmp, mult)
    prefix = ob.get_smiles_filename(s)
    inpfile = prefix + '.g09'
    outfile = prefix + '_gaussian.log'
    command = [exe, inpfile, outfile]
    if io.check_file(outfile, timeout=1):
        if overwrite:
            msg = 'Overwriting previous calculation "{0}"\n'.format(io.get_path(outfile))
            run = True
        else:
            msg = 'Skipping calculation, found "{0}"\n'.format(io.get_path(outfile))
            run = False
    else:
        run = True
    if run:
        if not io.check_file(inpfile, timeout=1) or overwrite:
            io.write_file(inptext, inpfile)
        if io.check_file(inpfile, timeout=1):
            msg = io.execute(command)
            if io.check_file(outfile, timeout=1):
                msg += ' Output file: "{0}"\n'.format(io.get_path(outfile))
        else:
            msg = 'Failed, cannot find input file "{0}"\n'.format(io.get_path(inpfile))
    return msg
示例#5
0
def run_mopac(s, exe='mopac', template='mopac_template.txt', mult=None, overwrite=False):
    """
    Runs mopac, returns a string specifying the status of the calculation.
    mopac inp inp.out
    Mopac always writes the log file into a file with .out extension
    """
    mol = ob.get_mol(s, make3D=True)
    if mult is None:
        mult = ob.get_multiplicity(mol)
    tmp = io.read_file(template)
    inptext = get_input(mol, tmp, mult)
    prefix = ob.get_smiles_filename(s)
    inpfile = prefix + '.mop'
    outfile = prefix + '.out'
    command = [exe, inpfile]
    if io.check_file(outfile, timeout=1):
        if overwrite:
            msg = 'Overwriting previous calculation "{0}"\n'.format(io.get_path(outfile))
            run = True
        else:
            msg = 'Skipping calculation, found "{0}"\n'.format(io.get_path(outfile))
            run = False
    else:
        run = True
    if run:
        if not io.check_file(inpfile, timeout=1) or overwrite:
            io.write_file(inptext, inpfile)
        if io.check_file(inpfile, timeout=1):
            msg = io.execute(command)
            if io.check_file(outfile, timeout=1):
                msg += 'Output file: "{0}"\n'.format(io.get_path(outfile))
        else:
            msg = 'Failed, cannot find input file "{0}"\n'.format(io.get_path(inpfile))
    return msg
示例#6
0
def check_geoms(qtc, name, nsamps):
    """
    Checks MC geoms to make sure they are the same inchii as the starting species
    """
    import sys
    sys.path.insert(0, qtc)
    import iotools as io
    import obtools as ob

    msg = 'Checking level0 geometries'
    log.debug(msg)
    n = 2
    filename = 'geoms/' + name + '_' + '1'.zfill(n) + '.xyz'
    lowfilename = filename
    coords = io.read_file(filename)
    lowcoords = coords
    mol = ob.get_mol(coords)
    inchi = ob.get_inchi_key(mol)
    energy = float(coords.split('\n')[1])
    for i in range(2, int(nsamps) + 1):
        filename = 'geoms/' + name + '_' + '{}'.format(i).zfill(n) + '.xyz'
        log.info(filename)
        if io.check_file(filename):
            coords = io.read_file(filename)
            mol = ob.get_mol(coords)
            if inchi == ob.get_inchi_key(mol):
                if float(coords.split('\n')[1]) < energy:
                    energy = float(coords.split('\n')[1])
                    log.info('Lower energy of {:.2f} found in {}'.format(
                        energy, filename))
                    lowcoords = coords
                    lowfilename = filename
            else:
                log.info(
                    'Connectivity change after torsional optimization. (InChI mismatch) in {}.'
                    .format(filename))
    io.cp(lowfilename, 'torsopt.xyz')
    #io.write_file("\n".join(lowcoords.split("\n")),'geom.xyz')
    io.write_file("\n".join(lowcoords.split("\n")[2:]), 'geom.xyz')
    msg = '\nMonte Carlo sampling successfully found geom.xyz!\n'
    log.info(msg)
    return lowfilename
示例#7
0
def db_smiles_path(smiles, db_location=None):
    """
    Returns the path for a smiles molecule in a database
    """
    import obtools as ob
    mol = ob.get_mol(smiles)
    directory = ob.get_smiles_path(mol)
    if db_location == None:
        db_location = db_head_path()

    return join_path(db_location, directory)
示例#8
0
def run(s):
    """
    A driver function to run quantum chemistry and thermochemistry calculations based
    on command line options:
    --qcmethod
    --qccode
    """
    import qctools as qc
    import obtools as ob
    import tctools as tc
    import iotools as io
    mol = ob.get_mol(s)
    mult = ob.get_multiplicity(mol)
    dirpath = ob.get_unique_path(mol, method=_qcmethod, mult=mult)
    groupsfile = 'new.groups'
    io.mkdir(dirpath)
    cwd = io.pwd()
    if _runthermo:
        if io.check_file(groupsfile):
            io.cp(groupsfile, dirpath)
            if not io.check_file(groupsfile, 1):
                print 'Could not copy new.groups file to target directory {0}'.format(
                    dirpath)
                return -1
        else:
            print 'new.groups file required in working directory'
            return -1
    if io.check_dir(dirpath, 1):
        io.cd(dirpath)
    else:
        print 'I/O error, {0} directory not found'.format(dirpath)
        return -1
    if _runqc:
        if _qccode == 'mopac':
            outstr = qc.run_mopac(s,
                                  mopacexe=_mopacexe,
                                  method=_qcmethod,
                                  mult=mult)
            outfile = outstr.split(' : ')[0]
            if _runthermo:
                lines = io.read_file(outfile, aslines=True)
                xyz = qc.get_mopac_xyz(lines)
                freqs = qc.get_mopac_freq(lines)
                zpe = qc.get_mopac_zpe(lines)
                deltaH = qc.get_mopac_deltaH(lines)
                get_chemkin_polynomial(mol, _qcmethod, zpe, xyz, freqs, deltaH)
    io.cd(cwd)
    return outstr
示例#9
0
def run(s, template, parameters, mult=None):
    """
    Runs nwchem, returns a string specifying the status of the calculation.
    nwchem inp.nw > nw.log
    NWChem writes output and error to stdout.
    Generates .db (a binary file to restart a job) and .movecs (scf wavefunction) files in the run directory.
    Generates many junk files in a scratch directory.
    If scratch is not specified, these junk files are placed in the run directory.
    """
    package = parameters['qcpackage']
    overwrite = parameters['overwrite']
    mol = ob.get_mol(s, make3D=True)
    msg = ''
    if mult is None:
        mult = ob.get_multiplicity(mol)
    else:
        ob.set_mult(mol, mult)
    tmp = io.read_file(template)
    inptext = get_input(mol, tmp)
    prefix = ob.get_smiles_filename(s) + '_' + package
    inpfile = prefix + '.inp'
    outfile = prefix + '.out'
    if io.check_file(outfile, timeout=1):
        if overwrite:
            msg = 'Overwriting previous calculation "{0}"\n'.format(io.get_path(outfile))
            run = True
        else:
            msg = 'Skipping calculation, found "{0}"\n'.format(io.get_path(outfile))
            run = False
    else:
        run = True
    if run:
        if not io.check_file(inpfile, timeout=1) or overwrite:
            io.write_file(inptext, inpfile)
        if io.check_file(inpfile, timeout=1):
            if package == 'extrapolation':
                run_extrapolation(s, parameters)
            elif package == 'nwchem':
                command = [parameters['qcexe'], inpfile]
                msg += io.execute(command,stdoutfile=outfile,merge=True)
            else:
                command = [parameters['qcexe'], inpfile, outfile] 
                msg = io.execute(command)
            if io.check_file(outfile, timeout=1):
                msg += ' Output file: "{0}"\n'.format(io.get_path(outfile))
        else:
            msg += 'Failed, cannot find input file "{0}"\n'.format(io.get_path(inpfile))
    return msg
示例#10
0
文件: heatform.py 项目: snelliott/QTC
def build_gauss(dic, theory, basisset):
    """
    Builds a Guassian optimization inputfile for a molecule
    INPUT:
    dic     - dictionary for the molecule
    theory  - theory we want to optimize with
    basisset- basis set we want to optimize with
    OUPUT:
    None (but an inputfile now exists with name <stoich>.inp)
    """
    gauss = '%Mem=25GB\n%nproc=8\n'
    gauss += '#P ' + theory.lstrip('R').lstrip(
        'U'
    ) + '/' + basisset + ' opt=internal int=ultrafine scf=verytight nosym\n'

    gauss += '\nEnergy for HeatForm\n\n'

    meths = ['ccsdt', 'ccsd(t)', 'ccsd', 'm062x', 'b3lyp']
    bases = ['cc-pvqz', 'cc-pvtz', 'cc-pvdz', '6-311+g(d,p)', '6-31+g(d,p)']
    zmat = 'none'

    if theory.lower().lstrip('r') in dic['g09']:
        for j in range(len(bases)):
            if bases[j] in dic['g09'][theory.lower().lstrip('r')]:
                if zmat in dic['g09'][theory.lower().lstrip('r')][bases[j]]:
                    zmat = dic['g09'][theory.lower().lstrip('r')][
                        bases[j]]['zmat']
    if zmat == 'none':
        for i in range(len(meths)):
            if meths[i] in dic['g09']:
                for j in range(len(bases)):
                    if bases[j] in dic['g09'][meths[i]]:
                        if 'zmat' in dic['g09'][meths[i]][bases[j]]:
                            zmat = dic['g09'][meths[i]][bases[j]]['zmat']
    if zmat == 'none':
        import obtools as ob
        mol = ob.get_mol(dic['_id'])
        zmat = ob.get_zmat(mol)
        gauss += str(dic['charge']) + ' ' + str(dic['mult']) + '\n'
    gauss += zmat.lstrip('\n')

    io.write_file(gauss, dic['stoich'] + '.inp')

    return
示例#11
0
def get_mopac_input(x, method='pm3', keys='precise nosym threads=1 opt', mult=1, dothermo=False):
    """
    Returns mopac input as a string.
    Note: For doctest I had to escape newline characters \n as \\n
    Since it gives EOL error.
    Note2: Doctest is also sensitive to whitespace at the end of lines.
    Hence, I used .strip() to awoid unnecessary whitespace.
    >>> xyz = "2\\n \\n H 0. 0. 0.\\n H 0. 0. 0.9\\n  \\n"
    >>> print get_mopac_input(xyz,method='pm7',dothermo=True)
    pm7 precise nosym threads=1 opt
    <BLANKLINE>
    <BLANKLINE>
    H   0.00000 1  0.00000 1  0.00000 1
    H   0.00000 1  0.00000 1  0.90000 1
    <BLANKLINE>
    pm7 precise nosym threads=1 oldgeo thermo
    """
    if type(x) is str:
        mol = ob.get_mol(x)
    else:
        mol = x
    multDictionary = {
                        1: '',
                        2: 'uhf doublet',
                        3: 'uhf triplet',
                        4: 'uhf quartet',
                        5: 'uhf quintet',
                        6: 'uhf sextet',
                        7: 'uhf septet',
                        8: 'uhf octet',
                        9: 'uhf nonet',
                    }
    keys = method + ' ' + keys + ' ' + multDictionary[mult]
    inp = ob.get_mop(mol, keys=keys.strip())
    if dothermo:
        inp += '\n' + keys.replace('opt', 'oldgeo thermo').strip()
    return inp
示例#12
0
def run_nwchem(s, exe='nwchem', template='nwchem_template.txt', mult=None, overwrite=False):
    """
    Runs nwchem, returns a string specifying the status of the calculation.
    nwchem inp.nw > nw.log
    NWChem writes output and error to stdout.
    Generates .db (a binary file to restart a job) and .movecs (scf wavefunction) files in the run directory.
    Generates many junk files in a scratch directory.
    If scratch is not specified, these junk files are placed in the run directory.
    """
    mol = ob.get_mol(s, make3D=True)
    if mult is None:
        mult = ob.get_multiplicity(mol)
    tmp = io.read_file(template)
    inptext = get_input(mol, tmp)
    prefix = ob.get_smiles_filename(s)
    inpfile = prefix + '.nw'
    outfile = prefix + '_nwchem.log'
    command = [exe, inpfile]
    if io.check_file(outfile, timeout=1):
        if overwrite:
            msg = 'Overwriting previous calculation "{0}"\n'.format(io.get_path(outfile))
            run = True
        else:
            msg = 'Skipping calculation, found "{0}"\n'.format(io.get_path(outfile))
            run = False
    else:
        run = True
    if run:
        if not io.check_file(inpfile, timeout=1) or overwrite:
            io.write_file(inptext, inpfile)
        if io.check_file(inpfile, timeout=1):
            msg = io.execute(command,stdoutfile=outfile,merge=True)
            if io.check_file(outfile, timeout=1):
                msg += ' Output file: "{0}"\n'.format(io.get_path(outfile))
        else:
            msg = 'Failed, cannot find input file "{0}"\n'.format(io.get_path(inpfile))
    return msg
示例#13
0
def run(s):
    """
    A driver function to run quantum chemistry and thermochemistry calculations based
    on command line options:
    --qcmethod
    --qcpackage
    """
    global parameters
    runqc = parameters['runqc']
    parseqc = parameters['parseqc']
    runthermo = parameters['runthermo']
    runanharmonic = parameters['anharmonic']
    msg = "***************************************\n"
    msg += "{0}\n".format(s)
    mult = ob.get_mult(s)
    mol = ob.get_mol(s)
    smilesname = ob.get_smiles_filename(s)
    smilesdir = ob.get_smiles_path(mol, mult, method='', basis='', geopath='')
    qcdirectory = io.join_path(*[smilesdir, parameters['qcdirectory']])
    qctemplate = io.get_path(parameters['qctemplate'])
    qcpackage = parameters['qcpackage']
    qcscript = io.get_path(parameters['qcscript'])
    qclog = smilesname + '_' + qcpackage + '.out'
    xyzpath = parameters['xyzpath']
    xyzfile = None
    if xyzpath:
        if io.check_file(xyzpath):
            xyzfile = xyzpath
        elif io.check_file(io.join_path(*(smilesdir, xyzpath))):
            xyzfile = io.join_path(*(smilesdir, xyzpath))
        elif io.check_dir(xyzpath):
            try:
                xyzfile = next(io.find_files(xyzpath, '*.xyz'))
            except StopIteration:
                msg += "xyz file not found in {0}".format(xyzpath)
        elif io.check_dir(io.join_path(*(smilesdir, xyzpath))):
            xyzpath = io.join_path(*(smilesdir, xyzpath))
            try:
                xyzfile = next(io.find_files(xyzpath, '*.xyz'))
            except StopIteration:
                msg += "xyz file not found in {0}".format(xyzpath)
        else:
            msg += "xyz path not found {0}".format(xyzpath)
            return msg
    if xyzfile:
        msg += "Using xyz file in '{0}'\n".format(xyzfile)
        xyz = io.read_file(xyzfile)
        coords = ob.get_coordinates_array(xyz)
        mol = ob.set_xyz(mol, coords)
    print(msg)
    msg = ''
    io.mkdir(qcdirectory)
    cwd = io.pwd()
    if io.check_dir(qcdirectory, 1):
        io.cd(qcdirectory)
        msg += "cd '{0}'\n".format(qcdirectory)
    else:
        msg += ('I/O error, {0} directory not found.\n'.format(qcdirectory))
        return -1
    print(msg)
    msg = ''
    available_packages = [
        'nwchem', 'molpro', 'mopac', 'gaussian', 'extrapolation'
    ]
    if runqc:
        if qcpackage in available_packages:
            print('Running {0}'.format(qcpackage))
            msg += qc.run(s, qctemplate, parameters, mult)
        elif qcpackage == 'qcscript':
            msg += "Running qcscript...\n"
            geofile = smilesname + '.geo'
            geo = ob.get_geo(mol)
            io.write_file(geo, geofile)
            if io.check_file(geofile, 1):
                msg += qc.run_qcscript(qcscript, qctemplate, geofile, mult)
        else:
            msg = '{0} package not implemented\n'.format(qcpackage)
            msg += 'Available packages are {0}'.format(available_packages)
            exit(msg)
        print(msg)
        msg = ''
    if parseqc:
        if io.check_file(qclog, timeout=1, verbose=False):
            out = io.read_file(qclog, aslines=False)
            d = qc.parse_output(out, smilesname, parameters['writefiles'])
            pprint(d)

    if runthermo:
        groupstext = tc.get_new_groups()
        io.write_file(groupstext, 'new.groups')
        msg += "Parsing qc logfile '{0}'\n".format(io.get_path(qclog))
        newmsg, xyz, freqs, zpe, deltaH, afreqs, xmat = qc.parse_qclog(
            qclog, qcpackage, anharmonic=runanharmonic)
        msg += newmsg
        if xyz is not None:
            msg += "Optimized xyz in Angstroms:\n{0} \n".format(xyz)
        else:
            runthermo = False
        if freqs is not None:
            msg += "Harmonic frequencies in cm-1:\n {0} \n".format(freqs)
        else:
            runthermo = False
        if afreqs:
            msg += "Anharmonic frequencies in cm-1:\n {0}\n".format(afreqs)
        else:
            runanharmonic = False
        if zpe:
            msg += 'ZPE = {0} kcal/mol\n'.format(zpe)
        else:
            runthermo = False
        if deltaH is not None:
            msg += 'deltaH = {0} kcal/mol\n'.format(deltaH)
        else:
            runthermo = False
        if xmat is not None:
            msg += 'Xmat = {0} kcal/mol\n'.format(xmat)
        else:
            runanharmonic = False
        if runthermo:
            msg += tc.write_chemkin_polynomial(mol, zpe, xyz, freqs, deltaH,
                                               parameters)
    io.cd(cwd)
    print(msg)
    return
示例#14
0
def run(args, paths, d={}):
    """
    Runs heatform, partition_function, thermp, pac99, and write chemkin file
    """
    import sys
    sys.path.insert(0, paths['qtc'])
    global pa, io, ob, tc
    import patools as pa
    import iotools as io
    import tctools as tc
    import obtools as ob
    import heatform as hf
    import shutil
    import re

    reacs = args.reacs
    prods = args.prods
    anharm = args.anharm
    anovrwrt = args.anovrwrt
    node = args.nodes[0]
    meths = args.meths
    hfbasis = args.hfbasis
    qtchf = args.qtchf
    enlevel = args.enlevel
    hlen = args.hlen
    hfbases = []
    speciess, speclist, anfreqs, anxmat = build_pfinput(args, d)
    dH0 = []
    dH298 = []
    anharmbool = False
    deltaH = 0
    if anharm.lower() != 'false':
        anharmbool = True
    for i, species in enumerate(speciess):
        if len(species.split('_m')) > 1:
            species, mult = species.split('_m')[0], species.split('_m')[1]
        if qtchf[0].lower() not in ['false', 'auto']:
            if len(qtchf) >= i:
                deltaH = float(qtchf[i])
                hfbasis = ['N/A']
                hfbases.append(hfbasis)
        else:
            logfile = 'geoms/' + speclist[i] + '_l1.log'
            if speclist[i] == 'ts':
                logfile = 'geoms/' + speclist[i] + 'gta_l1.log'
            if io.check_file(logfile):
                lines = io.read_file(logfile)
                energy = pa.energy(lines)[1]
                zpve = pa.zpve(lines)
                printE = '{}-    E: {:5g} pulled from: {}'.format(
                    species, energy, logfile)
                printzpve = '{}- zpve: {:5g} pulled from: {}'.format(
                    species, zpve, logfile)
                if enlevel != 'optlevel':
                    energy = hlen[i]
                    printE = '{}-    E: {:5g} pulled from: {}'.format(
                        species, energy, 'me_files/' + speclist[i] + '_en.me')
                if io.check_file('me_files/' + speclist[i] + '_zpe.me'):
                    zpve = float(
                        io.read_file('me_files/' + speclist[i] + '_zpe.me'))
                    printzpve = '{}- ZPVE: {:5g} pulled from: {}'.format(
                        species, zpve, 'me_files/' + speclist[i] + '_zpe.me')
                if zpve:
                    energy = energy + zpve
                log.info(printE + '\n' + printzpve)
                deltaH, hfbasis = hf.main(species,
                                          logfile,
                                          E=energy,
                                          basis=hfbasis,
                                          anharm=anharmbool,
                                          enlevel=enlevel)
                hfbases.append(hfbasis)
            else:
                deltaH = 0.00
        dH0.append(deltaH)
        if not speclist[i] == 'ts':
            log.debug('Running mess')
            tc.run_pf('/home/ygeorgi/build/crossrate/partition_function',
                      species + '.pf')
            log.info('Completed')
            log.debug('Generating thermp input.\n')
            log.info('Completed')

            stoich = ob.get_formula(ob.get_mol(species))
            inp = tc.get_thermp_input(stoich, deltaH)
            log.debug('Running thermp.\n')
            if io.check_file(species + '.pf.dat'):
                os.rename(species + '.pf.dat', 'pf.dat')
            else:
                log.error(
                    'No pf.dat produced, try soft adding gcc-5.3 and intel-16.0.0 and use Restart at: 5!'
                )
                return [], [], [], [], []
            tc.run_thermp(inp, 'thermp.dat', 'pf.dat',
                          '/home/elliott/Packages/therm/thermp.exe')
            lines = io.read_file('thermp.out')
            log.info('Completed')
            deltaH298 = ' h298 final\s*([\d,\-,\.]*)'
            deltaH298 = re.findall(deltaH298, lines)[-1]
            dH298.append(deltaH298)
            log.debug('Running pac99.\n')
            shutil.copyfile('/home/elliott/Packages/therm/new.groups',
                            './new.groups')
            shutil.copyfile(stoich + '.i97', species + '.i97')
            tc.run_pac99(species, '/home/elliott/Packages/therm/pac99.x')
            c97file = species + '.c97'
            if io.check_file(c97file):
                c97text = io.read_file(c97file)
                las, has, msg = tc.get_coefficients(c97text)
                log.info('Completed')
            else:
                log.error('No {} produced'.format(c97file))
            chemkinfile = stoich + '.ckin'
            log.debug('Writing chemkin file {0}.\n'.format(chemkinfile))
            method = meths[-1][2]
            chemininput = tc.write_chemkin_file(species, method, deltaH,
                                                float(deltaH298), stoich, 0,
                                                las, has, chemkinfile)

        log.info('Completed')
    return dH0, dH298, hfbases, anfreqs, anxmat
示例#15
0
def main(inputfile, outputfile, configfile=''):
    torspath = os.path.dirname(os.path.realpath(sys.argv[0]))
    if configfile == '':
        configfile = torspath + os.path.sep + 'configfile.txt'
    args = config.ARGS(inputfile)
    Config = config.CONFIG(configfile, outputfile)
    paths = Config.path_dic()
    paths['torsscan'] = torspath
    sys.path.insert(0, es.get_paths(paths, 'bin'))
    sys.path.insert(0, es.get_paths(paths, 'qtc'))
    sys.path.insert(0, es.get_paths(paths, 'torsscan'))

    log.info(random_cute_animal())
    #####  Build and Run EStokTP  ######
    ####################################
    global io, ob
    import obtools as ob
    import iotools as io
    import tctools as tc
    import shutil

    symnums = []
    samps = None
    if args.restart < 8:
        index = 0
        if "Opt" in args.jobs and args.restart < 1:
            alljobs = args.jobs
            args.jobs = ["Opt"]
            es.run_level0(args, paths)
            args.restart = 1
            args.jobs = alljobs
        if "1dTau" in args.jobs and args.restart < 4:
            logging.info("========\nBEGIN LEVEL 1 and 1DHR\n========\n")
            alljobs = args.jobs
            negvals = True
            attempt = 0
            while (negvals and attempt < 3):
                attempt += 1
                args.jobs = ["Opt_1", "1dTau"]
                negvals = False
                if attempt == 1 and args.restart == 3:
                    pass
                else:
                    stoichs, symnums = es.build_files(args, paths)
                    es.execute(paths, args.nodes[0])
                if io.check_file('output/estoktp.out'):
                    shutil.copy('output/estoktp.out', 'output/estoktp_l1.out')
                args.restart = 3
                for i in range(len(args.reacs)):
                    lowene = 0.0
                    lowenefile = None
                    if io.check_file('me_files/reac' + str(i + 1) + '_hr.me'):
                        hr = io.read_file('me_files/reac' + str(i + 1) +
                                          '_hr.me')
                        hr = hr.split('Rotor')
                        startkey = 'Potential'
                        for j, rotor in enumerate(hr[1:]):
                            pot = rotor.split(startkey)[1]
                            pot = pot.splitlines()[1]
                            for k, ene in enumerate(pot.split()):
                                if float(ene) - lowene < -0.1:
                                    lowene = float(ene)
                                    lowenefile = 'hr_geoms/geom_isp' + str(
                                        i + 1).zfill(2) + '_hr' + str(
                                            j + 1).zfill(2) + '_hpt' + str(
                                                k + 1).zfill(2) + '.xyz'
                    if lowenefile:
                        xyz = io.read_file(lowenefile)
                        logging.info(xyz)
                        slabel = ob.get_slabel(ob.get_mol(xyz))
                        if slabel.split('_m')[0] == ob.get_slabel(
                                args.reacs[i]).split('_m')[0]:
                            negvals = True
                            if io.check_file('data/ts.dat') and i == 0:
                                if 'isomerization' in args.reactype.lower():
                                    tsfile = io.read_file('data/ts.dat')
                                    ijk = tsfile.split('ji ki')[1].split()[:3]
                                    ijk.append(
                                        tsfile.split('ireact2')[1].split('\n')
                                        [1].split()[-1])
                                    xyz = xyz.splitlines()
                                    xyz[int(ijk[0]) +
                                        1] = '2 ' + xyz[int(ijk[0]) + 1]
                                    xyz[int(ijk[1]) +
                                        1] = '3 ' + xyz[int(ijk[1]) + 1]
                                    xyz[int(ijk[2]) +
                                        1] = '4 ' + xyz[int(ijk[2]) + 1]
                                    xyz[int(ijk[3]) +
                                        1] = '1 ' + xyz[int(ijk[3]) + 1]
                                    xyz = '\n'.join(xyz)
                                else:
                                    ijk = io.read_file('data/ts.dat').split(
                                        'ksite')[1].split()[:3]
                                    xyz = xyz.splitlines()
                                    xyz[int(ijk[0]) +
                                        1] = '2 ' + xyz[int(ijk[0]) + 1]
                                    xyz[int(ijk[1]) +
                                        1] = '1 ' + xyz[int(ijk[1]) + 1]
                                    xyz[int(ijk[2]) +
                                        1] = '3 ' + xyz[int(ijk[2]) + 1]
                                    xyz = '\n'.join(xyz)
                            slabel = ob.get_smiles_filename(
                                ob.get_slabel(args.reacs[i]))
                            io.mkdir('geomdir')
                            io.write_file(xyz, 'geomdir/' + slabel + '.xyz')
                            args.restart = 1
                            args.XYZ = 'geomdir'
                            args.xyzstart = '0'
                            log.warning(
                                'Lower configuration found in 1dTau. Restarting at Level1. Saved geometry to {}'
                                .format(slabel + '.xyz'))
                        else:
                            log.warning(
                                'Lower configuration found in 1dTau. But has different smiles: {} vs. {}'
                                .format(slabel, ob.get_slabel(args.reacs[i])))
                for l in range(len(args.prods)):
                    lowene = 0.
                    lowenefile = None
                    if io.check_file('me_files/prod' + str(l + 1) + '_hr.me'):
                        hr = io.read_file('me_files/prod' + str(l + 1) +
                                          '_hr.me')
                        hr = hr.split('Rotor')
                        startkey = 'Potential'
                        for j, rotor in enumerate(hr[1:]):
                            pot = rotor.split(startkey)[1]
                            pot = pot.splitlines()[1]
                            for k, ene in enumerate(pot.split()):
                                if float(ene) - lowene < -0.1:
                                    lowene = float(ene)
                                    lowenefile = 'hr_geoms/geom_isp' + str(
                                        i + l + 2).zfill(2) + '_hr' + str(
                                            j + 1).zfill(2) + '_hpt' + str(
                                                k + 1).zfill(2) + '.xyz'
                    if lowenefile:
                        xyz = io.read_file(lowenefile)
                        slabel = ob.get_slabel(ob.get_mol(xyz))
                        if slabel.split('_m')[0] == ob.get_slabel(
                                args.prods[l]).split('_m')[0]:
                            negvals = True
                            slabel = ob.get_smiles_filename(
                                ob.get_slabel(args.prods[l]))
                            io.mkdir('geomdir')
                            io.write_file(xyz, 'geomdir/' + slabel + '.xyz')
                            args.restart = 1
                            args.XYZ = 'geomdir'
                            args.xyzstart = '0'
                            log.warning(
                                'Lower configuration found in 1dTau. Restarting at Level1. Saved geometry to {}'
                                .format(slabel + '.xyz'))
                        else:
                            log.warning(
                                'Lower configuration found in 1dTau. But has different smiles: {} vs. {}'
                                .format(slabel, ob.get_slabel(args.prods[l])))
                if args.reactype.lower() in [
                        'addition', 'abstraction', 'isomerization',
                        'addition_well', 'isomerization_well'
                ]:
                    lowene = 0.
                    lowenefile = None
                    if io.check_file('me_files/ts_hr.me'):
                        hr = io.read_file('me_files/ts_hr.me')
                        hr = hr.split('Rotor')
                        startkey = 'Potential'
                        for j, rotor in enumerate(hr[1:]):
                            pot = rotor.split(startkey)[1]
                            pot = pot.splitlines()[1]
                            for k, ene in enumerate(pot.split()):
                                if float(ene) - lowene < -0.1:
                                    lowene = float(ene)
                                    lowenefile = 'hr_geoms/geom_isp00_hr' + str(
                                        j + 1).zfill(2) + '_hpt' + str(
                                            k + 1).zfill(2) + '.xyz'
                    if lowenefile:
                        xyz = io.read_file(lowenefile)
                        negvals = True
                        io.mkdir('geomdir')
                        io.write_file(xyz, 'geomdir/ts.xyz')
                        args.restart = 1
                        args.XYZ = 'geomdir'
                        args.xyzstart = '0'
                        log.warning(
                            'Lower configuration found in 1dTau. Restarting at Level1. Saved geometry to ts.xyz'
                        )

                    if args.wellp and args.wellp.lower() != 'false':
                        lowene = 0.
                        lowenefile = None
                        if io.check_file('me_files/wellp_hr.me'):
                            hr = io.read_file('me_files/wellp_hr.me')
                            hr = hr.split('Rotor')
                            startkey = 'Potential'
                            for j, rotor in enumerate(hr[1:]):
                                pot = rotor.split(startkey)[1]
                                pot = pot.splitlines()[1]
                                for k, ene in enumerate(pot.split()):
                                    if float(ene) - lowene < -0.1:
                                        lowene = float(ene)
                                        lowenefile = 'hr_geoms/geom_isp06_hr' + str(
                                            j + 1).zfill(2) + '_hpt' + str(
                                                k + 1).zfill(2) + '.xyz'
                        if lowenefile:
                            xyz = io.read_file(lowenefile)
                            negvals = True
                            io.mkdir('geomdir')
                            io.write_file(xyz, 'geomdir/wellp.xyz')
                            args.restart = 1
                            args.XYZ = 'geomdir'
                            args.xyzstart = '0'
                            log.warning(
                                'Lower configuration found in 1dTau. Restarting at Level1. Saved geometry to wellp.xyz'
                            )
                    if args.wellr and args.wellr.lower() != 'false':
                        lowene = 0.
                        lowenefile = None
                        if io.check_file('me_files/wellr_hr.me'):
                            hr = io.read_file('me_files/wellr_hr.me')
                            hr = hr.split('Rotor')
                            startkey = 'Potential'
                            for j, rotor in enumerate(hr[1:]):
                                pot = rotor.split(startkey)[1]
                                pot = pot.splitlines()[1]
                                for k, ene in enumerate(pot.split()):
                                    if float(ene) - lowene < -0.1:
                                        lowene = float(ene)
                                        lowenefile = 'hr_geoms/geom_isp05_hr' + str(
                                            j + 1).zfill(2) + '_hpt' + str(
                                                k + 1).zfill(2) + '.xyz'
                        if lowenefile:
                            xyz = io.read_file(lowenefile)
                            negvals = True
                            io.mkdir('geomdir')
                            io.write_file(xyz, 'geomdir/wellr.xyz')
                            args.restart = 1
                            args.XYZ = 'geomdir'
                            args.xyzstart = '0'
                            log.warning(
                                'Lower configuration found in 1dTau. Restarting at Level1. Saved geometry to wellr.xyz'
                            )
            args.jobs = alljobs
        elif "Opt_1" in args.jobs and args.restart < 2:
            log.info("========\nBEGIN LEVEL 1\n========\n")
            alljobs = args.jobs
            args.jobs = ["Opt_1"]
            stoichs, symnums = es.build_files(args, paths)
            es.execute(paths, args.nodes[0])
            if io.check_file('output/estoktp.out'):
                shutil.copy('output/estoktp.out', 'output/estoktp_l1.out')
            args.jobs = alljobs
            args.restart = 2
        if args.anharm.lower() != 'false' and 'd' not in args.nodes[0]:
            import thermo
            log.info("========\nBEGIN VPT2\n========\n")
            optlevel, anlevel = thermo.get_anlevel(args.anharm, args.meths)
            for n, reac in enumerate(args.reacs):
                typ = 'reac'
                natom = ob.get_natom(reac)
                if natom > 2:
                    mult = ob.get_mult(reac)
                    if io.check_file('me_files/' + typ + str(n + 1) +
                                     '_fr.me'):
                        if not 'Anh' in io.read_file('me_files/' + typ +
                                                     str(n + 1) + '_fr.me'):
                            anfr, fr1, anx, fr2, fr3, _ = thermo.get_anharm(
                                typ, str(n + 1), natom, args.nodes[0],
                                anlevel, args.anovrwrt, reac,
                                optlevel.split('/'), paths)
                            lines = io.read_file('me_files/' + typ +
                                                 str(n + 1) + '_fr.me')
                            io.write_file(
                                lines,
                                'me_files/' + typ + str(n + 1) + '_harm.me')
                            lines = fr1 + fr2.split(
                                'End'
                            )[0] + fr3 + '\n !************************************\n'
                            io.write_file(
                                lines,
                                'me_files/' + typ + str(n + 1) + '_fr.me')
            for n, prod in enumerate(args.prods):
                typ = 'prod'
                natom = ob.get_natom(prod)
                if natom > 2:
                    mult = ob.get_mult(prod)
                    if io.check_file('me_files/' + typ + str(n + 1) +
                                     '_fr.me'):
                        if not 'Anh' in io.read_file('me_files/' + typ +
                                                     str(n + 1) + '_fr.me'):
                            anfr, fr1, anx, fr2, fr3, _ = thermo.get_anharm(
                                typ, str(n + 1), natom, args.nodes[0],
                                anlevel, args.anovrwrt, prod,
                                optlevel.split('/'), paths)
                            lines = io.read_file('me_files/' + typ +
                                                 str(n + 1) + '_fr.me')
                            io.write_file(
                                lines,
                                'me_files/' + typ + str(n + 1) + '_harm.me')
                            lines = fr1 + fr2.split(
                                'End'
                            )[0] + fr3 + '\n !************************************\n'
                            io.write_file(
                                lines,
                                'me_files/' + typ + str(n + 1) + '_fr.me')
            if args.reactype and io.check_file('geoms/tsgta_l1.xyz'):
                typ = 'ts'
                mol = io.read_file('geoms/tsgta_l1.xyz')
                ts = ob.get_mol(mol)
                natom = ob.get_natom(ts)
                mult = ob.get_mult(ts)
                if io.check_file('me_files/ts_fr.me'):
                    if not 'Anh' in io.read_file('me_files/ts_fr.me'):
                        anfr, fr1, anx, fr2, fr3, _ = thermo.get_anharm(
                            typ, str(n + 1), natom, args.nodes[0], anlevel,
                            args.anovrwrt, 'ts', optlevel.split('/'), paths)
                        lines = io.read_file('me_files/' + typ + '_fr.me')
                        io.write_file(lines, 'me_files/' + typ + '_harm.me')
                        lines = fr1 + fr2.split(
                            'End'
                        )[0] + fr3 + '\n End\n !************************************\n'
                        io.write_file(lines, 'me_files/' + typ + '_fr.me')
        log.info("========\nBEGIN MDHR, HL\n========\n")
        if 'kTP' in args.jobs:
            alljobs = args.jobs
            args.jobs = []
            for job in alljobs:
                if job != 'kTP':
                    args.jobs.append(job)
            stoichs, symnums = es.build_files(args, paths)
            es.execute(paths, args.nodes[0])
            if io.check_file('me_files/ts_en.me'):
                tsen = float(io.read_file('me_files/ts_en.me'))
                tsen += float(io.read_file('me_files/ts_zpe.me'))
                reacen = 0
                proden = 0
                for i, reac in enumerate(args.reacs):
                    if io.check_file('me_files/reac{}_en.me'.format(i + 1)):
                        reacen += float(
                            io.read_file('me_files/reac{}_en.me'.format(i +
                                                                        1)))
                        reacen += float(
                            io.read_file('me_files/reac{}_zpe.me'.format(i +
                                                                         1)))
                if args.reactype.lower(
                ) == 'addition_well' or args.reactype.lower(
                ) == 'isomerization_well':
                    if io.check_file('me_files/wellp_en.me'):
                        proden += float(io.read_file('me_files/wellp_en.me'))
                        proden += float(io.read_file('me_files/wellp_zpe.me'))
                else:
                    for i, prod in enumerate(args.prods):
                        if io.check_file('me_files/prod{}_en.me'.format(i +
                                                                        1)):
                            proden += float(
                                io.read_file(
                                    'me_files/prod{}_en.me'.format(i + 1)))
                            proden += float(
                                io.read_file(
                                    'me_files/prod{}_zpe.me'.format(i + 1)))
                if tsen <= reacen or tsen <= proden:
                    log.info('Well Depth is negative. NoTunnel is turned on')
                    if args.esoptions:
                        args.esoptions += ',NoTunnel'
                    else:
                        args.esoptions = 'NoTunnel'
            log.info("========\nBEGIN kTP\n========\n")
            args.jobs = alljobs
            restart = 7
            stoichs, symnums = es.build_files(args, paths)
            es.execute(paths, args.nodes[0])
        else:
            stoichs, symnums = es.build_files(args, paths)
            es.execute(paths, args.nodes[0])
    if ("1dTau" in args.jobs or 'MdTau' in args.jobs):
        for i in range(len(args.reacs)):
            es.check_hrs(i + 1, 'reac')
        for i in range(len(args.prods)):
            es.check_hrs(i + 1, 'prod')
        es.me_file_abs_path()

    if args.restart == 10:
        io.execute([paths['bin'] + os.path.sep + 'mess', 'me_ktp.inp'])

    if args.reactype and io.check_file('rate.out'):
        import me_parser
        #initialize the class in which to store the results
        data = me_parser.paper()
        data.reactions = []
        # set some constants, depending upon whether the rate coefficients are to be used for CHEMKIN or something else.
        data.T0 = 1.0
        data.R = 1.987  # cal/mol-K.  Note that PLOG formalism requires Ea in cal/mol-K!
        data.N_avo = 6.0221415E23  #convert bimolecular rate coefficients from cm^3/sec to cm^3/mol/s

        # set the minimum and maximum temperature
        #data.Tmin = 600.0
        #data.Tmax = 1200.0

        # read me.out file from the command line
        me_dot_out = 'rate.out'
        if io.check_file(me_dot_out):
            lines = io.read_file(me_dot_out, True)
            if len(lines) < 2:
                log.info('rate.out is empty')
            ## copy new plog executable to the path of the source file
            #path = os.path.abspath(os.path.dirname(me_dot_out))
            #
            #command = 'cp /home/elliott/bin/dsarrfit.x_cfg ' + path
            #log.info( command)
            #os.system(command)
            # parse results for the temperature, pressure, and names of channels
            me_parser.get_temp_pres(data, lines)
            # parse results for the pdep rate constants
            me_parser.get_pdep_k(data, lines)
            # fit the results to PLOG expressions
            me_parser.fit_pdep(
                data, nonlin_fit=False
            )  #replace <True> with <False> if you don't want to use the nonlinear solver (not recommended)
            # print the resulting PLOG expressions to file
            me_parser.print_plog(data, me_dot_out)
            # plot the results: dashed line = single PLOG, solid line = double PLOG
            #me_parser.plot_reactant(data, me_dot_out, show_plot=False, save_plot=True)

    #######  Parse results  #########
    ########################################
    import results
    rs = results.RESULTS(args, paths)
    args.hlen = rs.get_hlen()
    args.optlevel = rs.optlevel
    args.enlevel = rs.enlevel
    args.taulevel = rs.taulevel

    if args.parseall.lower() == 'true' or args.alltherm.lower() == 'true':
        rs.get_results()
    #######  Build and run thermo  #########
    ########################################
    import thermo
    rs.thermo = False
    if args.alltherm.lower() == 'true':
        rs.thermo = True
        args.symnums = symnums
        rs.dH0, rs.dH298, rs.hfbases, rs.anfreqs, rs.anxmat = thermo.run(
            args, paths, rs.d)
        if args.parseall.lower() == 'true':
            rs.get_thermo_results()
    return