Exemple #1
0
    def Quit_Wizard(self):

        try:
            General_cmd.unmask_Objects(self.exc)
            cmd.set('mouse_selection_mode', self.selection_mode)

            cmd.delete(self.LigDisplay)
            cmd.refresh()

            cmd.deselect()

        except:
            pass

        if self.ErrorCode > 0:
            self.FlexAID.WizardError = True

        self.FlexAID.WizardResult = self.AnchorAtom
        self.FlexAID.ActiveWizard = None

        self.queue.put(lambda: self.top.AnchorRunning(False))
        self.queue.put(lambda: self.FlexAID.root.deiconify())
        self.queue.put(lambda: self.FlexAID.root.update())

        cmd.set_wizard()
        cmd.set_view(self.View)
        cmd.refresh()
def initial_representations():
    """Configure the initial representations for the protein and the ligand"""
    cmd.hide('everything', 'all')
    cmd.show('cartoon', 'all')
    cmd.select('ligand', 'resn NFT')
    cmd.deselect()
    cmd.show("sticks", "ligand")
Exemple #3
0
    def selections_cleanup(self):
        """Cleans up non-used selections"""

        if not len(self.plcomplex.unpaired_hba_idx) == 0:
            self.select_by_ids('Unpaired-HBA',
                               self.plcomplex.unpaired_hba_idx,
                               selection_exists=True)
        if not len(self.plcomplex.unpaired_hbd_idx) == 0:
            self.select_by_ids('Unpaired-HBD',
                               self.plcomplex.unpaired_hbd_idx,
                               selection_exists=True)
        if not len(self.plcomplex.unpaired_hal_idx) == 0:
            self.select_by_ids('Unpaired-HAL',
                               self.plcomplex.unpaired_hal_idx,
                               selection_exists=True)

        selections = cmd.get_names("selections")
        for selection in selections:
            try:
                empty = len(cmd.get_model(selection).atom) == 0
            except:
                empty = True
            if empty:
                cmd.delete(selection)
        cmd.deselect()
        cmd.delete('tmp*')
        cmd.delete('ps-*')
Exemple #4
0
    def Start(self):

        self.queue.put(lambda: self.FlexAID.root.withdraw())
        cmd.window('hide')
        cmd.window('show')
        # self.queue.put(lambda: cmd.window('show'))
        cmd.refresh_wizard()

        self.ErrorCode = 1

        try:
            self.selection_mode = cmd.get("mouse_selection_mode")
            cmd.set("mouse_selection_mode", 0) # set selection mode to atomic

            # Mask objects
            self.exc = [self.LigDisplay]
            General_cmd.mask_Objects(self.exc)

            self.ErrorCode = 0
            
        except:
            self.queue.put(lambda: self.FlexAID.DisplayMessage("  ERROR: Could not start the Anchor Atom wizard", 1))
            self.queue.put(lambda: self.FlexAID.DisplayMessage("         The wizard will abort prematurely", 1))
            self.Quit_Wizard()
            return

        # Display the ligand from the PDB file
        if self.DisplayLigand() or self.RefreshDisplay():
            self.queue.put(lambda: self.FlexAID.DisplayMessage("  ERROR: Could not display the ligand", 1))
            self.queue.put(lambda: self.FlexAID.DisplayMessage("         The wizard will abort prematurely", 1))
            self.Quit_Wizard()
            return
        
        # remove any possible selection before selecting atoms
        cmd.deselect()
def selectAlignmentBlocks(alignFile, name1=None, name2=None):
    """usage: selectAlignment, [name1, [name2]]
    
    Defines two new selections based on the alignment given in alignFile.
    AlignFile is in the XML format used by CE and BioJava.

    If specified, the selections will be called name1 and name2. Otherwise the
    names will be taken from the alignment file.
    
    return the names of the two selections (sele_name1, sele_name2)
    """
    align = Alignment(alignFile)

    if name1 is None:
        name1 = align.name1[:4]
    if name2 is None:
        name2 = align.name2[:4]

    blocks1 = align.getSelect1ByBlock()
    blocks2 = align.getSelect2ByBlock()
    selections = []
    for blk in xrange(len(blocks1)):
        select1 = "%s and ( %s )" % (name1, blocks1[blk])
        select2 = "%s and ( %s )" % (name2, blocks2[blk])

        align1 = "sele_%s_%s" % (name1, blk)
        align2 = "sele_%s_%s" % (name2, blk)
        selections.append(align1)
        selections.append(align2)

        cmd.select(align1, select1)
        cmd.select(align2, select2)
    cmd.deselect()

    return selections
Exemple #6
0
    def Quit_Wizard(self, rv):
        
        try:
            cmd.delete(self.LigDisplay)
            cmd.delete(self.AtomDisplay)         

            cmd.deselect()

            if rv != 1:
                General.unmask_Objects(self.exc)
                cmd.set('mouse_selection_mode', self.selection_mode)
                #cmd.config_mouse('three_button_editing', 1)
      
            if rv > 0:
                self.FlexAID.WizardError = True
        
            self.FlexAID.ActiveWizard = None

            cmd.set_wizard()
            cmd.set_view(self.View)
            cmd.refresh()

            self.top.SATRunning(False)

            self.queue.put(lambda: self.top.AnchorRunning(False))
            self.queue.put(lambda: self.FlexAID.root.deiconify())
            self.queue.put(lambda: self.FlexAID.root.update())

        except:
            pass
def initial_representations():
    """Configure the initial representations for the protein and the ligand"""
    cmd.hide('everything', 'all')
    cmd.show('cartoon', 'all')
    cmd.select('ligand', 'resn NFT')
    cmd.deselect()
    cmd.show("sticks", "ligand")
Exemple #8
0
 def set_mode(self, mode):
     self.mode = mode
     #reset pickCount and deselect everything
     self.pickCount = 0
     cmd.deselect()
     cmd.delete("sele*")
     self.cmd.refresh_wizard()
Exemple #9
0
    def Quit_Wizard(self):
        
        try:
            General_cmd.unmask_Objects(self.exc)
            cmd.set('mouse_selection_mode', self.selection_mode)

            cmd.delete(self.LigDisplay)
            cmd.refresh()
            
            cmd.deselect()
            
        except:
            pass
      
        if self.ErrorCode > 0:
            self.FlexAID.WizardError = True
        
        self.FlexAID.WizardResult = self.AnchorAtom
        self.FlexAID.ActiveWizard = None
        
        self.queue.put(lambda: self.top.AnchorRunning(False))
        self.queue.put(lambda: self.FlexAID.root.deiconify())
        self.queue.put(lambda: self.FlexAID.root.update())

        cmd.set_wizard()
        cmd.set_view(self.View)
        cmd.refresh()
Exemple #10
0
    def Start(self):
        
        self.queue.put(lambda: self.FlexAID.root.withdraw())
        cmd.window('hide')
        self.queue.put(lambda: cmd.window('show'))
        cmd.refresh_wizard()

        # Display the ligand from the PDB file
        if self.DisplayLigand():
            self.FlexAID.DisplayMessage("Error while trying to display the ligand from PDB file", 1)
            self.Quit_Wizard(self.ErrorCode)
            return
                    
        # Color the Atoms based on their type
        if self.ColorByType():
            self.FlexAID.DisplayMessage("Error while coloring the ligand atoms by type", 1)
            self.Quit_Wizard(self.ErrorCode)
            return            

        # Mask everythign except modifyable object (ligand)
        self.exc = [self.LigDisplay]
        General.mask_Objects(self.exc)        

        self.selection_mode = cmd.get("mouse_selection_mode")
        cmd.set("mouse_selection_mode", 0) # set selection mode to atomic

        # remove any possible selection before selecting atoms
        cmd.deselect()

        self.ErrorCode += 1
