def vis(res,
        path_prefix,
        c=["firebrick", "forest", 'purple', 'salmon', "gold", "red"]):

    for ind, r in enumerate(res):
        for a in r.atoms:
            cmd.show("spheres", "id " + str(a.id))
            cmd.set("sphere_color", c[ind], "id " + str(a.id))
        cmd.distance("d" + str(ind), "id " + str(r.atoms[0].id),
                     "id " + str(r.atoms[1].id))
        cmd.hide("labels")
        cmd.set("grid_slot", -2, "d" + str(ind))

    cmd.ray(1200)
    time.sleep(2)
    cmd.set("grid_mode", 0)
    cmd.png(path_prefix + "_restraints.png")
    #cmd.set("grid_mode", 1)
    cmd.move("zoom", -10)

    cmd.ray(1200, )
    time.sleep(4)
    cmd.png(path_prefix + "_grid_restraints.png")
    cmd.set("grid_mode", 0)
    cmd.hide("spheres")
    cmd.delete("d*")
Exemple #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)
Exemple #3
0
 def show_cationpi(self):
     """Visualize cation-pi interactions."""
     for i, p in enumerate(self.plcomplex.pication):
         cmd.pseudoatom('ps-picat-1-%i' % i, pos=p.ring_center)
         cmd.pseudoatom('ps-picat-2-%i' % i, pos=p.charge_center)
         if p.protcharged:
             cmd.pseudoatom('Chargecenter-P', pos=p.charge_center)
             cmd.pseudoatom('Centroids-L', pos=p.ring_center)
             pilig_ids = '+'.join(map(str, p.ring_atoms))
             cmd.select(
                 'PiCatRing-L',
                 'PiCatRing-L or (id %s & %s)' % (pilig_ids, self.ligname))
             for a in p.charge_atoms:
                 cmd.select(
                     'PosCharge-P',
                     'PosCharge-P or (id %i & %s)' % (a, self.protname))
         else:
             cmd.pseudoatom('Chargecenter-L', pos=p.charge_center)
             cmd.pseudoatom('Centroids-P', pos=p.ring_center)
             pires_ids = '+'.join(map(str, p.ring_atoms))
             cmd.select(
                 'PiCatRing-P',
                 'PiCatRing-P or (id %s & %s)' % (pires_ids, self.protname))
             for a in p.charge_atoms:
                 cmd.select(
                     'PosCharge-L',
                     'PosCharge-L or (id %i & %s)' % (a, self.ligname))
         cmd.distance('PiCation', 'ps-picat-1-%i' % i, 'ps-picat-2-%i' % i)
     if self.object_exists('PiCation'):
         cmd.set('dash_color', 'orange', 'PiCation')
         cmd.set('dash_gap', 0.3, 'PiCation')
         cmd.set('dash_length', 0.6, 'PiCation')
def get_dehydrons():
    cmd.delete('dehydrons')
    cmd.delete('DH_pairs')
    cmd.hide()
    angle = float(angle_value.get())
    cutoff = float(dist_cutoff_value.get())
    desolv = float(desolv_sphere.get())
    min_wrappers = float(min_value.get())
    selection = 'name n or name o and not resn hoh'
    hb = cmd.find_pairs("((byres "+selection+") and n. n)","((byres "+selection+") and n. o)",mode=1,cutoff=cutoff,angle=angle)
# sort the list for easier reading
    hb.sort(lambda x,y:(cmp(x[0][1],y[0][1])))
    print "------------------------------------------------\n----------------dehydron Results-----------------\n------------------------------------------------\n    Donor      |    Aceptor    |  \nChain Residue  | Chain Residue | # dehydrons"
    sel = []
    wra = 0
    for pairs in hb:
        cmd.iterate("%s and index %s" % (pairs[0][0], pairs[0][1]), 'stored.nitro = chain, resi, resn') # extracts the nitrogen
        cmd.iterate("%s and index %s" % (pairs[1][0], pairs[1][1]), 'stored.oxy = chain, resi, resn') # extracts the oxygen
        wrappers = cmd.select('wrap', '(((chain %s and name ca and resi %s) around %f) or ((chain %s and name ca and resi %s) around %f)) and (not ((neighbor name n*+o*) or (name n*+o*+h*)))' % (stored.nitro[0], stored.nitro[1], desolv, stored.oxy[0], stored.oxy[1], desolv)) #Identifies the putative dehydrons
        if wrappers < min_wrappers:
            wra = 1
            cmd.distance('Dehydrons',"%s and index %s" % (pairs[0][0],pairs[0][1]),"%s and index %s" % (pairs[1][0],pairs[1][1]))
            print ' %s%7s%5d | %s%7s%5d |%7s' % (stored.nitro[0], stored.nitro[2], int(stored.nitro[1]), stored.oxy[0], stored.oxy[2], int(stored.oxy[1]), wrappers)
            if stored.nitro[1] not in sel:
                sel.append(stored.nitro[1])
            if stored.oxy[1] not in sel:
                sel.append(stored.oxy[1])
    if wra == 1:
        cmd.select('DH_pairs', 'resi %s' % ('+').join(sel))
        cmd.show('lines', 'DH_pairs')
    cmd.disable('DH_pairs')
    cmd.hide('labels')
    cmd.delete('wrap')
    cmd.show('cartoon')
    cmd.show('dashes')
Exemple #5
0
def show_contacts(self, point='rc', split_contacts=False, add_name='_cmap'):
    """Shows distances between all contacted mers.

    Argument:
    point -- string, name of mers pseudoatom to be merged with distance lines.
    """
    # pylint: disable=invalid-name
    trt = self.substructure.trt_matrix
    points = []
    for ind1 in self.contacts:
        for ind2 in self.contacts[ind1]:
            try:
                p1 = getattr(self.substructure[ind1], point)
                p2 = getattr(self.substructure[ind2], point)
            except AttributeError:
                print('Skipping contact between %s and %s due to lack of pseudoatom.' % (self.substructure[ind1].pid, self.substructure[ind1].pid))
            p1n = fmt(str(self.substructure) + "_" + str(ind1) + '_' + point)
            p2n = fmt(str(self.substructure) + "_" + str(ind2) + '_' + point)
            cmd.pseudoatom(p1n, pos=p1.get_coord(trt))
            cmd.pseudoatom(p2n, pos=p2.get_coord(trt))
            name = p1n + '_' + p2n if split_contacts else self.substructure.name + add_name
            cmd.distance(fmt(name), p1n, p2n)
            points.extend([p1n, p2n])
    if not split_contacts:
        for i in points:
            cmd.delete(i)
    cmd.hide('labels')
Exemple #6
0
    def testRepsExist(self):
        cmd.viewport(200, 150)
        cmd.load(self.datafile('1oky-frag.pdb'), 'm1')

        # make some nonbonded
        cmd.unbond('resi 115-', 'resi 115-')

        # labels
        cmd.label('all', 'name')

        # measurements
        cmd.distance('measure1', 'index 1', 'index 10')
        cmd.angle('measure1', 'index 1', 'index 10', 'index 20')
        cmd.dihedral('measure1', 'index 1', 'index 10', 'index 20', 'index 30')

        # color test setup
        cmd.color('white', '*')
        cmd.set('ambient', 1)
        cmd.set('depth_cue', 0)
        cmd.set('antialias', 0)
        cmd.set('line_smooth', 0)
        cmd.orient()

        # test most reps
        for rep in REPS:
            cmd.show_as(rep)
            self.assertImageHasColor('white', msg='rep missing: ' + rep)

        # test cartoon
        cmd.show_as('cartoon')
        for cart in CARTOONS:
            cmd.cartoon(cart)
            self.assertImageHasColor('white', msg='cartoon missing: ' + cart)
Exemple #7
0
    def show_sbridges(self):
        """Visualize salt bridges."""
        for i, saltb in enumerate(self.plcomplex.saltbridges):
            if saltb.protispos:
                for patom in saltb.positive_atoms:
                    cmd.select('PosCharge-P', 'PosCharge-P or (id %i & %s)' % (patom, self.protname))
                for latom in saltb.negative_atoms:
                    cmd.select('NegCharge-L', 'NegCharge-L or (id %i & %s)' % (latom, self.ligname))
                for sbgroup in [['ps-sbl-1-%i' % i, 'Chargecenter-P', saltb.positive_center],
                                ['ps-sbl-2-%i' % i, 'Chargecenter-L', saltb.negative_center]]:
                    cmd.pseudoatom(sbgroup[0], pos=sbgroup[2])
                    cmd.pseudoatom(sbgroup[1], pos=sbgroup[2])
                cmd.distance('Saltbridges', 'ps-sbl-1-%i' % i, 'ps-sbl-2-%i' % i)
            else:
                for patom in saltb.negative_atoms:
                    cmd.select('NegCharge-P', 'NegCharge-P or (id %i & %s)' % (patom, self.protname))
                for latom in saltb.positive_atoms:
                    cmd.select('PosCharge-L', 'PosCharge-L or (id %i & %s)' % (latom, self.ligname))
                for sbgroup in [['ps-sbp-1-%i' % i, 'Chargecenter-P', saltb.negative_center],
                                ['ps-sbp-2-%i' % i, 'Chargecenter-L', saltb.positive_center]]:
                    cmd.pseudoatom(sbgroup[0], pos=sbgroup[2])
                    cmd.pseudoatom(sbgroup[1], pos=sbgroup[2])
                cmd.distance('Saltbridges', 'ps-sbp-1-%i' % i, 'ps-sbp-2-%i' % i)

        if self.object_exists('Saltbridges'):
            cmd.set('dash_color', 'yellow', 'Saltbridges')
            cmd.set('dash_gap', 0.5, 'Saltbridges')
Exemple #8
0
 def show_wbridges(self):
     """Visualize water bridges."""
     for bridge in self.plcomplex.waterbridges:
         if bridge.protisdon:
             cmd.select(
                 'HBondDonor-P', 'HBondDonor-P or (id %i & %s)' %
                 (bridge.don_id, self.protname))
             cmd.select(
                 'HBondAccept-L', 'HBondAccept-L or (id %i & %s)' %
                 (bridge.acc_id, self.ligname))
             cmd.select('tmp_don',
                        'id %i & %s' % (bridge.don_id, self.protname))
             cmd.select('tmp_acc',
                        'id %i & %s' % (bridge.acc_id, self.ligname))
         else:
             cmd.select(
                 'HBondDonor-L', 'HBondDonor-L or (id %i & %s)' %
                 (bridge.don_id, self.ligname))
             cmd.select(
                 'HBondAccept-P', 'HBondAccept-P or (id %i & %s)' %
                 (bridge.acc_id, self.protname))
             cmd.select('tmp_don',
                        'id %i & %s' % (bridge.don_id, self.ligname))
             cmd.select('tmp_acc',
                        'id %i & %s' % (bridge.acc_id, self.protname))
         cmd.select('Water',
                    'Water or (id %i & resn HOH)' % bridge.water_id)
         cmd.select('tmp_water', 'id %i & resn HOH' % bridge.water_id)
         cmd.distance('WaterBridges', 'tmp_acc', 'tmp_water')
         cmd.distance('WaterBridges', 'tmp_don', 'tmp_water')
     if self.object_exists('WaterBridges'):
         cmd.set('dash_color', 'lightblue', 'WaterBridges')
     cmd.delete('tmp_water or tmp_acc or tmp_don')
     cmd.color('lightblue', 'Water')
     cmd.show('spheres', 'Water')
