Exemple #1
0
def get_itargets(targets, dpath, dctc):
    '''
    get individual targets
    '''
    # Targets?
    if (len(targets) == 0) or ("*" in targets): targets = dpath.keys()

    # generate list of individual targets
    itargets = []
    for target in targets:
        ctc, itc = PN.name2data(target)
        # check ctc
        if ctc not in dctc.keys():
            fncs.print_string("* '%s' not in '%s'" % (target, PN.IFILE1), 3)
            print("")
            continue
        if ctc not in dpath.keys():
            fncs.print_string("* '%s' not in '%s'" % (target, PN.IFILE3), 3)
            print("")
            continue
        # list of itcs for the ctc
        itclist = [itc_i for itc_i, weight_i in dctc[ctc]._itcs]
        # add itc
        if itc is None:
            itargets += [
                PN.struckey(ctc, itc) for itc, weight in dctc[ctc]._itcs
            ]
        elif itc in itclist:
            itargets += [PN.struckey(ctc, itc)]
    return sorted(itargets)
Exemple #2
0
def obtain_cvt(dMols,
               points,
               VadiSpl,
               temps,
               pathvars,
               si=-float("inf"),
               sj=+float("inf"),
               dcfs={}):
    print
    print "    Calculating CVT variational coefficient..."
    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
Exemple #3
0
def dctc_from_DIR1(gtsfiles):
    # list of gts files
    print("  - File '%s' does not exist but '%s' is not empty!" %
          (PN.IFILE1, PN.DIR1))
    print("")
    # classify gts files according to ctc
    dctc = {}
    for gtsfile in gtsfiles:
        gts_name = gtsname(gtsfile, "name")
        gts_full = gtsname(gtsfile, "full")
        ctc, itc = gts_name.split(".")[0:2]
        dctc[ctc] = dctc.get(ctc, []) + [gts_full]
    # generate real dctc
    print("     number of structures: %i" % len(dctc.keys()))
    print("")
    ml = max([len(key) for key in dctc.keys()] + [1])
    for ctc, gtsfiles in dctc.items():
        print("       * %%-%is (num gts files: %%2i)" % ml %
              (ctc, len(gtsfiles)))
        CTC = ClusterConf(ctc)
        status, string = CTC.set_from_gtsfiles(gtsfiles)
        if status == -1:
            print("         INCONSISTENCES!")
            print_string(string, 9)
            answer = input("         Remove gts files (y/N)?")
            if answer.strip().lower() in ["y", "yes"]:
                for gts in gtsfiles:
                    os.remove(gts)
            else:
                raise Exc.ABORTED
        dctc[ctc] = CTC
    print("")
    return dctc
Exemple #4
0
def print_summary(targets, LINES):
    # Print lines for KMC
    string = ""
    string += "=================\n"
    string += " FITTING SUMMARY \n"
    string += "=================\n"
    string += "\n"
    for X in METHODS:
        bloque_X = ""
        for anatype in [1, 2, 3, 4, 5]:
            bloque_at = ""
            for rcname in targets:
                for direc in "fw,bw".split(","):
                    key = (anatype, X, rcname, direc)
                    line = LINES.get(key, None)
                    if line is None: continue
                    bloque_at += line
                    #bloque_at += line.split("#")[0]+"\n"
            if bloque_at == "": continue
            bloque_X += bloque_at + "\n"
        if bloque_X == "": continue
        # add to string
        string += "%s\n" % PS.KEYNICE[X]
        string += "\n" + bloque_X + "\n"
    print_string(string, NINIT)
Exemple #5
0
def check_ctc(targets, dctc):
    updated = []
    for ctc in targets:
        if ctc not in dctc.keys():
            print_string(
                "Selected target (%s) not found as a STRUC. Skipped!" % ctc, 2)
            print("")
            continue
        updated.append(ctc)
    return updated
Exemple #6
0
def get_path_sctconv(itarget, gtsTS, pathvars, tsoftware, ltemp, TMP,
                     plotfile):
    # assert no DLEVEL will be done (just in case)
    pathvars._dlevel = None
    # go ahead
    convlist_sct = []
    convlist_lim = []
    for step in range(pathvars._sctmns + 2):
        if step == 0: decrease = True
        else: decrease = False
        tcommon, drst, pathvars = calc_mep(itarget, gtsTS, pathvars, tsoftware,
                                           TMP, decrease)
        dcfs, pathvars = calc_coefs(itarget, tcommon, drst, pathvars, ltemp,
                                    plotfile)
        # expand data
        lbw, lfw, sbw, sfw, Ebw, Efw = sd.rstlimits(drst)
        SCT = dcfs["sct"]
        del drst
        # Save data only for lower temperature
        convlist_sct.append(SCT[0])
        convlist_lim.append((sbw, sfw))
        # print convergence table
        fncs.print_string(
            PS.ssct_convergence(convlist_sct, convlist_lim, pathvars._scterr),
            4)
        # Check convergence
        if len(convlist_sct) > 1:
            SCT_a = convlist_sct[-1]
            SCT_b = convlist_sct[-2]
            dif100 = 100 * abs(SCT_a - SCT_b) / SCT_a
            if dif100 < pathvars._scterr: break
        # last  step and not converged
        if step + 1 == pathvars._sctmns + 2:
            print "    WARNING: SCT has not converged but 'sctmns' was reached!"
            print
            break
        # increase variables sbw and sfw
        sbw1, sfw1 = pathvars._sbw, pathvars._sfw
        pathvars.increase_svals(Ebw, Efw)
        sbw2, sfw2 = pathvars._sbw, pathvars._sfw
        if abs(sbw1 - sbw2) < EPS_MEPS and abs(sfw1 - sfw2) < EPS_MEPS:
            print "    WARNING: MEP cannot be increased and SCT is not converged!"
            print "    Maybe epse and epsg criteria should be modified..."
            print
            break
        else:
            print "    MEP will be increased for SCT convergence:"
            print
            print "        sbw: %+8.4f --> %+8.4f bohr" % (sbw1, sbw2)
            print "        sfw: %+8.4f --> %+8.4f bohr" % (sfw1, sfw2)
            print
            print "   =================================================="
            print
    return dcfs
Exemple #7
0
def calc_mep(itarget, gtsTS, pathvars, tsoftware, TMP, decrease=False):
    '''
     if decrease = True, MEP is reduced hsteps steps
    '''
    # data in name
    ctc, itc = PN.name2data(itarget)
    # calculate path
    tcommon, drst, pathvars = obtain_mep(itarget, gtsTS, pathvars, tsoftware,
                                         TMP)
    # decrease mep??
    if decrease:
        sbw1, sfw1 = pathvars._sbw, pathvars._sfw
        pathvars.decrease_svals()
        sbw2, sfw2 = pathvars._sbw, pathvars._sfw
        print "    MEP will be reduced to check SCT convergence:"
        print
        print "        sbw: %+8.4f --> %+8.4f bohr" % (sbw1, sbw2)
        print "        sfw: %+8.4f --> %+8.4f bohr" % (sfw1, sfw2)
        print
        drst = {
            label: data
            for label, data in drst.items()
            if in_interval(data[0], sbw2, sfw2)
        }
    # DLEVEL??
    if pathvars._dlevel is not None:
        print "    Applying Dual-Level..."
        print
        dlevel_xy = [(find_label_in_rst(x, drst)[0], y)
                     for x, y in pathvars._dlevel.items()]
        dlevel_xy = [(x, y) for x, y in dlevel_xy if x is not None]
        # Print points (sorted by s value)
        dummy = [(drst[xx][0], idx) for idx, (xx, yy) in enumerate(dlevel_xy)]
        dummy.sort()
        for s_i, idx_i in dummy:
            xx_i, yy_i = dlevel_xy[idx_i]
            print "             %+8.4f bohr (%-6s) --> %.7f hartree" % (
                s_i, xx_i, yy_i)
        print
        # interpolation
        drst, points, xx, yyll, yyhl = ispe.ispe(tcommon,
                                                 drst,
                                                 dlevel_xy,
                                                 tension=0.0)
        tdleveldata = (points, xx, yyll, yyhl)
        # table new values
        fncs.print_string(
            PS.smep_tableDLEVEL(drst, tdleveldata, pathvars._eref), 4)
    else:
        # Print table
        fncs.print_string(PS.smep_table(drst, pathvars._eref), 4)
    return tcommon, drst, pathvars
