Example #1
0
    def add_selected_positions(self, selection='sele'):
        """
        Add any positions currently in the given selection to the list of 
        mutations to show (even if those positions are not in fact mutations).
        """
        wt_obj = self.wildtype_obj
        mut_obj = self.mutant_obj

        if 'wt_env' in cmd.get_names('objects'):
            wt_obj = '({}) or wt_env'.format(wt_obj)
        if 'mut_env' in cmd.get_names('objects'):
            mut_obj = '({}) or mut_env'.format(mut_obj)

        wt_resis = get_residues('({}) and ({})'.format(selection, wt_obj))
        mut_resis = get_residues('({}) and ({})'.format(selection, mut_obj))
        
        for resi in wt_resis:
            muti = self.aligned_resis[0].index(resi)
            self.extra_positions.add(muti)

        for resi in mut_resis:
            muti = self.aligned_resis[1].index(resi)
            self.extra_positions.add(muti)

        self.update_mutation_list()
        self.redraw()
Example #2
0
def fisapt():
    
    # Make it pretty 
    cmd.show("sticks", "all")

    # Initialize pm molecule object
    total_molecule = read_original_geometry()

    allowed_classifications = ['A', 'B', 'C']
    # Take in user border atoms
    frag_names = cmd.get_names("all")[1:]
    frags = {}
    for name in frag_names:
        classification = name.split('_')[-1].upper()
        if classification not in allowed_classifications: 
            print("USAGE!")
            sys.exit()
        frags[name] = []
        stored.list=[]
        cmd.iterate("("+name+")","stored.list.append((name,rank))")
        for atom in stored.list: 
            frags[name].append(atom[1])
        
        # All C fragments are in "ISAPT_C"
        if classification == 'C':
            cmd.delete(name)

    # Fill up with fragments and color the fragments 
    fragments = total_molecule.cut(frags)

    # Should write input, fA, and fB outside of class, need info from above
    total_molecule.write_input(fragments, fil_name = cmd.get_names("all")[0]+".in")
Example #3
0
def drab(nlim=-2.0, plim=2.0):
    #zero the indexes
    #zero_residues("all", 1, 1)
    #Read the values in
    fileName = cmd.get_names()[0]
    print fileName
    fileName = fileName + ".dat"
    cmd.alter("all", "b=0.0")
    #file = open(fileName, 'r')
    #table = [row.strip().split('\t') for row in file]
    bVals = []
    #print table
    for line in file(fileName):
        line = line.strip().split()
        if (line[0][0] != "#"):
            selection = "resi %s" % line[0]
            #Normalize the values
            bval = (float(line[1]) - nlim) / (plim - nlim)
            #print bval
            cmd.alter(selection, "b=%f" % bval)
            print(selection, "b=%f" % bval)
            bVals.append([selection, bval])
    cmd.hide("all")
    cmd.show("cartoon")
    cmd.spectrum("b", "blue_white_red", "all", "0.0", "1.0", "1")
    cmd.ramp_new("rawFac_ramp",
                 cmd.get_names()[0], [nlim, plim],
                 color="[blue, white, red ]")
    cmd.recolor()
Example #4
0
def load_alignment(filename, object1=None, object2=None, delimiter="_"):
    """DESCRIPTION

    Structural comparison tools from the PDB website can save aligned
    structures as a two-model structure. This function loads such a file and
    splits the structures into two pymol objects for easy comparison.

USAGE

    load_alignment filename[, object1, object2][, delimiter]

ARGUMENTS

    filename    Path to the PDB file
    object1     What to name the first model from the file [optional]
    object2     What to name the second model from the file [optional]
    delimiter   Delimiter which separates object1 and object2 in the filename.
                See DETAILS. [default '_']

DETAILS

    The input file must contain at least two states (MODEL lines in the PDB
    file). Additional states are ignored.

    If object1 and object2 are ommitted, the script will attempt to generate
    them based on the filename. The extension is first removed from the
    filename, then the name is split around the first instance of <delimiter>.
    Thus, alignment files which follow the convention "object1_object2.pdb"
    will be properly split without additional arguments.

EXAMPLES

    # Results in objects '1AX8.A' and '3PIV.A'
    load_alignment 1AX8.A_3PIV.A.pdb

    # Results in objects 'query' and 'target'
    load_alignment alignment.pdb, query, target

    # Results in objects '1AX8.A' and '3PIV.A'
    load_alignment 1AX8.A_vs_3PIV.A.pdb, delimiter="_vs_"
"""
    # load the file, which should generate a new object
    num_objects = len(cmd.get_names("objects"))
    cmd.load(filename)
    objects = cmd.get_names("objects")
    if len(objects) != num_objects + 1:
        # an error occured with loading
        print ("Error loading file")
        return
    obj = objects[-1]

    if cmd.count_states(obj) >= 2:
        # split the object
        split_alignment(obj, object1, object2, delimiter)

        # clean up
        cmd.delete(obj)
    else:
        print ("Error: Expected 2 models in %s, but found %d." % filename, cmd.count_states(obj))
        return
Example #5
0
    def selectoption2(self):
        self.file.toggle()
        if (self.sv.get() == 0):
            self.fv.set(0)
            self.sv.set(1)
            self.entry1.config(state=DISABLED)
            self.browserButton.config(state=DISABLED)
            self.lb1.config(state="normal")
            self.lb1.delete(0, 'end')

            objects = cmd.get_names("all")
            objects.extend(["Pick object"])
            for x in objects:
                self.lb1.insert(END, x)
        else:
            self.sv.set(0)
            self.fv.set(1)
            self.entry1.config(state="normal")
            self.browserButton.config(state="normal")
            self.lb1.config(state=DISABLED)
            # self.vsb.config(state="normal")
            self.lb1.delete(0, 'end')
            objects = cmd.get_names("all")
            objects.extend(["Pick object"])
            for x in objects:
                self.lb1.insert(END, x)
def find_pdb_file(mut, flex):
    """
    Find the pdb file of a pymol selection

    This function checks the current working directory for a pdb file with the
    same name as the selection model. This will ONLY work if the file is in the
    cwd.

    Args:
        mut (str): PyMol selection name for the mutable design residues
        flex(str): PyMol selection name for the flexible design residues
    """
    mut_obj_list = cmd.get_names("objects", 0, mut)
    flex_obj_list = cmd.get_names("objects", 0, flex)

    assert len(mut_obj_list) == 1, "ERROR!: mut_obj_list has length %d, not 1." %len(mut_obj_list)
    assert len(flex_obj_list) == 1, "ERROR!: flex_obj_list has length %d, not 1." %len(flex_obj_list)

    mut_obj = mut_obj_list[0]
    flex_obj = flex_obj_list[0]

    assert mut_obj == flex_obj

    pdb_rel = mut_obj+".pdb"

    if os.path.isfile(pdb_rel):
        # Return the absolute path to the pdb
        return os.path.abspath(pdb_rel)
        # Return the relative path to the pdb
        # return pdb_rel
    else:
        print("WARNING! Could not find pdb file. Please set manually")
        return "UNSET"
Example #7
0
    def testFetchLocal(self):
        try:
            import urllib.parse as urlparse
        except ImportError:
            import urlparse

        # PyMOL 1.8.6 adds full URLs, remove them
        import pymol
        pdbpaths = pymol.importing.hostPaths['pdb']
        pdbpaths[:] = [p for p in pdbpaths if '://' not in p]

        with testing.mkdtemp() as fetch_path:
            names = []
            cmd.set('fetch_path', fetch_path)
            cmd.set('fetch_host', urlparse.urlunsplit(['file', '',
                self.datafile('pdb.mirror'), '', '']))

            cmd.fetch('1avy', type='pdb')
            names += ['1avy']
            self.assertItemsEqual(cmd.get_names(), names)

            cmd.fetch('1avyB', type='pdb')
            names += ['1avyB']
            self.assertItemsEqual(cmd.get_names(), names)
            self.assertEqual(cmd.get_chains('1avyB'), ['B'])

            cmd.fetch('1aq5', type='pdb', multiplex=1)
            names += ['1aq5_%04d' % (i+1) for i in range(20)]
            self.assertItemsEqual(cmd.get_names(), names)
