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("count", "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 rd(): """ rhiju's favorite coloring of proteins and generic molecules side chains are all-heavy-atom and colored CPK, backbone is rainbow cartoon from N to C terminus. """ cmd.bg_color("white") AllObj = cmd.get_names("all") for x in AllObj: #print(AllObj[0],x) print x cmd.show("cartoon", x) cmd.hide("line", x) cmd.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("count", "rainbow", x + " and name CA+C") cmd.show("sticks", x + " and not elem H and not name C+N+O") cmd.show("sticks", x + " and resn PRO and name N") cmd.show("sticks", x + " and name NR+CR+CS+CP+CQ") cmd.show("sticks", x + " and not elem H and neighbor name NR+CQ+CR+CS+CP") cmd.show( "sticks", x + " and not elem H and neighbor neighbor name NR+CQ+CR+CS+CP") cmd.set("cartoon_oval_width", 0.1) cmd.set("cartoon_oval_length", 0.5)
def loadBfacts(mol, startaa=1, source="newBfactors.txt", visual="Y"): """ Replaces B-factors with a list of values contained in a plain txt file usage: loadBfacts mol, [startaa, [source, [visual]]] mol = any object selection (within one single object though) startaa = number of first amino acid in 'new B-factors' file (default=1) source = name of the file containing new B-factor values (default=newBfactors.txt) visual = redraws structure as cartoon_putty and displays bar with min/max values (default=Y) example: loadBfacts 1LVM and chain A """ obj = cmd.get_object_list(mol)[0] cmd.alter(mol, "b=-1.0") inFile = open(source, 'r') counter = int(startaa) bfacts = [] for line in inFile.readlines(): bfact = float(line) bfacts.append(bfact) cmd.alter("%s and resi %s and n. CA" % (mol, counter), "b=%s" % bfact) counter = counter + 1 if visual == "Y": cmd.show_as("cartoon", mol) cmd.cartoon("putty", mol) cmd.set("cartoon_putty_scale_min", min(bfacts), obj) cmd.set("cartoon_putty_scale_max", max(bfacts), obj) cmd.set("cartoon_putty_transform", 0, obj) cmd.set("cartoon_putty_radius", 0.2, obj) cmd.spectrum("b", "rainbow", "%s and n. CA " % mol) cmd.ramp_new("count", obj, [min(bfacts), max(bfacts)], "rainbow") cmd.recolor()
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 plot(self, outfile): ctrl_id, case_id, snp_df_sub = self.score_on_var() df = pd.merge(snp_df_sub, self.snps2aa, on='id') #pymol.finish_launching() cmd.reinitialize() cmd.fetch(self.pdb) cmd.alter(self.pdb, 'b = 0.5') cmd.show_as('cartoon', self.pdb) cmd.color('white', self.pdb) for i, row in df.iterrows(): resi = row['structure_position'] chain = row['chain'] pheno = row['es'] selec = 'snp%s' % i selec_atom = 'snp_atom%s' % i cmd.select(selec, 'name ca and resi %s and chain %s' % (resi, chain)) cmd.create(selec_atom, selec) cmd.set("sphere_scale", 0.8) cmd.show('sphere', selec_atom) cmd.alter(selec_atom, 'b=%s' % pheno) cmd.spectrum("b", "blue_white_red", selec_atom, maximum=1.0, minimum=0.0) cmd.bg_color("white") cmd.zoom() cmd.orient() cmd.save('%s.pse' % outfile) cmd.png('%s.png' % outfile, width=2400, height=2400, dpi=300, ray=1)
def testSpectrumany(self): self._testSpectrum_setup() cmd.spectrum('count', 'red blue') img = self.get_imagearray() self.assertImageHasColor('red', img) self.assertImageHasColor('blue', img) self.assertImageHasColor('0x7f007f', img, delta=30)
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 drab(nlim=-2.0, plim=2.0): #zero the indexes #zero_residues("all", 1, 1) #Read the values in fileName = cmd.get_names()[0] print fileName fileName = fileName + ".dat" cmd.alter("all", "b=0.0") #file = open(fileName, 'r') #table = [row.strip().split('\t') for row in file] bVals = [] #print table for line in file(fileName): line = line.strip().split() if (line[0][0] != "#"): selection = "resi %s" % line[0] #Normalize the values bval = (float(line[1]) - nlim) / (plim - nlim) #print bval cmd.alter(selection, "b=%f" % bval) print(selection, "b=%f" % bval) bVals.append([selection, bval]) cmd.hide("all") cmd.show("cartoon") cmd.spectrum("b", "blue_white_red", "all", "0.0", "1.0", "1") cmd.ramp_new("rawFac_ramp", cmd.get_names()[0], [nlim, plim], color="[blue, white, red ]") cmd.recolor()
def rs(): """ The function creates super-cool cartoon-like RNA and colors each structure as a rainbow. Good to view aligned structures in a grid. .. image:: ../../rna_tools/utils/PyMOL4RNA/doc/rs.png """ cmd.hide("sticks", "all") cmd.hide("lines", "all") cmd.show("cartoon", "all") cmd.set("cartoon_ring_mode", 3) cmd.set("cartoon_ring_finder", 2) cmd.set("cartoon_ladder_mode", 2) cmd.set("cartoon_ring_transparency", 0.30) cmd.spectrum() obj_list = cmd.get_names('objects') colours = ['rainbow'] ncolours = len(colours) # Loop over objects i = 0 for obj in obj_list: print(" ", obj, colours[i]) cmd.spectrum('count', colours[i], obj) i = i+1 if(i == ncolours): i = 0
def 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 loadFitnessFactors (mol,startaa=1,source="/Users/student/Box Sync/PUBS/Pymol-practice.txt", visual="Y"): # adapted from http://www.pymolwiki.org/index.php/Load_new_B-factors """ Replaces B-factors with a list of fitness factor values contained in a plain txt file usage: loadFitnessFactors mol, [startaa, [source, [visual]]] mol = any object selection (within one single object though) startaa = number of first amino acid in 'new Fitness-factors' file (default=1) source = name of the file containing new Fitness-factor values (default=newFitnessFactors.txt) visual = redraws structure as cartoon_putty and displays bar with min/max values (default=Y) example: loadFitnessFactors 1LVM and chain A """ obj=cmd.get_object_list(mol)[0] cmd.alter(mol,"b=-1.0") inFile = open(source, 'r') counter=int(startaa) fitnessFacts=[] for line in inFile.readlines(): fitnessFact=float(line) fitnessFacts.append(fitnessFact) cmd.alter("%s and resi %s and n. CA"%(mol,counter), "b=%s"%fitnessFact) counter=counter+1 if visual=="Y": cmd.show_as("cartoon",mol) cmd.cartoon("putty", mol) # cmd.set("cartoon_putty_scale_min", min(fitnessFacts),obj) # cmd.set("cartoon_putty_scale_max", max(fitnessFacts),obj) cmd.set("cartoon_putty_transform", 0,obj) cmd.set("cartoon_putty_radius", 0.2,obj) cmd.spectrum("b","red_white_blue", "%s and n. CA " %mol) cmd.ramp_new("count", obj, [min(fitnessFacts), (min(fitnessFacts)+max(fitnessFacts))/2, max(fitnessFacts)], color = ["blue", "white", "red"]) cmd.recolor()
def loadBfacts (mol,startaa=1,source="/Users/student/Box Sync/PUBS/Pymol-practice.txt", visual="Y"): """ Replaces B-factors with a list of values contained in a plain txt file usage: loadBfacts mol, [startaa, [source, [visual]]] mol = any object selection (within one single object though) startaa = number of first amino acid in 'new B-factors' file (default=1) source = name of the file containing new B-factor values (default=newBfactors.txt) visual = redraws structure as cartoon_putty and displays bar with min/max values (default=Y) example: loadBfacts 1LVM and chain A """ obj=cmd.get_object_list(mol)[0] cmd.alter(mol,"b=-1.0") inFile = open(source, 'r') counter=int(startaa) bfacts=[] for line in inFile.readlines(): bfact=float(line) bfacts.append(bfact) cmd.alter("%s and resi %s and n. CA"%(mol,counter), "b=%s"%bfact) counter=counter+1 if visual=="Y": cmd.show_as("cartoon",mol) cmd.cartoon("putty", mol) cmd.set("cartoon_putty_scale_min", min(bfacts),obj) cmd.set("cartoon_putty_scale_max", max(bfacts),obj) cmd.set("cartoon_putty_transform", 0,obj) cmd.set("cartoon_putty_radius", 0.2,obj) cmd.spectrum("b","rainbow", "%s and n. CA " %mol) cmd.ramp_new("count", obj, [min(bfacts), max(bfacts)], "rainbow") cmd.recolor()
def rs(): """ The function creates super-cool cartoon-like RNA and colors each structure as a rainbow. Good to view aligned structures in a grid. .. image:: ../../rna_tools/utils/PyMOL4RNA/doc/rs.png """ cmd.hide("sticks", "all") cmd.hide("lines", "all") cmd.show("cartoon", "all") cmd.set("cartoon_ring_mode", 3) cmd.set("cartoon_ring_finder", 2) cmd.set("cartoon_ladder_mode", 2) cmd.set("cartoon_ring_transparency", 0.30) cmd.spectrum() obj_list = cmd.get_names('objects') colours = ['rainbow'] ncolours = len(colours) # Loop over objects i = 0 for obj in obj_list: print(" ", obj, colours[i]) cmd.spectrum('count', colours[i], obj) i = i + 1 if (i == ncolours): i = 0
def rd(): """ rhiju's favorite coloring of proteins and generic molecules side chains are all-heavy-atom and colored CPK, backbone is rainbow cartoon from N to C terminus. """ cmd.bg_color( "white" ) AllObj=cmd.get_names("all") for x in AllObj: #print(AllObj[0],x) print x cmd.show( "cartoon", x ) cmd.hide( "line", x ) cmd.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.show( "sticks", x +" and resn PRO and name N" ) cmd.show( "sticks", x + " and name NR+CR+CS+CP+CQ" ) cmd.show( "sticks", x + " and not elem H and neighbor name NR+CQ+CR+CS+CP" ) cmd.show( "sticks", x + " and not elem H and neighbor neighbor name NR+CQ+CR+CS+CP" ) cmd.set( "cartoon_oval_width", 0.1 ) cmd.set( "cartoon_oval_length", 0.5 )
def blue_red( which_property = "resi", selection="all", minval = 0.0, maxval = 2.0 ): """ mainly a mnemonic for a command I use all the time. Note that which_property can be "p.bisulfite" or something, if the user-defined property is defined! """ cmd.spectrum( which_property, "blue_white_red", selection, minval, maxval )
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 saveMultiplepng(pnamein, nbstates): finish_launching() for state in range(0,nbstates): print(state, nbstates) finish_launching() pfilin = pnamein + "_state" + str(state) + ".pdb" print (pfilin) cmd.load(pfilin, "state" + str(state)) cmd.hide("everything", "all") for state in range(0, nbstates): cmd.show("surface", selection="state" + str(state)) cmd.set("transparency", value=0.4) cmd.show("cartoon", selection="state" + str(state)) cmd.spectrum("b", "chocolate_firebrick_red_tv_red_deepsalmon_darksalmon_salmon_lightpink_white", selection="all", minimum=0, maximum=100) cmd.select("lig" + str(state), "resn UNK and state" + str(state)) cmd.show("stick", selection="lig" + str(state)) cmd.bg_color("white") cmd.ray(2000, 2000) cmd.save(pnamein + "_state" + str(state) + ".png", selection="state" + str(state)) cmd.hide("everything", "all") cmd.quit()
def show_ligand_interactions(recsel="not hetatm", ligsel="hetatm", cutoff=5): """ DESCRIPTION Visualize interactions between receptor and ligand. ARGUMENTS recsel = string: atom selection of the receptor {default: "not hetatm"} ligsel = string: atom selections of the ligand {default: "hetatm"} cutoff = float: show as sticks all receptor residues within this distance from the ligand {default: 5.0} """ cmd.select('ligand', ligsel) cmd.select('receptor', recsel) cmd.bg_color('white') cmd.show_as('cartoon') cmd.show_as('sticks', 'hetatm') cmd.set('cartoon_transparency', 0.2) cmd.spectrum(selection=recsel+" or "+ligsel,byres=1) util.cbag('not elem C') cmd.set('cartoon_fancy_helices', 1); cmd.show("sticks", "(hydro)"); cmd.select("pocket", "byres (receptor within %s of ligand)" % cutoff); cmd.show("sticks", "pocket") cmd.hide('(h. and (e. c extend 1))') cmd.set('h_bond_max_angle', 30) cmd.set('h_bond_cutoff_center', 3.6) cmd.set('h_bond_cutoff_edge', 3.2) cmd.dist('ligand_Hbonds', 'ligand', 'receptor', 3.5, mode=2) cmd.set('dash_radius', 0.15) # now set the label options cmd.set('label_size', 20) cmd.set('label_position', [0,0,10])
def ss(mol, startaa=1, visual="Y"): """ Replaces B-factors with TALOS predicted secondary structure elements mol = any object selection (within one single object though) startaa = number of first amino acid in 'new B-factors' file (default=1) visual = redraws structure as cartoon_putty and displays bar with min/max values (default=Y) example: ss 1LVM, startaa=4 """ source = 'predSS.tab' ss_dict = {'L': 0, 'H': 2, 'E': 1, 'X': 0} ss_only = [] with open(source) as ss_file: for lines in ss_file: searcher = re.search('^\d+', lines.strip()) if searcher != None: if int(lines.strip().split()[0]) < int(startaa): continue ss_only.append(ss_dict[lines.strip().split()[8]]) obj = cmd.get_object_list(mol)[0] cmd.alter(mol, "b=-1.0") counter = int(startaa) bfacts = [] for line in ss_only: bfact = float(line) bfacts.append(bfact) cmd.alter("%s and resi %s and n. CA" % (mol, counter), "b=%s" % bfact) counter = counter + 1 if visual == "Y": cmd.cartoon("automatic", mol) cmd.spectrum("b", "grey blue red", "%s and n. CA " % mol) cmd.recolor()
def visualize( *args, **kwargs ): if len(args) < 1: print("No molecules selected") return stored.b_factors = [] for selection in args: cmd.iterate_state(1, selector.process(selection), "stored.b_factors.append(b)") max = 0.00 for value in stored.b_factors: if abs(value) > max: max = abs(value) print("Maximum absolute b-factor value: %s") % (max) #Uses same magnitude for maximum and minimum to stay symmetrical around zero for selection_item in args: cmd.spectrum("b", "red_white_green", minimum = (0-max), maximum = max, selection = selection_item)
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 lsupdateview(self, lig, zone, min, max, prev, index, hlig, label): cmd.hide("all") x = cmd.get_names("all") cmd.label( "( " + x[index] + " and (r. " + lig + " a. " + prev + ") ) and (not (" + x[index] + " and (r. SWT or r. BWT or r. SWP))) " + " and name CA", "\" \"") cmd.show("cartoon", "bo. " + x[index]) cmd.show("sticks", x[index] + " and r. " + lig) cmd.color("white", x[index] + " and pol.") fp = open(tempfile.gettempdir() + "/temp.txt", "r") stored.bfact = [] for line in fp: stored.bfact.append(line) fp.close() cmd.alter(x[index], "b=stored.bfact.pop(0)") cmd.spectrum("b", "blue_white_red", x[index], minimum=min, maximum=max) cmd.ramp_new("ramp_obj", x[index], range=[min, 0, max], color="[blue, white, red ]") cmd.util.cbaw(x[index] + " and r. " + lig) cmd.show( "licorice", "( " + x[index] + " and (r. " + lig + " a. " + zone + ") ) and (not (" + x[index] + " and (r. SWT or r. BWT or r. SWP))) ") cmd.hide("licorice", x[index] + " and r. " + hlig) self.togglelabells(label, index, lig, zone, hlig)
def rs(): """RNA like in papers ;-) - even better :D Creates supercool cartoon-like RNA and colors each (and every) structure as a rainbow. Good to view aligned structures in a grid. """ cmd.hide("sticks", "all") cmd.hide("lines", "all") cmd.show("cartoon", "all") cmd.set("cartoon_ring_mode", 3) cmd.set("cartoon_ring_finder", 2) cmd.set("cartoon_ladder_mode", 2) cmd.set("cartoon_ring_transparency", 0.30) cmd.spectrum() obj_list = cmd.get_names('objects') colours = ['rainbow'] ncolours = len(colours) # Loop over objects i = 0 for obj in obj_list: print " ", obj, colours[i] cmd.spectrum('count', colours[i], obj) i = i+1 if(i == ncolours): i = 0
def color_protein(protein, df): #df["importance"] = np.abs(df["importance"].values) #df["importance"] = np.log(df["importance"].values) #df["importance"] = df["importance"].values/np.max(df["importance"].values) min_imp = min(df["importance"].values) max_imp = max(df["importance"].values) print(min_imp) print(max_imp) cmd.spectrum("b", "blue red", selection=protein, minimum=min_imp, maximum=max_imp) for index in df.index: print(df.loc[index]) resid = int(df.loc[index]["resid"]) net_importance = df.loc[index]["importance"] cmd.alter("resid %d & %s" % (resid, protein), "b=%f" % (net_importance)) cmd.show("ribbon", "resi %d" % resid) if net_importance > np.percentile(df["importance"].values, 95): cmd.show("sticks", "resi %d" % resid) #if "2" in protein: # cmd.util.cbac("resi %d & sidechain & %s" % (resid, protein)) #else: # cmd.util.cbag("resi %d & sidechain & %s" % (resid, protein)) print(resid) print(net_importance)
def wsvisualizer(self, index, lig, zone, min, max, label): cmd.hide("all") x = cmd.get_names("all") cmd.show("cartoon", "bo. " + x[index]) cmd.show("sticks", x[index] + " and r. " + lig) cmd.color("white", x[index] + " and pol.") fp = open(tempfile.gettempdir() + "/temp.txt", "r") #tt=0 stored.bfact = [] for line in fp: stored.bfact.append(line) #print(stored.bfact[tt]+"\t"+line+"\t"+str(tt)) #tt=tt+1 #print(tt) fp.close() cmd.alter(x[index], "b=stored.bfact.pop(0)") cmd.spectrum("b", "blue_white_red", x[index], minimum=min, maximum=max) cmd.ramp_new("ramp_obj", x[index], range=[min, 0, max], color="[blue, white, red ]") cmd.util.cbaw(x[index] + " and r. " + lig) cmd.show( "licorice", "( " + x[index] + " and (r. " + lig + " a. " + zone + ") ) and (not (" + x[index] + " and (r. SWT or r. BWT or r. SWP))) ") self.togglelabelws(label, index, lig, zone)
def colorByProp(self, prop, palette="rainbow"): stored.propUniqVals = set() cmd.iterate(self.objName, "stored.propUniqVals.add(%s)" % prop) v = sorted(stored.propUniqVals) b = n.arange(1, len(v) + 1, dtype=float) # / len(v) stored.b = dict(zip(v, b)) cmd.alter(self.objName, "b=stored.b[%s]" % prop) cmd.spectrum("b", palette, self.objName)
def color_by_data(filename, offset=0, min_val=-1.0, max_val=0.0, palette="rainbow"): """ Read in a text file with rows like: 125 0.12 126 1.50 and color specified residue numbers by scalar values. Takes advantage of B-factor column, and color by temperature function in pymol. Note that coloring is scaled/offset based on lowest/highest scalar value. """ lines = open(filename).readlines() data = {} data_backbone = {} avg_data = 0.0 min_data = 0.0 max_data = 0.0 for line in lines: cols = string.split(line) dataval = float(cols[1]) if min_val >= 0 and dataval < min_val: dataval = min_val if max_val > 0 and dataval > max_val: dataval = max_val data[int(cols[0])] = dataval avg_data = avg_data + dataval if (dataval < min_data): min_data = dataval if (dataval > max_data): max_data = dataval if len(cols) > 2: dataval2 = float(cols[2]) if min_val >= 0 and dataval2 < min_val: dataval2 = min_val if max_val > 0 and dataval2 > max_val: dataval2 = max_val data_backbone[int(cols[0])] = dataval2 avg_data /= len(data.keys()) cmd.alter('all', 'b=%6.3f' % avg_data) for i in data.keys(): cmd.alter('resi \\%d' % (i + int(offset)), 'b=%6.3f' % data[i]) backbone_tag = " and (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 i in data_backbone.keys(): cmd.alter('resi \\%d %s' % (i + int(offset), backbone_tag), 'b=%6.3f' % data_backbone[i]) if (min_val < 0): min_val = min_data if (max_val < 0): max_val = max_data if palette == 'rainbow': cmd.spectrum("b", palette, "all", min_val, max_val) else: spectrumany("b", palette, "all", min_val, max_val)
def align_and_color(moving, fixed, maximum=None, native_color="blue"): if maximum == "0": maximum = None alignment_name = "alignment_" + moving cmd.align(moving, fixed, object=alignment_name, cycles=0) cmd.disable(alignment_name) rmsd_b(moving + " & " + alignment_name, fixed + " & " + alignment_name) cmd.color(native_color, fixed) cmd.spectrum("b", "green_red", moving, 0, maximum)
def load_weights(): file_weights = open_it() i = 0 for line in open(file_weights, "r"): i = i + 1 selec = "resi " + str(i) ocup = line.split() cmd.alter(selec, "b=" + ocup[0]) cmd.spectrum("b", "blue_red")
def redraw(self): cmd.refresh_wizard() i, j = self.get_indices() sele = f'({self.sele}) and resi {i}-{j}' print(sele) cmd.color('green', self.sele) cmd.spectrum('b', 'blue_white_red', sele, minimum=self.low, maximum=self.high) cmd.zoom(sele, buffer=10, animate=-1)
def color_by_data( filename, offset = 0, min_val=-1.0, max_val = 0.0, palette = "rainbow" ): """ Read in a text file with rows like: 125 0.12 126 1.50 and color specified residue numbers by scalar values. If you specify a third column, that will set color of the backbone, separately from the base. Takes advantage of B-factor column, and color by temperature function in pymol. Note that coloring is scaled/offset based on lowest/highest scalar value. """ lines = open( filename ).readlines() data = {} data_backbone = {} avg_data = 0.0 min_data = 0.0 max_data = 0.0 for line in lines: cols = string.split( line ) dataval = float( cols[1] ) if min_val >= 0 and dataval < min_val: dataval = min_val if max_val > 0 and dataval > max_val: dataval = max_val data[ int( cols[0] ) ] = dataval avg_data = avg_data + dataval if ( dataval < min_data ): min_data = dataval if ( dataval > max_data ): max_data = dataval if len( cols ) > 2: dataval2 = float( cols[2] ) if min_val >= 0 and dataval2 < min_val: dataval2 = min_val if max_val > 0 and dataval2 > max_val: dataval2 = max_val data_backbone[ int( cols[0] ) ] = dataval2 avg_data /= len( data.keys() ) cmd.alter( 'all', 'b=%6.3f' % avg_data ) for i in data.keys(): cmd.alter( 'resi \\%d' % (i+int(offset)), 'b=%6.3f' % data[i] ) backbone_tag = " and (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 i in data_backbone.keys(): cmd.alter( 'resi \\%d %s' % (i+int(offset),backbone_tag), 'b=%6.3f' % data_backbone[i] ) if ( min_val < 0 ): min_val = min_data if ( max_val < 0 ): max_val = max_data #if palette == 'rainbow': cmd.spectrum( "b", palette,"all",min_val,max_val )
def rener(inName=""): #zero the indexes zero_residues("all", 1, 1) #Read the values in infileName = "" if (inName == ""): infileName = cmd.get_names()[0] else: infileName = inName fileName = infileName + ".pdb" cmd.alter("all", "b=0.0") file = open(fileName, 'r') table = [row.strip().split() for row in file] bVals = [] did_start = False rowcount = 0 for i in table: if (i[0] == "#BEGIN_POSE_ENERGIES_TABLE"): did_start = True rowcount = 0 continue elif did_start: rowcount += 1 if (rowcount > 3): if (i[0] == "#END_POSE_ENERGIES_TABLE"): did_start = False continue resn = i[0].split('_')[-1] selection = "resi %s" % resn val = i[-1] #if (val > 1.67): # val=1.67 #elif (val < 0.08): # val=0.08 bfac = val bVals.append([selection, bfac]) numres = len(bVals) bValsAvg = zeros(numres) for i in range(0, numres): bValsAvg[i] = float(bVals[i][1]) # for j in range( 0, frag_size): # tmpval=float(bVals[i][1]) # if(bValsAvg[i+j] < tmpval): # bValsAvg[i+j] = tmpval # bValsAvg[i]+= (float(bVals[i+j][1])/float(frag_size)) # bValsAvg=bValsAvg+bValsAvg[i].min() for i in range(0, numres): print(bVals[i][0], bValsAvg[i]) bfac = ("b=%f" % bValsAvg[i]) cmd.alter(bVals[i][0], bfac) #cmd.hide("all") #cmd.show("cartoon") # cmd.spectrum("b", "blue_white_red", infileName, bValsAvg.min(), bValsAvg.max(), "1") cmd.spectrum("b", "blue_white_red", infileName, -2.0, 0.0, "1")
def colorize(): """color according to the b-factor using the cheshift-code""" try: cmd.spectrum('b', 'red_white_blue', minimum='-1', maximum='1') cmd.select('missing', 'b = -2.0') cmd.color('yellow','missing') cmd.delete('missing') cmd.hide() cmd.show('cartoon') except: pass
def plot_mode(net): mode= tkSimpleDialog.askstring('Modes of the GNM', 'Please enter the index of the mode:') mode=int(mode) for ii in range(net.num_nodes): selec='id '+str(net.nodes[ii]) cmd.alter(selec,"q="+str(net.modes[mode][ii])) maxx=ma.maximum(net.modes[mode][:]) cmd.spectrum("q", 'red_white_blue',minimum=str(-maxx),maximum=str(maxx))
def load_net(): file_coors= open_it() net=network(file_coors) for ii in range(net.num_nodes): cmd.pseudoatom('net',pos=net.node[ii].coors,resi=ii,chain='A') selec='resi '+str(ii) cmd.alter(selec,'resn='+'"'+net.node[ii].label+'"') cmd.label(selec,'"'+net.node[ii].label+'"') cmd.alter(selec,'b='+str(net.node[ii].weight)) cmd.alter(selec,'q='+str(net.node[ii].cluster)) for ii in range(net.num_nodes): for jj in net.node[ii].link.keys(): cmd.bond('resi '+str(ii),'resi '+str(jj)) cmd.spectrum('b','blue_red')
def shape(): cmd.hide("sticks", "all") cmd.hide("lines", "all") cmd.show("cartoon", "all") cmd.set("cartoon_ring_mode", 3) cmd.set("cartoon_ring_finder", 2) cmd.set("cartoon_ladder_mode", 2) cmd.set("cartoon_ring_transparency", 0.30) cmd.spectrum('b', 'white_paleyellow_yellow_red_brown_grey', minimum=-0.25, maximum=1.25, byres=1)
def dms(): cmd.hide("sticks", "all") cmd.hide("lines", "all") cmd.show("cartoon", "all") cmd.set("cartoon_ring_mode", 3) cmd.set("cartoon_ring_finder", 2) cmd.set("cartoon_ladder_mode", 2) cmd.set("cartoon_ring_transparency", 0.30) cmd.spectrum('b', 'white_yellow_green_forest_grey', minimum=-0.25, maximum=1.25, byres=1)
def cmct(): cmd.hide("sticks", "all") cmd.hide("lines", "all") cmd.show("cartoon", "all") cmd.set("cartoon_ring_mode", 3) cmd.set("cartoon_ring_finder", 2) cmd.set("cartoon_ladder_mode", 2) cmd.set("cartoon_ring_transparency", 0.30) cmd.spectrum('b', 'white_lightpink_tv_red_firebrick_grey', minimum=-0.25, maximum=1.25, byres=1)
def colorize(): """color according to the b-factor using the cheshift-code""" try: cmd.spectrum('b', 'red_yellow_green', minimum='-1.0', maximum='0.0') cmd.select('missing', 'b = -2.0') cmd.color('white', 'missing') cmd.delete('missing') cmd.select('fixable', 'b = 2.0') cmd.color('blue', 'fixable') cmd.delete('fixable') cmd.hide() cmd.show('cartoon') except: pass
def colorize(): """color according to the b-factor using the cheshift-code""" try: cmd.spectrum('b', 'red_yellow_green', minimum='-1.0', maximum='0.0') cmd.select('missing', 'b = -2.0') cmd.color('white','missing') cmd.delete('missing') cmd.select('fixable', 'b = 2.0') cmd.color('blue','fixable') cmd.delete('fixable') cmd.hide() cmd.show('cartoon') except: pass
def plddt(selection='(all)', scheme="AlphaFoldDB", lower=50.0, upper=90.0, cnc=0): ''' DESCRIPTION Coloring by per-resude predicted LDDT (pLDDT) scores. (see Jumper et al. 2021 https://doi.org/10.1038/s41586-021-03819-2 Suppl. Methods 1.9.6 for details) Note: The pLDDT score is embedded in the B-factor column of the PDB output from AlphaFold version 2. ARGUMENTS selection = string: atom selection {default: (all)} scheme = string: Coloring scheme. AlphaFoldDB or spectrum {default: AlphaFoldDB}. lower = float: minimum of spectrum {default: 50.0} upper = float: maximum of spectrum {default: 90.0} cnc = 0/1 SEE ALSO spectrum ''' if scheme == "AlphaFoldDB": cmd.set_color("very_high", [0.051, 0.341, 0.827]) cmd.set_color("confident", [0.416, 0.796, 0.945]) cmd.set_color("low", [0.996, 0.851, 0.212]) cmd.set_color("very_low", [0.992, 0.490, 0.302]) cmd.color("very_high", "b < 100") cmd.color("confident", "b < 90") cmd.color("low", "b < 70") cmd.color("very_low", "b < 50") cmd.set('cartoon_discrete_colors', '1') cmd.util.cnc(selection) elif scheme == "spectrum": lower, upper = float(lower), float(upper) cmd.spectrum("b", "red_yellow_green_cyan_blue", selection, lower, upper) cmd.util.cnc(selection) else: print( "scheme is not valid. Use 'AlphaFoldDB' (default) or 'spectrum'.")
def feature3D(args): import pymol from pymol import cmd, util # get parameters pdb_id = args.pdb_id short_win = args.short_win large_win = args.large_win contact_threshold = args.contact_threshold feature_name = args.feature_name # compute features for each residue in a labelled chain residues, features, lip_indexes = prot_dataset.generate_test( pdb_id, short_win=short_win, large_win=large_win, contact_threshold=contact_threshold) # make a dataframe df = prot_dataset.as_dataframe(features, lip_indexes) # get the array with desired feature feature = df[feature_name] # Open Pymol (not necessary from pyMOL 2.1) pymol.finish_launching() # Download the PDB cmd.fetch(pdb_id, pdb_id) # Hide lines cmd.hide("lines", pdb_id) # Show ribbon cmd.show("cartoon", pdb_id) # Set all B-factor to 0.0 cmd.alter("(all)", "b=0.0") # for each residue for i in range(0, len(residues)): # Residue selection in Pymol syntax residue_string = '{}/{}{}/'.format(residues[i].get_full_id()[2], residues[i].id[1], '') # Substitute the B-score with the feature score cmd.alter(residue_string, "b={:2f}".format(feature[i])) # If the residue is labelled as LIP show it as sphere if lip_indexes[i] == 1: cmd.show_as( "spheres", "chain {} and resi {}".format(residues[i].get_full_id()[2], residues[i].id[1])) # color by B-factor values cmd.spectrum("b", palette="rainbow", selection="(all)")
def show_entropies(srcObj, chainNo, name=None): """Extracts the specified chain from srcObj and displays b-factors on the surface. chainNo: Either a string giving the chain to extract, a positive integer giving the number of the chain to extract (starting at 1), or 0 to extract all chains. name: Name of object to store the entropies. {default <srcObj>-<chain>_entropy """ if name is None: name = "{}-{{}}_entropy".format(srcObj) def append_if_different(arr, c): if len(arr) == 0 or arr[-1] != c: arr.append(c) stored._fetch_eppic_append_if_different = append_if_different if type(chainNo) == int: # Create list of chains stored._fetch_eppic_chain_ids = [] cmd.iterate( srcObj, "stored._fetch_eppic_append_if_different(stored._fetch_eppic_chain_ids,chain)" ) if chainNo == 0: chains = stored._fetch_eppic_chain_ids else: #TODO input validation chains = [stored._fetch_eppic_chain_ids[chainNo - 1]] else: chains = [chainNo] for chain in chains: # Create new object objname = name.format(chain) cmd.create(objname, "({}) and chain {}".format(srcObj, chain)) # Show entropies (stored in b factors) cmd.show_as('surface', "%s" % (objname)) cmd.spectrum(expression='b', palette='rainbow', selection='%s' % (objname), minimum=0.0, maximum=3.3219280948873626)
def load_sets(): dict1 = { "1": "00-0", "2": "00-1", "3": "00-2", "4": "10-0", "5": "02-0", "6": "10-1", "7": "02-1", "8": "10-2", "9": "02-2", "10": "12-0", "11": "12-1", "12": "12-2", "13": "00-K", "14": "10-K", "15": "02-K", "16": "12-K", "17": "12-K1", "18": "00-1K", "19": "10-1K", "20": "01-1K", "21": "12-1K", "22": "0K-0", "23": "0K-1", "24": "0K-2", "25": "1K-0", "26": "1K-1", "27": "1K-2", "28": "K0-0", "29": "K0-1", "30": "K0-2", "31": "K2-0", "32": "K2-1", "33": "K2-2", } file_sets = open_it() i = 0 for line in open(file_sets, "r"): i = i + 1 selec = "resi " + str(i) ocup = line.split() cmd.alter(selec, "resn=" + '"' + dict1[ocup[0]] + '"') cmd.alter(selec, "q=" + ocup[0]) for ii in sorted(dict1.iterkeys()): cmd.select('"' + dict1[ii] + '"', 'resn "' + dict1[ii] + '"') cmd.spectrum("q", "rainbow")
def rr( selection = "all" ): """ 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",selection ) cmd.show('sticks','not elem H and ' + selection ) cmd.hide( "everything","resn HOH" ) cmd.color('white','elem C and ' + selection ) cmd.color( 'red','resn rG+G+DG+GUA and ' + selection) cmd.color( 'forest','resn rC+C+DC+CYT and ' + selection) cmd.color( 'orange','resn rA+A+DA+ADE and ' + selection) cmd.color( 'blue','resn rU+U+DT+BRU+URA+THY and ' + selection) cmd.color( 'red','resn rG+G+DG+GUA and name n1+c6+o6+c5+c4+n7+c8+n9+n3+c2+n1+n2 and ' + selection) cmd.color( 'forest','resn rC+C+DC+CYT and name n1+c2+o2+n3+c4+n4+c5+c6 and ' + selection) cmd.color( 'orange','resn rA+A+DA+ADE and name n1+c6+n6+c5+n7+c8+n9+c4+n3+c2 and ' + selection) cmd.color( 'blue','resn rU+U+URA+THY and name n3+c4+o4+c5+c6+n1+c2+o2 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) and " + selection) cmd.spectrum( "resi", "rainbow", "backbone" ) cmd.cartoon( "tube", "backbone" ) cmd.hide( "sticks", "backbone" ) cmd.delete('backbone') cmd.show( "cartoon", selection ) cmd.set( "cartoon_ring_mode", 3 ) cmd.set( "cartoon_ring_transparency", 0.0 ) cmd.set( "cartoon_tube_radius", 0.2 ) cmd.alter( "name o2* and "+selection,"vdw=0.5" ) cmd.show( "spheres", "name o2'+'o2*' and not name o2+o2p and "+selection) cmd.show( "sticks", "name o2'+c2'+'o2*'+'c2*' and "+selection ) cmd.show( "sticks", "resn hoh and "+selection ) cmd.alter( "name MG and "+selection,"vdw=0.5") cmd.show( "spheres", "name MG and "+selection ) cmd.alter( "resn mg and "+selection, "vdw=1.0") cmd.alter( "resn hoh and "+selection, "vdw=0.5") cmd.show( "spheres", "resn mg+sr+co+zn and not elem H and "+selection) cmd.hide( "ev","name RP* and "+selection)
def rb(): """ basic cartoon coloring """ AllObj = cmd.get_names("all") cmd.bg_color("white") cmd.hide("ev") cmd.show("cartoon") cmd.cartoon("rectangle") cmd.set("cartoon_ring_mode", 1) cmd.set("cartoon_rect_length", 0.7) cmd.set("cartoon_rect_width", 0.2) for x in AllObj: print(AllObj[0], x) cmd.spectrum("count", "rainbow", x)
def rb(): """ basic cartoon coloring """ AllObj=cmd.get_names("all") cmd.bg_color( "white" ) cmd.hide( "ev" ) cmd.show( "cartoon" ) cmd.cartoon( "rectangle" ) cmd.set( "cartoon_ring_mode", 1 ) cmd.set( "cartoon_rect_length", 0.7 ) cmd.set( "cartoon_rect_width", 0.2 ) for x in AllObj: print(AllObj[0],x) cmd.spectrum( "resi", "rainbow", x )
def disp_putty(selection='all', limits=10, only=True): ''' DESCRIPTION Formats the passed object into a Putty b-factor sausage USEAGE disp_putty [ selection ] selection <str> input selection limits=10 <list or flaot> applies only if color_m=='putty' sets the b-factor range limits (by protein) <list> [min,max] <float> percentile cutoff (both sides) only=True <bool> if True will use show_as; else show ''' try: selection = '(' + selection + ')' only = bool(str(only) != 'False') except: print("Input error") return False for p in cmd.get_object_list(selection): limits = get_b_limits(limits, p) if not limits: print("Input error (limits must be <list> or <float (<=50)>)!") return False # settings cmd.set('cartoon_discrete_colors', 'off', p) cmd.set('cartoon_putty_scale_max', 5, p) cmd.set('cartoon_putty_scale_min', 1, p) # normalized nonlinear scaling cmd.set('cartoon_putty_transform', 0, p) cmd.spectrum('b', 'rainbow', '(not hetatm) and %s' % p, minimum='%f' % limits[0], maximum='%f' % limits[1], byres=1) cmd.cartoon('putty', '(%s and %s)' % (selection, p)) if only: cmd.show_as('cartoon', '(%s and %s)' % (selection, p)) else: cmd.show('cartoon', '(%s and %s)' % (selection, p))
def LoadResidueResults(results, resultfield="value", objectName="", selectionName = None, spectrum = "blue_white_red", spectrumMinimum = None, spectrumMaximum = None): if selectionName is None: selectionName = "%s_results" % objectName #Clear B factor on the entire object and results selection cmd.alter("/%s/" % objectName, "b=0.0") cmd.select(selectionName, "none") #Reset b factor to value and create named selection for result in results: selectexpr = "/%s//%s/%i/" % (objectName, result['chain'], result['residue_id']) cmd.alter(selectexpr, "b=%f" % result[resultfield]) cmd.select(selectionName, "%s | %s " % (selectionName, selectexpr)) cmd.spectrum("b", spectrum, selectionName, minimum = spectrumMinimum, maximum = spectrumMaximum)
def loadFitnessFactors( mol, startaa=1, source="/Users/student/Box Sync/PUBS/Pymol-practice.txt", visual="Y"): # adapted from http://www.pymolwiki.org/index.php/Load_new_B-factors """ Replaces B-factors with a list of fitness factor values contained in a plain txt file usage: loadFitnessFactors mol, [startaa, [source, [visual]]] mol = any object selection (within one single object though) startaa = number of first amino acid in 'new Fitness-factors' file (default=1) source = name of the file containing new Fitness-factor values (default=newFitnessFactors.txt) visual = redraws structure as cartoon_putty and displays bar with min/max values (default=Y) example: loadFitnessFactors 1LVM and chain A """ obj = cmd.get_object_list(mol)[0] cmd.alter(mol, "b=-1.0") inFile = open(source, 'r') counter = int(startaa) fitnessFacts = [] for line in inFile.readlines(): fitnessFact = float(line) fitnessFacts.append(fitnessFact) cmd.alter("%s and resi %s and n. CA" % (mol, counter), "b=%s" % fitnessFact) counter = counter + 1 if visual == "Y": cmd.show_as("cartoon", mol) cmd.cartoon("putty", mol) # cmd.set("cartoon_putty_scale_min", min(fitnessFacts),obj) # cmd.set("cartoon_putty_scale_max", max(fitnessFacts),obj) cmd.set("cartoon_putty_transform", 0, obj) cmd.set("cartoon_putty_radius", 0.2, obj) cmd.spectrum("b", "red_white_blue", "%s and n. CA " % mol) cmd.ramp_new("count", obj, [ min(fitnessFacts), (min(fitnessFacts) + max(fitnessFacts)) / 2, max(fitnessFacts) ], color=["blue", "white", "red"]) cmd.recolor()
def cartoon(self,cleanup=0): if not cleanup: try: cmd.set("suspend_updates",1,quiet=1) cmd.disable() cmd.delete("1tii") cmd.load("$PYMOL_DATA/demo/1tii.pdb") cmd.hide("(1tii)") cmd.show("cartoon","1tii") cmd.zoom("1tii") cmd.spectrum("count","rainbow","1tii////ca") cmd.set("cartoon_highlight_color","grey50","1tii") cmd.set("cartoon_fancy_helices",1,"1tii") finally: cmd.set("suspend_updates",0,quiet=1) cmd.refresh() else: cmd.delete("1tii")
def tmalign_pairs(): all_pdbs = cmd.get_names( 'all' ) pdb_pairs = [] while ( len( all_pdbs ) > 1 ): pdb_pairs.append( all_pdbs[:2] ) all_pdbs = all_pdbs[2:] for pdb_pair in pdb_pairs: tmalign( pdb_pair[0], pdb_pair[1] ) cmd.spectrum( 'count', 'rainbow', pdb_pair[0] + ' and e. c' ) cmd.color( 'white', pdb_pair[1] ) cmd.create( pdb_pair[0] + '/' + pdb_pair[1], pdb_pair[0], 0, 1 ) cmd.create( pdb_pair[0] + '/' + pdb_pair[1], pdb_pair[1], 0, 2 ) cmd.delete( pdb_pair[0] ) cmd.delete( pdb_pair[1] ) cmd.set( 'all_states', 1 )
def assign_colors(selection, by='residues'): ''' Assigns a unique color to every atom, residue, ss, or chain in the selection. ''' stored.index = [] stored.atoms = [] myspace = {'atoms':[]} if by != 'atoms': selection += ' and n. CA' cmd.iterate(selection, 'stored.atoms.append((model,chain,ss,resi,name))') counter = 0 increment = 1 previous = 'hfjkdasnck12dd32' # pseudo-random if DEBUG: print "coloring by ", by for (model, chain, ss, resi, name) in stored.atoms: if by == 'atoms': counter += increment elif by == 'residues': if resi != previous: counter += increment previous = resi elif by == 'ss': if ss != previous: counter += increment previous = ss elif by == 'chain': if chain != previous: counter += increment previous = chain # alternating colors from both ends of the spectrum stored.index.append(counter if counter % 2 else -counter) cmd.alter(selection, 'b = stored.index.pop(0)') cmd.spectrum('b', 'rainbow', selection) if DEBUG: print "number of features: ", counter return counter
def viewANCHORSmapResultDirectory(resultdir, score_cutoff, spectrum = "blue_white_red", spectrumMinimum = None, spectrumMaximum = None): assert path.exists(resultdir) #Create result directory selection result_selection = "anchors-%s" % path.basename(resultdir) result_objects = [] cmd.select(result_selection, "none") stubdirs = glob(path.join(resultdir,"*")) for stubdir in stubdirs: if not path.exists(path.join(stubdir, "Out", "ranks.out")): continue ranks = numpy.recfromtxt(ProcessANCHORSmapRanksFile(path.join(stubdir, "Out", "ranks.out")), names=True, skiprows=1) #Create result stub selection stub_selection = "%s-%s" % (result_selection, path.basename(stubdir)) stub_objects = [] cmd.select(stub_selection, "none") for x in xrange(len(ranks)): if ranks["DG"][x] < score_cutoff: #Load the stub result into an object filename = "%s.pdb" % path.join(stubdir, "Pdb", ranks["FName"][x]) objectname = "%s-%s-%s" % (path.basename(resultdir), path.basename(stubdir), ranks["FName"][x]) cmd.load(filename, objectname) #Add object to result and stub selections result_objects.append(objectname) stub_objects.append(objectname) #Load DDG value into B value cmd.alter("/%s/" % objectname, "b=%s" % ranks["DG"][x]) cmd.select(stub_selection, " | ".join(stub_objects)) cmd.select(result_selection, " | ".join(result_objects)) #Color result selection by B value cmd.spectrum("b", spectrum, result_selection, minimum = spectrumMinimum, maximum = spectrumMaximum)
def disp_putty(selection='all', limits=10, only=True): ''' DESCRIPTION Formats the passed object into a Putty b-factor sausage USEAGE disp_putty [ selection ] selection <str> input selection limits=10 <list or flaot> applies only if color_m=='putty' sets the b-factor range limits (by protein) <list> [min,max] <float> percentile cutoff (both sides) only=True <bool> if True will use show_as; else show ''' try: selection = '(' + selection + ')' only = bool(str(only) != 'False') except: print "Input error" return False for p in cmd.get_object_list(selection): limits = get_b_limits(limits, p) if not limits: print "Input error (limits must be <list> or <float (<=50)>)!" return False # settings cmd.set('cartoon_discrete_colors', 'off', p) cmd.set('cartoon_putty_scale_max', 5, p) cmd.set('cartoon_putty_scale_min', 1, p) # normalized nonlinear scaling cmd.set('cartoon_putty_transform', 0, p) cmd.spectrum('b', 'rainbow', '(not hetatm) and %s' % p, minimum='%f' % limits[0], maximum='%f' % limits[1], byres=1) cmd.cartoon('putty', '(%s and %s)' % (selection, p)) if only: cmd.show_as('cartoon', '(%s and %s)' % (selection, p)) else: cmd.show('cartoon', '(%s and %s)' % (selection, p))
def show_entropies(srcObj,chainNo,name=None): """Extracts the specified chain from srcObj and displays b-factors on the surface. chainNo: Either a string giving the chain to extract, a positive integer giving the number of the chain to extract (starting at 1), or 0 to extract all chains. name: Name of object to store the entropies. {default <srcObj>-<chain>_entropy """ if name is None: name = "{}-{{}}_entropy".format(srcObj) def append_if_different(arr,c): if len(arr) == 0 or arr[-1] != c: arr.append(c) stored._fetch_eppic_append_if_different = append_if_different if type(chainNo) == int: # Create list of chains stored._fetch_eppic_chain_ids = [] cmd.iterate(srcObj,"stored._fetch_eppic_append_if_different(stored._fetch_eppic_chain_ids,chain)") if chainNo == 0: chains = stored._fetch_eppic_chain_ids else: #TODO input validation chains = [stored._fetch_eppic_chain_ids[chainNo-1]] else: chains = [chainNo] for chain in chains: # Create new object objname = name.format(chain) cmd.create( objname , "({}) and chain {}".format(srcObj,chain) ) # Show entropies (stored in b factors) cmd.show_as('surface',"%s"%(objname)) cmd.spectrum(expression='b',palette='rainbow',selection='%s'%(objname), minimum=0.0,maximum=3.3219280948873626)