def export_objects_to_png():
    objects = cmd.get_object_list('all')
    cmd.disable('all')
    for pobj in objects:
        cmd.enable(pobj)
        cmd.png('{}.png'.format(pobj), width=2340, height=1239, ray=1)
        cmd.disable(pobj)
Beispiel #2
0
def create_ds_uns(lines, name):
    uns = {'uns_sc': [], 'uns_bb': []}
    for line in lines:
        type = line[3:8]
        if type == 'SCACC' or type == 'SCDON':
            uns['uns_sc'].append(UnsAtom(line))
        elif type == 'BBACC' or type == 'BBDON':
            uns['uns_bb'].append(UnsAtom(line))

    for type, list in list(uns.items()):
        if list == []: continue
        selstr = string.join([
            '/%s//%s/%s/%s' % (name, atom.chain, atom.resi, atom.atom)
            for atom in list
        ], ' or ')
        typename = '%s_%s' % (type, name)
        cmd.select(typename, selstr)

    # copy unsatisfieds into a separate object (allows unique transparency, among other things)
    for type in uns:
        typename = '%s_%s' % (type, name)
        cmd.disable(typename)
        obj = '%s_obj' % typename
        cmd.create(obj, typename)
        cmd.show('spheres', obj)
        cmd.set('sphere_scale', '0.75', obj)
        cmd.set('sphere_transparency', '0.5', obj)
Beispiel #3
0
def load():
   try:
      r = 0
      list = glob(ent_dir)
      list.sort()
#      list = [ "pdb/vq" ]
      for dir in list:
         sys.__stdout__.write("\n"+dir)
         sys.__stdout__.flush()
         for file in glob(dir+"/pdb*"):
            name = os.path.split(file)[-1]
            name = string.split(name,'.')[0]
            cmd.disable()
            cmd.load(file,name)
            cmd.show_as("cartoon",name)
            cmd.refresh()
            cmd.dss(name)
            cmd.refresh()
            time.sleep(0.1)
            sys.__stdout__.write(".")
            sys.__stdout__.flush()
         sys.__stdout__.write("("+str(cmd.count_atoms())+")")
         sys.__stdout__.flush()         
         cmd.dss()
         cmd.delete('all')
   except:
      traceback.print_exc()
Beispiel #4
0
    def additional_cleanup(self):
        """Cleanup of various representations"""

        cmd.remove('not alt ""+A')  # Remove alternate conformations
        cmd.hide('labels', 'Interactions')  # Hide labels of lines
        cmd.disable('%sCartoon' % self.protname)
        cmd.hide('everything', 'hydrogens')
Beispiel #5
0
def draw_interp(out_dir, selection='*', width=1000, height=1000, antialias=2, dpi=-1):

    structs = []
    interp_prefixes = []
    for obj in cmd.get_names('objects'):
        m = re.match(r'^.*lig(_gen)?(_fit)?(_add)?$', obj)
        if m:
            structs.append(obj)
        m = re.match(r'^(.*_lig_gen)_surfaces$', obj)
        if m and fnmatch.fnmatch(obj, selection):
            interp_prefixes.append(m.group(1))

    # try to infer the job_name from working directory
    job_name = os.path.basename(os.getcwd())

    # once we have a job_name, we can correctly parse the prefixes
    interp_re = re.compile(
        '^' + '_'.join([
            r'(?P<job_name>{})'.format(job_name),
            r'(?P<array_idx>\d+)',
            r'(?P<interp_name>(.+)_to_(.+))',
            r'(?P<grid_type>lig(_gen)?(_fit)?)'
        ]) + '$'
    )

    for interp_prefix in interp_prefixes:
        
        m = interp_re.match(interp_prefix)
        if not m:
            continue

        interp_name = m.group('interp_name')
        interp_dir = os.path.join(out_dir, job_name, interp_name)
        os.makedirs(interp_dir, exist_ok=True)

        density = interp_prefix + '_surfaces'
        struct = interp_prefix + '_fit_add'

        # hide everything except the grouped surface objects,
        # since their visibility is controlled by the group object
        cmd.disable('all')
        cmd.enable('*_surface')

        # density only
        cmd.enable(density)
        cmd.set('transparency', 0.2, density)
        im_prefix = os.path.join(interp_dir, interp_prefix) + '_density_'
        cmd.mpng(im_prefix, first=0, last=0, mode=1, width=width, height=height)

        # density and struct
        cmd.enable(struct)
        cmd.set('transparency', 0.5, density)
        im_prefix = os.path.join(interp_dir, interp_prefix) + '_both_'
        cmd.mpng(im_prefix, first=0, last=0, mode=1, width=width, height=height)

        cmd.disable(density)
        im_prefix = os.path.join(interp_dir, interp_prefix) + '_struct_'
        cmd.mpng(im_prefix, first=0, last=0, mode=1, width=width, height=height)

    print('Done')
Beispiel #6
0
def fatslim_apl_prot():
    global REF_BEAD
    setup()

    FILENAME = BILAYER_PROT
    REF_BEAD = BILAYER_PROT_REF

    # Load file
    cmd.load("%s.pdb" % FILENAME)
    main_obj = "%s" % FILENAME
    cmd.disable(main_obj)
    traj = load_trajectory("%s.gro" % FILENAME, "%s.ndx" % FILENAME)
    traj.initialize()
    frame = traj[0]
    draw_pbc_box(main_obj)

    cmd.create("protein", "resi 1-160")
    cmd.hide("lines", "protein")
    cmd.color("yellow", "protein")
    cmd.show("cartoon", "protein")
    cmd.show("surface", "protein")
    cmd.set("transparency", 0.5, "protein")
    cmd.set("surface_color", "yelloworange", "protein")

    # Show leaflets
    show_leaflets(frame)

    # Show stuff related to APL
    show_apl(frame)

    print("Bilayer with protein loaded!")
