Example #1
0
def execute(ifile,ofile,err,folder=None):
    # Add folder to names
    if folder is not None:
       if not folder.endswith("/"): folder = folder + "/"
       ifile = folder + ifile
       ofile = folder + ofile
       err   = folder + err
    # Execution file?
    set_EXE()
    check_EXE()
    # Exception
    exception = Exc.CalcFails(Exception)
    exception._var = ofile
    # Execute Gaussian
    command = "%s <%s 1>%s 2>%s"%(EXE,ifile,ofile,err)
    # Try up to NN times
    NN = 5
    for ii in range(NN):
        try   : status = os.system(command)
        except: status = 0
        # interrupted by ctrl+c (status = 2?)
        if status == 2: raise KeyboardInterrupt
        # Get log status
        logstatus = log_status(ofile)
        # Act according log status
        # (a) Normal termination
        if   logstatus == 1       : break
        # (b) empty file, no file or open-new-file error
        elif logstatus in (-1,0,2):
             time.sleep(1)
             continue
        # (c) other type of error
        else: raise exception
    return status
Example #2
0
def obtain_cvt(dMols,
               points,
               VadiSpl,
               temps,
               pathvars,
               si=-float("inf"),
               sj=+float("inf"),
               dcfs={}):
    print("")
    fncs.print_string("Calculating CVT variational coefficient...", 4)
    print("")
    useics = pathvars._useics
    if len(temps) == 0: raise Exc.NoTemps(Exception)
    # Only points between si and sj
    points = [pp for pp in points if si <= dMols[pp][0] <= sj]
    lcvt_s, lcvt_gamma, gibbs_matrix, gibbsTS, lnew = cv.get_cvt(
        dMols, points, VadiSpl, temps, useics)
    # print gibbs
    svals = [dMols[point][0] for point in points]
    fncs.print_string(
        PS.scvt_gibbs(svals, temps, gibbs_matrix.copy(), pathvars, gibbsTS), 8)
    # print cvt coefs
    fncs.print_string(PS.scvt_coefs(lcvt_s, lcvt_gamma, temps), 8)
    # save data
    dcfs["cvt"] = lcvt_gamma
    return dcfs, lcvt_s, gibbs_matrix, lnew
Example #3
0
def get_contributions(ctc, dall, dctc, ltemp):
    if ctc not in dctc.keys(): return None
    # Only one conformer?
    if len(dctc[ctc]._itcs) == 1:
        itc, weight = dctc[ctc]._itcs[0]
        dchi = {itc: [1.0 for T in ltemp]}
        return dchi
    # Get total partition function
    V0, V1, PFN = dall["pfn"]["%s.msho" % ctc]
    # Get ratios
    dchi = {}
    for itc, weight in dctc[ctc]._itcs:
        # Get individual partition functions
        try:
            V0i, V1i, PFNi = dall["pfn"][PN.struckey(ctc, itc)]
            # Calculate contribution
            dE = (V1i - V1)
            exp_arg = [-dE / pc.KB / T for T in ltemp]
            ratio_pfn = [weight * pfi / pftot for pfi, pftot in zip(PFNi, PFN)]
            chi_i = [
                aa * fncs.exp128(bb) for aa, bb in zip(ratio_pfn, exp_arg)
            ]
            dchi[itc] = np.array(chi_i)
        except:
            exception = Exc.LostConformer(Exception)
            exception._var = PN.struckey(ctc, itc)
            raise exception
    # Return data
    return dchi
Example #4
0
def random_angle(tdomain=[(0, 360)]):
    for ii in range(10**6):
        # random angle as integer
        angle = int(round(random.random() * 360))
        # assert in range
        if fncs.float_in_domain(angle, tdomain): return angle
    # unable to generate angle
    exception = exc.UnableGenRandAng(Exception)
    exception._domain = tdomain
    raise exception
Example #5
0
def read_orcaout(orca_out):
    # Read lines
    lines = read_file(orca_out)
    # CHECK FILE IS ORCA OUT
    correct = False
    for line in lines:
        if "This ORCA versions uses" in line:
            correct = True
            break
    if not correct: raise Exc.FileType(Exception)
    # Initialize
    ch, mtp, E = None, None, None
    xcc, symbols, atonums = [], [], []
    # basis set
    basisset = ""
    try:
        for line in lines:
            if "utilizes the basis" in line:
                basisset = line.split(":")[1]
                break
    except:
        pass
    # hamiltonian
    hamiltonian = ""
    try:
        for idx, line in enumerate(lines):
            if "Hamiltonian:" in line:
                hamiltonian = lines[idx + 1].split()[-1]
                break
    except:
        pass
    # level of calculation
    calclevel = hamiltonian + " " + basisset
    # Get ch, mtp, E
    pos = None
    for idx in range(len(lines)):
        line = lines[idx]
        if "Total Charge           Charge" in line: ch = int(line.split()[-1])
        if "Multiplicity           Mult" in line: mtp = int(line.split()[-1])
        if "FINAL SINGLE POINT ENERGY " in line: E = float(line.split()[-1])
        if "CARTESIAN COORDINATES (A.U.)" in line: pos = idx
    # Get xcc, symbols, atonums
    if pos is None:
        sys.exit(
            "Unable to find 'CARTESIAN COORDINATES (A.U.)' label in file!")
    pos = pos + 3
    for line in lines[pos:]:
        line = line.strip()
        if line == "": break
        idx, symbol, atonum, dummy, mass, x, y, z = line.split()
        xcc = xcc + [float(x), float(y), float(z)]
        symbols.append(symbol)
        atonums.append(int(atonum.split(".")[0]))
    # Return
    return xcc, atonums, ch, mtp, E, calclevel.strip()
