def color_destab(posfile,binding=False):
	#re_pos = re.compile('([A-Z])\s+([0-9]+)\s+[a-zA-Z]+\s+([0-9]+)\s+([0-9]+)')
	re_pos = re.compile('([A-Z])\s+([0-9]+)\s+([0-9]+)')
	cols = [ ('destab%i' %i, [float(i)/20,0,0]) for i in range(20) ]
	print cols
	for name,col in cols: cmd.set_color(name,col)
	cmd.color('gray','all')
	for match in re_pos.finditer( open(posfile).read() ):
		#chain,pos,ndestab,nbind = match.groups()
		chain,pos,ndestab = match.groups()
		which_n = ndestab
		if binding: which_n = nbind
		print chain, pos, which_n
		print cols[int(which_n)]
		cmd.color( cols[int(which_n)][0], 'c. %s and i. %s' %(chain,pos) )
	# the following only works if DNASelections has alreay been run/called
	cmd.hide('everything')
	cmd.show('ribbon','notDNA')
	cmd.set('ribbon_sampling',5)
	cmd.show('lines','notDNA')
	cmd.set('ray_trace_mode',0)
	cmd.create('dnao','DNA')
	cmd.hide('labels')
	cmd.hide('everything','dnao')
	cmd.hide('everything','DNA')
	cmd.show('surface','dnao')
	cmd.show('spheres','r. hoh w. 4 of DNA')
	cmd.color('marine','r. hoh')
Esempio n. 2
0
def axes(name='axes'):
    '''
DESCRIPTION

    Puts coordinate axes to the lower left corner of the viewport.
    '''
    from pymol import cgo

    auto_zoom = cmd.get('auto_zoom')
    cmd.set('auto_zoom', 0)

    w = 0.06 # cylinder width
    l = 0.75 # cylinder length
    h = 0.25 # cone hight
    d = w * 1.618 # cone base diameter

    obj = [cgo.CYLINDER, 0.0, 0.0, 0.0,   l, 0.0, 0.0, w, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0,
           cgo.CYLINDER, 0.0, 0.0, 0.0, 0.0,   l, 0.0, w, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0,
           cgo.CYLINDER, 0.0, 0.0, 0.0, 0.0, 0.0,   l, w, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0,
           cgo.CONE,   l, 0.0, 0.0, h+l, 0.0, 0.0, d, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0,
           cgo.CONE, 0.0,   l, 0.0, 0.0, h+l, 0.0, d, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0,
           cgo.CONE, 0.0, 0.0,   l, 0.0, 0.0, h+l, d, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0]

    PutCenterCallback(name, 1).load()
    cmd.load_cgo(obj, name)

    cmd.set('auto_zoom',auto_zoom)
Esempio n. 3
0
File: T01.py Progetto: Almad/pymol
def bg_rgb():
   while 1:
      time.sleep(random.random()*5)
      cmd.set('bg_rgb','%8.3f %8.3f %8.3f'%(
              random.random()/3,
              random.random()/3,
              random.random()/3))
Esempio n. 4
0
def test_msms_surface():
    eps = 1e-3
    cmd.reinitialize()
    cmd.fragment('ala', 'm1')
    # default
    psico.msms.msms_surface(name='surf1')
    extent = cmd.get_extent('surf1')
    assert extent[0] == approx([-2.705, -3.208, -2.413], rel=eps)
    assert extent[1] == approx([3.530, 2.907, 2.676], rel=eps)
    # global solvent_radius
    cmd.set('solvent_radius', 3.5)
    psico.msms.msms_surface(name='surf2')
    extent = cmd.get_extent('surf2')
    assert extent[0] == approx([-2.705, -3.169, -2.436], rel=eps)
    assert extent[1] == approx([3.530, 2.907, 2.676], rel=eps)
    # object-level solvent_radius
    cmd.set('solvent_radius', 2.8, 'm1')
    psico.msms.msms_surface(name='surf3')
    extent = cmd.get_extent('surf3')
    assert extent[0] == approx([-2.705, -3.161, -2.427], rel=eps)
    assert extent[1] == approx([3.530, 2.907, 2.676], rel=eps)
    # modified atom radii
    cmd.alter('m1', 'vdw = 3.0')
    psico.msms.msms_surface(name='surf4')
    extent = cmd.get_extent('surf4')
    assert extent[0] == approx([-4.605, -5.162, -4.418], rel=eps)
    assert extent[1] == approx([5.030, 4.861, 4.681], rel=eps)
Esempio n. 5
0
def paper_settings(fancy=0, quiet=0):
    '''
DESCRIPTION

    Set rendering quality high and some stuff good for printing:
    
     * Side chain helper (cartoon_side_chain_helper = 1)
     * No shadows (ray_shadows = 0)

ARGUMENTS

    fancy = 0 or 1: set cartoon_fancy_helices and cartoon_highlight_color
    {default: 0}

NOTES

    You may also try "set ray_trace_mode, 1"
    '''
    fancy, quiet = int(fancy), int(quiet)
    if fancy == 1:
        cmd.set('cartoon_fancy_helices', 1, quiet=quiet)
        cmd.set('cartoon_highlight_color', 'grey50', quiet=quiet)
    cmd.set('cartoon_side_chain_helper', 1, quiet=quiet)
    cmd.set('ray_shadows', 0, quiet=quiet)
    cmd.set('opaque_background', 0, quiet=quiet)
    cmd.bg_color('white')
 def testLoadNoProperties(self, molfilename):
     cmd.set('load_object_props_default', '')
     cmd.load(self.datafile(molfilename), 'test')
     objs = cmd.get_object_list()
     for obj in objs:
         prop_list= cmd.get_property_list(obj)
         self.assertEquals(prop_list, None)
Esempio n. 7
0
def grepset(regexp=''):
    '''
DESCRIPTION
    "grepset" greps through the list of settings using a python
    regular expression as defined in the 're' module.
    It returns a list of settings/values matching the regexp.
    No regexp returns every setting.

USAGE
    grepset [regexp]

EXAMPLE
    grepset line
    grepset ray
    grepset (^line|color$)

SEE ALSO
        Python re module
    '''

    count = 0
    regexp = re.compile(regexp)
    matches = []
    for a in pymol.setting.get_index_list():
        setting = pymol.setting._get_name(a)
        if regexp.search(setting):
            count += 1
            matches.append((setting, cmd.get_setting_text(a, '', -1)))
    # max length of the setting names that matched
    maxlen = max([len(s[0]) for s in matches] + [0])
    fmt = "%%-%ds : %%s" % (maxlen,)
    for setting in matches:
        print fmt % setting
    print '%d settings matched' % (count,)
    cmd.set('text', 1)
Esempio n. 8
0
def load():
   cmd.set("valence")
   r = 0
   list = glob("pdb/*/*")
#   while list[0]!="pdb/f8/pdb1f8u":
#      list.pop(0)
   for file in list:
      try:
         cmd.delete('pdb')
         cmd.load(file,'pdb')
         cmd.set_title('pdb',1,os.path.split(file)[-1])
         cmd.rewind()
         cmd.orient('pdb')
         cmd.refresh()
         cmd.show_as("ribbon")
         cmd.refresh()
         cmd.show_as("sticks")
         cmd.refresh()
         sys.__stderr__.write(".")
         sys.__stderr__.flush()
         n = cmd.count_states()
         if n>1:
            cmd.rewind()
            sys.__stderr__.write(file+"\n")
            sys.__stderr__.flush()
            for a in range(1,n+1):
               cmd.forward()
               cmd.refresh()
      except:
         traceback.print_exc()
def useRosettaRadii():
	cmd.alter("element C", "vdw=2.00")
	cmd.alter("element N", "vdw=1.75")
	cmd.alter("element O", "vdw=1.55")
	cmd.alter("element H", "vdw=1.00")
	cmd.alter("element P", "vdw=1.90")
	cmd.set("sphere_scale", 1.0)
Esempio n. 10
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)
Esempio n. 11
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)
Esempio n. 12
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')
Esempio n. 13
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)
Esempio n. 14
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)
Esempio n. 15
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);
Esempio n. 16
0
def packing(pdb):
    "Derive mean packing density of pdb as pd.Series."
    cmd.delete('all')
    cmd.load(pdb)
    cmd.remove('solvent')
    # Only heavy atoms
    cmd.remove('hydro')
    # Compute SAS per atom
    cmd.set('dot_solvent', 1)
    cmd.get_area('all', load_b=1)
    cmd.select('interior', 'b = 0')

    counts = pd.Series(0, index=RADS)
    vest = pd.Series(0, index=RADS)
    # from biggest to smallest radius
    for r in RADS[::-1]:
        # Counting
        counts.loc[r] = cmd.select('extended', 'interior extend {}'.format(r))
        cmd.remove('not extended')
        # moleculare area
        #cmd.set('dot_solvent', 0)
        vest[r] = cmd.get_area('all')
    # Results
    cvdens = counts / vest
    counts.index = ["{}_rawcount".format(i) for i in counts.index]
    vest.index = ["{}_volume estimate".format(i) for i in vest.index]
    cvdens.index = ["{}_cv density".format(i) for i in cvdens.index]
    return pd.concat(([counts, cvdens, vest]))
Esempio n. 17
0
def slowpacking(pdb):
    "Derive mean packing density of pdb as pd.Series."
    cmd.delete('all')
    cmd.load(pdb)
    cmd.remove('solvent')
    # Only heavy atoms
    cmd.remove('hydro')
    # Compute SAS per atom
    cmd.set('dot_solvent')
    cmd.get_area('all', load_b=1)
    N = float(cmd.select('interior', 'b = 0'))

    internal_coords = [at.coord for at in cmd.get_model('interior').atom]#[1:50]
    all_coords = [at.coord for at in cmd.get_model('all').atom]#[1:50]

    # Count
    counts = pd.Series(0, index=RADS)
    for a, b in product(internal_coords, all_coords):
        es = euclid_step(a, b)
        if es is not None:
            counts.loc[es] += 1
    counts = counts.cumsum()
    # Mean per center atom
    meancounts = counts / N
    # Normalize to density
    volumina = pd.Series(4 / 3.0 * sp.pi * (RADS ** 3), index=RADS)
    density = meancounts / volumina
    # Correct for center
    density -= 1 / (4/3 * sp.pi * RADS ** 3)
    # Results
    counts.index = ["{}_correctcount".format(i) for i in counts.index]
    density.index = ["{}_density".format(i) for i in density.index]
    return pd.concat(([counts, density]))
Esempio n. 18
0
def show_interface(obj1, obj2, threshold=5.0):
	inter = get_interface(obj1, obj2, threshold)
	cmd.hide('everything', inter)
	cmd.show('cartoon', inter)
	cmd.show('surface', inter)
	cmd.show('sticks', inter + ' and not name c+o+n+ca ')
	cmd.set('transparency', 0.3, inter)
Esempio n. 19
0
def makeMovie(numClusts, frameRate):
	real = int(numClusts)+1;
	fr = int(frameRate)
	
	movieSetup = "1 x" + str(real*fr)
	cmd.mset(movieSetup)
	
	#Load in all the system data.
	for x in range(0, real):
		# load the next system.
		clustName = "system-" + str(x)
		system = clustName + ".xyz"
		cmd.load(system)
		# Set the sphere scale and view
		cmd.set("sphere_scale","0.5","all")
	
	#Set the right view
	cmd.set_view("0.910306633, -0.382467061, 0.158301696, 0.326706469, 0.898694992, 0.292592257, -0.254171938, -0.214630708, 0.943043232, 0.000000000, 0.000000000, -99.425979614, 10.461934090, 13.087766647, 11.786855698, 80.009132385, 118.842796326, -20.000000000")
	
	#Set all the frame data
	for x in range(0, real):
		# set the current frame.
		frameNum = (x*fr)+1
		cmd.frame(frameNum)
		clustName = "system-" + str(x)
		movieState = "hide; show spheres, " + clustName
		cmd.mdo(frameNum,movieState)
		cmd.mview("store")

	cmd.mview("reinterpolate")
	cmd.mplay()