Example #8
0
    def testFetchLocal(self):
        try:
            import urllib.parse as urlparse
        except ImportError:
            import urlparse
        with testing.mkdtemp() as fetch_path:
            names = []
            cmd.set('fetch_path', fetch_path)
            cmd.set(
                'fetch_host',
                urlparse.urlunsplit(
                    ['file', '',
                     self.datafile('pdb.mirror'), '', '']))

            cmd.fetch('1avy', type='pdb')
            names += ['1avy']
            self.assertItemsEqual(cmd.get_names(), names)

            cmd.fetch('1avyB', type='pdb')
            names += ['1avyB']
            self.assertItemsEqual(cmd.get_names(), names)
            self.assertEqual(cmd.get_chains('1avyB'), ['B'])

            cmd.fetch('1aq5', type='pdb', multiplex=1)
            names += ['1aq5_%04d' % (i + 1) for i in range(20)]
            self.assertItemsEqual(cmd.get_names(), names)
Example #9
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)
Example #10
0
    def testFetchLocal(self):
        try:
            import urllib.parse as urlparse
        except ImportError:
            import urlparse

        # PyMOL 1.8.6 adds full URLs, remove them
        import pymol
        pdbpaths = pymol.importing.hostPaths['pdb']
        pdbpaths[:] = [p for p in pdbpaths if '://' not in p]

        with testing.mkdtemp() as fetch_path:
            names = []
            cmd.set('fetch_path', fetch_path)
            cmd.set(
                'fetch_host',
                urlparse.urlunsplit(
                    ['file', '',
                     self.datafile('pdb.mirror'), '', '']))

            cmd.fetch('1avy', type='pdb')
            names += ['1avy']
            self.assertItemsEqual(cmd.get_names(), names)

            cmd.fetch('1avyB', type='pdb')
            names += ['1avyB']
            self.assertItemsEqual(cmd.get_names(), names)
            self.assertEqual(cmd.get_chains('1avyB'), ['B'])

            cmd.fetch('1aq5', type='pdb', multiplex=1)
            names += ['1aq5_%04d' % (i + 1) for i in range(20)]
            self.assertItemsEqual(cmd.get_names(), names)
Example #11
0
    def selectoption1(self):
        self.sel.toggle()
        if (self.fv.get() == 0):
            self.fv.set(1)
            self.sv.set(0)
            self.entry1.config(state="normal")
            self.browserButton.config(state="normal")
            self.lb1.config(state=DISABLED)
            self.lb1.delete(0, 'end')
            objects = cmd.get_names("all")
            objects.extend(["Pick object"])
            for x in objects:
                self.lb1.insert(END, x)
        else:
            self.fv.set(0)
            self.sv.set(1)
            self.entry1.config(state=DISABLED)
            self.browserButton.config(state=DISABLED)
            self.lb1.config(state="normal")
            # self.vsb.config(state="normal")
            self.lb1.delete(0, 'end')

            if pymolenv:  # if being loaded in pymol
                objects = cmd.get_names("all")
                objects.extend(["Pick object"])
            else:  # dummy arguments for dev mode
                objects = ["anl5", "cbm"]
            for x in objects:
                self.lb1.insert(END, x)
Example #12
0
def mytkdialog(parent):

    root = tk.Tk()
    root.geometry("500x200+100+80")
    root.title("Dock Plugin")
    root.iconbitmap('@idea.xbm')

    receptors = cmd.get_names(selection='(all)')
    combobox1 = ttk.Combobox(root,
                             values=receptors,
                             height=3,
                             state='readonly')
    combobox1.set(u"Receptor")
    combobox1.grid(column=0, row=0)
    rec = receptors[combobox1.current()]

    ligands = cmd.get_names(selection='(all)')
    combobox2 = ttk.Combobox(root, values=ligands, height=3, state='readonly')
    combobox2.set(u"Ligand")
    combobox2.grid(column=1, row=0)
    lig = ligands[combobox2.current()]

    buttonDock = tk.Button(root,
                           text='Dock!',
                           width=6,
                           height=1,
                           bg='blue',
                           fg='white',
                           font='arial 14',
                           command=lambda: fmftpath(rec, lig))
    buttonDock.grid(column=2, row=1)
Example #13
0
    def animate(self):
        '''Toggle between 'reduce' and 'flip' flipkin kinemage groups.

        The 'flip' group is either 'flipNQ' or 'flipH', depending on which
        kinemage is enabled.

        Note: Using this method is not recommended if you're using the GUI, as
        it doesn't currently affect the state of the flipkin group checkboxes.

        '''
        # TODO integrate GUI animate button with this function.
        # Check which flipkin kinemages are enabled.
        logger.debug('checking which kinemages are enabled')
        enabled_flipkins = []
        for fk in ['flipkinNQ', 'flipkinH']:
            kin_grp = self.get_kin_cgo_group(fk)
            if kin_grp in cmd.get_names(enabled_only=1):
                logger.debug('  {} flipkin is enabled.'.format(fk))
                enabled_flipkins.append(fk)
                continue

        if not enabled_flipkins:
            logger.debug('  no flipkin kinemages enabled...enabling flipkinNQ')
            self.solo_kin('flipkinNQ')
            self.animate()
            return

        # Regex to match `mp_myobj.*.reduce` (flipkin 'reduce' group)
        reduce_group_regex = re.compile(
            re.escape(self.mp_group) + r'\.[^\.]+\.reduce$')

        # If at least one flipkin kinemage is enabled AND either the 'reduce'
        # molecule or any 'reduce' kinemage CGO groups are enabled, solo the
        # 'flipX' groups of both flipkin kinemages and the 'flip' molecule of
        # whichever flipkin kinemages are enabled.
        logger.debug(
            'checking if any reduce molecule or kinemage is enabled...')
        reduce_is_enabled = 0
        for name in cmd.get_names(enabled_only=1):
            logger.debug('  checking {} for reduce group match'.format(name))
            if reduce_group_regex.match(name) or name == self.pdb['reduce']:
                logger.debug('  match! {}')
                reduce_is_enabled = 1
                continue
        if reduce_is_enabled:
            logger.debug('reduce was enabled, switching to flips.')
            self.disable_pdb('reduce')
            # Enable the flipkin 'flip' groups
            self.solo_flipkin_group('flip')
            # And the molecules for each enabled flipkin.
            for fk in enabled_flipkins:
                self.enable_pdb(fk)

        # If, on the other hand, no 'reduce' group or molecule is enabled, solo
        # the 'reduce' groups for all kinemages and the 'reduce'
        # coordinates for this MPObject.
        else:
            self.solo_pdb('reduce')
            self.solo_flipkin_group('reduce')