Beispiel #7
0
    def sculpt(self,cleanup=0):
        if not cleanup:
            cmd.set("suspend_updates",1,quiet=1)
            cmd.disable()
            cmd.delete("sculpt")
            cmd.set("sphere_scale","1.0")
            cmd.set("sphere_mode",5)
            cmd.load("$PYMOL_DATA/demo/pept.pdb","sculpt")
            cmd.hide("lines","sculpt")
#            cmd.show("sticks","sculpt")
            cmd.show("spheres","sculpt")
#            cmd.set("sphere_transparency","0.75","sculpt")
#            cmd.set("sphere_color","grey","sculpt")
            cmd.frame(1)
            cmd.set("auto_sculpt",1)
            cmd.set("sculpting",1)
            cmd.sculpt_activate("sculpt")
            cmd.set("sculpting_cycles","100")
            cmd.do("edit_mode")
            cmd.set("valence","0.05")
            cmd.set("suspend_updates",0,quiet=0)
            cmd.sculpt_iterate("sculpt")
            cmd.alter_state(1,"sculpt","x=x*1.5;y=y*0.1;z=z*1.5")
            cmd.zoom()

            cmd.unpick()
        else:
            cmd.set("valence","0")
            cmd.set("sculpting",0)
            cmd.set("auto_sculpt",0)
            cmd.delete("sculpt")
            cmd.mouse()
Beispiel #8
0
    def testMeasureBetweenStates(self):
        cmd.load(self.datafile('1v5a-3models.cif'), 'm1')

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

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

        # visual test
        cmd.viewport(100, 100)
        cmd.set('dash_radius', 1.0)
        self.ambientOnly()
        for name in ['d1', 'a1']:
            cmd.disable('*')
            cmd.enable(name)
            cmd.zoom(name)
            self.assertImageHasColor('yellow')
    def test(self):
        cmd.viewport(100,100)

        cmd.set('gaussian_b_floor', 20)
        cmd.set('ambient', 1)
        cmd.set('specular', 0)
        cmd.set('mesh_color', 'blue')
        cmd.set('dot_color', 'green')

        cmd.fragment('gly')
        cmd.map_new('map1')
        cmd.disable('*')

        cmd.isomesh('o1', 'map1')
        cmd.color('red', 'o1')
        cmd.show('cell')
        self._check_colors('red', 'blue')
        cmd.delete('o1')
 
        cmd.isodot('o1', 'map1')
        cmd.color('red', 'o1')
        self._check_colors('green')
        cmd.delete('o1')

        cmd.gradient('o1', 'map1')
        cmd.color('yellow', 'o1')
        self._check_colors('yellow')
        cmd.delete('o1')
Beispiel #10
0
def get_dehydrons():
    cmd.delete('dehydrons')
    cmd.delete('DH_pairs')
    cmd.hide()
    angle = float(angle_value.get())
    cutoff = float(dist_cutoff_value.get())
    desolv = float(desolv_sphere.get())
    min_wrappers = float(min_value.get())
    selection = 'name n or name o and not resn hoh'
    hb = cmd.find_pairs("((byres "+selection+") and n. n)","((byres "+selection+") and n. o)",mode=1,cutoff=cutoff,angle=angle)
# sort the list for easier reading
    hb.sort(lambda x,y:(cmp(x[0][1],y[0][1])))
    print "------------------------------------------------\n----------------dehydron Results-----------------\n------------------------------------------------\n    Donor      |    Aceptor    |  \nChain Residue  | Chain Residue | # dehydrons"
    sel = []
    wra = 0
    for pairs in hb:
        cmd.iterate("%s and index %s" % (pairs[0][0], pairs[0][1]), 'stored.nitro = chain, resi, resn') # extracts the nitrogen
        cmd.iterate("%s and index %s" % (pairs[1][0], pairs[1][1]), 'stored.oxy = chain, resi, resn') # extracts the oxygen
        wrappers = cmd.select('wrap', '(((chain %s and name ca and resi %s) around %f) or ((chain %s and name ca and resi %s) around %f)) and (not ((neighbor name n*+o*) or (name n*+o*+h*)))' % (stored.nitro[0], stored.nitro[1], desolv, stored.oxy[0], stored.oxy[1], desolv)) #Identifies the putative dehydrons
        if wrappers < min_wrappers:
            wra = 1
            cmd.distance('Dehydrons',"%s and index %s" % (pairs[0][0],pairs[0][1]),"%s and index %s" % (pairs[1][0],pairs[1][1]))
            print ' %s%7s%5d | %s%7s%5d |%7s' % (stored.nitro[0], stored.nitro[2], int(stored.nitro[1]), stored.oxy[0], stored.oxy[2], int(stored.oxy[1]), wrappers)
            if stored.nitro[1] not in sel:
                sel.append(stored.nitro[1])
            if stored.oxy[1] not in sel:
                sel.append(stored.oxy[1])
    if wra == 1:
        cmd.select('DH_pairs', 'resi %s' % ('+').join(sel))
        cmd.show('lines', 'DH_pairs')
    cmd.disable('DH_pairs')
    cmd.hide('labels')
    cmd.delete('wrap')
    cmd.show('cartoon')
    cmd.show('dashes')