Exemple #8
0
def obtain_cag(Vadi, ltemp, lscvt=None, dcfs={}):
    print
    print "    Calculating CAG coefficient..."
    print
    dE_cagtst, cagtst = cag.calc_cag(ltemp, Vadi)
    dcfs["cagtst"] = cagtst
    if lscvt is not None:
        dE_cagcvt, cagcvt = cag.calc_cag(ltemp, Vadi, lscvt)
        dcfs["cagcvt"] = cagcvt
    else:
        dE_cagcvt = None
        cagcvt = None
    fncs.print_string(
        PS.scag_table(ltemp, dE_cagtst, cagtst, dE_cagcvt, cagcvt), 8)
    return dcfs
Exemple #9
0
def obtain_cag(Vadi, ltemp, E0, VAG, lscvt=None, dcfs={}):
    print("")
    fncs.print_string("Calculating CAG coefficient...", 4)
    print("")
    # calculate CAGTST
    dE_cagtst, cagtst = cag.calc_cag(ltemp, Vadi)
    # calculate CAGCVT
    if lscvt is not None: dE_cagcvt, cagcvt = cag.calc_cag(ltemp, Vadi, lscvt)
    else: dE_cagcvt, cagcvt = None, None
    # In case E0 > VAG
    if E0 >= VAG:
        cagtst = list([1.0 for T in ltemp])
        if cagcvt is not None: cagcvt = list([1.0 for T in ltemp])
    # print data
    fncs.print_string(
        PS.scag_table(ltemp, dE_cagtst, cagtst, dE_cagcvt, cagcvt), 8)
    # save in dict and return
    if cagtst is not None: dcfs["cagtst"] = cagtst
    if cagcvt is not None: dcfs["cagcvt"] = cagcvt
    return dcfs
Exemple #10
0
def main(idata,status,case):

    stat2check = [2,5]
    mustexist  = []
    tocreate   = []
    #-------------------------------------------------------#
    # Read Pilgrim input files, check file/folder status    #
    # and expand tuple 'case'                               #
    #-------------------------------------------------------#
    # expand data
    (dctc,dimasses), ltemp, dpath, (dtesLL,dtesHL), dchem, tkmc, ddlevel = idata
    # status ok?
    fstatus = status_check(status,stat2check)
    if fstatus == -1: exit()
    # existency of folders
    fstatus = ffchecking(mustexist,tocreate)
    if fstatus == -1: exit()
    # expand case
    (dof,hlf,plotfile),dlevel,software = case
    #-------------------------------------------------------#

    # read dofs
    dall, ltemp = RW.read_alldata(dof)
    # get saved reactions
    print_string(PS.skies_summary(dchem,dall),5)

    # Ask user which reactions
    count = 0
    while True:
         # Ask user for reactions
         bool_end,bool_cont,reaction1,reaction2 = ask_for_reactions(dchem)
         print("")
         print("")
         if bool_end : break
         if bool_cont: continue
         kies_from_pair_of_reactions(reaction1,reaction2,ltemp,dchem,dctc,dall)
Exemple #11
0
def kies_from_pair_of_reactions(reactionH,reactionD,ltemp,dchem,dctc,dall):

    # a) Deal with reaction without isotopes
    rcnameH, dirH = reactionH.split(".")[0:2]
    RsH,TSH,PsH = dchem[rcnameH]
    chemreacH = ChemReaction(rcnameH,RsH,TSH,PsH,ltemp,dctc)
    chemreacH.external_data(dall)


    # b) Deal with reaction with isotopes
    rcnameD, dirD = reactionD.split(".")[0:2]
    RsD,TSD,PsD = dchem[rcnameD]
    chemreacD = ChemReaction(rcnameD,RsD,TSD,PsD,ltemp,dctc)
    chemreacD.external_data(dall)

    # c) chi_i's, transmission coefficients, anharmonicity, rate constants
    chemreacH.obtain_pfns()
    chemreacD.obtain_pfns()
    chemreacH.calculate_transcoeffs()
    chemreacD.calculate_transcoeffs()
    chemreacH.calculate_anharmonicity()
    chemreacD.calculate_anharmonicity()
    chemreacH.calculate_rateconstants()
    chemreacD.calculate_rateconstants()

    #lXH = chemreacH._tschi.keys()
    #lXD = chemreacD._tschi.keys()

    # d) translational, rovibrational and torsional KIES
    print_string(PS.skies_definitions(),5)
    kies_tr,kies_rv,kies_el,kies_tor = contrib_tr_rv_el_tor(chemreacH,chemreacD,dirH,dirD)
    print_string(PS.skies_basiccontris(ltemp,kies_tr,kies_rv,kies_tor),5)

    # e) vtun, total and total with anharmonicity
    kies_vtun, kies_tot = contrib_vtun_tot(chemreacH,chemreacD,dirH,dirD,kies_tr,kies_rv,kies_tor)
    print_string(PS.skies_vtun_tot(ltemp,kies_vtun,kies_tot),5)

    # f) individual contributions
    ikies_rv, ikies_vtun = contrib_ind_rv_vtun(chemreacH,chemreacD,dirH,dirD,kies_rv)
    pjh, pjd             = contrib_pjd_pjh(chemreacH,chemreacD,dirH,dirD,\
                           kies_rv,kies_vtun,ikies_rv,ikies_vtun)
    totkies_j,totkiest_j = contrib_totikies(pjh,pjd,kies_tot)

    print_string(PS.skies_indkies(ltemp,ikies_rv,ikies_vtun,pjh,pjd,totkies_j,totkiest_j),5)
Exemple #12
0
def factors_from_TS(TS, V1TS, QTS, ltemp, dctc, dall):
    # list of itcs
    ctc, itc = PN.name2data(TS)
    if itc is None: itcs = dctc[ctc]._itcs
    else: itcs = [(itc, 1)]
    # get TST ratios
    tst_ratios = get_TSratios(ctc, itcs, V1TS, QTS, ltemp, dall)
    # print TST ratios
    print_string(PS.srcons_tstratios(ltemp, tst_ratios), 7)
    # get total correction factors
    corrfactors = get_corrfactors(ltemp, ctc, itcs, dall, tst_ratios)
    # print correction factors
    print_string(PS.string_corrfactors(ltemp, corrfactors), 7)
    # print VTST contributions
    print_string(PS.srcons_vtstratios(ltemp, tst_ratios, corrfactors), 7)
    return tst_ratios, corrfactors
Exemple #13
0
def execute_pfn(itargets, dchem, idata, status, case):
    reactions = set([])
    for target in itargets:
        ctc1, itc1 = PN.name2data(target)
        the_reaction = None
        for reaction, (Rs, TS, Ps) in dchem.items():
            try:
                ctc2, itc2 = PN.name2data(TS)
            except:
                continue
            if ctc1 == ctc2:
                the_reaction = reaction
                if itc1 == itc2: break
        if the_reaction is not None: reactions.add(the_reaction)
    if len(reactions) == 0: return
    reactions = sorted(list(reactions))

    fncs.print_string(
        "The selected transitions states are involved in defined reactions!",
        3)
    pfn_targets = set([])
    for reaction in reactions:
        fncs.print_string("* %s" % reaction, 6)
        Rs, TS, Ps = dchem[reaction]
        for xx in Rs + [TS] + Ps:
            pfn_targets.add(PN.name2data(xx)[0])
    if len(pfn_targets) == 0: return
    pfn_targets = sorted(list(pfn_targets))
    print("")

    import opt_pfn as pfn
    fncs.print_string("Calculating partition functions for the next targets:",
                      3)
    for target in pfn_targets:
        fncs.print_string("* %s" % target, 6)
    print("")
    pfn.main(idata, status, case, targets=pfn_targets)
