Exemplo n.º 1
0
def get_distance(file_name, res1, atom1, res2, atom2):
    pymol.finish_launching()
    cmd.delete('all')
    cmd.load(file_name)
    cmd.select('atom1', 'resn ' + res1 + ' and name ' + atom1)
    cmd.select('atom2', 'resn ' + res2 + ' and name ' + atom2)
    print cmd.get_distance('atom1', 'atom2')
Exemplo n.º 2
0
def generate_distances(obj1,
                       startres,
                       endres,
                       atname,
                       filename="",
                       resi_offset=0):
    if (filename != ""):
        file = open(filename, 'w')
    for first_res_iterate in range(int(startres), int(endres)):
        for second_res_iterate in range(
                int(first_res_iterate) + 1,
                int(endres) + 1):
            mydist = cmd.get_distance(
                atom1=obj1 + " and resi " + str(first_res_iterate) +
                " and name " + atname,
                atom2=obj1 + " and resi " + str(second_res_iterate) +
                " and name " + atname)
            print str(first_res_iterate) + " " + str(
                second_res_iterate) + " " + str(mydist)
            if (filename != ""):
                file.write("AtomPair " + atname + " " +
                           str(int(first_res_iterate) + int(resi_offset)) +
                           " " + atname + " " +
                           str(int(second_res_iterate) + int(resi_offset)) +
                           " HARMONIC " + str(mydist) + " " + str(2) + "\n")

    if (filename != ""):
        file.close()
Exemplo n.º 3
0
def TMdistCheck(selection, z):
    """
    determine cross section distances about origin of trans-membrane region of protein PDB
    (distance from origin to protein atoms in xy plane)
    """
    cmd.pseudoatom("origin0", pos=[0, 0, 10])
    dmax = []
    for ang in range(0, 181, 10):
        dlist = []
        cmd.rotate('z', ang, selection)
        xLine = "{} and z > {} and z < {}  and y > {} and y < {}".format(selection, -z, z, -z, z)
        atoms = cmd.index(xLine)
        if len(atoms) == 0:
            print("No atoms in {}.".format(xLine))
            continue
        # find R in only one cross-section
        for at1 in cmd.index("origin0"):
            for at2 in atoms:
                dist = cmd.get_distance(atom1=at1, atom2=at2, state=0)
                dlist.append(dist)
        dmax.append(max(dlist))
        cmd.rotate('z', -ang, selection)
    if len(dmax) == 0:
        meanXY = -1
    else:
        meanXY = np.mean(dmax)
    cmd.pseudoatom("origin0", pos=[0, 0, 0])
    return meanXY
Exemplo n.º 4
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)
Exemplo n.º 5
0
def evaluate_clash(atom1, atom2, threshold):
    """Evaluate if atoms are closer that trashold.

    Parameters
    ----------
    atom1 : String
        String selection for atom1.
    atom2 : String
        String selection for atom1.
    threshold : Float
        Minimum distance to report a clash.

    Returns
    -------
    bool
        If distance is less than threshold, it returns True.

    """
    # get distance between atoms
    distance = cmd.get_distance(atom1, atom2)

    if distance <= threshold:

        return True

    return False
Exemplo n.º 6
0
def f_get_monomer_distances(monomer_PDB, monomer_PDB_type, term_residue, iface_res, iface_residues):
  e_dist = -1
  s_dist = -1
  min_iface_dist = -1
  try:
   if ((monomer_PDB != "NA") & (iface_res != "NA") & (term_residue != "NA")):
    if (monomer_PDB_type == "Model"):
      this_PDB_path = PATH_PDB_MONO_MOD
    else:
      this_PDB_path = PATH_PDB_MONO_EXP
    PDB_file = "%s/%s" % (this_PDB_path, monomer_PDB)
    cmd.load(PDB_file, "this_mono")
    # distance from terminal to interface center
    e_dist = cmd.get_distance("first this_mono & name ca & resi %s" % term_residue, "first this_mono & name ca & resi %s" % iface_res)
    ## minimum distance to interface residues
    if (iface_residues != ["NA"]):
      if (term_residue in iface_residues):
        min_iface_dist = 0
      else:
        resi_txt = " or ".join(["resi " + this_res for this_res in iface_residues])
        min_iface_dist = distancetoatom.distancetoatom(origin="first this_mono & name ca & resi %s" % term_residue, selection="this_mono & name ca & (%s)" % resi_txt, property_name="", cutoff=1000)[2][4]
  except:
    print "ERROR in monomer distances %s (%s) %s %s\n" % (monomer_PDB, monomer_PDB_type, term_residue, iface_res)
  cmd.delete("this_mono")
  to_return = { 'e_dist': e_dist }
  return to_return
Exemplo n.º 7
0
def get_Ca_distance(pymol_object, chainID1, aa_number1, chainID2, aa_number2):
    """Get distance between CA atoms between two residues.

    Method to measure the distance between Ca carbon of different residues
    defined by their chainID and residue number.

    Parameters
    ----------
    pymol_object : String
        Name of Pymol object in the session.
    chainID1 : String
        ChainID of the first residue.
    aa_number1 : Integer
        Residue number of the first residue.
    chainID2 : String
        ChainID of the second residue.
    aa_number2 : Integer
        Residue number of the second residue.

    Returns
    -------
    distance : Float
        Value of distance between the two Ca carbons selected.


    """
    # Atom selection following Pymol format
    atom1 = pymol_object + '//' + chainID1 + '/' + str(aa_number1) + '/CA'
    atom2 = pymol_object + '//' + chainID2 + '/' + str(aa_number2) + '/CA'

    distance = cmd.get_distance(atom1, atom2)

    return distance
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
Exemplo n.º 9
0
def findAverDist(selection):
    dlist = []
    cmd.pseudoatom("origin0", pos=[0, 0, 0])
    for at1 in cmd.index("origin0"):
        for at2 in cmd.index(selection)[::30]:
            dist = cmd.get_distance(atom1=at1, atom2=at2, state=0)
            dlist.append(dist)
    return np.mean(dlist)