Beispiel #11
0
    def sculpt(self, cleanup=0):
        if not cleanup:
            cmd.set("suspend_updates", 1, quiet=1)
            cmd.disable()
            cmd.delete("sculpt")
            cmd.set("sphere_scale", "1.0")
            cmd.set("sphere_mode", 5)
            cmd.load("$PYMOL_DATA/demo/pept.pdb", "sculpt")
            cmd.hide("lines", "sculpt")
            #            cmd.show("sticks","sculpt")
            cmd.show("spheres", "sculpt")
            #            cmd.set("sphere_transparency","0.75","sculpt")
            #            cmd.set("sphere_color","grey","sculpt")
            cmd.frame(1)
            cmd.set("auto_sculpt", 1)
            cmd.set("sculpting", 1)
            cmd.sculpt_activate("sculpt")
            cmd.set("sculpting_cycles", "100")
            cmd.do("edit_mode")
            cmd.set("valence", "0.05")
            cmd.set("suspend_updates", 0, quiet=0)
            cmd.sculpt_iterate("sculpt")
            cmd.alter_state(1, "sculpt", "x=x*1.5;y=y*0.1;z=z*1.5")
            cmd.zoom()

            cmd.unpick()
        else:
            cmd.set("valence", "0")
            cmd.set("sculpting", 0)
            cmd.set("auto_sculpt", 0)
            cmd.delete("sculpt")
            cmd.mouse()
Beispiel #12
0
def save_surface(arg1):
    cmd.disable()
    cmd.enable(arg1)
    cmd.hide("everything", arg1)
    cmd.show("surface", arg1)
    cmd.save("%s.obj" % arg1, arg1)
    cmd.enable()
Beispiel #13
0
def split_chains(selection='(all)', prefix=None):
    '''
DESCRIPTION

    Create a single object for each chain in selection

SEE ALSO

    split_states, http://pymolwiki.org/index.php/Split_object
    '''
    count = 0
    models = cmd.get_object_list('(' + selection + ')')
    for model in models:
        for chain in cmd.get_chains('(%s) and model %s' % (selection, model)):
            if chain == '':
                chain = "''"
            count += 1
            if not prefix:
                name = '%s_%s' % (model, chain)
            else:
                name = '%s%04d' % (prefix, count)
            cmd.create(
                name,
                '(%s) and model %s and chain %s' % (selection, model, chain))
        cmd.disable(model)
Beispiel #14
0
def fatslim_apl_prot():
    global REF_BEAD
    setup()

    FILENAME = BILAYER_PROT
    REF_BEAD = BILAYER_PROT_REF

    # Load file
    cmd.load("%s.pdb" % FILENAME)
    main_obj = "%s" % FILENAME
    cmd.disable(main_obj)
    traj = load_trajectory("%s.gro" % FILENAME, "%s.ndx" % FILENAME)
    traj.initialize()
    frame = traj[0]
    draw_pbc_box(main_obj)

    cmd.create("protein", "resi 1-160")
    cmd.hide("lines", "protein")
    cmd.color("yellow", "protein")
    cmd.show("cartoon", "protein")
    cmd.show("surface", "protein")
    cmd.set("transparency", 0.5, "protein")
    cmd.set("surface_color", "yelloworange", "protein")

    # Show leaflets
    show_leaflets(frame)

    # Show stuff related to APL
    show_apl(frame)

    print("Bilayer with protein loaded!")
Beispiel #15
0
def fatslim_bilayer():
    global REF_BEAD
    REF_BEAD = BILAYER_REF
    setup()

    # Load file
    cmd.load("%s.pdb" % BILAYER)
    main_obj = "bilayer"
    cmd.disable(main_obj)
    traj = load_trajectory("%s.gro" % BILAYER, "%s.ndx" % BILAYER)
    traj.initialize()
    frame = traj[0]
    draw_pbc_box(main_obj)
    print("Bilayer Loaded!")

    # Show lipids
    cmd.create("lipids", "resname DMPC")
    cmd.hide("lines", "lipids")
    cmd.show("spheres", "lipids")

    # Show water
    cmd.create("water", "resname SOL")
    cmd.hide("lines", "water")
    cmd.set("solvent_radius", 2)
    cmd.show("surface", "water")
    cmd.color("skyblue", "water")
    cmd.set("transparency", 0.5, "water")
    # cmd.rebuild()
    # cmd.refresh()

    # Show positions
    show_positions(frame)

    # Show directions
    show_directions(frame)

    # Show ref bead and its neighbors
    show_ref(frame)

    show_ref_ns(frame)

    # Show normals
    show_normals(frame)

    # Identify leaflets
    show_leaflets(frame)

    # Calculate and show normals
    show_leaflet_normals(frame)

    # Show stuff related to thickness
    show_thickness(frame)

    # Show stuff related to APL
    show_apl(frame)

    # Zoom on leaflets
    cmd.zoom("all", 5)
Beispiel #16
0
def gremlin(file,chain='B',s_score_th=1.5,prob_th=1,inc='0',color="red"):

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

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

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

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

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

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

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

				if prob >= float(prob_th) and s_score >= float(s_score_th):
					dist = cmd.distance("%s"%(pair),"resi %i and name ca and chain %s"%(pos1,chain),"resi %i and name ca and chain %s"%(pos2,chain))
					if dist <= 12:
						cmd.set("dash_color","yellow","%s"%(pair))
					if dist > 12 and dist <= 20:
						cmd.set("dash_color","orange","%s"%(pair))
					if dist > 20:
						cmd.set("dash_color","red","%s"%(pair))