Exemple #14
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
Exemple #15
0
def main(idata, status):

    stat2check = []
    mustexist = []
    tocreate = []

    #-------------------------------------------------------#
    # Read Pilgrim input files and check file/folder status #
    #-------------------------------------------------------#
    # expand data
    (dctc, dimasses), ltemp, dpath, (dtesLL,
                                     dtesHL), dchem, dkmc, ddlevel = idata
    # status ok?
    fstatus = status_check(status, [])
    if fstatus == -1: exit()
    # special warning
    if status[0] == -1:
        print("     WARNING! '%s' file not found." % PN.IFILE1)
        print("     In order to generate it, run")
        print("        pilgrim --gather")
    # existency of folders
    fstatus = ffchecking(mustexist=[], tocreate=[])
    if fstatus == -1: exit()
    #-------------------------------------------------------#

    # print menu
    print_string(MENU, 1)

    # setup dpath
    for ctc in dpath.keys():
        dpath[ctc].setup1()
        dpath[ctc].setup2()

    # interactive menu
    dbool = {}
    while True:
        set_completer(1)
        line = input(ILINE1).split()
        if len(line) == 0: continue
        command = line[0].lower()
        try:
            var = line[1].lower()
        except:
            var = None
        try:
            val = line[2:]
        except:
            val = None
        # update list of transition states
        lts = [ctc for ctc in dctc.keys() if dctc[ctc]._type == 1]
        # user ask for help
        if command == "help":
            if var is None: print_string(MENU, 3)
            elif var == "temp": print_string(HELP_temp, 6)
            elif var == "path": print_string(HELP_path, 6)
            elif var == "chem": print_string(HELP_chem, 6)
            elif var == "kmc": print_string(HELP_kmc, 6)
            elif var == "dlevel": print_string(HELP_dlevel, 6)
            elif var == "isomass": print_string(HELP_isomass, 6)
            elif var == "struc": print_string(HELP_struc, 6)
        # user ask for list
        elif command == "ls":
            if var == "struc": ls_struc(dctc)
            elif var == "temp": ls_temp(ltemp)
            elif var == "path": ls_path(dpath)
            elif var == "chem": ls_chem(dchem)
            elif var == "kmc": ls_kmc(dkmc)
            elif var == "dlevel": ls_dlevel(ddlevel)
            elif var == "isomass": ls_isomass(dimasses)
            else: continue
        # add
        elif command == "add":
            if var == "temp": ltemp = add_temp(val, ltemp)
            elif var == "path":
                dpath, dtesLL = add_path(val, dpath, dctc, dtesLL, lts)
            elif var == "chem":
                dchem = add_chem(val, dchem)
            elif var == "kmc":
                dkmc = add_kmc(val, dkmc, dchem)
            elif var == "dlevel":
                ddlevel, dtesHL = add_dlevel(val, ddlevel, dctc, dtesHL)
            elif var == "isomass":
                dimasses = add_isomass(val, dimasses)
            dbool[var] = True
        # mod
        elif command == "mod":
            if var == "path":
                dpath, dtesLL = add_path(val,
                                         dpath,
                                         dctc,
                                         dtesLL,
                                         lts,
                                         mod=True)
            elif var == "struc":
                dctc = mod_struc(val, dctc, dimasses)
            elif var == "kmc":
                dkmc = mod_kmc(val, dkmc, dchem)
            dbool[var] = True
        # rm
        elif command == "rm":
            if var == "temp": ltemp = rm_temp(val, ltemp)
            elif var == "path": dpath = rm_path(val, dpath)
            elif var == "chem": dchem = rm_chem(val, dchem)
            elif var == "dlevel": ddlevel = rm_dlevel(val, ddlevel)
            elif var == "struc": dctc = rm_struc(val, dctc)
            elif var == "isomass": dimasses = rm_isomass(val, dimasses)
            elif var == "kmc": dkmc = rm_kmc(val, dkmc)
            dbool[var] = True
        # user ask for finishing
        elif command in END:
            if dbool != {}:
                print("")
                print("  (Re)Writing files:")
                if dbool.get("isomass", False) or dbool.get("struc", False):
                    print("     %s" % PN.IFILE1)
                    RW.write_ctc(dctc, dimasses)
                if dbool.get("temp", False):
                    print("     %s" % PN.IFILE2)
                    RW.write_temp(ltemp)
                if dbool.get("path", False):
                    print("     %s" % PN.IFILE3)
                    RW.write_path(dpath)
                if dbool.get("path", False) or dbool.get("dlevel", False):
                    print("     %s" % PN.IFILE4)
                    RW.write_tes(dtesLL, dtesHL)
                if dbool.get("chem", False):
                    print("     %s" % PN.IFILE5)
                    RW.write_chem(dchem)
                if dbool.get("kmc", False):
                    print("     %s" % PN.IFILE6)
                    RW.write_kmc(dkmc)
                if dbool.get("dlevel", False):
                    print("     %s" % PN.IFILE7)
                    RW.write_dlevel(ddlevel)
                print("")
            break
        # user ask for nothing
        else:
            continue
Exemple #16
0
def basicinfo_reaction(Rs, TS, Ps, dctc, dimasses):
    # Equation of the reaction
    string = ""
    string += "  equation   : "
    string += " + ".join(Rs)
    string += " --> "
    if TS is not None: string += TS
    string += " --> "
    string += " + ".join(Ps)
    string += "\n\n"
    # Identify reactants, transition state and products
    string += "  reactant(s)     : %s\n" % (" + ".join(Rs))
    if TS is not None: string += "  transition state: %s\n" % TS
    string += "  product(s)      : %s\n" % (" + ".join(Ps))
    string += "\n"
    if len(Rs) == 2 and Rs[0] == Rs[1]:
        string += "  The two reactants are equal.\n"
        string += "  Forward rate constants will be multiplied by 2\n"
        string += "\n"
    if len(Ps) == 2 and Ps[0] == Ps[1]:
        string += "  The two products are equal.\n"
        string += "  Backward rate constants will be multiplied by 2\n"
        string += "\n"
    print_string(string, 5)

    # get length of name
    not_in_dctc = []
    data = []
    ml = 4
    for target in Rs + [TS] + Ps:
        if target is None: continue
        # ctc and itc name
        if "." in target: ctc, itc = target.split(".")
        else: ctc, itc = target, None
        # list of itcs
        if itc is None:
            if ctc in dctc.keys(): itcs = dctc[ctc]._itcs
            else: itcs = None
        else: itcs = [(itc, 1)]
        # save data?
        if itcs is None:
            not_in_dctc.append(target)
            continue
        data.append((target, itcs))
        if len(target) > ml: ml = len(target)

    # anything not defined in dctc?
    if len(not_in_dctc) != 0:
        string = "The following compounds are not defined in '%s':\n" % PN.IFILE1
        for target in not_in_dctc:
            string += "   * %s\n" % target
            if target in Rs: Rs = []
            if target in Ps: Ps = []
        print_string(string, 7)

    # head of table and division line
    head = (" %%%is | conformer | weight" % ml) % "Name"
    division = "-" * len(head)
    # listing conformers and weights
    string = "Conformational flexibility:\n"
    string += "\n"
    string += "   " + division + "\n"
    string += "   " + head + "\n"
    string += "   " + division + "\n"
    for target, itcs in data:
        for idx, (itc, weight) in enumerate(itcs):
            if idx == 0:
                string += "   " + (" %%%is " %
                                   ml) % target + "|    %3s    |  %2i  \n" % (
                                       itc, weight)
            else:
                string += "   " + (
                    " %%%is " % ml) % "" + "|    %3s    |  %2i  \n" % (itc,
                                                                       weight)
        string += "   " + division + "\n"
    print_string(string, 7)

    # Conservation of mass/ch
    string, conserved = check_balance(dctc, dimasses, Rs, TS, Ps)
    print_string(string, 7)

    return conserved, not_in_dctc
Exemple #17
0
        for unkn in unknown:
            print "      * %s" % unkn
        print

    # read dof
    dall = RW.read_alldata(dof, ltemp)[0]

    #--------------------------------#
    # Calculations for each reaction #
    #--------------------------------#
    for rcname in targets:
        # pof file
        pof = PN.get_pof(dlevel, "rcons", rcname)
        sys.stdout = Logger(pof, "w", True)
        # print title
        print_string(PS.title_rcons(rcname, pof), 3)
        # get data
        Rs, TS, Ps = dchem[rcname]
        # Rs = Ps?
        wfw, wbw = 1, 1
        if len(Rs) == 2 and Rs[0] == Rs[1]: wfw *= 2
        if len(Ps) == 2 and Ps[0] == Ps[1]: wbw *= 2
        # basic info
        allright, not_in_dctc = basicinfo_reaction(Rs, TS, Ps, dctc, dimasses)
        if not allright: continue
        # clean data
        if len(set(not_in_dctc).intersection(Rs)) != 0: Rs = []
        if len(set(not_in_dctc).intersection(Ps)) != 0: Ps = []
        if TS in not_in_dctc: TS = None
        nR = len(Rs)
        nP = len(Ps)
