Example #1
0
def get_all_fc_with_zmatrix(pdbf, logfname, scalef):
    """Generate all the force constants with Z-matrix method"""

    sturefs, vals, fcs = get_fc_from_log(logfname)

    #pdb file
    mol, atids, resids = get_atominfo_fpdb(pdbf)

    #reverse new id dict
    rvnatids = {}
    for i in xrange(len(atids)):
        rvnatids[i + 1] = atids[i]

    print_method_title('Z-matrix')

    print_bond_title()
    for i in xrange(len(sturefs)):
        if len(sturefs[i]) == 2:
            at1 = rvnatids[sturefs[i][0]]
            at2 = rvnatids[sturefs[i][1]]
            dis = vals[i]
            fcfinal = fcs[i] * HB2_TO_KCAL_MOL_A2 * 0.5
            fcfinal = fcfinal * scalef * scalef

            at1_rep = atom_rep(mol, at1)
            at2_rep = atom_rep(mol, at2)
            print_bond_inf(at1_rep, at2_rep, fcfinal, dis)

    print_angle_title()
    for i in xrange(len(sturefs)):
        if len(sturefs[i]) == 3:
            at1 = rvnatids[sturefs[i][0]]
            at2 = rvnatids[sturefs[i][1]]
            at3 = rvnatids[sturefs[i][2]]
            angval = vals[i]
            fcfinal = fcs[i] * H_TO_KCAL_MOL * 0.5

            at1_rep = atom_rep(mol, at1)
            at2_rep = atom_rep(mol, at2)
            at3_rep = atom_rep(mol, at3)
            print_angle_inf(at1_rep, at2_rep, at3_rep, fcfinal, angval)

    print_dih_title()
    for i in xrange(len(sturefs)):
        if len(sturefs[i]) == 4:
            at1 = rvnatids[sturefs[i][0]]
            at2 = rvnatids[sturefs[i][1]]
            at3 = rvnatids[sturefs[i][2]]
            at4 = rvnatids[sturefs[i][3]]
            dihval = vals[i]
            fcfinal = fcs[i] * H_TO_KCAL_MOL * 0.5

            at1_rep = atom_rep(mol, at1)
            at2_rep = atom_rep(mol, at2)
            at3_rep = atom_rep(mol, at3)
            at4_rep = atom_rep(mol, at4)
            print_dih_inf(at1_rep, at2_rep, at3_rep, at4_rep, fcfinal, dihval)
Example #2
0
#environment file
ef = open(options.envrmtf, 'w')
print('PDB,', 'ION_RESID,', 'ION_RESNAME,', 'ION_ATOM_ID,', \
             'ION_ATOM_NAME,', 'RESID,', 'RESNAME,', 'ATOM_ID,', 'ATOM_NAME,',\
             'DISTANCE,', 'GEOMETRY,', 'GEO_RMS,', 'COORDINATE_SPHERE,', \
             'EXP_TECH,', 'RESOLUTION', file=ef)

#==============================================================================
# Do analysis for each pdb file
#==============================================================================

for fname in pdbfnl:
    print("Performing the " + fname + " file")

    #get the metal list
    mol, atids, resids = get_atominfo_fpdb(fname)

    #Get the resolution and method
    fp1 = open(fname, 'r')
    for line in fp1:
        if 'RESOLUTION.' in line:
            line = line.split()
            try:
                reso = float(line[-1])
            except:
                try:
                    reso = float(line[-2])
                except:
                    reso = 'UNKNOWN'
        elif 'EXPERIMENT TYPE' in line:
            line = line.split()
Example #3
0
            gid = i.index(":")
            key = int(i[:gid])
            gafftype = i[(gid+1):].replace(" ", "")
            id_list[key] = gafftype 
inputfile.close()

if (options.step == "1"):
    if found_resid == False:
        print("Error: Residue numbers for adduct not specified.")
    if found_connect == True and found_gaff == False:
        print("Error: GAFF type not specified for atoms in adduct_connection_atoms.")
    if found_connect == False and found_gaff == True:
        print("Error: atoms in adduct_connection_atoms not specified.")
    if (found_resid and found_connect and found_gaff):
        print("Writing separate pdb containing capped adduct...")
        reslist = extract_adduct(get_atominfo_fpdb(pdbname + ".pdb")[0], residues, external, project_name, gatms, reslist, extlist)[1]
        print("Creating  mol2 to establish gaff atom types...")
        write_init_mol2(project_name)
        write_fixed_mol2(project_name, gatms, found_gaff, id_list, found_connect, connect_list)
        print("Writing gaussian input files...")
        write_gaussian(project_name, gatms, charge, multiplicity)
        os.remove(project_name + "_init.mol2")
        os.remove("ATOMTYPE.INF")
        os.remove("ANTECHAMBER_BOND_TYPE.AC0")
        os.remove("ANTECHAMBER_BOND_TYPE.AC")
        os.remove("ANTECHAMBER_AC.AC0")
        os.remove("ANTECHAMBER_AC.AC")
    if (found_resid and not found_connect and not found_gaff):
        print("Writing separate pdb containing capped adduct...")
        reslist = extract_adduct(get_atominfo_fpdb(pdbname + ".pdb")[0], residues, external, project_name, gatms, reslist, extlist)[1]
        print("Creating  mol2 to establish gaff atom types...")
Example #4
0
def gene_by_QM_fitting_zmatrix(smpdbf, ionids, stfpf, pref, finf, logfname,
                               scalef):

    print("=============Using the Z-matrix method to generate the parameters.")

    sturefs, vals, fcs = get_fc_from_log(logfname)

    #pdb file
    mol, atids, resids = get_atominfo_fpdb(smpdbf)
    blist = get_mc_blist(mol, atids, ionids, stfpf)
    alist = get_alist(mol, blist)

    #reverse new id dict
    rvnatids = {}
    for i in range(0, len(atids)):
        rvnatids[i + 1] = atids[i]

    attypdict = get_attypdict(stfpf, atids)
    missbondtyps, missangtyps = get_misstyps(pref)

    #final parameter dicts
    finalparmdict = {}

    #for bond
    print("=======================Generate the bond parameters===============")
    for misbond in missbondtyps:
        bondlen = []
        bfconst = []
        for i in range(0, len(sturefs)):
            if len(sturefs[i]) == 2:
                at1 = sturefs[i][0]
                at2 = sturefs[i][1]
                bondtyp = (attypdict[rvnatids[at1]], attypdict[rvnatids[at2]])
                "The unit in log file is Angs."
                if bondtyp == misbond or bondtyp[::-1] == misbond:
                    dis = vals[i]
                    fcfinal = fcs[i] * HB2_TO_KCAL_MOL_A2 * 0.5
                    fcfinal = fcfinal * scalef * scalef
                    #Hatree/(Bohr^2) to kcal/(mol*angstrom^2)
                    #Times 0.5 factor since AMBER use k(r-r0)^2 but not 1/2*k*(r-r0)^2
                    bondlen.append(dis)
                    bfconst.append(fcfinal)

        #Get average bond parameters
        misbondat12 = misbond[0] + '-' + misbond[1]
        bond_para = avg_bond_para(misbondat12, bondlen, bfconst)
        #get the force constant
        finalparmdict[misbondat12] = bond_para

    #for angle
    print("=======================Generate the angle parameters==============")
    for misang in missangtyps:
        angvals = []
        afconst = []
        for i in range(0, len(sturefs)):
            if len(sturefs[i]) == 3:
                at1 = sturefs[i][0]
                at2 = sturefs[i][1]
                at3 = sturefs[i][2]
                angtyp = (attypdict[rvnatids[at1]], attypdict[rvnatids[at2]],
                          attypdict[rvnatids[at3]])
                if angtyp == misang or angtyp[::-1] == misang:
                    angval = vals[i]
                    fcfinal = fcs[i] * H_TO_KCAL_MOL * 0.5
                    fcfinal = fcfinal * scalef * scalef
                    #Hatree to kcal/mol
                    #Times 0.5 factor since AMBER use k(r-r0)^2 but not 1/2*k*(r-r0)^2
                    angvals.append(angval)
                    afconst.append(fcfinal)

        #Get average angle parameters
        misangat123 = misang[0] + '-' + misang[1] + '-' + misang[2]
        ang_para = avg_angle_para(misangat123, angvals, afconst)
        finalparmdict[misangat123] = ang_para

    #Print out the final frcmod file
    print_frcmod_file(pref, finf, finalparmdict, 'Z-matrix')
Example #5
0
def gene_by_QM_fitting_sem(smpdbf, ionids, stfpf, pref, finf, chkfname,
                           logfile, g0x, scalef, bondavg, angavg):

    print("==================Using the Seminario method to solve the problem.")

    mol, atids, resids = get_atominfo_fpdb(smpdbf)
    blist = get_mc_blist(mol, atids, ionids, stfpf)
    alist = get_alist(mol, blist)

    #crds after optimization
    if g0x in ['g03', 'g09']:
        crds = get_crds_from_fchk(chkfname, len(atids))
    elif g0x == 'gms':
        crds = get_crds_from_gms(logfile)

    #Whole Hessian Matrix
    if g0x in ['g03', 'g09']:
        fcmatrix = get_matrix_from_fchk(chkfname, 3 * len(atids))
    elif g0x == 'gms':
        fcmatrix = get_matrix_from_gms(logfile, 3 * len(atids))

    natids = {}
    for i in range(0, len(atids)):
        natids[atids[i]] = i + 1

    attypdict = get_attypdict(stfpf, atids)
    missbondtyps, missangtyps = get_misstyps(pref)

    finalparmdict = {}

    #for bond
    print("=======================Generate the bond parameters===============")
    for misbond in missbondtyps:
        bondlen = []
        bfconst = []
        for bond in blist:
            at1 = bond[0]
            at2 = bond[1]
            bondtyp = (attypdict[at1], attypdict[at2])
            "The unit in fchk file is a.u. so the distance is in Bohr."
            if bondtyp == misbond or bondtyp[::-1] == misbond:
                nat1 = natids[at1]
                nat2 = natids[at2]

                if bondavg == 1:
                    dis, fcfinal, stdv = get_bond_fc_with_sem(
                        crds, fcmatrix, nat1, nat2, scalef, bondavg)
                    print('### Bond force constant between ' + \
                      mol.atoms[at1].resname + str(mol.atoms[at1].resid) + '@' + mol.atoms[at1].atname + ' and ' + \
                      mol.atoms[at2].resname + str(mol.atoms[at2].resid) + '@' + mol.atoms[at2].atname + ' : ' + \
                      str(round(fcfinal, 1)) + ' with StdDev ' + str(round(stdv, 1)))
                elif bondavg == 0:
                    dis, fcfinal = get_bond_fc_with_sem(
                        crds, fcmatrix, nat1, nat2, scalef, bondavg)

                bondlen.append(dis)
                bfconst.append(fcfinal)

        #Get average bond parameters
        misbondat12 = misbond[0] + '-' + misbond[1]
        bond_para = avg_bond_para(misbondat12, bondlen, bfconst)
        #get the force constant
        finalparmdict[misbondat12] = bond_para

    #for angle
    print("=======================Generate the angle parameters==============")
    for misang in missangtyps:
        angvals = []
        afconst = []
        for ang in alist:
            at1 = ang[0]
            at2 = ang[1]
            at3 = ang[2]
            angtyp = (attypdict[at1], attypdict[at2], attypdict[at3])

            if angtyp == misang or angtyp[::-1] == misang:
                nat1 = natids[at1]
                nat2 = natids[at2]
                nat3 = natids[at3]

                if angavg == 1:
                    angval, fcfinal, stdv = get_ang_fc_with_sem(
                        crds, fcmatrix, nat1, nat2, nat3, scalef, angavg)
                    print('### Angle force constant between ' + \
                      mol.atoms[at1].resname + str(mol.atoms[at1].resid) +  '@' + mol.atoms[at1].atname + ', ' + \
                      mol.atoms[at2].resname + str(mol.atoms[at2].resid) +  '@' + mol.atoms[at2].atname + ' and ' + \
                      mol.atoms[at3].resname + str(mol.atoms[at3].resid) +  '@' + mol.atoms[at3].atname + ' : ' + \
                      str(round(fcfinal, 2)) + ' with StdDev ' + str(round(stdv, 2)))
                elif angavg == 0:
                    angval, fcfinal = get_ang_fc_with_sem(
                        crds, fcmatrix, nat1, nat2, nat3, scalef, angavg)

                angvals.append(angval)
                afconst.append(fcfinal)

        #Get average angle parameters
        misangat123 = misang[0] + '-' + misang[1] + '-' + misang[2]
        ang_para = avg_angle_para(misangat123, angvals, afconst)
        finalparmdict[misangat123] = ang_para

    #Print out the final frcmod file
    print_frcmod_file(pref, finf, finalparmdict, 'Seminario')