Example #6
0
def mep_first(xcc,
              gcc,
              Fcc,
              symbols,
              masses,
              var_first,
              spc_fnc,
              spc_args,
              drst={},
              parallel=False):

    #global PARALLEL, delayed, multiprocessing, Parallel
    #PARALLEL, delayed, multiprocessing, Parallel = fncs.set_parallel(parallel)
    ds, mu, cubic, idir = var_first

    # convert cubic variable to d3 (in bohr)
    d3 = cubic2float(cubic)

    # mass-scaled
    xcc = fncs.shift2com(xcc, masses)
    xms = fncs.cc2ms_x(xcc, masses, mu)
    gms = fncs.cc2ms_g(gcc, masses, mu)
    Fms = fncs.cc2ms_F(Fcc, masses, mu)

    # Data in backup?
    if TSLABEL in drst.keys():
        si, E, xms2, gms, Fms, v0, v1, t = drst[TSLABEL]
        gms = np.array(gms)
        Fms = np.array(Fms)
        v0 = np.array(v0)
        if v1 is not None: v1 = np.array(v1)
        same = fncs.same_geom(xms, xms2)
        if not same: raise Exc.RstDiffTS(Exception)
    else:
        # Calculation of v0
        freqs, evals, evecs = fncs.calc_ccfreqs(Fcc, masses, xcc)
        ifreq, Lms = get_imagfreq(freqs, evecs)
        v0 = fncs.normalize_vec(Lms)
        v0 = correctdir_v0(xms, v0, idir, masses, mu)

        # Calculation of v1
        if d3 is None: v1 = None
        else:
            v1 = calculate_v1(xms, v0, Fms, symbols, masses, mu, d3, spc_fnc,
                              spc_args, parallel)
    # Final structures
    if d3 is None:
        xms_bw = sd_taylor(xms, ds, v0=-v0)
        xms_fw = sd_taylor(xms, ds, v0=+v0)
    else:
        xms_bw = sd_taylor(xms, ds, v0=-v0, v1=-v1)
        xms_fw = sd_taylor(xms, ds, v0=+v0, v1=+v1)

    return (xms, gms, Fms), (v0, v1), (xms_bw, xms_fw)
Example #7
0
def set_EXE():
    global EXE
    # Defined in this file
    if 'EXE' in globals():
        return
    # Try to export it from bashrc
    elif KEYGAU in os.environ:
        EXE = os.environ[KEYGAU]
        return
    # Not found
    else: raise Exc.ExeNotDef(Exception)
Example #8
0
def set_FCHK():
    global FCHK
    # Defined in this file
    if 'FCHK' in globals():
        return
    # Try to export it from bashrc
    elif KEYFCHK in os.environ:
        FCHK = os.environ[KEYFCHK]
        return
    # Not found
    else: raise Exc.ExeNotDef(Exception)
Example #9
0
def read_path(filename=PN.IFILE3):
    lines, status = file2lines(filename)
    # Get info for lines
    dpath = {}
    ctc_lines = None
    bool_mep = False
    bool_drp = False
    saveline = False
    for line in lines:
        #-- MEP --#
        if line.startswith("end_mep"):
            bool_mep = False
            saveline = False
            dpath[ctc] = ("mep", pathlines)
            continue
        #-- DRP --#
        if line.startswith("end_drp"):
            bool_drp = False
            saveline = False
            dpath[ctc] = ("drp", pathlines)
            continue
        # save line
        if saveline: pathlines.append(line)
        #-- MEP --#
        if line.startswith("start_mep"):
            bool_mep = True
            saveline = True
            ctc = line.split()[1]
            pathlines = []
            continue
        #-- DRP --#
        if line.startswith("start_drp"):
            bool_drp = True
            saveline = True
            ctc = line.split()[1]
            pathlines = []
            continue
    # Read data for each ctc
    for ctc, (pathtype, lines) in dpath.items():
        pathvars = PathVars(pathtype)
        # Read info in lines
        for line in lines:
            line = line.lower()
            key = line.split()[0]
            value = " ".join(line.split()[1:]).lower()
            try:
                pathvars.setvar(key, value)
            except:
                exception = Exc.ReadProblem(Exception)
                exception._file = filename
                exception._var = line.split("\n")[0]
                raise exception
        dpath[ctc] = pathvars
    return dpath, (filename, status)
