Exemplo n.º 1
0
def dirll_conformers(dirll,ts):
    # initialize domains
    ddomains = {domain:set([]) for domain in DOMAINS}

    # check folder
    if os.path.exists(dirll):
       for fpoint in tfh.folder_points(dirll):
           if ts: statusFRQ = 1
           else : statusFRQ = 0
           ddomains["conf"].add( (None,fpoint,statusFRQ) )
    else: tfh.create_dir(dirll)

    # print conformers
    confs = [fpoint for ipoint,fpoint,statusFRQ in ddomains["conf"]]
    if len(confs) != 0:
       sprint("Num conformers found in '%s': %i"%(dirll,len(confs)),NIBS2)
       sprint()

    # return data
    return ddomains, confs
Exemplo n.º 2
0
def regen_from_tmp(inpvars):
    # assert file does not exist
    if os.path.exists(FDOMAINS):
       sprint("File '%s' already exists!"%FDOMAINS,NIBS2)
       sprint()
       return

    #-------------------------------------#
    # Already located conformers in dirll #
    #-------------------------------------#
    ddomains, confs = dirll_conformers(inpvars._dirll,inpvars._ts)

        
    #---------------#
    # Data in tmpll #
    #---------------#
    if os.path.exists(inpvars._tmpll):
       # list of log files 
       opts = [log for log in os.listdir(inpvars._tmpll) \
               if log.startswith("opt") and log.endswith(".log")]
       opts.sort()
       sprint("Num opt log files in '%s': %i"%(inpvars._tmpll,len(opts)),NIBS2)
       repe_or_excl = []
       for log in opts:
           vec1     = TorPESpoint(log.split(".")[1])
           if log.startswith("optprec."):
              case = "prec"
              log_frq  = log.replace("optprec.","frqprec.")
           elif log.startswith("optstoc."):
              case = "stoc"
              log_frq  = log.replace("optstoc.","frqstoc.")
Exemplo n.º 3
0
def calculate_mj(inpvars, strconfs, weights, allconfs, denantio):
    ttorsions = list(inpvars._ttorsions)
    ntor = len(ttorsions)
    nconfs = len(strconfs)
    # convert each point in points to string
    # initialize number of points at each point
    lNj = np.array([0 for conf in strconfs])
    lwj = np.array([weights[conf] for conf in strconfs])

    # update frequency for (Mj,sigma_j) & max number of iterations
    #UPDATEFREQ, MAXITER = ntor  *10**3, ntor  *(2*10**5)
    UPDATEFREQ, MAXITER = nconfs * 10**2, nconfs * 10**5
    # Calculate Mj's
    Ntot = 0
    while True:
        Ntot += 1
        # generate random point
        rvec = tfh.random_point(inpvars._tdomain, inpvars._tlimit)
        # check which is closest structure
        closest = str(rvec.closest(allconfs))
        # enantiomer??
        closest = denantio.get(closest, closest)
        # locate point
        idx = strconfs.index(closest)
        # update frequency of the structure
        lNj[idx] += 1
        # Calculate Mj and sigma_j
        if Ntot % UPDATEFREQ == 0:
            # correct Nj with weight
            llNj = [1.0 * Nj / wj for Nj, wj in zip(lNj, lwj)]
            # calculate Mj and sigma(Mj)
            llMj = [(1.0 * Ntot / Nj)**(1.0 / ntor) if Nj != 0 else np.inf
                    for Nj in llNj]
            llsj = [
                Mj / ntor / np.sqrt(Nj) if Nj != 0 else 0
                for Nj, Mj in zip(llNj, llMj)
            ]
            # ignore infinity for max(sigma)
            max_sigma = max(llsj)
            sprint("iteration %6i --> max(sigma_j)= %5.3f" % (Ntot, max_sigma),
                   NIBS2 + 4)
            if max_sigma <= inpvars._sigmamj: break

        # if too many, break anyway
        if Ntot == MAXITER:
            sprint("too many iterations...", NIBS2 + 4)
            break
    # print values
    sprint()
    pp.print_mjtable(llMj, llsj, strconfs, Ntot)
    # Any conformer not visited?
    notvisited = [strconfs[idx] for idx, Nj in enumerate(lNj) if Nj == 0]
    if len(notvisited) != 0: pp.print_notvisited(notvisited)
    # return data
    return {strconf: Mj for strconf, Mj in zip(strconfs, llMj)}, notvisited
Exemplo n.º 4
0
def gen_guess_zmatrix(vec, i_zmatvals, inpvars, log, distance):
    # read z-matrix from closest domain
    use_default = True
    try:
        logdata = gau.read_gaussian_log(inpvars._dirll + log)
        zmatlines = logdata[10]
        (lzmat, zmatvals, zmatatoms), symbols = gau.convert_zmat(zmatlines)
        sprint("using Z-matrix from stored file (%s)" % log, tvars.NIBS2 + 4)
        sprint("distance to stored Z-matrix: %.0f degrees" % distance,
               tvars.NIBS2 + 4)
        use_default = False
    except:
        use_default = True
    # get closest z-matrix
    if use_default:
        sprint("using default Z-matrix (%s)" % inpvars._zmatfile,
               tvars.NIBS2 + 4)
        zmatvals = {k: v for (k, v) in i_zmatvals.items()}
    # Apply vector to current z-matrix
    for angle, ic in zip(vec._fvec, inpvars._tic):
        zmatvals[ic] = angle
    # return zmatvals
    return zmatvals
Exemplo n.º 5
0
        freqscal = inpvars._freqscalHL

    # Folder with data does not exist
    if not os.path.exists(folder):
        pp.print_dirnotfound(folder, NIBS2, 1)
        return
    # Create folder for mstor files
    tfh.create_dir(folder + DIRMSTOR)

    # list of points
    logs = [log for log in os.listdir(folder) if log.endswith(".log")]
    points = [TorPESpoint(log.split(".")[1]) for log in logs]

    # no files?
    if len(logs) == 0:
        sprint("There are no log files inside folder '%s'" % folder, NIBS2, 1)
        return

    #----------------#
    # Read log files #
    #----------------#
    sprint("Reading log files...", NIBS2, 1)
    geoms = []
    weights = {}
    strconfs = []
    allconfs = []
    denantio = {}
    for log, point in zip(logs, points):
        logdata = gau.read_gaussian_log(folder + log, target_level=None)

        ch = logdata[2]