Exemplo n.º 10
0
def get_terminal_residues_and_euclidian_distances_from_residue(chain, residue, position=0):
  N_res = len(cmd.get_model("chain %s & name ca" % chain).atom)
  if (position < N_res):
    N_term_res         = cmd.get_model("chain %s & name ca and resi 1-" % chain).atom[position].resi            # smallest residue is 1 (negative residues are ignored)
    C_term_res         = cmd.get_model("chain %s & name ca" % chain).atom[-(position+1)].resi
    d_N_term_iface     = cmd.get_distance("first chain %s & name ca & resi %s" % (chain, N_term_res), residue)  # we have to use "first" because there was some strange error message
    d_C_term_iface     = cmd.get_distance("first chain %s & name ca & resi %s" % (chain, C_term_res), residue)
  else:
    N_term_res = "NA"
    C_term_res = "NA"
    d_N_term_iface = float('nan')
    d_C_term_iface = float('nan')
  to_return = {'N_term_res' : N_term_res,
               'C_term_res' : C_term_res,
               'd_N_term_iface' : d_N_term_iface,
               'd_C_term_iface' : d_C_term_iface}
  return to_return
Exemplo n.º 11
0
def find_beta_hbonds(selection,
                     mindist,
                     maxdist,
                     anglemin,
                     verbose: bool = False,
                     nitrogen_atomnames='N+NT',
                     oxygen_atomnames='O+OT1+OT2',
                     hydrogen_atomnames='H+HN+HT1+HT2+HT+H1+H2+H3'):
    """
    Detect hydrogen bonds in beta peptides (and probably other peptides, too)

    Inputs:
        selection: a selection containing everything,

    """
    donors = cmd.get_model('({}) and name {}'.format(selection,
                                                     nitrogen_atomnames))
    acceptors = cmd.get_model('({}) and name {}'.format(
        selection, oxygen_atomnames))
    if verbose:
        print('Finding hydrogen bonds in selection {}'.format(selection))
        print('Donors: {}'.format(len(donors.atom)))
        print('Acceptors: {}'.format(len(acceptors.atom)))
    for d in donors.atom:
        assert isinstance(d, chempy.Atom)
        hydrogens = cmd.get_model(
            '(neighbor (({}) and index {})) and name {}'.format(
                selection, d.index, hydrogen_atomnames))
        if verbose:
            print('Looking at donor {}, having {} hydrogens'.format(
                d.index, len(hydrogens.atom)))
        for h in hydrogens.atom:
            assert isinstance(h, chempy.Atom)
            for a in acceptors.atom:
                assert isinstance(a, chempy.Atom)
                # check hydrogen-acceptor distance
                dist = cmd.get_distance(
                    '({}) and name {} and index {}'.format(
                        selection, oxygen_atomnames, a.index),
                    '({}) and name {} and index {}'.format(
                        selection, hydrogen_atomnames, h.index))
                cmd.unpick()
                angle = cmd.get_angle(
                    '({}) and name {} and index {}'.format(
                        selection, oxygen_atomnames,
                        a.index), '({}) and name {} and index {}'.format(
                            selection, hydrogen_atomnames, h.index),
                    '({}) and name {} and index {}'.format(
                        selection, nitrogen_atomnames, d.index))
                if verbose:
                    print('Distance between hydrogen {} and acceptor {}: {}'.
                          format(h.index, a.index, dist))
                    print(
                        'Angle between donor {}, hydrogen {} and acceptor {}: {}'
                        .format(d.index, h.index, a.index, angle))
                if (dist <= float(maxdist)) and (dist >= float(mindist)) and (
                        angle >= float(anglemin)):
                    yield d.index, h.index, a.index, dist, angle
Exemplo n.º 12
0
def DrawDRSASA_ByRes(fname):
    cols, rows, matrix, direc = ReadProtDNAByResTable(fname)

    mtrx = np.array(matrix).flatten()
    mtrx = mtrx[mtrx != 0]
    mvalue = np.max(mtrx)
    minvalue = np.min(mtrx)
    mv075 = mvalue * 0.75
    median = np.median(mtrx)
    avg = np.average(mtrx)
    cutoff = mvalue * 0.05
    cmd.color("grey", "all")
    print median, avg, cutoff, minvalue
    Rl = []
    Gl = []
    Bl = []

    for row in range(len(matrix)):
        for col in range(len(matrix[row])):
            v = float(matrix[row][col])
            if v < cutoff:
                continue
            R = 1.8 * v / mvalue

            rid = [str(item) for item in rows[row]]
            cid = [str(item) for item in cols[col]]
            sele1, resn1 = GenSele(rid[0], rid[1], rid[2])
            sele2, resn2 = GenSele(cid[0], cid[1], cid[2])
            print(sele1, sele2)
            cmd.select("atom1", sele1)
            cmd.select("atom2", sele2)
            d = cmd.get_distance("atom1", "atom2")
            if direc == 0:
                resn_s = resn2
            elif direc == 1:
                resn_s = resn1
            if (v >= mv075):
                color = "red red"
                Rl.append(resn_s)
                cmd.color("red", resn_s)
            elif (v > median):
                color = "green green"
                Gl.append(resn_s)
                if not resn_s in Rl:
                    cmd.color("green", resn_s)
            else:
                color = "blue blue"
                if (not resn_s in Rl) and (not resn_s in Gl):
                    cmd.color("blue", resn_s)

            if direc == 0:
                cgo_arrow("atom2", "atom1", 0.1, d * 0.25, d * 0.1, R, color,
                          "/".join(rid) + "_" + "/".join(cid))
            elif direc == 1:
                cgo_arrow("atom1", "atom2", 0.1, d * 0.25, d * 0.1, R, color,
                          "/".join(rid) + "_" + "/".join(cid))
Exemplo n.º 13
0
def findMaxDist(selection):
    """
    finds the longest distance within a molecule
    """
    dlist = []
    for at1 in cmd.index(selection):
        for at2 in cmd.index(selection):
            dist = cmd.get_distance(atom1=at1, atom2=at2, state=0)
            dlist.append(dist)
    dmax = max(dlist)
    return dmax
Exemplo n.º 14
0
def DistancesFromPKSelection(selections = []):
    """ Function doc """
    distances = {} 
    try:
        distances['pk1pk2'] = str(cmd.get_distance('pk1','pk2') )
    except:
        distances['pk1pk2'] = None
    try:
        distances['pk1pk3'] = str(cmd.get_distance('pk1','pk3') )
    except:
        distances['pk1pk3'] = None
    try:
        distances['pk1pk4'] = str(cmd.get_distance('pk1','pk4') )
    except:
        distances['pk1pk4'] = None
    try:
        distances['pk2pk3'] = str(cmd.get_distance('pk2','pk3') )
    except:
        distances['pk2pk3'] = None
    try:
        distances['pk2pk4'] = str(cmd.get_distance('pk2','pk4') )
    except:
        distances['pk2pk4'] = None
    try:
        distances['pk3pk4'] = str(cmd.get_distance('pk3','pk4') )
    except:
        distances['pk3pk4'] = None
    return distances