def selectAlignment(alignFile, name1=None, name2=None):
    """usage: selectAlignment, [name1, [name2]]
    
    Defines two new selections based on the alignment given in alignFile.
    AlignFile is in the XML format used by CE and BioJava.

    If specified, the selections will be called name1 and name2. Otherwise the
    names will be taken from the alignment file.
    
    return the names of the two selections (sele_name1, sele_name2)
    """
    align = Alignment(alignFile)

    if name1 is None:
        name1 = align.name1[:4]
    if name2 is None:
        name2 = align.name2[:4]

    select1 = "%s and ( %s )" % (name1, align.getSelect1())
    select2 = "%s and ( %s )" % (name2, align.getSelect2())
    cmd.select("sele_" + name1, select1)
    cmd.select("sele_" + name2, select2)

    cmd.deselect()

    return ("sele_" + name1, "sele_" + name2)
Exemple #12
0
def nicesele(delete=None):
    """
DESCRIPTION

    easily select relevant groups of atoms in a martini system

USAGE

    nicesele [, delete]

ARGUMENTS

    delete = if set, will delete the selections instead of creating them
    """
    if delete:
        if delete == 'delete':
            for sel in stored.nice_selectors:
                cmd.delete(sel)
        else:
            print(
                'Unknown option. Type `nicesele delete` to delete all the pre-made selections'
            )
    else:
        for sel, logic in stored.nice_selectors.items():
            cmd.select(sel, logic)
    cmd.sync()
    # disable last selection to avoid accidental modifications to it
    cmd.deselect()
    cmd.sync()
Exemple #13
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
Exemple #14
0
    def do_select(self, name):

        self.atom = self.get_Atom(name)

        if self.atom:

            resn = self.atom[1]
            resi = self.atom[2]
            chain = self.atom[3]

            if chain == '':
                chain = '-'

            self.ResidueName = resn + str(resi) + chain
            
            Error = self.top.Validate_EnterResidue(self.ResidueName)
            
            if Error != '':
                self.ErrorStatus = [ Error ]
                self.btn_Reset()
                
            else:
                self.ErrorStatus = [ ]
                self.highlight_Residue(name)
        
        cmd.deselect()
        cmd.refresh_wizard()
Exemple #15
0
 def testDeselect(self):
     cmd.load(self.datafile("1oky.pdb.gz"), "m1")
     cmd.select("all")
     self.assertEquals("sele" in cmd.get_names("all", enabled_only=1), True)
     cmd.deselect()
     self.assertEquals("sele" in cmd.get_names("all", enabled_only=1),
                       False)
    def __init__(self, _self=cmd):

        cmd.unpick()
        Wizard.__init__(self, _self)

        self.status = 0  # 0 no atoms selections, 1 atom selected
        self.error = None
        self.object_name = None

        # mode selection subsystem

        self.mode = default_mode
        self.modes = [
            'polar',
            'heavy',
            'neigh',
            'pairs',
        ]

        self.mode_name = {
            'polar': 'Polar Neighbors',
            'heavy': 'Heavy Neighbors',
            'neigh': 'Neighbors',
            'pairs': 'Pairwise Distances',
        }

        smm = []
        smm.append([2, 'Measurement Mode', ''])
        for a in self.modes:
            smm.append([
                1, self.mode_name[a], 'cmd.get_wizard().set_mode("' + a + '")'
            ])
        self.menu['mode'] = smm

        # overwrite mode selection subsystem

        self.object_mode = default_object_mode
        self.object_modes = [
            'overwr',
            'append',
        ]
        self.object_mode_name = {
            'overwr': 'Replace Previous',
            'append': 'Create New',
        }

        smm = []
        smm.append([2, 'New Distances?', ''])
        for a in self.object_modes:
            smm.append([
                1, self.object_mode_name[a],
                'cmd.get_wizard().set_object_mode("' + a + '")'
            ])
        self.menu['object_mode'] = smm
        self.selection_mode = cmd.get_setting_int("mouse_selection_mode")
        cmd.set("mouse_selection_mode", 0)  # set selection mode to atomic
        cmd.deselect()  # disable the active selection (if any)
Exemple #17
0
 def cleanupAfterRun(self):
     cmd.deselect()
     self.pickCount = 0
     cmd.delete("pk*")
     cmd.delete("sele*")
     cmd.delete("*_tmp*")
     cmd.delete("*tmp*")
     cmd.delete("_indicate*")
     cmd.delete("labelEnvironment*")
     cmd.delete("currentLabel")
     self.cmd.refresh_wizard()
Exemple #18
0
    def __init__(self):
        Wizard.__init__(self)

        # some attributes to do with picking
        self.pick_count = 0
        self.object_count = 0
        self.object_prefix = "pw"

        self.selection_mode = cmd.get_setting_legacy("mouse_selection_mode")
        cmd.set("mouse_selection_mode", 0)  # set selection mode to atomic
        cmd.deselect()
Exemple #19
0
def space_fill_ligand():
    cmd.select('Bad', 'resn GLY+PRO+ALA+VAL+LEU+ILE+MET+CYS+PHE+TYR+TRP+'+
        'HIS+LYS+ARG+GLN+ASN+GLU+ASP+SER+THR+ACD+ACE+ALB+ALI+ABU+ARO+ASX+'+
        'BAS+BET+FOR+GLX+HET+HSE+HYP+HYL+ORN+PCA+SAR+TAU+TER+THY+UNK+a+g+c'+
        '+t+u+HOH+MSE')
    cmd.select("ligand", "!Bad")
    cmd.hide("everything", "ligand")
    cmd.show("spheres", "ligand")
    cmd.delete("Bad")
    cpkligands()
    cmd.deselect()
Exemple #20
0
    def __init__(self, _self=cmd):

        Wizard.__init__(self, _self)

        self.memory = 0
        self.n_pair = 0
        self.status = 0  # 0 node not selected, 1 node selected
        self.message = None

        self.selection_mode = cmd.get_setting_legacy("process_mode")
        cmd.set("mouse_selection_mode", 0)  # set selection mode to atomic
        cmd.deselect()  # disable the active selection (if any)
Exemple #21
0
def load_ndx(fname="index.ndx", names=[]):
    if not os.path.isfile(fname): return
    ndx_file = IndexFile(fname)
    if not names:
        names = ndx_file.names
    for name in names:
        print name
        if ndx_file.dic.has_key(name):
            ids = ndx_file[name].ids
            __sel_from_id_list(name, ids)

    cmd.deselect()
Exemple #22
0
def load_ndx( fname = "index.ndx", names = []):
    if not os.path.isfile( fname ): return
    ndx_file = IndexFile( fname )
    if not names:
        names = ndx_file.names
    for name in names:
        print name
        if ndx_file.dic.has_key( name ):
            ids = ndx_file[name].ids
            __sel_from_id_list( name, ids )
                
    cmd.deselect()
Exemple #23
0
def space_fill_ligand():
    cmd.select(
        'Bad', 'resn GLY+PRO+ALA+VAL+LEU+ILE+MET+CYS+PHE+TYR+TRP+' +
        'HIS+LYS+ARG+GLN+ASN+GLU+ASP+SER+THR+ACD+ACE+ALB+ALI+ABU+ARO+ASX+' +
        'BAS+BET+FOR+GLX+HET+HSE+HYP+HYL+ORN+PCA+SAR+TAU+TER+THY+UNK+a+g+c' +
        '+t+u+HOH+MSE')
    cmd.select("ligand", "!Bad")
    cmd.hide("everything", "ligand")
    cmd.show("spheres", "ligand")
    cmd.delete("Bad")
    cpkligands()
    cmd.deselect()