Exemplo n.º 6
0
def highlevel_reopt(inpvars,cmatrix,\
                    lowerconformer=0,\
                    upperconformer=float("inf"),\
                    calculate=False,\
                    lNH2=[]):

    dirll, dirhl = inpvars._dirll , inpvars._dirhl
    if not os.path.exists(dirll):
       print("       Folder NOT FOUND: %s\n"%dirll)
       return
    # Create folders
    if not os.path.exists(dirhl):
       try   : mkdir_recursive(dirhl)
       except: pp.print_createdir(dirhl,tvars.NIBS2); exit()
    # Check Gaussian software
    if calculate:
       end_program = itf.check_executable()
       if end_program: return

    # print status of tests
    pp.print_tests(inpvars._tests,1)
    pp.print_ifreqconstr(inpvars._ifqrangeHL)

    #------------------------#
    # Templates for Gaussian #
    #------------------------#
    # HL opt & HL freq templates for MIN
    if not inpvars._ts: file1,file2 = tvars.TEMPLMINOPTHL,tvars.TEMPLMINFRQHL
    # HL opt & HL freq templates for TS
    else              : file1,file2 = tvars.TEMPLTSOPTHL,tvars.TEMPLTSFRQHL
    # (a) do templates exist??
    if not os.path.exists(file1): pp.print_filenotfound(file1,tvars.NIBS2,1); raise exc.END
    if not os.path.exists(file2): pp.print_filenotfound(file2,tvars.NIBS2,1); raise exc.END
    # (b) read templates
    with open(file1,'r') as asdf: loptHL = asdf.readlines()
    pp.print_template(loptHL,file1,"HL optimization",tvars.NIBS2)
    with open(file2,'r') as asdf: lfrqHL = asdf.readlines()
    pp.print_template(lfrqHL,file2,"HL frequency calculation",tvars.NIBS2)
    # (c) temporal folder
    if not os.path.exists(inpvars._tmphl):
        try   : mkdir_recursive(inpvars._tmphl)
        except: pp.print_createdir(inpvars._tmphl,tvars.NIBS2); exit()


    # read LL energies
    if not os.path.exists(tvars.ENERGYSUMLL):
        sprint("- file NOT found: %s"%tvars.ENERGYSUMLL,tvars.NIBS2)
        sprint("  execute %s using --msho ll"%tvars.PROGNAMEnopy,tvars.NIBS2)
        sprint("")
        return
    sprint("- reading file: %s"%tvars.ENERGYSUMLL,tvars.NIBS2)
    sprint("")
    llenergies,  lltemp = rw.read_llenergies()
    # check temperature
    if abs(lltemp-inpvars._temp) > 1e-3:
        sprint("  something went wrong!",tvars.NIBS2)
        sprint("")
        sprint("  temperature in file         : %.3f K"%(lltemp),tvars.NIBS2)
        sprint("  temperature in %s: %.3f K"%(tvars.IFILE,inpvars._temp),tvars.NIBS2)
        sprint("")
        return
    sprint("  temperature for Gibbs free energy: %.3f K"%lltemp,tvars.NIBS2)
    # check number of conformers
    logs = [fname for fname in os.listdir(inpvars._dirll) if fname.endswith(".log")]
    if len(logs) != len(llenergies):
        sprint("  something went wrong!",tvars.NIBS2)
        sprint("  number of conformer differs!",tvars.NIBS2)
        sprint("")
        sprint("  # of conformers in file     : %i"%len(llenergies),tvars.NIBS2)
        sprint("  # of conformers in LL folder: %i"%len(logs),tvars.NIBS2)
        sprint("")
        return
    sprint("  number of low-level conformers   : %i"%len(llenergies),tvars.NIBS2)
    sprint("")
    # check conformers
    svecs_llenergies = [svec for count,V0,G,svec in llenergies]
    for log in logs:
        svec_i = log.split(".")[1]
        if svec_i not in svecs_llenergies:
           sprint("  something went wrong!",tvars.NIBS2)
           sprint("")
           sprint("  conformer NOT included: %s"%log,tvars.NIBS2)
           sprint("")
           return

    #---------------------#
    # Create HL gjf files #
    #---------------------#
    nopt  = 0
    nfrq  = 0
    nsp   = 0
    minV0 = llenergies[0][0]
    for count,relV0_kcalmol,relG_kcalmol,svec in llenergies:
        if not (lowerconformer <= count <= upperconformer): continue
        # read LL/HL-correlation file
        correlations = rw.read_llhlcorr()
        # LL log file
        log_prec = "prec.%s.log"%svec
        log_stoc = "stoc.%s.log"%svec
        if   os.path.exists(inpvars._dirll+log_prec):
             log     = log_prec
             prefix1 = "optprec."
             prefix2 = "frqprec."
             prefix3 = "prec."
        elif os.path.exists(inpvars._dirll+log_stoc):
             log     = log_stoc
             prefix1 = "optstoc."
             prefix2 = "frqstoc."
             prefix3 = "stoc."
        else: raise Exception
        # read log file
        conftuple,symbols,string_fccards = itf.log_data(log,inpvars,inpvars._freqscalLL,dirll)
        # unpack conftuple
        vecA,V0,V1,G,weight,Qrv,ifreq,lzmat,zmatvals,log = conftuple
        sprint("(%i) %s [%s]"%(count,str(vecA),prefix3[:-1]),tvars.NIBS2)
        sprint("")


        # ONLY CONFORMERS IN ENERGY WINDOWS
        sprint("LL electronic energy: %.4f kcal/mol"%relV0_kcalmol,tvars.NIBS2+4)

        # ONLY CONFORMERS BELOW HLCUTOFF IN GIBBS
        if inpvars._hlcutoff is not None:
           relG = (G-minG)*KCALMOL
           sprint("Gibbs energy: %.3f kcal/mol"%relG,tvars.NIBS2+4)
           if relG > inpvars._hlcutoff:
              sprint("hlcutoff    : %.3f kcal/mol"%inpvars._hlcutoff,tvars.NIBS2+4)
              sprint("HL optimization will not be carried out!",tvars.NIBS2+4)
              sprint()
              continue
           sprint()

        # SKIP IF ALREADY CALCULATED
        if str(vecA) in correlations.keys():
           vecB = correlations[str(vecA)]
           # possible names for log files
           saved_log1 = inpvars._dirhl+"prec.%s.log"%str(vecB)
           saved_log2 = inpvars._dirhl+"stoc.%s.log"%str(vecB)
           # check existence
           bool1 = os.path.exists(saved_log1)
           bool2 = os.path.exists(saved_log2)
           # exists? then skip
           if bool1 or bool2:
              sprint("already in %s"%inpvars._dirhl,tvars.NIBS2+4)
              sprint("optimized conformer: %s"%str(vecB),tvars.NIBS2+4)
              sprint()
              continue
        sprint()

        #-----------------#
        # OPT CALCULATION #
        #-----------------#
        # Perform HL optimization
        data = (loptHL,prefix1+str(vecA),inpvars,lzmat,zmatvals,"HL",string_fccards)
        if calculate:
           sprint("optimization...",tvars.NIBS2+4)
           # execute Gaussian
           ofileOPT,statusOPT,dummy,vecB,zmatvals,zmatatoms = itf.execute(*data)
           sprint()
           # opt ends ok?
           if statusOPT == -1: continue
        else:
           sprint("optimization file:",tvars.NIBS2+4)
           generated, ifile, ofile, err = itf.generate_gjf(*data)
           sprint("- %s"%ifile,tvars.NIBS2+8)
           if generated:
              sprint("- generated!",tvars.NIBS2+8,1)
              nopt += 1
              continue
           sprint("- not generated!",tvars.NIBS2+8,1)
           logdata = gau.read_gaussian_log(ofile)
           commands,comment,ch,mtp,symbols,xcc,gcc,Fcc,energy,statusFRQ,ozmat,level = logdata
           lzmat,zmatvals,zmatatoms = gau.convert_zmat(ozmat)[0]
           for ic in inpvars._tic: zmatvals[ic] %= 360
           vecB = TorPESpoint(tfh.zmat2vec(zmatvals,inpvars._tic),inpvars._tlimit)

        # The optimization succedeed!
        sprint("analysing geometry...",tvars.NIBS2+4)
        sprint("- optimized point: %s"%str(vecB),tvars.NIBS+8,1)

        # NH2 inversion
        zmatvals,inversion = tfh.correct_NH2_inversion(lzmat,zmatvals,zmatatoms,lNH2)
        if inversion:
           svecB1 = str(vecB)
           vecB   = TorPESpoint(tfh.zmat2vec(zmatvals,inpvars._tic),inpvars._tlimit)
           svecB2 = str(vecB)
           if svecB1 != svecB2:
              sprint("- NH2 inversion detected! Exchanging H atoms...",tvars.NIBS+8)
              sprint("- final vector: %s"%svecB2,tvars.NIBS+8,1)

        bools = tfh.precheck_geom(lzmat,zmatvals,cmatrix,inpvars)
        if (inpvars._tests[1][0] == 1) and not bools[0]:
           sprint("- connectivity test is negative!",tvars.NIBS+8,1)
           continue
        if (inpvars._tests[1][1] == 1) and not bools[1]:
           sprint("- torsion angle out of domain!",tvars.NIBS+8,1)
           continue
        if (inpvars._tests[1][2] == 1) and not bools[2]:
           sprint("- hard constraint test is negative!",tvars.NIBS+8,1)
           continue
        if (inpvars._tests[1][3] == 1) and not bools[3]:
           sprint("- soft constraint test is negative!",tvars.NIBS+8,1)
           continue

        # Already saved?
        pointsHL = tfh.folder_points(inpvars._dirhl)
        inlist, equalto = vecB.is_in_list(pointsHL,inpvars._epsdeg)
        if inlist:
           # exists?
           sprint("already in %s (%s)"%(inpvars._dirhl,str(equalto)),tvars.NIBS2+4)
           sprint()
           # rename stoc --> prec if required!
           for ext in "log,zmat".split(","):
               # possible names for log files
               saved_log1 = inpvars._dirhl+"prec.%s.%s"%(str(equalto),ext)
               saved_log2 = inpvars._dirhl+"stoc.%s.%s"%(str(equalto),ext)
               # check existence
               bool1 = os.path.exists(saved_log1)
               bool2 = os.path.exists(saved_log2)
               # if this is prec and the one obtained is stoc, replace name!!
               if bool2 and "prec" in prefix3: move(saved_log2,saved_log1)
           # save LL-->HL correlation
           correlations[str(vecA)] = str(vecB)
           rw.add_llhlcorr(str(vecA),str(vecB))
           continue
        sprint()

        #-----------------#
        # FRQ CALCULATION #
        #-----------------#
        data = (lfrqHL,prefix2+str(vecA),inpvars,lzmat,zmatvals,"HL")
        if not calculate:
           sprint("frequency file:",tvars.NIBS2+4)
           generated, ifile, ofile, err = itf.generate_gjf(*data)
           sprint("- %s"%ifile,tvars.NIBS2+8)
           if generated:
              sprint("- generated!\n",tvars.NIBS2+8,1)
              nfrq += 1
              continue
           # log with normal termination!
           else:
              sprint("- not generated!\n",tvars.NIBS2+8,1)
              statusFRQ,vecB_frq,dummy1,dummy2 = itf.read_normal_log(ofile,inpvars,"HL")
              ofileFRQ = ofile

        # Perform HL frequency
        else:
           sprint("frequency calculation...",tvars.NIBS2+4)
           ofileFRQ,dummy,statusFRQ,vecB_frq,dummy,dummy = itf.execute(*data)

        #============#
        # Save files #
        #============#
        bool1 = (statusFRQ == 0 and not inpvars._ts)
        bool2 = (statusFRQ == 1 and     inpvars._ts)

        # check imag freq
        if bool2 and inpvars._ifqrangeHL != []:
           ifreq = abs( fncs.afreq2cm(itf.get_imag_freq(ofileFRQ,inpvars._freqscalHL)) )
           isok  = fncs.float_in_domain(ifreq,inpvars._ifqrangeHL)
           if not isok:
              sprint("imaginary frequency is: %.2fi cm^-1"%ifreq,tvars.NIBS2+4)
              bool2 = False

        if bool1 or bool2:
           nsp += 1
           # create z-matrix file
           dst = inpvars._dirhl+prefix3+"%s.zmat"%str(vecB)
           write_zmat(dst,lzmat, zmatvals)
           # copy frq file
           src = ofileFRQ
           dst = inpvars._dirhl+prefix3+"%s.log"%str(vecB)
           if not os.path.exists(dst): copyfile(src, dst)
           # save LL-->HL correlation
           correlations[str(vecA)] = str(vecB)
           rw.add_llhlcorr(str(vecA),str(vecB))

        sprint()


    # Print number of calculations
    pp.print_numcalcs(count,nopt,nfrq,nsp)

    if not calculate:
       sprint("Number of opt gjf files generated: %i"%nopt,tvars.NIBS2)
       sprint("Number of frq gjf files generated: %i"%nfrq,tvars.NIBS2)
       sprint()
    else:
       # rewrite correlations to remove repetitions
       correlations = rw.read_llhlcorr()
       rw.write_llhlcorr(correlations)