Exemplo n.º 15
0
def get_hbdists(angles, resmin, resmax, resistep, selection='all', helicize=True):
    if helicize:
        helicize_beta_peptide(angles, selection)
    dists = []
    for r, rstep in zip(range(resmin, resmax + 1), itertools.cycle(resistep)):
        if rstep == 0: continue
        if r<resmin or r+rstep<resmin or r>resmax or r+rstep>resmax: continue
        selections = ['({}) and resi {} and name HN'.format(selection, r),
                      '({}) and resi {} and name O'.format(selection, r + rstep)]
        if not all([cmd.count_atoms(sel) for sel in selections]):
            continue
        dists.append(cmd.get_distance(*selections))
    return np.array(dists)
Exemplo n.º 16
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()
Exemplo n.º 17
0
    def getOrderedDist(self, motif, id):
        distDict = {}
        orderedDistDict = {}
        resilist = []
        chain = lib.getChain(id)
        for res in motif:
            resilist.append(res[1])

        for res_1 in motif:
            for res_2 in motif:
                if res_1[1] != res_2[1]:

                    if res_1[0] == 'GLY':
                        atom_1 = 'CA'
                    elif self.isMetal(res_1[0]):
                        atom_1 = res_1[0]
                    else:
                        atom_1 = 'CB'

                    if res_2[0] == 'GLY':
                        atom_2 = 'CA'
                    elif self.isMetal(res_2[0]):
                        atom_2 = res_2[0]
                    else:
                        atom_2 = 'CB'

                    cmd.reinitialize()
                    cmd.fetch(id, async=0, path=glb.FETCH_PATH)
                    dstr = chain + '/' + res_1[
                        1] + '/' + atom_1 + ' and ' + chain + '/' + res_2[
                            1] + '/' + atom_2
                    try:
                        d = cmd.get_distance(
                            chain + '/' + res_1[1] + '/' + atom_1,
                            chain + '/' + res_2[1] + '/' + atom_2)
                        distDict.update({res_1[1] + '_' + res_2[1]: d})
                    except CmdException:
                        print "Can't calculate distance between ", dstr, " ... :("

        orderedDistDict = OrderedDict(
            sorted(distDict.items(), key=lambda x: x[1]))
        return orderedDistDict
Exemplo n.º 18
0
def check_disulphide(pdb, resnum_i, resnum_j, f):

	selection_i = "resi " + str(resnum_i)
	selection_j = "resi " + str(resnum_j)

	# cmd.wizard("mutagenesis")

	# cmd.get_wizard().set_mode("CYS")

	cmd.do("refresh_wizard")
	# Select the rotamer
	for frame_i in [1, 2, 3]:
		# cmd.do("refresh_wizard")

		cmd.get_wizard().do_select(selection_i)
		cmd.frame(frame_i)
		cmd.create("rotamer_i_" + str(frame_i), "mutation", frame_i, 1)
		rotamer_i_pymol_prefix = "/" + "rotamer_i_" + str(frame_i) + "///" + resnum_i + "/"


	for frame_j in [1, 2, 3]:

		# cmd.do("refresh_wizard")

		cmd.get_wizard().do_select(selection_j)
		cmd.frame(frame_j)
		cmd.create("rotamer_j_" + str(frame_j), "mutation", frame_j, 1)
		rotamer_j_pymol_prefix = "/" + "rotamer_j_" + str(frame_j) + "///" + resnum_j + "/"

		# s_gamma_distance = cmd.get_distance(rotamer_i_pymol_prefix + "SG", rotamer_j_pymol_prefix + "SG")
		# print s_gamma_distance

	cmd.set_wizard("clear")

	for frame_i in [1, 2, 3]:
		rotamer_i_pymol_prefix = "/" + "rotamer_i_" + str(frame_i) + "///" + resnum_i + "/"
		for frame_j in [1, 2, 3]:
			rotamer_j_pymol_prefix = "/" + "rotamer_j_" + str(frame_j) + "///" + resnum_j + "/"

			s_gamma_distance = cmd.get_distance(rotamer_i_pymol_prefix + "SG", rotamer_j_pymol_prefix + "SG")

			print s_gamma_distance
Exemplo n.º 19
0
def get_bond_lenghts(atom_name, pdb_file):
    try:
        cmd.load(pdb_file)
        n_states = cmd.count_states('all')
        n_residues = cmd.count_atoms('name CA')
        distance = np.zeros((n_states, n_residues))

        for s in range(1, n_states + 1):
            conf = []
            for i in range(1, n_residues + 1):
                try:
                    dst = cmd.get_distance('resi {} and name CA'.format(i),
                                           'resi {} and name {}'.format(
                                               i, atom_name),
                                           state=s)
                    conf.append(dst)
                except:
                    conf.append(np.nan)
            distance[s - 1] = conf
        return distance
    except:
        print('Cannot open file {}. Please try a diferent PDB file.'.format(
            pdb_file))
Exemplo n.º 20
0
def find_hbonds(selection_donor_and_hydrogen,
                selection_acceptor=None,
                dmin: float = 1.,
                dmax: float = 2.5,
                anglemin: float = 135):
    dmin = float(dmin)
    dmax = float(dmax)
    anglemin = float(anglemin)
    selection_hydrogen = '({}) and (e. H)'.format(selection_donor_and_hydrogen)
    found_bonds = []
    if selection_acceptor is None:
        selection_acceptor = selection_donor_and_hydrogen
    for acceptor in iterate_indices(
            '({}) and (e. N+O)'.format(selection_acceptor)):
        print('Trying acceptor idx {}'.format(acceptor))
        for hydrogen in iterate_indices(
                '({}) and (e. H) and not (neighbor (idx {} and ({})))'.format(
                    selection_hydrogen, acceptor, selection_acceptor)):
            donors = list(
                iterate_indices(
                    'neighbor ((idx {}) and ({})) and not ((idx {}) and ({}))'.
                    format(hydrogen, selection_hydrogen, acceptor,
                           selection_acceptor)))
            donor = donors[0]
            dist = cmd.get_distance(
                '(idx {}) and ({})'.format(hydrogen, selection_hydrogen),
                '(idx {}) and ({})'.format(acceptor, selection_acceptor))
            angle = cmd.get_angle(
                '(idx {}) and ({})'.format(donor,
                                           selection_donor_and_hydrogen),
                '(idx {}) and ({})'.format(hydrogen, selection_hydrogen),
                '(idx {}) and ({})'.format(acceptor, selection_acceptor))
            if dist >= dmin and dist <= dmax and angle >= anglemin:
                found_bonds.append((donor, hydrogen, acceptor, dist, angle))

    for donor, hydrogen, acceptor, dist, angle in found_bonds:
        yield (acceptor, hydrogen, dist)