Example #14
0
def check_selections(queue):
    """ Check if the selection made by the user changed """
    global previous_mouse_mode
    global myspace
    while True:
        # Check if the user changed the selection mode (atom/residue/chain/molecule)
        logging.debug("Current mouse selection mode : %d" %
                      int(cmd.get("mouse_selection_mode")))
        logging.debug("Number of selections: %d" %
                      len(cmd.get_names("selections")))
        if int(cmd.get("mouse_selection_mode")) == 5 and len(
                cmd.get_names("selections")) > 0:
            #logging.debug(cmd.get_names("selections")[1])
            nb_selected_objects = cmd.count_atoms('sele')
            if nb_selected_objects > 0:
                logging.info("--- Selection made by the user ---")
                logging.info(nb_selected_objects)
                cmd.iterate('(sele)', 'models.add(model)', space=myspace)
                logging.info(myspace['models'])
                tmp = set()
                # Make the list with unique items
                for i in myspace['models']:
                    if int(i) not in tmp:
                        tmp.add(int(i))
                # Check if the selection has changed
                if tmp != myspace['previous']:
                    myspace['previous'] = tmp
                    queue.put(tmp)
                else:
                    time.sleep(1)
                cmd.select('none')
        elif int(cmd.get("mouse_selection_mode")) == 1 and len(
                cmd.get_names("selections")) > 0:
            #logging.debug(cmd.get_names("selections")[0])

            nb_selected_objects = cmd.count_atoms('sele')
            if nb_selected_objects > 0:
                logging.info("--- Selection made by the user ---")
                cmd.iterate('(sele)', 'residues.add(resv)', space=myspace)
                logging.info(myspace['residues'])
                tmp = set()
                # Make the list with unique items
                for i in myspace['residues']:
                    if int(i) not in tmp:
                        tmp.add(int(i))
                # Check if the selection has changed
                if tmp != myspace['previous']:
                    myspace['previous'] = tmp
                    queue.put(tmp)
                    #cmd.delete('lb')
                else:
                    time.sleep(1)
                cmd.select('none')

        else:
            # if len(cmd.get_names("selections", enabled_only=1)) == 0:
            #     queue.put(set())
            #previous_mouse_mode = cmd.get("mouse_selection_mode")
            time.sleep(0.5)
Example #15
0
def propka(molecule="NIL",chain="*",resi="0",resn="NIL",method="upload",logtime=time.strftime("%m%d",time.localtime()),server_wait=3.0,version="v3.1",verbose="no",showresult="no",pkafile="NIL",makebonds="yes"):
	Script_Version="20110823"
	### First we have to be sure, we give reasonable arguments
	if pkafile!="NIL":
		method='file'
	assert method in ['upload', 'file'], "'method' has to be either: method=upload or method=file"
	### If molecule="all", then try to get the last molecule
	##assert molecule not in ['NIL'], "You always have to provide molecule name. Example: molecule=4ins"
	if molecule=="NIL":
		assert len(cmd.get_names())!=0, "Did you forget to load a molecule? There are no objects in pymol."
		molecule=cmd.get_names()[-1]
	### To print out to screen for selected residues. Can be separated with "." or make ranges with "-". Example: resi="4-8.10"
	if resi != "0": resi_range = ResiRange(resi)
	else: resi_range=[]
	### Also works for residue names. They are all converted to bigger letters. Example: resn="cys.Tyr"
	if resn != "NIL": resn_range = ResnRange(resn)
	else: resn_range = resn
	### Make chain range, and upper case.
	chain = ChainRange(chain)
	### Make result directory. We also the absolut path to the new directory.
	Newdir = createdirs()
	if method=="upload":
		### We try to load mechanize. If this fail, one can always get the .pka file manual and the run: method=file
		try: from modules import mechanize; importedmechanize='yes'
		except ImportError: print("Import error. Is a module missing?"); print(sys.exc_info()); print("Look if missing module is in your python path\n%s")%sys.path;importedmechanize='no'; import modules.mechanize as mechanize
		### The name for the new molecule
		newmolecule = "%s%s"%(molecule,logtime)
		### Create the new molecule from original loaded and for the specified chains. Save it, and disable the old molecule.
		cmd.create("%s"%newmolecule, "%s and chain %s"%(molecule,chain))
		cmd.save("%s%s.pdb"%(Newdir,newmolecule), "%s"%newmolecule)
		cmd.disable("%s"%molecule)
		if molecule=="all": cmd.enable("%s"%molecule); cmd.show("cartoon", "%s"%molecule)
		### Let the new molecule be shown in cartoon.
		cmd.hide("everything", "%s"%newmolecule)
		cmd.show("cartoon", "%s"%newmolecule)
		### Make the absolut path to the newly created .pdb file.
		PDB="%s%s.pdb"%(Newdir,newmolecule);source="upload"; PDBID=""
		### Request server, and get the absolut path to the result file.
		pkafile = getpropka(PDB,chain,resi,resn,source,PDBID,logtime,server_wait,version,verbose,showresult)
		### Open the result file and put in into a handy list.
		list_results,ligands_results = importpropkaresult(pkafile)
	if method=="file":
		assert pkafile not in ['NIL'], "You have to provide path to file. Example: pkafile=./Results_propka/4ins_2011.pka"
		assert ".pka" in pkafile, 'The propka result file should end with ".pka" \nExample: pkafile=./Results_propka/4ins_2011.pka \npkafile=%s'%(pkafile)
		### The name for the molecule we pass to the writing script of pymol commands
		newmolecule = "%s"%molecule
		cmd.hide("everything", "%s"%newmolecule)
		cmd.show("cartoon", "%s"%newmolecule)
		### We open the result file we have got in the manual way and put in into a handy list.
		list_results,ligands_results = importpropkaresult(pkafile)
		### Then we print the interesting residues to the screen.
		printpropkaresult(list_results, resi, resi_range, resn, resn_range, showresult, ligands_results)
	### Now create the pymol command file. This should label the protein. We get back the absolut path to the file, so we can execute it.
	result_pka_pymol_name = writepymolcmd(newmolecule,pkafile,verbose,makebonds)
	### Now run our command file. But only if we are running pymol.
	if runningpymol=='yes': cmd.do("run %s"%result_pka_pymol_name)
	##if runningpymol=='yes': cmd.do("@%s"%result_pka_pymol_name)
	return(list_results)
Example #16
0
 def testEnable(self):
     cmd.create('m1', 'none')
     cmd.create('m2', 'none')
     cmd.disable()
     self.assertEqual(cmd.get_names('public_objects', 1), [])
     cmd.enable('m1')
     self.assertEqual(cmd.get_names('public_objects', 1), ['m1'])
     cmd.enable()
     self.assertEqual(cmd.get_names('public_objects', 1), ['m1', 'm2'])
Example #17
0
 def testEnable(self):
     cmd.create('m1', 'none')
     cmd.create('m2', 'none')
     cmd.disable()
     self.assertEqual(cmd.get_names('public_objects', 1), [])
     cmd.enable('m1')
     self.assertEqual(cmd.get_names('public_objects', 1), ['m1'])
     cmd.enable()
     self.assertEqual(cmd.get_names('public_objects', 1), ['m1', 'm2'])
Example #18
0
    def animate(self):
        '''Toggle between 'reduce' and 'flip' flipkin kinemage groups.

        The 'flip' group is either 'flipNQ' or 'flipH', depending on which
        kinemage is enabled.

        Note: Using this method is not recommended if you're using the GUI, as
        it doesn't currently affect the state of the flipkin group checkboxes.

        '''
        # TODO integrate GUI animate button with this function.
        # Check which flipkin kinemages are enabled.
        logger.debug('checking which kinemages are enabled')
        enabled_flipkins = []
        for fk in ['flipkinNQ', 'flipkinH']:
            kin_grp = self.get_kin_cgo_group(fk)
            if kin_grp in cmd.get_names(enabled_only=1):
                logger.debug('  {} flipkin is enabled.'.format(fk))
                enabled_flipkins.append(fk)
                continue

        if not enabled_flipkins:
            logger.debug('  no flipkin kinemages enabled...enabling flipkinNQ')
            self.solo_kin('flipkinNQ')
            self.animate()
            return

        # Regex to match `mp_myobj.*.reduce` (flipkin 'reduce' group)
        reduce_group_regex = re.compile(re.escape(self.mp_group) + r'\.[^\.]+\.reduce$')

        # If at least one flipkin kinemage is enabled AND either the 'reduce'
        # molecule or any 'reduce' kinemage CGO groups are enabled, solo the
        # 'flipX' groups of both flipkin kinemages and the 'flip' molecule of
        # whichever flipkin kinemages are enabled.
        logger.debug('checking if any reduce molecule or kinemage is enabled...')
        reduce_is_enabled = 0
        for name in cmd.get_names(enabled_only=1):
            logger.debug('  checking {} for reduce group match'.format(name))
            if reduce_group_regex.match(name) or name == self.pdb['reduce']:
                logger.debug('  match! {}')
                reduce_is_enabled = 1
                continue
        if reduce_is_enabled:
            logger.debug('reduce was enabled, switching to flips.')
            self.disable_pdb('reduce')
            # Enable the flipkin 'flip' groups
            self.solo_flipkin_group('flip')
            # And the molecules for each enabled flipkin.
            for fk in enabled_flipkins:
                self.enable_pdb(fk)

        # If, on the other hand, no 'reduce' group or molecule is enabled, solo
        # the 'reduce' groups for all kinemages and the 'reduce'
        # coordinates for this MPObject.
        else:
            self.solo_pdb('reduce')
            self.solo_flipkin_group('reduce')