Example #6
0
def gene_pre_frcmod_file(ionids, naamol2f, stpdbf, stfpf, smresf, prefcdf,
                         ffchoice, gaff, frcmodfs, watermodel):

    print("******************************************************************")
    print("*                                                                *")
    print("*===================Generate the Initial frcmod file=============*")
    print("*                                                                *")
    print("******************************************************************")

    libdict = {}
    chargedict = {}

    for mol2f in naamol2f:
        libdict1, chargedict1 = get_lib_dict(mol2f)
        libdict.update(libdict1)
        chargedict.update(chargedict1)

    #get the parameter dicts
    Params = get_parm_dict(ffchoice, gaff, frcmodfs)

    massparms = Params.mass
    bondparms = Params.bond
    angparms = Params.ang
    dihparms = Params.dih
    impparms = Params.imp
    nbparms = Params.nb
    ljedparms = Params.ljed

    #--------------------------------------------------------------------------

    #############Get the metal center information####################

    #--------------------------------------------------------------------------

    mol, atids, resids = get_atominfo_fpdb(stpdbf)

    #get the blist
    blist = get_mc_blist(mol, atids, ionids, stfpf)

    #get_all_the_lists from standard model
    all_list = get_all_list(mol, blist, atids, 10.0)

    #atom type dictionary, key is the atom id, value is atom type
    attypdict = {}

    #atom ids which has been transfered to another atom type
    atidtrans = []

    #get the information for the three from finger print
    fp = open(stfpf, 'r')
    for line in fp:
        if line[0:4] != "LINK":
            atinfo, atid, attyp1st, symbol, attyp2nd = line.split()
            atid = int(atid)
            attyp1st = addspace(attyp1st)
            attyp2nd = addspace(attyp2nd)
            attypdict[atid] = (attyp1st, attyp2nd)
            if attyp1st != attyp2nd:
                atidtrans.append(atid)
    fp.close()

    print("Atoms which has changed the atom types:", atidtrans)

    for atid in atidtrans:
        resid = mol.atoms[atid].resid
        resname = mol.residues[resid].resname
        attyp1 = attypdict[atid][0]
        attyp2 = attypdict[atid][1]
        print(str(resid) + '-' + resname + '@' + str(atid) + '-' + \
              mol.atoms[atid].atname + ' : ' + attyp1, '-->', attyp2)

    #-------------------------------------------------------------------------

    ########Print the pre-generated frcmod files##############

    #-------------------------------------------------------------------------

    fmf = open(prefcdf, 'w')

    #for atoms which changed atom types
    print('REMARK GOES HERE, THIS FILE IS GENERATED BY MCPB.PY', file=fmf)
    print('MASS', file=fmf)

    #for metal ions
    for i in ionids:
        attyp = attypdict[i][1]
        element = mol.atoms[i].element
        massi = Mass[element]
        print('YES', attyp + ' '  + str(round(massi, 2))  + \
              '                              ' + element + ' ion', file=fmf)

    #for ligating atoms
    for atid in atidtrans:
        if atid not in ionids: #not include metal ion
            atyp1 = attypdict[atid][0]
            atyp2 = attypdict[atid][1]
            print('YES', atyp2 + massparms[atyp1], file=fmf)

    #--------------------------------------------------------------------------
    bondparamsdict1 = {} #For metal ions
    bondparamsdict2 = {} #For the others

    print(' ', file=fmf)
    print('BOND', file=fmf)

    #for bond
    for bonds in all_list.bondlist:
        i = bonds[0]
        j = bonds[1]
        if list(set(ionids) & set([i, j])) != []:
            #The bonds which related to the ions
            bondtyp2 = (attypdict[i][1], attypdict[j][1])
            if (bondtyp2 not in list(bondparamsdict1.keys())) and (bondtyp2[::-1] \
                not in list(bondparamsdict1.keys())):
                bondparamsdict1[bondtyp2] = ' '
        elif list(set(atidtrans) & set([i, j])) != []:
            #The bonds related to the atoms which changed their atom types
            bondtyp1 = (attypdict[i][0], attypdict[j][0])
            bondtyp2 = (attypdict[i][1], attypdict[j][1])
            if (bondtyp2 not in list(bondparamsdict2.keys())) and (bondtyp2[::-1] \
                not in list(bondparamsdict2.keys())):
                if bondtyp1 in list(bondparms.keys()):
                    bondparamsdict2[bondtyp2] = bondparms[bondtyp1]
                elif bondtyp1[::-1] in list(bondparms.keys()):
                    bondparamsdict2[bondtyp2] = bondparms[bondtyp1[::-1]]

    for i in sorted(list(bondparamsdict1.keys())):
        print('NON', i[0] + '-' + i[1] + bondparamsdict1[i], file=fmf)

    for i in sorted(list(bondparamsdict2.keys())):
        print('YES', i[0] + '-' + i[1] + bondparamsdict2[i], file=fmf)

    #--------------------------------------------------------------------------
    coparas = []

    r_smresf = open(smresf, 'r')
    for line in r_smresf:
        line = line.strip('\n')
        line = line.split('-')
        resid = int(line[1])
        if ('GLY' in line) or ('KCO' in line) or ('ACE' in line):
            if resid+1 not in resids:
                coparas.append(resid)
    r_smresf.close()

    angparamsdict1 = {} #For metal ions
    angparamsdict2 = {} #For the others
    print(' ', file=fmf)
    print('ANGL', file=fmf)
    #for angle
    for angs in all_list.anglist:
        i = angs[0]
        j = angs[1]
        k = angs[2]
        if list(set(ionids) & set(angs)) != []:
            #The angles which related to the ions
            angtyp2 = (attypdict[i][1], attypdict[j][1], attypdict[k][1])
            if (angtyp2 not in list(angparamsdict1.keys())) and (angtyp2[::-1] \
                not in list(angparamsdict1.keys())):
                angparamsdict1[angtyp2] = ' '
            #print >> fmf, 'NON', attypdict[i][1] + '-' + attypdict[j][1] + \
            #'-' + attypdict[k][1]
        elif list(set(atidtrans) & set(angs)) != []:
            #The angles related to the atoms
            #which changed their atom types
            angtyp1 = (attypdict[i][0], attypdict[j][0], attypdict[k][0])
            angtyp2 = (attypdict[i][1], attypdict[j][1], attypdict[k][1])
            if (angtyp2 not in list(angparamsdict2.keys())) and (angtyp2[::-1] \
                not in list(angparamsdict2.keys())):
                if angtyp1 in list(angparms.keys()):
                    angparamsdict2[angtyp2] = angparms[angtyp1]
                elif angtyp1[::-1] in list(angparms.keys()):
                    angparamsdict2[angtyp2] = angparms[angtyp1[::-1]]

    #Add for a specific situation
    for i in coparas:
        for atid in atidtrans:
            if mol.atoms[atid].atname == 'O' and mol.atoms[atid].resid == i:
                angtyp1 = (attypdict[atid][0], 'C ', 'N ')
                angtyp2 = (attypdict[atid][1], 'C ', 'N ')
                if (angtyp2 not in list(angparamsdict2.keys())) and (angtyp2[::-1] \
                    not in list(angparamsdict2.keys())):
                    if angtyp1 in list(angparms.keys()):
                        angparamsdict2[angtyp2] = angparms[angtyp1]
                    elif angtyp1[::-1] in list(angparms.keys()):
                        angparamsdict2[angtyp2] = angparms[angtyp1[::-1]]

    for i in sorted(list(angparamsdict1.keys())):
        print('NON', i[0] + '-' + i[1] + '-' + i[2] + angparamsdict1[i], file=fmf)
    for i in sorted(list(angparamsdict2.keys())):
        print('YES', i[0] + '-' + i[1] + '-' + i[2] + angparamsdict2[i], file=fmf)

    #--------------------------------------------------------------------------
    dihparamsdict = {}

    #for dihedral
    for dihs in all_list.dihlist:
        i = dihs[0]
        j = dihs[1]
        k = dihs[2]
        l = dihs[3]
        if list(set(ionids) & set(dihs)) != []:
            # Treat the dihedrals related to the metal ions as zero
            dihtyp1 = (attypdict[i][0], attypdict[j][0], attypdict[k][0], \
                       attypdict[l][0])
            dihtyp1n = (attypdict[i][1], attypdict[j][1], attypdict[k][1], \
                        attypdict[l][1])
            if (dihtyp1 not in list(dihparamsdict.keys())) and (dihtyp1[::-1] \
               not in list(dihparamsdict.keys())):
                dihparamsdict[dihtyp1n] = ['    3       0.00       0.00 ', 3, '    Treat as zero by MCPB.py']

        elif list(set(atidtrans) & set(dihs)) != []:
            if list(set(atidtrans) & set(dihs[0::3])) == []:
            #Neither the 1st and 4th atom change atom types
            #There is 2nd or 3rd or both changed atom type(s)
                dihtyp1 = (attypdict[i][0], attypdict[j][0], attypdict[k][0], \
                           attypdict[l][0])
                dihtyp1n = (attypdict[i][1], attypdict[j][1], attypdict[k][1], \
                            attypdict[l][1])
                dihtyp2 = ('X ', attypdict[j][0], attypdict[k][0], 'X ')
                dihtyp2n = ('X ', attypdict[j][1], attypdict[k][1], 'X ')

                if dihtyp1 in list(dihparms.keys()):
                    if (dihtyp1n not in list(dihparamsdict.keys())) and (dihtyp1n[::-1] \
                        not in list(dihparamsdict.keys())):
                        dihparamsdict[dihtyp1n] = dihparms[dihtyp1]
                elif dihtyp1[::-1] in list(dihparms.keys()):
                    if (dihtyp1n not in list(dihparamsdict.keys())) and (dihtyp1n[::-1] \
                        not in list(dihparamsdict.keys())):
                        dihparamsdict[dihtyp1n] = dihparms[dihtyp1[::-1]]
                elif dihtyp2 in list(dihparms.keys()):
                    if (dihtyp2n not in list(dihparamsdict.keys())) and (dihtyp2n[::-1] \
                        not in list(dihparamsdict.keys())):
                        dihparamsdict[dihtyp2n] = dihparms[dihtyp2]
                elif dihtyp2[::-1] in list(dihparms.keys()):
                    if (dihtyp2n not in list(dihparamsdict.keys())) and (dihtyp2n[::-1] \
                        not in list(dihparamsdict.keys())):
                        dihparamsdict[dihtyp2n] = dihparms[dihtyp2[::-1]]
                else:
                    if (dihtyp1n not in list(dihparamsdict.keys())) and (dihtyp1n[::-1] \
                        not in list(dihparamsdict.keys())):
                        dihparamsdict[dihtyp1n] = ['    3       0.00       0.00 ', 3, '    Treat as zero by MCPB.py']

            else:
            #There is 1st or 4th atoms or both changed the atom type(s)
                dihtyp1 = (attypdict[i][0], attypdict[j][0], attypdict[k][0], \
                           attypdict[l][0])
                dihtyp1n = (attypdict[i][1], attypdict[j][1], attypdict[k][1], \
                            attypdict[l][1])
                dihtyp2 = ('X ', attypdict[j][1], attypdict[k][1], 'X ')

                if dihtyp1 in list(dihparms.keys()):
                    if (dihtyp1n not in list(dihparamsdict.keys())) and (dihtyp1n[::-1] \
                        not in list(dihparamsdict.keys())):
                        dihparamsdict[dihtyp1n] = dihparms[dihtyp1]
                elif dihtyp1[::-1] in list(dihparms.keys()):
                    if (dihtyp1n not in list(dihparamsdict.keys())) and (dihtyp1n[::-1] \
                        not in list(dihparamsdict.keys())):
                        dihparamsdict[dihtyp1n] = dihparms[dihtyp1[::-1]]
                else:
                    if (dihtyp2 in list(dihparms.keys())) or (dihtyp2[::-1] \
                        in list(dihparms.keys())):
                        continue
                    elif (dihtyp1n not in list(dihparamsdict.keys())) and (dihtyp1n[::-1] \
                          not in list(dihparamsdict.keys())):
                        dihparamsdict[dihtyp1n] =  ['    3       0.00       0.00 ', 3, '    Treat as zero by MCPB.py']

    #Add for a specfic situation
    for i in coparas:
        for atid in atidtrans:
            if mol.atoms[atid].atname == 'O' and mol.atoms[atid].resid == i:
                for ionid in ionids:
                    if ((atid, ionid, 1) in all_list.bondlist) or \
                       ((ionid, atid, 1) in all_list.bondlist):
                        dihtyp1 = (attypdict[ionid][0], attypdict[atid][0], 'C ', 'N ')
                        dihtyp2 = (attypdict[ionid][1], attypdict[atid][1], 'C ', 'N ')
                        if (dihtyp2 not in dihparamsdict) and (dihtyp2[::-1] not in dihparamsdict):
                            if dihtyp1 in list(dihparms.keys()):
                                dihparamsdict[dihtyp2] = dihparms[dihtyp1]
                            elif dihtyp1[::-1] in list(dihparms.keys()):
                                dihparamsdict[dihtyp2] = dihparms[dihtyp1[::-1]]
                            else:
                                dihparamsdict[dihtyp2] = ['    3       0.00       0.00 ', 3, '    Treat as zero by MCPB.py']

    print(' ', file=fmf)
    print('DIHE', file=fmf)
    # First is the term contains X and then the others, consistent with Amber
    # manual
    for keyv in sorted(list(dihparamsdict.keys())):
        if 'X ' in keyv:     #For types contain X
            valv = dihparamsdict[keyv]
            keyv = keyv[0] + '-' + keyv[1] + '-' + keyv[2] + '-' + keyv[3]
            terms = len(valv)//3
            for i in range(0, terms):
                temp = i * 3
                print('YES', keyv + valv[temp] + str(valv[temp+1]).rjust(3) + \
                    '.0' + valv[temp+2], file=fmf)

    for keyv in sorted(list(dihparamsdict.keys())):
        if 'X ' not in keyv: #For types don't contain X
            valv = dihparamsdict[keyv]
            keyv = keyv[0] + '-' + keyv[1] + '-' + keyv[2] + '-' + keyv[3]
            terms = len(valv)//3
            for i in range(0, terms):
                temp = i * 3
                print('YES', keyv + valv[temp] + str(valv[temp+1]).rjust(3) + \
                    '.0' + valv[temp+2], file=fmf)
    #--------------------------------------------------------------------------
    impparamsdict = {} # Dict for the new improper parameters

    # For improper torsion, which is only not necessary term in Amber force
    # field here the code only duplicates the available improper parameters
    # for changed atom types
    for imps in all_list.implist:
        i = imps[0]
        j = imps[1]
        k = imps[2]
        l = imps[3]

        # For improper torsions related to metal ions, doesn't consider them
        if list(set(ionids) & set(imps)) != []:
            continue
        elif list(set(atidtrans) & set(imps)) != []:
        # Find all possible improper torsions which are related to the atoms
        # whose atom types were changed, and get them into a dict

            imptyps = {}

            #1 situation for all atom representation
            imptyp1 = (attypdict[i][0], attypdict[j][0], attypdict[k][0], \
                       attypdict[l][0])
            imptyp1n = (attypdict[i][1], attypdict[j][1], attypdict[k][1], \
                        attypdict[l][1])
            imptyp1 = seq_imp(imptyp1)
            imptyp1n = seq_imp(imptyp1n)

            #3 situations for two X used in the representation, i, j, l
            imptyp2 = ('X ', 'X ', attypdict[k][0], attypdict[i][0])
            imptyp2n = ('X ', 'X ', attypdict[k][1], attypdict[i][1])
            imptyp2 = seq_imp(imptyp2)
            imptyp2n = seq_imp(imptyp2n)

            imptyp3 = ('X ', 'X ', attypdict[k][0], attypdict[j][0])
            imptyp3n = ('X ', 'X ', attypdict[k][1], attypdict[j][1])
            imptyp3 = seq_imp(imptyp3)
            imptyp3n = seq_imp(imptyp3n)

            imptyp4 = ('X ', 'X ', attypdict[k][0], attypdict[l][0])
            imptyp4n = ('X ', 'X ', attypdict[k][1], attypdict[l][1])
            imptyp4 = seq_imp(imptyp4)
            imptyp4n = seq_imp(imptyp4n)

            #6 situations for one X used in the representation: ij, ji, il, li, jl, lj
            imptyp5 = ('X ', attypdict[i][0], attypdict[k][0], attypdict[j][0])
            imptyp5n = ('X ', attypdict[i][1], attypdict[k][1], attypdict[j][1])
            imptyp5 = seq_imp(imptyp5)
            imptyp5n = seq_imp(imptyp5n)

            imptyp6 = ('X ', attypdict[j][0], attypdict[k][0], attypdict[i][0])
            imptyp6n = ('X ', attypdict[j][1], attypdict[k][1], attypdict[i][1])
            imptyp6 = seq_imp(imptyp6)
            imptyp6n = seq_imp(imptyp6n)

            imptyp7 = ('X ', attypdict[i][0], attypdict[k][0], attypdict[l][0])
            imptyp7n = ('X ', attypdict[i][0], attypdict[k][1], attypdict[l][1])
            imptyp7 = seq_imp(imptyp7)
            imptyp7n = seq_imp(imptyp7n)

            imptyp8 = ('X ', attypdict[l][0], attypdict[k][0], attypdict[i][0])
            imptyp8n = ('X ', attypdict[l][1], attypdict[k][1], attypdict[i][1])
            imptyp8 = seq_imp(imptyp8)
            imptyp8n = seq_imp(imptyp8n)

            imptyp9 = ('X ', attypdict[j][0], attypdict[k][0], attypdict[l][0])
            imptyp9n = ('X ', attypdict[j][1], attypdict[k][1], attypdict[l][1])
            imptyp9 = seq_imp(imptyp9)
            imptyp9n = seq_imp(imptyp9n)

            imptyp10 = ('X ', attypdict[l][0], attypdict[k][0], attypdict[j][0])
            imptyp10n = ('X ', attypdict[l][1], attypdict[k][1], attypdict[j][1])
            imptyp10 = seq_imp(imptyp10)
            imptyp10n = seq_imp(imptyp10n)

            # If the improper torsion don't change, don't consider them, this
            # is due to the old force field lib would be enough to deal with
            # these situations
            if imptyp1n != imptyp1:
                imptyps[imptyp1] = imptyp1n

            if imptyp2n != imptyp2:
                imptyps[imptyp2] = imptyp2n

            if imptyp3n != imptyp3:
                imptyps[imptyp3] = imptyp3n

            if imptyp4n != imptyp4:
                imptyps[imptyp4] = imptyp4n

            if imptyp5n != imptyp5:
                imptyps[imptyp5] = imptyp5n

            if imptyp6n != imptyp6:
                imptyps[imptyp6] = imptyp6n

            if imptyp7n != imptyp7:
                imptyps[imptyp7] = imptyp7n

            if imptyp8n != imptyp8:
                imptyps[imptyp8] = imptyp8n

            if imptyp9n != imptyp9:
                imptyps[imptyp9] = imptyp9n

            if imptyp10n != imptyp10:
                imptyps[imptyp10] = imptyp10n

            # If the corresponding old improper types available in the lib, then
            # add the parameters to the impparamsdict for new improper types
            for imptypkey in list(imptyps.keys()):
                if imptypkey in list(impparms.keys()):
                    impparamsdict[imptyps[imptypkey]] = impparms[imptypkey]

    print(' ', file=fmf)
    print('IMPR', file=fmf)
    # Print improper torsion, first has two Xs, then one X, then the others
    for i in list(impparamsdict.keys()):
        if i[0] == 'X ' and i[1] == 'X ':
            imptypkey = i[0] + '-' + i[1] + '-' + i[2] + '-' + i[3]
            print('YES', imptypkey + impparamsdict[i], file=fmf)

    for i in list(impparamsdict.keys()):
        if i[0] == 'X ' and i[1] != 'X ':
            imptypkey = i[0] + '-' + i[1] + '-' + i[2] + '-' + i[3]
            print('YES', imptypkey + impparamsdict[i], file=fmf)

    for i in list(impparamsdict.keys()):
        if 'X ' not in i:
            imptypkey = i[0] + '-' + i[1] + '-' + i[2] + '-' + i[3]
            print('YES', imptypkey + impparamsdict[i], file=fmf)
    #--------------------------------------------------------------------------
    #for nb
    print(' ', file=fmf)
    print('NONB', file=fmf)

    #For metal ions
    IonLJParaDict = get_ionljparadict(watermodel)

    for i in ionids:
        element = mol.atoms[i].element
        chg = int(round(chargedict[mol.atoms[i].resname], 0))
        attyp2 = attypdict[i][1]

        mnum = max([9-chg, chg])
        for j in range(0, mnum):

            fchg1 = chg - j
            fchg2 = chg + j

            if j == 0 and element+str(fchg1) in list(IonLJParaDict.keys()):
                rmin = IonLJParaDict[element + str(fchg1)][0]
                ep = IonLJParaDict[element + str(fchg1)][1]
                annot = IonLJParaDict[element + str(fchg1)][2]
                break
            elif fchg1 > 0 and element+str(fchg1) in list(IonLJParaDict.keys()):
                print("Could not find VDW radius for element %s with charge "
                      "+%d, use the one of charge +%d" %(element, chg, fchg1))
                rmin = IonLJParaDict[element + str(fchg1)][0]
                ep = IonLJParaDict[element + str(fchg1)][1]
                annot = IonLJParaDict[element + str(fchg1)][2]
                break
            elif fchg2 <= 8 and element+str(fchg2) in list(IonLJParaDict.keys()):
                print("Could not find VDW radius for element %s with charge "
                      "+%d, use the one of charge +%d" %(element, chg, fchg2))
                rmin = IonLJParaDict[element + str(fchg2)][0]
                ep = IonLJParaDict[element + str(fchg2)][1]
                annot = IonLJParaDict[element + str(fchg2)][2]
                break

        if rmin is None:
            raise pymsmtError("Could not find VDW parameters/radius for "
                              "element %s with charge +%d " %(element, chg))
        print('YES   %s        %8.4f %13.10f       %-s' %(attyp2, rmin, \
                 ep, annot), file=fmf)

    #For the others
    for atid in atidtrans:
        if atid not in ionids:
            attyp1 = attypdict[atid][0]
            attyp2 = attypdict[atid][1]
            print('YES  ', attyp2 + nbparms[attyp1], file=fmf)

    print(' ', file=fmf)
    print(' ', file=fmf)

    fmf.close()
    #--------------------------------------------------------------------------

    #Move the file, delete the repeat parts
    os.system("mv %s temp" %prefcdf)
    os.system("uniq temp > %s" %prefcdf)
    os.system("rm temp")