Esempio n. 20
0
def process_molecule_mae(file_header, mol, suspend_undo):
    global already_processed
    global undo_each_molecule
    tot = []
    tot.extend(file_header)
    tot.extend(mol)
    molstr = string.join(tot,'')

    nameorig, mdl = read_mae_model(molstr)
    name = nameorig.strip()
    if name in already_processed:
        return True
    already_processed = set(already_processed | set([name]))
    tmpname = "_temp_%s" % name
    cmd.delete(tmpname)

    try:
        cmd.load_model(mdl, tmpname)
        natoms = cmd.count_atoms(tmpname)
    except:
        return False
    if undo_each_molecule:
        cmd.push_undo( "( %s )" % name, just_coordinates=0)
        cmd.set("suspend_undo", 1, updates=0)
    cmd.remove(name)
    cmd.create(name, tmpname, copy_properties=True)
    cmd.set_title(name, -1, "")

    cmd.delete(tmpname)
    if undo_each_molecule:
        cmd.set("suspend_undo", suspend_undo, updates=0)
        cmd.push_undo("", just_coordinates=0, finish_undo=1)
    return True
Esempio n. 21
0
def process_output_mae(outFile, suspend_undo):
    global undo_all_molecules_at_once
    global already_processed
    print "process_output_mae() called : outFile=", outFile
    file_header = None
    already_processed = set([])
    if undo_all_molecules_at_once:
        pushstr = ""
        it = iter(querying.get_object_list("enabled"))
        pushstr = it.next()
        for name in it:
            pushstr = "%s or %s" % (pushstr, name)
        cmd.push_undo( "( %s )" % pushstr, just_coordinates=0)
        cmd.set("suspend_undo", 1, updates=0)
    f2 = open(outFile)
    curmol = []
    success = True
    for l in f2.readlines():
        if l.find("f_m_ct") >=0:
            if not file_header:
                file_header = curmol
            else:
                success = process_molecule_mae(file_header, curmol, suspend_undo ) and success
            curmol = []
        curmol.append(l)
    if len(curmol) > 0:
        success = process_molecule_mae(file_header, curmol, suspend_undo ) and success
    if undo_all_molecules_at_once:
        cmd.set("suspend_undo", suspend_undo, updates=0)
        cmd.push_undo("", just_coordinates=0, finish_undo=1)
    return success
Esempio n. 22
0
def rcd( selection = "all" ):
  """
  fancy ribbon coloring for large RNA comparisons
  """
  rc( selection )
  cmd.cartoon( 'dumbbell')
  cmd.set( 'cartoon_dumbbell_radius', 0.5 )
Esempio n. 23
0
def rd():
  """
  rhiju's favorite coloring of proteins and generic molecules
  side chains are all-heavy-atom and colored CPK, backbone is
  rainbow cartoon from N to C terminus.
  """
  cmd.bg_color( "white" )
  AllObj=cmd.get_names("all")

  for x in AllObj:
    #print(AllObj[0],x)
    print x
    cmd.show( "cartoon", x )
    cmd.hide( "line", x )
    cmd.color( "white", x+" and elem C" )
    cmd.color( "blue", x+" and elem N" )
    cmd.color( "red", x+" and elem O" )
    cmd.color( "yellow", x+" and elem S" )
    cmd.spectrum( "resi", "rainbow", x+" and name CA+C" )
    cmd.show( "sticks", x +" and not elem H and not name C+N+O" )
    cmd.show( "sticks", x +" and resn PRO and name N" )
    cmd.show( "sticks", x + " and name NR+CR+CS+CP+CQ" )
    cmd.show( "sticks", x + " and not elem H and neighbor name NR+CQ+CR+CS+CP" )
    cmd.show( "sticks", x + " and not elem H and neighbor neighbor name NR+CQ+CR+CS+CP" )
    cmd.set( "cartoon_oval_width", 0.1 )
    cmd.set( "cartoon_oval_length", 0.5 )
Esempio n. 24
0
File: B08.py Progetto: Almad/pymol
def load():
   cmd.set("valence")
   r = 0
   list = glob("pdb/*/*")
#   while list[0]!="pdb/f8/pdb1f8u":
#      list.pop(0)
   for file in list:
      try:
         cmd.delete('pdb')
         cmd.load(file,'pdb')
         cmd.set_title('pdb',1,os.path.split(file)[-1])
         cmd.rewind()
         cmd.orient('pdb')
         cmd.refresh()
         cmd.zoom('center',16)
         cmd.label("polymer and (name ca or elem P)","'//%s/%s/%s`%s/%s'%(segi,chain,resn,resi,name)")
         cmd.refresh()
         sys.__stderr__.write(".")
         sys.__stderr__.flush()
         n = cmd.count_states()
         if n>1:
            cmd.rewind()
            sys.__stderr__.write(file+"\n")
            sys.__stderr__.flush()
            for a in range(1,n+1):
               cmd.forward()
               cmd.refresh()
      except:
         traceback.print_exc()
Esempio n. 25
0
    def testIgnoreCase(self):
        # check defaults
        self.assertEqual(cmd.get_setting_int('ignore_case'), 1)
        self.assertEqual(cmd.get_setting_int('ignore_case_chain'), 0)

        # data
        natoms = 10
        cmd.fragment('ala', 'm1')
        cmd.copy('m2', 'm1')
        cmd.alter('m1', 'chain, segi = "C", "S"')
        cmd.alter('m2', 'chain, segi = "c", "s"')
        cmd.alter('m2', 'resn, name = resn.lower(), name.lower()')

        self.assertEqual(cmd.count_atoms('chain C'), natoms)
        self.assertEqual(cmd.count_atoms('segi  S'), natoms)
        self.assertEqual(cmd.count_atoms('chain c'), natoms)
        self.assertEqual(cmd.count_atoms('segi  s'), natoms)
        self.assertEqual(cmd.count_atoms('resn ALA'), natoms * 2)
        self.assertEqual(cmd.count_atoms('resn ala'), natoms * 2)
        self.assertEqual(cmd.count_atoms('name CA'), 2)
        self.assertEqual(cmd.count_atoms('name ca'), 2)

        cmd.set('ignore_case_chain')

        self.assertEqual(cmd.count_atoms('chain C'), natoms * 2)
        self.assertEqual(cmd.count_atoms('segi  S'), natoms * 2)
        self.assertEqual(cmd.count_atoms('chain c'), natoms * 2)
        self.assertEqual(cmd.count_atoms('segi  s'), natoms * 2)

        cmd.set('ignore_case', 0)

        self.assertEqual(cmd.count_atoms('resn ALA'), natoms)
        self.assertEqual(cmd.count_atoms('resn ala'), natoms)
        self.assertEqual(cmd.count_atoms('name CA'), 1)
        self.assertEqual(cmd.count_atoms('name ca'), 1)
def findSurfaceAtoms(selection="all", cutoff=2.5, quiet=1):
    """
DESCRIPTION

    Finds those atoms on the surface of a protein
    that have at least 'cutoff' exposed A**2 surface area.

USAGE

    findSurfaceAtoms [ selection, [ cutoff ]]

SEE ALSO

    findSurfaceResidues
    """
    cutoff, quiet = float(cutoff), int(quiet)

    tmpObj = cmd.get_unused_name("_tmp")
    cmd.create(tmpObj, "(" + selection + ") and polymer", zoom=0)

    cmd.set("dot_solvent", 1, tmpObj)
    cmd.get_area(selection=tmpObj, load_b=1)

    # threshold on what one considers an "exposed" atom (in A**2):
    cmd.remove(tmpObj + " and b < " + str(cutoff))

    selName = cmd.get_unused_name("exposed_atm_")
    cmd.select(selName, "(" + selection + ") in " + tmpObj)

    cmd.delete(tmpObj)

    if not quiet:
        print("Exposed atoms are selected in: " + selName)

    return selName
Esempio n. 27
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')
Esempio n. 28
0
def rx():
  """
  rhiju's favorite coloring of proteins, more details --
  no cartoon; heavy backbone
  """
  cmd.bg_color( "white" )
  AllObj=cmd.get_names("all")

  for x in AllObj:
    #print(AllObj[0],x)
    print x
    cmd.hide( "line", x )
    cmd.color( "white", x+" and elem C" )
    cmd.color( "blue", x+" and elem N" )
    cmd.color( "red", x+" and elem O" )
    cmd.color( "yellow", x+" and elem S" )
    cmd.spectrum( "resi", "rainbow", x+" and name CA+C" )
    #cmd.show( "sticks", x +" and not elem H and not name C+N+O" )

    cmd.select('backbone','name o+c+ca+n')
    cmd.show('sticks','not elem H')

    if not x.count( 'BACKBONE' ):
      cmd.create( x+"_BACKBONE", x+" and not element H and backbone" )


    cmd.set('stick_radius', '0.5', "*BACKBONE" )
Esempio n. 29
0
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()
Esempio n. 30
0
def process_molecule_sdf(mol, suspend_undo):
    global already_processed
    global undo_each_molecule
    nameorig = mol[0]
    name = nameorig.strip()
    if name in already_processed:
        return True
    already_processed = set(already_processed | set([name]))
    tmpname = "_temp_%s" % name
    molstr = string.join(mol,'')
    cmd.delete(tmpname)
    try:
        importing.read_sdfstr(molstr, tmpname,object_props='*')
        natoms = cmd.count_atoms(tmpname)
    except:
        return False
    if undo_each_molecule:
        cmd.push_undo( "( %s )" % name, just_coordinates=0)
        cmd.set("suspend_undo", 1, updates=0)
    cmd.remove(name)

    print "before cmd.create(): using copy_properties=True"
    cmd.create(name, tmpname, copy_properties=True)
    cmd.set_title(name, -1, "")

    cmd.delete(tmpname)
    if undo_each_molecule:
        cmd.set("suspend_undo", suspend_undo, updates=0)
        cmd.push_undo("", just_coordinates=0, finish_undo=1)
    return True
Esempio n. 31
0
###### PREAMBLE

import pymol
from pymol import cmd
import sys

structure = '4uad'

cmd.reinitialize()
cmd.set('bg_rgb', '[1,1,1]')  # white
cmd.set('antialias', '2')
cmd.set('ray_opaque_background', 'off')
cmd.set('depth_cue', 'off')

### Modify here
url = 'https://files.rcsb.org/download/4UAD.pdb'
cmd.load(url, 'orig')

cmd.select('importin', 'chain A')
cmd.select('origPB2', 'chain E')

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

cmd.hide('everything')
cmd.show('cartoon')
# cmd.show('surface')
for c in ['importin', 'S009']:
    cmd.show('surface', '{0}'.format(c))
# cmd.remove('origPB2')
cmd.color('wheat', 'importin')
Esempio n. 32
0
def trajectory():
    """
    optimization settings for trajectory visualization
    """
    # improves performance drastically when loading a lot of states
    cmd.set('defer_builds_mode', 3)
Esempio n. 33
0
 def load_traj(*args, **kwargs):
     cmd.set('defer_builds_mode', 3)
     cmd.sync()
     cmd.load_traj(*args, **kwargs)
Esempio n. 34
0
zip_dir = 'out.zip'
with zipfile.ZipFile(zip_dir) as hs_zip:
    hs_zip.extractall(dirpath)

cmd.load(join(dirpath, "protein.pdb"), "protein")
cmd.show("cartoon", "protein")

if dirpath:
    f = join(dirpath, "label_threshold_10.mol2")
else:
    f = "label_threshold_10.mol2"

cmd.load(f, 'label_threshold_10')
cmd.hide('everything', 'label_threshold_10')
cmd.label("label_threshold_10", "name")
cmd.set("label_font_id", 7)
cmd.set("label_size", -0.4)

if dirpath:
    f = join(dirpath, "label_threshold_14.mol2")
else:
    f = "label_threshold_14.mol2"

cmd.load(f, 'label_threshold_14')
cmd.hide('everything', 'label_threshold_14')
cmd.label("label_threshold_14", "name")
cmd.set("label_font_id", 7)
cmd.set("label_size", -0.4)

