def get_6dof_cst(D3, D2, D1, U1, U2, U3):
    cur_cst = {
        "distanceAB": [0.0, 0.2, 80.0, 0, 0],
        "angle_A": [0.0, 5.0, 10.0, 360, 0],
        "angle_B": [0.0, 5.0, 10.0, 360, 0],
        "torsion_A": [0.0, 10.0, 10.0, 360, 0],
        "torsion_AB": [0.0, 10.0, 10.0, 360, 0],
        "torsion_B": [0.0, 10.0, 10.0, 360, 0]
    }
    if U1.split("/")[-1] == "NZ" and U2.split("/")[-1] == "CE" and U3.split(
            "/")[-1] == "2HZ":  #means processing constraint for LYS
        cur_cst = {
            "distanceAB": [
                0.0, 0.1, 80.0, 1, 0
            ],  #the only difference is periodicity will be set at 1 indicating covalent interaction in the cst file
            "angle_A": [0.0, 5.0, 10.0, 360, 0],
            "angle_B": [0.0, 5.0, 10.0, 360, 0],
            "torsion_A": [0.0, 10.0, 10.0, 360, 0],
            "torsion_AB": [0.0, 10.0, 10.0, 360, 0],
            "torsion_B": [0.0, 10.0, 10.0, 360, 0]
        }
    cur_cst["distanceAB"][0] = round(cmd.get_distance(D1, U1), 1)
    cur_cst["angle_A"][0] = round(cmd.get_angle(D2, D1, U1), 1)
    cur_cst["angle_B"][0] = round(cmd.get_angle(D1, U1, U2), 1)
    cur_cst["torsion_A"][0] = round(cmd.get_dihedral(D3, D2, D1, U1), 1)
    cur_cst["torsion_AB"][0] = round(cmd.get_dihedral(D2, D1, U1, U2), 1)
    cur_cst["torsion_B"][0] = round(cmd.get_dihedral(D1, U1, U2, U3), 1)
    return cur_cst
Пример #2
0
def check_disulphide_criteria(pdb, resnum_i, resnum_j, f):
	selection_i = "resi " + str(resnum_i)
	selection_j = "resi " + str(resnum_j)

	for frame_i in [1, 2]:
		rotamer_i_pymol_prefix = "/" + "rotamer_" + str(resnum_i) + "_" + str(frame_i) + "///" + resnum_i + "/"

		chi1_i = cmd.get_dihedral(rotamer_i_pymol_prefix + "N", rotamer_i_pymol_prefix + "CA", rotamer_i_pymol_prefix + "CB", rotamer_i_pymol_prefix + "SG")
		theta_i = cmd.get_angle(rotamer_i_pymol_prefix + "CA", rotamer_i_pymol_prefix + "CB", rotamer_i_pymol_prefix + "SG")

		for frame_j in [1, 2]:
			rotamer_j_pymol_prefix = "/" + "rotamer_" + str(resnum_j) + "_" + str(frame_j) + "///" + resnum_j + "/"
	
			chi1_j = cmd.get_dihedral(rotamer_j_pymol_prefix + "N", rotamer_j_pymol_prefix + "CA", rotamer_j_pymol_prefix + "CB", rotamer_j_pymol_prefix + "SG")
			theta_j = cmd.get_angle(rotamer_j_pymol_prefix + "CA", rotamer_j_pymol_prefix + "CB", rotamer_j_pymol_prefix + "SG")

			chi3 = cmd.get_dihedral(rotamer_i_pymol_prefix + "CB", rotamer_i_pymol_prefix + "SG", rotamer_j_pymol_prefix + "SG", rotamer_j_pymol_prefix + "CB")

			#Energy = compute_energy(chi1_i, chi1_j, theta_i, theta_j, chi3)

			s_gamma_distance = cmd.get_distance(rotamer_i_pymol_prefix + "SG", rotamer_j_pymol_prefix + "SG")	
			if (s_gamma_distance < 3 and ((chi3 > -110 and chi3 < -60) or (chi3 > 70 and chi3 < 130))):
				print rotamer_i_pymol_prefix, rotamer_j_pymol_prefix, s_gamma_distance, chi3
				f.write("%s\t%s\t%f\t%f\n" % (rotamer_i_pymol_prefix, rotamer_j_pymol_prefix, s_gamma_distance, chi3))
				rotamer_i = "rotamer_" + str(resnum_i) + "_" + str(frame_i)
				rotamer_j = "rotamer_" + str(resnum_j) + "_" + str(frame_j)
				cmd.enable(rotamer_i)
				cmd.enable(rotamer_j)
				cmd.distance(rotamer_i_pymol_prefix + "SG", rotamer_j_pymol_prefix + "SG")
				cmd.create(rotamer_i + rotamer_j, rotamer_i_pymol_prefix + "or" + rotamer_j_pymol_prefix)
Пример #3
0
 def test_torsion(self):
     cmd.fragment('ala')
     delta = 10
     atoms = ('ID 7', 'ID 2', 'ID 1', 'ID 9')
     d1 = cmd.get_dihedral(*atoms)
     cmd.edit(*atoms[1:3])
     cmd.torsion(delta)
     d2 = cmd.get_dihedral(*atoms)
     self.assertAlmostEqual(d1 + delta, d2, 4)
Пример #4
0
 def test_torsion(self):
     cmd.fragment('ala')
     delta = 10
     atoms = ('ID 7', 'ID 2', 'ID 1', 'ID 9')
     d1 = cmd.get_dihedral(*atoms)
     cmd.edit(*atoms[1:3])
     cmd.torsion(delta)
     d2 = cmd.get_dihedral(*atoms)
     self.assertAlmostEqual(d1 + delta, d2, 4)
Пример #5
0
        def start(self,sel):

            # Get selection model
            model = cmd.get_model(sel)
            residues = ['dummy']
            resnames = ['dummy']
            phi = []
            psi = []
            dummy = []
            i = 0

            # Loop through each atom
            for at in model.atom:

                # Only plot once per residue
                if at.chain+":"+at.resn+":"+at.resi not in residues:
                    residues.append(at.chain+":"+at.resn+":"+at.resi)
                    resnames.append(at.resn+at.resi)
                    dummy.append(i)
                    i += 1

                    # Check for a null chain id (some PDBs contain this)
                    unit_select = ""
                    if at.chain != "":
                        unit_select = "chain "+str(at.chain)+" and "

                    # Define selections for residue i-1, i and i+1
                    residue_def = unit_select+'resi '+str(at.resi)
                    residue_def_prev = unit_select+'resi '+str(int(at.resi)-1)
                    residue_def_next = unit_select+'resi '+str(int(at.resi)+1)

                    try:
                        # Store phi,psi residue definitions to pass on to plot routine
                        phi_psi = [
                                # Phi angles
                                   residue_def_prev+' and name C',
                                   residue_def+' and name N',
                                   residue_def+' and name CA',
                                   residue_def+' and name C',
                                # Psi angles
                                   residue_def+' and name N',
                                   residue_def+' and name CA',
                                   residue_def+' and name C',
                                   residue_def_next+' and name N']

                        # Compute phi/psi angle
                        phi = cmd.get_dihedral(phi_psi[0],phi_psi[1],phi_psi[2],phi_psi[3])
                        psi = cmd.get_dihedral(phi_psi[4],phi_psi[5],phi_psi[6],phi_psi[7])

                        print "Plotting Phi,Psi: "+str(phi)+","+str(psi)
                        ramaplot(phi,psi,meta=phi_psi)
                    except:
                        continue
Пример #6
0
def set_phipsi(sel, phi, psi):
    # Get atoms from selection
    atoms = cmd.get_model("byres (" + sel + ")")

    # Loop through atoms in selection
    for at in atoms.atom:  # pylint: disable=E1103
        if at.name == "N":
            # Check for a null chain id (some PDBs contain this)
            unit_select = ""
            if not at.chain == "":
                unit_select = "chain " + str(at.chain) + " and "
            # end if

            try:
                # Define residue selections
                rdef_prev = unit_select + 'resi ' + str(int(at.resi) - 1)
                rdef = unit_select + 'resi ' + str(at.resi)
                #                print "rdef_prev: [%s]" % rdef_prev
                #                print "rdef     : [%s]" % rdef
                if at.resn == "PRO":
                    print "Skipping setting phi for PRO"
                else:
                    old_phi = cmd.get_dihedral(rdef_prev + ' and name C',
                                               rdef + ' and name N',
                                               rdef + ' and name CA',
                                               rdef + ' and name C')
                    cmd.set_dihedral(rdef_prev + ' and name C',
                                     rdef + ' and name N',
                                     rdef + ' and name CA',
                                     rdef + ' and name C', phi)
                    print "Changed residue %4s %4s phi: from %6.1f to %6.1f" % (
                        at.resn, at.resi, old_phi, float(phi))
            except:

                print "Note skipping set of phi because of error; this is normal for a N-terminal residue"
            try:
                rdef = unit_select + 'resi ' + str(at.resi)
                residue_def_next = unit_select + 'resi ' + str(
                    int(at.resi) + 1)
                #                print "rdef     : [%s]" % rdef
                #                print "residue_def_next: [%s]" % residue_def_next
                old_psi = cmd.get_dihedral(rdef + ' and name N',
                                           rdef + ' and name CA',
                                           rdef + ' and name C',
                                           residue_def_next + ' and name N')
                cmd.set_dihedral(rdef + ' and name N', rdef + ' and name CA',
                                 rdef + ' and name C',
                                 residue_def_next + ' and name N', psi)  # pylint: disable=C0301
                print "Changed residue %4s %4s psi: from %6.1f to %6.1f" % (
                    at.resn, at.resi, old_psi, float(psi))
            except:
                print "Note skipping set of psi; this is normal for a C terminal residue"
Пример #7
0
def main():

    args = parse_args()
    pep_pdbs = read_rmsd(args)

    for i in range(0, 7):
        outputfilehandler = open('phi_psi_' + str(i + 2) + '.csv', 'w')
        outputfilehandler.write("pdb,chain,pep_seq,index,phi,psi\n")
        outputfilehandler.close()

    for key in pep_pdbs:
        phi = []
        psi = []
        model_name = key + '_reordered'
        pdbfile = key + '_reordered.pdb'
        targetfile = args.dir + '/' + pdbfile

        cmd.load(targetfile)
        chains = cmd.get_chains(model_name)

        try:
            #psi.append(cmd.get_dihedral(chains[1]+"/1/N,",chains[1]+"/1/ca,",chains[1]+"/1/c,",chains[1]+"/2/n"))
            #phi_psi = cmd.phi_psi(model_name+ " and chain "+chains[1])
            for i in range(2, 9):
                phi.append(
                    cmd.get_dihedral(chains[1] + "/" + str(i - 1) + "/c,",
                                     chains[1] + "/" + str(i) + "/n,",
                                     chains[1] + "/" + str(i) + "/ca,",
                                     chains[1] + "/" + str(i) + "/c"))
                psi.append(
                    cmd.get_dihedral(chains[1] + "/" + str(i) + "/N,",
                                     chains[1] + "/" + str(i) + "/ca,",
                                     chains[1] + "/" + str(i) + "/c,",
                                     chains[1] + "/" + str(i + 1) + "/n"))

            #phi.append(cmd.get_dihedral(chains[1]+"/8/c,",chains[1]+"/9/n,",chains[1]+"/9/ca,",chains[1]+"/9/c"))

        except:
            print("Found exception, ignoring")

        if len(phi) == 7 and len(psi) == 7:
            for i in range(0, len(phi)):
                outputfilehandler = open('phi_psi_' + str(i + 2) + '.csv', 'a')
                print(pep_pdbs[key] + ',' + chains[1] + ',' + str(i + 2) +
                      ',' + str(phi[i]) + ',' + str(psi[i]))
                outputfilehandler.write(key + ',' + chains[1] + ',' +
                                        pep_pdbs[key] + ',' + str(i + 2) +
                                        ',' + str(phi[i]) + ',' + str(psi[i]) +
                                        '\n')
                outputfilehandler.close()

        pymol.cmd.do("delete all")
Пример #8
0
 def doFinish(self):
     r_aA = cmd.get_distance(atom1="pw2", atom2="pw3", state=0)
     cmd.distance(self.params_str[0], "pw2", "pw3")
     th_a = cmd.get_angle(atom1="pw1", atom2="pw2", atom3="pw3", state=0)
     cmd.angle(self.params_str[1], "pw1", "pw2", "pw3")
     th_A = cmd.get_angle(atom1="pw2", atom2="pw3", atom3="pw4", state=0)
     cmd.angle(self.params_str[2], "pw2", "pw3", "pw4")
     if not (r_aA and th_a and th_A):
         showerror(self.parent, "Error!",
                   "Maybe you made a mistake when choosing atoms!")
         self.reset()
     phi_ba = cmd.get_dihedral(atom1="pw0",
                               atom2="pw1",
                               atom3="pw2",
                               atom4="pw3",
                               state=0)
     cmd.dihedral(self.params_str[3], "pw0", "pw1", "pw2", "pw3")
     phi_aA = cmd.get_dihedral(atom1="pw1",
                               atom2="pw2",
                               atom3="pw3",
                               atom4="pw4",
                               state=0)
     cmd.dihedral(self.params_str[4], "pw1", "pw2", "pw3", "pw4")
     phi_AB = cmd.get_dihedral(atom1="pw2",
                               atom2="pw3",
                               atom3="pw4",
                               atom4="pw5",
                               state=0)
     cmd.dihedral(self.params_str[5], "pw2", "pw3", "pw4", "pw5")
     index_c = cmd.id_atom("pw0")
     index_c_name = getAtomString('pw0')
     index_b = cmd.id_atom("pw1")
     index_b_name = getAtomString('pw1')
     index_a = cmd.id_atom("pw2")
     index_a_name = getAtomString('pw2')
     index_A = cmd.id_atom("pw3")
     index_A_name = getAtomString('pw3')
     index_B = cmd.id_atom("pw4")
     index_B_name = getAtomString('pw4')
     index_C = cmd.id_atom("pw5")
     index_C_name = getAtomString('pw5')
     self.setBondForceParam(r_aA, th_a, th_A, phi_ba, phi_aA, phi_AB,
                            index_c, index_b, index_a, index_A, index_B,
                            index_C)
     self.setAtomsDef(index_c_name, index_b_name, index_a_name,
                      index_A_name, index_B_name, index_C_name)
     top = Toplevel(
         self.parent)  # <- freeze when open gro file in pymol 1.X
     Output(top, self.bondForceParams, self.atoms_def)
     cmd.set_wizard()
Пример #9
0
 def test_set_dihedral(self):
     cmd.fragment('ala')
     angle = 45.0
     atoms = ('ID 7', 'ID 2', 'ID 1', 'ID 9')
     cmd.set_dihedral(*atoms, angle=angle)
     v = cmd.get_dihedral(*atoms)
     self.assertAlmostEqual(v, angle, 4)
