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 testRepsExist(self): cmd.viewport(200, 150) cmd.load(self.datafile('1oky-frag.pdb'), 'm1') # make some nonbonded cmd.unbond('resi 115-', 'resi 115-') # labels cmd.label('all', 'name') # measurements cmd.distance('measure1', 'index 1', 'index 10') cmd.angle('measure1', 'index 1', 'index 10', 'index 20') cmd.dihedral('measure1', 'index 1', 'index 10', 'index 20', 'index 30') # color test setup cmd.color('white', '*') cmd.set('ambient', 1) cmd.set('depth_cue', 0) cmd.set('antialias', 0) cmd.set('line_smooth', 0) cmd.orient() # test most reps for rep in REPS: cmd.show_as(rep) self.assertImageHasColor('white', msg='rep missing: ' + rep) # test cartoon cmd.show_as('cartoon') for cart in CARTOONS: cmd.cartoon(cart) self.assertImageHasColor('white', msg='cartoon missing: ' + cart)
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 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 rcd(selection="all"): """ fancy ribbon coloring for large RNA comparisons """ rc(selection) cmd.cartoon('dumbbell') cmd.set('cartoon_dumbbell_radius', 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 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 rcd( selection = "all" ): """ fancy ribbon coloring for large RNA comparisons """ rc( selection ) cmd.cartoon( 'dumbbell') cmd.set( 'cartoon_dumbbell_radius', 0.5 )
def map_interaction_freq_to_structure(pdb, chain, interaction_freq_file, exp_rep_id, threshold=0.0): ### Background coloring settings cmd.bg_color("white") cmd.fetch(pdb) cmd.hide() cmd.show("cartoon") cmd.cartoon("loop") cmd.color("white", pdb) cmd.set("dash_gap", 0) cmd.set("dash_width", 5) ### Extract interaction frequency information interaction_freq_info_list = getInteractionFreqList( pdb, interaction_freq_file, exp_rep_id, threshold) ### Color interactions by frequency print("color interactions by frequency") for gpcrdb_pair, resid1, resid2, freq in interaction_freq_info_list: cmd.distance( "%s" % (gpcrdb_pair), "%s and resi %d and name CA and chain %s" % (pdb, resid1, chain), "%s and resi %d and name CA and chain %s" % (pdb, resid2, chain)) mapped_col = freq_to_grayscale(freq) cmd.set("dash_color", mapped_col, gpcrdb_pair) cmd.hide("labels")
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 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 defaults(tag = ''): if tag == 'cartoon': cmd.set('cartoon_rect_length', '1.4', 'all') cmd.set('cartoon_oval_length', '1.4', 'all') cmd.set('cartoon_rect_width', '0.3', 'all') cmd.set('cartoon_oval_width', '0.3', 'all') cmd.set('cartoon_tube_radius', '0.5', 'all') cmd.set('cartoon_transparency', '0.0', 'all') cmd.cartoon('automatic', glb.SELE) GUI.view['toonWidth'].set('1.4') GUI.view['toonThickness'].set('0.3') GUI.view['cartoonTransparency'].set('0.0') GUI.view['toonTubeRadius'].set('0.5') GUI.view['ribbonTypes'].invoke(0) elif tag == 'spheres': cmd.set('sphere_scale', '0.7', 'all') cmd.set('sphere_transparency', '0.0', 'all') GUI.view['sphereScale'].set('0.7') GUI.view['sphereTransparency'].set('0.0') elif tag == 'sticks': cmd.set('stick_radius', '0.2', 'all') cmd.set('stick_transparency', '0.0', 'all') GUI.view['stickRadius'].set('0.2') GUI.view['stickTransparency'].set('0.0') elif tag == 'surface': cmd.set('transparency', '0.0', 'all') GUI.view['surfaceTransparency'].set('0.0') elif tag == 'ambient': cmd.set('ambient', '0.25', 'all') GUI.view['ambientLight'].set('0.25') cmd.delete('surface') cmd.delete('mesh1') cmd.delete('cartoon') cmd.delete('helix') cmd.delete('sheets') cmd.delete('sticks') cmd.delete('rov_1') cmd.delete('rov_m1') cmd.delete('map1') cmd.delete('sphere1') cmd.delete('rov_pc') cmd.delete('rov_s1') cmd.set("roving_detail", 0) cmd.set("roving_origin", 0) cmd.set("roving_sticks", 0) cmd.set('roving_spheres', 0) cmd.set("roving_polar_contacts", 0) cmd.set('roving_lines', 0) cmd.set('roving_isosurface', 0) cmd.set('transparency', '0.0', 'all') cmd.set('cartoon_transparency', '0.0', 'all') cmd.set('sphere_transparency', '0.0', 'all') cmd.set('stick_transparency', '0.0', 'all') cmd.set('sphere_scale', '0.7', 'all') cmd.set('stick_radius', '0.2', 'all') cmd.cartoon('automatic', 'all')
def testAtomCartoonTransparencyNuc(self): ''' Test atom-level cartoon_transparency with nucleic acid ''' cmd.load(self.datafile('1ehz-5.pdb')) cmd.select('sele', 'resi 4-', 0) # hide blended parts between residues cmd.cartoon('skip', 'resi 3') return self._testAtomCartoonTransparency()
def stride2pymol(mol='', sel=''): """ usage: stride2pymol object, [selection] where the object name is required, but the selection is optional (defaults to all of the object). e.g. stride2pymol prot, i. 1-300 and c. a """ #Save the specified molecule (and optional selection sel) to a temporary #PDB format file and call stride_extract on it from pymol import cmd # map stride's secondary structure alphabet onto pymol's # strides definitions: # G = 3/10 helix # B = Bridge # C = coil # T = turn # H = helix # E = strand/sheet # create tmpfile from the selection name and the current time in seconds since the epoch ext = str(int(time.time())) tmpfile = mol + '.pdb_' + ext if sel: # make sure that selection forces the molecule name to be included in the selection # (i.e. is 'and'-ed with the rest of the selection) sel = mol + ' and ' + sel cmd.save(tmpfile, sel, 1, 'pdb') else: cmd.save(tmpfile, mol, 1, 'pdb') # run stride on the saved pdb file and read the standard output to extract the # data to the sec_dict and res_dict dictionaries sec_dict, res_dict = stride_extract(tmpfile) os.remove(tmpfile) # make lists of chains and residues within the chains and sort them chain_list = sec_dict.keys() chain_list.sort() for chain in chain_list: res_list = sec_dict[chain].keys() res_list.sort() # now do the alteration of the secondary structure. for resnum in res_list: cmd.do( "alter /%s//%s/%s,ss='%s'" % (mol, chain, resnum, stride_2_pymol[sec_dict[chain][resnum]])) # make sure that cartoon automatic is set for this molecule cmd.cartoon('automatic', mol) # force a rebuild of the drawing cmd.rebuild()
def testAtomCartoonTransparency(self): ''' Test atom-level cartoon_transparency ''' cmd.load(self.datafile('1oky-frag.pdb')) cmd.select('sele', 'resi 106-111', 0) # hide blended parts between residues cmd.cartoon('skip', 'resi 105+112') return self._testAtomCartoonTransparency()
def stride2pymol(mol='',sel=''): """ usage: stride2pymol object, [selection] where the object name is required, but the selection is optional (defaults to all of the object). e.g. stride2pymol prot, i. 1-300 and c. a """ #Save the specified molecule (and optional selection sel) to a temporary #PDB format file and call stride_extract on it from pymol import cmd # map stride's secondary structure alphabet onto pymol's # strides definitions: # G = 3/10 helix # B = Bridge # C = coil # T = turn # H = helix # E = strand/sheet # create tmpfile from the selection name and the current time in seconds since the epoch ext = str(int(time.time())) tmpfile=mol + '.pdb_' + ext if sel: # make sure that selection forces the molecule name to be included in the selection # (i.e. is 'and'-ed with the rest of the selection) sel = mol + ' and ' + sel cmd.save(tmpfile,sel,1,'pdb') else: cmd.save(tmpfile,mol,1,'pdb') # run stride on the saved pdb file and read the standard output to extract the # data to the sec_dict and res_dict dictionaries sec_dict,res_dict = stride_extract(tmpfile) os.remove(tmpfile) # make lists of chains and residues within the chains and sort them chain_list = sec_dict.keys() chain_list.sort() for chain in chain_list: res_list = sec_dict[chain].keys() res_list.sort() # now do the alteration of the secondary structure. for resnum in res_list: cmd.do("alter /%s//%s/%s,ss='%s'" % (mol,chain,resnum,stride_2_pymol[sec_dict[chain][resnum]])) # make sure that cartoon automatic is set for this molecule cmd.cartoon('automatic',mol) # force a rebuild of the drawing cmd.rebuild()
def testAtomCartoonTransparencyCylHelices(self): ''' Test atom-level cartoon_transparency with cylindrical helices ''' cmd.load(self.datafile('1oky-frag.pdb')) cmd.select('sele', 'resi 113-', 0) # hide blended parts between residues cmd.cartoon('skip', 'resi 112') cmd.set('cartoon_cylindrical_helices') return self._testAtomCartoonTransparency()
def _common_ss_alter(selection, ss_dict, ss_map, raw=''): ''' DESCRIPTION Shared code of 'dssp' and 'stride' functions. ''' if raw != 'ss': cmd.alter(selection, 'ss = ss_map.get(ss_dict.get((model,chain,resi)), "")', space={'ss_dict': ss_dict, 'ss_map': ss_map}) if raw != '': cmd.alter(selection, raw + ' = ss_dict.get((model,chain,resi), "")', space={'ss_dict': ss_dict}) cmd.cartoon('auto', selection) cmd.rebuild(selection, 'cartoon')
def 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( "resi", "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("count", "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 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 map_water_stability(TOP, WATER_STABILITY): top_name = TOP.split("/")[-1].split(".")[0] cmd.bg_color("white") cmd.load(TOP) cmd.hide() cmd.show("cartoon") cmd.cartoon("loop") cmd.do("set cartoon_transparency, 0.7") cmd.do("set sphere_scale, 0.75") cmd.color("white", top_name) f = open(WATER_STABILITY, 'r') for line in f: linfo = line.strip().split("\t") resi, occupancy = linfo[0], float(linfo[1]) color = occupancy_to_color(occupancy) cmd.do("sele water_%s, resn HOH and resi %s" % (resi, resi)) cmd.do("show spheres, water_%s" % (resi)) cmd.color(color, "water_%s" % (resi))
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 render_visualization(PDB, LIGAND, TOP_FILE, hbond_pairs): """ Render the visualization of each of the interactions between resid1 -- water -- resid2 """ top_name = PDB cmd.bg_color("white") cmd.load(TOP_FILE) cmd.hide() cmd.show("cartoon") cmd.cartoon("loop") cmd.do("set cartoon_transparency, 0.7") cmd.do("remove hydrogens") cmd.color("white", top_name) ### Draw background residues and waters aa_query, w_query = display_resi_water_query(PDB, hbond_pairs) lig_query = "sele lig, resn " + LIGAND cmd.do(aa_query) cmd.do(w_query) cmd.do(lig_query) cmd.do("show sticks, aa") cmd.do("show sticks, lig") cmd.do("show spheres, w") cmd.do("set sphere_scale, 0.25") ### Draw lines for interactions between ligand/residues to waters and waters to waters for atom1, atom2 in hbond_pairs: sele1 = gen_selection(atom1, PDB, LIGAND, top_name) sele2 = gen_selection(atom2, PDB, LIGAND, top_name) for i, s1 in enumerate(sele1): for j, s2 in enumerate(sele2): label = atom1 + "_" + atom2 + "_" + str(i) + "_" + str(j) print(label, s1, s2) dist = cmd.distance(label, s1, s2) if (dist > DIST_CUTOFF): cmd.delete(label) else: cmd.set("dash_color", "black", label) cmd.hide("labels")
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 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 cartoon_view(cartoon=None): glb.update() cmd.hide('all') objects = cmd.get_names('all') if 'protein' in objects: cmd.show('cartoon', 'protein') cmd.color("red", "ss h") cmd.color("yellow", "ss s") cmd.color("cyan", "ss l+\'\'") if 'ligands' in objects: glb.procolor('ligands','spheres','orange',None) if 'dna' in objects: glb.procolor('dna','sticks','cpk',None) if 'rna' in objects: glb.procolor('rna','sticks','cpk',None) if cartoon == 'putty': try: cmd.cartoon('putty', 'protein') except: showinfo('Error', 'Putty is not supported by this version of PyMol') else: cmd.set('cartoon_ring_mode' , '1')
def test(self): cmd.set('cartoon_gap_cutoff', 0) # default varies by version self.ambientOnly() cmd.viewport(150, 150) cmd.load(self.datafile('1oky-frag.pdb')) cmd.cartoon('dash') cmd.show_as('cartoon') cmd.orient() # no gaps img_nogaps = self.get_imagearray() # gap of length 0 cmd.unbond('96/C', '97/N') img_gap = self.get_imagearray() self.assertFalse((img_gap == img_nogaps).all()) # close gap with setting, should match first image (special case) cmd.set('cartoon_gap_cutoff', 1) # exact cutoff img_gap = self.get_imagearray() self.assertTrue((img_gap == img_nogaps).all()) # gap of length 1 cmd.remove('92/') img_gap = self.get_imagearray() cmd.set('cartoon_gap_cutoff', 2) # exact cutoff img_nogaps = self.get_imagearray() self.assertFalse((img_gap == img_nogaps).all()) # gap of length 3 cmd.remove('102-104/') cmd.cartoon('auto') # default img_gap = self.get_imagearray() cmd.set('cartoon_gap_cutoff', 10) # arbitrary larger cutoff img_nogaps = self.get_imagearray() self.assertFalse((img_gap == img_nogaps).all())
def cartoon_view(cartoon=None): glb.update() cmd.hide('all') objects = cmd.get_names('all') if 'protein' in objects: cmd.show('cartoon', 'protein') cmd.color("red", "ss h") cmd.color("yellow", "ss s") cmd.color("cyan", "ss l+\'\'") if 'ligands' in objects: glb.procolor('ligands', 'spheres', 'orange', None) if 'dna' in objects: glb.procolor('dna', 'sticks', 'cpk', None) if 'rna' in objects: glb.procolor('rna', 'sticks', 'cpk', None) if cartoon == 'putty': try: cmd.cartoon('putty', 'protein') except: showinfo('Error', 'Putty is not supported by this version of PyMol') else: cmd.set('cartoon_ring_mode', '1')
def ribType(tag): try: glb.populate() if tag == 'Skip': cmd.cartoon('skip', glb.SELE) elif tag == 'Automatic': cmd.cartoon('automatic', glb.SELE) elif tag == 'Oval': cmd.cartoon('oval', glb.SELE) elif tag == 'Tube': cmd.cartoon('tube', glb.SELE) elif tag == 'Rectangle': cmd.cartoon('rectangle', glb.SELE) elif tag == 'Loop': cmd.cartoon('loop', glb.SELE) elif tag == 'Arrow': cmd.cartoon('arrow', glb.SELE) elif tag == 'Dumbbell': cmd.cartoon('dumbbell', glb.SELE) elif tag == 'Putty': cmd.cartoon('putty', glb.SELE) except: showinfo('Error', 'Drop down menu is set to an invalid selection\n'+ 'You may need to update selections')
def reps(self, cleanup=0): rep_list = [ "lines", "sticks", "spheres", "surface", "mesh", "dots", "ribbon", "cartoon" ] try: if not cleanup: cmd.disable() cmd.set("suspend_updates", 1, quiet=1) cmd.load("$PYMOL_DATA/demo/pept.pdb", "rep1") cmd.alter("rep1///1-5+8-13/", "ss='S'") cmd.cartoon("auto") cmd.hide("everything", "rep1") for a in range(2, 9): cmd.create("rep%d" % a, "rep1") for x, y in enumerate(rep_list, 1): cmd.show(x, "rep%d" % y) cmd.reset() cmd.zoom("rep1", 24) util.cbay("rep2") util.cbac("rep3") util.cbas("rep4") util.cbab("rep5") util.cbaw("rep6") util.cbay("rep8") cmd.set("suspend_updates", 0, quiet=1) scale = 0.5 for b in range(1, 20): cmd.set("suspend_updates", 0, quiet=1) cmd.refresh() cmd.set("suspend_updates", 1, quiet=1) xt = -3.2 yt = 1.6 for a in range(1, 5): cmd.translate([xt * scale, yt * scale, 0], object="rep%d" % a, camera=0) xt = xt + 2 yt = -yt xt = -3.2 for a in range(5, 9): cmd.translate([xt * scale, yt * scale, 0], object="rep%d" % a, camera=0) xt = xt + 2 for a in range(1, 9): cmd.origin("rep%d" % a, object="rep%d" % a) cmd.mset("1") st = ' '.join( map( lambda x, y: "rotate angle=-3,object=rep%d,axis=%s;" % (x, y), list(range(1, 9)), ['x', 'y', 'x', 'y', 'x', 'y', 'x', 'y'])) cmd.mdo(1, st) cmd.set("suspend_updates", 0, quiet=1) cmd.mplay() cgo = [] axes = [[4.5, 0.0, 0.0], [0.0, 3.0, 0.0], [0.0, 0.0, 3.0]] c = 1 for a in rep_list: ext = cmd.get_extent("rep%d" % c) pos = [(ext[0][0] + ext[1][0]) / 2, (ext[0][1] + ext[1][1]) / 2 + 14, (ext[0][2] + ext[1][2]) / 2] c = c + 1 pos[0] = pos[0] - (measure_text(plain, a, axes) / 2) wire_text(cgo, plain, pos, a, axes) cmd.set("cgo_line_width", 1.5) cmd.set("auto_zoom", 0) cmd.load_cgo(cgo, 'reps') cmd.set("auto_zoom", 1) else: cmd.delete("rep*") cmd.mset() cmd.mstop() except: traceback.print_exc()
def reps(self,cleanup=0): rep_list = [ "lines","sticks","spheres","surface","mesh","dots","ribbon","cartoon" ] try: if not cleanup: cmd.disable() cmd.set("suspend_updates",1,quiet=1) cmd.load("$PYMOL_DATA/demo/pept.pdb","rep1") cmd.alter("rep1///1-5+8-13/","ss='S'") cmd.cartoon("auto") cmd.hide("everything","rep1") for a in range(2,9): cmd.create("rep%d"%a,"rep1") for x, y in enumerate(rep_list, 1): cmd.show(x, "rep%d" % y) cmd.reset() cmd.zoom("rep1",24) util.cbay("rep2") util.cbac("rep3") util.cbas("rep4") util.cbab("rep5") util.cbaw("rep6") util.cbay("rep8") cmd.set("suspend_updates",0,quiet=1) scale=0.5 for b in range(1,20): cmd.set("suspend_updates",0,quiet=1) cmd.refresh() cmd.set("suspend_updates",1,quiet=1) xt=-3.2 yt=1.6 for a in range(1,5): cmd.translate([xt*scale,yt*scale,0],object="rep%d"%a,camera=0) xt=xt+2 yt=-yt xt=-3.2 for a in range(5,9): cmd.translate([xt*scale,yt*scale,0],object="rep%d"%a,camera=0) xt=xt+2 for a in range(1,9): cmd.origin("rep%d"%a,object="rep%d"%a) cmd.mset("1") st = ' '.join(map(lambda x,y:"rotate angle=-3,object=rep%d,axis=%s;"%(x,y),list(range(1,9)), ['x','y','x','y','x','y','x','y'])) cmd.mdo(1,st) cmd.set("suspend_updates",0,quiet=1) cmd.mplay() cgo = [] axes = [[4.5,0.0,0.0],[0.0,3.0,0.0],[0.0,0.0,3.0]] c = 1 for a in rep_list: ext = cmd.get_extent("rep%d"%c) pos = [(ext[0][0]+ext[1][0])/2, (ext[0][1]+ext[1][1])/2+14, (ext[0][2]+ext[1][2])/2] c = c + 1 pos[0]=pos[0]-(measure_text(plain,a,axes)/2) wire_text(cgo,plain,pos,a,axes) cmd.set("cgo_line_width",1.5) cmd.set("auto_zoom",0) cmd.load_cgo(cgo,'reps') cmd.set("auto_zoom",1) else: cmd.delete("rep*") cmd.mset() cmd.mstop() except: traceback.print_exc()
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 growProtein(): cmd.mstop() cmd.mclear() cmd.mset() glb.update() objects = cmd.get_names('all') if 'protein' in objects: cmd.bg_color('black') # create the objects to be used in this movie cmd.create('helix', 'ss h and protein') cmd.create('sheets', 'ss s and protein') cmd.create('surface', objects[0]) cmd.mset('1', '1400') # dna and rna will be represented as sticks # to make them stand out from the protein if 'dna' in objects: glb.procolor('dna','sticks','cpk',None) if 'rna' in objects: glb.procolor('rna','sticks','cpk',None) # coloring the protein and secondary structures cmd.color('white', 'protein') cmd.color('purple', 'helix') cmd.color('teal', 'sheets') cmd.cartoon('loop', 'protein') cmd.cartoon('automatic', 'helix') cmd.cartoon('automatic', 'sheets') cmd.hide('all') cmd.show('cartoon', 'protein') #cmd.mdo(1,'hide cartoon, helix; hide cartoon, sheets;') cmd.util.mrock('2', '200', '90', '1', '1') cmd.mdo(201,'show cartoon, helix;') cmd.util.mrock('202', '400', '90', '1', '1') cmd.mdo(401,'show cartoon, sheets;') cmd.util.mrock('402', '600', '90', '1', '1') if 'ligands' in objects: cmd.color('hotpink', 'ligands') cmd.mdo(600, 'show spheres, ligands; show sticks, ligands;'+ ' set sphere_transparency = 0.5, ligands;') cmd.util.mroll('601', '800', '1', axis = "x") cmd.color('blue', 'surface') cmd.mview('store', '800') cmd.turn('z', 180) cmd.mview('store' , '1000') cmd.turn('z', 180) cmd.mdo(800, 'show surface, surface; '+ 'set transparency = 0.8, surface;') cmd.mdo(850,'set transparency = 0.7, surface;') cmd.mdo(900,'set transparency = 0.6, surface;') cmd.mdo(950,'set transparency = 0.5, surface;') cmd.mdo(1000,'set transparency = 0.4, surface;') cmd.mdo(1050,'set transparency = 0.3, surface;') cmd.mdo(1100,'set transparency = 0.2, surface;') cmd.mdo(1150,'set transparency = 0.1, surface;') cmd.mdo(1200,'set transparency = 0.0, surface;') cmd.mview('store', '1200') cmd.util.mrock('1201', '1399', '180', '1', '1') cmd.hide('everything', 'surface') cmd.hide('everything', 'helix') cmd.hide('everything', 'sheets') cmd.reset() cmd.orient() cmd.mdo(1400,'hide everything, all; show cartoon, protein;') cmd.mdo(1400,'mstop') cmd.mview('interpolate') cmd.rewind()
def carts(): while 1: resi = int(random.random() * 150) cmd.cartoon('loop', "(resi %d)" % resi) time.sleep(random.random() * 0.05) resi = int(random.random() * 150) cmd.cartoon('oval', "(resi %d)" % resi) cmd.cartoon('oval', "(resi %d)" % (resi + 1)) time.sleep(random.random() * 0.05) resi = int(random.random() * 150) cmd.cartoon('auto', "(resi %d)" % resi) cmd.cartoon('auto', "(resi %d)" % (resi + 1)) time.sleep(random.random() * 0.05) resi = int(random.random() * 150) cmd.cartoon('tube', "(resi %d)" % resi) cmd.cartoon('tube', "(resi %d)" % (resi + 1)) time.sleep(random.random() * 0.05) resi = int(random.random() * 150) cmd.cartoon('rect', "(resi %d)" % resi) cmd.cartoon('rect', "(resi %d)" % (resi + 1)) resi = int(random.random() * 150) cmd.cartoon('oval', "(resi %d)" % resi) time.sleep(random.random() * 0.05) resi = int(random.random() * 150) cmd.cartoon('auto', "(resi %d)" % resi) time.sleep(random.random() * 0.05) resi = int(random.random() * 150) cmd.cartoon('tube', "(resi %d)" % resi) time.sleep(random.random() * 0.05) resi = int(random.random() * 150) cmd.cartoon('rect', "(resi %d)" % resi) time.sleep(random.random() * 0.05) resi = int(random.random() * 150) cmd.hide('car', "(resi %d)" % resi) time.sleep(random.random() * 0.05) resi = int(random.random() * 150) cmd.show('car', "(resi %d)" % resi) time.sleep(random.random() * 0.05) resi = int(random.random() * 150) cmd.show('car', "(resi %d)" % resi) time.sleep(random.random() * 0.05) resi = int(random.random() * 150) cmd.show('car', "(resi %d)" % resi) time.sleep(random.random() * 0.05) resi = int(random.random() * 150) cmd.show('car', "(resi %d)" % resi) time.sleep(random.random() * 0.05)
def local_rms(mobile, target, window=20, mobile_state=1, target_state=1, match='align', load_b=1, visualize=1, quiet=1): ''' DESCRIPTION "local_rms" computes the C-alpha RMS fit within a sliding window along the backbone. The obtained RMS is assigned as a pseudo b-factor to the residue in the middle of the window. This is useful to visualize hinge-regions. The result is very sensitive to window size. USAGE local_rms mobile, target [, window ] ARGUMENTS mobile = string: object to assign b-factors and to visualize as putty cartoon target = string: object to superimpose mobile to window = integer: width of sliding window {default: 20} match = string: in, like, align, none or the name of an alignment object {default: align} * in: match all atom identifiers (segi,chain,resn,resi,name) * like: match residue number (resi) * align: do a sequence alignment * none: assume same number of atoms in both selections * name of alignment object: take sequence alignment from object EXAMPLE fetch 2x19 2xwu, async=0 remove not chain B or not polymer local_rms 2x19, 2xwu, 40 ''' rmsd = get_rmsd_func() array = rmsd.array window = int(window) mobile_state, target_state = int(mobile_state), int(target_state) load_b, visualize, quiet = int(load_b), int(visualize), int(quiet) w2 = window / 2 w4 = window / 4 mm = MatchMaker('(%s) and guide' % (mobile), '(%s) and guide' % (target), match) model_mobile = cmd.get_model(mm.mobile) model_target = cmd.get_model(mm.target) if len(model_mobile.atom) != len(model_mobile.atom): print('Error: number of atoms differ, please check match method') raise CmdException seq_start = model_mobile.atom[0].resi_number seq_end = model_mobile.atom[-1].resi_number resv2i = dict( (a.resi_number, i) for (i, a) in enumerate(model_mobile.atom)) resv2b = dict() X_mobile = array(model_mobile.get_coord_list()) X_target = array(model_target.get_coord_list()) for resv in range(seq_start, seq_end + 1): for resv_from in range(resv - w2, resv + 1): i_from = resv2i.get(resv_from) if i_from is not None: break for resv_to in range(resv + w2, resv - 1, -1): i_to = resv2i.get(resv_to) if i_to is not None: break if i_from is None or i_to is None: continue if i_to - i_from < w4: continue x = X_mobile[i_from:i_to + 1] y = X_target[i_from:i_to + 1] resv2b[resv] = rmsd(x, y) if not quiet: print(' resi %4d: RMS = %6.3f (%4d atoms)' % (resv, resv2b[resv], i_to - i_from + 1)) if load_b: cmd.alter(mobile, 'b=resv2b.get(resv, -1.0)', space={'resv2b': resv2b}) if load_b and visualize: cmd.color('yellow', '(%s) and b < -0.5' % (mobile)) cmd.spectrum('b', 'blue_white_red', '(%s) and b > -0.5' % (mobile)) cmd.show_as('cartoon', mobile) cmd.hide('cartoon', '(%s) and b < -0.5' % (mobile)) cmd.cartoon('putty', mobile) return resv2b
def local_rms(mobile, target, window=20, mobile_state=1, target_state=1, match='align', load_b=1, visualize=1, quiet=1): ''' DESCRIPTION "local_rms" computes the C-alpha RMS fit within a sliding window along the backbone. The obtained RMS is assigned as a pseudo b-factor to the residue in the middle of the window. This is useful to visualize hinge-regions. The result is very sensitive to window size. USAGE local_rms mobile, target [, window ] ARGUMENTS mobile = string: object to assign b-factors and to visualize as putty cartoon target = string: object to superimpose mobile to window = integer: width of sliding window {default: 20} match = string: in, like, align, none or the name of an alignment object {default: align} * in: match all atom identifiers (segi,chain,resn,resi,name) * like: match residue number (resi) * align: do a sequence alignment * none: assume same number of atoms in both selections * name of alignment object: take sequence alignment from object EXAMPLE fetch 2x19 2xwu, async=0 remove not chain B or not polymer local_rms 2x19, 2xwu, 40 ''' rmsd = get_rmsd_func() array = rmsd.array window = int(window) mobile_state, target_state = int(mobile_state), int(target_state) load_b, visualize, quiet = int(load_b), int(visualize), int(quiet) w2 = window // 2 w4 = window // 4 mm = MatchMaker('(%s) and guide' % (mobile), '(%s) and guide' % (target), match) model_mobile = cmd.get_model(mm.mobile) model_target = cmd.get_model(mm.target) if len(model_mobile.atom) != len(model_mobile.atom): print('Error: number of atoms differ, please check match method') raise CmdException seq_start = model_mobile.atom[0].resi_number seq_end = model_mobile.atom[-1].resi_number resv2i = dict((a.resi_number,i) for (i,a) in enumerate(model_mobile.atom)) resv2b = dict() X_mobile = array(model_mobile.get_coord_list()) X_target = array(model_target.get_coord_list()) for resv in range(seq_start, seq_end + 1): for resv_from in range(resv-w2, resv+1): i_from = resv2i.get(resv_from) if i_from is not None: break for resv_to in range(resv+w2, resv-1, -1): i_to = resv2i.get(resv_to) if i_to is not None: break if i_from is None or i_to is None: continue if i_to - i_from < w4: continue x = X_mobile[i_from:i_to+1] y = X_target[i_from:i_to+1] resv2b[resv] = rmsd(x, y) if not quiet: print(' resi %4d: RMS = %6.3f (%4d atoms)' % (resv, resv2b[resv], i_to - i_from + 1)) if load_b: cmd.alter(mobile, 'b=resv2b.get(resv, -1.0)', space={'resv2b': resv2b}) if load_b and visualize: cmd.color('yellow', '(%s) and b < -0.5' % (mobile)) cmd.spectrum('b', 'blue_white_red', '(%s) and b > -0.5' % (mobile)) cmd.show_as('cartoon', mobile) cmd.hide('cartoon', '(%s) and b < -0.5' % (mobile)) cmd.cartoon('putty', mobile) return resv2b
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))
def modevectors( first_obj_frame, last_obj_frame, outname="modevectors", head=1.0,tail=0.3, head_length=1.5, headrgb="1.0,1.0,1.0",tailrgb="1.0,1.0,1.0",cutoff=4.0,skip=0,cut=0.5,atom="CA",stat="show",factor=1.0): """ Authors Sean Law & Srinivasa Michigan State University slaw_(at)_msu_dot_edu Editor Sacha Yee USAGE While in PyMOL Parameter Preset Type Description first_obj_frame Undefined String Object name of the first structure. The mode vector will propagate from this structure. Defined by user. last_obj_frame Undefined String Object name of the last structure. The mode vector (arrow head) will end at this structure. Defined by user. outname modevectors String Name of object to store mode vectors in. head 1.0 Float Radius for the circular base of the arrow head (cone) tail 0.3 Float Radius for the cylinder of the arrow tail (cylinder) head_length 1.5 Float Length of the arrow head (from the base of the cone to the tip of cone) head_rgb 1.0,1.0,1.0 String RGB colour for the arrow head. tail_rgb 1.0,1.0,1.0 String RGB colour for the arrow tail. cutoff 4.0 Float Skips mode vectors that do not meet the cutoff distance (in Angstroms). skip 0 Integer Denotes how many atoms to skip. No arrows will be created for skipped atoms. cut 0.0 Float Truncates all arrow tail lengths (without disturbing the arrow head) (in Angstroms). atom CA String Designates the atom to derive mode vectors from. stat show String Keeps track and prints statistics (total modevectors, skipped, cutoff). factor 1.0 Float Multiplies each mode vector length by a specified factor. Values between 0 and 1 will decrease the relative mode vector length. Values greater than 1 will increase the relative mode vector length. """ framefirst=cmd.get_model(first_obj_frame) framelast=cmd.get_model(last_obj_frame) objectname=outname factor=float(factor) arrow_head_radius=float(head) arrow_tail_radius=float(tail) arrow_head_length=float(head_length) cutoff=float(cutoff) skip=int(skip) cut=float(cut) atomtype=atom.strip('"[]()') headrgb=headrgb.strip('" []()') tailrgb=tailrgb.strip('" []()') hr,hg,hb=map(float,headrgb.split(',')) tr,tg,tb=map(float,tailrgb.split(',')) version=cmd.get_version() arrow=[] arrowhead = [] arrowtail = [] x1 = [] y1 = [] z1 = [] x2 = [] y2 = [] z2 = [] exit_flag=False ############################################################## # # # Define an object called "tail" and store the tail and a # # circular base of the triangle in this object. # # # ############################################################## skipcount=0 skipcounter=0 keepcounter=0 atom_lookup={} for atom in framefirst.atom: if atom.name == atomtype: if skipcount == skip: x1.append(atom.coord[0]) y1.append(atom.coord[1]) z1.append(atom.coord[2]) ########################################## # # # Set atom_lookup for a specific atom # # equal to ONE for the first input set. # # This dictionary will be used as a # # reference for the second set. # # # ########################################## current_atom="CHAIN "+atom.chain+" RESID "\ +atom.resi+" RESTYPE "\ +atom.resn+\ " ATMNAME "+atom.name # print current_atom atom_lookup[current_atom]=1 skipcount=0 keepcounter+=1 else: # print skipcount skipcount+=1 skipcounter+=1 skipcount=0 for atom in framelast.atom: if atom.name == atomtype: if skipcount == skip: x2.append(atom.coord[0]) y2.append(atom.coord[1]) z2.append(atom.coord[2]) ######################################### # # # Get atom information from second set # # and compare with first set. All # # atoms from this second set MUST be # # found in the first set! Otherwise, # # the script will exit with an error # # since modevectors can only be created # # by calculating values from identical # # sources. # # # ######################################### current_atom="CHAIN "+atom.chain+" RESID "\ +atom.resi+" RESTYPE "\ +atom.resn+\ " ATMNAME "+atom.name # print current_atom if current_atom not in atom_lookup: print "\nError: "+current_atom+" from \""\ +last_obj_frame+\ " \"is not found in \""+first_obj_frame+"\"." print "\nPlease check your input and/or selections and try again." exit_flag=True break skipcount=0 else: skipcount+=1 if exit_flag == 1: ########################################### # # # Exit script because an atom cannot be # # found in both input files # # # ########################################### return cutoff_counter=0 # Track number of atoms failing to meet the cutoff ################################################### # # # Check that the two selections/PDB files contain # # the same number of atoms. # # # ################################################### if len(x2) != len(x1): print "\nError: \""+first_obj_frame+\ "\" and \""+last_obj_frame+\ "\" contain different number of residue/atoms." print "\nPlease check your input and/or selections and try again." return else: #Continue with representing modevectors! ######################################### # # # Delete old selection or object if it # # exists so that it can be overwritten # # # ######################################### save_view=cmd.get_view(output=1,quiet=1) cmd.delete(name=outname) cmd.hide(representation="everything",selection=first_obj_frame) cmd.hide(representation="everything",selection=last_obj_frame) ################################################### # # # Begin drawing arrow tails # # # ################################################### arrowtail = [] for mv in range(len(x1)): vectorx=x2[mv]-x1[mv] vectory=y2[mv]-y1[mv] vectorz=z2[mv]-z1[mv] length=sqrt(vectorx**2+vectory**2+vectorz**2) if length < cutoff: cutoff_counter+=1 continue t=1.0-(cut/length) x2[mv]=x1[mv]+factor*t*vectorx y2[mv]=y1[mv]+factor*t*vectory z2[mv]=z1[mv]+factor*t*vectorz vectorx=x2[mv]-x1[mv] vectory=y2[mv]-y1[mv] vectorz=z2[mv]-z1[mv] length=sqrt(vectorx**2+vectory**2+vectorz**2) d=arrow_head_length # Distance from arrow tip to arrow base t=1.0-(d/length) tail = [ # Tail of cylinder CYLINDER, x1[mv],y1[mv],z1[mv]\ ,x1[mv]+(t+0.01)*vectorx,y1[mv]+(t+0.01)*vectory,z1[mv]+(t+0.01)*vectorz\ ,arrow_tail_radius,tr,tg,tb,tr,tg,tb # Radius and RGB for each cylinder tail ] arrow.extend(tail) x=x1[mv]+t*vectorx y=y1[mv]+t*vectory z=z1[mv]+t*vectorz dx=x2[mv]-x dy=y2[mv]-y dz=z2[mv]-z seg=d/100 intfactor=int(factor) if version < 1.1: #Version >= 1.1 has cone primitive for i in range (100,0,-1): #i=100 is tip of cone print i t1=seg*i t2=seg*(i+1) radius=arrow_head_radius*(1.0-i/(100.0)) #Radius of each disc that forms cone head=[ CYLINDER, x+t2*dx,y+t2*dy,z+t2*dz\ ,x+t1*dx,y+t1*dy,z+t1*dz\ ,radius,hr,hg,hb,hr,hg,hb # Radius and RGB for slice of arrow head ] arrow.extend(head) else: head=[ CONE, x, y ,z, x+d*dx, y+d*dy, z+d*dz, arrow_head_radius, 0.0, hr, hg, hb, hr, hg, hb, 1.0, 1.0 ] arrow.extend(head) ############################################################## # # # Load the entire object into PyMOL # # # # Print statistics if requested by user # # # ############################################################## if stat == "show": natoms=skipcounter+keepcounter print "\nTotal number of atoms = "+str(natoms) print "Atoms skipped = "+str(skipcounter) if keepcounter-cutoff_counter > 0: print "Atoms counted = "+str(keepcounter-cutoff_counter)+" (see PyMOL object \""+outname+"\")" else: print "Atoms counted = "+str(keepcounter-cutoff_counter)+" (Empty CGO object not loaded)" print "Atoms cutoff = "+str(cutoff_counter) #Note that cutoff occurs AFTER skipping! if keepcounter-cutoff_counter > 0: cmd.load_cgo(arrow,objectname) #Ray tracing an empty object will cause a segmentation fault. No arrows = Do not display in PyMOL!!! cmd.show(representation="cartoon",selection=first_obj_frame) cmd.cartoon("tube") cmd.show(representation="cartoon",selection=last_obj_frame) cmd.hide(representation="cartoon",selection=last_obj_frame) cmd.bg_color(color="white") cmd.set_view(save_view) return
#from spectrumany import spectrumany from pymol import cmd pdb = '2YP7clean' cmd.load(pdb + '.pdb') cmd.hide('all') cmd.show('cartoon') cmd.cartoon('tube') cmd.set('cartoon_tube_radius', 0.9) # open the file of new values (just 1 column of numbers, one for each alpha carbon) infilename="unpassaged_inverse_dnds.corr" inFile = open(infilename, 'r') values = inFile.readlines() print values # create the global, stored array stored = [] # read the new B factors from file for line in values: stored.append( float(line) ) print stored max_b = max(stored) min_b = min(stored) cmd.bg_color("white") print min_b print max_b
def loadPDB(self, fileNamePath_pdb=False): """Load PDB or CIF file. CIF files will be converted to PDB internally""" if not fileNamePath_pdb: self.fileNamePath_pdb, _ = QtWidgets.QFileDialog.getOpenFileName( self, "Load PDB / CIF", "", "PDB / CIF file (*.pdb *cif);;All Files (*)") else: self.fileNamePath_pdb = fileNamePath_pdb if self.fileNamePath_pdb: self.fileName_pdb = self.fileNamePath_pdb.split("/")[-1] try: if " " in self.fileName_pdb: raise ValueError except ValueError: print("filename cannot contain whitespaces.") return 0 else: if self.fileName_pdb[-3:] == "cif": self.fileNamePath_pdb, _ = self.cif2pdb( self.fileNamePath_pdb) try: self.struct = md.load_pdb(self.fileNamePath_pdb) except IndexError: self.openErrorWin( "File Error", 'The specified file "{}" cannot be loaded'.format( self.fileName_pdb[-3:])) return 0 else: self.struct_original = copy.deepcopy(self.struct) NA_list = [ "A", "G", "C", "U", "RA", "RG", "RC", "RU", "DA", "DG", "DC", "DT", "ATP", "GTP", "CTP", "UTP", "ADP", "GDP", "CDP", "UDP", ] nucleic_str = " or ".join([f"resn {r}" for r in NA_list]) idx_protein_nucleic = self.struct.top.select( f"protein or {nucleic_str}") self.struct = self.struct.atom_slice(idx_protein_nucleic) self.lineEdit_pdbFile.setText(self.fileName_pdb) self.spinBox_statePDB.setMaximum(self.struct.n_frames) self.spinBox_atomID.setMaximum(self.struct.n_atoms) self.atom_chainIDs = [ chain.index for chain in self.struct.top.chains for i in range(chain.n_atoms) ] self.push_computeACV.setEnabled(True) self.spinBox_statePDB.setEnabled(True) self.spinBox_atomID.setEnabled(True) self.push_transfer.setEnabled(True) self.push_loadParameterFile.setEnabled(True) self.push_clear.setEnabled(True) with open(self.fileNamePath_pdb, "r") as f: self.pdbText = f.read() self.push_showText.setEnabled(True) if self._pymol_running: cmd.reinitialize() cmd.load(self.fileNamePath_pdb) cmd.remove("solvent or inorganic") chain_startIDs = [ 1, *[ chain.n_atoms + 1 for chain in self.struct.top.chains ][:-1] ] self.chain_names = [ cmd.get_chains("index {}".format(i))[0] for i in chain_startIDs ] cmd.set_color("ft_blue", [51, 83, 183]) cmd.set_color("ft_gray", [181, 189, 197]) cmd.set_color("ft_orange", [227, 128, 82]) cmd.hide("nonbonded") cmd.show("cartoon") cmd.cartoon("oval") cmd.set("cartoon_oval_length", 1) cmd.set("cartoon_oval_width", 0.25) cmd.set("cartoon_ring_finder", 2) cmd.set("cartoon_ring_mode", 1) cmd.set("cartoon_ring_transparency", 0.5) cmd.set("cartoon_ring_width", 0.3) cmd.show( "sticks", "name C6+N6+O6+C2+N2+O2+C4+O4+N4 and polymer.nucleic" ) cmd.set("stick_radius", 0.15, "polymer.nucleic") cmd.spectrum("count", "gray20 gray80") else: self.chain_names = list( string.ascii_uppercase[0:self.struct.top.n_chains]) self.update_atom() return 1
def disp_ss(selection='all', colors='marine red white', only=False): ''' DESCRIPTION Formats the passed object into secondary structure cartoon USAGE disp_ss [ selection [, colors [, only ]]] PARAMETERS NAME=DEFAULT TYPE FUNCTION selection='all' <str> input selection colors='marine red white' <str> any three colors for: sheets, helices and loops e.g. 'marine red white' can also be set to either util.cbc, util.rainbow, or util.chainbow (alone) set='False' to supress coloring altogether, or enter False for the coloring to be omitted, e.g. 'marine False green' only <bool> if True will use show_as; else show ''' try: selection = '(' + selection + ')' colors = str(colors) only = bool(str(only) != 'False') except: print("Input error") return False if colors == 'False': color_s = color_h = color_l = False elif colors.startswith('util.'): util_choices = ['util.cbc', 'util.rainbow', 'util.chainbow', 'util.ss'] if colors in util_choices: color_s = color_h = color_l = '%s ' % util_choices[ util_choices.index(colors)] else: print( "Input error! Please check the color setting using util. is one of:", util_choices) return False else: try: color_s, color_h, color_l = colors.split()[:3] if color_s != 'False': cmd.color(color_s, None) color_s = 'color %s, ' % color_s else: color_s = False if color_h != 'False': cmd.color(color_h, None) color_h = 'color %s, ' % color_h else: color_h = False if color_l != 'False': cmd.color(color_l, None) color_l = 'color %s, ' % color_l else: color_l = False except: print( "Input error! Please check that three valid colors (or False) are provided" ) return False for p in cmd.get_object_list(selection): cmd.set('cartoon_discrete_colors', 'on', p) # settings cmd.cartoon('rectangle', 'ss s and %s and %s' % (selection, p)) cmd.cartoon('dumbbell', 'ss h and %s and %s' % (selection, p)) cmd.cartoon('loop', 'ss l+"" and %s and %s' % (selection, p)) # sheets if color_s: print(cmd.do(color_s + '(ss s and %s and %s)' % (selection, p))) cmd.set('cartoon_rect_length', 1.5, p) cmd.set('cartoon_rect_width', 0.25, p) # a-helices if color_h: print(cmd.do(color_h + '(ss h and %s and %s)' % (selection, p))) cmd.set('cartoon_dumbbell_length', 1.5, p) cmd.set('cartoon_dumbbell_width', 0.25, p) cmd.set('cartoon_dumbbell_radius', 0.2, p) # loops if color_l: print(cmd.do(color_l + '(ss l+"" and %s and %s)' % (selection, p))) cmd.set('cartoon_loop_radius', 0.25, p) if only: cmd.show_as('cartoon', '%s and %s' % (selection, p)) else: cmd.show('cartoon', '%s and %s' % (selection, p))
def disp_ss( selection='all', colors='marine red white', only=False): ''' DESCRIPTION Formats the passed object into secondary structure cartoon USAGE disp_ss [ selection [, colors [, only ]]] PARAMETERS NAME=DEFAULT TYPE FUNCTION selection='all' <str> input selection colors='marine red white' <str> any three colors for: sheets, helices and loops e.g. 'marine red white' can also be set to either util.cbc, util.rainbow, or util.chainbow (alone) set='False' to supress coloring altogether, or enter False for the coloring to be omitted, e.g. 'marine False green' only <bool> if True will use show_as; else show ''' try: selection='('+selection+')' colors=str(colors) only=bool(str(only)!='False') except: print "Input error" return False if colors=='False': color_s = color_h = color_l = False elif colors.startswith('util.'): util_choices=['util.cbc','util.rainbow','util.chainbow', 'util.ss'] if colors in util_choices: color_s=color_h=color_l= '%s '%util_choices[util_choices.index(colors)] else: print "Input error! Please check the color setting using util. is one of:",util_choices return False else: try: color_s, color_h, color_l=colors.split()[:3] if color_s!='False': cmd.color(color_s,None) color_s='color %s, '%color_s else: color_s=False if color_h!='False': cmd.color(color_h,None) color_h='color %s, '%color_h else: color_h=False if color_l!='False': cmd.color(color_l,None) color_l='color %s, '%color_l else: color_l=False except: print "Input error! Please check that three valid colors (or False) are provided" return False for p in cmd.get_object_list(selection): cmd.set('cartoon_discrete_colors','on', p) # settings cmd.cartoon('rectangle', 'ss s and %s and %s' %(selection, p)) cmd.cartoon('dumbbell', 'ss h and %s and %s' %(selection, p)) cmd.cartoon('loop', 'ss l+"" and %s and %s' %(selection, p)) # sheets if color_s: print cmd.do(color_s+'(ss s and %s and %s)' %(selection, p)) cmd.set('cartoon_rect_length',1.5, p) cmd.set('cartoon_rect_width',0.25, p) # a-helices if color_h: print cmd.do(color_h+'(ss h and %s and %s)' %(selection, p)) cmd.set('cartoon_dumbbell_length',1.5, p) cmd.set('cartoon_dumbbell_width',0.25, p) cmd.set('cartoon_dumbbell_radius',0.2, p) #loops if color_l: print cmd.do(color_l+'(ss l+"" and %s and %s)' %(selection, p)) cmd.set('cartoon_loop_radius',0.25, p) if only: cmd.show_as('cartoon', '%s and %s' %(selection, p)) else: cmd.show('cartoon', '%s and %s' %(selection, p))
def carts(): while 1: resi = int(random.random()*150) cmd.cartoon('loop',"(resi %d)"%resi) time.sleep(random.random()*0.05) resi = int(random.random()*150) cmd.cartoon('oval',"(resi %d)"%resi) cmd.cartoon('oval',"(resi %d)"%(resi+1)) time.sleep(random.random()*0.05) resi = int(random.random()*150) cmd.cartoon('auto',"(resi %d)"%resi) cmd.cartoon('auto',"(resi %d)"%(resi+1)) time.sleep(random.random()*0.05) resi = int(random.random()*150) cmd.cartoon('tube',"(resi %d)"%resi) cmd.cartoon('tube',"(resi %d)"%(resi+1)) time.sleep(random.random()*0.05) resi = int(random.random()*150) cmd.cartoon('rect',"(resi %d)"%resi) cmd.cartoon('rect',"(resi %d)"%(resi+1)) resi = int(random.random()*150) cmd.cartoon('oval',"(resi %d)"%resi) time.sleep(random.random()*0.05) resi = int(random.random()*150) cmd.cartoon('auto',"(resi %d)"%resi) time.sleep(random.random()*0.05) resi = int(random.random()*150) cmd.cartoon('tube',"(resi %d)"%resi) time.sleep(random.random()*0.05) resi = int(random.random()*150) cmd.cartoon('rect',"(resi %d)"%resi) time.sleep(random.random()*0.05) resi = int(random.random()*150) cmd.hide('car',"(resi %d)"%resi) time.sleep(random.random()*0.05) resi = int(random.random()*150) cmd.show('car',"(resi %d)"%resi) time.sleep(random.random()*0.05) resi = int(random.random()*150) cmd.show('car',"(resi %d)"%resi) time.sleep(random.random()*0.05) resi = int(random.random()*150) cmd.show('car',"(resi %d)"%resi) time.sleep(random.random()*0.05) resi = int(random.random()*150) cmd.show('car',"(resi %d)"%resi) time.sleep(random.random()*0.05)