Exemplo n.º 7
0
def main():

    # Presentation and arguments
    argsbools = get_options_from_prompt()

    num_options = len([argsbools[option] for option in OPTIONS__.split(",") \
                                    if argsbools[option] is not False])

    # No options selected & no input- print info
    if num_options == 0 and not os.path.exists(tvars.IFILE):
        pp.print_notfound(tvars.IFILE)
        sprint("No options were given! Use --help for more information",
               tvars.NIBS, 1)
        raise exc.END

    # Input & Templates creation
    if argsbools["inp"] or argsbools["input"]:
        inpvars = deal_with_input(case="create")
        raise exc.END
    else:
        try:
            inpvars = deal_with_input(case="read")
        except:
            raise exc.END

    # No options selected & no zmatrix - print info
    if num_options == 0 and not os.path.exists(inpvars._zmatfile):
        pp.print_notfound(inpvars._zmatfile)
        sprint("No options were given! Use --help for more information",
               tvars.NIBS, 1)
        raise exc.END

    # zmat file exists?
    if not os.path.exists(inpvars._zmatfile):
        pp.print_filenotfound(inpvars._zmatfile, tvars.NIBS, 1)
        raise exc.END

    # Read zmat, check variables, generate templates and update current variables
    inpvars.prepare_variables()
    if len(inpvars._ttorsions) == 0:
        sprint("No torsions selected in input file!", tvars.NIBS)
        if num_options == 0:
            sprint("No options were given! Use --help for more information",
                   tvars.NIBS, 1)
        raise exc.END
    inpvars, zmat, symbols, masses, cmatrix, lCH3, lNH2, ndummy = zmat_preparation(
        inpvars)

    # Enantiomers? Correlate numbering
    dcorr = None
    if inpvars._enantio:
        sprint("--> enantio keyword activated!", tvars.NIBS2)
        sprint("    testing on reference...", tvars.NIBS2)
        lzmat, zmatvals, zmatatoms = zmat
        # reference geom
        xcc0 = intl.zmat2xcc(lzmat, zmatvals)
        vec0 = tfh.xcc2vec(xcc0, inpvars)
        sprint("    reference : %s" % str(vec0), tvars.NIBS2)
        try:
            # (1) First, try checking Cs symmetry!
            # 1.1 - create geom with all torsions at 180
            zmatvals2 = zmatvals.copy()
            for ic in inpvars._tic:
                zmatvals2[ic] = 180.0
            xcc0 = intl.zmat2xcc(lzmat, zmatvals2)
            # 1.2 check is point group is Cs
            pg, rotsigma = get_pgs(symbols, masses, xcc0)
            if pg == "Cs":
                dcorr = "Cs"
                sprint("    enantiomer: phi --> -phi", tvars.NIBS2, 1)
            # (2) Correlate atoms with enantiomer
            else:
                # enantiomer
                xcc_enantio = enan.generate_enantio(xcc0)
                dcorr = enan.correlate_enantio(xcc0, xcc_enantio, symbols)
                xcc_enantio = enan.reorder_enantio(xcc_enantio, dcorr)
                vec_enantio = tfh.xcc2vec(xcc_enantio, inpvars)
                sprint("    enantiomer: %s" % str(vec_enantio), tvars.NIBS2, 1)
        except:
            dcorr = None
            sprint("    something went wrong... enantio deactivated!",
                   tvars.NIBS2, 1)
            inpvars._enantio = False

    # Check opt mode
    if ndummy != 0 and inpvars._optmode != 0:
        sprint(
            "WARNING! Dummy atoms detected! Keyword 'optmode' will be set to 0!!",
            tvars.NIBS, 1)
        inpvars._optmode = 0

    # dealing with TS?
    if not inpvars._ts:
        inpvars._ifqrangeLL = []
        inpvars._ifqrangeHL = []

    #=========================#
    # Act according option(s) #
    #=========================#
    # No options selected - print info
    if num_options == 0:
        sprint("", tvars.NIBS)
        sprint("No options were given! Use --help for more information",
               tvars.NIBS, 1)
        raise exc.END

    #--------------------------#
    # LL SEARCH (opt + search) #
    #--------------------------#
    if argsbools["prec"] is not False or argsbools["stoc"]:
        # Preconditioned search?
        inpvars._prec = argsbools["prec"]

        try:
            args = (inpvars, zmat, symbols, cmatrix, dcorr, lNH2)
            execute_code(search_conformers, args, "Low-Level search")
        except exc.WrongDimension as exception:
            sprint("ERROR! Wrong dimension in file '%s'!" % inpvars._pcfile,
                   tvars.NIBS2)
            sprint(
                "First line of file contains %i torsion(s)!" % exception._ntor,
                tvars.NIBS2 + 7)
            sprint("--> %s " % exception._fline, tvars.NIBS2 + 7)
            sprint("Line which causes this error:", tvars.NIBS2 + 7)
            sprint("--> %s " % exception._line, tvars.NIBS2 + 7)
            sprint()
            raise exc.END
        except exc.UnableGenRandAng as exception:
            sprint("ERROR! Unable to generate valid random angle!",
                   tvars.NIBS2)
            if len(exception._domain) == 0:
                sprint("Empty domain for one of the torsions!",
                       tvars.NIBS2 + 7)
            else:
                the_domain = "U".join(
                    ["(%.0f,%.0f)" % (p1, p2) for p1, p2 in exception._domain])
                sprint("Domain for torsion: %s" % the_domain, tvars.NIBS2 + 7)
            sprint()
            raise exc.END
        except exc.ErrorHConstraint:
            sprint("ERROR! Problem(s) when checking hard constraint(s)!\n",
                   tvars.NIBS2)
            raise exc.END
        except exc.ErrorSConstraint:
            sprint("ERROR! Problem(s) when checking soft constraint(s)!\n",
                   tvars.NIBS2)
            raise exc.END

    #--------------------------#
    #         MSHO  LL         #
    #--------------------------#
    if argsbools["msho"] in ["ll", "all"]:
        argsLL = (inpvars, cmatrix, "LL", dcorr)
        execute_code(classify_files, argsLL,
                     "Low-Level MSHO partition functions")

    #--------------------------#
    #         MSTOR LL         #
    #--------------------------#
    if argsbools["mstor"] in ["ll", "all"]:
        args = (inpvars, "ll", dcorr, lCH3)
        execute_code(gen_mstor, args, "Generating MsTor input (LL)")

    #--------------------------#
    # HLOPT  (re-optimization) #
    #--------------------------#
    if argsbools["hlopt"] is not False:
        mode_hlopt, lowerconformer, upperconformer = argsbools["hlopt"]
        if mode_hlopt == "0":
            args = (inpvars, cmatrix, lowerconformer, upperconformer, True,
                    lNH2)
            execute_code(highlevel_reopt, args, "High-Level calculations")
        elif mode_hlopt == "1":
            args = (inpvars, cmatrix, lowerconformer, upperconformer, False,
                    lNH2)
            execute_code(highlevel_reopt, args,
                         "Generating High-Level input files")
            raise exc.END

    #--------------------------#
    #         MSHO  HL         #
    #--------------------------#
    if argsbools["msho"] in ["hl", "all"]:
        argsHL = (inpvars, cmatrix, "HL", dcorr)
        execute_code(classify_files, argsHL,
                     "High-Level MSHO partition functions")

    #--------------------------#
    #         MSTOR HL         #
    #--------------------------#
    if argsbools["mstor"] in ["hl", "all"]:
        args = (inpvars, "hl", dcorr, lCH3)
        execute_code(gen_mstor, args, "Generating MsTor input (HL)")

    #--------------------------#
    # REGEN  (regenerate data) #
    #--------------------------#
    if argsbools["regen"]:
        args = (inpvars, )
        execute_code(regen_from_tmp, args, "Regenerating domains")
        raise exc.END