Exemple #24
0
    def __init__(self,_self=cmd):

        Wizard.__init__(self,_self)
        
        self.memory = 0
        self.n_pair = 0
        self.status = 0 # 0 no atoms selections, 1 atom selected
        self.message = None

        self.selection_mode = cmd.get_setting_int("mouse_selection_mode")
        cmd.set("mouse_selection_mode",0) # set selection mode to atomic
        cmd.deselect() # disable the active selection (if any)
Exemple #25
0
    def __init__(self,_self=cmd):

        cmd.unpick();
        Wizard.__init__(self,_self)
        
        self.status = 0 # 0 no atoms selections, 1 atom selected
        self.error = None
        self.object_name = None

        # mode selection subsystem
        
        self.mode = default_mode
        self.modes = [
            'polar',
            'heavy',
            'neigh',
            'pairs',
            ]
        
        self.mode_name = {
            'polar':'Polar Neighbors',
            'heavy':'Heavy Neighbors',
            'neigh':'Neighbors',
            'pairs':'Pairwise Distances',
            }

        smm = []
        smm.append([ 2, 'Measurement Mode', '' ])
        for a in self.modes:
            smm.append([ 1, self.mode_name[a], 'cmd.get_wizard().set_mode("'+a+'")'])
        self.menu['mode']=smm

        # overwrite mode selection subsystem
        
        self.object_mode=default_object_mode
        self.object_modes = [
            'overwr',
            'append',
            ]
        self.object_mode_name = {
            'overwr':'Replace Previous',
            'append':'Create New',         
            }

        smm = []
        smm.append([ 2, 'New Distances?', '' ])
        for a in self.object_modes:
            smm.append([ 1, self.object_mode_name[a], 'cmd.get_wizard().set_object_mode("'+a+'")'])
        self.menu['object_mode']=smm
        self.selection_mode = cmd.get_setting_legacy("mouse_selection_mode")
        cmd.set("mouse_selection_mode",0) # set selection mode to atomic
        cmd.deselect() # disable the active selection (if any)
Exemple #26
0
def visualize_in_pymol(args,outfolder,clusters,interactions,pdb,cut,freq):

    #(args,outfolder,clusters,interactions,pdb,cut,freq)=input_args
    #print(cut)
    #return
    pymol.finish_launching()
    cmd.reinitialize()
    cmd.load(pdb)
    cmd.hide("everything")
#    cmd.show("ribbon")
    cmd.show("cartoon")
    # Create bindings and selections, and color them
    bond_connections(clusters, interactions)
    selections = select_clusters(clusters)
    colors = color_selections(selections)
    print(colors)

#    colors = color_selections([sele])


    #cmd.color("gray70")
    #cmd.set("sphere_scale",0.75)
    cmd.space("cmyk")
    #cmd.set("ray_shadow","off")
    #cmd.bg_color("white")
    sele = "chain A and resi 131 and not name H*"
    cmd.show("sticks",sele)
    cmd.util.cnc(sele)
    #cmd.center("chain A")
    cmd.deselect()
    ### cut below here and paste into script ###
    cmd.set_view ([\
                   0.185403526,   -0.784912288,   -0.591205537,\
                   -0.726189077,    0.295874894,   -0.620551527,\
                   0.662004888,    0.544381559,   -0.515144050,\
                   -0.001714554,   -0.001769811, -125.023078918,\
                   30.330446243,   78.181671143,  146.038742065,\
                   98.763908386,  151.776306152,  -20.000000000] )
    outfile="{}cluster{}-{}.png".format(outfolder,cut,freq)
    if args.ray or args.generate_all:
        cmd.save(outfile)
### cut above here and paste into script ###

    # Show clusters
    if args.show[0] is None:
        show_cluster(clusters)
    else:
        shw = [int(c) for c in args.show[0].split(',')]
        for c in args.show[0]:
            show_cluster(clusters[c - 1])
    cmd.save(outfile)
    cmd.quit()
Exemple #27
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()
Exemple #28
0
    def Start(self):

        self.queue.put(lambda: self.FlexAID.root.withdraw())
        cmd.window('hide')
        cmd.window('show')
        # self.queue.put(lambda: cmd.window('show'))
        cmd.refresh_wizard()

        self.ErrorCode = 1        

        try:
            #self.selection_mode = cmd.get_setting_legacy("mouse_selection_mode")
            self.selection_mode = cmd.get("mouse_selection_mode")
            cmd.set("mouse_selection_mode", 0) # set selection mode to atomic

            # Mask objects
            self.exc = [self.LigDisplay, self.PossFlexDisplay, self.SelFlexDisplay]
            General_cmd.mask_Objects(self.exc)

            self.ErrorCode = 0

        except:
            self.queue.put(lambda: self.top.DisplayMessage("  ERROR: Could not start the Flexible Bonds wizard", 1))
            self.queue.put(lambda: self.top.DisplayMessage("         The wizard will abort prematurely", 1))
            self.Quit_Wizard()
            return

        # Display the ligand from the PDB file
        if self.DisplayLigand():
            self.queue.put(lambda: self.top.DisplayMessage("  ERROR: Could not display the ligand", 1))
            self.queue.put(lambda: self.top.DisplayMessage("         The wizard will abort prematurely", 1))
            self.Quit_Wizard()
            return

        # Display all Possible Flexible Bonds
        if self.show_FlexibleBonds():
            self.queue.put(lambda: self.top.DisplayMessage("  ERROR: Could not display the flexible bonds", 1))
            self.queue.put(lambda: self.top.DisplayMessage("         The wizard will abort prematurely", 1))
            self.Quit_Wizard()
            return

        # Display all Selected Flexible Bonds
        if self.show_SelectedBonds():
            self.queue.put(lambda: self.top.DisplayMessage("  ERROR: Could not display the selected flexible bonds", 1))
            self.queue.put(lambda: self.top.DisplayMessage("         The wizard will abort prematurely", 1))
            self.Quit_Wizard()
            return
        
        # remove any possible selection before selecting atoms
        cmd.deselect()
        cmd.unpick()
Exemple #29
0
    def __init__(self):
        Wizard.__init__(self)

        # some attributes to do with picking
        self.pick_count = 0
        self.object_count = 0
        self.object_prefix = "pw"

        # the plane facet size (the 'radius' of the section of plane we show)
        self.facetSize = 5

        self.selection_mode = cmd.get_setting_legacy("mouse_selection_mode")
        cmd.set("mouse_selection_mode", 0)  # set selection mode to atomic
        cmd.deselect()
    def __init__(self):
        Wizard.__init__(self)
 
        # some attributes to do with picking
        self.pick_count = 0
        self.object_count = 0
        self.object_prefix = "pw"
 
        # the plane facet size (the 'radius' of the section of plane we show)
        self.facetSize = 5
 
        self.selection_mode = cmd.get_setting_legacy("mouse_selection_mode")
        cmd.set("mouse_selection_mode",0) # set selection mode to atomic
        cmd.deselect()
Exemple #31
0
def prepare_pymol():
    cmd.set("ray_trace_color", "black")
    cmd.set("ray_trace_gain", 0)
    cmd.set("ray_trace_mode", 3)
    cmd.set("depth_cue", 0)
    cmd.clip("near", 100000)
    cmd.clip("slab", 100000)
    cmd.clip("far", -100000)
    cmd.hide("all")
    util.cbc()
    cmd.show('surface')
    cmd.bg_color("black")
    cmd.zoom("all", buffer=2.0) # buffer might help clipping problem
    cmd.center("all")
    cmd.deselect()