Example #7
0
#environment file
ef = open(options.envrmtf, 'w')
print('PDB,', 'ION_RESID,', 'ION_RESNAME,', 'ION_ATOM_ID,', \
             'ION_ATOM_NAME,', 'RESID,', 'RESNAME,', 'ATOM_ID,', 'ATOM_NAME,',\
             'DISTANCE,', 'GEOMETRY,', 'GEO_RMS,', 'COORDINATE_SPHERE,', \
             'EXP_TECH,', 'RESOLUTION', file=ef)

#==============================================================================
# Do analysis for each pdb file
#==============================================================================

for fname in pdbfnl:
    print("Performing the " + fname + " file")

    #get the metal list
    mol, atids, resids = get_atominfo_fpdb(fname)

    #Get the resolution and method
    fp1 = open(fname, 'r')
    for line in fp1:
        if 'RESOLUTION.' in line:
            line = line.split()
            try:
                reso = float(line[-1])
            except:
                try:
                    reso = float(line[-2])
                except:
                    reso = 'UNKNOWN'
        elif 'EXPERIMENT TYPE' in line:
            line = line.split()
Example #8
0
def gene_leaprc(gname, orpdbf, fipdbf, stpdbf, stfpf, ionids,\
                ionmol2fs, ioninf, mcresname, naamol2fs, ff_choice, frcmodfs,
                finfcdf, ileapf, model, watermodel='tip3p', paraset='cm'):

    print("******************************************************************")
    print("*                                                                *")
    print("*=================Generating input file for leap=================*")
    print("*                                                                *")
    print("******************************************************************")

    #---------------------Generate the new pdb file--------------------------
    #mol0 is the old mol while mol is new mol file with new names

    mol0, atids0, resids0 = get_atominfo_fpdb(orpdbf)

    reslist0 = get_reslist(mol0, resids0)

    mol, atids, resids = get_atominfo_fpdb(orpdbf)

    #rename the residue names into AMBER style, e.g. HIS --> HID, HIP, HIE
    mol = rename_res(mol, atids)

    #get the disulfur bond information
    disul = get_diS_bond(mol, atids)

    #resname the old residue names to new ones if it is not metal ion
    if model in [1, 2]:
      metcenres1 = [] #Old residue ids
      fp = open(stfpf, 'r')
      for line in fp:
        if line[0:4] != "LINK":
          line = line.split('-')
          if int(line[0]) not in metcenres1:
            metcenres1.append(int(line[0]))
      fp.close()
      metcenres2 = mcresname #New residue names
      resndict = {}
      resns = []
      for i in range(0, len(metcenres1)):
          resndict[metcenres1[i]] = metcenres2[i]
          resns.append(metcenres2[i])

      for i in resndict.keys():
        mol.residues[i].resname = resndict[i]

    writepdb(mol, atids, fipdbf)
    #----------------------------get the atom names which changed atom type
    if model in [1, 2]:
      atomdefs = {}
      fp0 = open(stfpf, 'r')
      for line in fp0:
        if line[0:4] != "LINK":
          line = line.strip('\n')
          line = line.split()
          if line[2] != line[4]:
            atnewtype = line[4]
            element = mol.atoms[int(line[1])].element
            if atnewtype not in atomdefs.keys():
              atomdefs[atnewtype] = element
            else:
              if element != atomdefs[atnewtype]:
                raise pymsmtError('There are atoms in fingerprint file '
                                  'of standard model with same atom type '
                                  'but different element.')
      fp0.close()
    #---------------------Get the bond information, mol2 is the standard model

    if model == 1:
      mol2, atids2, resids2 = get_atominfo_fpdb(stpdbf)
      blist = get_mc_blist(mol2, atids2, ionids, stfpf)
      blist1 = [(i[0], i[1]) for i in blist]

    #----------------------Generate the lib file and get the frcmod file name
    if model == 2:
      frcmodfs = []
      for ionmol2f in ionmol2fs:
        ionmol, ionatids, ionresids = get_atominfo(ionmol2f)
        for i in ionatids:
          element = ionmol.atoms[i].element
          chg = int(ionmol.atoms[i].charge)
          frcmodf = get_frcmod_fname(element, chg, watermodel, paraset)
          if frcmodf not in frcmodfs:
            frcmodfs.append(frcmodf)
    elif model == 3 and ioninf != []:
      #get the metal information
      metresns = ioninf[0::4]
      metatns = ioninf[1::4]
      metelmts = ioninf[2::4]
      metelmts = [i[0] + i[1:].lower() for i in metelmts]
      metchgs = ioninf[3::4]
      metchgs = [int(i) for i in metchgs]
      #check the charge of the metal ions
      for metchg in metchgs:
        if metchg < -1 or metchg > 4:
          raise pymsmtError('Could not deal with atomic ion which has charge '
                            'less than -1 or bigger than +4.')
      frcmodfs = []
      for i in range(0, len(metresns)):
        if metchgs[i] > 1: #if it is -1 or +1 ions, no need to create the lib file
          gene_ion_libfile(metresns[i], metatns[i], metelmts[i], metchgs[i])
          frcmodf = get_frcmod_fname(metelmts[i], metchgs[i], watermodel, paraset)
          if frcmodf not in frcmodfs:
            frcmodfs.append(frcmodf)

    #-----------------------Generate the leap input file-----------------------

    print('Generating the leap input file...')

    ##Generate the tleap.in file
    lp = open(ileapf, 'w')
    if ff_choice in ['ff94', 'ff99', 'ff99SB', 'ff03', 'ff10']:
      print('source oldff/leaprc.%s' %ff_choice, file=lp)
    elif ff_choice in ['ff03.r1', 'ff12SB', 'ff14SB']:
      print('source leaprc.%s' %ff_choice, file=lp)
    print('source leaprc.gaff', file=lp)
    #Add atom types, for bonded model
    if model in [1, 2]:
      if atomdefs.keys() != []:
        print('addAtomTypes {', file=lp)
        for i in sorted(list(atomdefs.keys())):
          print('        { "%s"  "%s" "sp3" }' %(i, atomdefs[i]), file=lp)
        print('}', file=lp)

    #load lib and frcmod files for monovalent ions (for salt)
    if ff_choice in ['ff94', 'ff99', 'ff99SB', 'ff03', 'ff03.r1']:
      print('loadoff atomic_ions.lib', file=lp)
    print('loadamberparams frcmod.ions1lsm_hfe_%s' %watermodel, file=lp)

    #Load mol2 file for the refitting charge residues
    if model in [1, 2]:
      for i in resns:
        print('%s = loadmol2 %s.mol2' %(i, i), file=lp)
    elif model == 3:
      for i in naamol2fs:
        print('%s = loadmol2 %s.mol2' %(i, i), file=lp)

    #Load frcmod files for non-standard residues and metal site
    for i in frcmodfs:
      print('loadamberparams %s' %i, file=lp)

    if model == 1:
      print('loadamberparams %s' %finfcdf, file=lp)
    elif model == 2:
      for frcmodf in frcmodfs:
        print('loadamberparams %s' %frcmodf, file=lp)
    elif model == 3:
      for metresn in metresns:
        print('loadoff %s.lib' %metresn, file=lp)
      for frcmodf in frcmodfs:
        print('loadamberparams %s' %frcmodf, file=lp)

    #load pdb file
    print('mol = loadpdb %s' %fipdbf, file=lp)

    ##The Disulfur Bond information
    if disul != []:
      for i in disul:
        at1 = i[0]
        at2 = i[1]
        resid1 = mol.atoms[at1].resid
        resid2 = mol.atoms[at2].resid
        atname1 = mol.atoms[at1].atname
        atname2 = mol.atoms[at2].atname
        print('bond', 'mol.' + str(resid1) + '.' + atname1, 'mol.' + \
              str(resid2) + '.' + atname2, file=lp)

    ##Bond including the metal ions
    if model == 1:
      for bond in blist1:
        if list(set(bond) & set(ionids)) != []:
          at1 = bond[0]
          at2 = bond[1]
          resid1 = mol.atoms[at1].resid
          resid2 = mol.atoms[at2].resid
          atname1 = mol.atoms[at1].atname
          atname2 = mol.atoms[at2].atname
          print('bond', 'mol.' + str(resid1) + '.' + atname1, 'mol.' + \
                str(resid2) + '.' + atname2, file=lp)

    ##Nonstandard residues with nearby residues

    if model in [1, 2]:
      bondcmds = []
      for i in metcenres1:
        resname = mol0.residues[i].resname
        print('Renamed residues includes: ' + str(i) + '-' + resname)
        if i in reslist0.nterm:
          cmdi = 'bond mol.' + str(i) + '.C' + ' mol.' + str(i+i) + '.N'
          if cmdi not in bondcmds:
            bondcmds.append(cmdi)
        elif i in reslist0.cterm:
          cmdi = 'bond mol.' + str(i-1) + '.C' + ' mol.' + str(i) + '.N'
          if cmdi not in bondcmds:
            bondcmds.append(cmdi)
        elif i in reslist0.std:
          cmdi = 'bond mol.' + str(i-1) + '.C' + ' mol.' + str(i) + '.N'
          if cmdi not in bondcmds:
            bondcmds.append(cmdi)
          cmdi = 'bond mol.' + str(i) + '.C' + ' mol.' + str(i+1) + '.N'
          if cmdi not in bondcmds:
            bondcmds.append(cmdi)
      for j in bondcmds:
          print(j, file=lp)

    #Save dry structure
    print('savepdb mol %s_dry.pdb' %gname, file=lp)
    print('saveamberparm mol %s_dry.prmtop %s_dry.inpcrd' \
          %(gname, gname), file=lp)
    #Solvatebox
    if watermodel == 'tip3p':
      print('solvatebox mol TIP3PBOX 10.0', file=lp)
    elif watermodel == 'spce':
      print('solvatebox mol SPCBOX 10.0', file=lp)
      print('loadamberparams frcmod.spce', file=lp)
    elif watermodel == 'tip4pew':
      print('solvatebox mol TIP4PEWBOX 10.0', file=lp)
      print('loadamberparams frcmod.tip4pew', file=lp)
    #Add counter ions
    print('addions mol Na+ 0', file=lp)
    print('addions mol Cl- 0', file=lp)
    #Save solvated structure
    print('savepdb mol %s_solv.pdb' %gname, file=lp)
    print('saveamberparm mol %s_solv.prmtop %s_solv.inpcrd' \
          %(gname, gname), file=lp)
    print('quit', file=lp)
    print(' ', file=lp)

    lp.close()

    print('Finish generating the leap input file.')
def gene_by_QM_fitting_zmatrix(smpdbf, ionids, stfpf, pref, finf, logfname,
                               scalef):

    print("=============Using the Z-matrix method to generate the parameters.")

    sturefs, vals, fcs = get_fc_from_log(logfname)

    #pdb file
    mol, atids, resids = get_atominfo_fpdb(smpdbf)
    blist = get_mc_blist(mol, atids, ionids, stfpf)
    alist = get_alist(mol, blist)   

    #reverse new id dict
    rvnatids = {}
    for i in range(0, len(atids)):
      rvnatids[i+1] = atids[i]

    attypdict = get_attypdict(stfpf, atids)
    missbondtyps, missangtyps = get_misstyps(pref)

    #final parameter dicts
    finalparmdict = {}

    #for bond
    print("=======================Generate the bond parameters===============")
    for misbond in missbondtyps:
      bondlen = []      
      bfconst = []
      for i in range(0, len(sturefs)):
        if len(sturefs[i]) == 2:
          at1 = sturefs[i][0]
          at2 = sturefs[i][1]
          bondtyp = (attypdict[rvnatids[at1]], attypdict[rvnatids[at2]])
          "The unit in log file is Angs."
          if bondtyp == misbond or bondtyp[::-1] == misbond:
            dis = vals[i]
            fcfinal = fcs[i] * HB2_TO_KCAL_MOL_A2 * 0.5
            fcfinal = fcfinal * scalef * scalef
            #Hatree/(Bohr^2) to kcal/(mol*angstrom^2)
            #Times 0.5 factor since AMBER use k(r-r0)^2 but not 1/2*k*(r-r0)^2
            bondlen.append(dis)
            bfconst.append(fcfinal)

      #Get average bond parameters
      misbondat12 = misbond[0] + '-' + misbond[1]
      bond_para = avg_bond_para(misbondat12, bondlen, bfconst)
      #get the force constant
      finalparmdict[misbondat12] = bond_para

    #for angle
    print("=======================Generate the angle parameters==============")
    for misang in missangtyps:
      angvals = []
      afconst = []
      for i in range(0, len(sturefs)):
        if len(sturefs[i]) == 3:
          at1 = sturefs[i][0]
          at2 = sturefs[i][1]
          at3 = sturefs[i][2]
          angtyp = (attypdict[rvnatids[at1]], attypdict[rvnatids[at2]], attypdict[rvnatids[at3]])
          if angtyp == misang or angtyp[::-1] == misang:
            angval = vals[i]
            fcfinal = fcs[i] * H_TO_KCAL_MOL * 0.5
            fcfinal = fcfinal * scalef * scalef
            #Hatree to kcal/mol
            #Times 0.5 factor since AMBER use k(r-r0)^2 but not 1/2*k*(r-r0)^2
            angvals.append(angval)
            afconst.append(fcfinal)

      #Get average angle parameters
      misangat123 = misang[0] + '-' + misang[1] + '-' + misang[2]
      ang_para = avg_angle_para(misangat123, angvals, afconst)
      finalparmdict[misangat123] = ang_para

    #Print out the final frcmod file
    print_frcmod_file(pref, finf, finalparmdict, 'Z-matrix')