Exemplo n.º 8
0
def zmat_preparation(inpvars):
    # Read zmat file
    pp.print_found(inpvars._zmatfile)
    try:
        xcc, zmat, symbols, masses, other, string = rw.readfile_xyz(
            inpvars._zmatfile)
        dwithout, molecule, natoms, ndummy = other
        for line in string.split("\n"):
            print("       " + line)
    except:
        pp.print_sthwrong(inpvars._zmatfile)
        raise Exception

    # Get connectivity matrix
    sprint("   * calculating adjacency (connection) matrix...", tvars.NIBS)
    sprint("     - connectivity scale factor: %.3f" % inpvars._cfactor,
           tvars.NIBS)
    cmatrix, dmatrix, nbonds = intl.get_adjmatrix(xcc,
                                                  symbols,
                                                  scale=inpvars._cfactor,
                                                  mode="bool")
    fragments = list(intl.get_fragments_from_adjmatrix(cmatrix))
    sprint("     - number of bonds: %i" % nbonds, tvars.NIBS)
    # print bonds
    nrows, ncols = dmatrix.shape
    bonds = []
    for idx1 in range(nrows):
        for idx2 in range(idx1 + 1, ncols):
            if not cmatrix[idx1][idx2]: continue
            bonds.append("%s%i-%s%i" %
                         (symbols[idx1], idx1 + 1, symbols[idx2], idx2 + 1))
    ml = max([len(bond) for bond in bonds])
    for idx in range(0, len(bonds), 5):
        line = "  ".join(["%%-%is" % ml % bond for bond in bonds[idx:idx + 5]])
        sprint(line, tvars.NIBS + 7)
    sprint()
    # fragments
    sprint("     - number of fragments: %i" % len(fragments), tvars.NIBS)
    for count, fragment in enumerate(fragments):
        frag_mformu = fncs.get_molformula([symbols[idx] for idx in fragment])
        sprint("       (%i) %s" % (count + 1, frag_mformu), tvars.NIBS)
    sprint()

    # pairs to be skipped
    if inpvars._skipconn != []:
        sprint(
            "     - Pair(s) of atoms to be skipped in the connectivity test",
            tvars.NIBS)
        for at1, at2 in inpvars._skipconn:
            sprint(
                "       (%s%i,%s%i)" %
                (symbols[at1], at1 + 1, symbols[at2], at2 + 1), tvars.NIBS)
        sprint()

    # Get atoms of target torsions
    sprint("   * identifying target torsions in z-matrix...", tvars.NIBS)
    lzmat, zmatvals, zmatatoms = zmat
    for X, ic in zip(inpvars._ttorsions, inpvars._tic):
        if ic not in zmatatoms.keys():
            sprint("   ERROR: Unable to find '%s' in z-matrix..." % ic,
                   tvars.NIBS)
            raise Exception
        inpvars._tatoms[X] = list(zmatatoms[ic])
        storsion = "-".join(
            [symbols[atom] + "%i" % (atom + 1) for atom in inpvars._tatoms[X]])
        sprint("  torsion%s (%s): %s" % (X, ic, storsion), tvars.NIBS + 3)
    sprint()

    # Check lists and dicts related to torsions
    sthwrong = False
    for idx, X in enumerate(inpvars._ttorsions):
        sprint("   * variables for torsion%s (angles in degrees):" % X,
               tvars.NIBS)
        sprint("tsigma  : %i" % (inpvars._tsigma[idx]), tvars.NIBS + 5)
        sprint("maxvalue: %.0f" % (inpvars._tlimit[idx]), tvars.NIBS + 5)
        values = "U".join("(%i,%i)" % (phi1, phi2)
                          for phi1, phi2 in inpvars._tdomain[idx])
        sprint("tdomain : %s" % (values), tvars.NIBS + 5)
        values = ",".join("%i" % val for val in inpvars._precond[idx])
        sprint("precond : %s" % (values), tvars.NIBS + 5)
        sprint()
        if len(inpvars._tdomain[idx]) == 0:
            sprint("ERROR! Something wrong with this torsion!", tvars.NIBS + 5)
            raise exc.END

    # Important variable not defined
    status, variable = inpvars.check()
    if status == -1:
        pp.print_readerror(variable)
        end_program = True
        raise Exception

    # Detect CH3 groups
    lCH3 = detect_ch3(cmatrix, symbols, inpvars)
    if len(lCH3) != 0:
        sprint("* CH3 group(s) detected!", tvars.NIBS + 3)
        for CH3 in lCH3:
            sprint(
                "dihedral: " +
                "-".join(["%s%i" % (symbols[idx], idx + 1) for idx in CH3]),
                tvars.NIBS2 + 2)
        if len(lCH3) == 1:
            sprint("It will be considered when using --mstor", tvars.NIBS + 5)
        else:
            sprint("They will be considered when using --mstor",
                   tvars.NIBS + 5)
        sprint()

    # Detect NH2 groups
    lNH2 = detect_nh2(cmatrix, symbols, lzmat, zmatvals, inpvars)
    if len(lNH2) != 0:
        sprint("* NH2 group(s) detected!", tvars.NIBS + 3)
        for HNRH_atoms, HNRH_value, HNRH_bool in lNH2:
            H1, N, R, H2 = HNRH_atoms
            nh2 = "H%i-N%i-H%i" % (H1 + 1, N + 1, H2 + 1)
            angle_args = (H1 + 1, N + 1, symbols[R], R + 1, H2 + 1,
                          np.rad2deg(HNRH_value))
            angle = "angle(H%i-N%i-%s%i...H%i) = %.0f degrees" % angle_args
            sprint("%s  --> %s" % (nh2, angle), tvars.NIBS2 + 2)
        sprint()

    return inpvars, zmat, symbols, masses, cmatrix, lCH3, lNH2, ndummy
