Esempio n. 1
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
Esempio n. 2
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
Esempio n. 3
0
def create_hbonds( lines, name ):

	model = cmd.get_model(name)

	# Ron Jacak's cool monster regex, borrowed from the Rosetta Pymol Plugin
	hb_re = re.compile("(?:PROT|BASE) \s*[A-Z]+ \s*\d+ \s*(\d+) ([ A-Z]) \s*([A-Z0-9]+) \s*[A-Z]+ \s*\d+ \s*(\d+) ([ A-Z]) \s*([A-Z0-9]+)\s* (-?[\d\.]*)")
	hbonds = []
	for line in lines:
		match = hb_re.search(line)
		if match == None: continue
		(d_resi, d_chain, d_atom, a_resi, a_chain, a_atom, energy) = match.groups()
		energy = float(energy)

		if energy < -0.05: # ingores very weak "hydrogen bonds"

			d_addr = '/%s//%s/%s/%s' % ( name, d_chain, d_resi, d_atom )
			a_addr = '/%s//%s/%s/%s' % ( name, a_chain, a_resi, a_atom )

			d_atm = model.atom[ cmd.index(d_addr)[0][1] - 1 ]
			a_atm = model.atom[ cmd.index(a_addr)[0][1] - 1 ]

			if energy <= -0.9: colorscale = 1.0
			else: colorscale = -1 * energy + 0.1 # ratio to strong, with offset
			hbonds.extend( hbond( d_atm, a_atm, colorscale, colorscale, 0.0 ) )
	cmd.load_cgo( hbonds, 'hb_%s' % name )
Esempio n. 4
0
def create_hbonds(lines, name):

    model = cmd.get_model(name)

    # Ron Jacak's cool monster regex, borrowed from the Rosetta Pymol Plugin
    hb_re = re.compile(
        "(?:PROT|BASE) \s*[A-Z]+ \s*\d+ \s*(\d+) ([ A-Z]) \s*([A-Z0-9]+) \s*[A-Z]+ \s*\d+ \s*(\d+) ([ A-Z]) \s*([A-Z0-9]+)\s* (-?[\d\.]*)"
    )
    hbonds = []
    for line in lines:
        match = hb_re.search(line)
        if match == None: continue
        (d_resi, d_chain, d_atom, a_resi, a_chain, a_atom,
         energy) = match.groups()
        energy = float(energy)

        if energy < -0.05:  # ingores very weak "hydrogen bonds"

            d_addr = '/%s//%s/%s/%s' % (name, d_chain, d_resi, d_atom)
            a_addr = '/%s//%s/%s/%s' % (name, a_chain, a_resi, a_atom)

            d_atm = model.atom[cmd.index(d_addr)[0][1] - 1]
            a_atm = model.atom[cmd.index(a_addr)[0][1] - 1]

            if energy <= -0.9: colorscale = 1.0
            else:
                colorscale = -1 * energy + 0.1  # ratio to strong, with offset
            hbonds.extend(hbond(d_atm, a_atm, colorscale, colorscale, 0.0))
    cmd.load_cgo(hbonds, 'hb_%s' % name)
Esempio n. 5
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)
Esempio n. 6
0
 def test_set_raw_alignment(self):
     cmd.fab('ACDEF', 'm1')
     cmd.fab('CDE', 'm2')
     index_m1 = [('m1', 12), ('m1', 23), ('m1', 35)]
     index_m2 = [('m2',  2), ('m2', 13), ('m2', 25)]
     raw = [list(t) for t in zip(index_m1, index_m2)]
     cmd.set_raw_alignment('aln', raw)
     self.assertEqual(cmd.index('m1 & aln'), index_m1)
     self.assertEqual(cmd.index('m2 & aln'), index_m2)
Esempio n. 7
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
Esempio n. 8
0
    def from_alignment(self, mobile, target, aln_obj):
        '''
        Use alignment given by "aln_obj" (name of alignment object)
        '''
        from .selecting import wait_for
        wait_for(aln_obj)

        self.mobile = '(%s) and %s' % (mobile, aln_obj)
        self.target = '(%s) and %s' % (target, aln_obj)
        if self.check():
            return

        # difficult: if selections spans only part of the alignment or
        # if alignment object covers more than the two objects, then we
        # need to pick those columns that have no gap in any of the two
        # given selections

        mobileidx = set(cmd.index(mobile))
        targetidx = set(cmd.index(target))
        mobileidxsel = []
        targetidxsel = []

        for column in cmd.get_raw_alignment(aln_obj):
            mobiles = mobileidx.intersection(column)
            if len(mobiles) == 1:
                targets = targetidx.intersection(column)
                if len(targets) == 1:
                    mobileidxsel.extend(mobiles)
                    targetidxsel.extend(targets)

        self.mobile = cmd.get_unused_name('_mobile')
        self.target = cmd.get_unused_name('_target')
        self.temporary.append(self.mobile)
        self.temporary.append(self.target)

        mobile_objects = set(idx[0] for idx in mobileidxsel)
        target_objects = set(idx[0] for idx in targetidxsel)

        if len(mobile_objects) == len(target_objects) == 1:
            mobile_index_list = [idx[1] for idx in mobileidxsel]
            target_index_list = [idx[1] for idx in targetidxsel]
            cmd.select_list(self.mobile,
                            mobile_objects.pop(),
                            mobile_index_list,
                            mode='index')
            cmd.select_list(self.target,
                            target_objects.pop(),
                            target_index_list,
                            mode='index')
        else:
            cmd.select(self.mobile,
                       ' '.join('%s`%d' % idx for idx in mobileidxsel))
            cmd.select(self.target,
                       ' '.join('%s`%d' % idx for idx in targetidxsel))
Esempio n. 9
0
def drawHydroPolar(path1, path2, threshold=0, edge_norm=None, scale_norm=True, norm_expected=False, fromstruct=None, **kwargs):

    if norm_expected:
        scale_norm = False

    if fromstruct == None:
        cmd.select("hydrophobic", "(elem C or (all within 2 of elem C) and elem H)")
        cmd.select("polar", "not hydrophobic")
    else:
        cmd.load(fromstruct, 'struct')
        cmd.select("hydrophobic", "struct and (elem C or (all within 2 of elem C) and elem H)")
        cmd.select("polar", "not hydrophobic and struct")

    hydro = [elt[1] for elt in cmd.index(selection="hydrophobic")]
    polar = [elt[1] for elt in cmd.index(selection="polar")]

    if fromstruct != None:
        cmd.delete('struct')

    normalization_factor = len(hydro)**2/len(polar)**2

    offset = min(hydro[0], polar[0])
    sel_hydro = "index "+" ".join([str(elt-offset) for elt in hydro])
    sel_polar = "index "+" ".join([str(elt-offset) for elt in polar])

    drawNetwork(path1, path2, sele=sel_hydro, edge_color1=(1, 0.86, 0.73), edge_color2=(1, 0.86, 0), 
                name1="hydro1", name2="hydro2", name_nodes="hydrophobic_nodes", threshold=threshold, 
                edge_norm=edge_norm, norm_expected=norm_expected, **kwargs)

    if scale_norm:
        t2 = threshold/normalization_factor
        print("Normalization factor polar:", normalization_factor)
        edge_norm2 = None if edge_norm is None else edge_norm/normalization_factor 
    else:
        t2 = threshold
        edge_norm2 = edge_norm

    drawNetwork(path1, path2, sele=sel_polar, edge_color1=(0.68, 0.85, 0.90), edge_color2=(0.25, 0.41, 0.88), 
                name1="polar1", name2="polar2", name_nodes="polar_nodes", threshold=t2, 
                edge_norm=edge_norm2,  norm_expected=norm_expected, keep_previous=True, **kwargs)

    if scale_norm:
        t3 = threshold*len(polar)/len(hydro)
        print("Normalization factor mixed:", len(hydro)/len(polar))
        edge_norm3 = None if edge_norm is None else edge_norm*len(polar)/len(hydro)
    else:
        t3 = threshold
        edge_norm3 = edge_norm

    drawNetwork(path1, path2, sele1=sel_polar, sele2=sel_hydro, edge_color1=(0.60, 0.98, 0.60), edge_color2=(0, 0.50, 0), 
                name1="mixed1", name2="mixed2", name_nodes="mixed_nodes", threshold=t3, 
                edge_norm=edge_norm3, norm_expected=norm_expected, keep_previous=True, **kwargs)