def gene_by_QM_fitting_sem(smpdbf, ionids, stfpf, pref, finf, chkfname,
                           logfile, g0x, scalef, bondavg, angavg):

    print("==================Using the Seminario method to solve the problem.")

    mol, atids, resids = get_atominfo_fpdb(smpdbf)
    blist = get_mc_blist(mol, atids, ionids, stfpf)
    alist = get_alist(mol, blist)   

    #crds after optimization
    if g0x in ['g03', 'g09']:
      crds = get_crds_from_fchk(chkfname, len(atids))
    elif g0x == 'gms':
      crds = get_crds_from_gms(logfile)

    #Whole Hessian Matrix
    if g0x in ['g03', 'g09']:
      fcmatrix = get_matrix_from_fchk(chkfname, 3*len(atids))
    elif g0x == 'gms':
      fcmatrix = get_matrix_from_gms(logfile, 3*len(atids))

    natids = {}
    for i in range(0, len(atids)):
      natids[atids[i]] = i + 1

    attypdict = get_attypdict(stfpf, atids)
    missbondtyps, missangtyps = get_misstyps(pref)

    finalparmdict = {}

    #for bond
    print("=======================Generate the bond parameters===============")
    for misbond in missbondtyps:
      bondlen = []      
      bfconst = []
      for bond in blist:
        at1 = bond[0]
        at2 = bond[1]
        bondtyp = (attypdict[at1], attypdict[at2])
        "The unit in fchk file is a.u. so the distance is in Bohr."
        if bondtyp == misbond or bondtyp[::-1] == misbond:
          nat1 = natids[at1]
          nat2 = natids[at2]

          if bondavg == 1:
            dis, fcfinal, stdv = get_bond_fc_with_sem(crds, fcmatrix, nat1, nat2, scalef, bondavg)
            print('### Bond force constant between ' + \
              mol.atoms[at1].resname + str(mol.atoms[at1].resid) + '@' + mol.atoms[at1].atname + ' and ' + \
              mol.atoms[at2].resname + str(mol.atoms[at2].resid) + '@' + mol.atoms[at2].atname + ' : ' + \
              str(round(fcfinal, 1)) + ' with StdDev ' + str(round(stdv, 1)))
          elif bondavg == 0:
            dis, fcfinal = get_bond_fc_with_sem(crds, fcmatrix, nat1, nat2, scalef, bondavg)

          bondlen.append(dis)
          bfconst.append(fcfinal)

      #Get average bond parameters
      misbondat12 = misbond[0] + '-' + misbond[1]
      bond_para = avg_bond_para(misbondat12, bondlen, bfconst)
      #get the force constant
      finalparmdict[misbondat12] = bond_para

    #for angle
    print("=======================Generate the angle parameters==============")
    for misang in missangtyps:
      angvals = []
      afconst = []
      for ang in alist:
        at1 = ang[0]
        at2 = ang[1]
        at3 = ang[2]
        angtyp = (attypdict[at1], attypdict[at2], attypdict[at3])

        if angtyp == misang or angtyp[::-1] == misang:
          nat1 = natids[at1]
          nat2 = natids[at2]
          nat3 = natids[at3]

          if angavg == 1:
            angval, fcfinal, stdv = get_ang_fc_with_sem(crds, fcmatrix, nat1, nat2, nat3, scalef, angavg)
            print('### Angle force constant between ' + \
              mol.atoms[at1].resname + str(mol.atoms[at1].resid) +  '@' + mol.atoms[at1].atname + ', ' + \
              mol.atoms[at2].resname + str(mol.atoms[at2].resid) +  '@' + mol.atoms[at2].atname + ' and ' + \
              mol.atoms[at3].resname + str(mol.atoms[at3].resid) +  '@' + mol.atoms[at3].atname + ' : ' + \
              str(round(fcfinal, 2)) + ' with StdDev ' + str(round(stdv, 2)))
          elif angavg == 0:
             angval, fcfinal = get_ang_fc_with_sem(crds, fcmatrix, nat1, nat2, nat3, scalef, angavg)

          angvals.append(angval)
          afconst.append(fcfinal)

      #Get average angle parameters
      misangat123 = misang[0] + '-' + misang[1] + '-' + misang[2]
      ang_para = avg_angle_para(misangat123, angvals, afconst)
      finalparmdict[misangat123] = ang_para

    #Print out the final frcmod file
    print_frcmod_file(pref, finf, finalparmdict, 'Seminario')
def gene_by_empirical_way(smpdbf, ionids, stfpf, pref, finf):

    print("******************************************************************")
    print("*                                                                *")
    print("*===========Using the empirical way to solve the problem=========*")
    print("*                                                                *")
    print("******************************************************************")

    #Read from small pdb
    mol, atids, resids = get_atominfo_fpdb(smpdbf)
    blist = get_mc_blist(mol, atids, ionids, stfpf)
    alist = get_alist(mol, blist)

    attypdict = get_attypdict(stfpf, atids)
    missbondtyps, missangtyps = get_misstyps(pref)

    finalparmdict = {}

    #for bond
    print("=======================Generate the bond parameters===============")

    for misbond in missbondtyps:
      bondlen = []
      bfconst = []
      for bond in blist:
        at1 = bond[0]
        at2 = bond[1]
        bondtyp = (attypdict[at1], attypdict[at2])
        if bondtyp == misbond or bondtyp[::-1] == misbond:
          crd1 = mol.atoms[at1].crd
          crd2 = mol.atoms[at2].crd
          dis = calc_bond(crd1, crd2)
          dis = round(dis, 4)
          bondlen.append(dis)

          #get the atom number
          elmt1 = mol.atoms[at1].element
          elmt2 = mol.atoms[at2].element
          elmts = [elmt1, elmt2]
          elmts = sorted(elmts)

          fcfinal = fcfit_ep_bond(dis, elmts)
          bfconst.append(fcfinal)

      #Get average bond parameters
      misbondat12 = misbond[0] + '-' + misbond[1]
      bond_para = avg_bond_para(misbondat12, bondlen, bfconst)
      #get the force constant
      finalparmdict[misbondat12] = bond_para

    #for angle
    print("=======================Generate the angle parameters==============")

    for misang in missangtyps:
      angvals = []
      afconst = []
      for ang in alist:
        at1 = ang[0]
        at2 = ang[1]
        at3 = ang[2]
        angtyp = (attypdict[at1], attypdict[at2], attypdict[at3])
        if angtyp == misang or angtyp[::-1] == misang:
          crd1 = mol.atoms[at1].crd
          crd2 = mol.atoms[at2].crd
          crd3 = mol.atoms[at3].crd
          angval = calc_angle(crd1, crd2, crd3)
          angvals.append(angval)

          elmt1 = mol.atoms[at1].element
          elmt2 = mol.atoms[at2].element
          elmt3 = mol.atoms[at3].element
          elmts = [elmt1, elmt2, elmt3]
          fcfinal = fcfit_ep_angle(elmts)
          afconst.append(fcfinal)

      #Get average angle parameters
      misangat123 = misang[0] + '-' + misang[1] + '-' + misang[2]
      ang_para = avg_angle_para(misangat123, angvals, afconst)
      finalparmdict[misangat123] = ang_para

    #Print out the final frcmod file
    print_frcmod_file(pref, finf, finalparmdict, 'empirical')
Example #12
0
version = '2.0'
print_title('CartHess2FC.py', version)

# Not suport combinations
if options.softv == 'gms' and options.method == 'Z':
    raise pymsmtErorr("Don\'t support Z-matrix method using GAMESS-US in "
                      "current verison!")

avg = options.bavg or options.avg13 or options.aavg

if avg is True and options.method == 'Z':
    raise pymsmtError("Make average of force constants are not applicable "
                      "to Z-matrix method.")

# Get the molecular information from the PDB file
mol, atids, resids = get_atominfo_fpdb(options.pdbf)

if options.nstpdb is True:
    for i in atids:
        atname = mol.atoms[i].atname
        if atname[1] in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
            mol.atoms[i].element = atname[0]
        else:
            mol.atoms[i].element = atname[0:2]

# Print the results with different method
if options.method.lower() == 'zmx':
    get_all_fc_with_zmatrix(mol, atids, options.hessf, options.scalef)
