Esempio n. 1
0
def readfile_xyz(fname):
    string = ""
    zmat, symbols, masses = ff.read_xyz_zmat(fname)
    xcc = intl.zmat2xcc(zmat[0],zmat[1])
    # Print more information
    ndummy = symbols.count("XX")
    natoms = len(symbols)-ndummy
    # without dummies
    symbols_wo , xcc_wo    = fncs.clean_dummies(symbols,xcc=xcc)
    symbols_wo , masses_wo = fncs.clean_dummies(symbols,masses=masses)
    molecule = Molecule()
    molecule.setvar(xcc=xcc_wo,symbols=symbols_wo,masses=masses_wo,ch=0,mtp=1)
    molecule.prepare()
    molecule.setup()
    string += "Molecular formula     : %s\n"%molecule._mform
    string += "Number of atoms       : %i\n"%natoms
    string += "Number of dummy atoms : %i\n"%ndummy
    string += "Vibrational d.o.f.    : %i\n"%molecule._nvdof
    string += "\n"
    # Cartesian Coordinates
    string += "Cartesian coordinates (in Angstrom):\n"
    sidx = "%%%si"%len(str(len(symbols)))
    at_wo = -1
    dwithout = {}
    for at,symbol in enumerate(symbols):
        xi,yi,zi = [value*pc.ANGSTROM for value in xcc[3*at : 3*at+3]]
        mass     = masses[at]*pc.AMU
        datainline = (sidx%(at+1),symbol,xi,yi,zi,mass)
        if symbol != "XX": at_wo += 1; dwithout[at] = at_wo
        else: dwithout[at] = None
        string += "[%s]  %-2s  %+12.7f  %+12.7f  %+12.7f  (%7.3f amu)\n"%datainline
    string += "\n"
    return xcc,zmat,symbols,masses,(dwithout,molecule,natoms,ndummy),string
Esempio n. 2
0
def detect_nh2(cmatrix, symbols, lzmat, zmatvals, inpvars):
    lNH2 = []
    xcc = None
    enantio = {}
    for idxN, symbol in enumerate(symbols):
        if symbol != "N": continue
        # check bonded atoms
        bonded_N = [idx2 for idx2, bool2 in enumerate(cmatrix[idxN]) if bool2]
        if len(bonded_N) != 3: continue
        hatoms = [idx2 for idx2 in bonded_N if symbols[idx2] == "H"]
        ratoms = [idx2 for idx2 in bonded_N if symbols[idx2] != "H"]
        if len(hatoms) != 2: continue
        # Get Cartesians
        if xcc is None: xcc = intl.zmat2xcc(lzmat, zmatvals)
        # Define dihedral for reference configuration
        idxH1, idxH2 = sorted(hatoms)
        idxR = ratoms[0]
        HNRH_atoms = (idxH1, idxN, idxR, idxH2)
        HNRH_value, HNRH_bool = tfh.deal_with_HNRH(HNRH_atoms, xcc)
        lNH2.append((HNRH_atoms, HNRH_value, HNRH_bool))
        # in target torsion?
        for X, tatoms in inpvars._tatoms.items():
            atA, atB, atC, atD = tatoms
            # see case and define dihedral for the other H
            if (atB == idxN and atA == idxH1) or (atC == idxN
                                                  and atD == idxH1):
                enantio[X] = +HNRH_value
            elif (atB == idxN and atA == idxH2) or (atC == idxN
                                                    and atD == idxH2):
                enantio[X] = -HNRH_value
            else:
                continue
    return lNH2
Esempio n. 3
0
def test_hsconstraints(lzmat, zmatvals, constr, which="hard"):
    if constr is None or len(constr) == 0: return True
    # the xcc
    xcc = None
    # check constraints
    for ic, icdomain in constr:
        if ic in zmatvals:
            icvalue = zmatvals[ic]
            if icvalue < 0.0: icvalue = icvalue % 360
        else:
            # Get atoms
            icatoms = [int(at) - 1 for at in ic.split("-")]
            nicatoms = len(icatoms)
            # Get xcc for each atom
            if xcc is None: xcc = intl.zmat2xcc(lzmat, zmatvals)
            xyzs = [fncs.xyz(xcc, at) for at in icatoms]
            # calculate value in xcc
            if nicatoms == 2: icvalue = fncs.distance(*xyzs) * ANGSTROM
            elif nicatoms == 3: icvalue = np.rad2deg(fncs.angle(*xyzs)) % 360
            elif nicatoms == 4:
                icvalue = np.rad2deg(fncs.dihedral(*xyzs)) % 360
            else:
                raise Exception
        # in domain?
        boolean = fncs.float_in_domain(icvalue, icdomain)
        if which == "hard" and boolean is False: return False
        if which == "soft" and boolean is True: return True
    # (hard) all of them are fulfilled
    if which == "hard": return True
    # (soft) all of them failed
    if which == "soft": return False