Example #10
0
def obtain_adipot(tcommon, drst, pathvars, symmetry):
    print("")
    fncs.print_string("Calculating adiabatic potential...", 4)
    print()
    ics = pathvars.get_ics()
    icsbw = pathvars._icsbw
    icsfw = pathvars._icsfw
    if pathvars._useics == "yes" and (ics is None or len(ics) == 0):
        raise Exc.NoICS(Exception)
    # calculate adiabatic potential
    idata = (tcommon, drst, pathvars._eref, ics, pathvars._useics,
             pathvars._lowfq, pathvars._freqscal, icsbw, icsfw, symmetry)
    dMols, ccVadi, icVadi, tuple_cc, tuple_ic, listV0 = ap.path2vadi(*idata)
    # expand tuples
    data_x, lcc_frqs, lcc_tzpe = tuple_cc
    data_x, lic_frqs, lic_tzpe = tuple_ic
    # check data
    fncs.print_string(PS.sadipot_ics(ics, pathvars._useics, icsbw, icsfw), 8)
    if pathvars._useics == "yes":
        ok1 = ap.ccvsic_checknfreqs(lcc_frqs, lic_frqs)
        ok2 = ap.ccvsic_checkts(data_x, lcc_frqs, lic_frqs)
        ok3 = ap.ccvsic_checkzpe(lcc_tzpe, lic_tzpe)
        checks = (ok1, ok2, ok3)
        # select spline
        if not ok1 or not ok2: Vadi, pathvars._useics = ccVadi, "no"
        elif pathvars._useics == "yes": Vadi, pathvars._useics = icVadi, "yes"
        else: Vadi, pathvars._useics = ccVadi, "no"
    else:
        ok1, ok2, ok3 = True, True, True
        Vadi, pathvars._useics = ccVadi, "no"
    # Any imag freq along the MEP?
    if pathvars._useics == "yes": lfqs = list(lic_frqs)
    else: lfqs = list(lcc_frqs)
    nfreqs = min([len(xx) for xx in lcc_frqs])
    allfqreal = True
    for lfq in lfqs:
        if len(lfq) > nfreqs: lfq = lfq[1:]
        if True in [fq < 0.0 for fq in lfq]: allfqreal = False
    del lfqs
    # print checks
    fncs.print_string(
        PS.sadipot_checks(ok1, ok2, ok3, pathvars._useics, allfqreal), 8)
    # setup spline
    Vadi.setup()
    data4print = (Vadi.xx(), Vadi.yy(), Vadi._sAG, Vadi._VAG, listV0, lcc_tzpe,
                  lic_tzpe, pathvars._eref)
    fncs.print_string(PS.sadipot_table(*data4print), 8)
    # print freqs
    fncs.print_string("- Vibrational frequencies summary: cc (ic) [in cm^-1]:",
                      8)
    print("")
    fncs.print_string(PS.sadipot_freqs(Vadi.xx(), lcc_frqs, lic_frqs), 8)
    return dMols, Vadi, pathvars
Example #11
0
def read_gaussian_log(filename,target_level=None):
    '''
    xcc,gcc,Fcc and symbols --> returned without dummy atoms
    '''
    if not os.path.exists(filename): return
    # split lines into blocks (in case of Link1)
    blocks = split_gaulog_into_gaublocks(filename)
    # Get info of each block
    data = [get_data_from_gaublock(block) for block in blocks]
    # There is nothing to return
    if data == []: return [None]*12
    # Localize data with hessian matrix
    IDX = -1
    for idx,data_i in enumerate(data):
        Fcc =  data_i[7]
        if Fcc is not None:
           IDX = idx
           break
    # Return the best set of data (the last with the hessian or the last block)
    commands,comment,ch,mtp,symbols,xcc,gcc,Fcc,energies,E_oniom,num_imag,zmat = data[IDX]
    # Recalculating xcc from z-matrix (do not trust the orientation read from output)
    if zmat is not None:
       (lzmat,zmatvals,zmatatoms),symbols = convert_zmat(zmat)
       xcc = zmat2xcc(lzmat,zmatvals)
    # Correct symbols (just in case)
    symbols,atonums = symbols_and_atonums(symbols)
    # Remove dummies from xcc, gcc and Fcc!
    if xcc is not None: xcc = clean_dummies(symbols,xcc=xcc)[1]
    if gcc is not None: gcc = clean_dummies(symbols,gcc=gcc)[1]
    if Fcc is not None: Fcc = clean_dummies(symbols,Fcc=Fcc)[1]
    symbols = clean_dummies(symbols)

    # If user does not ask for level, send one of lowest energy
    if target_level is None:
       energies.sort()
       energy,level = energies[0]
    else:
       IDX = None
       exception = Exc.LevelNotFound()
       exception._var = target_level
       for idx,(energy,level) in enumerate(energies):
           if level.lower() == target_level.lower():
               IDX = idx
               break
       if IDX is None: raise exception
       energy, level = energies[IDX]
    # oniom?
    if E_oniom is not None:
       energy = E_oniom
       level  = "ONIOM"
    # Return data
    return commands,comment,ch,mtp,symbols,xcc,gcc,Fcc,energy,num_imag,zmat,level
Example #12
0
def get_ratecons(rcs,dchem,dall,idx,temp):
    drcons    = dall.get("rcons",{})
    processes = []
    for key,(rctype,weight,coefs) in sorted(rcs.items()):
        rctype = rctype.lower()
        # reaction name and direction
        if "." in key: rcname, direction = key.split(".")
        else         : rcname, direction = key, "both"
        # elements in reaction
        Rs,TS,Ps = dchem[rcname]
        nR,nP = len(Rs),len(Ps)
        # read/calculate rate constant
        if "analytic" not in rctype:
           key_fw = "%s.%s.%s"%(rctype,rcname,"fw")
           key_bw = "%s.%s.%s"%(rctype,rcname,"bw")
           # get rate constants
           kfw = drcons.get(key_fw,None)
           kbw = drcons.get(key_bw,None)
           if kfw is not None: kfw = kfw[idx]
           if kbw is not None: kbw = kbw[idx]
           # any non-desired rate constants
           if direction == "fw": kbw = None
           if direction == "bw": kfw = None
           # none
           if kbw is None and kfw is None:
              exception =Exc.NoRateCons(Exception)
              exception._var = (rctype,key)
              raise exception
        else:
           if   rctype.lower() == "analytic1": k = log_anarc1(temp,*coefs)
           elif rctype.lower() == "analytic2": k = log_anarc2(temp,*coefs)
           elif rctype.lower() == "analytic3": k = log_anarc3(temp,*coefs)
           elif rctype.lower() == "analytic4": k = log_anarc4(temp,*coefs)
           elif rctype.lower() == "analytic5": k = log_anarc5(temp,*coefs)
           else                              : k = None
           # log --> exp
           if k is not None: k = exp128(k)
           # save data properly
           if   direction in ["fw","both"]: kfw, kbw = k   , None
           elif direction in ["bw"       ]: kfw, kbw = None, k
           else                           : kfw, kbw = None, None
           # in atomic units
           hunitsFW = ML**(nR-1.0) / SECOND
           hunitsBW = ML**(nP-1.0) / SECOND
           if kfw is not None: kfw /= hunitsFW
           if kbw is not None: kbw /= hunitsBW
        # ignore reactions giving rise to bimolecular products
        if len(Ps) > 1 and direction != "bw": kbw = None
        # save in processes
        if kfw is not None: processes.append( (Rs,Ps,weight*kfw) )
        if kbw is not None: processes.append( (Ps,Rs,weight*kbw) )
    return processes
