Exemplo n.º 1
0
def getsimilar(smi, nmols, dbselect, finger, squery, args):
    # get database files
    [dbsdf, dbfs] = setupdb(dbselect)
    print(('database set up :' + str(dbsdf) + ' || ' + str(dbfs)))
    globs = globalvars()
    print(('Finding results similar, comparing to ' + smi))

    obab = 'babel'
    if dbfs and args.dbfs:
        com = obab + ' ' + dbfs + ' ' + 'simres.smi -d -xf' + \
            finger + ' -s"' + smi + '" -al' + nmols
    else:
        mybash(obab + ' -isdf ' + dbsdf + ' -osdf -O tmp.sdf -d')
        com = obab + ' tmp.sdf simres.smi -xf' + finger + ' -s"' + smi + '"'
    # perform search using bash commandline
    print('Performing substructure search:')
    print(('running:  ' + str(com)))
    res = mybash(com)
    print(('res = ' + str(res)))
    print(('number of SMILES returned : ' +
           str(mybash('cat simres.smi | wc -l'))))

    if os.path.isfile('tmp.sdf'):
        os.remove('tmp.sdf')
    shutil.copy('simres.smi', 'initial.smi')
    if args.dbmaxsmartsmatches:
        print('Applying filters: inside get similar')
        com = obab + " -ismi simres.smi -osmi -O simres.smi -h --filter " + squery
        print(('running:  ' + str(com)))
        mybash(com)
        print(('number of lines in simres.smi: ' +
               str(mybash('cat simres.smi | wc -l'))))

    #		com = obab+" -ismi simres.smi -osmi -O simres.smi -d --filter 'nsmartsmatches<="+args.dbmaxsmartsmatches+"'"
    #		rint('running:  '+ str(com))

    #		res = mybash(com)
    #		print('number of lines in simres.smi after dxbsmartmatches: '+str(mybash('cat simres.smi | wc -l')))

    #		print res
    shutil.copy('simres.smi', 'afterfilteringsmarts.smi')
    # check output and print error if nothing was found
    if ('errors' in res):
        ss = 'No matches were found in DB. Log info:\n' + res
        print(ss)
        return ss, True
    else:
        return 'simres.smi', False
Exemplo n.º 2
0
def getresd(dirf):
    # get results files
    resfiles = mybash("find '"+dirf+"' -name *_orbs.txt")
    resfiles = [_f for _f in re.split('\n', resfiles) if _f]
    txt = 'Filename                                                              e0(base)   d-band      e-h**o      e-lumo      e-fermi     e-gap     [Hartree]  Av-Occup\n'
    txt += '--------------------------------------------------------------------------------------------------------------------------------------------------------------\n'
    text = []
    for resf in resfiles:
        rrfs = resf.split('_orbs')[0]
        rrfs = rrfs.replace('/MO_files', '')
        rrfs = rrfs.rsplit('/', 1)[-1]
        rrfs = rrfs.replace('_', '/')
        rr = parsed(resf)
        text.append(rrfs.ljust(70)+"{0:.3f}".format(rr[0]).ljust(10)+"{0:.3f}".format(rr[1]).ljust(13) +
                    "{0:.3f}".format(rr[2]).ljust(12)+"{0:.3f}".format(rr[3]).ljust(13)+"{0:.3f}".format(rr[4]).ljust(10) +
                    "{0:.3f}".format(rr[5]).ljust(23)+"{0:.3f}".format(rr[6]).ljust(10)+'\n')
    text = sorted(text)
    f = open(dirf+'/avorbs.txt', 'w')
    f.write(txt+''.join(text))
    f.close()