Exemplo n.º 21
0
def get_euclidian_distances_bw_terminals():
  # get N_terms and C_terms (only CA atoms)
  cmd.select("A_N_term", "first chain A & name ca")
  cmd.select("A_C_term", "last chain A & name ca")
  cmd.select("B_N_term", "first chain B & name ca")
  cmd.select("B_C_term", "last chain B & name ca")

  # euclidian distance between terminals
  d_A_N_term_to_B_N_term = cmd.get_distance("A_N_term", "B_N_term")
  d_A_N_term_to_B_C_term = cmd.get_distance("A_N_term", "B_C_term")
  d_A_N_term_to_A_C_term = cmd.get_distance("A_N_term", "A_C_term")
  d_A_C_term_to_B_N_term = cmd.get_distance("A_C_term", "B_N_term")
  d_A_C_term_to_B_C_term = cmd.get_distance("A_C_term", "B_C_term")
  d_B_N_term_to_B_C_term = cmd.get_distance("B_N_term", "B_C_term")
  #return d_A_N_term_to_B_N_term, d_A_N_term_to_B_C_term, d_A_N_term_to_A_C_term, d_A_C_term_to_B_N_term, d_A_C_term_to_B_C_term, d_B_N_term_to_B_C_term
  to_return = {'d_A_N_term_to_B_N_term' : d_A_N_term_to_B_N_term,
               'd_A_N_term_to_B_C_term' : d_A_N_term_to_B_C_term,
               'd_A_N_term_to_A_C_term' : d_A_N_term_to_A_C_term,
               'd_A_C_term_to_B_N_term' : d_A_C_term_to_B_N_term,
               'd_A_C_term_to_B_C_term' : d_A_C_term_to_B_C_term,
               'd_B_N_term_to_B_C_term' : d_B_N_term_to_B_C_term}
  return to_return
Exemplo n.º 22
0
write_cst = open('cstfile.txt', 'w')

for i in [x for x in range(1, 248) if x not in missing_positions]:
    #determining number of missing positions for with respect to position i
    minus_i = 0
    for miss_i in range(len(missing_positions)):
        if missing_positions[miss_i] < i:
            minus_i += 1

    for j in [x for x in range(i + 1, 249) if x not in missing_positions]:
        #determining number of missing positions for with respect to position j
        minus_j = 0
        for miss_j in range(len(missing_positions)):
            if missing_positions[miss_j] < j:
                minus_j += 1

        distance = cmd.get_distance(name + ' and name CA and resi ' + str(i),
                                    name + ' and name CA and resi ' + str(j))

        if distance < cutoff:
            element = [i - minus_i, j - minus_j, distance]
            atom_list.append(element)

for element in atom_list:
    write_cst.write('AtomPair CA ' + str(element[0]) + ' CA ' +
                    str(element[1]) + ' HARMONIC ' + str(element[2]) +
                    ' 2.0\n')

write_cst.close()
Exemplo n.º 23
0
for filename in filenames:
    with open(filename, 'r') as f:
        lines = f.readlines()
        lines = list(filter(filter_func, lines))
        dis_pairs.extend(list(map(map_func, lines)))
        restraints.extend(list(map(map_func2, lines)))

out_lines = []
for dis_pair, restraint in zip(dis_pairs, restraints):
    group1 = "(id %d)" % dis_pair[0]
    group2 = "(id %d)" % dis_pair[1]
    cmd.distance("%d-%d" % (dis_pair[0], dis_pair[1]), group1, group2)
    resns = []
    resis = []
    atoms = []
    cmd.iterate("id %d+%d" % dis_pair, "resns.append(resn)")
    cmd.iterate("id %d+%d" % dis_pair, "resis.append(resi)")
    cmd.iterate("id %d+%d" % dis_pair, "atoms.append(name)")
    distance = cmd.get_distance(atom1=group1, atom2=group2)
    out_lines.append("[ %s%s(%s)-%s%s(%s) ~ %.2fA (%s, %s, %s)]\n" %
                     ((resns[0], resis[0], atoms[0], resns[1], resis[1],
                       atoms[1], distance) + restraint))
    out_lines.append("%d %d\n" % dis_pair)

# write dis_pairs to distance_pairs.ndx for analysis
with open("dist_out.ndx", 'w') as f:
    for line in out_lines:
        f.write(line)
        print(line)