Exemple #32
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()
Exemple #33
0
def stucture_attribution(pdb_id, attributions_path, pdb_path, flag=False):
    '''
    '''
    data = np.load(attributions_path)
    attributions = data['data']
    kernels = data['kernels']
    labels = data['labels']
    offsets = data['offsets']
    ind = np.where(labels == pdb_id)
    #attribution = attributions[ind][0][:,-1]
    if flag:
        a_ = data["all_"][0]
        a_[a_ <= 0] = 0.0
        attribution = data['all_'][0] + data['all_'][1]
        attribution[attribution <= 0] = 0.0
        attribution = a_ * attribution
    else:
        a_ = data["all_"][1]
        a_[a_ <= 0] = 0.0
        attribution = data['all_'][0] + data['all_'][1]
        attribution[attribution <= 0] = 0.0
        attribution = a_ * attribution

    # Load PDB
    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()

    cmd.color('white', pdb_id)
    for i, _ in enumerate(attribution):
        #if flag: _ = _ *-1
        cmd.select('toBecolored',
                   pdb_id + ' and res ' + str(i + offsets[ind][0]))
        cmd.set_color('saliency' + str(i) + pdb_id, list(cmap(norm(_)))[:3])
        #else: cmd.set_color('saliency'+str(i)+pdb_id, list(cmap2(norm(_)))[:3])
        cmd.color('saliency' + str(i) + pdb_id, 'toBecolored')

    cmd.select('selected', pdb_id)
    #cmd.show('mesh', 'selected')
    #cmd.show('sticks', 'selected')
    cmd.deselect()
def residues_around_ligand(selection="het"):
    #
    # Usage:
    #       run /path/to/residues_around_ligand.py
    #       sele ATP, resname ATP
    #       residues_around_ligand ATP
    #

    cmd.select("near", "%s around 5" % selection)
    cmd.select("nearres", "br. near")
    cmd.select("sidechain", "not (name c+n+o) in nearres")
    cmd.show("sticks", "nearres")
    cmd.label("n. CA and nearres", '"%s, %s" % (resn, resi)')
    cmd.set("label_color", "white", "sidechain")
    cmd.set("label_size", "-0.6")
    cmd.color("blue", "name n*")
    cmd.color("red", "name o*")
    cmd.deselect()
    def do_select(self, selection):
        '''
        Selection callback during wizard
        Overrides method from Wizard class
        :param selection: A PyMOL selection
        :type selection: string
        '''
        cmd = self.cmd

        cmd.select(SRC_SELE, selection)
        cmd.unpick()
        try:
            self._do_mutation()
        except pymol.wizarding.WizardError as e:
            print(e)
        cmd.delete(selection)
        cmd.refresh_wizard()
        cmd.deselect()
Exemple #36
0
    def do_select(self, selection):
        '''
        Selection callback during wizard
        Overrides method from Wizard class
        :param selection: A PyMOL selection
        :type selection: string
        '''
        cmd = self.cmd

        cmd.select(SRC_SELE, selection)
        cmd.unpick()
        try:
            self._do_mutation()
        except pymol.wizarding.WizardError as e:
            print(e)
        cmd.delete(selection)
        cmd.refresh_wizard()
        cmd.deselect()
Exemple #37
0
def kernels(pdb_id, data_path, pdb_path, flag=False):
    '''
    '''
    data = np.load(data_path)
    kernels = data['kernels']
    labels = data['labels']
    offsets = data['offsets']
    ind = np.where(labels == pdb_id)
    kernels = kernels[ind][0][0]

    # Load PDB
    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 + 'kernel'
    cmd.create(pdb_id2, pdb_id)
    cmd.delete(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.9, pdb_id2 + ' and name ca')

    for i, _ in enumerate(kernels):
        print(_)
        cmd.set(
            'sphere_scale', _ / (1.7 * 2),
            pdb_id2 + ' and res ' + str(i + offsets[ind][0]) + ' and name ca')
    cmd.deselect()
Exemple #38
0
 def __init__(self, parent, bondForceParams, atoms_def):
     Wizard.__init__(self)
     self.parent = parent
     self.atoms_def = atoms_def
     self.params_str = [
         'r_aA', 'th_a', "th_A1'", 'phi_ba', 'phi_aA', 'phi_AB'
     ]
     self.indexes_list = [
         'atom_c', 'atom_b', 'atom_a', "atom_A1", "atom_B1", "atom_C1"
     ]
     self.bondForceParams = bondForceParams
     # some attributes to do with picking
     self.pick_count = 0
     self.pick_count_max = 5
     self.object_prefix = "pw"
     self.error = None
     self.selection_mode = cmd.get_setting_legacy("mouse_selection_mode")
     cmd.set("mouse_selection_mode", 0)  # set selection mode to atomic
     cmd.deselect()
 def do_select(self,selection):
     print("Selected!")
     cmd=self.cmd
     if (obj_name in cmd.get_names()):
         if cmd.count_atoms("(%s) and (%s)"%(obj_name,selection)):
             cmd.deselect()
             return 1
     if self.status!=0:
         cmd.delete(obj_name)
     cmd.select(src_sele,selection)
     cmd.unpick()
     cmd.enable(src_sele)
     self.status = 1
     self.error = None
     self.do_library()
     cmd.delete(selection)
     cmd.refresh_wizard()
     cmd.deselect()
     return 1
 def do_select(self,selection):
     print("Selected!")
     cmd=self.cmd
     if (obj_name in cmd.get_names()):
         if cmd.count_atoms("(%s) and (%s)"%(obj_name,selection)):
             cmd.deselect()
             return 1
     if self.status!=0:
         cmd.delete(obj_name)
     cmd.select(src_sele,selection)
     cmd.unpick()
     cmd.enable(src_sele)
     self.status = 1
     self.error = None
     self.do_library()
     cmd.delete(selection)
     cmd.refresh_wizard()
     cmd.deselect()
     return 1
Exemple #41
0
    def structure_attribution(self, pdb_id, flag=False):

        # Load Attribution
        data = np.load(self.attribution_path, allow_pickle=True)
        attributions = data['data']
        offsets = data['offsets']
        labels = data['labels']
        ind = np.where(labels == pdb_id)
        attribution = attributions[ind][0][:, -1]

        cmd.bg_color('white')
        cmd.load(self.data_path + pdb_id[:-2] + '.pdb')
        cmd.split_chains()
        for name in cmd.get_names('objects', 0, '(all)'):
            if not name.endswith(pdb_id[-1].upper()):
                cmd.delete(name)
            else:
                zero_residues(name)
        cmd.reset()

        cmd.color('white', pdb_id)
        for i, _ in enumerate(attribution):
            cmd.select('toBecolored', 'res ' + str(i + offsets[ind][0]))
            cmd.set_color('saliency' + str(i), list(cmap(norm(_)))[:3])
            cmd.color('saliency' + str(i), 'toBecolored')

        cmd.select('selected', 'chain ' + pdb_id[-1].upper())
        #cmd.show('mesh', 'selected')
        cmd.deselect()
        cmd.save(self.output_path + pdb_id + '.pse')
        return self.output_path + pdb_id + '.pse'


#############################################################
# pdb_id = '4q9z_a'
# attributions_path = 'Output/Kinases/seed1/attributions.npz'
# data_path = 'pdb_extractor/Kinases/PDB/'

