Пример #1
0
def nice(selection='(all)', simple=1e5):
    '''
DESCRIPTION

    My favourite representation

    Color: by chain (elem C) and by element (others)

    Representation: cartoon (polymer), sticks (organic),
    spheres (inorganic) and nonbonded (solvent)

USAGE

    nice [ selection ]
    '''
    simple = int(simple)
    cmd.util.cbc(selection)
    cmd.color('atomic', '(%s) and not elem C' % (selection))
    if simple and cmd.count_atoms(selection) >= simple:
        cmd.show_as('ribbon', selection)
        cmd.show_as('lines', '(%s) and organic' % (selection))
        cmd.show_as('nonbonded', '(%s) and inorganic' % (selection))
    else:
        cmd.show_as('cartoon', selection)
        cmd.show_as('sticks', '(%s) and organic' % (selection))
        cmd.show_as('spheres', '(%s) and inorganic' % (selection))
        cmd.show_as('nonbonded', '(%s) and solvent' % (selection))
Пример #2
0
    def displayPartition(self):

        auto_zoom = cmd.get("auto_zoom")

        try:
            cmd.delete(self.PartitionDisplay)
            cmd.refresh()
        except:
            pass
            
        try:
            cmd.set("auto_zoom", 0)
            
            cmd.load(self.TempPartition, self.PartitionDisplay, format='pdb')
            cmd.refresh()

            cmd.hide('everything', self.PartitionDisplay)
            cmd.refresh()

            cmd.show('surface', self.PartitionDisplay)
            cmd.refresh()

            cmd.color('grey60', self.PartitionDisplay)
            cmd.refresh()
            
            General_cmd.Oscillate(self.Cleft.CleftName, 0.0)

        except:
            self.top.DisplayMessage("  ERROR: An error occured while displaying the partitionned cleft", 1)

        cmd.set("auto_zoom", auto_zoom)
Пример #3
0
def DNA_selections(display='all'):
	bbatoms = 'name C2\*+C3\*+C4\*+C5\*+P+O3\*+O4\*+O5\*+O1P+O2P+H1\*+1H2\*+2H2\*+H3\*+H4\*+1H5\*+2H5\*+c2\'+c3\'+c4\'+c5\'+o3\'+o4\'+o5\'+op2+op1+h1\'+1h2\'+2h2\'+h3\'+h4\'+1h5\'+2h5\''
	waters = 'n. wo6+wn7+wn6+wn4+wo4 or r. hoh'
	cmd.select('DNA', 'r. g+a+c+t+gua+ade+cyt+thy+da+dc+dg+dt+5mc',enable=0)
	cmd.select('notDNA','not DNA',enable=0)
	cmd.select('DNAbases','DNA and not %s' % bbatoms ,enable=0)
	cmd.select('DNAbb','DNA and %s' % bbatoms ,enable=0)
	cmd.select('sc_base','byres notDNA w. 7 of DNAbases',enable=0)
	cmd.select('sc_base','sc_base and not n. c+n+o',enable=0)
	cmd.select('dna_h2o','%s w. 3.6 of DNAbases' %waters ,enable=0)
	cmd.set('sphere_transparency','0.5'); cmd.color('marine','dna_h2o')
	cmd.do('selectPolarProtons')
#	color_by_chains()
	cmd.color('gray','e. c')

	cmd.select('pbb','notDNA and n. c+n+ca',enable=0)

	if display != 'none':
		cmd.label('n. c1\*+c1\' and DNA','\'%s%s(%s)\' % (chain,resi,resn)')
		cmd.set('label_color','white')

	if display == 'all':
		# display things
		cmd.show('sticks','DNAbases or sc_base')
		cmd.show('ribbon','DNAbb')
		cmd.show('cartoon','notDNA')
		cmd.show('spheres','dna_h2o')
		cmd.hide('everything','e. h and not polar_protons')
Пример #4
0
    def testStickBall(self, use_shader):
        '''
        Test some stick_ball* settings
        '''
        cmd.viewport(100, 100)

        cmd.set('use_shaders', use_shader)

        self.ambientOnly()

        cmd.set('stick_ball')
        cmd.set('stick_ball_ratio', 2.0)
        cmd.set('stick_ball_color', 'blue')
        cmd.set('stick_color', 'red')

        cmd.fragment('gly')
        cmd.orient()

        cmd.color('green')
        cmd.show_as('sticks')

        img = self.get_imagearray()
        self.assertImageHasColor('blue', img)
        self.assertImageHasColor('red', img)
        self.assertImageHasNotColor('green', img)
Пример #5
0
    def testAA(self):
        '''
        Make a black/white image and check if gray pixels are found with
        antialias_shader=1/2
        '''
        cmd.viewport(100, 100)

        cmd.set('use_shaders', True)

        self.ambientOnly()

        cmd.fragment('gly')
        cmd.show_as('spheres')
        cmd.color('white')
        cmd.zoom()

        # b/w image, we expect only two color values
        img = self.get_imagearray()
        self.assertTrue(len(numpy.unique(img[...,:3])) == 2)

        for aa in (1, 2):
            cmd.set('antialias_shader', aa)

            # smoothed edges, we expect more than two color values
            img = self.get_imagearray()
            self.assertTrue(len(numpy.unique(img[...,:3])) > 2)
Пример #6
0
def damdisplay(sel, color='white', transparency=0.5):
    '''set visualization of dummy atom models'''
    #cmd.hide(representation="nonbonded", selection = sel);
    cmd.hide(representation="everything", selection = sel);
    cmd.color(color, selection = sel);
    cmd.set("transparency", transparency, selection = sel);
    cmd.show(representation="surface", selection = sel);
Пример #7
0
def colorize():
    cmd.hide('(not (name C+CA+N+O))')

    cmd.spectrum('b', 'red_yellow_green', minimum='-1.0', maximum='1.0')
    cmd.select('missing', 'b = -2.0')
    cmd.color('white', 'missing')
    cmd.delete('missing')
Пример #8
0
    def DisplaySphere(self):
   
        try:
            # Display the Sphere
            cmd.delete(self.SphereDisplay)
            cmd.refresh()
        except:
            pass

        try:
            cmd.pseudoatom(self.SphereDisplay,
                           pos=self.SphereView.Center,
                           vdw=self.SphereView.Radius,
                           state=self.State)
            cmd.refresh()

            cmd.color('oxygen', self.SphereDisplay)
            cmd.refresh()

            cmd.hide('everything', self.SphereDisplay)
            cmd.refresh()

            cmd.show('spheres', self.SphereDisplay)
            cmd.refresh()
            
        except:
            self.ErrorCode = 1

        return self.ErrorCode
Пример #9
0
def loadBR(pdb, saveName=None, color=None):
    if not saveName:
        saveName = pdb.split('.')[0]
   
    cmd.load(pdb, saveName)

    if color: cmd.color(color, saveName)
    cmd.hide("lines")
    cmd.hide("nonbonded")
#     cmd.show("cartoon")
    cmd.show("ribbon")

    cmd.set("cartoon_transparency", 0.7)
    keyResidues = ["ASPA0085", "ARGA0082", "GLUA0194", "GLUA0204", "LYSA0216", "RET", "ASPA0212"]
    for eachRes in keyResidues:
        # retinal's residue sequence id can vary in different pdbs.
        selection = ""
        if eachRes == "RET":
            selection = "resn ret"
        else:
            selection = parseResidue(eachRes)
        
        selection += " and not name c+o+n"
        cmd.show("sticks", selection)
        util.cbag(selection)
Пример #10
0
def mesh_ribbon():
    cmd.hide('everything')
    glb.update()
    cmd.map_new('map', "gaussian", "0.75", 'all')
    glb.procolor(None,show_all=('lines','ribbon'),color_all='red')
    cmd.isomesh('map1', 'map', '1')
    cmd.color('purple','map1')
Пример #11
0
    def testLabelPositionZ(self, use_shaders, ray):
        '''
        Test label z position for regular labels
        '''
        if not ray and invocation.options.no_gui:
            self.skipTest('no gui')

        cmd.set('use_shaders', use_shaders)

        cmd.viewport(200, 200)

        cmd.pseudoatom('m1', vdw=10, label='X')
        cmd.zoom(buffer=12)

        cmd.show('spheres')
        cmd.color('blue')
        cmd.set('label_color', 'red')
        cmd.set('label_size', 20)
        cmd.set('label_font_id', 7) # bold
        self.ambientOnly()

        # label outside of sphere
        cmd.set('label_position', [0, 0, 11.1])
        img = self.get_imagearray(ray=ray)
        self.assertImageHasColor('blue', img)
        self.assertImageHasColor('red', img, delta=20)

        # label inside of sphere
        cmd.set('label_position', [0, 0, 10.5])
        img = self.get_imagearray(ray=ray)
        self.assertImageHasColor('blue', img)
        self.assertImageHasNotColor('red', img, delta=20)
Пример #12
0
def rpcLabel(pos, labelText, id='lab1', color=(1, 1, 1)):
  """ create a text label
 
    Arguments:
      pos: a 3 tuple with the position of the label
      text: a string with the label
      color: a 3 tuple with the color of the label. (1,1,1) is white
      id: (OPTIONAL) the name of the object to be created
 
    NOTE:
      at the moment this is, how you say, a hack
 
  """
  x, y, z = pos
  text = """
Atom
 
  1  0  0  0  0  0  0  0  0  0999 V2000
% 10.4f% 10.4f%10.4f C   0  0  0  0  0  0  0  0  0  0  0  0
M  END""" % (x, y, z)
  cmd.read_molstr(text, id)
  cmd.label("%s" % (id), '"%s"' % labelText)
  cmd.hide("nonbonded", id)
  cmd.set_color("%s-color" % id, color)
  cmd.color("%s-color" % id, id)
  return 1
Пример #13
0
	def load(self):
		self.manager.d = self
		self.manager.m = None
		self.manager.m = None # to also set prevm = None		
		# cmd.delete(self.manager.prevd.obj)
		# cmd.delete(self.manager.prevd.pid)
		# print self.manager.d.obj
		# print self.manager.prevd.obj		
		# sys.exit()
		cmd.delete("all")
		cmd.load(self.getloadname(),self.obj,1)
		cmd.remove(self.obj+" and not chain A")
		cmd.fetch(self.pid)
		cmd.remove("het or hydro")
		cmd.color('gray',self.pid+' and elem C')
		self.scores['rms'] = cmd.align(self.pid,self.obj+" and chain A")[0]
		cmd.hide('ev')
		cmd.show('lines')
		cmd.show("car")
		#cmd.disable(self.pid)
		redopent(self.obj)
		self.recalc_design_pos()
		self.read_data_dir('avg_deg')
		self.read_data_dir('ddG')
		self.read_data_dir('rot_boltz')
		self.read_bup()
		self.read_tot_scores()
		self.read_res_scores()
		cmd.orient(self.obj+" or pnt*")
		self.manager.m = self.remembermm
		if self.manager.m: self.manager.m.focus()
		if self.remembermv: cmd.set_view(self.remembermv)