Exemplo n.º 24
0
def set_dihedral_angles_update(pymol_object, chainID, Aa_list,
                               phi_psi_list, protect_selection,
                               moving_atom, target_atom, start_num=1):
    """Set several dihedral angles to a set of amino acids.

    Function that will change the dihedral angles for each amino acid in
    Aa_list for the ones in the phi_psi_list. Amino acids selected in
    protect_selection will not move. After changing the angles the new
    structure is saved.
    This method is an updated version of "set_dihedral_angles". Instead of
    changing the angles of the structures and then setting them back to
    the original values, this method creates a copy of the pymol object
    and then changes its angles. Thus, this does not modify the initial
    structure. 
    This method also returns a list with information regarding the amino acid
    modified, the angle used, the distance between moving atom and target atom
    and the pdb file created. This is useful to create a log of the
    modifications made.

    Parameters
    ----------
    pymol_object : String
        Name of Pymol object in the session.
    chainID : String
        ChainID of residue.
    Aa_list : List
        List of amino acid numbers (int).
    phi_psi_list : List
        List of tuples containing phi and psi angles.
    protect_selection : String
        Slection string from pymol_object which will remain static.
        Example: '//X/44-316/*'
    moving_atom : String
        Atom selection for atom 1 used for distance mesurement, ussualy from
        chain being modified.
    target_atom : String
        Atom selection for atom 2 used for distance mesurement.
    start_num : Int, optional
        Number used to start the pdb files counter. The default is 1.

    Returns
    -------
    pdb_files : List
        List of tuples containing information about the output pdb file,
        distance between target-moving atoms, aminoacid modified and new phi
        and psi angles: (pdb_name,distance, aa_number, (new_phi, new_psi)).

    """
    # track of PDB file numbers
    pdb_num = start_num

    # pdb_file_list = [] #PDB file name list as output

    pdb_files = []

    for aa_number in Aa_list:

        for dihedral_angles in phi_psi_list:

            # Create a copy of object to be modified
            cmd.copy('obj_copy', pymol_object)

            # Protect residues
            cmd.protect('obj_copy'+protect_selection)

            new_phi, new_psi = dihedral_angles

            set_phi_psi_angles('obj_copy', chainID, aa_number,
                               phi=new_phi, psi=new_psi)

            # get distance
            distance = cmd.get_distance('obj_copy' + moving_atom, target_atom)

            # save new structure with pdb_num as name

            pdb_name = '{}_{}.pdb'.format(pymol_object, pdb_num)

            cmd.save(pdb_name, 'obj_copy')

            pdb_files.append((pdb_name, distance, aa_number, (new_phi, new_psi)))

            pdb_num += 1

            # Remove the object copy
            cmd.delete('obj_copy')

    print('Finished!')

    return pdb_files
Exemplo n.º 25
0
def DrawDRSASA_ByAtom(fname, mode='0'):
    mode = int(mode)
    cols, rows, matrix, direc, sumv = ReadDRSASAIntTable(fname)
    mtrx = np.array(matrix).flatten()
    mtrx = mtrx[mtrx != 0]
    mvalue = np.max(mtrx)
    minvalue = np.min(mtrx)
    mv075 = mvalue * 0.75
    median = np.median(mtrx)
    avg = np.average(mtrx)
    cutoff = mvalue * 0.05
    cmd.color("grey", "all")
    print median, avg, cutoff, minvalue
    Rl = []
    Gl = []
    Bl = []
    cmd.set('suspend_updates', 'on')
    view = cmd.get_view()
    for row in range(len(matrix)):
        for col in range(len(matrix[row])):
            v = float(matrix[row][col])
            if v < cutoff:
                continue
            R = 1.8 * v / mvalue
            nR = v / mvalue
            colorn = "drsasa_" + str(row) + "_" + str(col)
            cmd.set_color(colorn, (int(255 * nR), 0, 255 - int(255 * nR)))
            rid = [str(item) for item in rows[row]]
            cid = [str(item) for item in cols[col]]
            print(rid, cid)
            sele1 = GenSeleAtom(rid[0], rid[1], rid[2], rid[3])
            sele2 = GenSeleAtom(cid[0], cid[1], cid[2], cid[3])
            print(sele1, sele2)
            cmd.select("atom1", sele1)
            cmd.select("atom2", sele2)
            d = cmd.get_distance("atom1", "atom2")
            if direc == "row":
                atom_s = sele2
            elif direc == "col":
                atom_s = sele1
            #name = "/".join(rid)+"_"+"/".join(cid)
            name = "a_" + str(row) + "_" + str(col)

            if mode == 0:
                if (v >= mv075):
                    color = colorn + " " + colorn
                    Rl.append(atom_s)
                    cmd.color("red", atom_s)
                elif (v > median):
                    color = "green green"
                    Gl.append(atom_s)
                    if not atom_s in Rl:
                        cmd.color("green", atom_s)
                else:
                    color = "blue blue"
                    if (not atom_s in Rl) and (not atom_s in Gl):
                        cmd.color("blue", atom_s)
            elif mode == 1:
                color = colorn + " " + colorn
            if direc == "row":
                if mode == 0:
                    cgo_arrow("atom2", "atom1", 0.1, d * 0.25, d * 0.1, R,
                              color, name)
                elif mode == 1:
                    cgo_arrow("atom2", "atom1", 0.1, d * 0.25, d * 0.1, 0.2,
                              color, name)
            elif direc == "col":
                if mode == 0:
                    cgo_arrow("atom1", "atom2", 0.1, d * 0.25, d * 0.1, R,
                              color, name)
                elif mode == 1:
                    cgo_arrow("atom1", "atom2", 0.1, d * 0.25, d * 0.1, 0.2,
                              color, name)
    cmd.set_view(view)
    cmd.set('suspend_updates', 'off')
Exemplo n.º 26
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)
Exemplo n.º 27
0
def distance(a, idA, b, idB):
    atomA = "%s and id %s" % (a, idA)
    atomB = "%s and id %s" % (b, idB)
    #print atomA
    #print atomB
    return cmd.get_distance(atomA, atomB)