Esempio n. 10
0
    def get_Atom(self, name):

        info = []

        try:
            # test if the click is on the protein
            list = cmd.index(name + " & " + self.TargetName)

            if len(list) > 0:
                atoms = cmd.get_model(name, state=1)
                for at in atoms.atom:
                    info.extend([ at.index, at.resn, at.resi, at.chain, at.name,
                                  at.coord[0], at.coord[1], at.coord[2] ])
                    break

            else:
                self.ErrorStatus = [ "You can only select side-chains from the object " + self.TargetName + ". Try again." ]
                return info

            cmd.deselect()

        except:
            self.ErrorStatus = [ "An error occured while retrieving atom info. Try again." ]
            self.Quit_Wizard()
        
        return info
Esempio n. 11
0
def set_phipsi(selection, phi=None, psi=None):
    '''
DESCRIPTION

    Set phi/psi angles for all residues in selection.

SEE ALSO

    set_phi, set_psi, set_dihedral, phi_psi, cmd.get_phipsi, DynoPlot
    '''
    for model, index in cmd.index('byca (' + selection + ')'):
        atsele = [
            'first ((%s`%d) extend 2 and name C)' % (model, index),  # prev C
            'first ((%s`%d) extend 1 and name N)' % (model, index),  # this N
            '(%s`%d)' % (model, index),  # this CA
            'last ((%s`%d) extend 1 and name C)' % (model, index),  # this C
            'last ((%s`%d) extend 2 and name N)' % (model, index),  # next N
        ]
        try:
            if phi is not None:
                cmd.set_dihedral(atsele[0], atsele[1], atsele[2], atsele[3],
                                 phi)
            if psi is not None:
                cmd.set_dihedral(atsele[1], atsele[2], atsele[3], atsele[4],
                                 psi)
        except:
            print ' Error: cmd.set_dihedral failed'
Esempio n. 12
0
def set_phipsi(selection, phi=None, psi=None):
    '''
DESCRIPTION

    Set phi/psi angles for all residues in selection.

SEE ALSO

    set_phi, set_psi, set_dihedral, phi_psi, cmd.get_phipsi, DynoPlot
    '''
    for model, index in cmd.index('byca (' + selection + ')'):
        atsele = [
            'first ((%s`%d) extend 2 and name C)' % (model, index),  # prev C
            'first ((%s`%d) extend 1 and name N)' % (model, index),  # this N
            '(%s`%d)' % (model, index),                             # this CA
            'last ((%s`%d) extend 1 and name C)' % (model, index),  # this C
            'last ((%s`%d) extend 2 and name N)' % (model, index),  # next N
        ]
        try:
            if phi is not None:
                cmd.set_dihedral(atsele[0], atsele[1], atsele[2], atsele[3], phi)
            if psi is not None:
                cmd.set_dihedral(atsele[1], atsele[2], atsele[3], atsele[4], psi)
        except:
            print ' Error: cmd.set_dihedral failed'
Esempio n. 13
0
 def do_select(self,name):
     try:
         obj_name = cmd.index('first ?' + name)[0][0]
         self.set_object(obj_name)
     except:
         pass
     self.cmd.deselect()
Esempio n. 14
0
    def from_alignment(self, mobile, target, aln_obj):
        '''
        Use alignment given by "aln_obj" (name of alignment object)
        '''
        from .selecting import wait_for
        wait_for(aln_obj)

        self.mobile = '(%s) and %s' % (mobile, aln_obj)
        self.target = '(%s) and %s' % (target, aln_obj)
        if self.check():
            return

        # difficult: if selections spans only part of the alignment or
        # if alignment object covers more than the two objects, then we
        # need to pick those columns that have no gap in any of the two
        # given selections

        mobileidx = set(cmd.index(mobile))
        targetidx = set(cmd.index(target))
        mobileidxsel = []
        targetidxsel = []

        for column in cmd.get_raw_alignment(aln_obj):
            mobiles = mobileidx.intersection(column)
            if len(mobiles) == 1:
                targets = targetidx.intersection(column)
                if len(targets) == 1:
                    mobileidxsel.extend(mobiles)
                    targetidxsel.extend(targets)

        self.mobile = cmd.get_unused_name('_mobile')
        self.target = cmd.get_unused_name('_target')
        self.temporary.append(self.mobile)
        self.temporary.append(self.target)

        mobile_objects = set(idx[0] for idx in mobileidxsel)
        target_objects = set(idx[0] for idx in targetidxsel)

        if len(mobile_objects) == len(target_objects) == 1:
            mobile_index_list = [idx[1] for idx in mobileidxsel]
            target_index_list = [idx[1] for idx in targetidxsel]
            cmd.select_list(self.mobile, mobile_objects.pop(), mobile_index_list, mode='index')
            cmd.select_list(self.target, target_objects.pop(), target_index_list, mode='index')
        else:
            cmd.select(self.mobile, ' '.join('%s`%d' % idx for idx in mobileidxsel))
            cmd.select(self.target, ' '.join('%s`%d' % idx for idx in targetidxsel))