Exemplo n.º 9
0
def get_options_from_prompt():
    # Get user arguments (options)
    args = sys.argv[1:]
    #--------------------#
    # --version / --help #
    #--------------------#
    # check if user asks for help
    if "-h" in args or "--help" in args:
        pp.print_welcome(tvars.PROGNAME)
        sprint(pp.HSTRING)
        raise exc.END
    # check if user asks for version
    if "-v" in args or "--version" in args:
        sprint(tvars.PROGNAME.split(".py")[0] + " " + tvars.PROGVER)
        raise exc.END

    #--------------------#
    # Re-order arguments #
    #--------------------#
    current = None
    arguments = {}
    for arg in args:
        if arg.startswith("--"):
            current = arg
            arguments[current] = []
        elif current is not None:
            arguments[current].append(arg)

    #-------------------------#
    # Go argument by argument #
    #-------------------------#
    valid_args = ["--" + arg for arg in OPTIONS__.split(",")]
    argbools = {option: False for option in OPTIONS__.split(",")}
    for argument, options in arguments.items():
        # unknown option
        if argument not in valid_args:
            pp.print_unknown_option(arg, tvars.PROGNAME)
            raise exc.END
        # option was chosen
        else:
            argbools[arg[2:]] = True
        # ARGUMENT: --prec
        if argument == "--prec":
            try:
                if len(options) == 2: prec1, prec2 = options
                else: prec1, prec2 = 1, 1
                prec1, prec2 = int(prec1), int(prec2)
                argbools["prec"] = (max(prec1, prec2,
                                        1), max(min(prec1, prec2), 1))
            except:
                sprint("arguments for --prec must be integers!!")
                raise exc.END
        # ARGUMENT: --hlopt
        elif argument == "--hlopt":
            mode_hlopt = "0"
            lowerconformer = 0
            upperconformer = float("inf")
            try:
                if "nocalc" in options:
                    mode_hlopt = "1"
                    options.remove("nocalc")
                if len(options) == 2:
                    lowerconformer, upperconformer = options
                    lowerconformer = int(lowerconformer)
                    upperconformer = int(upperconformer)
                elif len(options) != 0:
                    raise Exception
                lowerconformer = min(lowerconformer, upperconformer)
                upperconformer = max(lowerconformer, upperconformer)
                argbools["hlopt"] = (mode_hlopt, lowerconformer,
                                     upperconformer)
            except:
                sprint(
                    "arguments for --hlopt must be 'nocalc' and/or two float numbers!!"
                )
                raise exc.END
        # ARGUMENT: --msho
        elif argument == "--msho":
            mode_msho = "all"
            if "ll" in options: mode_msho = "ll"
            elif "hl" in options: mode_msho = "hl"
            elif len(options) != 0:
                sprint("argument for --msho can only be 'll' or 'hl'!!")
                raise exc.END
            argbools["msho"] = mode_msho
        # ARGUMENT: --mstor
        elif argument == "--mstor":
            mode_mstor = "all"
            if "ll" in options: mode_mstor = "ll"
            elif "hl" in options: mode_mstor = "hl"
            elif len(options) != 0:
                sprint("argument for --mstor can only be 'll' or 'hl'!!")
                raise exc.END
            argbools["mstor"] = mode_mstor

    pp.print_welcome(tvars.PROGNAME)
    pp.print_user_info()
    return argbools