# cmd.reinitialize()
# cmd.bg_color('black')
# sA = StructureAttribution(attributions_path,data_path)
# sA.structure_attribution(pdb_id)
Exemple #42
0
 def reset(self):
     default_thoroughness = "thorough"
     default_label = "R1"
     default_cutoff = 3.4
     default_clashes = 0
     default_mode = "Search"
     default_vdwRestraints = "tight"
     internalClash_cutoff = 2.5
     self.homoOligomerMode = False
     self.running = False
     self.toggleStatesCaption = "Toggle states: ON"
     self.object_prefix = "mW-"
     self.pickCount = 0
     self.object_count = 0
     self.vdwRestraints = "tight"
     self.thoroughness = default_thoroughness
     self.cutoff = default_cutoff
     self.clashes = default_clashes
     self.set_currentLabel(default_label)
     self.residue1Name = None
     self.residue2Name = None
     self.pickedObject1 = None
     self.pickedObject2 = None
     self.numberOfLabel = 0
     self.mode = default_mode
     self.writeToFile = False
     self.label = None
     #create array for plots
     try:
         print stored.plots
     except:
         print "Created plots list."
         stored.plots = []
     cmd.set("mouse_selection_mode", 1)  # set selection mode to residue
     cmd.deselect()
     cmd.unpick()
     cmd.delete("sele*")
     cmd.delete("_indicate*")
     cmd.delete("pk*")
     cmd.delete("*_tmp*")
     cmd.refresh_wizard()
Exemple #43
0
    def closeAutoMotifForTesting(self):
        if glb.GUI.motif_maker['radio'].get() == 1:
            cmd.reinitialize()
            cmd.fetch(glb.GUI.motif_maker['testpdb'].get(),
                      async=0,
                      path=glb.FETCH_PATH)
            glb.update()
        elif glb.GUI.motif_maker['radio'].get() == 2:
            glb.randompdb()

        d = 1

        lines = ''.join(glb.GUI.motif_maker['motif']).split('\n')
        for line in lines:
            if line != '':
                eval(line)
        cmd.select('matching_subset', self.name)
        # I think here it's OK to delete the motif name
        cmd.delete(self.name)
        cmd.deselect()
        return True
Exemple #44
0
 def showAround(self):
     if not self.logData["displaying"]:
         return
     
     radius = self.ent_around.get()
     try:
         radius = float(radius)
     except:
         return
     
     if self.chkvar_around.get() > 0 and not self.logData["displayingAround"]:
         selectionAroundName = "suprAround"
         cmd.select( selectionAroundName,  "byres ( suprSelection around "+str(radius)+" ) " )
         cmd.show("lines", selectionAroundName)
         self.logData["displayingAround"] = True
     elif self.chkvar_around.get() == 0 and self.logData["displayingAround"]:
         cmd.hide("lines" , "suprAround")
         cmd.delete("suprAround")
         self.logData["displayingAround"] = False
         
     cmd.deselect()
Exemple #45
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
Exemple #46
0
    def __init__(self, _self=cmd):

        cmd.unpick();
        Wizard.__init__(self, _self)

        self.mouse_selection_mode = cmd.get_setting_int('mouse_selection_mode')
        cmd.set('mouse_selection_mode',0) # set selection mode to atomic
        cmd.deselect() # disable the active selection (if any)

        self.error = None
        self.selection_mode = 1 if self.mouse_selection_mode == 6 else 0
        self.selection_modes = [
            'Residues',
            'C-alphas',
        ]

        smm = []
        smm.append([ 2, 'Selection Mode', '' ])
        for i, label in enumerate(self.selection_modes):
            smm.append([1, label, 'cmd.get_wizard().set_mode(%d)' % i])
        self.menu['selection_mode'] = smm

        self.name = None
 def testDeselect(self):
     cmd.load(self.datafile("1oky.pdb.gz"), "m1")
     cmd.select("all")
     self.assertEquals("sele" in cmd.get_names("all",enabled_only=1), True)
     cmd.deselect()
     self.assertEquals("sele" in cmd.get_names("all",enabled_only=1), False)
# DEBUG: ANALYSIS PATH IS HARD-CODED FOR NOW
source_directory = 'output'

reference_pdbfile = 'setup/complex-implicit-initial.pdb'
phase = 'complex-implicit'
replica = 0 # replica index to render
#replica = 15 # replica index to render

# Load PDB file.
cmd.rewind()
cmd.delete('all')
cmd.reset()
cmd.load(reference_pdbfile, 'complex')
cmd.select('receptor', 'not chain C and not hydrogen')
cmd.select('ligand', 'chain C and not hydrogen')
cmd.deselect()
cmd.hide('all')
cmd.show('cartoon', 'receptor')
cmd.show('sticks', 'ligand')
util.cbay('ligand')
cmd.color('green', 'receptor')

# speed up builds
cmd.set('defer_builds_mode', 3)
cmd.set('cache_frames', 0)

model = cmd.get_model('complex')
#for atom in model.atom:
#    print "%8d %4s %3s %5d %8.3f %8.3f %8.3f" % (atom.index, atom.name, atom.resn, int(atom.resi), atom.coord[0], atom.coord[1], atom.coord[2])

# Read atoms from PDB
Exemple #49
0
def visualize_in_pymol(plcomplex):
    """Visualizes the protein-ligand pliprofiler at one site in PyMOL."""

    vis = PyMOLVisualizer(plcomplex)

    #####################
    # Set everything up #
    #####################

    pdbid = plcomplex.pdbid
    lig_members = plcomplex.lig_members
    chain = plcomplex.chain
    if config.PEPTIDES != []:
        vis.ligname = 'PeptideChain%s' % plcomplex.chain
    if config.INTRA is not None:
        vis.ligname = 'Intra%s' % plcomplex.chain

    ligname = vis.ligname
    hetid = plcomplex.hetid

    metal_ids = plcomplex.metal_ids
    metal_ids_str = '+'.join([str(i) for i in metal_ids])

    ########################
    # Basic visualizations #
    ########################

    start_pymol(run=True, options='-pcq', quiet=not config.DEBUG)
    vis.set_initial_representations()

    cmd.load(plcomplex.sourcefile)
    current_name = cmd.get_object_list(selection='(all)')[0]
    write_message('Setting current_name to "%s" and pdbid to "%s\n"' % (current_name, pdbid), mtype='debug')
    cmd.set_name(current_name, pdbid)
    cmd.hide('everything', 'all')
    if config.PEPTIDES != []:
        cmd.select(ligname, 'chain %s and not resn HOH' % plcomplex.chain)
    else:
        cmd.select(ligname, 'resn %s and chain %s and resi %s*' % (hetid, chain, plcomplex.position))
    write_message("Selecting ligand for PDBID %s and ligand name %s with: " % (pdbid, ligname), mtype='debug')
    write_message('resn %s and chain %s and resi %s*' % (hetid, chain, plcomplex.position), mtype='debug')

    # Visualize and color metal ions if there are any
    if not len(metal_ids) == 0:
        vis.select_by_ids(ligname, metal_ids, selection_exists=True)
        cmd.show('spheres', 'id %s and %s' % (metal_ids_str, pdbid))

    # Additionally, select all members of composite ligands
    if len(lig_members) > 1:
        for member in lig_members:
           resid, chain, resnr = member[0], member[1], str(member[2])
           cmd.select(ligname, '%s or (resn %s and chain %s and resi %s)' % (ligname, resid, chain, resnr))

    cmd.show('sticks', ligname)
    cmd.color('myblue')
    cmd.color('myorange', ligname)
    cmd.util.cnc('all')
    if not len(metal_ids) == 0:
        cmd.color('hotpink', 'id %s' % metal_ids_str)
        cmd.hide('sticks', 'id %s' % metal_ids_str)
        cmd.set('sphere_scale', 0.3, ligname)
    cmd.deselect()

    vis.make_initial_selections()

    vis.show_hydrophobic()  # Hydrophobic Contacts
    vis.show_hbonds()  # Hydrogen Bonds
    vis.show_halogen()  # Halogen Bonds
    vis.show_stacking()  # pi-Stacking Interactions
    vis.show_cationpi()  # pi-Cation Interactions
    vis.show_sbridges()  # Salt Bridges
    vis.show_wbridges()  # Water Bridges
    vis.show_metal()  # Metal Coordination

    vis.refinements()

    vis.zoom_to_ligand()

    vis.selections_cleanup()

    vis.selections_group()
    vis.additional_cleanup()
    if config.DNARECEPTOR:
        # Rename Cartoon selection to Line selection and change repr.
        cmd.set_name('%sCartoon' % plcomplex.pdbid, '%sLines' % plcomplex.pdbid)
        cmd.hide('cartoon', '%sLines' % plcomplex.pdbid)
        cmd.show('lines', '%sLines' % plcomplex.pdbid)

    if config.PEPTIDES != []:
        filename = "%s_PeptideChain%s" % (pdbid.upper(), plcomplex.chain)
        if config.PYMOL:
            vis.save_session(config.OUTPATH, override=filename)
    elif config.INTRA is not None:
        filename = "%s_IntraChain%s" % (pdbid.upper(), plcomplex.chain)
        if config.PYMOL:
            vis.save_session(config.OUTPATH, override=filename)
    else:
        filename = '%s_%s' % (pdbid.upper(), "_".join([hetid, plcomplex.chain, plcomplex.position]))
        if config.PYMOL:
            vis.save_session(config.OUTPATH)
    if config.PICS:
        vis.save_picture(config.OUTPATH, filename)
    cmd.viewport(800, 800)