Exemple #9
0
 def show_metal(self):
     """Visualize metal coordination."""
     metal_complexes = self.plcomplex.metal_complexes
     if not len(metal_complexes) == 0:
         self.select_by_ids('Metal-M', self.metal_ids)
         for metal_complex in metal_complexes:
             cmd.select('tmp_m', 'id %i' % metal_complex.metal_id)
             cmd.select('tmp_t', 'id %i' % metal_complex.target_id)
             if metal_complex.location == 'water':
                 cmd.select('Metal-W',
                            'Metal-W or id %s' % metal_complex.target_id)
             if metal_complex.location.startswith('protein'):
                 cmd.select('tmp_t', 'tmp_t & %s' % self.protname)
                 cmd.select(
                     'Metal-P', 'Metal-P or (id %s & %s)' %
                     (metal_complex.target_id, self.protname))
             if metal_complex.location == 'ligand':
                 cmd.select('tmp_t', 'tmp_t & %s' % self.ligname)
                 cmd.select(
                     'Metal-L', 'Metal-L or (id %s & %s)' %
                     (metal_complex.target_id, self.ligname))
             cmd.distance('MetalComplexes', 'tmp_m', 'tmp_t')
             cmd.delete('tmp_m or tmp_t')
     if self.object_exists('MetalComplexes'):
         cmd.set('dash_color', 'violetpurple', 'MetalComplexes')
         cmd.set('dash_gap', 0.5, 'MetalComplexes')
         # Show water molecules for metal complexes
         cmd.show('spheres', 'Metal-W')
         cmd.color('lightblue', 'Metal-W')
Exemple #10
0
def all_distances(selection,
                  min_seq_dist=6,
                  max_seq_dist=40,
                  min_seq=0,
                  max_seq=0):

    stored.ca = []
    cmd.iterate(selection + ' and n. ca', 'stored.ca.append((resi, resn))')

    if max_seq_dist == 0: max_seq_dist = len(stored.ca)
    if max_seq == 0: max_seq = len(stored.ca)

    for cat1, at1 in enumerate(stored.ca):
        if int(cat1) < int(min_seq): continue
        print(cat1)
        if int(cat1) >= int(max_seq): break
        for cat2, at2 in enumerate(stored.ca):
            if cat2 < cat1: continue
            if int(cat2) >= int(max_seq): break
            if cat2 > cat1 + int(min_seq_dist) and cat2 < cat1 + int(
                    max_seq_dist):
                sele1 = selection + " and r. " + str(
                    at1[1]) + " and i. " + str(at1[0]) + " and n. ca"
                sele2 = selection + " and r. " + str(
                    at2[1]) + " and i. " + str(at2[0]) + " and n. ca"
                print("distance ", "dist_" + str(cat1) + "_" + str(cat2), ",",
                      sele1, ",", sele2)
                cmd.distance("dist_" + str(cat1) + "_" + str(cat2), sele1,
                             sele2)
    cmd.group(selection + "_dists", "dist_*")
def draw_dist_pairs(drs_inp, molecule, draw_type="line"):
    f_drsinp = open(drs_inp, "r")
    obj = "network"
    cmd.create(obj, molecule)
    cmd.hide("everything", obj)
    for i, line in enumerate(f_drsinp):
        print "Pair No.: ", i
        if line.split()[1] != "LIST" and line.split()[1] != "STOP":
            chainid1, resid1, resname1, atomname1 = line.split(
            )[0], line.split()[1], line.split()[2], line.split()[3]
            chainid2, resid2, resname2, atomname2 = line.split(
            )[4], line.split()[5], line.split()[6], line.split()[7]
            print chainid1, resid1, resname1, atomname1, chainid2, resid2, resname2, atomname2
            if draw_type == "line":
                cmd.bond("%s and chain %s and resi %s and name %s"%(obj,chainid1,resid1,atomname1),\
                         "%s and chain %s and resi %s and name %s"%(obj,chainid2,resid2,atomname2) )
                cmd.show(
                    "lines", "%s and chain %s and resi %s and name %s" %
                    (obj, chainid1, resid1, atomname1))
                cmd.show(
                    "lines", "%s and chain %s and resi %s and name %s" %
                    (obj, chainid2, resid2, atomname2))
            elif draw_type == "dist":
                cmd.distance("dist%s"%i, "chain %s and resi %s and name %s"%(chainid1,str(resid1),atomname1),\
                                         "chain %s and resi %s and name %s"%(chainid2,str(resid2),atomname2) )
            print "chain %s and resi %s and name %s" % (chainid1, resid1,
                                                        atomname1)
        elif line.split()[1] == "STOP":
            print "Reached last line"
            break
Exemple #12
0
    def testRepsExist(self):
        cmd.viewport(200, 150)
        cmd.load(self.datafile('1oky-frag.pdb'), 'm1')

        # make some nonbonded
        cmd.unbond('resi 115-', 'resi 115-')

        # labels
        cmd.label('all', 'name')

        # measurements
        cmd.distance('measure1', 'index 1', 'index 10')
        cmd.angle('measure1', 'index 1', 'index 10', 'index 20')
        cmd.dihedral('measure1', 'index 1', 'index 10', 'index 20', 'index 30')

        # color test setup
        cmd.color('white', '*')
        cmd.set('ambient', 1)
        cmd.set('depth_cue', 0)
        cmd.set('antialias', 0)
        cmd.set('line_smooth', 0)
        cmd.orient()

        # test most reps
        for rep in REPS:
            cmd.show_as(rep)
            self.assertImageHasColor('white', msg='rep missing: ' + rep)

        # test cartoon
        cmd.show_as('cartoon')
        for cart in CARTOONS:
            cmd.cartoon(cart)
            self.assertImageHasColor('white', msg='cartoon missing: ' + cart)
def map_interaction_freq_to_structure(pdb,
                                      chain,
                                      interaction_freq_file,
                                      exp_rep_id,
                                      threshold=0.0):

    ### Background coloring settings
    cmd.bg_color("white")
    cmd.fetch(pdb)
    cmd.hide()
    cmd.show("cartoon")
    cmd.cartoon("loop")
    cmd.color("white", pdb)
    cmd.set("dash_gap", 0)
    cmd.set("dash_width", 5)

    ### Extract interaction frequency information
    interaction_freq_info_list = getInteractionFreqList(
        pdb, interaction_freq_file, exp_rep_id, threshold)

    ### Color interactions by frequency
    print("color interactions by frequency")
    for gpcrdb_pair, resid1, resid2, freq in interaction_freq_info_list:
        cmd.distance(
            "%s" % (gpcrdb_pair),
            "%s and resi %d and name CA and chain %s" % (pdb, resid1, chain),
            "%s and resi %d and name CA and chain %s" % (pdb, resid2, chain))
        mapped_col = freq_to_grayscale(freq)
        cmd.set("dash_color", mapped_col, gpcrdb_pair)
        cmd.hide("labels")
Exemple #14
0
def mindist(selection1, selection2, n=1, t=500, unique=0, _legacy=0):
    # Create selection objects
    sele_1 = Selection(selection1)
    sele_2 = Selection(selection2)
    sele_2.remove_dupes(sele_1)
    try:
        if int(_legacy) != 0:
            raise ImportError("Used for testing without numpy")
        gen_mindist = get_mindist_np(sele_1, sele_2)
    except (NameError, ImportError, NotImplementedError):
        gen_mindist = get_mindist(selection1, selection2, t=500)
    resi_pairs = []  # keep track of residue pairs in case we want to skip
    count = 0
    while count < int(n):
        try:
            min_pair = next(gen_mindist)
        except StopIteration:
            # it could be that < n pairs were selected
            break
        a, b = min_pair
        resi_pair = {ir(a), ir(b)}
        if unique == 1 and resi_pair in resi_pairs:
            # skip if we want only unique residues
            # distances are sorted anyway so we'll get the shortes distance
            continue
        else:
            resi_pairs.append(resi_pair)
        cmd.distance(f"mindist_{a}_{b}", f"index {a} and {sele_1.obj}",
                     f"index {b} and {sele_2.obj}")
        count += 1
Exemple #15
0
    def show_stacking(self):
        """Visualize pi-stacking interactions."""
        stacks = self.plcomplex.pistacking
        for i, stack in enumerate(stacks):
            pires_ids = '+'.join(map(str, stack.proteinring_atoms))
            pilig_ids = '+'.join(map(str, stack.ligandring_atoms))
            cmd.select(
                'StackRings-P',
                'StackRings-P or (id %s & %s)' % (pires_ids, self.protname))
            cmd.select(
                'StackRings-L',
                'StackRings-L or (id %s & %s)' % (pilig_ids, self.ligname))
            cmd.select('StackRings-P', 'byres StackRings-P')
            cmd.show('sticks', 'StackRings-P')

            cmd.pseudoatom('ps-pistack-1-%i' % i, pos=stack.proteinring_center)
            cmd.pseudoatom('ps-pistack-2-%i' % i, pos=stack.ligandring_center)
            cmd.pseudoatom('Centroids-P', pos=stack.proteinring_center)
            cmd.pseudoatom('Centroids-L', pos=stack.ligandring_center)

            if stack.type == 'P':
                cmd.distance('PiStackingP', 'ps-pistack-1-%i' % i,
                             'ps-pistack-2-%i' % i)
            if stack.type == 'T':
                cmd.distance('PiStackingT', 'ps-pistack-1-%i' % i,
                             'ps-pistack-2-%i' % i)
        if self.object_exists('PiStackingP'):
            cmd.set('dash_color', 'green', 'PiStackingP')
            cmd.set('dash_gap', 0.3, 'PiStackingP')
            cmd.set('dash_length', 0.6, 'PiStackingP')
        if self.object_exists('PiStackingT'):
            cmd.set('dash_color', 'smudge', 'PiStackingT')
            cmd.set('dash_gap', 0.3, 'PiStackingT')
            cmd.set('dash_length', 0.6, 'PiStackingT')
Exemple #16
0
 def Highlight_HBonds(self, Result, ResultName, ResultHBondsName):
     
     cmd.distance(ResultHBondsName, 
                  'resn LIG & ' + ResultName,
                  ResultName + ' & !resn LIG',
                  3.5, # distance in A
                  2)   # mode (2=polar atoms)