Exemplo n.º 10
0
           # 2. Log file with Normal termination & frq file exists
           elif os.path.exists(log_frq):
              statusFRQ = tgau.status_from_log(log_frq,inpvars)[1]
              bool_min = (statusFRQ == 0) and (not inpvars._ts)
              bool_ts  = (statusFRQ == 1) and (    inpvars._ts)
              # 2.1. correct number of ifreqs
              if bool_min or bool_ts:
                 bool_in,closest = vec2.is_in_list(confs,inpvars._epsdeg)
                 if bool_in: ddomains["repe"].add( (vec1,vec2,statusFRQ) )
                 else:
                     ddomains["conf"].add( (vec1,vec2,statusFRQ) )
                     # copy file to dirll
                     log_conf = inpvars._dirll+"%s.%s.log"%(case,str(vec2))
                     if not os.path.exists(log_conf):
                        sprint("  %s  -->  %s"%(log_frq,log_conf),NIBS2)
                        copyfile(log_frq,log_conf)
                     # update confs
                     confs.append(vec2)
              # 2.2. wrong number of ifreqs
              else: ddomains["wimag"].add( (vec1,vec2,statusFRQ) )

           # 3. Log file with Normal termination & frq file does not exist
           else:
              repe_or_excl.append( (vec1,vec2) )

       #------------------------#
       # deal with repe or excl #
       #------------------------#
       for vec1,vec2 in repe_or_excl:
           domain = "excl"