Esempio n. 15
0
def renumber(selection='all', start=1, startsele=None, quiet=1):
    '''
DESCRIPTION

    Set residue numbering (resi) based on connectivity.

ARGUMENTS

    selection = string: atom selection to renumber {default: all}

    start = integer: counting start {default: 1}

    startsele = string: residue to start counting from {default: first in
    selection}
    '''
    start, quiet = int(start), int(quiet)
    model = cmd.get_model(selection)
    cmd.iterate(selection, 'atom_it.next().model = model',
                space={'atom_it': iter(model.atom)})
    if startsele is not None:
        startidx = cmd.index('first (' + startsele + ')')[0]
        for atom in model.atom:
            if (atom.model, atom.index) == startidx:
                startatom = atom
                break
        else:
            print ' Error: startsele not in selection'
            raise CmdException
    else:
        startatom = model.atom[0]
    for atom in model.atom:
        atom.adjacent = []
        atom.visited = False
    for bond in model.bond:
        atoms = [model.atom[i] for i in bond.index]
        atoms[0].adjacent.append(atoms[1])
        atoms[1].adjacent.append(atoms[0])
    minmax = [start, start]

    def traverse(atom, resi):
        atom.resi = resi
        atom.visited = True
        for other in atom.adjacent:
            if other.visited:
                continue
            if (atom.name, other.name) in [('C', 'N'), ("O3'", 'P')]:
                minmax[1] = resi + 1
                traverse(other, resi + 1)
            elif (atom.name, other.name) in [('N', 'C'), ('P', "O3'")]:
                minmax[0] = resi - 1
                traverse(other, resi - 1)
            elif (atom.name, other.name) not in [('SG', 'SG')]:
                traverse(other, resi)
    traverse(startatom, start)
    cmd.alter(selection, 'resi = atom_it.next().resi',
              space={'atom_it': iter(model.atom)})
    if not quiet:
        print ' Renumber: range (%d to %d)' % tuple(minmax)
Esempio n. 16
0
def renumber(selection='all', start=1, startsele=None, quiet=1):
    '''
DESCRIPTION

    Set residue numbering (resi) based on connectivity.

ARGUMENTS

    selection = string: atom selection to renumber {default: all}

    start = integer: counting start {default: 1}

    startsele = string: residue to start counting from {default: first in
    selection}
    '''
    start, quiet = int(start), int(quiet)
    model = cmd.get_model(selection)
    cmd.iterate(selection, 'atom_it.next().model = model',
                space={'atom_it': iter(model.atom)})
    if startsele is not None:
        startidx = cmd.index('first (' + startsele + ')')[0]
        for atom in model.atom:
            if (atom.model, atom.index) == startidx:
                startatom = atom
                break
        else:
            print(' Error: startsele not in selection')
            raise CmdException
    else:
        startatom = model.atom[0]
    for atom in model.atom:
        atom.adjacent = []
        atom.visited = False
    for bond in model.bond:
        atoms = [model.atom[i] for i in bond.index]
        atoms[0].adjacent.append(atoms[1])
        atoms[1].adjacent.append(atoms[0])
    minmax = [start, start]

    def traverse(atom, resi):
        atom.resi = resi
        atom.visited = True
        for other in atom.adjacent:
            if other.visited:
                continue
            if (atom.name, other.name) in [('C', 'N'), ("O3'", 'P')]:
                minmax[1] = resi + 1
                traverse(other, resi + 1)
            elif (atom.name, other.name) in [('N', 'C'), ('P', "O3'")]:
                minmax[0] = resi - 1
                traverse(other, resi - 1)
            elif (atom.name, other.name) not in [('SG', 'SG')]:
                traverse(other, resi)
    traverse(startatom, start)
    cmd.alter(selection, 'resi = atom_it.next().resi',
              space={'atom_it': iter(model.atom)})
    if not quiet:
        print(' Renumber: range (%d to %d)' % tuple(minmax))
Esempio n. 17
0
def colors():
    while 1:
        color = 0
        for a in cmd.index("name ca"):
            cmd.color(str(color), "byres %s`%d" % a, quiet=1)
            color = color + 1
            if color > 50:
                color = 0
            time.sleep(0.001)
Esempio n. 18
0
def set_phipsi(selection, phi=None, psi=None, state=1, quiet=1):
    '''
DESCRIPTION

    Set phi/psi angles for all residues in selection.

SEE ALSO

    phi_psi, cmd.get_phipsi, set_dihedral, DynoPlot
    '''
    for idx in cmd.index('byca (' + selection + ')'):
        x = cmd.index('((%s`%d) extend 2 and name C+N+CA)' % idx)
        if len(x) != 5 or x[2] != idx:
            print(' Warning: set_phipsi: missing atoms (%s`%d)' % idx)
            continue
        if phi is not None:
            cmd.set_dihedral(x[0], x[1], x[2], x[3], phi, state, quiet)
        if psi is not None:
            cmd.set_dihedral(x[1], x[2], x[3], x[4], psi, state, quiet)
Esempio n. 19
0
def set_phipsi(selection, phi=None, psi=None, state=1, quiet=1):
    '''
DESCRIPTION

    Set phi/psi angles for all residues in selection.

SEE ALSO

    phi_psi, cmd.get_phipsi, set_dihedral, DynoPlot
    '''
    for idx in cmd.index('byca (' + selection + ')'):
        x = cmd.index('((%s`%d) extend 2 and name C+N+CA)' % idx)
        if len(x) != 5 or x[2] != idx:
            print(' Warning: set_phipsi: missing atoms (%s`%d)' % idx)
            continue
        if phi is not None:
            cmd.set_dihedral(x[0], x[1], x[2], x[3], phi, state, quiet)
        if psi is not None:
            cmd.set_dihedral(x[1], x[2], x[3], x[4], psi, state, quiet)
Esempio n. 20
0
def get_exclusions():
    """
    Computes the 1_3 exclusions
    """
    nb_vdw_list = []
    model = cmd.get_model('all')
    for at in model.atom:
        nb = cmd.index('(index %s extend 2)' % at.index)
        nb_vdw_list.extend([tuple(sorted([at.index-1, i[1]-1])) for i in nb])
    nb_vdw = set(nb_vdw_list)
    return nb_vdw
Esempio n. 21
0
def read_buried_unsats_from_logfile( fname ):
    buns = []
    for line in [x.strip() for x in open( fname ).readlines() ] :
        cols = line.split()

        if len(cols) == 0 : continue
        if cols[0] == "CalcOutput:" and cols[ 14 ] == "1":
            #m = cmd.get_model(cols[2])
            sel = cmd.index( "resi " + cols[6] + " and name " + cols[8], 1 )
            buns.append( (cols[2], sel[ 0 ][ 1 ] - 1) ) # index of the atom with a buried-unsatisfied hydrogen bonding group
    return buns
Esempio n. 22
0
    def do_select(self, name):


        lt = cmd.index(name + ' &  !hydrogens')

        for t in lt:
            if t[0] != self.LigDisplay:
                self.ErrorStatus = [ "You can only select a non-Hydrogen from the object " + self.LigDisplay + ". Try again." ]
            else:
                self.AnchorAtom = General_cmd.get_ID(t[1],t[0])
                self.RefreshDisplay()
            break
        cmd.deselect()
Esempio n. 23
0
def get_hydro_polar(selection, fromstruct=None):
    hydrosel = "(elem C or (all within 2 of elem C) and elem H)"
    if selection == "hydrophobic":
        if fromstruct == None:
            cmd.select("atoms", "{}".format(hydrosel))
        else:
            cmd.load(fromstruct, 'struct')
            cmd.select("atoms", "struct and {}".format(hydrosel))
    elif selection == "polar":
        if fromstruct == None:
            cmd.select("atoms", "not {}".format(hydrosel))
        else:
            cmd.load(fromstruct, 'struct')
            cmd.select("atoms", "struct and not {}".format(hydrosel))

    if fromstruct == None:
        cmd.select("f", "first all")
    else:
        cmd.select("f", "first struct")
    offset = cmd.index(selection="f")[0][1]
    indexes = [elt[1] for elt in cmd.index(selection="atoms")]
    selection = "index "+" ".join([str(elt-offset) for elt in indexes])
    cmd.delete('struct or atoms or f')
    return selection