Exemplo n.º 28
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)
Exemplo n.º 29
0
def save_shell_figures(mol_pdb_file,
                       shell_pdb_files,
                       graph,
                       atom_colors,
                       dpi=3000,
                       overwrite=False,
                       out_dir=""):
    """Save all mol/shell/substructure figures."""
    cmd.reinitialize()
    sleep(0.5)

    mol_color_hetero_img = os.path.join(out_dir, "mol_plain.png")
    mol_color_types_img = os.path.join(out_dir, "mol_atom_types.png")
    pymol_load_with_defaults(mol_pdb_file)
    cmd.zoom('all', complete=1, buffer=1)
    if overwrite or not os.path.isfile(mol_color_hetero_img):
        cmd.util.cbaw()
        pymol_color_atoms_by_elem()
        cmd.ray(dpi)
        cmd.png(mol_color_hetero_img)
        partial_opaque_to_opaque(mol_color_hetero_img)
        sleep(0.5)

    if overwrite or not os.path.isfile(mol_color_types_img):
        pymol_color_by_atom_types(atom_colors)
        cmd.ray(dpi)
        cmd.png(mol_color_types_img)
        partial_opaque_to_opaque(mol_color_types_img)
        sleep(0.5)

    stored.names_ids = []
    cmd.iterate("all", "stored.names_ids.append((ID, name))")
    ids_names_map = dict(stored.names_ids)
    atom_colors = {
        ids_names_map[atom_id + 1]: color
        for atom_id, color in atom_colors.items()
    }

    vector_shell_pdb_file = None
    vector_shell = None
    radii = set()
    for pdb_file in shell_pdb_files:
        identifier = int(os.path.basename(pdb_file).split('.')[0])
        shell_image_file = os.path.join(out_dir,
                                        "{}_shell.png".format(identifier))
        graph.node[identifier]["image"] = shell_image_file
        if not overwrite and os.path.isfile(shell_image_file):
            continue
        cmd.reinitialize()
        pymol_load_with_defaults(pdb_file)
        shell = list(graph.node[identifier]["shell"])[0]
        radius = shell.radius
        if radius > 0:
            radii.add(radius)
            draw_shell_sphere(radius, linespacing=radius * .15 / 1.5)
            cmd.center('sphere_*')
            cmd.origin('sphere_*')
            if vector_shell is None and round(
                    radius / RADIUS_MULTIPLIER) == 1.:
                vector_shell_pdb_file = pdb_file
                vector_shell = shell

        pymol_color_by_atom_types(atom_colors, mode="name")
        cmd.turn('y', 90)
        cmd.turn('x', 35)
        cmd.zoom('all', complete=1)
        cmd.ray(dpi)
        cmd.png(shell_image_file)
        partial_opaque_to_opaque(shell_image_file)
        sleep(0.5)

    vector_figure = os.path.join(out_dir, "vector_axes.png")
    if overwrite or not os.path.isfile(vector_figure):
        cmd.reinitialize()
        pymol_load_with_defaults(vector_shell_pdb_file)
        radius = vector_shell.radius
        draw_shell_sphere(radius, linespacing=radius * .15 / 1.5)
        center_atom = vector_shell.center_atom
        for atom in vector_shell.atoms:
            dist = cmd.get_distance(
                "{} and id {}".format(vector_shell.identifier, center_atom),
                "{} and id {}".format(vector_shell.identifier, atom),
                state=1)
            if dist <= radius:
                coords = cmd.get_coords("{} and id {}".format(
                    vector_shell.identifier, atom),
                                        state=1)[0]
                draw_sphere_marker(radius, coords)
        cmd.center('sphere_*')
        cmd.origin('sphere_*')

        pymol_color_by_atom_types(atom_colors, mode="name")
        cmd.turn('y', 90)
        cmd.turn('x', 35)
        cmd.delete(str(vector_shell.identifier))
        cmd.zoom('all', complete=1)
        cmd.ray(dpi)
        cmd.png(vector_figure)
        partial_opaque_to_opaque(vector_figure)
        sleep(0.5)

    axes_figure = os.path.join(out_dir, "axes.png")
    if overwrite or not os.path.isfile(axes_figure):
        cmd.reinitialize()
        pymol_load_with_defaults()
        draw_shell_sphere(min(radii), linespacing=min(radii) * .15 / 1.5)
        sleep(.1)
        draw_xy_axes(scale=min(radii))
        sleep(.1)
        cmd.turn('y', 90)
        cmd.turn('x', 35)
        cmd.zoom('all', complete=1)
        cmd.ray(dpi)
        cmd.png(axes_figure)
        partial_opaque_to_opaque(axes_figure)
        sleep(0.5)
Exemplo n.º 30
0
from pymol import cmd
import json
from tqdm import tqdm

distances = {}

for i in tqdm(range(23, 1017)):
    for j in range(i + 1, 1017):
        distances["{} {}".format(i, j)] = cmd.get_distance(
            atom1="{}/CA".format(i), atom2="{}/CA".format(j), state=-1)

with open("distances.json", "w") as fh:
    json.dump(distances, fh, indent=4)

with open("distances.json", "r") as fh:
    dist = json.load(fh)
Exemplo n.º 31
0
    ff = ob.OBForceField.FindForceField(forcefield)
    ff.Setup(mol)
    if cutoff == True:
        ff.EnableCutOff(True)
        ff.SetVDWCutOff(cut_vdw)
        ff.SetElectrostaticCutOff(cut_elec)
    if method == 'cg':
        ff.ConjugateGradients(nsteps, conv)
    else:
        ff.SteepestDescent(nsteps, conv)
    ff.GetCoordinates(mol)
    nrg = ff.Energy()
    pdb_string = obconversion.WriteString(mol)
    cmd.delete(name)
    if name == 'all':
        name = 'all_'
    cmd.read_pdbstr(pdb_string, name)
    return nrg


pbl = []
for res_name_i in aa:
    for res_name_j in aa:
        cmd.fab(res_name_i + res_name_j)
        minimize(selection=sel, forcefield='GAFF')
        a = cmd.get_distance('resi 1 and name C', 'resi 2 and name N')
        pbl.append(a)
        cmd.delete('all')
mean = sum(pbl) / len(pbl)
print(mean)
Exemplo n.º 32
0
    def run(self):
        my_view = cmd.get_view()
        #mark Search
        if self.mode == 'Search':
            #show message
            cmd.wizard("message", "Searching conformers...")
            cmd.refresh()
            if self.currentLabel.uid != "Rx":
                self.search()
                print "Creating Rotamers in PyMOL...",
                for aRotamer in self.currentLabel.ensembles["mW"].rotamers:
                    self.createRotamerInPymol(aRotamer, "mW")