Пример #10
0
def measure_all_torsions(sele,prot_dict):
   id_list = cmd.identify("((%s) and name ca)"%sele)
   for a in id_list:
      res_sele = "(alt '' and (byres id %d) and (%s))"%(a,sele)
      lst = find_torsions(res_sele)
      if len(lst):
         cmd.iterate("(%s and n;ca)"%res_sele,"stored.resn=resn")
         resn = pymol.stored.resn
         print(resn)
         name_list = []
         for a in lst:
            pymol.stored.names = []
            for b in a:
               cmd.iterate("(%s and id %d)"%(res_sele,b),"stored.names.append(name)")
            name_list.append(tuple(pymol.stored.names))
         res_dict = {}
         for a in name_list:
            dihe = cmd.get_dihedral("(%s and name %s)"%(res_sele,a[0]),
                                    "(%s and name %s)"%(res_sele,a[1]),
                                    "(%s and name %s)"%(res_sele,a[2]),
                                    "(%s and name %s)"%(res_sele,a[3]))
            res_dict[a]=dihe
         if resn not in prot_dict:
            prot_dict[resn]=[]
         prot_dict[resn].append(res_dict)
Пример #11
0
def measure_all_torsions(sele,prot_dict):
   id_list = cmd.identify("((%s) and name ca)"%sele)
   for a in id_list:
      res_sele = "(alt '' and (byres id %d) and (%s))"%(a,sele)
      lst = find_torsions(res_sele)
      if len(lst):
         cmd.iterate("(%s and n;ca)"%res_sele,"stored.resn=resn")
         resn = pymol.stored.resn
         print resn
         name_list = []
         for a in lst:
            pymol.stored.names = []
            for b in a:
               cmd.iterate("(%s and id %d)"%(res_sele,b),"stored.names.append(name)")
            name_list.append(tuple(pymol.stored.names))
         res_dict = {}
         for a in name_list:
            dihe = cmd.get_dihedral("(%s and name %s)"%(res_sele,a[0]),
                                    "(%s and name %s)"%(res_sele,a[1]),
                                    "(%s and name %s)"%(res_sele,a[2]),
                                    "(%s and name %s)"%(res_sele,a[3]))
            res_dict[a]=dihe
         if not prot_dict.has_key(resn):
            prot_dict[resn]=[]
         prot_dict[resn].append(res_dict)
Пример #12
0
def get_psi_angle(pymol_object, chainID, aa_number):
    """Get Psi dihedral angle of a given residue.

    Parameters
    ----------
    pymol_object : String
        Name of Pymol object in the session.
    chainID : String
        ChainID of residue.
    aa_number : Integer
        Residue number.

    Returns
    -------
    angle : Float
        Value of Psi angle.

    """
    # Atom selection for each atom that participates in the angle
    # Ni
    atom1 = pymol_object + '//' + chainID + '/' + str(aa_number) + '/N'
    # CAi
    atom2 = pymol_object + '//' + chainID + '/' + str(aa_number) + '/CA'
    # Ci
    atom3 = pymol_object + '//' + chainID + '/' + str(aa_number) + '/C'
    # Ni+1
    atom4 = pymol_object + '//' + chainID + '/' + str(aa_number+1) + '/N'

    angle = cmd.get_dihedral(atom1, atom2, atom3, atom4)

    return angle
 def updateSels(self,event):
     
     if (event.widget.widgetName == "toplevel"):
         selections = self.getSels()
         
         #set objects in box for adding Hs
         objects = cmd.get_names_of_type("object:molecule");
         if list(self.h_sel.get()) != list(objects):
             self.h_sel.setlist(objects)
         
         selections = objects+selections
         for cBox in self.cBoxes:
             listEles = cBox.component('scrolledlist').get()
             #listEles = cBox.get()
             if list(selections) != list(listEles):
                 cBox.setlist(selections)
         
         #Rotamer Dihedral Code
         if('pkresi' in cmd.get_names("public_selections")):
             cmd.select('_kropkresi','pkresi')       
             myspace = {'resName': [], 'resNum': []}
             cmd.iterate('_kropkresi and name CA', 'resName.append(resn);resNum.append(resi)',  space=myspace)
             
             if(list(myspace['resName']) != list(self.rotResList) or list(myspace['resNum']) != list(self.rotResIList)):
                 self.rotResList = myspace['resName']
                 self.rotResIList = myspace['resNum']
                 if(len(self.rotResList) == 1):
                     resn = self.rotResList[0].upper()
                 
                     if(resn in self.AAtypes):
                         aa = self.AAtypes[resn]
                         self.curAAtype = aa
                         numDih = len(aa.dihAtomNames)
                         
                         #set orig dihVals
                         self.origRotVals = []
                         for atoms in self.AAtypes[resn].dihAtomNames:
                             self.origRotVals.append(cmd.get_dihedral('_kropkresi and name ' + atoms[0], '_kropkresi and name ' + atoms[1], '_kropkresi and name ' + atoms[2], 
                                              '_kropkresi and name ' + atoms[3]))
                             
                         for i,val in enumerate(self.origRotVals):
                             self.dihScale[i].grid()
                             self.dihScale[i].set(val)
                         for i in range(numDih,4):
                             self.dihScale[i].grid_remove()    
                             
                         self.rotsToAdd = []
                         self.rotsToAdd.append("orig")
                         for vals in self.AAtypes[resn].dihVals:
                             self.rotsToAdd.append(vals)
                             
                         self.rotBox.setlist(self.rotsToAdd)
                         resStr = self.rotResList[0] + " " + str(self.rotResIList[0])
                         self.resLabel.config(text=resStr)
                         self.dotCheckCB()    
                                 
                     else:
                         self.clearRot()
                 else:
                     self.clearRot()
Пример #14
0
 def test_set_dihedral(self):
     cmd.fragment('ala')
     angle = 45.0
     atoms = ('ID 7', 'ID 2', 'ID 1', 'ID 9')
     cmd.set_dihedral(*atoms, angle=angle)
     v = cmd.get_dihedral(*atoms)
     self.assertAlmostEqual(v, angle, 4)
Пример #15
0
 def test_CorrectChiDihedral(self):
     cmd.load(self.datafile("1rna.cif"))
     src_dihedral = cmd.get_dihedral("/1rna/A/A/14 & name O4'",
                                     "/1rna/A/A/14 & name C1'",
                                     "/1rna/A/A/14 & name N9",
                                     "/1rna/A/A/14 & name C4'")
     cmd.wizard("nucmutagenesis")
     cmd.select("/1rna/A/A/14")
     cmd.get_wizard().mode = "Guanine"
     cmd.get_wizard().do_select("sele")
     cmd.get_wizard().apply()
     des_dihedral = cmd.get_dihedral("/1rna/A/A/14 & name O4'",
                                     "/1rna/A/A/14 & name C1'",
                                     "/1rna/A/A/14 & name N9",
                                     "/1rna/A/A/14 & name C4'")
     self.assertAlmostEqual(src_dihedral, des_dihedral, delta = 2.0)
Пример #16
0
def is_pro_cis_or_trans(obj, resi, chain=None):
    gen_sel = '%s and chain %s and resi %s ' % (obj, chain, resi)
    cmd.select(
        'temp_O',
        '%s and chain %s and resi %i and name O' % (obj, chain, int(resi) - 1))
    cmd.select(
        'temp_C',
        '%s and chain %s and resi %i and name C' % (obj, chain, int(resi) - 1))
    cmd.select('temp_N', '%s and name N' % gen_sel)
    cmd.select('temp_CD', '%s and name CD' % gen_sel)

    dihedral = cmd.get_dihedral('temp_O',
                                'temp_C',
                                'temp_N',
                                'temp_CD',
                                state=0)
    if -170 <= dihedral <= 190:
        cis_or_trans = 'trans'
    elif -10 <= dihedral <= +10:
        cis_or_trans = 'cis'
    else:
        cis_or_trans = 'unknown'
    print('the dihedral is %.2f, I think it is %s' % (dihedral, cis_or_trans))

    for atom in ['O', 'C', 'N', 'CD']:
        cmd.delete('temp_%s' % atom)
Пример #17
0
 def test_CorrectChiDihedral(self):
     cmd.load(self.datafile("1rna.cif"))
     src_dihedral = cmd.get_dihedral("/1rna/A/A/14 & name O4'",
                                     "/1rna/A/A/14 & name C1'",
                                     "/1rna/A/A/14 & name N9",
                                     "/1rna/A/A/14 & name C4'")
     cmd.wizard("nucmutagenesis")
     cmd.select("/1rna/A/A/14")
     cmd.get_wizard().mode = "Guanine"
     cmd.get_wizard().do_select("sele")
     cmd.get_wizard().apply()
     des_dihedral = cmd.get_dihedral("/1rna/A/A/14 & name O4'",
                                     "/1rna/A/A/14 & name C1'",
                                     "/1rna/A/A/14 & name N9",
                                     "/1rna/A/A/14 & name C4'")
     self.assertAlmostEqual(src_dihedral, des_dihedral, delta=2.0)
Пример #18
0
def DihedralFromPKSelection (selections = []):
    """ Function doc """
    dihedral = {}
    if 'pk4' in selections:
        dihedral['pk1pk2pk3pk4'] = str(cmd.get_dihedral ('pk1','pk2','pk3','pk4')) 
    else:
        dihedral['pk1pk2pk3pk4'] = None  
    return dihedral
Пример #19
0
 def getdihedral(selection, resids, atomnames):
     # first check if all atoms are present and unique:
     for an, resi in zip(atomnames, resids):
         presentandunique(selection, resi, an)
     return cmd.get_dihedral(*[
         '({0}) and (resi {1}) and (name {2})'.format(selection, resi, an)
         for resi, an in zip(resids, atomnames)
     ],
                             quiet=True)
Пример #20
0
def get_dihedral(modelname, nameandresi1, nameandresi2, nameandresi3,
                 nameandresi4):
    """A safer version of cmd.get_dihedral(): doesn't choke on non-singleton selections"""
    selections = [
        '({}) and name {} and resi {}'.format(modelname, *nr)
        for nr in [nameandresi1, nameandresi2, nameandresi3, nameandresi4]
    ]
    if not all([cmd.count_atoms(s) == 1 for s in selections]):
        return None
    return cmd.get_dihedral(*selections)
Пример #21
0
def get_chi(obj, resi, state): 
    """
    Get the dihedral angle chi (C1-O'x-C'x-C'x-1)
    """
    atom1 = '%s and resi %s and name N' % (obj, resi)
    atom2 = '%s and resi %s and name CA'% (obj, resi)
    atom3 = '%s and resi %s and name CB' % (obj, resi)
    atom4 = '%s and resi %s and name CG' % (obj, resi)
    value = cmd.get_dihedral(atom1, atom2, atom3, atom4, state=state)
    return value 
Пример #22
0
def get_phi(res_num, state):
    """Computes the phi torsional angle"""
    if res_num != 0:
        cmd.select('A', 'resi %s and name C' % (res_num-1))
        cmd.select('B', 'resi %s and name N' % res_num)
        cmd.select('C', 'resi %s and name CA' % res_num)
        cmd.select('D', 'resi %s and name C' % res_num)
        return cmd.get_dihedral('A', 'B', 'C', 'D', state)
    else:
        return float('nan')
Пример #23
0
def get_omega(obj, bond, state=1): 
    """
    Get the dihedral angle omega (O6-C6-C5-C4)
    """
    resi_i, resi_j, atom_i, atom_j = bond[0], bond[2], bond[4], bond[5]
    atom1 = '%s and resi %s and name O6' % (obj, resi_j)
    atom2 = '%s and resi %s and name C6' % (obj, resi_j)
    atom3 = '%s and resi %s and name C5' % (obj, resi_j)
    atom4 = '%s and resi %s and name C4' % (obj, resi_j)
    value = cmd.get_dihedral(atom1, atom2, atom3, atom4, state=state)
    return value
Пример #24
0
def get_omega(obj, bond, state=1):
    """
    Get the dihedral angle omega (O6-C6-C5-C4)
    """
    resi_i, resi_j, atom_i, atom_j = bond[0], bond[2], bond[4], bond[5]
    atom1 = '%s and resi %s and name O6' % (obj, resi_j)
    atom2 = '%s and resi %s and name C6' % (obj, resi_j)
    atom3 = '%s and resi %s and name C5' % (obj, resi_j)
    atom4 = '%s and resi %s and name C4' % (obj, resi_j)
    value = cmd.get_dihedral(atom1, atom2, atom3, atom4, state=state)
    return value
Пример #25
0
def get_chi2(res_num, res_name, state):
    """Computes the chi2 torsional angle"""
    if res_name not in ['ALA', 'GLY', 'PRO', 'SER', 'THR', 'VAL', 'CYS']:
        cmd.select('A', 'resi %s and name CA' % res_num)
        cmd.select('B', 'resi %s and name CB' % res_num)
        cmd.select('C', 'resi %s and (name CG or name CG1 or name OG1 or name OG)' % res_num)
        cmd.select('D', 'resi %s and (name CD or name CD1 or name OD1 or name ND1 or name SD)' % res_num)
        chi2 = cmd.get_dihedral('A', 'B', 'C', 'D', state)
        return chi2
    else:
        return float('nan')
Пример #26
0
def get_chi1(res_num, res_name, state):
    """Computes the chi1 torsional angle"""
    if res_name not in ['ALA', 'GLY', 'PRO']:
        cmd.select('A', 'resi %s and name N' % res_num)
        cmd.select('B', 'resi %s and name CA' % res_num)
        cmd.select('C', 'resi %s and name CB' % res_num)
        cmd.select('D', 'resi %s and (name CG or name CG1 or name OG1 or name OG or name SG)' % res_num)
        chi1 = cmd.get_dihedral('A', 'B', 'C', 'D', state)
        return chi1
    else:
        return float('nan')
Пример #27
0
def get_omega(res_num, state, total_residues):
    """Computes the omega torsional angle"""
    if res_num != total_residues-1:
        cmd.select('A', 'resi %s and name CA' % res_num)
        cmd.select('B', 'resi %s and name C' % res_num)
        cmd.select('C', 'resi %s and name N' % (res_num+1))
        cmd.select('D', 'resi %s and name CA' % (res_num+1))
        omega = cmd.get_dihedral('A', 'B', 'C', 'D', state)
        return omega
    else:
        return float('nan')
Пример #28
0
def hw3(model):

    cmd.remove(model + ' and resn hoh')
    cmd.remove(model + ' and not alt a+""')
    cmd.remove(model + ' and not chain A')

    resis = []
    cmd.iterate('/{}//A//CA'.format(model),
                'resis.append(resi)',
                space={'resis': resis})

    resis_int = map(int, resis)
    resis = map(sm, resis)

    #Pro

    resP = []
    cmd.iterate('/{}//A//CA'.format(model),
                'resP.append(resn == "PRO")',
                space={'resP': resP})

    angs_phi = []
    angs_psi = []
    for i in range(1, len(resis) - 1):
        if (resis_int[i - 1] + 1
                == resis_int[i]) and (resis_int[i] + 1
                                      == resis_int[i + 1]) and resP[i]:
            angs_phi.append(cmd.get_dihedral('/{}//A/{}/C'.format(model, resis[i-1]), \
              '/{}//A/{}/N'.format(model, resis[i]), \
              '/{}//A/{}/CA'.format(model, resis[i]), \
              '/{}//A/{}/C'.format(model, resis[i]))),
            angs_psi.append(cmd.get_dihedral('/{}//A/{}/N'.format(model, resis[i]), \
              '/{}//A/{}/CA'.format(model, resis[i]), \
              '/{}//A/{}/C'.format(model, resis[i]), \
              '/{}//A/{}/N'.format(model, resis[i+1])))
    fname = 'C:\\Users\\Nick\\Desktop\\Bank\\PhystechStuding\\Buslaev\\project3\\hw3_{}_Pro.dat'.format(
        model)
    open(fname, 'w').close()
    np.savetxt(fname, np.transpose([angs_phi, angs_psi]))