Beispiel #17
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)
Beispiel #18
0
def fatslim_bilayer():
    global REF_BEAD
    REF_BEAD = BILAYER_REF
    setup()

    # Load file
    cmd.load("%s.pdb" % BILAYER)
    main_obj = "bilayer"
    cmd.disable(main_obj)
    traj = load_trajectory("%s.gro" % BILAYER, "%s.ndx" % BILAYER)
    traj.initialize()
    frame = traj[0]
    draw_pbc_box(main_obj)
    print("Bilayer Loaded!")

    # Show lipids
    cmd.create("lipids", "resname DMPC")
    cmd.hide("lines", "lipids")
    cmd.show("spheres", "lipids")

    # Show water
    cmd.create("water", "resname SOL")
    cmd.hide("lines", "water")
    cmd.set("solvent_radius", 2)
    cmd.show("surface", "water")
    cmd.color("skyblue", "water")
    cmd.set("transparency", 0.5, "water")
    # cmd.rebuild()
    # cmd.refresh()

    # Show positions
    show_positions(frame)

    # Show directions
    show_directions(frame)

    # Show ref bead and its neighbors
    show_ref(frame)

    show_ref_ns(frame)

    # Show normals
    show_normals(frame)

    # Identify leaflets
    show_leaflets(frame)

    # Calculate and show normals
    show_leaflet_normals(frame)

    # Show stuff related to thickness
    show_thickness(frame)

    # Show stuff related to APL
    show_apl(frame)

    # Zoom on leaflets
    cmd.zoom("all", 5)
Beispiel #19
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'])
Beispiel #20
0
 def toggle_subgroup(subgroup, enable):
     SEL = {
             '1->2': 'mp_*.1to2.*',
             '2->1': 'mp_*.2to1.*',
             }
     if enable:
         cmd.enable(SEL[subgroup])
     else:
         cmd.disable(SEL[subgroup])
Beispiel #21
0
def align_and_color(moving, fixed, maximum=None, native_color="blue"):
    if maximum == "0":
        maximum = None
    alignment_name = "alignment_" + moving
    cmd.align(moving, fixed, object=alignment_name, cycles=0)
    cmd.disable(alignment_name)
    rmsd_b(moving + " & " + alignment_name, fixed + " & " + alignment_name)
    cmd.color(native_color, fixed)
    cmd.spectrum("b", "green_red", moving, 0, maximum)
Beispiel #22
0
def align_and_color(moving, fixed, maximum=None, native_color="blue"):
    if maximum == "0":
        maximum = None
    alignment_name = "alignment_" + moving
    cmd.align(moving, fixed, object=alignment_name, cycles=0)
    cmd.disable(alignment_name)
    rmsd_b(moving + " & " + alignment_name, fixed + " & " + alignment_name)
    cmd.color(native_color, fixed)
    cmd.spectrum("b", "green_red", moving, 0, maximum)
Beispiel #23
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'])
Beispiel #24
0
 def toggle_subgroup(subgroup, enable):
     SEL = {
         '1->2': 'mp_*.1to2.*',
         '2->1': 'mp_*.2to1.*',
     }
     if enable:
         cmd.enable(SEL[subgroup])
     else:
         cmd.disable(SEL[subgroup])
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)
Beispiel #26
0
def smooth_map_from_xyz(name,
                        selection,
                        contour_level,
                        grid_spacing,
                        bfactor=100,
                        gaussRes=3,
                        grid_buffer=2,
                        state=0):
    """Creates a map object from a selection with xyz coordinates (e.g. a PDB or XYZ object)
    and draws a smooth isosurface at the specified contour level.

    Parameters
    ----------

    name : str
        name of the map
    selection : xyz object
        loaded PDB or XYZ file
    contour_level : float
        contour level (in sigma units)
    grid_spacing : float
        spacing between grid points (in A)
    bfactor : int
        temperature factor; higher numbers generates smoother surfaces
    gaussRes : int, optional=3
        Gaussian resolution; higher numbers generate smoother surfaces
    grid_buffer : float, optional=2
        buffer for map
    state : int, optional=0
        0: use all states independently with independent extents (default)
        -3: combine all states (ACVs) into a single map

    Notes
    ----
    If a map for each ACV of a multi-model PDB file should be generated,
    the PDB file must be loaded with the flag discrete=1 (load as discrete objects
    to allow each ACV to have different numbers of grid points.
    (see also https://www.pymolwiki.org/index.php/Discrete_objects)

    """
    name_surf = name + "_isosurf"
    name_map = name + "_map"
    bfactor_str = "b={:d}".format(int(bfactor))
    cmd.alter(selection, bfactor_str)
    cmd.alter(selection, bfactor_str)
    gaussRes_default = cmd.get("gaussian_resolution")
    cmd.set("gaussian_resolution", gaussRes)
    cmd.map_new(name_map, "gaussian", grid_spacing, selection, state=state)
    cmd.isosurface(name_surf,
                   name_map,
                   contour_level,
                   selection,
                   buffer=grid_buffer)
    cmd.set("gaussian_resolution", gaussRes_default)
    cmd.disable(selection)
Beispiel #27
0
 def display_selected():
     """Display entries corresponding to selected rows"""
     #TODO: multiple selection
     selected_row = widget.tableDocked.selectedItems()
     if selected_row:
         row_n = selected_row[0].row()
         object = widget.tableDocked.item(row_n, 1).text()
         state = widget.tableDocked.item(row_n, 2).text()
         cmd.set('state', state)
         cmd.disable(" ".join(docked.objects))
         cmd.enable(object)
Beispiel #28
0
def clean(pose):
    """Deletes everything and load the validated models"""
    cmd.delete('all')
    cmd.load('%s_Ca.pdb' % pose)
    cmd.load('%s_Cb.pdb' % pose)
    cmd.load('%s_CaCb.pdb' % pose)
    cmd.intra_fit('%s_Ca' % pose, 0, quiet=1)
    cmd.intra_fit('%s_Cb' % pose, 0, quiet=1)
    cmd.intra_fit('%s_CaCb' % pose, 0, quiet=1)
    cmd.dss('all')
    cmd.disable('%s_Ca' % pose)
    cmd.disable('%s_Cb' % pose)
    def enable_selected():
        selected = list(set([int(x.resi) for x in cmd.get_model("sele").atom]))

        for name in cmd.get_names("objects"):
            if (name.startswith("esto_res")):
                cmd.disable(name)

        for seqpos in selected:
            name = "esto_res%i"%seqpos
            cmd.enable(name)

        cmd.delete("sele")