Esempio n. 24
0
def set_phipsi(selection, phi=None, psi=None):
    for model, index in cmd.index('byca (' + selection + ')'):
        angles = [
            'first ((%s`%d) extend 2 and name C)' % (model, index),  # prev C
            'first ((%s`%d) extend 1 and name N)' % (model, index),  # this N
            '(%s`%d)' % (model, index),  # this CA
            'last ((%s`%d) extend 1 and name C)' % (model, index),  # this C
            'last ((%s`%d) extend 2 and name N)' % (model, index),  # next N
        ]
        try:
            if phi is not None:
                cmd.set_dihedral(angles[0], angles[1], angles[2], angles[3],
                                 phi)
            if psi is not None:
                cmd.set_dihedral(angles[1], angles[2], angles[3], angles[4],
                                 psi)
        except:
            print 'Error: cmd.set_dihedral failed'
Esempio n. 25
0
def set_phipsi(selection, phi=None, psi=None):
    for model, index in cmd.index(
            'byca (' + selection +
            ')'):  # 'byca' limits selection to one atom per residue
        atsele = [
            'first ((%s`%d) extend 2 and name C)' % (model, index),  # prev C
            'first ((%s`%d) extend 1 and name N)' % (model, index),  # this N
            '(%s`%d)' % (model, index),  # this CA
            'last ((%s`%d) extend 1 and name C)' % (model, index),  # this C
            'last ((%s`%d) extend 2 and name N)' % (model, index),  # next N
        ]
        try:
            if phi is not None:
                cmd.set_dihedral(atsele[0], atsele[1], atsele[2], atsele[3],
                                 phi)  #sets value for all phi in selection
            if psi is not None:
                cmd.set_dihedral(atsele[1], atsele[2], atsele[3], atsele[4],
                                 psi)  #sets value for all psi
        except:
            print ' Error: cmd.set_dihedral failed'
Esempio n. 26
0
    def get_Atom(self, name):

        info = []

        try: 
            list = cmd.index(name + " & " + self.LigDisplay)

            if len(list) > 0:
                atoms = cmd.get_model(name, state=cmd.get_state())
                for at in atoms.atom:
                    info.extend([ at.index, at.resn, at.resi, at.chain, at.name,
                                  at.coord[0], at.coord[1], at.coord[2] ])                  
            else:
                self.ErrorStatus = [ "You can only select atoms from the object " + self.LigDisplay + ". Try again." ]
                return info
                
            cmd.deselect()

        except:
            self.ErrorStatus = [ "An error occured while retrieving atom info. Try again." ]
            self.Quit_Wizard()
        
        return info
Esempio n. 27
0
    def get_Atom(self, name):

        info = []

        try: 
            list = cmd.index(name + " & " + self.LigDisplay)

            if len(list) > 0:
                atoms = cmd.get_model(name, state=cmd.get_state())
                for at in atoms.atom:
                    info.extend([ at.index, at.resn, at.resi, at.chain, at.name,
                                  at.coord[0], at.coord[1], at.coord[2] ])                  
            else:
                self.FlexAID.DisplayMessage("You must click in the object " + self.LigDisplay, 1)
                return info
                
            cmd.deselect()

        except:
            self.FlexAID.DisplayMessage("Error while retrieving atom info", 1)
            self.Quit_Wizard(self.ErrorCode)
        
        return info
from pymol import cmd
from glob import glob
 
for file in glob("*.pdb"):
    print file
    cmd.load(file,'prot')
    for a in cmd.index("CYS/SG"):
        for b in cmd.index("CYS/SG"):
            if a[1]<b[1]:
                cmd.select("s1","%s`%d"%a)
                cmd.select("s2","%s`%d"%b)
                if cmd.select("(s1|s2) and not ?skip"):
                    cmd.iterate("s1|s2","print ' ',chain,resn,resi,name")
                    print '   ',round(cmd.dist("tmp","s1","s2"),3)
                    cmd.select("skip","s1|s2|?skip")
    cmd.delete("all")
Esempio n. 29
0
MAX_DIST = 2.15  # Lepsi 2.05

#cmd.delete("all")
#cmd.load("2bem.pdb")

#cmd.color("white") # Pro jistotu
#cmd.show("lines")

cmd.select("cis", "resn CYS")
cmd.color("yellow", "cis")

list_of_bonds = []

# Projdi atom po atomu
for a_mol in cmd.index("CYS/SG", "cis"):
    for b_mol in cmd.index("CYS/SG", "cis"):
        if a_mol[1] < b_mol[1]:  # Neprchazej molekuly ktere uz mam
            if cmd.dist("tmp", a_mol, b_mol) < MAX_DIST:  # Seber Vzdalenost
                print "dist(" + str(b_mol[1]) + ", " + str(
                    a_mol[1]) + ") = " + str(cmd.dist("result", a_mol, b_mol))
                list_of_bonds.append(a_mol[1])
                list_of_bonds.append(b_mol[1])
                cmd.select(
                    "sulfidy",
                    "?sulfidy | (" + a_mol[0] + "`" + str(a_mol[1]) + ")")
                cmd.select(
                    "sulfidy",
                    "?sulfidy | (" + b_mol[0] + "`" + str(b_mol[1]) + ")")
            cmd.delete("tmp")