Пример #14
0
def chain_contact():
    def chain_contact_loop(c,skip,chainPullList):
        d = 0
        l = c + 1
        while len(chainPullList) > l and (26-d) >= 0:
            cmd.select('chain_contact','%s w. 5 of %s'%(chainPullList[d],chainPullList[c+1]),enable=0,quiet=1,merge=1)
            cmd.select('chain_contact','%s w. 5 of %s'%(chainPullList[c+1],chainPullList[d]),enable=0,quiet=1,merge=1)
            d += 1
            l += 1
            while d == (c+1) or d in skip:
                d += 1
    glb.update()
    cmd.hide('everything')
    cmd.show('mesh', 'all')
    cmd.color('gray40', 'all')
    objects = cmd.get_names('all')
    chainPullList = []
    for i in cmd.get_chains(quiet=1):
        chainPullList.append('Chain-'+i)
    if len(chainPullList) < 2:
        showinfo('Notice','There needs to be two or more chains to run this functions.')
        return False
    c = 0
    skip = []
    while c < (len(chainPullList)-1) and c < 26:
        skip.append(c+1)
        chain_contact_loop(c,skip,chainPullList)
        c += 1
    glb.procolor('chain_contact','mesh','cpk',None)
    cmd.delete('chain_contact')
    return chainPullList
Пример #15
0
def add_color(col2, butt):
# checking if the button was already hit
# if so, toggling the selection off

  button_list.append(butt)

  if button_list.count(butt) > 1:

    button_list.remove(butt)
    button_list.remove(butt)	
    cmd.util.cbag ('all')

  elif butt != button_list[0]:
    button_list.remove(button_list[0])
    cmd.util.cbag ('all')
    curSel = col2

  else:
    cmd.util.cbag ('all')
    curSel = col2

# colouring selection with specified colour scheme
  cmd.set_color('siff', curSel )
  cmd.color('siff', InteractionButton[InteractionName.index(butt)]+'_'+butt )
  butt=[]
Пример #16
0
 	def sele2Color(self, sele):
 		globalShader = self.optionMenu_shader.getvalue()

		newShader =  self.seleShaderDict[sele]
		if newShader != globalShader: # should be different from global shader, otherwise do nothing
			newColorInc = ShaderFactory.seleSlot[newShader]


			stored.idcolor_list = set() 
			cmd.iterate(sele, 'stored.idcolor_list.add(int(color))')

			if(len(stored.idcolor_list)>1):
				self.selectionConsole.set('Warning: Selection [%s] contains more than one color.' % sele)

			color = stored.idcolor_list.pop()
			rgb_color = cmd.get_color_tuple(color)

			if rgb_color[2] >= 0.990:
				color_id = '%s %s %s' % (str(rgb_color[0])[0:5].ljust(5, '0'), str(rgb_color[1])[0:5].ljust(5, '0'), str(rgb_color[2]-newColorInc)[0:5])
			else:
				color_id = '%s %s %s' % (str(rgb_color[0])[0:5].ljust(5, '0'), str(rgb_color[1])[0:5].ljust(5, '0'), str(rgb_color[2]+newColorInc)[0:5])

			# color_id from all the sele:shader dictionary
			# determine color_id:shader pair
			if color_id not in self.spColorShaderDict:
				self.spColorShaderDict[color_id] = [newShader, sele]

			# apply new color to atom set
			newRGB = color_id.split(' ')
			newColor = [float(newRGB[0]), float(newRGB[1]), float(newRGB[2])]
			cmd.set_color(color_id, newColor)
			cmd.color(color_id, sele)			

			print 'apply shader [%s] to selection [%s].' % (newShader, sele)			
Пример #17
0
def mkpntx(s1, s2):
    x = com(s1) - com(s2)
    if abs(x.x) > 0.1 or abs(x.y) > 0.1:
        print "DIE!", x
        return
    z = x.z
    c = Vec(0, z / 2 / math.tan(36.0 * math.pi / 180), z / 2)
    cmd.delete("p1")
    cmd.delete("p2")
    cmd.delete("p3")
    cmd.delete("p4")
    cmd.delete("p5")
    cmd.create("p1", s1)
    cmd.create("p2", s1)
    cmd.create("p3", s1)
    cmd.create("p4", s1)
    cmd.create("p5", s1)
    rot("p1", Vec(1, 0, 0), 0 * 72, c)
    rot("p2", Vec(1, 0, 0), 1 * 72, c)
    rot("p3", Vec(1, 0, 0), 2 * 72, c)
    rot("p4", Vec(1, 0, 0), 3 * 72, c)
    rot("p5", Vec(1, 0, 0), 4 * 72, c)
    cmd.color("green", "p1 and elem C")
    cmd.color("cyan", "p2 and elem C")
    cmd.color("yellow", "p3 and elem C")
    cmd.color("magenta", "p4 and elem C")
    cmd.color("orange", "p5 and elem C")
Пример #18
0
def option2():

	vinacomd = str(checkutilities())
	A = inputdata2()

	global proteinfile, ligandfile

	import addwater
	addwater.main(ligandfile)

	waterfile()
	#Writes the water.pdbqt file

	import dockcheck
	dockcheck.main(proteinfile, ligandfile, vinacomd)

	os.remove('waterdetails.txt')
	os.remove('placedwaters.pdb')
	os.remove('water.pdbqt')


	cmd.set("retain_order", 1)
	cmd.set("pdb_use_ter_records", 0)
	cmd.load(proteinfile, 'pro')
	cmd.show_as('cartoon', 'pro')
	cmd.color('blue','pro')
	cmd.load('predictedwaters.pdb','wats')
	cmd.color('red','wats')
	cmd.load(ligandfile,'lig')
	cmd.show_as('sticks','lig')
	cmd.center('lig')
def preProcessPDB(fname):
        stored.residues = []
        stored.chains = []
        cmd.iterate('(name ca)', 'stored.residues.append(resi)')
        cmd.iterate('(name ca)', 'stored.chains.append(chain)')
        cmd.show_as("cartoon", '(all)')
        cmd.color("white", '(all)')
Пример #20
0
def testFun(filePath):
    import networkx as nx
    cmd.delete("all")
    
    cmd.fetch("1C3W")
    cmd.hide("lines", "all")
    cmd.show("cartoon", "1C3W")
    cmd.color("green", "all")
    
    #------------------------------ cmd.color("yellow", "resi 194 and resn GLU")
    #------------------------------- cmd.show("sticks", "resi 194 and resn GLU")
    highlightRes("GLUA0194", color="yellow")
    highlightRes("GLUA0204", color="yellow")
    
        
    g = loadHbTxt(filePath)
    allNodes = nx.node_connected_component(g, "GLUA0194")
    #===========================================================================
    # print allNodes
    #===========================================================================
    
    accRes = {}
    for line in open("/Users/xzhu/sibyl/BR/1C3W/hydro/def/raw/acc.res"):
        fields = line.split()
        resString = fields[1] + fields[2]
        acc = float(fields[4])
        accRes[resString] = acc
    
    colorThreshold = 0.02
    for eachResidue in accRes.keys():
        if accRes[eachResidue] > colorThreshold:
            if eachResidue in allNodes:
                print eachResidue
                highlightRes(eachResidue)
Пример #21
0
def PyMOLRepresentations (representation, selection):
    """ Function doc """
    #print "aqui"
    if representation['lines'  ]:
        cmd.show("lines",  selection)

    if representation['stick'  ]:
        cmd.show("stick",  selection)

    if representation['ribbon' ]:
        cmd.show("ribbon",  selection)

    if representation['cartoon']:
        cmd.show("cartoon",  selection)

    if representation['dot'    ]:
        cmd.show("dot",  selection)

    if representation['sphere' ]:
        cmd.show("sphere",  selection)

    if representation['mesh'   ]:
        cmd.show("mesh",  selection)

    if representation['surface']:                           
        cmd.show("surface",  selection)
    
    try:
        cmd.color(representation['color'],  selection)
    except:
        pass
Пример #22
0
    def RefreshDisplay(self):
        
        try:
            # Display the atoms spheres
            cmd.show('spheres', self.LigDisplay)
            cmd.refresh()

            cmd.alter(self.LigDisplay,'vdw=0.25')
            cmd.rebuild(self.LigDisplay)
            cmd.refresh()

            util.cbag(self.LigDisplay)
            cmd.refresh()
            
            if self.AnchorAtom != -1:
                AtomSel = self.LigDisplay + ' & id ' + str(self.AnchorAtom)
                cmd.color('white',AtomSel)
                cmd.refresh()

                cmd.alter(AtomSel ,'vdw=0.30')
                cmd.rebuild(AtomSel)
                cmd.refresh()
                        
        except:
            self.ErrorCode = 1

        return self.ErrorCode
Пример #23
0
def fatslim_apl_prot():
    global REF_BEAD
    setup()

    FILENAME = BILAYER_PROT
    REF_BEAD = BILAYER_PROT_REF

    # Load file
    cmd.load("%s.pdb" % FILENAME)
    main_obj = "%s" % FILENAME
    cmd.disable(main_obj)
    traj = load_trajectory("%s.gro" % FILENAME, "%s.ndx" % FILENAME)
    traj.initialize()
    frame = traj[0]
    draw_pbc_box(main_obj)

    cmd.create("protein", "resi 1-160")
    cmd.hide("lines", "protein")
    cmd.color("yellow", "protein")
    cmd.show("cartoon", "protein")
    cmd.show("surface", "protein")
    cmd.set("transparency", 0.5, "protein")
    cmd.set("surface_color", "yelloworange", "protein")

    # Show leaflets
    show_leaflets(frame)

    # Show stuff related to APL
    show_apl(frame)

    print("Bilayer with protein loaded!")
Пример #24
0
def ino():
    """Sphare and yellow inorganic, such us Mg.

    .. image:: ../../rna_tools/utils/PyMOL4RNA/doc/ion.png"""
    cmd.show("spheres", "inorganic")
    cmd.set('sphere_scale', '0.25', '(all)')
    cmd.color("yellow", "inorganic")