Пример #29
0
def set_phipsi(sel,phi,psi):
    # Get atoms from selection
    atoms = cmd.get_model("byres ("+sel+")")

    # Loop through atoms in selection
    for at in atoms.atom: # pylint: disable=E1103
        if at.name == "N":
            # Check for a null chain id (some PDBs contain this)
            unit_select = ""
            if not at.chain == "":
                unit_select = "chain "+str(at.chain)+" and "
            # end if
            
            try:
                # Define residue selections
                rdef_prev = unit_select+'resi '+str(int(at.resi)-1)
                rdef      = unit_select+'resi '+str(at.resi)
#                print "rdef_prev: [%s]" % rdef_prev
#                print "rdef     : [%s]" % rdef
                if at.resn == "PRO":
                    print "Skipping setting phi for PRO"
                else:
                    old_phi = cmd.get_dihedral(rdef_prev+' and name C',rdef+' and name N', rdef+' and name CA',rdef+' and name C')
                    cmd.set_dihedral(          rdef_prev+' and name C',rdef+' and name N', rdef+' and name CA',rdef+' and name C',phi)
                    print "Changed residue %4s %4s phi: from %6.1f to %6.1f" % (at.resn, at.resi, old_phi, float(phi))
            except:

                print "Note skipping set of phi because of error; this is normal for a N-terminal residue"
            try:
                rdef      = unit_select+'resi '+str(at.resi)
                residue_def_next = unit_select+'resi '+str(int(at.resi)+1)
#                print "rdef     : [%s]" % rdef
#                print "residue_def_next: [%s]" % residue_def_next
                old_psi = cmd.get_dihedral(rdef     +' and name N',rdef+' and name CA',rdef+' and name C', residue_def_next+' and name N')
                cmd.set_dihedral(          rdef     +' and name N',rdef+' and name CA',rdef+' and name C', residue_def_next+' and name N',psi) # pylint: disable=C0301
                print "Changed residue %4s %4s psi: from %6.1f to %6.1f" % (at.resn, at.resi, old_psi, float(psi))
            except:
                print "Note skipping set of psi; this is normal for a C terminal residue"
Пример #30
0
def get_psi(obj, bond, state=1):
    """
    Get the dihedral angle psi (C1-O'x-C'x-C'x-1)
    """
    resi_i, resi_j, atom_i, atom_j = bond[0], bond[2], bond[4], bond[5]
    if atom_i > atom_j:
        atom_j = atom_i
        resi_i, resi_j = resi_j, resi_i
    atom1 = '%s and resi %s and name C1' % (obj, resi_i)
    atom2 = '%s and resi %s and name O%s' % (obj, resi_j, atom_j)
    atom3 = '%s and resi %s and name C%s' % (obj, resi_j, atom_j)
    atom4 = '%s and resi %s and name C%s' % (obj, resi_j, (atom_j - 1))
    value = cmd.get_dihedral(atom1, atom2, atom3, atom4, state=state)
    return value
Пример #31
0
def get_psi(obj, bond, state=1): 
    """
    Get the dihedral angle psi (C1-O'x-C'x-C'x-1)
    """
    resi_i, resi_j, atom_i, atom_j = bond[0], bond[2], bond[4], bond[5]
    if atom_i > atom_j:
        atom_j = atom_i
        resi_i, resi_j = resi_j, resi_i
    atom1 = '%s and resi %s and name C1' % (obj, resi_i)
    atom2 = '%s and resi %s and name O%s' % (obj, resi_j, atom_j)
    atom3 = '%s and resi %s and name C%s' % (obj, resi_j, atom_j)
    atom4 = '%s and resi %s and name C%s' % (obj, resi_j, (atom_j-1))
    value = cmd.get_dihedral(atom1, atom2, atom3, atom4, state=state)
    return value  
Пример #32
0
def calculateAlphaHelicalPhaseYieldPerResidue(caPositions, helixAxisPoints,correct):
    alphaHelicalPhaseYieldPerResidue=[]
    alphaHelicalPhaseYieldPerResidue.append(0)
    #alphaHelicalPhaseYieldPerResidue.append(0)
    for i in range (1,len(helixAxisPoints)-1):
        #generate pseudoatoms for dihedral calculation
        id=random.random()*1000
        cmd.pseudoatom(pos=str([caPositions[i-1].item(0),caPositions[i-1].item(1),caPositions[i-1].item(2)]), object="ca_i-1"+str(id))
        cmd.pseudoatom(pos=str([caPositions[i].item(0),caPositions[i].item(1),caPositions[i].item(2)]), object="ca_i"+str(id))
        cmd.pseudoatom(pos=str([caPositions[i+1].item(0),caPositions[i+1].item(1),caPositions[i+1].item(2)]), object="ca_i+1"+str(id))
        cmd.pseudoatom(pos=str([helixAxisPoints[i-1].item(0),helixAxisPoints[i-1].item(1),helixAxisPoints[i-1].item(2)]), object="axis_i-1"+str(id))
        cmd.pseudoatom(pos=str([helixAxisPoints[i].item(0),helixAxisPoints[i].item(1),helixAxisPoints[i].item(2)]), object="axis_i"+str(id))
        cmd.pseudoatom(pos=str([helixAxisPoints[i+1].item(0),helixAxisPoints[i+1].item(1),helixAxisPoints[i+1].item(2)]), object="axis_i+1"+str(id))
        a=cmd.get_dihedral("ca_i-1"+str(id),"axis_i-1"+str(id),"axis_i"+str(id),"ca_i"+str(id),state=0)
        b=cmd.get_dihedral("ca_i"+str(id),"axis_i"+str(id),"axis_i+1"+str(id),"ca_i+1"+str(id),state=0)
        #print i,a,b, (a+b)/2
        cmd.delete("ca_i-1"+str(id))
        cmd.delete("ca_i"+str(id))
        cmd.delete("ca_i+1"+str(id))
        cmd.delete("axis_i-1"+str(id))
        cmd.delete("axis_i"+str(id))
        cmd.delete("axis_i+1"+str(id))
        alphaHelicalPhaseYieldPerResidue.append(correct+(a+b)/2)
    return alphaHelicalPhaseYieldPerResidue
Пример #33
0
    def flip_by_atoms(self, atmA, atmB, atmC, atmD):
        from pymol import CmdException, cmd
        sele = self.selector()

        a, b, c, d = map(lambda a: '{}/{}'.format(sele, a),
                [atmA, atmB, atmC, atmD])

        try:
            dh = cmd.get_dihedral(a, b, c, d)
        except CmdException:
            print "Error on '{}'.".format(self.selector())
            pass
        else:
            cmd.set_dihedral(a, b, c, d, dh + 180)
            cmd.unpick()
Пример #34
0
def fix_gln_hydrogens(selection):
    """Fix the naming of cis and trans hydrogens in glutamine"""
    # HZ21 is the cis, HZ22 is the trans
    for hindex in iterate_indices(
            '({}) and (name HZ21+HZ22)'.format(selection)):
        if abs(
                cmd.get_dihedral(
                    '(idx {}) and ({})'.format(hindex, selection),
                    '(name NZ2) and ({})'.format(selection),
                    '(name CE) and ({})'.format(selection),
                    '(name OZ1) and ({})'.format(selection))) < 90:
            cmd.alter('(idx {}) and ({})'.format(hindex, selection),
                      'name="HZ21"')
        else:
            cmd.alter('(idx {}) and ({})'.format(hindex, selection),
                      'name="HZ22"')
Пример #35
0
    def get_zmat_ext_freeze_torsion(self,flag=3):
        # requires PYMOL to read dihedrals from structure
        # requires list of dihedrals from tinker.amber
        #
        from pymol import cmd
        from .tinker.amber import Topology      

        cmd.load_model(self.model,'_gamess1')
        model = self.model

        # get mapping of model ordering to zmat ordering
        m2z = {}
        z2m = {}
        c = 1 # GAMESS is one-based
        for a in self.get_zmat_ordering():
            m2z[a] = c
            z2m[c] = a
            c = c + 1

        # get all torsions in the molecule

        topo = Topology(self.model)

        # find those where flag is set in all atoms

        mask = 2 ** flag

        frozen_list = []

        for a in list(topo.torsion.keys()):
            if (model.atom[a[0]].flags&
                 model.atom[a[1]].flags&
                 model.atom[a[2]].flags&
                 model.atom[a[3]].flags)&mask:
                frozen_list.append(a)

        print(" freeze-torsion: %d torsions will be frozen."%len(frozen_list))

        irzmat = []
        ifzmat = []
        fvalue = []
        if len(frozen_list):

            for frozen in frozen_list:
                # find additional torsions which need to be removed

                remove = []

                for a in list(topo.torsion.keys()):
                    if (((a[1]==frozen[1])and(a[2]==frozen[2])) or
                         ((a[2]==frozen[1])and(a[1]==frozen[2]))):
                        if a!=frozen:
                            remove.append(a)

                # convert to internal coordinate ordering

                frozen_z = (m2z[frozen[0]],m2z[frozen[1]],
                                m2z[frozen[2]],m2z[frozen[3]])

                remove_z = []
                for a in remove:
                    remove_z.append(m2z[a[0]],m2z[a[1]],m2z[a[2]],m2z[a[3]])

                # now reorder atoms in torsions to reflect z_matrix ordering
                # (not sure this is necessary)

                if frozen_z[0]>frozen_z[3]:
                    frozen_z = (frozen_z[3],frozen_z[2],frozen_z[1],frozen_z[0])
                tmp_z = []
                for a in remove_z:
                    if a[0]>a[3]:
                        tmp_z.append((a[3],a[2],a[1],a[0]))
                    else:
                        tmp_z.append(a)
                remove_z = tmp_z

                # get value of the fixed torsion

                fixed = (z2m[frozen_z[0]],z2m[frozen_z[1]],
                            z2m[frozen_z[2]],z2m[frozen_z[3]])

                dihe = cmd.get_dihedral("(_gamess1 and id %d)"%fixed[0],
                                      "(_gamess1 and id %d)"%fixed[1],
                                      "(_gamess1 and id %d)"%fixed[2],
                                      "(_gamess1 and id %d)"%fixed[3])

                # write out report for user edification

                print(" freeze-torsion: fixing freeze-torsion:")
                print(" freeze-torsion: %d-%d-%d-%d (pymol), %d-%d-%d-%d (gamess)"%(
                    fixed[0],fixed[1],fixed[2],fixed[3],
                    frozen_z[0],frozen_z[1],frozen_z[2],frozen_z[3]))
                print(" freeze-torsion: at %5.3f"%dihe)
                print(" freeze-torsion: removing redundant torsions:")
                for a in remove_z[1:]:
                    print(" freeze-torsion: %d-%d-%d-%d (pymol), %d-%d-%d-%d (gamess)"%(
                        z2m[a[0]],z2m[a[1]],z2m[a[2]],z2m[a[3]],
                        a[0],a[1],a[2],a[3]))

                # add parameters for this torsion into the list

                ifzmat.append((3,frozen_z[0],frozen_z[1],frozen_z[2],frozen_z[3]))
                fvalue.append(dihe)

                if len(remove_z):
                    for a in remove_z[1:]:
                        irzmat.append((3,a[0],a[1],a[2],a[3]))

        # generate restrained dihedral information

        zmat_ext = []
        if len(ifzmat):
            zmat_ext.append(" IFZMAT(1)=\n")
            comma = ""
            for a in ifzmat:
                zmat_ext.append(comma+"%d,%d,%d,%d,%d\n"%a)
                comma = ","
        if len(fvalue):
            zmat_ext.append(" FVALUE(1)=\n")
            comma = ""
            for a in fvalue:
                zmat_ext.append(comma+"%1.7f\n"%a)
                comma = ","
        if len(irzmat):
            zmat_ext.append(" IRZMAT(1)=\n")
            comma = ""
            for a in irzmat:
                zmat_ext.append(comma+"%d,%d,%d,%d,%d\n"%a)
                comma = ","

        cmd.delete("_gamess1") # important
        if len(zmat_ext):
            return zmat_ext
        else:
            return None