setup_pymol()

# After setting up PyMOL, we will load a PDB file an prepare it for a simple use case.
# Let's show the complex between Cathepsin K and one of its inhibitors (PDB ID 1VSN)

cmd.load('../../input-files/Cathepsin.pdb')  # Load the PDB file

# A good starting point for an animation is to hide all representation to start from scratch
# Then, we want to show the protein in cartoon representation and its ligand in ball-and-stick representation
cmd.hide('everything', 'all')  # Hide everything
cmd.show('cartoon', 'all')  # Show protein in cartoon representation
cmd.select('ligand', 'resn NFT')  # Select the ligand (NFT)
cmd.deselect()  # Deselect everything to hide the selection markers in PyMOL
cmd.show("sticks", "ligand")  # Show the ligand in ball-and-stick representation

# Now let's zoom out to show the whole protein and then do a close-up on the ligand.
# In both cases, we will save the camera perspective as a scene.
# We can switch between saved scenes and connect them later. It's just like in a movie storyboard.
cmd.zoom('Cathepsin', 10)  # Zoom out to get a view on the whole complex
cmd.scene('001', 'store', message='This is the first scene with a view on the complex!')  # Save the first scene (001)
cmd.zoom('ligand', 5)  # Get a close-up of the ligand
cmd.scene('002', 'store', message='This is the second scene with a close-up on the ligand!')  # Save the second scene


# Running the script, PyMOL should display you the complex with the chosen representations and two scenes
# The scenes are accessible in the lower left corner. You can click on the buttons to switch between them.
# We can use this feature later to connect the scenes and make a smooth transition for the movie.
# Note that the scene messages are optional, i.e. you can omit the message argument.
def color_by_mutation(obj1, obj2, waters=0, labels=0):
    '''
    DESCRIPTION
 
        Creates an alignment of two proteins and superimposes them. 
        Aligned residues that are different in the two (i.e. mutations) are highlighted and 
        colored according to their difference in the BLOSUM90 matrix. 
        Is meant to be used for similar proteins, e.g. close homologs or point mutants, 
        to visualize their differences.      
 
    USAGE
 
        color_by_mutation selection1, selection2 [,waters [,labels ]]
 
    ARGUMENTS
 
        obj1: object or selection
 
        obj2: object or selection    
 
        waters: bool (0 or 1). If 1, waters are included in the view, colored
                differently for the both input structures.
                default = 0
 
        labels: bool (0 or 1). If 1, the possibly mutated sidechains are 
                labeled by their chain, name and id
                default = 0
 
    EXAMPLE
 
        color_by_mutation protein1, protein2
 
    SEE ALSO
 
        super
    '''
    from pymol import stored, CmdException
 
    if cmd.count_atoms(obj1) == 0:
        print '%s is empty'%obj1
        return
    if cmd.count_atoms(obj2) == 0:
        print '%s is empty'%obj2
        return
    waters = int(waters)
    labels = int(labels)
 
    # align the two proteins
    aln = '__aln'
 
    # first, an alignment with 0 cycles (no atoms are rejected, which maximized the number of aligned residues)
    # for some mutations in the same protein this works fine). This is essentially done to get a
    # sequence alignment
    cmd.super(obj1, obj2, object=aln, cycles=0)
 
    # superimpose the the object using the default parameters to get a slightly better superimposition,
    # i.e. get the best structural alignment    
    cmd.super(obj1, obj2)
 
    stored.resn1, stored.resn2 = [], []
    stored.resi1, stored.resi2 = [], []
    stored.chain1, stored.chain2 = [], []
 
    # store residue ids, residue names and chains of aligned residues
    cmd.iterate(obj1 + ' and name CA and ' + aln, 'stored.resn1.append(resn)')
    cmd.iterate(obj2 + ' and name CA and ' + aln, 'stored.resn2.append(resn)')
 
    cmd.iterate(obj1 + ' and name CA and ' + aln, 'stored.resi1.append(resi)')
    cmd.iterate(obj2 + ' and name CA and ' + aln, 'stored.resi2.append(resi)')
 
    cmd.iterate(obj1 + ' and name CA and ' + aln, 'stored.chain1.append(chain)')
    cmd.iterate(obj2 + ' and name CA and ' + aln, 'stored.chain2.append(chain)')
 
 
    mutant_selection = '' 
    non_mutant_selection = 'none or '
    colors = []
 
    # loop over the aligned residues
    for n1, n2, i1, i2, c1, c2 in zip(stored.resn1, stored.resn2,
                                      stored.resi1, stored.resi2,
                                      stored.chain1, stored.chain2):
        # take care of 'empty' chain names
        if c1 == '':
            c1 = '""'
        if c2 == '':
            c2 = '""'
        if n1 == n2:
            non_mutant_selection += '((%s and resi %s and chain %s) or (%s and resi %s and chain %s)) or '%(obj1, i1, c1, obj2, i2, c2 )            
        else:
            mutant_selection += '((%s and resi %s and chain %s) or (%s and resi %s and chain %s)) or '%(obj1, i1, c1, obj2, i2, c2 )
            # get the similarity (according to the blosum matrix) of the two residues and
            c = getBlosum90ColorName(n1, n2)
            colors.append((c, '%s and resi %s and chain %s and elem C'%(obj2, i2, c2)))
 
    if mutant_selection == '':
        print ' Error: No mutations found'
        raise CmdException
 
    # create selections        
    cmd.select('mutations', mutant_selection[:-4])
    cmd.select('non_mutations', non_mutant_selection[:-4])
    cmd.select('not_aligned', '(%s or %s) and not mutations and not non_mutations'%(obj1, obj2))
 
    # create the view and coloring
    cmd.hide('everything', '%s or %s'%(obj1, obj2))
    cmd.show('cartoon', '%s or %s'%(obj1, obj2))
    cmd.show('lines', '(%s or %s) and ((non_mutations or not_aligned) and not name c+o+n)'%(obj1, obj2))
    cmd.show('sticks', '(%s or %s) and mutations and not name c+o+n'%(obj1, obj2))
    cmd.color('gray', 'elem C and not_aligned')
    cmd.color('white', 'elem C and non_mutations')
    cmd.color('blue', 'elem C and mutations and %s'%obj1)
    for (col, sel) in colors:
        cmd.color(col, sel)
 
    cmd.hide('everything', '(hydro) and (%s or %s)'%(obj1, obj2))        
    cmd.center('%s or %s'%(obj1, obj2))
    if labels:
        cmd.label('mutations and name CA','"(%s-%s-%s)"%(chain, resi, resn)')    
    if waters:
        cmd.set('sphere_scale', '0.1')
        cmd.show('spheres', 'resn HOH and (%s or %s)'%(obj1, obj2))
        cmd.color('red', 'resn HOH and %s'%obj1)
        cmd.color('salmon', 'resn HOH and %s'%obj2)
    print '''
             Mutations are highlighted in blue and red.
             All mutated sidechains of %s are colored blue, the corresponding ones from %s are
             colored on a spectrum from blue to red according to how similar the two amino acids are
             (as measured by the BLOSUM90 substitution matrix).
             Aligned regions without mutations are colored white.
             Regions not used for the alignment are gray.
             NOTE: There could be mutations in the gray regions that were not detected.'''%(obj1, obj2)
    cmd.delete(aln)
    cmd.deselect()