Exemplo n.º 3
0
def dbsearch(rundir, args, globs):
    cwd = os.getcwd()
    flag = False

    obab = 'obabel'
    if args.gui:
        from molSimplify.Classes.mWidgets import mQDialogWarn
        from molSimplify.Classes.mWidgets import mQDialogInf
    ### in any case do similarity search over indexed db ###
    outf = args.dbfname if args.dbfname else 'simres.smi'  # output file
    # convert to SMILES/SMARTS if file
    if not args.dbbase:
        if args.gui:
            qqb = mQDialogWarn(
                'Warning', "No database file found within " + globs.chemdbdir +
                '. Search not possible.')
            qqb.setParent(args.gui.DBWindow)
        print(("No database file found within " + globs.chemdbdir +
               '. Search not possible.'))
        return True
    # if args.dbsim:
    # print('similarity searching')
    # if '.smi' in args.dbsim:
    # if glob.glob(args.dbsim):
    # f = open(args.dbsim,'r')
    # smistr = f.read()
    # f.close()
    # else:
    # print 'File '+args.dbsim+' not existing. Check your input.'
    # print 'Similarity search terminating..'
    # return True
    # elif ('.mol' in args.dbsim or '.xyz' in args.dbsim):
    # if glob.glob(args.dbsim):
    # ftype = args.dbsim.split('.')[-1]
    # obConversion = openbabel.OBConversion()
    # obConversion.SetInFormat(ftype)
    # OBMol = openbabel.OBMol()
    # obConversion.ReadFile(OBMol,args.dbsim)
    # smistr = pybel.write("smi")
    # else:
    # print 'File '+args.dbsim+' not existing. Check your input.'
    # print 'Similarity search terminating..'
    # return True
    # else:
    # smistr = args.dbsim
    # print smistr
    if args.dbsmarts:
        if '.smi' in args.dbsmarts:
            if glob.glob(args.dbsmarts):
                f = open(args.dbsmarts, 'r')
                smistr = f.read()
                f.close()
            else:
                print(('File ' + args.dbsmarts +
                       ' does not exist. Check your input.'))
                print('Substructure search terminating..')
                return 1
        elif ('.mol' in args.dbsmarts or '.xyz' in args.dbsmarts):
            if glob.glob(args.dbsmarts):
                ftype = args.dbsmarts.split('.')[-1]

                smistr = pymol.write("smi")
            else:
                print(('File ' + args.dbsmarts +
                       ' does not exist. Check your input.'))
                print('Substructure search terminating..')
                return True
        else:
            smistr = args.dbsmarts
    elif args.dbhuman:
        smistr = []
        denticity = args.dbvdent if args.dbvdent else '1'
        coordatoms = args.dbvconns if args.dbvconns else 'N'
        hyb = args.dbvhyb if args.dbvhyb else '3'
        nlinks = args.dbvlinks if args.dbvlinks else '2'
        monod = ['1', 'mono', 'Mono', 'monodentate', 'Monodentate']
        bid = ['2', 'bi', 'Bi', 'bidentate', 'Bidentate']
        if args.debug:
            print('dbhuman conversion')
            print(('dbhuman coordatoms ' + str(coordatoms)))
            print(('dbhuman nlinks ' + str(nlinks)))
            print(('dbhuman hyb ' + str(hyb)))
        if denticity in monod:
            smistr = '[#' + str(
                amassdict[coordatoms[0]][1]) + '^' + hyb[0] + ';!+]'
        elif denticity in bid:
            smistr = '[#' + str(
                amassdict[coordatoms[0]][1]) + '^' + hyb[0] + ';!+]'
            for i in range(int(nlinks)):
                smistr = smistr + '[#6;R0]'
            print((coordatoms, hyb))
            smistr = smistr + \
                '[#' + str(amassdict[coordatoms[1]][1]) + '^' + hyb[1] + ';!+]'
        print(('setting smistr from dbhuman ' + smistr))

    # else:
    # get database
    # [dbsdf,dbfs] = setupdb(args.dbbase)
    # convert to smiles and print to output
    # if globs.osx:
    # cmd = "/usr/local/bin/obabel "+dbsdf+" -f0 -l100 -o"+outf[-3:]+" -O "+outf
    # else:
    # cmd = obab+" "+dbsdf+" -f0 -l100 -o"+outf[-3:]+" -O "+outf
    # t = mybash(cmd)
    # os.rename(outf,args.rundir+'/'+outf)
    # print t
    # return False
    # parse filters
    squery = checkscr(args)
    if args.debug:
        print(("squery is " + str(squery)))

    if args.dbmaxsmartsmatches:
        plugin_path = plugin_defs()
        shutil.copy(plugin_path, 'plugindefines.txt')
        cmd = "sed -i '/nsmartsmatches/!b;n;c" + smistr + "' " + 'plugindefines.txt'
        mybash(cmd)
    ### run substructure search ###
    nmols = '10000' if not args.dbnsearch else args.dbnsearch
    finger = 'FP2' if not args.dbfinger else args.dbfinger
    if int(nmols) > 3000 and args.gui:
        qqb = mQDialogInf(
            'Warning',
            "Database search is going to take a few minutes. Please wait..OK?")
        qqb.setParent(args.gui.DBWindow)
    if args.dbsmarts or args.dbhuman or args.dbsim:
        outputf, flag = getsimilar(smistr, nmols, args.dbbase, finger, squery,
                                   args)
        try:
            shutil.copy('simres.smi', outf)
        except:
            pass

    if args.debug:
        print(('after similarity search, outf is ' + str(outputf)))
    if flag:
        if args.gui:
            qqb = mQDialogWarn('Warning', "No matches found in search..")
            qqb.setParent(args.gui.DBWindow)
        print("No matches found in search..")
        return True
    # strip metals and clean-up, remove duplicates etc
    # print('mb ' +  str(mybash('cat '+outf)))
    if args.dbsmarts or args.dbhuman:
        print('Stripping salts and removing duplicates')

        print(('number of smiles strings BEFORE salt stripping: ' +
               mybash("cat " + outf + '| wc -l')))
        flag = stripsalts(outf)
        print(('number of smiles strings AFTER salt stripping: ' +
               mybash("cat " + outf + '| wc -l')))
        # print('flag from salt stripping: ' + str(flag))
        print(('number of smiles strings BEFORE unique: ' +
               mybash("cat " + outf + '| wc -l')))
        cmd = obab + " -ismi " + outf + " -osmi -O " + outf + " --unique"
        # print('running:' + str(cmd))
        shutil.copy(outf, 'afterstrippingsalts.smi')
        t = mybash(cmd)
        print(('number of smiles strings AFTER unique: ' +
               mybash("cat " + outf + '| wc -l')))

    # print 't (ret from bash) is  '+ str(t)
    # filter results containing elements that aren't allowed
    if args.dballowedels:
        if args.dballowedels == 'organic':  # HCNO only
            allowedels = ['H', 'C', 'N', 'O']
        elif args.dballowedels == 'organohalides':
            allowedels = ['H', 'C', 'N', 'O', 'F', 'Cl', 'Br', 'I']
        elif args.dballowedels == 'common':
            allowedels = ['H', 'C', 'N', 'O', 'F', 'Cl', 'Br', 'I', 'P', 'S']
        else:
            allowedels = args.dballowedels
        print(('number of smiles strings BEFORE element filter: ' +
               mybash("cat " + outf + '| wc -l')))
        checkels(outf, allowedels)
        print(('number of smiles strings AFTER element filter unique: ' +
               mybash("cat " + outf + '| wc -l')))

        shutil.copy(outf, 'afterfilteringels.smi')
    # check if defined connection atoms
    if args.dbcatoms:
        catoms = [int(a) for a in args.dbcatoms]
    else:
        catoms = [1]
    # do pattern matching
    nres = 50 if not args.dbresults else int(args.dbresults)
    if args.dbsmarts or args.dbhuman:
        print(('number of smiles strings BEFORE SMARTS filter: ' +
               mybash("cat " + outf + '| wc -l')))
        flag = matchsmarts(smistr, outf, catoms, args)
        print(('number of smiles strings AFTER SMARTS filter: ' +
               mybash("cat " + outf + '| wc -l')))
    if args.debug:
        print(('outf is ' + str(outf)))
    # maximal dissimilarity search
    if args.dbdissim:
        dissim(outf, int(args.dbdissim))
    if args.rundir:
        print(
            ('writing output to ' + str(args.rundir) + '/' + str(outf) + '\n'))
        os.rename(outf, args.rundir + '/' + outf)
    else:
        print(('writing output to ' + str(cwd) + '/' + str(outf) + '\n'))
    # os.chdir(cwd)
    return False