Пример #36
0
    def do_library(self):
        cmd = self.cmd
        pymol = cmd._pymol
        if not (
            (cmd.count_atoms("(%s) and name n" % src_sele) == 1)
            and (cmd.count_atoms("(%s) and name c" % src_sele) == 1)
            and (cmd.count_atoms("(%s) and name o" % src_sele) == 1)
        ):
            self.clear()
            return 1
        cmd.feedback("push")
        cmd.feedback("disable", "selector", "everythin")
        cmd.feedback("disable", "editor", "actions")
        self.prompt = ["Loading rotamers..."]

        pymol.stored.name = "residue"
        cmd.iterate("first (%s)" % src_sele, 'stored.name=model+"/"+segi+"/"+chain+"/"+resn+"`"+resi')
        self.res_text = pymol.stored.name
        cmd.select("_seeker_hilight", src_sele)

        auto_zoom = cmd.get_setting_text("auto_zoom")
        cmd.set("auto_zoom", "0", quiet=1)
        cmd.frame(0)
        cmd.delete(frag_name)
        if self.auto_center:
            cmd.center(src_sele, animate=-1)

        self.lib_mode = self.mode
        if self.lib_mode == "current":
            pymol.stored.resn = ""
            cmd.iterate("(%s and n;ca)" % src_sele, "stored.resn=resn")
            rot_type = _rot_type_xref.get(pymol.stored.resn, pymol.stored.resn)
            if (self.c_cap != "none") or (self.n_cap != "none") or (self.hyd != "auto"):
                self.lib_mode = rot_type  # force fragment-based load
            else:
                cmd.create(frag_name, src_sele, 1, 1)
                if self.c_cap == "open":
                    cmd.remove("%s and name OXT" % frag_name)

        if self.lib_mode != "current":
            rot_type = self.lib_mode
            frag_type = self.lib_mode
            if (self.n_cap == "posi") and (frag_type[0:3] != "NT_"):
                if not (cmd.count_atoms("elem c & !(%s) & (bto. (n;n & (%s))) &! r. ace" % (src_sele, src_sele))):
                    # use N-terminal fragment
                    frag_type = "NT_" + frag_type
            if (self.c_cap == "nega") and (frag_type[0:3] != "CT_"):
                if not (cmd.count_atoms("elem n & !(%s) & (bto. (n;c & (%s))) & !r. nme+nhh" % (src_sele, src_sele))):
                    # use C-terminal fragment
                    frag_type = "CT_" + frag_type
            if rot_type[0:3] in ["NT_", "CT_"]:
                rot_type = rot_type[3:]
            rot_type = _rot_type_xref.get(rot_type, rot_type)
            cmd.fragment(string.lower(frag_type), frag_name)
            # trim off hydrogens
            if self.hyd == "none":
                cmd.remove("(" + frag_name + " and hydro)")
            elif self.hyd == "auto":
                if cmd.count_atoms("(" + src_sele + ") and hydro") == 0:
                    cmd.remove("(" + frag_name + " and hydro)")
            # copy identifying information
            cmd.iterate("(%s and n;ca)" % src_sele, "stored.chain=chain")
            cmd.alter("(%s)" % frag_name, "chain=stored.chain")
            cmd.iterate("(%s and n;ca)" % src_sele, "stored.resi=resi")
            cmd.alter("(%s)" % frag_name, "resi=stored.resi")
            cmd.iterate("(%s and n;ca)" % src_sele, "stored.segi=segi")
            cmd.alter("(%s)" % frag_name, "segi=stored.segi")
            cmd.iterate("(%s and n;ca)" % src_sele, "stored.ss=ss")
            cmd.alter("(%s)" % frag_name, "ss=stored.ss")
            # move the fragment
            if (cmd.count_atoms("(%s and n;cb)" % frag_name) == 1) and (
                cmd.count_atoms("(%s and n;cb)" % src_sele) == 1
            ):
                cmd.pair_fit(
                    "(%s and n;ca)" % frag_name,
                    "(%s and n;ca)" % src_sele,
                    "(%s and n;cb)" % frag_name,
                    "(%s and n;cb)" % src_sele,
                    "(%s and n;c)" % frag_name,
                    "(%s and n;c)" % src_sele,
                    "(%s and n;n)" % frag_name,
                    "(%s and n;n)" % src_sele,
                )
            else:
                cmd.pair_fit(
                    "(%s and n;ca)" % frag_name,
                    "(%s and n;ca)" % src_sele,
                    "(%s and n;c)" % frag_name,
                    "(%s and n;c)" % src_sele,
                    "(%s and n;n)" % frag_name,
                    "(%s and n;n)" % src_sele,
                )

            # fix the carbonyl position...
            cmd.iterate_state(1, "(%s and n;o)" % src_sele, "stored.list=[x,y,z]")
            cmd.alter_state(1, "(%s and n;o)" % frag_name, "(x,y,z)=stored.list")
            if cmd.count_atoms("(%s and n;oxt)" % src_sele):
                cmd.iterate_state(1, "(%s and n;oxt)" % src_sele, "stored.list=[x,y,z]")
                cmd.alter_state(1, "(%s and n;oxt)" % frag_name, "(x,y,z)=stored.list")
            elif cmd.count_atoms("(%s and n;oxt)" % frag_name):  # place OXT if no template exists
                angle = cmd.get_dihedral(
                    "(%s and n;n)" % frag_name,
                    "(%s and n;ca)" % frag_name,
                    "(%s and n;c)" % frag_name,
                    "(%s and n;o)" % frag_name,
                )
                cmd.protect("(%s and n;o)" % frag_name)
                cmd.set_dihedral(
                    "(%s and n;n)" % frag_name,
                    "(%s and n;ca)" % frag_name,
                    "(%s and n;c)" % frag_name,
                    "(%s and n;oxt)" % frag_name,
                    180.0 + angle,
                )
                cmd.deprotect(frag_name)

            # fix the hydrogen position (if any)
            if cmd.count_atoms("(elem h and bound_to (n;n and (%s)))" % frag_name) == 1:
                if cmd.count_atoms("(elem h and bound_to (n;n and (%s)))" % src_sele) == 1:
                    cmd.iterate_state(1, "(elem h and bound_to (n;n and (%s)))" % src_sele, "stored.list=[x,y,z]")
                    cmd.alter_state(1, "(elem h and bound_to (n;n and (%s)))" % frag_name, "(x,y,z)=stored.list")
                elif cmd.select(tmp_sele1, "(n;c and bound_to (%s and e;n))" % src_sele) == 1:
                    # position hydro based on location of the carbonyl
                    angle = cmd.get_dihedral(
                        "(%s and n;c)" % frag_name, "(%s and n;ca)" % frag_name, "(%s and n;n)" % frag_name, tmp_sele1
                    )
                    cmd.set_dihedral(
                        "(%s and n;c)" % frag_name,
                        "(%s and n;ca)" % frag_name,
                        "(%s and n;n)" % frag_name,
                        "(%s and n;h)" % frag_name,
                        180.0 + angle,
                    )
                    cmd.delete(tmp_sele1)

            # add c-cap (if appropriate)
            if self.c_cap in ["amin", "nmet"]:
                if not cmd.count_atoms("elem n & !(%s) & (bto. (n;c & (%s))) & !r. nme+nhh" % (src_sele, src_sele)):
                    if cmd.count_atoms("n;c & (%s)" % (frag_name)) == 1:
                        if self.c_cap == "amin":
                            editor.attach_amino_acid("n;c & (%s)" % (frag_name), "nhh")
                        elif self.c_cap == "nmet":
                            editor.attach_amino_acid("n;c & (%s)" % (frag_name), "nme")
                        if cmd.count_atoms("hydro & bound_to (n;n & bound_to (n;c & (%s)))" % frag_name):
                            cmd.h_fix("n;n & bound_to (n;c & (%s))" % frag_name)
                        # trim hydrogens
                        if self.hyd == "none":
                            cmd.remove("(" + frag_name + " and hydro)")
                        elif self.hyd == "auto":
                            if cmd.count_atoms("(" + src_sele + ") and hydro") == 0:
                                cmd.remove("(" + frag_name + " and hydro)")

            # add n-cap (if appropriate)
            if self.n_cap in ["acet"]:
                if not cmd.count_atoms("elem c & !(%s) & (bto. (n;n & (%s))) & !r. ace " % (src_sele, src_sele)):
                    if cmd.count_atoms("n;n & (%s)" % (frag_name)) == 1:
                        if self.n_cap == "acet":
                            editor.attach_amino_acid("n;n & (%s)" % (frag_name), "ace")
                        if cmd.count_atoms("hydro & bound_to (n;n & bound_to (n;c & (%s)))" % frag_name):
                            cmd.h_fix("n;n & (%s)" % frag_name)
                        # trim hydrogens
                        if self.hyd == "none":
                            cmd.remove("(" + frag_name + " and hydro)")
                        elif self.hyd == "auto":
                            if cmd.count_atoms("(" + src_sele + ") and hydro") == 0:
                                cmd.remove("(" + frag_name + " and hydro)")

        cartoon = cmd.count_atoms("(%s and n;ca and rep cartoon)" % src_sele) > 0
        sticks = cmd.count_atoms("(%s and n;ca and rep sticks)" % src_sele) > 0

        cmd.delete(obj_name)
        key = rot_type
        lib = None
        if self.dep == "dep":
            try:
                result = cmd.phi_psi("%s" % src_sele)
                if len(result) == 1:
                    (phi, psi) = result[result.keys()[0]]
                    (phi, psi) = (int(10 * round(phi / 10)), int(10 * (round(psi / 10))))
                    key = (rot_type, phi, psi)
                    if not self.dep_library.has_key(key):
                        (phi, psi) = (int(20 * round(phi / 20)), int(20 * (round(psi / 20))))
                        key = (rot_type, phi, psi)
                        if not self.dep_library.has_key(key):
                            (phi, psi) = (int(60 * round(phi / 60)), int(60 * (round(psi / 60))))
                            key = (rot_type, phi, psi)
                    lib = self.dep_library.get(key, None)
            except:
                pass
        if lib == None:
            key = rot_type
            lib = self.ind_library.get(key, None)
            if (lib != None) and self.dep == "dep":
                print " Mutagenesis: no phi/psi, using backbone-independent rotamers."
        if lib != None:
            state = 1
            for a in lib:
                cmd.create(obj_name, frag_name, 1, state)
                if state == 1:
                    cmd.select(mut_sele, "(byres (%s like %s))" % (obj_name, src_sele))
                if rot_type == "PRO":
                    cmd.unbond("(%s & name N)" % mut_sele, "(%s & name CD)" % mut_sele)
                for b in a.keys():
                    if b != "FREQ":
                        cmd.set_dihedral(
                            "(%s & n;%s)" % (mut_sele, b[0]),
                            "(%s & n;%s)" % (mut_sele, b[1]),
                            "(%s & n;%s)" % (mut_sele, b[2]),
                            "(%s & n;%s)" % (mut_sele, b[3]),
                            a[b],
                            state=state,
                        )
                    else:
                        cmd.set_title(obj_name, state, "%1.1f%%" % (a[b] * 100))
                if rot_type == "PRO":
                    cmd.bond("(%s & name N)" % mut_sele, "(%s & name CD)" % mut_sele)
                state = state + 1
            cmd.delete(frag_name)
            print " Mutagenesis: %d rotamers loaded." % len(lib)
            if self.bump_check:
                cmd.delete(bump_name)
                cmd.create(
                    bump_name,
                    "(((byobj %s) within 6 of (%s and not name n+c+ca+o+h+ha)) and (not (%s)))|(%s)"
                    % (src_sele, mut_sele, src_sele, mut_sele),
                    singletons=1,
                )
                cmd.color("gray50", bump_name + " and elem c")
                cmd.set("seq_view", 0, bump_name, quiet=1)
                cmd.hide("everything", bump_name)
                if (cmd.select(tmp_sele1, "(n;N and (%s in (neighbor %s)))" % (bump_name, src_sele)) == 1) and (
                    cmd.select(tmp_sele2, "(n;C and (%s in %s))" % (bump_name, mut_sele)) == 1
                ):
                    cmd.bond(tmp_sele1, tmp_sele2)
                if (cmd.select(tmp_sele1, "(n;C and (%s in (neighbor %s)))" % (bump_name, src_sele)) == 1) and (
                    cmd.select(tmp_sele2, "(n;N and (%s in %s))" % (bump_name, mut_sele)) == 1
                ):
                    cmd.bond(tmp_sele1, tmp_sele2)
                cmd.delete(tmp_sele1)
                cmd.delete(tmp_sele2)

                cmd.protect("%s and not (%s in (%s and not name n+c+ca+o+h+ha))" % (bump_name, bump_name, mut_sele))
                cmd.sculpt_activate(bump_name)
                cmd.show("cgo", bump_name)
                # draw the bumps
                cmd.set("sculpt_vdw_vis_mode", 1, bump_name)
                state = 1
                for a in lib:
                    cmd.sculpt_iterate(bump_name, state=state)
                    state = state + 1
            cmd.delete(mut_sele)
        else:
            cmd.create(obj_name, frag_name, 1, 1)
            print " Mutagenesis: no rotamers found in library."
        cmd.set("seq_view", 0, obj_name, quiet=1)
        pymol.util.cbaw(obj_name)
        cmd.hide("(" + obj_name + ")")
        cmd.show(self.rep, obj_name)
        cmd.show("lines", obj_name)  # neighbor  always show lines
        if cartoon:
            cmd.show("cartoon", obj_name)
        if sticks:
            cmd.show("sticks", obj_name)
        cmd.set("auto_zoom", auto_zoom, quiet=1)
        cmd.delete(frag_name)
        cmd.frame(0)
        cmd.unpick()
        cmd.feedback("pop")
Пример #37
0
def print_dihedrals(selection='sele',
                    state=1,
                    quiet=1,
                    ss='',
                    fc=10.0,
                    chi=0,
                    label='ID'):
    '''
DESCRIPTION

    "print_dihedrals" return the phi, psi, and chi1 angles for a protein atom
    selection.

ARGUMENTS

    state = integer: object state {default: 1}

    selection = string: atom selection {default: all}

    amber = integer: generate AMBER rst file {default: 1;ON}

    label = string: label type ('ID' or 'index') {default: ID}

    fc = float: force constant for the dihedral angles {default: 10.0}

    chi = 0: Do not print chi angles (default)
    chi = 1: print chi1 dihedral angle (if exists)
    chi = 2: print chi1 and chi2 dihedral angles (if exists) (not implemented yet)

SEE ALSO

    phipsi
    '''
    # selectionからCalpha原子のIDリストを取得
    chi = int(chi)
    caindex = []
    cmd.iterate('bycalpha (%s)' % selection,
                'caindex.append(ID)',
                space=locals())
    # Calpha原子が属する残基ごとに処理を行う
    for ca in caindex:
        # resinameに残基名のみ取得
        n_sele = "((byres ID %s) & name N)" % ca
        c_sele = "((byres ID %s) & name C)" % ca
        ca_sele = "((byres ID %s) & name CA)" % ca
        cb_sele = "((byres ID %s) & name CB)" % ca

        resiname_sele = []
        cmd.iterate(ca_sele, "resiname_sele.append(resn)", space=locals())
        resiname = str(resiname_sele[0])

        if resiname == 'ILE' or resiname == 'VAL':
            cg_sele = "((byres ID %s) & name CG1)" % ca
        elif resiname == 'THR':
            cg_sele = "((byres ID %s) & name OG1)" % ca
        elif resiname == 'CYS' or resiname == 'CYX':
            cg_sele = "((byres ID %s) & name SG)" % ca
        else:
            cg_sele = "((byres ID %s) & name CG)" % ca

        cm_sele = "((neighbor (%s)) and not (byres (%s)))" % (n_sele, n_sele
                                                              )  #前の残基のC
        np_sele = "((neighbor (%s)) and not (byres (%s)))" % (c_sele, c_sele
                                                              )  #次の残基のN
        cmd.feedback("push")
        cmd.feedback("disable", "selector", "everything")
        cm_cnt = cmd.select("_pp_cm", cm_sele)
        n_cnt = cmd.select("_pp_n", n_sele)
        c_cnt = cmd.select("_pp_c", c_sele)
        ca_cnt = cmd.select("_pp_ca", ca_sele)
        cb_cnt = cmd.select("_pp_cb", cb_sele)
        cg_cnt = cmd.select("_pp_cg", cg_sele)
        np_cnt = cmd.select("_pp_np", np_sele)

        # 残基名+残基番号取得(ASP704みたいな)
        rname = []
        cmd.iterate(ca_sele, "rname.append(resn+resi)", space=locals())

        if (cm_cnt and n_cnt and ca_cnt and c_cnt):
            phi = cmd.get_dihedral("_pp_c", "_pp_ca", "_pp_n", "_pp_cm")
        else:
            phi = None
        if (n_cnt and ca_cnt and c_cnt and np_cnt):
            psi = cmd.get_dihedral("_pp_np", "_pp_c", "_pp_ca", "_pp_n")
        else:
            psi = None
        if (n_cnt and ca_cnt and cb_cnt and cg_cnt):
            chi1 = cmd.get_dihedral("_pp_cg", "_pp_cb", "_pp_ca", "_pp_n")
        else:
            chi1 = None

        atomdict = {}
        strings = [
            "_pp_cm", "_pp_n", "_pp_c", "_pp_ca", "_pp_cb", "_pp_np", "_pp_cg"
        ]
        for i in strings:
            temp = cmd.identify(i)
            # tempが空リストでなければatomdictに追加
            if temp:
                atomdict[i] = temp[0]

        # phi, psi用に制限を設ける
        # 引数でssが指定されている場合、その範囲になるよう設定
        def phir2limit(x, sigma, ss):
            if ss == '':
                val = x - sigma
                if val <= -180.0:
                    val = -180.0
                return val
            elif ss == 'alpha':
                val = -80.0
                return val
            elif ss == 'beta':
                val = -155.0
                return val

        def phir3limit(x, sigma, ss):
            if ss == '':
                val = x + sigma
                if val >= 180.0:
                    val = 180.0
                return val
            elif ss == 'alpha':
                val = -50.0
                return val
            elif ss == 'beta':
                val = -125.0
                return val

        def psir2limit(x, sigma, ss):
            if ss == '':
                val = x - sigma
                if val <= -180.0:
                    val = -180.0
                return val
            elif ss == 'alpha':
                val = -55.0
                return val
            elif ss == 'beta':
                val = 115.0
                return val

        def psir3limit(x, sigma, ss):
            if ss == '':
                val = x + sigma
                if val >= 180.0:
                    val = 180.0
                return val
            elif ss == 'alpha':
                val = -25.0
                return val
            elif ss == 'beta':
                val = 145.0
                return val

        def r2limit(x, sigma):
            val = x - sigma
            if val <= -180.0:
                val = -180.0
            return val

        def r3limit(x, sigma):
            val = x + sigma
            if val >= 180.0:
                val = 180.0
            return val

        if phi is not None:
            print('''# {6} phi
&rst iat=  {0},  {1},  {2},  {3},
r1=-180.0, r2={4:.2f}, r3={5:.2f}, r4= 180.0,
rk2= {7}, rk3= {7},\n/'''.format(int(atomdict['_pp_c']),
                                 int(atomdict['_pp_ca']),
                                 int(atomdict['_pp_n']),
                                 int(atomdict['_pp_cm']),
                                 phir2limit(phi, 10.0, ss),
                                 phir3limit(phi, 10.0, ss), str(rname[0]),
                                 float(fc)))
        if psi is not None:
            print('''# {6} psi
&rst iat=  {0},  {1},  {2},  {3},
r1=-180.0, r2={4:.2f}, r3={5:.2f}, r4= 180.0,
rk2= {7}, rk3= {7},\n/'''.format(int(atomdict['_pp_np']),
                                 int(atomdict['_pp_c']),
                                 int(atomdict['_pp_ca']),
                                 int(atomdict['_pp_n']),
                                 psir2limit(psi, 10.0, ss),
                                 psir3limit(psi, 10.0, ss), str(rname[0]),
                                 float(fc)))
        if (chi > 0) and (chi1 is not None):
            print('''# {6} chi1
&rst iat=  {0},  {1},  {2},  {3},
r1=-180.0, r2={4:.2f}, r3={5:.2f}, r4= 180.0,
rk2= {7}, rk3= {7},\n/'''.format(int(atomdict['_pp_cg']),
                                 int(atomdict['_pp_cb']),
                                 int(atomdict['_pp_ca']),
                                 int(atomdict['_pp_n']), r2limit(chi1, 10.0),
                                 r3limit(chi1,
                                         10.0), str(rname[0]), float(fc)))