Exemplo n.º 11
0
def search_conformers(inpvars, zmat, symbols, cmatrix, dcorr, lNH2):

    ntorsions = len(inpvars._ttorsions)
    lzmat, zmatvals, zmatatoms = zmat
    # reference torsional vector
    vecR = TorPESpoint(tfh.zmat2vec(zmatvals, inpvars._tic), inpvars._tlimit)
    inpvars._vecR = vecR

    # Create folders
    try:
        tfh.create_dir(inpvars._tmpll)
    except:
        raise exc.END
    try:
        tfh.create_dir(inpvars._dirll)
    except:
        raise exc.END

    #====================================#
    # Print information before searching #
    #====================================#
    if inpvars._ts: file1, file2 = tvars.TEMPLTSOPTLL, tvars.TEMPLTSFRQLL
    else: file1, file2 = tvars.TEMPLMINOPTLL, tvars.TEMPLMINFRQLL
    # do templates exist??
    if not os.path.exists(file1):
        pp.print_filenotfound(file1, tvars.NIBS2, 1)
        raise exc.END
    if not os.path.exists(file2):
        pp.print_filenotfound(file2, tvars.NIBS2, 1)
        raise exc.END
    # read templates
    with open(file1, 'r') as asdf:
        loptLL = asdf.readlines()
    with open(file2, 'r') as asdf:
        lfrqLL = asdf.readlines()
    pp.print_infoLLsearch(inpvars, file1, file2, loptLL, lfrqLL)

    # Check gaussian software
    end_program = itf.check_executable()
    if end_program: return

    pp.print_tests(inpvars._tests)
    pp.print_ifreqconstr(inpvars._ifqrangeLL)

    #=======================#
    # Deal with domain file #
    #=======================#
    ddomains = rw.read_domains()
    if os.path.exists(tvars.FDOMAINS):
        sprint("Domain file exists (%s)!" % tvars.FDOMAINS, tvars.NIBS2, 1)
        pp.print_domains(ddomains, tvars.DOMAINS)
    else:
        rw.initialize_domains(ntorsions)

    #=========================#
    # Search in torsional PES #
    #=========================#
    if inpvars._prec is not False:
        sprint("Preconditioned algorithm will be used!", tvars.NIBS2)
        prefix1, prefix2, prefix3 = "optprec.", "frqprec.", "prec."
        if inpvars._prec != (1, 1):
            sprint(" - Number of blocks: %i" % inpvars._prec[0], tvars.NIBS2)
            sprint(" - Selected block  : %i" % inpvars._prec[1], tvars.NIBS2)
        sprint()
    else:
        sprint("Stochastic algorithm will be used!", tvars.NIBS2, 1)
        prefix1, prefix2, prefix3 = "optstoc.", "frqstoc.", "stoc."

    # save initial zmat
    i_lzmat = list(lzmat)
    i_zmatvals = {k: v for (k, v) in zmatvals.items()}
    # Calculate for each random angle
    count = 0
    nopt = 0
    nfrq = 0
    nsp = 0
    svec2log = tfh.get_logs_vecs(inpvars, dcorr, svec2log={})
    for vecA in tfh.yield_angles(inpvars):

        count += 1
        # read domains
        ddomains = rw.read_domains()
        # print target point
        sprint("(%i) %s" % (count, str(vecA)), tvars.NIBS2)
        sprint()

        #------------------#
        # analyze geometry #
        #------------------#
        sprint("preparing Z-matrix...", tvars.NIBS2 + 4)
        args = (vecA, inpvars, ddomains, svec2log, dcorr)
        bool_guess, closest, svec2log, distance = tfh.test_similarity_redundancy(
            *args)
        if bool_guess == -1:
            sprint("already listed in %s" % tvars.FDOMAINS, tvars.NIBS2 + 4)
            sprint()
            continue
        if bool_guess == 0 and (inpvars._tests[0][1] == 1):
            sprint(
                "similarity test is negative: in the domain of %s" %
                str(closest), tvars.NIBS2 + 4)
            sprint()
            continue
        closest_log = svec2log.get(str(closest), None)
        args = (vecA, i_zmatvals, inpvars, closest_log, distance)
        zmatvals = gen_guess_zmatrix(*args)
        if inpvars._enantio:
            vecA_enantio = tfh.enantiovec(lzmat, zmatvals, dcorr, inpvars)
            sprint("enantiomer: %s" % str(vecA_enantio), tvars.NIBS2 + 4)

        #- - - - - - - - - #
        # 1st set of TESTS #
        #- - - - - - - - - #
        bools = tfh.precheck_geom(lzmat, zmatvals, cmatrix, inpvars)
        if (inpvars._tests[0][0] == 1) and (bools[0] is False):
            sprint("connectivity test is negative: different connectivity!",
                   tvars.NIBS + 7, 1)
            continue
        if (bools[1] is False):
            sprint("torsion angle out of domain...", tvars.NIBS + 7, 1)
            continue
        if (inpvars._tests[0][2] == 1) and (bools[2] is False):
            sprint("hard constraint test is negative!", tvars.NIBS + 7, 1)
            continue
        if (inpvars._tests[0][3] == 1) and (bools[3] is False):
            sprint("soft constraint test is negative!", tvars.NIBS + 7, 1)
            continue
        sprint()

        #------------------#
        # optimization     #
        #------------------#
        sprint("optimization...", tvars.NIBS2 + 4)
        data = (loptLL, prefix1 + str(vecA), inpvars, lzmat, zmatvals, "LL")
        ofileOPT, statusOPT, dummy, vecB, zmatvals, zmatatoms = itf.execute(
            *data)
        nopt += 1

        # optimization was carried out --> save guess
        if statusOPT != 0:
            rw.add_domain("fail", vecA, None, -1)
            #if inpvars._enantio: rw.add_domain("fail",vecA_enantio,None,-1)
            sprint()
            continue

        #===========================#
        #    check NH2 inversion    #
        #===========================#
        zmatvals, inversion = tfh.correct_NH2_inversion(
            lzmat, zmatvals, zmatatoms, lNH2)
        if inversion:
            # recalculate vector
            svecB1 = str(vecB)
            vecB = TorPESpoint(tfh.zmat2vec(zmatvals, inpvars._tic),
                               inpvars._tlimit)
            svecB2 = str(vecB)
            if svecB1 != svecB2:
                sprint("NH2 inversion detected! Exchanging H atoms...",
                       tvars.NIBS2 + 4)
                sprint("final vector: %s" % svecB2, tvars.NIBS2 + 4)
        #===========================#

        if inpvars._enantio:
            vecB_enantio = tfh.enantiovec(lzmat, zmatvals, dcorr, inpvars)
            sprint("enantiomer  : %s" % str(vecB_enantio), tvars.NIBS2 + 4)

        change = int(round(vecA.distance(vecB)))
        sprint("distance from guess point: %i degrees" % change,
               tvars.NIBS2 + 4)
        sprint()

        #------------------#
        # analyze geometry #
        #------------------#
        sprint("analysing geometry...", tvars.NIBS2 + 4)
        #- - - - - - - - - #
        # 2nd set of TESTS #
        #- - - - - - - - - #
        bools = tfh.precheck_geom(lzmat, zmatvals, cmatrix, inpvars)
        if (inpvars._tests[1][0] == 1) and not bools[0]:
            sprint("connectivity test is negative: different connectivity!",
                   tvars.NIBS + 7, 1)
            rw.add_domain("excl", vecA, vecB, -1)
            if inpvars._enantio:
                rw.add_domain("excl", vecA_enantio, vecB_enantio, -1)
            continue
        if not bools[1]:
            sprint("torsion angle out of domain...", tvars.NIBS + 7, 1)
            rw.add_domain("excl", vecA, vecB, -1)
            if inpvars._enantio:
                rw.add_domain("excl", vecA_enantio, vecB_enantio, -1)
            continue
        if (inpvars._tests[1][2] == 1) and not bools[2]:
            sprint("hard constraint test is negative!", tvars.NIBS + 7, 1)
            rw.add_domain("excl", vecA, vecB, -1)
            if inpvars._enantio:
                rw.add_domain("excl", vecA_enantio, vecB_enantio, -1)
            continue
        if (inpvars._tests[1][3] == 1) and not bools[3]:
            sprint("soft constraint test is negative!", tvars.NIBS + 7, 1)
            rw.add_domain("excl", vecA, vecB, -1)
            if inpvars._enantio:
                rw.add_domain("excl", vecA_enantio, vecB_enantio, -1)
            continue
        # current conformations
    #confs = tfh.folder_points(inpvars._dirll)
        confs = [fvec for ivec, fvec, frqstatus in ddomains["conf"]]
        confs += [fvec for ivec, fvec, frqstatus in ddomains["enan"]]
        # already stored?
        inlist, equalto = vecB.is_in_list(confs, inpvars._epsdeg)
        if inlist and (inpvars._tests[1][1] == 1):
            sprint(
                "redundancy test is negative: same as stored point (%s)" %
                equalto, tvars.NIBS2 + 4, 1)
            rw.add_domain("repe", vecA, vecB, -1)
            if inpvars._enantio:
                rw.add_domain("repe", vecA_enantio, vecB_enantio, -1)
            continue
        sprint("new geometry found!", tvars.NIBS2 + 4)
        sprint()

        #------------------#
        # freq calculation #
        #------------------#
        sprint("frequency calculation...", tvars.NIBS2 + 4)
        data = (lfrqLL, prefix2 + str(vecA), inpvars, lzmat, zmatvals, "LL")
        ofileFRQ, dummy, statusFRQ, vecB_frq, dummy, dummy = itf.execute(*data)
        nfrq += 1

        #------------------------------#
        # Save points into domain file #
        #------------------------------#
        bool1 = (statusFRQ == 0 and not inpvars._ts)
        bool2 = (statusFRQ == 1 and inpvars._ts)
        bool_conf = bool1 or bool2
        # Save optimized point
        if bool_conf: seldomain = "conf"
        else: seldomain = "wimag"

        # check imag freq
        if seldomain == "conf" and inpvars._ifqrangeLL != []:
            ifreq = abs(
                fncs.afreq2cm(itf.get_imag_freq(ofileFRQ,
                                                inpvars._freqscalLL)))
            isok = fncs.float_in_domain(ifreq, inpvars._ifqrangeLL)
            if not isok:
                seldomain, bool_conf = "wimag", False
                pp.print_excluded_ifreq(ifreq)
            else:
                pp.print_accepted_ifreq(ifreq)

        rw.add_domain(seldomain, vecA, vecB, statusFRQ)
        if inpvars._enantio and seldomain == "conf":
            rw.add_domain("enan", vecA_enantio, vecB_enantio, statusFRQ)
        elif inpvars._enantio and seldomain == "wimag":
            rw.add_domain("wimag", vecA_enantio, vecB_enantio, statusFRQ)
        #============#
        # Save files #
        #============#
        if bool_conf:
            # create z-matrix file
            dst = inpvars._dirll + prefix3 + "%s.zmat" % str(vecB)
            write_zmat(dst, lzmat, zmatvals)
            # copy frq file
            src = ofileFRQ
            dst = inpvars._dirll + prefix3 + "%s.log" % str(vecB)
            if not os.path.exists(dst): copyfile(src, dst)
            # update counter
            nsp += 1
        sprint()

    # Print number of calculations
    pp.print_numcalcs(count, nopt, nfrq, nsp)