Exemplo n.º 4
0
def dissim(outf, n):
    globs = globalvars()

    obab = 'babel'

    # clone hitlist file
    hit_list_path = "hitlist.smi"

    with open(outf) as f:
        smiles_list = f.readlines()
    with open(hit_list_path, 'w') as f:
        f.writelines(smiles_list)

    # generate fs of original hit list
    mybash(obab + ' -ismi ' + hit_list_path + ' -osdf tmp.sdf')
    mybash(obab + ' tmp.sdf -ofs')
    # number of hits
    numcpds = mybash('obabel tmp.sdf -onul')
    numcpds = int(numcpds.split(None)[0])
    # pick first element of list
    mybash('obabel tmp.sdf -O 1.smi -f 1  -l 1')
    del smiles_list[0]
    with open(hit_list_path, 'w') as f:
        f.writelines(smiles_list)
    # recompute the fs and number of hits parameters
    numcpds += -1  # decrease number of hits
    mybash(obab + ' -ismi ' + hit_list_path + ' -osdf tmp.sdf')
    mybash(obab + ' tmp.sdf -ofs')

    print('Performing dissimilarity search:')
    mostdissim = []
    if n > 1:
        # find most dissimilar structure
        for i in range(n - 1):

            # initialize list of total similarities
            simsum = [0] * numcpds
            # compute total similarity of each dissimilar structure with hit list
            for j in range(i + 1):
                a = mybash('obabel ' + str(j + 1) + '.smi tmp.sdf -ofpt')
                a = a.splitlines()
                a = [s.split('= ') for s in a]
                a = [item for sublist in a for item in sublist]
                aa = []
                for k in a:
                    try:
                        aa.append(float(k))
                    except:
                        pass
                a = aa
                simsum = [x + y for x, y in zip(simsum, a)]
            # pick most dissimilar structure by greedily minimizing total similarity
            mostdissim = simsum.index(min(simsum))
            mybash('obabel tmp.sdf -O ' + str(i + 2) + '.smi -f ' +
                   str(mostdissim + 1) + ' -l' + str(mostdissim + 1))

            # remove most dissimilar from the list and re-write the smi file
            del smiles_list[mostdissim]
            with open(hit_list_path, 'w') as f:
                f.writelines(smiles_list)

            # recompute the fs and number of hits parameters
            numcpds += -1  # decrease number of hits
            mybash(obab + ' -ismi ' + hit_list_path + ' -osdf tmp.sdf')
            mybash(obab + ' tmp.sdf -ofs')

    # combine results into one file
    f = open('dissimres.smi', 'w')
    for i in range(n):
        ff = open(str(i + 1) + '.smi', 'r')
        s = ff.read().splitlines()
        ff.close()
        f.write(s[0] + '\n')
        os.remove(str(i + 1) + '.smi')
    f.close()
    return 0