Example #13
0
def compare_tcommon(tcommon, tcommon2, rstfile, eps=0.01):
    exception = Exc.RstDiffVar(Exception)
    exception._rst = rstfile
    if tcommon2 is None: return
    the_vars = ("ch", "mtp", "atonums", "masses", "mu")
    for idx, var in enumerate(the_vars):
        exception._var = var
        var1, var2 = tcommon[idx], tcommon2[idx]
        if type(var1) == type(1) or type(var1) == type(1.0):
            var1 = [var1]
            var2 = [var2]
        for ii, jj in zip(var1, var2):
            if abs(ii - jj) > eps: raise exception
Example #14
0
def compare_tpath(tpath, tpath2, rstfile, eps=1e-8):
    exception = Exc.RstDiffVar(Exception)
    exception._rst = rstfile
    if tpath2 is None: return
    the_vars = ("method", "mu", "ds", "hsteps", "cubic")
    for idx, var in enumerate(the_vars):
        exception._var = var
        var1, var2 = tpath[idx], tpath2[idx]
        if type(var1) != type(var2): raise exception
        if type(var1) == type(""):
            if var1 != var2: raise exception
        if type(var1) == type(1.0):
            if abs(var1 - var2) > eps: raise exception
Example #15
0
def execute(ifile,ofile,err,folder=None):
    # Add folder to names
    if folder is not None:
       if not folder.endswith("/"): folder = folder + "/"
       ifile = folder + ifile
       ofile = folder + ofile
       err   = folder + err
    # Execution file?
    set_EXE()
    check_EXE()
    # Exception
    exception = Exc.CalcFails(Exception)
    exception._var = ofile
    # Execute command
    command = "%s %s 1>%s 2>%s"%(EXE,ifile,ofile,err)
    try   : status  = os.system(command)
    except: raise exception
    return status
Example #16
0
def prepare_dpath(dpath):
    # Read data for each ctc
    for ctc, (pathtype, lines) in dpath.items():
        pathvars = PathVars(pathtype)
        # Read info in lines
        for line in lines:
            line = line.lower()
            key = line.split()[0]
            value = " ".join(line.split()[1:]).lower()
            try:
                pathvars.setvar(key, value)
            except:
                exception = Exc.ReadProblem(Exception)
                exception._file = filename
                exception._var = line.split("\n")[0]
                raise exception
        dpath[ctc] = pathvars
    return dpath
Example #17
0
def genfchk(chk,fchk,err,folder=None):
    # Add folder to names
    if folder is not None:
       if not folder.endswith("/"): folder = folder + "/"
       chk   = folder + chk
       fchk  = folder + fchk
       err   = folder + err
    # fchk tool?
    set_FCHK()
    check_FCHK()
    # Exception
    exception = Exc.CalcFails(Exception)
    exception._var = chk
    # Execute fchk tool
    command = "%s %s %s 1>%s 2>&1"%(FCHK,chk,fchk,err)
    try   : status = os.system(command)
    except: raise exception
    return status
Example #18
0
def get_TSratios(ctc, itcs, V1TS, QTS, ltemp, dall):
    '''
    ratio = QTS(i)/QTS * exp(-dE(i) * beta)
    '''
    exception = Exc.LostConformer(Exception)
    tst_ratios = {}
    for itc, weight in itcs:
        key = PN.struckey(ctc, itc)
        if key not in dall["pfn"].keys():
            exception._var = key
            raise exception
        V0_i, V1_i, Q_i = dall["pfn"][key]
        ratio = [0.0 for T in ltemp]
        dE = (V1_i - V1TS)
        for idx, T in enumerate(ltemp):
            ratio[idx] = weight * Q_i[idx] / QTS[idx] * np.exp(-dE / KB / T)
        tst_ratios[itc] = ratio
    # get individual data
    return tst_ratios
Example #19
0
def highlevel_sp(ctc, itc, keyHL, gtsfile, software, dtesHL, dhighlvl):
    # is calculation needed?
    if keyHL in dhighlvl.keys(): return None
    # folder for calculation and file name
    TMP = PN.TMPHLi % keyHL
    mname = "%s.%s" % (keyHL, "sp")
    # Function for calculation and template
    spc_fnc = get_spc_fnc(software)
    tes = dtesHL.get(software, {}).get(ctc, None)
    if tes is None: raise Exc.NoTemplateGiven(Exception)
    # extra-arguments for spc_fnc
    clean = False  # do not delete files
    bhess = False  # do not calculate hessian (no needed actually)
    eargs = (tes, TMP, clean)
    # Read gts file (Molecule instance)
    molecule = Molecule()
    molecule.set_from_gts(gtsfile)
    # HL-calculation
    out_spc = spc_fnc(molecule._xcc, molecule._symbols, bhess, mname, eargs)
    return out_spc[4]