if len(list_of_bonds) > 0:
Esempio n. 30
0
def edge(name, i_node, j_node, color = None, r = 1.0, g=0.0, b=0.0, dg = 0.3, dl = 0.5, dr = 0.2, dir = 1, dir_color = None, dir_r = 0.0, dir_g = 1.0, dir_b = 0.0): 
	
	'''
	DESCRIPTION

	"edge" creates a cylinder (actually sausage) between the two
	selections that	correspond to the 2 nodes. If the edge is
	directed, only half of the user-formatted cylinder will be
	drawn towards the target node n2 and the rest will be drawn as
	a thin cylinder. 

	USAGE

	edge name, i_node, j_node [, color, r, g, b, dg, dl, dr, dir,
	dir_color, dir_r, dir_g, dir_b]

	name = name of edge
	i_node, j_node = atom selections for node 1 and node 2
	color = color name (overwrites rgb)
	r, g, b = rgb color (default red)
	dg = dash gap (default 0 - alternative 0.3)
	dl = dash length (default 0.5)
	dr = dash radius (default 0.2)
	dir = directed edge (default 1-yes)
	dir_color = color name for the other half (overwrites dir_rgb)
	dir_[r, g, b] = rgb color for the other half (default green)
	'''
	
	if color is not None:
		 color_rgb =  cmd.get_color_tuple(cmd.get_color_index(color))
		 r = color_rgb[0]
		 g = color_rgb[1]
		 b = color_rgb[2]
	else:
		# Convert arguments into floating point values
		r = float(r)
		g = float(g)
		b = float(b)
		
	if dir_color is not None:
		dir_color_rgb =	cmd.get_color_tuple(cmd.get_color_index(dir_color))
		dir_r = dir_color_rgb[0]
		dir_g = dir_color_rgb[1]
		dir_b = dir_color_rgb[2]
	else:
		dir_r = float(dir_r)
		dir_g = float(dir_g)
		dir_b = float(dir_b)
	
	dg = float(dg)
	dl = float(dl)
	dr = float(dr)
	
	directed = int(dir)
	frag = directed + 1

	# Get tuple containing object and index of atoms in these
	# selections
	x1 = cmd.index(i_node,1)
	x2 = cmd.index(j_node,1)

	# Get number of atoms in each selection
	n1 = len(x1)
	n2 = len(x2)
	if(n1 < 1):
		print "Error: node " + n1 + " has no atoms"
		return
	if(n2 < 1):
		print "Error: node " + n2 + " has no atoms"
		return

	# Get objects and atom indices
	o1 = x1[0][0]
	i1 = x1[0][1]
	o2 = x2[0][0]
	i2 = x2[0][1]

	# Get ChemPy models
	m1 = cmd.get_model(o1)
	m2 = cmd.get_model(o2)

	# Get atoms
	a1 = m1.atom[i1-1]
	a2 = m2.atom[i2-1]

	# Get coords
	x1 = a1.coord[0]
	y1 = a1.coord[1]
	z1 = a1.coord[2]
	x2 = a2.coord[0]
	y2 = a2.coord[1]
	z2 = a2.coord[2]

	# Make some nice strings for user feedback
	#n1 = o1 + "/" + a1.segi + "/" + a1.chain + "/" + a1.resn + "." + a1.resi + "/" + a1.name
	#print n1 + "(" + str(x1) + "," + str(y1) + "," + str(z1) + ")"
	#n2 = o2 + "/" + a2.segi + "/" + "/" + a2.chain + "/" + a2.resn + "." + a2.resi + "/" + a2.name
	#print n2 + "(" + str(x2) + "," + str(y2) + "," + str(z2) + ")"

	# Calculate distances 
	dx = (x2 - x1) / frag
	dy = (y2 - y1) / frag
	dz = (z2 - z1) / frag
	d = math.sqrt((dx*dx) + (dy*dy) + (dz*dz))
	#print "distance = " + str(d) + "A"

	# Work out how many times (dash_len + gap_len) fits into d
	dash_tot = dl + dg
	n_dash = math.floor(d / dash_tot)

	# Work out step lengths
	dx1 = (dl / dash_tot) * (dx / n_dash)
	dy1 = (dl / dash_tot) * (dy / n_dash)
	dz1 = (dl / dash_tot) * (dz / n_dash)
	dx2 = (dx / n_dash)
	dy2 = (dy / n_dash)
	dz2 = (dz / n_dash)

	# Generate dashes
	x = x1
	y = y1
	z = z1

	# Empty CGO object
	obj = []	
	for i in range(n_dash):
	   # Generate a sausage
	   obj.extend([SAUSAGE, x, y, z, x+dx1, y+dy1, z+dz1, dr, r, g, b, r, g, b])
	   
	   # Move to start of next dash
	   x = x + dx2
	   y = y + dy2
	   z = z + dz2

	if directed == 1:
	   obj.extend([SAUSAGE, x, y, z, x2, y2, z2, 0.05, dir_r, dir_g, dir_b, dir_r, dir_g, dir_b])

	cmd.set("stick_quality", 24)
	# Load the object into PyMOL
	cmd.load_cgo(obj, name)
Esempio n. 31
0
def unfold(chains):
    for chain in chains:
        np.array([
            unfold_index(name, index)
            for name, index in cmd.index('byca (chain {})'.format(chain))
        ])
Esempio n. 32
0
def populate():
    # Create named selections automatically
    cmd.select('protein', 'resn GLY+PRO+ALA+VAL+LEU+ILE+MET+CYS+PHE+TYR+TRP+'+
        'HIS+LYS+ARG+GLN+ASN+GLU+ASP+SER+THR')
    cmd.select('dna', 'resn %s'%(DNASTR))
    cmd.select('rna', 'resn %s'%(RNASTR))
    cmd.select('hydrophobic', 'resn ALA+ILE+LEU+MET+PHE+PRO+TRP+VAL')
    cmd.select('hydrophilic', 'resn THR+SER+ARG+ASN+ASP+GLN+GLU+HIS+LYS')
    cmd.select('acidic', 'resn ASP+GLU')
    cmd.select('basic', 'resn ARG+HIS+LYS')
    cmd.select('ligands', 'het')
    cmd.select('heme', 'resn hem')
    cmd.select('b12', 'resn b12')
    cmd.select('cub', 'resn cub')
    cmd.select('fes', 'resn fes')
    cmd.select('mos', 'resn mos')
    cmd.select('hea', 'resn hea')
    cmd.select('cua', 'resn cua')
    cmd.select('fco', 'resn fco')
    cmd.select('sf4', 'resn sf4')
    cmd.select('f3s', 'resn f3s')
    cmd.select('fe2', 'symbol fe')
    cmd.select('cfm', 'resn cfm')
    cmd.select('clf', 'resn clf')
    cmd.select('hec', 'resn hec')
    cmd.select('cob', 'resn cob')
    cmd.select('c2o', 'resn c2o')
    cmd.select('pcd', 'resn pcd')
    cmd.select('f43', 'resn f43')
    cmd.select('sodium', 'symbol na')
    cmd.select('zinc', 'symbol zn')
    cmd.select('3co', 'symbol co')
    cmd.select('Cobalt', 'symbol co')
    cmd.select('Nickle', 'symbol ni')
    cmd.select('Iron', 'symbol fe')
    cmd.select('Copper', 'symbol cu')
    cmd.select('Manganese', 'symbol mn')
    cmd.select('Magnesium', 'symbol mg')
    cmd.select('4mo', 'symbol mo')
    cmd.select('Molybdenum', 'symbol mo')
    cmd.select('calcium', 'symbol ca')
    # Then turn them off
    cmd.disable('ca')
    cmd.disable('mo')
    cmd.disable('4mo')
    cmd.disable('mg')
    cmd.disable('mn')
    cmd.disable('cu')
    cmd.disable('fe')
    cmd.disable('ni')
    cmd.disable('co')
    cmd.disable('3co')
    cmd.disable('zn')
    cmd.disable('na')
    cmd.disable('f43')
    cmd.disable('pcd')
    cmd.disable('c2o')
    cmd.disable('cob')
    cmd.disable('hec')
    cmd.disable('clf')
    cmd.disable('cfm')
    cmd.disable('fe2')
    cmd.disable('f3s')
    cmd.disable('sf4')
    cmd.disable('fco')
    cmd.disable('cua')
    cmd.disable('hea')
    cmd.disable('mos')
    cmd.disable('fes')
    cmd.disable('cub')
    cmd.disable('b12')
    cmd.disable('heme')
    cmd.disable('ligands')
    cmd.disable('basic')
    cmd.disable('acidic')
    cmd.disable('hydrophilic')
    cmd.disable('hydrophobic')
    cmd.disable('dna')
    cmd.disable('rna')
    cmd.disable('protein')
    # Create named selections for each chain, and leave them off by default
    for letter in cmd.get_chains():
        if letter=="":
            letter="\"\""
        chain = 'Chain-%s'%(letter)
        cmd.select(chain, "chain %s"%(letter))
        cmd.disable(chain)
    # Delete any selections (or other objects) that contain no atoms
    objects = cmd.get_names('all')
    for obj in objects:
        try:
            if(len(cmd.index(obj)) < 1):
                cmd.delete(obj)
        except:
            cmd.delete(obj)
    # See what's left
    objects = cmd.get_names('all')
    # Create a list containing all the remaining objects, plus "All".
    # If there's any protein, dna, or rna, add selections representing
    # their negation (everything else) to the list too
    items = ['All', ]
    for obj in objects:
        items.append(obj)
        if obj in ['protein', 'dna', 'rna']:
            items.append('not %s' % obj)
    # Add everything in that list as an option in the EZ-Viz and View Options
    # selection menus.  _setit is an internal TkInter class, not sure
    # exactly why its constructor is being called here (it deals with option
    # menu commands though, so it kind of makes sense).
    try:
        GUI.ez_viz['selection_menu']['menu'].delete(0, tk.END)
        GUI.view['advanced_selection_menu']['menu'].delete(0, tk.END)
        for item in items:
            GUI.ez_viz['selection_menu']['menu'].add_command(label=item,
                command=tk._setit(GUI.ez_viz['selection'], item, set_selection))
            GUI.view['advanced_selection_menu']['menu'].add_command(label=item,
                command=tk._setit(GUI.view['advanced_selection'], item, 
                    set_selection))
    except AttributeError:
        pass