Пример #25
0
    def testTrilines(self, trilines):
        cmd.viewport(100, 100)

        cmd.set('use_shaders', True)

        self.ambientOnly()

        cmd.set('dynamic_width', 0)
        cmd.set('line_width', 5)
        cmd.set('line_smooth', 0)

        cmd.fragment('ethylene')
        cmd.show_as('lines')
        cmd.color('white')
        cmd.orient()

        cmd.set('trilines', trilines)

        # check percentage of covered pixels
        img = self.get_imagearray()
        npixels = img.shape[0] * img.shape[1]
        covered = numpy.count_nonzero(img[...,:3])
        ratio = covered / float(npixels)
        msg = "covered=%d npixels=%d ratio=%f" % (covered, npixels, ratio)
        self.assertTrue(0.14 < ratio < 0.165, msg)
Пример #26
0
    def test(self):
        cmd.viewport(100, 100)

        # make map
        cmd.fragment('gly', 'm1')
        cmd.set('gaussian_b_floor', 30)
        cmd.set('mesh_width', 5)
        cmd.map_new('map')
        cmd.delete('m1')

        # make mesh 
        cmd.isomesh('mesh', 'map')

        # check mesh presence by color
        meshcolor = 'red'
        cmd.color(meshcolor, 'mesh')
        self.ambientOnly()
        self.assertImageHasColor(meshcolor)

        # continue without map
        cmd.delete('map')

        with testing.mktemp('.pse') as filename:
            cmd.save(filename)

            cmd.delete('*')
            self.assertImageHasNotColor(meshcolor)

            cmd.load(filename)
            self.assertImageHasColor(meshcolor)
Пример #27
0
def rcomp():
    """RNA like in papers ;-)

    Similar to rc() but this time it colors each (and every) structure in different colour.
    Great on viewing-comparing superimposed structures.

    """
    cmd.hide("sticks", "all")
    cmd.hide("lines", "all")
    cmd.show("cartoon", "all")
    cmd.set("cartoon_ring_mode", 3)
    cmd.set("cartoon_ring_finder", 2)
    cmd.set("cartoon_ladder_mode", 2)
    cmd.set("cartoon_ring_transparency", 0.30)

    obj_list = cmd.get_names('objects')

    colours = ['red', 'green', 'blue', 'yellow', 'violet', 'cyan',    \
           'salmon', 'lime', 'pink', 'slate', 'magenta', 'orange', 'marine', \
           'olive', 'purple', 'teal', 'forest', 'firebrick', 'chocolate',    \
           'wheat', 'white', 'grey' ]
    ncolours = len(colours)

           # Loop over objects
    i = 0
    for obj in obj_list:
        print("  ", obj, colours[i])
        cmd.color(colours[i], obj)
        i = i+1
        if(i == ncolours):
           i = 0
Пример #28
0
    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)
Пример #29
0
    def testMMTF(self):
        '''Styled MMTF export/import'''
        S = 0b10            # 1 << 1 spheres
        D = 0b1000000000    # 1 << 9 dots
        B = 2 # blue
        R = 4 # red

        cmd.fragment('gly')
        cmd.color(B)
        cmd.color(R, 'elem C')
        cmd.show_as('spheres')
        cmd.show_as('dots', 'elem C')

        with testing.mktemp('.mmtf') as filename:
            cmd.save(filename)
            cmd.delete('*')
            cmd.load(filename)

        color_list = []
        reps_list = []

        cmd.iterate('*', 'color_list.append(color)', space=locals())
        cmd.iterate('*', 'reps_list.append(reps)', space=locals())

        self.assertEqual(color_list, [B, R, R, B, B, B, B])
        self.assertEqual(reps_list, [S, D, D, S, S, S, S])
Пример #30
0
    def updateColor(self):
        if self.ss_asgn_prog is None:
            err_msg = 'Run DSSP or Stride to assign secondary structures first!'
            print('ERROR: %s' % (err_msg,))
            tkMessageBox.showinfo(title='ERROR', message=err_msg)
        else:
            print('Update color for %s' % (self.pymol_sel.get()), end=' ')
            print('using secondary structure assignment by %s' % (self.ss_asgn_prog,))

            if self.ss_asgn_prog == 'DSSP':
                SSE_list = self.DSSP_SSE_list
            elif self.ss_asgn_prog == 'Stride':
                SSE_list = self.STRIDE_SSE_list

            for sse in SSE_list:  # give color names
                cmd.set_color('%s_color' % (sse,), self.SSE_col_RGB[sse])
            for sse in SSE_list:  # color each SSE
                for sel_obj in self.sel_obj_list:
                    if self.SSE_sel_dict[sel_obj][sse] is not None:
                        cmd.color('%s_color' % (sse,), self.SSE_sel_dict[sel_obj][sse])
                        print('color', self.SSE_sel_dict[sel_obj][sse], ',', self.SSE_col_RGB[sse])
                    else:
                        print('No residues with SSE \'%s\' to color.' % (sse,))

        return
Пример #31
0
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, bsync=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
Пример #32
0
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()
Пример #33
0
def colour_antibody(object="all",
                    heavy_col="orange",
                    light_col="yellow",
                    h1="",
                    h2="",
                    h3="",
                    l1="",
                    l2="",
                    l3="",
                    heavy="H",
                    light="L",
                    cdr_def="North-Aho"):
    """
DESCRIPTION

        Command to create selection objects that cover various CDRs, and colour the regions as well.  The CDR definition of the antibody needs to be correctly specified.  No colouring will be performed if a particular region has "" specififed as its colour.  CDR colouring supercedes chain colouring.
        
USAGE

        colour_antibody myantibody, cdr_def=chothia, light_col=red, h3=blue, cdr_def=chothia
        
ARGUMENTS

        object = str: name of the object(s) to create selections for.  If multiple objects are specified, a unique specifier for each will be created.
        heavy_col = str: What colour to make the heavy chain.
        light_col = str: What colour to make the light chain.
        h1 = str: What colour to make HCDR1.
        h2 = str: What colour to make HCDR2.
        h3 = str: What colour to make HCDR3.
        l1 = str: What colour to make LCDR1.
        l2 = str: What colour to make LCDR2.
        l3 = str: What colour to make LCDR3.
        heavy = str: Chain identifier for the heavy chain.
        light = str: Chain identifier for the light chain.
        cdr_def = str: Antibody numbering scheme and CDR definition combination to use.

NOTES

    """

    # First, figure out which objects to process
    objects = parse_object_list(object)

    # We will use select_cdrs to generate the appropriate selections.  This will also automatically error check in
    # the same way, so we don't have to do it again.  Pass through params.
    select_cdrs(object=object, heavy=heavy, light=light, cdr_def=cdr_def)

    # Loop over all objects to colour
    for obj in objects:
        # For all colouring, skip if we have an empty string.
        # First, colour the chains.
        if not heavy_col == "":
            cmd.color(heavy_col,
                      "elem c and chain {0} and {1}".format(heavy, obj))
        if not light_col == "":
            cmd.color(light_col,
                      "elem c and chain {0} and {1}".format(light, obj))

        # Now, colour the cdrs
        if not h1 == "": cmd.color(h1, "elem c and {}_H1".format(obj))
        if not h2 == "": cmd.color(h2, "elem c and {}_H2".format(obj))
        if not h3 == "": cmd.color(h3, "elem c and {}_H3".format(obj))
        if not l1 == "": cmd.color(l1, "elem c and {}_L1".format(obj))
        if not l2 == "": cmd.color(l2, "elem c and {}_L2".format(obj))
        if not l3 == "": cmd.color(l3, "elem c and {}_L3".format(obj))
Пример #34
0
 def testColor(self):
     cmd.fragment('ala')
     cmd.color(3)
     colors = set()
     cmd.iterate('all', 'colors.add(color)', space=locals())
     self.assertItemsEqual(colors, [3])
Пример #35
0
def my_color(color="red",sele="name CA"):
    print "I am coloring "+color+ " all atoms in selection: "+sele
    cmd.color(color, sele)
Пример #36
0
from pymol.cgo import *
from pymol import cmd

cmd.set("cartoon_fancy_helices", 1)
cmd.set("cartoon_transparency", 0.5)
cmd.set("sphere_transparency", 0.7)
cmd.set("ray_trace_mode", 0)
cmd.set("two_sided_lighting", "on")
cmd.set("reflect", 0.9)
cmd.set("ambient", 0.1)
cmd.set('''ray_opaque_background''', '''off''')

cmd.load("4xcp_hv.pdb")
cmd.color("chocolate", "4xcp_hv")
cmd.load("hv_cavity_1.pdb")
cmd.color("salmon", "hv_cavity_1")

cmd.set_view (\
  '''0.456030250,    0.888168931,    0.056359597,\
    -0.276825786,    0.081376061,    0.957462490,\
     0.845804632,   -0.452238709,    0.282975733,\
    -0.000969257,   -0.000390973, -118.043930054,\
    33.933498383,   32.315837860,   33.869487762,\
    83.247825623,  152.777328491,  -20.000000000''')

cmd.png("dynamics_hv.png", width=500, height=400, dpi=100, ray=1)

cmd.quit()
Пример #37
0
def load_consurf(filename, selection, palette='red_white_blue', quiet=1):
    '''
DESCRIPTION

    Color by evolutionary conservation. Writes scores to b-factor.

    You need a "r4s.res" or "consurf.grades" input file.

USAGE

    load_consurf filename, selection [, palette ]

SEE ALSO

    consurfdb
    '''
    import re
    from .seqalign import needle_alignment, alignment_mapping
    from . import one_letter

    # reduced pattern that matches both r4s.res and consurf.grades
    pattern = re.compile(r'\s*(\d+)\s+([A-Y])\s+([-.0-9]+)\s')

    scores = []
    seqlist = []

    if cmd.is_string(filename):
        handle = open(filename)
    else:
        handle = filename

    if len(cmd.get_chains(selection)) > 1:
        print(' Warning: selection spans multiple chains')

    for line in handle:
        if line.startswith('#') or line.strip() == '':
            continue
        m = pattern.match(line)
        if m is None:
            continue
        scores.append(float(m.group(3)))
        seqlist.append(m.group(2))

    selection = '(%s) and polymer' % selection
    model_ca = cmd.get_model(selection + ' and guide')
    model_seq = ''.join(one_letter.get(a.resn, 'X') for a in model_ca.atom)
    sequence = ''.join(seqlist)

    aln = needle_alignment(model_seq, sequence)
    scores_resi = dict((model_ca.atom[i].resi, scores[j])
            for (i, j) in alignment_mapping(*aln))

    cmd.alter(selection, 'b=scores.get(resi, -10)',
            space={'scores': scores_resi}, quiet=quiet)

    if palette:
        cmd.color('yellow', selection + ' and b<-9')
        if ' ' in palette:
            from .viewing import spectrumany as spectrum
        else:
            spectrum = cmd.spectrum
        spectrum('b', palette, selection + ' and b>-9.5')
