def rrs(): """) rhiju's favorite coloring of RNA, showing all heavy atoms as sticks -- more detail than rr(). """ rr() cmd.show( 'sticks', 'not elem H' )
def occupiedWaters(sele=None, fName="fixedProtonations.txt"): '''Color the occupied waters in a different color. ''' WAT_COLOR = {"IPE_UNOCC":"white", "IPE_OCC":"blue", "CRY_UNOCC":"yellow", "CRY_OCC":"red"} extra = "" if sele: extra = " and %s" % sele cmd.color(WAT_COLOR["IPE_UNOCC"], "resn hoh and chain x" + extra) cmd.set("sphere_scale", "0.1", "resn hoh and chain x" + extra) cmd.color(WAT_COLOR["CRY_UNOCC"], "resn hoh and chain a" + extra) cmd.set("sphere_scale", "0.2", "resn hoh and chain a" + extra) cmd.show("spheres", "resn hoh" + extra) cmd.set("label_position", (0,-1.5,0)) if os.path.exists(fName): counter = 0 for eachLine in open(fName): fields = eachLine.split() if fields[0][:3] != "HOH": continue chainId = fields[0][3] resSeq = int(fields[0][-4:]) selection = ("resn hoh and chain %c and resi %d" % (chainId, resSeq)) + extra if int(fields[1]) != DUMMY_WATER: cmd.set("sphere_scale", "0.3", selection) if chainId == 'A': cmd.color(WAT_COLOR["CRY_OCC"], selection) cmd.label(selection, '"A" + resi') elif chainId == 'X': cmd.color(WAT_COLOR["IPE_OCC"], selection) cmd.label(selection, '"X" + resi') counter += 1 print "%d occupied waters colored" % counter
def sewalign(first,second): #hide waters cmd.hide("(solvent and (all))") #hide hydrogens cmd.hide( 'sticks', 'elem H' ) cmd.hide( 'lines', 'elem H' ) #show cartoon cmd.show("cartoon" ,"all") #create duplicate of first first_copy = first + "_copy" cmd.copy(first_copy, first) #select first 14 residues cmd.select('node_9_selection', '(obj *_9_* and resi 1-14)') cmd.select('node_12_selection', '(obj *_12_* and resi 1-14)') cmd.select('node_15_selection', '(obj *_15_* and resi 1-14)') alignment_1 = cmd.align(first, 'node_9_selection') print alignment_1[0] alignment_2 = cmd.align(second, 'node_12_selection') print alignment_2[0] alignment_3 = cmd.align(first_copy, 'node_15_selection') print alignment_3[0]
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')
def cartoon(): cmd.show("cartoon") cmd.hide("(solvent and (all))") cmd.hide("(all and hydro)") cmd.hide( 'sticks' ) cmd.hide( 'lines' ) color_chains(rainbow = 0)
def do_pick(self, picked_bond): # this shouldn't actually happen if going through the "do_select" if picked_bond: self.error = "Error: please select bonds, not atoms" print self.error return atom_name = self.object_prefix + str(self.pick_count) if self.pick_count < 2: self.pickNextAtom(atom_name) else: self.pickNextAtom(atom_name) point1 = cmd.get_atom_coords("(%s%s)" % (self.object_prefix, "0")) point2 = cmd.get_atom_coords("(%s%s)" % (self.object_prefix, "1")) point3 = cmd.get_atom_coords("(%s%s)" % (self.object_prefix, "2")) plane = planeFromPoints(point1, point2, point3, self.facetSize) planeName = "plane-%02d" % self.object_count self.object_count += 1 makePrimitive(plane, planeName) cmd.show("cgo", "plane*") self.pick_count = 0 self.reset()
def com(selection,state=None,mass=None,object=None, quiet=1, **kwargs): """ DESCRIPTION Places a pseudoatom at the center of mass Author: Sean Law Michigan State University slaw (at) msu . edu SEE ALSO pseudoatom, get_com """ quiet = int(quiet) if (object == None): object = cmd.get_legal_name(selection) object = cmd.get_unused_name(object + "_COM", 0) cmd.delete(object) if (state != None): x, y, z=get_com(selection,mass=mass, quiet=quiet) if not quiet: print "%f %f %f" % (x, y, z) cmd.pseudoatom(object,pos=[x, y, z], **kwargs) cmd.show("spheres",object) else: for i in range(cmd.count_states()): x, y, z=get_com(selection,mass=mass,state=i+1, quiet=quiet) if not quiet: print "State %d:%f %f %f" % (i+1, x, y, z) cmd.pseudoatom(object,pos=[x, y, z],state=i+1, **kwargs) cmd.show("spheres", 'last ' + object)
def loadBR(pdb, saveName=None, color=None): if not saveName: saveName = pdb.split('.')[0] cmd.load(pdb, saveName) if color: cmd.color(color, saveName) cmd.hide("lines") cmd.hide("nonbonded") # cmd.show("cartoon") cmd.show("ribbon") cmd.set("cartoon_transparency", 0.7) keyResidues = ["ASPA0085", "ARGA0082", "GLUA0194", "GLUA0204", "LYSA0216", "RET", "ASPA0212"] for eachRes in keyResidues: # retinal's residue sequence id can vary in different pdbs. selection = "" if eachRes == "RET": selection = "resn ret" else: selection = parseResidue(eachRes) selection += " and not name c+o+n" cmd.show("sticks", selection) util.cbag(selection)
def damdisplay(sel, color='white', transparency=0.5): '''set visualization of dummy atom models''' #cmd.hide(representation="nonbonded", selection = sel); cmd.hide(representation="everything", selection = sel); cmd.color(color, selection = sel); cmd.set("transparency", transparency, selection = sel); cmd.show(representation="surface", selection = sel);
def DisplaySphere(self): try: # Display the Sphere cmd.delete(self.SphereDisplay) cmd.refresh() except: pass try: cmd.pseudoatom(self.SphereDisplay, pos=self.SphereView.Center, vdw=self.SphereView.Radius, state=self.State) cmd.refresh() cmd.color('oxygen', self.SphereDisplay) cmd.refresh() cmd.hide('everything', self.SphereDisplay) cmd.refresh() cmd.show('spheres', self.SphereDisplay) cmd.refresh() except: self.ErrorCode = 1 return self.ErrorCode
def updateSS(self): if self.ss_asgn_prog is None: err_msg = 'Run DSSP or Stride to assign secondary structures first!' print 'ERROR: %s' % (err_msg,) tkMessageBox.showinfo(title='ERROR', message=err_msg) else: print 'Update secondary structures for %s' % (self.pymol_sel.get()), print 'using secondary structure assignment by %s' % (self.ss_asgn_prog,) print 'SSE mapping: (H,G,I) ==> H; (E,B,b) ==> S; (T,S,-,C) ==> L' if self.ss_asgn_prog == 'DSSP': SSE_list = self.DSSP_SSE_list elif self.ss_asgn_prog == 'Stride': SSE_list = self.STRIDE_SSE_list for sse in SSE_list: for sel_obj in self.sel_obj_list: if self.SSE_sel_dict[sel_obj][sse] is not None: cmd.alter(self.SSE_sel_dict[sel_obj][sse], 'ss=\'%s\''% (self.SSE_map[sse],)) print 'alter %s, ss=%s' % (self.SSE_sel_dict[sel_obj][sse], self.SSE_map[sse]) else: print 'No residue with SSE %s to update ss.' % (sse,) # show cartoon for the input selection, and rebuild cmd.show('cartoon',self.pymol_sel.get()) cmd.rebuild(self.pymol_sel.get()) return
def rc( selection = "all" ): """ tube coloring for large RNA comparisons """ cmd.bg_color( "white" ) cmd.hide( 'everything',selection ) cmd.color( 'red','resn rG+G+DG and '+selection ) cmd.color( 'forest','resn rC+C+DC and '+selection) cmd.color( 'orange','resn rA+A+DA and '+selection) cmd.color( 'blue','resn rU+U+DT+BRU and '+selection) 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: #print x cmd.show( "cartoon", selection ) cmd.spectrum( "resi", "rainbow", selection+" and backbone" ) cmd.cartoon( "tube", "backbone and "+selection ) cmd.set( "cartoon_ring_mode", 0 ) cmd.set( "cartoon_ring_transparency", 0.0 ) cmd.set( "cartoon_tube_radius", 1.0 ) cmd.color( 'red','resn rG+G and name n1+c6+o6+c5+c4+n7+c8+n9+n3+c2+n1+n2 and '+selection) cmd.color( 'forest','resn rC+C and name n1+c2+o2+n3+c4+n4+c5+c6 and '+selection) cmd.color( 'orange','resn rA+A and name n1+c6+n6+c5+n7+c8+n9+c4+n3+c2 and '+selection) cmd.color( 'blue','resn rU+U and name n3+c4+o4+c5+c6+n1+c2+o2 and '+selection) cmd.delete('backbone')
def testLabelPositionZ(self, use_shaders, ray): ''' Test label z position for regular labels ''' if not ray and invocation.options.no_gui: self.skipTest('no gui') cmd.set('use_shaders', use_shaders) cmd.viewport(200, 200) cmd.pseudoatom('m1', vdw=10, label='X') cmd.zoom(buffer=12) cmd.show('spheres') cmd.color('blue') cmd.set('label_color', 'red') cmd.set('label_size', 20) cmd.set('label_font_id', 7) # bold self.ambientOnly() # label outside of sphere cmd.set('label_position', [0, 0, 11.1]) img = self.get_imagearray(ray=ray) self.assertImageHasColor('blue', img) self.assertImageHasColor('red', img, delta=20) # label inside of sphere cmd.set('label_position', [0, 0, 10.5]) img = self.get_imagearray(ray=ray) self.assertImageHasColor('blue', img) self.assertImageHasNotColor('red', img, delta=20)
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" )
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 )
def loadTag( tag , directory , name=None, native=None, increment=True, extra="" ): global POINTER,LOADLIST if name is None: name = tag if tag.endswith("_packing.pdb"): if increment: LOADLIST.append( (tag,directory,name,native) ) POINTER = len(LOADLIST)-1 print POINTER if native is None: cmd.do('loadPackingPDB '+directory+'/'+tag+","+name ) else: cmd.do('loadPackingPDB '+directory+'/'+tag+","+name+','+native) elif tag.endswith('.pdb'): if directory is None: cmd.load(tag) else: cmd.load(path.join(directory, tag)) else: pattern = directory+'/'+tag+'*.pdb' print pattern g = glob.glob( pattern ) #print g cmd.load( g[0], name ) cmd.show('cartoon') print "DO:",extra #TODO FIXME cmd.do(extra)
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
def testFun(filePath): import networkx as nx cmd.delete("all") cmd.fetch("1C3W") cmd.hide("lines", "all") cmd.show("cartoon", "1C3W") cmd.color("green", "all") #------------------------------ cmd.color("yellow", "resi 194 and resn GLU") #------------------------------- cmd.show("sticks", "resi 194 and resn GLU") highlightRes("GLUA0194", color="yellow") highlightRes("GLUA0204", color="yellow") g = loadHbTxt(filePath) allNodes = nx.node_connected_component(g, "GLUA0194") #=========================================================================== # print allNodes #=========================================================================== accRes = {} for line in open("/Users/xzhu/sibyl/BR/1C3W/hydro/def/raw/acc.res"): fields = line.split() resString = fields[1] + fields[2] acc = float(fields[4]) accRes[resString] = acc colorThreshold = 0.02 for eachResidue in accRes.keys(): if accRes[eachResidue] > colorThreshold: if eachResidue in allNodes: print eachResidue highlightRes(eachResidue)
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()
def initial_representations(): """Configure the initial representations for the protein and the ligand""" cmd.hide('everything', 'all') cmd.show('cartoon', 'all') cmd.select('ligand', 'resn NFT') cmd.deselect() cmd.show("sticks", "ligand")
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()
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')
def RefreshDisplay(self): try: # Display the atoms spheres cmd.show('spheres', self.LigDisplay) cmd.refresh() cmd.alter(self.LigDisplay,'vdw=0.25') cmd.rebuild(self.LigDisplay) cmd.refresh() util.cbag(self.LigDisplay) cmd.refresh() if self.AnchorAtom != -1: AtomSel = self.LigDisplay + ' & id ' + str(self.AnchorAtom) cmd.color('white',AtomSel) cmd.refresh() cmd.alter(AtomSel ,'vdw=0.30') cmd.rebuild(AtomSel) cmd.refresh() except: self.ErrorCode = 1 return self.ErrorCode
def testShow(self): cmd.fragment('ala') self.assertEqual(cmd.count_atoms('rep sticks'), 0) cmd.show('sticks') self.assertEqual(cmd.count_atoms('rep sticks'), 10) cmd.hide('lines', 'not elem C') self.assertEqual(cmd.count_atoms('rep lines'), 3)
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!")
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
def ino(): """Sphare and yellow inorganic, such us Mg. .. image:: ../../rna_tools/utils/PyMOL4RNA/doc/ion.png""" cmd.show("spheres", "inorganic") cmd.set('sphere_scale', '0.25', '(all)') cmd.color("yellow", "inorganic")
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
def hideUnoccupiedWater(fileName, threshold=-1.0): cmd.hide("lines") cmd.show("cartoon") cmd.set("cartoon_transparency", 0.8) keyResidues = ["ASPA0085", "ARGA0082", "GLUA0194"] for eachRes in keyResidues: showResidue(eachRes) cmd.set("sphere_scale", 0.4) keptWaters = [] for eachLine in open(fileName): if not eachLine.startswith("HOHDM"): continue fields = eachLine.split() confName = fields[0] occ = float(fields[1]) if occ > float(threshold): continue else: keptWaters.append(confName[:3] + confName[5:10]) print "number of kept waters: ", len(keptWaters) cmd.hide("everything", "resn HOH") for eachWat in keptWaters: chainId = eachWat[3] seq = int(eachWat[4:]) cmd.show("spheres", "resn HOH and chain " + chainId + " and resi " + str(seq))
def do_library(self): cmd = self.cmd pymol = cmd._pymol suspend_undo = self.cmd.get("suspend_undo") cmd.set("suspend_undo", 1, updates=0) if not ((cmd.count_atoms("(%s) and name N" % src_sele) == 1) and (cmd.count_atoms("(%s) and name C" % src_sele) == 1) and (cmd.count_atoms("(%s) and name O" % src_sele) == 1)): self.clear() return 1 cmd.feedback("push") cmd.feedback("disable", "selector", "everythin") cmd.feedback("disable", "editor", "actions") self.prompt = ['Loading rotamers...'] self.bump_scores = [] state_best = 0 pymol.stored.name = 'residue' cmd.iterate("first (%s)" % src_sele, 'stored.name=model+"/"+segi+"/"+chain+"/"+resn+"`"+resi') self.res_text = pymol.stored.name cmd.select("_seeker_hilight", src_sele) auto_zoom = cmd.get_setting_text('auto_zoom') cmd.set('auto_zoom', "0", quiet=1) cmd.frame(0) cmd.delete(frag_name) if self.auto_center: cmd.center(src_sele, animate=-1) self.lib_mode = self.mode if self.lib_mode == "current": pymol.stored.resn = "" cmd.iterate("(%s & name CA)" % src_sele, "stored.resn=resn") rot_type = _rot_type_xref.get(pymol.stored.resn, pymol.stored.resn) if (self.c_cap != 'none') or (self.n_cap != 'none') or (self.hyd != 'auto'): self.lib_mode = rot_type # force fragment-based load else: cmd.create(frag_name, src_sele, 1, 1) if self.c_cap == 'open': cmd.remove("%s and name OXT" % frag_name) if self.lib_mode != 'current': rot_type = self.lib_mode frag_type = self.lib_mode if (self.n_cap == 'posi') and (frag_type[0:3] != 'NT_'): if not (cmd.count_atoms( "elem C & !(%s) & (bto. (name N & (%s))) &! resn ACE" % (src_sele, src_sele))): # use N-terminal fragment frag_type = "NT_" + frag_type if (self.c_cap == 'nega') and (frag_type[0:3] != 'CT_'): if not (cmd.count_atoms( "elem N & !(%s) & (bto. (name C & (%s))) & !resn NME+NHH" % (src_sele, src_sele))): # use C-terminal fragment frag_type = "CT_" + frag_type if rot_type[0:3] in ['NT_', 'CT_']: rot_type = rot_type[3:] rot_type = _rot_type_xref.get(rot_type, rot_type) cmd.fragment(frag_type.lower(), frag_name, origin=0) # trim off hydrogens if (self.hyd == 'none'): cmd.remove("(" + frag_name + " and hydro)") elif (self.hyd == 'auto'): if cmd.count_atoms("(" + src_sele + ") and hydro") == 0: cmd.remove("(" + frag_name + " and hydro)") # copy identifying information cmd.alter("?%s & name CA" % src_sele, "stored.identifiers = (segi, chain, resi, ss, color)", space=self.space) cmd.alter("?%s" % frag_name, "(segi, chain, resi, ss) = stored.identifiers[:4]", space=self.space) # move the fragment if ((cmd.count_atoms("(%s & name CB)" % frag_name) == 1) and (cmd.count_atoms("(%s & name CB)" % src_sele) == 1)): cmd.pair_fit( "(%s & name CA)" % frag_name, "(%s & name CA)" % src_sele, "(%s & name CB)" % frag_name, "(%s & name CB)" % src_sele, "(%s & name C)" % frag_name, "(%s & name C)" % src_sele, "(%s & name N)" % frag_name, "(%s & name N)" % src_sele) else: cmd.pair_fit("(%s & name CA)" % frag_name, "(%s & name CA)" % src_sele, "(%s & name C)" % frag_name, "(%s & name C)" % src_sele, "(%s & name N)" % frag_name, "(%s & name N)" % src_sele) # fix the carbonyl position... cmd.iterate_state(1, "(%s & name O)" % src_sele, "stored.list=[x,y,z]") cmd.alter_state(1, "(%s & name O)" % frag_name, "(x,y,z)=stored.list") if cmd.count_atoms("(%s & name OXT)" % src_sele): cmd.iterate_state(1, "(%s & name OXT)" % src_sele, "stored.list=[x,y,z]") cmd.alter_state(1, "(%s & name OXT)" % frag_name, "(x,y,z)=stored.list") elif cmd.count_atoms("(%s & name OXT)" % frag_name): # place OXT if no template exists angle = cmd.get_dihedral("(%s & name N)" % frag_name, "(%s & name CA)" % frag_name, "(%s & name C)" % frag_name, "(%s & name O)" % frag_name) cmd.protect("(%s & name O)" % frag_name) cmd.set_dihedral("(%s & name N)" % frag_name, "(%s & name CA)" % frag_name, "(%s & name C)" % frag_name, "(%s & name OXT)" % frag_name, 180.0 + angle) cmd.deprotect(frag_name) # fix the hydrogen position (if any) if cmd.count_atoms("(hydro and bound_to (name N & (%s)))" % frag_name) == 1: if cmd.count_atoms("(hydro and bound_to (name N & (%s)))" % src_sele) == 1: cmd.iterate_state( 1, "(hydro and bound_to (name N & (%s)))" % src_sele, "stored.list=[x,y,z]") cmd.alter_state( 1, "(hydro and bound_to (name N & (%s)))" % frag_name, "(x,y,z)=stored.list") elif cmd.select( tmp_sele1, "(name C & bound_to (%s and elem N))" % src_sele) == 1: # position hydro based on location of the carbonyl angle = cmd.get_dihedral("(%s & name C)" % frag_name, "(%s & name CA)" % frag_name, "(%s & name N)" % frag_name, tmp_sele1) cmd.set_dihedral("(%s & name C)" % frag_name, "(%s & name CA)" % frag_name, "(%s & name N)" % frag_name, "(%s & name H)" % frag_name, 180.0 + angle) cmd.delete(tmp_sele1) # add c-cap (if appropriate) if self.c_cap in ['amin', 'nmet']: if not cmd.count_atoms( "elem N & !(%s) & (bto. (name C & (%s))) & !resn NME+NHH" % (src_sele, src_sele)): if cmd.count_atoms("name C & (%s)" % (frag_name)) == 1: if self.c_cap == 'amin': editor.attach_amino_acid( "name C & (%s)" % (frag_name), 'nhh') elif self.c_cap == 'nmet': editor.attach_amino_acid( "name C & (%s)" % (frag_name), 'nme') if cmd.count_atoms( "hydro & bound_to (name N & bound_to (name C & (%s)))" % frag_name): cmd.h_fix("name N & bound_to (name C & (%s))" % frag_name) # trim hydrogens if (self.hyd == 'none'): cmd.remove("(" + frag_name + " and hydro)") elif (self.hyd == 'auto'): if cmd.count_atoms("(" + src_sele + ") and hydro") == 0: cmd.remove("(" + frag_name + " and hydro)") # add n-cap (if appropriate) if self.n_cap in ['acet']: if not cmd.count_atoms( "elem C & !(%s) & (bto. (name N & (%s))) & !resn ACE " % (src_sele, src_sele)): if cmd.count_atoms("name N & (%s)" % (frag_name)) == 1: if self.n_cap == 'acet': editor.attach_amino_acid( "name N & (%s)" % (frag_name), 'ace') if cmd.count_atoms( "hydro & bound_to (name N & bound_to (name C & (%s)))" % frag_name): cmd.h_fix("name N & (%s)" % frag_name) # trim hydrogens if (self.hyd == 'none'): cmd.remove("(" + frag_name + " and hydro)") elif (self.hyd == 'auto'): if cmd.count_atoms("(" + src_sele + ") and hydro") == 0: cmd.remove("(" + frag_name + " and hydro)") cartoon = (cmd.count_atoms("(%s & name CA & rep cartoon)" % src_sele) > 0) sticks = (cmd.count_atoms("(%s & name CA & rep sticks)" % src_sele) > 0) cmd.delete(obj_name) key = rot_type lib = None if self.dep == 'dep': try: result = cmd.phi_psi("%s" % src_sele) if len(result) == 1: (phi, psi) = list(result.values())[0] (phi, psi) = (int(10 * round(phi / 10)), int(10 * (round(psi / 10)))) key = (rot_type, phi, psi) if key not in self.dep_library: (phi, psi) = (int(20 * round(phi / 20)), int(20 * (round(psi / 20)))) key = (rot_type, phi, psi) if key not in self.dep_library: (phi, psi) = (int(60 * round(phi / 60)), int(60 * (round(psi / 60)))) key = (rot_type, phi, psi) lib = self.dep_library.get(key, None) except: pass if lib == None: key = rot_type lib = self.ind_library.get(key, None) if (lib != None) and self.dep == 'dep': print( ' Mutagenesis: no phi/psi, using backbone-independent rotamers.' ) if lib != None: state = 1 for a in lib: cmd.create(obj_name, frag_name, 1, state) if state == 1: cmd.select(mut_sele, "(byres (%s like %s))" % (obj_name, src_sele)) if rot_type == 'PRO': cmd.unbond("(%s & name N)" % mut_sele, "(%s & name CD)" % mut_sele) for b in a.keys(): if b != 'FREQ': cmd.set_dihedral("(%s & n;%s)" % (mut_sele, b[0]), "(%s & n;%s)" % (mut_sele, b[1]), "(%s & n;%s)" % (mut_sele, b[2]), "(%s & n;%s)" % (mut_sele, b[3]), a[b], state=state) else: cmd.set_title(obj_name, state, "%1.1f%%" % (a[b] * 100)) if rot_type == 'PRO': cmd.bond("(%s & name N)" % mut_sele, "(%s & name CD)" % mut_sele) state = state + 1 cmd.delete(frag_name) print(" Mutagenesis: %d rotamers loaded." % len(lib)) if self.bump_check: cmd.delete(bump_name) cmd.create( bump_name, "(((byobj %s) within 6 of (%s and not name N+C+CA+O+H+HA)) and (not (%s)))|(%s)" % (src_sele, mut_sele, src_sele, mut_sele), singletons=1) cmd.color("gray50", bump_name + " and elem C") cmd.set("seq_view", 0, bump_name, quiet=1) cmd.hide("everything", bump_name) if ((cmd.select( tmp_sele1, "(name N & (%s in (neighbor %s)))" % (bump_name, src_sele)) == 1) and (cmd.select( tmp_sele2, "(name C & (%s in %s))" % (bump_name, mut_sele)) == 1)): cmd.bond(tmp_sele1, tmp_sele2) if ((cmd.select( tmp_sele1, "(name C & (%s in (neighbor %s)))" % (bump_name, src_sele)) == 1) and (cmd.select( tmp_sele2, "(name N & (%s in %s))" % (bump_name, mut_sele)) == 1)): cmd.bond(tmp_sele1, tmp_sele2) cmd.delete(tmp_sele1) cmd.delete(tmp_sele2) cmd.protect( "%s and not (%s in (%s and not name N+C+CA+O+H+HA))" % (bump_name, bump_name, mut_sele)) cmd.sculpt_activate(bump_name) cmd.show("cgo", bump_name) # draw the bumps cmd.set("sculpt_vdw_vis_mode", 1, bump_name) state = 1 score_best = 1e6 for a in lib: score = cmd.sculpt_iterate(bump_name, state, 1) self.bump_scores.append(score) if score < score_best: state_best = state score_best = score state = state + 1 cmd.delete(mut_sele) else: cmd.create(obj_name, frag_name, 1, 1) print(" Mutagenesis: no rotamers found in library.") cmd.set("seq_view", 0, obj_name, quiet=1) pymol.util.cbaw(obj_name) cmd.hide("(" + obj_name + ")") cmd.show(self.rep, obj_name) cmd.show('lines', obj_name) #neighbor always show lines if cartoon: cmd.show("cartoon", obj_name) if sticks: cmd.show("sticks", obj_name) cmd.set('auto_zoom', auto_zoom, quiet=1) cmd.delete(frag_name) cmd.frame(state_best) cmd.unpick() cmd.set("suspend_undo", suspend_undo, updates=0) cmd.feedback("pop")
cmd.select("Astrand9", "resi 249-261 & chain A ") cmd.color("red", "Astrand9") cmd.select("Astrand10", "resi 271-291 & chain A ") cmd.color("orange", "Astrand10") cmd.select("Astrand11", "resi 300-319 & chain A ") cmd.color("yellow", "Astrand11") cmd.select("Astrand12", "resi 323-334 & chain A ") cmd.color("green", "Astrand12") cmd.select("Astrand13", "resi 377-388 & chain A ") cmd.color("cyan", "Astrand13") cmd.select("Astrand14", "resi 391-403 & chain A ") cmd.color("blue", "Astrand14") cmd.select("Astrand15", "resi 424-437 & chain A ") cmd.color("purple", "Astrand15") cmd.select("Astrand16", "resi 457-466 & chain A ") cmd.color("red", "Astrand16") cmd.select("Astrand17", "resi 479-490 & chain A ") cmd.color("orange", "Astrand17") cmd.select("barrel", "Astrand*") cmd.show("cartoon", "barrel") cmd.zoom("barrel")
xyz3 = cpv.add(cpv.scale(normal, hlength), xyz2) obj = [cgo.CYLINDER] + xyz1 + xyz3 + [radius] + color1 + color2 + [ cgo.CONE ] + xyz3 + xyz2 + [hradius, 0.0] + color2 + color2 + [1.0, 0.0] return obj dirpath = tempfile.mkdtemp() zip_dir = 'out.zip' with zipfile.ZipFile(zip_dir) as hs_zip: hs_zip.extractall(dirpath) cmd.load(join(dirpath, "protein.pdb"), "protein") cmd.show("cartoon", "protein") if dirpath: f = join(dirpath, "label_threshold_10.mol2") else: f = "label_threshold_10.mol2" cmd.load(f, 'label_threshold_10') cmd.hide('everything', 'label_threshold_10') cmd.label("label_threshold_10", "name") cmd.set("label_font_id", 7) cmd.set("label_size", -0.4) if dirpath: f = join(dirpath, "label_threshold_14.mol2") else:
cmd.set('ray_opaque_background', 'off') cmd.set('depth_cue', 'off') ### Modify here url = 'https://files.rcsb.org/download/6F5O.pdb' cmd.load(url, 'orig') cmd.select('origPA', 'chain A') cmd.select('origPB1', 'chain B') cmd.select('origPB2', 'chain C') cmd.load('S009PB2_{0}.pdb'.format(structure, 'S009')) cmd.super('S009', 'orig') cmd.hide('everything') cmd.show('cartoon') # cmd.show('surface') for c in ['origPA', 'origPB1', 'S009']: cmd.show('surface', '{0}'.format(c)) cmd.remove('origPB2') cmd.color('palegreen', 'origPA') cmd.color('palecyan', 'origPB1') cmd.color('white', 'S009') cmd.orient() ### To get PB2 only cmd.hide('everything', 'orig') cmd.hide('surface', 'S009') # cmd.show('cartoon', 'orig') cmd.show('surface', 'S009')
def elbow_angle(obj, light='L', heavy='H', limit_l=107, limit_h=113, draw=0): """ DESCRIPTION Calculates the integer elbow angle of an antibody Fab complex and optionally draws a graphical representation of the vectors used to determine the angle. ARGUMENTS obj = string: object light/heavy = strings: chain ID of light and heavy chains, respectively limit_l/limit_h = integers: residue numbers of the last residue in the light and heavy chain variable domains, respectively draw = boolean: Choose whether or not to draw the angle visualization REQUIRES: com.py, transformations.py, numpy (see above) """ # store current view orig_view = cmd.get_view() limit_l = int(limit_l) limit_h = int(limit_h) draw = int(draw) # for temp object names tmp_prefix = "tmp_elbow_" prefix = tmp_prefix + obj + '_' # names vl = prefix + 'VL' vh = prefix + 'VH' cl = prefix + 'CL' ch = prefix + 'CH' # selections vl_sel = 'polymer and %s and chain %s and resi 1-%i' % (obj, light, limit_l) vh_sel = 'polymer and %s and chain %s and resi 1-%i' % (obj, heavy, limit_h) cl_sel = 'polymer and %s and chain %s and not resi 1-%i' % (obj, light, limit_l) ch_sel = 'polymer and %s and chain %s and not resi 1-%i' % (obj, heavy, limit_h) v_sel = '((' + vl_sel + ') or (' + vh_sel + '))' c_sel = '((' + cl_sel + ') or (' + ch_sel + '))' # create temp objects cmd.create(vl, vl_sel) cmd.create(vh, vh_sel) cmd.create(cl, cl_sel) cmd.create(ch, ch_sel) # superimpose vl onto vh, calculate axis and angle Rv = calc_super_matrix(vl, vh) angle_v, direction_v, point_v = transformations.rotation_from_matrix(Rv) # superimpose cl onto ch, calculate axis and angle Rc = calc_super_matrix(cl, ch) angle_c, direction_c, point_c = transformations.rotation_from_matrix(Rc) # delete temporary objects cmd.delete(vl) cmd.delete(vh) cmd.delete(cl) cmd.delete(ch) # if dot product is positive, angle is acute if (numpy.dot(direction_v, direction_c) > 0): direction_c = direction_c * -1 # ensure angle is > 90 (need to standardize this) # TODO: make both directions point away from the elbow axis. elbow = int(numpy.degrees(numpy.arccos(numpy.dot(direction_v, direction_c)))) # while (elbow < 90): # elbow = 180 - elbow # limit to physically reasonable range # compare the direction_v and direction_c axes to the vector defined by # the C-alpha atoms of limit_l and limit_h of the original fab hinge_l_sel = "%s//%s/%s/CA" % (obj, light, limit_l) hinge_h_sel = "%s//%s/%s/CA" % (obj, heavy, limit_h) hinge_l = cmd.get_atom_coords(hinge_l_sel) hinge_h = cmd.get_atom_coords(hinge_h_sel) hinge_vec = numpy.array(hinge_h) - numpy.array(hinge_l) test = numpy.dot(hinge_vec, numpy.cross(direction_v, direction_c)) if (test > 0): elbow = 360 - elbow print(" Elbow angle: %i degrees" % elbow) if (draw == 1): # there is probably a more elegant way to do this, but # it works so I'm not going to mess with it for now pre = obj + '_elbow_' # draw hinge vector cmd.pseudoatom(pre + "hinge_l", pos=hinge_l) cmd.pseudoatom(pre + "hinge_h", pos=hinge_h) cmd.distance(pre + "hinge_vec", pre + "hinge_l", pre + "hinge_h") cmd.set("dash_gap", 0) # draw the variable domain axis com_v = COM(v_sel) start_v = [a - 10 * b for a, b in zip(com_v, direction_v)] end_v = [a + 10 * b for a, b in zip(com_v, direction_v)] cmd.pseudoatom(pre + "start_v", pos=start_v) cmd.pseudoatom(pre + "end_v", pos=end_v) cmd.distance(pre + "v_vec", pre + "start_v", pre + "end_v") # draw the constant domain axis com_c = COM(c_sel) start_c = [a - 10 * b for a, b in zip(com_c, direction_c)] end_c = [a + 10 * b for a, b in zip(com_c, direction_c)] cmd.pseudoatom(pre + "start_c", pos=start_c) cmd.pseudoatom(pre + "end_c", pos=end_c) cmd.distance(pre + "c_vec", pre + "start_c", pre + "end_c") # customize appearance cmd.hide("labels", pre + "hinge_vec") cmd.hide("labels", pre + "v_vec") cmd.hide("labels", pre + "c_vec") cmd.color("green", pre + "hinge_l") cmd.color("red", pre + "hinge_h") cmd.color("black", pre + "hinge_vec") cmd.color("black", pre + "start_v") cmd.color("black", pre + "end_v") cmd.color("black", pre + "v_vec") cmd.color("black", pre + "start_c") cmd.color("black", pre + "end_c") cmd.color("black", pre + "c_vec") # draw spheres cmd.show("spheres", pre + "hinge_l or " + pre + "hinge_h") cmd.show("spheres", pre + "start_v or " + pre + "start_c") cmd.show("spheres", pre + "end_v or " + pre + "end_c") cmd.set("sphere_scale", 2) cmd.set("dash_gap", 0, pre + "hinge_vec") cmd.set("dash_width", 5) cmd.set("dash_radius", 0.3) # group drawing objects cmd.group(pre, pre + "*") # restore original view cmd.set_view(orig_view) return 0
if me == 0: import pymol pymol.finish_launching() from dump import dump from pdbfile import pdbfile from pymol import cmd as pm d = dump("tmp.dump", 0) p = pdbfile(d) d.next() d.unscale() p.single(ntimestep) pm.load("tmp.pdb") pm.show("spheres", "tmp") # run nfreq steps at a time w/out pre/post, read dump snapshot, display it while ntimestep < nsteps: lmp.command("run %d pre no post no" % nfreq) ntimestep += nfreq if me == 0: d.next() d.unscale() p.single(ntimestep) pm.load("tmp.pdb") pm.forward() lmp.command("run 0 pre no post yes")
print(resi_list_neut_part) # stabilizing part resi_list_stab_part = '' for item in range(len(res_pos_stab)): resi_list_stab_part += str(res_pos_stab[item]) + '+' resi_list_stab_part = resi_list_stab_part[:-1] # remove extra + print(resi_list_stab_part) cmd.load(pdb_path, pdb_name) cmd.bg_color('white') # cmd.zoom() # cmd.orient() cmd.hide('everything', pdb_name) cmd.show('cartoon', pdb_name) cmd.color('grey90', pdb_name) try: cmd.create('HCM_part', 'resi ' + resi_list_HCM_part) cmd.select('HCM_ca', 'bycalpha HCM_part') cmd.show('sphere', 'HCM_ca') cmd.color('greencyan', 'HCM_part') except CmdException: print('no HCM mutation') try: cmd.create('DCM_part', 'resi ' + resi_list_DCM_part) cmd.select('DCM_ca', 'bycalpha DCM_part') cmd.show('sphere', 'DCM_ca') cmd.color('chartreuse', 'DCM_part')
def visualize_in_pymol(plcomplex): """Visualizes the protein-ligand pliprofiler at one site in PyMOL.""" vis = PyMOLVisualizer(plcomplex) ##################### # Set everything up # ##################### pdbid = plcomplex.pdbid lig_members = plcomplex.lig_members chain = plcomplex.chain if config.PEPTIDES: vis.ligname = 'PeptideChain%s' % plcomplex.chain if config.INTRA is not None: vis.ligname = 'Intra%s' % plcomplex.chain ligname = vis.ligname hetid = plcomplex.hetid metal_ids = plcomplex.metal_ids metal_ids_str = '+'.join([str(i) for i in metal_ids]) ######################## # Basic visualizations # ######################## start_pymol(run=True, options='-pcq', quiet=not config.VERBOSE and not config.SILENT) vis.set_initial_representations() cmd.load(plcomplex.sourcefile) current_name = cmd.get_object_list(selection='(all)')[0] logger.debug( f'setting current_name to {current_name} and pdbid to {pdbid}') cmd.set_name(current_name, pdbid) cmd.hide('everything', 'all') if config.PEPTIDES: cmd.select(ligname, 'chain %s and not resn HOH' % plcomplex.chain) else: cmd.select( ligname, 'resn %s and chain %s and resi %s*' % (hetid, chain, plcomplex.position)) logger.debug( f'selecting ligand for PDBID {pdbid} and ligand name {ligname}') logger.debug( f'resn {hetid} and chain {chain} and resi {plcomplex.position}') # Visualize and color metal ions if there are any if not len(metal_ids) == 0: vis.select_by_ids(ligname, metal_ids, selection_exists=True) cmd.show('spheres', 'id %s and %s' % (metal_ids_str, pdbid)) # Additionally, select all members of composite ligands if len(lig_members) > 1: for member in lig_members: resid, chain, resnr = member[0], member[1], str(member[2]) cmd.select( ligname, '%s or (resn %s and chain %s and resi %s)' % (ligname, resid, chain, resnr)) cmd.show('sticks', ligname) cmd.color('myblue') cmd.color('myorange', ligname) cmd.util.cnc('all') if not len(metal_ids) == 0: cmd.color('hotpink', 'id %s' % metal_ids_str) cmd.hide('sticks', 'id %s' % metal_ids_str) cmd.set('sphere_scale', 0.3, ligname) cmd.deselect() vis.make_initial_selections() vis.show_hydrophobic() # Hydrophobic Contacts vis.show_hbonds() # Hydrogen Bonds vis.show_halogen() # Halogen Bonds vis.show_stacking() # pi-Stacking Interactions vis.show_cationpi() # pi-Cation Interactions vis.show_sbridges() # Salt Bridges vis.show_wbridges() # Water Bridges vis.show_metal() # Metal Coordination vis.refinements() vis.zoom_to_ligand() vis.selections_cleanup() vis.selections_group() vis.additional_cleanup() if config.DNARECEPTOR: # Rename Cartoon selection to Line selection and change repr. cmd.set_name('%sCartoon' % plcomplex.pdbid, '%sLines' % plcomplex.pdbid) cmd.hide('cartoon', '%sLines' % plcomplex.pdbid) cmd.show('lines', '%sLines' % plcomplex.pdbid) if config.PEPTIDES: filename = "%s_PeptideChain%s" % (pdbid.upper(), plcomplex.chain) if config.PYMOL: vis.save_session(config.OUTPATH, override=filename) elif config.INTRA is not None: filename = "%s_IntraChain%s" % (pdbid.upper(), plcomplex.chain) if config.PYMOL: vis.save_session(config.OUTPATH, override=filename) else: filename = '%s_%s' % (pdbid.upper(), "_".join( [hetid, plcomplex.chain, plcomplex.position])) if config.PYMOL: vis.save_session(config.OUTPATH) if config.PICS: vis.save_picture(config.OUTPATH, filename)
# spawn chempy_model02.py, global # # Then you have access to the "cont" variable, and can stop the loop by # simply setting it: # # cont = False # cont = True # first we need a model cmd.load("$PYMOL_PATH/test/dat/pept.pdb", "demo") # let's dress it up a little bit cmd.show("sticks", "demo") cmd.show("spheres", "resi 10") cmd.color("yellow", "resi 5 and element c") # turn off some of the chatter about reloading the object... cmd.feedback("disable", "executive", "actions") # now loop, updating the coordinates and reloading the model into # state 1 of the "demo" object m = cmd.get_model() while cont: time.sleep(0.05)
def modevectors(first_obj_frame, last_obj_frame, first_state=1, last_state=1, outname="modevectors", head=1.0, tail=0.3, head_length=1.5, headrgb="1.0,1.0,1.0", tailrgb="1.0,1.0,1.0", cutoff=4.0, skip=0, cut=0.5, atom="CA", stat="show", factor=1.0, notail=0): """ Authors Sean Law & Srinivasa Michigan State University slaw_(at)_msu_dot_edu Editor Sacha Yee USAGE While in PyMOL Parameter Preset Type Description first_obj_frame Undefined String Object name of the first structure. The mode vector will propagate from this structure. Defined by user. last_obj_frame Undefined String Object name of the last structure. The mode vector (arrow head) will end at this structure. Defined by user. first_state 1 Integer Defines state of first object last_state 1 Integer Defines state of last object outname modevectors String Name of object to store mode vectors in. head 1.0 Float Radius for the circular base of the arrow head (cone) tail 0.3 Float Radius for the cylinder of the arrow tail (cylinder) head_length 1.5 Float Length of the arrow head (from the base of the cone to the tip of cone) head_rgb 1.0,1.0,1.0 String RGB colour for the arrow head. tail_rgb 1.0,1.0,1.0 String RGB colour for the arrow tail. cutoff 4.0 Float Skips mode vectors that do not meet the cutoff distance (in Angstroms). skip 0 Integer Denotes how many atoms to skip. No arrows will be created for skipped atoms. cut 0.0 Float Truncates all arrow tail lengths (without disturbing the arrow head) (in Angstroms). atom CA String Designates the atom to derive mode vectors from. stat show String Keeps track and prints statistics (total modevectors, skipped, cutoff). factor 1.0 Float Multiplies each mode vector length by a specified factor. Values between 0 and 1 will decrease the relative mode vector length. Values greater than 1 will increase the relative mode vector length. notail 0 Integer Hides tails and only uses cones (porcupine plot) """ framefirst = cmd.get_model(first_obj_frame, first_state) framelast = cmd.get_model(last_obj_frame, last_state) objectname = outname factor = float(factor) arrow_head_radius = float(head) arrow_tail_radius = float(tail) arrow_head_length = float(head_length) cutoff = float(cutoff) skip = int(skip) cut = float(cut) atomtype = atom.strip('"[]()') objectname = objectname.strip('"[]()') headrgb = headrgb.strip('" []()') tailrgb = tailrgb.strip('" []()') hr, hg, hb = list(map(float, headrgb.split(','))) tr, tg, tb = list(map(float, tailrgb.split(','))) version = cmd.get_version()[1] arrow = [] arrowhead = [] arrowtail = [] x1 = [] y1 = [] z1 = [] x2 = [] y2 = [] z2 = [] exit_flag = False ############################################################## # # # Define an object called "tail" and store the tail and a # # circular base of the triangle in this object. # # # ############################################################## skipcount = 0 skipcounter = 0 keepcounter = 0 atom_lookup = {} for atom in framefirst.atom: if atom.name == atomtype: if skipcount == skip: x1.append(atom.coord[0]) y1.append(atom.coord[1]) z1.append(atom.coord[2]) ########################################## # # # Set atom_lookup for a specific atom # # equal to ONE for the first input set. # # This dictionary will be used as a # # reference for the second set. # # # ########################################## current_atom = "CHAIN " + atom.chain + " RESID "\ + atom.resi + " RESTYPE "\ + atom.resn +\ " ATMNUM " + str(atom.index) # print current_atom atom_lookup['current_atom'] = 1 skipcount = 0 keepcounter += 1 else: # print skipcount skipcount += 1 skipcounter += 1 skipcount = 0 for atom in framelast.atom: if atom.name == atomtype: if skipcount == skip: x2.append(atom.coord[0]) y2.append(atom.coord[1]) z2.append(atom.coord[2]) ######################################### # # # Get atom information from second set # # and compare with first set. All # # atoms from this second set MUST be # # found in the first set! Otherwise, # # the script will exit with an error # # since modevectors can only be created # # by calculating values from identical # # sources. # # # ######################################### current_atom = "CHAIN " + atom.chain + " RESID "\ + atom.resi + " RESTYPE "\ + atom.resn +\ " ATMNUM " + str(atom.index) # print current_atom if 'current_atom' not in atom_lookup: print("\nError: " + current_atom + " from \""\ + last_obj_frame +\ " \"is not found in \"" + first_obj_frame + "\".") print("\nPlease check your input and/or selections and try again.") exit_flag = True break skipcount = 0 else: skipcount += 1 if exit_flag == 1: ########################################### # # # Exit script because an atom cannot be # # found in both input files # # # ########################################### return cutoff_counter = 0 # Track number of atoms failing to meet the cutoff ################################################### # # # Check that the two selections/PDB files contain # # the same number of atoms. # # # ################################################### if len(x2) != len(x1): print("\nError: \"" + first_obj_frame +\ "\" and \"" + last_obj_frame +\ "\" contain different number of residue/atoms.") print("\nPlease check your input and/or selections and try again.") return else: # Continue with representing modevectors! ######################################### # # # Delete old selection or object if it # # exists so that it can be overwritten # # # ######################################### save_view = cmd.get_view(output=1, quiet=1) cmd.delete(objectname) cmd.hide(representation="everything", selection=first_obj_frame) cmd.hide(representation="everything", selection=last_obj_frame) ################################################### # # # Begin drawing arrow tails # # # ################################################### arrowtail = [] for mv in range(len(x1)): vectorx = x2[mv] - x1[mv] vectory = y2[mv] - y1[mv] vectorz = z2[mv] - z1[mv] length = sqrt(vectorx ** 2 + vectory ** 2 + vectorz ** 2) if length < cutoff: cutoff_counter += 1 continue t = 1.0 - (cut / length) x2[mv] = x1[mv] + factor * t * vectorx y2[mv] = y1[mv] + factor * t * vectory z2[mv] = z1[mv] + factor * t * vectorz vectorx = x2[mv] - x1[mv] vectory = y2[mv] - y1[mv] vectorz = z2[mv] - z1[mv] length = sqrt(vectorx ** 2 + vectory ** 2 + vectorz ** 2) d = arrow_head_length # Distance from arrow tip to arrow base t = 1.0 - (d / length) if notail: t = 0 tail = [ # Tail of cylinder CYLINDER, x1[mv], y1[mv], z1[mv]\ , x1[mv] + (t + 0.01) * vectorx, y1[mv] + (t + 0.01) * vectory, z1[mv] + (t + 0.01) * vectorz\ , arrow_tail_radius, tr, tg, tb, tr, tg, tb # Radius and RGB for each cylinder tail ] if notail == 0: arrow.extend(tail) x = x1[mv] + t * vectorx y = y1[mv] + t * vectory z = z1[mv] + t * vectorz dx = x2[mv] - x dy = y2[mv] - y dz = z2[mv] - z seg = d / 100 intfactor = int(factor) if version < 1.1: # Version >= 1.1 has cone primitive for i in range(100, 0, -1): # i=100 is tip of cone print(i) t1 = seg * i t2 = seg * (i + 1) radius = arrow_head_radius * (1.0 - i / (100.0)) # Radius of each disc that forms cone head = [ CYLINDER, x + t2 * dx, y + t2 * dy, z + t2 * dz\ , x + t1 * dx, y + t1 * dy, z + t1 * dz\ , radius, hr, hg, hb, hr, hg, hb # Radius and RGB for slice of arrow head ] arrow.extend(head) else: head = [ CONE, x, y, z, x + d * dx, y + d * dy, z + d * dz, arrow_head_radius, 0.0, hr, hg, hb, hr, hg, hb, 1.0, 1.0] arrow.extend(head) ############################################################## # # # Load the entire object into PyMOL # # # # Print statistics if requested by user # # # ############################################################## if stat == "show": natoms = skipcounter + keepcounter print("\nTotal number of atoms = " + str(natoms)) print("Atoms skipped = " + str(skipcounter)) if keepcounter - cutoff_counter > 0: print("Atoms counted = " + str(keepcounter - cutoff_counter) + " (see PyMOL object \"" + objectname + "\")") else: print("Atoms counted = " + str(keepcounter - cutoff_counter) + " (Empty CGO object not loaded)") print("Atoms cutoff = " + str(cutoff_counter)) # Note that cutoff occurs AFTER skipping! if keepcounter - cutoff_counter > 0: cmd.delete(objectname) cmd.load_cgo(arrow, objectname) # Ray tracing an empty object will cause a segmentation fault. No arrows = Do not display in PyMOL!!! cmd.show(representation="cartoon", selection=first_obj_frame) if (first_obj_frame != last_obj_frame): cmd.show(representation="cartoon", selection=last_obj_frame) cmd.hide(representation="cartoon", selection=last_obj_frame) cmd.bg_color(color="black") cmd.set_view(save_view) return
def main(d1, d2): ## Make an output folder outdir = 'output_dd/' + input_protein + '+' + d1 + '+' + d2 + '/' #print (outdir) if os.path.isdir(outdir) == False: os.system('mkdir ' + outdir) domains = d1 + '+' + d2 for pdb in dd[domains]: download_pdb_cif(pdb) for coordinates in dd[domains][pdb]: #print (pdb, domains, dd[domains][pdb][coordinates]) chainA = coordinates.split('+')[0].split(':')[0] chainA_res = coordinates.split('+')[0].split(':')[1] chainB = coordinates.split('+')[1].split(':')[0] chainB_res = coordinates.split('+')[1].split(':')[1] cmd.load('pdbs/' + pdb.upper() + '.pdb') cmd.hide('everything') cmd.show('cartoon', 'chain ' + chainA + '+' + chainB) cmd.set('cartoon_fancy_helices', 1) print(pdb, chainA, chainA_res, chainB, chainB_res) try: x = cmd.centerofmass('chain ' + chainA) print('Success chainA') cmd.pseudoatom('chainA_label', pos=x) global nameA nameA = id_to_name[d1] + '(' + d1 + ')' cmd.label('chainA_label', 'nameA') except: print('Failed chainA') try: x = cmd.centerofmass('chain ' + chainB) print('Success chainB') cmd.pseudoatom('chainB_label', pos=x) global nameB nameB = id_to_name[d2] + '(' + d2 + ')' cmd.label('chainB_label', 'nameB') x = cmd.centerofmass('chain ' + chainA + '+' + chainB) cmd.origin(position=x) cmd.center('origin') except: print('Failed chainB') cmd.set('label_size', 7.5) cmd.set('cartoon_fancy_helices', 1) cmd.color('red', 'chain ' + chainA) cmd.color('orange', 'chain ' + chainB) for row in dd[domains][pdb][coordinates]: res1 = row[2] res2 = row[3] #cmd.distance('chain '+chainA+' and i. '+res1+' and n. CB', 'chain '+chainB+' and i. '+res2+' and n. CB') cutoff = 6.5 m = cmd.distance( 'dist', 'chain ' + chainA + ' and i. ' + res1 + ' and n. CB', 'chain ' + chainB + ' and i. ' + res2 + ' and n. CB', cutoff, 0) #m = cmd.get_distance(atom1='chain '+chainA+' and i. '+res1+' and n. CB',atom2='chain '+chainB+' and i. '+res2+' and n. CB',state=0) #print (pdb, m, chainA, res1, chainB, res2) cmd.select('res1', 'chain ' + chainA + ' and resi ' + res1) cmd.select('res2', 'chain ' + chainB + ' and resi ' + res2) if float(m) != 0.0: cmd.show('sticks', 'res1') cmd.show('sticks', 'res2') cmd.color('cyan', 'res1') cmd.color('yellow', 'res2') cmd.save(outdir + pdb + '_' + input_protein + '_' + d1 + '_' + d2 + '_' + coordinates.replace(':', '_').replace( '+', '_').replace('-', '_') + '.pse') cmd.save(outdir + pdb + '_' + input_protein + '_' + d1 + '_' + d2 + '_' + coordinates.replace(':', '_').replace( '+', '_').replace('-', '_') + '.pdb') cmd.delete('all') #break '''
#cmd.bond('id 1', 'id 3') #cmd.bond('id 1', 'id 4') #cmd.set_bond ('stick_color', 'white', 'all', 'all') #cmd.set_bond ('stick_radius', -0.14, 'all', 'all') #cmd.set ('stick_ball', 1) #cmd.set ('stick_ball_ratio', -1) #cmd.set ('stick_ball_color', 'atomic') #cmd.show ('sticks', 'all') #cmd.color('black', 'id 1') #cmd.color('gray', '(name Au*)') cmd.set_bond('stick_radius', 0.1, 'all', 'all') cmd.set('sphere_scale', 0.15, 'all') cmd.show('sticks', 'all') cmd.show('spheres', 'all') cmd.set('stick_ball_color', 'atomic') cmd.color('gray20', '(name C*)') cmd.set('transparency_mode', 1) #w = 0.01 # cylinder width #l = 0.5 # cylinder length #h = 0.15 # cone hight #d = w * 1.618 # cone base diameter w = 0.03 # cylinder width l = 1.65 # cylinder length h = 0.2 # cone hight d = w * 1.618 # cone base diameter
from pymol import cmd cmd.load("./3W32_A.pdb") cmd.set("cartoon_transparency", "0.5") cmd.set("stick_radius", "0.5") cmd.select("nlobe", "resi 1:95") cmd.select("clobe", "resi 96:150+178:277") cmd.select("aloop", "resi 151:177") cmd.select("HRD", "resi 133:135") cmd.select("K745", "resi 43") cmd.select("E762", "resi 60") cmd.hide("lines", "all") cmd.show("cartoon", "all") cmd.show("sticks", "K745") #cmd.color("", "K745") cmd.show("sticks", "E762") #cmd.color("", "K745") cmd.color("limon", "nlobe") cmd.color("bluewhite", "clobe") cmd.color("deepsalmon", "aloop") cmd.set("cartoon_fancy_helices", 1) cmd.set("ray_trace_mode", 1) cmd.set("two_sided_lighting", "on") cmd.set("reflect", 0) cmd.set("ambient", 0.5)
def pairwise_dist(pdbfile, sel1, sel2, max_dist, output="P", sidechain="N", show="N", outfile="./"): """ usage: pairwise_dist sel1, sel2, max_dist, [output=S/P/N, [sidechain=N/Y, [show=Y/N]]] sel1 and sel2 can be any to pre-existing or newly defined selections max_dist: maximum distance in Angstrom between atoms in the two selections --optional settings: output: accepts Screen/Print/None (default N) sidechain: limits (Y) results to sidechain atoms (default N) show: shows (Y) individual distances in pymol menu (default=N) """ print "" cmd.delete("dist*") extra = "" if sidechain == "Y": extra = " and not name c+o+n" #builds models m1 = cmd.get_model(sel2 + " around " + str(max_dist) + " and " + sel1 + extra) m1o = cmd.get_object_list(sel1) m2 = cmd.get_model(sel1 + " around " + str(max_dist) + " and " + sel2 + extra) m2o = cmd.get_object_list(sel2) #defines selections cmd.select("__tsel1a", sel1 + " around " + str(max_dist) + " and " + sel2 + extra) cmd.select("__tsel1", "__tsel1a and " + sel2 + extra) cmd.select("__tsel2a", sel2 + " around " + str(max_dist) + " and " + sel1 + extra) cmd.select("__tsel2", "__tsel2a and " + sel1 + extra) cmd.select("IntAtoms_" + str(max_dist), "__tsel1 or __tsel2") cmd.select("IntRes_" + str(max_dist), "byres IntAtoms_" + str(max_dist)) #controlers-1 if len(m1o) == 0: print "warning, '" + sel1 + extra + "' does not contain any atoms." return if len(m2o) == 0: print "warning, '" + sel2 + extra + "' does not contain any atoms." return #measures distances s = "" counter = 0 for c1 in range(len(m1.atom)): for c2 in range(len(m2.atom)): distance = math.sqrt( sum( map(lambda f: (f[0] - f[1])**2, zip(m1.atom[c1].coord, m2.atom[c2].coord)))) if distance < float(max_dist): s += "%s/%s/%s/%s/%s to %s/%s/%s/%s/%s: %.3f\n" % ( m1o[0], m1.atom[c1].chain, m1.atom[c1].resn, m1.atom[c1].resi, m1.atom[c1].name, m2o[0], m2.atom[c2].chain, m2.atom[c2].resn, m2.atom[c2].resi, m2.atom[c2].name, distance) counter += 1 if show == "Y": cmd.distance( m1o[0] + " and " + m1.atom[c1].chain + "/" + m1.atom[c1].resi + "/" + m1.atom[c1].name, m2o[0] + " and " + m2.atom[c2].chain + "/" + m2.atom[c2].resi + "/" + m2.atom[c2].name) #controler-2 if counter == 0: print "warning, no distances were measured! Check your selections/max_dist value" return #outputs if output == "S": print s if output == "P": filename = os.getcwd( ) + '/interface_analyzer/' + pdbfile + '_distance' + str(max_dist) f = open(filename, 'w') f.write("Number of distances calculated: %s\n" % (counter)) f.write(s) f.close() print "Results saved in _%s" % filename print "Number of distances calculated: %s" % (counter) cmd.hide("lines", "IntRes_*") if show == "Y": cmd.show("lines", "IntRes_" + max_dist) cmd.deselect()
def select_sites(selection='all', filename=None, prefix=None, nice=1, quiet=0): ''' DESCRIPTION Make named selections from SITE records. ARGUMENTS name = string: molecular object {default: all} filename = string: PDB file name with SITE records {default: look in current directory and fetch_path for <name>.pdb} prefix = string: prefix for named selections {default: site_} nice = 0 or 1: make colored sticks representation for sites {default :1} ''' nice, quiet = int(nice), int(quiet) names = cmd.get_names('public_objects', 1, '(' + selection + ')') selenames = set() cysselenames = set() hetselenames = set() for name in names: pfx = prefix or name + '_' fname = filename grpselenames = set() if fname is None: for fname in [ '%s.pdb' % (name), '%s/%s.pdb' % (cmd.get('fetch_path'), name) ]: if os.path.exists(fname): break else: print(' Error: please provide filename') raise CmdException if not quiet: print('loading from %s' % (fname)) for line in open(fname): if line.startswith('SITE '): siteID = line[11:14].strip() selename = pfx + siteID selenames.add(selename) grpselenames.add(selename) for i in range(4): res = line[18 + 11 * i:29 + 11 * i] if res.strip(): chain = res[4] resi = res[5:].strip() selestr = '%s and chain %s and resi %s' % (name, chain, resi) cmd.select(selename, selestr, 0, 1, 1) elif line.startswith('LINK '): siteID = line[12:16].strip() distname = pfx + 'LINK_' + siteID s1 = '/%s//%s/%s/%s' % (name, line[21], line[22:27].strip(), line[12:16].strip()) s2 = '/%s//%s/%s/%s' % (name, line[51], line[52:57].strip(), line[42:46].strip()) cmd.distance(distname, s1, s2) elif line.startswith('SSBOND'): selename = pfx + 'SSBOND' selenames.add(selename) grpselenames.add(selename) cysselenames.add(selename) selestr = '%s & (chain %s & resi %s | chain %s & resi %s) & name CA+CB+SG' selestr = selestr % (name, line[15], line[17:22], line[29], line[31:36]) cmd.select(selename, selestr, 0, 1, 1) elif line.startswith('HET '): siteID = line[7:10].strip() selename = pfx + 'HET_' + siteID selenames.add(selename) grpselenames.add(selename) hetselenames.add(selename) selestr = '%s & (chain %s & resi %s)' % (name, line[12], line[13:17]) cmd.select(selename, selestr, 0, 1, 1) # Make selection for solvent selename = pfx + 'solv' selestr = '%s & solvent' % (name) grpselenames.add(selename) cmd.select(selename, selestr, 0, 1, 1) cmd.group(name + '_sites', ' '.join(grpselenames)) if nice: allsites = ' '.join(selenames) cmd.show_as('cartoon', selection) cmd.show('lines', '(%s) and not polymer' % (selection)) cmd.show('nonbonded', '(%s) and not polymer' % (selection)) cmd.show('sticks', '(%s) and (%s)' % (selection, allsites)) cmd.show('nb_spheres', '(%s) and (%s)' % (selection, allsites)) cmd.show('dashes', '*LINK*') cmd.show('labels', '*LINK*') cmd.color('gray', selection) for i, selename in enumerate(selenames): cmd.color(i + 2, '(%s) and (%s)' % (selection, selename)) # for i, selename in enumerate(cysselenames): # cmd.color('sulfur', '(%s) and (%s)' % (selection, selename)) for i, selename in enumerate(hetselenames): cmd.show('spheres', '%s and inorganic' % (selename)) cmd.util.cnc('%s' % (allsites))
cmd.group("label_acceptor_hotspot", members="PS_acceptor_hotspot_2") cmd.group("label_acceptor_hotspot", members="PS_acceptor_hotspot_3") cmd.group("label_acceptor_hotspot", members="PS_acceptor_hotspot_3") cmd.group("label_acceptor_hotspot", members="PS_acceptor_hotspot_4") cmd.group("label_acceptor_hotspot", members="PS_acceptor_hotspot_4") cmd.group("label_acceptor_hotspot", members="PS_acceptor_hotspot_5") cmd.group("label_acceptor_hotspot", members="PS_acceptor_hotspot_5") cmd.group("label_acceptor_hotspot", members="PS_acceptor_hotspot_6") cmd.group("label_acceptor_hotspot", members="PS_acceptor_hotspot_6") cmd.group("label_acceptor_hotspot", members="PS_acceptor_hotspot_7") cmd.group("label_acceptor_hotspot", members="PS_acceptor_hotspot_7") cmd.group("labels_hotspot", members="label_apolar_hotspot") cmd.group("labels_hotspot", members="label_donor_hotspot") cmd.group("labels_hotspot", members="label_acceptor_hotspot") cmd.load("hotspot/protein.pdb", "protein_hotspot") cmd.show("cartoon", "protein_hotspot") cmd.hide("line", "protein_hotspot") cmd.show("sticks", "organic") class IsoLevel(tk.Variable): def __init__(self, master, name, level): tk.Variable.__init__(self, master, value=level) self.name = name self.trace('w', self.callback) def callback(self, *args): cmd.isolevel(self.name, self.get()) def increment(self, event=None, delta=0.1): self.set(round(float(self.get()) + delta, 2))
def show_rna(): cmd.show('(polymer.nucleic)')
# Importing the PyMOL module will create the window. import pymol # Call the function below before using any PyMOL modules. pymol.finish_launching() # Now we can import cmd from pymol import cmd cmd.load("$PYMOL_PATH/test/dat/pept.pdb") cmd.show("sticks")
def redraw(self): """ redraw paints all selected atoms, and the atoms in the active selection in different colours. Sets all other atoms back to standard colours Different colours for 1) Atoms in the curently active selections (not yet confirmed) 2) Selected Atoms 3) Atoms in restraints 4) Atoms in restraints we are looking at at the moment (in tst mode)) :return: - :rtype: - """ # Has anything that influences the coloring of atoms changed? atoms_hash = hash(str(self.logic_handler.selected_atoms)) selection_hash = hash( str(self.logic_handler.my_selection.atoms) ) if self.logic_handler.my_selection != None else hash(str([None])) restraints_hash = hash(str(self.logic_handler.selected_restraints)) test_mode_hash = hash( str(self.check_results_mode) + str(self.check_result_dict)) if atoms_hash != self.last_hashes['atoms'] or selection_hash != self.last_hashes['selection'] \ or restraints_hash != self.last_hashes['restraints'] or test_mode_hash != self.last_hashes['test_mode']: # 0) Recolour all atoms to standard colour try: self.cmd.util.cba( 'vanadium' ) # The colour for carbon atoms needs to be given explicitly. WARNING; The python cba command does not work properly. It does not work at all with gray. It raises an exception with vanadium, but it does paint it corectly. except: pass # 1) Colour selected atoms pu.help_pymol_with_big_atom_list(self.cmd.color, self.logic_handler.selected_atoms, color='copper') # 2) Colour atoms in current selection if self.logic_handler.my_selection != None: pu.help_pymol_with_big_atom_list( self.cmd.color, self.logic_handler.my_selection.atoms, color='hassium') # 3) Colour atoms in restraints # Have the restraints changed? if restraints_hash != self.last_hashes['restraints']: self.last_hashes.update(restraints=restraints_hash) self.create_pymol_objects_for_restraints() already_colored = False restrained_atoms = [] for i, r in enumerate(self.logic_handler.selected_restraints): pair = [] for a in r.atoms: if (a in restrained_atoms): already_colored = True restrained_atoms.append(a) pair.append(a) if (already_colored): pu.help_pymol_with_big_atom_list(self.cmd.color, pair, color=i % 54) else: pu.help_pymol_with_big_atom_list(self.cmd.set, pair, name="sphere_color", value=i % 54) already_colored = False # 3a) Colour all restrained atoms if not self.check_objects_exists('SphericalSelection'): cmd.hide("spheres", "all") else: cmd.hide("spheres", "not SphericalSelection") cmd.show("spheres", "SphericalSelection") pu.help_pymol_with_big_atom_list(self.cmd.show, restrained_atoms, representation='spheres') # 3b) In test mode: Colour atoms in restraints we are looking at at the moment if self.check_results_mode in [ 4, 6 ] and test_mode_hash != self.last_hashes['test_mode']: restrained_atoms = [] if self.check_results_mode == 4: for r in self.logic_handler.selected_restraints: if (r.atoms[0].resi == self.check_result_dict['mol1'][4:] and r.atoms[1].resi == self.check_result_dict['mol2'][4:]) \ or ( r.atoms[0].resi == self.check_result_dict['mol2'][4:] and r.atoms[1].resi == self.check_result_dict['mol1'][4:]): for a in r.atoms: restrained_atoms.append(a) if self.check_results_mode == 6: for r in self.logic_handler.selected_restraints: m1, m2 = self.check_result_dict['pairs'][ self.check_result_dict['i_pair']] if (r.atoms[0].resi == m1 and r.atoms[1].resi == m2) \ or (r.atoms[0].resi == m2 and r.atoms[1].resi == m1): for a in r.atoms: restrained_atoms.append(a) pu.help_pymol_with_big_atom_list(self.cmd.color, restrained_atoms, color='cyan') self.last_hashes.update(atoms=atoms_hash, selection=selection_hash, restraints=restraints_hash, test_mode=test_mode_hash) # -----------END OF if has has changed clause------------------------------------- # SPECIAL CASE FOR SPHERICAL SELECTION; CHECK IF SPHERICAL SELECTION IS STILL ACTIVE if (not isinstance(self.logic_handler.my_selection, SphericalSelection) ) and self.check_objects_exists('SphericalSelection'): self.cmd.unmask('all') self.cmd.delete('SphericalSelection') self.cmd.button('Left', 'None', "Rota")
import threading def dump_thread(): print for thr in threading.enumerate(): print(thr) dump_thread() import pymol pymol.pymol_launch=4 pymol.pymol_argv = [ 'pymol', '-qc'] # Quiet / no GUI from pymol import cmd pymol.finish_launching() dump_thread() cmd.fetch('1TUP', async=False) cmd.disable('all') cmd.enable('1TUP') cmd.bg_color('white') cmd.hide('all') cmd.show('cartoon') #cmd.hide('cartoon', 'chain E+F') #cmd.show('ribbon', 'chain E+F') cmd.select('zinc', 'name zn') cmd.show('sphere', 'zinc') cmd.set('ray_trace_mode', 3) cmd.png('1TUP.png', width=1980, height=1080, quiet=0, ray=1, prior=False) dump_thread() cmd.set('ray_trace_mode', 1) cmd.png('TUP.png', width=1980, height=1080, quiet=0, ray=1, prior=False) cmd.quit()
def StructureAnalyzer(pdbCode: str = "6hn0", ligandCode: str = "DIF", inputString: str = "* 1*vdw *", ignoreH2O: bool = False, defaultRadius: Optional[float] = None, pocketSize: float = 8.0, writeMD: bool = True) -> None: """ Main-code. Calculates the distances between a selected ligand and all atoms within a given cutoff-restriction of a given .pdb-code. Args: pdbCode (str, optional): Determines the protein structure from pdb. Defaults to "6hn0". ligandCode (str, optional): Determines the pdb code of the ligand. Defaults to "DIF". inputString (str, optional): see readme. Defaults to "* 1*vdw *". ignoreH2O (bool, optional): Determines if water should be ignored. Defaults to False. defaultRadius (float, optional): Default atom radius if no radius is given for the element. Defaults to None. pocketSize (float, optional): View distance of pocket and ligand in pyMOL. Defaults to 8. writeMD (bool, optional): Determinest if a markdown file should be written. Defaults to True. """ try: os.mkdir("Output") except: pass if writeMD: mdFile = open((f"./Output/{pdbCode}.md"), "w", encoding="utf-8") mdFile.close() defineDict(defaultRadius) cmd.reinitialize() condition = analyzeInput(inputString) cmd.fetch(pdbCode) # downloads given .pdb-file cmd.remove("hydro") cmd.select("allLigands", "resn " + ligandCode) stored.allLigandsAtoms = [] stored.oldResi = "" # iterates all Atoms belonging to the given ligand code and splits them up so you have an array of atoms cmd.iterate_state(-1, "allLigands", """\ if(resi == stored.oldResi): stored.allLigandsAtoms[(len(stored.allLigandsAtoms)-1)].append(Atom(x, y, z, model, chain, resn, resi, name, elem)) else: stored.oldResi = resi stored.allLigandsAtoms.append([Atom(x, y, z, model, chain, resn, resi, name, elem)]) """) # gets the ligand with the least distance to the global cog for ligands in stored.allLigandsAtoms: ligandResName = ligands[0].resn # e.g. DIF ligandResID = ligands[0].resi # e.g. 601 LigandName = ligandResName + str(ligandResID) # e.g. DIFxxx print(f"Analyzing {LigandName}...") # drawing pocket and ligand cmd.hide('all') cmd.select(LigandName, ligandResName + "`" + str(ligandResID) + "/") cmd.select('view', 'br. all within ' + str(pocketSize) + ' of ' + LigandName) pocketLayerName = f"pocket_{LigandName}" cmd.select(pocketLayerName, 'view and not ' + LigandName) cmd.show('sticks', pocketLayerName) cmd.show('sticks', LigandName) cmd.show('nb_spheres', pocketLayerName) cmd.show('nb_spheres', LigandName) cmd.util.cbaw(pocketLayerName) cmd.util.cbao(LigandName) stored.atomsPocket = [] # all Atoms of the Pocket # reads all informations belonging to the selected binding pocket cmd.iterate_state(-1, pocketLayerName, "stored.atomsPocket.append(Atom(x, y, z, model, chain, resn, resi, name, elem))") interactionList = [] atomsForGraph = [] # main-main-code: calculates the distances of each atom belonging to the pocket to each atom belonging to the ligand. If the distance is less than the cutoff the distance is drawn for ligandAtoms in ligands: atomsForGraph.append(ligandAtoms) conditionElementsLigand = condition[0] if not (ligandAtoms.element in conditionElementsLigand or "*" in conditionElementsLigand): continue for pocketAtoms in stored.atomsPocket: if (pocketAtoms.resn == "HOH") and ignoreH2O: continue conditionElementsPocket = condition[2] if not (pocketAtoms.element in conditionElementsPocket or "*" in conditionElementsPocket): continue conditionDistance = condition[1] if "vdw" in conditionDistance: cutoff = getCutoff( (ligandAtoms, conditionDistance, pocketAtoms)) else: cutoff = float(conditionDistance[0]) if cutoff is None: continue currDist = calcDist(ligandAtoms.pos, pocketAtoms.pos) if currDist > cutoff: continue interactionLayerName = f"inter_{LigandName}" cmd.distance( interactionLayerName, ligandAtoms.identifierString, pocketAtoms.identifierString, cutoff+1) cmd.color("cyan", interactionLayerName) cmd.show("dashes", interactionLayerName) interactionList.append(Interaction( ligandAtoms, pocketAtoms, currDist)) atomsForGraph.append(pocketAtoms) currGraph = buildGraph(atomsForGraph) writeXML(currGraph, interactionList, pdbCode, ligands) print(f"Analyzing {LigandName} finished") if writeMD: mdFile = open((f"./Output/{pdbCode}.md"), "a", encoding="utf-8") writeTable(mdFile, interactionList) print(f"Analyzing {pdbCode} finished")
def load_rep(prot): cmd.load(prot['prot_pdb'], prot['prot_type']) # load protein cmd.show('cartoon', prot['prot_type']) # representation cmd.show('sticks', 'hetatm') cmd.show('sphere', 'resn ZN') cmd.hide('lines', prot['prot_type']) # representation cmd.color(prot['colors'][0], prot['prot_type']) # color if prot['rep_type'] == 0: pymol_sel = '%s or ' % prot['prot_type'] lign = 1 prot['ligands'].sort() for lig in prot['ligands']: cmd.load(lig, '%s_FILL_%s' % (prot['prot_type'][0], lign)) # load ligand if lign < len(prot['ligands']): pymol_sel += '%s_FILL_%s or ' % (prot['prot_type'][0], lign) else: pymol_sel += '%s_FILL_%s' % (prot['prot_type'][0], lign) lign += 1 ligand_sites_trans(pymol_sel) cmd.hide("sticks", prot['prot_type']) cmd.hide("ribbon", prot['prot_type']) cmd.show('cartoon', prot['prot_type']) cmd.delete('polar_contacts') cmd.color(prot['colors'][0], prot['prot_type'] ) # redundant? is needed because ligand_sites_trans for lign in range(len(prot['ligands'])): cmd.color(prot['colors'][lign + 1], '%s_FILL_%s' % (prot['prot_type'][0], lign + 1)) # cmd.zoom('%s_ref_center' % prot['prot_type'][0].upper(), 15, animate=1) # zoom to selected fill elif prot['rep_type'] == 1: cmd.load(prot['ligands'][0], '%s_FILL' % prot['prot_type'][0]) # load ligand cmd.color('cyan', '%s_FILL' % prot['prot_type'][0]) cmd.hide('lines', '%s_FILL' % prot['prot_type'][0]) cmd.show('dots', '%s_FILL' % prot['prot_type'][0]) res_list = [] for x in prot['residues'].split(';'): x = str(x).strip() if x and not x in res_list: res_list.append(x) for res in res_list: chain, resi, num = res.split(':') cmd.show('sticks', 'chain %s and resi %s' % (chain, num)) if prot['colors'][-1] == 'green': util.cbag('chain %s and resi %s' % (chain, num)) else: util.cbam('chain %s and resi %s' % (chain, num)) # cmd.zoom('%s_FILL' % prot['prot_type'][0], 15, animate=1) elif prot['rep_type'] == 2: cmd.load(prot['ligands'][0], '%s_ligand' % prot['prot_type'][0]) cmd.show('sticks', '%s_ligand' % prot['prot_type'][0]) if prot['colors'][-1] == 'green': util.cbag('%s_ligand' % prot['prot_type'][0]) else: util.cbam('%s_ligand' % prot['prot_type'][0]) # cmd.zoom('%s_ligand' % prot['prot_type'][0], 15, animate=1) calculate_box(prot['center'][0], prot['center'][1], prot['center'][2], prot['size'][0], prot['size'][1], prot['size'][2], prot['prot_type'])
def disp_ss( selection='all', colors='marine red white', only=False): ''' DESCRIPTION Formats the passed object into secondary structure cartoon USAGE disp_ss [ selection [, colors [, only ]]] PARAMETERS NAME=DEFAULT TYPE FUNCTION selection='all' <str> input selection colors='marine red white' <str> any three colors for: sheets, helices and loops e.g. 'marine red white' can also be set to either util.cbc, util.rainbow, or util.chainbow (alone) set='False' to supress coloring altogether, or enter False for the coloring to be omitted, e.g. 'marine False green' only <bool> if True will use show_as; else show ''' try: selection = '(' + selection + ')' colors = str(colors) only = bool(str(only) != 'False') except: print("Input error") return False if colors == 'False': color_s = color_h = color_l = False elif colors.startswith('util.'): util_choices = ['util.cbc', 'util.rainbow', 'util.chainbow', 'util.ss'] if colors in util_choices: color_s = color_h = color_l = '%s ' % util_choices[util_choices.index(colors)] else: print("Input error! Please check the color setting using util. is one of:", util_choices) return False else: try: color_s, color_h, color_l = colors.split()[:3] if color_s != 'False': cmd.color(color_s, None) color_s = 'color %s, ' % color_s else: color_s = False if color_h != 'False': cmd.color(color_h, None) color_h = 'color %s, ' % color_h else: color_h = False if color_l != 'False': cmd.color(color_l, None) color_l = 'color %s, ' % color_l else: color_l = False except: print("Input error! Please check that three valid colors (or False) are provided") return False for p in cmd.get_object_list(selection): cmd.set('cartoon_discrete_colors', 'on', p) # settings cmd.cartoon('rectangle', 'ss s and %s and %s' % (selection, p)) cmd.cartoon('dumbbell', 'ss h and %s and %s' % (selection, p)) cmd.cartoon('loop', 'ss l+"" and %s and %s' % (selection, p)) # sheets if color_s: print(cmd.do(color_s + '(ss s and %s and %s)' % (selection, p))) cmd.set('cartoon_rect_length', 1.5, p) cmd.set('cartoon_rect_width', 0.25, p) # a-helices if color_h: print(cmd.do(color_h + '(ss h and %s and %s)' % (selection, p))) cmd.set('cartoon_dumbbell_length', 1.5, p) cmd.set('cartoon_dumbbell_width', 0.25, p) cmd.set('cartoon_dumbbell_radius', 0.2, p) # loops if color_l: print(cmd.do(color_l + '(ss l+"" and %s and %s)' % (selection, p))) cmd.set('cartoon_loop_radius', 0.25, p) if only: cmd.show_as('cartoon', '%s and %s' % (selection, p)) else: cmd.show('cartoon', '%s and %s' % (selection, p))
from pymol import cmd cmd.load("1r_final.pdb") cmd.hide("lines") cmd.show("cartoon") cmd.set("cartoon_fancy_helices", 1) cmd.set("ray_trace_mode", 1) cmd.set("two_sided_lighting", "on") cmd.set("reflect", 0) cmd.set("ambient", 0.5) cmd.set("ray_trace_mode", 0) cmd.set('''ray_opaque_background''', '''off''') inFile = open("rmsf_pymol", 'r') stored.newB = [] for line in inFile.readlines(): stored.newB.append( float(line) ) inFile.close() alter 1r_final, b=0.0 alter 1r_final and n. CA, b=stored.newB.pop(0) # color the protein based on the new B Factors of the alpha carbons cmd.spectrum("b", "1r_final and n. CA") cmd.png("bfac_1r_final.png", width=1800, height=1100, dpi=600, ray=1)
def disp_mesh(selection='all', color_m='default', hydrogens=0, only=False, limits=5): ''' DESCRIPTION Adds a mesh to the object Has advanced coloring options and automatically accounts for the hydrogens USEAGE disp_mesh [ selection [, color_m [, hydrogens [, only [, limits]]]]] disp_mesh selection=all, color_m=default disp_mesh selection=all, color_m=white disp_mesh selection=all, color_m=putty PARAMETERS NAME=DEFAULT TYPE FUNCTION selection='all' <str> input selection color_m='default' <str> 'default': as current 'name': colors by color or ramp called name 'putty': b-factor on surface hydrogens=0 <int> -1: remove; 1: add; else: as is only=False <bool> if True will use show_as; else show limits=5 <list or flaot> applies only if color_m=='putty' sets the b-factor range limits <list> [min,max] # absolute values <float> percentile cutoff (both sides) # relative for each protein ''' try: selection = '(' + selection + ')' color_m = str(color_m) hydrogens = int(hydrogens) only = bool(str(only) != 'False') except: print("Input error") return False if hydrogens == 1: cmd.h_add('%s' % selection) if hydrogens == -1: cmd.remove('%s and elem H' % selection) for p in cmd.get_object_list(selection): cmd.set('mesh_width', 0.25, p) if (color_m == 'putty'): limits = get_b_limits(limits, p) if not limits: print("Input error (limits must be <list> or <float (<=50)>)!") return False cmd.set('mesh_color', 'default', p) cmd.spectrum('b', 'rainbow', '(not hetatm) and %s' % p, minimum='%f' % limits[0], maximum='%f' % limits[1], byres=0) print("disp_mesh:", p, "displayed in putty mode - mesh as putty - limits=[%.4f,%.4f]" % (limits[0], limits[1])) else: cmd.set('mesh_color', color_m, p) print("disp_mesh: regular mode - mesh - " + p) if only: cmd.show_as('mesh', '%s and %s' % (selection, p)) else: cmd.show('mesh', '%s and %s' % (selection, p)) cmd.rebuild()
def reps(self,cleanup=0): rep_list = [ "lines","sticks","spheres","surface","mesh","dots","ribbon","cartoon" ] try: if not cleanup: cmd.disable() cmd.set("suspend_updates",1,quiet=1) cmd.load("$PYMOL_DATA/demo/pept.pdb","rep1") cmd.alter("rep1///1-5+8-13/","ss='S'") cmd.cartoon("auto") cmd.hide("everything","rep1") for a in range(2,9): cmd.create("rep%d"%a,"rep1") for x, y in enumerate(rep_list, 1): cmd.show(x, "rep%d" % y) cmd.reset() cmd.zoom("rep1",24) util.cbay("rep2") util.cbac("rep3") util.cbas("rep4") util.cbab("rep5") util.cbaw("rep6") util.cbay("rep8") cmd.set("suspend_updates",0,quiet=1) scale=0.5 for b in range(1,20): cmd.set("suspend_updates",0,quiet=1) cmd.refresh() cmd.set("suspend_updates",1,quiet=1) xt=-3.2 yt=1.6 for a in range(1,5): cmd.translate([xt*scale,yt*scale,0],object="rep%d"%a,camera=0) xt=xt+2 yt=-yt xt=-3.2 for a in range(5,9): cmd.translate([xt*scale,yt*scale,0],object="rep%d"%a,camera=0) xt=xt+2 for a in range(1,9): cmd.origin("rep%d"%a,object="rep%d"%a) cmd.mset("1") st = ' '.join(map(lambda x,y:"rotate angle=-3,object=rep%d,axis=%s;"%(x,y),list(range(1,9)), ['x','y','x','y','x','y','x','y'])) cmd.mdo(1,st) cmd.set("suspend_updates",0,quiet=1) cmd.mplay() cgo = [] axes = [[4.5,0.0,0.0],[0.0,3.0,0.0],[0.0,0.0,3.0]] c = 1 for a in rep_list: ext = cmd.get_extent("rep%d"%c) pos = [(ext[0][0]+ext[1][0])/2, (ext[0][1]+ext[1][1])/2+14, (ext[0][2]+ext[1][2])/2] c = c + 1 pos[0]=pos[0]-(measure_text(plain,a,axes)/2) wire_text(cgo,plain,pos,a,axes) cmd.set("cgo_line_width",1.5) cmd.set("auto_zoom",0) cmd.load_cgo(cgo,'reps') cmd.set("auto_zoom",1) else: cmd.delete("rep*") cmd.mset() cmd.mstop() except: traceback.print_exc()
def visualize_in_pymol(model, attribution_fn, plcomplex, input_dim, output_dir, radius=12, bs=16): """Visualizes the given Protein-Ligand complex at one site in PyMOL. This function is based on the origina plip.visualization.vizualise_in_pymol function, with the added functinoality which uses a machine learning model to colour the receptor atoms by """ vis = PyMOLVisualizerWithBFactorColouring(plcomplex) ##################### # Set everything up # ##################### pdbid = plcomplex.pdbid lig_members = plcomplex.lig_members chain = plcomplex.chain if config.PEPTIDES: vis.ligname = 'PeptideChain%s' % plcomplex.chain if config.INTRA is not None: vis.ligname = 'Intra%s' % plcomplex.chain ligname = vis.ligname hetid = plcomplex.hetid metal_ids = plcomplex.metal_ids metal_ids_str = '+'.join([str(i) for i in metal_ids]) ######################## # Basic visualizations # ######################## start_pymol(run=True, options='-pcq', quiet=not config.VERBOSE and not config.SILENT) vis.set_initial_representations() cmd.load(plcomplex.sourcefile) current_name = cmd.get_object_list(selection='(all)')[0] logger.debug( f'setting current_name to {current_name} and PDB-ID to {pdbid}') cmd.set_name(current_name, pdbid) cmd.hide('everything', 'all') if config.PEPTIDES: cmd.select(ligname, 'chain %s and not resn HOH' % plcomplex.chain) else: cmd.select( ligname, 'resn %s and chain %s and resi %s*' % (hetid, chain, plcomplex.position)) logger.debug( f'selecting ligand for PDBID {pdbid} and ligand name {ligname}') logger.debug( f'resn {hetid} and chain {chain} and resi {plcomplex.position}') # Visualize and color metal ions if there are any if not len(metal_ids) == 0: vis.select_by_ids(ligname, metal_ids, selection_exists=True) cmd.show('spheres', 'id %s and %s' % (metal_ids_str, pdbid)) # Additionally, select all members of composite ligands if len(lig_members) > 1: for member in lig_members: resid, chain, resnr = member[0], member[1], str(member[2]) cmd.select( ligname, '%s or (resn %s and chain %s and resi %s)' % (ligname, resid, chain, resnr)) cmd.show('sticks', ligname) cmd.color('myblue') cmd.color('myorange', ligname) cmd.util.cnc('all') if not len(metal_ids) == 0: cmd.color('hotpink', 'id %s' % metal_ids_str) cmd.hide('sticks', 'id %s' % metal_ids_str) cmd.set('sphere_scale', 0.3, ligname) cmd.deselect() vis.make_initial_selections() vis.show_hydrophobic() # Hydrophobic Contacts vis.show_hbonds() # Hydrogen Bonds vis.show_halogen() # Halogen Bonds vis.show_stacking() # pi-Stacking Interactions vis.show_cationpi() # pi-Cation Interactions vis.show_sbridges() # Salt Bridges vis.show_wbridges() # Water Bridges vis.show_metal() # Metal Coordination results_fname = Path( output_dir, '{0}_{1}_results.txt'.format( pdbid.upper(), '_'.join([hetid, plcomplex.chain, plcomplex.position]))).expanduser() parser = PDBInteractionParser() vis.colour_b_factors_pdb(model, attribution_fn=attribution_fn, parser=parser, results_fname=results_fname, input_dim=input_dim, radius=radius, bs=bs) vis.refinements() vis.zoom_to_ligand() vis.selections_cleanup() vis.selections_group() vis.additional_cleanup() if config.DNARECEPTOR: # Rename Cartoon selection to Line selection and change repr. cmd.set_name('%sCartoon' % plcomplex.pdbid, '%sLines' % plcomplex.pdbid) cmd.hide('cartoon', '%sLines' % plcomplex.pdbid) cmd.show('lines', '%sLines' % plcomplex.pdbid) if config.PEPTIDES: filename = "%s_PeptideChain%s" % (pdbid.upper(), plcomplex.chain) if config.PYMOL: vis.save_session(config.OUTPATH, override=filename) elif config.INTRA is not None: filename = "%s_IntraChain%s" % (pdbid.upper(), plcomplex.chain) if config.PYMOL: vis.save_session(config.OUTPATH, override=filename) else: filename = '%s_%s' % (pdbid.upper(), "_".join( [hetid, plcomplex.chain, plcomplex.position])) vis.save_session(plcomplex.mol.output_path, override=filename) if config.PICS: vis.save_picture(config.OUTPATH, filename)
def disp_surf( selection='all', color_s='default', transparency=0, hydrogens=0, solvent=0, ramp_above=1, only=False, limits=5): ''' DESCRIPTION Advanced surface representation (cf. examples) USAGE disp_surf [ selection [, color_s [, transparency [, hydrogens [, solvent [, ramp_above [, only [, limits]]]]]]]] EXAMPLES disp_surf # opaque surface with default colors disp_surf all, white, 0.5 # half-transparent white surface disp_surf all, putty # b-factor on surface PARAMETERS NAME=DEFAULT TYPE FUNCTION selection='all' <str> input selection color_s='default' <str> 'default': as current 'name': colors by color or ramp called name 'putty': b-factor on surface (by resi) transparency=0 <float> set surface transparency hydrogens=0 <int> -1: remove; 1: add; else: as is solvent=0 <int> defines 'surface_solvent' ramp_above=1 <int> defines 'surface_ramp_above_mode' only=False <bool> if True will use show_as; else show limits=5 <list or flaot> applies only if color_s=='putty' sets the b-factor range limits <list> [min,max] # absolute values <float> percentile cutoff (both sides) # relative for each protein ''' try: selection = '(' + selection + ')' color_s = str(color_s) transparency = float(transparency) hydrogens = int(hydrogens) solvent = int(solvent) ramp_above = int(ramp_above) only = bool(str(only) != 'False') except: print("Input error") return False for p in cmd.get_object_list(selection): if hydrogens == -1: cmd.remove('%s and elem H' % p) if hydrogens == 1: cmd.h_add(p) # if hydrogens==0: as is # some defaults (settings can be changed later, too) cmd.set('surface_carve_cutoff', '4.5', p) cmd.set('surface_quality', '2', p) cmd.set('solvent_radius', '1.5', p) cmd.set('cavity_cull', '2', p) #cmd.set('surface_carve_selection', p) # this causes issues when using the command on different objects # it is better to define surface_carve_selection manually # defined cmd.set('surface_solvent', solvent, p) cmd.set('surface_ramp_above_mode', ramp_above, p) cmd.set('transparency', transparency, p) if (color_s == 'putty'): limits = get_b_limits(limits, p) if not limits: print("Input error (limits must be <list> or <float (<=50)>)!") return False cmd.set('surface_color', 'default', p) cmd.spectrum('b', 'rainbow', '(not hetatm) and %s' % p, minimum='%f' % limits[0], maximum='%f' % limits[1], byres=0) print("disp_surf:", p, "displayed in putty mode - surface as putty - limits=[%.4f,%.4f]" % (limits[0], limits[1])) else: cmd.set('surface_color', color_s, selection) print("disp_surf:", p, "displayed as regular surface") if only: cmd.show_as('surface', '(%s and %s)' % (selection, p)) else: cmd.show('surface', '(%s and %s)' % (selection, p))
#if(len(params) == 2): #path = params[1] #cmd.cd(path) #else: #print "No Path specified" except ValueError: print "No Path specified" for file in glob("*.pdb"): print "file: ", file listname = file.split(".") name = listname[0] cmd.load(file, name) cmd.system("mv " + file + " ../pdb/") cmd.hide("all") cmd.show("sticks") cmd.reset() cmd.origin(position=[0.0, 0.0, 0.0]) cmd.save(name + "stix.wrl") cmd.hide("all") cmd.show("ribbon") cmd.reset() cmd.origin(position=[0.0, 0.0, 0.0]) cmd.save(name + "rib.wrl") cmd.hide("all") preset.pretty(name) cmd.reset() cmd.origin(position=[0.0, 0.0, 0.0]) cmd.save(name + "cart.wrl") cmd.hide("all") cmd.show("surface")
def refinements(self): """Refinements for the visualization""" # Show sticks for all residues interacing with the ligand cmd.select( 'AllBSRes', 'byres (Hydrophobic-P or HBondDonor-P or HBondAccept-P or PosCharge-P or NegCharge-P or ' 'StackRings-P or PiCatRing-P or HalogenAcc or Metal-P)') cmd.show('sticks', 'AllBSRes') # Show spheres for the ring centroids cmd.hide('everything', 'centroids*') cmd.show('nb_spheres', 'centroids*') # Show spheres for centers of charge if self.object_exists('Chargecenter-P') or self.object_exists( 'Chargecenter-L'): cmd.hide('nonbonded', 'chargecenter*') cmd.show('spheres', 'chargecenter*') cmd.set('sphere_scale', 0.4, 'chargecenter*') cmd.color('yellow', 'chargecenter*') cmd.set('valence', 1) # Show bond valency (e.g. double bonds) # Optional cartoon representation of the protein cmd.copy('%sCartoon' % self.protname, self.protname) cmd.show('cartoon', '%sCartoon' % self.protname) cmd.show('sticks', '%sCartoon' % self.protname) cmd.set('stick_transparency', 1, '%sCartoon' % self.protname) # Resize water molecules. Sometimes they are not heteroatoms HOH, but part of the protein cmd.set('sphere_scale', 0.2, 'resn HOH or Water' ) # Needs to be done here because of the copy made cmd.set('sphere_transparency', 0.4, '!(resn HOH or Water)') if 'Centroids*' in cmd.get_names("selections"): cmd.color('grey80', 'Centroids*') cmd.hide('spheres', '%sCartoon' % self.protname) cmd.hide('cartoon', '%sCartoon and resn DA+DG+DC+DU+DT+A+G+C+U+T' % self.protname) # Hide DNA/RNA Cartoon if self.ligname == 'SF4': # Special case for iron-sulfur clusters, can't be visualized with sticks cmd.show('spheres', '%s' % self.ligname) cmd.hide( 'everything', 'resn HOH &!Water') # Hide all non-interacting water molecules cmd.hide( 'sticks', '%s and !%s and !AllBSRes' % (self.protname, self.ligname)) # Hide all non-interacting residues if self.ligandtype in ['PEPTIDE', 'INTRA']: self.adapt_for_peptides() if self.ligandtype == 'INTRA': self.adapt_for_intra()