Example #20
0
    def setup3(self):
        '''
          apply default value to those not defined!
          '''
        # use ics but no ics?
        if self._useics == "yes" and (self._ics is None
                                      or len(self._ics) == 0):
            raise Exc.NoICS(Exception)

        # path variables (via input) - advanced
        if self._fwdir == "default": self._fwdir = None  # ("1-2","++")
        if self._cvt == "default": self._cvt = "yes"
        if self._sct == "default": self._sct = "yes"
        if self._mtype == "default": self._mtype = "pm"
        if self._mu == "default": self._mu = 1.0 / AMU
        if self._cubic == "default": self._cubic = "no"
        if self._eref in ["default", "auto"]: self._eref = None
        if self._paral == "default": self._paral = "no"
        if self._epse == "default": self._epse = 1e-8
        if self._epsg == "default": self._epsg = 1e-4
        if self._useics == "default": self._useics = "yes"
        if self._v1mode == "default": self._v1mode = "grad"
        if self._scterr == "default": self._scterr = 0.0
        if self._e0 in ["default", "auto"]: self._e0 = None
        if self._lowfq == "default": self._lowfq = {}
        if self._muintrpl == "default": self._muintrpl = ("linear", 0)
        if self._qrc == "default": self._qrc = None
        if self._onioml == "default": self._onioml = []
        if self._oniomm == "default": self._oniomm = []
        if self._oniomh == "default": self._oniomh = []

        # setup parallel
        self._paral = do_parallel(self._paral)

        # setup cag
        self.set_cag()

        # useics = yes but there are no ics?
        if self._useics == "yes" and (self._ics is None
                                      or len(self._ics) == 0):
            self._useics = "no"
Example #21
0
def read_gaussian_log(filename, target_level=None):
    if not os.path.exists(filename): return
    # split lines into blocks (in case of Link1)
    blocks = split_gaulog_into_gaublocks(filename)
    # Get info of each block
    data = [get_data_from_gaublock(block) for block in blocks]
    # There is nothing to return
    if data == []: return [None] * 12
    # Localize data with hessian matrix
    IDX = -1
    for idx, data_i in enumerate(data):
        Fcc = data_i[7]
        if Fcc is not None:
            IDX = idx
            break
    # Return the best set of data (the last with the hessian or the last block)
    commands, comment, ch, mtp, symbols, xcc, gcc, Fcc, energies, E_oniom, num_imag, zmat = data[
        IDX]
    # If user does not ask for level, send one of lowest energy
    if target_level is None:
        energies.sort()
        energy, level = energies[0]
    else:
        IDX = None
        exception = Exc.LevelNotFound()
        exception._var = target_level
        for idx, (energy, level) in enumerate(energies):
            if level.lower() == target_level.lower():
                IDX = idx
                break
        if IDX is None: raise exception
        energy, level = energies[IDX]
    # oniom?
    if E_oniom is not None:
        energy = E_oniom
        level = "ONIOM"
    # Return data
    return commands, comment, ch, mtp, symbols, xcc, gcc, Fcc, energy, num_imag, zmat, level
Example #22
0
def set_EXE():
    global EXE
    txt = os.path.dirname(os.path.realpath(__file__))+"/paths.txt"
    # Defined in this file
    if 'EXE' in globals():
        return
    # Try to export it from bashrc
    elif "OrcaExe" in os.environ:
        # in .bashrc: export OrcaExe="$MYHOME/Software/orca_4_0_1_2/orca"
        EXE = os.environ["OrcaExe"]
        return
    # Export it from file
    elif os.path.exists(txt):
        lines = read_file(txt)
        lines = clean_lines(lines,"#",True)
        for line in lines:
            if line == "\n": continue
            name, path = line.split()
            if name == "orca":
                EXE = path
                return
    # Not found
    else: raise Exc.ExeNotDef(Exception)
Example #23
0
def obtain_adipot(tcommon, drst, pathvars):
    print
    print "    Calculating adiabatic potential..."
    print
    ics = pathvars.get_ics()
    if pathvars._useics == "yes" and (ics is None or len(ics) == 0):
        raise Exc.NoICS(Exception)
    # calculate adiabatic potential
    idata = (tcommon, drst, pathvars._eref, ics, pathvars._useics,
             pathvars._lowfq, pathvars._freqscal)
    dMols, ccVadi, icVadi, tuple_cc, tuple_ic, listV0 = ap.path2vadi(*idata)
    # expand tuples
    data_x, lcc_frqs, lcc_tzpe = tuple_cc
    data_x, lic_frqs, lic_tzpe = tuple_ic
    # check data
    fncs.print_string(PS.sadipot_ics(ics, pathvars._useics), 8)
    if pathvars._useics == "yes":
        ok1 = ap.ccvsic_checknfreqs(lcc_frqs, lic_frqs)
        ok2 = ap.ccvsic_checkts(data_x, lcc_frqs, lic_frqs)
        ok3 = ap.ccvsic_checkzpe(lcc_tzpe, lic_tzpe)
        checks = (ok1, ok2, ok3)
        fncs.print_string(PS.sadipot_checks(checks), 8)
        # select spline
        if not ok1 or not ok2: Vadi, pathvars._useics = ccVadi, "no"
        elif pathvars._useics == "yes": Vadi, pathvars._useics = icVadi, "yes"
        else: Vadi, pathvars._useics = ccVadi, "no"
    else:
        Vadi, pathvars._useics = ccVadi, "no"
    # setup spline
    Vadi.setup()
    data4print = (Vadi.xx(), Vadi.yy(), Vadi._sAG, Vadi._VAG, listV0, lcc_tzpe,
                  lic_tzpe, pathvars._eref)
    fncs.print_string(PS.sadipot_table(*data4print), 8)
    # print freqs
    print "      Vibrational frequencies summary: cc (ic) [in cm^-1]:"
    fncs.print_string(PS.sadipot_freqs(Vadi.xx(), lcc_frqs, lic_frqs), 8)
    return dMols, Vadi, pathvars
Example #24
0
def check_FCHK():
    if not os.path.exists(FCHK): raise Exc.ExeNotFound(Exception)
Example #25
0
def check_EXE():
    if not os.path.exists(EXE): raise Exc.ExeNotFound(Exception)