Exemple #18
0
def main():
    date = time.strftime("%Y/%m/%d %H:%M")
    t1 = time.time()

    # Read user arguments
    user_args = sys.argv[1:]
    if len(user_args) == 0:
       print PROGNAME
       print AUTHORINFO
       print_string(HELP_main,2)
       return
    dargs = classify_args(user_args)

    # User asked for version
    if   "version"    in dargs.keys():
       print "Current version: %s"%VERSION
       return

    # User asked for help
    elif "help"    in dargs.keys():
       print PROGNAME
       print AUTHORINFO
       if len(dargs["help"]) == 0   : print_string(HELP_main  ,2)
       if "gather"  in dargs["help"]: print_string(HELP_gather,1)
       if "input"   in dargs["help"]: print_string(HELP_input ,1)
       if "ics"     in dargs["help"]: print_string(HELP_ics   ,1)
       if "pfn"     in dargs["help"]: print_string(HELP_pfn   ,1)
       if "path"    in dargs["help"]: print_string(HELP_path  ,1)
       if "hlcalc"  in dargs["help"]: print_string(HELP_hlcalc,1)
       if "rcons"   in dargs["help"]: print_string(HELP_rcons ,1)
       if "fit"     in dargs["help"]: print_string(HELP_fit   ,1)
       if "kmc"     in dargs["help"]: print_string(HELP_kmc   ,1)
       if "plot"    in dargs["help"]: print_string(HELP_plot  ,1)
       return

    # Print logo and current date
    print PROGNAME
    print AUTHORINFO
    print
    print " -----------------------------------------------------------"
    print "  Current date: %s"%date
    print " -----------------------------------------------------------"
    print 

    # check some arguments
    dargs    = check_ics(dargs)
    software = check_sft(dargs)
    dlevel   = check_dlevel(dargs)

    # --software used properly
    if software is None:
       print "  Software option has to be followed by an argument!"
       print
       exit()

    # Act according user argument
    IN_OPTS = False
    for option in "ls,gather,input,ics,pfn,path,hlcalc,rcons,kmc,fit,plot".split(","):
        if option not in dargs.keys(): continue
        IN_OPTS = True
        # read input files and print table
        idata, status, string = get_input_data()
        print_string(string,nbs=3)
        # data files according to case
        datafiles,string = dlevel_to_files(dlevel)
        if option in "pfn,path,hlcalc,rcons,kmc,fit,plot".split(","):
           print_string(string,nbs=3)
        case = (datafiles,dlevel,software)
        # execute pilgrim with option
        print  " ==========================================================="
        print  " ||  EXECUTING PILGRIM WITH --%-6s                      ||"%option
        print  " ==========================================================="
        print
        if   option == "ls"    :  gather.ls_struc(idata[0][0])
        elif option == "gather":  gather.main(idata,status                      )
        elif option == "input" : inpmenu.main(idata,status                      )
        elif option == "ics"   :     ics.main(idata,status,*dargs["ics"   ]     )
        elif option == "pfn"   :     pfn.main(idata,status,case, dargs["pfn"   ])
        elif option == "path"  :    path.main(idata,status,case, dargs["path"  ])
        elif option == "hlcalc":  hlcalc.main(idata,status,case, dargs["hlcalc"])
        elif option == "rcons" :   rcons.main(idata,status,case, dargs["rcons" ])
        elif option == "kmc"   :     kmc.main(idata,status,case                 )
        elif option == "fit"   :     fit.main(idata,status,case, dargs["fit"   ])
        elif option == "plot"  :    plot.main(             case, dargs["plot"  ])
        print
        print " ===========================================================\n"
        break

    # User asked for nothing. Print help!
    if not IN_OPTS: print_string(HELP_main,2); return


    # Print elapsed time
    t2 = time.time()
    timeline = "Total Elapsed Time: %5.1f %5s |"%time2human(t2-t1,"secs")
    print "                            "+timeline
    print "                            "+"-"*len(timeline)
Exemple #19
0
    #-------------------------------------------------------#
    # expand data
    (dctc, dimasses), ltemp, dpath, (dtesLL,
                                     dtesHL), dchem, tkmc, ddlevel = idata
    # status ok?
    fstatus = status_check(status, stat2check)
    if fstatus == -1: exit()
    # existency of folders
    fstatus = ffchecking(mustexist, tocreate)
    if fstatus == -1: exit()
    # expand case
    (dof, hlf, plotfile), dlevel, software = case
    #-------------------------------------------------------#

    # print selected software
    fncs.print_string("Selected software: %s" % software, 3)
    print("")

    # read high level file
    if dlevel: dhighlvl = RW.read_highlevelfile(hlf)
    else: dhighlvl = {}

    # update targets
    if targets == [] or targets == "*": targets = dpath.keys()
    itargets = get_itargets(targets, dpath, dctc)

    # Print targets
    if len(itargets) != 0:
        fncs.print_string("The paths will be calculated for:", 3)
        for idx in range(0, len(itargets), 4):
            fncs.print_string("%s" % (", ".join(itargets[idx:idx + 4])), 7)
Exemple #20
0
def main():
    cdate = time.strftime("%Y-%m-%d")
    ctime = time.strftime("%H:%M:%S")
    t1 = time.time()

    # Read user arguments
    user_args = sys.argv[1:]
    if len(user_args) == 0:
        print(PROGNAME)
        print(PROGHEAD)
        print(AUTHORINFO)
        print_string(HELP_main, 2)
        return
    dargs = classify_args(user_args)

    # User asked for version
    if "version" in dargs.keys() or "-v" in user_args:
        print("Current version: %s" % VERSION)
        return

    # User asked for help
    elif "help" in dargs.keys():
        print(PROGNAME)
        print(PROGHEAD)
        print(AUTHORINFO)
        if len(dargs["help"]) == 0: print_string(HELP_main, 2)
        if "gather" in dargs["help"]: print_string(HELP_gather, 1)
        if "input" in dargs["help"]: print_string(HELP_input, 1)
        if "ics" in dargs["help"]: print_string(HELP_ics, 1)
        if "pfn" in dargs["help"]: print_string(HELP_pfn, 1)
        if "path" in dargs["help"]: print_string(HELP_path, 1)
        if "hlcalc" in dargs["help"]: print_string(HELP_hlcalc, 1)
        if "rcons" in dargs["help"]: print_string(HELP_rcons, 1)
        if "fit" in dargs["help"]: print_string(HELP_fit, 1)
        if "kmc" in dargs["help"]: print_string(HELP_kmc, 1)
        if "plot" in dargs["help"]: print_string(HELP_plot, 1)
        if "kies" in dargs["help"]: print_string(HELP_kies, 1)
        return

    # Print logo and current date
    string_head = PROGNAME + "\n" + PROGHEAD + "\n" + AUTHORINFO + "\n" + "\n"
    string_head += " -----------------------------------------------------------\n"
    string_head += exe_info()
    string_head += " -----------------------------------------------------------\n\n"
    print(string_head)

    # check some arguments
    dargs = check_ics(dargs)
    software = check_sft(dargs)
    dlevel = check_dlevel(dargs)

    # --software used properly
    if software is None:
        print("  Software option has to be followed by an argument!")
        print("")
        exit()

    # Act according user argument
    IN_OPTS = False
    for option in "ls,gather,input,ics,pfn,path,hlcalc,rcons,kmc,fit,plot,kies".split(
            ","):
        if option not in dargs.keys(): continue
        IN_OPTS = True
        # read input files and print table
        idata, status, string = get_input_data()
        print_string(string, nbs=3)
        # data files according to case
        datafiles, string = dlevel_to_files(dlevel)
        if option in "pfn,path,hlcalc,rcons,kmc,fit,plot".split(","):
            print_string(string, nbs=3)
        case = (datafiles, dlevel, software)
        # execute pilgrim with option
        print(" ===========================================================")
        print(" ||  EXECUTING PILGRIM WITH --%-6s                      ||" %
              option)
        print(" ===========================================================")
        print("")
        if option == "ls": gather.ls_struc(idata[0][0])
        elif option == "gather": gather.main(idata, status)
        elif option == "input": inpmenu.main(idata, status)
        elif option == "ics": ics.main(idata, status, *dargs["ics"])
        elif option == "pfn": pfn.main(idata, status, case, dargs["pfn"])
        elif option == "path": path.main(idata, status, case, dargs["path"])
        elif option == "hlcalc":
            hlcalc.main(idata, status, case, dargs["hlcalc"])
        elif option == "rcons":
            rcons.main(idata, status, case, dargs["rcons"])