def dehydron(selection='all', angle_range=40, max_distance=3.5, desolv=6.5, min_wrappers=19, quiet=0):
    '''
DESCRIPTION

    dehydron calculator

USAGE

    dehydron [ selection [, angle_range [, max_distance [, desolv [, min_wrappers ]]]]]
    '''

    angle, max_distance = float(angle_range), float(max_distance)
    desolv, min_wrappers = float(desolv), int(min_wrappers)
    quiet = int(quiet)


    name = cmd.get_legal_name('DH_%s' % selection)
    cmd.delete(name)

    selection_hb = '((%s) and polymer)' % (selection)
    hb = cmd.find_pairs("((byres "+selection_hb+") and n. n)","((byres "+selection_hb+") and n. o)",mode=1,cutoff=max_distance,angle=angle_range)

    if not quiet:
        hb.sort(lambda x,y:(cmp(x[0][1],y[0][1])))
        print "--------------------------------------------------------------------"
        print "--------------------------Dehydron Results--------------------------"
        print "--------------------------------------------------------------------"
        print "            Donor            |            Aceptor          |"
        print "     Object   Chain Residue  |     Object   Chain Residue  | # wrappers"

    cmd.select('_nonpolar', '(elem C) and not (solvent or (elem N+O) extend 1)', 0)
    try:
        cmd.select('_selection', '%s' % selection, 0)
    except:
        pass

    sel = []
    for pairs in hb:
        wrappers = cmd.count_atoms('((%s and _nonpolar and _selection) within %f of byca (%s`%d %s`%d))' % 
                ((pairs[0][0], desolv) + pairs[0] + pairs[1]))
        if wrappers < min_wrappers:
            cmd.distance(name, pairs[0], pairs[1])
            if not quiet:
                cmd.iterate(pairs[0], 'stored.nitro = chain, resi, resn')
                cmd.iterate(pairs[1], 'stored.oxy = chain, resi, resn')
                print ' %12s%4s%6s%5d | %12s%4s%6s%5d |%7s' % (pairs[0][0], stored.nitro[0], stored.nitro[2], int(stored.nitro[1]), pairs[1][0], stored.oxy[0], stored.oxy[2], int(stored.oxy[1]), wrappers)
            sel.append(pairs[0])
            sel.append(pairs[1])
    cmd.delete('_nonpolar')
    cmd.delete('_selection')

    if len(sel) > 0:
        cmd.show_as('dashes', name)
    elif not quiet and len(hb) != 0:
        print ' - no dehydrons were found - '
    else:
        print ' - no hydrogen bonds were found - '
Exemple #18
0
def selection_(path):
    ids = get_ids(path, '_ah')
    #for [h,i,j,k] in ids:   #1
    for [h, i, j, k, l] in ids:  #2
        print h, 'id ' + i.strip() + ',' + j.strip()
        #cmd.select(h,'id '+i.strip()+','+j.strip())
        cmd.distance(h, 'id ' + i.strip(), 'id ' + j.strip())
        cmd.hide('labels', h)
        cmd.pseudoatom(h + '_ps', pos=k, label=l)
Exemple #19
0
 def testMeasurementColor(self):
     self._make_objects(1)
     sele = 'd1'
     cmd.distance(sele, 'first all', 'last all')
     m = menu.measurement_color(cmd, sele)
     self._eval_first(m)
     m = menu.measurement_hide(cmd, sele)
     self._eval_first(m)
     m = menu.measurement_show(cmd, sele)
     self._eval_first(m)
Exemple #20
0
 def testMeasurementColor(self):
     self._make_objects(1)
     sele = 'd1'
     cmd.distance(sele, 'first all', 'last all')
     m = menu.measurement_color(cmd, sele)
     self._eval_first(m)
     m = menu.measurement_hide(cmd, sele)
     self._eval_first(m)
     m = menu.measurement_show(cmd, sele)
     self._eval_first(m)
Exemple #21
0
def beta_hbonds(selection_hydrogen, selection_acceptor, dmin=1, dmax=3):
    i = 0
    for o, h, d in find_hbonds(selection_hydrogen, selection_acceptor, dmin,
                               dmax):
        cmd.distance('dist{:04d}'.format(i),
                     '(idx {}) and ({})'.format(o, selection_acceptor),
                     '(idx {}) and ({})'.format(h, selection_hydrogen),
                     mode=0)
        cmd.group('hbonds', 'dist{:04d}'.format(i))
        i += 1
def draw_bonds(protein_obj, ligand_obj, distance):
    cmd.select("donor", "(elem n,o and (neighbor hydro))")
    cmd.select("acceptor", "(elem o or (elem n and not (neighbor hydro)))")
    cmd.distance("HBAcc", "({} and acceptor)".format(ligand_obj),
                 "({} and donor)".format(protein_obj), distance)
    cmd.distance("HBDon", "({} and donor)".format(ligand_obj),
                 "({} and acceptor)".format(protein_obj), distance)

    cmd.delete("donor")
    cmd.delete("acceptor")
    cmd.hide("labels")
def draw_axis(chA, chB, scale_factor=20, w=0.6, r1=1, g1=1, b1=1, r2=1, g2=0, b2=0):
    T = transf_matrix(chA, chB)
    angle=angle_axis(chA, chB)
    angle_degrees=(angle*180)/math.pi
    axis1=[direction_cosines(chA, chB)[0], direction_cosines(chA, chB)[1], direction_cosines(chA, chB)[2]]
    p = nearest_point_to_axis(chA, chB)
    x1, y1, z1 = p[0] + (3*scale_factor*axis1[0]), p[1] + (3*scale_factor*axis1[1]), p[2] + (3*scale_factor*axis1[2])
    x2, y2, z2 = p[0] - (3*scale_factor*axis1[0]), p[1] - (3*scale_factor*axis1[1]), p[2] - (3*scale_factor*axis1[2])
    obj = [cgo.CYLINDER, x1, y1, z1, x2, y2, z2, w, r1, g1, b1, r2, g2, b2, 0.0]
    cmd.load_cgo(obj, angle_degrees)

    cmA=center_of_Mass(chA)
    cmB=cmW
    cmAver=(cmB+cmA)/2
    vector=numpy.array([(cmB[0]-cmA[0]), (cmB[1]-cmA[1]), (cmB[2]-cmA[2])])
    moduli_vector=numpy.linalg.norm(vector)
    vector_director=numpy.array([(cmB[0]-cmA[0])/moduli_vector, (cmB[1]-cmA[1])/moduli_vector, (cmB[2]-cmA[2])/moduli_vector])
    pC_A = proyeccion_centroide(chA, chA, chB)
    pC_B = proyeccion_centroide_working(chA, chB)


    trans_vector = numpy.array([(pC_B[0]-pC_A[0]), (pC_B[1]-pC_A[1]), (pC_B[2]-pC_A[2])])
    modu_tr = numpy.linalg.norm(trans_vector)
    rota_centroid_rad=numpy.dot(vector_director, axis1)
    rota_centroid = (rota_centroid_rad*180)/math.pi
    rota_centroid_absol_0= numpy.absolute(rota_centroid)
    rota_centroid_absol=round(rota_centroid_absol_0,2)


    if rota_centroid_absol == 0.00:
        p1 = '_1'
        p2 = '_2'
        p3 = '_3'
        cmd.pseudoatom (pos=[cmA[0], cmA[1], cmA[2]], object=p1)
        cmd.pseudoatom (pos=[pC_A[0], pC_A[1], pC_A[2]], object=p2)
        cmd.pseudoatom (pos=[cmB[0], cmB[1], cmB[2]], object=p3)
        cmd.angle(None, p1, p2, p3)
        print_information(T, axis1, angle_degrees,  moduli_vector, obj, x1, y1, z1, x2, y2, z2, w, r1, g1, b1, r2, g2, b2)

    if rota_centroid_absol != 0:
        p1 = '_1'
        p2 = '_2'
        p3 = '_3'
        p4 = '_4'
        cmd.pseudoatom (pos=[cmA[0], cmA[1], cmA[2]], object=p1)
        cmd.pseudoatom (pos=[pC_A[0], pC_A[1], pC_A[2]], object=p2)
        cmd.pseudoatom (pos=[pC_B[0], pC_B[1], pC_B[2]], object=p3)
        cmd.pseudoatom (pos=[cmB[0], cmB[1], cmB[2]], object=p4)
        cmd.dihedral(None, p1, p2, p3, p4)
        cmd.distance(None, p2, p3)
        print_information(T, axis1, angle_degrees,  moduli_vector, obj, x1, y1, z1, x2, y2, z2, w, r1, g1, b1, r2, g2, b2, modu_tr)

    cmd.create('working', chA)
    cmd.super('working', chB)
Exemple #24
0
def draw_bonds(protein_obj, ligand_obj, distance):
    cmd.select("donor", "(elem n,o and (neighbor hydro))")
    cmd.select("acceptor", "(elem o or (elem n and not (neighbor hydro)))")
    cmd.distance("HBAcc", "({} and acceptor)".format(ligand_obj),
           "({} and donor)".format(protein_obj), distance)
    cmd.distance("HBDon", "({} and donor)".format(ligand_obj),
                "({} and acceptor)".format(protein_obj), distance)

    cmd.delete("donor")
    cmd.delete("acceptor")
    cmd.hide("labels")
Exemple #25
0
def draw_vector(x, y):
    """
    draws a line (vector) between two point 

    :param x: coordinates of the first point 
    :param y: coordinates of the second point
    :return:
    """
    id_ = str(uuid4())
    cmd.pseudoatom('vx' + id_, pos=x, color="red", name='x')
    cmd.pseudoatom('vy' + id_, pos=y, color="red", name='y')
    cmd.distance('vx' + id_ + '////x', 'vy' + id_ + '////y')
    pymol.cmd.reset()
Exemple #26
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()
Exemple #27
0
    def input_file(self):
        import tkMessageBox
        import tkFileDialog
        import os
        import string
        global file_class
		  file=open(self.return_app())
		  filelist=file.readlines()
		  for r in filelist:
			  tag=r.split()
			  selection1='resid '+tag[0]+' and '+'name CA'
			  selection2='resid '+tag[1]+' and '+'name CA'
			  dist_name=r
			  cmd.distance(dist_name,selection1,selection2)
Exemple #28
0
    def click_on_plot_ali(self, i, j):
        """
        Used when analyzing multiple structures. The residues of the reference structures will be
        used in PyMOL.
        """
        if i == j:
            return None

        sel_1 = self.ref_selectors[i]
        sel_2 = self.ref_selectors[j]
        if sel_1 is None or sel_2 is None:
            return None
        cmd.distance("pymod_dist_%s" % self.distance_count, sel_1, sel_2)
        self.distance_count += 1
        self.delete_distances_button.setEnabled(True)
Exemple #29
0
def draw_bonds(bond_list):
    c = itertools.cycle(("yellow", "blue", "green", "red", "white", "black"))

    colors = dict()
    for t in bond_list:
        if t[2] not in colors:
            colors[t[2]] = c.next()

    for bond in bond_list:
        print(bond_list)
        cmd.distance("%s" % bond[2], "id %s" % bond[0], "id %s" % bond[1])
        cmd.set("dash_color", colors[bond[2]], "%s" % bond[2])

        cmd.hide("labels")
    cmd.set("dash_gap", 0.20)
Exemple #30
0
    def show_hydrophobic(self):
        """Visualizes hydrophobic contacts."""
        hydroph = self.plcomplex.hydrophobic_contacts
        if not len(hydroph.bs_ids) == 0:
            self.select_by_ids('Hydrophobic-P', hydroph.bs_ids, restrict=self.protname)
            self.select_by_ids('Hydrophobic-L', hydroph.lig_ids, restrict=self.ligname)

            for i in hydroph.pairs_ids:
                cmd.select('tmp_bs', 'id %i & %s' % (i[0], self.protname))
                cmd.select('tmp_lig', 'id %i & %s' % (i[1], self.ligname))
                cmd.distance('Hydrophobic', 'tmp_bs', 'tmp_lig')
            if self.object_exists('Hydrophobic'):
                cmd.set('dash_gap', 0.5, 'Hydrophobic')
                cmd.set('dash_color', 'grey50', 'Hydrophobic')
        else:
            cmd.select('Hydrophobic-P', 'None')