def surfaceatoms(molecule="NIL",show=True, verbose=True, cutoff=2.5):
	"""
	surfaceatoms
		finds those residues on the surface of a protein
		that have at least 'cutoff' exposed A**2 surface area.
 	PARAMS
		molecule (string)
			the object or selection in which to find
			exposed residues
			DEFAULT: (last molecule in pymol)
 		cutoff (float)
			your cutoff of what is exposed or not. 
			DEFAULT: 2.5 Ang**2
	RETURNS
		(list: (chain, resv ) )
			A Python list of residue numbers corresponding
			to those residues w/more exposure than the cutoff.
	"""
	if molecule=="NIL":
		assert len(cmd.get_names())!=0, "Did you forget to load a molecule? There are no objects in pymol."
		molecule=cmd.get_names()[-1]
	tmpObj="__tmp"
	cmd.create(tmpObj, "(%s and polymer) and not resn HOH"%molecule)
	if verbose!=False:
		print "WARNING: I'm setting dot_solvent.  You may not care for this."
	cmd.set("dot_solvent")
	cmd.get_area(selection=tmpObj, load_b=1)
 	# threshold on what one considers an "exposed" atom (in A**2):
	cmd.remove( tmpObj + " and b < " + str(cutoff) )
 	stored.tmp_dict = {}
	cmd.iterate(tmpObj, "stored.tmp_dict[(chain,resv)]=1")
	exposed = stored.tmp_dict.keys()
	exposed.sort()
 
	selName = "%s_atoms"%molecule
	cmd.select(selName, molecule + " in " + tmpObj ) 
	if verbose!=False:
		print "Exposed residues are selected in: " + selName
	selNameRes = "%s_resi"%molecule
	cmd.select(selNameRes, "byres " + selName )
 
 	if show!=False:
		cmd.hide("everything", molecule)
		cmd.show("cartoon", "%s and not %s and not resn HOH"%(molecule,selNameRes))
		cmd.show("sticks", "%s"%selNameRes)
		cmd.util.cbaw(selNameRes)
		cmd.disable(selNameRes)
		#cmd.alter('%s'%(selName),'vdw=0.5') # affects repeated runs
                cmd.set('sphere_scale','0.3','%s'%(selName)) # does not affect repeated runs
		cmd.show("spheres", "%s"%selName)
		cmd.util.cbao(selName)
		cmd.disable(selName)
 
 	cmd.delete(tmpObj)
	print(exposed)
 	return(exposed)
def test_gen(max_num_mut=6, target_num_mut=None, flex_only=False,
             limit_seqspace=False):
    """Generate all reasonable designs from the current pdb

    Args:
        max_num_mut (int): The maximum number of mutations to allow
        target_num_mut (int): Only return mutable sets of this size
        flex_only (boolean): Allow mutations?

    Raises:
        CmdException: Error in a PyMol command

    """

    # Generate all interfaces
    # Note - this command seems to work well for picking only
    # sidechain-sidechain contacts
    interface(None,None,3,1)
    try:
        inter_list = cmd.get_names("selections", 0, "all")
    except:
        raise CmdException

    inter_list = [ e for e in inter_list if e[0:3]=="int" ]

    # Find potential mutable residues
    mut_list = []
    for inter in inter_list:
        chains = cmd.get_chains(inter)
        inter_1 = inter+' and chain '+chains[0]
        inter_2 = inter+' and chain '+chains[1]
        print(inter_1)
        mut_list.extend(gen_mut(inter_1, max_num_mut, target_num_mut))
        print(inter_2)
        mut_list.extend(gen_mut(inter_2, max_num_mut, target_num_mut))


    print('Generated '+str(len(mut_list))+' sets of mutations')
    # For each mutable residue set, generate a flexible shell and print design
    counter = 0
    for mut in mut_list:
        #Select muts
        obj_name = cmd.get_names('objects',0,'all')[0]
        resi_list = [ str(res.res_seq)+res.i_code for res in mut ]
        chain = next(iter(mut)).chain_id
        selection = "br. chain "+chain+" and resi "+'+'.join(resi_list)
        cmd.select("mut", selection)

        #gen_shell
        gen_shell(1,0,"mut",5)

        #print output
        name = '_'.join([obj_name[:4], chain])+".cfs"
        print_design("mut", "flex", name, flex_only, limit_seqspace)
        counter = counter+1
Example #21
0
def move_up():
    enabled_objs = cmd.get_names("objects", enabled_only=1)
    all_objs = cmd.get_names("objects", enabled_only=0)
    for obj in enabled_objs:
        cmd.disable(obj)
        last_obj = obj
        for i in range(0, len(all_objs)):
            if all_objs[i] == obj:
                if i - 1 < 0:
                    cmd.enable(all_objs[-1])
                else:
                    cmd.enable(all_objs[i - 1])
Example #22
0
 def testGetNames(self):
     cmd.fragment('gly')
     cmd.fragment('cys')
     cmd.ramp_new('ramp1', 'none')  # non-molecular object
     cmd.select('foo', 'none')
     self.assertEqual(cmd.get_names(), ['gly', 'cys', 'ramp1'])
     self.assertEqual(cmd.get_names(selection="elem S"), ['cys'])
     cmd.disable('gly')
     cmd.disable('ramp1')
     self.assertEqual(cmd.get_names(enabled_only=1), ['cys'])
     self.assertEqual(cmd.get_names('selections'), ['foo'])
     self.assertEqual(cmd.get_names('all'), ['gly', 'cys', 'ramp1', 'foo'])
Example #23
0
def move_down():
	enabled_objs = cmd.get_names("objects",enabled_only=1)
	all_objs = cmd.get_names("objects",enabled_only=0)
	for obj in enabled_objs:
		cmd.disable(obj)
		last_obj=obj
		for i in range(0,len(all_objs)):
			if all_objs[i] == obj:
				if i+1 >= len(all_objs):
					cmd.enable( all_objs[0] )
				else:
					cmd.enable( all_objs[i+1] )
	cmd.orient
Example #24
0
def move_down():
    enabled_objs = cmd.get_names("objects", enabled_only=1)
    all_objs = cmd.get_names("objects", enabled_only=0)
    for obj in enabled_objs:
        cmd.disable(obj)
        last_obj = obj
        for i in range(0, len(all_objs)):
            if all_objs[i] == obj:
                if i + 1 >= len(all_objs):
                    cmd.enable(all_objs[0])
                else:
                    cmd.enable(all_objs[i + 1])
    cmd.orient
def move_up():
        enabled_objs = cmd.get_names("object",enabled_only=1)
        all_objs = cmd.get_names("object",enabled_only=0)
        for obj in enabled_objs:
                cmd.disable(obj)
                last_obj=obj
                for i in range(0,len(all_objs)):
                        if all_objs[i] == obj:
                                if i-1 < 0:
                                        cmd.enable( all_objs[-1] )
                                else:
                                        cmd.enable( all_objs[i-1] )
        cmd.orient