Exemplo n.º 5
0
def deloc(molf, folder, gui, flog):
    # get multiwfn exec
    globs = globalvars()
    Multiwfn = globs.multiwfn
    # get results files
    header = "\nFile                                                                No Attr     Loc-indx     Tot-Deloc\n"
    header += "-------------------------------------------------------------------------------------------------------\n"
    text = []
    indexin = []
    mindices = []
    skipm = False
    # loop over molden files
    for numi, resf in enumerate(molf):
        indxst = ''
        resd = resf.rsplit('/', 1)[0]
        moln = resf.rsplit('/', 1)[-1]
        moln = moln.split('.molden')[0]
        resd = os.path.relpath(resd, folder)
        resd = resd.replace('/', '_') + '_' + moln
        print(resd)
        outfile = folder + '/Deloc_files/' + resd + '-deloc.txt'
        print(('Processing  ' + resd + ' and writing output to ' + outfile))
        flog.write('Processing  ' + resd + '\n')
        if gui:
            gui.iWtxt.setText('Processing ' + resd + '\n' +
                              gui.iWtxt.toPlainText())
            gui.app.processEvents()
        # get coordinates of metal
        f = open(resf, 'r')
        sm = f.read().splitlines()
        f.close()
        # get indices of heavy elements
        found = False
        for met in metals:
            if (found == False):
                ml = [line for line in sm if met in line]
            if len(ml) > 0 and found == False:
                if 'Title' in ml[0] and len(ml) > 1:
                    mlll = ml[1].split(None)
                else:
                    mlll = ml[0].split(None)
                if len(mlll) > 2:
                    found = True
                    fmet = met
        if len(ml) == 0:
            print(
                'WARNING:No metal found, defaulting to 1st atom for relative properties..'
            )
            skipm = True
            ml = [sm[4]]
            mlll = [_f for _f in ml[0].split(None) if _f]
        mindex = mlll[1]
        mindices.append(mindex)
        mcoords = [float(mlll[3]), float(mlll[4]), float(mlll[5])]
        parse, skipc = False, False
        # Run multiwfn
        if not glob.glob(outfile):
            inputtxt = '17\n1\n1\n2\n4\n'
            f = open('input0', 'w')
            f.write(inputtxt)
            f.close()
            com = Multiwfn + ' ' + "'" + resf + "'" + " < input0 > '" + outfile + "'"
            tt = mybash(com)
            print(tt)
            # check if seg fault
            skipc = False
            if 'Segmentation' in tt or 'core dumped' in tt:
                skipc = True
            # read outputfile and check
            f = open(outfile, 'r')
            ssf = f.read()
            f.close()
            # if error redo
            if ('Note: There are attractors having very low ' in ssf
                    or 'Hint' in ssf):
                inputtxt = '17\n1\n1\n2\n3\n4\n'
                f = open('input0', 'w')
                f.write(inputtxt)
                f.close()
                tt = mybash(com)
            os.remove('input0')
        # check if good
        f = open(outfile, 'r')
        ssf = f.read()
        f.close()
        parse = False
        if 'Total localization' in ssf:
            parse = True
        ################
        # parse output #
        ################
        if not skipc and parse:
            f = open(outfile, 'r')
            s = f.read()
            f.close()
            # get basins
            if ('The attractors after clustering' in s):
                st = find_between(s, 'Index      Average', 'The number')
                sst = [_f for _f in st.splitlines()[1:] if _f]
            else:
                st = find_between(s, 'Attractor', 'Detecting')
                sst = [_f for _f in st.splitlines()[1:] if _f]
            basidx = []  # list with metal attractors
            attlist = []  # List with neighboring attractors
            att_thrsd = 2.4  # Angstrom
            att_range = 1.0  # Angstrom
            for line in sst:
                xyzcoords = line.split(None)
                if (len(xyzcoords) > 3):
                    xyzc = [
                        float(xyzcoords[1]),
                        float(xyzcoords[2]),
                        float(xyzcoords[3])
                    ]
                    if distance(mcoords, xyzc) < att_range:
                        basidx.append(xyzcoords[0])
                        indxst += mindex + '\n'
                    elif (distance(mcoords, xyzc) > att_range
                          and distance(mcoords, xyzc) < att_thrsd):
                        attlist.append(int(xyzcoords[0]))
            # get total number of basins
            if not skipm:
                dd = int(
                    find_between(s, 'matrix for basin', '...').split(None)[-1])
                # get delocalization matrix
                sdel = find_between(s, 'Total delocalization index matrix',
                                    'Total localization')
                sdeloc = sdel.splitlines()[1:]
                deloc = []
                for bidx in basidx:
                    [a, b] = divmod(int(bidx) - 1, 5)
                    ll = sdeloc[a * (dd + 1) + 1:(a + 1) * (dd + 1)]
                    for ii, l in enumerate(ll):
                        if (ii + 1 in attlist):
                            lf = [_f for _f in l.split(None) if _f]
                            deloc.append(float(lf[b + 1]))
                    # get localization index
                s = find_between(s, 'Total localization index:', '==')
                loc = []
                for bidx in basidx:
                    ss = s.split(bidx + ':')[-1]
                    ss = ss.split(None)
                    loc.append(float(ss[0]))
                if (len(attlist) == 0):
                    tdeloc = 0.0
                else:
                    tdeloc = sum(deloc) / len(attlist)
                tloc = sum(loc)
                tt = resd.ljust(70) + str(
                    len(basidx)).ljust(6) + "{:10.3f}".format(tloc).ljust(
                        14) + "{:10.3f}".format(tdeloc).ljust(10) + '\n'
                text.append(tt)
            indexin.append(indxst)
    # sort alphabetically and print
    text = sorted(text)
    f = open(folder + '/deloc_res.txt', 'w')
    f.write(header + ''.join(text))
    print(
        "\n##################### Deloc indices are ready ######################\n"
    )