if dirpath:
    f = join(dirpath, "label_threshold_17.mol2")
Esempio n. 35
0
    def __init__(self, _self=cmd):
        Wizard.__init__(self, _self)
        cmd = self.cmd

        if self.cmd.get_movie_length() > 0:
            raise pymol.wizarding.WizardError(
                'Mutagenesis Wizard cannot be used with Movie')

        cmd.unpick()

        self.stored = pymol.Scratch_Storage()
        self.space = {'stored': self.stored}

        self.bump_scores = []
        self.dep = default_dep

        self.ind_library = io.pkl.fromFile(os.environ['PYMOL_DATA'] +
                                           "/chempy/sidechains/sc_bb_ind.pkl")
        self.load_library()
        self.status = 0  # 0 no selection, 1 mutagenizing
        self.bump_check = 1
        self.auto_center = 1
        self.error = None
        self.object_name = None
        self.modes = ['current']
        self.mode = default_mode
        self.rep = default_rep
        self.hyd = default_hyd
        self.n_cap = default_n_cap
        self.c_cap = default_c_cap
        residues = list(self.ind_library.keys())
        # could extent with additional fragments manually as below
        residues.extend(['GLY', 'ALA'])
        residues.extend(['HID', 'HIE', 'HIP'])
        residues.extend(['ARGN', 'LYSN', 'ASPH', 'GLUH'])
        residues.sort()
        res_copy = deepcopy(residues)
        for a in res_copy:
            residues.append('NT_' + a)
            residues.append('CT_' + a)
        self.modes.extend(residues)
        self.mode_label = {}
        for a in self.modes:
            self.mode_label[a] = "" + a
        self.mode_label['current'] = "No Mutant"

        self.selection_mode = cmd.get_setting_int("mouse_selection_mode")
        cmd.set("mouse_selection_mode", 1)

        smm = []
        smm.append([2, 'Mutant', ''])
        smm.append([1, 'No change', 'cmd.get_wizard().set_mode("current")'])
        #        smm.append([ 1, 'N-Term', [] ])
        #        smm.append([ 1, 'C-Term', [] ])
        smm.append([0, '', ''])
        for a in self.modes:
            if a == 'current':
                pass
            elif a[0:3] == 'NT_':
                pass
#                smm[2][2].append([ 1, self.mode_label[a[3:]], 'cmd.get_wizard().set_mode("'+a+'")'])
            elif a[0:3] == 'CT_':
                pass
#                smm[3][2].append([ 1, self.mode_label[a[3:]], 'cmd.get_wizard().set_mode("'+a+'")'])
            else:
                smm.append([
                    1, self.mode_label[a],
                    'cmd.get_wizard().set_mode("' + a + '")'
                ])

        # group arg, lys, his, glu, asp

        for lst in [smm]:  # [ smm, smm[2][2], smm[3][2] ]:
            for a in 'ARG', 'LYS', 'HID', 'GLU', 'ASP':
                ix = 0
                start = 0
                stop = 0
                for b in lst:
                    if start == 0:
                        if b[1][0:] == a:
                            start = ix
                            stop = ix + 1
                    elif b[1][0:3] == a[0:3] or (b[1][0:2] == a[0:2]
                                                 and a[0:2] == 'HI'):
                        stop = ix + 1
                    ix = ix + 1
                if start != 0 and stop != 0:
                    slice = lst[start:stop]
                    if a != 'HID':
                        slice2 = [slice[0]] + [[0, '', '']] + slice[1:]
                        lst[start:stop] = [[
                            1, self.mode_label[a] + "... ", slice2
                        ]]
                    else:
                        slice2 = [slice[3]] + [[0, '', '']] + slice[0:3]
                        lst[start:stop] = [[
                            1, self.mode_label['HIS'] + "... ", slice2
                        ]]

        self.menu['mode'] = smm

        self.reps = ['lines', 'sticks', 'spheres', 'dots']

        self.rep_name = {
            'lines': "Show Lines",
            'sticks': "Show Sticks",
            'spheres': "Show Spheres",
            'dots': "Show Dots",
        }

        self.dep_name = {
            'dep': "Backbone Depen. Rotamers",
            'ind': "Backbone Indep. Rotamers"
        }

        self.hyd_name = {
            'auto': "Hydrogens: Current",
            'keep': "Hydrogens: Add & Retain",
            #            'polar' : "Polar Hydrogens",
            'none': "Hydrogens: Remove",
        }
        self.hyds = ['auto', 'keep', 'none']

        self.n_cap_name = {
            'none': 'Open',
            'posi': 'NH3+',
            'acet': 'Acetyl',
        }
        self.n_caps = ['none', 'posi', 'acet']

        self.c_cap_name = {
            'none': 'Open',
            'nega': 'COO-',
            'amin': 'Amine',
            'nmet': 'N-methyl',
        }
        self.c_caps = ['none', 'nega', 'amin', 'nmet']

        smm = []
        smm.append([2, 'N-Cap', ''])
        for a in self.n_caps:
            smm.append([
                1, self.n_cap_name[a],
                'cmd.get_wizard().set_n_cap("' + a + '")'
            ])
        self.menu['n_cap'] = smm

        smm = []
        smm.append([2, 'C-Cap', ''])
        for a in self.c_caps:
            smm.append([
                1, self.c_cap_name[a],
                'cmd.get_wizard().set_c_cap("' + a + '")'
            ])
        self.menu['c_cap'] = smm

        smm = []
        smm.append([2, 'Hydrogens', ''])
        for a in self.hyds:
            smm.append(
                [1, self.hyd_name[a], 'cmd.get_wizard().set_hyd("' + a + '")'])
        self.menu['hyd'] = smm

        smm = []
        smm.append([2, 'Representation', ''])
        for a in self.reps:
            smm.append(
                [1, self.rep_name[a], 'cmd.get_wizard().set_rep("' + a + '")'])
        self.menu['rep'] = smm

        self.deps = ['dep', 'ind']
        smm = []
        smm.append([2, 'Rotamers', ''])
        for a in self.deps:
            smm.append(
                [1, self.dep_name[a], 'cmd.get_wizard().set_dep("' + a + '")'])
        self.menu['dep'] = smm

        if 'pk1' in cmd.get_names('selections'):
            cmd.select(src_sele, "(byres pk1)")
            cmd.unpick()
            cmd.enable(src_sele)
            self.status = 1
            self.error = None
            self.do_library()
            cmd.refresh_wizard()