Example #26
0
    def test(self):
        names_ungrouped = ['a0', 'a1', 'b0', 'b1', 'c0', 'c1', 'g1']
        names_grouped   = ['a0', 'a1', 'c0', 'c1', 'b0', 'g1', 'b1']

        for name in names_ungrouped[:-1]:
            cmd.pseudoatom(name)
        cmd.group(names_ungrouped[-1])

        self.assertEqual(cmd.get_names(), names_ungrouped)

        cmd.group('g1', 'b*')
        cmd.order('b0 g1', location="upper")

        self.assertEqual(cmd.get_names(), names_grouped)
Example #27
0
    def testFetch(self):
        with testing.mkdtemp() as fetch_path:
            names = []
            cmd.set('fetch_path', fetch_path)
            cmd.set('fetch_host', 'pdb pdbe')

            cmd.fetch('1avy', '1avy1', type='pdb1')
            names += ['1avy1']
            self.assertItemsEqual(cmd.get_names(), names)
            self.assertEqual(cmd.count_states('1avy1'), 3)

            cmd.fetch('1avy', type='2fofc')
            names += ['1avy_2fofc']
            self.assertItemsEqual(cmd.get_names(), names)
            self.assertEqual(cmd.get_type('1avy_2fofc'), 'object:map')
Example #28
0
def test_angle_between_helices():
    cmd.reinitialize()
    cmd.load(DATA_PATH / "1nmr-frag-nohydro.pdb", "m1")

    angle = psico.orientation.angle_between_helices("resi 53-61",
                                                    "resi 63-79",
                                                    method="helix")
    assert angle == approx(159.164, abs=0.01)
    assert set(["oriVec01", "oriVec02", "angle01"]).issubset(cmd.get_names())

    angle = psico.orientation.angle_between_helices("resi 53-61",
                                                    "resi 63-79",
                                                    method="cafit")
    assert angle == approx(158.624, abs=0.01)
    assert set(["oriVec03", "oriVec04", "angle02"]).issubset(cmd.get_names())
Example #29
0
    def testFetch(self):
        with testing.mkdtemp() as fetch_path:
            names = []
            cmd.set('fetch_path', fetch_path)
            cmd.set('fetch_host', 'pdb pdbe')

            cmd.fetch('1avy', '1avy1', type='pdb1')
            names += ['1avy1']
            self.assertItemsEqual(cmd.get_names(), names)
            self.assertEqual(cmd.count_states('1avy1'), 3)

            cmd.fetch('1avy', type='2fofc')
            names += ['1avy_2fofc']
            self.assertItemsEqual(cmd.get_names(), names)
            self.assertEqual(cmd.get_type('1avy_2fofc'), 'object:map')
Example #30
0
def align_all( subset = [] ):
  """
  Superimpose all open models onto the first one.
  This may not work well with selections.

  This function is probably taken from https://daslab.stanford.edu/site_data/docs_pymol_rhiju.pdf
  """
  print("""This returns a list with 7 items:

    RMSD after refinement
    Number of aligned atoms after refinement
    Number of refinement cycles
    RMSD before refinement
    Number of aligned atoms before refinement
    Raw alignment score
    Number of residues aligned """)

  AllObj=cmd.get_names("all")
  for x in AllObj[1:]:
    #print(AllObj[0],x)
    subset_tag = ''
    if isinstance( subset, int ):
      subset_tag = ' and resi %d' % subset
    elif isinstance( subset, list ) and len( subset ) > 0:
      subset_tag = ' and resi %d' % (subset[0])
      for m in range( 1,len(subset)): subset_tag += '+%d' % subset[m]
    elif isinstance( subset, str ) and len( subset ) > 0:
      subset_tag = ' and %s' % subset
    values = cmd.align(x+subset_tag,AllObj[0]+subset_tag)
    print(AllObj[0], x, ' '.join([str(v) for v in values]), '-- RMSD', values[3], ' of ', values[6], 'residues')
    cmd.zoom()
Example #31
0
def na():
	
	cmd.view('v', 'store');
	
	object = cmd.get_names()[0]
	
	pdbid = object[0:4]
	chainid = object[4:5]
	
	cmd.fetch(pdbid)
	cmd.select("design_na","%s and chain %s"%(object,"B"))
	cmd.select("native_na","%s and chain %s"%(pdbid,chainid))
	
	cmd.select("other_na","%s and not chain %s"%(pdbid,chainid))
	cmd.hide("everything","other")
	cmd.hide('(resn HOH)')
	
	cmd.super("design_na","native_na")
	
	cmd.select("none")
	cmd.orient(object)
	
	cmd.system("rm %s.pdb"%(pdbid));
	
	cmd.view('v', 'recall')
Example #32
0
def na():
	
	cmd.view('v', 'store');
	
	
	object = cmd.get_names()[0]

	if object[0] == 'd':
		pdbid = object[1:5]
		chainid = object[5:6]
	else:
		pdbid = object[0:4]
		chainid = object[4:5]
	
	cmd.fetch(pdbid)
	cmd.select("design_na","%s and chain %s and not hydro"%(object,"B"))
	cmd.select("native_na","%s and chain %s and not hydro"%(pdbid,chainid))
	
	cmd.select("other_na","%s and not chain %s"%(pdbid,chainid))
	cmd.hide("everything","other")
	cmd.hide('(resn HOH)')
	
	cmd.super("native_na","design_na")
	
	cmd.hide("lines","all");
	cmd.show("sticks","native_na");
	cmd.show("cartoon","native_na");
	
	cmd.select("none")
	cmd.orient(object)
	
	pdbid = pdbid.lower()
	cmd.system("rm %s.pdb"%(pdbid));
	
	cmd.view('v', 'recall')
def rs():
    """    The function creates super-cool cartoon-like RNA and colors each structure as a rainbow.
    Good to view aligned structures in a grid.

    .. image:: ../../rna_tools/utils/PyMOL4RNA/doc/rs.png
    """
    cmd.hide("sticks", "all")
    cmd.hide("lines", "all")
    cmd.show("cartoon", "all")
    cmd.set("cartoon_ring_mode", 3)
    cmd.set("cartoon_ring_finder", 2)
    cmd.set("cartoon_ladder_mode", 2)
    cmd.set("cartoon_ring_transparency", 0.30)
    cmd.spectrum()

    obj_list = cmd.get_names('objects')

    colours = ['rainbow']
    ncolours = len(colours)
    # Loop over objects
    i = 0
    for obj in obj_list:
        print("  ", obj, colours[i])
        cmd.spectrum('count', colours[i], obj)
        i = i + 1
        if (i == ncolours):
            i = 0
Example #34
0
    def launch_search(self):
        """
        launches the search in the separate thread
        does some basic checking and gets selection
        """
        
        # gets the active selections from pymol
        active_selections = cmd.get_names('selections', 1)
        if len(active_selections) == 0:
            self.status = 'no selection'
        else:

            selection = active_selections[0]
            print "The active selections are " + str(selection)
            pdbstr = cmd.get_pdbstr(selection)
            print 'pdbstr is', pdbstr
            self.stop_search()
            self.searchThread = SearchThread(self,
                self.rmsd_cutoff,
                self.number_of_structures,
                self.full_match,
                self.database,
                pdbstr,
                self.url,
                self.cmd,
                self.dictionary)
            self.searchThread.start()
            self.status = 'search launched'
            self.searchProgress = 0
        self.cmd.refresh_wizard()
Example #35
0
    def testAppend(self):
        cmd.set('auto_rename_duplicate_objects', 0)

        self._load_session_twice()

        v = cmd.get_names()
        self.assertEqual(v, self.v_ref)