Пример #38
0
def Ligand_Pull():
    glb.update()
    cmd.mstop()
    cmd.mclear()
    cmd.mset('1', '442')
    cmd.hide('everything')
    cmd.remove('resn HOH')
    cmd.color('green', 'all')
    objects = cmd.get_names('all')
    if 'ligands' in objects:
        cmd.set('stick_radius', '0.3')
        glb.procolor('ligands around 6','sticks','cpk','cartoon')
        glb.procolor('ligands','spheres','orange',None)
        cmd.set("cartoon_fancy_helices", "1")
        cmd.set("cartoon_fancy_sheets", "1")
        cmd.set('cartoon_transparency', '0.5')
        cmd.zoom()
        cmd.orient()
        cmd.mdo(1,'orient')
        cmd.mdo(2,'translate [2,0,0],ligands;')
        cmd.mdo(3,'translate [2,0,0],ligands;')
        cmd.mdo(4,'translate [2,0,0],ligands;')
        cmd.mdo(5,'translate [2,0,0],ligands;')
        cmd.mdo(6,'translate [2,0,0],ligands;')
        cmd.mdo(7,'translate [2,0,0],ligands;')
        cmd.mdo(8,'translate [2,0,0],ligands;')
        cmd.mdo(9,'translate [2,0,0],ligands;')
        cmd.mdo(10,'translate [2,0,0],ligands;')
        cmd.mdo(11,'translate [2,0,0],ligands;')
        cmd.mdo(12,'translate [2,0,0],ligands;')
        cmd.mdo(13,'translate [2,0,0],ligands;')
        cmd.mdo(14,'translate [2,0,0],ligands;')
        cmd.mdo(15,'translate [2,0,0],ligands;')
        cmd.mdo(16,'translate [2,0,0],ligands;')
        cmd.mdo(17,'translate [2,0,0],ligands;')
        cmd.mdo(18,'translate [2,0,0],ligands;')
        cmd.mdo(19,'translate [2,0,0],ligands;')
        cmd.mdo(20,'translate [2,0,0],ligands;')
        cmd.mdo(21,'translate [2,0,0],ligands;')
        cmd.mdo(22,'translate [2,0,0],ligands;')
        cmd.mdo(23,'translate [2,0,0],ligands;')
        cmd.mdo(24,'translate [2,0,0],ligands;')
        cmd.mdo(25,'translate [2,0,0],ligands;')
        cmd.mdo(26,'translate [2,0,0],ligands;')
        cmd.mdo(27,'translate [2,0,0],ligands;')
        cmd.mdo(28,'translate [2,0,0],ligands;')
        cmd.mdo(29,'translate [2,0,0],ligands;')
        cmd.mdo(30,'translate [2,0,0],ligands;')
        cmd.mdo(31,'translate [2,0,0],ligands;')
        cmd.mdo(32,'translate [2,0,0],ligands;')
        cmd.mdo(33,'translate [2,0,0],ligands;')
        cmd.mdo(34,'translate [2,0,0],ligands;')
        cmd.mdo(35,'translate [2,0,0],ligands;')
        cmd.mdo(36,'translate [2,0,0],ligands;')
        cmd.mdo(37,'translate [2,0,0],ligands;')
        cmd.mdo(38,'translate [2,0,0],ligands;')
        cmd.mdo(39,'translate [2,0,0],ligands;')
        cmd.mdo(40,'translate [2,0,0],ligands;')
        cmd.mdo(41,'translate [2,0,0],ligands;')
        cmd.mdo(42,'orient')
        cmd.util.mroll('42','222','1')
        cmd.mdo(223,'translate [-2,0,0],ligands;')
        cmd.mdo(224,'translate [-2,0,0],ligands;')
        cmd.mdo(225,'translate [-2,0,0],ligands;')
        cmd.mdo(226,'translate [-2,0,0],ligands;')
        cmd.mdo(227,'translate [-2,0,0],ligands;')
        cmd.mdo(228,'translate [-2,0,0],ligands;')
        cmd.mdo(229,'translate [-2,0,0],ligands;')
        cmd.mdo(230,'translate [-2,0,0],ligands;')
        cmd.mdo(231,'translate [-2,0,0],ligands;')
        cmd.mdo(232,'translate [-2,0,0],ligands;')
        cmd.mdo(233,'translate [-2,0,0],ligands;')
        cmd.mdo(234,'translate [-2,0,0],ligands;')
        cmd.mdo(235,'translate [-2,0,0],ligands;')
        cmd.mdo(236,'translate [-2,0,0],ligands;')
        cmd.mdo(237,'translate [-2,0,0],ligands;')
        cmd.mdo(238,'translate [-2,0,0],ligands;')
        cmd.mdo(239,'translate [-2,0,0],ligands;')
        cmd.mdo(240,'translate [-2,0,0],ligands;')
        cmd.mdo(241,'translate [-2,0,0],ligands;')
        cmd.mdo(242,'translate [-2,0,0],ligands;')
        cmd.mdo(243,'translate [-2,0,0],ligands;')
        cmd.mdo(244,'translate [-2,0,0],ligands;')
        cmd.mdo(245,'translate [-2,0,0],ligands;')
        cmd.mdo(246,'translate [-2,0,0],ligands;')
        cmd.mdo(247,'translate [-2,0,0],ligands;')
        cmd.mdo(248,'translate [-2,0,0],ligands;')
        cmd.mdo(249,'translate [-2,0,0],ligands;')
        cmd.mdo(250,'translate [-2,0,0],ligands;')
        cmd.mdo(251,'translate [-2,0,0],ligands;')
        cmd.mdo(252,'translate [-2,0,0],ligands;')
        cmd.mdo(253,'translate [-2,0,0],ligands;')
        cmd.mdo(254,'translate [-2,0,0],ligands;')
        cmd.mdo(255,'translate [-2,0,0],ligands;')
        cmd.mdo(256,'translate [-2,0,0],ligands;')
        cmd.mdo(257,'translate [-2,0,0],ligands;')
        cmd.mdo(258,'translate [-2,0,0],ligands;')
        cmd.mdo(259,'translate [-2,0,0],ligands;')
        cmd.mdo(260,'translate [-2,0,0],ligands;')
        cmd.mdo(261,'translate [-2,0,0],ligands;')
        cmd.mdo(262,'translate [-2,0,0],ligands;')
        cmd.mdo(263,'orient')
        cmd.util.mroll('264','442','1')
    else:
        showinfo('No ligands','There are no ligands in this PDB.')
cmd.orient(prefix)
colors = np.array([np.random.choice(np.arange(256, dtype=float), size=3) for dummy in range(binding_site_id)])
colors /= 255.0
            
residue_set = np.array(residue_set, dtype=str)
residue_rank_set = np.array(residue_rank_set, dtype=int)
binding_site_identifiers = np.array(binding_site_identifiers, dtype=int)
residue_identifiers = list(residue_identifiers)
for bs_id in np.arange(binding_site_id):
    cmd.set_color("tmp_{}".format(bs_id), list(colors[bs_id]))
    for entry_id in np.where(binding_site_identifiers == bs_id)[0]:
        selected_residue = residue_set[entry_id]
        selected_residue_rank = residue_rank_set[entry_id]
        identifier_from_pdb = residue_identifiers[selected_residue_rank]
        if re.findall("[a-zA-Z]+$", selected_residue)[0] != identifier_from_pdb[1]:
            raise IndexError("The {}th residue in the provided pdb file ({}{}) is different from that in the simulations ({})!".format(entry_id+1,
                                                                                                                                     identifier_from_pdb[0],
                                                                                                                                     identifier_from_pdb[1],
                                                                                                                                     selected_residue))
        if identifier_from_pdb[2] != " ":
            cmd.select("BSid{}_{}".format(bs_id, selected_residue), "chain {} and resid {} and (not name C+O+N)".format(identifier_from_pdb[2],
                                                                                                                      identifier_from_pdb[0]))
        else:
            cmd.select("BSid{}_{}".format(bs_id, selected_residue), "resid {} and (not name C+O+N)".format(identifier_from_pdb[0]))
        cmd.show("spheres", "BSid{}_{}".format(bs_id, selected_residue))
        cmd.set("sphere_scale", SCALES[entry_id], selection="BSid{}_{}".format(bs_id, selected_residue))
        cmd.color("tmp_{}".format(bs_id), "BSid{}_{}".format(bs_id, selected_residue))
    cmd.group("BSid{}".format(bs_id), "BSid{}_*".format(bs_id))

            
Пример #40
0
cmd.spectrum("count", selection="(protein)&e. c")
#preset.publication("protein")
cmd.show("spheres", "surface")
cmd.clip("atoms", 5, "all")
cmd.select("prot_int", "protein w. 5 of surface")
cmd.disable('prot_int')
cmd.select("surf_int", "surface w. 5 of protein")
cmd.disable('surf_int')
cmd.hide("everything", "surface")
cmd.show("spheres", "surf_int")
cmd.show("sticks", "((byres (prot_int))&(!(n;c,o,h|(n. n&!r. pro))))")
cmd.space('cmyk')
cmd.bg_color('black')
cmd.select("BackBone", "name c+ca+o+n")
cmd.select("SC_Carbon", "elem c and not BackBone")
cmd.color("grey60", "SC_Carbon")
cmd.disable('SC_Carbon')
############## OSTEOCALCIN STUFF ###############
cmd.color("red", "name OE11")
cmd.color("red", "name OE12")
cmd.color("red", "name OE21")
cmd.color("red", "name OE22")
cmd.remove("resn cys and name hg")
cmd.show("sticks", "resn cys and not BackBone")
cmd.show("sticks", "resn cys and name CA+HA")
###########################################
cmd.create("ProtObj", "protein")
cmd.hide("everything", "ProtObj")
cmd.show("surface", "ProtObj")
cmd.set('transparency', 0.65)
#cmd.set('cartoon_transparency',0.2)
Пример #41
0
def color_as(col, str):
    hsv = (col, 1, 1)
    rgb = hsv_to_rgb(hsv)
    cmd.set_color("color" + str, rgb)
    cmd.color("color" + str, str)
    cmd.disable(str)