Esempio n. 36
0
    def do_library(self):
        cmd = self.cmd
        pymol = cmd._pymol
        if not ((cmd.count_atoms("(%s) and name N" % src_sele) == 1) and
                (cmd.count_atoms("(%s) and name C" % src_sele) == 1) and
                (cmd.count_atoms("(%s) and name O" % src_sele) == 1)):
            self.clear()
            return 1
        cmd.feedback("push")
        cmd.feedback("disable", "selector", "everythin")
        cmd.feedback("disable", "editor", "actions")
        self.prompt = ['Loading rotamers...']
        self.bump_scores = []
        state_best = 0

        pymol.stored.name = 'residue'
        cmd.iterate("first (%s)" % src_sele,
                    'stored.name=model+"/"+segi+"/"+chain+"/"+resn+"`"+resi')
        self.res_text = pymol.stored.name
        cmd.select("_seeker_hilight", src_sele)

        auto_zoom = cmd.get_setting_text('auto_zoom')
        cmd.set('auto_zoom', "0", quiet=1)
        cmd.frame(0)
        cmd.delete(frag_name)
        if self.auto_center:
            cmd.center(src_sele, animate=-1)

        self.lib_mode = self.mode
        if self.lib_mode == "current":
            pymol.stored.resn = ""
            cmd.iterate("(%s & name CA)" % src_sele, "stored.resn=resn")
            rot_type = _rot_type_xref.get(pymol.stored.resn, pymol.stored.resn)
            if (self.c_cap != 'none') or (self.n_cap != 'none') or (self.hyd !=
                                                                    'auto'):
                self.lib_mode = rot_type  # force fragment-based load
            else:
                cmd.create(frag_name, src_sele, 1, 1)
                if self.c_cap == 'open':
                    cmd.remove("%s and name OXT" % frag_name)

        if self.lib_mode != 'current':
            rot_type = self.lib_mode
            frag_type = self.lib_mode
            if (self.n_cap == 'posi') and (frag_type[0:3] != 'NT_'):
                if not (cmd.count_atoms(
                        "elem C & !(%s) & (bto. (name N & (%s))) &! resn ACE" %
                    (src_sele, src_sele))):
                    # use N-terminal fragment
                    frag_type = "NT_" + frag_type
            if (self.c_cap == 'nega') and (frag_type[0:3] != 'CT_'):
                if not (cmd.count_atoms(
                        "elem N & !(%s) & (bto. (name C & (%s))) & !resn NME+NHH"
                        % (src_sele, src_sele))):
                    # use C-terminal fragment
                    frag_type = "CT_" + frag_type
            if rot_type[0:3] in ['NT_', 'CT_']:
                rot_type = rot_type[3:]
            rot_type = _rot_type_xref.get(rot_type, rot_type)
            cmd.fragment(frag_type.lower(), frag_name, origin=0)
            # trim off hydrogens
            if (self.hyd == 'none'):
                cmd.remove("(" + frag_name + " and hydro)")
            elif (self.hyd == 'auto'):
                if cmd.count_atoms("(" + src_sele + ") and hydro") == 0:
                    cmd.remove("(" + frag_name + " and hydro)")
            # copy identifying information
            cmd.alter("?%s & name CA" % src_sele,
                      "stored.identifiers = (segi, chain, resi, ss, color)",
                      space=self.space)
            cmd.alter("?%s" % frag_name,
                      "(segi, chain, resi, ss) = stored.identifiers[:4]",
                      space=self.space)
            # move the fragment
            if ((cmd.count_atoms("(%s & name CB)" % frag_name) == 1)
                    and (cmd.count_atoms("(%s & name CB)" % src_sele) == 1)):
                cmd.pair_fit(
                    "(%s & name CA)" % frag_name, "(%s & name CA)" % src_sele,
                    "(%s & name CB)" % frag_name, "(%s & name CB)" % src_sele,
                    "(%s & name C)" % frag_name, "(%s & name C)" % src_sele,
                    "(%s & name N)" % frag_name, "(%s & name N)" % src_sele)
            else:
                cmd.pair_fit("(%s & name CA)" % frag_name,
                             "(%s & name CA)" % src_sele,
                             "(%s & name C)" % frag_name,
                             "(%s & name C)" % src_sele,
                             "(%s & name N)" % frag_name,
                             "(%s & name N)" % src_sele)

            # fix the carbonyl position...
            cmd.iterate_state(1, "(%s & name O)" % src_sele,
                              "stored.list=[x,y,z]")
            cmd.alter_state(1, "(%s & name O)" % frag_name,
                            "(x,y,z)=stored.list")
            if cmd.count_atoms("(%s & name OXT)" % src_sele):
                cmd.iterate_state(1, "(%s & name OXT)" % src_sele,
                                  "stored.list=[x,y,z]")
                cmd.alter_state(1, "(%s & name OXT)" % frag_name,
                                "(x,y,z)=stored.list")
            elif cmd.count_atoms("(%s & name OXT)" %
                                 frag_name):  # place OXT if no template exists
                angle = cmd.get_dihedral("(%s & name N)" % frag_name,
                                         "(%s & name CA)" % frag_name,
                                         "(%s & name C)" % frag_name,
                                         "(%s & name O)" % frag_name)
                cmd.protect("(%s & name O)" % frag_name)
                cmd.set_dihedral("(%s & name N)" % frag_name,
                                 "(%s & name CA)" % frag_name,
                                 "(%s & name C)" % frag_name,
                                 "(%s & name OXT)" % frag_name, 180.0 + angle)
                cmd.deprotect(frag_name)

            # fix the hydrogen position (if any)
            if cmd.count_atoms("(hydro and bound_to (name N & (%s)))" %
                               frag_name) == 1:
                if cmd.count_atoms("(hydro and bound_to (name N & (%s)))" %
                                   src_sele) == 1:
                    cmd.iterate_state(
                        1, "(hydro and bound_to (name N & (%s)))" % src_sele,
                        "stored.list=[x,y,z]")
                    cmd.alter_state(
                        1, "(hydro and bound_to (name N & (%s)))" % frag_name,
                        "(x,y,z)=stored.list")
                elif cmd.select(
                        tmp_sele1,
                        "(name C & bound_to (%s and elem N))" % src_sele) == 1:
                    # position hydro based on location of the carbonyl
                    angle = cmd.get_dihedral("(%s & name C)" % frag_name,
                                             "(%s & name CA)" % frag_name,
                                             "(%s & name N)" % frag_name,
                                             tmp_sele1)
                    cmd.set_dihedral("(%s & name C)" % frag_name,
                                     "(%s & name CA)" % frag_name,
                                     "(%s & name N)" % frag_name,
                                     "(%s & name H)" % frag_name,
                                     180.0 + angle)
                    cmd.delete(tmp_sele1)

            # add c-cap (if appropriate)
            if self.c_cap in ['amin', 'nmet']:
                if not cmd.count_atoms(
                        "elem N & !(%s) & (bto. (name C & (%s))) & !resn NME+NHH"
                        % (src_sele, src_sele)):
                    if cmd.count_atoms("name C & (%s)" % (frag_name)) == 1:
                        if self.c_cap == 'amin':
                            editor.attach_amino_acid("name C & (%s)" %
                                                     (frag_name),
                                                     'nhh',
                                                     _self=cmd)
                        elif self.c_cap == 'nmet':
                            editor.attach_amino_acid("name C & (%s)" %
                                                     (frag_name),
                                                     'nme',
                                                     _self=cmd)
                        if cmd.count_atoms(
                                "hydro & bound_to (name N & bound_to (name C & (%s)))"
                                % frag_name):
                            cmd.h_fix("name N & bound_to (name C & (%s))" %
                                      frag_name)
                        # trim hydrogens
                        if (self.hyd == 'none'):
                            cmd.remove("(" + frag_name + " and hydro)")
                        elif (self.hyd == 'auto'):
                            if cmd.count_atoms("(" + src_sele +
                                               ") and hydro") == 0:
                                cmd.remove("(" + frag_name + " and hydro)")

            # add n-cap (if appropriate)
            if self.n_cap in ['acet']:
                if not cmd.count_atoms(
                        "elem C & !(%s) & (bto. (name N & (%s))) & !resn ACE "
                        % (src_sele, src_sele)):
                    if cmd.count_atoms("name N & (%s)" % (frag_name)) == 1:
                        if self.n_cap == 'acet':
                            editor.attach_amino_acid("name N & (%s)" %
                                                     (frag_name),
                                                     'ace',
                                                     _self=cmd)
                        if cmd.count_atoms(
                                "hydro & bound_to (name N & bound_to (name C & (%s)))"
                                % frag_name):
                            cmd.h_fix("name N & (%s)" % frag_name)
                        # trim hydrogens
                        if (self.hyd == 'none'):
                            cmd.remove("(" + frag_name + " and hydro)")
                        elif (self.hyd == 'auto'):
                            if cmd.count_atoms("(" + src_sele +
                                               ") and hydro") == 0:
                                cmd.remove("(" + frag_name + " and hydro)")

        cartoon = (cmd.count_atoms("(%s & name CA & rep cartoon)" % src_sele) >
                   0)
        sticks = (cmd.count_atoms("(%s & name CA & rep sticks)" % src_sele) >
                  0)

        cmd.delete(obj_name)
        key = rot_type
        lib = None
        if self.dep == 'dep':
            try:
                result = cmd.phi_psi("%s" % src_sele)
                if len(result) == 1:
                    (phi, psi) = list(result.values())[0]
                    (phi, psi) = (int(10 * round(phi / 10)),
                                  int(10 * (round(psi / 10))))
                    key = (rot_type, phi, psi)
                    if key not in self.dep_library:
                        (phi, psi) = (int(20 * round(phi / 20)),
                                      int(20 * (round(psi / 20))))
                        key = (rot_type, phi, psi)
                        if key not in self.dep_library:
                            (phi, psi) = (int(60 * round(phi / 60)),
                                          int(60 * (round(psi / 60))))
                            key = (rot_type, phi, psi)
                    lib = self.dep_library.get(key, None)
            except:
                pass
        if lib is None:
            key = rot_type
            lib = self.ind_library.get(key, None)
            if (lib is not None) and self.dep == 'dep':
                print(
                    ' Mutagenesis: no phi/psi, using backbone-independent rotamers.'
                )
        if lib is not None:
            state = 1
            for a in lib:
                cmd.create(obj_name, frag_name, 1, state)
                if state == 1:
                    cmd.select(mut_sele,
                               "(byres (%s like %s))" % (obj_name, src_sele))
                if rot_type == 'PRO':
                    cmd.unbond("(%s & name N)" % mut_sele,
                               "(%s & name CD)" % mut_sele)
                for b in a.keys():
                    if b != 'FREQ':
                        cmd.set_dihedral("(%s & n;%s)" % (mut_sele, b[0]),
                                         "(%s & n;%s)" % (mut_sele, b[1]),
                                         "(%s & n;%s)" % (mut_sele, b[2]),
                                         "(%s & n;%s)" % (mut_sele, b[3]),
                                         a[b],
                                         state=state)
                    else:
                        cmd.set_title(obj_name, state,
                                      "%1.1f%%" % (a[b] * 100))
                if rot_type == 'PRO':
                    cmd.bond("(%s & name N)" % mut_sele,
                             "(%s & name CD)" % mut_sele)
                state = state + 1
            cmd.delete(frag_name)
            print(" Mutagenesis: %d rotamers loaded." % len(lib))
            if self.bump_check:
                cmd.delete(bump_name)
                cmd.create(
                    bump_name,
                    "(((byobj %s) within 6 of (%s and not name N+C+CA+O+H+HA)) and (not (%s)))|(%s)"
                    % (src_sele, mut_sele, src_sele, mut_sele),
                    singletons=1)
                cmd.color("gray50", bump_name + " and elem C")
                cmd.set("seq_view", 0, bump_name, quiet=1)
                cmd.hide("everything", bump_name)
                if ((cmd.select(
                        tmp_sele1, "(name N & (%s in (neighbor %s)))" %
                    (bump_name, src_sele)) == 1) and (cmd.select(
                        tmp_sele2, "(name C & (%s in %s))" %
                        (bump_name, mut_sele)) == 1)):
                    cmd.bond(tmp_sele1, tmp_sele2)
                if ((cmd.select(
                        tmp_sele1, "(name C & (%s in (neighbor %s)))" %
                    (bump_name, src_sele)) == 1) and (cmd.select(
                        tmp_sele2, "(name N & (%s in %s))" %
                        (bump_name, mut_sele)) == 1)):
                    cmd.bond(tmp_sele1, tmp_sele2)
                cmd.delete(tmp_sele1)
                cmd.delete(tmp_sele2)

                cmd.protect(
                    "%s and not (%s in (%s and not name N+C+CA+O+H+HA))" %
                    (bump_name, bump_name, mut_sele))
                cmd.sculpt_activate(bump_name)
                cmd.show("cgo", bump_name)
                # draw the bumps
                cmd.set("sculpt_vdw_vis_mode", 1, bump_name)
                state = 1
                score_best = 1e6
                for a in lib:
                    score = cmd.sculpt_iterate(bump_name, state, 1)
                    self.bump_scores.append(score)
                    if score < score_best:
                        state_best = state
                        score_best = score
                    state = state + 1
            cmd.delete(mut_sele)
        else:
            cmd.create(obj_name, frag_name, 1, 1)
            print(" Mutagenesis: no rotamers found in library.")
        cmd.set("seq_view", 0, obj_name, quiet=1)
        pymol.util.cbaw(obj_name, _self=cmd)
        cmd.hide("(" + obj_name + ")")
        cmd.show(self.rep, obj_name)
        cmd.show('lines', obj_name)  #neighbor  always show lines
        if cartoon:
            cmd.show("cartoon", obj_name)
        if sticks:
            cmd.show("sticks", obj_name)
        cmd.set('auto_zoom', auto_zoom, quiet=1)
        cmd.delete(frag_name)
        cmd.frame(state_best)

        # this might be redundant if frame(state_best) changed the state
        self.do_state(state_best)

        cmd.unpick()
        cmd.feedback("pop")
Esempio n. 37
0
    def apply(self):
        cmd = self.cmd
        if self.status == 1:
            # find the name of the object which contains the selection
            src_frame = cmd.get_state()
            try:
                new_name = cmd.get_object_list(src_sele)[0]
            except IndexError:
                print(" Mutagenesis: object not found.")
                return

            if True:
                auto_zoom = cmd.get_setting_text('auto_zoom')
                cmd.set('auto_zoom', "0", quiet=1)
                if self.lib_mode != "current":
                    # create copy with mutant in correct frame
                    state = cmd.get_object_state(new_name)
                    cmd.create(tmp_obj2, obj_name, src_frame, state)
                    cmd.set_title(tmp_obj2, state, '')
                    cmd.color(self.stored.identifiers[4],
                              "?%s & elem C" % tmp_obj2)
                    cmd.alter(tmp_obj2, 'ID = -1')

                    # select backbone connection atoms
                    cmd.select(tmp_sele1, 'neighbor ?%s' % (src_sele), 0)

                    # remove residue and neighboring c-cap/n-cap (if any)
                    cmd.remove("?%s | byres (?%s & "
                               "(name N & resn NME+NHH | name C & resn ACE))" %
                               (src_sele, tmp_sele1))

                    # create the merged molecule
                    cmd.create(new_name, "?%s | ?%s" % (new_name, tmp_obj2),
                               state, state)

                    # now connect them
                    cmd.select(
                        tmp_sele2, '/%s/%s/%s/%s' %
                        ((new_name, ) + self.stored.identifiers[:3]))
                    cmd.bond('?%s & name C' % (tmp_sele1),
                             '?%s & name N' % (tmp_sele2),
                             quiet=1)
                    cmd.bond('?%s & name N' % (tmp_sele1),
                             '?%s & name C' % (tmp_sele2),
                             quiet=1)
                    cmd.set_geometry('(?%s | ?%s) & name C+N' %
                                     (tmp_sele1, tmp_sele2), 3,
                                     3)  # make amide planer

                    # fix N-H hydrogen position (if any exists)
                    cmd.h_fix('?%s & name N' % (tmp_sele2))

                    # delete temporary objects/selections
                    cmd.delete(tmp_sele1)
                    cmd.delete(tmp_sele2)
                    cmd.delete(tmp_obj2)
                    self.clear()
                    # and return to frame 1
                    cmd.frame(1)
                    cmd.refresh_wizard()
                else:
                    # create copy with conformation in correct state
                    cmd.create(tmp_obj2, obj_name, src_frame, 1)

                    # remove existing c-cap in copy (if any)
                    cmd.remove(
                        "byres (name N and (%s in (neighbor %s)) and resn NME+NHH)"
                        % (new_name, src_sele))
                    cmd.remove("(%s) and name OXT" % src_sele)

                    # remove existing n-cap in copy (if any)
                    cmd.remove(
                        "byres (name C and (%s in (neighbor %s)) and resn ACE)"
                        % (new_name, src_sele))

                    # save existing conformation on undo stack
                    #               cmd.edit("((%s in %s) and name ca)"%(new_name,src_sele))
                    cmd.push_undo("(" + src_sele + ")")
                    # modify the conformation
                    cmd.update(new_name, tmp_obj2)
                    #               cmd.unpick()
                    cmd.delete(tmp_obj2)
                    self.clear()
                    # and return to frame 1
                    cmd.frame(1)
                    cmd.refresh_wizard()
                cmd.set('auto_zoom', auto_zoom, quiet=1)