Exemple #21
0
        print("   Pilgrim output file: %s"%pof)
        print("")

        sys.stdout = Logger(pof,"w",True)
        sys.stdout.writeinfile(PS.init_txt())

        # expand KMC tuple
        ipops,rcs,psteps,volume,timeunits,excess = dkmc[target]
        valid_tu = "fs,ps,mcs,ms,s,min,hr".split(",")
        if timeunits not in valid_tu: timeunits = "ps"

        # reactivo limitante
        try   : POP0 = min([ipop for species,ipop in sorted(ipops.items()) if ipop != 0.0])
        except: POP0 = 0

        print_string(PS.skmc_init(ipops,POP0,excess,rcs,psteps,volume,timeunits,dof),5)

        # continue?
        if POP0 == 0:
            print("   All initial populations are zero...")
            print("")
            return
        if rcs == {}:
            print("   No reactions considered in %s"%PN.IFILE6)
            print("")
            return

        # read dof
        dall = RW.read_alldata(dof,ltemp)[0]

        # perform KMC for each temperature
Exemple #22
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
Exemple #23
0
def obtain_mep(target, gtsTS, pathvars, tsoftware, TMP):
    ctc, itc = PN.name2data(target)

    # create folder now and not in the parallel process
    if not os.path.exists(TMP):
        try:
            os.mkdir(TMP)
        except:
            pass

    # Files
    rstfile = PN.get_rst(ctc, itc)
    xyzfile = PN.get_rstxyz(ctc, itc)

    # print
    software, tes = tsoftware
    fncs.print_string(PS.smep_init(target,software,pathvars._paral,pathvars.tuple_first(),\
                 pathvars.tuple_sdbw(),pathvars.tuple_sdfw()),4)
    fncs.print_string(PS.smep_ff(TMP, PN.DIR4, PN.DIR5, rstfile, xyzfile), 4)

    # read rst
    try:
        tpath2, tcommon2, drst = ff.read_rst(rstfile)
    except:
        exception = Exc.RstReadProblem(Exception)
        exception._var = rstfile
        raise exception
    fncs.print_string(PS.smep_rst(rstfile, drst), 4)

    # correct MEP direction?
    if TSLABEL in drst.keys():
        ii_s, ii_V, ii_x, ii_g, ii_F, ii_v0, ii_v1, ii_t = drst[TSLABEL]
        ii_ic, ii_sign = pathvars._fwdir
        if not intl.ics_correctdir(ii_x, ii_v0, ii_ic, ii_sign, tcommon2[3],
                                   tcommon2[4]):
            fncs.print_string(
                "'fwdir' variable differs from MEP direction in rst file!", 4)
            fncs.print_string("* modifying rst internal dictionary...", 8)
            new_drst = {}
            for key in drst.keys():
                ii_s, ii_V, ii_x, ii_g, ii_F, ii_v0, ii_v1, ii_t = drst[key]
                ii_s = -ii_s
                if ii_v0 is not None: ii_v0 = [-ii for ii in ii_v0]
                if ii_v1 is not None: ii_v1 = [-ii for ii in ii_v1]
                if "bw" in key: newkey = key.replace("bw", "fw")
                else: newkey = key.replace("fw", "bw")
                new_drst[newkey] = (ii_s, ii_V, ii_x, ii_g, ii_F, ii_v0, ii_v1,
                                    ii_t)
            drst = new_drst
            del new_drst
            fncs.print_string("* rewriting rst file...", 8)
            ff.write_rst(rstfile, tpath2, tcommon2, drst)

    # Extension of MEP in rst is bigger
    if drst != {}:
        lbw, lfw, sbw, sfw, V0bw, V0fw = sd.rstlimits(drst)
        pathvars._sbw = min(pathvars._sbw, sbw)
        pathvars._sfw = max(pathvars._sfw, sfw)

    # Read gts
    ts = Molecule()
    ts.set_from_gts(gtsTS)
    # scaling of frequencies
    ts.setvar(fscal=pathvars._freqscal)
    # apply iso mod
    if pathvars._masses is not None: ts.mod_masses(pathvars._masses)
    # setup
    ts.setup(mu=pathvars._mu)
    ts.ana_freqs(case="cc")

    fncs.print_string(PS.smep_ts(ts), 4)

    tcommon = (ts._ch, ts._mtp, ts._atnums, ts._masses, ts._mu)
    compare_tpath(pathvars.tuple_rst(), tpath2, rstfile)
    compare_tcommon(tcommon, tcommon2, rstfile)

    # data for single-point calculation
    frozen = RW.read_frozen(gtsTS + ".frozen")
    oniom_layers = (list(pathvars._oniomh), list(pathvars._oniomm),
                    list(pathvars._onioml))
    spc_args = (tes, TMP, False, frozen, oniom_layers)
    spc_fnc = get_spc_fnc(software)

    #------------#
    # First step #
    #------------#
    print("")
    fncs.print_string("Performing first step of MEP...", 4)
    print("")
    inputvars = (ts._xcc,ts._gcc,ts._Fcc,ts._symbols,ts._masses,pathvars.tuple_first(),\
                 spc_fnc,spc_args,drst,pathvars._paral)
    (xms, gms, Fms), (v0, v1), (xms_bw, xms_fw) = sd.mep_first(*inputvars)
    s1bw = -float(pathvars._ds)
    s1fw = +float(pathvars._ds)

    # oniom layers?
    oniom_ok = pathvars.isONIOMok(ts._natoms, software)
    layers = pathvars.get_layers()
    fncs.print_string(PS.smep_oniom(layers, ts._natoms, software), 8)
    if not oniom_ok: raise Exc.WrongONIOMlayers(Exception)

    # Print MEP info
    fncs.print_string(PS.smep_first(ts._symbols, ts._xms, v0, v1, layers), 8)

    # write rst file
    if TSLABEL not in drst.keys():
        drst[TSLABEL] = (0.0, ts._V0, xms, gms, Fms, v0, v1, None)
        ff.write_rst_head(rstfile, pathvars.tuple_rst(), tcommon)
        ff.write_rst_add(rstfile, TSLABEL, drst[TSLABEL])

    #------------#
    # The MEP    #
    #------------#
    print("")
    fncs.print_string("Calculating MEP...", 4)
    print("")
    fncs.print_string(
        "* REMEMBER: data of each step will be saved at %s" % rstfile, 7)
    fncs.print_string("            a summary will be printed when finished", 7)
    # preparation
    xcc_bw = fncs.ms2cc_x(xms_bw, ts._masses, pathvars._mu)
    xcc_fw = fncs.ms2cc_x(xms_fw, ts._masses, pathvars._mu)
    args_bw = ((xcc_bw,s1bw,ts._symbols,ts._masses,pathvars.tuple_sdbw(),\
                spc_fnc,spc_args,drst,ts._Fms,"bw%i") , rstfile,drst)
    args_fw = ((xcc_fw,s1fw,ts._symbols,ts._masses,pathvars.tuple_sdfw(),\
                spc_fnc,spc_args,drst,ts._Fms,"fw%i") , rstfile,drst)
    # execution
    if pathvars._paral:
        import multiprocessing
        pool = multiprocessing.Pool()
        out = [
            pool.apply_async(onesidemep, args=args)
            for args in [args_bw, args_fw]
        ]
        drstbw, pointsbw, convbw = out[0].get()
        drstfw, pointsfw, convfw = out[1].get()
        del out
        # clean up pool
        pool.close()
        pool.join()
    else:
        drstbw, pointsbw, convbw = onesidemep(*args_bw)
        drstfw, pointsfw, convfw = onesidemep(*args_fw)
    # update drst
    fncs.print_string("* FINISHED!", 7)
    print("")
    drst.update(drstbw)
    drst.update(drstfw)
    points = [TSLABEL] + pointsbw + pointsfw
    # empty variables
    del drstbw, pointsbw
    del drstfw, pointsfw
    # Rewrite rst
    fncs.print_string("* (re)writing file: %s (sorted version)" % rstfile, 7)
    ff.write_rst(rstfile, pathvars.tuple_rst(), tcommon, drst)
    print("")
    ## restrict drst to points
    #if restrict: drst = {point:drst[point] for point in points}
    # Get limits of rst
    lbw, lfw, sbw, sfw, V0bw, V0fw = sd.rstlimits(drst)
    convbw, l1bw, l2bw = convbw
    convfw, l1fw, l2fw = convfw
    if l1bw + l1fw != "":
        fncs.print_string("* MEP convergence criteria (epse and epsg):", 7)
        print("")
        if l1bw != "": fncs.print_string("%s" % l1bw, 9)
        if l2bw != "": fncs.print_string("%s" % l2bw, 9)
        if l1fw != "": fncs.print_string("%s" % l1fw, 9)
        if l2fw != "": fncs.print_string("%s" % l2fw, 9)
        print("")
        if convbw:
            pathvars.converged_in_bw(sbw)
            fncs.print_string("CRITERIA FULFILLED in backward dir.!", 9)
            fncs.print_string("path stopped at sbw = %+8.4f bohr" % sbw, 9)
            print("")
        if convfw:
            pathvars.converged_in_fw(sfw)
            fncs.print_string("CRITERIA FULFILLED in forward dir.!", 9)
            fncs.print_string("path stopped at sfw = %+8.4f bohr" % sfw, 9)
            print("")
    # write molden file
    fncs.print_string("* writing file: %s" % xyzfile, 7)
    ff.rst2xyz(rstfile, xyzfile, onlyhess=True)
    print("")
    # reference energy
    if pathvars._eref is None: pathvars._eref = V0bw
    # return data
    return tcommon, drst, pathvars