def show_mutations(offset=0):
    obj_list = cmd.get_names('objects')

    length = len(obj_list)
    if (length < 2):
        print 'Error! Not two models!'
        sys.exit()

    #Declare models
    origin = obj_list[0]
    mutate = obj_list[1]

    #Get residues of structures
    residues_dic = {'original_list': [], 'mutant_list': []}
    #populate original list
    cmd.iterate("(" + "model " + origin + " and name ca)",
                "original_list.append((resi,resn))",
                space=residues_dic)
    print origin, residues_dic['original_list']
    #populate mutant list
    cmd.iterate("(" + "model " + mutate + " and name ca)",
                "mutant_list.append((resi,resn))",
                space=residues_dic)
    print mutate, residues_dic['mutant_list']

    #Superimpose structure
    cmd.align(origin, mutate)

    #Compare residues:check for amino acid length
    if (abs(
            len(residues_dic['original_list']) -
            len(residues_dic['mutant_list'])) > 1):
        print 'Unequal length of amino acids'  #on is tolerated because of offset
        sys.exit()

    #Compare residues: find mutations
    mutations = list()
    select_origin = "(" + "model " + origin + " and resi 0"  #select all atoms from model1 with the following residues ids
    select_mutant = "(" + "model " + mutate + " and resi 0"

    for x, y in zip(residues_dic['original_list'][int(offset):],
                    residues_dic['mutant_list']):
        if (x[1] != y[1]):
            #print x,y,' is different.'
            mutations.append((x, y))
            select_origin += '+' + str(int(x[0]))
            select_mutant += '+' + str(int(y[0]))

    select_origin += ")"
    select_mutant += ")"

    #prepare view
    cmd.show("cartoon")

    #Create surface
    cmd.show("surface", "(Model " + origin + ")")
    cmd.show("surface", "(Model " + mutate + ")")

    cmd.set("transparency", 0.8)
    cmd.set("surface_color", "white", "*")

    #create objects of affected residues
    cmd.create("original", select_origin, 0, 1)
    cmd.create("mutate", select_mutant, 0, 1)

    #Change vis of altered residues
    cmd.color("red", "(Model original)")
    cmd.color("blue", "(Model mutate)")
    cmd.hide("everything", "(Model mutate)")
    cmd.hide("everything", "(Model original)")
    cmd.show("sticks", "(Model original)")
    cmd.show("sticks", "(Model mutate)")
Пример #43
0
from pymol import cmd
from m2_7 import calc_gc
filename = "data/1buw.pdb"
cmd.load(filename)
cmd.hide("everything")
c = cmd.centerofmass("chain A")
cmd.origin(position=c)
cmd.center('origin')
print(cmd.get_position())
cmd.select(
    "inside",
    "chain A within {:.2f} of origin".format(calc_gc(filename, "chain A")))
cmd.select("outside", "not inside")

cmd.color("red", "inside")
cmd.color("blue", "outside")

cmd.show("sphere", "inside")
cmd.show("sphere", "outside")
Пример #44
0
            (r, g, b) = (v, p, q)
        else:
            (r, g, b) = (v, v, v)
            print "error, i not equal 1-5"
    return [r, g, b]


def color_as(col, str):
    hsv = (col, 1, 1)
    rgb = hsv_to_rgb(hsv)
    cmd.set_color("color" + str, rgb)
    cmd.color("color" + str, str)
    cmd.disable(str)


cmd.color("white", "resi 2171")
cmd.color("white", "resi 2172")
cmd.color("white", "resi 2173")
cmd.color("white", "resi 2174")
cmd.color("white", "resi 2175")
cmd.color("white", "resi 2176")
cmd.color("white", "resi 2177")
cmd.color("white", "resi 2178")
cmd.color("white", "resi 2179")
cmd.color("white", "resi 2180")
cmd.color("white", "resi 2181")
cmd.color("white", "resi 2182")
color_as(70, "resi 2183")
color_as(70, "resi 2184")
color_as(70, "resi 2185")
color_as(70, "resi 2186")
Пример #45
0
def color_grad(selection='',
               item='b',
               mode='hist',
               gradient='bgr',
               nbins=11,
               sat=1,
               value=1,
               minimum='1',
               maximum='1',
               dummy='dummy_all',
               hs=1,
               he=1,
               ss=1,
               se=1,
               vs=1,
               ve=1,
               colorname='init'):
    """
    --- color_grad: color gradient tool for PyMOL --- 
    Author  : Gregor Hagelueken
    Program : Color_grad
    Date    : Oct 2007
    Version : 0.1.0
    Mail    : [email protected]
 
 
 
 
    This is a modified version of the color_b program by Robert L. Campbell & James Stroud
 
    Literature:
    DeLano, W.L. The PyMOL Molecular Graphics System (2002) DeLano Scientific, San Carlos, CA, USA. http://www.pymol.org
 
    ----------------------------------------------------------------------
    ----------------------------------------------------------------------
  """

    nbins = int(nbins)
    sat = float(sat)
    value = float(value)
    hs = float(hs)
    he = float(he)
    ss = float(ss)
    se = float(se)
    vs = float(vs)
    ve = float(ve)
    colorname = 'color_' + selection

    nbins = int(maximum) - int(minimum) + 2
    dummy = "dummy-" + selection
    colname = "col" + selection

    # make sure sat and value are in the range 0-1.0
    sat = min(sat, 1.0)
    sat = max(sat, 0.0)
    value = min(value, 1.0)
    value = max(value, 0.0)

    # make sure lowercase
    gradient.lower()
    mode.lower()

    # Sanity checking
    if nbins == 1:
        print "\n     WARNING: You specified nbins=1, which doesn't make sense...resetting nbins=11\n"
        nbins = 11

    if mode not in ('hist', 'ramp'):
        print "\n     WARNING: Unknown mode ", mode, "    ----->   Nothing done.\n"
        return
    if selection == '':
        print "\n USAGE: color_grad dimB, minimum=380, maximum=531, hs=0.3, he=0.25,ss=0.7,se=0.2,vs=1,ve=0.5\n"
        return
    elif gradient not in ('bgr', 'rgb', 'rainbow', 'reverserainbow', 'bwr',
                          'rwb', 'bmr', 'rmb', 'rw', 'wr', 'gw', 'wg', 'bw',
                          'wb', 'gy', 'yg', 'gray', 'grey', 'reversegray',
                          'reversegrey'):
        print "\n     WARNING: Unknown gradient: ", gradient, "    ----->   Nothing done.\n"
        return

    print "MODE, GRADIENT, NBINS:", mode, gradient, nbins

    # get list of B-factors from selection
    m = cmd.get_model(selection)
    sel = []
    b_list = []

    if len(m.atom) == 0:
        print "Sorry, no atoms selected"

    else:
        if item == 'b':
            for i in range(len(m.atom)):
                m.atom[i].b = m.atom[i].resi
                b_list.append(m.atom[i].b)

        elif item == 'q':
            for i in range(len(m.atom)):
                b_list.append(m.atom[i].q)

        else:
            print "Not configured to work on item %s" % item
            return

        cmd.load_model(m, dummy)

        print selection
        max_b = maximum
        min_b = minimum
        print "Minimum and Maximum B-values: ", min_b, max_b
        #nbins = (max_b - min_b)

        if mode == 'hist':

            # check if minimum or maximum was specified and use the entered values
            if minimum != '':
                min_b = int(minimum) - 1
            if maximum != '':
                max_b = int(maximum) + 1
            # histogram:
            # color in bins of equal B-value ranges
            # subtract 0.1 from the lowest B in order to ensure that the single
            # atom with the lowest B value doesn't get omitted
            bin_width = (max_b - min_b) / nbins
            sel.append(selection + " and (%s = %4.4g" %
                       (item, min_b + bin_width) + ")")
            for j in range(1, nbins):
                #sel.append(selection + " and %s > %4.4g" % (item,min_b + j*bin_width))
                sel.append(dummy + " and %s = %4.4g" %
                           (item, min_b + j * bin_width))

# call the function to create the gradient which returns a list of colours
        colours = make_gradient(sel, gradient, nbins, sat, value, hs, he, ss,
                                se, vs, ve, colorname)

        # do the colouring now
        for j in range(nbins):
            print "Color select: ", sel[j]
            cmd.color(colours[j], sel[j])
    sel = []
    colours = []
Пример #46
0
cmd.load(url, 'orig')

cmd.select('origPA', 'chain A')
cmd.select('origPB1', 'chain B')
cmd.select('origPB2', 'chain C')

cmd.load('S009PB2_{0}.pdb'.format(structure, 'S009'))
cmd.super('S009', 'orig')

cmd.hide('everything')
cmd.show('cartoon')
# cmd.show('surface')
for c in ['origPA', 'origPB1', 'S009']:
    cmd.show('surface', '{0}'.format(c))
cmd.remove('origPB2')
cmd.color('palegreen', 'origPA')
cmd.color('palecyan', 'origPB1')
cmd.color('white', 'S009')

cmd.orient()

### To get PB2 only
cmd.hide('everything', 'orig')
cmd.hide('surface', 'S009')
# cmd.show('cartoon', 'orig')
cmd.show('surface', 'S009')

###### END PREAMBLE

metric = 'topA549'
cmd.color('white', 'S009')
Пример #47
0
grids = ['donor', 'apolar', 'acceptor']
num = 0
surf_transparency = 0.2

if dirpath:
    gfiles = [join(dirpath, g) for g in gfiles]

for t in threshold_list:
    for i in range(len(grids)):
        try:
            cmd.load(r'%s' % (gfiles[i]), '%s_%s' % (grids[i], str(num)))
            cmd.isosurface('surface_%s_%s_%s' % (grids[i], t, num),
                           '%s_%s' % (grids[i], num), t)
            cmd.set('transparency', surf_transparency,
                    'surface_%s_%s_%s' % (grids[i], t, num))
            cmd.color(colour_dict['%s' % (grids[i])],
                      'surface_%s_%s_%s' % (grids[i], t, num))
            cmd.group('threshold_%s' % (t),
                      members='surface_%s_%s_%s' % (grids[i], t, num))
            cmd.group('threshold_%s' % (t), members='label_threshold_%s' % (t))
        except:
            continue

    try:
        cmd.group('hotspot_%s' % (num), members='threshold_%s' % (t))
    except:
        continue

    for g in grids:

        cmd.group('hotspot_%s' % (num), members='%s_%s' % (g, num))