Exemple #31
0
    def show_halogen(self):
        """Visualize halogen bonds."""
        halogen = self.plcomplex.halogen_bonds
        all_don_x, all_acc_o = [], []
        for h in halogen:
            all_don_x.append(h.don_id)
            all_acc_o.append(h.acc_id)
            cmd.select('tmp_bs', 'id %i & %s' % (h.acc_id, self.protname))
            cmd.select('tmp_lig', 'id %i & %s' % (h.don_id, self.ligname))

            cmd.distance('HalogenBonds', 'tmp_bs', 'tmp_lig')
        if not len(all_acc_o) == 0:
            self.select_by_ids('HalogenAccept', all_acc_o, restrict=self.protname)
            self.select_by_ids('HalogenDonor', all_don_x, restrict=self.ligname)
        if self.object_exists('HalogenBonds'):
            cmd.set('dash_color', 'greencyan', 'HalogenBonds')
Exemple #32
0
def displacementUpdateBAll(objA, alnAri, objB, alnBri):
    print(
        "This will take a while to go through the for loops. Give me around 3-5 minutes..."
    )
    # If residue is unassigned in one of the pdb files, we reset its value
    for x in range(len(alnAri)):
        s1 = objA + " and resi " + alnAri[x][0] + " and name " + str(
            alnAri[x][1])
        cmd.alter(s1, "b = " + str(-0.01))
    for x in range(len(alnBri)):
        s2 = objB + " and resi " + alnBri[x][0] + " and name " + alnBri[x][1]
        cmd.alter(s2, "b = " + str(-0.01))
    cmd.sort(objA)
    cmd.sort(objB)
    for x in range(len(alnAri)):
        s1 = objA + " and resi " + alnAri[x][0] + " and name " + alnAri[x][1]
        s2 = objB + " and resi " + alnAri[x][0] + " and name " + alnAri[x][1]
        # Names starting with __ (underscores) are normally hidden by PyMOL
        tempObject = "__tempObject"
        Displacement = cmd.distance(tempObject, s1, s2)
        cmd.alter(s1, "b = " + str(Displacement))
        cmd.alter(s2, "b = " + str(Displacement))
        cmd.delete(tempObject)
    cmd.sort(objA)
    cmd.sort(objB)
Exemple #33
0
    def testMeasureBetweenStates(self):
        cmd.load(self.datafile('1v5a-3models.cif'), 'm1')

        # distance
        d = cmd.distance('d1', '24/CZ', 'same', state1=2, state2=3)
        self.assertAlmostEqual(d, 3.0, delta=1e-1)

        # angle
        a = cmd.angle('a1',
                      '24/CZ',
                      'same',
                      'same',
                      state1=2,
                      state2=3,
                      state3=1)
        self.assertAlmostEqual(a, 73.5, delta=1e-1)

        # visual test
        cmd.viewport(100, 100)
        cmd.set('dash_radius', 1.0)
        self.ambientOnly()
        for name in ['d1', 'a1']:
            cmd.disable('*')
            cmd.enable(name)
            cmd.zoom(name)
            self.assertImageHasColor('yellow')
Exemple #34
0
def get_dist_pymol(n=5):
    cmd.load("tutorial/data/drd3_gi_pd.pdb")
    # cmd.select("polymer.protein")
    # atoms = cmd.count_atoms("polymer.protein")
    # print("Atoms selected: ", atoms)
    # residues = len(cmd.get_model("poly and chain C").get_residues())
    # dist_arr = np.zeros((residues, residues))
    # for i in range(residues):
    #     for j in range(residues):
    dist_arr = np.zeros((n, n))
    for i in range(n):
        for j in range(n):
            if i == j:
                continue
            else:
                ind_a = cmd.index("resi %d" % (i + 1))
                ind_b = cmd.index("resi %d" % (j + 1))
                temp_dist = []
                for a in range(len(ind_a)):
                    for b in range(len(ind_b)):
                        temp_dist.append(
                            cmd.distance("index %d" % ind_a[a][1],
                                         "index %d" % ind_b[b][1]))
                dist_arr[i, j] = min(temp_dist)

    h.heap().dump("benchmarking/heaps/5_pymol.out")

    return dist_arr
    def do_state(self,state):
        cmd=self.cmd
        if cmd.get("sculpting")=="on":
            names = cmd.get_names("all_objects")
            if (bump_name in names) and (obj_name in names):
                cmd.update(bump_name,obj_name)
        if self.bump_scores:
            print(' Rotamer %d/%d, strain=%.2f' % (state,
                    cmd.count_states(obj_name), self.bump_scores[state - 1]))

        # update hbonds (polar contacts)
        cmd.delete(tmp_hbonds)
        cmd.distance(tmp_hbonds,
                "?{}".format(obj_name),
                "(byobj ?{}) and not ?{}".format(src_sele, src_sele),
                mode=2, state1=state, state2=1)
def showHbBond(sele1, sele2, onlyShortest=True):
    '''Show hydrogen bond between two residues.
    '''
    
    atoms1 = getAllAtoms(sele1)
    atoms2 = getAllAtoms(sele2)
    
    smallestDist = 10000
    smallestDistObj = None
    
    for firstAtom in atoms1:
        if not hasHbond(firstAtom): continue
        firstSele = "name " + firstAtom + " and " + sele1 
        for secondAtom in atoms2:
            if not hasHbond(secondAtom): continue
            secondSele = "name " + secondAtom + " and " + sele2
#             print firstSele
#             print secondSele 
            distName = sele1+firstAtom+'-'+sele2+secondAtom
            tempDist = cmd.distance(distName, firstSele, secondSele)
            
            if tempDist < smallestDist:
                smallestDist = tempDist
                if smallestDistObj:
                    cmd.delete(smallestDistObj)
                smallestDistObj = distName
         
            else:
                cmd.delete(distName)
Exemple #37
0
def list_hb(selection,
            selection2=None,
            cutoff=3.2,
            angle=55,
            mode=1,
            hb_list_name='hbonds'):
    """
    USAGE
  
    list_hb selection, [selection2 (default=None)], [cutoff (default=3.2)],
                       [angle (default=55)], [mode (default=1)],
                       [hb_list_name (default='hbonds')]
  
    The script automatically adds a requirement that atoms in the
    selection (and selection2 if used) must be either of the elements N or
    O.
  
    If mode is set to 0 instead of the default value 1, then no angle
    cutoff is used, otherwise the angle cutoff is used and defaults to 55
    degrees.
  
    e.g.
    To get a list of all H-bonds within chain A of an object
      list_hb 1abc & c. a &! r. hoh, cutoff=3.2, hb_list_name=abc-hbonds
  
    To get a list of H-bonds between chain B and everything else:
      list_hb 1tl9 & c. b, 1tl9 &! c. b
  
    """
    cutoff = float(cutoff)
    angle = float(angle)
    mode = float(mode)
    # ensure only N and O atoms are in the selection
    selection = selection + " & e. n+o"
    if not selection2:
        hb = cmd.find_pairs(selection,
                            selection,
                            mode=mode,
                            cutoff=cutoff,
                            angle=angle)
    else:
        selection2 = selection2 + " & e. n+o"
        hb = cmd.find_pairs(selection,
                            selection2,
                            mode=mode,
                            cutoff=cutoff,
                            angle=angle)

    # sort the list for easier reading
    hb.sort(lambda x, y: (cmp(x[0][1], y[0][1])))

    for pairs in hb:
        cmd.iterate("%s and index %s" % (pairs[0][0], pairs[0][1]),
                    'print "%1s/%3s`%s/%-4s " % (chain,resn,resi,name),')
        cmd.iterate("%s and index %s" % (pairs[1][0], pairs[1][1]),
                    'print "%1s/%3s`%s/%-4s " % (chain,resn,resi,name),')
        print "%.2f" % cmd.distance(
            hb_list_name, "%s and index %s" %
            (pairs[0][0], pairs[0][1]), "%s and index %s" %
            (pairs[1][0], pairs[1][1]))
Exemple #38
0
def display_graphkernel(pdb_id, pdb_path):
    '''
    '''
    # Load PDB
    cmd.bg_color('white')
    cmd.load(pdb_path + pdb_id[:-2] + '.pdb')
    cmd.split_chains(pdb_id[:-2])
    for name in cmd.get_names('objects', 0, '(all)'):
        if not name.endswith(pdb_id[-1].upper()) and name.startswith(
                pdb_id[:4]):
            cmd.delete(name)
        else:
            zero_residues(name)
    cmd.reset()

    pdb_id2 = pdb_id + 'copy'
    cmd.create(pdb_id2, pdb_id)

    cmd.hide('everything', pdb_id)
    cmd.show_as('lines', pdb_id + ' and (name ca or name c or name n)')
    cmd.set('line_width', 5)
    cmd.set_bond('line_width', 5,
                 pdb_id + ' and (name ca or name c or name n)')
    cmd.show('spheres', pdb_id + ' and name ca')
    cmd.set('sphere_transparency', 0.0, pdb_id + ' and name ca')
    cmd.set('sphere_scale', 0.5, pdb_id + ' and name ca')

    cmd.hide('everything', pdb_id2)
    cmd.show('spheres', pdb_id2 + ' and name ca')
    cmd.set('sphere_transparency', 0.8, pdb_id2 + ' and name ca')
    cmd.set('sphere_scale', code2[elem], elem + '&' + selection)
    #cmd.set('sphere_scale', 2, pdb_id2 + ' and name ca')

    data = cmd.get_coords(selection=pdb_id + ' and name ca', state=1)

    j = 55
    cmd.set('dash_width', 1.0)
    cmd.set('dash_color', 'marine')
    for i in range(len(data)):
        cmd.distance('d' + str(i) + str(j),
                     pdb_id2 + ' and name ca and res ' + str(i),
                     pdb_id2 + ' and name ca and res ' + str(j))
        cmd.hide('labels', 'd' + str(i) + str(j))
    resicolor(pdb_id)

    resicolor(pdb_id)
    resicolor(pdb_id2, True)
Exemple #39
0
    def draw_line(self):
        import tkSimpleDialog
        import tkMessageBox
        import urllib
        import os
        import string

        from arrow import cgo_arrow

        atoms=self.return_app()
        terminals=atoms.split(',')
        print "hello terminals"
        print terminals
        dist_name=terminals[0]+'_'+terminals[1]+'_'+terminals[2]+'_'+terminals[3]
        selection1='resid '+terminals[0]+' and '+'name '+terminals[1]
        selection2='resid '+terminals[2]+' and '+'name '+terminals[3]
        cmd.distance(dist_name,selection1,selection2)