elif options.method.lower() == 'sem':
    get_all_fc_with_sem(mol, atids, options.hessf, options.softv,
                        options.scalef, options.bavg, options.avg13,
Example #13
0
def resp_fitting(stpdbf, lgpdbf, stfpf, lgfpf, mklogf, ionids,\
           ffchoice, mol2fs, metcenres2, chgmod, fixchg_resids, g0x, lgchg):

    print("******************************************************************")
    print("*                                                                *")
    print("*======================RESP Charge fitting=======================*")
    print("*                                                                *")
    print("******************************************************************")

    gene_resp_input_file(lgpdbf, ionids, stfpf, ffchoice, mol2fs,
                         chgmod, fixchg_resids, lgchg)

    #-------------------------------------------------------------------------
    ####################RESP charge fitting###################################
    #-------------------------------------------------------------------------

    print('***Doing the RESP charge fiting...')

    espf = mklogf.strip('.log') + '.esp'

    if g0x in ['g03', 'g09']:
      get_esp_from_gau(mklogf, espf)
    elif g0x == 'gms':
      get_esp_from_gms(mklogf, espf)

    os.system("resp -O -i resp1.in -o resp1.out -p resp1.pch -t resp1.chg \
               -e %s -s resp1_calc.esp" %espf)
    os.system("resp -O -i resp2.in -o resp2.out -p resp2.pch -q resp1.chg \
              -t resp2.chg -e %s -s resp2_calc.esp" %espf)

    #-------------------------------------------------------------------------
    ####################Collecting the atom type and charge data##############
    #-------------------------------------------------------------------------

    #------------Atom type----------
    sddict = {} #get the atom type information from standard model
    r_stfpf = open(stfpf, 'r')
    for line in r_stfpf:
      if line[0:4] != "LINK":
        line = line.strip('\n')
        line = line.split(' ')
        line = [i for i in line if i != '']
        if len(line[-1]) == 1:
          line[-1] = line[-1] + ' '
        sddict[line[0]] = line[-1]
    r_stfpf.close()

    #------------Charge-------------
    chgs = read_resp_file('resp2.chg')

    metcenres1 = [] #original name of the metal center residue
    stlist = [] #get the atom name list from the standard model
    stf = open(stfpf, 'r')
    for line in stf:
      if line[0:4] != "LINK":
        line = line.strip('\n')
        line = line.split()
        stlist.append(line[0])
        line = line[0].split('-')
        lresname = line[0] + '-' + line[1]
        if lresname not in metcenres1:
          metcenres1.append(lresname)
    stf.close()

    llist = [] #get the atom name list from the large model
    lf = open(lgfpf, 'r')
    for line in lf:
      line = line.strip('\n')
      llist.append(line)
    lf.close()

    ldict = {} #get charge of the large model, one-to-one relationship
    for i in range(0, len(llist)):
      ldict[llist[i]] = chgs[i]

    stdict = {} #get the charge of the standard model
    for i in list(ldict.keys()):
      if i in stlist:
        stdict[i] = ldict[i]

    #-------------------------------------------------------------------------
    ####################Checking Models#########################
    #-------------------------------------------------------------------------

    print("=========================Checking models==========================")
    print('***Check the large model...')
    if len(chgs) != len(llist):
      raise pymsmtError('Error: the charges and atom numbers are mismatch '
                        'for the large model!')
    else:
      print('Good. The charges and atom numbers are match for the ' + \
            'large model.')
      print('Good. There are ' + str(len(llist)) + ' atoms in the ' + \
            'large model.')

    print('***Check the standard model...')
    if len(stlist) != len(stdict):
      raise pymsmtError('Error: the charges and atom numbers are mismatch '
                        'for the standard model!')
    else:
      print('Good. The charges and atom numbers are match for the ' + \
            'standard model.')
      print('Good. There are ' + str(len(stlist)) + ' atoms in the ' + \
            'standard model.')

    print('***Check the residue names provided...')
    if len(metcenres1) != len(metcenres2):
      print('You gave the residue names: ', str(metcenres2))
      print('Database had them: ', str(metcenres1))
      raise pymsmtError('Error: The number of the residue names given is '
                        'mismatch the database!')
    else:
      print('Good. The number of the residue names given matches ' + \
            'the database.')

    #-------------------------------------------------------------------------
    ####################Building mol2 files for modeling######################
    #-------------------------------------------------------------------------
 
    #Load the force field
    libdict, chargedict = get_lib_dict(ffchoice)

    for mol2f in mol2fs:
      libdict1, chargedict1 = get_lib_dict(mol2f)
      libdict.update(libdict1)
      chargedict.update(chargedict1)

    ##get the bondlist
    mol, atids, resids = get_atominfo_fpdb(stpdbf) #from standard pdb

    blist = get_mc_blist(mol, atids, ionids, stfpf)

    blist2 = [(i[0], i[1]) for i in blist]

    print("=======================Building mol2 files========================")
    #for each residue, print out the mol2 file
    for i in range(0, len(resids)):

      resconter = mol.residues[resids[i]].resconter #atom ids in the residue
      resname1 =  mol.residues[resids[i]].resname #load residue name
      resname2 = metcenres2[i] #new residue name

      #Backbone atoms use AMBER backbone atom types
      #if resname1 in resnamel:
      #  for bbatm in ['N', 'H', 'CA', 'HA','C', 'O']:
      #    key1 = str(resids[i]) + '-' + resname1 + '-' + bbatm
      #    key2 = resname1 + '-' + bbatm
      #    sddict[key1] = libdict[key2][0]

      #New id dict
      iddict1 = {}
      for j in range(0, len(resconter)):
        iddict1[resconter[j]] = j + 1

      #Bond list for each residue with new atom ids
      blist_each = []
      for k in blist2:
        if set(resconter) & set(k) == set(k):
          blist_each.append((iddict1[k[0]], iddict1[k[1]]))

      print_mol2f(resids[i], resname1, resname2, resconter, mol, iddict1, \
                  sddict, stdict, blist_each)
Example #14
0
def gene_resp_input_file(lgpdbf, ionids, stfpf, ffchoice, mol2fs,
                         chgmod, fixchg_resids, lgchg):

    libdict, chargedict = get_lib_dict(ffchoice)

    for mol2f in mol2fs:
      libdict1, chargedict1 = get_lib_dict(mol2f)
      libdict.update(libdict1)
      chargedict.update(chargedict1)

    mol, atids, resids = get_atominfo_fpdb(lgpdbf)

    reslist = get_reslist(mol, resids)

    blist = get_mc_blist(mol, atids, ionids, stfpf)

    bnoatids = [] #Binding backbone N and C Atom IDs

    mcresids = [] #Metal site residues
    stfpff = open(stfpf, 'r')
    for line in stfpff:
      if line[0:4] != 'LINK':
        line = line.split()
        line = line[0].split('-')
        mcresids.append(int(line[0]))
      else:
        line = line.strip('\n')
        line = line.split()
        if (line[-1][-1] in ['N3', 'N', 'O', 'OXT']):
          atid, atom = line[-1].split('-')
          bnoatids.append(int(atid))
    stfpff.close()

    bnoresids = [] #Binding Backbone N and C Residue IDs, which are not fitted
                   #with backbone restriction in the charge fitting
    for i in bnoatids:
      resid = mol.atoms[i].resid
      if resid not in bnoresids:
        bnoresids.append(resid)

    angresids = [] #ACE, NME, GLY residues
    for i in resids:
      if i not in mcresids:
        angresids.append(i)

    #Get the total charge of the system-------------------------------------
    totchg = 0.0

    for i in resids:
      resname = mol.residues[i].resname
      if i in reslist.nterm:
        reschg = chargedict['N' + resname]
      elif i in reslist.cterm:
        reschg = chargedict['C' + resname]
      else:
        reschg = chargedict[resname]
      totchg = totchg + reschg

    totchg = int(round(totchg, 0))

    if lgchg == -99:
      lgchg = totchg

    #-------------------------------------------------------------------------
    ##############RESP1.IN file###############################################
    #-------------------------------------------------------------------------

    print("***Generating the 1st stage resp charge fitting input file...")

    #print the 1st part, the title
    fresp1 = open('resp1.in', 'w')
    print("Resp charges for organic molecule", file=fresp1)
    print(" ", file=fresp1)
    print(" &cntrl", file=fresp1)
    print(" ", file=fresp1)
    print(" nmol = 1,", file=fresp1)
    print(" ihfree = 1,", file=fresp1)
    print(" ioutopt = 1,", file=fresp1)
    print(" ", file=fresp1)
    print(" &end", file=fresp1)
    print("    1.0", file=fresp1)
    print("Resp charges for organic molecule", file=fresp1)
    print("%5d" %lgchg, end=' ', file=fresp1)
    print("%4d" %len(atids), file=fresp1)

    #2. print the 2nd part, the free and fozen atoms---------------------------
    natids = [i for i in range(1, len(atids)+1)] #new atids

    iddict = {} #First number in iddict is new atom id, second is atomic number

    for i in range(0, len(atids)):
      iddict[atids[i]] = natids[i]

    for i in atids:
      element = mol.atoms[i].element
      elenum = Atnum[element]
      iddict[i] = (iddict[i], elenum)

    for i in resids:
      get_equal_atoms(mol, i, blist, iddict)

    #other atoms (except the CH2 and CH3 groups) are frozen
    for i in atids:
      if (len(iddict[i]) == 2):
        iddict[i] = (iddict[i][0], iddict[i][1], -99)

    for i in atids:
      #if iddict[i][2] == -99:
      print("%5d" %iddict[i][1], end=' ', file=fresp1)
      print("%4s" %'0', file=fresp1)
      #else:
      #  print >> fresp1, "%5d" %iddict[i][1],
      #  print >> fresp1, "%4s" %iddict[i][2]
    fresp1.close()

    add_restriction('resp1.in', libdict, mol, resids, reslist, mcresids,
                    bnoresids, angresids, iddict, chgmod, fixchg_resids)

    #-------------------------------------------------------------------------
    ####################RESP2.IN file#########################################
    #-------------------------------------------------------------------------
    print("***Generating the 2nd stage resp charge fitting input file...")

    #1. print the 1st part, the title------------------------------------------
    fresp2 = open('resp2.in', 'w')
    print("Resp charges for organic molecule", file=fresp2)
    print(" ", file=fresp2)
    print(" &cntrl", file=fresp2)
    print(" ", file=fresp2)
    print(" nmol = 1,", file=fresp2)
    print(" ihfree = 1,", file=fresp2)
    print(" ioutopt = 1,", file=fresp2)
    print(" iqopt = 2,", file=fresp2)
    print(" qwt = 0.001,", file=fresp2)
    print(" ", file=fresp2)
    print(" &end", file=fresp2)
    print("    1.0", file=fresp2)
    print("Resp charges for organic molecule", file=fresp2)
    print("%5d" %lgchg, end=' ', file=fresp2)
    print("%4d" %len(atids), file=fresp2)

    #2. print the 2nd part, the free or frozen information---------------------
    for i in atids:
      print("%5d" %iddict[i][1], end=' ', file=fresp2)
      print("%4s" %iddict[i][2], file=fresp2)
    fresp2.close()

    add_restriction('resp2.in', libdict, mol, resids, reslist, mcresids,
                    bnoresids, angresids, iddict, chgmod, fixchg_resids)
Example #15
0
def gene_leaprc(gname, orpdbf, fipdbf, stpdbf, stfpf, ionids,\
                ionmol2fs, ioninf, mcresname, naamol2fs, ff_choice, frcmodfs,
                finfcdf, ileapf, model, watermodel='tip3p', paraset='cm'):

    print("******************************************************************")
    print("*                                                                *")
    print("*=================Generating input file for leap=================*")
    print("*                                                                *")
    print("******************************************************************")

    #---------------------Generate the new pdb file--------------------------
    #mol0 is the old mol while mol is new mol file with new names

    mol0, atids0, resids0 = get_atominfo_fpdb(orpdbf)

    reslist0 = get_reslist(mol0, resids0)

    mol, atids, resids = get_atominfo_fpdb(orpdbf)

    #rename the residue names into AMBER style, e.g. HIS --> HID, HIP, HIE
    mol = rename_res(mol, atids)

    #get the disulfur bond information
    disul = get_diS_bond(mol, atids)

    #resname the old residue names to new ones if it is not metal ion
    if model in [1, 2]:
        metcenres1 = []  #Old residue ids
        fp = open(stfpf, 'r')
        for line in fp:
            if line[0:4] != "LINK":
                line = line.split('-')
                if int(line[0]) not in metcenres1:
                    metcenres1.append(int(line[0]))
        fp.close()
        metcenres2 = mcresname  #New residue names
        resndict = {}
        resns = []
        for i in range(0, len(metcenres1)):
            resndict[metcenres1[i]] = metcenres2[i]
            resns.append(metcenres2[i])

        for i in resndict.keys():
            mol.residues[i].resname = resndict[i]

    writepdb(mol, atids, fipdbf)
    #----------------------------get the atom names which changed atom type
    if model in [1, 2]:
        atomdefs = {}
        fp0 = open(stfpf, 'r')
        for line in fp0:
            if line[0:4] != "LINK":
                line = line.strip('\n')
                line = line.split()
                if line[2] != line[4]:
                    atnewtype = line[4]
                    element = mol.atoms[int(line[1])].element
                    if atnewtype not in atomdefs.keys():
                        atomdefs[atnewtype] = element
                    else:
                        if element != atomdefs[atnewtype]:
                            raise pymsmtError(
                                'There are atoms in fingerprint file '
                                'of standard model with same atom type '
                                'but different element.')
        fp0.close()
    #---------------------Get the bond information, mol2 is the standard model

    if model == 1:
        mol2, atids2, resids2 = get_atominfo_fpdb(stpdbf)
        blist = get_mc_blist(mol2, atids2, ionids, stfpf)
        blist1 = [(i[0], i[1]) for i in blist]

    #----------------------Generate the lib file and get the frcmod file name
    if model == 2:
        frcmodfs = []
        for ionmol2f in ionmol2fs:
            ionmol, ionatids, ionresids = get_atominfo(ionmol2f)
            for i in ionatids:
                element = ionmol.atoms[i].element
                chg = int(ionmol.atoms[i].charge)
                frcmodf = get_frcmod_fname(element, chg, watermodel, paraset)
                if frcmodf not in frcmodfs:
                    frcmodfs.append(frcmodf)
    elif model == 3 and ioninf != []:
        #get the metal information
        metresns = ioninf[0::4]
        metatns = ioninf[1::4]
        metelmts = ioninf[2::4]
        metelmts = [i[0] + i[1:].lower() for i in metelmts]
        metchgs = ioninf[3::4]
        metchgs = [int(i) for i in metchgs]
        #check the charge of the metal ions
        for metchg in metchgs:
            if metchg < -1 or metchg > 4:
                raise pymsmtError(
                    'Could not deal with atomic ion which has charge '
                    'less than -1 or bigger than +4.')
        frcmodfs = []
        for i in range(0, len(metresns)):
            if metchgs[
                    i] > 1:  #if it is -1 or +1 ions, no need to create the lib file
                gene_ion_libfile(metresns[i], metatns[i], metelmts[i],
                                 metchgs[i])
                frcmodf = get_frcmod_fname(metelmts[i], metchgs[i], watermodel,
                                           paraset)
                if frcmodf not in frcmodfs:
                    frcmodfs.append(frcmodf)

    #-----------------------Generate the leap input file-----------------------

    print('Generating the leap input file...')

    ##Generate the tleap.in file
    lp = open(ileapf, 'w')
    if ff_choice in ['ff94', 'ff99', 'ff99SB', 'ff03', 'ff10']:
        print('source oldff/leaprc.%s' % ff_choice, file=lp)
    elif ff_choice in ['ff03.r1', 'ff12SB', 'ff14SB']:
        print('source leaprc.%s' % ff_choice, file=lp)
    print('source leaprc.gaff', file=lp)
    #Add atom types, for bonded model
    if model in [1, 2]:
        if atomdefs.keys() != []:
            print('addAtomTypes {', file=lp)
            for i in sorted(list(atomdefs.keys())):
                print('        { "%s"  "%s" "sp3" }' % (i, atomdefs[i]),
                      file=lp)
            print('}', file=lp)

    #load lib and frcmod files for monovalent ions (for salt)
    if ff_choice in ['ff94', 'ff99', 'ff99SB', 'ff03', 'ff03.r1']:
        print('loadoff atomic_ions.lib', file=lp)
    print('loadamberparams frcmod.ions1lsm_hfe_%s' % watermodel, file=lp)

    #Load mol2 file for the refitting charge residues
    if model in [1, 2]:
        for i in resns:
            print('%s = loadmol2 %s.mol2' % (i, i), file=lp)
    elif model == 3:
        for i in naamol2fs:
            print('%s = loadmol2 %s.mol2' % (i, i), file=lp)

    #Load frcmod files for non-standard residues and metal site
    for i in frcmodfs:
        print('loadamberparams %s' % i, file=lp)

    if model == 1:
        print('loadamberparams %s' % finfcdf, file=lp)
    elif model == 2:
        for frcmodf in frcmodfs:
            print('loadamberparams %s' % frcmodf, file=lp)
    elif model == 3:
        for metresn in metresns:
            print('loadoff %s.lib' % metresn, file=lp)
        for frcmodf in frcmodfs:
            print('loadamberparams %s' % frcmodf, file=lp)

    #load pdb file
    print('mol = loadpdb %s' % fipdbf, file=lp)

    ##The Disulfur Bond information
    if disul != []:
        for i in disul:
            at1 = i[0]
            at2 = i[1]
            resid1 = mol.atoms[at1].resid
            resid2 = mol.atoms[at2].resid
            atname1 = mol.atoms[at1].atname
            atname2 = mol.atoms[at2].atname
            print('bond', 'mol.' + str(resid1) + '.' + atname1, 'mol.' + \
                  str(resid2) + '.' + atname2, file=lp)

    ##Bond including the metal ions
    if model == 1:
        for bond in blist1:
            if list(set(bond) & set(ionids)) != []:
                at1 = bond[0]
                at2 = bond[1]
                resid1 = mol.atoms[at1].resid
                resid2 = mol.atoms[at2].resid
                atname1 = mol.atoms[at1].atname
                atname2 = mol.atoms[at2].atname
                print('bond', 'mol.' + str(resid1) + '.' + atname1, 'mol.' + \
                      str(resid2) + '.' + atname2, file=lp)

    ##Nonstandard residues with nearby residues

    if model in [1, 2]:
        bondcmds = []
        for i in metcenres1:
            resname = mol0.residues[i].resname
            print('Renamed residues includes: ' + str(i) + '-' + resname)
            if i in reslist0.nterm:
                cmdi = 'bond mol.' + str(i) + '.C' + ' mol.' + str(i +
                                                                   i) + '.N'
                if cmdi not in bondcmds:
                    bondcmds.append(cmdi)
            elif i in reslist0.cterm:
                cmdi = 'bond mol.' + str(i -
                                         1) + '.C' + ' mol.' + str(i) + '.N'
                if cmdi not in bondcmds:
                    bondcmds.append(cmdi)
            elif i in reslist0.std:
                cmdi = 'bond mol.' + str(i -
                                         1) + '.C' + ' mol.' + str(i) + '.N'
                if cmdi not in bondcmds:
                    bondcmds.append(cmdi)
                cmdi = 'bond mol.' + str(i) + '.C' + ' mol.' + str(i +
                                                                   1) + '.N'
                if cmdi not in bondcmds:
                    bondcmds.append(cmdi)
        for j in bondcmds:
            print(j, file=lp)

    #Save dry structure
    print('savepdb mol %s_dry.pdb' % gname, file=lp)
    print('saveamberparm mol %s_dry.prmtop %s_dry.inpcrd' \
          %(gname, gname), file=lp)
    #Solvatebox
    if watermodel == 'tip3p':
        print('solvatebox mol TIP3PBOX 10.0', file=lp)
    elif watermodel == 'spce':
        print('solvatebox mol SPCBOX 10.0', file=lp)
        print('loadamberparams frcmod.spce', file=lp)
    elif watermodel == 'tip4pew':
        print('solvatebox mol TIP4PEWBOX 10.0', file=lp)
        print('loadamberparams frcmod.tip4pew', file=lp)
    #Add counter ions
    print('addions mol Na+ 0', file=lp)
    print('addions mol Cl- 0', file=lp)
    #Save solvated structure
    print('savepdb mol %s_solv.pdb' % gname, file=lp)
    print('saveamberparm mol %s_solv.prmtop %s_solv.inpcrd' \
          %(gname, gname), file=lp)
    print('quit', file=lp)
    print(' ', file=lp)

    lp.close()

    print('Finish generating the leap input file.')
Example #16
0
def gene_resp_input_file(lgpdbf, ionids, stfpf, ffchoice, mol2fs, chgmod,
                         fixchg_resids, lgchg):

    libdict, chargedict = get_lib_dict(ffchoice)

    for mol2f in mol2fs:
        libdict1, chargedict1 = get_lib_dict(mol2f)
        libdict.update(libdict1)
        chargedict.update(chargedict1)

    mol, atids, resids = get_atominfo_fpdb(lgpdbf)

    reslist = get_reslist(mol, resids)

    blist = get_mc_blist(mol, atids, ionids, stfpf)

    bnoatids = []  #Binding backbone N and C Atom IDs

    mcresids = []  #Metal site residues
    stfpff = open(stfpf, 'r')
    for line in stfpff:
        if line[0:4] != 'LINK':
            line = line.split()
            line = line[0].split('-')
            mcresids.append(int(line[0]))
        else:
            line = line.strip('\n')
            line = line.split()
            if (line[-1][-1] in ['N3', 'N', 'O', 'OXT']):
                atid, atom = line[-1].split('-')
                bnoatids.append(int(atid))
    stfpff.close()

    bnoresids = []  #Binding Backbone N and C Residue IDs, which are not fitted
    #with backbone restriction in the charge fitting
    for i in bnoatids:
        resid = mol.atoms[i].resid
        if resid not in bnoresids:
            bnoresids.append(resid)

    angresids = []  #ACE, NME, GLY residues
    for i in resids:
        if i not in mcresids:
            angresids.append(i)

    #Get the total charge of the system-------------------------------------
    totchg = 0.0

    for i in resids:
        resname = mol.residues[i].resname
        if i in reslist.nterm:
            reschg = chargedict['N' + resname]
        elif i in reslist.cterm:
            reschg = chargedict['C' + resname]
        else:
            reschg = chargedict[resname]
        totchg = totchg + reschg

    totchg = int(round(totchg, 0))

    if lgchg == -99:
        lgchg = totchg

    #-------------------------------------------------------------------------
    ##############RESP1.IN file###############################################
    #-------------------------------------------------------------------------

    print("***Generating the 1st stage resp charge fitting input file...")

    #print the 1st part, the title
    fresp1 = open('resp1.in', 'w')
    print("Resp charges for organic molecule", file=fresp1)
    print(" ", file=fresp1)
    print(" &cntrl", file=fresp1)
    print(" ", file=fresp1)
    print(" nmol = 1,", file=fresp1)
    print(" ihfree = 1,", file=fresp1)
    print(" ioutopt = 1,", file=fresp1)
    print(" ", file=fresp1)
    print(" &end", file=fresp1)
    print("    1.0", file=fresp1)
    print("Resp charges for organic molecule", file=fresp1)
    print("%5d" % lgchg, end=' ', file=fresp1)
    print("%4d" % len(atids), file=fresp1)

    #2. print the 2nd part, the free and fozen atoms---------------------------
    natids = [i for i in range(1, len(atids) + 1)]  #new atids

    iddict = {
    }  #First number in iddict is new atom id, second is atomic number

    for i in range(0, len(atids)):
        iddict[atids[i]] = natids[i]

    for i in atids:
        element = mol.atoms[i].element
        elenum = Atnum[element]
        iddict[i] = (iddict[i], elenum)

    for i in resids:
        get_equal_atoms(mol, i, blist, iddict)

    #other atoms (except the CH2 and CH3 groups) are frozen
    for i in atids:
        if (len(iddict[i]) == 2):
            iddict[i] = (iddict[i][0], iddict[i][1], -99)

    for i in atids:
        #if iddict[i][2] == -99:
        print("%5d" % iddict[i][1], end=' ', file=fresp1)
        print("%4s" % '0', file=fresp1)
        #else:
        #  print >> fresp1, "%5d" %iddict[i][1],
        #  print >> fresp1, "%4s" %iddict[i][2]
    fresp1.close()

    add_restriction('resp1.in', libdict, mol, resids, reslist, mcresids,
                    bnoresids, angresids, iddict, chgmod, fixchg_resids)

    #-------------------------------------------------------------------------
    ####################RESP2.IN file#########################################
    #-------------------------------------------------------------------------
    print("***Generating the 2nd stage resp charge fitting input file...")

    #1. print the 1st part, the title------------------------------------------
    fresp2 = open('resp2.in', 'w')
    print("Resp charges for organic molecule", file=fresp2)
    print(" ", file=fresp2)
    print(" &cntrl", file=fresp2)
    print(" ", file=fresp2)
    print(" nmol = 1,", file=fresp2)
    print(" ihfree = 1,", file=fresp2)
    print(" ioutopt = 1,", file=fresp2)
    print(" iqopt = 2,", file=fresp2)
    print(" qwt = 0.001,", file=fresp2)
    print(" ", file=fresp2)
    print(" &end", file=fresp2)
    print("    1.0", file=fresp2)
    print("Resp charges for organic molecule", file=fresp2)
    print("%5d" % lgchg, end=' ', file=fresp2)
    print("%4d" % len(atids), file=fresp2)

    #2. print the 2nd part, the free or frozen information---------------------
    for i in atids:
        print("%5d" % iddict[i][1], end=' ', file=fresp2)
        print("%4s" % iddict[i][2], file=fresp2)
    fresp2.close()

    add_restriction('resp2.in', libdict, mol, resids, reslist, mcresids,
                    bnoresids, angresids, iddict, chgmod, fixchg_resids)
Example #17
0
parser.add_option("--imp",
                  dest="improper",
                  action="store_true",
                  default=False,
                  help="Print improper parameters")
parser.add_option("--scalef", dest="scalef", type='float', help="Scale factor")
parser.add_option(
    "-v",
    dest="softversion",
    type='string',
    help="Software version [Default is g03 (means Gaussian03), \n"
    "           other option are, g09 (means Gaussian09), \n"
    "                       and gms (means GAMESS-US)]")
(options, args) = parser.parse_args()

mol, atids, resids = get_atominfo_fpdb(options.inputfile)

if options.nstdpdb is True:
    for i in atids:
        atname = mol.atoms[i].atname
        if atname[1] in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
            mol.atoms[i].element = atname[0]
        else:
            mol.atoms[i].element = atname[0:2]

blist = get_blist(mol, atids)
all_list = get_all_list(mol, blist, atids, 8.0)

natids = {}
for i in range(0, len(atids)):
    natids[atids[i]] = i + 1
Example #18
0
def resp_fitting(stpdbf, lgpdbf, stfpf, lgfpf, mklogf, ionids,\
           ffchoice, mol2fs, metcenres2, chgmod, fixchg_resids, g0x, lgchg):

    print("******************************************************************")
    print("*                                                                *")
    print("*======================RESP Charge fitting=======================*")
    print("*                                                                *")
    print("******************************************************************")

    gene_resp_input_file(lgpdbf, ionids, stfpf, ffchoice, mol2fs, chgmod,
                         fixchg_resids, lgchg)

    #-------------------------------------------------------------------------
    ####################RESP charge fitting###################################
    #-------------------------------------------------------------------------

    print('***Doing the RESP charge fiting...')

    espf = mklogf.strip('.log') + '.esp'

    if g0x in ['g03', 'g09']:
        get_esp_from_gau(mklogf, espf)
    elif g0x == 'gms':
        get_esp_from_gms(mklogf, espf)

    os.system("resp -O -i resp1.in -o resp1.out -p resp1.pch -t resp1.chg \
               -e %s -s resp1_calc.esp" % espf)
    os.system("resp -O -i resp2.in -o resp2.out -p resp2.pch -q resp1.chg \
              -t resp2.chg -e %s -s resp2_calc.esp" % espf)

    #-------------------------------------------------------------------------
    ####################Collecting the atom type and charge data##############
    #-------------------------------------------------------------------------

    #------------Atom type----------
    sddict = {}  #get the atom type information from standard model
    r_stfpf = open(stfpf, 'r')
    for line in r_stfpf:
        if line[0:4] != "LINK":
            line = line.strip('\n')
            line = line.split(' ')
            line = [i for i in line if i != '']
            if len(line[-1]) == 1:
                line[-1] = line[-1] + ' '
            sddict[line[0]] = line[-1]
    r_stfpf.close()

    #------------Charge-------------
    chgs = read_resp_file('resp2.chg')

    metcenres1 = []  #original name of the metal center residue
    stlist = []  #get the atom name list from the standard model
    stf = open(stfpf, 'r')
    for line in stf:
        if line[0:4] != "LINK":
            line = line.strip('\n')
            line = line.split()
            stlist.append(line[0])
            line = line[0].split('-')
            lresname = line[0] + '-' + line[1]
            if lresname not in metcenres1:
                metcenres1.append(lresname)
    stf.close()

    llist = []  #get the atom name list from the large model
    lf = open(lgfpf, 'r')
    for line in lf:
        line = line.strip('\n')
        llist.append(line)
    lf.close()

    ldict = {}  #get charge of the large model, one-to-one relationship
    for i in range(0, len(llist)):
        ldict[llist[i]] = chgs[i]

    stdict = {}  #get the charge of the standard model
    for i in list(ldict.keys()):
        if i in stlist:
            stdict[i] = ldict[i]

    #-------------------------------------------------------------------------
    ####################Checking Models#########################
    #-------------------------------------------------------------------------

    print("=========================Checking models==========================")
    print('***Check the large model...')
    if len(chgs) != len(llist):
        raise pymsmtError('Error: the charges and atom numbers are mismatch '
                          'for the large model!')
    else:
        print('Good. The charges and atom numbers are match for the ' + \
              'large model.')
        print('Good. There are ' + str(len(llist)) + ' atoms in the ' + \
              'large model.')

    print('***Check the standard model...')
    if len(stlist) != len(stdict):
        raise pymsmtError('Error: the charges and atom numbers are mismatch '
                          'for the standard model!')
    else:
        print('Good. The charges and atom numbers are match for the ' + \
              'standard model.')
        print('Good. There are ' + str(len(stlist)) + ' atoms in the ' + \
              'standard model.')

    print('***Check the residue names provided...')
    if len(metcenres1) != len(metcenres2):
        print('You gave the residue names: ', str(metcenres2))
        print('Database had them: ', str(metcenres1))
        raise pymsmtError('Error: The number of the residue names given is '
                          'mismatch the database!')
    else:
        print('Good. The number of the residue names given matches ' + \
              'the database.')

    #-------------------------------------------------------------------------
    ####################Building mol2 files for modeling######################
    #-------------------------------------------------------------------------

    #Load the force field
    libdict, chargedict = get_lib_dict(ffchoice)

    for mol2f in mol2fs:
        libdict1, chargedict1 = get_lib_dict(mol2f)
        libdict.update(libdict1)
        chargedict.update(chargedict1)

    ##get the bondlist
    mol, atids, resids = get_atominfo_fpdb(stpdbf)  #from standard pdb

    blist = get_mc_blist(mol, atids, ionids, stfpf)

    blist2 = [(i[0], i[1]) for i in blist]

    print("=======================Building mol2 files========================")
    #for each residue, print out the mol2 file
    for i in range(0, len(resids)):

        resconter = mol.residues[resids[i]].resconter  #atom ids in the residue
        resname1 = mol.residues[resids[i]].resname  #load residue name
        resname2 = metcenres2[i]  #new residue name

        #Backbone atoms use AMBER backbone atom types
        #if resname1 in resnamel:
        #  for bbatm in ['N', 'H', 'CA', 'HA','C', 'O']:
        #    key1 = str(resids[i]) + '-' + resname1 + '-' + bbatm
        #    key2 = resname1 + '-' + bbatm
        #    sddict[key1] = libdict[key2][0]

        #New id dict
        iddict1 = {}
        for j in range(0, len(resconter)):
            iddict1[resconter[j]] = j + 1

        #Bond list for each residue with new atom ids
        blist_each = []
        for k in blist2:
            if set(resconter) & set(k) == set(k):
                blist_each.append((iddict1[k[0]], iddict1[k[1]]))

        print_mol2f(resids[i], resname1, resname2, resconter, mol, iddict1, \
                    sddict, stdict, blist_each)
Example #19
0
def gene_pre_frcmod_file(ionids, naamol2f, stpdbf, stfpf, smresf, prefcdf,
                         ffchoice, gaff, frcmodfs, watermodel):

    print("******************************************************************")
    print("*                                                                *")
    print("*===================Generate the Initial frcmod file=============*")
    print("*                                                                *")
    print("******************************************************************")

    libdict = {}
    chargedict = {}

    for mol2f in naamol2f:
        libdict1, chargedict1 = get_lib_dict(mol2f)
        libdict.update(libdict1)
        chargedict.update(chargedict1)

    #get the parameter dicts
    Params = get_parm_dict(ffchoice, gaff, frcmodfs)

    massparms = Params.mass
    bondparms = Params.bond
    angparms = Params.ang
    dihparms = Params.dih
    impparms = Params.imp
    nbparms = Params.nb

    #--------------------------------------------------------------------------

    #############Get the metal center information####################

    #--------------------------------------------------------------------------

    mol, atids, resids = get_atominfo_fpdb(stpdbf)

    #get the blist
    blist = get_mc_blist(mol, atids, ionids, stfpf)

    #get_all_the_lists from standard model
    all_list = get_all_list(mol, blist, atids, 10.0)

    #atom type dictionary, key is the atom id, value is atom type
    attypdict = {}

    #atom ids which has been transfered to another atom type
    atidtrans = []

    #get the information for the three from finger print
    fp = open(stfpf, 'r')
    for line in fp:
        if line[0:4] != "LINK":
            atinfo, atid, attyp1st, symbol, attyp2nd = line.split()
            atid = int(atid)
            attyp1st = addspace(attyp1st)
            attyp2nd = addspace(attyp2nd)
            attypdict[atid] = (attyp1st, attyp2nd)
            if attyp1st != attyp2nd:
                atidtrans.append(atid)
    fp.close()

    print("Atoms which has changed the atom types:", atidtrans)

    for atid in atidtrans:
        resid = mol.atoms[atid].resid
        resname = mol.residues[resid].resname
        attyp1 = attypdict[atid][0]
        attyp2 = attypdict[atid][1]
        print(str(resid) + '-' + resname + '@' + str(atid) + '-' + \
              mol.atoms[atid].atname + ' : ' + attyp1, '-->', attyp2)

    #-------------------------------------------------------------------------

    ########Print the pre-generated frcmod files##############

    #-------------------------------------------------------------------------

    fmf = open(prefcdf, 'w')

    #for atoms which changed atom types
    print('REMARK GOES HERE, THIS FILE IS GENERATED BY MCPB.PY', file=fmf)
    print('MASS', file=fmf)

    #for metal ions
    for i in ionids:
        attyp = attypdict[i][1]
        atname = mol.atoms[i].atname
        if len(atname) > 1:
            atname = atname[0] + atname[1:].lower()
        massi = Mass[atname]
        print('YES', attyp + ' '  + str(round(massi, 2))  + \
              '                              ' + atname + ' ion', file=fmf)

    #for ligating atoms
    for atid in atidtrans:
        if atid not in ionids: #not include metal ion
            atyp1 = attypdict[atid][0]
            atyp2 = attypdict[atid][1]
            print('YES', atyp2 + massparms[atyp1], file=fmf)

    #--------------------------------------------------------------------------
    bondparamsdict1 = {} #For metal ions
    bondparamsdict2 = {} #For the others

    print(' ', file=fmf)
    print('BOND', file=fmf)

    #for bond
    for bonds in all_list.bondlist:
        i = bonds[0]
        j = bonds[1]
        if list(set(ionids) & set([i, j])) != []:
            #The bonds which related to the ions
            bondtyp2 = (attypdict[i][1], attypdict[j][1])
            if (bondtyp2 not in list(bondparamsdict1.keys())) and (bondtyp2[::-1] \
                not in list(bondparamsdict1.keys())):
                bondparamsdict1[bondtyp2] = ' '
        elif list(set(atidtrans) & set([i, j])) != []:
            #The bonds related to the atoms which changed their atom types
            bondtyp1 = (attypdict[i][0], attypdict[j][0])
            bondtyp2 = (attypdict[i][1], attypdict[j][1])
            if (bondtyp2 not in list(bondparamsdict2.keys())) and (bondtyp2[::-1] \
                not in list(bondparamsdict2.keys())):
                if bondtyp1 in list(bondparms.keys()):
                    bondparamsdict2[bondtyp2] = bondparms[bondtyp1]
                elif bondtyp1[::-1] in list(bondparms.keys()):
                    bondparamsdict2[bondtyp2] = bondparms[bondtyp1[::-1]]

    for i in sorted(list(bondparamsdict1.keys())):
        print('NON', i[0] + '-' + i[1] + bondparamsdict1[i], file=fmf)

    for i in sorted(list(bondparamsdict2.keys())):
        print('YES', i[0] + '-' + i[1] + bondparamsdict2[i], file=fmf)

    #--------------------------------------------------------------------------
    coparas = []

    r_smresf = open(smresf, 'r')
    for line in r_smresf:
        line = line.strip('\n')
        line = line.split('-')
        resid = int(line[1])
        if ('GLY' in line) or ('KCO' in line) or ('ACE' in line):
            if resid+1 not in resids:
                coparas.append(resid)
    r_smresf.close()

    angparamsdict1 = {} #For metal ions
    angparamsdict2 = {} #For the others
    print(' ', file=fmf)
    print('ANGL', file=fmf)
    #for angle
    for angs in all_list.anglist:
        i = angs[0]
        j = angs[1]
        k = angs[2]
        if list(set(ionids) & set(angs)) != []:
            #The angles which related to the ions
            angtyp2 = (attypdict[i][1], attypdict[j][1], attypdict[k][1])
            if (angtyp2 not in list(angparamsdict1.keys())) and (angtyp2[::-1] \
                not in list(angparamsdict1.keys())):
                angparamsdict1[angtyp2] = ' '
            #print >> fmf, 'NON', attypdict[i][1] + '-' + attypdict[j][1] + \
            #'-' + attypdict[k][1]
        elif list(set(atidtrans) & set(angs)) != []:
            #The angles related to the atoms
            #which changed their atom types
            angtyp1 = (attypdict[i][0], attypdict[j][0], attypdict[k][0])
            angtyp2 = (attypdict[i][1], attypdict[j][1], attypdict[k][1])
            if (angtyp2 not in list(angparamsdict2.keys())) and (angtyp2[::-1] \
                not in list(angparamsdict2.keys())):
                if angtyp1 in list(angparms.keys()):
                    angparamsdict2[angtyp2] = angparms[angtyp1]
                elif angtyp1[::-1] in list(angparms.keys()):
                    angparamsdict2[angtyp2] = angparms[angtyp1[::-1]]

    #Add for a specific situation
    for i in coparas:
        for atid in atidtrans:
            if mol.atoms[atid].atname == 'O' and mol.atoms[atid].resid == i:
                angtyp1 = (attypdict[atid][0], 'C ', 'N ')
                angtyp2 = (attypdict[atid][1], 'C ', 'N ')
                if (angtyp2 not in list(angparamsdict2.keys())) and (angtyp2[::-1] \
                    not in list(angparamsdict2.keys())):
                    if angtyp1 in list(angparms.keys()):
                        angparamsdict2[angtyp2] = angparms[angtyp1]
                    elif angtyp1[::-1] in list(angparms.keys()):
                        angparamsdict2[angtyp2] = angparms[angtyp1[::-1]]

    for i in sorted(list(angparamsdict1.keys())):
        print('NON', i[0] + '-' + i[1] + '-' + i[2] + angparamsdict1[i], file=fmf)
    for i in sorted(list(angparamsdict2.keys())):
        print('YES', i[0] + '-' + i[1] + '-' + i[2] + angparamsdict2[i], file=fmf)

    #--------------------------------------------------------------------------
    dihparamsdict = {}

    #for dihedral
    for dihs in all_list.dihlist:
        i = dihs[0]
        j = dihs[1]
        k = dihs[2]
        l = dihs[3]
        if list(set(ionids) & set(dihs)) != []:
            #The dihedral related to the metal ions
            dihtyp1 = (attypdict[i][0], attypdict[j][0], attypdict[k][0], \
                       attypdict[l][0])
            dihtyp1n = (attypdict[i][1], attypdict[j][1], attypdict[k][1], \
                        attypdict[l][1])
            if (dihtyp1 not in list(dihparamsdict.keys())) and (dihtyp1[::-1] \
               not in list(dihparamsdict.keys())):
                dihparamsdict[dihtyp1n] = ['   3    0.00          0.0   ', \
                                           '          3.   ', ' ']
        elif list(set(atidtrans) & set(dihs)) != []:
            if list(set(atidtrans) & set(dihs[0::3])) == []:
            #Neither the 1st and 4th atom change atom types
            #There is 2nd or 3rd or both changed atom type(s)
                dihtyp1 = (attypdict[i][0], attypdict[j][0], attypdict[k][0], \
                           attypdict[l][0])
                dihtyp1n = (attypdict[i][1], attypdict[j][1], attypdict[k][1], \
                            attypdict[l][1])
                dihtyp2 = ('X ', attypdict[j][0], attypdict[k][0], 'X ')
                dihtyp2n = ('X ', attypdict[j][1], attypdict[k][1], 'X ')

                if dihtyp1 in list(dihparms.keys()):
                    if (dihtyp1n not in list(dihparamsdict.keys())) and (dihtyp1n[::-1] \
                        not in list(dihparamsdict.keys())):
                        dihparamsdict[dihtyp1n] = dihparms[dihtyp1]
                elif dihtyp1[::-1] in list(dihparms.keys()):
                    if (dihtyp1n not in list(dihparamsdict.keys())) and (dihtyp1n[::-1] \
                        not in list(dihparamsdict.keys())):
                        dihparamsdict[dihtyp1n] = dihparms[dihtyp1[::-1]]
                elif dihtyp2 in list(dihparms.keys()):
                    if (dihtyp2n not in list(dihparamsdict.keys())) and (dihtyp2n[::-1] \
                        not in list(dihparamsdict.keys())):
                        dihparamsdict[dihtyp2n] = dihparms[dihtyp2]
                elif dihtyp2[::-1] in list(dihparms.keys()):
                    if (dihtyp2n not in list(dihparamsdict.keys())) and (dihtyp2n[::-1] \
                        not in list(dihparamsdict.keys())):
                        dihparamsdict[dihtyp2n] = dihparms[dihtyp2[::-1]]
                else:
                    if (dihtyp1n not in list(dihparamsdict.keys())) and (dihtyp1n[::-1] \
                        not in list(dihparamsdict.keys())):
                        dihparamsdict[dihtyp1n] = ['   3    0.00          0.0   ', \
                                                   '          3.   ', ' ']
            else:
            #There is 1st or 4th atoms or both changed the atom type(s)
                dihtyp1 = (attypdict[i][0], attypdict[j][0], attypdict[k][0], \
                           attypdict[l][0])
                dihtyp1n = (attypdict[i][1], attypdict[j][1], attypdict[k][1], \
                            attypdict[l][1])
                dihtyp2 = ('X ', attypdict[j][1], attypdict[k][1], 'X ')

                if dihtyp1 in list(dihparms.keys()):
                    if (dihtyp1n not in list(dihparamsdict.keys())) and (dihtyp1n[::-1] \
                        not in list(dihparamsdict.keys())):
                        dihparamsdict[dihtyp1n] = dihparms[dihtyp1]
                elif dihtyp1[::-1] in list(dihparms.keys()):
                    if (dihtyp1n not in list(dihparamsdict.keys())) and (dihtyp1n[::-1] \
                        not in list(dihparamsdict.keys())):
                        dihparamsdict[dihtyp1n] = dihparms[dihtyp1[::-1]]
                else:
                    if (dihtyp2 in list(dihparms.keys())) or (dihtyp2[::-1] \
                        in list(dihparms.keys())):
                        continue
                    elif (dihtyp1n not in list(dihparamsdict.keys())) and (dihtyp1n[::-1] \
                          not in list(dihparamsdict.keys())):
                        dihparamsdict[dihtyp1n] = ['   3    0.00          0.0   ', \
                                                   '          3.   ', ' ']

    #Add for a specfic situation
    for i in coparas:
        for atid in atidtrans:
            if mol.atoms[atid].atname == 'O' and mol.atoms[atid].resid == i:
                for ionid in ionids:
                    if ((atid, ionid, 1) in all_list.bondlist) or \
                       ((ionid, atid, 1) in all_list.bondlist):
                        dihtyp1 = (attypdict[ionid][0], attypdict[atid][0], 'C ', 'N ')
                        dihtyp2 = (attypdict[ionid][1], attypdict[atid][1], 'C ', 'N ')
                        if (dihtyp2 not in dihparamsdict) and (dihtyp2[::-1] not in dihparamsdict):
                            if dihtyp1 in list(dihparms.keys()):
                                dihparamsdict[dihtyp2] = dihparms[dihtyp1]
                            elif dihtyp1[::-1] in list(dihparms.keys()):
                                dihparamsdict[dihtyp2] = dihparms[dihtyp1[::-1]]
                            else:
                                dihparamsdict[dihtyp2] = ['   3    0.00          0.0   ', \
                                                       '          3.   ', ' ']

    print(' ', file=fmf)
    print('DIHE', file=fmf)
    for keyv in sorted(list(dihparamsdict.keys())):
        if 'X ' not in keyv: #For types don't contain X
            valv = dihparamsdict[keyv]
            keyv = keyv[0] + '-' + keyv[1] + '-' + keyv[2] + '-' + keyv[3]
            terms = len(valv)//3
            for i in range(0, terms):
                temp = i * 3
                print('YES', keyv, valv[temp] + valv[temp+1] + \
                         valv[temp+2], file=fmf)

    for keyv in sorted(list(dihparamsdict.keys())):
        if 'X ' in keyv:     #For types contain X
            valv = dihparamsdict[keyv]
            keyv = keyv[0] + '-' + keyv[1] + '-' + keyv[2] + '-' + keyv[3]
            terms = len(valv)//3
            for i in range(0, terms):
                temp = i * 3
                print('YES', keyv, valv[temp] + valv[temp+1] + \
                         valv[temp+2], file=fmf)
    #--------------------------------------------------------------------------
    impparamsdict = {}

    #For improper torsion
    for imps in all_list.implist:
        i = imps[0]
        j = imps[1]
        k = imps[2]
        l = imps[3]

        if list(set(ionids) & set(imps)) != []:
            continue
        elif list(set(atidtrans) & set(imps)) != []:
            imptyps = {}

            #1 situation
            imptyp1 = (attypdict[i][0], attypdict[j][0], attypdict[k][0], \
                       attypdict[l][0])
            imptyp1n = (attypdict[i][1], attypdict[j][1], attypdict[k][1], \
                        attypdict[l][1])

            #3 situations
            imptyp2 = ('X ', 'X ', attypdict[k][0], attypdict[i][0])
            imptyp2n = ('X ', 'X ', attypdict[k][1], attypdict[i][1])

            imptyp3 = ('X ', 'X ', attypdict[k][0], attypdict[j][0])
            imptyp3n = ('X ', 'X ', attypdict[k][1], attypdict[j][1])

            imptyp4 = ('X ', 'X ', attypdict[k][0], attypdict[l][0])
            imptyp4n = ('X ', 'X ', attypdict[k][1], attypdict[l][1])

            #6 situations
            imptyp5 = ('X ', attypdict[i][0], attypdict[k][0], attypdict[j][0])
            imptyp5n = ('X ', attypdict[i][1], attypdict[k][1], attypdict[j][1])

            imptyp6 = ('X ', attypdict[j][0], attypdict[k][0], attypdict[i][0])
            imptyp6n = ('X ', attypdict[j][1], attypdict[k][1], attypdict[i][1])

            imptyp7 = ('X ', attypdict[i][0], attypdict[k][0], attypdict[l][0])
            imptyp7n = ('X ', attypdict[i][0], attypdict[k][1], attypdict[l][1])

            imptyp8 = ('X ', attypdict[l][0], attypdict[k][0], attypdict[i][0])
            imptyp8n = ('X ', attypdict[l][1], attypdict[k][1], attypdict[i][1])

            imptyp9 = ('X ', attypdict[j][0], attypdict[k][0], attypdict[l][0])
            imptyp9n = ('X ', attypdict[j][1], attypdict[k][1], attypdict[l][1])

            imptyp10 = ('X ', attypdict[l][0], attypdict[k][0], attypdict[j][0])
            imptyp10n = ('X ', attypdict[l][1], attypdict[k][1], attypdict[j][1])

            imptyps[imptyp1] = imptyp1n
            imptyps[imptyp2] = imptyp2n
            imptyps[imptyp3] = imptyp3n
            imptyps[imptyp4] = imptyp4n
            imptyps[imptyp5] = imptyp5n
            imptyps[imptyp6] = imptyp6n
            imptyps[imptyp7] = imptyp7n
            imptyps[imptyp8] = imptyp8n
            imptyps[imptyp9] = imptyp9n
            imptyps[imptyp10] = imptyp10n

            for imptypkey in list(imptyps.keys()):
                if imptypkey in list(impparms.keys()):
                    impparamsdict[imptyps[imptypkey]] = impparms[imptypkey]

    print(' ', file=fmf)
    print('IMPR', file=fmf)
    #for improper torsion
    for i in sorted(list(impparamsdict.keys())):
        if i not in list(impparms.keys()):
            imptypkey = i[0] + '-' + i[1] + '-' + i[2] + '-' + i[3]
            print('YES', imptypkey, impparamsdict[i], file=fmf)
    #--------------------------------------------------------------------------
    #for nb
    print(' ', file=fmf)
    print('NONB', file=fmf)

    #For metal ions
    IonLJParaDict = get_ionljparadict(watermodel)

    for i in ionids:
        element = mol.atoms[i].element
        chg = int(round(chargedict[mol.atoms[i].resname], 0))
        attyp2 = attypdict[i][1]

        mnum = max([9-chg, chg])
        for j in range(0, mnum):

            fchg1 = chg - j
            fchg2 = chg + j

            if j == 0 and element+str(fchg1) in list(IonLJParaDict.keys()):
                rmin = IonLJParaDict[element + str(fchg1)][0]
                ep = IonLJParaDict[element + str(fchg1)][1]
                annot = IonLJParaDict[element + str(fchg1)][2]
                break
            elif fchg1 > 0 and element+str(fchg1) in list(IonLJParaDict.keys()):
                print("Could not find VDW radius for element %s with charge "
                      "+%d, use the one of charge +%d" %(element, chg, fchg1))
                rmin = IonLJParaDict[element + str(fchg1)][0]
                ep = IonLJParaDict[element + str(fchg1)][1]
                annot = IonLJParaDict[element + str(fchg1)][2]
                break
            elif fchg2 <= 8 and element+str(fchg2) in list(IonLJParaDict.keys()):
                print("Could not find VDW radius for element %s with charge "
                      "+%d, use the one of charge +%d" %(element, chg, fchg2))
                rmin = IonLJParaDict[element + str(fchg2)][0]
                ep = IonLJParaDict[element + str(fchg2)][1]
                annot = IonLJParaDict[element + str(fchg2)][2]
                break

        if rmin is None:
            raise pymsmtError("Could not find VDW parameters/radius for "
                              "element %s with charge +%d " %(element, chg))
        print('YES   %s        %8.4f %13.10f       %-s' %(attyp2, rmin, \
                 ep, annot), file=fmf)

    #For the others
    for atid in atidtrans:
        if atid not in ionids:
            attyp1 = attypdict[atid][0]
            attyp2 = attypdict[atid][1]
            print('YES  ', attyp2 + nbparms[attyp1], file=fmf)

    print(' ', file=fmf)
    print(' ', file=fmf)

    fmf.close()
    #--------------------------------------------------------------------------

    #Move the file, delete the repeat parts
    os.system("mv %s temp" %prefcdf)
    os.system("uniq temp > %s" %prefcdf)
    os.system("rm temp")
Example #20
0
def gene_by_empirical_way(smpdbf, ionids, stfpf, pref, finf):

    print("******************************************************************")
    print("*                                                                *")
    print("*===========Using the empirical way to solve the problem=========*")
    print("*                                                                *")
    print("******************************************************************")

    #Read from small pdb
    mol, atids, resids = get_atominfo_fpdb(smpdbf)
    blist = get_mc_blist(mol, atids, ionids, stfpf)
    alist = get_alist(mol, blist)

    attypdict = get_attypdict(stfpf, atids)
    missbondtyps, missangtyps = get_misstyps(pref)

    finalparmdict = {}

    #for bond
    print("=======================Generate the bond parameters===============")

    for misbond in missbondtyps:
        bondlen = []
        bfconst = []
        for bond in blist:
            at1 = bond[0]
            at2 = bond[1]
            bondtyp = (attypdict[at1], attypdict[at2])
            if bondtyp == misbond or bondtyp[::-1] == misbond:
                crd1 = mol.atoms[at1].crd
                crd2 = mol.atoms[at2].crd
                dis = calc_bond(crd1, crd2)
                dis = round(dis, 4)
                bondlen.append(dis)

                #get the atom number
                elmt1 = mol.atoms[at1].element
                elmt2 = mol.atoms[at2].element
                elmts = [elmt1, elmt2]
                elmts = sorted(elmts)

                fcfinal = fcfit_ep_bond(dis, elmts)
                bfconst.append(fcfinal)

        #Get average bond parameters
        misbondat12 = misbond[0] + '-' + misbond[1]
        bond_para = avg_bond_para(misbondat12, bondlen, bfconst)
        #get the force constant
        finalparmdict[misbondat12] = bond_para

    #for angle
    print("=======================Generate the angle parameters==============")

    for misang in missangtyps:
        angvals = []
        afconst = []
        for ang in alist:
            at1 = ang[0]
            at2 = ang[1]
            at3 = ang[2]
            angtyp = (attypdict[at1], attypdict[at2], attypdict[at3])
            if angtyp == misang or angtyp[::-1] == misang:
                crd1 = mol.atoms[at1].crd
                crd2 = mol.atoms[at2].crd
                crd3 = mol.atoms[at3].crd
                angval = calc_angle(crd1, crd2, crd3)
                angvals.append(angval)

                elmt1 = mol.atoms[at1].element
                elmt2 = mol.atoms[at2].element
                elmt3 = mol.atoms[at3].element
                elmts = [elmt1, elmt2, elmt3]
                fcfinal = fcfit_ep_angle(elmts)
                afconst.append(fcfinal)

        #Get average angle parameters
        misangat123 = misang[0] + '-' + misang[1] + '-' + misang[2]
        ang_para = avg_angle_para(misangat123, angvals, afconst)
        finalparmdict[misangat123] = ang_para

    #Print out the final frcmod file
    print_frcmod_file(pref, finf, finalparmdict, 'empirical')
Example #21
0
                  help="Bond force constant average.")