Esempio n. 33
0
        # PRESKOC TO CO UZ MAME
        if (int(atom_a.resi)) <= (int(atom_b.resi) + 1):  # +1  PRESKOC SUSEDA
            continue

        dist = sqrt((atom_a.coord[0] - atom_b.coord[0])**2 +
                    (atom_a.coord[1] - atom_b.coord[1])**2 +
                    (atom_a.coord[2] - atom_b.coord[2])**2)
        if maximal < dist:
            maximal = dist
            max_atom_a = atom_a
            max_atom_b = atom_b
        if dist < minimal:
            minimal = dist
            min_atom_a = atom_a
            min_atom_b = atom_b

print "MAX distance: " + str(maximal) + " " + "[" + str(
    max_atom_a.index) + ", " + str(max_atom_b.index) + "]"
print "MIN distance: " + str(minimal) + " " + "[" + str(
    min_atom_a.index) + ", " + str(min_atom_b.index) + "]"
cmd.dist("MAX_DISTANCE",
         cmd.index("index " + str(max_atom_a.index))[0],
         cmd.index("index " + str(max_atom_b.index))[0])
cmd.dist("MIN_DISTANCE",
         cmd.index("index " + str(min_atom_a.index))[0],
         cmd.index("index " + str(min_atom_b.index))[0])
cmd.color("orange", "MIN_DISTANCE")
cmd.color("white", "MAX_DISTANCE")

#"""
Esempio n. 34
0
File: rpc.py Progetto: jandom/rdkit
def rpcIndex(what='all'):
  """ returns the results of cmd.index(what) """
  return cmd.index(what)