Exemple #40
0
def gremlin(file,chain='B',s_score_th=1.5,prob_th=1,inc='0',color="red"):

	count = 0
	pos1 = 0
	pos2 = 0
	pos1_rem = 0
	pos2_rem = 0
	pattern = re.compile('\_')

	# Initial Parameters
	cmd.set("dash_gap","0")
	cmd.set("dash_width","6") # max is 6

	# Display Setup
	cmd.disable("hbonds");
	cmd.delete("*_X");

	# Read Gremlin File
	for line in open(file):
		
		# Split Resfile Line by Tab
		data = line.split(' ')
		
		# Only Consider Lines that have the Pattern
		pair = data[0]
		if pattern.search(pair):
#print pair
			contact = pair.split('_')
			pos1 = int(contact[0])
			pos2 = int(contact[1])
			aa = contact[2]

			if aa == 'X':
				l2_score = float(data[1])
				s_score = float(data[2])
				prob = float(data[3])
				print prob

				if pos1 == pos1_rem:
					continue
				if pos2 == pos2_rem:
					continue
				if abs(pos1-pos2) <= 3:
					continue
				pos1_rem = pos1
				pos2_rem = pos2

				pos1 += int(inc)
				pos2 += int(inc)

				if prob >= float(prob_th) and s_score >= float(s_score_th):
					dist = cmd.distance("%s"%(pair),"resi %i and name ca and chain %s"%(pos1,chain),"resi %i and name ca and chain %s"%(pos2,chain))
					if dist <= 12:
						cmd.set("dash_color","yellow","%s"%(pair))
					if dist > 12 and dist <= 20:
						cmd.set("dash_color","orange","%s"%(pair))
					if dist > 20:
						cmd.set("dash_color","red","%s"%(pair))
def draw_vector(name, vector_, center):
    """Create a distance with the length and direction of a given vector,
    and then hide its label.
    The center should have the same xy projection as the center you gave to
    the moment function, but you might want to change the z value to make it
    more visible.
    
    ARGUMENTS:
    (name, vector_, center)
    RETURNS:
    Nothing."""
    
    # The awkward tuple(Vector(center)) thing turns (a,b) into (a,b,0)
    cmd.pseudoatom('ps1', pos = tuple(Vector(center)))
    cmd.pseudoatom('ps2', pos = tuple((Vector(center) + Vector(vector_))))
    cmd.distance(name, 'ps1', 'ps2')
    cmd.hide('labels', name)
    cmd.delete('ps1 ps2')
Exemple #42
0
def draw_bonds(bond_list):

    c = itertools.cycle(("yellow", "blue", "green", "red", "white", "black"))

    colors = dict()
    for t in bond_list:
        if t[2] not in colors:
            colors[t[2]] = c.next()


    for bond in bond_list:

        print(bond_list)
        cmd.distance("%s" % bond[2], "id %s" % bond[0], "id %s" % bond[1])
        cmd.set("dash_color", colors[bond[2]], "%s" % bond[2])


        cmd.hide("labels")
    cmd.set("dash_gap", 0.20)