Beispiel #30
0
    def run(self):
        
        print("FlexAID parsing thread has begun.")

        # Set the auto_zoom to off
        cmd.set("auto_zoom", 0)
        cmd.delete("TOP_*__")
        cmd.delete("RESULT_*")
        cmd.refresh()
        cmd.frame(1)
        
        self.queue.put(lambda: self.top.InitStatus())
        self.queue.put(lambda: self.top.progressBarHandler(0, self.NbTotalGen))
        
        # send ready to simulate signal
        print('  Signal sent to start simulation')
        self.FlexAID.ParseState = 0
        
        print('  Waiting for FlexAID to start')
        # wait for FlexAID to start, to crash or to finish (if simulation is very short and quickly done)
        while self.FlexAID.SimulateState < 0:
            time.sleep(self.top.INTERVAL)
            
        print('  Parsing the logfile of FlexAID')
        while self.FlexAID.Run is not None: # and self.FlexAID.Run.poll() is None:
            time.sleep(self.top.INTERVAL)
            if self.ParseLines():
                break
        
        if not self.FlexAID.ParseState > 0:
            self.ParseLines()
        
        # Put back the auto_zoom to on
        cmd.set("auto_zoom", self.auto_zoom)

        # error in simulation or parsing?
        if self.FlexAID.SimulateState > 0 or self.FlexAID.ParseState > 0:
            self.queue.put(lambda: self.top.ErrorStatus(self.ErrorMsg))
        else:
            self.queue.put(lambda: self.top.SuccessStatus())
    
            if self.top.Results:
                cmd.enable("RESULT_*")
                cmd.refresh()

            cmd.disable("TOP_*__")
            cmd.refresh()
                
            cmd.frame(1)
        
        self.FlexAID.ParseState = 10

        print("FlexAID parsing thread has ended.")
Beispiel #31
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'])
Beispiel #32
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])
Beispiel #33
0
    def align(self, mobile, target, match):
        '''
        Align mobile to target using the alignment method given by "match"
        '''
        aln_obj = cmd.get_unused_name('_')
        self.temporary.append(aln_obj)

        align = cmd.keyword[match][0]
        align(mobile, target, cycles=0, transform=0, object=aln_obj)
        cmd.disable(aln_obj)

        self.from_alignment(mobile, target, aln_obj)
Beispiel #34
0
    def run(self):

        print("FlexAID parsing thread has begun.")

        # Set the auto_zoom to off
        cmd.set("auto_zoom", 0)
        cmd.delete("TOP_*__")
        cmd.delete("RESULT_*")
        cmd.refresh()
        cmd.frame(1)

        self.queue.put(lambda: self.top.InitStatus())
        self.queue.put(lambda: self.top.progressBarHandler(0, self.NbTotalGen))

        # send ready to simulate signal
        print('  Signal sent to start simulation')
        self.FlexAID.ParseState = 0

        print('  Waiting for FlexAID to start')
        # wait for FlexAID to start, to crash or to finish (if simulation is very short and quickly done)
        while self.FlexAID.SimulateState < 0:
            time.sleep(self.top.INTERVAL)

        print('  Parsing the logfile of FlexAID')
        while self.FlexAID.Run is not None:  # and self.FlexAID.Run.poll() is None:
            time.sleep(self.top.INTERVAL)
            if self.ParseLines():
                break

        if not self.FlexAID.ParseState > 0:
            self.ParseLines()

        # Put back the auto_zoom to on
        cmd.set("auto_zoom", self.auto_zoom)

        # error in simulation or parsing?
        if self.FlexAID.SimulateState > 0 or self.FlexAID.ParseState > 0:
            self.queue.put(lambda: self.top.ErrorStatus(self.ErrorMsg))
        else:
            self.queue.put(lambda: self.top.SuccessStatus())

            if self.top.Results:
                cmd.enable("RESULT_*")
                cmd.refresh()

            cmd.disable("TOP_*__")
            cmd.refresh()

            cmd.frame(1)

        self.FlexAID.ParseState = 10

        print("FlexAID parsing thread has ended.")
Beispiel #35
0
    def align(self, mobile, target, match):
        '''
        Align mobile to target using the alignment method given by "match"
        '''
        aln_obj = cmd.get_unused_name('_')
        self.temporary.append(aln_obj)

        align = cmd.keyword[match][0]
        align(mobile, target, cycles=0, transform=0, object=aln_obj)
        cmd.disable(aln_obj)

        self.from_alignment(mobile, target, aln_obj)