# 				if self.thoroughness == "painstaking" and self.currentLabel.uid == "R1":
# 					scoringWeights = {"totalContactWeight": 0.0, "typeOfContactWeight": 1.0}
# 					for aRotamer in self.currentLabel.ensembles["mW"].rotamers:
# 						aRotamer.score(scoringWeights)
# 					self.currentLabel.ensembles["mW"].sortRotamers("chi2")
# 					numberOfRotamers = len(self.currentLabel.ensembles["mW"].rotamers)
# 					newEnsemble = ensemble.Ensemble()
# 					newEnsemble.name = "contactFit"
# 					newEnsemble.rotamers = self.currentLabel.ensembles["mW"].rotamers[0:20]
# 					self.currentLabel.ensembles["contactFit"] = newEnsemble
# 					for aRotamer in self.currentLabel.ensembles["contactFit"].rotamers:
# 						self.createRotamerInPymol(aRotamer, "contactFit")
                print "done!"

            elif self.currentLabel.uid == "Rx":
                ca1 = numpy.array(
                    cmd.get_model(self.residue1Name + " & name CA",
                                  1).get_coord_list()[0])
                ca2 = numpy.array(
                    cmd.get_model(self.residue2Name + " & name CA",
                                  1).get_coord_list()[0])
                try:
                    cb1 = numpy.array(
                        cmd.get_model(self.residue1Name + " & name CB",
                                      1).get_coord_list()[0])
                except:
                    cb1 = ca1
                try:
                    cb2 = numpy.array(
                        cmd.get_model(self.residue2Name + " & name CB",
                                      1).get_coord_list()[0])
                except:
                    cb2 = ca2

                environmentatoms = numpy.array(cmd.get_model("(%s within 10 of %s or %s) and not (%s or %s)" \
                     %(self.pickedObject1, \
                      self.residue1Name, \
                      self.residue2Name, \
                      self.residue1Name, \
                      self.residue2Name), 1).get_coord_list())
                anchor1rotamers = self.currentLabel.calculateCone(
                    ca1, cb1, environmentatoms, numberOfAtoms=8000)
                anchor2rotamers = self.currentLabel.calculateCone(
                    ca2, cb2, environmentatoms, numberOfAtoms=8000)
                solutions1 = []
                solutions2 = []
                for anchor1rotamer in anchor1rotamers:
                    anAtom = anchor1rotamer.atoms["N1"]
                    solutions1.append(anAtom.coordinate)
                for anchor2rotamer in anchor2rotamers:
                    anAtom = anchor2rotamer.atoms["N1"]
                    solutions2.append(anAtom.coordinate)

                #determine common accessible volume
                distances1 = self.currentLabel.quick_map(solutions1, cb2)
                distances2 = self.currentLabel.quick_map(solutions2, cb1)
                indices1 = numpy.where(numpy.any(distances1 > 6, axis=1))
                indices2 = numpy.where(numpy.any(distances2 > 6, axis=1))
                solutions1 = numpy.delete(solutions1, indices1, 0)
                solutions2 = numpy.delete(solutions2, indices2, 0)
                solutions = numpy.concatenate((solutions1, solutions2))

                #create resulting ensemble
                newEnsemble = ensemble.Ensemble()
                newEnsemble.name = "mW"
                id = 0
                newRotamers = []
                if len(solutions) > 0:
                    for solution in solutions:
                        newRotamer = rotamer.Rotamer()
                        thisAtom = atom.Atom()
                        thisAtom.coordinate = solution
                        thisAtom.name = "N1"
                        thisAtom.element = "N"
                        newRotamer.id = id
                        newRotamer.atoms["N1"] = thisAtom
                        id += 1
                        newRotamers.append(newRotamer)
                else:
                    print "Did not find any possible N1 locations. Are the two anchorpoints too far apart?"
                newEnsemble.rotamers = newRotamers
                self.currentLabel.ensembles[newEnsemble.name] = newEnsemble
                cmd.load(
                    "%s/labels/%s" % (self.path, self.currentLabel.pdbFile),
                    "currentLabel")
                for aRotamer in self.currentLabel.ensembles["mW"].rotamers:
                    self.createRotamerInPymol(aRotamer, "mW")
            self.numberOfLabel += 1
            self.finalCosmetics()
            #dismiss message
            cmd.wizard()

        #mark Measure
        elif self.mode == "Measure":
            cmd.wizard("message", "Calculating distances...")
            cmd.refresh()
            print "\n\n\nDistance calculation:\n"
            print "The dashed lines are the c-beta distance (green),\nand the distance between the geometric averages\nof the two ensembles (yellow).\n"
            print "The following statistics refer to the distribution\nof the individual distances between all conformers (may take a while):\n"

            #find out what the selections are
            stored.label1 = []
            stored.label2 = []
            stored.label1Coordinates = []
            stored.label2Coordinates = []
            stored.atomNames1 = []
            stored.atomNames2 = []

            #extract label info
            cmd.iterate(self.residue1Name, 'stored.label1.append(segi)')
            cmd.iterate(self.residue2Name, 'stored.label2.append(segi)')
            cmd.iterate(self.residue1Name, 'stored.atomNames1.append(name)')
            cmd.iterate(self.residue2Name, 'stored.atomNames2.append(name)')
            try:
                label1 = label.Label.fromfile("labels/%s.txt" %
                                              stored.label1[0])
                cmd.iterate_state(
                    0,
                    "%s & name %s" % (self.residue1Name, label1.spinLocation),
                    'stored.label1Coordinates.append((x,y,z))')
            except:
                cmd.iterate_state(0, "%s" % (self.residue1Name),
                                  'stored.label1Coordinates.append((x,y,z))')
            try:
                label2 = label.Label.fromfile("labels/%s.txt" %
                                              stored.label2[0])
                cmd.iterate_state(
                    0,
                    "%s & name %s" % (self.residue2Name, label2.spinLocation),
                    'stored.label2Coordinates.append((x,y,z))')
            except:
                cmd.iterate_state(0, "%s" % (self.residue2Name),
                                  'stored.label2Coordinates.append((x,y,z))')
            #calculate distances
            distances = distanceDistribution.DistanceDistribution()
            dist = distances.calculateDistanceDistribution(
                stored.label1Coordinates, stored.label2Coordinates)

            #create pseudoatom at average coordinate of each ensemble and display the distance between them
            atoms1 = numpy.array(stored.label1Coordinates)
            atoms2 = numpy.array(stored.label2Coordinates)
            avgAtoms1 = numpy.average(atoms1, axis=0)
            avgAtoms2 = numpy.average(atoms2, axis=0)
            self.createPseudoatom(avgAtoms1, "tmp_average1", 1)
            self.createPseudoatom(avgAtoms2, "tmp_average2", 1)
            cmd.distance(self.object_prefix + "avg", "tmp_average1 & name PS1",
                         "tmp_average2 & name PS1")
            cmd.delete("tmp_average1")
            cmd.delete("tmp_average2")

            #cbeta distance if cbeta is present in both selections
            #cBetaDistance = 0.0
            if any("CB" in atom for atom in stored.atomNames1) and any(
                    "CB" in atom for atom in stored.atomNames2):
                cmd.distance(self.object_prefix + "cBeta",
                             self.residue1Name + " & name CB",
                             self.residue2Name + " & name CB")
                #for some reason, cmd.distance does not return the correct distance. Although it is shown in the viewer...
                #get_distance gives the correct distance, but does not create the object in the viewer.
                cBetaDistance = cmd.get_distance(
                    self.residue1Name + " & name CB",
                    self.residue2Name + " & name CB")
                cmd.set("dash_color", "green", self.object_prefix + "cBeta")

            histogram = numpy.histogram(dist, numpy.arange(100))
            envelopePlot = numpy.zeros((100, 2))
            envelopePlot[0:99] = numpy.column_stack(
                (histogram[1][0:len(histogram[1]) - 1], histogram[0]))

            #put point in mid of bin
            envelopePlot[:, 0] += 0.5
            normEnvelopePlot = numpy.copy(envelopePlot)
            normEnvelopePlot[:, 1] = normEnvelopePlot[:, 1] / numpy.amax(
                histogram[0])

            #combine dist and histogram to single array before output
            output = numpy.column_stack((envelopePlot, normEnvelopePlot[:, 1]))
            averageDistance = numpy.average(dist)

            #make graph dictionary for mtsslPlotter
            graphtitle = "%s-%s" % (self.residue1Name, self.residue2Name)
            xlim = [0, 100]
            ylim = [0, 1]
            plotDictionary = self.makeGraphDataDictionary(
                graphtitle, "DistanceDistribution", "Distance (Angstrom)",
                "Relative Probability", output[:, 0], output[:,
                                                             2], 0, xlim, ylim)
            stored.plots.append(plotDictionary)
            print "Distribution plot added to memory. Inspect it with mtsslPlotter."

            #Copy to clipboard
            header = "Dist.   Count   Norm.Count\n"
            outputStr = header + numpy.array_str(output)
            outputStr = outputStr.replace("[", "")
            outputStr = outputStr.replace("]", "")
            self.copyStringToClipboard(outputStr)

            #Write to file
            if self.writeToFile:
                try:
                    filename = "%s-%s" % (self.residue1Name, self.residue2Name)
                    numpy.savetxt(filename + ".txt", output, delimiter='\t')
                    print "Written to file:"
                    print "%s/%s" % (os.getcwd(), filename)
                except:
                    print "Writing to file failed!"
            print self.calculateStatistics2(dist)
            try:
                if cBetaDistance > 0.0:
                    print "Cbeta distance: %3.1f" % cBetaDistance
            except:
                print "No Cbeta distance."
            cmd.wizard()

        #mark Distance Map
        elif self.mode == "Distance Map":
            #show message
            cmd.wizard("message",
                       "Calculating distance maps. Please be patient...")
            cmd.refresh()
            dm = distanceMap.DistanceMap(self.writeToFile, self.currentLabel,
                                         self.homoOligomerMode)
            if self.pickedObject1 == self.pickedObject2:
                dm.intraDistanceMap(self.pickedObject1)
            else:
                dm.interDistanceMap(self.pickedObject1, self.pickedObject2)
            print "Done!"
            cmd.wizard()

        self.cleanupAfterRun()
        cmd.set_view(my_view)
