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 testGetType(self): cmd.fragment('gly', 'm1') self.assertEqual(cmd.get_type('m1'), 'object:molecule') cmd.ramp_new('ramp1', 'none') self.assertEqual(cmd.get_type('ramp1'), 'object:ramp') cmd.select('s1', 'elem C') self.assertEqual(cmd.get_type('s1'), 'selection')
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 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 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 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 nci(arg1, arg2, arg3): densf = arg1 + "-dens" gradf = arg1 + "-grad" cmd.isosurface("grad", gradf, 0.5) cmd.ramp_new("ramp", densf, [int(arg2), int(arg3)], "rainbow") cmd.set("surface_color", "ramp", "grad") cmd.set('two_sided_lighting', value=1)
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 testGetNamesOfType(self): cmd.fragment('gly', 'm1') cmd.fragment('ala', 'm2') cmd.ramp_new('ramp1', 'none') self.assertEqual(cmd.get_names_of_type('object:molecule'), ['m1', 'm2']) self.assertEqual(cmd.get_names_of_type('object:ramp'), ['ramp1']) self.assertEqual(cmd.get_names_of_type('object:map'), [])
def nci(arg1): densf = arg1 + "-dens" gradf = arg1 + "-grad" # gdens=open(densf+".cube","r") # grad=open(gradf+".cube","r") cmd.isosurface("grad", gradf, 0.5) cmd.ramp_new("ramp", densf, [-5, 5], "rainbow") cmd.set("surface_color", "ramp", "grad") cmd.set('two_sided_lighting', value=1)
def apbs_surface(selection='all', maximum=None, minimum=None, map_name=None, ramp_name=None, grid=0.5, quiet=1): ''' DESCRIPTION Show electrostatic potential on surface (calculated with APBS). Important: surface_color is a object property, so when calculating surface potential for different selections and visualize them all together, you should first split them into separate objects. USAGE apbs_surface [ selection [, maximum [, minimum ]]] EXAMPLE fetch 2x19, bsync=0 split_chains apbs_surface 2x19_A, 10 apbs_surface 2x19_B, 10 SEE ALSO map_new_apbs, APBS Tools Plugin, isosurface, gradient, util.protein_vacuum_esp ''' quiet = int(quiet) if ramp_name is None: ramp_name = cmd.get_unused_name('ramp') if map_name is None: map_name = cmd.get_unused_name('map') map_new_apbs(map_name, selection, float(grid), quiet=quiet) if maximum is not None: maximum = float(maximum) minimum = -maximum if minimum is None else float(minimum) kwargs = {'range': [minimum, (minimum + maximum) * 0.5, maximum]} else: kwargs = {'selection': selection} cmd.ramp_new(ramp_name, map_name, **kwargs) object_names = cmd.get_object_list('(' + selection + ')') for name in object_names: cmd.set('surface_color', ramp_name, name) cmd.show('surface', selection) cmd.set('surface_solvent', 0) cmd.set('surface_ramp_above_mode', 1)
def nci( arg1 ): densf=arg1+"-dens" gradf=arg1+"-grad" # gdens=open(densf+".cube","r") # grad=open(gradf+".cube","r") cmd.isosurface("grad",gradf, 0.5) cmd.ramp_new("ramp", densf, [-5,5], "rainbow") cmd.set("surface_color", "ramp", "grad") cmd.set('two_sided_lighting',value=1)
def testGetNames(self): cmd.fragment('gly') cmd.fragment('cys') cmd.ramp_new('ramp1', 'none') # non-molecular object cmd.select('foo', 'none') self.assertEqual(cmd.get_names(), ['gly', 'cys', 'ramp1']) self.assertEqual(cmd.get_names(selection="elem S"), ['cys']) cmd.disable('gly') cmd.disable('ramp1') self.assertEqual(cmd.get_names(enabled_only=1), ['cys']) self.assertEqual(cmd.get_names('selections'), ['foo']) self.assertEqual(cmd.get_names('all'), ['gly', 'cys', 'ramp1', 'foo'])
def apbs_surface(selection='all', maximum=None, minimum=None, map_name=None, ramp_name=None, grid=0.5, quiet=1): ''' DESCRIPTION Show electrostatic potential on surface (calculated with APBS). Important: surface_color is a object property, so when calculating surface potential for different selections and visualize them all together, you should first split them into separate objects. USAGE apbs_surface [ selection [, maximum [, minimum ]]] EXAMPLE fetch 2x19, async=0 split_chains apbs_surface 2x19_A, 10 apbs_surface 2x19_B, 10 SEE ALSO map_new_apbs, APBS Tools Plugin, isosurface, gradient, util.protein_vacuum_esp ''' quiet = int(quiet) if ramp_name is None: ramp_name = cmd.get_unused_name('ramp') if map_name is None: map_name = cmd.get_unused_name('map') map_new_apbs(map_name, selection, float(grid), quiet=quiet) if maximum is not None: maximum = float(maximum) minimum = -maximum if minimum is None else float(minimum) kwargs = {'range': [minimum, (minimum+maximum)*0.5, maximum]} else: kwargs = {'selection': selection} cmd.ramp_new(ramp_name, map_name, **kwargs) object_names = cmd.get_object_list('(' + selection + ')') for name in object_names: cmd.set('surface_color', ramp_name, name) cmd.show('surface', selection) cmd.set('surface_solvent', 0) cmd.set('surface_ramp_above_mode', 1)
def testSliceAction(self): sele = 'slice1' mapname = 'map1' self._make_map(mapname) cmd.slice_new(sele, mapname) cmd.ramp_new('r2', mapname) m = menu.slice_color(cmd, sele) self._eval_first(m) m = menu.slice_hide(cmd, sele) self._eval_first(m) m = menu.slice_show(cmd, sele) self._eval_first(m) m = menu.slice_action(cmd, sele) self._eval_first(m)
def map_esp(dens, esp, iso=0.02): """ Map the ESP onto the density. dens - File containing the density on a grid esp - File containing the ESP on a grid iso - isovalue for the density """ ename = path.splitext(esp)[0] dname = "esp_map" #"d_%s"%ename rname = "esp_ramp" #"r_%s"%ename cmd.load(dens, dname, zoom=0) cmd.load(esp, ename, zoom=0) cmd.ramp_new(rname, ename, stored.ramp_vals, stored.ramp_cols) show_iso(dname, float(iso), rname)
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 elec(self, cleanup=0): if not cleanup: cmd.disable() cmd.delete("pept") cmd.delete("e_pot") cmd.delete("e_lvl") cmd.load("$PYMOL_DATA/demo/pept.pkl") cmd.hide("(pept)") cmd.show("surface", "pept") cmd.set("coulomb_dielectric", 80.0) cmd.map_new("e_pot", "coulomb", 1.0, "pept", 5) cmd.ramp_new("e_lvl", "e_pot", [-3.6, -1.6, 0.4]) cmd.set("surface_color", "e_lvl", "pept") cmd.refresh() else: cmd.delete("pept") cmd.delete("e_pot") cmd.delete("e_lvl")
def elec(self,cleanup=0): if not cleanup: cmd.disable() cmd.delete("pept") cmd.delete("e_pot") cmd.delete("e_lvl") cmd.load("$PYMOL_DATA/demo/pept.pkl") cmd.hide("(pept)") cmd.show("surface","pept") cmd.set("coulomb_dielectric",80.0) cmd.map_new("e_pot","coulomb",1.0,"pept",5) cmd.ramp_new("e_lvl","e_pot",[-3.6,-1.6,0.4]) cmd.set("surface_color","e_lvl","pept") cmd.refresh() else: cmd.delete("pept") cmd.delete("e_pot") cmd.delete("e_lvl")
def protein_vacuum_esp(selection, mode=2, border=10.0, quiet = 1, _self=cmd): pymol=_self._pymol cmd=_self if ((string.split(selection)!=[selection]) or selection not in cmd.get_names('objects')): print " Error: must provide an object name" raise cmd.QuietException obj_name = selection + "_e_chg" map_name = selection + "_e_map" pot_name = selection + "_e_pot" cmd.disable(selection) cmd.delete(obj_name) cmd.delete(map_name) cmd.delete(pot_name) cmd.create(obj_name,"((polymer and ("+selection+ ") and (not resn A+C+T+G+U)) or ((bymol (polymer and ("+ selection+"))) and resn NME+NHE+ACE)) and (not hydro)") # try to just get protein... protein_assign_charges_and_radii(obj_name,_self=_self) ext = cmd.get_extent(obj_name) max_length = max(abs(ext[0][0] - ext[1][0]),abs(ext[0][1] - ext[1][1]),abs(ext[0][2]-ext[1][2])) + 2*border # compute an grid with a maximum dimension of 50, with 10 A borders around molecule, and a 1.0 A minimum grid sep = max_length/50.0 if sep<1.0: sep = 1.0 print " Util: Calculating electrostatic potential..." if mode==0: # absolute, no cutoff cmd.map_new(map_name,"coulomb",sep,obj_name,border) elif mode==1: # neutral, no cutoff cmd.map_new(map_name,"coulomb_neutral",sep,obj_name,border) else: # local, with cutoff cmd.map_new(map_name,"coulomb_local",sep,obj_name,border) cmd.ramp_new(pot_name, map_name, selection=obj_name,zero=1) cmd.hide("everything",obj_name) cmd.show("surface",selection) cmd.set("surface_color",pot_name,selection) cmd.set("surface_ramp_above_mode",1,selection)
def loadBfacts(mol, startaa=1, visual="Y"): obj = cmd.get_object_list(mol)[0] cmd.alter(mol, "b=-1.0") counter = int(startaa) bfacts = [] for item in List1: bfact = float(item * 10) 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", "blue_white_red", "%s and n. CA " % mol) cmd.ramp_new("count", obj, [min(bfacts), max(bfacts)], ['blue', 'white', 'red']) cmd.recolor()
def s2(mol, startaa=1, visual="Y"): """ Replaces B-factors with TALOS predicted RCI S2 values Thickness and color are determined by S2 values with thicker values being more dynamic 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 = 'predS2.tab' s2_only = [] with open(source) as s2_file: for lines in s2_file: searcher = re.search('\d+\.\d{3}', lines) if searcher != None: if int(lines.strip().split()[0]) < int(startaa): continue s2_only.append(searcher.group(0)) obj = cmd.get_object_list(mol)[0] cmd.alter(mol, "b=-1.0") counter = int(startaa) bfacts = [] for line in s2_only: bfact = ((1 / (float(line))) - float(line)) / 1.5 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", 7, obj) cmd.set("cartoon_putty_radius", max(bfacts), obj) cmd.spectrum("b", "white red", "%s and n. CA " % mol) cmd.ramp_new("color_bar", obj, [min(bfacts), max(bfacts)], ["white", "red"]) cmd.recolor()
def complexb(mol, startaa=1, visual="Y"): """ Replaces B-factors with a list of values contained in a plain txt file and colours the structure accordingly if in visual mode. usage: complexb mol, [startaa, [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: complexb 1LVM """ for subchains in cmd.get_chains(mol): source = "bfactors_%s_%s.txt" % (mol, subchains) obj = cmd.get_object_list(mol)[0] cmd.alter("%s and chain %s" % (mol, subchains), "b=-1.0") infile = open(source, 'r') counter = int(startaa) bfacts = [] for line in infile.readlines(): bfact = float(line) print(bfact) bfacts.append(bfact) # the counter method will break for skips encoded in fasta header # file. Needs fixing. cmd.alter( "%s and chain %s and resi %s" % (mol, subchains, counter), "b=%s" % bfact) counter = counter + 1 if visual == "Y": cmd.cartoon("tube", mol) cmd.spectrum("b", "rainbow", "%s" % mol, 1, 3) # print(b) cmd.ramp_new("count", obj, [1, 3], "rainbow") cmd.recolor()
def test(self): cmd.viewport(200, 100) cmd.fragment('ethylene', 'm1') cmd.remove('hydro') cmd.pseudoatom('p1', 'index 1') cmd.disable('p1') cmd.ramp_new('r1', 'p1', [0.1, 1.2], ['red', 'blue']) cmd.disable('r1') cmd.color('r1') cmd.show_as('sticks', 'm1') cmd.orient('m1') cmd.move('z', 11) self.ambientOnly() img = self.get_imagearray() self.assertImageHasColor('red', img) self.assertImageHasColor('blue', img) self.assertImageHasColor([.5, .0, .5], img, delta=1)
def ramp_levels(name, levels, quiet=1): ''' DESCRIPTION Changes the slot levels of a ramp. SEE ALSO ramp_new, isolevel ''' quiet = int(quiet) if cmd.is_string(levels): levels = cmd.safe_list_eval(levels) try: position = cmd.get_names('all').index(name) odata = cmd.get_session(name, 1, 1, 0, 0)['names'][0] if odata[4] != 8: raise TypeError('not a ramp') data = odata[5] except: print(' Error: Get session data for ramp "%s" failed' % (name)) raise CmdException if len(levels) != len(data[3]): print(' Error: number of levels must agree with existing object') raise CmdException map_name = data[6] colors = [data[4][i:i + 3] for i in range(0, len(data[4]), 3)] cmd.ramp_new(name, map_name, levels, colors, quiet=quiet) # restore original position if position == 0: cmd.order(name, location='top') else: cmd.order(cmd.get_names('all')[position - 1] + ' ' + name)
def ramp_levels(name, levels, quiet=1): ''' DESCRIPTION Changes the slot levels of a ramp. SEE ALSO ramp_new, isolevel ''' quiet = int(quiet) if cmd.is_string(levels): levels = cmd.safe_list_eval(levels) try: position = cmd.get_names('all').index(name) odata = cmd.get_session(name, 1, 1, 0, 0)['names'][0] if odata[4] != 8: raise TypeError('not a ramp') data = odata[5] except: print(' Error: Get session data for ramp "%s" failed' % (name)) raise CmdException if len(levels) != len(data[3]): print(' Error: number of levels must agree with existing object') raise CmdException map_name = data[6] colors = [data[4][i:i+3] for i in range(0, len(data[4]), 3)] cmd.ramp_new(name, map_name, levels, colors, quiet=quiet) # restore original position if position == 0: cmd.order(name, location='top') else: cmd.order(cmd.get_names('all')[position-1] + ' ' + name)
def testColorramps(self): cmd.ramp_new('r1', 'none') cmd.ramp_new('r2', 'none') m = menu.colorramps(cmd, '') d = self._to_dict(m) self.assertEqual(sorted(d), ['r1', 'r2'])
def testGetObjectList(self): cmd.fragment('gly') cmd.fragment('cys') cmd.ramp_new('ramp1', 'none') # non-molecular object self.assertEqual(cmd.get_object_list(), ['gly', 'cys']) self.assertEqual(cmd.get_object_list('elem S'), ['cys'])
def testRampAction(self): sele = 'r1' cmd.ramp_new(sele, 'none') self._testRampColor(sele) m = menu.ramp_action(cmd, sele) self._eval_first(m)
def _ramp_new(self): cmd.ramp_new('foo_ramp', 'foo_map', '[red, white, blue, green]')
def bfactorRamp(mol, color1="blue", color2="red", color3="yellow", cartoon="off", cartoon_putty="off", invcolor="grey40", style="off", fancy="off"): ''' DESCRIPTION Version: bfactorRamp_v1.1 Author : Erik Breslmayr; April 2020 - bfactorRamp colors the molecule of choise in regard of bfactors provided in the pdb file and adds a color legend starting from the lowest to the highest bfactor. - Additionally some styling features are included, for nicer visualization Usage: bfactorRamp mol, color1, color2, color3, cartoon=on or off, cartoon_putty=on or off, invcolor=color, style=on or off, fancy=on or off mol = any object selection (within one single object!) color1,2,3 (optional) = three colors, first for lowest, second for middle and third for highest bfactors cartoon (optional) = on or off -> enbales cartoon representation cartoon_putty (optional) = on or off -> enbales cartoon_putty representation invcolor (optional) = add color, which should represent not selected atoms style (optional) = styles the cartoon representation in regard of helix oval length and width fancy = changes to fancy helices representaton Defaults: - spectrum colors: blue, red, yellow - cartoon: off - cartoon_putty: off - invcolor: grey40 - style: off - fancy: off Examples: > bfactorRamp objectName -> uses all defaults > bfactorRamp objectName, red, green, grey -> changes the colors for the spectrum > bfactorRamp objectName, cartoon=on -> turns cartoon representation on > bfactorRamp objectName, cartoon=on -> turns cartoon_putty representation on > bfactorRamp objectName, invcolor=green -> changes the color of the not selected region to green > bfactorRamp objectName, style=on -> changes helices style and not selected region will be transparent > bfactorRamp objectName, fancy=on -> changes helices style to fancy and not selected region will be transparent ''' obj = cmd.get_object_list(mol)[0] range = cmd.spectrum("b", "%s %s %s" % (color1, color2, color3), mol) cmd.select("invSele", "!%s" % (mol)) cmd.color(invcolor, "invSele") cmd.ramp_new("ramp", obj, range, color=["%s" % (color1), "%s" % (color2), "%s" % (color3)]) #reset styles cmd.set("cartoon_transparency", 0, "enabled") cmd.set("cartoon_oval_length", 1.2, obj) cmd.set("cartoon_oval_width", 0.25, obj) cmd.set("cartoon_fancy_helices", 0, obj) cmd.set("cartoon_highlight_color", -1, obj) if cartoon == "on": cmd.show_as("cartoon", mol) cmd.dss(obj, 1) cmd.recolor() if cartoon_putty == "on": cmd.show_as("cartoon", mol) cmd.cartoon("putty", mol) cmd.recolor() if style == "on": cmd.set("cartoon_transparency", 0.5, "invSele") cmd.set("cartoon_oval_length", 0.8, obj) cmd.set("cartoon_oval_width", 0.2, obj) if fancy == "on": cmd.set("cartoon_transparency", 0.5, "invSele") cmd.set("cartoon_highlight_color", invcolor, obj) cmd.set("cartoon_fancy_helices", 1, obj) #Output for screen print("for help type: help bfactorRamp") print("") print("Minimum bfactor: %s | Maximum bfactor: %s" % (range[0], range[1])) print("") print("Following settings were taken:") print("- mol : %s" % (obj)) print("- color1,2,3 : %s, %s, %s" % (color1, color2, color3)) print("- cartoon : %s" % (cartoon)) print("- cartoon_putty : %s" % (cartoon_putty)) print("- invcolor : %s" % (invcolor)) print("- style : %s" % (style)) print("- fancy : %s" % (fancy)) return (color1, color2, color3)
def updateColor(self): selection = 'all' stored.atoms_charge = [] stored.atoms_colors = [] cmd.map_new('chargyc_map', selection="(all)") if not self.colorNeutral: tkMessageBox.showerror("Error", "Set Neutral Color, Please") return if not self.colorNegative: tkMessageBox.showerror("Error", "Set Negative Color, Please") return if not self.colorPositive: tkMessageBox.showerror("Error", "Set Positive Color, Please") return cmd.iterate_state(1, '(' + selection + ')', 'stored.atoms_charge.append(partial_charge)') _i = 0 minValue = None maxValue = None while _i < len(stored.atoms_charge): color = [] if _i == 0: maxValue = stored.atoms_charge[_i] minValue = stored.atoms_charge[_i] if(stored.atoms_charge[_i] > maxValue): maxValue = stored.atoms_charge[_i] if stored.atoms_charge[_i] < minValue: minValue = stored.atoms_charge[_i] _i += 1 self.minNegativeLbl["text"] = 'Min Found: ' + str(round(minValue, 3)) self.maxPositiveLbl["text"] = 'Max Found: ' + str(round(maxValue, 3)) if(self.scaleNegative == 0.0 and self.scalePositive == 0.0): self.scaleNegative = round(minValue, 3) self.scalePositive = round(maxValue, 3) self.sclSelectNegative.delete(0, "end") self.sclSelectPositive.delete(0, "end") self.sclSelectNegative.insert(0, round(minValue, 3)) self.sclSelectPositive.insert(0, round(maxValue, 3)) else: self.scaleNegative = float(self.sclSelectNegative.get()) self.scalePositive = float(self.sclSelectPositive.get()) minValue = float(self.sclSelectNegative.get()) maxValue = float(self.sclSelectPositive.get()) self.scaleLbl["text"] = 'Scale: ' + str( self.scaleNegative) + ' to ' + str(self.scalePositive) middleValue = 0 if(maxValue < 0): maxValue = 0 if(minValue > 0): minValue = 0 _i = 0 while _i < len(stored.atoms_charge): color = [] cmd.set_color("neutral_color", self.colorNeutral[0]) cmd.set_color("positive_color", self.colorPositive[0]) cmd.set_color("negative_color", self.colorNegative[0]) if(stored.atoms_charge[_i] >= middleValue): if(stored.atoms_charge[_i] == middleValue): cmd.set_color(str(_i) + "_color", self.colorNeutral[0]) else: cmd.set_color(str(_i) + "_color", self.getColor( self.colorNeutral[0], self.colorPositive[0], maxValue, stored.atoms_charge[_i] if stored.atoms_charge[_i] < maxValue else maxValue)) else: cmd.set_color(str(_i) + "_color", self.getColor( self.colorNeutral[0], self.colorNegative[0], abs(minValue), abs(stored.atoms_charge[_i]) if abs(stored.atoms_charge[_i]) < abs(minValue) else abs(minValue))) index = cmd.get_color_index(str(_i) + "_color") stored.atoms_colors.append(index) _i += 1 cmd.alter_state(1, '(' + selection + ')', "color=stored.atoms_colors.pop(0)") cmd.ramp_new('chargy_ramp', 'chargyc_map', range=[self.scaleNegative, ((self.scaleNegative+self.scalePositive)/2.0), self.scalePositive], color=['negative_color', 'neutral_color', 'positive_color'])
def displayInPyMOL(outdir, selectedPDBChain, atomNumbersProbDic): pdbCWMs = os.path.join(outdir, '%s_withConservedWaters.pdb' % selectedPDBChain) pdb = os.path.join(outdir, '%s.pdb' % selectedPDBChain) h_bond_dist = 4.0 queryProteinCWMs = '%s_withConservedWaters' % selectedPDBChain cmd.load(pdbCWMs) cmd.orient(queryProteinCWMs) cmd.h_add(queryProteinCWMs) cmd.select('cwm_protein','polymer and %s' % queryProteinCWMs) cmd.select('cwm_waters','resn hoh and %s' % queryProteinCWMs) cmd.select('cwm_ligand','organic and %s' % queryProteinCWMs) cmd.select('don', '(elem n,o and (neighbor hydro)) and %s' % queryProteinCWMs) cmd.select('acc', '(elem o or (elem n and not (neighbor hydro))) and %s' % queryProteinCWMs) # h bonds between protein and conserved waters cmd.distance ('PW_HBA', '(cwm_protein and acc)','(cwm_waters and don)', h_bond_dist) cmd.distance ('PW_HBD', '(cwm_protein and don)','(cwm_waters and acc)', h_bond_dist) # h bonds between ligands and conserved waters cmd.distance ('LW_HBA', '(cwm_ligand and acc)','(cwm_waters and don)', h_bond_dist) cmd.distance ('LW_HBD', '(cwm_ligand and don)','(cwm_waters and acc)', h_bond_dist) # h bonds in between conserved waters cmd.distance ('HW_HBA', '(cwm_waters and acc)','(cwm_waters and don)', h_bond_dist) cmd.distance ('HW_HBD', '(cwm_waters and don)','(cwm_waters and acc)', h_bond_dist) cmd.delete('don') cmd.delete('acc') cmd.set('dash_color','yellow') cmd.set('dash_gap',0.3) cmd.set('dash_length',0.2) cmd.set('dash_round_ends','on') cmd.set('dash_width',3) # color and display cmd.util.cbam('cwm_ligand') cmd.show_as('sticks','cwm_ligand') MinDoc = min(atomNumbersProbDic.values()) MaxDoc = max(atomNumbersProbDic.values()) cmd.create ('conserved_waters','cwm_waters') for key, value in atomNumbersProbDic.items(): cmd.alter('/conserved_waters//A/HOH`%s/O' % key, 'b=%s' % value) cmd.spectrum('b', 'red_blue', 'conserved_waters',minimum=MinDoc, maximum=MaxDoc) cmd.ramp_new('DOC', 'conserved_waters', range = [MinDoc,MaxDoc], color = '[red,blue]') cmd.set('sphere_scale',0.40,'conserved_waters') cmd.show_as('spheres','conserved_waters') cmd.hide('labels','*_HB*') cmd.remove('(hydro) and conserved_waters') cmd.remove('(hydro) and %s' % queryProteinCWMs) cmd.util.cbac('cwm_protein') cmd.set('transparency', 0.2) cmd.show('surface', 'cwm_protein') cmd.set('surface_color', 'gray', 'cwm_protein') cmd.load(pdb) cmd.create('all waters', 'resn hoh and %s' % selectedPDBChain) cmd.color('red','ss h and %s' % selectedPDBChain) cmd.color('yellow','ss s and %s' % selectedPDBChain) cmd.color('green','ss l+ and %s' % selectedPDBChain) cmd.show_as('cartoon', selectedPDBChain) cmd.set('ray_shadows', 0)
def rmsdCA(refMol, tgtMol, puttyview="Y", bfactorca="CA"): """ Written up by Yufeng Tong 2020-01-29 Inspired by rmsdByRes Zhenting Gao on 7/28/2016 and by loadBfacts from PyMOLWiki USAGE rmsdCA refMol, tgtMol, puttyview="Y", bfactorca="CA" Calculate the RMSD of Calpha and backbone for each residue pairs from two chains of proteins with same residue numbers and close conformations for the two structures. The two proteins can be mutants. Only residue numbers but not identity are matched. It will generate a putty representation of the target molecule by default. You can specify whether to use the RMSD of Calpha or Backbone for the coloring of the putty display. I think it's not neccessary to calculate RMSD of the whole residue. A CSV file is saved of the calculated RMSD of Calpha and backbone atoms. A PDB file is saved with BFactor replaced by the RMSD. Workflow Read reference and target pdb files 1. Select two objects for comparison 2. Align two structures 3. rmsdByRes refMol, tgtMol TODO: 1. Save output files to the folder pdb files are loaded. 2. Handle missing residues. """ # Create temporary objects, exclude alternative conformation B cmd.delete("tgt_gzt rmsdPuttyScale") cmd.create("ref_gzt", refMol + " and polymer and not alt B") cmd.alter("ref_gzt", "chain='A'") cmd.alter("ref_gzt", "segi=''") cmd.create("tgt_gzt", tgtMol + " and polymer and not alt B") cmd.alter("tgt_gzt", "chain='A'") cmd.alter("tgt_gzt", "segi=''") cmd.alter("tgt_gzt", "b=-1.0") # parameters outputText = "" csvHeadline = ("refMol,refRes,refResID,target,residueName,residueId," "rmsdResCa,rmsdResBackbone\n") outputFile = 'rmsd%s_%s.csv' % (bfactorca, tgtMol) outputpdb = 'rmsdBFactor%s_%s.pdb' % (bfactorca, tgtMol) bfactors = [] # select alpha carbon of selected residues in reference structure calpha_ref = cmd.get_model("ref_gzt and name CA") calpha_tgt = cmd.get_model("tgt_gzt and name CA") # build an index dict of {resi : index} ref_dict = {int(v.resi): k for k, v in enumerate(calpha_ref.atom)} tgt_dict = {int(v.resi): k for k, v in enumerate(calpha_tgt.atom)} # loop through residues in the target molecule and calculate per residue RMSDs. for k in sorted(ref_dict): if k in tgt_dict: ref_atom = calpha_ref.atom[ref_dict[k]] tgt_atom = calpha_tgt.atom[tgt_dict[k]] rmsdResCA = cmd.rms_cur( "ref_gzt and n. ca and i. " + ref_atom.resi, "tgt_gzt and n. ca and i. " + tgt_atom.resi, matchmaker=-1) rmsdResBb = cmd.rms_cur( "ref_gzt and n. ca+n+c+o and i. " + ref_atom.resi, "tgt_gzt and n. ca+n+c+o and i. " + tgt_atom.resi, matchmaker=-1) if bfactorca == "bb": bfactor = rmsdResBb else: bfactor = rmsdResCA cmd.alter("%s and i. %s" % ("tgt_gzt", tgt_atom.resi), "b=%s" % bfactor) bfactors.append(bfactor) outputText += "%s,%s,%s,%s,%s,%s,%.3f,%.3f\n" % ( refMol, ref_atom.resn, ref_atom.resi, tgtMol, tgt_atom.resn, tgt_atom.resi, rmsdResCA, rmsdResBb) print(outputText) max_b, min_b = max(bfactors), min(bfactors) print("RMSD: max:%.3f; min:%.3f" % (max_b, min_b)) if puttyview == "Y": cmd.show_as("cartoon", "tgt_gzt") cmd.cartoon("putty", "tgt_gzt") cmd.set("cartoon_putty_scale_min", min_b, "tgt_gzt") cmd.set("cartoon_putty_scale_max", max_b, "tgt_gzt") cmd.set("cartoon_putty_transform", 0, "tgt_gzt") cmd.spectrum("b", "rainbow", "tgt_gzt and n. CA") cmd.ramp_new("rmsdPuttyScale", "tgt_gzt", [min_b, max_b], "rainbow") cmd.recolor() # Destroy temporary objects cmd.delete("ref_gzt") # Save data into csv and pdb f = open(outputFile, 'w+') f.write(csvHeadline) f.write(outputText) f.close() cmd.save(outputpdb, "tgt_gzt") print("Results are saved in %s and %s " % (outputFile, outputpdb))