Example #36
0
def all_vs_all(filename='rms_matrix.txt'):
  AllObj=cmd.get_names("public_objects") # not temps created by alignment or selections
  matrix = []
  for x in AllObj:
    x_to_all = []
    for y in AllObj:
      rmsd = cmd.rms( x, y, cutoff=10)#[0] # super-inclusive
      x_to_all.append(rmsd)
    matrix.append(x_to_all)
  print matrix
  outfile = open(filename,'w')
  # No names 'on top' -- we can figure these out from the vertical ordering
  # and they're way too long...
  #for name in AllObj:
  #  outfile.write("\t%s" % name)
  #outfile.write("\n")
  maxlen = 0
  for obj in AllObj:
    if maxlen < len(obj):
      maxlen = len(obj)

  print_allobj = []
  for obj in AllObj:
    while len(obj) < maxlen:
      obj += ' '
    print_allobj.append(obj)
  ni = 0
  for x in matrix:
    outfile.write(print_allobj[ni])
    ni += 1
    for y in x:
      outfile.write("\t%0.2f" % y)
    outfile.write("\n")
Example #37
0
    def __call__(self):
        if self.name not in cmd.get_names('objects'):
            import threading
            threading.Thread(None, cmd.delete, args=(self.cb_name,)).start()
            return

        v = cmd.get_view()
        if v == self.prev_v:
            return
        self.prev_v = v

        t = v[12:15]

        if self.corner:
            vp = cmd.get_viewport()
            R_mc = [v[0:3], v[3:6], v[6:9]]
            off_c = [0.15 * v[11] * vp[0] / vp[1], 0.15 * v[11], 0.0]
            if self.corner in [2,3]:
                off_c[0] *= -1
            if self.corner in [3,4]:
                off_c[1] *= -1
            off_m = cpv.transform(R_mc, off_c)
            t = cpv.add(t, off_m)

        z = -v[11] / 30.0
        m = [z, 0, 0, t[0] / z, 0, z, 0, t[1] / z, 0, 0, z, t[2] / z, 0, 0, 0, 1]
        cmd.set_object_ttt(self.name, m, homogenous=1)
Example #38
0
 def testPseSupport(self):
     cmd.load_callback(callback.Callback(), 'c1')
     with testing.mktemp('tmp.pse') as session_filename:
         cmd.save(session_filename)
         cmd.delete('*')
         cmd.load(session_filename)
         self.assertTrue('c1' in cmd.get_names())
Example #39
0
def rcomp():
    """RNA like in papers ;-)

    Similar to rc() but this time it colors each (and every) structure in different colour.
    Great on viewing-comparing superimposed structures.

    """
    cmd.hide("sticks", "all")
    cmd.hide("lines", "all")
    cmd.show("cartoon", "all")
    cmd.set("cartoon_ring_mode", 3)
    cmd.set("cartoon_ring_finder", 2)
    cmd.set("cartoon_ladder_mode", 2)
    cmd.set("cartoon_ring_transparency", 0.30)

    obj_list = cmd.get_names('objects')

    colours = ['red', 'green', 'blue', 'yellow', 'violet', 'cyan',    \
           'salmon', 'lime', 'pink', 'slate', 'magenta', 'orange', 'marine', \
           'olive', 'purple', 'teal', 'forest', 'firebrick', 'chocolate',    \
           'wheat', 'white', 'grey' ]
    ncolours = len(colours)

           # Loop over objects
    i = 0
    for obj in obj_list:
        print("  ", obj, colours[i])
        cmd.color(colours[i], obj)
        i = i+1
        if(i == ncolours):
           i = 0
Example #40
0
def rs():
    """    The function creates super-cool cartoon-like RNA and colors each structure as a rainbow.
    Good to view aligned structures in a grid.

    .. image:: ../../rna_tools/utils/PyMOL4RNA/doc/rs.png
    """
    cmd.hide("sticks", "all")
    cmd.hide("lines", "all")
    cmd.show("cartoon", "all")
    cmd.set("cartoon_ring_mode", 3)
    cmd.set("cartoon_ring_finder", 2)
    cmd.set("cartoon_ladder_mode", 2)
    cmd.set("cartoon_ring_transparency", 0.30)
    cmd.spectrum()

    obj_list = cmd.get_names('objects')

    colours = ['rainbow']
    ncolours = len(colours)
    # Loop over objects
    i = 0
    for obj in obj_list:
        print("  ", obj, colours[i])
        cmd.spectrum('count', colours[i], obj)
        i = i+1
        if(i == ncolours):
           i = 0
Example #41
0
def rd():
  """
  rhiju's favorite coloring of proteins and generic molecules
  side chains are all-heavy-atom and colored CPK, backbone is
  rainbow cartoon from N to C terminus.
  """
  cmd.bg_color( "white" )
  AllObj=cmd.get_names("all")

  for x in AllObj:
    #print(AllObj[0],x)
    print x
    cmd.show( "cartoon", x )
    cmd.hide( "line", x )
    cmd.color( "white", x+" and elem C" )
    cmd.color( "blue", x+" and elem N" )
    cmd.color( "red", x+" and elem O" )
    cmd.color( "yellow", x+" and elem S" )
    cmd.spectrum( "resi", "rainbow", x+" and name CA+C" )
    cmd.show( "sticks", x +" and not elem H and not name C+N+O" )
    cmd.show( "sticks", x +" and resn PRO and name N" )
    cmd.show( "sticks", x + " and name NR+CR+CS+CP+CQ" )
    cmd.show( "sticks", x + " and not elem H and neighbor name NR+CQ+CR+CS+CP" )
    cmd.show( "sticks", x + " and not elem H and neighbor neighbor name NR+CQ+CR+CS+CP" )
    cmd.set( "cartoon_oval_width", 0.1 )
    cmd.set( "cartoon_oval_length", 0.5 )
Example #42
0
def rr():
  """
  rhiju's favorite coloring of RNA
  with 2' OH as spheres,
  bases as filled rings, and backbone as cartoon
  ribbons, rainbow colored from 5' to 3'. No hydrogens,
  white background.
  """
  cmd.bg_color( "white" )

  cmd.hide( 'everything' )
  cmd.show('sticks','not elem H')

  cmd.color( 'red','resn rG+G+DG')
  cmd.color( 'forest','resn rC+C+DC')
  cmd.color( 'orange','resn rA+A+DA')
  cmd.color( 'blue','resn rU+U+DT+BRU')

  #cmd.set( 'cartoon_ring_color',  'red','resn rG+G+DG')
  #cmd.set( 'cartoon_ring_color',  'forest','resn rC+C+DC')
  #cmd.set( 'cartoon_ring_color',  'orange','resn rA+A+DA')
  #cmd.set( 'cartoon_ring_color',  'blue','resn rU+U+DT+BRU')

  #cmd.select('bases','name c2+c4+c5+c6+c8+n1+n2+n3+n4+n6+n7+n9+o2+o4+o6+n1p')
  #cmd.select('backbone', 'name o1p+o2p+o3p+p+c1*+c2*+c3*+c5*+o2*+o3*+o4*+o5*')
  #cmd.select('sugar', 'name c1*+c2*+c3*+c4*+o2*+o4*')
  AllObj=cmd.get_names("all")

  cmd.color( 'red','resn rG+G and name n1+c6+o6+c5+c4+n7+c8+n9+n3+c2+n1+n2')
  cmd.color( 'forest','resn rC+C and name n1+c2+o2+n3+c4+n4+c5+c6')
  cmd.color( 'orange','resn rA+A and name n1+c6+n6+c5+n7+c8+n9+c4+n3+c2')
  cmd.color( 'blue','resn rU+U and name n3+c4+o4+c5+c6+n1+c2+o2')


  cmd.select( 'backbone', " (name o1p+o2p+o3p+p+op1+op2+'c1*'+'c2*'+'c3*'+'c5*'+'o2*'+'o3*'+'o4*'+'o5*'+'c1*'+'c2*'+'c3*'+'c4*'+'o2*'+'o4*'+c1'+c2'+c3'+c5'+o2'+o3'+o4'+o5'+c1'+c2'+c3'+c4'+o2'+o4') and (not name c1+c2+c3+c4+c5+o2+o3+o4+o5) ")

  for x in AllObj:
    cmd.show( "cartoon", x )
    cmd.spectrum( "count", "rainbow", x+" and backbone" )
    #cmd.color( 'white', 'backbone' )

  cmd.cartoon( "tube", "backbone" )

  cmd.set( "cartoon_ring_mode", 3 )
  cmd.set( "cartoon_ring_transparency", 0.0 )
  cmd.set( "cartoon_tube_radius", 0.2 )

  cmd.hide( "sticks", "backbone" )

  cmd.delete('backbone')


  cmd.alter( "name o2*","vdw=0.5" )
  cmd.show( "spheres", "name o2'+'o2*' and not name o2" )
  cmd.show( "sticks", "name 'o2*'+'c2*'a" )
  cmd.show( "sticks", "resn hoh" )

  cmd.alter( "resn mg", "vdw=1.0")
  cmd.alter( "resn hoh", "vdw=0.5")
  cmd.show( "spheres", "resn mg+sr+co+zn+hoh and not elem H")