Beispiel #36
0
    def batch_convert_modules(src_dir=None, dst_dir=None, ext='obj'):
        """Batch convert Elfin protein module PDBs.

        Args:
        - src_dir - input PDB directory (one that contains sub_dirs like singles,
            doubles, hubs)
        - dst_dir - output PDB directory
        - ext - file extension supported by PyMol
        """

        if src_dir is None or dst_dir is None:
            print(batch_convert.__doc__)
        else:
            # Clear workspace
            cmd.reinitialize()

            sub_dirs = ['singles', 'doubles',
                        'hubs']  # don't think we need cappings

            for sd in sub_dirs:
                make_dir(dst_dir + '/' + sd)

            files = [
                f for flist in [
                    glob.glob(src_dir + '/{}/*.pdb'.format(sd))
                    for sd in sub_dirs
                ] for f in flist
            ]

            cmd.set('auto_show_nonbonded', 'off')
            cmd.set('auto_show_selections', 'off')
            cmd.set('auto_show_spheres', 'off')
            cmd.set('auto_show_classified', 'off')
            cmd.set('auto_show_lines', 'off')

            fn_info = []
            for f in files:
                cmd.load(f)
                name = '.'.join((re.split(r'/|\\', f)[-1]).split('.')[:-1])
                fn_info.append((f, name))

            cmd.disable('all')
            cmd.show('cartoon')
            for (file_path, module_name) in fn_info:
                cmd.enable(module_name)
                cmd.save(
                    file_path.replace(src_dir,
                                      dst_dir).replace('.pdb', '.' + ext))
                cmd.disable(module_name)

            # Clear workspace
            cmd.delete('all')
Beispiel #37
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
Beispiel #38
0
def trans():
    cmd.disable("all")
    objs=[x for x in cmd.get_names("objects") if x.find("start")==0]
    trans=float(1)/len(objs)
    t=0
    for x in objs:
        t+=trans
        cmd.enable(x)
        print x,t
        cmd.set("cartoon_transparency",t)
        cmd.set("stick_transparency",t)       
        cmd.png("%s.png" %x,ray=1)
        cmd.disable(x)
Beispiel #39
0
    def _load_example(self):
        # object in hidden group
        cmd.fragment('ile', 'm1')
        cmd.fragment('his', 'm2')
        cmd.group('g1', 'm1')
        cmd.disable('g1')

        # testable styling
        self.ambientOnly()
        cmd.orient()
        cmd.color('red', 'm1')
        cmd.color('blue', 'm2')
        cmd.show_as('spheres')
Beispiel #40
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
Beispiel #42
0
    def _load_example(self):
        # object in hidden group
        cmd.fragment('ile', 'm1')
        cmd.fragment('his', 'm2')
        cmd.group('g1', 'm1')
        cmd.disable('g1')

        # testable styling
        self.ambientOnly()
        cmd.orient()
        cmd.color('red', 'm1')
        cmd.color('blue', 'm2')
        cmd.show_as('spheres')
Beispiel #43
0
def genAV(obstacles, attachment, linker_length=20.0, linker_diameter=2.0, dye_radius=3.5, disc_step=0.9, name=None, state=1, stripsc=True, allowed_sphere_radius=0.0, smoothSurf=True):

  source = np.array(cmd.get_model(attachment, state).get_coord_list())
  if (source.shape[0]!=1):
    print('attachment selection must contain exactly one atom, selected: {}'.format(source.shape[0]))
    return
  source=source.reshape(3)

  srcAt = cmd.get_model(attachment, state).atom[0]
  srcModelName = cmd.get_names('objects',0,attachment)[0]

  obstacles = '(' + obstacles + ') and not (' + attachment + ')'
  if stripsc and isAA(srcAt.resn):
    obstacles += ' and not (' + srcModelName
    if len(srcAt.chain)>0:
      obstacles += ' and chain ' + srcAt.chain
    obstacles+=' and resi '+srcAt.resi+' and sidechain'+')'
  if allowed_sphere_radius > 0.0:
    obstacles+=' and not (({}) around {})'.format(attachment, allowed_sphere_radius)

  xyzRT=np.zeros((1,4))
  nAtoms=cmd.count_atoms(obstacles)
  if nAtoms>0:
    atoms=cmd.get_model(obstacles, state).atom
    nAtoms=len(atoms)
    xyzRT=np.zeros((nAtoms,4))
    for i,at in enumerate(atoms):
      xyzRT[i]=[at.coord[0],at.coord[1],at.coord[2],at.vdw]

  av1=ll.dyeDensityAV1(xyzRT.T,source,linker_length, linker_diameter, dye_radius, disc_step)
  m=avToModel(av1)
  if len(m.atom)==0:
    print('Failed: Empty AV. Is attachment position buried?')
    return
  if name is None:
    name = srcModelName + '_'
    if len(srcAt.chain)>0:
      name += srcAt.chain + '-'
    name +=  srcAt.resi + '-' + srcAt.name
  cmd.load_model(m, name)

  if smoothSurf:
    surfName=name+'_surf'
    mapName=name+'_map'
    gRes=cmd.get('gaussian_resolution')
    cmd.set('gaussian_resolution',3.0)
    cmd.map_new(mapName,'gaussian', 1.0, name, 6)
    cmd.isosurface(surfName,mapName,0.9)
    cmd.set('gaussian_resolution',gRes)
    cmd.disable(name)
def save_sele_as_ligExp(selection='sele'):
    ([minX, minY, minZ], [maxX, maxY, maxZ]) = cmd.get_extent(selection)
    pdb_base = cmd.get_object_list(selection)[0]
    cmd.disable('*')
    cmd.enable('pdb_base', 1)
    replace_list = ['_aligned_rm_ion', '_aligned', '_rm', '_ion', '_preped']
    pdb_base_short = pdb_base
    for rep in replace_list:
        pdb_base_short = pdb_base_short.replace(rep, '')
    cmd.save('ligExp_' + pdb_base_short + ".sdf", 'sele', -1, 'sdf')
    cmd.delete('sele')
    #cmd.disable(pdb_base)
    cmd.delete(pdb_base)
    return
Beispiel #45
0
def rpcHide(objs):
  """ hides (disables) an object (or objects) """
  if type(objs) not in (types.ListType, types.TupleType):
    objs = (objs, )

  for objName in objs:
    try:
      cmd.disable(objName)
    except Exception:
      res = 0
      break
    else:
      res = 1
  return res