Example #26
0
def read_gauout_old(gauout):
    '''
    Read Gaussian output (data in final message)
    and return important data
    '''
    # check extension
    end_out = (gauout.lower()).endswith(".out")
    end_log = (gauout.lower()).endswith(".log")
    if (not end_out) and (not end_log):
        raise Exc.FileType(Exception)
    # read lines
    lines = read_file(gauout)
    # CHECK FILE IS GAUSSIAN OUT
    correct = False
    for line in lines:
        if "Entering Gaussian System" in line:
           correct = True
           break
    if not correct: raise Exc.FileType(Exception)
    # ONIOM energy?
    try:
       E_ONIOM = None
       for line in lines[::-1]:
           if "ONIOM: extrapolated energy" in line:
               E_ONIOM = float(line.split()[-1])
               break
    except: E_ONIOM = None
    # Get Forces if exists
    key1 = "Forces (Hartrees/Bohr)"
    key2 = "Cartesian Forces:"
    try:
       gcc = []
       for line in extract_string(lines,key1,key2).split("\n")[3:-3]:
           dummy, dummy, gx, gy, gz = line.split()
           gcc += [float(gx),float(gy),float(gz)]
       # forces to gradient
       gcc = [-g_i for g_i in gcc]
    except: gcc = None
    if gcc == []: gcc = None
    # Read string from gaussian output
    DATA_LAST = []
    DATA_WFCC = []
    key1, key2 = "\GINC-","@"
    strings = extract_string(lines,key1,key2,accumulate=True)
    for string in strings:
        lines = "".join([line.strip() for line in string.split()])
        lines = lines.split("\\\\")
        if lines == [""]: return None, None, None, None, None, None

        # lines[3]: ch, mtp, symbols, xcc
        str_geom = lines[3].split("\\")
        ch , mtp = str_geom[0].split(",")
        xcc      = []
        symbols  = []
        ch  = int(ch)
        mtp = int(mtp)
        E   = None
        masses = []
        for line in str_geom[1:]:
            coords = line.split(",")
            if   len(coords) == 4:
               symbol, x, y, z = line.split(",")
            else:
               symbol, tmp, x, y, z = line.split(",")
            xcc += [float(x),float(y),float(z)]
            symbols.append(symbol)
        xcc = [xi/ANGSTROM for xi in xcc] # in bohr
        # lines[4]: energy
        E = float(lines[4].split("HF=")[1].split("\\")[0])
        # Gradient
        if gcc is None or len(gcc) == 0: gcc = [0.0 for x in xcc]
        # Hessian
        Fcc = []
        for idx in range(len(lines)):
            line = lines[idx]
            if "NImag" not in line: continue
            Fcc = [float(fij) for fij in lines[idx+1].split(",")]
        # other lists
        atonums = get_atonums(symbols)
        masses  = atonums2masses(atonums)
        calclevel = ""
        # Does it have hessian?
        if Fcc != []: DATA_WFCC = [xcc, atonums, ch, mtp, E, gcc, Fcc, masses, calclevel]
        # Save data
        DATA_LAST = [xcc, atonums, ch, mtp, E, gcc, Fcc, masses, calclevel]
    # Use ONIOM extrapolated energy if found!
    if E_ONIOM is not None:
       if len(DATA_WFCC) != 0: DATA_WFCC[4] = E_ONIOM
       if len(DATA_LAST) != 0: DATA_LAST[4] = E_ONIOM
    # return
    if DATA_WFCC != []: return DATA_WFCC
    else              : return DATA_LAST
Example #27
0
def read_fchk(fchkfile):
    #------------------------#
    # The labels to look for #
    #------------------------#
    labels     = {}                              ; found_dict    = {}
    labels[0]  = "Number of atoms"               ; found_dict[0] = False
    labels[1]  = "Charge"                        ; found_dict[1] = False
    labels[2]  = "Multiplicity"                  ; found_dict[2] = False
    labels[3]  = "Total Energy"                  ; found_dict[3] = False
    labels[4]  = "Atomic numbers"                ; found_dict[4] = False
    labels[5]  = "Current cartesian coordinates" ; found_dict[5] = False
    labels[6]  = "Real atomic weights"           ; found_dict[6] = False
    labels[7]  = "Cartesian Gradient"            ; found_dict[7] = False
    labels[8]  = "Cartesian Force Constants"     ; found_dict[8] = False
    # mandatory labels in fchk
    idx_basic_labels = [0,1,2,3,4,5,6]
    # initialization
    natoms   = None ; ch     = None ; mtp  = None  ; E = None
    atonums  = []   ; masses = []
    xcc      = []   ; gcc    = []   ; Fcc  = []
    # read file
    lines = read_file(fchkfile)
    # check extension
    end_fchk = (fchkfile.lower()).endswith(".fchk")
    if (not end_fchk): raise Exc.FileType(Exception)
    # CHECK FILE IS FCHK
    correct = False
    for line in lines:
        if line.startswith("Current cartesian coordinates  "):
           correct = True
           break
    if not correct: raise Exc.FileType(Exception)
    # Get level of calculation
    calclevel = " ".join(lines[1].split()[1:])
    # get data from lines
    for idx in range(len(lines)):
        line = lines[idx]
        # Number of atoms
        if line.startswith(labels[0]):
            found_dict[0] = True
            natoms = int(line.split()[-1])
        # Charge
        elif line.startswith(labels[1]):
            found_dict[1] = True
            ch = int(line.split()[-1])
        # Spin multiplicity
        elif line.startswith(labels[2]):
            found_dict[2] = True
            mtp = int(line.split()[-1])
        # Total Energy
        elif line.startswith(labels[3]):
            found_dict[3] = True
            E = float(line.split()[-1])
        # Atomic Numbers
        elif line.startswith(labels[4]):
            found_dict[4] = True
            length = int(line.split()[-1])
            idx2   = idx+1
            while len(atonums) != length:
                  nextline = lines[idx2]
                  atonums += [int(i) for i in nextline.split()]
                  idx2    += 1
        # Cartesian Coordinates
        elif line.startswith(labels[5]):
            found_dict[5] = True
            length = int(line.split()[-1])
            idx2   = idx+1
            while len(xcc) != length:
                  nextline = lines[idx2]
                  xcc     += [float(i) for i in nextline.split()]
                  idx2    += 1
        # List of atomic masses
        elif line.startswith(labels[6]):
            found_dict[6] = True
            length = int(line.split()[-1])
            idx2   = idx+1
            while len(masses) != length:
                  nextline = lines[idx2]
                  masses  += [float(i) for i in nextline.split()]
                  idx2    += 1
        # Cartesian Gradient
        elif line.startswith(labels[7]) and natoms != 1:
            found_dict[7] = True
            length = int(line.split()[-1])
            idx2   = idx+1
            while len(gcc) != length:
                  nextline = lines[idx2]
                  gcc     += [float(i) for i in nextline.split()]
                  idx2    += 1
        # Cartesian Force Constant Matrix
        elif line.startswith(labels[8]) and natoms != 1:
            found_dict[8] = True
            length = int(line.split()[-1])
            idx2   = idx+1
            while len(Fcc) != length:
                  nextline = lines[idx2]
                  Fcc     += [float(fij) for fij in nextline.split()]
                  idx2    += 1
    # Return data
    #if gcc == []: gcc = None
    #if Fcc == []: Fcc = None
    return xcc,atonums,ch,mtp,E,gcc,Fcc,masses, calclevel.strip()