Example #43
0
def rx():
  """
  rhiju's favorite coloring of proteins, more details --
  no cartoon; heavy backbone
  """
  cmd.bg_color( "white" )
  AllObj=cmd.get_names("all")

  for x in AllObj:
    #print(AllObj[0],x)
    print x
    cmd.hide( "line", x )
    cmd.color( "white", x+" and elem C" )
    cmd.color( "blue", x+" and elem N" )
    cmd.color( "red", x+" and elem O" )
    cmd.color( "yellow", x+" and elem S" )
    cmd.spectrum( "resi", "rainbow", x+" and name CA+C" )
    #cmd.show( "sticks", x +" and not elem H and not name C+N+O" )

    cmd.select('backbone','name o+c+ca+n')
    cmd.show('sticks','not elem H')

    if not x.count( 'BACKBONE' ):
      cmd.create( x+"_BACKBONE", x+" and not element H and backbone" )


    cmd.set('stick_radius', '0.5', "*BACKBONE" )
Example #44
0
def getChains():
	'''获取当前导入的PDB文件所含有的chains'''
	chains=[]
	for x in cmd.get_names():
  		for ch in cmd.get_chains(x):
			chains.append(ch)
	return chains
Example #45
0
def rj():
  """
  rhiju's residue-level favorite coloring of proteins
  """
  cmd.bg_color( "white" )
  AllObj=cmd.get_names("all")

  for x in AllObj:
    #print(AllObj[0],x)
    print x
    cmd.show( "cartoon", x )
    #cmd.hide( "line", x )
    cmd.show( "line", x )
    cmd.color( "gray", x+" and resn trp+phe+ala+val+leu+ile+pro+met" )
    cmd.color( "orange", x+" and resn gly" )
    cmd.color( "red", x+" and resn asp+glu" )
    cmd.color( "blue", x+" and resn lys+arg+his" )
    cmd.color( "purple", x+" and resn cys" )
    cmd.color( "forest", x+" and resn tyr+thr+ser+gln+asn" )
    #cmd.spectrum( "resi", "rainbow", x+" and name CA" )
    cmd.show( "sticks", x +" and not elem H and not name C+N+O" )
    cmd.show( "sticks", x +" and resn PRO and name N" )
    cmd.hide( "sticks", x + " and name NR+CR+CS+CP+CQ" )
    cmd.show( "sticks", x + " and not elem H and neighbor name NR+CQ+CR+CS+CP" )
  cmd.set( "cartoon_rect_length", 0.75 )
  cmd.set( "cartoon_rect_width", 0.1 )
  cmd.set( "cartoon_oval_length", 0.6 )
  cmd.set( "cartoon_oval_width", 0.2 )
Example #46
0
    def launch_search(self):
        """
        launches the search in the separate thread
        does some basic checking and gets selection
        """

        # gets the active selections from pymol
        active_selections = cmd.get_names('selections', 1)
        if len(active_selections) == 0:
            cmd.get_wizard().set_status('no selection')
        else:

            selection = active_selections[0]
            print "The active selections are " + str(selection)
            pdbstr = cmd.get_pdbstr(selection)
            print 'pdbstr is', pdbstr
            self.stop_search()

            #            print cmd.get_wizard(), self.win.rmsd.get(), self.win.num_structs.get(), self.win.full_match, self.win.datab, pdbstr, self.win.serverURL, cmd.get_wizard().cmd, self.win.jobIDs

            self.win.searchThread = SearchThread(cmd.get_wizard(),
                                                 self.win.rmsd.get(),
                                                 self.win.num_structs.get(),
                                                 self.win.full_match,
                                                 self.win.datab, pdbstr,
                                                 self.win.serverURL,
                                                 cmd.get_wizard().cmd,
                                                 self.win.jobIDs)
            self.win.searchThread.start()
            cmd.get_wizard().set_status('search launched')
            cmd.get_wizard().searchProgress = 0

        cmd.refresh_wizard()
Example #47
0
def na():

    cmd.view('v', 'store')

    object = cmd.get_names()[0]

    if object[0] == 'd':
        pdbid = object[1:5]
        chainid = object[5:6]
    else:
        pdbid = object[0:4]
        chainid = object[4:5]

    cmd.fetch(pdbid)
    cmd.select("design_na", "%s and chain %s and not hydro" % (object, "B"))
    cmd.select("native_na", "%s and chain %s and not hydro" % (pdbid, chainid))

    cmd.select("other_na", "%s and not chain %s" % (pdbid, chainid))
    cmd.hide("everything", "other")
    cmd.hide('(resn HOH)')

    cmd.super("native_na", "design_na")

    cmd.hide("lines", "all")
    cmd.show("sticks", "native_na")
    cmd.show("cartoon", "native_na")

    cmd.select("none")
    cmd.orient(object)

    pdbid = pdbid.lower()
    cmd.system("rm %s.pdb" % (pdbid))

    cmd.view('v', 'recall')
def rcomp():
    """RNA like in papers ;-)

    Similar to rc() but this time it colors each (and every) structure in different colour.
    Great on viewing-comparing superimposed structures.

    """
    cmd.hide("sticks", "all")
    cmd.hide("lines", "all")
    cmd.show("cartoon", "all")
    cmd.set("cartoon_ring_mode", 3)
    cmd.set("cartoon_ring_finder", 2)
    cmd.set("cartoon_ladder_mode", 2)
    cmd.set("cartoon_ring_transparency", 0.30)

    obj_list = cmd.get_names('objects')

    colours = ['red', 'green', 'blue', 'yellow', 'violet', 'cyan',    \
           'salmon', 'lime', 'pink', 'slate', 'magenta', 'orange', 'marine', \
           'olive', 'purple', 'teal', 'forest', 'firebrick', 'chocolate',    \
           'wheat', 'white', 'grey' ]
    ncolours = len(colours)

    # Loop over objects
    i = 0
    for obj in obj_list:
        print("  ", obj, colours[i])
        cmd.color(colours[i], obj)
        i = i + 1
        if (i == ncolours):
            i = 0
Example #49
0
def nat(pdbid,chainid):
	
	cmd.view('v', 'store');
	
	object = cmd.get_names()[0]
		
	cmd.fetch(pdbid)
	cmd.select("design_nat","%s and chain %s and not hydro"%(object,"B"))
	cmd.select("native_nat","%s and chain %s and not hydro"%(pdbid,chainid))
	
	cmd.select("other_nat","%s and not chain %s"%(pdbid,chainid))
	cmd.hide("everything","other")
	cmd.hide('(resn HOH)')
	
	cmd.super("design_nat","native_nat")
	
	cmd.select("none")
	cmd.orient(object)
	
	cmd.hide("lines","all");
	cmd.show("sticks","native_nat");
	cmd.show("cartoon","native_nat");

	cmd.system("rm %s.pdb"%(pdbid));
	
	cmd.view('v', 'recall')