Exemple #24
0
def calc_mep(itarget, gtsTS, pathvars, tsoftware, TMP):
    # data in name
    ctc, itc = PN.name2data(itarget)
    # Low-Level
    if pathvars._dlevel is None:
        tcommon, drst, pathvars = obtain_mep(itarget, gtsTS, pathvars,
                                             tsoftware, TMP)
        fncs.print_string(PS.smep_table(drst, pathvars._eref), 4)
    # Dual-Level
    else:
        rstfile = PN.get_rst(ctc, itc)
        xyzfile = PN.get_rstxyz(ctc, itc)
        software, tes = tsoftware
        fncs.print_string(PS.smep_init(itarget,software,pathvars._paral,pathvars.tuple_first(),\
                     pathvars.tuple_sdbw(),pathvars.tuple_sdfw()),4)
        fncs.print_string(PS.smep_ff(TMP, PN.DIR4, PN.DIR5, rstfile, xyzfile),
                          4)

        # read rst
        tpath, tcommon, drst = ff.read_rst(rstfile)
        fncs.print_string(PS.smep_rst(rstfile, drst), 4)

        fncs.print_string("Applying Dual-Level...", 4)
        print("")
        dlevel_xy = [(find_label_in_rst(x, drst)[0], y)
                     for x, y in pathvars._dlevel.items()]
        dlevel_xy = [(x, y) for x, y in dlevel_xy if x is not None]
        # Print points (sorted by s value)
        dummy = [(drst[xx][0], idx) for idx, (xx, yy) in enumerate(dlevel_xy)]
        dummy.sort()
        for s_i, idx_i in dummy:
            xx_i, yy_i = dlevel_xy[idx_i]
            fncs.print_string(
                "%+8.4f bohr (%-6s) --> %.7f hartree" % (s_i, xx_i, yy_i), 13)
        print("")
        # interpolation
        drst, points, xx, yyll, yyhl = ispe.ispe(tcommon,
                                                 drst,
                                                 dlevel_xy,
                                                 tension=0.0)
        tdleveldata = (points, xx, yyll, yyhl)
        # table new values
        fncs.print_string(
            PS.smep_tableDLEVEL(drst, tdleveldata, pathvars._eref), 4)
    return tcommon, drst, pathvars
Exemple #25
0
    #--------------------------------#
    # Calculations for each reaction #
    #--------------------------------#
    print(" " * NINIT + "Analytic expressions:")
    print("")
    print(" " * NINIT + "(1) k = A exp(-B/T)              ")
    print(" " * NINIT + "(2) k = A*T^n*exp(-B/T)          ")
    print(" " * NINIT + "(3) k = A*(T/Tr)^n*exp(-B/T)     ")
    print(" " * NINIT + "(4) k = A*(T/Tr)^n*exp(-B*(T+T0)/(T^2+T0^2))")
    print(" " * NINIT + "(5) k = A*((T+T0)/Tr)^n*exp(-B*(T+T0)/(T^2+T0^2))")
    print("")

    LINES, plotdata = {}, {}
    ml = max(len(rcname) for rcname in targets) + 3
    for rcname in targets:
        print_string(PS.sfit_reaction(rcname), 3)
        Rs, TS, Ps = dchem[rcname]
        nR, nP = len(Rs), len(Ps)
        # perform fitting
        fitting_i = fit_reaction(rcname, nR, nP, dall, ltemp)
        # generate plotdata
        plotdata_i = prepare_plotdata(rcname, nR, nP, ltemp, fitting_i)
        # generate summary lines
        LINES_i = get_summary_lines(rcname, fitting_i, ltemp, ml)
        # update dictionaries
        plotdata.update(plotdata_i)
        LINES.update(LINES_i)
        print_string(PS.sfit_fitting(rcname, fitting_i, ltemp), 5)

    # update file with plots
    if plotfile is not None and plotdata != {}:
Exemple #26
0
def obtain_sct(dMols, points, VadiSpl, temps, dv1, pathvars, dcfs={}):
    print("")
    fncs.print_string("Calculating SCT transmission coefficient...", 4)
    print("")
    # data from  pathvars
    useics = pathvars._useics
    v1mode = pathvars._v1mode
    # E0 value
    if pathvars._e0 is None:
        V1bw = pathvars._eref + VadiSpl.get_alpha()[1]
        V1fw = pathvars._eref + VadiSpl.get_omega()[1]
        if pathvars._V1R is not None: E0bw = pathvars._V1R
        else: E0bw = V1bw
        if pathvars._V1P is not None: E0fw = pathvars._V1P
        else: E0fw = V1fw
        E0 = max(E0bw, E0fw) - pathvars._eref
    else:
        E0 = pathvars._e0 - pathvars._eref
    # some checks
    if len(temps) == 0: raise Exc.NoTemps(Exception)
    if useics in ["yes", True]: case = "ic"
    else: case = "cc"
    # MEP LIMITS
    sbw, sfw = VadiSpl.get_alpha()[0], VadiSpl.get_omega()[0]
    # Part I - Get E0 and VAG
    E0 = sct.get_sct_part1(points, VadiSpl, E0)
    sAG, VAG = VadiSpl.get_max()
    fncs.print_string(PS.ssct_init(E0, VadiSpl, pathvars, v1mode), 8)
    # Part II - Calculate tbar, bmfs and mueff
    tuple_part2 = (dMols, points, dv1, case, pathvars._muintrpl)
    svals, lkappa, ltbar, ldtbar, mu, lmueff, toignore = sct.get_sct_part2(
        *tuple_part2)
    fncs.print_string(
        PS.ssct_mueff(svals, VadiSpl, lkappa, ltbar, lmueff, mu, toignore), 8)
    #----------#
    # E0 < VAG #
    #----------#
    if E0 < VAG:
        # Part III - Quantum reaction coordinate
        fncs.print_string(PS.ssct_E0VAG(E0, VAG), 8)
        if pathvars._qrc is not None:
            afreq = pathvars._qrcafreq
            lEquant = [E0 + E_i for E_i in pathvars._qrclE]
            fncs.print_string(PS.ssct_qrc(pathvars), 8)
            if pathvars._qrccase != 0: return dcfs, None, E0, VAG
            qrc_ZCT = sct.get_sct_part3(svals, mu, VadiSpl, afreq, lEquant, E0,
                                        VAG, temps)
            qrc_SCT = sct.get_sct_part3(svals, lmueff, VadiSpl, afreq, lEquant,
                                        E0, VAG, temps)
            fncs.print_string(
                PS.ssct_probs(qrc_SCT[1], qrc_ZCT[2], qrc_SCT[2], qrc_SCT[3],
                              sbw, sfw), 12)
            kappaI1_zct = qrc_ZCT[0]
            kappaI1_sct = qrc_SCT[0]
            qrc_Elim = lEquant[1]
        else:
            kappaI1_zct = None
            kappaI1_sct = None
            qrc_Elim = None
        # apply QRC always?
        if not pathvars._qrcauto: qrc_Elim = None
        # Part IV - calculate thetas and probs
        fncs.print_string(
            "Transmission probabilities for Kappa^SAG calculation:", 8)
        print("")
        outZCT = sct.get_sct_part4(svals, mu, VadiSpl, E0)
        outSCT = sct.get_sct_part4(svals, lmueff, VadiSpl, E0)
        weights_ZCT, lE_ZCT, probs_ZCT, rpoints_ZCT, diffs_ZCT, (
            pZCT0, rpZCT0) = outZCT
        weights_SCT, lE_SCT, probs_SCT, rpoints_SCT, diffs_SCT, (
            pSCT0, rpSCT0) = outSCT
        # include also prob at E=E0 (pZCT0 and pSCT0)
        fncs.print_string(PS.ssct_probs(         [E0]+lE_SCT   ,\
                                        [pZCT0 ]+probs_ZCT,\
                                        [pSCT0 ]+probs_SCT,\
                                        [rpSCT0]+rpoints_SCT,sbw,sfw),8)
        fncs.print_string(PS.ssct_diffs(lE_SCT, diffs_SCT), 8)
        # Part V - calculate coefficients
        ZCTdata = sct.get_sct_part5(lE_ZCT, probs_ZCT, weights_ZCT, E0, VAG,
                                    temps, kappaI1_zct, qrc_Elim)
        SCTdata = sct.get_sct_part5(lE_SCT, probs_SCT, weights_SCT, E0, VAG,
                                    temps, kappaI1_sct, qrc_Elim)
        ZCT, lIi_ZCT, RTE_ZCT, INTG_ZCT, bqrcZCT = ZCTdata
        SCT, lIi_SCT, RTE_SCT, INTG_SCT, bqrcSCT = SCTdata
        fncs.print_string(
            PS.ssct_kappa(temps,
                          ZCT,
                          lIi_ZCT,
                          RTE_ZCT,
                          E0,
                          bqrcZCT,
                          case="zct"), 8)
        fncs.print_string(
            PS.ssct_kappa(temps,
                          SCT,
                          lIi_SCT,
                          RTE_SCT,
                          E0,
                          bqrcSCT,
                          case="sct"), 8)
    #----------#
    # E0 > VAG #
    #----------#
    else:
        ZCT = [1.0 for T in temps]
        SCT = [1.0 for T in temps]
        INTG_ZCT = None
        INTG_SCT = None
        RTE_ZCT = None
        RTE_SCT = None
        fncs.print_string(PS.ssct_E0_above_VAG(E0, VAG), 8)
        fncs.print_string(PS.ssct_onlykappa(temps, ZCT, SCT), 8)
    # data for the plot
    forplot = (svals, lmueff, temps, INTG_ZCT, INTG_SCT, RTE_ZCT, RTE_SCT, E0,
               VAG)
    # save data
    dcfs["zct"] = ZCT
    dcfs["sct"] = SCT
    return dcfs, forplot, E0, VAG
Exemple #27
0
            rcons.main(idata, status, case, dargs["rcons"])
        elif option == "kmc":
            kmc.main(idata, status, case, dargs["kmc"])
        elif option == "kies":
            kies.main(idata, status, case)
        elif option == "fit":
            fit.main(idata, status, case, dargs["fit"])
        elif option == "plot":
            plot.main(case, dargs["plot"])
        print("")
        print(" ===========================================================")
        break

    # User asked for nothing. Print help!
    if not IN_OPTS:
        print_string(HELP_main, 2)
        return

    # Print elapsed time
    t2 = time.time()
    timeline = "| Total Elapsed Time: %5.1f %5s |" % time2human(
        t2 - t1, "secs")
    print(" " * 25 + "-" * len(timeline))
    print(" " * 25 + timeline)
    print(" " * 25 + "-" * len(timeline))
    print("")


#==========================================================#

#==========================================================#
Exemple #28
0
def get_path_sctconv(itarget, gtsTS, pathvars, tsoftware, ltemp, TMP, symmetry,
                     plotfile):
    # assert no DLEVEL will be done (just in case)
    pathvars._dlevel = None
    # The step to be increased
    hessds = abs(pathvars._hsteps * pathvars._ds)
    # some initializations
    convlist_sct = []
    convlist_lim = []
    # do we have products?
    bool_prods = pathvars._V1P is not None
    ntimesdecrease = 0
    # (a) Define the limits of MEP to calculate SCT
    sbw0, sfw0 = 0.0, 0.0
    while sbw0 > -0.5:
        sbw0 -= hessds
    while sfw0 < +0.5:
        sfw0 += hessds
    sbwN, sfwN = pathvars._sbw, pathvars._sfw
    if fncs.is_greatereq(sbwN, sbw0, EPS_MEPS): sbw0 = sbwN + hessds
    if fncs.is_smallereq(sfwN, sfw0, EPS_MEPS): sfw0 = sfwN - hessds
    # (b) Update pathvars and calculate MEP
    pathvars._sbw = sbw0
    pathvars._sfw = sfw0
    fncs.print_string("--> scterr keyword was detected! <--", 4)
    fncs.print_string(
        "    MEP limited to: [%.4f,%.4f] (bohr)\n" % (sbw0, sfw0), 4)
    tcommon, drst, pathvars = calc_mep(itarget, gtsTS, pathvars, tsoftware,
                                       TMP)
    # (c) if MEP was calculated previously, it may be longer
    lbw, lfw, sbw, sfw, V0bw, V0fw = sd.rstlimits(drst)
    if fncs.is_smaller(sbw, sbw0, EPS_MEPS): sbw0 = sbw + 2 * hessds
    if fncs.is_greater(sfw, sfw0, EPS_MEPS): sfw0 = sfw - 2 * hessds
    # (c) Go ahead
    pathvars._sbw, pathvars._sfw = sbw0, sfw0
    while True:
        # Reduce MEP to current limits
        sbwi = pathvars._sbw
        sfwi = pathvars._sfw
        fncs.print_string(
            "--> CALCULATING COEFFICIENTS IN [%.4f,%.4f] (in bohr)<--" %
            (sbwi, sfwi), 4)
        drst = {
            label: data
            for label, data in drst.items()
            if in_interval(data[0], sbwi, sfwi)
        }
        # Calculate corresponding coefficients
        dcfs, pathvars, palpha, pomega = calc_coefs(itarget, tcommon, drst,
                                                    pathvars, ltemp, symmetry,
                                                    plotfile)
        # expand data
        try:
            SCT = dcfs["sct"]
        except:
            return dcfs
        # Save data only for lower temperature
        convlist_sct.append(SCT[0])
        convlist_lim.append((sbwi, sfwi))
        # Check convergence
        if len(convlist_sct) > 1:
            SCT_a = convlist_sct[-1]
            SCT_b = convlist_sct[-2]
            dif100 = 100 * abs(SCT_a - SCT_b) / SCT_a
            # reduce value only to two decimal places
            dif100 = float("%9.2f" % dif100)
            # compare
            converged = (dif100 <= pathvars._scterr)
            if float("%.4E" % SCT_a) <= float("%.4E" % SCT_b):
                ntimesdecrease += 1
        else:
            converged = False
        # Be more strict with convergence if no products
        if not bool_prods and ntimesdecrease < 2: converged = False
        # Print convergence table
        tuple_table = (convlist_sct, convlist_lim, pathvars._scterr, converged)
        fncs.print_string(PS.ssct_convergence(*tuple_table), 4)
        if converged: break
        # If current limits are outside required, break
        if fncs.is_smallereq(sbwi, sbwN, EPS_MEPS) or fncs.is_greatereq(
                sfwi, sfwN, EPS_MEPS):
            fncs.print_string(
                "WARNING: SCT transmission coefficient is NOT converged YET!",
                4)
            fncs.print_string(
                "         Unfortunately, the MEP limit defined by the user", 4)
            fncs.print_string("         was reached...", 4)
            fncs.print_string(
                "         [sbw,sfw] = [%.4f,%.4f]" % (sbwN, sfwN), 4)
            print("")
            break
        # Increase MEP
        sbwi = pathvars._sbw
        sfwi = pathvars._sfw
        V1bw = palpha[1] + pathvars._eref
        V1fw = pomega[1] + pathvars._eref
        lbw, lfw, sbw, sfw, V0bw, V0fw = sd.rstlimits(drst)
        pathvars.increase_svals(V0bw, V0fw, V1bw, V1fw)
        sbwj = pathvars._sbw
        sfwj = pathvars._sfw
        fncs.print_string(
            "--> MEP will be calculated between [%.4f,%.4f] (in bohr) <--" %
            (sbwj, sfwj), 4)
        print("")
        fncs.print_string("sbw: %+8.4f --> %+8.4f bohr" % (sbwi, sbwj), 8)
        fncs.print_string("sfw: %+8.4f --> %+8.4f bohr" % (sfwi, sfwj), 8)
        print("")
        tcommon, drst, pathvars = calc_mep(itarget, gtsTS, pathvars, tsoftware,
                                           TMP)
        pathvars._sbw = sbwj
        pathvars._sfw = sfwj
    del drst
    return dcfs, converged