Example #28
0
def read_orcaout(orca_out):
    # Read lines
    lines = read_file(orca_out)
    # CHECK FILE IS ORCA OUT
    correct = False
    for line in lines:
        if "This ORCA versions uses" in line:
            correct = True
            break
    if not correct: raise Exc.FileType(Exception)
    # Initialize
    ch, mtp, E = None, None, None
    xcc, symbols, atonums = [], [], []
    # basis set
    basisset = ""
    try:
        for line in lines:
            if "utilizes the basis" in line:
                basisset = line.split(":")[1]
                break
    except:
        pass
    # hamiltonian
    hamiltonian = ""
    try:
        for idx, line in enumerate(lines):
            if "Hamiltonian:" in line:
                hamiltonian = lines[idx + 1].split()[-1]
                break
    except:
        pass
    # level of calculation
    calclevel = hamiltonian + " " + basisset
    # Get ch, mtp, E
    pos_cart = None
    pos_zmat = None
    for idx in range(len(lines)):
        line = lines[idx]
        if "Total Charge           Charge" in line: ch = int(line.split()[-1])
        if "Multiplicity           Mult" in line: mtp = int(line.split()[-1])
        if "FINAL SINGLE POINT ENERGY " in line: E = float(line.split()[-1])
        if "CARTESIAN COORDINATES (A.U.)" in line: pos_cart = idx
        if "INTERNAL COORDINATES (ANGST" in line: pos_zmat = idx
    # Get xcc, symbols, atonums
    if pos_cart is None:
        sys.exit(
            "Unable to find 'CARTESIAN COORDINATES (A.U.)' label in file!")
    pos_cart += 3
    for line in lines[pos_cart:]:
        line = line.strip()
        if line == "": break
        idx, symbol, atonum, dummy, mass, x, y, z = line.split()
        if symbol == "-": symbol = "XX"
        xcc += [float(x), float(y), float(z)]
        symbols.append(symbol)
        atonums.append(int(atonum.split(".")[0]))
    # data in internal coordinates
    lzmat = None
    if pos_zmat is not None:
        pos_zmat += 2
        lzmat = []
        for idx, line in enumerate(lines[pos_zmat:]):
            line = line.strip()
            if line == "": break
            symbol, atk, atj, ati, dist, angle, dihedral = line.split()
            if symbol == "-": symbol = "XX"
            atk, atj, ati = int(atk) - 1, int(atj) - 1, int(ati) - 1
            dist, angle, dihedral = float(dist), float(angle), float(dihedral)
            if idx == 0: connections, values = (), ()
            elif idx == 1: connections, values = (atk, ), (dist, )
            elif idx == 2: connections, values = (atk, atj), (dist, angle)
            else:
                connections, values = (atk, atj, ati), (dist, angle, dihedral)
            data = (symbol, connections, values)
            lzmat += [data]
    # Return
    return xcc, lzmat, atonums, ch, mtp, E, calclevel.strip()