Esempio n. 38
0
    def runDSSPOneObj(self, one_obj_sel):
        """ Run DSSP on only one object.
        
            @param one_obj_sel: the selection/object involving only one object
            @param type: string
        """
        SSE_res = {
            'H': {},
            'G': {},
            'I': {},
            'E': {},
            'B': {},
            'T': {},
            'S': {},
            '-': {}
        }
        SSE_sel = {
            'H': None,
            'G': None,
            'I': None,
            'E': None,
            'B': None,
            'T': None,
            'S': None,
            '-': None
        }

        pdb_fn = None
        pdb_os_fh, pdb_fn = tempfile.mkstemp(
            suffix='.pdb')  # file os handle, file name
        os.close(pdb_os_fh)
        # DSSP 2.0.4 ignores all residues after 1st TER in the same chain
        v = cmd.get(name='pdb_use_ter_records')
        if v:
            cmd.set(name='pdb_use_ter_records',
                    value=0)  # do not insert TER into the pdb
        cmd.save(filename=pdb_fn, selection=one_obj_sel)
        if v: cmd.set(name='pdb_use_ter_records', value=v)  # restore old value

        if VERBOSE:
            print 'Selection %s saved to %s.' % (one_obj_sel, pdb_fn)

        if pdb_fn is None:
            print 'WARNING: DSSP has no pdb file to work on!'
            return None

        print 'Running DSSP for %s ...' % (one_obj_sel, )
        dssp_sse_dict = {}
        if sys.version_info >= (2, 4):
            dssp_proc = subprocess.Popen([self.dssp_bin.get(), pdb_fn],
                                         stdout=subprocess.PIPE,
                                         stderr=subprocess.STDOUT)
            dssp_stdout, dssp_stderr = dssp_proc.communicate()
        else:  # use os.system + tempfile
            dssp_tmpout_os_fh, dssp_tmpout_fn = tempfile.mkstemp(
                suffix='.dssp')
            os.close(dssp_tmpout_os_fh)
            dssp_cmd = '%s %s > %s' % (self.dssp_bin.get(), pdb_fn,
                                       dssp_tmpout_fn)
            os.system(dssp_cmd)
            fh = open(dssp_tmpout_fn)
            dssp_stdout = ''.join(fh.readlines())
            fh.close()

        sse_started = False
        for line in dssp_stdout.splitlines():
            if line.startswith('  #  RESIDUE'):
                sse_started = True
                continue
            elif line.startswith(' !!!'):
                sse_started = False
                continue
            elif sse_started:
                if len(line) < 10 or line[9] == ' ': continue
                ch, resname = line[11], line[13]
                residen, sscode = line[5:11].strip(), line[
                    16]  # residen = resnum+icode, col 10 is for icode
                if sscode == ' ': sscode = '-'
                k = (ch, resname, residen)
                dssp_sse_dict[k] = sscode

        self.dssp_rlt_dict[one_obj_sel] = dssp_sse_dict
        print 'Got SSE for %d residues.' % (len(
            self.dssp_rlt_dict[one_obj_sel]), )

        # group residues according to their SSE, and chain name
        for k in self.dssp_rlt_dict[one_obj_sel].keys():
            #res = '/%s//%s/%d%s/' % (sel,k[0],k[1][1], k[1][2].strip()) # sel name, chain ID, res serial num, icode
            sse = self.dssp_rlt_dict[one_obj_sel][k]
            chn = k[0]
            res = k[2]
            if VERBOSE:
                print '(%s) and \"%s\"/%s/  sse=%s' % (str(one_obj_sel),
                                                       chn.strip(), res, sse)
            SSE_res[sse].setdefault(chn, []).append(res)

        self.SSE_res_dict[one_obj_sel] = SSE_res

        for sse in self.DSSP_SSE_list:
            sse_sel_name = self.selectSSE(one_obj_sel, sse)
            SSE_sel[sse] = sse_sel_name

        self.SSE_sel_dict[one_obj_sel] = SSE_sel

        print '\nNumber of residues with SSE element:'
        for sse in self.DSSP_SSE_list:
            num = sum([len(SSE_res[sse][chn]) for chn in SSE_res[sse]])
            print '%20s (%s) : %5d' % (self.SSE_name[sse], sse, num)
        print

        # clean up pdb_fn and dssp_tmpout_fn created by tempfile.mkstemp()
        if os.path.isfile(pdb_fn):
            os.remove(pdb_fn)
        if sys.version_info < (2, 4) and os.path.isfile(dssp_tmpout_fn):
            os.remove(dssp_tmpout_fn)

        return
Esempio n. 39
0
cmd.do("color green, loop_3")
cmd.do("sele loop_5, resi 177-188")
cmd.do("color forest, loop_5")
cmd.do("sele loop_6, resi 217-234")
cmd.do("color yellow, loop_6")
cmd.do("sele loop_7, resi 259-267")
cmd.do("color red, loop_7")
cmd.deselect()
# Show as Connolly surface (probe radius = 1.4 A = H20)
# Note: probe radius can be changed by:
# cmd.set("solvent_radius", <new radius in Angstrom>)
# http://www.pymolwiki.org/index.php/Surface
cmd.show("surface")
# Crank up the ambient lighting to get rid of shading effects
# http://pymol.org/dokuwiki/doku.php?id=setting:light
cmd.set("ambient", 3.0)
# Turn off specular highlights
cmd.set("specular", "off")
# Set direct light intensity to 0
cmd.set("direct", 0.0)
# Set number of camera lights to 0
cmd.set("light_count", 1)
# Turn off depth cue "fog" effect
cmd.set("depth_cue", 0)
# Set to orthographic rendering mode
cmd.set("orthoscopic", "on")
# Assume beta-barrel is oriented along z-axis
# with top of barrel at +z. We want to orient the
# camera so that is below the barrel looking toward
# +z axis (looking from bottom to top). This was
# done using the following:
Esempio n. 40
0
import tempfile
import zipfile
from pymol import cmd
from pymol.cgo import *

dirpath = None

dirpath = tempfile.mkdtemp()
zip_dir = 'out.zip'
with zipfile.ZipFile(zip_dir) as hs_zip:
    hs_zip.extractall(dirpath)

cmd.load(join(dirpath, "protein.pdb"), "protein")
cmd.show("cartoon", "protein")

cmd.set("surface_cavity_mode", 1)
cmd.show("surface", "protein")
cmd.set("surface_trim_factor", 13)
cmd.set('transparency', 0.5, "protein")

if dirpath:
    f = join(dirpath, "label_threshold_10.mol2")
else:
    f = "label_threshold_10.mol2"

cmd.load(f, 'label_threshold_10')
cmd.hide('everything', 'label_threshold_10')
cmd.label("label_threshold_10", "name")
cmd.set("label_font_id", 7)
cmd.set("label_size", -0.4)
zip_dir = 'out.zip'
with zipfile.ZipFile(zip_dir) as hs_zip:
    hs_zip.extractall(dirpath)

cmd.load(join(dirpath, "protein.pdb"), "protein")
cmd.show("cartoon", "protein")

if dirpath:
    f = join(dirpath, "label_threshold_10.mol2")
else:
    f = "label_threshold_10.mol2"

cmd.load(f, 'label_threshold_10')
cmd.hide('everything', 'label_threshold_10')
cmd.label("label_threshold_10", "name")
cmd.set("label_font_id", 7)
cmd.set("label_size", -0.4)

if dirpath:
    f = join(dirpath, "label_threshold_14.mol2")
else:
    f = "label_threshold_14.mol2"

cmd.load(f, 'label_threshold_14')
cmd.hide('everything', 'label_threshold_14')
cmd.label("label_threshold_14", "name")
cmd.set("label_font_id", 7)
cmd.set("label_size", -0.4)

if dirpath:
    f = join(dirpath, "label_threshold_17.mol2")
Esempio n. 42
0
def color_by_mutation(obj1, obj2, waters=0, labels=0):
    '''
    DESCRIPTION
    
        Creates an alignment of two proteins and superimposes them. 
        Aligned residues that are different in the two (i.e. mutations) are highlighted and 
        colored according to their difference in the BLOSUM90 matrix. 
        Is meant to be used for similar proteins, e.g. close homologs or point mutants, 
        to visualize their differences.      
    
    USAGE
    
        color_by_mutation selection1, selection2 [,waters [,labels ]]
        
    ARGUMENTS
    
        obj1: object or selection
        
        obj2: object or selection    
        
        waters: bool (0 or 1). If 1, waters are included in the view, colored
                differently for the both input structures.
                default = 0

        labels: bool (0 or 1). If 1, the possibly mutated sidechains are 
                labeled by their chain, name and id
                default = 0
        
    EXAMPLE
        
        color_by_mutation protein1, protein2
        
    SEE ALSO

        super
    '''
    from pymol import stored, CmdException

    if cmd.count_atoms(obj1) == 0:
        print '%s is empty'%obj1
        return
    if cmd.count_atoms(obj2) == 0:
        print '%s is empty'%obj2
        return
    waters = int(waters)
    labels = int(labels)
    
    # align the two proteins
    aln = '__aln'
    
    # first, an alignment with 0 cycles (no atoms are rejected, which maximized the number of aligned residues)
    # for some mutations in the same protein this works fine). This is essentially done to get a
    # sequence alignment
    cmd.super(obj1, obj2, object=aln, cycles=0)
    
    # superimpose the the object using the default parameters to get a slightly better superimposition,
    # i.e. get the best structural alignment    
    cmd.super(obj1, obj2)

    stored.resn1, stored.resn2 = [], []
    stored.resi1, stored.resi2 = [], []
    stored.chain1, stored.chain2 = [], []
    
    # store residue ids, residue names and chains of aligned residues
    cmd.iterate(obj1 + ' and name CA and ' + aln, 'stored.resn1.append(resn)')
    cmd.iterate(obj2 + ' and name CA and ' + aln, 'stored.resn2.append(resn)')

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

    cmd.iterate(obj1 + ' and name CA and ' + aln, 'stored.chain1.append(chain)')
    cmd.iterate(obj2 + ' and name CA and ' + aln, 'stored.chain2.append(chain)')
    
    
    mutant_selection = '' 
    non_mutant_selection = 'none or '
    colors = []

    # loop over the aligned residues
    for n1, n2, i1, i2, c1, c2 in zip(stored.resn1, stored.resn2,
                                      stored.resi1, stored.resi2,
                                      stored.chain1, stored.chain2):
        # take care of 'empty' chain names
        if c1 == '':
            c1 = '""'
        if c2 == '':
            c2 = '""'
        if n1 == n2:
            non_mutant_selection += '((%s and resi %s and chain %s) or (%s and resi %s and chain %s)) or '%(obj1, i1, c1, obj2, i2, c2 )            
        else:
            mutant_selection += '((%s and resi %s and chain %s) or (%s and resi %s and chain %s)) or '%(obj1, i1, c1, obj2, i2, c2 )
            # get the similarity (according to the blosum matrix) of the two residues and
            c = getBlosum90ColorName(n1, n2)
            colors.append((c, '%s and resi %s and chain %s and elem C'%(obj2, i2, c2)))

    if mutant_selection == '':
        print ' Error: No mutations found'
        raise CmdException

    # create selections        
    cmd.select('mutations', mutant_selection[:-4])
    cmd.select('non_mutations', non_mutant_selection[:-4])
    cmd.select('not_aligned', '(%s or %s) and not mutations and not non_mutations'%(obj1, obj2))
    
    # create the view and coloring
    cmd.hide('everything', '%s or %s'%(obj1, obj2))
    cmd.show('cartoon', '%s or %s'%(obj1, obj2))
    cmd.show('lines', '(%s or %s) and ((non_mutations or not_aligned) and not name c+o+n)'%(obj1, obj2))
    cmd.show('sticks', '(%s or %s) and mutations and not name c+o+n'%(obj1, obj2))
    cmd.color('gray', 'elem C and not_aligned')
    cmd.color('white', 'elem C and non_mutations')
    cmd.color('blue', 'elem C and mutations and %s'%obj1)
    for (col, sel) in colors:
        cmd.color(col, sel)

    cmd.hide('everything', '(hydro) and (%s or %s)'%(obj1, obj2))        
    cmd.center('%s or %s'%(obj1, obj2))
    if labels:
        cmd.label('mutations and name CA','"(%s-%s-%s)"%(chain, resi, resn)')    
    if waters:
        cmd.set('sphere_scale', '0.1')
        cmd.show('spheres', 'resn HOH and (%s or %s)'%(obj1, obj2))
        cmd.color('red', 'resn HOH and %s'%obj1)
        cmd.color('salmon', 'resn HOH and %s'%obj2)
    print '''
             Mutations are highlighted in blue and red.
             All mutated sidechains of %s are colored blue, the corresponding ones from %s are
             colored on a spectrum from blue to red according to how similar the two amino acids are
             (as measured by the BLOSUM90 substitution matrix).
             Aligned regions without mutations are colored white.
             Regions not used for the alignment are gray.
             NOTE: There could be mutations in the gray regions that were not detected.'''%(obj1, obj2)
    cmd.delete(aln)
    cmd.deselect()