parser.add_option("--aavg", dest="angavg", action="store_true", default=False,
                  help="Angle force constant average.")
parser.add_option("--dih", dest="dihedral", action="store_true", default=False,
                  help="Print dihedral parameters")
parser.add_option("--imp", dest="improper", action="store_true", default=False,
                  help="Print improper parameters")
parser.add_option("--scalef", dest="scalef", type='float',
                  help="Scale factor")
parser.add_option("-v", dest="softversion", type='string',
                  help="Software version [Default is g03 (means Gaussian03), \n"
                       "           other option are, g09 (means Gaussian09), \n"
                       "                       and gms (means GAMESS-US)]")
(options, args) = parser.parse_args()

mol, atids, resids = get_atominfo_fpdb(options.inputfile)

if options.nstdpdb is True:
    for i in atids:
        atname = mol.atoms[i].atname
        if atname[1] in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
            mol.atoms[i].element = atname[0]
        else:
            mol.atoms[i].element = atname[0:2]

blist = get_blist(mol, atids)
all_list = get_all_list(mol, blist, atids, 8.0)

natids = {}
for i in range(0, len(atids)):
    natids[atids[i]] = i + 1
Example #22
0
def gene_pre_frcmod_file(ionids, naamol2f, stpdbf, stfpf, smresf, prefcdf,
                         ffchoice, gaff, frcmodfs, watermodel):

    print("******************************************************************")
    print("*                                                                *")
    print("*===================Generate the Initial frcmod file=============*")
    print("*                                                                *")
    print("******************************************************************")
 
    libdict = {}
    chargedict = {}

    for mol2f in naamol2f:
      libdict1, chargedict1 = get_lib_dict(mol2f)
      libdict.update(libdict1)
      chargedict.update(chargedict1)

    #get the parameter dicts
    Params = get_parm_dict(ffchoice, gaff, frcmodfs)

    massparms = Params.mass
    bondparms = Params.bond
    angparms = Params.ang
    dihparms = Params.dih
    impparms = Params.imp
    nbparms = Params.nb

    #--------------------------------------------------------------------------

    #############Get the metal center information####################

    #--------------------------------------------------------------------------

    mol, atids, resids = get_atominfo_fpdb(stpdbf)

    #get the blist
    blist = get_mc_blist(mol, atids, ionids, stfpf)

    #get_all_the_lists from standard model
    all_list = get_all_list(mol, blist, atids, 10.0)

    #atom type dictionary, key is the atom id, value is atom type
    attypdict = {}

    #atom ids which has been transfered to another atom type
    atidtrans = []

    #get the information for the three from finger print
    fp = open(stfpf, 'r')
    for line in fp:
      if line[0:4] != "LINK":
        atinfo, atid, attyp1st, symbol, attyp2nd = line.split()
        atid = int(atid)
        attyp1st = addspace(attyp1st)
        attyp2nd = addspace(attyp2nd)
        attypdict[atid] = (attyp1st, attyp2nd)
        if attyp1st != attyp2nd:
          atidtrans.append(atid)
    fp.close()

    print("Atoms which has changed the atom types:", atidtrans)

    for atid in atidtrans:
      resid = mol.atoms[atid].resid
      resname = mol.residues[resid].resname
      attyp1 = attypdict[atid][0]
      attyp2 = attypdict[atid][1]
      print(str(resid) + '-' + resname + '@' + str(atid) + '-' + \
            mol.atoms[atid].atname + ' : ' + attyp1, '-->', attyp2)

    #-------------------------------------------------------------------------

    ########Print the pre-generated frcmod files##############

    #-------------------------------------------------------------------------

    fmf = open(prefcdf, 'w')

    #for atoms which changed atom types
    print('REMARK GOES HERE, THIS FILE IS GENERATED BY MCPB.PY', file=fmf)
    print('MASS', file=fmf)

    #for metal ions
    for i in ionids:
      attyp = attypdict[i][1]
      atname = mol.atoms[i].atname
      if len(atname) > 1:
        atname = atname[0] + atname[1:].lower()
      massi = Mass[atname]
      print('YES', attyp + ' '  + str(round(massi, 2))  + \
            '                              ' + atname + ' ion', file=fmf)

    #for ligating atoms
    for atid in atidtrans:
      if atid not in ionids: #not include metal ion
        atyp1 = attypdict[atid][0]
        atyp2 = attypdict[atid][1]
        print('YES', atyp2 + massparms[atyp1], file=fmf)

    #--------------------------------------------------------------------------
    bondparamsdict1 = {} #For metal ions
    bondparamsdict2 = {} #For the others

    print(' ', file=fmf)
    print('BOND', file=fmf)

    #for bond
    for bonds in all_list.bondlist:
      i = bonds[0]
      j = bonds[1]
      if list(set(ionids) & set(bonds)) != []:
        #The bonds which related to the ions
        bondtyp2 = (attypdict[i][1], attypdict[j][1])
        if (bondtyp2 not in list(bondparamsdict1.keys())) and (bondtyp2[::-1] \
            not in list(bondparamsdict1.keys())):
          bondparamsdict1[bondtyp2] = ' '
      elif list(set(atidtrans) & set(bonds)) != []:
        #The bonds related to the atoms which changed their atom types
        bondtyp1 = (attypdict[i][0], attypdict[j][0])
        bondtyp2 = (attypdict[i][1], attypdict[j][1])
        if (bondtyp2 not in list(bondparamsdict2.keys())) and (bondtyp2[::-1] \
            not in list(bondparamsdict2.keys())):
          if bondtyp1 in list(bondparms.keys()):
            bondparamsdict2[bondtyp2] = bondparms[bondtyp1]
          elif bondtyp1[::-1] in list(bondparms.keys()):
            bondparamsdict2[bondtyp2] = bondparms[bondtyp1[::-1]]

    for i in sorted(list(bondparamsdict1.keys())):
      print('NON', i[0] + '-' + i[1] + bondparamsdict1[i], file=fmf)

    for i in sorted(list(bondparamsdict2.keys())):
      print('YES', i[0] + '-' + i[1] + bondparamsdict2[i], file=fmf)

    #--------------------------------------------------------------------------
    coparas = []

    r_smresf = open(smresf, 'r')
    for line in r_smresf:
      line = line.strip('\n')
      line = line.split('-')
      resid = int(line[1])
      if ('GLY' in line) or ('KCO' in line) or ('ACE' in line):
        if resid+1 not in resids:
          coparas.append(resid)
    r_smresf.close()

    angparamsdict1 = {} #For metal ions
    angparamsdict2 = {} #For the others
    print(' ', file=fmf)
    print('ANGL', file=fmf)
    #for angle
    for angs in all_list.anglist:
      i = angs[0]
      j = angs[1]
      k = angs[2]
      if list(set(ionids) & set(angs)) != []:
        #The angles which related to the ions
        angtyp2 = (attypdict[i][1], attypdict[j][1], attypdict[k][1])
        if (angtyp2 not in list(angparamsdict1.keys())) and (angtyp2[::-1] \
            not in list(angparamsdict1.keys())):
          angparamsdict1[angtyp2] = ' '
        #print >> fmf, 'NON', attypdict[i][1] + '-' + attypdict[j][1] + \
        #'-' + attypdict[k][1]
      elif list(set(atidtrans) & set(angs)) != []:
        #The angles related to the atoms
        #which changed their atom types
        angtyp1 = (attypdict[i][0], attypdict[j][0], attypdict[k][0])
        angtyp2 = (attypdict[i][1], attypdict[j][1], attypdict[k][1])
        if (angtyp2 not in list(angparamsdict2.keys())) and (angtyp2[::-1] \
            not in list(angparamsdict2.keys())):
          if angtyp1 in list(angparms.keys()):
            angparamsdict2[angtyp2] = angparms[angtyp1]
          elif angtyp1[::-1] in list(angparms.keys()):
            angparamsdict2[angtyp2] = angparms[angtyp1[::-1]]

    #Add for a specific situation
    for i in coparas:
      for atid in atidtrans:
        if mol.atoms[atid].atname == 'O' and mol.atoms[atid].resid == i:
          angtyp1 = (attypdict[atid][0], 'C ', 'N ')
          angtyp2 = (attypdict[atid][1], 'C ', 'N ')
          if (angtyp2 not in list(angparamsdict2.keys())) and (angtyp2[::-1] \
              not in list(angparamsdict2.keys())):
            if angtyp1 in list(angparms.keys()):
              angparamsdict2[angtyp2] = angparms[angtyp1]
            elif angtyp1[::-1] in list(angparms.keys()):
              angparamsdict2[angtyp2] = angparms[angtyp1[::-1]]

    for i in sorted(list(angparamsdict1.keys())):
      print('NON', i[0] + '-' + i[1] + '-' + i[2] + angparamsdict1[i], file=fmf)
    for i in sorted(list(angparamsdict2.keys())):
      print('YES', i[0] + '-' + i[1] + '-' + i[2] + angparamsdict2[i], file=fmf)

    #--------------------------------------------------------------------------
    dihparamsdict = {}

    #for dihedral
    for dihs in all_list.dihlist:
      i = dihs[0]
      j = dihs[1]
      k = dihs[2]
      l = dihs[3]
      if list(set(ionids) & set(dihs)) != []:
        #The dihedral related to the metal ions
        dihtyp1 = (attypdict[i][0], attypdict[j][0], attypdict[k][0], \
                   attypdict[l][0])
        dihtyp1n = (attypdict[i][1], attypdict[j][1], attypdict[k][1], \
                    attypdict[l][1])
        if (dihtyp1 not in list(dihparamsdict.keys())) and (dihtyp1[::-1] \
           not in list(dihparamsdict.keys())):
          dihparamsdict[dihtyp1n] = ['   3    0.00          0.0   ', \
                                     '          3.   ', ' ']
      elif list(set(atidtrans) & set(dihs)) != []:
        if list(set(atidtrans) & set(dihs[0::3])) == []:
        #Neither the 1st and 4th atom change atom types
        #There is 2nd or 3rd or both changed atom type(s)
          dihtyp1 = (attypdict[i][0], attypdict[j][0], attypdict[k][0], \
                     attypdict[l][0])
          dihtyp1n = (attypdict[i][1], attypdict[j][1], attypdict[k][1], \
                      attypdict[l][1])
          dihtyp2 = ('X ', attypdict[j][0], attypdict[k][0], 'X ')
          dihtyp2n = ('X ', attypdict[j][1], attypdict[k][1], 'X ')

          if dihtyp1 in list(dihparms.keys()):
            if (dihtyp1n not in list(dihparamsdict.keys())) and (dihtyp1n[::-1] \
                not in list(dihparamsdict.keys())):
              dihparamsdict[dihtyp1n] = dihparms[dihtyp1]
          elif dihtyp1[::-1] in list(dihparms.keys()):
            if (dihtyp1n not in list(dihparamsdict.keys())) and (dihtyp1n[::-1] \
                not in list(dihparamsdict.keys())):
              dihparamsdict[dihtyp1n] = dihparms[dihtyp1[::-1]]
          elif dihtyp2 in list(dihparms.keys()):
            if (dihtyp2n not in list(dihparamsdict.keys())) and (dihtyp2n[::-1] \
                not in list(dihparamsdict.keys())):
              dihparamsdict[dihtyp2n] = dihparms[dihtyp2]
          elif dihtyp2[::-1] in list(dihparms.keys()):
            if (dihtyp2n not in list(dihparamsdict.keys())) and (dihtyp2n[::-1] \
                not in list(dihparamsdict.keys())):
              dihparamsdict[dihtyp2n] = dihparms[dihtyp2[::-1]]
          else:
            if (dihtyp1n not in list(dihparamsdict.keys())) and (dihtyp1n[::-1] \
                not in list(dihparamsdict.keys())):
              dihparamsdict[dihtyp1n] = ['   3    0.00          0.0   ', \
                                         '          3.   ', ' ']
        else:
        #There is 1st or 4th atoms or both changed the atom type(s)
          dihtyp1 = (attypdict[i][0], attypdict[j][0], attypdict[k][0], \
                     attypdict[l][0])
          dihtyp1n = (attypdict[i][1], attypdict[j][1], attypdict[k][1], \
                      attypdict[l][1])
          dihtyp2 = ('X ', attypdict[j][1], attypdict[k][1], 'X ')

          if dihtyp1 in list(dihparms.keys()):
            if (dihtyp1n not in list(dihparamsdict.keys())) and (dihtyp1n[::-1] \
                not in list(dihparamsdict.keys())):
              dihparamsdict[dihtyp1n] = dihparms[dihtyp1]
          elif dihtyp1[::-1] in list(dihparms.keys()):
            if (dihtyp1n not in list(dihparamsdict.keys())) and (dihtyp1n[::-1] \
                not in list(dihparamsdict.keys())):
              dihparamsdict[dihtyp1n] = dihparms[dihtyp1[::-1]]
          else:
            if (dihtyp2 in list(dihparms.keys())) or (dihtyp2[::-1] \
                in list(dihparms.keys())):
              continue
            elif (dihtyp1n not in list(dihparamsdict.keys())) and (dihtyp1n[::-1] \
                  not in list(dihparamsdict.keys())):
              dihparamsdict[dihtyp1n] = ['   3    0.00          0.0   ', \
                                         '          3.   ', ' ']

    #Add for a specfic situation
    for i in coparas:
      for atid in atidtrans:
        if mol.atoms[atid].atname == 'O' and mol.atoms[atid].resid == i:
          for ionid in ionids:
            if ((atid, ionid, 1) in all_list.bondlist) or \
               ((ionid, atid, 1) in all_list.bondlist):
              dihtyp1 = (attypdict[ionid][0], attypdict[atid][0], 'C ', 'N ')
              dihtyp2 = (attypdict[ionid][1], attypdict[atid][1], 'C ', 'N ')
              if (dihtyp2 not in dihparamsdict) and (dihtyp2[::-1] not in dihparamsdict):
                if dihtyp1 in list(dihparms.keys()):
                  dihparamsdict[dihtyp2] = dihparms[dihtyp1]
                elif dihtyp1[::-1] in list(dihparms.keys()):
                  dihparamsdict[dihtyp2] = dihparms[dihtyp1[::-1]]
                else:
                  dihparamsdict[dihtyp2] = ['   3    0.00          0.0   ', \
                                         '          3.   ', ' ']

    print(' ', file=fmf)
    print('DIHE', file=fmf)
    for keyv in sorted(list(dihparamsdict.keys())):
      if 'X ' not in keyv: #For types don't contain X
        valv = dihparamsdict[keyv]
        keyv = keyv[0] + '-' + keyv[1] + '-' + keyv[2] + '-' + keyv[3]
        terms = len(valv)//3
        for i in range(0, terms):
          temp = i * 3
          print('YES', keyv, valv[temp] + valv[temp+1] + \
                   valv[temp+2], file=fmf)

    for keyv in sorted(list(dihparamsdict.keys())):
      if 'X ' in keyv:     #For types contain X
        valv = dihparamsdict[keyv]
        keyv = keyv[0] + '-' + keyv[1] + '-' + keyv[2] + '-' + keyv[3]
        terms = len(valv)//3
        for i in range(0, terms):
          temp = i * 3
          print('YES', keyv, valv[temp] + valv[temp+1] + \
                   valv[temp+2], file=fmf)
    #--------------------------------------------------------------------------
    impparamsdict = {}

    #For improper torsion
    for imps in all_list.implist:
      i = imps[0]
      j = imps[1]
      k = imps[2]
      l = imps[3]

      if list(set(ionids) & set(imps)) != []:
        continue
      elif list(set(atidtrans) & set(imps)) != []:
        imptyps = {}

        #1 situation
        imptyp1 = (attypdict[i][0], attypdict[j][0], attypdict[k][0], \
                   attypdict[l][0])
        imptyp1n = (attypdict[i][1], attypdict[j][1], attypdict[k][1], \
                    attypdict[l][1])

        #3 situations
        imptyp2 = ('X ', 'X ', attypdict[k][0], attypdict[i][0])
        imptyp2n = ('X ', 'X ', attypdict[k][1], attypdict[i][1])

        imptyp3 = ('X ', 'X ', attypdict[k][0], attypdict[j][0])
        imptyp3n = ('X ', 'X ', attypdict[k][1], attypdict[j][1])

        imptyp4 = ('X ', 'X ', attypdict[k][0], attypdict[l][0])
        imptyp4n = ('X ', 'X ', attypdict[k][1], attypdict[l][1])

        #6 situations
        imptyp5 = ('X ', attypdict[i][0], attypdict[k][0], attypdict[j][0])
        imptyp5n = ('X ', attypdict[i][1], attypdict[k][1], attypdict[j][1])

        imptyp6 = ('X ', attypdict[j][0], attypdict[k][0], attypdict[i][0])
        imptyp6n = ('X ', attypdict[j][1], attypdict[k][1], attypdict[i][1])

        imptyp7 = ('X ', attypdict[i][0], attypdict[k][0], attypdict[l][0])
        imptyp7n = ('X ', attypdict[i][0], attypdict[k][1], attypdict[l][1])

        imptyp8 = ('X ', attypdict[l][0], attypdict[k][0], attypdict[i][0])
        imptyp8n = ('X ', attypdict[l][1], attypdict[k][1], attypdict[i][1])

        imptyp9 = ('X ', attypdict[j][0], attypdict[k][0], attypdict[l][0])
        imptyp9n = ('X ', attypdict[j][1], attypdict[k][1], attypdict[l][1])

        imptyp10 = ('X ', attypdict[l][0], attypdict[k][0], attypdict[j][0])
        imptyp10n = ('X ', attypdict[l][1], attypdict[k][1], attypdict[j][1])

        imptyps[imptyp1] = imptyp1n
        imptyps[imptyp2] = imptyp2n
        imptyps[imptyp3] = imptyp3n
        imptyps[imptyp4] = imptyp4n
        imptyps[imptyp5] = imptyp5n
        imptyps[imptyp6] = imptyp6n
        imptyps[imptyp7] = imptyp7n
        imptyps[imptyp8] = imptyp8n
        imptyps[imptyp9] = imptyp9n
        imptyps[imptyp10] = imptyp10n

        for imptypkey in list(imptyps.keys()):
          if imptypkey in list(impparms.keys()):
            impparamsdict[imptyps[imptypkey]] = impparms[imptypkey]

    print(' ', file=fmf)
    print('IMPR', file=fmf)
    #for improper torsion
    for i in sorted(list(impparamsdict.keys())):
      if i not in list(impparms.keys()):
        imptypkey = i[0] + '-' + i[1] + '-' + i[2] + '-' + i[3]
        print('YES', imptypkey, impparamsdict[i], file=fmf)
    #--------------------------------------------------------------------------
    #for nb
    print(' ', file=fmf)
    print('NONB', file=fmf)

    #For metal ions
    IonLJParaDict = get_ionljparadict(watermodel)
    for i in ionids:
      element = mol.atoms[i].element
      chg = str(int(chargedict[mol.atoms[i].resname]))
      attyp2 = attypdict[i][1]
      rmin = IonLJParaDict[element + chg][0]
      ep = IonLJParaDict[element + chg][1]
      annot = IonLJParaDict[element + chg][2]
      print('YES   %s    %11.3f  %13.10f       %-s' %(attyp2, rmin, \
               ep, annot), file=fmf)

    #For the others
    for atid in atidtrans: 
      if atid not in ionids:
        attyp1 = attypdict[atid][0]
        attyp2 = attypdict[atid][1]
        print('YES  ', attyp2 + nbparms[attyp1], file=fmf)

    print(' ', file=fmf)
    print(' ', file=fmf)

    fmf.close()
    #--------------------------------------------------------------------------

    #Move the file, delete the repeat parts
    os.system("mv %s temp" %prefcdf)
    os.system("uniq temp > %s" %prefcdf)
    os.system("rm temp")