Example #29
0
def path2vadi(tcommon,drst,Eref=None,ics=None,boolint=False,lowfq={},freqscal=1.0,icsbw=None,icsfw=None,symmetry=None):
    '''
    lowfq: in case of imaginary frequencies
    '''
    # boolint as boolean
    if   boolint in [False,"no","No","n","N",None]: boolint = False
    elif boolint in [True,"yes","YES","y","Y"]    : boolint = True
    # check there are internal coordinates if required
    if boolint and ics in [None,False,[]]: raise Exc.NoICS(Exception)
    # expand data in tcommon
    ch,mtp,atnums,masses,mu = tcommon
    # Sorted labels (by s)
    slabels = sd.sorted_points(drst,hess=True)
    # Reference energy
    if Eref is None: lbw, lfw, sbw, sfw, Eref, Efw = sd.rstlimits(drst)
    # Independent variable
    data_x = [drst[label][0] for label in slabels]
    # mep energy (relative value)
    listV0 = [drst[label][1]-Eref for label in slabels]

    # Initializing data
    lcc_tzpe, lcc_frqs, lcc_Vadi = [], [], []
    lic_tzpe, lic_frqs, lic_Vadi = [], [], []
    dMols = {}

    # Updating data
    for label in slabels:
        # data in drst
        s_i, E_i, xms_i,gms_i,Fms_i,v0_i,v1_i,t_i = drst[label]
        # project gradient
        if s_i == 0.0: bool_pg = False
        else         : bool_pg = True
        # lowfq
        if   s_i == 0.0: dlowfq = {}
        elif s_i  < 0.0: dlowfq = lowfq.get("bw",{})
        elif s_i  > 0.0: dlowfq = lowfq.get("fw",{})
        # mass-scaled --> Cartesian coords
        xcc = fncs.ms2cc_x(xms_i,masses,mu)
        gcc = fncs.ms2cc_g(gms_i,masses,mu)
        Fcc = fncs.ms2cc_F(Fms_i,masses,mu)
        # create Molecule instance
        mol = Molecule()
        mol.setvar(xcc=xcc,gcc=gcc,Fcc=Fcc)
        mol.setvar(atonums=atnums,masses=masses)
        mol.setvar(ch=ch,mtp=mtp,V0=E_i)
        mol.setvar(fscal=freqscal)
        if symmetry is not None:
            mol.setvar(pgroup=symmetry[0])
            mol.setvar(rotsigma=symmetry[1])
        mol.prepare()
        mol.setup(mu,projgrad=bool_pg)
        mol.clean_freqs("cc")       # it may be needed with orca
        mol.deal_lowfq(dlowfq,"cc") # deal with low frequencies
        mol.ana_freqs("cc")         # calculate zpe
        # append data
        lcc_tzpe.append(float(mol._cczpe)   )
        lcc_Vadi.append(mol._ccV1 - Eref    )
        lcc_frqs.append(list(mol._ccfreqs))
        # internal coordinates
        if boolint:
           if   s_i < 0.0 and icsbw is not None: mol.icfreqs(icsbw,bool_pg)
           elif s_i > 0.0 and icsfw is not None: mol.icfreqs(icsfw,bool_pg)
           else                                : mol.icfreqs(ics  ,bool_pg)
           mol.deal_lowfq(dlowfq,"ic")
           mol.ana_freqs("ic")
           # append data
           lic_tzpe.append(float(mol._iczpe) )
           lic_Vadi.append(mol._icV1 - Eref  )
           lic_frqs.append(list(mol._icfreqs))
        # save instance
        dMols[label] = (s_i,mol)

    # package data
    tuple_cc = (data_x,lcc_frqs,lcc_tzpe)
    tuple_ic = (data_x,lic_frqs,lic_tzpe)
    # Generate splines
    Vadi_cc = VadiSpline(data_x,lcc_Vadi)
    if boolint: Vadi_ic = VadiSpline(data_x,lic_Vadi)
    else      : Vadi_ic = None
    # Return data
    return dMols, Vadi_cc, Vadi_ic, tuple_cc, tuple_ic, listV0
Example #30
0
def pilgrim_spc(xcc, symbols, bhessian, mname, eargs):
    # expand extra-args
    if len(eargs) == 1:
        spc_template = eargs[0]
        folder, clean = None, False
    elif len(eargs) == 2:
        spc_template, folder = eargs
        clean = False
    elif len(eargs) == 3:
        spc_template, folder, clean = eargs
    elif len(eargs) == 5:
        spc_template, folder, clean, frozen, oniom_layers = eargs
    # no template??
    if spc_template is None: raise Exc.NoTemplateGiven(Exception)
    # create folder
    if folder is not None:
        if not os.path.exists(folder): os.mkdir(folder)
    # Calculate gradient&hessian or just gradient
    if bhessian: inkey3 = "! EnGrad Freq "
    else: inkey3 = "! EnGrad      "
    # names of files
    wname, ifile, ofile, engrad, hess, gbw, err = ITF.iofiles(mname, folder)
    # Input
    string_ifile = ""
    for line in spc_template.split("\n"):
        if key1 in line:
            line = ""
            for idx, symbol in enumerate(symbols):
                x, y, z = fncs.xyz(xcc, idx)
                linedata = (symbol, x * pc.ANGSTROM, y * pc.ANGSTROM,
                            z * pc.ANGSTROM)
                line += "%2s   %+11.6f  %+11.6f  %+11.6f\n" % linedata
        if key2 in line:
            pos = line.find(key2)
            line = line[0:pos] + wname + line[pos + len(key2):]
        if key3 in line:
            pos = line.find(key3)
            line = line[0:pos] + inkey3 + line[pos + len(key3):]
        # Add \n to line
        if not line.endswith("\n"): line += "\n"
        string_ifile += line
    ff.write_file(ifile, string_ifile)
    # Send calculation
    status = ITF.execute(ifile, ofile, err)
    # # Sleep 0.5 seconds, so Orca can write the files
    # time.sleep(0.5)
    # Check output
    exception = Exc.CalcFails(Exception)
    exception._var = ofile
    if not ITF.normal_termination(ofile): raise exception
    # Read data
    xcc, atonums, ch, mtp, E, gcc, Fcc, masses, clevel = ff.read_orca(ofile)
    # Remove files
    if clean:
        files = os.listdir(folder)
        files = [fff for fff in files if fff.startswith(name)]
        files = [fff for fff in files if not fff.endswith(".inp")]
        files = [fff for fff in files if not fff.endswith(".out")]
        files = [fff for fff in files if not fff.endswith(".engrad")]
        files = [fff for fff in files if not fff.endswith(".hess")]
        for fff in files:
            os.remove(folder + fff)
    return xcc, atonums, ch, mtp, E, gcc, Fcc, masses