def hbplus(selection='all', exe='hbplus', prefix='hb_', state=-1, quiet=1):
    '''
DESCRIPTION

    HBPLUS wrapper
    '''
    import subprocess
    import tempfile
    import os
    import shutil

    state, quiet = int(state), int(quiet)

    tempdir = tempfile.mkdtemp()
    pdbfile = os.path.join(tempdir, 'foo.pdb')
    hb2file = os.path.join(tempdir, 'foo.hb2')

    try:
        for model in cmd.get_object_list('(' + selection + ')'):
            cmd.save(pdbfile, 'model %s and (%s)' % (model, selection), state)
            process = subprocess.Popen([exe, pdbfile], cwd=tempdir,
                                       stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
            stdout, _ = process.communicate()

            if not quiet:
                print(stdout)

            for line in open(hb2file):
                if line[5] != '-' or line[19] != '-':
                    continue
                chain1, resi1, name1 = line[0], line[1:5], line[10:14]
                chain2, resi2, name2 = line[14], line[15:19], line[24:28]
                sele1 = '/%s//%s/%s/%s' % (model, chain1, resi1.lstrip('0'), name1.rstrip())
                sele2 = '/%s//%s/%s/%s' % (model, chain2, resi2.lstrip('0'), name2.rstrip())
                cat = line[33:35]
                cmd.distance(prefix + cat, sele1, sele2)

    except OSError:
        print('Error: Cannot execute exe=' + exe)
        raise CmdException
    finally:
        shutil.rmtree(tempdir)
Exemple #44
0
def polarpairs(sel1, sel2, cutoff=4.0, angle=63.0, name='', state=1, quiet=1):
    '''
ARGUMENTS
 
    sel1, sel2 = string: atom selections
 
    cutoff = float: distance cutoff
 
    angle = float: h-bond angle cutoff in degrees. If angle="default", take
    "h_bond_max_angle" setting. If angle=0, do not detect h-bonding.
 
    name = string: If given, also create a distance object for visual representation
 
SEE ALSO
 
    cmd.find_pairs, cmd.distance
    '''
    cutoff = float(cutoff)
    quiet = int(quiet)
    state = int(state)
    if angle == 'default':
        angle = cmd.get('h_bond_max_angle', cmd.get_object_list(sel1)[0])
    angle = float(angle)
    mode = 1 if angle > 0 else 0
    x = cmd.find_pairs('(%s) and donors' % sel1, '(%s) and acceptors' % sel2,
            state, state,
            cutoff=cutoff, mode=mode, angle=angle) + \
        cmd.find_pairs('(%s) and acceptors' % sel1, '(%s) and donors' % sel2,
            state, state,
            cutoff=cutoff, mode=mode, angle=angle)
    x = sorted(set(x))
    if not quiet:
        print 'Settings: cutoff=%.1fangstrom angle=%.1fdegree' % (cutoff, angle)
        print 'Found %d polar contacts' % (len(x))
    if len(name) > 0:
        for p in x:
            cmd.distance(name, '(%s`%s)' % p[0], '(%s`%s)' % p[1])
    return x
def draw_dist_pairs(drs_inp, molecule, draw_type="line"):
  f_drsinp = open(drs_inp, "r")
  obj = "network"
  cmd.create(obj, molecule)
  cmd.hide("everything", obj)
  for i, line in enumerate(f_drsinp):
    print "Pair No.: ", i
    if line.split()[1] != "LIST" and line.split()[1] != "STOP":
      chainid1, resid1, resname1, atomname1 = line.split()[0], line.split()[1], line.split()[2],line.split()[3]
      chainid2, resid2, resname2, atomname2 = line.split()[4], line.split()[5], line.split()[6],line.split()[7]
      print chainid1, resid1, resname1, atomname1, chainid2, resid2, resname2, atomname2
      if draw_type == "line":
        cmd.bond("%s and chain %s and resi %s and name %s"%(obj,chainid1,resid1,atomname1),\
                 "%s and chain %s and resi %s and name %s"%(obj,chainid2,resid2,atomname2) )
        cmd.show("lines", "%s and chain %s and resi %s and name %s"%(obj, chainid1,resid1,atomname1))
        cmd.show("lines", "%s and chain %s and resi %s and name %s"%(obj, chainid2,resid2,atomname2))
      elif draw_type == "dist":
        cmd.distance("dist%s"%i, "chain %s and resi %s and name %s"%(chainid1,str(resid1),atomname1),\
                                 "chain %s and resi %s and name %s"%(chainid2,str(resid2),atomname2) )
      print "chain %s and resi %s and name %s"%(chainid1,resid1,atomname1)
    elif line.split()[1] == "STOP":
      print "Reached last line"
      break
def calcDist(obj, l1, l2):
    # obj is the protein in question, l1, l2 are the positions of residues.
    # delete previous selections and displayed distances
    print ""
    cmd.delete("dist")
    cmd.delete("sele")
    cmd.delete("Residue_1")
    cmd.delete("Residue_2")

    # select two residues based on input, at positions l1 and l2 in the sequence
    cmd.select("Residue_1", "resi {}".format(l1))
    cmd.select("Residue_2", "resi {}".format(l2))

    #the underscores ARE IMPORTANT
    distance = cmd.distance("dist", "Residue_1", "Residue_2")
    return distance
def list_hb(selection,cutoff=3.2,angle=55,hb_list_name='hbonds'):
  """
  USAGE

  list_hb selection, [cutoff (default=3.2)], [angle (default=55)], [hb_list_name]
  
  e.g.
    list_hb 1abc & c. a &! r. hoh, cutoff=3.2, hb_list_name=abc-hbonds
  """
  cutoff=float(cutoff)
  angle=float(angle)
  hb = cmd.find_pairs("((byres "+selection+") and n;n)","((byres "+selection+") and n;o)",mode=1,cutoff=cutoff,angle=angle)
# sort the list for easier reading
  hb.sort(lambda x,y:(cmp(x[0][1],y[0][1])))

  for pairs in hb:
    for ind in [0,1]:
      cmd.iterate("%s and index %s" % (pairs[ind][0],pairs[ind][1]), 'print "%s/%3s`%s/%s/%s " % (chain,resn,resi,name,index),')
    print "%.2f" % cmd.distance(hb_list_name,"%s and index %s" % (pairs[0][0],pairs[0][1]),"%s and index %s" % (pairs[1][0],pairs[1][1]))
def list_hb(selection,selection2=None,cutoff=3.2,angle=55,mode=1,hb_list_name='hbonds'):
  """
  USAGE

  list_hb selection, [selection2 (default=None)], [cutoff (default=3.2)],
                     [angle (default=55)], [mode (default=1)],
                     [hb_list_name (default='hbonds')]

  The script automatically adds a requirement that atoms in the
  selection (and selection2 if used) must be either of the elements N or
  O.

  If mode is set to 0 instead of the default value 1, then no angle
  cutoff is used, otherwise the angle cutoff is used and defaults to 55
  degrees.

  e.g.
  To get a list of all H-bonds within chain A of an object
    list_hb 1abc & c. a &! r. hoh, cutoff=3.2, hb_list_name=abc-hbonds

  To get a list of H-bonds between chain B and everything else:
    list_hb 1tl9 & c. b, 1tl9 &! c. b

  """
  cutoff=float(cutoff)
  angle=float(angle)
  mode=float(mode)
# ensure only N and O atoms are in the selection
  selection = selection + " & e. n+o"
  if not selection2:
    hb = cmd.find_pairs(selection,selection,mode=mode,cutoff=cutoff,angle=angle)
  else:
    selection2 = selection2 + " & e. n+o"
    hb = cmd.find_pairs(selection,selection2,mode=mode,cutoff=cutoff,angle=angle)

# sort the list for easier reading
  hb.sort(lambda x,y:(cmp(x[0][1],y[0][1])))

  for pairs in hb:
    cmd.iterate("%s and index %s" % (pairs[0][0],pairs[0][1]), 'print "%1s/%3s`%s/%-4s " % (chain,resn,resi,name),')
    cmd.iterate("%s and index %s" % (pairs[1][0],pairs[1][1]), 'print "%1s/%3s`%s/%-4s " % (chain,resn,resi,name),')
    print "%.2f" % cmd.distance(hb_list_name,"%s and index %s" % (pairs[0][0],pairs[0][1]),"%s and index %s" % (pairs[1][0],pairs[1][1]))
def displacementUpdateBAll(objA, alnAri, objB, alnBri):
    print "This will take a while to go through the for loops. Give me around 3-5 minutes..."
    ### If residue is unassigned in one of the pdb files, we reset its value
    for x in range(len(alnAri)):
        s1 = objA + " and resi " + alnAri[x][0] + " and name " + str(alnAri[x][1])
        cmd.alter( s1, "b = " + str(-0.01))
    for x in range(len(alnBri)):
        s2 = objB + " and resi " + alnBri[x][0] + " and name " + alnBri[x][1]
        cmd.alter( s2, "b = " + str(-0.01))
    cmd.sort(objA); cmd.sort(objB)
    for x in range(len(alnAri)):
        s1 = objA + " and resi " + alnAri[x][0] + " and name " + alnAri[x][1]
        s2 = objB + " and resi " + alnAri[x][0] + " and name " + alnAri[x][1]
        ### Names starting with __ (underscores) are normally hidden by PyMOL
        tempObject = "__tempObject"
        Displacement = cmd.distance(tempObject, s1, s2)
        cmd.alter( s1, "b = " + str(Displacement))
        cmd.alter( s2, "b = " + str(Displacement))
        cmd.delete(tempObject)
    cmd.sort(objA); cmd.sort(objB)
    def testDistanceMode4(self):
        # create two 2-state objects
        cmd.fragment('gly', 'm1', origin=0)
        cmd.create('m1', 'm1', 1, 2)
        cmd.create('m2', 'm1', 1, 1)
        cmd.create('m2', 'm1', 1, 2)

        # shift one state by 5 and the other by 9 angstrom
        cs = cmd.get_coordset('m1', state=1, copy=0)
        cs += [5., 0., 0.]
        cs = cmd.get_coordset('m2', state=2, copy=0)
        cs += [9., 0., 0.]

        # creates one distance measure per state
        d = cmd.distance('d1', '?m1', '?m2', mode=4)

        # expecting 7 = (5 + 9) / 2
        self.assertAlmostEqual(d, 7.0, delta=1e-4)

        # one distance measurement has 2 * 3 coordinates
        d1states = cmd.get_session('d1', 1, 1, 0, 0)['names'][0][5][2]
        self.assertEqual(len(d1states[0][1]), 6)
        self.assertEqual(len(d1states[1][1]), 6)
def _draw_restraint(restraints, line_color, line_width, single, quiet, per_residue, per_atom, advanced_coloring):
    cnt = 0
    for restraint in restraints["connections"]:
        cnt += 1
        sele1 = 'segid %s and resi %s and name %s' % (
            restraint["src_segid"], restraint["src_resid"], restraint["src_atom"].replace("#", "*")
        )
        sele2 = 'segid %s and resi %s and name %s' % (
            restraint["dst_segid"], restraint["dst_resid"], restraint["dst_atom"].replace("#", "*")
        )

        if line_color is None:
            if advanced_coloring == 1:
                if restraints["distance"] < 2 or restraints["distance"] > 6:
                    line_color = "red"
                elif 5 < restraints["distance"] < 6:
                    line_color = "orange"
                else:
                    line_color = "splitpea"
            else:
                line_color = "yellow"

        if per_atom or per_residue:
            for x, y, z in [
                [restraint["dst_segid"], restraint["dst_resid"], restraint["dst_atom"]],
                [restraint["src_segid"], restraint["src_resid"], restraint["src_atom"]]
            ]:
                if per_atom:
                    label = "NOE_%s_%s_%s" % (x, y, z)
                elif per_residue:
                    label = "NOE_%s_%s" % (x, y)
                if advanced_coloring == 1:
                    label += ".%s_%i" % (restraints["ID"], cnt)

                try:
                    cmd.distance(label, sele1, sele2, quiet=quiet,
                                 width=line_width, gap=0, label=0)
                    _color_restraint(label, line_color)
                except CmdException:
                    print('FAILED: %s - %s' % (sele1, sele2))
                    print(restraints["ID"])
                    return 0

        else:
            if single:
                label = "NOE"

            else:
                label = "NOE_" + restraints["ID"]

            try:
                cmd.distance(label, sele1, sele2, quiet=quiet,
                             width=line_width, gap=0, label=0)

                _color_restraint(label, line_color)
            except CmdException:
                print('FAILED: %s - %s' % (sele1, sele2))
                print(restraints["ID"])
                return 0

    return 1
def angle_between_domains(selection1, selection2, method='align',
        state1=STATE, state2=STATE, visualize=1, quiet=1):
    '''
DESCRIPTION

    Angle by which a molecular selection would be rotated when superposing
    on a selection2.

    Do not use for measuring angle between helices, since the alignment of
    the helices might involve a rotation around the helix axis, which will
    result in a larger angle compared to the angle between helix axes.

USAGE

    angle_between_domains selection1, selection2 [, method ]

ARGUMENTS

    selection1 = string: atom selection of first helix

    selection2 = string: atom selection of second helix

    method = string: alignment command like "align" or "super" {default: align}

EXAMPLE

    fetch 3iplA 3iplB, async=0
    select domain1, resi 1-391
    select domain2, resi 392-475
    align 3iplA and domain1, 3iplB and domain1
    angle_between_domains 3iplA and domain2, 3iplB and domain2

SEE ALSO

    align, super, angle_between_helices
    '''
    import math

    try:
        import numpy
    except ImportError:
        print ' Error: numpy not available'
        raise CmdException

    state1, state2 = int(state1), int(state2)
    visualize, quiet = int(visualize), int(quiet)

    if cmd.is_string(method):
        try:
            method = cmd.keyword[method][0]
        except KeyError:
            print 'no such method:', method
            raise CmdException

    mobile_tmp = get_unused_name('_')
    cmd.create(mobile_tmp, selection1, state1, 1,  zoom=0)
    try:
        method(mobile=mobile_tmp, target=selection2, mobile_state=1,
                target_state=state2, quiet=quiet)
        mat = cmd.get_object_matrix(mobile_tmp)
    except:
        print ' Error: superposition with method "%s" failed' % (method.__name__)
        raise CmdException
    finally:
        cmd.delete(mobile_tmp)

    try:
        # Based on transformations.rotation_from_matrix
        # Copyright (c) 2006-2012, Christoph Gohlke

        R33 = [mat[i:i+3] for i in [0,4,8]]
        R33 = numpy.array(R33, float)

        # direction: unit eigenvector of R33 corresponding to eigenvalue of 1
        w, W = numpy.linalg.eig(R33.T)
        i = w.real.argmax()
        direction = W[:, i].real

        # rotation angle depending on direction
        m = direction.argmax()
        i,j,k,l = [
            [2,1,1,2],
            [0,2,0,2],
            [1,0,0,1]][m]
        cosa = (R33.trace() - 1.0) / 2.0
        sina = (R33[i, j] + (cosa - 1.0) * direction[k] * direction[l]) / direction[m]

        angle = math.atan2(sina, cosa)
        angle = abs(math.degrees(angle))
    except:
        print ' Error: rotation from matrix failed'
        raise CmdException

    if not quiet:
        try:
            # make this import optional to support running this script standalone
            from .querying import centerofmass, gyradius
        except (ValueError, ImportError):
            gyradius = None
            try:
                # PyMOL 1.7.1.6+
                centerofmass = cmd.centerofmass
            except AttributeError:
                centerofmass = lambda s: cpv.scale(cpv.add(*cmd.get_extent(s)), 0.5)

        center1 = centerofmass(selection1)
        center2 = centerofmass(selection2)
        print ' Angle: %.2f deg, Displacement: %.2f angstrom' % (angle, cpv.distance(center1, center2))

        if visualize:
            center1 = numpy.array(center1, float)
            center2 = numpy.array(center2, float)
            center = (center1 + center2) / 2.0

            if gyradius is not None:
                rg = numpy.array(gyradius(selection1), float)
            else:
                rg = 10.0

            h1 = numpy.cross(center2 - center1, direction)
            h2 = numpy.dot(R33, h1)
            h1 *= rg / cpv.length(h1)
            h2 *= rg / cpv.length(h2)

            for pos in [center1, center2, center1 + h1, center1 + h2]:
                cmd.pseudoatom(mobile_tmp, pos=list(pos), state=1)

            # measurement object for angle and displacement
            name = get_unused_name('measurement')
            cmd.distance(name, *['%s`%d' % (mobile_tmp, i) for i in [1,2]])
            cmd.angle(name, *['%s`%d' % (mobile_tmp, i) for i in [3,1,4]])

            # CGO arrow for axis of rotation
            visualize_orientation(direction, center1, rg, color='blue')

            cmd.delete(mobile_tmp)

    return angle
def test():
  cmd.distance("test","resi %s and name %s"%(2, "CA") , "resi %s and name %s"%(3, "CA") )
Exemple #54
0
 def execute(self, result):
     self.create_FMN_colors()
     if result == "Show edges":
         mat = self.read_distfile(self.distfilename)
         nrow = len(mat)
         ncol = nrow
         cutoff = float(self.cutoff.getvalue())
         try:
             self.changeRepresentation(self.object.getvalue())
         except:
             print "Error: cannot change representation of object %s!" % self.object.getvalue()
         try:
             for d in stored.distancelist:
                 cmd.delete(d)
         except:
             pass
         try:
             stored.distancelist = []
             for i in range(nrow):
                 for j in range(i, ncol):
                     if mat[i][j] > cutoff:
                         cmd.distance(
                             "%s_%s" % (i + 1, j + 1),
                             "name CA and resi %s" % (i + 1),
                             "name CA and resi %s" % (j + 1),
                         )
                         cmd.hide("label", "%s_%s" % (i + 1, j + 1))
                         cmd.set("dash_gap", 0, "%s_%s" % (i + 1, j + 1))
                         cmd.set("dash_width", 4, "%s_%s" % (i + 1, j + 1))
                         if self.colorscale.getvalue() == "greyscale":
                             cmd.color(
                                 "grey%02d" % int((mat[i][j] - cutoff) / (self.max - cutoff) * 99),
                                 "%s_%s" % (i + 1, j + 1),
                             )
                         if self.colorscale.getvalue() == "colorscale":
                             cmd.color("FMN%03d" % (int((mat[i][j] / self.max * 49)) + 1), "%s_%s" % (i + 1, j + 1))
                         if self.dashproportional.getvalue() == "yes":
                             cmd.set("dash_radius", (mat[i][j] / self.max) * 0.25, "%s_%s" % (i + 1, j + 1))
                         stored.distancelist.append("%s_%s" % (i + 1, j + 1))
         except:
             print "Error: inconsistency in the residue numbering!"
     else:
         if result == "Update Cutoff Range":
             mat = self.read_distfile(self.distfilename)
             nrow = len(mat)
             ncol = nrow
             minV = self.min
             maxV = self.max
             for i in range(nrow):
                 for j in range(i, ncol):
                     if self.min > mat[i][j]:
                         stored.minValue = mat[i][j] - self.incr
                         self.min = stored.minValue
                         minV = mat[i][j]
                     if self.max < mat[i][j]:
                         stored.maxValue = mat[i][j] + self.incr
                         self.max = stored.maxValue
                         maxV = mat[i][j]
             if minV >= 0.0 and self.min < 0.0:
                 self.min = 0.0
             stored.midValue = self.max - (self.max - self.min) / 2
             self.mid = stored.midValue
             print "max %8.3f" % maxV
             print "min %8.3f" % minV
             stored.filename = self.distfilename.getvalue()
             self.dialog.withdraw()
         else:
             if result == "Remove edges":
                 try:
                     for d in stored.distancelist:
                         cmd.delete(d)
                 except:
                     pass
             else:
                 if __name__ == "__main__":
                     self.parent.destroy()
                 else:
                     self.dialog.withdraw()
Exemple #55
0
def displayInPyMOL(outdir, selectedPDBChain, atomNumbersProbDic):
    pdbCWMs = os.path.join(outdir, '%s_withConservedWaters.pdb' % selectedPDBChain)
    pdb = os.path.join(outdir, '%s.pdb' % selectedPDBChain)
    h_bond_dist = 4.0

    queryProteinCWMs = '%s_withConservedWaters' % selectedPDBChain

    cmd.load(pdbCWMs)
    cmd.orient(queryProteinCWMs)
    cmd.h_add(queryProteinCWMs)

    cmd.select('cwm_protein','polymer and %s' % queryProteinCWMs)
    cmd.select('cwm_waters','resn hoh and %s' % queryProteinCWMs)
    cmd.select('cwm_ligand','organic and %s' % queryProteinCWMs)

    cmd.select('don', '(elem n,o and (neighbor hydro)) and %s' % queryProteinCWMs)
    cmd.select('acc', '(elem o or (elem n and not (neighbor hydro))) and %s' % queryProteinCWMs)
    # h bonds between protein and conserved waters
    cmd.distance ('PW_HBA', '(cwm_protein and acc)','(cwm_waters and don)', h_bond_dist)
    cmd.distance ('PW_HBD', '(cwm_protein and don)','(cwm_waters and acc)', h_bond_dist)
    # h bonds between ligands and conserved waters
    cmd.distance ('LW_HBA', '(cwm_ligand and acc)','(cwm_waters and don)', h_bond_dist)
    cmd.distance ('LW_HBD', '(cwm_ligand and don)','(cwm_waters and acc)', h_bond_dist)
    # h bonds in between conserved waters
    cmd.distance ('HW_HBA', '(cwm_waters and acc)','(cwm_waters and don)', h_bond_dist)
    cmd.distance ('HW_HBD', '(cwm_waters and don)','(cwm_waters and acc)', h_bond_dist)

    cmd.delete('don')
    cmd.delete('acc')

    cmd.set('dash_color','yellow')
    cmd.set('dash_gap',0.3)
    cmd.set('dash_length',0.2)
    cmd.set('dash_round_ends','on')
    cmd.set('dash_width',3)

    # color and display
    cmd.util.cbam('cwm_ligand')
    cmd.show_as('sticks','cwm_ligand')

    MinDoc = min(atomNumbersProbDic.values())
    MaxDoc = max(atomNumbersProbDic.values())
    cmd.create ('conserved_waters','cwm_waters')
    for key, value in atomNumbersProbDic.items():
        cmd.alter('/conserved_waters//A/HOH`%s/O' % key, 'b=%s' % value)

    cmd.spectrum('b', 'red_blue', 'conserved_waters',minimum=MinDoc, maximum=MaxDoc)
    cmd.ramp_new('DOC', 'conserved_waters', range = [MinDoc,MaxDoc], color = '[red,blue]')
    cmd.set('sphere_scale',0.40,'conserved_waters')
    cmd.show_as('spheres','conserved_waters')

    cmd.hide('labels','*_HB*')
    cmd.remove('(hydro) and conserved_waters')
    cmd.remove('(hydro) and %s' % queryProteinCWMs)

    cmd.util.cbac('cwm_protein')
    cmd.set('transparency', 0.2)
    cmd.show('surface', 'cwm_protein')
    cmd.set('surface_color', 'gray', 'cwm_protein')

    cmd.load(pdb)
    cmd.create('all waters', 'resn hoh and %s' % selectedPDBChain)
    cmd.color('red','ss h and %s' % selectedPDBChain)
    cmd.color('yellow','ss s and %s' % selectedPDBChain)
    cmd.color('green','ss l+ and %s' % selectedPDBChain)
    cmd.show_as('cartoon', selectedPDBChain)
    cmd.set('ray_shadows', 0)
Exemple #56
0
def plot_noe(filename, selection='', line_color='gray20', line_width='1.0', single=0, quiet=1, aria=0, per_atom=0, per_residue=1):
    """
DESCRIPTION

    A function for plotting XPLOR NOE restraints on a structure

ARGUMENTS

    filename = string: The filename of the NOE retraint file in XPLOR NIH format.

    selection = string: atom selection {default: all}

    line_color = string: The color for the NOE lines. {default: black}

    line_width = float: The thickness of the NOE lines. {default: 1.0}

    aria = integer: Name NOEs after Aria IDs.

    per_atom: Group NOEs on atom basis

    per_residue: Group NOEs on residue basis (default)

NOE Restraint Format Example

    assign (residue 5 and name HB#) (residue 21 and name HA) 3.0 0.7 0.7

EXAMPLE

    PyMOL> plot_noe noe_short.tbl
    """
    from pymol.parsing import split

    single, quiet, aria, per_residue, per_atom = int(single), int(quiet), int(aria), int(per_residue), int(per_atom)

    count = 0
    parent_id = None

    rgx_restraint = re.compile(
                        r"""
                            \s*(?P<parent>\w*)\s+\(
                            (segid\s+\"\s*(?P<src_segid>[\w\d]+)\"\s+and\s+)?
                            resid\s+(?P<src_resid>\d+)\s+and\s+
                            name\s+(?P<src_atom>[\w\d]+)
                            \)\s+\(
                            (segid\s+\"\s+(?P<dst_segid>[\w\d]+)\"\s+and\s+)?
                            resid\s*(?P<dst_resid>\d+)\s+and\s+
                            name\s*(?P<dst_atom>[\w\d]+)
                            \)
                            (\s+(?P<dist>[\d\.]+))?
                            (.*id=(?P<ID>\d+))?
                            .*
                        """, re.X)


    for line in open(filename):
        restraint = rgx_restraint.match(line)
        count += 1

        if restraint:
            restraint = restraint.groupdict()

            if restraint["src_segid"] == None:
                restraint["src_segid"] = "A"

            if restraint["dst_segid"] == None:
                restraint["dst_segid"] = "A"

            if restraint["parent"][:4].upper() == "ASSI":
                parent = restraint

            sele1 = 'segid %s and resi %s and name %s' % (restraint["src_segid"], restraint["src_resid"], restraint["src_atom"])
            sele2 = 'segid %s and resi %s and name %s' % (restraint["dst_segid"], restraint["dst_resid"], restraint["dst_atom"])

            if single:
                label = "NOE"

            elif aria and restraint["ID"]:
                label = "NOE_" + restraint["ID"]
            elif aria and parent and parent["ID"]:
                label = "NOE_" + parent["ID"]

            elif per_atom:
                label = "NOE_%s_%s_%s" % (restraint["dst_segid"], restraint["dst_resid"], restraint["dst_atom"])
            elif per_residue:
                label = "NOE_%s_%s" % (restraint["dst_segid"], restraint["dst_resid"])

            elif restraint["parent"][:4].upper() == "ASSI":
                label = parent_id
            else:
                parent_id = "NOE_%d" % count
                label = parent_id

            try:
                cmd.distance(label, sele1, sele2, quiet=quiet,
                        width=line_width, gap=0, label=0)
            except CmdException:
                print 'FAILED: %s - %s' % (sele1, sele2)
                continue

            cmd.set("dash_color", line_color, label)
        else:
            print line

    cmd.order("NOE*", "yes")

    if not quiet:
        print ' Info: Created distance objects for %d restraints' % (count)
def dehydron(selection='all', angle_range=40., max_distance=3.5, desolv=6.5, min_wrappers=19, max_wrappers=35, quiet=0):
    '''
DESCRIPTION

    dehydron calculator

USAGE

    wrappy [ selection [, angle_range [, max_distance [, desolv [, min_wrappers [, max_wrappers ]]]]]]
    '''

    angle, max_distance = float(angle_range), float(max_distance)
    desolv, min_wrappers, max_wrappers = float(desolv), int(min_wrappers), int(max_wrappers)
    quiet = int(quiet)

    DH_name = cmd.get_legal_name('DH_%s' % selection)
    cmd.delete(DH_name)
    HBA_name = cmd.get_legal_name('HBA_%s' % selection)
    cmd.delete(HBA_name)
    HBO_name = cmd.get_legal_name('HBO_%s' % selection)
    cmd.delete(HBO_name)

    selection_hb = '((%s) and polymer)' % (selection)
    hb = cmd.find_pairs("((byres " + selection_hb + ") and n. n)", "((byres " + selection_hb + ") and n. o)", mode=1, cutoff=max_distance, angle=angle_range)

    cmd.select('_nonpolar', '(elem C) and not (solvent or (elem N+O) extend 1)', 0)
    try:
        cmd.select('_selection', '%s' % selection, 0)
    except:
        pass

    low_sel = []
    mean_sel = []
    high_sel = []
    total_wrappers = 0
    for pairs in hb:
        wrappers = cmd.count_atoms('((%s and _nonpolar and _selection) within %f of byca (%s`%d %s`%d))' %
                                   ((pairs[0][0], desolv) + pairs[0] + pairs[1]))
        total_wrappers = total_wrappers + wrappers
        cmd.iterate(pairs[0], 'stored.donor = chain, resi, resn')
        cmd.iterate(pairs[1], 'stored.aceptor = chain, resi, resn')
        if wrappers < min_wrappers:
            cmd.distance(DH_name, pairs[0], pairs[1])
            line = (wrappers, '%12s%4s%6s%6s | %12s%4s%6s%6s |%7s        below' % (pairs[0][0], stored.donor[0], stored.donor[2], stored.donor[1], pairs[1][0], stored.aceptor[0], stored.aceptor[2], stored.aceptor[1], wrappers))
            low_sel.append(line)
        elif wrappers < max_wrappers:
            cmd.distance(HBA_name, pairs[0], pairs[1])
            line = (wrappers, '%12s%4s%6s%6s | %12s%4s%6s%6s |%7s      average' % (pairs[0][0], stored.donor[0], stored.donor[2], stored.donor[1], pairs[1][0], stored.aceptor[0], stored.aceptor[2], stored.aceptor[1], wrappers))
            mean_sel.append(line)
        else:
            cmd.distance(HBO_name, pairs[0], pairs[1])
            line = (wrappers, '%12s%4s%6s%6s | %12s%4s%6s%6s |%7s         over' % (pairs[0][0], stored.donor[0], stored.donor[2], stored.donor[1], pairs[1][0], stored.aceptor[0], stored.aceptor[2], stored.aceptor[1], wrappers))
            high_sel.append(line)

    cmd.delete('_nonpolar')
    cmd.delete('_selection')
    # compute the z_scores. Useful for protein structure validation.
    stored.ResiduesNames = []
    cmd.iterate('(name ca)', 'stored.ResiduesNames.append((resn))')
    total_residues = float(len(stored.ResiduesNames))
    z_score_wrappers = ((total_wrappers / total_residues) - 17) / 2
    z_score_hb = ((len(hb) / total_residues) - 0.62) / 0.06

    if len(low_sel) > 0:
        cmd.show_as('dashes', DH_name)
        cmd.color('red', DH_name)
        low_sel.sort()
    if len(mean_sel) > 0:
        cmd.show_as('dashes', HBA_name)
        cmd.color('yellow', HBA_name)
        mean_sel.sort()
    if len(high_sel) > 0:
        cmd.show_as('dashes', HBO_name)
        cmd.color('green', HBO_name)
        high_sel.sort()

    if not quiet:
        hb.sort()
        print "--------------------------------------------------------------------"
        print "------------------------------Results ------------------------------"
        print "--------------------------------------------------------------------"
        print "           Donor             |            Aceptor           |"
        print "    Object   Chain Residue   |     Object   Chain Residue   | # wrappers  wrapping"
        for line in low_sel:
            print line[1]
        for line in mean_sel:
            print line[1]
        for line in high_sel:
            print line[1]
        print '\nProtein global statistics:'
        print '\nz-score wrappers = %6.2f\nz-score hydrogen bonds = %6.2f\n' % (z_score_wrappers, z_score_hb)
    elif not quiet and len(hb) != 0:
        print '\n - no dehydrons were found - '
        print '\nz-score hydrogen bonds = %6.2f\n' % (z_score_hb)
    else:
        print '\n - no hydrogen bonds were found - '
Exemple #58
0
def show_restraints( restraint_file , sele = "all", show_sidechains = True, print_label = False ):

	tp = [0,0,0]
	fp = [0,0,0]

	restraint_count = 0
	restraint_count_shown = 0


	for line in open(restraint_file,'r'):

		if line.strip() == "":
			continue

		res = line.split()

		restraint_count += 1
		label = "_dist_" + str(restraint_count)

		myspace = {'atom_names_1': [],'atom_names_2': [], 'resn1': [], 'resn2' : []}
		cmd.iterate( sele + " and resi " + res[2], 'atom_names_1.append(name)', space=myspace)
		cmd.iterate( sele + " and resi " + res[4], 'atom_names_2.append(name)', space=myspace)
		cmd.iterate( sele + " and resi " + res[2], 'resn1.append(resn)', space=myspace)
		cmd.iterate( sele + " and resi " + res[4], 'resn2.append(resn)', space=myspace)

		aa1 = rename_atoms( res[1], myspace[ 'resn1' ], myspace[ 'atom_names_1' ] )
		aa2 = rename_atoms( res[3], myspace[ 'resn2' ], myspace[ 'atom_names_2' ] )


		if not aa1 in myspace["atom_names_1"]:
			temp = aa1[-1]+aa1[:-1]
			if temp in  myspace["atom_names_1"]:
				aa1 = temp
			else:
				print "Problem finding %s/%s" %(res[2],aa1)
				continue

		if not aa2 in  myspace["atom_names_2"]:
			temp = aa2[-1]+aa2[:-1]
			if temp in  myspace["atom_names_2"]:
				aa2 = temp
			else:
				print "Problem finding %s/%s" %(res[4],aa2)
				continue

		dist = float(cmd.distance(label,"(/%s///%s/%s)"%(sele, res[2], aa1), "(/%s///%s/%s)"%(sele, res[4], aa2)))

		if show_sidechains == True:
			# get colors of sidechains and color accordingly
			pymol.color_list = []
			cmd.iterate("/"+sele+"///"+res[2]+"/"+aa1, 'pymol.color_list.append(color)')
			cmd.show("lines", "%s and resi %s" %(sele,res[2]) )
			cmd.color(pymol.color_list[0], "%s and resi %s" %(sele,res[2]) )
			pymol.color_list = []
			cmd.iterate("/" + sele+"///"+res[4]+"/"+aa2, 'pymol.color_list.append(color)')
			cmd.show("lines", "%s and resi %s" %(sele,res[4]) )
			cmd.color(pymol.color_list[0], "%s and resi %s" %(sele,res[4]) )

		#color restraints based on actual distance
		lb = 0
		ub = 100
		if res[5].lower() == "sigmoid":
			ub = float(res[6])
			lb = 0.0
		elif res[5].lower() == "bounded":
			ub = float(res[7])
			lb = float(res[6])
		else:
			print "Function not recognized. Setting lower and upperbound to 0 and 100 ... "


		ff = ""

		if dist <= ub and dist >= lb:
			color = "blue"
			tp[0] += 1
			tp[1] += 1
			tp[2] += 1
			ff = "SATISFIED"
		elif dist <= ub + 0.5 and dist >= lb - 0.5:
			color = "purpleblue"
			fp[0] += 1
			tp[1] += 1
			tp[2] += 1
		elif dist <= ub + 0.5 and dist >= lb - 0.5:
			color = "magenta"
			tp[2] += 1
			fp[0] += 1
			fp[1] += 1
		else:
			color = "red"
			fp[0] += 1
			fp[1] += 1
			fp[2] += 1

		print "%s/%s %s/%s with distance %.2f   Restraint: %.2f - %.2f     %s"%(res[2], aa1, res[4], aa2, dist, lb, ub, ff)

		restraint_count_shown += 1
		cmd.color(color, label)
		if not print_label:
			cmd.hide("label",label)
		cmd.set('dash_gap','0')
	print "Total Restraints: %.0f"%restraint_count
	print "Shown Restraints: %.0f"%restraint_count_shown
	print "Padding: [0, 0.5, 1]"
	print "Satisfied Restraints: " + str(tp)
	print "Unsatisfied Restraints: " + str(fp)
def plot_noe(filename, selection='', line_color='gray20', line_width='1.0', single=0, quiet=1):
    """
DESCRIPTION

    A function for plotting XPLOR NOE restraints on a structure

ARGUMENTS

    filename = string: The filename of the NOE retraint file in XPLOR NIH format.

    selection = string: atom selection {default: all}

    line_color = string: The color for the NOE lines. {default: black}

    line_width = float: The thickness of the NOE lines. {default: 1.0}

NOE Restraint Format Example

    assign (residue 5 and name HB#) (residue 21 and name HA) 3.0 0.7 0.7

EXAMPLE

    PyMOL> plot_noe noe_short.tbl
    """
    from pymol.parsing import split

    single, quiet = int(single), int(quiet)

    count = 0

    for line in open(filename):
        line = line.replace('(', ' (').replace(')', ') ').replace('#', '*')

        a = filter(None, split(line, ' \t'))
        if len(a) < 4 or not a[0].startswith('assi'):
            continue

        try:
            float(a[3])
        except ValueError:
            continue

        sele1, sele2 = a[1:3]

        if selection:
            sele1 = '(%s) and (%s)' % (selection, sele1)
            sele2 = '(%s) and (%s)' % (selection, sele2)

        label = single and "NOE" or ("NOE_%d" % (count + 1))

        try:
            cmd.distance(label, sele1, sele2, quiet=quiet,
                    width=line_width, gap=0, label=0)
        except CmdException:
            print 'FAILED: %s - %s' % (sele1, sele2)
            continue

        cmd.set("dash_color", line_color, label)
        count += 1

    if not quiet:
        print ' Info: Created distance objects for %d restraints' % (count)
def stix():

	backbone_colorlist = ['plutonium','wheat','green', 'yellow', 'violet', 'cyan',    \
		   'salmon', 'lime', 'slate', 'magenta', 'orange', 'marine', \
		   'olive', 'forest', 'firebrick', 'chocolate' ]
	curr_bb_color = 0

 	carbon_colorlist = ['teal', 'wheat', 'grey', 'pink' ]
	curr_carbon_color = 0

	# Derive selections for the interface, color by chain
	cmd.select("interface", "none")
	cmd.select("heavy_interface", "none")
	selectPolarProtons("polar_protons")
	selectApolarProtons("apolar_protons")
	alphabet = list(('abcdefghijklmnopqrstuvwxyz').upper())
	for letter in alphabet:
		chainname = "chain"+letter
		cmd.select( chainname, "chain %s and not hetatm and not symbol w"%(letter) )

		# Check whether any protein atoms exist with this chain ID
		# JK Later, put in a special "non-interface" case for L/H antibody chains
		if cmd.count_atoms("chain%s"%(letter))>0:
			interfacename = "interface"+letter
			cmd.select("not_this_chain", "not hetatm and not symbol w and not %s"%(chainname) )
			cmd.select(interfacename, "byres %s and (not_this_chain around 4.0)"%(chainname) )
			cmd.select("heavy_%s"%(interfacename), "%s and not apolar_protons"%(interfacename))
			cmd.select("interface", "interface or %s"%(interfacename) )
			cmd.select("heavy_interface", "heavy_interface or heavy_%s"%(interfacename) )
			cmd.delete("not_this_chain")

			cmd.color(backbone_colorlist[curr_bb_color], chainname)
			colorCPK(chainname,backbone_colorlist[curr_bb_color])
			curr_bb_color = curr_bb_color+1
			if(curr_bb_color == len(backbone_colorlist)):
				curr_bb_color = 0

			#colorCPK(interfacename,carbon_colorlist[curr_carbon_color])
			curr_carbon_color = curr_carbon_color+1
			if(curr_carbon_color == len(carbon_colorlist)):
				curr_carbon_color = 0
			cmd.color("white", "%s and polar_protons"%(interfacename))

		else:
			cmd.delete(chainname)

	cmd.delete("apolar_protons")
	cmd.delete("polar_protons")

	# Show the interface in sticks, colored cpk
	#cmd.hide( "cartoon", "interface" )
	cmd.show( "sticks", "not hydro" )
	cmd.zoom("interface")

	cmd.show( "cartoon", "(not interface) or byres(neighbor(interface)) or byres(neighbor(byres(neighbor(interface))))" )

	# Show interface waters as small purple spheres
	cmd.select( "interface_water", "(symbol w or resn HOH) and (interface around 8.0)")
	if cmd.count_atoms("interface_water")>0:
		# Put the waters in a separate object, so that we can scale their radii
		newwatername = name+"waters"
		cmd.create(newwatername, "interface_water")
		cmd.remove("interface_water")
		cmd.color("purple", newwatername)
		cmd.show( "spheres", newwatername )
		cmd.set( "sphere_scale", 0.1, newwatername )

	else:
		cmd.delete("interface_water")

	# Show interface ligands as pink sticks
	cmd.select( "interface_hetero", "(not symbol w and not resn HOH) and (hetatm and not symbol w and not resn WSS) and (interface around 4.5)")
	if cmd.count_atoms("interface_hetero")>0:
		cmd.color("pink", "interface_hetero")
		cmd.show( "sticks", "interface_hetero" )
	else:
		cmd.delete("interface_hetero")
	
	    # Show polar contacts
        #cmd.distance("hbonds","interfaceA","interfaceB",3.2,mode=1)
        cmd.distance("hbonds","interfaceA","interfaceB",4.5,mode=2)
        #cmd.distance("hbonds","interfaceA","interfaceB",3.2,mode=3)


        cmd.hide("labels")
        cmd.hide("lines")
	cmd.select("none")