def normalmodes_prody(selection, cutoff=15, first=7, last=10, guide=1, prefix='prody', states=7, factor=-1, quiet=1): ''' DESCRIPTION Anisotropic Network Model (ANM) analysis with ProDy. Based on: http://www.csb.pitt.edu/prody/examples/dynamics/enm/anm.html ''' try: import prody except ImportError: print('Failed to import prody, please add to PYTHONPATH') raise CmdException first, last, guide = int(first), int(last), int(guide) states, factor, quiet = int(states), float(factor), int(quiet) assert first > 6 if guide: selection = '(%s) and guide and alt A+' % (selection) tmpsele = cmd.get_unused_name('_') cmd.select(tmpsele, selection) f = StringIO(cmd.get_pdbstr(tmpsele)) conf = prody.parsePDBStream(f) modes = prody.ANM() modes.buildHessian(conf, float(cutoff)) modes.calcModes(last - first + 1) if factor < 0: from math import log natoms = modes.numAtoms() factor = log(natoms) * 10 if not quiet: print(' set factor to %.2f' % (factor)) for mode in range(first, last + 1): name = prefix + '%d' % mode cmd.delete(name) if not quiet: print(' normalmodes: object "%s" for mode %d' % (name, mode)) for state in range(1, states+1): xyz_it = iter(modes[mode-7].getArrayNx3() * (factor * ((state-1.0)/(states-1.0) - 0.5))) cmd.create(name, tmpsele, 1, state, zoom=0) cmd.alter_state(state, name, '(x,y,z) = xyz_it.next() + (x,y,z)', space=locals()) cmd.delete(tmpsele) if guide: cmd.set('ribbon_trace_atoms', 1, prefix + '*') cmd.show_as('ribbon', prefix + '*') else: cmd.show_as('lines', prefix + '*')
def load_cp2k_qmmm(filename, obj_name, qmsele_name): """ Load &QMMM section of CP2K input into selection N.B.: run "set retain_order, 1" command before loading QMMM object to PyMol to avoid atoms indices mismatch between PyMol and CP2K USAGE: load_cp2k_qmmm filename, obj_name, selection_name """ atcount=0 inp = open(filename, 'r') in_qmkind=0 for str in inp: if (in_qmkind): if (re.match("\s*&END", str)): in_qmkind=0 if (in_qmkind): str_mmindex=re_mmindex.match(str) if (str_mmindex): for id in str_mmindex.group(1).split(): if (atcount): cmd.select(qmsele_name, obj_name+" & ("+qmsele_name+" | "+"index "+id+")" ) atcount += 1 else: cmd.select(qmsele_name, obj_name+" & index "+id) atcount += 1 if (re.match('\s*&QM_KIND', str)): in_qmkind=1 print atcount, "atoms selected"
def chargeupdate(self): pos = cmd.select("tmpcharge",self.d.obj+" and resn ARG+LYS and name CA") neg = cmd.select("tmpcharge",self.d.obj+" and resn ASP+GLU and name CA") cmd.delete("tmpcharge") c = "Total Charge: %i"%(pos-neg) print c if self.gui: self.gui.charge.set(c)
def get_dehydrons(): cmd.delete('dehydrons') cmd.delete('DH_pairs') cmd.hide() angle = float(angle_value.get()) cutoff = float(dist_cutoff_value.get()) desolv = float(desolv_sphere.get()) min_wrappers = float(min_value.get()) selection = 'name n or name o and not resn hoh' hb = cmd.find_pairs("((byres "+selection+") and n. n)","((byres "+selection+") and n. o)",mode=1,cutoff=cutoff,angle=angle) # sort the list for easier reading hb.sort(lambda x,y:(cmp(x[0][1],y[0][1]))) print "------------------------------------------------\n----------------dehydron Results-----------------\n------------------------------------------------\n Donor | Aceptor | \nChain Residue | Chain Residue | # dehydrons" sel = [] wra = 0 for pairs in hb: cmd.iterate("%s and index %s" % (pairs[0][0], pairs[0][1]), 'stored.nitro = chain, resi, resn') # extracts the nitrogen cmd.iterate("%s and index %s" % (pairs[1][0], pairs[1][1]), 'stored.oxy = chain, resi, resn') # extracts the oxygen wrappers = cmd.select('wrap', '(((chain %s and name ca and resi %s) around %f) or ((chain %s and name ca and resi %s) around %f)) and (not ((neighbor name n*+o*) or (name n*+o*+h*)))' % (stored.nitro[0], stored.nitro[1], desolv, stored.oxy[0], stored.oxy[1], desolv)) #Identifies the putative dehydrons if wrappers < min_wrappers: wra = 1 cmd.distance('Dehydrons',"%s and index %s" % (pairs[0][0],pairs[0][1]),"%s and index %s" % (pairs[1][0],pairs[1][1])) print ' %s%7s%5d | %s%7s%5d |%7s' % (stored.nitro[0], stored.nitro[2], int(stored.nitro[1]), stored.oxy[0], stored.oxy[2], int(stored.oxy[1]), wrappers) if stored.nitro[1] not in sel: sel.append(stored.nitro[1]) if stored.oxy[1] not in sel: sel.append(stored.oxy[1]) if wra == 1: cmd.select('DH_pairs', 'resi %s' % ('+').join(sel)) cmd.show('lines', 'DH_pairs') cmd.disable('DH_pairs') cmd.hide('labels') cmd.delete('wrap') cmd.show('cartoon') cmd.show('dashes')
def colorize(): cmd.hide('(not (name C+CA+N+O))') cmd.spectrum('b', 'red_yellow_green', minimum='-1.0', maximum='1.0') cmd.select('missing', 'b = -2.0') cmd.color('white', 'missing') cmd.delete('missing')
def findSurfaceAtoms(selection="all", cutoff=2.5, quiet=1): """ DESCRIPTION Finds those atoms on the surface of a protein that have at least 'cutoff' exposed A**2 surface area. USAGE findSurfaceAtoms [ selection, [ cutoff ]] SEE ALSO findSurfaceResidues """ cutoff, quiet = float(cutoff), int(quiet) tmpObj = cmd.get_unused_name("_tmp") cmd.create(tmpObj, "(" + selection + ") and polymer", zoom=0) cmd.set("dot_solvent", 1, tmpObj) cmd.get_area(selection=tmpObj, load_b=1) # threshold on what one considers an "exposed" atom (in A**2): cmd.remove(tmpObj + " and b < " + str(cutoff)) selName = cmd.get_unused_name("exposed_atm_") cmd.select(selName, "(" + selection + ") in " + tmpObj) cmd.delete(tmpObj) if not quiet: print("Exposed atoms are selected in: " + selName) return selName
def fSumWMCFirst(molecule, SGNameAngle, chain, residue, MCNeighbour, DieElecMC, MCchargeC, MCchargeO, printMC): # print "First", MCNeighbour SumWMCFirst = 0.0 SGnameselect = "/" + SGNameAngle + "//" + "/" + "/SG" NBnameselect = "/" + molecule + "//" + chain + "/" + str(MCNeighbour) cmd.select("MC", NBnameselect) MCpdbstr = cmd.get_pdbstr("MC") MCsplit = MCpdbstr.split() residueName = MCsplit[3] # print NBnameselect, residueName # Mainchain C Cnameselect = "/" + molecule + "//" + chain + "/" + str(MCNeighbour) + "/C" ResDist = cmd.dist(residue + 'distFirstC', SGnameselect, Cnameselect) WMC = fWMC(MCchargeC, DieElecMC, ResDist) SumWMCFirst = SumWMCFirst + WMC if printMC == 'yes': print("MC C ", MCNeighbour, " ", MCchargeC, " ", DieElecMC, " ", ResDist, " ", WMC) # Mainchain O Onameselect = "/" + molecule + "//" + chain + "/" + str(MCNeighbour) + "/O" ResDist = cmd.dist(residue + 'distFirstO', SGnameselect, Onameselect) WMC = fWMC(MCchargeO, DieElecMC, ResDist) SumWMCFirst = SumWMCFirst + WMC if printMC == 'yes': print("MC O ", MCNeighbour, " ", MCchargeO, " ", DieElecMC, " ", ResDist, " ", WMC) cmd.delete(residue + 'distFirstC') cmd.delete(residue + 'distFirstO') cmd.delete("MC") return SumWMCFirst
def rc( selection = "all" ): """ tube coloring for large RNA comparisons """ cmd.bg_color( "white" ) cmd.hide( 'everything',selection ) cmd.color( 'red','resn rG+G+DG and '+selection ) cmd.color( 'forest','resn rC+C+DC and '+selection) cmd.color( 'orange','resn rA+A+DA and '+selection) cmd.color( 'blue','resn rU+U+DT+BRU and '+selection) cmd.select( 'backbone', " (name o1p+o2p+o3p+p+op1+op2+'c1*'+'c2*'+'c3*'+'c5*'+'o2*'+'o3*'+'o4*'+'o5*'+'c1*'+'c2*'+'c3*'+'c4*'+'o2*'+'o4*'+c1'+c2'+c3'+c5'+o2'+o3'+o4'+o5'+c1'+c2'+c3'+c4'+o2'+o4') and (not name c1+c2+c3+c4+c5+o2+o3+o4+o5) ") #for x in AllObj: #print x cmd.show( "cartoon", selection ) cmd.spectrum( "resi", "rainbow", selection+" and backbone" ) cmd.cartoon( "tube", "backbone and "+selection ) cmd.set( "cartoon_ring_mode", 0 ) cmd.set( "cartoon_ring_transparency", 0.0 ) cmd.set( "cartoon_tube_radius", 1.0 ) cmd.color( 'red','resn rG+G and name n1+c6+o6+c5+c4+n7+c8+n9+n3+c2+n1+n2 and '+selection) cmd.color( 'forest','resn rC+C and name n1+c2+o2+n3+c4+n4+c5+c6 and '+selection) cmd.color( 'orange','resn rA+A and name n1+c6+n6+c5+n7+c8+n9+c4+n3+c2 and '+selection) cmd.color( 'blue','resn rU+U and name n3+c4+o4+c5+c6+n1+c2+o2 and '+selection) cmd.delete('backbone')
def ccp4_pisa(filename): bond_types = [ ('h-bonds', 'h-bonds/bond', 'hb'), ('salt-bridges', 'salt-bridges/bond', 'sb'), ('ss-bonds', 'ss-bonds/bond', 'ss'), ('cov-bonds', 'cov-bonds/bond', 'cv') ] tree = ElementTree.parse(open(filename)) interfaces = tree.findall('//interface') result = [] for name, path, prefix in bond_types: allcontacts = [edge for edge in [parseInterface(i, path) for i in interfaces] if edge != None] allselections = [] for c in allcontacts: allselections.extend(createInterfaceSelection(c, prefix)) result.append(len(allselections) / 2) if len(allselections) > 0: try: cmd.select(name, " or ".join(allselections)) except: print(name, '\t', " or ".join(allselections)) print('selectPISAContacts found interfaces with', end=' ') for number, type in zip(result, bond_types): print(number, type[0], ",", end=' ')
def rx(): """ rhiju's favorite coloring of proteins, more details -- no cartoon; heavy backbone """ cmd.bg_color( "white" ) AllObj=cmd.get_names("all") for x in AllObj: #print(AllObj[0],x) print x cmd.hide( "line", x ) cmd.color( "white", x+" and elem C" ) cmd.color( "blue", x+" and elem N" ) cmd.color( "red", x+" and elem O" ) cmd.color( "yellow", x+" and elem S" ) cmd.spectrum( "resi", "rainbow", x+" and name CA+C" ) #cmd.show( "sticks", x +" and not elem H and not name C+N+O" ) cmd.select('backbone','name o+c+ca+n') cmd.show('sticks','not elem H') if not x.count( 'BACKBONE' ): cmd.create( x+"_BACKBONE", x+" and not element H and backbone" ) cmd.set('stick_radius', '0.5', "*BACKBONE" )
def selectAlignmentBlocks(alignFile, name1=None, name2=None): """usage: selectAlignment, [name1, [name2]] Defines two new selections based on the alignment given in alignFile. AlignFile is in the XML format used by CE and BioJava. If specified, the selections will be called name1 and name2. Otherwise the names will be taken from the alignment file. return the names of the two selections (sele_name1, sele_name2) """ align = Alignment(alignFile) if name1 is None: name1 = align.name1[:4] if name2 is None: name2 = align.name2[:4] blocks1 = align.getSelect1ByBlock() blocks2 = align.getSelect2ByBlock() selections = [] for blk in xrange(len(blocks1)): select1 = "%s and ( %s )" % (name1, blocks1[blk]) select2 = "%s and ( %s )" % (name2, blocks2[blk]) align1 = "sele_%s_%s" % (name1, blk) align2 = "sele_%s_%s" % (name2, blk) selections.append(align1) selections.append(align2) cmd.select(align1, select1) cmd.select(align2, select2) cmd.deselect() return selections
def make_objects(self,chain): for epitope in self.interest_epitope: if self.interest_epitope[epitope]: name = epitope selection = ",".join(str(x) for x in self.interest_epitope[epitope]) cmd.select("{}_{}".format(chain.lower(),name),"chain {} and resi {}".format(chain,selection)) cmd.group("chain_{}".format(chain),"{}_*".format(chain.lower()))
def from_file(selectionname, moleculename, csvfile): '''Create selections from a csv file, formatted like 1A0S,31,32,35,... 1AF6,1,2,3... ARGUMENTS: The name you want for your selection (if you want '1AF6.blar', this should be 'blar' The name of the molecule part of the group from which you're selecting (if it's '1AF6.blar', this should be 'blar') A csv reader RETURNS: Nothing''' for row in csvfile: groupname = row[0] try: end = row[1:].index('') except ValueError: end = len(row[1:]) selection = row[1:end] selectionstring = '(' +\ '|'.join(['i. ' + resi for resi in selection]) \ + ')' cmd.select(groupname + '.' + selectionname, groupname + '.' + moleculename + ' & ' + selectionstring)
def packing(pdb): "Derive mean packing density of pdb as pd.Series." cmd.delete('all') cmd.load(pdb) cmd.remove('solvent') # Only heavy atoms cmd.remove('hydro') # Compute SAS per atom cmd.set('dot_solvent', 1) cmd.get_area('all', load_b=1) cmd.select('interior', 'b = 0') counts = pd.Series(0, index=RADS) vest = pd.Series(0, index=RADS) # from biggest to smallest radius for r in RADS[::-1]: # Counting counts.loc[r] = cmd.select('extended', 'interior extend {}'.format(r)) cmd.remove('not extended') # moleculare area #cmd.set('dot_solvent', 0) vest[r] = cmd.get_area('all') # Results cvdens = counts / vest counts.index = ["{}_rawcount".format(i) for i in counts.index] vest.index = ["{}_volume estimate".format(i) for i in vest.index] cvdens.index = ["{}_cv density".format(i) for i in cvdens.index] return pd.concat(([counts, cvdens, vest]))
def main(): parser=argparse.ArgumentParser() parser.add_argument('-p', action='store', required=True, dest='pdbfile', help='pathfile is a textfile of name of pdb') parser.add_argument('-l', action='store', required=True, dest='loop', help='loop is an int number') inputs=parser.parse_args() pdbfile=inputs.pdbfile loop=int(inputs.loop) print "loop is %s "% loop dirname=os.getcwd()+'/interface_analyzer/pdbdata/'+pdbfile pdbfileselect=pdbfile.split('.') savefile=os.getcwd()+'/interface_analyzer/pdbdata/'+pdbfileselect[0]+'_antigen.pdb' print "remove antibody of complex,so can caculate the value of antigen sasa " pymol.finish_launching() if loop!=0: pymol.cmd.reinitialize() cmd.load(dirname) cmd.remove('hetatm') cmd.select('target1',pdbfileselect[0]) cmd.save(dirname,(('target1'))) cmd.delete('target1') cmd.remove('solvent') cmd.remove('hydrogens') cmd.remove('chain L+H') cmd.select('target',pdbfileselect[0]) cmd.save(savefile,(('target'))) cmd.delete(all) cmd.sync() cmd.quit() print "remove the antibody of complex have done"
def selectApolarProtons( name = None, hideother = False ): if name is None: name = "apolar_protons" polh = selectPolarProtons() cmd.select( name, 'symbol h and not %s' % polh ) # cmd.delete( polh ) # but why not keep it? if hideother: cmd.hide( 'everything', 'e. h and not %s' % name ) return name
def initial_representations(): """Configure the initial representations for the protein and the ligand""" cmd.hide('everything', 'all') cmd.show('cartoon', 'all') cmd.select('ligand', 'resn NFT') cmd.deselect() cmd.show("sticks", "ligand")
def PymolPutTable(table, selection): ''' # old - pymol_put_table # add a selection in PyMOL from a given table [pDynamoProject mainly] # obs: In pDynamo the index starts in number 0 ''' try: cmd.delete(selection) except: pass # selection that will be generated in the pymol selection_string = selection + ", index " n = 0 # n_limit = 0 # limit = len(table) for i in table: # selection_string = selection_string + "+" + str(i + 1) n = n + 1 # n_limit = n_limit + 1 # if n == 100: # # generates the pymol selection cmd.select(selection, selection_string) n = 0 # selection_string = selection + ", index " # # if n_limit == limit: # cmd.select(selection, selection_string) n = 0 selection_string = selection + ", index "
def selectAlignment(alignFile, name1=None, name2=None): """usage: selectAlignment, [name1, [name2]] Defines two new selections based on the alignment given in alignFile. AlignFile is in the XML format used by CE and BioJava. If specified, the selections will be called name1 and name2. Otherwise the names will be taken from the alignment file. return the names of the two selections (sele_name1, sele_name2) """ align = Alignment(alignFile) if name1 is None: name1 = align.name1[:4] if name2 is None: name2 = align.name2[:4] select1 = "%s and ( %s )" % (name1, align.getSelect1()) select2 = "%s and ( %s )" % (name2, align.getSelect2()) cmd.select("sele_" + name1, select1) cmd.select("sele_" + name2, select2) cmd.deselect() return ("sele_" + name1, "sele_" + name2)
def cartoonize(color, rep): """draw a cartoon representation of glycans""" stored.ResiduesNumber = [] cmd.iterate('name c1', 'stored.ResiduesNumber.append((resi))') resn_list = [int(i) for i in stored.ResiduesNumber] bonds = get_glyco_bonds(resn_list[0], resn_list[-1]+1) con_matrix = writer(bonds) #con_matrix = writer2(bonds) rings = find_rings(resn_list) rings_coords = get_ring_coords(resn_list, rings) bonds_coords = get_bonds_coords(resn_list, con_matrix) colors = get_colors_c1(resn_list, color) bonds_colors = get_bonds_colors(resn_list, con_matrix, color) cmd.set('suspend_updates', 'on') for state, coords in enumerate(rings_coords): obj = [] if rep == 'beads': radius_s = 1.8 radius_b = 0.18 obj = beads(obj, coords, colors[state], radius_s) obj = cylinder(obj, bonds_coords[state], bonds_colors[state], radius_b) else: if rep == 'cartoon': radius = 0.075 else: radius = 0.035 obj = hexagon(obj, coords, colors[state], rep, radius) obj = cylinder(obj, bonds_coords[state], bonds_colors[state], radius) cmd.load_cgo(obj,'cgo01', state+1) cmd.select('glycan', 'byres name C1') cmd.delete('glycan') cmd.delete('tmp') cmd.set('two_sided_lighting', 1) cmd.set('suspend_updates', 'off')
def rr(): """ rhiju's favorite coloring of RNA with 2' OH as spheres, bases as filled rings, and backbone as cartoon ribbons, rainbow colored from 5' to 3'. No hydrogens, white background. """ cmd.bg_color( "white" ) cmd.hide( 'everything' ) cmd.show('sticks','not elem H') cmd.color( 'red','resn rG+G+DG') cmd.color( 'forest','resn rC+C+DC') cmd.color( 'orange','resn rA+A+DA') cmd.color( 'blue','resn rU+U+DT+BRU') #cmd.set( 'cartoon_ring_color', 'red','resn rG+G+DG') #cmd.set( 'cartoon_ring_color', 'forest','resn rC+C+DC') #cmd.set( 'cartoon_ring_color', 'orange','resn rA+A+DA') #cmd.set( 'cartoon_ring_color', 'blue','resn rU+U+DT+BRU') #cmd.select('bases','name c2+c4+c5+c6+c8+n1+n2+n3+n4+n6+n7+n9+o2+o4+o6+n1p') #cmd.select('backbone', 'name o1p+o2p+o3p+p+c1*+c2*+c3*+c5*+o2*+o3*+o4*+o5*') #cmd.select('sugar', 'name c1*+c2*+c3*+c4*+o2*+o4*') AllObj=cmd.get_names("all") cmd.color( 'red','resn rG+G and name n1+c6+o6+c5+c4+n7+c8+n9+n3+c2+n1+n2') cmd.color( 'forest','resn rC+C and name n1+c2+o2+n3+c4+n4+c5+c6') cmd.color( 'orange','resn rA+A and name n1+c6+n6+c5+n7+c8+n9+c4+n3+c2') cmd.color( 'blue','resn rU+U and name n3+c4+o4+c5+c6+n1+c2+o2') cmd.select( 'backbone', " (name o1p+o2p+o3p+p+op1+op2+'c1*'+'c2*'+'c3*'+'c5*'+'o2*'+'o3*'+'o4*'+'o5*'+'c1*'+'c2*'+'c3*'+'c4*'+'o2*'+'o4*'+c1'+c2'+c3'+c5'+o2'+o3'+o4'+o5'+c1'+c2'+c3'+c4'+o2'+o4') and (not name c1+c2+c3+c4+c5+o2+o3+o4+o5) ") for x in AllObj: cmd.show( "cartoon", x ) cmd.spectrum( "count", "rainbow", x+" and backbone" ) #cmd.color( 'white', 'backbone' ) cmd.cartoon( "tube", "backbone" ) cmd.set( "cartoon_ring_mode", 3 ) cmd.set( "cartoon_ring_transparency", 0.0 ) cmd.set( "cartoon_tube_radius", 0.2 ) cmd.hide( "sticks", "backbone" ) cmd.delete('backbone') cmd.alter( "name o2*","vdw=0.5" ) cmd.show( "spheres", "name o2'+'o2*' and not name o2" ) cmd.show( "sticks", "name 'o2*'+'c2*'a" ) cmd.show( "sticks", "resn hoh" ) cmd.alter( "resn mg", "vdw=1.0") cmd.alter( "resn hoh", "vdw=0.5") cmd.show( "spheres", "resn mg+sr+co+zn+hoh and not elem H")
def read_siftp(filename): try: #first line in file contains averaged sift with open(filename, 'r') as f: siftline = f.readline() min_aa, sift = siftline.split(':') sift = sift.split(' ') print sift for interaction in range(9): selection = [] for index in range(len(sift[interaction::9])): if index == len(sift[interaction::9]) - 1: print len(sift[interaction::9]) print 'index',index, print 'interaction',sift[interaction::9][index] if sift[interaction::9][index].strip() != '0': if interaction == 8: print sift[interaction::9][index] print int(min_aa) + index print sift[index:index + 9] selection.append(str(int(min_aa)+index)) if len(selection) > 0: cmd.select ( InteractionButton[interaction]+'_'+InteractionName[interaction], 'resi ' + "+".join(selection) ) if interaction == 0: cmd.show ( 'sticks', InteractionButton[interaction]+'_'+InteractionName[interaction] ) cmd.remove ( 'hydro' ) print InteractionButton[interaction]+'_'+InteractionName[interaction], 'resi ' + "+".join(selection) del selection with open(filename) as f: f.readline() #print 'here we go' for line in f.readlines(): try: #print line resi= line.split()[0] fp = line.split()[1:] fp = ''.join(fp) #print resi,fp if fp != '000000000': #print 'yes',fp cmd.select('residue '+resi,'resi '+ resi) cmd.show('sticks','resi '+ resi) cmd.label('residue '+resi,'resi') else: #cmd.select('residue '+resi,'resi '+ resi) #cmd.label('residue '+resi,'"no"') #print 'no',fp pass except: pass except Exception, e: print "Failed to open file %s\n%s" % (filename, e)
def findSurfaceResidues(objSel="(all)", cutoff=2.5, doShow=False, verbose=True): """ findSurfaceResidues finds those residues on the surface of a protein that have at least 'cutoff' exposed A**2 surface area. PARAMS objSel (string) the object or selection in which to find exposed residues DEFAULT: (all) cutoff (float) your cutoff of what is exposed or not. DEFAULT: 2.5 Ang**2 asSel (boolean) make a selection out of the residues found RETURNS (list: (chain, resv ) ) A Python list of residue numbers corresponding to those residues w/more exposure than the cutoff. """ tmpObj="__tmp" cmd.create( tmpObj, objSel + " and polymer"); if verbose!=False: print "WARNING: I'm setting dot_solvent. You may not care for this." cmd.set("dot_solvent"); cmd.get_area(selection=tmpObj, load_b=1) # threshold on what one considers an "exposed" atom (in A**2): cmd.remove( tmpObj + " and b < " + str(cutoff) ) stored.tmp_dict = {} cmd.iterate(tmpObj, "stored.tmp_dict[(chain,resv)]=1") exposed = stored.tmp_dict.keys() exposed.sort() randstr = str(random.randint(0,10000)) selName = "exposed_atm_" + randstr if verbose!=False: print "Exposed residues are selected in: " + selName cmd.select(selName, objSel + " in " + tmpObj ) selNameRes = "exposed_res_" + randstr cmd.select(selNameRes, "byres " + selName ) if doShow!=False: cmd.show_as("spheres", objSel + " and poly") cmd.color("white", objSel) cmd.color("red", selName) cmd.delete(tmpObj) print exposed return exposed
def fNeighbourCount(molecule, Cysmolecule, chain, residue, DieElecSpheDist): nameselect = "(((/" + molecule + "//" + chain + " and not /" + molecule + "//" + chain + "/" + residue + ") or /" + molecule + "//" + chain + "/" + residue + "/N+CA+C+O) within " + str(DieElecSpheDist) + " of /" + Cysmolecule + "//" + "/" + "/SG) and not resn HOH" # print nameselect cmd.select(residue + "NC", nameselect) # Adding 1 for CB Neighbours = cmd.count_atoms(residue + "NC") + 1 cmd.delete(residue + "NC") return Neighbours
def load_selection_id(selection_name, selection_id_string): selection_id_string = selection_id_string.replace('"', '') selection_id_string = selection_id_string.replace('\'', '') selection_id_list = [res.split(".") for res in selection_id_string.split(",")] selection_string = " or ".join("(chain %s and resi %s)" % (chain, resi) for chain, resi in selection_id_list) print "Selection ids: %s" % selection_id_string print "Selection string: %s" % selection_string cmd.select(selection_name, selection_string)
def testPop(self): cmd.fragment("ala") cmd.select("src", "ala") # iterate across the 10 atoms in ala cnt = 0 while cmd.pop("tmp","src"): cnt+=1 self.assertEquals(cnt,10)
def get_positions_in_selection(sub, distance): cmd.do("select lig-def, resi %s" % sub) cmd.select("lig-around", "(byres (lig-def around %s))" % distance) cmd.select("lig-around-ca", "lig-around and name ca") cmd.do("stored.li = []") cmd.do("iterate (lig-around-ca), stored.li.append((resi, resn))") cmd.do("delete all") return stored.li
def do_select(self,name): # handle mouse selection callback if not sele_name in cmd.get_names('selections'): cmd.select(sele_name,'none') cmd.enable(sele_name) cmd.refresh_wizard()
def extra_fit(selection='(all)', reference=None, method='align', zoom=1, quiet=0, _self=cmd, **kwargs): ''' DESCRIPTION Like "intra_fit", but for multiple objects instead of multiple states. ARGUMENTS selection = string: atom selection of multiple objects {default: all} reference = string: reference object name {default: first object in selection} method = string: alignment method (command that takes "mobile" and "target" arguments, like "align", "super", "cealign" {default: align} ... extra arguments are passed to "method" SEE ALSO alignto, cmd.util.mass_align, align_all.py from Robert Campbell ''' zoom, quiet = int(zoom), int(quiet) sele_name = cmd.get_unused_name('_') cmd.select(sele_name, selection) # for speed models = cmd.get_object_list(sele_name) if reference is None: reference = models[0] models = models[1:] elif reference in models: models.remove(reference) else: cmd.select(sele_name, reference, merge=1) if cmd.is_string(method): if method in cmd.keyword: method = cmd.keyword[method][0] else: print('Unknown method:', method) raise CmdException for model in models: x = method(mobile='%s and model %s' % (sele_name, model), target='%s and model %s' % (sele_name, reference), **kwargs) if not quiet: if cmd.is_sequence(x): print('%-20s RMS = %8.3f (%d atoms)' % (model, x[0], x[1])) elif isinstance(x, float): print('%-20s RMS = %8.3f' % (model, x)) elif isinstance(x, dict) and 'RMSD' in x: natoms = x.get('alignment_length', 0) suffix = (' (%s atoms)' % natoms) if natoms else '' print('%-20s RMS = %8.3f' % (model, x['RMSD']) + suffix) else: print('%-20s' % (model,)) if zoom: cmd.zoom(sele_name) cmd.delete(sele_name)
def select_all(): previous_hand = None while True: hand = (yield) if hand and not previous_hand: cmd.select('all') elif previous_hand and not hand: cmd.select('none') previous_hand = hand
def create_subchain_object(pdbid, subchain): tempname = 'selection_{}.{}'.format(pdbid, subchain) cmd.select(tempname ,'m. {} and c. {}'.format( pdbid, subchain)) cmd.create('{}.{}'.format(pdbid,subchain), tempname) cmd.delete(tempname)
def runStride(self): """ """ # delete old results self.sel_obj_list = [] self.stride_rlt_dict = {} self.SSE_res_dict = {} self.SSE_sel_dict = {} ## self.SSE_res = { ## 'H':{}, 'G':{}, 'I':{}, ## 'E':{}, 'B':{}, 'b':{}, ## 'T':{}, 'C':{} ## } ## self.SSE_sel = { ## 'H':None, 'G':None, 'I':None, ## 'E':None, 'B':None, 'b':None, ## 'T':None, 'C':None ## } pdb_fn = None sel_name = None sel = self.pymol_sel.get() if len(sel) > 0: # if any pymol selection/object is specified all_sel_names = cmd.get_names('all') # get names of all selections if sel in all_sel_names: if cmd.count_atoms(sel) == 0: err_msg = 'ERROR: The selection %s is empty.' % (sel, ) print 'ERROR: %s' % (err_msg, ) tkMessageBox.showinfo(title='ERROR', message=err_msg) return False else: sel_name = sel ## # To make the plugin work in windows, I have to use ## # tempfile.makestemp() instead of ## # tempfile.NamedTemporaryFile() ## # Therefore, remember to clean up the mess later! ## #tmpf = tempfile.NamedTemporaryFile(suffix='.pdb') ## #pdb_fn = tmpf.name ## tmpf = tempfile.mkstemp(suffix='.pdb') ## pdb_os_fh, pdb_fn = tmpf # file os handle, file name ## os.close(pdb_os_fh) ## cmd.save(filename=pdb_fn,selection=sel) ## if VERBOSE: ## print 'Selection/object %s saved to tmp file %s.' % (sel, pdb_fn) # no selection/object with the input name is found # we assume either a single-word selector or # some other selection-expression is uesd else: print 'The selection/object you specified is not found.' print 'Your input will be interpreted as a selection-expression.' tmpsel = self.randomSeleName(prefix='your_sele_') cmd.select(tmpsel, sel) if cmd.count_atoms(tmpsel) == 0: cmd.delete(tmpsel) err_msg = 'ERROR: The selection %s is empty.' % (sel, ) print 'ERROR: %s' % (err_msg, ) tkMessageBox.showinfo(title='ERROR', message=err_msg) return False else: sel_name = tmpsel ## # To make the plugin work in windows, I have to use ## # tempfile.makestemp() instead of ## # tempfile.NamedTemporaryFile() ## # Therefore, remember to clean up the mess later! ## #tmpf = tempfile.NamedTemporaryFile(suffix='.pdb') ## #pdb_fn = tmpf.name ## tmpf = tempfile.mkstemp(suffix='.pdb') ## pdb_os_fh, pdb_fn = tmpf # file os handle, file name ## os.close(pdb_os_fh) ## cmd.save(filename=pdb_fn,selection=sel) ## cmd.delete(tmpsel) ## if VERBOSE: ## print 'Selection %s saved to %s.' % (sel, pdb_fn) else: # what structure do you want Stride to work on? err_msg = 'No PyMOL selection/object specified!' print 'ERROR: %s' % (err_msg, ) tkMessageBox.showinfo(title='ERROR', message=err_msg) return False # each object in the selection is treated as an independent struc objlist = cmd.get_object_list(sel_name) self.ss_asgn_prog = 'Stride' print 'Running %s ...' % (self.ss_asgn_prog, ) for objname in objlist: self.sel_obj_list.append('%s and %s' % (sel_name, objname)) self.runStrideOneObj(self.sel_obj_list[-1]) return True
import pymol from pymol import cmd # Input variables structure = '5VN3' # Clear pymol, get structure, and remove non-Env chains # gp41 = chain A, B, D # gp120 = chain G, I, J # CD4 = chains C, E, F # 17b = chains H, K, M and L, N, O cmd.delete('all') cmd.fetch(structure) #, type='pdb1') cmd.remove('c;C,E,F,H,K,M,L,N,O') cmd.set_name(structure, '5VN3_trimer') cmd.select('gp160', 'c;A,G') cmd.create(structure, 'gp160') # Read in RSA values from file d = {} with open('5VN3_RSA_and_SS.txt') as f: for (i, line) in enumerate(f): line = line.strip().split(',') site = line[0] RSA = line[3] if i == 0: assert site == 'site' assert RSA == 'RSA' else: site = int(site) d[site] = float(RSA)
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")
from pymol import cmd, stored cmd.load( "/Users/meghan/Documents/PhD/GitProjects/v6_2018_Network/CompStrDefns/CompPDBs/3SLT.pdb" ) cmd.hide("everything", "all") cmd.color("wheat", "all") cmd.select("Astrand0", "resi 1039-1052 & chain A ") cmd.color("white", "Astrand0") cmd.select("Astrand1", "resi 1056-1071 & chain A ") cmd.color("red", "Astrand1") cmd.select("Astrand2", "resi 1077-1092 & chain A ") cmd.color("orange", "Astrand2") cmd.select("Astrand3", "resi 1097-1112 & chain A ") cmd.color("purple", "Astrand3") cmd.select("Astrand4", "resi 1118-1134 & chain A ") cmd.color("yellow", "Astrand4") cmd.select("Astrand5", "resi 1140-1161 & chain A ") cmd.color("green", "Astrand5") cmd.select("Astrand6", "resi 1164-1185 & chain A ") cmd.color("cyan", "Astrand6") cmd.select("Astrand7", "resi 1192-1214 & chain A ") cmd.color("blue", "Astrand7")
def select_protein(): cmd.select('polymer.protein')
def muta(): ''' DESCRIPTION Creates an alignment of two proteins and superimposes them. Aligned residues that are different in the two (i.e. mutations) are highlighted and colored according to their difference in the BLOSUM90 matrix. Is meant to be used for similar proteins, e.g. close homologs or point mutants, to visualize their differences. USAGE color_by_mutation selection1, selection2 [,waters [,labels ]] ARGUMENTS obj1: object or selection obj2: object or selection waters: bool (0 or 1). If 1, waters are included in the view, colored differently for the both input structures. default = 0 labels: bool (0 or 1). If 1, the possibly mutated sidechains are labeled by their chain, name and id default = 0 EXAMPLE color_by_mutation protein1, protein2 SEE ALSO super ''' from pymol import stored, CmdException obj1 = "native_na" obj2 = "design_na" waters = 0 labels = 0 if cmd.count_atoms(obj1) == 0: print('%s is empty' % obj1) return if cmd.count_atoms(obj2) == 0: print('%s is empty' % obj2) return waters = int(waters) labels = int(labels) # align the two proteins aln = '__aln' # first, an alignment with 0 cycles (no atoms are rejected, which maximized the number of aligned residues) # for some mutations in the same protein this works fine). This is essentially done to get a # sequence alignment cmd.super(obj2, obj1, object=aln, cycles=0) # superimpose the the object using the default parameters to get a slightly better superimposition, # i.e. get the best structural alignment cmd.super(obj2, obj1) stored.resn1, stored.resn2 = [], [] stored.resi1, stored.resi2 = [], [] stored.chain1, stored.chain2 = [], [] # store residue ids, residue names and chains of aligned residues cmd.iterate(obj1 + ' and name CA and ' + aln, 'stored.resn1.append(resn)') cmd.iterate(obj2 + ' and name CA and ' + aln, 'stored.resn2.append(resn)') cmd.iterate(obj1 + ' and name CA and ' + aln, 'stored.resi1.append(resi)') cmd.iterate(obj2 + ' and name CA and ' + aln, 'stored.resi2.append(resi)') cmd.iterate(obj1 + ' and name CA and ' + aln, 'stored.chain1.append(chain)') cmd.iterate(obj2 + ' and name CA and ' + aln, 'stored.chain2.append(chain)') mutant_selection = '' non_mutant_selection = 'none or ' colors = [] # loop over the aligned residues for n1, n2, i1, i2, c1, c2 in zip(stored.resn1, stored.resn2, stored.resi1, stored.resi2, stored.chain1, stored.chain2): # take care of 'empty' chain names if c1 == '': c1 = '""' if c2 == '': c2 = '""' if n1 == n2: non_mutant_selection += '((%s and resi %s and chain %s) or (%s and resi %s and chain %s)) or ' % ( obj1, i1, c1, obj2, i2, c2) else: mutant_selection += '((%s and resi %s and chain %s) or (%s and resi %s and chain %s)) or ' % ( obj1, i1, c1, obj2, i2, c2) # get the similarity (according to the blosum matrix) of the two residues and c = getBlosum90ColorName(n1, n2) colors.append( (c, '%s and resi %s and chain %s and elem C' % (obj2, i2, c2))) if mutant_selection == '': print(' Error: No mutations found') raise CmdException # create selections cmd.select('mutations', mutant_selection[:-4]) cmd.select('non_mutations', non_mutant_selection[:-4]) cmd.select( 'not_aligned', '(%s or %s) and not mutations and not non_mutations' % (obj1, obj2)) # create the view and coloring cmd.hide('everything', '%s or %s' % (obj1, obj1)) cmd.show('cartoon', '%s or %s' % (obj2, obj1)) cmd.show( 'lines', '(%s or %s) and ((non_mutations or not_aligned) and not name c+o+n)' % (obj2, obj1)) cmd.show('sticks', '(%s or %s) and mutations and not name c+o+n' % (obj2, obj1)) cmd.color('white', 'elem C and non_mutations') cmd.color('cyan', 'elem C and mutations and %s' % obj1) cmd.color('gray', 'elem C and not_aligned') cmd.color('limon', 'chainA') cmd.util.cnc("all") for (col, sel) in colors: cmd.color(col, sel) cmd.hide('everything', '(hydro) and (%s or %s)' % (obj2, obj1)) cmd.center('%s or %s' % (obj2, obj1)) if labels: cmd.label('mutations and name CA', '"(%s-%s-%s)"%(chain, resi, resn)') if waters: cmd.set('sphere_scale', '0.1') cmd.show('spheres', 'resn HOH and (%s or %s)' % (obj2, obj1)) cmd.color('red', 'resn HOH and %s' % obj1) cmd.color('salmon', 'resn HOH and %s' % obj2) print(''' Mutations are highlighted in blue and red. All mutated sidechains of %s are colored blue, the corresponding ones from %s are colored on a spectrum from blue to red according to how similar the two amino acids are (as measured by the BLOSUM90 substitution matrix). Aligned regions without mutations are colored white. Regions not used for the alignment are gray. NOTE: There could be mutations in the gray regions that were not detected.''' % (obj2, obj1)) cmd.delete(aln) cmd.deselect() cmd.zoom("interface")
def formal_charges(selection="(all)", quiet=0, _self=cmd): cmd = _self result = 1 # assumes that hydogens are not present! # first, set all formal charges to zero cmd.alter(selection, "formal_charge=0") # next, flag all atoms so that we'll be able to detect what we miss cmd.flag(23, selection, 'set') # get the residue dictionary for formal charges if not hasattr(champ, 'formal_charge_dict'): from chempy.champ.formal_charges import formal_charge_dict champ.formal_charge_dict = formal_charge_dict # iterate through the residue dictionary matching each residue based on chemistry # and generating the expressions for reassigning formal charges alter_list = [] for resn in champ.formal_charge_dict.keys(): if cmd.select(tmp_sele1, "(%s) and resn %s" % (selection, resn)) > 0: entry = champ.formal_charge_dict[resn] for rule in entry: model = cmd.get_model(tmp_sele1) ch = Champ() model_pat = ch.insert_model(model) assn_pat = ch.insert_pattern_string(rule[0]) ch.pattern_clear_tags(model_pat) if ch.match_1v1_n(assn_pat, model_pat, 10000, 2) > 0: result = ch.pattern_get_ext_indices_with_tags(model_pat) for atom_tag in result[0]: # just iterate over atom tags if len(atom_tag[1]) == 1: # one and only one match tag = atom_tag[1][0] formal_charge = rule[1][tag] # the following expression both changes the formal charge and resets flag 23 alter_list.append([ atom_tag[0], "formal_charge=%d;flags=flags&-8388609" % formal_charge ]) if 1: # n-terminal amine # non-proline ch = Champ() model = cmd.get_model(selection) model_pat = ch.insert_model(model) assn_pat = ch.insert_pattern_string("[N;D1]<0>CC(=O)") ch.pattern_clear_tags(model_pat) if ch.match_1v1_n(assn_pat, model_pat, 10000, 2) > 0: result = ch.pattern_get_ext_indices_with_tags(model_pat) for atom_tag in result[0]: # just iterate over atom tags if len(atom_tag[1]) == 1: # one and only one match if atom_tag[1][0] == 0: # the following expression both changes the formal charge and resets flag 23 alter_list.append([ atom_tag[0], "formal_charge=1;flags=flags&-8388609" ]) # proline residues ch = Champ() model = cmd.get_model(selection) model_pat = ch.insert_model(model) assn_pat = ch.insert_pattern_string("C1CC[N;D2]<0>C1C(=O)") ch.pattern_clear_tags(model_pat) if ch.match_1v1_n(assn_pat, model_pat, 10000, 2) > 0: result = ch.pattern_get_ext_indices_with_tags(model_pat) for atom_tag in result[0]: # just iterate over atom tags if len(atom_tag[1]) == 1: # one and only one match if atom_tag[1][0] == 0: # the following expression both changes the formal charge and resets flag 23 alter_list.append([ atom_tag[0], "formal_charge=1;flags=flags&-8388609" ]) if 1: # c-terminal acid ch = Champ() model = cmd.get_model(selection) model_pat = ch.insert_model(model) assn_pat = ch.insert_pattern_string("NCC(=O<0>)[O;D1]<1>") ch.pattern_clear_tags(model_pat) if ch.match_1v1_n(assn_pat, model_pat, 10000, 2) > 0: result = ch.pattern_get_ext_indices_with_tags(model_pat) for atom_tag in result[0]: # just iterate over atom tags if len(atom_tag[1]) == 1: # one and only one match if atom_tag[1][0] == 1: # the following expression both changes the formal charge and resets flag 23 alter_list.append([ atom_tag[0], "formal_charge=-1;flags=flags&-8388609" ]) # now evaluate all of these expressions efficiently en-masse cmd.alter_list(selection, alter_list) # see if we missed any atoms missed_count = cmd.count_atoms("(" + selection + ") and flag 23") if missed_count > 0: if not quiet: # looks like we did, so alter the user print(" WARNING: %d atoms did not have formal charges assigned" % missed_count) result = 0 # remove the temporary selection we used to select appropriate residues cmd.delete(tmp_sele1) return result
def select_rna(): cmd.select('polymer.nucleic')
def amber99(selection="(all)", quiet=0, _self=cmd): cmd = _self result = 1 # first, set all parameters to zero cmd.alter(selection, "partial_charge=0") cmd.alter(selection, "elec_radius=0.0") cmd.alter(selection, "text_type=''") # next, flag all atoms so that we'll be able to detect what we miss cmd.flag(23, selection, 'set') # get the amber99 dictionary if not hasattr(champ, 'amber99_dict'): from chempy.champ.amber99 import amber99_dict champ.amber99_dict = amber99_dict # iterate through the residue dictionary matching each residue based on chemistry # and generating the expressions for reassigning formal charges alter_list = [] for resn in champ.amber99_dict.keys(): if cmd.select(tmp_sele1, "(%s) and resn %s" % (selection, resn)) > 0: entry = champ.amber99_dict[resn] for rule in entry: model = cmd.get_model(tmp_sele1) ch = Champ() model_pat = ch.insert_model(model) ch.pattern_detect_chirality(model_pat) assn_pat = ch.insert_pattern_string(rule[0]) ch.pattern_clear_tags(model_pat) if ch.match_1v1_n(assn_pat, model_pat, 10000, 2) > 0: result = ch.pattern_get_ext_indices_with_tags(model_pat) for atom_tag in result[0]: # just iterate over atom tags if len(atom_tag[1]) == 1: # one and only one match tag = atom_tag[1][0] prop_list = rule[1][tag] # the following expression both changes the formal charge and resets flag 23 alter_list.append([ atom_tag[0], "name='''%s''';text_type='''%s''';partial_charge=%f;elec_radius=%f;flags=flags&-8388609" % prop_list ]) # now evaluate all of these expressions efficiently en-masse cmd.alter_list(selection, alter_list) # see if we missed any atoms missed_count = cmd.count_atoms("(" + selection + ") and flag 23") if missed_count > 0: if not quiet: # looks like we did, so alter the user print(" WARNING: %d atoms did not have properties assigned" % missed_count) result = 0 # remove the temporary selection we used to select appropriate residues cmd.delete(tmp_sele1) return result
def visualize_in_pymol(plcomplex): """Visualizes the protein-ligand pliprofiler at one site in PyMOL.""" vis = PyMOLVisualizer(plcomplex) ##################### # Set everything up # ##################### pdbid = plcomplex.pdbid lig_members = plcomplex.lig_members chain = plcomplex.chain if config.PEPTIDES != []: vis.ligname = 'PeptideChain%s' % plcomplex.chain if config.INTRA is not None: vis.ligname = 'Intra%s' % plcomplex.chain ligname = vis.ligname hetid = plcomplex.hetid metal_ids = plcomplex.metal_ids metal_ids_str = '+'.join([str(i) for i in metal_ids]) ######################## # Basic visualizations # ######################## start_pymol(run=True, options='-pcq', quiet=not config.DEBUG) vis.set_initial_representations() cmd.load(plcomplex.sourcefile) current_name = cmd.get_object_list(selection='(all)')[0] write_message('Setting current_name to "%s" and pdbid to "%s\n"' % (current_name, pdbid), mtype='debug') cmd.set_name(current_name, pdbid) cmd.hide('everything', 'all') if config.PEPTIDES != []: cmd.select(ligname, 'chain %s and not resn HOH' % plcomplex.chain) else: cmd.select( ligname, 'resn %s and chain %s and resi %s*' % (hetid, chain, plcomplex.position)) write_message("Selecting ligand for PDBID %s and ligand name %s with: " % (pdbid, ligname), mtype='debug') write_message('resn %s and chain %s and resi %s*' % (hetid, chain, plcomplex.position), mtype='debug') # Visualize and color metal ions if there are any if not len(metal_ids) == 0: vis.select_by_ids(ligname, metal_ids, selection_exists=True) cmd.show('spheres', 'id %s and %s' % (metal_ids_str, pdbid)) # Additionally, select all members of composite ligands if len(lig_members) > 1: for member in lig_members: resid, chain, resnr = member[0], member[1], str(member[2]) cmd.select( ligname, '%s or (resn %s and chain %s and resi %s)' % (ligname, resid, chain, resnr)) cmd.show('sticks', ligname) cmd.color('myblue') cmd.color('myorange', ligname) cmd.util.cnc('all') if not len(metal_ids) == 0: cmd.color('hotpink', 'id %s' % metal_ids_str) cmd.hide('sticks', 'id %s' % metal_ids_str) cmd.set('sphere_scale', 0.3, ligname) cmd.deselect() vis.make_initial_selections() vis.show_hydrophobic() # Hydrophobic Contacts vis.show_hbonds() # Hydrogen Bonds vis.show_halogen() # Halogen Bonds vis.show_stacking() # pi-Stacking Interactions vis.show_cationpi() # pi-Cation Interactions vis.show_sbridges() # Salt Bridges vis.show_wbridges() # Water Bridges vis.show_metal() # Metal Coordination vis.refinements() vis.zoom_to_ligand() vis.selections_cleanup() vis.selections_group() vis.additional_cleanup() if config.DNARECEPTOR: # Rename Cartoon selection to Line selection and change repr. cmd.set_name('%sCartoon' % plcomplex.pdbid, '%sLines' % plcomplex.pdbid) cmd.hide('cartoon', '%sLines' % plcomplex.pdbid) cmd.show('lines', '%sLines' % plcomplex.pdbid) if config.PEPTIDES != []: filename = "%s_PeptideChain%s" % (pdbid.upper(), plcomplex.chain) if config.PYMOL: vis.save_session(config.OUTPATH, override=filename) elif config.INTRA is not None: filename = "%s_IntraChain%s" % (pdbid.upper(), plcomplex.chain) if config.PYMOL: vis.save_session(config.OUTPATH, override=filename) else: filename = '%s_%s' % (pdbid.upper(), "_".join( [hetid, plcomplex.chain, plcomplex.position])) if config.PYMOL: vis.save_session(config.OUTPATH) if config.PICS: vis.save_picture(config.OUTPATH, filename)
"\nThe following sites in the structure, but lacking data will be colored white: {0}" .format(', '.join(sites_lacking_data))) cmd.color( 'black', '{0} and resi {1}'.format(structure, '+'.join(sites_lacking_data))) # Show significant sites as spheres print("\nUsing a Q-value cutoff of {0}".format(Q_cutoff)) print( "\n{0} sites that evolve slower than expected with significant Q values: {1}" .format(len(sites_sig_slow[h]), ', '.join(sites_sig_slow[h]))) print( "\n{0} sites that evolve faster than expected with significant Q values: {1}" .format(len(sites_sig_fast[h]), ', '.join(sites_sig_fast[h]))) cmd.select( 'sites_sig_slow', '{0} and resi {1}'.format(structure, '+'.join(sites_sig_slow[h]))) cmd.select( 'sites_sig_fast', '{0} and resi {1}'.format(structure, '+'.join(sites_sig_fast[h]))) cmd.show('spheres', 'sites_sig_fast') cmd.show('spheres', 'sites_sig_slow') # Take a pictures of Env rotated 120 degrees relative to one another cmd.set_view("""\ 0.413237274, 0.018612767, -0.910427451,\ 0.910516560, 0.006436472, 0.413409144,\ 0.013554142, -0.999800861, -0.014289021,\ -0.000450239, -0.000266090, -364.028167725,\ 64.596366882, 39.767127991, -5.709826946,\ 224.197448730, 503.894958496, -20.000000000""")
def pairwise_dist(sel1, sel2, max_dist, output="N", output_filename="", sidechain="N", show="N"): """ usage: pairwise_dist sel1, sel2, max_dist, [output=S/P/N, [sidechain=N/Y, [show=Y/N]]] sel1 and sel2 can be any to pre-existing or newly defined selections max_dist: maximum distance in Angstrom between atoms in the two selections --optional settings: output: accepts Screen/Print/None (default N) sidechain: limits (Y) results to sidechain atoms (default N) show: shows (Y) individual distances in pymol menu (default=N) """ print "" cmd.delete("dist*") extra = "" if sidechain == "Y": extra = " and not name c+o+n" #builds models m1 = cmd.get_model(sel2 + " around " + str(max_dist) + " and " + sel1 + extra) m1o = cmd.get_object_list(sel1) m2 = cmd.get_model(sel1 + " around " + str(max_dist) + " and " + sel2 + extra) m2o = cmd.get_object_list(sel2) #defines selections cmd.select("__tsel1a", sel1 + " around " + str(max_dist) + " and " + sel2 + extra) cmd.select("__tsel1", "__tsel1a and " + sel2 + extra) cmd.select("__tsel2a", sel2 + " around " + str(max_dist) + " and " + sel1 + extra) cmd.select("__tsel2", "__tsel2a and " + sel1 + extra) cmd.select("IntAtoms_" + max_dist, "__tsel1 or __tsel2") cmd.select("IntRes_" + max_dist, "byres IntAtoms_" + max_dist) #controlers-1 if len(m1o) == 0: print "warning, '" + sel1 + extra + "' does not contain any atoms." return if len(m2o) == 0: print "warning, '" + sel2 + extra + "' does not contain any atoms." return #measures distances s = "" counter = 0 for c1 in range(len(m1.atom)): for c2 in range(len(m2.atom)): distance = math.sqrt( sum( map(lambda f: (f[0] - f[1])**2, zip(m1.atom[c1].coord, m2.atom[c2].coord)))) if distance < float(max_dist): s += "%s/%s/%s/%s/%s to %s/%s/%s/%s/%s: %.3f\n" % ( m1o[0], m1.atom[c1].chain, m1.atom[c1].resn, m1.atom[c1].resi, m1.atom[c1].name, m2o[0], m2.atom[c2].chain, m2.atom[c2].resn, m2.atom[c2].resi, m2.atom[c2].name, distance) counter += 1 if show == "Y": cmd.distance( m1o[0] + " and " + m1.atom[c1].chain + "/" + m1.atom[c1].resi + "/" + m1.atom[c1].name, m2o[0] + " and " + m2.atom[c2].chain + "/" + m2.atom[c2].resi + "/" + m2.atom[c2].name) #controler-2 if counter == 0: print "warning, no distances were measured! Check your selections/max_dist value" return #outputs if output == "S": print s if output == "P": f = open(output_filename, 'w') f.write("Number of distances calculated: %s\n" % (counter)) f.write(s) f.close() print "Results saved in %s" % output_filename print "Number of distances calculated: %s" % (counter) cmd.hide("lines", "IntRes_*") if show == "Y": cmd.show("lines", "IntRes_" + max_dist) cmd.deselect()
To dos: -remove the second monomer """ import pymol from pymol import cmd # Input variables structure = '1EA3' # name of structure n_eff_input_f = './results/prefs/neff_and_prefs.csv' # Fetch and display structure cmd.delete('all') cmd.fetch(structure) cmd.hide('everything') cmd.select('monomer', 'chain A') cmd.bg_color('white') cmd.show('cartoon', 'monomer') # Read in neff values neffs = {} with open(n_eff_input_f) as f: lines = f.readlines()[1:] for line in lines: line_elements = line.strip().split(',') site = int(line_elements[0]) neff = float(line_elements[-1]) neffs[site] = neff # Determine the min and max entropy to set the range of the color scale min_neff = min(neffs.values())
def select_alpha_carbons(sele, name='alpha_c'): cmd.select(name, selector.process(sele + " and n. ca")) return name
def morpheasy(source, target, source_state=0, target_state=0, name=None, refinement=5, quiet=1): ''' DESCRIPTION Morph source to target, based on sequence alignment USAGE morpheasy source, target [, source_state [, target_state [, name ]]] EXAMPLE fetch 1akeA 4akeA, async=0 extra_fit morpheasy 1akeA, 4akeA ''' try: from epymol import rigimol except ImportError: print('No epymol available, please use a "Incentive PyMOL" build') print('You may use "morpheasy_linear" instead') return from .editing import mse2met from .querying import get_selection_state # arguments source_state = int(source_state) target_state = int(target_state) refinement = int(refinement) quiet = int(quiet) if source_state < 1: source_state = get_selection_state(source) if target_state < 1: target_state = get_selection_state(target) # temporary objects # IMPORTANT: cmd.get_raw_alignment does not work with underscore object names! alnobj = cmd.get_unused_name('_aln') so_obj = cmd.get_unused_name('source') # see above ta_obj = cmd.get_unused_name('target') # see above so_sel = cmd.get_unused_name('_source_sel') ta_sel = cmd.get_unused_name('_target_sel') cmd.create(so_obj, source, source_state, 1) cmd.create(ta_obj, target, target_state, 1) mse2met(so_obj) mse2met(ta_obj) # align sequence cmd.align(ta_obj, so_obj, object=alnobj, cycles=0, transform=0, mobile_state=1, target_state=1) cmd.refresh() cmd.select(so_sel, '%s and %s' % (so_obj, alnobj)) cmd.select(ta_sel, '%s and %s' % (ta_obj, alnobj)) alnmap = dict(cmd.get_raw_alignment(alnobj)) alnmap.update(dict((v, k) for (k, v) in alnmap.items())) # copy source atom identifiers to temporary target idmap = dict() cmd.iterate(so_sel, 'idmap[model,index] = (segi,chain,resi,resn,name)', space={'idmap': idmap}) cmd.alter(ta_sel, '(segi,chain,resi,resn,name) = idmap[alnmap[model,index]]', space={ 'idmap': idmap, 'alnmap': alnmap }) # remove unaligned cmd.remove('%s and not %s' % (so_obj, so_sel)) cmd.remove('%s and not %s' % (ta_obj, ta_sel)) assert cmd.count_atoms(so_obj) == cmd.count_atoms(ta_obj) cmd.sort(so_obj) cmd.sort(ta_obj) # append target to source as 2-state morph-in object cmd.create(so_obj, ta_obj, 1, 2) # morph if name is None: name = cmd.get_unused_name('morph') rigimol.morph(so_obj, name, refinement=refinement, async=0) # clean up for obj in [alnobj, so_obj, so_sel, ta_obj, ta_sel]: cmd.delete(obj) return name
def apply(self): cmd=self.cmd if self.status==1: # find the name of the object which contains the selection src_frame = cmd.get_state() try: new_name = cmd.get_object_list(src_sele)[0] except IndexError: print(" Mutagenesis: object not found.") return if True: auto_zoom = cmd.get_setting_text('auto_zoom') cmd.set('auto_zoom',"0",quiet=1) if self.lib_mode!="current": # create copy with mutant in correct frame state = cmd.get_object_state(new_name) cmd.create(tmp_obj2, obj_name, src_frame, state) cmd.set_title(tmp_obj2, state, '') cmd.color(self.stored.identifiers[4], "?%s & elem C" % tmp_obj2) cmd.alter(tmp_obj2, 'ID = -1') # select backbone connection atoms cmd.select(tmp_sele1, 'neighbor ?%s' % (src_sele), 0) # remove residue and neighboring c-cap/n-cap (if any) cmd.remove("?%s | byres (?%s & " "(name N & resn NME+NHH | name C & resn ACE))" % (src_sele, tmp_sele1)) # create the merged molecule cmd.create(new_name, "?%s | ?%s" % (new_name, tmp_obj2), state, state) # now connect them cmd.select(tmp_sele2, '/%s/%s/%s/%s' % ((new_name,) + self.stored.identifiers[:3])) cmd.bond('?%s & name C' % (tmp_sele1), '?%s & name N' % (tmp_sele2), quiet=1) cmd.bond('?%s & name N' % (tmp_sele1), '?%s & name C' % (tmp_sele2), quiet=1) cmd.set_geometry('(?%s | ?%s) & name C+N' % (tmp_sele1, tmp_sele2), 3, 3) # make amide planer # fix N-H hydrogen position (if any exists) cmd.h_fix('?%s & name N' % (tmp_sele2)) # delete temporary objects/selections cmd.delete(tmp_sele1) cmd.delete(tmp_sele2) cmd.delete(tmp_obj2) self.clear() # and return to frame 1 cmd.frame(1) cmd.refresh_wizard() else: # create copy with conformation in correct state cmd.create(tmp_obj2,obj_name,src_frame,1) # remove existing c-cap in copy (if any) cmd.remove("byres (name N and (%s in (neighbor %s)) and resn NME+NHH)"% (new_name,src_sele)) cmd.remove("(%s) and name OXT"%src_sele) # remove existing n-cap in copy (if any) cmd.remove("byres (name C and (%s in (neighbor %s)) and resn ACE)"% (new_name,src_sele)) # save existing conformation on undo stack # cmd.edit("((%s in %s) and name ca)"%(new_name,src_sele)) cmd.push_undo("("+src_sele+")") # modify the conformation cmd.update(new_name,tmp_obj2) # cmd.unpick() cmd.delete(tmp_obj2) self.clear() # and return to frame 1 cmd.frame(1) cmd.refresh_wizard() cmd.set('auto_zoom',auto_zoom,quiet=1)
pymol.finish_launching() from pymol import cmd import sys import os ofile = open('lig_rmsd_rel.txt', 'w') native_complex = 'nat_relaxed.pdb' for file in sys.argv[2:]: if file != native_complex and file != 'natlig.pdb' and file != 'modlig.pdb': print file cmd.load(native_complex, 'native_complex') cmd.load(file, 'model_complex') cmd.align('native_complex', 'model_complex') cmd.select('natlig', 'native_complex and chain P') cmd.select('modlig', 'model_complex and chain C') cmd.save('natlig.pdb', 'natlig') cmd.save('modlig.pdb', 'modlig') cmd.delete('model_complex') cmd.delete('native_complex') cmd.load('natlig.pdb', 'native_ligand') cmd.load('modlig.pdb', 'model_ligand') cmd.alter('all', 'chain=""') cmd.alter('all', 'segi=""') cmd.select('natligca', 'native_ligand and name ca') cmd.select('modligca', 'model_ligand and name ca') rms_ca = cmd.rms_cur('natligca', 'modligca') ofile.write(file + ': ' + str(rms_ca) + '\n') cmd.delete('native_ligand') cmd.delete('model_ligand')
def __init__(self,_self=cmd): Wizard.__init__(self,_self) cmd=self.cmd if self.cmd.get_movie_length() > 0: raise pymol.wizarding.WizardError('Mutagenesis Wizard cannot be used with Movie') cmd.unpick() self.stored = pymol.Scratch_Storage() self.space = {'stored': self.stored} self.bump_scores = [] self.dep = default_dep self.ind_library = io.pkl.fromFile(os.environ['PYMOL_DATA']+ "/chempy/sidechains/sc_bb_ind.pkl") self.load_library() self.status = 0 # 0 no selection, 1 mutagenizing self.bump_check = 1 self.auto_center = 1 self.error = None self.object_name = None self.modes = [ 'current' ] self.mode = default_mode self.rep = default_rep self.hyd = default_hyd self.n_cap = default_n_cap self.c_cap = default_c_cap residues = list(self.ind_library.keys()) # could extent with additional fragments manually as below residues.extend(['GLY','ALA']) residues.extend(['HID','HIE','HIP']) residues.extend(['ARGN','LYSN','ASPH','GLUH']) residues.sort() res_copy = deepcopy(residues) for a in res_copy: residues.append('NT_'+a) residues.append('CT_'+a) self.modes.extend(residues) self.mode_label={} for a in self.modes: self.mode_label[a] = ""+a self.mode_label['current']="No Mutant" self.selection_mode = cmd.get_setting_int("mouse_selection_mode") cmd.set("mouse_selection_mode",1) smm = [] smm.append([ 2, 'Mutant', '' ]) smm.append([ 1, 'No change', 'cmd.get_wizard().set_mode("current")' ]) # smm.append([ 1, 'N-Term', [] ]) # smm.append([ 1, 'C-Term', [] ]) smm.append([ 0, '', '' ]) for a in self.modes: if a == 'current': pass elif a[0:3]=='NT_': pass # smm[2][2].append([ 1, self.mode_label[a[3:]], 'cmd.get_wizard().set_mode("'+a+'")']) elif a[0:3]=='CT_': pass # smm[3][2].append([ 1, self.mode_label[a[3:]], 'cmd.get_wizard().set_mode("'+a+'")']) else: smm.append([ 1, self.mode_label[a], 'cmd.get_wizard().set_mode("'+a+'")']) # group arg, lys, his, glu, asp for lst in [ smm ]: # [ smm, smm[2][2], smm[3][2] ]: for a in 'ARG','LYS','HID','GLU','ASP': ix = 0 start = 0 stop = 0 for b in lst: if start==0: if b[1][0:]==a: start = ix stop = ix + 1 elif b[1][0:3]==a[0:3] or ( b[1][0:2]==a[0:2] and a[0:2]=='HI' ): stop = ix + 1 ix = ix + 1 if start!=0 and stop!=0: slice = lst[start:stop] if a != 'HID': slice2 = [slice[0] ] + [ [0,'',''] ] + slice[1:] lst[start:stop] = [ [1, self.mode_label[a] + "... " , slice2 ] ] else: slice2 = [ slice[3] ] + [ [0,'',''] ] + slice[0:3] lst[start:stop] = [ [1, self.mode_label['HIS']+ "... ", slice2 ] ] self.menu['mode']=smm self.reps = [ 'lines', 'sticks', 'spheres', 'dots' ] self.rep_name = { 'lines' : "Show Lines", 'sticks' : "Show Sticks", 'spheres' : "Show Spheres", 'dots' : "Show Dots", } self.dep_name = { 'dep' : "Backbone Depen. Rotamers", 'ind' : "Backbone Indep. Rotamers" } self.hyd_name = { 'auto' : "Hydrogens: Current", 'keep' : "Hydrogens: Add & Retain", # 'polar' : "Polar Hydrogens", 'none' : "Hydrogens: Remove", } self.hyds = [ 'auto', 'keep', 'none' ] self.n_cap_name = { 'none' : 'Open', 'posi' : 'NH3+', 'acet' : 'Acetyl', } self.n_caps = [ 'none', 'posi', 'acet' ] self.c_cap_name = { 'none' : 'Open', 'nega' : 'COO-', 'amin' : 'Amine', 'nmet' : 'N-methyl', } self.c_caps = [ 'none', 'nega', 'amin', 'nmet' ] smm = [] smm.append([ 2, 'N-Cap', '' ]) for a in self.n_caps: smm.append([ 1, self.n_cap_name[a], 'cmd.get_wizard().set_n_cap("'+a+'")']) self.menu['n_cap']=smm smm = [] smm.append([ 2, 'C-Cap', '' ]) for a in self.c_caps: smm.append([ 1, self.c_cap_name[a], 'cmd.get_wizard().set_c_cap("'+a+'")']) self.menu['c_cap']=smm smm = [] smm.append([ 2, 'Hydrogens', '' ]) for a in self.hyds: smm.append([ 1, self.hyd_name[a], 'cmd.get_wizard().set_hyd("'+a+'")']) self.menu['hyd']=smm smm = [] smm.append([ 2, 'Representation', '' ]) for a in self.reps: smm.append([ 1, self.rep_name[a], 'cmd.get_wizard().set_rep("'+a+'")']) self.menu['rep']=smm self.deps = [ 'dep', 'ind' ] smm = [] smm.append([ 2, 'Rotamers', '' ]) for a in self.deps: smm.append([ 1, self.dep_name[a], 'cmd.get_wizard().set_dep("'+a+'")']) self.menu['dep']=smm if 'pk1' in cmd.get_names('selections'): cmd.select(src_sele,"(byres pk1)") cmd.unpick() cmd.enable(src_sele) self.status = 1 self.error = None self.do_library() cmd.refresh_wizard()
outname="1modo", head=0.5, tail=0.3, cut=0.5, headrgb="1.0, 0.0, 0.2", tailrgb="1.0, 0.0, 0.2") modevectors("3W32_A", "3_modo2_3W32_A", outname="2modo", head=0.5, tail=0.3, cut=0.5, headrgb="0.2, 0.0, 1.0", tailrgb="0.2, 0.0, 1.0") cmd.select("nlobe", "resi 1:95") cmd.select("clobe", "resi 96:150+178:277") cmd.select("aloop", "resi 151:177") cmd.select("HRD", "resi 133:135") cmd.select("K745", "resi 43") cmd.select("E762", "resi 60") cmd.color("limon", "nlobe") cmd.color("bluewhite", "clobe") cmd.color("deepsalmon", "aloop") cmd.set_view (\ '''0.734080613, 0.234402448, -0.637322366,\ 0.464893073, -0.857580781, 0.220061228,\ -0.494974792, -0.457829952, -0.738506436,\ -0.000087790, 0.000049151, -170.278991699,\ 28.221431732, 7.799482346, 55.593132019,\
def calc_psa3d(self, obj_list=None, include_SandP: bool = True, atom_to_remove=None): """ Help function to calculate the 3d polar surface area (3D-PSA) of molecules in Interface_Pymol for all the snapshots in a MD trajectory. (Contribution by Benjamin Schroeder) Parameters ---------- obj_list: list, optional list of pymol objects (Default = "cmpd1") include_SandP: bool, optional Set to False to exclude the S and P atoms from the calculation of the 3D-PSA. (Default = True) atom_to_remove: str, optional Single atom name of the atom to remove from the selection (Default = None). Useful if you want to include only S or only P in the calculation of the 3D-PSA. Returns ---------- obj_psa_dict: list Values correspond to mean, standard deviation, and median of the 3D-PSA calculated over the simulation time """ # IO if (obj_list is None): obj_list = cmd.get_names("objects") # Loop over objects obj_psa_dict = {} for obj in obj_list: cmd.frame(0) states = range(1, cmd.count_states(obj) + 1) # get all states of the object ##Loop over all states psa = [] for state in states: ###select all needed atoms by partialCSelection or element or H next to (O ,N) if atom_to_remove != None and isinstance(atom_to_remove, str): if include_SandP: select_string = "resn LIG and (elem N or elem O or elem S or elem P or (elem H and (neighbor elem N+O+S+P))) and " + obj + " and not name {}".format( atom_to_remove) #@carmen add: "or elem S" else: select_string = "resn LIG and (elem N or elem O or (elem H and (neighbor elem N+O))) and " + obj + " and not name {}".format( atom_to_remove) #@carmen add: "or elem S" else: if include_SandP: select_string = "resn LIG and (elem N or elem O or elem S or elem P or (elem H and (neighbor elem N+O+S+P))) and " + obj #@carmen add: "or elem S" else: select_string = "resn LIG and (elem N or elem O or (elem H and (neighbor elem N+O))) and " + obj #@carmen add: "or elem S" cmd.select("noh", select_string) ###calc surface area psa.append(float(cmd.get_area("noh", state=state))) ###gather data #obj_psa_dict.update({obj: psa}) obj_psa_dict = [ np.mean(psa) / 100, np.std(psa) / 100, np.median(psa) / 100 ] #/100 to have nm instead of Angstrom return obj_psa_dict
def _normalmodes(selection, cutoff, force, mass, first, last, choose, substruct, blocksize, exe, diag_exe, prefix, states, factor, clean, quiet, wiz=None): import tempfile, subprocess, os, shutil, sys from chempy import cpv cutoff, force = float(cutoff), float(force) first, last, blocksize = int(first), int(last), int(blocksize) clean, quiet = int(clean), int(quiet) exe = cmd.exp_path(exe) diag_exe = cmd.exp_path(diag_exe) tempdir = tempfile.mkdtemp() if not quiet: print(' normalmodes: Temporary directory is', tempdir) try: sele_name = cmd.get_unused_name('__pdbmat') except AttributeError: sele_name = '__pdbmat' try: filename = os.path.join(tempdir, 'mobile.pdb') commandfile = os.path.join(tempdir, 'pdbmat.dat') cmd.select(sele_name, '(%s) and not hetatm' % (selection)) cmd.save(filename, sele_name) f = open(commandfile, 'w') f.write('''! pdbmat file Coordinate FILENAME = %s MATRIx FILENAME = matrix.sdijb INTERACtion DISTance CUTOF = %.3f INTERACtion FORCE CONStant = %.3f Origin of MASS values = %s Output PRINTing level = 0 MATRix FORMat = BINA ''' % (filename, cutoff, force, mass.upper())) f.close() if not quiet: print(' normalmodes: running', exe, '...') if wiz is not None: wiz.message[1] = 'running pdbmat' cmd.refresh_wizard() process = subprocess.Popen([exe], cwd=tempdir, universal_newlines=True, stderr=subprocess.STDOUT, stdout=subprocess.PIPE) for line in process.stdout: if not quiet: sys.stdout.write(line) try: natoms = len( open(os.path.join(tempdir, 'pdbmat.xyzm')).readlines()) except Exception as e: print(e) natoms = cmd.count_atoms(sele_name) if natoms != cmd.count_atoms(sele_name): print('Error: pdbmat did not recognize all atoms') raise CmdException commandfile = os.path.join(tempdir, 'diagrtb.dat') f = open(commandfile, 'w') f.write('''! diagrtb file MATRIx FILENAME = matrix.sdijb COORdinates filename = %s Eigenvector OUTPut filename= diagrtb.eigenfacs Nb of VECTors required = %d EigeNVALues chosen = %s Type of SUBStructuring = %s Nb of residues per BLOck = %d Origin of MASS values = %s Temporary files cleaning = ALL MATRix FORMat = BINA Output PRINting level = 0 ''' % (filename, last, choose.upper(), substruct.upper(), blocksize, mass.upper())) f.close() exe = diag_exe if not quiet: print(' normalmodes: running', exe, '...') if wiz is not None: wiz.message[1] = 'running diagrtb' cmd.refresh_wizard() process = subprocess.Popen([exe], cwd=tempdir, universal_newlines=True, stderr=subprocess.STDOUT, stdout=subprocess.PIPE) for line in process.stdout: if not quiet: sys.stdout.write(line) eigenfacs, frequencies = parse_eigenfacs( os.path.join(tempdir, 'diagrtb.eigenfacs'), last) if wiz is not None: wiz.message[1] = 'generating objects' cmd.refresh_wizard() states = int(states) factor = float(factor) if factor < 0: factor = natoms**0.5 for mode in range(first, last + 1): name = prefix + '%d' % mode cmd.delete(name) if not quiet: print(' normalmodes: object "%s" for mode %d with freq. %.6f' % \ (name, mode, frequencies[mode-1])) for state in range(1, states + 1): cmd.create(name, sele_name, 1, state, zoom=0) cmd.alter_state( state, name, '(x,y,z) = cpv.add([x,y,z], cpv.scale(next(myit), myfac))', space={ 'cpv': cpv, 'myit': iter(eigenfacs[mode - 1]), 'next': next, 'myfac': factor * (state - (states + 1) / 2.0) }) # if CA only selection, show ribbon trace if natoms == cmd.count_atoms('(%s) and name CA' % sele_name): cmd.set('ribbon_trace_atoms', 1, prefix + '*') cmd.show_as('ribbon', prefix + '*') # store results if not hasattr(stored, 'nma_results'): stored.nma_results = [] stored.nma_results.append({ 'facs': eigenfacs, 'freq': frequencies, 'sele': sele_name, }) except OSError: print('Cannot execute "%s", please provide full path to executable' % (exe)) except CmdException as e: print(' normalmodes: failed!', e) finally: if clean: shutil.rmtree(tempdir) elif not quiet: print(' normalmodes: Working directory "%s" not removed!' % (tempdir)) # cmd.delete(sele_name) if wiz is not None: cmd.set_wizard_stack( [w for w in cmd.get_wizard_stack() if w != wiz])
def selectSSE(self, sel, sse): """ generate selector for selecting all residues having the given sse. return the selection name. """ #sel = self.pymol_sel.get() sel_list_chn = [] if VERBOSE: print '\nSelecting SSE %s ... \n' % (sse) for chn in self.SSE_res_dict[sel][sse]: # color one chain at a time if chn == ' ': chn_str = '-' else: chn_str = chn if VERBOSE: print 'Selecting SSE %s on chain %s ... \n' % (sse, chn) limit = 150 # color every 150 residues sel_name_chn = self.randomSeleName( prefix='%s_%s_%s_' % ('_'.join(sel.split()), chn_str, sse)) if len(self.SSE_res_dict[sel][sse][chn]) < limit: #sel_expr = '/%s//%s/%s/' % (sel,chn.strip(), '+'.join(self.SSE_res[sse][chn])) sel_expr = '(%s) and %s/%s/' % (sel, chn.strip(), '+'.join( self.SSE_res_dict[sel][sse][chn])) cmd.select(sel_name_chn, sel_expr) if VERBOSE: print 'select %s, %s' % (sel_name_chn, sel_expr) sel_list_chn.append(sel_name_chn) else: rn = len(self.SSE_res_dict[sel][sse][chn]) print 'total number of res with %s = %d' % (sse, rn) sz = int(math.ceil(rn / float(limit))) sel_list_seg = [] for i in xrange(sz): s, e = i * limit, min((i + 1) * limit, rn) print s, e #sel_expr = '/%s//%s/%s/' % (sel,chn.strip(), '+'.join(self.SSE_res[sse][chn][s:e])) sel_expr = '(%s) and %s/%s/' % (sel, chn.strip(), '+'.join( self.SSE_res_dict[sel][sse][chn][s:e])) sel_name_seg = self.randomSeleName( prefix='%s_%s_%s_tmp_' % ('_'.join(sel.split()), chn_str, sse)) cmd.select(sel_name_seg, sel_expr) if VERBOSE: print 'select %s, %s' % (sel_name_seg, sel_expr) sel_list_seg.append(sel_name_seg) sel_expr = ' or '.join(sel_list_seg) cmd.select(sel_name_chn, sel_expr) if VERBOSE: print 'select %s, %s' % (sel_name_chn, sel_expr) [cmd.delete(asel) for asel in sel_list_seg] sel_list_chn.append(sel_name_chn) if len(sel_list_chn) > 0: sel_name = self.randomSeleName( prefix='%s_%s_%s_' % ('_'.join(sel.split()), sse, self.ss_asgn_prog)) sel_expr = ' or '.join(sel_list_chn) cmd.select(sel_name, sel_expr) [cmd.delete(asel) for asel in sel_list_chn] else: print 'INFO: No residues are assigned to SSE \'%s\'.' % (sse, ) sel_name = None return sel_name
def normalmodes_prody(selection, cutoff=15, first=7, last=10, guide=1, prefix='prody', states=7, factor=-1, quiet=1): ''' DESCRIPTION Anisotropic Network Model (ANM) analysis with ProDy. Based on: http://www.csb.pitt.edu/prody/examples/dynamics/enm/anm.html ''' try: import prody except ImportError: print('Failed to import prody, please add to PYTHONPATH') raise CmdException first, last, guide = int(first), int(last), int(guide) states, factor, quiet = int(states), float(factor), int(quiet) assert first > 6 if guide: selection = '(%s) and guide and alt A+' % (selection) tmpsele = cmd.get_unused_name('_') cmd.select(tmpsele, selection) f = StringIO(cmd.get_pdbstr(tmpsele)) conf = prody.parsePDBStream(f) modes = prody.ANM() modes.buildHessian(conf, float(cutoff)) modes.calcModes(last - first + 1) if factor < 0: from math import log natoms = modes.numAtoms() factor = log(natoms) * 10 if not quiet: print(' set factor to %.2f' % (factor)) for mode in range(first, last + 1): name = prefix + '%d' % mode cmd.delete(name) if not quiet: print(' normalmodes: object "%s" for mode %d' % (name, mode)) for state in range(1, states + 1): xyz_it = iter(modes[mode - 7].getArrayNx3() * (factor * ((state - 1.0) / (states - 1.0) - 0.5))) cmd.create(name, tmpsele, 1, state, zoom=0) cmd.alter_state(state, name, '(x,y,z) = next(xyz_it) + (x,y,z)', space={ 'xyz_it': xyz_it, 'next': next }) cmd.delete(tmpsele) if guide: cmd.set('ribbon_trace_atoms', 1, prefix + '*') cmd.show_as('ribbon', prefix + '*') else: cmd.show_as('lines', prefix + '*')
def draw_memb(pdb_name): cmd.show_as("cartoon", "%s" % pdb_name) cmd.select("mem", "resn MEM") cmd.select("emb", "resn EMB") #cmd.hide("everything", "mem") #cmd.hide("everything", "emb") cmd.alter("emb", "vdw=1.5") cmd.rebuild() """cmd.set_view (\ 0.958278537, -0.025210002, 0.284718215,\ 0.285831660, 0.085169815, -0.954486012,\ -0.000186668, 0.996048152, 0.088822074,\ -0.000005720, 0.000001855, -301.575897217,\ 3.013955355, -3.607778311, -1.902338266,\ 241.575897217, 361.575897217, -20.000000000 )""" myspace = {"with_mem": [], "center_list": [], "normal_list": []} cmd.iterate("%s and resn MEM" % pdb_name, 'with_mem.append("MEM")', space=myspace) print(myspace["with_mem"]) if len(myspace["with_mem"]) == 0: print("No membrane") else: # set membrane plane length width = 100 # Read in center #myspace= {} cmd.iterate_state(1, "%s and resn MEM and name CNTR" % pdb_name, "center_list.append((x,y,z))", space=myspace) center_list = myspace["center_list"] center = XYZCoord(center_list[0][0], center_list[0][1], center_list[0][2]) # Read in normal position #myspace= {"normal_list": []} cmd.iterate_state(1, "%s and resn MEM and name NORM" % pdb_name, "normal_list.append((x, y, z))", space=myspace) normal_list = myspace["normal_list"] normalp = XYZCoord(normal_list[0][0], normal_list[0][1], normal_list[0][2]) # compute normal vector, leaflet thickness is 15A normal = subtract(normalp, center) normal = normalize(normal, 15) print(normal) # get upper and lower center point along normal upper_centerp = add(center, normal) lower_centerp = subtract(center, normal) print(upper_centerp) print(lower_centerp) # get a vector perpendicular (in membrane plane) to normal v1 = XYZCoord() v1.x = normal.z v1.y = normal.z v1.z = -normal.x - normal.y v1n = normalize(v1, width) # get vector perpendicular (in membrane plane) to v1 and normal v2 = XYZCoord() v2 = cross(normal, v1) v2n = normalize(v2, width) # get 4 points defining upper plane p1 = add(upper_centerp, v1n) p2 = add(upper_centerp, v2n) p3 = subtract(upper_centerp, v2n) p4 = subtract(upper_centerp, v1n) # get 4 points defining the lower plane q1 = add(lower_centerp, v1n) q2 = add(lower_centerp, v2n) q3 = subtract(lower_centerp, v2n) q4 = subtract(lower_centerp, v1n) with open("tmp.pml", "w+") as temp_pseudo: temp_pseudo.write("pseudoatom p1, pos=[" + str(p1.x) + ", " + str(p1.y) + ", " + str(p1.z) + "]\n") temp_pseudo.write("pseudoatom p2, pos=[" + str(p2.x) + ", " + str(p2.y) + ", " + str(p2.z) + "]\n") temp_pseudo.write("pseudoatom p3, pos=[" + str(p3.x) + ", " + str(p3.y) + ", " + str(p3.z) + "]\n") temp_pseudo.write("pseudoatom p4, pos=[" + str(p4.x) + ", " + str(p4.y) + ", " + str(p4.z) + "]\n") temp_pseudo.write("pseudoatom q1, pos=[" + str(q1.x) + ", " + str(q1.y) + ", " + str(q1.z) + "]\n") temp_pseudo.write("pseudoatom q2, pos=[" + str(q2.x) + ", " + str(q2.y) + ", " + str(q2.z) + "]\n") temp_pseudo.write("pseudoatom q3, pos=[" + str(q3.x) + ", " + str(q3.y) + ", " + str(q3.z) + "]\n") temp_pseudo.write("pseudoatom q4, pos=[" + str(q4.x) + ", " + str(q4.y) + ", " + str(q4.z) + "]\n\n") cmd.do("run tmp.pml") draw_plane("arbtr_up", "p1", "p2", "p3", "p4") draw_plane("arbtr_lo", "q1", "q2", "q3", "q4") # set transparency cmd.set("cgo_transparency", 0.5, "arbtr_lo") cmd.set("cgo_transparency", 0.5, "arbtr_up") # remove pseudoatoms cmd.delete("p1") cmd.delete("p2") cmd.delete("p3") cmd.delete("p4") cmd.delete("q1") cmd.delete("q2") cmd.delete("q3") cmd.delete("q4")
def testSelect(self): cmd.fragment("gly", "m1") NC = 2 # auto_number_selections=0 cmd.select("elem C") self.assertEquals(NC, cmd.count_atoms("sele")) self.assertEquals(0, cmd.get_setting_int("sel_counter")) # auto_number_selections=1 cmd.set('auto_number_selections', 1) cmd.set('sel_counter', 3) cmd.select("elem C") self.assertEquals(NC, cmd.count_atoms("sel04")) self.assertEquals(4, cmd.get_setting_int("sel_counter")) cmd.set('auto_number_selections', 1) cmd.select(None, "elem C") self.assertEquals(NC, cmd.count_atoms("sel05")) self.assertEquals(5, cmd.get_setting_int("sel_counter")) # name=None always numbers the selection cmd.set('auto_number_selections', 0) cmd.select(None, "elem C") self.assertEquals(NC, cmd.count_atoms("sel06")) self.assertEquals(6, cmd.get_setting_int("sel_counter")) # default cmd.select("foo", "elem C") self.assertEquals(NC, cmd.count_atoms("foo")) self.assertEquals(["foo"], cmd.get_names("selections", enabled_only=1)) # merge with non-existing, enable=0 cmd.delete('foo') cmd.select("foo", "elem C", 0, merge=1) self.assertEquals(NC, cmd.count_atoms("foo")) self.assertEquals([], cmd.get_names("selections", enabled_only=1)) # merge, enable=1 cmd.select("foo", "elem N", 1) self.assertEquals(1, cmd.count_atoms("foo")) self.assertEquals(["foo"], cmd.get_names("selections", enabled_only=1)) cmd.select("foo", "elem C", -1, merge=1) self.assertEquals(NC + 1, cmd.count_atoms("foo")) self.assertEquals(["foo"], cmd.get_names("selections", enabled_only=1)) cmd.select("foo", "elem O", -1, merge=2) self.assertEquals(NC + 2, cmd.count_atoms("foo")) self.assertEquals(["foo"], cmd.get_names("selections", enabled_only=1)) # merge, enable=0 cmd.select("foo", "elem N", 0) self.assertEquals(1, cmd.count_atoms("foo")) self.assertEquals([], cmd.get_names("selections", enabled_only=1)) cmd.select("foo", "elem C", -1, merge=1) self.assertEquals(NC + 1, cmd.count_atoms("foo")) self.assertEquals([], cmd.get_names("selections", enabled_only=1)) cmd.select("foo", "elem O", -1, merge=2) self.assertEquals(1, cmd.count_atoms("foo")) self.assertEquals([], cmd.get_names("selections", enabled_only=1)) # state cmd.create('m1', 'm1 & elem C', 1, 2) self.assertEquals(7, cmd.select('present')) self.assertEquals(7, cmd.select('present', state=1)) self.assertEquals(2, cmd.select('present', state=2)) self.assertEquals(0, cmd.select('present', state=3)) # domain cmd.select("foo", "elem C") cmd.select("bar", "name CA+N+O", domain="foo") self.assertEquals(1, cmd.count_atoms("bar"))
import sys import __main__ __main__.pymol_argv = ['pymol', '-qc'] # Pymol, quiet, noGUI import pymol pymol.finish_launching() from pymol import cmd filepath = sys.argv[1] cmd.load(filepath, "lig") cmd.select('lig1', 'state 1') cmd.alter('lig1', 'resi=str(int(resi)+701)') cmd.save(filepath, 'lig1')
def select_user_selection(sele, name="sele"): cmd.select(name, selector.process(sele))
from pymol import cmd, stored cmd.load( "/Users/meghan/Documents/PhD/GitProjects/v6_2018_Network/CompStrDefns/CompPDBs/5T4Y.pdb" ) cmd.hide("everything", "all") cmd.color("wheat", "all") cmd.select("Cstrand0", "resi 214-223 & chain C ") cmd.color("white", "Cstrand0") cmd.select("Cstrand1", "resi 301-314 & chain C ") cmd.color("red", "Cstrand1") cmd.select("Cstrand2", "resi 320-333 & chain C ") cmd.color("orange", "Cstrand2") cmd.select("Cstrand3", "resi 337-353 & chain C ") cmd.color("purple", "Cstrand3") cmd.select("Cstrand4", "resi 357-371 & chain C ") cmd.color("yellow", "Cstrand4") cmd.select("Cstrand5", "resi 422-435 & chain C ") cmd.color("green", "Cstrand5") cmd.select("Cstrand6", "resi 440-463 & chain C ") cmd.color("cyan", "Cstrand6") cmd.select("Cstrand7", "resi 470-496 & chain C ") cmd.color("blue", "Cstrand7") cmd.select("Cstrand8", "resi 502-525 & chain C ")
def loadInterfacePDB(file, name=None, native=None, wt=None): print " Loading interface PDB %s" % (file) if name is None: name = name = os.path.basename(file) if name.endswith('.pdb'): name = name[:-4] # Call Will's packing PDB loading function # Note: proteins will be cartoons, cavities will be spheres # Rosetta radii will be enabled name = loadPackingPDB(file, name, native) cavselname = name + "cavities" protselname = name + "protein" cmd.hide("lines", protselname) backbone_colorlist = ['green', 'yellow', 'violet', 'cyan', \ 'salmon', 'lime', 'slate', 'magenta', 'orange', 'marine', \ 'olive', 'forest', 'firebrick', 'chocolate' ] curr_bb_color = 0 carbon_colorlist = ['teal', 'wheat', 'grey', 'pink'] curr_carbon_color = 0 # Derive selections for the interface, color by chain cmd.select("interface", "none") cmd.select("heavy_interface", "none") selectPolarProtons("polar_protons") selectApolarProtons("apolar_protons") alphabet = list(('abcdefghijklmnopqrstuvwxyz').upper()) for letter in alphabet: chainname = "chain" + letter cmd.select(chainname, "chain %s and not hetatm and not symbol w" % (letter)) # Check whether any protein atoms exist with this chain ID # JK Later, put in a special "non-interface" case for L/H antibody chains if cmd.count_atoms("chain%s" % (letter)) > 0: interfacename = "interface" + letter cmd.select("not_this_chain", "not hetatm and not symbol w and not %s" % (chainname)) cmd.select( interfacename, "byres %s and (not_this_chain around 4.0)" % (chainname)) cmd.select("heavy_%s" % (interfacename), "%s and not apolar_protons" % (interfacename)) cmd.select("interface", "interface or %s" % (interfacename)) cmd.select("heavy_interface", "heavy_interface or heavy_%s" % (interfacename)) cmd.delete("not_this_chain") cmd.color(backbone_colorlist[curr_bb_color], chainname) curr_bb_color = curr_bb_color + 1 if (curr_bb_color == len(backbone_colorlist)): curr_bb_color = 0 colorCPK(interfacename, carbon_colorlist[curr_carbon_color]) curr_carbon_color = curr_carbon_color + 1 if (curr_carbon_color == len(carbon_colorlist)): curr_carbon_color = 0 cmd.color("white", "%s and polar_protons" % (interfacename)) else: cmd.delete(chainname) cmd.delete("apolar_protons") cmd.delete("polar_protons") # Show the interface in sticks, colored cpk #cmd.hide( "cartoon", "interface" ) cmd.show("sticks", "heavy_interface") cmd.zoom("interface") cmd.show( "cartoon", "(not interface) or byres(neighbor(interface)) or byres(neighbor(byres(neighbor(interface))))" ) # Show interface waters as small purple spheres cmd.select("interface_water", "(symbol w or resn HOH) and (interface around 8.0)") if cmd.count_atoms("interface_water") > 0: # Put the waters in a separate object, so that we can scale their radii newwatername = name + "waters" cmd.create(newwatername, "interface_water") cmd.remove("interface_water") cmd.color("purple", newwatername) cmd.show("spheres", newwatername) #cmd.set( "sphere_scale", 0.5, newwatername ) cmd.set("sphere_scale", 0.1, newwatername) else: cmd.delete("interface_water") # Show interface ligands as pink sticks cmd.select( "interface_hetero", "(not symbol w and not resn HOH) and (hetatm and not symbol w and not resn WSS) and (interface around 4.5)" ) if cmd.count_atoms("interface_hetero") > 0: cmd.color("pink", "interface_hetero") cmd.show("sticks", "interface_hetero") else: cmd.delete("interface_hetero") cmd.select("none") cmd.load(wt, "wt") cmd.create("wt_A", "wt and chain A") cmd.create("wt_B", "wt and chain B") cmd.select("none") cmd.create("des_A", "not wt and chain A") cmd.show("surface", "des_A") cmd.create("des_B", "not wt and chain B") cmd.show("surface", "des_B") cmd.align("wt_A", "des_A") cmd.align("wt_B", "des_B") # cmd.show( "lines", "wt_A" ) # cmd.show( "lines", "wt_B" ) cmd.set("transparency", 1) cmd.zoom("interface") return name