Exemple #29
0
                    units = "s^{-1} cc^{%i} molecule^{-%i}" % (num - 1,
                                                               num - 1)
                else:
                    units = "s^{-1}"
                # Fitting process
                print "      Fitting parameters:"
                print
                for rctype in "tst,cvt,tstzct,cvtzct,tstsct,cvtsct".split(","):
                    if case == 0: key = "%s.%s.%s" % (rctype, rcname, direc)
                    else: key = "anh%s.%s.%s" % (rctype, rcname, direc)
                    if key not in dall["rcons"].keys(): continue
                    rcons = dall["rcons"][key]
                    # the fitting
                    khu, dfit = fit2analytic(ltemp, rcons, num)
                    string, lines = PS.sfit_anafit(dfit, key)
                    print_string(string, 9)
                    # save lines for KMC
                    LINES.update({(anatype, rctype, case, rcname, direc): line
                                  for anatype, line in lines.items()})
                    # save data for plotting
                    if case == 0: d4plot[rctype] = (khu, dfit)
                    else: d4plot["anh" + rctype] = (khu, dfit)
                    plotdata.update(
                        manage_data_for_plot_rcons(rcname, direc, ltemp,
                                                   d4plot, units))
                if plotfile is not None and plotdata != {}:
                    write_plotfile(plotfile, plotdata)

    # create loop list
    loop = [(rctype,case) \
            for case    in [0,1] \
Exemple #30
0
def deal_with_path(target, dlevel, software, ltemp, dctc, pathvars, dtes,
                   dchem, dhighlvl, dimasses):
    dof = PN.get_dof(dlevel)
    plotfile = PN.get_plf(dlevel)
    # gts file for this TS
    ctc, itc = PN.name2data(target)
    gtsTS = dctc[ctc].gtsfile(itc)
    # rotational symmetry
    moleculeTS = Molecule()
    moleculeTS.set_from_gts(gtsTS)
    symmetry = str(moleculeTS._pgroup), int(moleculeTS._rotsigma)
    # temporal folder
    TMP = PN.TMPi % (target)
    # if exists,remove content (unless keeptmp is activated)
    # (to avoid reading old files from different levels of calculation)
    if os.path.exists(TMP) and not pathvars._keeptmp:
        shutil.rmtree(TMP, ignore_errors=True)
    # split target
    ctc, itc = PN.name2data(target)
    # name of rst file
    rstfile = PN.get_rst(ctc, itc)
    # tuple software
    tes = dtes.get(software, {}).get(ctc, None)
    tsoftw = (software, tes)
    # internal coordinates
    if itc in dctc[ctc]._dics.keys(): ics = dctc[ctc]._dics[itc]
    elif "*" in dctc[ctc]._dics.keys(): ics = dctc[ctc]._dics["*"]
    else: ics = None
    if itc in dctc[ctc]._dicsbw.keys(): icsbw = dctc[ctc]._dicsbw[itc]
    elif "*" in dctc[ctc]._dicsbw.keys(): icsbw = dctc[ctc]._dicsbw["*"]
    else: icsbw = None
    if itc in dctc[ctc]._dicsfw.keys(): icsfw = dctc[ctc]._dicsfw[itc]
    elif "*" in dctc[ctc]._dicsfw.keys(): icsfw = dctc[ctc]._dicsfw["*"]
    else: icsfw = None
    # path variables
    pathvars.set_ics(ics, icsbw, icsfw)  # before setup3!!
    pathvars.apply_specific(itc)
    pathvars.setup1()
    pathvars.setup2()
    pathvars.setup3()
    # Set Eref (from reaction)
    pathvars.set_eref_from_reaction(target, dchem, dof)
    # Quantum reaction coordinate qrc
    pathvars.prepare_qrc(dchem, dctc, dimasses)
    # frequency scaling factor
    pathvars._freqscal = float(dctc[ctc]._fscal)
    # if dlevel --> no convergence and dlevel data
    if dlevel:
        exception = Exc.NoDLEVELdata(Exception)
        pathvars._scterr = None
        keydhl = "%s.%s.path" % (ctc, itc)
        if keydhl not in dhighlvl.keys():
            # maybe only TS
            keydhl = "%s.%s" % (dctc[ctc]._root, itc)
            if keydhl in dhighlvl.keys():
                dictE = {0.0: dhighlvl[keydhl]}
            else:
                global WARNINGS
                WARNINGS.append("No high-level data for %s" % target)
                raise exception
        else:
            dictE = dhighlvl[keydhl]
        pathvars._dlevel = dictE
    # LOGGER
    pof = PN.get_pof(dlevel, "path", target)
    sys.stdout = Logger(pof, "w", True)
    sys.stdout.writeinfile(PS.init_txt())
    #string
    fncs.print_string(PS.smep_title(target, pathvars, pof), 2)
    # Was previously converged???
    ffloat = "%.3f"
    drstconv = RW.read_rstconv()
    if target in drstconv.keys() and not dlevel and os.path.exists(rstfile):
        lowtemp, useics, scterr, converged = drstconv[target]
        b0 = (converged == "yes")
        b1 = (pathvars._useics == useics)
        b2 = (ffloat % pathvars._scterr == ffloat % scterr)
        b3 = (ffloat % min(ltemp) == ffloat % lowtemp)
        if b0 and b1 and b2 and b3:
            pathvars._scterr = None
            fncs.print_string("THIS PATH IS STORED AS CONVERGED!\n", 4)
            tpath, tcommon, drst = ff.read_rst(rstfile)
            lbw, lfw, sbw, sfw, V0bw, V0fw = sd.rstlimits(drst)
            pathvars._sbw = sbw
            pathvars._sfw = sfw
            del drst
    #----------------#
    # calculate path #
    #----------------#

    # 1. Only MEP
    if not pathvars._beyondmep:
        common, drst, pathvars = calc_mep(target, gtsTS, pathvars, tsoftw, TMP)
        dcoefs = {}
        del drst
        # raise error
        raise Exc.OnlyMEP(Exception)

    # 2. MEP expanded till SCT convergence
    elif pathvars.sct_convergence():
        dcoefs, converged = get_path_sctconv(target, gtsTS, pathvars, tsoftw,
                                             ltemp, TMP, symmetry, plotfile)
        # save convergence in file!
        drstconv = RW.read_rstconv()
        if converged:
            drstconv[target] = (min(ltemp), pathvars._useics, pathvars._scterr,
                                "yes")
        else:
            drstconv[target] = (min(ltemp), pathvars._useics, pathvars._scterr,
                                "no")
        RW.write_rstconv(drstconv)

    # 3. Coefs with the current MEP extension
    else:
        tcommon, drst, pathvars = calc_mep(target, gtsTS, pathvars, tsoftw,
                                           TMP)
        dcoefs, pathvars, palpha, pomega = calc_coefs(target, tcommon, drst,
                                                      pathvars, ltemp,
                                                      symmetry, plotfile)
        del drst

    # print summary with the coefficients
    fncs.print_string(PS.spath_allcoefs(ltemp, dcoefs), 3)
    # return data
    return dcoefs, pathvars