Example #50
0
    def launch_search(self):
        """
        launches the search in the separate thread
        does some basic checking and gets selection
        """

        # gets the active selections from pymol
        active_selections = cmd.get_names('selections', 1)
        if len(active_selections) == 0:
            self.status = 'no selection'
        else:

            selection = active_selections[0]
            print "The active selections are" + str(selection)
            pdbstr = cmd.get_pdbstr(selection)
            print 'pdbstr is', pdbstr
            self.stop_search()
            self.searchThread = SearchThread(self, self.rmsd_cutoff,
                                             self.number_of_structures,
                                             self.full_match, self.database,
                                             pdbstr, self.url, self.cmd,
                                             self.dictionary)
            self.searchThread.start()
            self.status = 'search launched'
            self.searchProgress = 0
        self.cmd.refresh_wizard()
def build_seq(name, seq,ss=None,phi=None,psi=None):
  """
  usage: build_seq name, seq [, ss=helix | phi=phi, psi=psi]
  example: build_seq peptide, QGAADLESLGQYFEEMKTKLIQDMTE, ss=helix 

  will build the above sequence in a helical conformation
  ss can be: helix or h or alpha  (phi=-57, psi=-47)
             antiparallel or beta (phi=-139, psi=-135)
             parallel             (phi=-119, psi=113)
             3/10 helix           (phi=-40.7,psi=30)
             polypro              (phi=-78, psi=149) (polyproline helix type II)

  Alternatively, you can specify the phi and psi angles directly:

  build_seq peptide, QGAADLESLGQ, phi=-60, psi=-40

  This will create an object with the name you provided, unless
  unless that selection already exists, then it will build onto that.

  """

  if name in cmd.get_names("selections"):
    obj='pk1'
  else:
    obj=seq[0:3]

  if phi == None or psi == None:
    if ss == None:
      phi = -139
      psi = -135
    else:
      ss = ss.lower()
      if ss[0:5] == 'helix' or ss[0] == 'h' or ss[0:5] == 'alpha':
        phi = -57
        psi = -47
      elif ss[0:5] == 'antip' or ss[0:4] == 'beta':
        phi = -139
        psi = -135
      elif ss[0:5] == 'paral':
        phi = -119
        psi = 113
      elif ss[0:4] == '3/10':
        phi = -40.7
        psi = -30
      elif ss[0:7] == 'polypro':
        phi = -78
        psi = 149

  print "Building sequence: ",seq

  ### Here seq_convert is used ###
#  seq3=seq_convert.seq1_to_seq3(seq)
  seq3=seq1_to_seq3(seq)
  attach_amino_acid(obj,seq3[0].lower(),phi,psi)
  for aa in seq3[1:]:
    aa = aa.lower()
    attach_amino_acid('pk1',aa,phi,psi)
  cmd.delete('pk1')
  cmd.delete('pkmol')
  cmd.set_name(seq3[0].lower(), name)
Example #52
0
def nat(pdbid, chainid):

    cmd.view('v', 'store')

    object = cmd.get_names()[0]

    cmd.fetch(pdbid)
    cmd.select("design_nat", "%s and chain %s and not hydro" % (object, "B"))
    cmd.select("native_nat",
               "%s and chain %s and not hydro" % (pdbid, chainid))

    cmd.select("other_nat", "%s and not chain %s" % (pdbid, chainid))
    cmd.hide("everything", "other")
    cmd.hide('(resn HOH)')

    cmd.super("design_nat", "native_nat")

    cmd.select("none")
    cmd.orient(object)

    cmd.hide("lines", "all")
    cmd.show("sticks", "native_nat")
    cmd.show("cartoon", "native_nat")

    cmd.system("rm %s.pdb" % (pdbid))

    cmd.view('v', 'recall')
Example #53
0
 def do_select(self, name): # map selects into picks
     from .selecting import select_sspick
     if self.name not in cmd.get_names('selections', enabled_only=1):
         self.name = cmd.get_unused_name('ss')
     select_sspick(name, self.name, self.selection_mode)
     cmd.enable(self.name)
     cmd.refresh_wizard()
Example #54
0
def show_dna_rna():
    glb.update()
    objects = cmd.get_names('all')
    cmd.set('cartoon_ring_mode' , '1')
    if 'dna' in objects or 'rna' in objects:
        if 'protein' in objects:
            cmd.show('cartoon', 'protein')
            cmd.color('gray60', 'protein')
        if 'ligands' in objects:
            cmd.show('spheres', 'ligands')
            cmd.set('sphere_transparency', '0.4', 'ligands')
            cmd.set('sphere_scale', '0.4', 'ligands')
            cmd.color('orange', 'ligands')
        if 'dna' in objects:
            cmd.show('cartoon', 'dna')
        if 'rna' in objects:
            cmd.show('cartoon', 'rna')
        cmd.color('lightblue', 'resn a')
        cmd.color('orange', 'resn c')
        cmd.color('salmon', 'resn g')
        cmd.color('palegreen', 'resn t')
        cmd.color('paleyellow', 'resn u')
        showinfo('Nucleic Acid Key',
        'Adenine = light blue\nCytosine = orange\n'+
        'Guanine = salmon red\nThymine = light green\n'+
        'Uracil = light yellow')
    else:
        showinfo("Error", "There is no DNA or RNA in this molecule.")
Example #55
0
def chain_contact():
    def chain_contact_loop(c,skip,chainPullList):
        d = 0
        l = c + 1
        while len(chainPullList) > l and (26-d) >= 0:
            cmd.select('chain_contact','%s w. 5 of %s'%(chainPullList[d],chainPullList[c+1]),enable=0,quiet=1,merge=1)
            cmd.select('chain_contact','%s w. 5 of %s'%(chainPullList[c+1],chainPullList[d]),enable=0,quiet=1,merge=1)
            d += 1
            l += 1
            while d == (c+1) or d in skip:
                d += 1
    glb.update()
    cmd.hide('everything')
    cmd.show('mesh', 'all')
    cmd.color('gray40', 'all')
    objects = cmd.get_names('all')
    chainPullList = []
    for i in cmd.get_chains(quiet=1):
        chainPullList.append('Chain-'+i)
    if len(chainPullList) < 2:
        showinfo('Notice','There needs to be two or more chains to run this functions.')
        return False
    c = 0
    skip = []
    while c < (len(chainPullList)-1) and c < 26:
        skip.append(c+1)
        chain_contact_loop(c,skip,chainPullList)
        c += 1
    glb.procolor('chain_contact','mesh','cpk',None)
    cmd.delete('chain_contact')
    return chainPullList
Example #56
0
    def __call__(self):
        if self.name not in cmd.get_names('objects'):
            import threading
            threading.Thread(None, cmd.delete, args=(self.cb_name,)).start()
            return

        v = cmd.get_view()
        if v == self.prev_v:
            return
        self.prev_v = v

        t = v[12:15]

        if self.corner:
            vp = cmd.get_viewport()
            R_mc = [v[0:3], v[3:6], v[6:9]]
            off_c = [0.15 * v[11] * vp[0] / vp[1], 0.15 * v[11], 0.0]
            if self.corner in [2,3]:
                off_c[0] *= -1
            if self.corner in [3,4]:
                off_c[1] *= -1
            off_m = cpv.transform(R_mc, off_c)
            t = cpv.add(t, off_m)

        z = -v[11] / 30.0
        m = [z, 0, 0, 0, 0, z, 0, 0, 0, 0, z, 0, t[0] / z, t[1] / z, t[2] / z, 1]
        cmd.set_object_ttt(self.name, m)
Example #57
0
    def testMMTFExportEmpty(self):
        with testing.mktemp('.mmtf') as filename:
            cmd.save(filename)
            cmd.load(filename, 'm1')

        self.assertEqual(cmd.count_atoms(), 0)
        self.assertEqual(cmd.get_names(), ['m1'])