Beispiel #46
0
def rpcHide(objs):
    """ hides (disables) an object (or objects) """
    if type(objs) not in (types.ListType, types.TupleType):
        objs = (objs, )

    for objName in objs:
        try:
            cmd.disable(objName)
        except:
            res = 0
            break
        else:
            res = 1
    return res
Beispiel #47
0
    def testGetRawAlignment(self):
        from collections import defaultdict
        cmd.fab('ACDEGGKLMN', 'm1')
        cmd.fab('CDEFFGGK', 'm2')
        cmd.fab('ASDEKLMNFY', 'm3')
        cmd.align('m2 & guide', 'm1 & guide', cycles=0, object='aln')
        cmd.align('m3 & guide', 'm1 & guide', cycles=0, object='aln')
        cmd.disable('m2')
        # expecting alignment:
        # m1 ACDE--GGKLMN--
        # m2 -CDEFFGGK-----
        # m3 ASDE----KLMQFY
        guideids = defaultdict(list)
        cmd.iterate('guide', 'guideids[model].append(index)', space=locals())
        idx = lambda m, i: (m, guideids[m][i])
        aln_expect = [
            [idx('m1', 0), idx('m3', 0)],
            [idx('m1', 1), idx('m2', 0),
             idx('m3', 1)],
            [idx('m1', 2), idx('m2', 1),
             idx('m3', 2)],
            [idx('m1', 3), idx('m2', 2),
             idx('m3', 3)],
            [
                idx('m1', 4),
                idx('m2', 5),
            ],
            [
                idx('m1', 5),
                idx('m2', 6),
            ],
            [idx('m1', 6), idx('m2', 7),
             idx('m3', 4)],
            [idx('m1', 7), idx('m3', 5)],
            [idx('m1', 8), idx('m3', 6)],
            [idx('m1', 9), idx('m3', 7)],
        ]
        dictify = lambda aln: [dict(col) for col in aln]
        aln_expect = dictify(aln_expect)

        aln = cmd.get_raw_alignment('aln', 0)
        self.assertEqual(dictify(aln), aln_expect)

        # remove m2 from alignment
        for d in aln_expect:
            d.pop('m2', None)

        aln = cmd.get_raw_alignment('aln', 1)
        self.assertEqual(dictify(aln), aln_expect)
Beispiel #48
0
def save_images(title=1):
	cmd.set( 'ray_opaque_background', 0 )
	for x in cmd.get_names( 'all' ):
		rg = rgyrate( x , 1 )

		cmd.disable( 'all' )
		cmd.enable( x )
		cmd.zoom( x, buffer=0.0, state=0, complete=1 )
		if title:
			cmd.set( 'label_size', 25 )
			#cmd.set( 'label_position', (0,-25,0) )
			cmd.set( 'label_position', (0,(-10-rg),0) )
			cmd.pseudoatom( 'pa', label=x )
		cmd.zoom( 'visible', buffer=5, state=0, complete=1 )
		cmd.png( x+'.png', dpi=300, ray=1 )
		cmd.delete( 'pa' )
Beispiel #49
0
    def disable_kin(self, kin='all'):
        '''Disable an MPObject kinemage.

        PARAMETERS

            kin     (str) The kinemage to be disabled.  Possible values are
                    'flipkinNQ', 'flipkinH', 'probe', or 'all'.  (Default: all)

        '''
        if kin == 'all':
            for k in self.kin.keys():
                self.disable_kin(k)
        else:
            kin_grp = self.get_kin_cgo_group(kin)
            logger.debug('disabling'.format(kin_grp))
            cmd.disable(kin_grp)
Beispiel #50
0
    def disable_pdb(self, pdb='all'):
        '''Disable an MPObject structure object.

        PARAMETERS

            pdb     (str) The structure to be disabled.  Possible values are
                    'reduce', 'flipkinNQ', 'flipkinH', 'userflips', 'probe', or
                    'all'.  (Default: all)

        '''
        if pdb == 'all':
            for p in self.pdb.keys():
                self.disable_pdb(p)
        else:
            pdb_obj = self.pdb[pdb]
            logger.debug('disabling {}'.format(pdb_obj))
            cmd.disable(pdb_obj)
Beispiel #51
0
 def cartoon(self,cleanup=0):
     if not cleanup:
         try:
             cmd.set("suspend_updates",1,quiet=1)
             cmd.disable()
             cmd.delete("1tii")      
             cmd.load("$PYMOL_DATA/demo/1tii.pdb")
             cmd.hide("(1tii)")
             cmd.show("cartoon","1tii")
             cmd.zoom("1tii")
             cmd.spectrum("count","rainbow","1tii////ca")
             cmd.set("cartoon_highlight_color","grey50","1tii")
             cmd.set("cartoon_fancy_helices",1,"1tii")
         finally:
             cmd.set("suspend_updates",0,quiet=1)
         cmd.refresh()
     else:
         cmd.delete("1tii")
Beispiel #52
0
 def elec(self,cleanup=0):
     if not cleanup:
         cmd.disable()
         cmd.delete("pept")
         cmd.delete("e_pot")
         cmd.delete("e_lvl")
         cmd.load("$PYMOL_DATA/demo/pept.pkl")
         cmd.hide("(pept)")
         cmd.show("surface","pept")
         cmd.set("coulomb_dielectric",80.0)
         cmd.map_new("e_pot","coulomb",1.0,"pept",5)
         cmd.ramp_new("e_lvl","e_pot",[-3.6,-1.6,0.4])
         cmd.set("surface_color","e_lvl","pept")
         cmd.refresh()
     else:
         cmd.delete("pept")
         cmd.delete("e_pot")
         cmd.delete("e_lvl")