Пример #48
0
    def setzeFarbe(self, event):
        if ((self.selection != "") & (self.monograd == 'mono')):
            if (self.colorsystem == 'rgb'):
                col = []
                #read RGB values from scales
                r = int(self.ScaleRed.get())
                g = int(self.ScaleGreen.get())
                b = int(self.ScaleBlue.get())
                rgbcolor = r, g, b
                #Prepare a rgb tupel
                col.append(rgbcolor)
                #hexcolor for colorfields
                hexcolor = self.RGBToHTMLColor(rgbcolor)
                self.colorfield1.config(bg=hexcolor)
                self.colorfield2.config(bg=hexcolor)
                cmd.delete(self.selection + "_color")
                cmd.set_color(self.selection + "_color", col[0])
                cmd.color(self.selection + "_color", self.selection)
                del col[0]
            elif (self.colorsystem == 'hsv'):
                col = []
                #read HSV values from scales
                h = float(self.ScaleRed.get())
                s = float(self.ScaleGreen.get())
                v = float(self.ScaleBlue.get())

                #HSV to RGB and change from 1.0, 1.0, 1.0 format to 255,255,255 format
                rgbcolor = colorsys.hsv_to_rgb(h, s, v)
                r = 255 * rgbcolor[0]
                g = 255 * rgbcolor[1]
                b = 255 * rgbcolor[2]
                #as above
                rgbcolor = r, g, b
                col.append(rgbcolor)
                #hexcolor for colorfields
                hexcolor = self.RGBToHTMLColor(rgbcolor)
                self.colorfield1.config(bg=hexcolor)
                self.colorfield2.config(bg=hexcolor)
                cmd.delete(self.selection + "_color")
                cmd.set_color(self.selection + "_color", col[0])
                cmd.color(self.selection + "_color", self.selection)
                del col[0]
        elif ((self.selection != "") & (self.monograd == 'grad')):

            if (self.colorsystem == 'rgb'):
                col = []
                #read RGB values from scales
                r = int(self.ScaleRed.get())
                g = int(self.ScaleGreen.get())
                b = int(self.ScaleBlue.get())
                rgbcolor = r, g, b
                #Prepare a rgb tupel
                col.append(rgbcolor)
                #hexcolor for colorfields
                hexcolor = self.RGBToHTMLColor(rgbcolor)
                if (self.farbe12 == 'farbe1'):
                    self.colorfield1.config(bg=hexcolor)
                    self.farbe1 = rgbcolor
                elif (self.farbe12 == 'farbe2'):
                    self.colorfield2.config(bg=hexcolor)
                    self.farbe2 = rgbcolor

            elif (self.colorsystem == 'hsv'):
                col = []
                #read HSV values from scales
                h = float(self.ScaleRed.get())
                s = float(self.ScaleGreen.get())
                v = float(self.ScaleBlue.get())

                #HSV to RGB and change from 1.0, 1.0, 1.0 format to 255,255,255 format
                rgbcolor = colorsys.hsv_to_rgb(h, s, v)
                r = 255 * rgbcolor[0]
                g = 255 * rgbcolor[1]
                b = 255 * rgbcolor[2]
                #as above
                rgbcolor = r, g, b
                col.append(rgbcolor)
                #hexcolor for colorfields
                hexcolor = self.RGBToHTMLColor(rgbcolor)

                if (self.farbe12 == 'farbe1'):
                    self.colorfield1.config(bg=hexcolor)
                    self.farbe1 = rgbcolor
                elif (self.farbe12 == 'farbe2'):
                    self.colorfield2.config(bg=hexcolor)
                    self.farbe2 = rgbcolor
Пример #49
0
def process_session(
    ensemble_collector,
    patterns,
    group,
    max_size,
    plot,
    plot_annot,
    plot_class,
    plot_method,
    table,
    base_root=None,
):
    """Main plugin code."""

    results = {}
    for pattern in sorted(patterns):
        for path in glob(pattern):
            if base_root is None:
                root = pm.get_legal_name(splitext(basename(path))[0])
            else:
                root = base_root
            results[root] = [], []
            ensembles, clusters = results[root]

            if group:
                root = f"{group}.{root}"
            else:
                root = root

            with disable_feedback("all", "warnings"):
                with settings(group_auto_mode=1):
                    pm.load(path)

            try:
                collected_ensembles = list(ensemble_collector(max_size))
                if len(collected_ensembles) == 0:
                    raise Exception("No ensembles found.")
            except:
                raise CmdException(f"File {path} is invalid.")

            with settings(group_auto_mode=2):
                pm.create(f"{root}.protein", "protein")
                pm.delete("protein")

                i = 0

                for ensemble in collected_ensembles:
                    klass = ensemble.klass
                    if klass:
                        i += 1
                        pm.hide("sticks", ensemble.selection)
                        pm.show("line", ensemble.selection)
                        pm.util.cbas(ensemble.selection)

                        obj = f"{root}.{klass}.{i:03}"
                        pm.create(obj, ensemble.selection)

                        if hasattr(pm, "set_property"):
                            pm.set_property("Class", ensemble.klass, obj)
                            pm.set_property("S", ensemble.strength, obj)
                            pm.set_property("S (CS0)",
                                            ensemble.clusters[0].strength, obj)
                            pm.set_property("CD",
                                            ensemble.max_center_to_center, obj)
                            pm.set_property("MD", ensemble.max_dist, obj)

                        ensemble.selection = obj
                        ensembles.append(ensemble)

                for i, cluster in enumerate(Cluster.collect_atlas()):
                    pm.hide("sticks", cluster.selection)
                    pm.show("line", cluster.selection)
                    pm.util.cbay(cluster.selection)
                    obj = f"{root}.CS.{i:03}_{cluster.strength:03}"
                    pm.create(obj, cluster.selection)
                    pm.delete(cluster.selection)
                    cluster.selection = obj
                    clusters.append(cluster)

            pm.color("salmon", f"{root}.B.* or {root}.Bs.* {root}.Bl.*")
            pm.color("red", f"{root}.D.* or {root}.Ds.* {root}.Dl.*")

            pm.hide("lines", f"{root}.*")
            pm.disable(f"{root}.CS")

            pm.show("mesh", f"{root}.B.* or {root}.Bs.* {root}.Bl.*")
            pm.show("mesh", f"{root}.D.* or {root}.Ds.* {root}.Dl.*")

            pm.show("sticks", f"{root}.CS.*")
            pm.util.cbac(f"{root}.CS.000_*")
            pm.util.cbap(f"{root}.CS.001_*")
            pm.util.cbay(f"{root}.CS.002_*")
            pm.util.cbas(f"{root}.CS.003_*")
            pm.util.cbaw(f"{root}.CS.004_*")
            pm.util.cbab(f"{root}.CS.005_*")
            pm.util.cbao(f"{root}.CS.006_*")
            pm.util.cbag(f"{root}.CS.007_*")
            pm.util.cbam(f"{root}.CS.008_*")
            pm.util.cbak(f"{root}.CS.009_*")

            pm.hide("nb_spheres", "*label")

            pm.orient(root)

    if plot:

        roots = []
        selections = []

        for root in sorted(results):
            for ensemble in results[root][0]:
                roots.append(root)
                selections.append(ensemble.selection)

        if plot_class:
            selections = [s for s in selections if "." + plot_class + "." in s]

        matrix_over = np.zeros((len(selections), len(selections)))
        for i, (root1, selection1) in enumerate(zip(roots, selections)):
            for j, (root2, selection2) in enumerate(zip(roots, selections)):
                if i >= j:
                    matrix_over[i][j] = fo_(selection1, selection2)
                else:
                    matrix_over[i][j] = float('nan')

        fig, ax = plt.subplots(1, 1)
        sb.heatmap(
            matrix_over,
            vmax=1,
            vmin=0,
            yticklabels=selections,
            xticklabels=selections,
            annot=plot_annot,
            cmap="YlGnBu",
            ax=ax,
        )
        ax.set_title("fractional overlap")
        ax.set_xticklabels(selections, rotation=45, ha="right")
        plt.show()

    if table:
        tmpl = Template("""
            <table>
                <tr>
                    <th>Object</th>
                    <th>Class</th>
                    <th>S</th>
                    <th>S0</th>
                    <th>CD</th>
                    <th>MD</th>
                </tr>
                {% for root in results %}
                    {% for e in results[root][0] %}
                        <tr>
                            <td>{{ e.selection }}</td>
                            <td>{{ e.klass }}</td>
                            <td>{{ e.strength }}</td>
                            <td>{{ e.strength0 }}</td>
                            <td>{{ e.max_center_to_center | round(2) }}</td>
                            <td>{{ e.max_dist | round(2) }}</td>
                        </tr>
                    {% endfor %}
                {% endfor %}
            </table>
        """)

        _, path = tempfile.mkstemp(suffix=".html")
        with open(path, "w") as fd:
            fd.write(tmpl.render(results=results))
        webbrowser.open(path)

    return results
Пример #50
0
def colorObj(objName, colorScheme):
    """ sets an molecule's color scheme
    Arguments:
      - objName: the object (molecule) to change
      - colorScheme: name of the color scheme to use
        for the object (should be either 'std' or one of the
        color schemes defined in pymol.utils)
  """
    if colorScheme:
        if colorScheme == 'std':
            # this is an adaptation of the cbag scheme from util.py, but
            # with a gray carbon.
            cmd.color("magenta", "(" + objName + ")", quiet=1)
            cmd.color("oxygen", "(elem O and " + objName + ")", quiet=1)
            cmd.color("nitrogen", "(elem N and " + objName + ")", quiet=1)
            cmd.color("sulfur", "(elem S and " + objName + ")", quiet=1)
            cmd.color("hydrogen", "(elem H and " + objName + ")", quiet=1)
            cmd.color("gray", "(elem C and " + objName + ")", quiet=1)
        elif hasattr(utils, colorScheme):
            fn = getattr(utils, colorScheme)
            fn(objName, quiet=1)
        res = 1
    else:
        res = 0
    return res