Esempio n. 35
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)
Esempio n. 36
0
	def createHBonds(self, interface_only=False):
		""" Method which gets executed when the user selected "Quick Visualize Hydrogen Bonds" or "Apply"
		on the hydrogen bonds tab of the notebook in the main Rosetta Tools GUI."""

		self.interface_hbonds_only = interface_only

		# save the view so we can restore it later
		my_view = cmd.get_view()

		# we have to pass the path to the rosetta executable and the database files to this method somehow
		# the easiest way is to have a config file in the users home directory
		init_file_name = os.environ['HOME'] + '/.rosettatoolsplugin'

		#rj Done with paths file. Now read the att file. All the att file contains is the path to the executable, right Yi?
		if ( os.path.exists(init_file_name) ):
			init_file = open( init_file_name, "r" )
			for line in init_file.xreadlines():
				if ( line.find("rosetta_executable") != -1 ):
					self.path_to_executable = line.split()[1]
				if ( line.find("rosetta_database") != -1 ):
					self.path_to_database_files = line.split()[1]
			init_file.close()

		else:
			showerror('Rosetta Tools Plugin: ERROR', "You need to specify a path to the Rosetta executable " \
						"'report_hbonds_for_plugin', and to the Rosetta database in a file named '.rosettatoolsplugin' " \
						"in your home directory.\nrosetta_executable path/to/exec\nrosetta_database path/to/database", parent=self.parent )
			return

		print "Rosetta Tools Plugin: Scoring structure to find hydrogen bonds..."

		# set values for some of the cgo object parameters
		bond_width = 0.04
		gap_length = 0.20
		dash_length = 0.10

		# if no objects are loaded, do nothing except print to the log
		if ( len(cmd.get_object_list()) == 0 ):   # cmd.get_names could also be used
			print "Rosetta Tools Plugin: ERROR 001: No structure found. Please load a structure before using this plugin."
			return

		# first check for files in the current working directory
		# if not there, skip that structure
		# at some point in the future, we should pop up a small window that asks the user to input the path to the file
		path_to_pdb_files = os.getcwd()

		# if multiple objects have been loaded, draw the hydrogen bonds for all of them
		# for each structure....
		object_list = cmd.get_names("objects", enabled_only=1)
		selection_list = cmd.get_names("all")
		for object in object_list:

			# don't try to draw Hbonds for CGO objects that are hbond - this is a consequence of calling get_names() for
			# all enabled objects
			if ( object.endswith("-hb") ):
				continue
			
			# don't redraw H-bonds if they're already there. this allows one to load a structure,
			# visualize the H-bonds in that structures, load another structure and visualize again
			# but bonds aren't redrawn for the first object loaded. 
			# only checks for the -hb. if that's been deleted, then redraw for the object
			# I could check to see if both the hb's and unsats have been deleted, but there's no good reason to.
			
			if ( self.interface_hbonds_only ):
				if ( ( object + "-iface-hb" ) in selection_list ):
					print "Rosetta Tools Plugin: Interface H-bonds for object '" + object + "' already exist. Delete CGO object to recreate bonds."
					continue
			else:
				if ( ( object + "-hb" ) in selection_list ):
					print "Rosetta Tools Plugin: Bonds for object '" + object + "' already exist. Delete CGO object to recreate bonds."
					continue

			# concatenate the path to the filename and check if the file exists
			filename = object + ".pdb"
			absolute_file_path = os.path.join( path_to_pdb_files, filename )

			if ( os.path.exists(path_to_pdb_files) != True ):
				print "Rosetta Tools Plugin: ERROR 002: Path doesn't exist. A valid path to the PDB file must be specified. Skipping this structure."
				continue
			if ( os.path.isfile(absolute_file_path) != True ):
				print "Rosetta Tools Plugin: ERROR 003: Structure file " + filename + " not found. Issue fetch PDBID and retry."
				continue

			# Need to start a new thread/process to run rosetta with the right flags and create the hb output.
			# There are two ways to parallelize in python: forks and threads.  Threads are more lightweight
			# but created threads can't run on their own - the main thread must persist or the child threads
			# are killed. Also, PyMOL doesn't appear to run plugin code in a separate thread/process. When
			# a plugins code is executed, the main PyMOL GUI window stop responding until the plugin code 
			# finishes.  What this means is that it would do no good to make the Rosetta call a thread because 
			# the main plugin code would still have to return before control is returned to the main GUI window.
			# So, I believe a fork is the way to go. Can a fork exist on its own?  Presumably, the parent could
			# exit and the child process will be orphaned. Since orphaned processes are reaped somehow by the 
			# kernel, this should be ok. The child process is what will go on to display the CGO objects since
			# the hbond information will be created by it.  The parent process will not be able to do anything
			# really.

			command = "%s -database \"%s\" -s \"%s\" -ignore_unrecognized_res -no_output" % (self.path_to_executable, self.path_to_database_files, absolute_file_path)
			print "Rosetta Tools Plugin: Running command: '" + command + "'"
			try:
				p = Popen(command, stdout=PIPE, stderr=PIPE, shell=True)
				output,error = p.communicate()
			except:
				showerror('Rosetta Tools Plugin: ERROR', 'An error occurred while trying to run Rosetta to generate hydrogen bond information.', parent=self.parent)
				return

			#rj not sure how to check the return status and capture the output with this new Popen/subprocess python module
			#rj so I'm just going to assume that if there's output the command finished successfully.

			# old way of running Rosetta
			#thread.start_new_thread( self.runRosettaForHbonds, (object, pathToDatabaseFiles, path_to_pdb_file))
			#while (self.childFinished == 0):
			#	time.sleep(.1)

			# an error occurred (-1 return value) while trying to run Rosetta to generate the hbond information
			#if (self.childFinished == -1):
			#	showerror('Rosetta Tools Plugin: ERROR', 'An error occurred while trying to run Rosetta to generate hydrogen bond information.' \
			#		'The command run was as follows:\n\n' + self.commandRun + "\n\n" + 
			#		'Please try this command manually to determine why the command failed.', parent=self.parent )
			#	return
				

			# parse the output of the command
			hbDataStart = 0
			hbData = []
			#unsHbDataStart = 0
			#unsHbData = []
			for line in output.split("\n"):
				if ( string.find( line, "DONE" ) != -1 ):
					break
				if ( hbDataStart ):
					hbData.append(line)
				#elif ( unsHbDataStart ):
				#	unsHbData.append(line)

				if ( string.find( line,"don_resname") != -1 ):
					hbDataStart = 1
				#elif (line.startswith("GU ")):
				#	unsHbDataStart = 1

			if ( len(hbData) == 0 ):
				print "Rosetta Tools Plugin: Hydrogen Bond info not found in output from Rosetta command."
			else:
				print "Rosetta Tools Plugin: The following hydrogen bonds were found:"
				print "\n".join( hbData )

				# parse up the lines into 9-tuples containing the residue numbers in the hydrogen bond, the energy and the distance
				# don_chain, don_resi, don_resn, don_res_atom, acc_chain, acc_resi, acc_resn, acc_atom, energy, distance) )
				hbDataTuples = self.getHydrogenBondData( hbData )

				hbDataTuples.sort( lambda x, y: cmp(float(x[8]),float(y[8])) )
				self.sortedHbDataTuples = hbDataTuples

				try:
					best_energy = float(self.sortedHbDataTuples[0][8])
					worst_energy = float(self.sortedHbDataTuples[-1][8]) # will be zero, since Ehb shouldn't give positive values
				except:
					print "Error in hydrogen bond data."
					print self.sortedHbDataTuples
					return


				# let's start with 50 bins for the energy values, giving us 50 different shades of color possible
				# in the future, this can be expanded to be continuous, instead of discretized.
				nbins = 50
				bin_width = (worst_energy - best_energy) / nbins
				
				# the lowest value for transparency that can be seen in the viewer is 0.4
				# the highest value possible is 1.0
				# we want the low energy bonds to have a transparency of 1.0, and higher energies to be more see thru
				trans_bin_width = (1.0 - 0.3) / nbins

				# use default saturation and value(brightness) values
				hue = 0.16667
				sat = 1.0
				value = 1.0
				
				# create colors in pymol
				# use the colorsys module to make a gradient of colors in hsv color space and then convert
				# it into rgb values.  then save them in a dictionary for lookup later.
				self.colorDict = {}
				self.transparencyDict = {}
				for binNum in range(nbins):

					# create colors using hsv scale (fractional)
					# use a gradient of red to white. going through the color spectrum just causes confusion when
					# looking at structures. keep the lower limit a light red - sat of 0.2 - not gray.
					hsv = (hue, sat * float(nbins-binNum)/nbins, value)
					#convert to rgb and append to color list
					rgb = colorsys.hsv_to_rgb(hsv[0],hsv[1],hsv[2])
					color_name = str(best_energy + binNum*bin_width)
					self.colorDict[ color_name ] = rgb

					# the dictionary looks something like below
					#{ '-1.4829': (1.0, 1.0, 0.0), 
					#  '-1.305216': (1.0, 1.0, 0.12),
					#  '-1.157146': (1.0, 1.0, 0.22),
					# note, keys are not sorted in a dictionary
					
					# we want to do something similar with the transparency parameter
					transparency = 1.0 - trans_bin_width*binNum
					self.transparencyDict[ color_name ] = transparency
				
				# need the color keys to be in sorted order, as floats. unfortunately, no way to convert a list
				# of string to a list of floats easily. needed because this list is what we'll go through to figure
				# out what to color each hbond.
				colorKeys = self.colorDict.keys()
				fColorKeys = []
				for each in colorKeys:
					fColorKeys.append(float(each))
				fColorKeys.sort()
				colorKeys = fColorKeys
				# the list looks as [-1.4829, -1.453286, -1.423672, ... ]

				totalCount = len(self.sortedHbDataTuples)

				# partition the bonds into strong, mid, and weak
				bondsObjects = []


				# create a dictionary for holding labels. Since labels have to go on the donor atom and since a 
				# donor atom can participate in more than one h-bond, we need to save the labels in a dictionary
				# keyed on the donor atom and then go through this dict after all h-bonds have been drawn.
				labelList = {}

				# before we start creating labels, tell PyMOL to color them yellow and size them nicely
				cmd.set("label_color", "yellow")
				try:
					cmd.set("label_size", "12")
				except:
					print "Rosetta Tools Plugin: Old version of PyMOL. Default sized labels being used."

				# last thing before we start going through the tuples is to print out a line to the background
				# to explain what the lines being printed after this represent (interface bonds)
				print "Rosetta Tools Plugin: The following interface spanning hydrogen bonds were found:"
				
				# now go through the data tuples and call the hbond function
				model = cmd.get_model(object)
				for tuple in self.sortedHbDataTuples:

					# don_chain, don_resi, don_resn, don_res_atom, acc_chain, acc_resi, acc_resn, acc_atom, energy, distance
					don_chain = tuple[0]
					don_resi = tuple[1]
					don_resn = tuple[2]
					don_res_atom = tuple[3]
					acc_chain = tuple[4]
					acc_resi = tuple[5]
					acc_resn = tuple[6]
					acc_res_atom = tuple[7]
					energy = tuple[8]
					distance = tuple[9]
					
					name = "hb." + don_resi + '-' + don_res_atom + '.' + acc_resi + '-' + acc_res_atom

					# figure out which atoms to draw lines between
					# tuple: (donor_chain, donor res, donor atom, acceptor_chain, acceptor res, acceptor atom, energy)

					sele1_exp = '/' + '/'.join([ object, '', don_chain, don_resi, don_res_atom ])
					sele2_exp = '/' + '/'.join([ object, '', acc_chain, acc_resi, acc_res_atom ])

					# index returns tuples containing object name and atom object index
					x1 = cmd.index( sele1_exp, 1 )
					x2 = cmd.index( sele2_exp, 1 )

					# Check to make sure we got something out of index
					if( len(x1) < 1):
						print "Rosetta Tools Plugin: Selection " + sele1_exp + " has no atoms."
						continue
					if( len(x2) < 1):
						print "Rosetta Tools Plugin: Selection " + sele2_exp + " has no atoms."
						continue

					a1 = model.atom[ x1[0][1] - 1 ]
					a2 = model.atom[ x2[0][1] - 1 ]


					# figure out the rgb code to use
					# traverse the list of keys of the color dictionary and check if the energy is greater(worse)
					# than the current key and less(better) than the next key. If it is, the value in the color
					# dictionary for that key is what we want to use
					
					if ( energy <= float(colorKeys[0]) ):
						rgbTuple = self.colorDict[ str(colorKeys[0]) ]
						transparency = self.transparencyDict[ str(colorKeys[0]) ]
					else:
						for index in range( len(colorKeys) -1):
							if ( (energy > float(colorKeys[index])) and (energy <= float(colorKeys[index+1])) ):
								rgbTuple = self.colorDict[ str(colorKeys[index]) ]
								transparency = self.transparencyDict[ str(colorKeys[index]) ]
								break

					if ( len(rgbTuple) == 0 ):
						rgbTuple = self.colorDict[ str(colorKeys[-1]) ]
						transparency = self.transparencyDict[ str(colorKeys[-1]) ]

					if ( self.interface_hbonds_only ):
						if ( don_chain == acc_chain ):
							continue
						
					# make the call to Gareth's function to construct the CGO
					try:
						cgoObject = hbond(name=name, a1=a1, a2=a2, r=rgbTuple[0], g=rgbTuple[1], b=rgbTuple[2],
											weight=bond_width, dash_gap=gap_length, dash_length=dash_length, transparency=transparency )
					except:
						print sele1_exp
						print sele2_exp
						print "Rosetta Tools Plugin: ERROR 007: Error in creating CGO object for bond."
						# to next bond
						continue
					
					# now create a label next to this bond containing the distance and Rosetta energy for this H-bond
					#distanceAndEnergyText = '"%sA E:%s"' % (str(round(distance, 2)), str(round(energy, 2)))
					energyText = '"E: %s"' % (str(round(energy, 2)))
					if (don_chain != acc_chain):
						if (labelList.has_key(sele1_exp)):
							labelList[sele1_exp] = "%s, %s" % (labelList[sele1_exp], energyText)
						else:
							labelList[sele1_exp] = energyText
					
						# print out a line containing all the info in the PDB file so people can check the energy easily
						print "Rosetta Tools Plugin: %s %s-%s %s - %s-%s %s: distance: %2.2f, hbE: %2.2f" % \
							(object, don_resn, don_resi, don_res_atom, acc_resn, acc_resi, acc_res_atom, distance, energy)

					# save into our arrays for "load"ing later
					bondsObjects.extend( cgoObject )


				# now that the CGOs are all ready, make them visible in pymol
				if ( self.interface_hbonds_only ):
					cgo_objects_display_name = object + "-iface-hb"
				else:
					cgo_objects_display_name = object + "-hb"
					
				cmd.load_cgo( bondsObjects, cgo_objects_display_name )

				# go through the list of labels and display them
				for sele_exp in labelList.keys():
					try:
						cmd.label(sele_exp, labelList[sele_exp])
					except:
						print sele_exp
						print "Rosetta Tools Plugin: ERROR 008: Error in creating bond label."
						# to next bond
					
			
			# Now do the UNSATISFIED hydrogen bonds
			# make another list to hold the unsatisfied selections
			#unsatisfied = []
			#sele_exp = None

			#if ( len(unsHbData) == 0 ):
			#	print "Rosetta Tools Plugin: Unsatisfied hydrogen Bond info not found in file " + filename + "."
			#else:
			#	self.unsHbDataTuples = self.getUnsatisfiedHydrogenBondData( unsHbData, object, model )

			#	# tuple has: (group_type, resi_name, rosetta_resi_num)
			#	# since "COO", "ASP" has two O's that should be marked, use the group2atoms array
			#	# to figure out which atoms to make sphere objects on
			#	for tuple in self.unsHbDataTuples:
			#		# I'm assuming that unsatisfied IGNOR groups should be ignored...
			#		if ( tuple[0]=="IGNOR" ):
			#			continue
			#		if ( tuple[0]=="BBO" ):
			#			atoms = ["O"]
			#		elif ( tuple[0]=="BBH" ):
			#			atoms = ["H"]
			#		else:
			#			try:
			#				atoms = group2atoms[(tuple[0],tuple[1])]
			#			except:
			#				print "Rosetta Tools Plugin: No atom translation available for group: '" + tuple[0] + "-" + tuple[1] + "'. Omitting this group."
			#				continue
			#
			#		for atom in atoms:
			#			sele_exp = '/' + '/'.join([ object, '', '*', tuple[2], atom])
			#			unsatisfied.extend( self.makeSphereObject( sele_exp ) )

			#	# now that we have all the spheres created, load them all in
			#	cmd.load_cgo( unsatisfied, object + "-unsat" )


			print "Rosetta Tools Plugin: Object " + object + " finished."

		# restore the saved view
		cmd.set_view(my_view)
from pymol import cmd
from glob import glob
 
for file in glob("*.pdb"):
    print file
    cmd.load(file,'prot')
    for a in cmd.index("elem s and bound_to elem s"):
        if cmd.select("s1","%s`%d"%a) and \
           cmd.select("s2","elem s and bound_to %s`%d"%a):
            if cmd.select("(s1|s2) and not ?skip"):
                cmd.iterate("s1|s2","print ' ',chain,resn,resi,name")
                print '   ',round(cmd.dist("tmp","s1","s2"),3)
                cmd.select("skip","s1|s2|?skip")
    cmd.delete("all")