Esempio n. 4
0
def correct_NH2_inversion(lzmat, zmatvals, zmatatoms, lNH2):
    inversion = False
    if len(lNH2) != 0:
        # Create Cartesian coords
        xcc0 = intl.zmat2xcc(lzmat, zmatvals)
        # Check every NH2 group
        for HNRH_atoms, HNRH_value, HNRH_bool in lNH2:
            # check inversion
            cvalue, cbool = deal_with_HNRH(HNRH_atoms, xcc0)
            if HNRH_bool == cbool: continue
            # EXCHANGE HIDROGEN ATOMS!!
            inversion = True
            idxH1 = HNRH_atoms[0]
            idxH2 = HNRH_atoms[3]
            x1 = xcc0[3 * idxH1:3 * idxH1 + 3]
            x2 = xcc0[3 * idxH2:3 * idxH2 + 3]
            xcc0[3 * idxH1:3 * idxH1 + 3] = x2
            xcc0[3 * idxH2:3 * idxH2 + 3] = x1
            # recalculate zmatrix values (only those involving H1 or H2)
            for ic, atoms in zmatatoms.items():
                if not (idxH1 in atoms or idxH2 in atoms): continue
                xs = (xcc0[3 * at:3 * at + 3] for at in atoms)
                if len(atoms) == 2:
                    zmatvals[ic] = ANGSTROM * fncs.distance(*xs)
                if len(atoms) == 3: zmatvals[ic] = np.rad2deg(fncs.angle(*xs))
                if len(atoms) == 4:
                    zmatvals[ic] = np.rad2deg(fncs.dihedral(*xs))
    return zmatvals, inversion
Esempio n. 5
0
def adjmatrix_from_zmatrix(lzmat, zmatvals, cfactor):
    # convert to cartesian coordinates
    xcc = intl.zmat2xcc(lzmat, zmatvals)
    # symbols
    symbols = [pack[0] for pack in lzmat]
    # Get connection matrix
    cmatrix = intl.get_adjmatrix(xcc, symbols, scale=cfactor, mode="bool")[0]
    return cmatrix
Esempio n. 6
0
def enantiovec(lzmat, zmatvals, dcorr, inpvars):
    if dcorr == "Cs":
        vec = zmat2vec(zmatvals, inpvars._tic, negative=True)
        return TorPESpoint(vec)
    else:
        xcc0 = intl.zmat2xcc(lzmat, zmatvals)
        xcc_enantio = enan.generate_enantio(xcc0)
        xcc_enantio = enan.reorder_enantio(xcc_enantio, dcorr)
        vec_enantio = xcc2vec(xcc_enantio, inpvars)
    return vec_enantio
Esempio n. 7
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
Esempio n. 8
0
def get_rotcons(lzmat,zmatvals,symbols):
    xcc = zmat2xcc(lzmat,zmatvals)
    # correct symbols (just in case)
    symbols,atonums = fncs.symbols_and_atonums(symbols)
    # Data without dummies
    symbols_wo,xcc_wo = fncs.clean_dummies(symbols,xcc=list(xcc))
    # generate Molecule instance
    molecule = Molecule()
    molecule.setvar(xcc=xcc_wo)
    molecule.setvar(symbols=symbols_wo)
    molecule.setvar(V0=0)
    molecule.setvar(ch=0,mtp=1)
    molecule.prepare()
    molecule.setup()
    # in freq units (GHz)
    imoms   = [Ii * pc.KG*pc.METER**2 for Ii in molecule._imoms]
    rotcons = [pc.H_SI/(Ii*8*np.pi**2)/1E9 for Ii in imoms]
    return rotcons
Esempio n. 9
0
def write_molden_allconfs(dataconfs,Eref,allsymbols,folder):
       print(tvars.IBS2+"Generating xyz file with all geometries...")
       print(tvars.IBS2+"    filename: %s"%(folder+tvars.ALLCONFS))
       string = ""
       for idx,conftuple in enumerate(dataconfs):
           vec,V0,V1,G,weight,Qrv,ifreq,zmat,zmatvals,log = conftuple
           # convert to xyz
           V0_rel = (V0-Eref)*pc.KCALMOL
           description = " * E = %+7.3f kcal/mol ; (%i) %s"%(V0_rel,idx+1,str(vec))
           symbols   = [symbol for symbol in allsymbols if symbol.upper() not in ("X","XX")]
           natoms    = len(symbols)
           xcc = intl.zmat2xcc(zmat,zmatvals)
           # remove dummy atoms (if there is any)
           xcc = fncs.flatten_llist( [fncs.xyz(xcc,idx) for idx,symbol in enumerate(allsymbols) \
                                      if symbol.upper() not in ("X","XX")])
           # add to string
           string += string4xyzfile(xcc,symbols,info=description)
       with open(folder+tvars.ALLCONFS,'w') as asdf: asdf.write(string)
       print("")
Esempio n. 10
0
    from common.files import read_xyz
    from common.files import read_xyz_zmat
    from common.files import write_xyz
    from common.pgs import get_pgs

    files = [fname for fname in os.listdir(".") if fname.endswith(".xyz")]
    print(files)
    for xyz in files:
        #if "xyz_prueba2_en.xyz" not in xyz: continue
        print(xyz)
        # read file
        try:
            xcc, symbols, masses = read_xyz(xyz)
        except:
            (lzmat, zmatvals, zmatatoms), symbols, masses = read_xyz_zmat(xyz)
            xcc = intl.zmat2xcc(lzmat, zmatvals)
        # point group
        pg, rotsigma = get_pgs(symbols, masses, xcc)
        print("   -", pg)
        # Name for molden file
        xyz2 = xyz.replace(".xyz", "_en.xyz")
        # Get enantiomer
        try:
            xcc_enantio = gen_enantio_and_correlate(xcc,
                                                    symbols,
                                                    masses,
                                                    pp=True)
        except:
            xcc_enantio = None
        if xcc_enantio is None: print("unable to correlate!\n")
        elif os.path.exists(xyz2): print("%s already exists!\n" % xyz2)
Esempio n. 11
0
def main():

    # Presentation and arguments
    argsbools = get_options_from_prompt()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    #--------------------------#
    # REGEN  (regenerate data) #
    #--------------------------#
    if argsbools["regen"]:
        args = (inpvars, )
        execute_code(regen_from_tmp, args, "Regenerating domains")
        raise exc.END