Пример #38
0
def ens_measure(pk1 = None,
                pk2 = None,
                pk3 = None,
                pk4 = None,
                name = None,
                log = None,
                verbose = True):
    '''
DESCRIPTION

    Statistics from ensemble structure measurements.  If:
      2 selections give = distance
      3 selections give = angle
      4 selections give = dihedral angle

USAGE

    ens_measure pk1, pk2, pk3, pk4, name, log, verbose

ARGUMENTS

    log = name of log file
    verbose = prints individual measurements

 EXAMPLE

    ens_measure atom1, atom2, name = 'measure', log 'ens.log'
  '''
    print >> log, '\nEnsemble measurement'

    if [pk1, pk2, pk3, pk4].count(None) > 2:
        print '\nERROR: Please supply at least 2 seletions'
        return
    number_models = cmd.count_states(pk1)
    measurements = []

    # distance
    if [pk1, pk2, pk3, pk4].count(None) == 2:
        print >> log, 'Distance'
        if name == None: name = 'ens_distance'
        # display as object
        cmd.distance(name = name,
                     selection1 = pk1,
                     selection2 = pk2)

        # get individual values
        for n in xrange(number_models):
            measurements.append( cmd.get_distance(pk1, pk2, n+1) )
        assert len(measurements) == number_models

    # angle
    if [pk1, pk2, pk3, pk4].count(None) == 1:
        print >> log, 'Angle'
        # display as object
        if name == None: name = 'ens_angle'
        cmd.angle(name = name,
                  selection1 = pk1,
                  selection2 = pk2,
                  selection3 = pk3)

        # get individual values
        for n in xrange(number_models):
            measurements.append( cmd.get_angle(atom1 = pk1,
                                               atom2 = pk2,
                                               atom3 = pk3,
                                               state = n+1) )
        assert len(measurements) == number_models

    # Dihedral angle
    if [pk1, pk2, pk3, pk4].count(None) == 0:
        print >> log, 'Dihedral angle'
        # display as object
        if name == None: name = 'ens_dihedral'
        cmd.dihedral(name = name,
                  selection1 = pk1,
                  selection2 = pk2,
                  selection3 = pk3,
                  selection4 = pk4)

        # get individual values
        for n in xrange(number_models):
            measurements.append( cmd.get_dihedral(atom1 = pk1,
                                                  atom2 = pk2,
                                                  atom3 = pk3,
                                                  atom4 = pk4,
                                                  state = n+1) )
        assert len(measurements) == number_models

    # print stats
    if verbose:
        print >> log, ' State  Value'
        for n, measurement in enumerate(measurements):
            print >> log, '  %4d  %3.3f '%(n+1, measurement)

    print >> log, '\nMeasurement statistics'
    print_array_stats(array                 = measurements,
                      log                   = log)
Пример #39
0
    def get_zmat_ext_freeze_torsion(self, flag=3):
        # requires PYMOL to read dihedrals from structure
        # requires list of dihedrals from tinker.amber
        #
        from pymol import cmd
        from tinker.amber import Topology

        cmd.load_model(self.model, '_gamess1')
        model = self.model

        # get mapping of model ordering to zmat ordering
        m2z = {}
        z2m = {}
        c = 1  # GAMESS is one-based
        for a in self.get_zmat_ordering():
            m2z[a] = c
            z2m[c] = a
            c = c + 1

        # get all torsions in the molecule

        topo = Topology(self.model)

        # find those where flag is set in all atoms

        mask = 2**flag

        frozen_list = []

        for a in topo.torsion.keys():
            if (model.atom[a[0]].flags & model.atom[a[1]].flags
                    & model.atom[a[2]].flags & model.atom[a[3]].flags) & mask:
                frozen_list.append(a)

        print " freeze-torsion: %d torsions will be frozen." % len(frozen_list)

        irzmat = []
        ifzmat = []
        fvalue = []
        if len(frozen_list):

            for frozen in frozen_list:
                # find additional torsions which need to be removed

                remove = []

                for a in topo.torsion.keys():
                    if (((a[1] == frozen[1]) and (a[2] == frozen[2]))
                            or ((a[2] == frozen[1]) and (a[1] == frozen[2]))):
                        if a != frozen:
                            remove.append(a)

                # convert to internal coordinate ordering

                frozen_z = (m2z[frozen[0]], m2z[frozen[1]], m2z[frozen[2]],
                            m2z[frozen[3]])

                remove_z = []
                for a in remove:
                    remove_z.append(m2z[a[0]], m2z[a[1]], m2z[a[2]], m2z[a[3]])

                # now reorder atoms in torsions to reflect z_matrix ordering
                # (not sure this is necessary)

                if frozen_z[0] > frozen_z[3]:
                    frozen_z = (frozen_z[3], frozen_z[2], frozen_z[1],
                                frozen_z[0])
                tmp_z = []
                for a in remove_z:
                    if a[0] > a[3]:
                        tmp_z.append((a[3], a[2], a[1], a[0]))
                    else:
                        tmp_z.append(a)
                remove_z = tmp_z

                # get value of the fixed torsion

                fixed = (z2m[frozen_z[0]], z2m[frozen_z[1]], z2m[frozen_z[2]],
                         z2m[frozen_z[3]])

                dihe = cmd.get_dihedral("(_gamess1 and id %d)" % fixed[0],
                                        "(_gamess1 and id %d)" % fixed[1],
                                        "(_gamess1 and id %d)" % fixed[2],
                                        "(_gamess1 and id %d)" % fixed[3])

                # write out report for user edification

                print " freeze-torsion: fixing freeze-torsion:"
                print " freeze-torsion: %d-%d-%d-%d (pymol), %d-%d-%d-%d (gamess)" % (
                    fixed[0], fixed[1], fixed[2], fixed[3], frozen_z[0],
                    frozen_z[1], frozen_z[2], frozen_z[3])
                print " freeze-torsion: at %5.3f" % dihe
                print " freeze-torsion: removing redundant torsions:"
                for a in remove_z[1:]:
                    print " freeze-torsion: %d-%d-%d-%d (pymol), %d-%d-%d-%d (gamess)" % (
                        z2m[a[0]], z2m[a[1]], z2m[a[2]], z2m[a[3]], a[0], a[1],
                        a[2], a[3])

                # add parameters for this torsion into the list

                ifzmat.append(
                    (3, frozen_z[0], frozen_z[1], frozen_z[2], frozen_z[3]))
                fvalue.append(dihe)

                if len(remove_z):
                    for a in remove_z[1:]:
                        irzmat.append((3, a[0], a[1], a[2], a[3]))

        # generate restrained dihedral information

        zmat_ext = []
        if len(ifzmat):
            zmat_ext.append(" IFZMAT(1)=\n")
            comma = ""
            for a in ifzmat:
                zmat_ext.append(comma + "%d,%d,%d,%d,%d\n" % a)
                comma = ","
        if len(fvalue):
            zmat_ext.append(" FVALUE(1)=\n")
            comma = ""
            for a in fvalue:
                zmat_ext.append(comma + "%1.7f\n" % a)
                comma = ","
        if len(irzmat):
            zmat_ext.append(" IRZMAT(1)=\n")
            comma = ""
            for a in irzmat:
                zmat_ext.append(comma + "%d,%d,%d,%d,%d\n" % a)
                comma = ","

        cmd.delete("_gamess1")  # important
        if len(zmat_ext):
            return zmat_ext
        else:
            return None