Exemplo n.º 6
0
def getcharges(molf, folder, gui, flog):
    # get Multiwfn
    globs = globalvars()
    Multiwfn = globs.multiwfn
    # analyze results
    header = "\nFolder                                                    Hirshfeld    VDD     Mulliken\n"
    header += "-----------------------------------------------------------------------------------------\n"
    txt = []
    for numi, resf in enumerate(molf):
        resd = os.path.relpath(resf, folder)
        resd = resd.split('.molden')[0]
        resdp = resd
        resd = resd.replace('/', '_')
        # get metal index in molden file
        f = open(resf, 'r')
        ss = f.read()
        f.close()
        ss = find_between(ss, 'Atoms', 'GTO')
        ss = ss.splitlines()
        midx = 0  # default
        for sl in ss:
            sll = sl.split(None)
            for met in metals:
                if len(sll) > 1 and met in sll[0]:
                    midx = int(sll[1]) - 1
                    fmet = sll[0]
                    break
        #################################################
        outfile1 = folder + '/Charge_files/' + resd + '-chH.txt'
        print(('Processing ', resdp))
        flog.write('Processing ' + resdp + '\n')
        if gui:
            gui.iWtxt.setText('Processing ' + resf + '\n' +
                              gui.iWtxt.toPlainText())
            gui.app.processEvents()
        # Run multiwfn
        if not glob.glob(outfile1):
            inputtxt = '7\n1\n1\n'  # Hirschfeld
            f = open('input1', 'w')
            f.write(inputtxt)
            f.close()
            com = Multiwfn + ' ' + "'" + resf + "'" + " < input1 > '" + outfile1 + "'"
            tt = mybash(com)
            os.remove('input1')
        f = open(outfile1, 'r')
        ss = f.read()
        f.close()
        # get total charge
        schl = [line for line in ss.splitlines() if 'Net charge:' in line]
        tcharge = [_f for _f in schl[0] if _f].split(None)[2]
        s = find_between(ss, ' of atom     1', 'Atomic dipole')
        hirsch = 'NA'
        if len(s.splitlines()) > midx + 1:
            hirscht = s.splitlines()[midx]
            hirschll = hirscht.split(None)
            if len(hirschll) > 2:
                hirsch = "{:5.3f}".format(float(hirschll[-1]))
        #################################################
        outfile2 = folder + '/Charge_files/' + resd + '-chV.txt'
        if not glob.glob(outfile2):
            inputtxt = '7\n2\n1\n'  # VDD
            f = open('input1', 'w')
            f.write(inputtxt)
            f.close()
            com = Multiwfn + ' ' + "'" + resf + "'" + " < input1 > '" + outfile2 + "'"
            tt = mybash(com)
            os.remove('input1')
        f = open(outfile2, 'r')
        ss = f.read()
        f.close()
        s = find_between(ss, 'VDD charge', 'dipole')
        vdd = 'NA'
        if len(s.splitlines()) > midx + 1:
            vddt = s.splitlines()[midx]
            vddll = vddt.split(None)
            if len(vddll) > 2:
                vdd = "{:5.3f}".format(float(vddll[-1]))
        #################################################
        outfile3 = folder + '/Charge_files/' + resd + '-chM.txt'
        if not glob.glob(outfile3):
            inputtxt = '7\n5\n1\n'  # Mulliken
            f = open('input1', 'w')
            f.write(inputtxt)
            f.close()
            com = Multiwfn + ' ' + "'" + resf + "'" + " < input1 > '" + outfile3 + "'"
            tt = mybash(com)
            os.remove('input1')
        f = open(outfile3, 'r')
        ss = f.read()
        f.close()
        s = find_between(ss, 'Population of atoms', 'Total net')
        mull = 'NA'
        if len(s.splitlines()) > midx + 2:
            mullt = s.splitlines()[midx + 2]
            mulll = mullt.split(None)
            if len(mulll) > 2:
                mull = "{:5.3f}".format(float(mulll[-1]))
        txt.append(
            resdp.ljust(60) + hirsch.ljust(10) + vdd.ljust(10) +
            mull.ljust(10) + '\n')
    text = sorted(txt)
    f = open(folder + '/charges.txt', 'w')
    f.write(header + ''.join(text))
    f.close()
    f.close()