Esempio n. 43
0
from pymol.cgo import *
from pymol import cmd

cmd.set("cartoon_fancy_helices", 1)
cmd.set("cartoon_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("input_pdb.pdb")
cmd.set_view (\
  '''0.237595469,   -0.169580087,    0.956439614,\
     0.387604266,   -0.886297047,   -0.253433615,\
     0.890669584,    0.430938631,   -0.144854113,\
    -0.000374220,    0.000006055, -100.353157043,\
    31.699275970,   32.316436768,   33.389636993,\
    61.715843201,  138.970840454,  -20.000000000''')
cmd.png("quickstart_1.png", width=400, height=300, dpi=100, ray=1)

cmd.quit()
Esempio n. 44
0
 def test(self, normalize, ref):
     cmd.set('volume_data_range', 0)
     cmd.set('normalize_ccp4_maps', normalize)
     cmd.load(self.datafile('emd_1155.ccp4'), 'map')
     mmms = cmd.get_volume_histogram('map', 0)
     self.assertArrayEqual(mmms, ref, delta=0.05)
Esempio n. 45
0
def elbow_angle(obj, light='L', heavy='H', limit_l=107, limit_h=113, draw=0):
    """

DESCRIPTION

    Calculates the integer elbow angle of an antibody Fab complex and
    optionally draws a graphical representation of the vectors used to
    determine the angle.

ARGUMENTS

    obj = string: object

    light/heavy = strings: chain ID of light and heavy chains, respectively

    limit_l/limit_h = integers: residue numbers of the last residue in the
    light and heavy chain variable domains, respectively

    draw = boolean: Choose whether or not to draw the angle visualization

REQUIRES: com.py, transformations.py, numpy (see above)


    """

    # store current view
    orig_view = cmd.get_view()

    limit_l = int(limit_l)
    limit_h = int(limit_h)
    draw = int(draw)

    # for temp object names
    tmp_prefix = "tmp_elbow_"

    prefix = tmp_prefix + obj + '_'

    # names
    vl = prefix + 'VL'
    vh = prefix + 'VH'
    cl = prefix + 'CL'
    ch = prefix + 'CH'

    # selections
    vl_sel = 'polymer and %s and chain %s and resi 1-%i' % (obj, light, limit_l)
    vh_sel = 'polymer and %s and chain %s and resi 1-%i' % (obj, heavy, limit_h)
    cl_sel = 'polymer and %s and chain %s and not resi 1-%i' % (obj, light, limit_l)
    ch_sel = 'polymer and %s and chain %s and not resi 1-%i' % (obj, heavy, limit_h)
    v_sel = '((' + vl_sel + ') or (' + vh_sel + '))'
    c_sel = '((' + cl_sel + ') or (' + ch_sel + '))'

    # create temp objects
    cmd.create(vl, vl_sel)
    cmd.create(vh, vh_sel)
    cmd.create(cl, cl_sel)
    cmd.create(ch, ch_sel)

    # superimpose vl onto vh, calculate axis and angle
    Rv = calc_super_matrix(vl, vh)
    angle_v, direction_v, point_v = transformations.rotation_from_matrix(Rv)

    # superimpose cl onto ch, calculate axis and angle
    Rc = calc_super_matrix(cl, ch)
    angle_c, direction_c, point_c = transformations.rotation_from_matrix(Rc)

    # delete temporary objects
    cmd.delete(vl)
    cmd.delete(vh)
    cmd.delete(cl)
    cmd.delete(ch)

    # if dot product is positive, angle is acute
    if (numpy.dot(direction_v, direction_c) > 0):
        direction_c = direction_c * -1   # ensure angle is > 90 (need to standardize this)

        # TODO: make both directions point away from the elbow axis.

    elbow = int(numpy.degrees(numpy.arccos(numpy.dot(direction_v, direction_c))))
    # while (elbow < 90):
    # elbow = 180 - elbow   # limit to physically reasonable range

    # compare the direction_v and direction_c axes to the vector defined by
    # the C-alpha atoms of limit_l and limit_h of the original fab
    hinge_l_sel = "%s//%s/%s/CA" % (obj, light, limit_l)
    hinge_h_sel = "%s//%s/%s/CA" % (obj, heavy, limit_h)
    hinge_l = cmd.get_atom_coords(hinge_l_sel)
    hinge_h = cmd.get_atom_coords(hinge_h_sel)
    hinge_vec = numpy.array(hinge_h) - numpy.array(hinge_l)

    test = numpy.dot(hinge_vec, numpy.cross(direction_v, direction_c))
    if (test > 0):
        elbow = 360 - elbow

    print("    Elbow angle: %i degrees" % elbow)

    if (draw == 1):
        # there is probably a more elegant way to do this, but
        # it works so I'm not going to mess with it for now

        pre = obj + '_elbow_'

        # draw hinge vector
        cmd.pseudoatom(pre + "hinge_l", pos=hinge_l)
        cmd.pseudoatom(pre + "hinge_h", pos=hinge_h)
        cmd.distance(pre + "hinge_vec", pre + "hinge_l", pre + "hinge_h")
        cmd.set("dash_gap", 0)

        # draw the variable domain axis
        com_v = COM(v_sel)
        start_v = [a - 10 * b for a, b in zip(com_v, direction_v)]
        end_v = [a + 10 * b for a, b in zip(com_v, direction_v)]
        cmd.pseudoatom(pre + "start_v", pos=start_v)
        cmd.pseudoatom(pre + "end_v", pos=end_v)
        cmd.distance(pre + "v_vec", pre + "start_v", pre + "end_v")

        # draw the constant domain axis
        com_c = COM(c_sel)
        start_c = [a - 10 * b for a, b in zip(com_c, direction_c)]
        end_c = [a + 10 * b for a, b in zip(com_c, direction_c)]
        cmd.pseudoatom(pre + "start_c", pos=start_c)
        cmd.pseudoatom(pre + "end_c", pos=end_c)
        cmd.distance(pre + "c_vec", pre + "start_c", pre + "end_c")

        # customize appearance
        cmd.hide("labels", pre + "hinge_vec")
        cmd.hide("labels", pre + "v_vec")
        cmd.hide("labels", pre + "c_vec")
        cmd.color("green", pre + "hinge_l")
        cmd.color("red", pre + "hinge_h")
        cmd.color("black", pre + "hinge_vec")
        cmd.color("black", pre + "start_v")
        cmd.color("black", pre + "end_v")
        cmd.color("black", pre + "v_vec")
        cmd.color("black", pre + "start_c")
        cmd.color("black", pre + "end_c")
        cmd.color("black", pre + "c_vec")
        # draw spheres
        cmd.show("spheres", pre + "hinge_l or " + pre + "hinge_h")
        cmd.show("spheres", pre + "start_v or " + pre + "start_c")
        cmd.show("spheres", pre + "end_v or " + pre + "end_c")
        cmd.set("sphere_scale", 2)
        cmd.set("dash_gap", 0, pre + "hinge_vec")
        cmd.set("dash_width", 5)
        cmd.set("dash_radius", 0.3)

        # group drawing objects
        cmd.group(pre, pre + "*")

    # restore original view
    cmd.set_view(orig_view)

    return 0
Esempio n. 46
0
 def test(self):
     cmd.set('bg_rgb', 'red')
     cmd.stereo('anaglyph')
     self.assertImageHasColor('red')
Esempio n. 47
0
def run_morph(source,
              target,
              refinement,
              first,
              last,
              steps,
              n_state=0,
              quiet=1,
              _self=cmd):
    cmd = _self
    job = []
    job.append("load\n")
    for state in [first, last]:
        job.append("p2b\ninline\n")
        job.append(model_to_p2b(cmd.get_model(source, state)))
        job.append("\nend\n")
    job.append("end\n")
    job.append("""
# determine connectivity 

reference

   # how much VDW overlap generally determines a bond
   bond_cutoff    = 0.4

   # how far out are our neighbors?
   neighbor_cutoff = 8.0

   # should we treat HIS, ASN, GLN as symmetric (1=yes, 0=no)
   coarse_symmetry = 1 

end

# generate the difference distance matrix

compare end

# now cluster (the settings rarely need to be changed).

analyze

   group_distance_cutoff     =    0.50  #  Distance (Angstroms)
   group_angle_cutoff        =   90.00  #  Angle (Degrees) 0-180
   group_shape_cutoff        =  100.00  #  Shape Ratio (25-500)

   cluster_distance_cutoff   =    1.75  #  Distance (Angstroms)
   cluster_angle_cutoff      =  180.00  #  Angle (Degrees) 0-180
   cluster_shape_cutoff      =  250.00  #  Shape Ratio (25-500)

   domain_similarity_cutoff  =    2.50  #  Ratio > 1.0
   domain_size_cutoff        =   10     #  Atom Count
   domain_shape_cutoff       =  500.00  #  Shape Ratio (25-500)

end

# write out the interpolation

write 

   interpolation
      steps = %d
      from 1 to 2
   end

end

# terminate RigiMOL
   
stop

""" % (steps))
    input = ''.join(job)
    result = run(input, quiet)
    if (result == None) or len(result) == 0:
        open("rigimol.inp", 'w').write(input)
        print("Saved 'rigimol.inp' for troubleshooting...")
        raise CmdException("no rigimol output received!")
    if not quiet:
        print(" Morph: Loading rough coordinates...")
    cmd.create(target, source, first, 1)  # rep and color from source
    cmd.read_pdbstr(result, target, 1)
    cmd.set("defer_builds_mode", 1)
    if not quiet:
        cmd.disable()
        cmd.enable(target)
    if refinement > 0:
        if not quiet:
            print(" Morph: Refining morph (refinement level %d)..." %
                  refinement)
        refine(refinement, target, quiet=quiet)
    if not quiet:
        print(" Morph: Refinement complete.")
Esempio n. 48
0
    cmd.extend('rp17', rp17)
    cmd.extend('rp', rp)
    cmd.extend('p', p)
    cmd.extend('get_pdb', get_pdb)
    cmd.extend('get_seq', get_seq)
    cmd.extend('rna_cartoon', rna_cartoon)
    cmd.extend('rs', rs)
    cmd.extend('ino', ino)
    cmd.extend('rcomp', rcomp)
    cmd.extend('color_obj', color_obj)
    cmd.extend('color_rbw', color_rbw)
    cmd.extend('aa', align_all)
    cmd.extend('ss', ss)
    cmd.extend('ss_all', ss_all)
    cmd.extend('clarna', clarna)
    cmd.extend("rgyration", rgyration)
    cmd.extend("spli", spli)

    cmd.extend('color_aa_types', color_aa_types)

    cmd.extend('names', names)

    # set dash lines
    cmd.set('dash_color', 'red')
    cmd.set('dash_width', 4)

    print('###########################')
    print('PYMOL4RNA loading .... [ok]')
    print('###########################')
Esempio n. 49
0
    cmd.create('HCM_part', 'resi ' + resi_list_HCM_part)
    cmd.select('HCM_ca', 'bycalpha HCM_part')
    cmd.show('sphere', 'HCM_ca')
    cmd.color('greencyan', 'HCM_part')
except CmdException:
    print('no HCM mutation')

try:
    cmd.create('DCM_part', 'resi ' + resi_list_DCM_part)
    cmd.select('DCM_ca', 'bycalpha DCM_part')
    cmd.show('sphere', 'DCM_ca')
    cmd.color('chartreuse', 'DCM_part')
except CmdException:
    print('no DCM mutation')

cmd.set('label_size', 15)
cmd.set('float_labels', 'on')

try:
    cmd.create('de_stab_part', 'resi ' + resi_list_de_stab_part)
    cmd.select('de_stab_ca', 'bycalpha de_stab_part')
    cmd.label('de_stab_ca', 'one_letter[resn]+resi')
    cmd.set('label_color', 'red', 'de_stab_ca')
except CmdException:
    print('no de-stabilizing mutation')

try:
    cmd.create('stab_part', 'resi ' + resi_list_stab_part)
    cmd.select('stab_ca', 'bycalpha stab_part')
    cmd.label('stab_ca', 'one_letter[resn]+resi')
    cmd.set('label_color', 'green', 'stab_ca')
Esempio n. 50
0
def hydro_pairs(selection, cut_off):
    """
    Find hydrogen bonds for a given selection
    """
    states = cmd.count_states(selection)
    hb = []
    for i in range(1, states + 1):
        hb.append(
            cmd.find_pairs(
                "%s and (name O* and neighbor elem H) or (name N* and neighbor elem H)"
                % (selection),
                "%s and name N* or name O*" % (selection),
                cutoff=3.5,
                mode=1,
                angle=40,
                state1=i,
                state2=i))

    seen = {}
    for state in hb:
        for pairs in state:
            if pairs in seen:
                seen[pairs] = seen[pairs] + 1
            else:
                seen[pairs] = 1
    occurrence = seen.items()
    occurrence.sort(key=lambda x: x[1], reverse=True)

    fd = open("Hydrogen_bonds.dat", "w")

    fd.write(
        "--------------------------------------------------------------------\n"
    )
    fd.write(
        "-----------------------------Results--------------------------------\n"
    )
    fd.write(
        "--------------------------------------------------------------------\n"
    )
    fd.write(
        "            Donor             |            Aceptor           |\n")
    fd.write(
        "   Object  Residue  Atom Index|   Object  Residue  Atom Index| % occurrence\n"
    )

    stored.donors = []
    stored.aceptors = []
    sub = []

    occurrence_list = []
    for i in range(len(occurrence)):
        cmd.iterate("index %s" % (occurrence[i][0][0][1]),
                    "stored.donors.append((resn, elem))")
        cmd.iterate("index %s" % (occurrence[i][0][1][1]),
                    "stored.aceptors.append((resn, elem))")
        if (occurrence[i][1] * 100 / states) >= cut_off:
            fd.write("%8s%8s%6s%8s|%8s%8s%6s%8s|%5s\n" %
                     (occurrence[i][0][0][0], stored.donors[i][0],
                      stored.donors[i][1], occurrence[i][0][0][1],
                      occurrence[i][0][1][0], stored.aceptors[i][0],
                      stored.aceptors[i][1], occurrence[i][0][1][1], "%.2f" %
                      (occurrence[i][1] * 100 / states)))
            occurrence_list.append(occurrence[i][0])
    fd.close()

    cmd.set('suspend_updates', 'on')
    for state, bonds in enumerate(hb):
        for bond in bonds:
            if bond in occurrence_list:
                cmd.distance('HB',
                             'index %s' % bond[0][1],
                             'index %s' % bond[1][1],
                             state=state,
                             cutoff=3.5)
    cmd.hide("labels", "HB")
    cmd.set('suspend_updates', 'off')
    print "Check working directory for Hydrogen bonds text file report"
def DrawDRSASA_ByRes(fname):
    cols, rows, matrix, direc, sumv = ReadDRSASAIntTable(fname)

    mtrx = np.array(matrix).flatten()
    mtrx = mtrx[mtrx != 0]
    mvalue = np.max(mtrx)
    minvalue = np.min(mtrx)
    mv075 = mvalue * 0.75
    median = np.median(mtrx)
    avg = np.average(mtrx)
    cutoff = mvalue * 0.05
    cmd.color("grey", "all")
    print median, avg, cutoff, minvalue
    Rl = []
    Gl = []
    Bl = []
    cmd.set('suspend_updates', 'on')
    view = cmd.get_view()
    for row in range(len(matrix)):
        for col in range(len(matrix[row])):
            v = float(matrix[row][col])
            if v < cutoff:
                continue
            R = 1.8 * v / mvalue

            rid = [str(item) for item in rows[row]]
            cid = [str(item) for item in cols[col]]
            sele1, resn1 = GenSeleResn(rid[0], rid[1], rid[2])
            sele2, resn2 = GenSeleResn(cid[0], cid[1], cid[2])
            print(sele1, sele2)
            cmd.select("atom1", sele1)
            cmd.select("atom2", sele2)
            d = cmd.get_distance("atom1", "atom2")
            #name = "/".join(rid)+"_"+"/".join(cid)
            name = "a_" + str(row) + "_" + str(col)
            if direc == "row":
                resn_s = resn2
            elif direc == "col":
                resn_s = resn1
            if (v >= mv075):
                color = "red red"
                Rl.append(resn_s)
                cmd.color("red", resn_s)
            elif (v > median):
                color = "green green"
                Gl.append(resn_s)
                if not resn_s in Rl:
                    cmd.color("green", resn_s)
            else:
                color = "blue blue"
                if (not resn_s in Rl) and (not resn_s in Gl):
                    cmd.color("blue", resn_s)

            if direc == "row":
                cgo_arrow("atom2", "atom1", 0.1, d * 0.25, d * 0.1, R, color,
                          name)
            elif direc == "col":
                cgo_arrow("atom1", "atom2", 0.1, d * 0.25, d * 0.1, R, color,
                          name)
    cmd.set_view(view)
    cmd.set('suspend_updates', 'off')
Esempio n. 52
0
                    [random() + 0.5] +  # r
                    map(lambda x: (random() - 0.5), [0] * 3)  # vx,vy,vz
                    )

