def testIdAtom(self): cmd.fragment('gly', 'm1') self.assertEqual(cmd.id_atom('ID 3'), 3) self.assertEqual(cmd.id_atom('ID 3', 1), ('m1', 3)) cmd.feedback("disable", "cmd", "errors") self.assertRaises(CmdException, cmd.id_atom, 'ID 3+4') self.assertRaises(CmdException, cmd.id_atom, 'ID 100')
def start_pymol(quiet=False, options='-p', run=False): """Starts up PyMOL and sets general options. Quiet mode suppresses all PyMOL output. Command line options can be passed as the second argument.""" import pymol pymol.pymol_argv = ['pymol', '%s' % options] + sys.argv[1:] if run: initialize_pymol(options) if quiet: cmd.feedback('disable', 'all', 'everything')
def png_workaround(filepath, width=1200, height=800): """Workaround for (a) severe bug(s) in PyMOL preventing ray-traced images to be produced in command-line mode. Use this function in case neither cmd.ray() or cmd.png() work. """ sys.stdout = sys.__stdout__ cmd.feedback('disable', 'movie', 'everything') cmd.viewport(width, height) cmd.zoom('visible', 1.5) # Adapt the zoom to the viewport cmd.set('ray_trace_frames', 1) # Frames are raytraced before saving an image. cmd.mpng(filepath, config.MODEL, config.MODEL) # Use batch png mode with 1 frame only cmd.mplay() # cmd.mpng needs the animation to 'run' cmd.refresh() originalfile = "".join([ filepath, (4 - len(str(config.MODEL))) * '0' + str(config.MODEL) + '.png' ]) newfile = "".join([filepath, '.png']) ################################################# # Wait for file for max. 1 second and rename it # ################################################# attempts = 0 while not os.path.isfile(originalfile) and attempts <= 10: sleep(0.1) attempts += 1 if os.name == 'nt': # In Windows, make sure there is no file of the same name, cannot be overwritten as in Unix if os.path.isfile(newfile): os.remove(newfile) os.rename(originalfile, newfile) # Remove frame number in filename # Check if imagemagick is available and crop + resize the images if subprocess.call("type convert", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0: attempts, ecode = 0, 1 # Check if file is truncated and wait if that's the case while ecode != 0 and attempts <= 10: ecode = subprocess.call(['convert', newfile, '/dev/null'], stdout=open('/dev/null', 'w'), stderr=subprocess.STDOUT) sleep(0.1) attempts += 1 trim = 'convert -trim ' + newfile + ' -bordercolor White -border 20x20 ' + newfile + ';' # Trim the image os.system(trim) getwidth = 'w=`convert ' + newfile + ' -ping -format "%w" info:`;' # Get the width of the new image getheight = 'h=`convert ' + newfile + ' -ping -format "%h" info:`;' # Get the hight of the new image newres = 'if [ "$w" -gt "$h" ]; then newr="${w%.*}x$w"; else newr="${h%.*}x$h"; fi;' # Set quadratic ratio quadratic = 'convert ' + newfile + ' -gravity center -extent "$newr" ' + newfile # Fill with whitespace os.system(getwidth + getheight + newres + quadratic) else: sys.stderr.write( 'Imagemagick not available. Images will not be resized or cropped.' )
def electomo(self,cleanup=0): if not cleanup: cmd.feedback("disable","objectsurface","actions") cmd.set_session(self.get_sess("$PYMOL_DATA/big_demo/flagellar.pse")) cmd.set("sweep_mode",3) cmd.set("sweep_angle",3) cmd.rock() cmd.do("replace_wizard toggle, Electron Tomography") else: cmd.mstop() cmd.rock(0)
def builder(residues, bonds, mol_name): """Using the list generated by read_input connects monosacharides in a single oligosaccharide""" cmd.set('suspend_updates', 'on') cmd.feedback('disable', 'executive', 'actions') every_object = cmd.get_object_list('all') if mol_name in every_object: cmd.delete(mol_name) every_object.remove(mol_name) if every_object: sel = 'not (' + ' or '.join(every_object) + ') and' else: sel = '' for i in range(0, len(residues)): res_name = residues[i] cmd.load(os.path.join(path, 'db_glycans', '%s.pdb' % res_name)) cmd.set_name(res_name, i) #rename object (necessary to avoid repeating names) cmd.alter(i, 'resi = %s' % i) #name residues for further referencing cmd.sort(i) for i in range(0, len(bonds)): resi_i, resi_j, atom_i, atom_j = bonds[i][0], bonds[i][2], bonds[i][ 4], bonds[i][5] if atom_i > atom_j: cmd.remove('%s (resi %s and name O%s+H%so)' % (sel, resi_j, atom_j, atom_j)) cmd.remove('%s (resi %s and name H%so)' % (sel, resi_i, atom_i)) cmd.fuse('%s (resi %s and name O%s)' % (sel, resi_i, atom_i), '%s (resi %s and name C%s)' % (sel, resi_j, atom_j), mode=2) else: cmd.remove('%s (resi %s and name O%s+H%so)' % (sel, resi_i, atom_i, atom_i)) cmd.remove('%s (resi %s and name H%so)' % (sel, resi_j, atom_j)) cmd.fuse('%s (resi %s and name C%s)' % (sel, resi_i, atom_i), '%s (resi %s and name O%s)' % (sel, resi_j, atom_j), mode=2) cmd.delete('%s' % i) cmd.copy(mol_name, '%s' % resi_j) cmd.delete('%s' % resi_j) for i in range(0, len(bonds)): set_phi(mol_name, bonds[i], -60) set_psi(mol_name, bonds[i], 120) cmd.delete('pk1') cmd.delete('pk2') cmd.delete('pkbond') cmd.delete('pkmol') if babel: fast_min(mol_name, 5000) minimize(mol_name) else: fast_min(mol_name, 5000) cmd.feedback('enable', 'executive', 'actions') cmd.set('suspend_updates', 'off')
def setUp(self): self.oldcwd = os.getcwd() cmd.reinitialize() cmd.viewport(640, 480) cwd = self.moddirs[type(self).__module__] os.chdir(cwd) cmd.feedback('push') cmd.feedback('disable', 'all', 'details actions') self.timings = []
def movie(self, configurations): n = 1 cmd.feedback("disable","executive","actions") auto_zoom = cmd.get("auto_zoom") cmd.set("auto_zoom", 0) for conf in configurations: self._setCoordinates(conf) cmd.load_model(self.model, self.name, n) n = n + 1 cmd.set("auto_zoom", auto_zoom) cmd.feedback("enable","executive","actions") cmd.mplay()
def movie(self, configurations): n = 1 cmd.feedback("disable", "executive", "actions") auto_zoom = cmd.get("auto_zoom") cmd.set("auto_zoom", 0) for conf in configurations: self._setCoordinates(conf) cmd.load_model(self.model, self.name, n) n = n + 1 cmd.set("auto_zoom", auto_zoom) cmd.feedback("enable", "executive", "actions") cmd.mplay()
def setUp(self): self.oldcwd = os.getcwd() cmd.reinitialize() cmd.viewport(640, 480) if cliargs.no_undo: cmd.set('suspend_undo', updates=0) cwd = self.moddirs[type(self).__module__] os.chdir(cwd) cmd.feedback('push') cmd.feedback('disable', 'all', 'details actions') self.timings = []
def testCdLsPwd(self): with testing.mkdtemp() as path: cmd.cd(path) self.assertEqual(os.getcwd(), os.path.realpath(path)) touch('foo1.txt') touch('foo2.txt') touch('foo3.bin') cmd.feedback("disable", "python", "output") cmd.pwd() # no test of output possible cmd.ls('*.txt')
def builder(residues, bonds, mol_name): """Using the list generated by read_input connects monosacharides in a single oligosaccharide""" cmd.set('suspend_updates', 'on') cmd.feedback('disable', 'executive', 'actions') every_object = cmd.get_object_list('all') if mol_name in every_object: cmd.delete(mol_name) every_object.remove(mol_name) if every_object: sel = 'not (' + ' or '.join(every_object) + ') and' else: sel = '' for i in range(0, len(residues)): res_name = residues[i] cmd.load(os.path.join(path, 'db_glycans', '%s.pdb' % res_name)) cmd.set_name(res_name, i) #rename object (necessary to avoid repeating names) cmd.alter(i, 'resi = %s' % i) #name residues for further referencing cmd.sort(i) for i in range(0, len(bonds)): resi_i, resi_j, atom_i, atom_j = bonds[i][0], bonds[i][2], bonds[i][4], bonds[i][5] if atom_i > atom_j: cmd.remove('%s (resi %s and name O%s+H%so)' % (sel, resi_j, atom_j, atom_j)) cmd.remove('%s (resi %s and name H%so)' % (sel, resi_i, atom_i)) cmd.fuse('%s (resi %s and name O%s)' % (sel, resi_i, atom_i), '%s (resi %s and name C%s)' % (sel, resi_j, atom_j), mode=2) else: cmd.remove('%s (resi %s and name O%s+H%so)' % (sel, resi_i, atom_i, atom_i)) cmd.remove('%s (resi %s and name H%so)' % (sel, resi_j, atom_j)) cmd.fuse('%s (resi %s and name C%s)' % (sel, resi_i, atom_i), '%s (resi %s and name O%s)' % (sel, resi_j, atom_j), mode=2) cmd.delete('%s' % i) cmd.copy(mol_name, '%s' % resi_j) cmd.delete('%s' % resi_j) for i in range(0, len(bonds)): set_phi(mol_name, bonds[i], -60) set_psi(mol_name, bonds[i], 120) cmd.delete('pk1') cmd.delete('pk2') cmd.delete('pkbond') cmd.delete('pkmol') if babel: fast_min(mol_name, 5000) minimize(mol_name) else: fast_min(mol_name, 5000) cmd.feedback('enable', 'executive', 'actions') cmd.set('suspend_updates', 'off')
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()
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()
def disable_feedback(what, level): """Disable feedback.""" pm.feedback("disable", what, level) yield pm.feedback("enable", what, level)
if not int(quiet): print(' centroid: [%8.3f,%8.3f,%8.3f]' % tuple(centroid)) if int(center): cmd.alter_state(1, selection, "(x,y,z)=sub((x,y,z), centroid)", space={ 'centroid': centroid, 'sub': cpv.sub }) return centroid cmd.feedback("disable", "all", "actions") cmd.feedback("disable", "all", "results") cmd.feedback("disable", "all", "warnings actions") protName = path.basename(sys.argv[1]) ligName = path.basename(sys.argv[2]) cmd.load(sys.argv[1], protName) cmd.load(sys.argv[2], ligName) #if needed to center the search space on the ligand use this line instead #(comX, comY, comZ) = centroid(ligName) (comX, comY, comZ) = centroid(protName) ((maxX, maxY, maxZ), (minX, minY, minZ)) = cmd.get_extent(protName) print( 'center_x = %8.4f\ncenter_y = %8.4f\ncenter_z = %8.4f\nsize_x = %8.4f\nsize_y = %8.4f\nsize_z = %8.4f\n'
cmd.iterate("(%s and id %d)"%(res_sele,b),"stored.names.append(name)") name_list.append(tuple(pymol.stored.names)) res_dict = {} for a in name_list: dihe = cmd.get_dihedral("(%s and name %s)"%(res_sele,a[0]), "(%s and name %s)"%(res_sele,a[1]), "(%s and name %s)"%(res_sele,a[2]), "(%s and name %s)"%(res_sele,a[3])) res_dict[a]=dihe if not prot_dict.has_key(resn): prot_dict[resn]=[] prot_dict[resn].append(res_dict) sc_dict = {} cmd.feedback('disable','selector','result') cmd.feedback('disable','executive','action') for fyle in glob("source/*"): cmd.load(fyle) cmd.remove("(het)") cmd.remove("(hydro or not alt '')") cmd.remove("(byres b>25)") # only use well-defined residues cmd.remove("(not (byres name ca))") cmd.remove("(not (byres name n))") cmd.remove("(not (byres name c))") cmd.refresh() measure_all_torsions("all",sc_dict) cmd.delete("all") #for a in sc_dict.keys():
# while list[0]!="pdb/f8/pdb1f8u": # list.pop(0) for file in list: try: cmd.delete('pdb') cmd.load(file,'pdb') cmd.set_title('pdb',1,os.path.split(file)[-1]) cmd.rewind() cmd.orient('pdb') cmd.refresh() cmd.show_as("ribbon") cmd.refresh() cmd.show_as("sticks") cmd.refresh() sys.__stderr__.write(".") sys.__stderr__.flush() n = cmd.count_states() if n>1: cmd.rewind() sys.__stderr__.write(file+"\n") sys.__stderr__.flush() for a in range(1,n+1): cmd.forward() cmd.refresh() except: traceback.print_exc() cmd.feedback('disable','symmetry objectmolecule executive','everything') load()
def tearDown(self): cmd.feedback('pop') os.chdir(self.oldcwd)
def do_library(self): cmd=self.cmd pymol=cmd._pymol 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.feedback("pop")
f=open(dif_file) l=f.readlines() f.close() if len(l): print for a in l: print a, # save it so we have something to look at... os.system("/bin/cp -f %s %s_s"%(cmp_file,cmp_file)) os.system("/bin/cp -f %s %s_s"%(ref_file,ref_file)) os.system("/bin/cp -f %s %s_src"%(out_file,cmp_file)) os.system("/bin/cp -f %s %s_src"%(file,ref_file)) print file else: sys.__stdout__.write(".") sys.__stdout__.flush() except: traceback.print_exc() # allow the Tcl/Tk GUI time to get out of the way... time.sleep(3) cmd.set("retain_order",1) cmd.feedback('disable','symmetry objectmolecule executive','everything') # now start load()
def testSplash(self): cmd.feedback('disable', 'all', 'output') cmd.splash()
da = 0.9 * 2 * np.pi / 3 loncirc.append(circle(p, r, v1, v2, amin=da, amax=2 * np.pi - da)) return loncirc if __name__ == '__main__': import pdbsurf from pymol import cmd import matplotlib.pyplot as plt import misc.recutils as recutils import misc.Clustering from termcolor import colored import glob import argparse import sys cmd.feedback('disable', 'all', 'everything') # argparse.ArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=argparse.HelpFormatter, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True, allow_abbrev=True, exit_on_error=True) parser = argparse.ArgumentParser(description='') # parser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest]) parser.add_argument('-p', '--pdb') parser.add_argument('-s', '--sel') parser.add_argument('-c', '--caption') parser.add_argument( '--size', type=float, help='Size of the dots for the scatter plot (default=1.)', default=1.) parser.add_argument( '--levels', type=int, help='Number of levels in the contour plot (default=10)',
# 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 1: time.sleep(0.05) try: cmd.set("suspend_updates","1") # only necessary if multithreading... for a in m.atom: a.coord[0]+=(random()-0.5)*0.1 a.coord[1]+=(random()-0.5)*0.1 a.coord[2]+=(random()-0.5)*0.1 cmd.load_model(m,"demo",1) except:
def print_dihedrals(selection='sele', state=1, quiet=1, ss='', fc=10.0, chi=0, label='ID'): ''' DESCRIPTION "print_dihedrals" return the phi, psi, and chi1 angles for a protein atom selection. ARGUMENTS state = integer: object state {default: 1} selection = string: atom selection {default: all} amber = integer: generate AMBER rst file {default: 1;ON} label = string: label type ('ID' or 'index') {default: ID} fc = float: force constant for the dihedral angles {default: 10.0} chi = 0: Do not print chi angles (default) chi = 1: print chi1 dihedral angle (if exists) chi = 2: print chi1 and chi2 dihedral angles (if exists) (not implemented yet) SEE ALSO phipsi ''' # selectionからCalpha原子のIDリストを取得 chi = int(chi) caindex = [] cmd.iterate('bycalpha (%s)' % selection, 'caindex.append(ID)', space=locals()) # Calpha原子が属する残基ごとに処理を行う for ca in caindex: # resinameに残基名のみ取得 n_sele = "((byres ID %s) & name N)" % ca c_sele = "((byres ID %s) & name C)" % ca ca_sele = "((byres ID %s) & name CA)" % ca cb_sele = "((byres ID %s) & name CB)" % ca resiname_sele = [] cmd.iterate(ca_sele, "resiname_sele.append(resn)", space=locals()) resiname = str(resiname_sele[0]) if resiname == 'ILE' or resiname == 'VAL': cg_sele = "((byres ID %s) & name CG1)" % ca elif resiname == 'THR': cg_sele = "((byres ID %s) & name OG1)" % ca elif resiname == 'CYS' or resiname == 'CYX': cg_sele = "((byres ID %s) & name SG)" % ca else: cg_sele = "((byres ID %s) & name CG)" % ca cm_sele = "((neighbor (%s)) and not (byres (%s)))" % (n_sele, n_sele ) #前の残基のC np_sele = "((neighbor (%s)) and not (byres (%s)))" % (c_sele, c_sele ) #次の残基のN cmd.feedback("push") cmd.feedback("disable", "selector", "everything") cm_cnt = cmd.select("_pp_cm", cm_sele) n_cnt = cmd.select("_pp_n", n_sele) c_cnt = cmd.select("_pp_c", c_sele) ca_cnt = cmd.select("_pp_ca", ca_sele) cb_cnt = cmd.select("_pp_cb", cb_sele) cg_cnt = cmd.select("_pp_cg", cg_sele) np_cnt = cmd.select("_pp_np", np_sele) # 残基名+残基番号取得(ASP704みたいな) rname = [] cmd.iterate(ca_sele, "rname.append(resn+resi)", space=locals()) if (cm_cnt and n_cnt and ca_cnt and c_cnt): phi = cmd.get_dihedral("_pp_c", "_pp_ca", "_pp_n", "_pp_cm") else: phi = None if (n_cnt and ca_cnt and c_cnt and np_cnt): psi = cmd.get_dihedral("_pp_np", "_pp_c", "_pp_ca", "_pp_n") else: psi = None if (n_cnt and ca_cnt and cb_cnt and cg_cnt): chi1 = cmd.get_dihedral("_pp_cg", "_pp_cb", "_pp_ca", "_pp_n") else: chi1 = None atomdict = {} strings = [ "_pp_cm", "_pp_n", "_pp_c", "_pp_ca", "_pp_cb", "_pp_np", "_pp_cg" ] for i in strings: temp = cmd.identify(i) # tempが空リストでなければatomdictに追加 if temp: atomdict[i] = temp[0] # phi, psi用に制限を設ける # 引数でssが指定されている場合、その範囲になるよう設定 def phir2limit(x, sigma, ss): if ss == '': val = x - sigma if val <= -180.0: val = -180.0 return val elif ss == 'alpha': val = -80.0 return val elif ss == 'beta': val = -155.0 return val def phir3limit(x, sigma, ss): if ss == '': val = x + sigma if val >= 180.0: val = 180.0 return val elif ss == 'alpha': val = -50.0 return val elif ss == 'beta': val = -125.0 return val def psir2limit(x, sigma, ss): if ss == '': val = x - sigma if val <= -180.0: val = -180.0 return val elif ss == 'alpha': val = -55.0 return val elif ss == 'beta': val = 115.0 return val def psir3limit(x, sigma, ss): if ss == '': val = x + sigma if val >= 180.0: val = 180.0 return val elif ss == 'alpha': val = -25.0 return val elif ss == 'beta': val = 145.0 return val def r2limit(x, sigma): val = x - sigma if val <= -180.0: val = -180.0 return val def r3limit(x, sigma): val = x + sigma if val >= 180.0: val = 180.0 return val if phi is not None: print('''# {6} phi &rst iat= {0}, {1}, {2}, {3}, r1=-180.0, r2={4:.2f}, r3={5:.2f}, r4= 180.0, rk2= {7}, rk3= {7},\n/'''.format(int(atomdict['_pp_c']), int(atomdict['_pp_ca']), int(atomdict['_pp_n']), int(atomdict['_pp_cm']), phir2limit(phi, 10.0, ss), phir3limit(phi, 10.0, ss), str(rname[0]), float(fc))) if psi is not None: print('''# {6} psi &rst iat= {0}, {1}, {2}, {3}, r1=-180.0, r2={4:.2f}, r3={5:.2f}, r4= 180.0, rk2= {7}, rk3= {7},\n/'''.format(int(atomdict['_pp_np']), int(atomdict['_pp_c']), int(atomdict['_pp_ca']), int(atomdict['_pp_n']), psir2limit(psi, 10.0, ss), psir3limit(psi, 10.0, ss), str(rname[0]), float(fc))) if (chi > 0) and (chi1 is not None): print('''# {6} chi1 &rst iat= {0}, {1}, {2}, {3}, r1=-180.0, r2={4:.2f}, r3={5:.2f}, r4= 180.0, rk2= {7}, rk3= {7},\n/'''.format(int(atomdict['_pp_cg']), int(atomdict['_pp_cb']), int(atomdict['_pp_ca']), int(atomdict['_pp_n']), r2limit(chi1, 10.0), r3limit(chi1, 10.0), str(rname[0]), float(fc)))
def do_library(self): cmd = self.cmd pymol = cmd._pymol 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..."] 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 and n;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. (n;n & (%s))) &! r. 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. (n;c & (%s))) & !r. 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(string.lower(frag_type), frag_name) # 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.iterate("(%s and n;ca)" % src_sele, "stored.chain=chain") cmd.alter("(%s)" % frag_name, "chain=stored.chain") cmd.iterate("(%s and n;ca)" % src_sele, "stored.resi=resi") cmd.alter("(%s)" % frag_name, "resi=stored.resi") cmd.iterate("(%s and n;ca)" % src_sele, "stored.segi=segi") cmd.alter("(%s)" % frag_name, "segi=stored.segi") cmd.iterate("(%s and n;ca)" % src_sele, "stored.ss=ss") cmd.alter("(%s)" % frag_name, "ss=stored.ss") # move the fragment if (cmd.count_atoms("(%s and n;cb)" % frag_name) == 1) and ( cmd.count_atoms("(%s and n;cb)" % src_sele) == 1 ): cmd.pair_fit( "(%s and n;ca)" % frag_name, "(%s and n;ca)" % src_sele, "(%s and n;cb)" % frag_name, "(%s and n;cb)" % src_sele, "(%s and n;c)" % frag_name, "(%s and n;c)" % src_sele, "(%s and n;n)" % frag_name, "(%s and n;n)" % src_sele, ) else: cmd.pair_fit( "(%s and n;ca)" % frag_name, "(%s and n;ca)" % src_sele, "(%s and n;c)" % frag_name, "(%s and n;c)" % src_sele, "(%s and n;n)" % frag_name, "(%s and n;n)" % src_sele, ) # fix the carbonyl position... cmd.iterate_state(1, "(%s and n;o)" % src_sele, "stored.list=[x,y,z]") cmd.alter_state(1, "(%s and n;o)" % frag_name, "(x,y,z)=stored.list") if cmd.count_atoms("(%s and n;oxt)" % src_sele): cmd.iterate_state(1, "(%s and n;oxt)" % src_sele, "stored.list=[x,y,z]") cmd.alter_state(1, "(%s and n;oxt)" % frag_name, "(x,y,z)=stored.list") elif cmd.count_atoms("(%s and n;oxt)" % frag_name): # place OXT if no template exists angle = cmd.get_dihedral( "(%s and n;n)" % frag_name, "(%s and n;ca)" % frag_name, "(%s and n;c)" % frag_name, "(%s and n;o)" % frag_name, ) cmd.protect("(%s and n;o)" % frag_name) cmd.set_dihedral( "(%s and n;n)" % frag_name, "(%s and n;ca)" % frag_name, "(%s and n;c)" % frag_name, "(%s and n;oxt)" % frag_name, 180.0 + angle, ) cmd.deprotect(frag_name) # fix the hydrogen position (if any) if cmd.count_atoms("(elem h and bound_to (n;n and (%s)))" % frag_name) == 1: if cmd.count_atoms("(elem h and bound_to (n;n and (%s)))" % src_sele) == 1: cmd.iterate_state(1, "(elem h and bound_to (n;n and (%s)))" % src_sele, "stored.list=[x,y,z]") cmd.alter_state(1, "(elem h and bound_to (n;n and (%s)))" % frag_name, "(x,y,z)=stored.list") elif cmd.select(tmp_sele1, "(n;c and bound_to (%s and e;n))" % src_sele) == 1: # position hydro based on location of the carbonyl angle = cmd.get_dihedral( "(%s and n;c)" % frag_name, "(%s and n;ca)" % frag_name, "(%s and n;n)" % frag_name, tmp_sele1 ) cmd.set_dihedral( "(%s and n;c)" % frag_name, "(%s and n;ca)" % frag_name, "(%s and n;n)" % frag_name, "(%s and n;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. (n;c & (%s))) & !r. nme+nhh" % (src_sele, src_sele)): if cmd.count_atoms("n;c & (%s)" % (frag_name)) == 1: if self.c_cap == "amin": editor.attach_amino_acid("n;c & (%s)" % (frag_name), "nhh") elif self.c_cap == "nmet": editor.attach_amino_acid("n;c & (%s)" % (frag_name), "nme") if cmd.count_atoms("hydro & bound_to (n;n & bound_to (n;c & (%s)))" % frag_name): cmd.h_fix("n;n & bound_to (n;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. (n;n & (%s))) & !r. ace " % (src_sele, src_sele)): if cmd.count_atoms("n;n & (%s)" % (frag_name)) == 1: if self.n_cap == "acet": editor.attach_amino_acid("n;n & (%s)" % (frag_name), "ace") if cmd.count_atoms("hydro & bound_to (n;n & bound_to (n;c & (%s)))" % frag_name): cmd.h_fix("n;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 and n;ca and rep cartoon)" % src_sele) > 0 sticks = cmd.count_atoms("(%s and n;ca and 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) = result[result.keys()[0]] (phi, psi) = (int(10 * round(phi / 10)), int(10 * (round(psi / 10)))) key = (rot_type, phi, psi) if not self.dep_library.has_key(key): (phi, psi) = (int(20 * round(phi / 20)), int(20 * (round(psi / 20)))) key = (rot_type, phi, psi) if not self.dep_library.has_key(key): (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, "(n;N and (%s in (neighbor %s)))" % (bump_name, src_sele)) == 1) and ( cmd.select(tmp_sele2, "(n;C and (%s in %s))" % (bump_name, mut_sele)) == 1 ): cmd.bond(tmp_sele1, tmp_sele2) if (cmd.select(tmp_sele1, "(n;C and (%s in (neighbor %s)))" % (bump_name, src_sele)) == 1) and ( cmd.select(tmp_sele2, "(n;N and (%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 for a in lib: cmd.sculpt_iterate(bump_name, state=state) 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(0) cmd.unpick() cmd.feedback("pop")
cmd.iterate("(%s and id %d)"%(res_sele,b),"stored.names.append(name)") name_list.append(tuple(pymol.stored.names)) res_dict = {} for a in name_list: dihe = cmd.get_dihedral("(%s and name %s)"%(res_sele,a[0]), "(%s and name %s)"%(res_sele,a[1]), "(%s and name %s)"%(res_sele,a[2]), "(%s and name %s)"%(res_sele,a[3])) res_dict[a]=dihe if resn not in prot_dict: prot_dict[resn]=[] prot_dict[resn].append(res_dict) sc_dict = {} cmd.feedback('disable','selector','result') cmd.feedback('disable','executive','action') for fyle in glob("source/*"): cmd.load(fyle) cmd.remove("(het)") cmd.remove("(hydro or not alt '')") cmd.remove("(byres b>25)") # only use well-defined residues cmd.remove("(not (byres name ca))") cmd.remove("(not (byres name n))") cmd.remove("(not (byres name c))") cmd.refresh() measure_all_torsions("all",sc_dict) cmd.delete("all") #for a in sc_dict.keys():
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) try: cmd.set("suspend_updates", "1") # only necessary if multithreading... for a in m.atom: a.coord[0] += (random() - 0.5) * 0.1 a.coord[1] += (random() - 0.5) * 0.1 a.coord[2] += (random() - 0.5) * 0.1 cmd.load_model(m, "demo", 1) cmd.set("suspend_updates", "0") # only necessary if multithreading...
def do_library(self): cmd=self.cmd pymol=cmd._pymol 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 is None: key = rot_type lib = self.ind_library.get(key,None) if (lib is not None) and self.dep == 'dep': print(' Mutagenesis: no phi/psi, using backbone-independent rotamers.') if lib is not 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.feedback("pop")
def mcm(pose, mc_steps, SASA, randomize): ################################# MCM Parameters ########################## T = 300. # Temperature k = 0.0019872041 # Boltzmann constant angles_prob = [1/3, 1/3, 1/3] # probability to sample phi, psi or chi accepted = 0 ############################################################################ # first, last = pose_from_pdb(pose) if first or last: print('Starting MCM') from energy import minimize, set_sasa, get_sasa cmd.set('suspend_updates', 'on') cmd.feedback('disable', 'executive', 'everything') ##uncomment for debugging cmd.set('pdb_conect_all', 1) glyco_bonds = get_glyco_bonds(first, last) con_matrix = writer(glyco_bonds) # Remove previous pdb files prev_files = glob.glob('mcm_*.pdb') for prev_file in prev_files: os.remove(prev_file) # set all paramenters for sasa-energy computation if SASA: params, points, const = set_sasa(n=1000) ## randomize initial conformation if randomize: for i in range(len(con_matrix)-1): bond = con_matrix[i] angle_values = np.random.uniform(-180, 180, size=2) set_psi(pose, bond, angle_values[0]) set_phi(pose, bond, angle_values[1]) for i in range(6): set_chi(pose, bond) # minimize energy of starting conformation and save it NRG_old = minimize(pose, nsteps=5000, rigid_geometry=False) NRG_min = NRG_old cmd.save('mcm_%08d.pdb' % accepted) ## start MCM routine fd = open("mcm_log.txt", "w") print('# iterations remaining = %s' % (mc_steps)) for i in range(1, mc_steps+1): if i % (mc_steps//10) == 0: print('#remaining iterations = %s' % (mc_steps-i)) if True: sample_uniform(pose, con_matrix, angles_prob) NRG_new = minimize('tmp', nsteps=100, rigid_geometry=False) if SASA: solvatation_nrg = get_sasa(params, points, const, selection='all', probe=0)[0] NRG_new = NRG_new + solvatation_nrg if NRG_new < NRG_old: NRG_old = NRG_new fd.write('%8d%10.2f\n' % (accepted, NRG_new)) cmd.copy(pose, 'tmp') cmd.delete('tmp') cmd.save('mcm_%08d.pdb' % accepted) accepted += 1 else: delta = np.exp(-(NRG_new-NRG_old)/(T*k)) if delta > np.random.uniform(0, 1): NRG_old = NRG_new fd.write('%8d%10.2f\n' % (accepted, NRG_new)) cmd.copy(pose, 'tmp') cmd.delete('tmp') cmd.save('mcm_%08d.pdb' % accepted) accepted += 1 cmd.delete('tmp') if NRG_new < NRG_min: NRG_min = NRG_new cmd.save('mcm_min.pdb') fd.close() cmd.delete('all') print('Savings all accepted conformations on a single file') cmd.set('defer_builds_mode', 5) for i in range(0, accepted): cmd.load('mcm_%08d.pdb' % i, 'mcm_trace') cmd.save('mcm_trace.pdb', 'all', state=0) cmd.delete('all') cmd.load('mcm_trace.pdb') cmd.intra_fit('mcm_trace') print(' MCM completed') cmd.set('suspend_updates', 'off')
def mcm(pose, mc_steps, SASA, randomize): ################################# MCM Parameters ########################## T = 300. # Temperature k = 0.0019872041 # Boltzmann constant kT = k * T # probability to sample phi, psi or chi angles_prob = [1 / 3, 1 / 3, 1 / 3] accepted = 0 ########################################################################## # first, last = pose_from_pdb(pose) if first or last: print('Starting MCM') from energy import minimize, set_sasa, get_sasa sus_updates = cmd.get('suspend_updates') cmd.set('suspend_updates', 'on') # uncomment for debugging cmd.feedback('disable', 'executive', 'everything') pdb_conect = cmd.get('pdb_conect_all') cmd.set('pdb_conect_all', 1) glyco_bonds = get_glyco_bonds(first, last) con_matrix = writer(glyco_bonds) # Remove previous pdb files prev_files = glob.glob('mcm_*.pdb') for prev_file in prev_files: os.remove(prev_file) # set all paramenters for sasa-energy computation if SASA: params, points, const = set_sasa(n=1000) # randomize initial conformation if randomize: for i in range(len(con_matrix) - 1): bond = con_matrix[i] angle_values = np.random.uniform(-180, 180, size=2) set_psi(pose, bond, angle_values[0]) set_phi(pose, bond, angle_values[1]) for i in range(6): set_chi(pose, bond) # minimize energy of starting conformation and save it NRG_old = minimize(pose, nsteps=5000, rigid_geometry=False) NRG_min = NRG_old cmd.save('mcm_%08d.pdb' % accepted) # start MCM routine fd = open("mcm_log.txt", "w") print('# iterations remaining = %s' % (mc_steps)) for i in range(1, mc_steps + 1): if i % (mc_steps // 10) == 0: print('#remaining iterations = %s' % (mc_steps - i)) if True: sample_uniform(pose, con_matrix, angles_prob) NRG_new = minimize('tmp', nsteps=100, rigid_geometry=False) if SASA: solvatation_nrg = get_sasa(params, points, const, selection='all', probe=0)[0] NRG_new = NRG_new + solvatation_nrg if NRG_new < NRG_old: NRG_old = NRG_new fd.write('%8d%10.2f\n' % (accepted, NRG_new)) cmd.copy(pose, 'tmp') cmd.delete('tmp') cmd.save('mcm_%08d.pdb' % accepted) accepted += 1 else: delta = np.exp(-(NRG_new - NRG_old) / (kT)) if delta > np.random.uniform(0, 1): NRG_old = NRG_new fd.write('%8d%10.2f\n' % (accepted, NRG_new)) cmd.copy(pose, 'tmp') cmd.delete('tmp') cmd.save('mcm_%08d.pdb' % accepted) accepted += 1 cmd.delete('tmp') if NRG_new < NRG_min: NRG_min = NRG_new cmd.save('mcm_min.pdb') fd.close() cmd.delete('all') print('Savings all accepted conformations on a single file') de_builds = cmd.get('defer_builds_mode') cmd.set('defer_builds_mode', 5) for i in range(0, accepted): cmd.load('mcm_%08d.pdb' % i, 'mcm_trace') cmd.save('mcm_trace.pdb', 'all', state=0) cmd.delete('all') cmd.load('mcm_trace.pdb') cmd.intra_fit('mcm_trace') print('MCM completed') # restore settings cmd.set('suspend_updates', sus_updates) cmd.set('pdb_conect_all', pdb_conect) cmd.set('defer_builds_mode', de_builds)