Пример #40
0
    def do_library(self):
        cmd=self.cmd
        pymol=cmd._pymol
        if not ((cmd.count_atoms("(%s) and name N"%src_sele)==1) and
                (cmd.count_atoms("(%s) and name C"%src_sele)==1) and
                (cmd.count_atoms("(%s) and name O"%src_sele)==1)):
            self.clear()
            return 1
        cmd.feedback("push")
        cmd.feedback("disable","selector","everythin")
        cmd.feedback("disable","editor","actions")
        self.prompt = [ 'Loading rotamers...']
        self.bump_scores = []
        state_best = 0

        pymol.stored.name = 'residue'
        cmd.iterate("first (%s)"%src_sele,'stored.name=model+"/"+segi+"/"+chain+"/"+resn+"`"+resi')
        self.res_text = pymol.stored.name
        cmd.select("_seeker_hilight",src_sele)

        auto_zoom = cmd.get_setting_text('auto_zoom')
        cmd.set('auto_zoom',"0",quiet=1)
        cmd.frame(0)
        cmd.delete(frag_name)
        if self.auto_center:
            cmd.center(src_sele,animate=-1)

        self.lib_mode = self.mode
        if self.lib_mode=="current":
            pymol.stored.resn=""
            cmd.iterate("(%s & name CA)"%src_sele,"stored.resn=resn")
            rot_type = _rot_type_xref.get(pymol.stored.resn,pymol.stored.resn)
            if (self.c_cap!='none') or (self.n_cap!='none') or (self.hyd != 'auto'):
                self.lib_mode = rot_type # force fragment-based load
            else:
                cmd.create(frag_name,src_sele,1,1)
                if self.c_cap=='open':
                    cmd.remove("%s and name OXT"%frag_name)

        if self.lib_mode!='current':
            rot_type = self.lib_mode
            frag_type = self.lib_mode
            if (self.n_cap == 'posi') and (frag_type[0:3]!='NT_'):
                if not ( cmd.count_atoms(
                    "elem C & !(%s) & (bto. (name N & (%s))) &! resn ACE"%
                                     (src_sele,src_sele))):
                    # use N-terminal fragment
                    frag_type ="NT_"+frag_type
            if (self.c_cap == 'nega') and (frag_type[0:3]!='CT_'):
                if not ( cmd.count_atoms("elem N & !(%s) & (bto. (name C & (%s))) & !resn NME+NHH"%
                                     (src_sele,src_sele))):
                    # use C-terminal fragment
                    frag_type ="CT_"+frag_type
            if rot_type[0:3] in [ 'NT_', 'CT_' ]:
                rot_type = rot_type[3:]
            rot_type = _rot_type_xref.get(rot_type, rot_type)
            cmd.fragment(frag_type.lower(), frag_name, origin=0)
            # trim off hydrogens
            if (self.hyd == 'none'):
                cmd.remove("("+frag_name+" and hydro)")
            elif (self.hyd == 'auto'):
                if cmd.count_atoms("("+src_sele+") and hydro")==0:
                    cmd.remove("("+frag_name+" and hydro)")
            # copy identifying information
            cmd.alter("?%s & name CA" % src_sele, "stored.identifiers = (segi, chain, resi, ss, color)", space=self.space)
            cmd.alter("?%s" % frag_name, "(segi, chain, resi, ss) = stored.identifiers[:4]", space=self.space)
            # move the fragment
            if ((cmd.count_atoms("(%s & name CB)"%frag_name)==1) and
                 (cmd.count_atoms("(%s & name CB)"%src_sele)==1)):
                cmd.pair_fit("(%s & name CA)"%frag_name,
                             "(%s & name CA)"%src_sele,
                             "(%s & name CB)"%frag_name,
                             "(%s & name CB)"%src_sele,
                             "(%s & name C)"%frag_name,
                             "(%s & name C)"%src_sele,
                             "(%s & name N)"%frag_name,
                             "(%s & name N)"%src_sele)
            else:
                cmd.pair_fit("(%s & name CA)"%frag_name,
                             "(%s & name CA)"%src_sele,
                             "(%s & name C)"%frag_name,
                             "(%s & name C)"%src_sele,
                             "(%s & name N)"%frag_name,
                             "(%s & name N)"%src_sele)

            # fix the carbonyl position...
            cmd.iterate_state(1,"(%s & name O)"%src_sele,"stored.list=[x,y,z]")
            cmd.alter_state(1,"(%s & name O)"%frag_name,"(x,y,z)=stored.list")
            if cmd.count_atoms("(%s & name OXT)"%src_sele):
                cmd.iterate_state(1,"(%s & name OXT)"%src_sele,"stored.list=[x,y,z]")
                cmd.alter_state(1,"(%s & name OXT)"%frag_name,"(x,y,z)=stored.list")
            elif cmd.count_atoms("(%s & name OXT)"%frag_name): # place OXT if no template exists
                angle = cmd.get_dihedral("(%s & name N)"%frag_name,
                                         "(%s & name CA)"%frag_name,
                                         "(%s & name C)"%frag_name,
                                         "(%s & name O)"%frag_name)
                cmd.protect("(%s & name O)"%frag_name)
                cmd.set_dihedral("(%s & name N)"%frag_name,
                                 "(%s & name CA)"%frag_name,
                                 "(%s & name C)"%frag_name,
                                 "(%s & name OXT)"%frag_name,180.0+angle)
                cmd.deprotect(frag_name)


            # fix the hydrogen position (if any)
            if cmd.count_atoms("(hydro and bound_to (name N & (%s)))"%frag_name)==1:
                if cmd.count_atoms("(hydro and bound_to (name N & (%s)))"%src_sele)==1:
                    cmd.iterate_state(1,"(hydro and bound_to (name N & (%s)))"%src_sele,
                                      "stored.list=[x,y,z]")
                    cmd.alter_state(1,"(hydro and bound_to (name N & (%s)))"%frag_name,
                                    "(x,y,z)=stored.list")
                elif cmd.select(tmp_sele1,"(name C & bound_to (%s and elem N))"%src_sele)==1:
                    # position hydro based on location of the carbonyl
                    angle = cmd.get_dihedral("(%s & name C)"%frag_name,
                                             "(%s & name CA)"%frag_name,
                                             "(%s & name N)"%frag_name,
                                             tmp_sele1)
                    cmd.set_dihedral("(%s & name C)"%frag_name,
                                     "(%s & name CA)"%frag_name,
                                     "(%s & name N)"%frag_name,
                                     "(%s & name H)"%frag_name,180.0+angle)
                    cmd.delete(tmp_sele1)

            # add c-cap (if appropriate)
            if self.c_cap in [ 'amin', 'nmet' ]:
                if not cmd.count_atoms("elem N & !(%s) & (bto. (name C & (%s))) & !resn NME+NHH"%
                                       (src_sele,src_sele)):
                    if cmd.count_atoms("name C & (%s)"%(frag_name))==1:
                        if self.c_cap == 'amin':
                            editor.attach_amino_acid("name C & (%s)"%(frag_name), 'nhh')
                        elif self.c_cap == 'nmet':
                            editor.attach_amino_acid("name C & (%s)"%(frag_name), 'nme')
                        if cmd.count_atoms("hydro & bound_to (name N & bound_to (name C & (%s)))"%frag_name):
                            cmd.h_fix("name N & bound_to (name C & (%s))"%frag_name)
                        # trim hydrogens
                        if (self.hyd == 'none'):
                            cmd.remove("("+frag_name+" and hydro)")
                        elif (self.hyd == 'auto'):
                            if cmd.count_atoms("("+src_sele+") and hydro")==0:
                                cmd.remove("("+frag_name+" and hydro)")

            # add n-cap (if appropriate)
            if self.n_cap in [ 'acet' ]:
                if not cmd.count_atoms("elem C & !(%s) & (bto. (name N & (%s))) & !resn ACE "%
                                       (src_sele,src_sele)):
                    if cmd.count_atoms("name N & (%s)"%(frag_name))==1:
                        if self.n_cap == 'acet':
                            editor.attach_amino_acid("name N & (%s)"%(frag_name), 'ace')
                        if cmd.count_atoms("hydro & bound_to (name N & bound_to (name C & (%s)))"%frag_name):
                            cmd.h_fix("name N & (%s)"%frag_name)
                        # trim hydrogens
                        if (self.hyd == 'none'):
                            cmd.remove("("+frag_name+" and hydro)")
                        elif (self.hyd == 'auto'):
                            if cmd.count_atoms("("+src_sele+") and hydro")==0:
                                cmd.remove("("+frag_name+" and hydro)")




        cartoon = (cmd.count_atoms("(%s & name CA & rep cartoon)"%src_sele)>0)
        sticks = (cmd.count_atoms("(%s & name CA & rep sticks)"%src_sele)>0)

        cmd.delete(obj_name)
        key = rot_type
        lib = None
        if self.dep == 'dep':
            try:
                result = cmd.phi_psi("%s"%src_sele)
                if len(result)==1:
                    (phi,psi) = list(result.values())[0]
                    (phi,psi) = (int(10*round(phi/10)),int(10*(round(psi/10))))
                    key = (rot_type,phi,psi)
                    if key not in self.dep_library:
                        (phi,psi) = (int(20*round(phi/20)),int(20*(round(psi/20))))
                        key = (rot_type,phi,psi)
                        if key not in self.dep_library:
                            (phi,psi) = (int(60*round(phi/60)),int(60*(round(psi/60))))
                            key = (rot_type,phi,psi)
                    lib = self.dep_library.get(key,None)
            except:
                pass
        if lib is None:
            key = rot_type
            lib = self.ind_library.get(key,None)
            if (lib is not None) and self.dep == 'dep':
                print(' Mutagenesis: no phi/psi, using backbone-independent rotamers.')
        if lib is not None:
            state = 1
            for a in lib:
                cmd.create(obj_name,frag_name,1,state)
                if state == 1:
                    cmd.select(mut_sele,"(byres (%s like %s))"%(obj_name,src_sele))
                if rot_type=='PRO':
                    cmd.unbond("(%s & name N)"%mut_sele,"(%s & name CD)"%mut_sele)
                for b in a.keys():
                    if b!='FREQ':
                        cmd.set_dihedral("(%s & n;%s)"%(mut_sele,b[0]),
                                         "(%s & n;%s)"%(mut_sele,b[1]),
                                         "(%s & n;%s)"%(mut_sele,b[2]),
                                         "(%s & n;%s)"%(mut_sele,b[3]),
                                         a[b],state=state)
                    else:
                        cmd.set_title(obj_name,state,"%1.1f%%"%(a[b]*100))
                if rot_type=='PRO':
                    cmd.bond("(%s & name N)"%mut_sele,"(%s & name CD)"%mut_sele)
                state = state + 1
            cmd.delete(frag_name)
            print(" Mutagenesis: %d rotamers loaded."%len(lib))
            if self.bump_check:
                cmd.delete(bump_name)
                cmd.create(bump_name,
                "(((byobj %s) within 6 of (%s and not name N+C+CA+O+H+HA)) and (not (%s)))|(%s)"%
                           (src_sele,mut_sele,src_sele,mut_sele),singletons=1)
                cmd.color("gray50",bump_name+" and elem C")
                cmd.set("seq_view",0,bump_name,quiet=1)
                cmd.hide("everything",bump_name)
                if ((cmd.select(tmp_sele1, "(name N & (%s in (neighbor %s)))"%
                                (bump_name,src_sele)) == 1) and
                    (cmd.select(tmp_sele2, "(name C & (%s in %s))"%
                                (bump_name,mut_sele)) == 1)):
                    cmd.bond(tmp_sele1,tmp_sele2)
                if ((cmd.select(tmp_sele1,"(name C & (%s in (neighbor %s)))"%
                                (bump_name,src_sele)) == 1) and
                    (cmd.select(tmp_sele2,"(name N & (%s in %s))"%
                                (bump_name,mut_sele)) == 1)):
                    cmd.bond(tmp_sele1,tmp_sele2)
                cmd.delete(tmp_sele1)
                cmd.delete(tmp_sele2)

                cmd.protect("%s and not (%s in (%s and not name N+C+CA+O+H+HA))"%
                            (bump_name,bump_name,mut_sele))
                cmd.sculpt_activate(bump_name)
                cmd.show("cgo",bump_name)
                # draw the bumps
                cmd.set("sculpt_vdw_vis_mode",1,bump_name)
                state = 1
                score_best = 1e6
                for a in lib:
                    score = cmd.sculpt_iterate(bump_name, state, 1)
                    self.bump_scores.append(score)
                    if score < score_best:
                        state_best = state
                        score_best = score
                    state = state + 1
            cmd.delete(mut_sele)
        else:
            cmd.create(obj_name,frag_name,1,1)
            print(" Mutagenesis: no rotamers found in library.")
        cmd.set("seq_view",0,obj_name,quiet=1)
        pymol.util.cbaw(obj_name)
        cmd.hide("("+obj_name+")")
        cmd.show(self.rep,obj_name)
        cmd.show('lines',obj_name) #neighbor  always show lines
        if cartoon:
            cmd.show("cartoon",obj_name)
        if sticks:
            cmd.show("sticks",obj_name)
        cmd.set('auto_zoom',auto_zoom,quiet=1)
        cmd.delete(frag_name)
        cmd.frame(state_best)
        cmd.unpick()
        cmd.feedback("pop")
Пример #41
0
# pymol -qc mutate.py pdb selection new_residue
# example: pymol -qc mutate.py 0.pdb C/1/ ALA 0_mutated.pdb

from pymol import cmd
import sys

pdb, selection, mutant, output_name = sys.argv[-4:]
print("file:", pdb)
print("selection:", selection)
print("mutating to:", mutant)
print("output name:", output_name)

cmd.load(pdb, "file")

resi_num = selection.split("/")[1]
#prefix = "chain B & resi " + resi_num + " & name "
prefix = "chain A & resi " + resi_num + " & name "
orig_dihedral = cmd.get_dihedral(prefix + "C", prefix + "CA", prefix + "CB", prefix + "CG")

cmd.wizard("mutagenesis")
cmd.refresh_wizard()
cmd.get_wizard().do_select(selection)
cmd.get_wizard().set_mode(mutant)
cmd.get_wizard().apply()
cmd.set_wizard()

cmd.set_dihedral(prefix + "C", prefix + "CA", prefix + "CB", prefix + "1HB", orig_dihedral)