# create cloud object

for part in particle:
    cmd.pseudoatom("cloud", resi=part[0], pos=part[1:4], vdw=part[4])

# draw spheres efficiently
cmd.show_as("spheres")
cmd.unset("cull_spheres")

# defer geometry generation until needed

cmd.set("defer_builds", 1)

# position the camera

cmd.zoom()
cmd.zoom("center", box_size)

# let there be color

cmd.spectrum()

# this is the main loop


def simulation():
    state = 1
Esempio n. 53
0
def visualize_in_pymol(plcomplex):
    """Visualizes the protein-ligand pliprofiler at one site in PyMOL."""

    vis = PyMOLVisualizer(plcomplex)

    #####################
    # Set everything up #
    #####################

    pdbid = plcomplex.pdbid
    lig_members = plcomplex.lig_members
    chain = plcomplex.chain
    if config.PEPTIDES:
        vis.ligname = 'PeptideChain%s' % plcomplex.chain
    if config.INTRA is not None:
        vis.ligname = 'Intra%s' % plcomplex.chain

    ligname = vis.ligname
    hetid = plcomplex.hetid

    metal_ids = plcomplex.metal_ids
    metal_ids_str = '+'.join([str(i) for i in metal_ids])

    ########################
    # Basic visualizations #
    ########################

    start_pymol(run=True,
                options='-pcq',
                quiet=not config.VERBOSE and not config.SILENT)
    vis.set_initial_representations()

    cmd.load(plcomplex.sourcefile)
    current_name = cmd.get_object_list(selection='(all)')[0]
    logger.debug(
        f'setting current_name to {current_name} and pdbid to {pdbid}')
    cmd.set_name(current_name, pdbid)
    cmd.hide('everything', 'all')
    if config.PEPTIDES:
        cmd.select(ligname, 'chain %s and not resn HOH' % plcomplex.chain)
    else:
        cmd.select(
            ligname, 'resn %s and chain %s and resi %s*' %
            (hetid, chain, plcomplex.position))
    logger.debug(
        f'selecting ligand for PDBID {pdbid} and ligand name {ligname}')
    logger.debug(
        f'resn {hetid} and chain {chain} and resi {plcomplex.position}')

    # Visualize and color metal ions if there are any
    if not len(metal_ids) == 0:
        vis.select_by_ids(ligname, metal_ids, selection_exists=True)
        cmd.show('spheres', 'id %s and %s' % (metal_ids_str, pdbid))

    # Additionally, select all members of composite ligands
    if len(lig_members) > 1:
        for member in lig_members:
            resid, chain, resnr = member[0], member[1], str(member[2])
            cmd.select(
                ligname, '%s or (resn %s and chain %s and resi %s)' %
                (ligname, resid, chain, resnr))

    cmd.show('sticks', ligname)
    cmd.color('myblue')
    cmd.color('myorange', ligname)
    cmd.util.cnc('all')
    if not len(metal_ids) == 0:
        cmd.color('hotpink', 'id %s' % metal_ids_str)
        cmd.hide('sticks', 'id %s' % metal_ids_str)
        cmd.set('sphere_scale', 0.3, ligname)
    cmd.deselect()

    vis.make_initial_selections()

    vis.show_hydrophobic()  # Hydrophobic Contacts
    vis.show_hbonds()  # Hydrogen Bonds
    vis.show_halogen()  # Halogen Bonds
    vis.show_stacking()  # pi-Stacking Interactions
    vis.show_cationpi()  # pi-Cation Interactions
    vis.show_sbridges()  # Salt Bridges
    vis.show_wbridges()  # Water Bridges
    vis.show_metal()  # Metal Coordination

    vis.refinements()

    vis.zoom_to_ligand()

    vis.selections_cleanup()

    vis.selections_group()
    vis.additional_cleanup()
    if config.DNARECEPTOR:
        # Rename Cartoon selection to Line selection and change repr.
        cmd.set_name('%sCartoon' % plcomplex.pdbid,
                     '%sLines' % plcomplex.pdbid)
        cmd.hide('cartoon', '%sLines' % plcomplex.pdbid)
        cmd.show('lines', '%sLines' % plcomplex.pdbid)

    if config.PEPTIDES:
        filename = "%s_PeptideChain%s" % (pdbid.upper(), plcomplex.chain)
        if config.PYMOL:
            vis.save_session(config.OUTPATH, override=filename)
    elif config.INTRA is not None:
        filename = "%s_IntraChain%s" % (pdbid.upper(), plcomplex.chain)
        if config.PYMOL:
            vis.save_session(config.OUTPATH, override=filename)
    else:
        filename = '%s_%s' % (pdbid.upper(), "_".join(
            [hetid, plcomplex.chain, plcomplex.position]))
        if config.PYMOL:
            vis.save_session(config.OUTPATH)
    if config.PICS:
        vis.save_picture(config.OUTPATH, filename)
