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 load(): cmd.set("valence") r = 0 list = glob("pdb/*/*") (x, y, z) = (0, 0, 0) start = time.time() count = 1 scale = 100.0 for file in list: cmd.load(file, str(count), quiet=1) cmd.translate([x * scale, y * scale, z * scale], object=str(count)) # cmd.disable(str(count)) atoms = cmd.count_atoms() passed = time.time() - start print "%3d structures/%5.1f sec = %8.1f atom/sec over %6d atoms" % ( count, passed, atoms / passed, atoms) count = count + 1 if count > 100: break x = x + 1 if x > 7: x = 0 y = y + 1 if y > 7: y = 0 z = z + 1 if z > 9: y = 0 z = z + 1 cmd.zoom() cmd.set("sphere_mode", 1) cmd.show_as("spheres") cmd.rebuild() cmd.set("hash_max", 250)
def aver(settings): """ average pdb command :param settings: """ cmd.set('orthoscopic') if settings.config.get('all_states', 0): cmd.set('all_states') LOG.info("Load structure file %s" % settings.args.get('pdb')) try: cmd.load(settings.args.get('pdb')) except CmdException: LOG.error("Can't load %s", settings.args.get('pdb')) mypdb = os.path.splitext(os.path.basename(settings.args.get('pdb')))[0] cmd.hide('everything', mypdb) cmd.show('ribbon', mypdb) cmd.show('spheres', '%s and name CA' % mypdb) cmd.alter(mypdb, 'vdw=%.2f' % settings.config.get('vdwspheres_radius')) cmd.rebuild(mypdb, 'spheres') # Fit to the first state by default (which is the best one according to # aria order) objfit = avg_states(mypdb, object_sel=settings.args.get('sel'), first=settings.config.get('first'), last=settings.config.get('last'), newobj=settings.config.get('newobj'), fitverdict=settings.config.get('fit'), verb=settings.config.get('verb'), pairs=settings.config.get('pairs'), writefiles=settings.config.get('writefiles')) cmd.cartoon('putty', objfit) cmd.show('cartoon', objfit) cmd.spectrum('b', 'blue_white_red', objfit)
def displaySphere(self): try: cmd.delete(self.SphereDisplay) cmd.refresh() except: pass if self.Sphere != None: # Only display sphere in current state cmd.pseudoatom(self.SphereDisplay, pos=self.Sphere.Center, vdw=self.Sphere.Radius, color='purpleblue', state=cmd.get_state()) cmd.refresh() cmd.hide('nonbonded', self.SphereDisplay) cmd.refresh() cmd.show('spheres', self.SphereDisplay) cmd.refresh() cmd.set('sphere_transparency', 0.7, self.SphereDisplay) cmd.rebuild(self.SphereDisplay)
def zero_residues(sel1, offset=0, chains=0): offset = int(offset) # variable to store the offset stored.first = None # get the names of the proteins in the selection names = [ '(model %s and (%s))' % (p, sel1) for p in cmd.get_object_list('(' + sel1 + ')') ] if int(chains): names = [ '(%s and chain %s)' % (p, chain) for p in names for chain in cmd.get_chains(p) ] # for each name shown for p in names: # get this offset ok = cmd.iterate("first %s and polymer and n. CA" % p, "stored.first=resv") # don't waste time if we don't have to if not ok or stored.first == offset: continue # reassign the residue numbers #cmd.alter("%s" % p, "resi=str(int(resi)-%s)" % str(int(stored.first)-offset)) # update pymol cmd.rebuild()
def DisplayLigand(self): try: cmd.set("auto_zoom", 0) cmd.load(self.RefLigand, self.LigDisplay, state=self.State) cmd.refresh() # 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() cmd.translate(self.Translation,self.LigDisplay) cmd.refresh() cmd.zoom(self.LigDisplay) cmd.refresh() except: self.ErrorCode = 1 cmd.set("auto_zoom", self.auto_zoom) return self.ErrorCode
def load(): cmd.set("valence") r = 0 list = glob("pdb/*/*") (x,y,z)=(0,0,0) start = time.time() count = 1 scale = 100.0 for file in list: cmd.load(file,str(count),quiet=1) cmd.translate([x*scale,y*scale,z*scale],object=str(count)) # cmd.disable(str(count)) atoms = cmd.count_atoms() passed = time.time()-start print "%3d structures/%5.1f sec = %8.1f atom/sec over %6d atoms"%(count,passed,atoms/passed,atoms) count = count + 1 if count>100: break x = x + 1 if x>7: x = 0 y = y + 1 if y>7: y = 0 z = z + 1 if z>9: y = 0 z = z + 1 cmd.zoom() cmd.set("sphere_mode",1) cmd.as("spheres") cmd.rebuild() cmd.set("hash_max",250)
def data2q_res(mol='',data_file=''): """ usage: data2q_res <mol>, <data_file> where <mol> is the molecular object whose occupancy data you wish to modify and <data_file> is a file contain the data (one value for each residue) The format of <data_file> should be: chain resnum resname data or resnum resname data (i.e. "chain" is optional). Lines beginning with '#' are ignored as comments. """ # call the function to extract the data per residue from 'data_file' # alter 'mol' with it. from pymol import cmd # read the data file and extract the # data to the q_dict and res_dict dictionaries q_dict,res_dict = residue_data_extract(data_file) # make lists of chains and residues within the chains and sort them chain_list = q_dict.keys() chain_list.sort() for chain in chain_list: res_list = q_dict[chain].keys() res_list.sort() # now do the alteration of the occupancy (q) data for resnum in res_list: cmd.do("alter /%s//%s/%s/,q=%f" % (mol,chain,resnum,q_dict[chain][resnum])) # force a rebuild of the drawing cmd.rebuild()
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 renumber_residues(sel="polymer", start=1): """Renumber residues. Selection should be a single chain. Run from Pymol. See also this module for renumbering based on connectivity: https://pymolwiki.org/index.php/Renumber """ class gen_resi_cl: def __init__(self, start): self.prev_new_resi = start self.prev_old_resi = None def __call__(self, cur_old_resi): if self.prev_old_resi is None: ret = self.prev_new_resi else: if self.prev_old_resi != cur_old_resi: ret = self.prev_new_resi + 1 else: ret = self.prev_new_resi self.prev_old_resi = cur_old_resi self.prev_new_resi = ret print(ret, cur_old_resi) return ret space = dict(gen_resi=gen_resi_cl(start=start)) cmd.alter(sel, "resi=gen_resi(resi)", space=space) cmd.rebuild() cmd.sort()
def remap_residues(index_file, sel="polymer"): import pandas as pd from string import ascii_uppercase as ins df = pd.read_csv(index_file, dialect="excel-tab") gr_df = df.groupby("id_from") for chain, group in gr_df: ind = {} prev_to_ind = None i_ins = 0 for i_x, x in enumerate(group[["from_ind", "to_ind"]].itertuples(index=False)): item = tuple(str(_) for _ in tuple(x)) from_ind, to_ind = item ## runs of identical to_ind cause insertion codes if i_x > 0: if to_ind == prev_to_ind: to_ind = to_ind + ins[i_ins] i_ins += 1 else: i_ins = 0 if from_ind not in ind: ind[from_ind] = to_ind prev_to_ind = item[1] space = dict(ind_map=ind) cmd.alter("{} and chain {}".format(sel, chain), "resi=ind_map[resi]", space=space) cmd.rebuild() cmd.sort()
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 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 unhilightPolar(sel='all'): N = "elem N" # and (not name N)" O = "elem O" # and (not name O)" # want to inlude look BB atoms... S = "elem S" sel = sel + " and " + N + " or " + O + " or " + S cmd.alter(sel, "vdw=1.0") cmd.rebuild() cmd.hide('spheres', sel)
def useOccRadii(sel="all"): for a in cmd.get_model(sel).atom: q = a.q if q >= 3: print "shrik radius" q <- 0.1 cmd.alter("%s and resi %s and name %s"%(sel,a.resi,a.name),"vdw=%f"%(q)) cmd.rebuild()
def hilightPolar(sel='all'): N = "elem N"# and (not name N)" O = "elem O"# and (not name O)" # want to inlude look BB atoms... S = "elem S" sel = sel + " and " + N+" or "+O+" or "+S cmd.alter(sel,"vdw=0.3") cmd.rebuild() cmd.show('spheres',sel)
def useOccRadii(sel="all"): for a in cmd.get_model(sel).atom: q = a.q if q >= 3: print "shrik radius" q < -0.1 cmd.alter("%s and resi %s and name %s" % (sel, a.resi, a.name), "vdw=%f" % (q)) cmd.rebuild()
def stride2pymol(mol='', sel=''): """ usage: stride2pymol object, [selection] where the object name is required, but the selection is optional (defaults to all of the object). e.g. stride2pymol prot, i. 1-300 and c. a """ #Save the specified molecule (and optional selection sel) to a temporary #PDB format file and call stride_extract on it from pymol import cmd # map stride's secondary structure alphabet onto pymol's # strides definitions: # G = 3/10 helix # B = Bridge # C = coil # T = turn # H = helix # E = strand/sheet # create tmpfile from the selection name and the current time in seconds since the epoch ext = str(int(time.time())) tmpfile = mol + '.pdb_' + ext if sel: # make sure that selection forces the molecule name to be included in the selection # (i.e. is 'and'-ed with the rest of the selection) sel = mol + ' and ' + sel cmd.save(tmpfile, sel, 1, 'pdb') else: cmd.save(tmpfile, mol, 1, 'pdb') # run stride on the saved pdb file and read the standard output to extract the # data to the sec_dict and res_dict dictionaries sec_dict, res_dict = stride_extract(tmpfile) os.remove(tmpfile) # make lists of chains and residues within the chains and sort them chain_list = sec_dict.keys() chain_list.sort() for chain in chain_list: res_list = sec_dict[chain].keys() res_list.sort() # now do the alteration of the secondary structure. for resnum in res_list: cmd.do( "alter /%s//%s/%s,ss='%s'" % (mol, chain, resnum, stride_2_pymol[sec_dict[chain][resnum]])) # make sure that cartoon automatic is set for this molecule cmd.cartoon('automatic', mol) # force a rebuild of the drawing cmd.rebuild()
def ResizeSphere(self): self.SphereView.Set_Radius(self.SphereSize.get()) try: cmd.alter(self.SphereDisplay,'vdw=' + str(self.SphereView.Radius)) cmd.rebuild(self.SphereDisplay) cmd.refresh() except: self.queue.put(lambda: self.App.DisplayMessage(" ERROR: Could not resize the Sphere", 1)) self.queue.put(lambda: self.App.DisplayMessage(" The wizard will abort prematurely", 1)) self.Quit_Wizard()
def stride2pymol(mol='',sel=''): """ usage: stride2pymol object, [selection] where the object name is required, but the selection is optional (defaults to all of the object). e.g. stride2pymol prot, i. 1-300 and c. a """ #Save the specified molecule (and optional selection sel) to a temporary #PDB format file and call stride_extract on it from pymol import cmd # map stride's secondary structure alphabet onto pymol's # strides definitions: # G = 3/10 helix # B = Bridge # C = coil # T = turn # H = helix # E = strand/sheet # create tmpfile from the selection name and the current time in seconds since the epoch ext = str(int(time.time())) tmpfile=mol + '.pdb_' + ext if sel: # make sure that selection forces the molecule name to be included in the selection # (i.e. is 'and'-ed with the rest of the selection) sel = mol + ' and ' + sel cmd.save(tmpfile,sel,1,'pdb') else: cmd.save(tmpfile,mol,1,'pdb') # run stride on the saved pdb file and read the standard output to extract the # data to the sec_dict and res_dict dictionaries sec_dict,res_dict = stride_extract(tmpfile) os.remove(tmpfile) # make lists of chains and residues within the chains and sort them chain_list = sec_dict.keys() chain_list.sort() for chain in chain_list: res_list = sec_dict[chain].keys() res_list.sort() # now do the alteration of the secondary structure. for resnum in res_list: cmd.do("alter /%s//%s/%s,ss='%s'" % (mol,chain,resnum,stride_2_pymol[sec_dict[chain][resnum]])) # make sure that cartoon automatic is set for this molecule cmd.cartoon('automatic',mol) # force a rebuild of the drawing cmd.rebuild()
def _common_ss_alter(selection, ss_dict, ss_map, raw=''): ''' DESCRIPTION Shared code of 'dssp' and 'stride' functions. ''' if raw != 'ss': cmd.alter(selection, 'ss = ss_map.get(ss_dict.get((model,chain,resi)), "")', space={'ss_dict': ss_dict, 'ss_map': ss_map}) if raw != '': cmd.alter(selection, raw + ' = ss_dict.get((model,chain,resi), "")', space={'ss_dict': ss_dict}) cmd.rebuild(selection, 'cartoon')
def data2b_atom(mol='', data_file='', prop='b', quiet=0): """ DESCRIPTION Alters the B-factor data by atom. USAGE data2b_atom <mol>, <data_file> where <mol> is the molecular object whose B-factor data you wish to modify and <data_file> is a file contain the data (one value for each atom) The format of <data_file> should be: chain resi resn name data or resi resn name data or ID data (i.e. "chain" is optional if all atoms are in one chain). Lines beginning with '#' are ignored as comments. SEE ALSO data2b_res, data2q_atom, data2q_res """ b_dict = atom_data_extract(data_file) quiet = int(quiet) == 1 def b_lookup(chain, resi, name, ID, b): def _lookup(chain, resi, name, ID): if resi in b_dict[chain] and isinstance(b_dict[chain][resi], dict): return b_dict[chain][resi][name][0] else: # find data by ID return b_dict[chain][int(ID)][0] try: if not chain in b_dict: chain = '' b = _lookup(chain, resi, name, ID) if not quiet: print '///%s/%s/%s new: %f' % (chain, resi, name, b) except KeyError: if not quiet: print '///%s/%s/%s keeping: %f' % (chain, resi, name, b) return b stored.b = b_lookup cmd.alter(mol, '%s=stored.b(chain, resi, name, ID, %s)' % (prop, prop)) cmd.rebuild()
def _common_ss_alter(selection, ss_dict, ss_map, raw=''): ''' DESCRIPTION Shared code of 'dssp' and 'stride' functions. ''' if raw != 'ss': cmd.alter(selection, 'ss = ss_map.get(ss_dict.get((model,chain,resi)), "")', space={'ss_dict': ss_dict, 'ss_map': ss_map}) if raw != '': cmd.alter(selection, raw + ' = ss_dict.get((model,chain,resi), "")', space={'ss_dict': ss_dict}) cmd.cartoon('auto', selection) cmd.rebuild(selection, 'cartoon')
def zero_residues_sub(sel1, start=0, end=0, offset=0, chains=0): """ DESCRIPTION Renumbers the residues so that the given residue range starts at zero, or offset USAGE zero_residues_sub selection, start, end [, offset [, chains ]] EXAMPLES zero_residues_sub protName, 0, 10 # first residue is 0 zero_residues_sub protName, 0, 10, 5 # first residue is 5 zero_residues_sub protName, 0, 10, chains=1 # each chain starts at 0 zero_residues_sub * """ offset = int(offset) # variable to store the offset stored.first = None # get the names of the proteins in the selection names = [ '(model %s and (%s))' % (p, sel1) for p in cmd.get_object_list('(' + sel1 + ')') ] if int(chains): names = [ '(%s and chain %s)' % (p, chain) for p in names for chain in cmd.get_chains(p) ] # for each name shown for p in names: # get this offset ok = cmd.iterate("first %s and polymer and n. CA" % p, "stored.first=resv") # don't waste time if we don't have to #if not ok or stored.first == offset: if not ok: continue # reassign the residue numbers p = p + " and resi " + start + "-" + end cmd.alter("%s" % p, "resi=str(int(resi)-%s)" % str(int(start) - offset)) # update pymol cmd.rebuild()
def Display_BindingSite(self): auto_zoom = cmd.get("auto_zoom") cmd.set("auto_zoom", 0) self.Delete_BindingSite() try: if self.Vars.BindingSite.Type == 1: cmd.pseudoatom(self.BindingSiteDisplay, pos=self.Vars.BindingSite.Sphere.Center, vdw=self.Vars.BindingSite.Sphere.Radius, state=1) cmd.refresh() cmd.hide('everything', self.BindingSiteDisplay) cmd.refresh() cmd.show('spheres', self.BindingSiteDisplay) cmd.refresh() cmd.set('sphere_transparency', 0.7, self.BindingSiteDisplay) cmd.color('purpleblue', self.BindingSiteDisplay) cmd.refresh() elif self.Vars.BindingSite.Type == 2 and self.Vars.BindingSite.listClefts: self.Generate_CleftBindingSite() cmd.load(self.CleftTmpPath, self.BindingSiteDisplay, state=1) cmd.refresh() cmd.hide('everything', self.BindingSiteDisplay) cmd.refresh() cmd.show('mesh', self.BindingSiteDisplay) cmd.refresh() cmd.alter(self.BindingSiteDisplay, 'vdw=2.00') cmd.rebuild(self.BindingSiteDisplay) cmd.color('purpleblue', self.BindingSiteDisplay) cmd.refresh() # cmd.color('purpleblue', self.BindingSiteDisplay) # cmd.refresh() except: self.DisplayMessage(" ERROR: while displaying the binding-site", 2) cmd.set("auto_zoom", auto_zoom)
def ResizeSphere(self): self.SphereView.Set_Radius(self.SphereSize.get()) try: cmd.alter(self.SphereDisplay, 'vdw=' + str(self.SphereView.Radius)) cmd.rebuild(self.SphereDisplay) cmd.refresh() except: self.queue.put(lambda: self.App.DisplayMessage( " ERROR: Could not resize the Sphere", 1)) self.queue.put(lambda: self.App.DisplayMessage( " The wizard will abort prematurely", 1)) self.Quit_Wizard()
def _common_ss_alter(selection, ss_dict, ss_map, raw=""): """ DESCRIPTION Shared code of 'dssp' and 'stride' functions. """ if raw != "ss": cmd.alter( selection, 'ss = ss_map.get(ss_dict.get((model,chain,resi)), "")', space={"ss_dict": ss_dict, "ss_map": ss_map}, ) if raw != "": cmd.alter(selection, raw + ' = ss_dict.get((model,chain,resi), "")', space={"ss_dict": ss_dict}) cmd.rebuild(selection, "cartoon")
def data2b_res(mol='', data_file='', property='b', quiet=0): """ DESCRIPTION Alters the B-factor data by residue. USAGE data2b_res <mol>, <data_file> where <mol> is the molecular object whose B-factor data you wish to modify and <data_file> is a file contain the data (one value for each residue) The format of <data_file> should be: chain resi resn data or resi resn data or resi data (i.e. "chain" is optional). Lines beginning with '#' are ignored as comments. SEE ALSO data2b_atom, data2q_atom, data2q_res """ b_dict = residue_data_extract(data_file) quiet = int(quiet) == 1 def b_lookup(chain, resi, name, b): try: if chain in b_dict: b = b_dict[chain][resi][0] else: b = b_dict[''][resi][0] if not quiet: print '///%s/%s/%s new: %f' % (chain, resi, name, b) except KeyError: if not quiet: print '///%s/%s/%s keeping: %f' % (chain, resi, name, b) return b stored.b = b_lookup cmd.alter(mol, '%s=stored.b(chain, resi, name, %s)' % (property, property)) cmd.rebuild()
def assign_with_ksdssp(self): # Runs ksdssp. ksdssp_fp = self.pymod.ksdssp["exe_file_path"].get_value() input_filepath = os.path.join(self.pymod.structures_dirpath, self.pymod_element.get_structure_file()) dssptext = self.runKSDSSP(input_filepath, ksdssp_exe=ksdssp_fp) # Parses ksdssp's output, that is, an series of pdb format 'HELIX' and 'SHEET' record lines. dsspout = dssptext.split("\n") helices = set( ) # A set to store the sequence numbers of the residues in helical conformation. sheets = set( ) # A set to store the sequence numbers of the residues in sheet conformation. for line in dsspout: if line.startswith("HELIX"): new_residues_set = set( range(int(line[21:25]), int(line[33:37]) + 1)) helices.update(new_residues_set) elif line.startswith("SHEET"): new_residues_set = set( range(int(line[22:26]), int(line[33:37]) + 1)) sheets.update(new_residues_set) # Assigns to the PyMod element the observed secondaey structure observed using ksdssp. for residue in self.pymod_element.get_polymer_residues(): if residue.db_index in helices: self.assign_sec_str_to_residue(residue, "H") rsel = residue.get_pymol_selector() cmd.alter( rsel, "ss='H'") # Set the residue new conformation in PyMOL. elif residue.db_index in sheets: self.assign_sec_str_to_residue(residue, "S") rsel = residue.get_pymol_selector() cmd.alter( rsel, "ss='S'") # Set the residue new conformation in PyMOL. else: self.assign_sec_str_to_residue(residue, "L") rsel = residue.get_pymol_selector() cmd.alter( rsel, "ss='L'") # Set the residue new conformation in PyMOL. # Update in PyMOL. cmd.rebuild()
def DisplayLigand(self): try: cmd.load(self.pdbPath, self.LigDisplay, state=self.State) # Display the atoms spheres cmd.show('spheres', self.LigDisplay) cmd.alter(self.LigDisplay,'vdw=0.25') cmd.rebuild(self.LigDisplay) util.cbag(self.LigDisplay) cmd.translate(self.Translation,self.LigDisplay) cmd.zoom(self.LigDisplay) except: return 1 return 0
def data2b_res(mol='', data_file='', prop='b', quiet=0): """ DESCRIPTION Alters the B-factor data by residue. USAGE data2b_res <mol>, <data_file> where <mol> is the molecular object whose B-factor data you wish to modify and <data_file> is a file contain the data (one value for each residue) The format of <data_file> should be: chain resi resn data or resi resn data or resi data (i.e. "chain" is optional). Lines beginning with '#' are ignored as comments. SEE ALSO data2b_atom, data2q_atom, data2q_res """ b_dict = residue_data_extract(data_file) quiet = int(quiet) == 1 def b_lookup(chain, resi, name, b): try: if chain in b_dict: b = b_dict[chain][resi][0] else: b = b_dict[''][resi][0] if not quiet: print '///%s/%s/%s new: %f' % (chain, resi, name, b) except KeyError: if not quiet: print '///%s/%s/%s keeping: %f' % (chain, resi, name, b) return b stored.b = b_lookup cmd.alter(mol, '%s=stored.b(chain, resi, name, %s)' % (prop, prop)) cmd.rebuild()
def cbs(selection='all', first_color=2, quiet=1): ''' DESCRIPTION Color by segment ''' import itertools if isinstance(first_color, str) and first_color.endswith('s'): colors = get_color_family(first_color) col_it = itertools.cycle(colors) else: col_it = itertools.count(int(first_color)) segi_colors = dict() def callback(segi): if segi not in segi_colors: segi_colors[segi] = next(col_it) return segi_colors[segi] cmd.alter(selection, 'color = callback(segi)', space=locals()) cmd.rebuild()
def beautify_images(protein_name, residue_sets): cmd.delete("all") cmd.fetch(protein_name, async_=0) cmd.color( "0xFFFFFF" ) # colors the entire protein white (so that the predictions can be colored) cmd.hide("lines") cmd.hide("spheres") cmd.show("cartoon") sphere_size = f"vdw={SPHERE_SIZE}" # the size of the rendered sphere for res_set in residue_sets: cmd.color(res_set.color, res_set.selection_string) # colors annotated blue cmd.show("spheres", res_set.selection_string) cmd.alter(res_set.selection_string, sphere_size) # changes the sphere size cmd.rebuild() # rerenders the spheres to the new size # cmd.color(annotated.color, annotated.selection_string) # colors annotated blue # cmd.color(wrong.color, wrong.selection_string) # colors wrongly predicted red # cmd.color(correct.color, correct.selection_string) # colors correctly predicted green # cmd.show("spheres", annotated.selection_string) # cmd.show("spheres", correct.selection_string) # cmd.show("spheres", wrong.selection_string) # cmd.alter(wrong.selection_string, sphere_size) # changes the sphere size # cmd.alter(correct.selection_string, sphere_size) # cmd.alter(annotated.selection_string, sphere_size) # cmd.rebuild() # rerenders the spheres to the new size cmd.remove("resn hoh") # removes the HOH's from image cmd.orient(residue_sets[0].selection_string) cmd.zoom(complete=1) cmd.set("depth_cue", "0") # removes shadows of depth cmd.center(protein_name)
def alphaToAll(sel, col="b", forceRebuild=False): """ alphaToAll -- expand any property of the alpha carbons to all atoms in the residue PARAMS sel The selection or object (include "*" for all objects) to operate on. This will read the alpha carbon's "COL" property and expand that down to all atoms in the given residues in sel. col Any valid PyMOL property. For example, 'b' or 'q' or 'color', etc. DEFAULT: b, for B-factor as we most often overwrite that column forceRebuild If a color changes, this will rebuild the objects for us. For speed, we DEFAULT this to False. RETURNS None, just epxands the properties as dicsussed above. NOTES This script is useful for instances where we update the b-factor column for the alpha carbons and then want to expand that color to all atoms for smoother looking images. AUTHOR: Jason Vertrees, 2009. """ col = '(' + ','.join(col.split()) + ')' space = {'props': dict()} cmd.iterate('byca (%s)' % (sel), 'props[model,segi,chain,resi] = ' + col, space=space) cmd.alter(sel, col + ' = props.get((model,segi,chain,resi), ' + col + ')', space=space) if forceRebuild != False: cmd.rebuild(sel)
def displaySphere(self): try: cmd.delete(self.SphereDisplay) cmd.refresh() except: pass if self.Sphere != None: # Only display sphere in current state cmd.pseudoatom(self.SphereDisplay, pos=self.Sphere.Center, vdw=self.Sphere.Radius, color='purpleblue', state=cmd.get_state()) cmd.refresh() cmd.hide('nonbonded',self.SphereDisplay) cmd.refresh() cmd.show('spheres', self.SphereDisplay) cmd.refresh() cmd.set('sphere_transparency', 0.7, self.SphereDisplay) cmd.rebuild(self.SphereDisplay)
def data2b_atom(mol='',data_file=''): """ usage: data2b_atom <mol>, <data_file> where <mol> is the molecular object whose B-factor data you wish to modify and <data_file> is a file contain the data (one value for each atom) The format of <data_file> should be: chain resnum resname name data or resnum resname name data (i.e. "chain" is optional if all atoms are in one chain). Lines beginning with '#' are ignored as comments. """ # call the function to extract the data per atom from 'data_file' # alter 'mol' with it. from pymol import cmd # read the data file and extract the # data to the b_dict and res_dict dictionaries b_dict,res_dict = atom_data_extract(data_file) # make lists of chains and residues within the chains and sort them chain_list = b_dict.keys() chain_list.sort() for chain in chain_list: res_list = b_dict[chain].keys() res_list.sort() for resnum in res_list: atom_list = b_dict[chain][resnum].keys() # now do the alteration of the B-factor data for at in atom_list: cmd.do("alter /%s//%s/%s/%s/,b=%f" % (mol,chain,resnum,at,b_dict[chain][resnum][at])) # force a rebuild of the drawing cmd.rebuild()
def Add_VDW(object, radii=""): cmd.copy(object + "_vdw", object) cmd.alter(object + "_vdw and elem H", "vdw=1.09") radii = radii.lower() if radii == "cpk" or radii == "bondi": # retrieve the data (coords and atomtypes) ATOMTYPES = [] CARTESIANS = [] atomslist = cmd.get_model(object + "_vdw") for i in range(0, len(atomslist.atom)): ATOMTYPES.append(atomslist.atom[i].symbol) CARTESIANS.append(atomslist.atom[i].coord) for i in range(0, len(ATOMTYPES)): atomid = i + 1 # careful, pymol numbering starts at 1, but list starts at 0 cmd.alter( "%s_vdw & id %s" % (object, atomid), "vdw=%.2f" % atomicModelRadius(ATOMTYPES, CARTESIANS, radii, i)) cmd.rebuild() cmd.set("sphere_scale", 1, object + "_vdw") cmd.hide("nonbonded", object + "_vdw") cmd.hide("lines", object + "_vdw") cmd.hide("sticks", object + "_vdw") cmd.set("sphere_transparency", 0.7, object + "_vdw")
def make_post_fusion_f(): bu_pdb = "3rrr.pdb1.gz" id_pdb = bu_pdb.split(".")[0] fasta = id_pdb + "_f.fasta" pdb = id_pdb + "_f.pdb" cmd.reinitialize() cmd.load(bu_pdb, "bu") for chain, chain1, chain2 in (("X", "A", "B"), ("Y", "C", "D"), ("Z", "E", "F")): cmd.alter("chain {}+{}".format(chain1, chain2), "chain='{}'".format(chain)) cmd.rebuild() renumber_residues("polymer and chain {}".format(chain)) cmd.rebuild() for chain, chain0 in (("F", "X"), ("E", "Y"), ("D", "Z")): cmd.alter("chain {}".format(chain0), "chain='{}'".format(chain)) cmd.rebuild() cmd.create(chain, "bu and chain {}".format(chain)) cmd.rebuild() cmd.delete("bu") cmd.rebuild() cmd.save(fasta, "polymer", format="fasta") cmd.save(pdb, "polymer", format="pdb")
def alphaToAll(sel, col="b",forceRebuild=False): """ alphaToAll -- expand any property of the alpha carbons to all atoms in the residue PARAMS sel The selection or object (include "*" for all objects) to operate on. This will read the alpha carbon's "COL" property and expand that down to all atoms in the given residues in sel. col Any valid PyMOL property. For example, 'b' or 'q' or 'color', etc. DEFAULT: b, for B-factor as we most often overwrite that column forceRebuild If a color changes, this will rebuild the objects for us. For speed, we DEFAULT this to False. RETURNS None, just epxands the properties as dicsussed above. NOTES This script is useful for instances where we update the b-factor column for the alpha carbons and then want to expand that color to all atoms for smoother looking images. AUTHOR: Jason Vertrees, 2009. """ col = '(' + ','.join(col.split()) + ')' space = {'props': dict()} cmd.iterate('byca (%s)' % (sel), 'props[model,segi,chain,resi] = ' + col, space=space) cmd.alter(sel, col + ' = props.get((model,segi,chain,resi), ' + col + ')', space=space) if forceRebuild != False: cmd.rebuild(sel)
def make_pre_fusion_f(): bu_pdb = "4jhw.pdb1.gz" id_pdb = bu_pdb.split(".")[0] fasta = id_pdb + "_f.fasta" pdb = id_pdb + "_f.pdb" chain_sel = "F" cmd.reinitialize() cmd.load(bu_pdb, "bu", 2) for chain, state in (("F", 2), ("E", 3), ("D", 4)): cmd.create(chain, "bu and chain {}".format(chain_sel), state, 1) cmd.alter(chain, "chain='{}'".format(chain)) cmd.rebuild() renumber_residues("{} and polymer and chain {}".format(chain, chain)) cmd.rebuild() cmd.delete("bu") cmd.rebuild() cmd.save(fasta, "polymer", state=1, format="fasta") cmd.save(pdb, "polymer", state=1, format="pdb")
def useTempRadii(sel="all"): for ii in range(30): radius = "%0.1f" % (float(ii + 1) / 10) cmd.alter(sel + " and b=" + radius, "vdw=" + radius) cmd.rebuild()
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_ss:",p,"displayed in putty mode - mesh as putty - limits=[%.4f,%.4f]"%(limits[0],limits[1]) else: cmd.set('mesh_color', color_m, p) print"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 atmtypenumbers(filename="atmtypenumbers", selection="all", united=1, quiet=1): """ DESCRIPTION Update VDW radii for the given selection, based on "atmtypenumbers" file. ARGUMENTS filename = str: path to "atmtypenumbers" file selection = str: atom selection to update {default: all} united = 1: Use united (implicit hydrogens) radii {default} united = 0: Use explicit radii EXAMPLE atmtypenumbers /tmp/MSMS-release/atmtypenumbers, united=0 """ import re united = int(united) quiet = int(quiet) if united and not quiet and cmd.count_atoms("(%s) and hydro" % (selection)): print(" Warning: united=1 but found hydrogens in selection") types = {} patterns = [] _true_func = lambda s: True def _get_match_func(p): if p == "*": return _true_func return re.compile(p.replace("_", " ") + "$").match try: handle = open(filename) except IOError: raise CmdException("can't open file '%s', please provide correct " "filename" % (filename)) for line in handle: fields = line.split() for i, field in enumerate(fields): if field.startswith("#"): fields = fields[:i] break if not fields: continue if fields[0] == "radius": vdwidx = 4 if united and len(fields) > 4 else 3 types[fields[1]] = float(fields[vdwidx]) continue patterns.append((_get_match_func(fields[0]), _get_match_func(fields[1]), types[fields[2]])) handle.close() def callback(resn, name, vdw): for p in patterns: if p[0](resn) and p[1](name): return p[2] if not quiet: print(" Warning: no match for '%s/%s'" % (resn, name)) return vdw cmd.alter(selection, "vdw = callback(resn, name, vdw)", space={"callback": callback}) cmd.rebuild(selection)
def expandRadii(delta=1.0, sel="all"): for a in cmd.get_model(sel).atom: r = float(a.vdw) + float(delta) cmd.alter("index " + ` a.index `, "vdw = " + ` r `) cmd.rebuild(sel, "spheres")
def ColorByDisplacementAll(objSel1, objSel2, super1='all', super2='all', doColor="True", doAlign="True", AlignedWhite='yes'): # First create backup copies; names starting with __ (underscores) are normally hidden by PyMOL tObj1, tObj2, aln = "__tempObj1", "__tempObj2", "__aln" if strTrue(doAlign): # Create temp objects cmd.create(tObj1, objSel1) cmd.create(tObj2, objSel2) # Align and make create an object aln which indicates which atoms were paired between the two structures # Super is must faster than align http://www.pymolwiki.org/index.php/Super cmd.super(tObj1 + ' and ' + str(super1), tObj2 + ' and ' + str(super2), object=aln) # Modify the original matrix of object1 from the alignment cmd.matrix_copy(tObj1, objSel1) else: # Create temp objects cmd.create(tObj1, objSel1) cmd.create(tObj2, objSel2) # Align and make create an object aln which indicates which atoms were paired between the two structures # Super is must faster than align http://www.pymolwiki.org/index.php/Super cmd.super(tObj1 + ' and ' + str(super1), tObj2 + ' and ' + str(super2), object=aln) # Modify the B-factor columns of the original objects, # in order to identify the residues NOT used for alignment, later on cmd.alter(objSel1 + " or " + objSel2, "b=-0.2") cmd.alter(tObj1 + " or " + tObj2, "chain='A'") cmd.alter(tObj1 + " or " + tObj2, "segi='A'") # Update pymol internal representations; one of these should do the trick cmd.refresh() cmd.rebuild() cmd.sort(tObj1) cmd.sort(tObj2) # Create lists for storage stored.alnAres, stored.alnBres = [], [] # Iterate over objects and get resi if AlignedWhite == 'yes': cmd.iterate(tObj1 + " and not " + aln, "stored.alnAres.append((resi, name))") cmd.iterate(tObj2 + " and not " + aln, "stored.alnBres.append((resi, name))") else: cmd.iterate(tObj1, "stored.alnAres.append((resi, name))") cmd.iterate(tObj2, "stored.alnBres.append((resi, name))") # Change the B-factors for EACH object displacementUpdateBAll(tObj1, stored.alnAres, tObj2, stored.alnBres) # Store the NEW B-factors stored.alnAnb, stored.alnBnb = [], [] # Iterate over objects and get b if AlignedWhite == 'yes': # Iterate over objects which is not aligned cmd.iterate(tObj1 + " and not " + aln, "stored.alnAnb.append(b)") cmd.iterate(tObj2 + " and not " + aln, "stored.alnBnb.append(b)") else: # Or Iterate over all objects with CA cmd.iterate(tObj1, "stored.alnAnb.append(b)") cmd.iterate(tObj2, "stored.alnBnb.append(b)") # Get rid of all intermediate objects and clean up cmd.delete(tObj1) cmd.delete(tObj2) cmd.delete(aln) # Assign the just stored NEW B-factors to the original objects print "Sooon ready. 1 more minute" for x in range(len(stored.alnAres)): cmd.alter(objSel1 + " and resi " + str(stored.alnAres[x][0]) + " and name " + str(stored.alnAres[x][1]), "b = " + str(stored.alnAnb[x])) for x in range(len(stored.alnBres)): cmd.alter(objSel2 + " and resi " + str(stored.alnBres[x][0]) + " and name " + str(stored.alnBres[x][1]), "b = " + str(stored.alnBnb[x])) cmd.rebuild() cmd.refresh() cmd.sort(objSel1) cmd.sort(objSel2) # Provide some useful information stored.allRMSDval = [] stored.allRMSDval = stored.alnAnb + stored.alnBnb print "\nColorByDisplacementAll completed successfully." print "The MAXIMUM Displacement is: " + str(max(stored.allRMSDval)) + " residue " + str(stored.alnAres[int(stored.allRMSDval.index(max(stored.allRMSDval)))]) if strTrue(doColor): # Showcase what we did # cmd.orient() # cmd.hide("all") cmd.show("sticks", objSel1 + " or " + objSel2) # Select the residues not used for alignment; they still have their B-factors as "-0.2" cmd.select("notUsedForAln", "b = -0.2") # White-wash the residues not used for alignment cmd.color("white", "notUsedForAln") # Select the residues not in both pdb files; they have their B-factors as "-0.01" cmd.select("ResNotInBothPDB", "b = -0.01") # White-wash the residues not used for alignment cmd.color("black", "ResNotInBothPDB") # Color the residues used for alignment according to their B-factors (Displacement values) #cmd.spectrum("b", 'rainbow', "((" + objSel1 + ") or (" + objSel2 +" )) and not notUsedForAln+ResNotInBothPDB") cmd.spectrum("b", 'rainbow', "((" + objSel1 + ") or (" + objSel2 + " )) and not (notUsedForAln or ResNotInBothPDB)") # Delete the selection of atoms not used for alignment # If you would like to keep this selection intact, # just comment "cmd.delete" line and # uncomment the "cmd.disable" line abowe. cmd.disable("notUsedForAln") cmd.delete("notUsedForAln") cmd.disable("ResNotInBothPDB") cmd.delete("ResNotInBothPDB") print "\nObjects are now colored by C-alpha displacement deviation." print "Blue is minimum and red is maximum..." print "White is those residues used in the alignment algorithm. Can be turned off in top of algorithm." print "Black is residues that does not exist in both files..."
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_ss:", p, "displayed in putty mode - mesh as putty - limits=[%.4f,%.4f]" % (limits[0], limits[1])) else: cmd.set('mesh_color', color_m, p) print("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 expandRadii(delta=1.0, sel='all'): for a in cmd.get_model(sel).atom: r = float(a.vdw) + float(delta) cmd.alter("index "+a.index,'vdw='+r) cmd.rebuild(sel,"spheres")
def useTempRadii(sel="all"): for ii in range(30): radius = "%0.1f"%(float(ii+1)/10) vdw = "%0.1f"%(float(ii+1)/5) cmd.alter(sel+" and b="+radius,"vdw="+vdw) cmd.rebuild()
def contractRadii(delta=1.0, sel='all'): for a in cmd.get_model(sel).atom: r = float(a.vdw) - float(delta) cmd.alter("index "+`a.index`,'vdw='+`r`) cmd.rebuild(sel,"spheres")