Exemple #52
0
	def displayLargestHydrophobicPatch(self):
		""" Method which gets executed when the user selected "display largest hydrophobic patch" in the Rosetta Tools GUI"""

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

		# we have to pass the path to the QUILT executable to this method somehow
		# the easiest way is to have a config file in the users home directory
		self.path_to_quilt_executable = 0
		
		init_file_name = os.environ['HOME'] + '/.rosettatoolsplugin'
		if ( os.path.exists(init_file_name) ):
			init_file = open( init_file_name, "r" )
			for line in init_file.xreadlines():
				if ( line.find("quilt_executable") != -1 ):
					self.path_to_quilt_executable = line.split()[1]
			init_file.close()

		if ( self.path_to_quilt_executable == 0 ):
			showerror('Rosetta Tools Plugin: ERROR', "You need to specify a path to a QUILT executable in a file named '.rosettatoolsplugin' " \
						"in your home directory.\nquilt_executable path/to/executable", parent=self.parent )
			return

		print "Rosetta Tools Plugin: Running QUILT to find hydrophobic patches..."

		# 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 patches for all of them
		object_list = cmd.get_names("objects", enabled_only=1)
		selection_list = cmd.get_names("all")
		for object in object_list:

			# don't try to find patches for things that are not structures - this is a consequence of calling get_names() for
			# all enabled objects
			if ( object.endswith("-hb") ):
				continue
			
			# don't recreate the patches if they're already there. this allows one to load a structure,
			# visualize the patches in that structures, load another structure and visualize again
			# but the quilt run is not performed again.
			if ( ( object + "-hpatch" ) in selection_list ):
				print "Rosetta Tools Plugin: Largest hydrophobic patch for object '" + object + "' already exists. Delete CGO object to redetermine patch."
				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 -n 252 -ep 1.0 -P CS \"%s\"" % (self.path_to_quilt_executable, 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 QUILT to generate hydrophobic patch 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.

			# parse the output of the command
			patch_data_start = 0
			individual_patch_data = []
			all_patch_data = []
			for line in output.split("\n"):
				if ( string.find( line,"# 0") != -1 ): # start reading after we see the 1st largest patch line
					patch_data_start = 1
					continue
				if ( string.find( line, "# " ) != -1 ): # stop if we get to the 2nd largest patch
					all_patch_data.append( individual_patch_data )
					individual_patch_data = []
					continue

				if ( patch_data_start ):
					if ( string.find( line, "% " ) != -1 ): # ignore the lines that start with '%'
						continue
					else:
						individual_patch_data.append(line)

			if ( len(all_patch_data) == 0 ):
				print "Rosetta Tools Plugin: Hydrophobic patch info not found in output from quilt command."
			else:
				#print allPatchData
				print "Rosetta Tools Plugin: The following atoms are in hydrophobic patches:"
				patch_num = 1
				for patch_data in all_patch_data:
				
					print "Patch " + str(patch_num) + ": "
					# parse up the lines into 2-tuples containing the residue number and atom name
					# don_chain, don_resi, don_resn, don_res_atom, acc_chain, acc_resi, acc_resn, acc_atom, energy, distance) )
					patch_data_tuples = self.getPatchData( patch_data )

					sele_expr = ""
					
					# PyMOL can't handle long (~100-200 character) selection expressions. have to break down the really
					# long expressions into multiple selections
					line_count = 0
					
					# now go through the tuples and add them to the selection expression
					for tuple in patch_data_tuples:
					
						# we need the object name && residue and atom name for all atoms in the patch
						resnum = tuple[0]
						chain = tuple[1]
						atomname = tuple[2]
						
						if ( line_count != 0 ):
							sele_expr = object + "-hpatch" + str(patch_num) + " /" + '/'.join([ object, '', chain, resnum, atomname ])
						else:
							sele_expr = '/' + '/'.join([ object, '', chain, resnum, atomname ])
							
						#print sele_expr
						patch_sele = object + "-hpatch" + str(patch_num)

						try:
							cmd.select( patch_sele, sele_expr )
						except:
							print sele_expr
							print "Rosetta Tools Plugin: ERROR 007: Error in coloring patch."
							continue
						sele_expr = ""
						
						line_count += 1

					# only want to display the three largest hydrophobic patches - NOT all of them
					patch_num += 1
					if ( patch_num > 3 ):
						break

				cmd.show("spheres", object)
				cmd.color("sand", object)
				cmd.util.cnc("all")
				cmd.color("green", object + "-hpatch1")
				cmd.color("palegreen", object + "-hpatch2")
				cmd.color("gray80", object + "-hpatch3")
				cmd.hide("(all and hydro)")
				cmd.deselect()
			
			print "Rosetta Tools Plugin: Object " + object + " finished."

		# restore the saved view
		cmd.set_view(my_view)
 def gpssCastp(pdbCode,reinitialize):
     # David Borhani, 14-JAN-2009
     # Modified extensively to make this faster, more useful.
     
     GPSSpdbCode = 'GPSS_' + pdbCode
     if _gpssLoadPdb(pdbCode,reinitialize):
         
         # Get pocket count and pocket/cavity summary information
         castpInfo = urllib2.urlopen('http://gpss.mcsg.anl.gov/webservices/'+
                                     'gpssServerPymol.php?pdbId='+
                                     pdbCode + '&mode=castpInfo')
         castp_pocinfo = castpInfo.readlines()
         castpLength = int(castp_pocinfo[-1][13:16])
         n_pockets = castpLength
         
         # Write out pocket information file:
         pocinfo = pdbCode + '.pocinfo'
         f_pocinfo = open(pocinfo, 'w')
         for line in castp_pocinfo:
             f_pocinfo.write(line)
         f_pocinfo.close()
         
         # Write out CAVITY ("n_mouth" = 0) information file:
         cavinfo = pdbCode + '.cavinfo'
         f_cavinfo = open(cavinfo, 'w')
         f_cavinfo.write('\t\t\t>>>>>  CAVITIES ONLY  <<<<<\n')
         f_cavinfo.write(castp_pocinfo[0]) # Header line
         for line in castp_pocinfo[1:]:
             if (line[16:20] == '   0'):
                     f_cavinfo.write(line)
         f_cavinfo.close()
         
         # Get ALL pocket atoms, ordered from largest pocket to smallest...
         poc = pdbCode + '.poc'
         f_poc = open(poc, 'w')
         while castpLength > 0:
             castpSurfaceFile = urllib2.urlopen('http://gpss.mcsg.anl.gov/webservices/'+
                                                'gpssServerPymol.php?pdbId='+
                                                pdbCode + '&surfaceId='+str(castpLength)+
                                                '&mode=castpSurface')
             CASTpSelId = 'CASTp_' + pdbCode + '_' + str(castpLength)
             # Get the URL data all as one string (complete w/ \n's)
             castp_surf = castpSurfaceFile.read()
             
             # Write it to the file
             f_poc.write('>>>>> POCKET '+CASTpSelId+'\n')
             f_poc.write(castp_surf)
             
             # Create a PyMOL object from the string...
             # David Borhani, 14-JAN-2009
             # NO, WAY TOO SLOW. Create a SELECTION instead.
             #cmd.read_pdbstr(castp_surf,CASTpSelId)
             #cmd.do('hide everything,' + CASTpSelId)
             
             # List of atom (numbers, as STRING) in this pocket
             poc_atoms = []
             for line in castp_surf.splitlines():
                 atmnum = line[6:11].strip()
                 if(atmnum.isdigit()):
                     if len(poc_atoms) == 0:
                         poc_atoms = [atmnum]
                     else:
                         poc_atoms.append(atmnum)
             
             # Create the PyMOL selection:
             poc_atoms_range = yield_ranges(poc_atoms)
             # Key point from Warren DeLano:
             # Create selection in chunks so that don't exceed ~1024 characters
             chunk = 50
             cmd.select(CASTpSelId, 'none', quiet=0, enable=0)
             while len(poc_atoms_range):
                 id_pat = string.join(poc_atoms_range[0:chunk],"+")
                 cmd.select(CASTpSelId,'?'  +CASTpSelId + ' & ' + GPSSpdbCode + \
                     ' | (id ' + id_pat + ')', quiet=0, enable=0)
                 poc_atoms_range = poc_atoms_range[chunk:]
             
             ### WAY TOO SLOW TO SHOW THE SURFACES OF ALL POCKETS!
             # Also, the surfaces are inaccurate, as only some of the totality of atoms
             # are present, so true cavities may appear to just be invaginations.
             ######cmd.do('show surface,' + CASTpSelId)
             ######cmd.do('set transparency=0.2,'+ CASTpSelId) 
             
             castpLength -= 1
             
         f_poc.close()
         
         # Display the three files, so the user can DETERMINE which
         #  pockets/cavities are of interest.
         file_to_open = [poc, pocinfo, cavinfo]
         if (sys.platform).upper() != 'WIN32':
             # Set up xwindow geometry
             window_offset = 40
             window_x = self.window_width/2
             #window_y = self.window_height
             for (i, win) in enumerate(file_to_open):
                 x = window_x + i*window_offset
                 y = i*window_offset
                 geometry = '-geometry 80x40+%d+%d' % (x,y)
                 xterm_command= 'xterm -j +ls -rightbar ' + geometry + ' -title ' + \
                   win + ' -e vim ' + win
                 task = subprocess.Popen(xterm_command.split())
         else:
             for win in file_to_open:
                 wordpad_command= 'C:\\Program Files\\DeLano Scientific\\PyMOL\\modules\\pmg_tk\\wordpad.exe ' + '.\\' + win
                 task = subprocess.Popen(wordpad_command.split())
                     
     # And shut off all selections
     cmd.deselect()
     cmd.zoom(GPSSpdbCode, animate=0)
     cmd.set('two_sided_lighting', '1', quiet=0)
     print '\nCASTp> Created %d pocket/cavity selections for PDB entry %s\n' \
       % (n_pockets,pdbCode)
def pairwise_dist(pdbfile,sel1, sel2, max_dist, output="P", sidechain="N", show="N",outfile="./"):
	"""
	usage: pairwise_dist sel1, sel2, max_dist, [output=S/P/N, [sidechain=N/Y, [show=Y/N]]]
	sel1 and sel2 can be any to pre-existing or newly defined selections
	max_dist: maximum distance in Angstrom between atoms in the two selections
	--optional settings:
	output: accepts Screen/Print/None (default N)
	sidechain: limits (Y) results to sidechain atoms (default N)
	show: shows (Y) individual distances in pymol menu (default=N)
	"""
	print ""
	cmd.delete ("dist*")
	extra=""
	if sidechain=="Y": extra=" and not name c+o+n"
 
	#builds models
	m1=cmd.get_model(sel2+" around "+str(max_dist)+" and "+sel1+extra)
	m1o=cmd.get_object_list(sel1)
	m2=cmd.get_model(sel1+" around "+str(max_dist)+" and "+sel2+extra)
	m2o=cmd.get_object_list(sel2)
 
	#defines selections
	cmd.select("__tsel1a", sel1+" around "+str(max_dist)+" and "+sel2+extra)
	cmd.select("__tsel1", "__tsel1a and "+sel2+extra)
	cmd.select("__tsel2a", sel2+" around "+str(max_dist)+" and "+sel1+extra)
	cmd.select("__tsel2", "__tsel2a and "+sel1+extra)
	cmd.select("IntAtoms_"+str(max_dist), "__tsel1 or __tsel2")
	cmd.select("IntRes_"+str(max_dist), "byres IntAtoms_"+str(max_dist))
 
	#controlers-1
	if len(m1o)==0: 
		print "warning, '"+sel1+extra+"' does not contain any atoms."
		return
	if len(m2o)==0: 
		print "warning, '"+sel2+extra+"' does not contain any atoms."
		return
 
	#measures distances
	s=""
	counter=0
	for c1 in range(len(m1.atom)):
		for c2 in range(len(m2.atom)):
			distance=math.sqrt(sum(map(lambda f: (f[0]-f[1])**2, zip(m1.atom[c1].coord,m2.atom[c2].coord))))
			if distance<float(max_dist):
				s+="%s/%s/%s/%s/%s to %s/%s/%s/%s/%s: %.3f\n" % (m1o[0],m1.atom[c1].chain,m1.atom[c1].resn,m1.atom[c1].resi,m1.atom[c1].name,m2o[0],m2.atom[c2].chain,m2.atom[c2].resn,m2.atom[c2].resi,m2.atom[c2].name, distance)
				counter+=1
				if show=="Y": cmd.distance (m1o[0]+" and "+m1.atom[c1].chain+"/"+m1.atom[c1].resi+"/"+m1.atom[c1].name, m2o[0]+" and "+m2.atom[c2].chain+"/"+m2.atom[c2].resi+"/"+m2.atom[c2].name)
 
	#controler-2
	if counter==0: 
		print "warning, no distances were measured! Check your selections/max_dist value"
		return
 
	#outputs
	if output=="S": print s
	if output=="P":
                filename=os.getcwd()+'/interface_analyzer/'+pdbfile+'_distance'+str(max_dist)
		f=open(filename,'w')
		f.write("Number of distances calculated: %s\n" % (counter))
		f.write(s)
		f.close()
		print "Results saved in _%s" % filename 
	print "Number of distances calculated: %s" % (counter)
	cmd.hide("lines", "IntRes_*")
	if show=="Y": cmd.show("lines","IntRes_"+max_dist)
	cmd.deselect()