def DrawDRSASA_ByAtom(fname, mode='0'):
    mode = int(mode)
    cols, rows, matrix, direc, sumv = ReadDRSASAIntTable(fname)
    mtrx = np.array(matrix).flatten()
    mtrx = mtrx[mtrx != 0]
    mvalue = np.max(mtrx)
    minvalue = np.min(mtrx)
    mv075 = mvalue * 0.75
    median = np.median(mtrx)
    avg = np.average(mtrx)
    cutoff = mvalue * 0.05
    cmd.color("grey", "all")
    print median, avg, cutoff, minvalue
    Rl = []
    Gl = []
    Bl = []
    cmd.set('suspend_updates', 'on')
    view = cmd.get_view()
    for row in range(len(matrix)):
        for col in range(len(matrix[row])):
            v = float(matrix[row][col])
            if v < cutoff:
                continue
            R = 1.8 * v / mvalue
            nR = v / mvalue
            colorn = "drsasa_" + str(row) + "_" + str(col)
            cmd.set_color(colorn, (int(255 * nR), 0, 255 - int(255 * nR)))
            rid = [str(item) for item in rows[row]]
            cid = [str(item) for item in cols[col]]
            print(rid, cid)
            sele1 = GenSeleAtom(rid[0], rid[1], rid[2], rid[3])
            sele2 = GenSeleAtom(cid[0], cid[1], cid[2], cid[3])
            print(sele1, sele2)
            cmd.select("atom1", sele1)
            cmd.select("atom2", sele2)
            d = cmd.get_distance("atom1", "atom2")
            if direc == "row":
                atom_s = sele2
            elif direc == "col":
                atom_s = sele1
            #name = "/".join(rid)+"_"+"/".join(cid)
            name = "a_" + str(row) + "_" + str(col)

            if mode == 0:
                if (v >= mv075):
                    color = colorn + " " + colorn
                    Rl.append(atom_s)
                    cmd.color("red", atom_s)
                elif (v > median):
                    color = "green green"
                    Gl.append(atom_s)
                    if not atom_s in Rl:
                        cmd.color("green", atom_s)
                else:
                    color = "blue blue"
                    if (not atom_s in Rl) and (not atom_s in Gl):
                        cmd.color("blue", atom_s)
            elif mode == 1:
                color = colorn + " " + colorn
            if direc == "row":
                if mode == 0:
                    cgo_arrow("atom2", "atom1", 0.1, d * 0.25, d * 0.1, R,
                              color, name)
                elif mode == 1:
                    cgo_arrow("atom2", "atom1", 0.1, d * 0.25, d * 0.1, 0.2,
                              color, name)
            elif direc == "col":
                if mode == 0:
                    cgo_arrow("atom1", "atom2", 0.1, d * 0.25, d * 0.1, R,
                              color, name)
                elif mode == 1:
                    cgo_arrow("atom1", "atom2", 0.1, d * 0.25, d * 0.1, 0.2,
                              color, name)
    cmd.set_view(view)
    cmd.set('suspend_updates', 'off')
Esempio n. 55
0
cmd.show("spheres", "resi 10")

cmd.color("yellow", "resi 5 and element c")

# turn off some of the chatter about reloading the object...

cmd.feedback("disable", "executive", "actions")

# now loop, updating the coordinates and reloading the model into
# state 1 of the "demo" object

m = cmd.get_model()
while cont:
    time.sleep(0.05)
    try:
        cmd.set("suspend_updates", "1")  # only necessary if multithreading...
        for a in m.atom:
            a.coord[0] += (random() - 0.5) * 0.1
            a.coord[1] += (random() - 0.5) * 0.1
            a.coord[2] += (random() - 0.5) * 0.1
        cmd.load_model(m, "demo", 1)
        cmd.set("suspend_updates", "0")  # only necessary if multithreading...
    except:
        cmd.set("suspend_updates", "0")  # only necessary if multithreading...
        traceback.print_exc()
    cmd.refresh()

# Summary: this is portable, safe, but inefficient.  For real-time visualization
# of coordinate changes, there is a way to do this by passing in an opaque
# C data structure...
Esempio n. 56
0
def mcm(pose, mc_steps, SASA, randomize):
    ################################# MCM Parameters ##########################
    T = 300.  # Temperature
    k = 0.0019872041  # Boltzmann constant
    kT = k * T
    # probability to sample phi, psi or chi
    angles_prob = [1 / 3, 1 / 3, 1 / 3]
    accepted = 0
    ##########################################################################
    #
    first, last = pose_from_pdb(pose)
    if first or last:
        print('Starting MCM')
        from energy import minimize, set_sasa, get_sasa
        sus_updates = cmd.get('suspend_updates')
        cmd.set('suspend_updates', 'on')
        # uncomment for debugging
        cmd.feedback('disable', 'executive', 'everything')
        pdb_conect = cmd.get('pdb_conect_all')
        cmd.set('pdb_conect_all', 1)

        glyco_bonds = get_glyco_bonds(first, last)
        con_matrix = writer(glyco_bonds)

        # Remove previous pdb files
        prev_files = glob.glob('mcm_*.pdb')
        for prev_file in prev_files:
            os.remove(prev_file)

        # set all paramenters for sasa-energy computation
        if SASA:
            params, points, const = set_sasa(n=1000)
            # randomize initial conformation
        if randomize:
            for i in range(len(con_matrix) - 1):
                bond = con_matrix[i]
                angle_values = np.random.uniform(-180, 180, size=2)
                set_psi(pose, bond, angle_values[0])
                set_phi(pose, bond, angle_values[1])
                for i in range(6):
                    set_chi(pose, bond)

        # minimize energy of starting conformation and save it
        NRG_old = minimize(pose, nsteps=5000, rigid_geometry=False)
        NRG_min = NRG_old
        cmd.save('mcm_%08d.pdb' % accepted)

        # start MCM routine
        fd = open("mcm_log.txt", "w")
        print('# iterations remaining = %s' % (mc_steps))
        for i in range(1, mc_steps + 1):
            if i % (mc_steps // 10) == 0:
                print('#remaining iterations = %s' % (mc_steps - i))
            if True:
                sample_uniform(pose, con_matrix, angles_prob)
            NRG_new = minimize('tmp', nsteps=100, rigid_geometry=False)
            if SASA:
                solvatation_nrg = get_sasa(params,
                                           points,
                                           const,
                                           selection='all',
                                           probe=0)[0]
                NRG_new = NRG_new + solvatation_nrg
            if NRG_new < NRG_old:
                NRG_old = NRG_new
                fd.write('%8d%10.2f\n' % (accepted, NRG_new))
                cmd.copy(pose, 'tmp')
                cmd.delete('tmp')
                cmd.save('mcm_%08d.pdb' % accepted)
                accepted += 1
            else:
                delta = np.exp(-(NRG_new - NRG_old) / (kT))
                if delta > np.random.uniform(0, 1):
                    NRG_old = NRG_new
                    fd.write('%8d%10.2f\n' % (accepted, NRG_new))

                    cmd.copy(pose, 'tmp')
                    cmd.delete('tmp')
                    cmd.save('mcm_%08d.pdb' % accepted)
                    accepted += 1
            cmd.delete('tmp')
            if NRG_new < NRG_min:
                NRG_min = NRG_new
                cmd.save('mcm_min.pdb')
        fd.close()

        cmd.delete('all')
        print('Savings all accepted conformations on a single file')
        de_builds = cmd.get('defer_builds_mode')
        cmd.set('defer_builds_mode', 5)
        for i in range(0, accepted):
            cmd.load('mcm_%08d.pdb' % i, 'mcm_trace')
        cmd.save('mcm_trace.pdb', 'all', state=0)
        cmd.delete('all')
        cmd.load('mcm_trace.pdb')
        cmd.intra_fit('mcm_trace')
        print('MCM completed')
        # restore settings
        cmd.set('suspend_updates', sus_updates)
        cmd.set('pdb_conect_all', pdb_conect)
        cmd.set('defer_builds_mode', de_builds)
Esempio n. 57
0
def main(d1, d2):
    ## Make an output folder
    outdir = 'output_dd/' + input_protein + '+' + d1 + '+' + d2 + '/'
    #print (outdir)
    if os.path.isdir(outdir) == False:
        os.system('mkdir ' + outdir)

    domains = d1 + '+' + d2
    for pdb in dd[domains]:
        download_pdb_cif(pdb)
        for coordinates in dd[domains][pdb]:
            #print (pdb, domains, dd[domains][pdb][coordinates])
            chainA = coordinates.split('+')[0].split(':')[0]
            chainA_res = coordinates.split('+')[0].split(':')[1]
            chainB = coordinates.split('+')[1].split(':')[0]
            chainB_res = coordinates.split('+')[1].split(':')[1]
            cmd.load('pdbs/' + pdb.upper() + '.pdb')
            cmd.hide('everything')
            cmd.show('cartoon', 'chain ' + chainA + '+' + chainB)
            cmd.set('cartoon_fancy_helices', 1)
            print(pdb, chainA, chainA_res, chainB, chainB_res)
            try:
                x = cmd.centerofmass('chain ' + chainA)
                print('Success chainA')
                cmd.pseudoatom('chainA_label', pos=x)
                global nameA
                nameA = id_to_name[d1] + '(' + d1 + ')'
                cmd.label('chainA_label', 'nameA')
            except:
                print('Failed chainA')
            try:
                x = cmd.centerofmass('chain ' + chainB)
                print('Success chainB')
                cmd.pseudoatom('chainB_label', pos=x)
                global nameB
                nameB = id_to_name[d2] + '(' + d2 + ')'
                cmd.label('chainB_label', 'nameB')
                x = cmd.centerofmass('chain ' + chainA + '+' + chainB)
                cmd.origin(position=x)
                cmd.center('origin')
            except:
                print('Failed chainB')
            cmd.set('label_size', 7.5)
            cmd.set('cartoon_fancy_helices', 1)
            cmd.color('red', 'chain ' + chainA)
            cmd.color('orange', 'chain ' + chainB)
            for row in dd[domains][pdb][coordinates]:
                res1 = row[2]
                res2 = row[3]
                #cmd.distance('chain '+chainA+' and i. '+res1+' and n. CB', 'chain '+chainB+' and i. '+res2+' and n. CB')
                cutoff = 6.5
                m = cmd.distance(
                    'dist',
                    'chain ' + chainA + ' and i. ' + res1 + ' and n. CB',
                    'chain ' + chainB + ' and i. ' + res2 + ' and n. CB',
                    cutoff, 0)
                #m = cmd.get_distance(atom1='chain '+chainA+' and i. '+res1+' and n. CB',atom2='chain '+chainB+' and i. '+res2+' and n. CB',state=0)
                #print (pdb, m, chainA, res1, chainB, res2)
                cmd.select('res1', 'chain ' + chainA + ' and resi ' + res1)
                cmd.select('res2', 'chain ' + chainB + ' and resi ' + res2)

                if float(m) != 0.0:
                    cmd.show('sticks', 'res1')
                    cmd.show('sticks', 'res2')
                    cmd.color('cyan', 'res1')
                    cmd.color('yellow', 'res2')

            cmd.save(outdir + pdb + '_' + input_protein + '_' + d1 + '_' +
                     d2 + '_' + coordinates.replace(':', '_').replace(
                         '+', '_').replace('-', '_') + '.pse')
            cmd.save(outdir + pdb + '_' + input_protein + '_' + d1 + '_' +
                     d2 + '_' + coordinates.replace(':', '_').replace(
                         '+', '_').replace('-', '_') + '.pdb')
            cmd.delete('all')
        #break
    '''
Esempio n. 58
0
#cmd.bond('id 1', 'id 2')
#cmd.bond('id 1', 'id 3')
#cmd.bond('id 1', 'id 4')

#cmd.set_bond ('stick_color', 'white', 'all', 'all')
#cmd.set_bond ('stick_radius', -0.14, 'all', 'all')
#cmd.set ('stick_ball', 1)
#cmd.set ('stick_ball_ratio', -1)
#cmd.set ('stick_ball_color', 'atomic')
#cmd.show ('sticks', 'all')

#cmd.color('black', 'id 1')
#cmd.color('gray', '(name Au*)')

cmd.set_bond('stick_radius', 0.1, 'all', 'all')
cmd.set('sphere_scale', 0.15, 'all')
cmd.show('sticks', 'all')
cmd.show('spheres', 'all')
cmd.set('stick_ball_color', 'atomic')

cmd.color('gray20', '(name C*)')

cmd.set('transparency_mode', 1)

#w = 0.01 # cylinder width
#l = 0.5 # cylinder length
#h = 0.15 # cone hight
#d = w * 1.618 # cone base diameter
w = 0.03  # cylinder width
l = 1.65  # cylinder length
h = 0.2  # cone hight
Esempio n. 59
0
 def cleanup(self):
     self.clear()
     cmd.set("mouse_selection_mode",
             self.selection_mode)  # restore selection mode
Esempio n. 60
0
 def viewMode(mode, factor=1., subset=None, label=None):
     from pymol import cmd
     cmd.set("movie_delay", "200", log=1)
     genericViewMode(mode, factor, subset, label)