Пример #51
0
    def redraw(self):
        """
        Highlight the sidechains around the active mutation(s).  Everything 
        this method adds to the scene is put in its own object, so that it can 
        be easily undone by the next call to redraw() or cleanup().
        """
        cmd.refresh_wizard()
        if not self.active_mutations:
            return

        wt_obj = self.wildtype_obj
        mut_obj = self.mutant_obj

        # wt_seles and mut_seles: lists containing individual pymol selection 
        # expressions for each residue that the user wants to see.

        wt_seles = []
        mut_seles = []

        for muti in self.active_mutations:
            wt_resi, wt_chain = self.aligned_resis[0][muti]
            mut_resi, mut_chain = self.aligned_resis[1][muti]
            if wt_resi is not None:
                wt_seles.append('(resi {wt_resi} and chain {wt_chain})'.format(**locals()))
            if mut_resi is not None:
                mut_seles.append('(resi {mut_resi} and chain {mut_chain})'.format(**locals()))

        # wt_sele and mut_sele: Pymol selection expressions that combine all 
        # the individual selections in wt_seles and mut_seles.

        wt_sele = '({})'.format(' or '.join(wt_seles)) if wt_seles else 'none'
        mut_sele = '({})'.format(' or '.join(mut_seles)) if mut_seles else 'none'

        # env_sele: A pymol selection expression that specifies all which 
        # residues are close enough to the mutation(s) to be considered part of 
        # the "environment".  This selection is actually a template, and needs 
        # to be formatted with either wt_obj or mut_obj before use.

        h_sele = (
                '(elem H and (neighbor elem C))' if self.show_polar_h else
                '(elem H)')
        env_sele = (
                '(byres {{}} within {self.neighbor_radius} of '
                  '(({wt_obj} and {wt_sele}) or ({mut_obj} and {mut_sele})))'
                'and not {h_sele}'.format(**locals()))

        # Render the scene into the wt_env, mut_env, wt_hbonds, and mut_hbonds 
        # objects.  Limiting ourselves to these objects makes it easy to redraw 
        # our comparisons without getting in the user's way, or vice versa.

        initial_view = cmd.get_view()

        cmd.delete('wt_env')
        cmd.delete('mut_env')
        cmd.delete('wt_hbonds')
        cmd.delete('mut_hbonds')

        cmd.create('wt_env', env_sele.format(wt_obj))
        cmd.create('mut_env', env_sele.format(mut_obj))

        # Hide the wildtype polar contacts by default, because I'm more often 
        # interested in the contacts being made in the design.

        cmd.distance('wt_hbonds', 'wt_env', 'wt_env', mode=2)
        cmd.distance('mut_hbonds', 'mut_env', 'mut_env', mode=2)
        cmd.disable('wt_hbonds')

        cmd.show_as('sticks', 'wt_env')
        cmd.show_as('sticks', 'mut_env')

        if self.wildtype_hilite != 'none':
            cmd.color(self.wildtype_hilite, 'wt_env and {wt_sele} and elem C'.format(**locals()))
        if self.mutant_hilite != 'none':
            cmd.color(self.mutant_hilite, 'mut_env and {mut_sele} and elem C'.format(**locals()))

        # Pan smoothly to the new scene.

        cmd.set_view(initial_view)
        cmd.zoom('mut_env', buffer=self.zoom_padding, animate=-1)
Пример #52
0
cmd.set_view (\
     ''' 0.847476959,    0.312563360,   -0.429026186,\
     0.428718925,   -0.879621565,    0.206053212,\
    -0.312964320,   -0.358564079,   -0.879461229,\
     0.000346251,    0.000221314, -170.217346191,\
    28.520931244,    7.739858627,   56.579563141,\
   128.644897461,  212.033325195,  -20.000000000''' )


cmd.set("transparency", "0.3")
cmd.set("surface_quality", "1")

cmd.select("nlobe", "resi 1:95")
cmd.select("clobe", "resi 96:150+178:277")
cmd.select("aloop", "resi 151:177")
cmd.color("limon", "nlobe")
cmd.color("bluewhite", "clobe")
cmd.color("deepsalmon", "aloop")

cmd.select("pocket", "resi 16+17+18+19+20+21+22+24+41+43+60+64+73+86+88+89+90+91+92+94+95+97+98+101+134+135+137+139+140+142+152+153+154+155+156+171+172+173+174+175+176+177+178+179+183+184+187+189+204+211+212+218+219")
cmd.show("surface", "pocket")
cmd.color("deepteal", "pocket")

cmd.hide("lines", "all")
cmd.show("cartoon", "all")

cmd.set("cartoon_fancy_helices", 1)
cmd.set("ray_trace_mode",  1)
cmd.set("two_sided_lighting", "on")
cmd.set("reflect", 0)
cmd.set("ambient", 0.5)
Пример #53
0
def color_h(selection='all'):
    s = str(selection)
    print(s)
    cmd.set_color('color_ile', [0.996, 0.062, 0.062])
    cmd.set_color('color_phe', [0.996, 0.109, 0.109])
    cmd.set_color('color_val', [0.992, 0.156, 0.156])
    cmd.set_color('color_leu', [0.992, 0.207, 0.207])
    cmd.set_color('color_trp', [0.992, 0.254, 0.254])
    cmd.set_color('color_met', [0.988, 0.301, 0.301])
    cmd.set_color('color_ala', [0.988, 0.348, 0.348])
    cmd.set_color('color_gly', [0.984, 0.394, 0.394])
    cmd.set_color('color_cys', [0.984, 0.445, 0.445])
    cmd.set_color('color_tyr', [0.984, 0.492, 0.492])
    cmd.set_color('color_pro', [0.980, 0.539, 0.539])
    cmd.set_color('color_thr', [0.980, 0.586, 0.586])
    cmd.set_color('color_ser', [0.980, 0.637, 0.637])
    cmd.set_color('color_his', [0.977, 0.684, 0.684])
    cmd.set_color('color_glu', [0.977, 0.730, 0.730])
    cmd.set_color('color_asn', [0.973, 0.777, 0.777])
    cmd.set_color('color_gln', [0.973, 0.824, 0.824])
    cmd.set_color('color_asp', [0.973, 0.875, 0.875])
    cmd.set_color('color_lys', [0.899, 0.922, 0.922])
    cmd.set_color('color_arg', [0.899, 0.969, 0.969])
    cmd.color("color_ile", "(" + s + " and resn ile)")
    cmd.color("color_phe", "(" + s + " and resn phe)")
    cmd.color("color_val", "(" + s + " and resn val)")
    cmd.color("color_leu", "(" + s + " and resn leu)")
    cmd.color("color_trp", "(" + s + " and resn trp)")
    cmd.color("color_met", "(" + s + " and resn met)")
    cmd.color("color_ala", "(" + s + " and resn ala)")
    cmd.color("color_gly", "(" + s + " and resn gly)")
    cmd.color("color_cys", "(" + s + " and resn cys)")
    cmd.color("color_tyr", "(" + s + " and resn tyr)")
    cmd.color("color_pro", "(" + s + " and resn pro)")
    cmd.color("color_thr", "(" + s + " and resn thr)")
    cmd.color("color_ser", "(" + s + " and resn ser)")
    cmd.color("color_his", "(" + s + " and resn his)")
    cmd.color("color_glu", "(" + s + " and resn glu)")
    cmd.color("color_asn", "(" + s + " and resn asn)")
    cmd.color("color_gln", "(" + s + " and resn gln)")
    cmd.color("color_asp", "(" + s + " and resn asp)")
    cmd.color("color_lys", "(" + s + " and resn lys)")
    cmd.color("color_arg", "(" + s + " and resn arg)")
Пример #54
0
def color_h2(selection='all'):
    s = str(selection)
    print(s)
    cmd.set_color("color_ile2", [0.938, 1, 0.938])
    cmd.set_color("color_phe2", [0.891, 1, 0.891])
    cmd.set_color("color_val2", [0.844, 1, 0.844])
    cmd.set_color("color_leu2", [0.793, 1, 0.793])
    cmd.set_color("color_trp2", [0.746, 1, 0.746])
    cmd.set_color("color_met2", [0.699, 1, 0.699])
    cmd.set_color("color_ala2", [0.652, 1, 0.652])
    cmd.set_color("color_gly2", [0.606, 1, 0.606])
    cmd.set_color("color_cys2", [0.555, 1, 0.555])
    cmd.set_color("color_tyr2", [0.508, 1, 0.508])
    cmd.set_color("color_pro2", [0.461, 1, 0.461])
    cmd.set_color("color_thr2", [0.414, 1, 0.414])
    cmd.set_color("color_ser2", [0.363, 1, 0.363])
    cmd.set_color("color_his2", [0.316, 1, 0.316])
    cmd.set_color("color_glu2", [0.27, 1, 0.27])
    cmd.set_color("color_asn2", [0.223, 1, 0.223])
    cmd.set_color("color_gln2", [0.176, 1, 0.176])
    cmd.set_color("color_asp2", [0.125, 1, 0.125])
    cmd.set_color("color_lys2", [0.078, 1, 0.078])
    cmd.set_color("color_arg2", [0.031, 1, 0.031])
    cmd.color("color_ile2", "(" + s + " and resn ile)")
    cmd.color("color_phe2", "(" + s + " and resn phe)")
    cmd.color("color_val2", "(" + s + " and resn val)")
    cmd.color("color_leu2", "(" + s + " and resn leu)")
    cmd.color("color_trp2", "(" + s + " and resn trp)")
    cmd.color("color_met2", "(" + s + " and resn met)")
    cmd.color("color_ala2", "(" + s + " and resn ala)")
    cmd.color("color_gly2", "(" + s + " and resn gly)")
    cmd.color("color_cys2", "(" + s + " and resn cys)")
    cmd.color("color_tyr2", "(" + s + " and resn tyr)")
    cmd.color("color_pro2", "(" + s + " and resn pro)")
    cmd.color("color_thr2", "(" + s + " and resn thr)")
    cmd.color("color_ser2", "(" + s + " and resn ser)")
    cmd.color("color_his2", "(" + s + " and resn his)")
    cmd.color("color_glu2", "(" + s + " and resn glu)")
    cmd.color("color_asn2", "(" + s + " and resn asn)")
    cmd.color("color_gln2", "(" + s + " and resn gln)")
    cmd.color("color_asp2", "(" + s + " and resn asp)")
    cmd.color("color_lys2", "(" + s + " and resn lys)")
    cmd.color("color_arg2", "(" + s + " and resn arg)")
Пример #55
0
from pymol import cmd, stored
cmd.load(
    "/Users/meghan/Documents/PhD/GitHubProjects/v6_2018_Network/CompStrDefns/CompPDBs/1UYO.pdb"
)
cmd.hide("everything", "all")
cmd.color("wheat", "all")
cmd.select("Xstrand0", "resi 821-829 & chain X ")
cmd.color("white", "Xstrand0")