Exemplo n.º 7
0
def getcubes(molf, folder, gui, flog):
    # get Multiwfn
    globs = globalvars()
    Multiwfn = globs.multiwfn
    # analyze results
    flog.write(
        "##################### Generating cube files ######################\n")
    print(
        "##################### Generating cube files ######################\n")
    # loop over folders
    resf = []
    txt = []
    for numi, resf in enumerate(molf):
        resd = os.path.relpath(resf, folder)
        resd = resd.split('.molden')[0]
        resd = resd.replace('/', '_')
        cubedir = folder + '/Cube_files/'
        flog.write('Processing ' + resf + '\n')
        print(('Processing ', resf))
        if gui:
            gui.iWtxt.setText('Processing ' + resf + '\n' +
                              gui.iWtxt.toPlainText())
            gui.app.processEvents()
        #################################################
        ### generate density cube ###
        inputtxt = '5\n1\n3\n2\n'
        f = open('input1', 'w')
        f.write(inputtxt)
        f.close()
        com = Multiwfn + ' ' + "'" + resf + "'" + ' < input1'
        if not glob.glob(cubedir + resd + '-density.cub'):
            tt = mybash(com)
            os.remove('input1')
            if glob.glob('density.cub'):
                os.rename('density.cub', cubedir + resd + '-density.cub')
        #################################################
        inputtxt = '5\n9\n3\n2\n'  # generate ELF
        f = open('input1', 'w')
        f.write(inputtxt)
        f.close()
        com = Multiwfn + ' ' + "'" + resf + "'" + ' < input1'
        if not glob.glob(cubedir + resd + '-ELF.cub'):
            tt = mybash(com)
            os.remove('input1')
            if glob.glob('ELF.cub'):
                os.rename('ELF.cub', cubedir + resd + '-ELF.cub')
        #################################################
        inputtxt = '5\n5\n3\n2\n'  # generate spin density
        f = open('input1', 'w')
        f.write(inputtxt)
        f.close()
        com = Multiwfn + ' ' + "'" + resf + "'" + ' < input1'
        if not glob.glob(cubedir + resd + '-spindensity.cub'):
            tt = mybash(com)
            os.remove('input1')
            if glob.glob('spindensity.cub'):
                os.rename('spindensity.cub',
                          cubedir + resd + '-spindensity.cub')
        #################################################
        if not glob.glob(cubedir + resd + '-denalpha.cub'):
            cubespin(cubedir + resd + '-density.cub', cubedir + resd +
                     '-spindensity.cub')  # generate spin densities
            if glob.glob('denalpha.cub'):
                os.rename('denalpha.cub', cubedir + resd + '-denalpha.cub')
                os.rename('denbeta.cub', cubedir + resd + '-denbeta.cub')