cmd.save(output_name, "file")
Пример #42
0
                        (float(vdw) + float(Elec)))

                ###  only args.distance atom is considered
                if args.distance:
                    if number == str(args.distance):
                        model_dict.setdefault(
                            model,
                            distance(center, tuple(map(float, (x, y, z)))))
                else:
                    model_dict.setdefault(model, 0)

                ###  only args.angle atom is considered
                if args.angle:
                    if number in args.angle:
                        angle.setdefault(
                            model, abs(cmd.get_dihedral('1', '2', '3', '4')))
                else:
                    angle.setdefault(model, 0)

                ###  only args.catalytic atoms are considered
                if args.catalytic:
                    if number in args.catalytic:
                        cat.setdefault(model, []).append(
                            (float(vdw) + float(Elec)))
                else:
                    cat.setdefault(model, [0])

                ###  only args.prova atoms are considered
                if args.catalytic:
                    if number in args.catalytic:
                        oh.setdefault(model,
Пример #43
0
def ens_measure(pk1=None,
                pk2=None,
                pk3=None,
                pk4=None,
                name=None,
                log=None,
                verbose=True):
    '''
DESCRIPTION

    Statistics from ensemble structure measurements.  If:
      2 selections give = distance
      3 selections give = angle
      4 selections give = dihedral angle

USAGE

    ens_measure pk1, pk2, pk3, pk4, name, log, verbose

ARGUMENTS

    log = name of log file
    verbose = prints individual measurements

 EXAMPLE

    ens_measure atom1, atom2, name = 'measure', log 'ens.log'
  '''
    print('\nEnsemble measurement', file=log)

    if [pk1, pk2, pk3, pk4].count(None) > 2:
        print('\nERROR: Please supply at least 2 seletions')
        return
    number_models = cmd.count_states(pk1)
    measurements = []

    # distance
    if [pk1, pk2, pk3, pk4].count(None) == 2:
        print('Distance', file=log)
        if name == None: name = 'ens_distance'
        # display as object
        cmd.distance(name=name, selection1=pk1, selection2=pk2)

        # get individual values
        for n in range(number_models):
            measurements.append(cmd.get_distance(pk1, pk2, n + 1))
        assert len(measurements) == number_models

    # angle
    if [pk1, pk2, pk3, pk4].count(None) == 1:
        print('Angle', file=log)
        # display as object
        if name == None: name = 'ens_angle'
        cmd.angle(name=name, selection1=pk1, selection2=pk2, selection3=pk3)

        # get individual values
        for n in range(number_models):
            measurements.append(
                cmd.get_angle(atom1=pk1, atom2=pk2, atom3=pk3, state=n + 1))
        assert len(measurements) == number_models

    # Dihedral angle
    if [pk1, pk2, pk3, pk4].count(None) == 0:
        print('Dihedral angle', file=log)
        # display as object
        if name == None: name = 'ens_dihedral'
        cmd.dihedral(name=name,
                     selection1=pk1,
                     selection2=pk2,
                     selection3=pk3,
                     selection4=pk4)

        # get individual values
        for n in range(number_models):
            measurements.append(
                cmd.get_dihedral(atom1=pk1,
                                 atom2=pk2,
                                 atom3=pk3,
                                 atom4=pk4,
                                 state=n + 1))
        assert len(measurements) == number_models

    # print stats
    if verbose:
        print(' State  Value', file=log)
        for n, measurement in enumerate(measurements):
            print('  %4d  %3.3f ' % (n + 1, measurement), file=log)

    print('\nMeasurement statistics', file=log)
    print_array_stats(array=measurements, log=log)
def dihe(selection, a1, a2, a3, a4, state=-1):
	atm1=selection + " and name %s" %a1;
	atm2=selection + " and name %s" %a2;
	atm3=selection + " and name %s" %a3;
	atm4=selection + " and name %s" %a4;
	return cmd.get_dihedral(atm1,atm2,atm3,atm4, state=state);	
Пример #45
0
def find_peptide_bonds(selection):
    logger.debug('Finding peptide bonds in selection {}:'.format(selection))
    for idx in iterate_indices('({}) and (e. N)'.format(selection)):
        logger.debug('Candidate N: {}'.format(idx))
        # this nitrogen should have:
        # - at least one hydrogen neighbour
        # - one carbon neighbour such as it has exactly one oxygen
        #      neighbour which has no other neighbours
        hydrogens = list(
            iterate_indices('(neighbor (idx {})) and (e. H) and ({})'.format(
                idx, selection)))
        if not hydrogens:
            # check if idx is part of a proline ring
            if not (
                (cmd.count_atoms('(e. C) and (byring idx {}) and ({})'.format(
                    idx, selection)) == 4) and
                (cmd.count_atoms('(byring idx {}) and ({})'.format(
                    idx, selection)) == 5)):
                # idx is not part of a 5-ring with 4 other carbon atoms
                continue
            logger.debug('Idx {} is a proline nitrogen'.format(idx))
            hydrogens = list(
                iterate_indices(
                    '(neighbor (idx {0})) and (byring idx {0}) and ({1})'.
                    format(idx, selection)))
            # now hydrogens contains two CARBON atoms!!!
        carbon = None
        oxygen = None
        for c in iterate_indices(
                '(neighbor (idx {})) and (e. C) and ({})'.format(
                    idx, selection)):
            logger.debug('Candidate C: {}'.format(c))
            for o in iterate_indices(
                    '(neighbor (idx {})) and (e. O) and ({})'.format(
                        c, selection)):
                logger.debug('Candidate O: {}'.format(o))
                oneighbours = list(iterate_neighbours(o, selection))
                if len(oneighbours) == 1:
                    logger.debug('Carbon is {}, oxygen is {}'.format(c, o))
                    carbon = c
                    oxygen = o
                    break
            else:
                logger.debug('No good oxygens for this C')
                continue
            break
        else:
            logger.debug('No good carbons for this N.')
            continue
        if carbon is None or oxygen is None:
            logger.debug('No carbon or no oxygen -> no N')
            continue
        for h in hydrogens:
            dih = cmd.get_dihedral(
                '(idx {}) and ({})'.format(h, selection),
                '(idx {}) and ({})'.format(idx, selection),
                '(idx {}) and ({})'.format(carbon, selection),
                '(idx {}) and ({})'.format(oxygen, selection))
            if abs(dih) > 140 or abs(dih) < 40:
                hydrogen = h
                break
        else:
            logger.debug(
                'No appropriate (planar) hydrogens for this nitrogen, oxygen and carbon.'
            )
            continue
        if (len(hydrogens) > 1) and not cmd.count_atoms(
                '(e. C) and (idx {}) and ({})'.format(hydrogen, selection)):
            # if the nitrogen has more than one hydrogens and the trans hydrogen is not a carbon
            # (i.e. this peptide bond does not belong to a proline)
            continue
        logger.debug('Found peptide bond: {}, {}, {}, {}'.format(
            hydrogen, idx, carbon, oxygen))
        yield (hydrogen, idx, carbon, oxygen)
Пример #46
0
    def do_library(self):
        cmd=self.cmd
        pymol=cmd._pymol
        if not ((cmd.count_atoms("(%s) and name N"%src_sele)==1) and
                (cmd.count_atoms("(%s) and name C"%src_sele)==1) and
                (cmd.count_atoms("(%s) and name O"%src_sele)==1)):
            self.clear()
            return 1
        cmd.feedback("push")
        cmd.feedback("disable","selector","everythin")
        cmd.feedback("disable","editor","actions")
        self.prompt = [ 'Loading rotamers...']
        self.bump_scores = []
        state_best = 0

        pymol.stored.name = 'residue'
        cmd.iterate("first (%s)"%src_sele,'stored.name=model+"/"+segi+"/"+chain+"/"+resn+"`"+resi')
        self.res_text = pymol.stored.name
        cmd.select("_seeker_hilight",src_sele)
        
        auto_zoom = cmd.get_setting_text('auto_zoom')
        cmd.set('auto_zoom',"0",quiet=1)
        cmd.frame(0)
        cmd.delete(frag_name)
        if self.auto_center:
            cmd.center(src_sele,animate=-1)

        self.lib_mode = self.mode
        if self.lib_mode=="current":
            pymol.stored.resn=""
            cmd.iterate("(%s & name CA)"%src_sele,"stored.resn=resn")
            rot_type = _rot_type_xref.get(pymol.stored.resn,pymol.stored.resn)
            if (self.c_cap!='none') or (self.n_cap!='none') or (self.hyd != 'auto'):
                self.lib_mode = rot_type # force fragment-based load
            else:
                cmd.create(frag_name,src_sele,1,1)
                if self.c_cap=='open':
                    cmd.remove("%s and name OXT"%frag_name)
                    
        if self.lib_mode!='current':
            rot_type = self.lib_mode
            frag_type = self.lib_mode
            if (self.n_cap == 'posi') and (frag_type[0:3]!='NT_'):
                if not ( cmd.count_atoms(
                    "elem C & !(%s) & (bto. (name N & (%s))) &! resn ACE"%
                                     (src_sele,src_sele))):
                    # use N-terminal fragment
                    frag_type ="NT_"+frag_type
            if (self.c_cap == 'nega') and (frag_type[0:3]!='CT_'):
                if not ( cmd.count_atoms("elem N & !(%s) & (bto. (name C & (%s))) & !resn NME+NHH"%
                                     (src_sele,src_sele))):
                    # use C-terminal fragment
                    frag_type ="CT_"+frag_type
            if rot_type[0:3] in [ 'NT_', 'CT_' ]:
                rot_type = rot_type[3:]
            rot_type = _rot_type_xref.get(rot_type, rot_type)
            cmd.fragment(frag_type.lower(), frag_name, origin=0)
            # trim off hydrogens
            if (self.hyd == 'none'):
                cmd.remove("("+frag_name+" and hydro)")
            elif (self.hyd == 'auto'):
                if cmd.count_atoms("("+src_sele+") and hydro")==0:
                    cmd.remove("("+frag_name+" and hydro)")
            # copy identifying information
            cmd.alter("?%s & name CA" % src_sele, "stored.identifiers = (segi, chain, resi, ss, color)", space=self.space)
            cmd.alter("?%s" % frag_name, "(segi, chain, resi, ss) = stored.identifiers[:4]", space=self.space)
            # move the fragment
            if ((cmd.count_atoms("(%s & name CB)"%frag_name)==1) and
                 (cmd.count_atoms("(%s & name CB)"%src_sele)==1)):
                cmd.pair_fit("(%s & name CA)"%frag_name,
                             "(%s & name CA)"%src_sele,
                             "(%s & name CB)"%frag_name,
                             "(%s & name CB)"%src_sele,
                             "(%s & name C)"%frag_name,
                             "(%s & name C)"%src_sele,
                             "(%s & name N)"%frag_name,
                             "(%s & name N)"%src_sele)
            else:
                cmd.pair_fit("(%s & name CA)"%frag_name,
                             "(%s & name CA)"%src_sele,
                             "(%s & name C)"%frag_name,
                             "(%s & name C)"%src_sele,
                             "(%s & name N)"%frag_name,
                             "(%s & name N)"%src_sele)

            # fix the carbonyl position...
            cmd.iterate_state(1,"(%s & name O)"%src_sele,"stored.list=[x,y,z]")
            cmd.alter_state(1,"(%s & name O)"%frag_name,"(x,y,z)=stored.list")
            if cmd.count_atoms("(%s & name OXT)"%src_sele):
                cmd.iterate_state(1,"(%s & name OXT)"%src_sele,"stored.list=[x,y,z]")
                cmd.alter_state(1,"(%s & name OXT)"%frag_name,"(x,y,z)=stored.list")
            elif cmd.count_atoms("(%s & name OXT)"%frag_name): # place OXT if no template exists
                angle = cmd.get_dihedral("(%s & name N)"%frag_name,
                                         "(%s & name CA)"%frag_name,
                                         "(%s & name C)"%frag_name,
                                         "(%s & name O)"%frag_name)
                cmd.protect("(%s & name O)"%frag_name)
                cmd.set_dihedral("(%s & name N)"%frag_name,
                                 "(%s & name CA)"%frag_name,
                                 "(%s & name C)"%frag_name,
                                 "(%s & name OXT)"%frag_name,180.0+angle)
                cmd.deprotect(frag_name)

                
            # fix the hydrogen position (if any)
            if cmd.count_atoms("(hydro and bound_to (name N & (%s)))"%frag_name)==1:
                if cmd.count_atoms("(hydro and bound_to (name N & (%s)))"%src_sele)==1:
                    cmd.iterate_state(1,"(hydro and bound_to (name N & (%s)))"%src_sele,
                                      "stored.list=[x,y,z]")
                    cmd.alter_state(1,"(hydro and bound_to (name N & (%s)))"%frag_name,
                                    "(x,y,z)=stored.list")
                elif cmd.select(tmp_sele1,"(name C & bound_to (%s and elem N))"%src_sele)==1:
                    # position hydro based on location of the carbonyl
                    angle = cmd.get_dihedral("(%s & name C)"%frag_name,
                                             "(%s & name CA)"%frag_name,
                                             "(%s & name N)"%frag_name,
                                             tmp_sele1)
                    cmd.set_dihedral("(%s & name C)"%frag_name,
                                     "(%s & name CA)"%frag_name,
                                     "(%s & name N)"%frag_name,
                                     "(%s & name H)"%frag_name,180.0+angle)
                    cmd.delete(tmp_sele1)

            # add c-cap (if appropriate)
            if self.c_cap in [ 'amin', 'nmet' ]:
                if not cmd.count_atoms("elem N & !(%s) & (bto. (name C & (%s))) & !resn NME+NHH"%
                                       (src_sele,src_sele)):
                    if cmd.count_atoms("name C & (%s)"%(frag_name))==1:
                        if self.c_cap == 'amin':
                            editor.attach_amino_acid("name C & (%s)"%(frag_name), 'nhh')
                        elif self.c_cap == 'nmet':
                            editor.attach_amino_acid("name C & (%s)"%(frag_name), 'nme')
                        if cmd.count_atoms("hydro & bound_to (name N & bound_to (name C & (%s)))"%frag_name):
                            cmd.h_fix("name N & bound_to (name C & (%s))"%frag_name)
                        # trim hydrogens
                        if (self.hyd == 'none'):
                            cmd.remove("("+frag_name+" and hydro)")
                        elif (self.hyd == 'auto'):
                            if cmd.count_atoms("("+src_sele+") and hydro")==0:
                                cmd.remove("("+frag_name+" and hydro)")
                         
            # add n-cap (if appropriate)
            if self.n_cap in [ 'acet' ]:
                if not cmd.count_atoms("elem C & !(%s) & (bto. (name N & (%s))) & !resn ACE "%
                                       (src_sele,src_sele)):
                    if cmd.count_atoms("name N & (%s)"%(frag_name))==1:
                        if self.n_cap == 'acet':
                            editor.attach_amino_acid("name N & (%s)"%(frag_name), 'ace')
                        if cmd.count_atoms("hydro & bound_to (name N & bound_to (name C & (%s)))"%frag_name):
                            cmd.h_fix("name N & (%s)"%frag_name)
                        # trim hydrogens
                        if (self.hyd == 'none'):
                            cmd.remove("("+frag_name+" and hydro)")
                        elif (self.hyd == 'auto'):
                            if cmd.count_atoms("("+src_sele+") and hydro")==0:
                                cmd.remove("("+frag_name+" and hydro)")
 

                    

        cartoon = (cmd.count_atoms("(%s & name CA & rep cartoon)"%src_sele)>0)
        sticks = (cmd.count_atoms("(%s & name CA & rep sticks)"%src_sele)>0)
            
        cmd.delete(obj_name)
        key = rot_type
        lib = None
        if self.dep == 'dep':
            try:
                result = cmd.phi_psi("%s"%src_sele)
                if len(result)==1:
                    (phi,psi) = list(result.values())[0]
                    (phi,psi) = (int(10*round(phi/10)),int(10*(round(psi/10))))
                    key = (rot_type,phi,psi)
                    if key not in self.dep_library:
                        (phi,psi) = (int(20*round(phi/20)),int(20*(round(psi/20))))
                        key = (rot_type,phi,psi)                    
                        if key not in self.dep_library:
                            (phi,psi) = (int(60*round(phi/60)),int(60*(round(psi/60))))
                            key = (rot_type,phi,psi)
                    lib = self.dep_library.get(key,None)
            except:
                pass
        if lib == None:
            key = rot_type
            lib = self.ind_library.get(key,None)
            if (lib!= None) and self.dep == 'dep':
                print(' Mutagenesis: no phi/psi, using backbone-independent rotamers.')
        if lib != None:
            state = 1
            for a in lib:
                cmd.create(obj_name,frag_name,1,state)
                if state == 1:
                    cmd.select(mut_sele,"(byres (%s like %s))"%(obj_name,src_sele)) 
                if rot_type=='PRO':
                    cmd.unbond("(%s & name N)"%mut_sele,"(%s & name CD)"%mut_sele)
                for b in a.keys():
                    if b!='FREQ':
                        cmd.set_dihedral("(%s & n;%s)"%(mut_sele,b[0]),
                                         "(%s & n;%s)"%(mut_sele,b[1]),
                                         "(%s & n;%s)"%(mut_sele,b[2]),
                                         "(%s & n;%s)"%(mut_sele,b[3]),
                                         a[b],state=state)
                    else:
                        cmd.set_title(obj_name,state,"%1.1f%%"%(a[b]*100))
                if rot_type=='PRO':
                    cmd.bond("(%s & name N)"%mut_sele,"(%s & name CD)"%mut_sele)                
                state = state + 1
            cmd.delete(frag_name)
            print(" Mutagenesis: %d rotamers loaded."%len(lib))
            if self.bump_check:
                cmd.delete(bump_name)
                cmd.create(bump_name,
                "(((byobj %s) within 6 of (%s and not name N+C+CA+O+H+HA)) and (not (%s)))|(%s)"%
                           (src_sele,mut_sele,src_sele,mut_sele),singletons=1)
                cmd.color("gray50",bump_name+" and elem C")
                cmd.set("seq_view",0,bump_name,quiet=1)
                cmd.hide("everything",bump_name)
                if ((cmd.select(tmp_sele1, "(name N & (%s in (neighbor %s)))"%
                                (bump_name,src_sele)) == 1) and
                    (cmd.select(tmp_sele2, "(name C & (%s in %s))"%
                                (bump_name,mut_sele)) == 1)):
                    cmd.bond(tmp_sele1,tmp_sele2)
                if ((cmd.select(tmp_sele1,"(name C & (%s in (neighbor %s)))"%
                                (bump_name,src_sele)) == 1) and
                    (cmd.select(tmp_sele2,"(name N & (%s in %s))"%
                                (bump_name,mut_sele)) == 1)):
                    cmd.bond(tmp_sele1,tmp_sele2)
                cmd.delete(tmp_sele1)
                cmd.delete(tmp_sele2)
                
                cmd.protect("%s and not (%s in (%s and not name N+C+CA+O+H+HA))"%
                            (bump_name,bump_name,mut_sele))
                cmd.sculpt_activate(bump_name)
                cmd.show("cgo",bump_name)
                # draw the bumps
                cmd.set("sculpt_vdw_vis_mode",1,bump_name)
                state = 1
                score_best = 1e6
                for a in lib:
                    score = cmd.sculpt_iterate(bump_name, state, 1)
                    self.bump_scores.append(score)
                    if score < score_best:
                        state_best = state
                        score_best = score
                    state = state + 1
            cmd.delete(mut_sele)
        else:
            cmd.create(obj_name,frag_name,1,1)
            print(" Mutagenesis: no rotamers found in library.")
        cmd.set("seq_view",0,obj_name,quiet=1)
        pymol.util.cbaw(obj_name)
        cmd.hide("("+obj_name+")")
        cmd.show(self.rep,obj_name)
        cmd.show('lines',obj_name) #neighbor  always show lines
        if cartoon:
            cmd.show("cartoon",obj_name)
        if sticks:
            cmd.show("sticks",obj_name)
        cmd.set('auto_zoom',auto_zoom,quiet=1)
        cmd.delete(frag_name)
        cmd.frame(state_best)
        cmd.unpick()
        cmd.feedback("pop")
Пример #47
0
def mutate(selection, new_resn, inplace=0, sculpt=0, hydrogens='auto', mode=0, quiet=1):
    '''
DESCRIPTION

    Mutate a single residue. Does call the mutagenesis wizard non-interactively
    and tries to select the best rotamer. Can do some sculpting in the end to
    the best rotamer.

USAGE

    mutate selection, new_resn [, inplace [, sculpt [, hydrogens]]]

ARGUMENTS

    selection = string: atom selection of single residue

    new_resn = string: new residue name (3-letter or 1-letter)

    inplace = 0 or 1: work on copy of input object if 0 {default: 0}

    sculpt = 0: no sculpting {default}
    sculpt = 1: do sculpting on best rotamer
    sculpt = 2: do sculpting with neighbors

    hydrogens = string: keep, auto or none {default: auto}

    mode = 0: select rotamer with best clash score {default}
    mode = 1: take chi angles from original residue
    mode = 2: first rotamer

EXAMPLE

    fetch 2x19, async=0
    select x, A/CYS`122/
    zoom x
    mutate x, LYS
    '''
    from pymol.wizard import mutagenesis
    from . import three_letter

    inplace, sculpt = int(inplace), int(sculpt)
    mode = int(mode)
    quiet = int(quiet)
    org = cmd.get_object_list(selection)[0]
    tmp = cmd.get_unused_name()
    new_resn = new_resn.upper()
    new_resn = three_letter.get(new_resn, new_resn)

    if inplace:
        cpy = org
    else:
        cpy = cmd.get_unused_name(org + '_cpy')
        cmd.create(cpy, org, -1, 1, zoom=0)

    scr = []
    cmd.iterate('first (%s)' % selection, 'scr[:] = (segi,chain,resi,resn)', space={'scr': scr})
    res = '/%s/%s/%s/%s' % tuple([cpy] + scr[:3])

    if mode == 1:
        old_resn = scr[3]
        chi_atoms = {
            'ALA': [],
            'ARG': ['C','CA','CB','CG','CD','NE','CZ'],
            'ASN': ['C','CA','CB','CG','OD1'],
            'ASP': ['C','CA','CB','CG','OD1'],
            'CYS': ['C','CA','CB','SG'],
            'GLN': ['C','CA','CB','CG','CD','OE1'],
            'GLU': ['C','CA','CB','CG','CD','OE1'],
            'GLY': [],
            'HIS': ['C','CA','CB','CG','ND1'],
            'ILE': ['C','CA','CB','CG1','CD1'],
            'LEU': ['C','CA','CB','CG','CD1'],
            'LYS': ['C','CA','CB','CG','CD','CE','NZ'],
            'MET': ['C','CA','CB','CG','SD','CE'],
            'MSE': ['C','CA','CB','CG','SE','CE'],
            'PHE': ['C','CA','CB','CG','CD1'],
            'PRO': [],
            'SER': ['C','CA','CB','OG'],
            'THR': ['C','CA','CB','OG1'],
            'TRP': ['C','CA','CB','CG','CD2'],
            'TYR': ['C','CA','CB','CG','CD1'],
            'VAL': ['C','CA','CB','CG2'],
        }
        atoms = [res + '/' + name for name in chi_atoms.get(old_resn, [])]
        old_chi = []
        for args in zip(atoms, atoms[1:], atoms[2:], atoms[3:]):
            try:
                old_chi.append(cmd.get_dihedral(*args))
            except:
                break

    cmd.remove('%s and not name CA+C+N+O+OXT' % (res))

    # start the wizard to count the number of rotamers for this residue
    cmd.wizard("mutagenesis")
    cmd.get_wizard().set_mode(new_resn)
    cmd.get_wizard().set_hyd(hydrogens)
    cmd.get_wizard().do_select("("+res+")")

    def get_best_state_bump():
        best_state = (1, 1e9)
        cmd.create(tmp, '%s and not name CA+C+N+O or (%s within 8.0 of (%s and name CB))' % \
                (mutagenesis.obj_name, cpy, mutagenesis.obj_name), zoom=0, singletons=1)
        cmd.bond('name CB and %s in %s' % (tmp, mutagenesis.obj_name),
                'name CA and %s in %s' % (tmp, res))
        cmd.sculpt_activate(tmp)
        for i in range(1, cmd.count_states(tmp)+1):
            score = cmd.sculpt_iterate(tmp, state=i)
            if not quiet:
                print('Frame %d Score %.2f' % (i, score))
            if score < best_state[1]:
                best_state = (i, score)
        cmd.delete(tmp)
        if not quiet:
            print(' Best: Frame %d Score %.2f' % best_state)
        return best_state

    if cmd.count_states(mutagenesis.obj_name) < 2 or mode > 0:
        best_state = (1, -1.0)
    else:
        best_state = get_best_state_bump()
    cmd.frame(best_state[0])
    cmd.get_wizard().apply()
    cmd.wizard()

    if mode == 1:
        atoms = [res + '/' + name for name in chi_atoms.get(new_resn, [])]
        for args in zip(atoms, atoms[1:], atoms[2:], atoms[3:], old_chi):
            cmd.set_dihedral(*args)
        cmd.unpick()

    if sculpt > 0:
        sculpt_relax(res, 0, sculpt == 2, cpy)

    return cpy
Пример #48
0
def mutate(selection, new_resn, inplace=0, sculpt=0, hydrogens='auto', mode=0, quiet=1):
    '''
DESCRIPTION

    Mutate a single residue. Does call the mutagenesis wizard non-interactively
    and tries to select the best rotamer. Can do some sculpting in the end to
    the best rotamer.

USAGE

    mutate selection, new_resn [, inplace [, sculpt [, hydrogens]]]

ARGUMENTS

    selection = string: atom selection of single residue

    new_resn = string: new residue name (3-letter or 1-letter)

    inplace = 0 or 1: work on copy of input object if 0 {default: 0}

    sculpt = 0: no sculpting {default}
    sculpt = 1: do sculpting on best rotamer
    sculpt = 2: do sculpting with neighbors

    hydrogens = string: keep, auto or none {default: auto}

    mode = 0: select rotamer with best clash score {default}
    mode = 1: take chi angles from original residue
    mode = 2: first rotamer

EXAMPLE

    fetch 2x19, async=0
    select x, A/CYS`122/
    zoom x
    mutate x, LYS
    '''
    from pymol.wizard import mutagenesis
    from . import three_letter

    inplace, sculpt = int(inplace), int(sculpt)
    mode = int(mode)
    quiet = int(quiet)
    org = cmd.get_object_list(selection)[0]
    tmp = cmd.get_unused_name()
    new_resn = new_resn.upper()
    new_resn = three_letter.get(new_resn, new_resn)

    if inplace:
        cpy = org
    else:
        cpy = cmd.get_unused_name(org + '_cpy')
        cmd.create(cpy, org, -1, 1, zoom=0)

    scr = []
    cmd.iterate('first (%s)' % selection, 'scr[:] = (segi,chain,resi,resn)', space={'scr': scr})
    res = '/%s/%s/%s/%s' % tuple([cpy] + scr[:3])

    if mode == 1:
        old_resn = scr[3]
        chi_atoms = {
            'ALA': [],
            'ARG': ['C','CA','CB','CG','CD','NE','CZ'],
            'ASN': ['C','CA','CB','CG','OD1'],
            'ASP': ['C','CA','CB','CG','OD1'],
            'CYS': ['C','CA','CB','SG'],
            'GLN': ['C','CA','CB','CG','CD','OE1'],
            'GLU': ['C','CA','CB','CG','CD','OE1'],
            'GLY': [],
            'HIS': ['C','CA','CB','CG','ND1'],
            'ILE': ['C','CA','CB','CG1','CD1'],
            'LEU': ['C','CA','CB','CG','CD1'],
            'LYS': ['C','CA','CB','CG','CD','CE','NZ'],
            'MET': ['C','CA','CB','CG','SD','CE'],
            'MSE': ['C','CA','CB','CG','SE','CE'],
            'PHE': ['C','CA','CB','CG','CD1'],
            'PRO': [],
            'SER': ['C','CA','CB','OG'],
            'THR': ['C','CA','CB','OG1'],
            'TRP': ['C','CA','CB','CG','CD2'],
            'TYR': ['C','CA','CB','CG','CD1'],
            'VAL': ['C','CA','CB','CG2'],
        }
        atoms = [res + '/' + name for name in chi_atoms.get(old_resn, [])]
        old_chi = []
        for args in zip(atoms, atoms[1:], atoms[2:], atoms[3:]):
            try:
                old_chi.append(cmd.get_dihedral(*args))
            except:
                break

    cmd.remove('%s and not name CA+C+N+O+OXT' % (res))

    # start the wizard to count the number of rotamers for this residue
    cmd.wizard("mutagenesis")
    cmd.get_wizard().set_mode(new_resn)
    cmd.get_wizard().set_hyd(hydrogens)
    cmd.get_wizard().do_select("("+res+")")

    def get_best_state_bump():
        best_state = (1, 1e9)
        cmd.create(tmp, '%s and not name CA+C+N+O or (%s within 8.0 of (%s and name CB))' % \
                (mutagenesis.obj_name, cpy, mutagenesis.obj_name), zoom=0, singletons=1)
        cmd.bond('name CB and %s in %s' % (tmp, mutagenesis.obj_name),
                'name CA and %s in %s' % (tmp, res))
        cmd.sculpt_activate(tmp)
        for i in range(1, cmd.count_states(tmp)+1):
            score = cmd.sculpt_iterate(tmp, state=i)
            if not quiet:
                print('Frame %d Score %.2f' % (i, score))
            if score < best_state[1]:
                best_state = (i, score)
        cmd.delete(tmp)
        if not quiet:
            print(' Best: Frame %d Score %.2f' % best_state)
        return best_state

    if cmd.count_states(mutagenesis.obj_name) < 2 or mode > 0:
        best_state = (1, -1.0)
    else:
        best_state = get_best_state_bump()
    cmd.frame(best_state[0])
    cmd.get_wizard().apply()
    cmd.wizard()

    if mode == 1:
        atoms = [res + '/' + name for name in chi_atoms.get(new_resn, [])]
        for args in zip(atoms, atoms[1:], atoms[2:], atoms[3:], old_chi):
            cmd.set_dihedral(*args)
        cmd.unpick()

    if sculpt > 0:
        sculpt_relax(res, 0, sculpt == 2, cpy)

    return cpy
Пример #49
0
for filename in filenames:
    with open(filename, 'r') as f:
        lines = f.readlines()
        lines = list(filter(filter_func , lines))
        dih_pairs.extend(list(map(map_func, lines)))
        restraints.extend(list(map(map_func2, lines)))

out_lines = []
for dih_pair,restraint in zip(dih_pairs, restraints):
    group1 = "(id %d)" % dih_pair[0]
    group2 = "(id %d)" % dih_pair[1]
    group3 = "(id %d)" % dih_pair[2]
    group4 = "(id %d)" % dih_pair[3]
    cmd.dihedral("%d-%d-%d-%d" % dih_pair, group1, group2, group3, group4)
    resns = []
    resis = []
    atoms = []
    cmd.iterate("id %d+%d+%d+%d" % dih_pair, "resns.append(resn)")
    cmd.iterate("id %d+%d+%d+%d" % dih_pair, "resis.append(resi)")
    cmd.iterate("id %d+%d+%d+%d" % dih_pair, "atoms.append(name)")
    dihedral = cmd.get_dihedral(group1, group2, group3, group4)
    out_lines.append("[ %s%s(%s)-%s%s(%s)-%s%s(%s)-%s%s(%s) ~ %.2f degree (%s, %s, %s)]\n" % ((resns[0], resis[0], atoms[0], resns[1], resis[1], atoms[1], resns[2], resis[2], atoms[2],resns[3], resis[3], atoms[3],  dihedral) + restraint))
    out_lines.append("%d %d %d %d\n" % dih_pair)

# write dis_pairs to distance_pairs.ndx for analysis
with open("dihedral_out.ndx", 'w') as f:
    for line in out_lines:
        f.write(line)
        print(line)
Пример #50
0
def color_abego( opt_enabled_only=True ):
	pdb_list = PDB_list()
	
	# make a namespace for iterate()
	myspace = { 'pdb_list' : pdb_list }
	cmd.iterate( 'n. ca', 'pdb_list.add_res( model, chain, resv )', space=myspace )

	# loop over each object
	for key, pdb in pdb_list.pdbs.iteritems():
		if pdb.name in cmd.get_names( 'objects', enabled_only=opt_enabled_only ):
			
			# list of residues for each ABEGO type
			bb_a = []
			bb_b = []
			bb_e = []
			bb_g = []
			bb_o = []
			
			# loop over each residue and calculate ABEGO type
			for res in pdb.residues:
				if ( res[0], res[1] - 1 ) in pdb.residues and ( res[0], res[1] + 1 ) in pdb.residues:
					a1 = '{0} and chain {1} and resi {2} and name {3}'.format( pdb, res[0], res[1] - 1, 'C' )
					a2 = '{0} and chain {1} and resi {2} and name {3}'.format( pdb, res[0], res[1]    , 'N' )
					a3 = '{0} and chain {1} and resi {2} and name {3}'.format( pdb, res[0], res[1]    , 'CA' )
					a4 = '{0} and chain {1} and resi {2} and name {3}'.format( pdb, res[0], res[1]    , 'C' )
					a5 = '{0} and chain {1} and resi {2} and name {3}'.format( pdb, res[0], res[1] + 1, 'N' )
					a6 = '{0} and chain {1} and resi {2} and name {3}'.format( pdb, res[0], res[1] + 1, 'CA' )
					phi = cmd.get_dihedral( a1, a2, a3, a4 )
					psi = cmd.get_dihedral( a2, a3, a4, a5 )
					omega = cmd.get_dihedral( a3, a4, a5, a6 )
					if abs( omega ) < 90 or abs( omega ) > 270:
						bb_o.append( res )
						continue

					if phi > 0:
						if psi < 100 and psi > -100:
							bb_g.append( res )
							continue
						else:
							bb_e.append( res )	
							continue
					else:
						if psi < 50 and psi > -72:
							bb_a.append( res )
							continue
						else:
							bb_b.append( res )
							continue

			# color carbons based on residue ABEGO type
			cmd.color( 'gray', '{0} and e. c'.format( pdb ) )
			if bb_a:
				cmd.select( 'bb_a', ' OR '.join( '{0} and chain {1[0]} and resi {1[1]} and e. c'.format( pdb, x ) for x in bb_a ) )
				cmd.color( 'red', 'bb_a' )
			if bb_b:
				cmd.select( 'bb_b', ' OR '.join( '{0} and chain {1[0]} and resi {1[1]} and e. c'.format( pdb, x ) for x in bb_b ) )
				cmd.color( 'blue', 'bb_b' )
			if bb_e:
				cmd.select( 'bb_e', ' OR '.join( '{0} and chain {1[0]} and resi {1[1]} and e. c'.format( pdb, x ) for x in bb_e ) )
				cmd.color( 'yellow', 'bb_e' )
			if bb_g:
				cmd.select( 'bb_g', ' OR '.join( '{0} and chain {1[0]} and resi {1[1]} and e. c'.format( pdb, x ) for x in bb_g ) )
				cmd.color( 'green', 'bb_g' )
			if bb_o:
				cmd.select( 'bb_o', ' OR '.join( '{0} and chain {1[0]} and resi {1[1]} and e. c'.format( pdb, x ) for x in bb_o ) )
				cmd.color( 'orange', 'bb_o' )
	
	# delete selections
	cmd.delete( 'bb_a' )
	cmd.delete( 'bb_b' )
	cmd.delete( 'bb_e' )
	cmd.delete( 'bb_g' )
	cmd.delete( 'bb_o' )