cmd.select("Xstrand1", "resi 840-852 & chain X ")
cmd.color("red", "Xstrand1")

cmd.select("Xstrand2", "resi 859-872 & chain X ")
cmd.color("orange", "Xstrand2")

cmd.select("Xstrand3", "resi 877-893 & chain X ")
cmd.color("purple", "Xstrand3")

cmd.select("Xstrand4", "resi 897-916 & chain X ")
cmd.color("yellow", "Xstrand4")

cmd.select("Xstrand5", "resi 920-941 & chain X ")
cmd.color("green", "Xstrand5")

cmd.select("Xstrand6", "resi 948-968 & chain X ")
cmd.color("cyan", "Xstrand6")

cmd.select("Xstrand7", "resi 974-996 & chain X ")
cmd.color("blue", "Xstrand7")

cmd.select("Xstrand8", "resi 999-1009 & chain X ")
Пример #56
0
def seq_diff(obj1, obj2, doColor=False):
    if cmd.count_atoms(obj1 + ' and name CA') == 0:
        print('%s is empty' % obj1)
        return
    if cmd.count_atoms(obj2 + ' and name CA') == 0:
        print('%s is empty' % obj2)
        return

    if cmd.count_atoms(obj1 +
                       ' and name CA') != cmd.count_atoms(obj2 +
                                                          ' and name CA'):
        print('Selections have different number of residues.')
        return

    stored.resn1, stored.resn2 = [], []
    stored.resi1, stored.resi2 = [], []
    stored.chain1, stored.chain2 = [], []

    cmd.iterate(obj1 + ' and name CA', 'stored.resn1.append(resn)')
    cmd.iterate(obj2 + ' and name CA', 'stored.resn2.append(resn)')

    cmd.iterate(obj1 + ' and name CA', 'stored.resi1.append(resi)')
    cmd.iterate(obj2 + ' and name CA', 'stored.resi2.append(resi)')

    cmd.iterate(obj1 + ' and name CA', 'stored.chain1.append(chain)')
    cmd.iterate(obj2 + ' and name CA', 'stored.chain2.append(chain)')

    #print len(stored.resn1)

    mutant_selection = []

    for n1, n2, i1, i2, c1, c2 in zip(stored.resn1, stored.resn2, stored.resi1,
                                      stored.resi2, stored.chain1,
                                      stored.chain2):
        if c1 == '':
            c1 = '""'
        if c2 == '':
            c2 = '""'
        #print 'Resi1: '+i1
        #print 'Resi2: '+i2
        if n1 != n2:
            #print 'Mutation at resi: '+i2
            mutant_selection.append('%s and resi %s and chain %s' %
                                    (obj2, i2, c2))

    if mutant_selection == '':
        print('No mutations found')
        #raise CmdException

    total_selection = ''
    total_color = ''
    for m in mutant_selection:
        total_selection += '(' + m + ') or '
        total_color += '(' + m + ' and name C*) or '

    total_selection = total_selection[:-4]
    total_color = total_color[:-4]

    cmd.select("%s_diff" % (obj2), total_selection)

    if doColor:
        cmd.color('%s' % doColor, total_color)
Пример #57
0
def promix(mobile,
           target,
           K=0,
           prefix=None,
           mobile_state=-1,
           target_state=-1,
           match='align',
           guide=1,
           quiet=1,
           bsync=-1,
           _self=cmd):
    '''
DESCRIPTION

    Finds rigid segments in two objects with different conformation.

    Requires CSB, https://github.com/csb-toolbox/CSB

ARGUMENTS

    mobile, target = string: atom selections

    K = integer: Number of segments {default: guess}

    prefix = string: Prefix of named segment selections to make

SEE ALSO

    intra_promix

REFERENCE

    Mixture models for protein structure ensembles
    Hirsch M, Habeck M. - Bioinformatics. 2008 Oct 1;24(19):2184-92
    '''
    from numpy import asarray
    from csb.statistics.mixtures import SegmentMixture as Mixture
    from .querying import get_coords, get_object_name

    K, guide, quiet, bsync = int(K), int(guide), int(quiet), int(bsync)
    mobile_state, target_state = int(mobile_state), int(target_state)
    if bsync < 0:
        bsync = not quiet

    if isinstance(target, str) and target.isdigit() and \
            cmd.count_atoms('?' + target) == 0 and cmd.count_states(mobile) > 1:
        print(' Warning: sanity test suggest you want "intra_promix"')
        return intra_promix(mobile, target, prefix, 0, guide, quiet, bsync)

    if guide:
        mobile = '(%s) and guide' % (mobile)
        target = '(%s) and guide' % (target)

    cmd.color('gray', mobile)
    obj = get_object_name(mobile)
    mm = MatchMaker(mobile, target, match)
    selection = mm.mobile

    X = asarray([
        get_coords(mm.mobile, mobile_state),
        get_coords(mm.target, target_state),
    ])

    if not bsync:
        _promix(**locals())
    else:
        import threading
        t = threading.Thread(target=_promix, kwargs=locals())
        t.setDaemon(1)
        t.start()
Пример #58
0
grids = ['donor', 'apolar', 'acceptor']
num = 0
surf_transparency = 0.2

if dirpath:
    gfiles = [join(dirpath, g) for g in gfiles]

for t in threshold_list:
    for i in range(len(grids)):
        try:
            cmd.load(r'%s' % (gfiles[i]), '%s_%s' % (grids[i], str(num)))
            cmd.isosurface('surface_%s_%s_%s' % (grids[i], t, num),
                           '%s_%s' % (grids[i], num), t)
            cmd.set('transparency', surf_transparency,
                    'surface_%s_%s_%s' % (grids[i], t, num))
            cmd.color(colour_dict['%s' % (grids[i])],
                      'surface_%s_%s_%s' % (grids[i], t, num))
            cmd.group('threshold_%s' % (t),
                      members='surface_%s_%s_%s' % (grids[i], t, num))
            cmd.group('threshold_%s' % (t), members='label_threshold_%s' % (t))
        except:
            continue

    try:
        cmd.group('hotspot_%s' % (num), members='threshold_%s' % (t))
    except:
        continue

    for g in grids:

        cmd.group('hotspot_%s' % (num), members='%s_%s' % (g, num))
Пример #59
0
#cmd.zoom()

cmd.set("use_shaders", 1)
colors = ['red', 'green', 'blue', 'yellow', 'violet', 'cyan',    \
           'salmon', 'lime', 'pink', 'slate', 'magenta', 'orange', 'marine', \
           'olive', 'purple', 'teal', 'forest', 'firebrick', 'chocolate',    \
           'wheat', 'white', 'grey' ]

for file in os.listdir("."):
    if file.endswith(".pdb"):
        n = os.path.splitext(file)[0]
        cmd.load(file)
        cmd.hide("all")
        cmd.show("cartoon")
        i = 4
        for c in cmd.get_chains():
            if (c and c.strip()):
                print(n + " has chain " + c)
                cmd.color(colors[i], "chain " + c)
            else:
                cmd.color(colors[i], "chain *")
            i += 1
        print("Saving " + file + " as " + n + ".png")
        #cmd.png(n + ".png", 0, 0, 800)
        ###cmd.png(n + ".png", "3cm", "3cm", 600)
        ###cmd.png(n + ".png", 1200, 900, 300, 0, 0) #, 300, 0, 0)
        cmd.delete(n)

#print("saved pngs")
#cmd.quit()
Пример #60
0
def dyndom(mobile,
           target,
           window=5,
           domain=20,
           ratio=1.0,
           exe='',
           transform=1,
           quiet=1,
           mobile_state=1,
           target_state=1,
           match='align',
           preserve=0):
    '''
DESCRIPTION

    DynDom wrapper

    DynDom is a program to determine domains, hinge axes and hinge bending
    residues in proteins where two conformations are available.

    http://fizz.cmp.uea.ac.uk/dyndom/

USAGE

    dyndom mobile, target [, window [, domain [, ratio ]]]
    '''
    import tempfile, subprocess, os, shutil, sys
    from .exporting import save_pdb_without_ter

    window, domain, ratio = int(window), int(domain), float(ratio)
    transform, quiet = int(transform), int(quiet)
    mobile_state, target_state = int(mobile_state), int(target_state)

    mm = MatchMaker('(%s) & polymer & state %d' % (mobile, mobile_state),
                    '(%s) & polymer & state %d' % (target, target_state),
                    match)

    chains = cmd.get_chains(mm.mobile)
    if len(chains) != 1:
        print('mobile selection must be single chain')
        raise CmdException
    chain1id = chains[0]
    chains = cmd.get_chains(mm.target)
    if len(chains) != 1:
        print('target selection must be single chain')
        raise CmdException
    chain2id = chains[0]

    if not exe:
        from . import which
        exe = which('DynDom', 'dyndom')
        if not exe:
            print(' Error: Cannot find DynDom executable')
            raise CmdException
    else:
        exe = cmd.exp_path(exe)
    tempdir = tempfile.mkdtemp()

    try:
        filename1 = os.path.join(tempdir, 'mobile.pdb')
        filename2 = os.path.join(tempdir, 'target.pdb')
        commandfile = os.path.join(tempdir, 'command.txt')
        infofile = os.path.join(tempdir, 'out_info')

        save_pdb_without_ter(filename1, mm.mobile, state=mobile_state)
        save_pdb_without_ter(filename2, mm.target, state=target_state)

        f = open(commandfile, 'w')
        f.write('title=out\nfilename1=%s\nchain1id=%s\nfilename2=%s\nchain2id=%s\n' \
                'window=%d\ndomain=%d\nratio=%.4f\n' % (filename1, chain1id,
                    filename2, chain2id, window, domain, ratio))
        f.close()

        process = subprocess.Popen([exe, commandfile],
                                   cwd=tempdir,
                                   stderr=subprocess.STDOUT,
                                   stdout=subprocess.PIPE)

        for line in process.stdout:
            if not quiet:
                sys.stdout.write(line)

        if process.poll() != 0:
            raise CmdException('"%s" failed with status %d' %
                               (exe, process.returncode))

        cmd.color('gray', mobile)
        fixed_name = dyndom_parse_info(infofile, mm.mobile, quiet)
    except OSError:
        print(
            'Cannot execute "%s", please provide full path to DynDom executable'
            % (exe))
        raise CmdException
    finally:
        if not int(preserve):
            shutil.rmtree(tempdir)
        elif not quiet:
            print(' Not deleting temporary directory:', tempdir)

    if transform and fixed_name is not None:
        cmd.align(fixed_name, target)