Beispiel #53
0
 def trans(self,cleanup=0):
     if not cleanup:
         try:
             cmd.set("suspend_updates",1,quiet=1)
             cmd.disable()
             cmd.delete("trans")
             cmd.load("$PYMOL_DATA/demo/pept.pdb","trans")
             cmd.hide("(trans)")
             cmd.show("surface","trans")
             cmd.show("sticks","trans")
             cmd.set("surface_color","white","trans")
             cmd.set("transparency",0.5,"trans")
             cmd.zoom("trans")
         finally:
             cmd.set("suspend_updates",0,quiet=1)
         cmd.refresh()
     else:
         cmd.delete("trans")
Beispiel #54
0
def split(operator, selection, prefix="entity"):
    """
DESCRIPTION

    Create a single object for each entity in selection, defined by operator
    (e.g. bymolecule, bysegment, ...). Returns the number of created objects.
    """
    cmd.disable(" ".join(cmd.get_object_list("(" + selection + ")")))
    tmp = cmd.get_unused_name("_")
    cmd.create(tmp, selection)

    r = 0
    while cmd.count_atoms(tmp) > 0:
        name = cmd.get_unused_name(prefix)
        cmd.extract(name, operator + " first model " + tmp)
        r += 1

    cmd.delete(tmp)
    return r
Beispiel #55
0
 def roving_density(self,cleanup=0):
     if not cleanup:
         try:
             cmd.load("$PYMOL_DATA/demo/il2.pdb")
             cmd.set("suspend_updates",1,quiet=1)
             cmd.remove("hydro")
             cmd.disable()
             cmd.enable("il2")
             cmd.map_new("map","gaussian","0.75","il2")
             cmd.feedback("disable","objectmesh","actions")
             cmd.set("ribbon_color","purple","il2")
             cmd.set("roving_detail",1)
             cmd.set("roving_origin",1)
             cmd.set("stick_radius",0.12,"il2")
             cmd.set("roving_sticks",0)
             cmd.set("roving_polar_contacts",0)
             cmd.set("line_width","3")
             cmd.set("roving_map1_name","map")
             cmd.isomesh("rov_m1","map",9999.0,"il2")
             cmd.color("density","rov_m1")
             
             cmd.set_view ((\
       0.132852688,   -0.729740858,    0.670686543,\
       -0.228543565,    0.635894477,    0.737154961,\
       -0.964425683,   -0.251212329,   -0.082298420,\
       0.000062190,    0.000183226,  -58.861488342,\
       13.349151611,   -1.565427899,   22.383148193,\
       55.259441376,   63.259449005,    0.000000000 ))
         finally:
             cmd.set("suspend_updates",0,quiet=1)
         cmd.refresh()
     else:
         cmd.set("roving_detail",0)
         cmd.set("roving_map1_name","")
         cmd.set("roving_polar_contacts",7)
         cmd.set("roving_sticks",6)
         cmd.delete("il2")
         cmd.delete("map")
         cmd.set("line_width",1.5)
         cmd.refresh()
         cmd.set("roving_detail",0)
         cmd.delete("rov_*")
         cmd.sync()
Beispiel #56
0
def split(operator, selection, prefix='entity'):
    '''
DESCRIPTION

    Create a single object for each entity in selection, defined by operator
    (e.g. bymolecule, bysegment, ...). Returns the number of created objects.
    '''
    cmd.disable(' '.join(cmd.get_object_list('(' + selection + ')')))
    tmp = cmd.get_unused_name('_')
    cmd.create(tmp, selection)

    r = 0
    while cmd.count_atoms(tmp) > 0:
        name = cmd.get_unused_name(prefix)
        cmd.extract(name, operator + ' first model ' + tmp)
        r += 1

    cmd.delete(tmp)
    return r
Beispiel #57
0
def protein_vacuum_esp(selection, mode=2, border=10.0, quiet = 1, _self=cmd):
    pymol=_self._pymol
    cmd=_self

    if ((string.split(selection)!=[selection]) or
         selection not in cmd.get_names('objects')):
        print " Error: must provide an object name"
        raise cmd.QuietException
    obj_name = selection + "_e_chg"
    map_name = selection + "_e_map"
    pot_name = selection + "_e_pot"
    cmd.disable(selection)
    cmd.delete(obj_name)
    cmd.delete(map_name)
    cmd.delete(pot_name)
    cmd.create(obj_name,"((polymer and ("+selection+
               ") and (not resn A+C+T+G+U)) or ((bymol (polymer and ("+
               selection+"))) and resn NME+NHE+ACE)) and (not hydro)")
         # try to just get protein...

    protein_assign_charges_and_radii(obj_name,_self=_self)
        
    ext = cmd.get_extent(obj_name)
    max_length = max(abs(ext[0][0] - ext[1][0]),abs(ext[0][1] - ext[1][1]),abs(ext[0][2]-ext[1][2])) + 2*border

    # compute an grid with a maximum dimension of 50, with 10 A borders around molecule, and a 1.0 A minimum grid

    sep = max_length/50.0
    if sep<1.0: sep = 1.0
    print " Util: Calculating electrostatic potential..."
    if mode==0: # absolute, no cutoff
        cmd.map_new(map_name,"coulomb",sep,obj_name,border)
    elif mode==1: # neutral, no cutoff
        cmd.map_new(map_name,"coulomb_neutral",sep,obj_name,border)
    else: # local, with cutoff
        cmd.map_new(map_name,"coulomb_local",sep,obj_name,border)      
        
    cmd.ramp_new(pot_name, map_name, selection=obj_name,zero=1)
    cmd.hide("everything",obj_name)
    cmd.show("surface",selection)
    cmd.set("surface_color",pot_name,selection)
    cmd.set("surface_ramp_above_mode",1,selection)