Exemplo n.º 33
0
def builderCorona(theta, fi, detergent, protein, detR):
    # Build symmates with desired rotations
    refresh()
    cmd.pseudoatom("origin0"+protein, pos=[0, 0, 0])
    thetaSteps = len(theta)
    angleVer = np.linspace(-90, 90, thetaSteps)
    i = 0
    roffi = []
    # find surface grid todo: choose better one of these two approaches
    # for f in fi:
    # find distances to surface
    # cmd.rotate("z", (str)(-f), protein)
    # xLine = "{} and z > {} and z < {}  and y > {} and y < {} and x > 0".format(protein, -detR, detR, -5, 5)
    # atoms = cmd.index(xLine)
    # dlist = []
    # if len(atoms) == 0:
    #     print("No atoms at azimuthal angle: Phi = {}.".format(f))
    #     continue
    #     # find R in only one cross-section
    # for at1 in cmd.index("origin0"):
    #     for at2 in atoms[::10]:
    #         dist = cmd.get_distance(atom1=at1, atom2=at2, state=0)
    #         dlist.append(dist)
    # r = max(dlist) # * np.cos(np.deg2rad(t))
    # roffi.append(r)
    # cmd.rotate("z", (str)(f), protein)
    r = 0
    cmd.rotate("z", -90, detergent)
    for t, a in zip(theta, angleVer):
        for n, f in enumerate(fi):
            ###################EXPERIMENTAL###################
            cmd.rotate("z", str(-f), protein)
            cmd.translate("[0,0,{}]".format(r * np.sin(np.deg2rad(t))), protein)
            xLine = "{} and z > {} and z < {}  and y > {} and y < {} and x > 0 and name CA".format(protein, -detR, detR,
                                                                                                   -1, 1)
            atoms = cmd.index(xLine)
            dlist = []
            if len(atoms) == 0:
                print("No atoms at azimuthal angle: Phi = {}.".format(f))
                continue
                # find R in only one cross-section
            for at1 in cmd.index("origin0"):
                for at2 in atoms:
                    dist = cmd.get_distance(atom1=at1, atom2=at2, state=0)
                    dlist.append(dist)
            r = max(dlist)  # * np.cos(np.deg2rad(t))
            roffi.append(r)
            cmd.rotate("z", str(f), protein)
            cmd.translate("[0,0,{}]".format(-r * np.sin(np.deg2rad(t))), protein)
            ####################################################
            # r = roffi[n] / np.cos(np.deg2rad(t))
            i += 1
            cmd.copy("seg{}".format(i), detergent)
            cmd.alter("seg{}".format(i), "resi={}".format(i))  # assign residue numbers
            # corona
            cmd.rotate("y", str(-a), "seg{}".format(i))
            cmd.translate("[{},0,0]".format(r + 0.6 * detR * np.cos(np.deg2rad(a))), "seg{}".format(i))
            cmd.translate("[0,0,{}]".format((r + detR) * np.sin(np.deg2rad(t))), "seg{}".format(i))
            cmd.rotate("z", str(f), "seg{}".format(i))
            # print(f"seg{i} phi = {f} theta = {t} Distance: {r}") #DEBUG

    cmd.create("corona", "seg*")
    cmd.delete("seg*")
    cmd.delete("origin0"+protein)