예제 #1
0
    def testSaveRef(self, format):
        # for rms_cur (not all formats save all identifiers)
        m = -1
        cmd.set('retain_order')

        cmd.fragment('ala', 'm1')
        cmd.copy('m2', 'm1')
        cmd.copy('m3', 'm1')

        cmd.rotate('y', 90, 'm2')
        cmd.align('m3', 'm2')

        # with ref=m3
        with testing.mktemp('.' + format) as filename:
            cmd.save(filename, 'm2', ref='m3')
            cmd.load(filename, 'm4')
            self.assertAlmostEqual(cmd.rms_cur('m4', 'm1', matchmaker=m), 0.00, delta=1e-2)
            self.assertAlmostEqual(cmd.rms_cur('m4', 'm2', matchmaker=m), 1.87, delta=1e-2)

        # without ref
        with testing.mktemp('.' + format) as filename:
            cmd.save(filename, 'm2')
            cmd.load(filename, 'm5')
            self.assertAlmostEqual(cmd.rms_cur('m5', 'm2', matchmaker=m), 0.00, delta=1e-2)
            self.assertAlmostEqual(cmd.rms_cur('m5', 'm1', matchmaker=m), 1.87, delta=1e-2)
예제 #2
0
    def testSaveRef(self, format):
        # for rms_cur (not all formats save all identifiers)
        m = -1
        cmd.set('retain_order')

        cmd.fragment('ala', 'm1')
        cmd.copy('m2', 'm1')
        cmd.copy('m3', 'm1')

        cmd.rotate('y', 90, 'm2')
        cmd.align('m3', 'm2')

        # with ref=m3
        with testing.mktemp('.' + format) as filename:
            cmd.save(filename, 'm2', ref='m3')
            cmd.load(filename, 'm4')
            self.assertAlmostEqual(cmd.rms_cur('m4', 'm1', matchmaker=m), 0.00, delta=1e-2)
            self.assertAlmostEqual(cmd.rms_cur('m4', 'm2', matchmaker=m), 1.87, delta=1e-2)

        # without ref
        with testing.mktemp('.' + format) as filename:
            cmd.save(filename, 'm2')
            cmd.load(filename, 'm5')
            self.assertAlmostEqual(cmd.rms_cur('m5', 'm2', matchmaker=m), 0.00, delta=1e-2)
            self.assertAlmostEqual(cmd.rms_cur('m5', 'm1', matchmaker=m), 1.87, delta=1e-2)
예제 #3
0
def getRMSD(motifName, queryPDBCode, motifPDBCode):
            
        #querySubsetName = 'match_in_{0}'.format(queryPDBCode)
        querySubsetName = 'match_in_%s'%(queryPDBCode)
        cmd.select(querySubsetName, motifName)
        cmd.hide('everything', 'all')
        cmd.fetch(motifPDBCode, async=0, path=glb.FETCH_PATH)
        #motifSubsetName = 'match_in_{0}'.format(motifPDBCode)
        motifSubsetName = 'match_in_%s'%(motifPDBCode)
        cmd.select(motifSubsetName, '%s and (%s)' % (motifPDBCode,
            glb.MOTIFS[motifName]['loci']))
        cmd.hide('everything', 'all')
     
        #aligns and gets the rmsd of the alignment by all atoms
        dataAll = cmd.align(motifSubsetName, querySubsetName)  
        #aligns and gets the rmsd of the alignment by C alpha atoms
        cmd.select(querySubsetName, motifName+" and name ca")
        cmd.select(motifSubsetName, '%s and (%s) and name %s' % (motifPDBCode,
        glb.MOTIFS[motifName]['loci'], "ca"))
        dataAlpha = cmd.align(motifSubsetName, querySubsetName)
        #aligns and gets the rmsd of the alignment by C alpha and C beta atoms
        cmd.select(querySubsetName, motifName+" and name ca,cb")
        cmd.select(motifSubsetName, '%s and (%s) and name %s' % (motifPDBCode,
        glb.MOTIFS[motifName]['loci'], "ca,cb"))
        dataAlphaBeta = cmd.align(motifSubsetName, querySubsetName)
        rmsds = []
        rmsds.append(dataAll[0])
        rmsds.append(dataAlpha[0])
        rmsds.append(dataAlphaBeta[0])
        cmd.delete(motifName) 
        return rmsds
예제 #4
0
    def test(self, matrix_mode):
        cmd.viewport(100, 100)
        cmd.set('matrix_mode', matrix_mode)
        cmd.set('ambient', 1.0)

        cmd.read_pdbstr(v_pdbstr_anisou, 'm1', zoom=0)
        cmd.read_pdbstr(v_pdbstr_rotated, 'm2', zoom=0)
        self._rep()

        cmd.set_view(views[0])
        ref = self.get_imagearray()
        self.assertImageHasColor('yellow')

        cmd.align('m1', 'm2')
        cmd.set_view(views[1])
        self.assertImageEqual(ref,
                              count=100,
                              delta=1,
                              msg='ANISOU not aligned on display')

        pdbstr = cmd.get_pdbstr('m1')
        cmd.delete('*')
        cmd.read_pdbstr(pdbstr, 'm1', zoom=0)
        self._rep()
        self.assertImageEqual(ref, count=100, msg='ANISOU not aligned in PDB')
예제 #5
0
def sewalign(first,second):
	#hide waters
	cmd.hide("(solvent and (all))")
	#hide hydrogens
	cmd.hide( 'sticks', 'elem H' )
	cmd.hide( 'lines', 'elem H' )

	#show cartoon
	cmd.show("cartoon"   ,"all")

	#create duplicate of first
	first_copy = first + "_copy"
	cmd.copy(first_copy, first)

	#select first 14 residues 
	cmd.select('node_9_selection', '(obj *_9_* and resi 1-14)')
	cmd.select('node_12_selection', '(obj *_12_* and resi 1-14)')
	cmd.select('node_15_selection', '(obj *_15_* and resi 1-14)')

	alignment_1 = cmd.align(first, 'node_9_selection')
	print alignment_1[0]

	alignment_2 = cmd.align(second, 'node_12_selection')
	print alignment_2[0]

	alignment_3 = cmd.align(first_copy, 'node_15_selection')
	print alignment_3[0]
예제 #6
0
	def revert(self):
		v = cmd.get_view()
		cmd.remove(self.rdes.obj+" and not chain A")
		m = cmd.get_model(self.rdes.obj)
		n = self.oldcrd
		if not n:
			cmd.create("tmp12345",self.rnat.sel())
			cmd.align("tmp12345",self.rdes.sel())
			n = cmd.get_model("tmp12345").atom
			cmd.delete("tmp12345")
		di,ni = 0,0
		while m.atom[di].resi != str(self.rdes.resi): di += 1
		dj = di
		while m.atom[dj].resi == str(self.rdes.resi): dj += 1
		if self.oldcrd: self.oldcrd = None
		else:           self.oldcrd = m.atom[di:dj]
		m.atom = m.atom[:di] + n + m.atom[dj:]
		for i in range(di,di+len(n)):
			m.atom[i].resi  = str(self.rdes.resi)
			m.atom[i].chain = str(self.rdes.chain)
		cmd.load_model(m,self.rdes.obj,1)
		cmd.save("tmp.pdb",self.rdes.obj)
		cmd.delete(self.rdes.obj)
		cmd.load("tmp.pdb",self.rdes.obj,1)
		cmd.show('car',self.rdes.obj)
		cmd.show('lines')		
		redopent(self.rdes.obj)
		cmd.set_view(v)
		print "revert removing "+"".join(self.aas)+" from aas!"
		self.aas = [getaa('A',self.rdes.resi,self.manager.d.obj)]
예제 #7
0
def loadpair(file):
	id = file.split('/')[-1][:4]
	loadcenters(file,id+'nat')
	loadcenters(file[:-17]+'_decoy_sasa_centers.pdb',id+'decoy')
	d = id+'decoy'
	n = id+'nat'
	cmd.align(n,d)
예제 #8
0
def align_all(target=None,
              mobile_selection='name ca',
              target_selection='name ca',
              cutoff=2,
              cycles=5,
              cgo_object=0):
    """
  Aligns all models in a list to one target

  usage:
    align_all [target][target_selection=name ca][mobile_selection=name ca][cutoff=2][cycles=5][cgo_object=0]
        where target specifies the model id you want to align all others against,
        and target_selection, mobile_selection, cutoff and cycles are options
        passed to the align command.

    By default the selection is all C-alpha atoms and the cutoff is 2 and the
    number of cycles is 5.
    Setting cgo_object to 1, will cause the generation of an alignment object for
    each object.  They will be named like <object>_on_<target>, where <object> and
    <target> will be replaced by the real object and target names.

    Example:
      align_all target=name1, mobile_selection=c. b & n. n+ca+c+o,target_selection=c. a & n. n+ca+c+o

  """
    cutoff = int(cutoff)
    cycles = int(cycles)
    cgo_object = int(cgo_object)

    object_list = cmd.get_names()
    object_list.remove(target)

    rmsd = {}
    rmsd_list = []
    for i in range(len(object_list)):
        if cgo_object:
            objectname = 'align_%s_on_%s' % (object_list[i], target)
            rms = cmd.align('%s & %s' % (object_list[i], mobile_selection),
                            '%s & %s' % (target, target_selection),
                            cutoff=cutoff,
                            cycles=cycles,
                            object=objectname)
        else:
            rms = cmd.align('%s & %s' % (object_list[i], mobile_selection),
                            '%s & %s' % (target, target_selection),
                            cutoff=cutoff,
                            cycles=cycles)

        rmsd[object_list[i]] = rms[0]
        rmsd_list.append((rms[0], object_list[i]))

    rmsd_list.sort()
    # loop over dictionary and print out matrix of final rms values
    print "Aligning against:", target
    for object_name in object_list:
        print "%s: %6.3f" % (object_name, rmsd[object_name])

    for r in rmsd_list:
        print "%6.3f  %s" % r
예제 #9
0
def ligands_where_are_you(pdb, align_to, in_dir, out_dir):
    # load the pdb and align to reference 1AQL
    pdbe = join(in_dir, pdb + ".pdb")
    cmd.load(r"{}".format(pdbe),"{}".format(pdb))
    #cmd.align("""{} and chain A""".format(pdb), """{} and chain A""".format(align_to))
    cmd.align(pdb, align_to)
    cmd.save((os.path.join(out_dir,pdb + ".pdb")), pdb)
    cmd.delete(pdb)
예제 #10
0
def align_chain(ref, query, chain, out):
    pymol.finish_launching()
    cmd.delete('all')
    cmd.load(ref)
    cmd.load(query)
    ref_name = ref.split('/')[-1].split('.')[0]
    query_name = query.split('/')[-1].split('.')[0]
    cmd.align(query_name + ' and chain ' + chain, ref_name + ' and chain ' + chain)
    cmd.save(out, query_name)
예제 #11
0
def mican(mobile, target, option=""):
    '''
DESCRIPTION
    Align two (ligand) selections based on mican algorithm.
ARGUMENTS
    mobile = str: atom selection of mobile object
    target = str: atom selection of target object
EXAMPLE
    fetch 3zcf 4n8t, bsync=0
    mcsalign /3zcf//A/HEC, /4n8t//A/HEM
    zoom /4n8t//A/HEM, animate=2, buffer=3
    '''
    import subprocess
    import tempfile
    import os

    with tempfile.TemporaryDirectory() as dname:
        # print tmp dir name
        print("Temporary directory =" + dname)
        # make sure you have mican in PATH
        # directly giving 'execute' full path below is good alternative
        # For example : execute = "/usr/bin/mican"
        execute = "mican"
        tmptarget = dname + "/target.pdb"
        tmpmobile = dname + "/mobile.pdb"
        tmpout = dname + "/aligned.pdb"

        # save pdb for mican
        cmd.save(tmptarget, target)
        cmd.save(tmpmobile, mobile)

        modeoption = "-" + option
        option2 = "-o"
        outfile = tmpout


        mican = [execute, tmpmobile, tmptarget, option2, outfile]
        for op in option.split():
            if(op == "-o"):
                print("option -o is reserved")
                raise CmdException
            mican.append(op)

        proc=subprocess.run(mican,stdout = subprocess.PIPE)
        print(proc.stdout.decode("utf8")) # print result to pymol console

        cmd.load(outfile, "aligned")
        cmd.split_states("aligned")
        cmd.select("mobileback",mobile + " and backbone")
        cmd.align("mobileback", "aligned_0001 and backbone")
        # use cmd pair_fit if you think align is not good
        # print("Using cmd.align instead of cmd.pair_fit")
        # pymol.cmd.pair_fit("mobileback", "aligned_0001 and backbone")
        cmd.delete("mobileback")
        cmd.delete("aligned")
        cmd.delete("aligned_0001")
        cmd.delete("aligned_0002")
예제 #12
0
def align_and_color(moving, fixed, maximum=None, native_color="blue"):
    if maximum == "0":
        maximum = None
    alignment_name = "alignment_" + moving
    cmd.align(moving, fixed, object=alignment_name, cycles=0)
    cmd.disable(alignment_name)
    rmsd_b(moving + " & " + alignment_name, fixed + " & " + alignment_name)
    cmd.color(native_color, fixed)
    cmd.spectrum("b", "green_red", moving, 0, maximum)
예제 #13
0
def align_and_color(moving, fixed, maximum=None, native_color="blue"):
    if maximum == "0":
        maximum = None
    alignment_name = "alignment_" + moving
    cmd.align(moving, fixed, object=alignment_name, cycles=0)
    cmd.disable(alignment_name)
    rmsd_b(moving + " & " + alignment_name, fixed + " & " + alignment_name)
    cmd.color(native_color, fixed)
    cmd.spectrum("b", "green_red", moving, 0, maximum)
예제 #14
0
def Mutagenesis(kinase1, model, template,peptide_instance):
    """superposition the model and template, remove template and leave peptide behind """

    """replace peptide with instance peptide"""
    list_name = peptide_instance
    with open(input_data_folder+list_name,'r') as f:
        instances = f.readlines()
    instance = [x.strip() for x in instances]
    print "your peptide: ", instance 
    
    for pep in instance:
        cmd.delete('all')
        cmd.fetch(model)  # model_candidate, ex.chk1,chk2...
        cmd.remove("hetatm") #remove the nonstandard residues
        cmd.fetch(template)  #mutagenesis template, ex.2phk
        peptide_template = cmd.get_fastastr( "/"+template+'//B') #get the peptide from the template and generate another one for mutagenesis 
        peptide_template = peptide_template + 'G' #peptide of 2phk is 7 amino acid long, when our input peptide is 8 aa, we need to plus one character
        
        
        for aa in peptide_template[6:].lower(): #creat template_peptide for mutagenesis

            cmd._alt(aa)
        
        
        firstaa = AAcode_1_to_3(peptide_template[6]) #translate template_peptide to 3 letter
        low_firstaa = firstaa[0].lower()

        cmd.alter(low_firstaa, 'chain = "B"') #select this template_peptide        
        cmd.show_as("cartoon")
        cmd.align(model, template) #superpostion of model and template
        cmd.align(low_firstaa,template) #superpostion of template_peptide and template

        remove_part = "("+template+" and not resn ATP"+")" 
        cmd.select("remove_part",remove_part) 

        
        cmd.remove("remove_part") #remove the template except for ATP, there are only model and template_peptide
        cmd.remove("resn hoh") #remove water
        cmd.wizard("mutagenesis")
        peptide_position = 0

        for i in pep:
            #the peptide_position starting point depends the first position of mutagenesis peptide
            #pymol's peptide start from 1, not 0
            mutagenesis_template = '/'+low_firstaa+ '///' + str(peptide_position + 2) # because of 2phk start at 2nd of peptide
            #mutagenesis_template = '/' + template + '//B/' + str(peptide_position + 2)
            cmd.get_wizard().do_select(mutagenesis_template)  # select peptide position of mutation
            replace_aminoacid = AAcode_1_to_3(pep)[peptide_position]
            cmd.get_wizard().set_mode(replace_aminoacid)  # select which residue want to mutate to
            cmd.get_wizard().apply()
            peptide_position += 1
        filename = kinase1 + '_' + model + 'model_' + template + 'muta_' + pep + '.pdb' #build the canonical name
        cmd.save(filename)
        ATPchange(filename) #change ATP naming to the format of ATP.params
    cmd.wizard(None)
    return
예제 #15
0
 def testSaveAln(self):
     cmd.fab('ACDEFGH', 'm1')
     cmd.fab('ACDFGH', 'm2')
     cmd.align('m1', 'm2', cycles=0, object='aln')
     with testing.mktemp('.aln') as filename:
         cmd.save(filename)
         with open(filename) as handle:
             lines = list(handle)
     self.assertEqual(lines[0].split(), ['CLUSTAL'])
     self.assertEqual(lines[1].split(), [])
     self.assertEqual(lines[2].split(), ['m1', 'ACDEFGH'])
     self.assertEqual(lines[3].split(), ['m2', 'ACD-FGH'])
예제 #16
0
 def testSaveAln(self):
     cmd.fab('ACDEFGH', 'm1')
     cmd.fab('ACDFGH', 'm2')
     cmd.align('m1', 'm2', cycles=0, object='aln')
     with testing.mktemp('.aln') as filename:
         cmd.save(filename)
         with open(filename) as handle:
             lines = list(handle)
     self.assertEqual(lines[0].split(), ['CLUSTAL'])
     self.assertEqual(lines[1].split(), [])
     self.assertEqual(lines[2].split(), ['m1', 'ACDEFGH'])
     self.assertEqual(lines[3].split(), ['m2', 'ACD-FGH'])
예제 #17
0
	def focus(self):
		self.manager.m = self
		if self.manager.prevm: cmd.hide('sticks',self.manager.prevm.rdes.sel())
		if self.manager.prevm: cmd.color('green',self.manager.prevm.rdes.sel()+" and elem C")
		fr = self.rnat.obj+" and name n+ca+c and resi %i-%i"%(self.rnat.resi-10,self.rnat.resi+10)		
		to = self.rdes.obj+" and name n+ca+c and resi %i-%i"%(self.rdes.resi-10,self.rdes.resi+10)
		cmd.align(fr,to)
		cmd.show('sticks',self.rdes.sel())
		cmd.color('white',self.rdes.sel()+" and elem C")
		cmd.center(self.rdes.sel())
		v = list(cmd.get_view())
		v[11] = -80.0
		cmd.set_view(tuple(v))
		cmd.clip('slab',50,self.rdes.sel())
예제 #18
0
def loadPackingPDB(file,name=None,native=None):
	"""
	usage: loadPackingPDB <file> , [<name for object>]
	loads a foo_packing.pdb file and colors it all pretty-like
	creates two selections along with the loaded object called
	NAMEcavities and NAMEprotein which are the heteratoms representing
	holes and everything else, respectively. Names can get pretty long,
	by pymol lets you do good stuff like "select NA*cav*", which will
	match a selection called NAMEISREALLYLONGcavities.
	"""

	if name is None:
		name = name = os.path.basename(file)
	if name.endswith('.gz'):
		name = name[:-3] 
	if name.endswith('.pdb'):
		name = name[:-4] 
	if name.endswith('.'):
		name = name[:-1] 
	if name.endswith("_packing"):
		name = name[:-8]

	zload(file,name)
	cmd.hide('everything',name)
	
	if native is not None:
		cmd.align(name,native)	
		cmd.zoom(native)

	useRosettaRadii()

	cavselname  = name+"cavities"
	protselname = name+"protein"

	cmd.select(cavselname, "resn CAV and b > 0.1 and %s"%(name) )
	cmd.select(protselname,"(not resn CAV) and %s"%(name) )

	useTempRadii(cavselname)
	useOccColors(cavselname)
	cmd.color("white",protselname)

	cmd.show('spheres', cavselname )
	cmd.show("cartoon",protselname)
	cmd.show("lines",protselname)

	cmd.select("none")
	cmd.delete("sele*")
	cmd.move('z',-50)

	return name
예제 #19
0
	def showpack(self):
		print self.toggle['sph']
		#cmd.hide('spheres','not '+self.manager.d.bupsel)
		cmd.hide('spheres')
		if self.toggle['sph']:
			self.toggle['sph'] = False
			return
		fr = self.rnat.obj+" and name n+ca+c and resi %i-%i"%(self.rnat.resi-10,self.rnat.resi+10)		
		to = self.rdes.obj+" and name n+ca+c and resi %i-%i"%(self.rdes.resi-10,self.rdes.resi+10)
		cmd.align(fr,to)
		cmd.center(self.rdes.sel()+" or "+self.rnat.sel())
		#cmd.show('sticks',self.rnat.sel())
		cmd.show('spheres',"byres ((not "+self.rnat.obj+") within 6 of "+self.rdes.sel()+")")
		self.toggle['sph'] = True
예제 #20
0
def loadPackingPDB(file, name=None, native=None):
    """
    usage: loadPackingPDB <file> , [<name for object>]
    loads a foo_packing.pdb file and colors it all pretty-like
    creates two selections along with the loaded object called
    NAMEcavities and NAMEprotein which are the heteratoms representing
    holes and everything else, respectively. Names can get pretty long,
    by pymol lets you do good stuff like "select NA*cav*", which will
    match a selection called NAMEISREALLYLONGcavities.
    """

    if name is None:
        name = name = os.path.basename(file)
    if name.endswith('.gz'):
        name = name[:-3]
    if name.endswith('.pdb'):
        name = name[:-4]
    if name.endswith('.'):
        name = name[:-1]
    if name.endswith("_packing"):
        name = name[:-8]

    zload(file, name)
    cmd.hide('everything', name)

    if native is not None:
        cmd.align(name, native)
        cmd.zoom(native)

    useRosettaRadii()

    cavselname = name + "cavities"
    protselname = name + "protein"

    cmd.select(cavselname, "resn WSS and %s" % (name))
    cmd.select(protselname, "(not resn WSS) and %s" % (name))

    useTempRadii(cavselname)
    useOccColors(cavselname)
    cmd.color("white", protselname)

    cmd.show('spheres', cavselname)
    cmd.show("cartoon", protselname)
    cmd.show("lines", protselname)

    cmd.select("none")
    cmd.delete("sele*")
    cmd.move('z', -50)

    return name
예제 #21
0
    def testAlignMissingCoords(self):
        filename = self.datafile('1t46-frag.pdb')

        cmd.load(filename, 'm1')
        cmd.remove('m1 & resi 600-605')
        cmd.load(filename, 'm1', state=2)

        cmd.load(filename, 'm2')
        cmd.remove('m2 & resi 620-625')
        cmd.load(filename, 'm2', state=2)

        cmd.align('m1', 'm2', object='aln', mobile_state=1, target_state=1, cycles=0)

        self.assertIn('aln', cmd.get_names())
예제 #22
0
    def testGetRawAlignment(self):
        from collections import defaultdict
        cmd.fab('ACDEGGKLMN', 'm1')
        cmd.fab('CDEFFGGK', 'm2')
        cmd.fab('ASDEKLMNFY', 'm3')
        cmd.align('m2 & guide', 'm1 & guide', cycles=0, object='aln')
        cmd.align('m3 & guide', 'm1 & guide', cycles=0, object='aln')
        cmd.disable('m2')
        # expecting alignment:
        # m1 ACDE--GGKLMN--
        # m2 -CDEFFGGK-----
        # m3 ASDE----KLMQFY
        guideids = defaultdict(list)
        cmd.iterate('guide', 'guideids[model].append(index)', space=locals())
        idx = lambda m, i: (m, guideids[m][i])
        aln_expect = [
            [idx('m1', 0), idx('m3', 0)],
            [idx('m1', 1), idx('m2', 0),
             idx('m3', 1)],
            [idx('m1', 2), idx('m2', 1),
             idx('m3', 2)],
            [idx('m1', 3), idx('m2', 2),
             idx('m3', 3)],
            [
                idx('m1', 4),
                idx('m2', 5),
            ],
            [
                idx('m1', 5),
                idx('m2', 6),
            ],
            [idx('m1', 6), idx('m2', 7),
             idx('m3', 4)],
            [idx('m1', 7), idx('m3', 5)],
            [idx('m1', 8), idx('m3', 6)],
            [idx('m1', 9), idx('m3', 7)],
        ]
        dictify = lambda aln: [dict(col) for col in aln]
        aln_expect = dictify(aln_expect)

        aln = cmd.get_raw_alignment('aln', 0)
        self.assertEqual(dictify(aln), aln_expect)

        # remove m2 from alignment
        for d in aln_expect:
            d.pop('m2', None)

        aln = cmd.get_raw_alignment('aln', 1)
        self.assertEqual(dictify(aln), aln_expect)
예제 #23
0
def ie_build_file(fname, align='true', ortho='true', hide='true',
                  zoom='true', col='[0.5, 0.5, 0.5]', scale='1'):
    if to_bool(ortho):
        cmd.set('orthoscopic', 'true')
    cmd.load(fname)
    if to_bool(align):
        object_list = cmd.get_names()
        target = object_list.pop()
        for obj in object_list:
            cmd.align(obj, target)
    if to_bool(hide):
        cmd.hide('everything')
    ie_build_all(col, scale)
    if to_bool(zoom):
        cmd.zoom()
예제 #24
0
def prepare_data(arg1):
    cmd.load("%s_r_b.pdb" % arg1, zoom=0)
    cmd.load("%s_l_b.pdb" % arg1, zoom=0)
    cmd.load("%s_r_u.pdb" % arg1, zoom=0)
    cmd.load("%s_l_u.pdb" % arg1, zoom=0)

    save_surface("%s_r_b" % arg1)
    save_surface("%s_l_b" % arg1)
    save_surface("%s_r_u" % arg1)
    save_surface("%s_l_u" % arg1)

    cmd.align("%s_r_b" % arg1, "%s_r_u" % arg1, object="ra")
    cmd.align("%s_l_b" % arg1, "%s_l_u" % arg1, object="la")
    cmd.save("receptor.aln", "ra")
    cmd.save("ligand.aln", "la")
예제 #25
0
 def testSaveAlnNucleic(self):
     cmd.load(self.datafile('1rna.cif'))
     cmd.create('m1', 'chain A and not resi 6-7')
     cmd.create('m2', 'chain B')
     cmd.alter('m1 and resi 1', 'resn = "DT"')  # mimic DNA
     cmd.alter('m2 and resi 20', 'resn = "UNK"')  # mimic nonstd residue
     cmd.align('m1', 'm2', cycles=0, object='aln')
     with testing.mktemp('.aln') as filename:
         cmd.save(filename)
         with open(filename) as handle:
             lines = list(handle)
     self.assertEqual(lines[0].split(), ['CLUSTAL'])
     self.assertEqual(lines[1].split(), [])
     self.assertEqual(lines[2].split(), ['m1', 'TUAUA--UAUAUAA'])
     self.assertEqual(lines[3].split(), ['m2', 'UUAUA?AUAUAUAA'])
예제 #26
0
 def testSaveAlnNucleic(self):
     cmd.load(self.datafile('1rna.cif'))
     cmd.create('m1', 'chain A and not resi 6-7')
     cmd.create('m2', 'chain B')
     cmd.alter('m1 and resi 1', 'resn = "DT"') # mimic DNA
     cmd.alter('m2 and resi 20', 'resn = "UNK"') # mimic nonstd residue
     cmd.align('m1', 'm2', cycles=0, object='aln')
     with testing.mktemp('.aln') as filename:
         cmd.save(filename)
         with open(filename) as handle:
             lines = list(handle)
     self.assertEqual(lines[0].split(), ['CLUSTAL'])
     self.assertEqual(lines[1].split(), [])
     self.assertEqual(lines[2].split(), ['m1', 'TUAUA--UAUAUAA'])
     self.assertEqual(lines[3].split(), ['m2', 'UUAUA?AUAUAUAA'])
예제 #27
0
def return_aligned_res():
    cmd.align("thermo", "meso", object='aln')
    raw_aln = cmd.get_raw_alignment('aln')
    idx2resi = {}
    cmd.iterate('aln',
                'idx2resi[model, index] = resi',
                space={'idx2resi': idx2resi})
    raw_res = []
    for idx1, idx2 in raw_aln:
        raw_res.append((idx2resi[idx1], idx2resi[idx2]))
    aligned_res = []
    for (a, b) in raw_res:
        if (a, b) not in aligned_res:
            aligned_res.append((a, b))
    return aligned_res
예제 #28
0
def alignallrms(sele):
    r = {}
    for i in cmd.get_object_list():
        r[i] = cmd.align("fr52re", i)[0]
    for k, v in r.items():
        if v < 2:
            print k, v
예제 #29
0
def sa(intra=False, rainbow=True):
    """
  Superimpose all open models onto the first one.
  This may not work well with selections.
  Option intra can be set to True to enable intra_fit first, for working with multi-state (nmr) pdbs.
  [Thanks to Kyle Beauchamp for this one]
  """
    AllObj = cmd.get_names("all")
    for x in AllObj:
        print(AllObj[0], x)
        if intra == True:
            cmd.intra_fit(x)
        if rainbow == True:
            cmd.util.chainbow(x)
        cmd.align(x, AllObj[0])
        cmd.zoom()
예제 #30
0
파일: ribovis.py 프로젝트: ribokit/RiboVis
def sa(intra=False,rainbow=True):
  """
  Superimpose all open models onto the first one.
  This may not work well with selections.
  Option intra can be set to True to enable intra_fit first, for working with multi-state (nmr) pdbs.
  [Thanks to Kyle Beauchamp for this one]
  """
  AllObj=cmd.get_names("all")
  for x in AllObj:
    print(AllObj[0],x)
    if intra==True:
      cmd.intra_fit(x)
    if rainbow==True:
      cmd.util.chainbow(x)
    cmd.align(x,AllObj[0])
    cmd.zoom()
예제 #31
0
    def drawAnnote(self, axis, x, y, annote):

        if (x, y) in self.drawnAnnotations:
            markers = self.drawnAnnotations[(x, y)]
            for m in markers:
                m.set_visible(not m.get_visible())
            self.axis.figure.canvas.draw()

        else:
            """
           Mark data point and show data
           """
            t = axis.text(
                x,
                y,
                "(%3.2f, %3.2f) - %s" % (x, y, annote),
            )
            m = axis.scatter([x], [y], marker='d', c='r', zorder=100)
            self.drawnAnnotations[(x, y)] = (t, m)
            self.axis.figure.canvas.draw()

        # hide previous structures and load decoy
        # since native was loaded already, colour is always different
        cmd.hide("all")
        cmd.load(self.native_name + '/' + annote + '.pdb')
        # show, align, and zoom
        cmd.show("cartoon", self.native_name + ", " + annote)
        result = cmd.align(self.native_name, annote)
        cmd.zoom(self.native_name)
        print("Align of {} and {}, rmsd: {}".format(self.native_name, annote,
                                                    result[0]))
예제 #32
0
def align_all( subset = [] ):
  """
  Superimpose all open models onto the first one.
  This may not work well with selections.
  """
  print """This returns a list with 7 items:

    RMSD after refinement
    Number of aligned atoms after refinement
    Number of refinement cycles
    RMSD before refinement
    Number of aligned atoms before refinement
    Raw alignment score
    Number of residues aligned """

  AllObj=cmd.get_names("all")
  for x in AllObj[1:]:
    #print(AllObj[0],x)
    subset_tag = ''
    if isinstance( subset, int ):
      subset_tag = ' and resi %d' % subset
    elif isinstance( subset, list ) and len( subset ) > 0:
      subset_tag = ' and resi %d' % (subset[0])
      for m in range( 1,len(subset)): subset_tag += '+%d' % subset[m]
    elif isinstance( subset, str ) and len( subset ) > 0:
      subset_tag = ' and %s' % subset
    values = cmd.align(x+subset_tag,AllObj[0]+subset_tag)
    print AllObj[0], x, ' '.join([str(v) for v in values]), '-- RMSD', values[3], ' of ', values[6], 'residues'
    cmd.zoom()
예제 #33
0
def align_all( subset = [] ):
  """
  Superimpose all open models onto the first one.
  This may not work well with selections.

  This function is probably taken from https://daslab.stanford.edu/site_data/docs_pymol_rhiju.pdf
  """
  print("""This returns a list with 7 items:

    RMSD after refinement
    Number of aligned atoms after refinement
    Number of refinement cycles
    RMSD before refinement
    Number of aligned atoms before refinement
    Raw alignment score
    Number of residues aligned """)

  AllObj=cmd.get_names("all")
  for x in AllObj[1:]:
    #print(AllObj[0],x)
    subset_tag = ''
    if isinstance( subset, int ):
      subset_tag = ' and resi %d' % subset
    elif isinstance( subset, list ) and len( subset ) > 0:
      subset_tag = ' and resi %d' % (subset[0])
      for m in range( 1,len(subset)): subset_tag += '+%d' % subset[m]
    elif isinstance( subset, str ) and len( subset ) > 0:
      subset_tag = ' and %s' % subset
    values = cmd.align(x+subset_tag,AllObj[0]+subset_tag)
    print(AllObj[0], x, ' '.join([str(v) for v in values]), '-- RMSD', values[3], ' of ', values[6], 'residues')
    cmd.zoom()
예제 #34
0
	def load(self):
		self.manager.d = self
		self.manager.m = None
		self.manager.m = None # to also set prevm = None		
		# cmd.delete(self.manager.prevd.obj)
		# cmd.delete(self.manager.prevd.pid)
		# print self.manager.d.obj
		# print self.manager.prevd.obj		
		# sys.exit()
		cmd.delete("all")
		cmd.load(self.getloadname(),self.obj,1)
		cmd.remove(self.obj+" and not chain A")
		cmd.fetch(self.pid)
		cmd.remove("het or hydro")
		cmd.color('gray',self.pid+' and elem C')
		self.scores['rms'] = cmd.align(self.pid,self.obj+" and chain A")[0]
		cmd.hide('ev')
		cmd.show('lines')
		cmd.show("car")
		#cmd.disable(self.pid)
		redopent(self.obj)
		self.recalc_design_pos()
		self.read_data_dir('avg_deg')
		self.read_data_dir('ddG')
		self.read_data_dir('rot_boltz')
		self.read_bup()
		self.read_tot_scores()
		self.read_res_scores()
		cmd.orient(self.obj+" or pnt*")
		self.manager.m = self.remembermm
		if self.manager.m: self.manager.m.focus()
		if self.remembermv: cmd.set_view(self.remembermv)
예제 #35
0
def align_all(subset=[]):
    """
  Superimpose all open models onto the first one.
  This may not work well with selections.
  This function is taken from rnapdbtool(:P) and before the function is probably taken form: https://daslab.stanford.edu/site_data/docs_pymol_rhiju.pdf
  """
    print("""This returns a list with 7 items:
    RMSD after refinement
    Number of aligned atoms after refinement
    Number of refinement cycles
    RMSD before refinement
    Number of aligned atoms before refinement
    Raw alignment score
    Number of residues aligned """)

    AllObj = cmd.get_names("all")
    for x in AllObj[1:]:
        #print(AllObj[0],x)
        subset_tag = ''
        if isinstance(subset, int):
            subset_tag = ' and resi %d' % subset
        elif isinstance(subset, list) and len(subset) > 0:
            subset_tag = ' and resi %d' % (subset[0])
            for m in range(1, len(subset)):
                subset_tag += '+%d' % subset[m]
        elif isinstance(subset, str) and len(subset) > 0:
            subset_tag = ' and %s' % subset
        values = cmd.align(x + subset_tag, AllObj[0] + subset_tag)
        print(AllObj[0], x, ' '.join([str(v) for v in values]), '-- RMSD',
              values[3], ' of ', values[6], 'residues')
        cmd.zoom()
예제 #36
0
def getnative():
    v = cmd.get_view()
    nats = []
    for obj in cmd.get_object_list():
        if len(obj) == 4:
            nats.append(obj)
            continue
        pid = obj[:4]
        if pid in nats:
            continue
        print "fetching native", pid
        cmd.fetch(pid)
        cmd.remove(pid + " and not chain A")
        cmd.remove(pid + " and resn HOH")
        cmd.align(pid, obj)
    cmd.set_view(v)
예제 #37
0
def align_all(target=None,mobile_selection='name ca',target_selection='name ca',cutoff=2, cycles=5,cgo_object=0):
  """
  Aligns all models in a list to one target

  usage:
    align_all [target][target_selection=name ca][mobile_selection=name ca][cutoff=2][cycles=5][cgo_object=0]
        where target specifies the model id you want to align all others against,
        and target_selection, mobile_selection, cutoff and cycles are options
        passed to the align command.

    By default the selection is all C-alpha atoms and the cutoff is 2 and the
    number of cycles is 5.
    Setting cgo_object to 1, will cause the generation of an alignment object for
    each object.  They will be named like <object>_on_<target>, where <object> and
    <target> will be replaced by the real object and target names.

    Example:
      align_all target=name1, mobile_selection=c. b & n. n+ca+c+o,target_selection=c. a & n. n+ca+c+o

  """
  cutoff = int(cutoff)
  cycles = int(cycles)
  cgo_object = int(cgo_object)

  object_list = cmd.get_names()
  object_list.remove(target)

  rmsd = {}
  rmsd_list = []
  for i in range(len(object_list)):
    if cgo_object:
      objectname = 'align_%s_on_%s' % (object_list[i],target)
      rms = cmd.align('%s & %s'%(object_list[i],mobile_selection),'%s & %s'%(target,target_selection),cutoff=cutoff,cycles=cycles,object=objectname)
    else:
      rms = cmd.align('%s & %s'%(object_list[i],mobile_selection),'%s & %s'%(target,target_selection),cutoff=cutoff,cycles=cycles)

    rmsd[object_list[i]] = rms[0]
    rmsd_list.append((rms[0],object_list[i]))

  rmsd_list.sort()
# loop over dictionary and print out matrix of final rms values
  print "Aligning against:",target
  for object_name in object_list:
    print "%s: %6.3f" % (object_name,rmsd[object_name])

  for r in rmsd_list:
    print "%6.3f  %s" % r
예제 #38
0
def bssa(
    sel1,
    sel2,
    polymer1="polymer",
    polymer2="polymer",
    radius=4,
    method="overlap",
    verbose=1,
):
    """
    Bind site similarity analysis.

    Align the sequence of both selections and compute similarity
    coefficients between two sites.

    OPTIONS
        sel1        Selection or object 1.
        sel2        Selection or object 2.
        polymer1    protein of sel1.
        polymer2    protein of sel2.
        radius      Radius to look for nearby aminoacids.
        method      'overlap' or 'sorensen–dice'

    EXAMPLES
        bssa *CS.000_*, *CS.002_*, radius=4
        bssa *D.001*, *D.002*, polymer1='obj1', polymer2='obj2'
        bssa 6y84.Bs.001, 6y84.B.004, method=sorensen-dice
    """

    sel1 = f"(polymer and ({polymer1})) within {radius} of ({sel1})"
    sel2 = f"(polymer and ({polymer2})) within {radius} of ({sel2})"
    pm.align(sel1, sel2, object='aln')

    n1 = pm.count_atoms(sel1)
    n2 = pm.count_atoms(sel2)
    inter = len(pm.get_raw_alignment('aln'))
    pm.delete('aln')

    if method == "overlap":
        coef = inter / min(n1, n2)
    elif method == "sorensen-dice":
        coef = 2 * inter / (n1 + n2)
    else:
        raise Exception("Not supported method.")
    if verbose:
        print("Similarity coefficient =", coef)
    return coef
예제 #39
0
 def superpose_in_pymol(self,
                        mobile_selection,
                        fixed_selection,
                        save_superposed_structure=True,
                        output_directory=None):
     """
     Superpose 'mobile' to 'fixed' in PyMOL.
     """
     if not output_directory:
         output_directory = self.pymod.structures_dirpath
     if hasattr(cmd, "super"):  # 'super' is sequence-independent.
         cmd.super(mobile_selection, fixed_selection)
     else:  # PyMOL 0.99 does not have 'cmd.super'.
         cmd.align(mobile_selection, fixed_selection)
     if save_superposed_structure:
         cmd.save(os.path.join(output_directory, mobile_selection + ".pdb"),
                  mobile_selection)
예제 #40
0
def redoA(sel="not sub", N=None):
    cmd.delete("sub*")
    cmd.hide("ev", sel + " and not chain A")
    v = cmd.get_view()
    chains = list(set(a.chain for a in cmd.get_model("name ca").atom))
    chains.sort()
    if N:
        chains = chains[:N]
    for c in chains:
        if c == "A":
            continue
        cmd.create("sub" + c, sel + " and chain A")
        cmd.align("sub" + c, sel + " and chain " + c)
        cmd.alter("sub" + c, "chain = '%s'" % c)
    color_by_chain()
    cmd.set_view(v)
    print charge(sel + " and chain A")
def align_all(cycles=5, filename="_rmsd_.csv"):
    """
    Args:

        cycles (int): maximum number of outlier rejection cycles {default: 5}

    Returns:

        Prints a table of ref vs models with 7 items:

        RaR  RMSD after refinement
        #AA  Number of aligned atoms after refinement
        CoR  Number of refinement cycles
        RbR  RMSD before refinement
        #AbR Number of aligned atoms before refinement
        RS   Raw alignment score
        AR   Number of residues aligned 

        and saves the table to filename as csv

    old version:

          1_solution_0_rpr 1_santalucia_1_rpr 5.60600471496582 958 4 5.763411521911621 974 416.0 46 -- RMSD 5.76  of  46 residues

"""
    molecules = cmd.get_names_of_type("object:molecule")
    ref = molecules.pop(0)
    print("""
    RaR  RMSD after refinement
    #AA  Number of aligned atoms after refinement
    CoR  Number of refinement cycles
    RbR  RMSD before refinement
    #AbR Number of aligned atoms before refinement
    RS   Raw alignment score
    AR   Number of residues aligned 
    """)
    report = []
    header = 'Ref                  Model                RaR  #AA  CoR  RbR  #AbR RS   AR'
    print(header)
    txt = 'Ref,Model,RMSD after refinement,Number of aligned atoms after refinement, Number of refinement cycles, RMSD before refinement, Number of aligned atoms before refinement, Raw alignment score, Number of residues aligned\n'
    for molecule in molecules:
        values = cmd.align(molecule, ref, cycles=cycles)
        l = ([
            ref[:20].ljust(20), molecule[:20].ljust(20),
            str(round(values[0], 2)).ljust(4),
            str(round(values[1], 2)).ljust(4),
            str(round(values[2], 2)).ljust(4),
            str(round(values[3], 2)).ljust(4),
            str(round(values[4], 2)).ljust(4),
            str(round(values[5])).ljust(4),
            str(round(values[6], 2)).ljust(4)
        ])
        print(' '.join(l))
        txt += ','.join([x.strip() for x in l]) + '\n'
        report.append([ref, molecule, values[3], values[6]])

    with open(filename, 'w') as f:
        f.write(txt)
예제 #42
0
 def testAlign(self):
     cmd.load(self.datafile("1oky-frag.pdb"), "m1")
     cmd.load(self.datafile("1t46-frag.pdb"), "m2")
     cycles = 2
     r = cmd.align("m1", "m2", object="aln", cycles=cycles, transform=0)
     self.assertAlmostEqual(r[0], 1.52563, delta=1e-4)
     self.assertEqual(r[1], 177)
     self.assertEqual(r[1], cmd.count_atoms("aln") / 2)
     self.assertEqual(r[2], cycles)
예제 #43
0
def superalign(target, ligand_recogniser):
    receptors = cmd.get_names(selection='not *{}*'.format(ligand_recogniser))
    cmd.create('target', '{}'.format(target))

    for r in receptors:
        ligands = cmd.get_names(
            selection='{}_*{}*'.format(r, ligand_recogniser))
        for l in ligands:
            cmd.create('{}_superaligned'.format(l), 'None')
            cmd.create('TMP', '{} or {}'.format(r, l))
            cmd.align('TMP and name ca', 'target')
            #            states = cmd.count_states('{}_superaligned'.format(r))
            #            states += 1
            #            cmd.create('{}_superaligned'.format(r), 'TMP and resname UNL', '0', '{}'.format(states))
            cmd.create('{}_superaligned'.format(l), 'TMP and resname UNL')
            cmd.delete('TMP')
            cmd.delete('{}'.format(l))
        cmd.delete('{}'.format(r))
예제 #44
0
 def testAlign(self):
     cmd.load(self.datafile("1oky-frag.pdb"), "m1")
     cmd.load(self.datafile("1t46-frag.pdb"), "m2")
     cycles = 2
     r = cmd.align("m1", "m2", object="aln", cycles=cycles, transform=0)
     self.assertAlmostEqual(r[0], 1.52563, delta=1e-4)
     self.assertEqual(r[1], 177)
     self.assertEqual(r[1], cmd.count_atoms("aln") / 2)
     self.assertEqual(r[2], cycles)
예제 #45
0
def join_states(name, selection='all', discrete=-1, zoom=0, quiet=1):
    '''
DESCRIPTION

    The reverse of split_states

ARGUMENTS

    name = string: name of object to create or modify
 
    selection = string: atoms to include in the new object

    discrete = -2: match atoms by sequence alignment
    discrete = -1: Assume identical input objects (matching all atom
        identifiers) but also check for missing atoms and only include atoms
        that are present in all input objects {default}
    discrete = 0: Assume identical input objects
    discrete = 1: Input object may be (totally) different
    '''
    discrete, quiet = int(discrete), int(quiet)
    if discrete == -2:
        _assert_package_import()
        from .selecting import wait_for
        aln_obj = cmd.get_unused_name('_')
    models = cmd.get_object_list('(' + selection + ')')
    for i in range(len(models)):
        if discrete == -1 and i > 0:
            cmd.remove('(%s) and not (alt A+ and (%s) in (%s))' %
                       (name, name, models[i]))
            cmd.create(name, '(%s) in (%s)' % (models[i], name), 1, i + 1, 0,
                       0, quiet)
        elif discrete == -2 and i > 0:
            cmd.align(models[i], name, cycles=0, transform=0, object=aln_obj)
            wait_for(aln_obj)
            cmd.remove('(%s) and not (%s)' % (name, aln_obj))
            cmd.create(name, name, 1, i + 1, 0, 0, quiet)
            cmd.update(name, '(%s) and (%s)' % (models[i], aln_obj), i + 1, 1,
                       0, quiet)
            cmd.delete(aln_obj)
        else:
            cmd.create(name, models[i], 1, i + 1, discrete == 1, 0, quiet)
    if int(zoom):
        cmd.zoom(name, state=0)
예제 #46
0
def align_all( subset = [] ):
  """
  Superimpose all open models onto the first one.
  This may not work well with selections.
  """
  AllObj=cmd.get_names("all")
  for x in AllObj[1:]:
    print(AllObj[0],x)

    subset_tag = ''
    if isinstance( subset, int ):
      subset_tag = ' and resi %d' % subset
    elif isinstance( subset, list ) and len( subset ) > 0:
      subset_tag = ' and resi %d' % (subset[0])
      for m in range( 1,len(subset)): subset_tag += '+%d' % subset[m]
    elif isinstance( subset, str ) and len( subset ) > 0:
      subset_tag = ' and %s' % subset
    cmd.align(x+subset_tag,AllObj[0]+subset_tag)
    cmd.zoom()
예제 #47
0
    def testAlignMissingCoords(self):
        filename = self.datafile('1t46-frag.pdb')

        cmd.load(filename, 'm1')
        cmd.remove('m1 & resi 600-605')
        cmd.load(filename, 'm1', state=2)

        cmd.load(filename, 'm2')
        cmd.remove('m2 & resi 620-625')
        cmd.load(filename, 'm2', state=2)

        cmd.align('m1',
                  'm2',
                  object='aln',
                  mobile_state=1,
                  target_state=1,
                  cycles=0)

        self.assertIn('aln', cmd.get_names())
예제 #48
0
def diff(sele1, sele2, byres=1, name=None, operator='in', quiet=0):
    '''
DESCRIPTION

    Difference between two molecules

ARGUMENTS

    sele1 = string: atom selection

    sele2 = string: atom selection

    byres = 0/1: report residues, not atoms (does not affect selection)
    {default: 1}

    operator = in/like/align: operator to match atoms {default: in}

SEE ALSO

    symdiff
    '''
    byres, quiet = int(byres), int(quiet)
    if name is None:
        name = cmd.get_unused_name('diff')
    if operator == 'align':
        alnobj = cmd.get_unused_name('__aln')
        cmd.align(sele1, sele2, cycles=0, transform=0, object=alnobj)
        sele = '(%s) and not %s' % (sele1, alnobj)
        cmd.select(name, sele)
        cmd.delete(alnobj)
    else:
        sele = '(%s) and not ((%s) %s (%s))' % (sele1, sele1, operator, sele2)
        cmd.select(name, sele)
    if not quiet:
        if byres:
            seleiter = 'byca ' + name
            expr = 'print "/%s/%s/%s/%s`%s" % (model,segi,chain,resn,resi)'
        else:
            seleiter = name
            expr = 'print "/%s/%s/%s/%s`%s/%s" % (model,segi,chain,resn,resi,name)'
        cmd.iterate(seleiter, expr)
    return name
예제 #49
0
def diff(sele1, sele2, byres=1, name=None, operator='in', quiet=0):
    '''
DESCRIPTION

    Difference between two molecules

ARGUMENTS

    sele1 = string: atom selection

    sele2 = string: atom selection

    byres = 0/1: report residues, not atoms (does not affect selection)
    {default: 1}

    operator = in/like/align: operator to match atoms {default: in}

SEE ALSO

    symdiff
    '''
    byres, quiet = int(byres), int(quiet)
    if name is None:
        name = cmd.get_unused_name('diff')
    if operator == 'align':
        alnobj = cmd.get_unused_name('__aln')
        cmd.align(sele1, sele2, cycles=0, transform=0, object=alnobj)
        sele = '(%s) and not %s' % (sele1, alnobj)
        cmd.select(name, sele)
        cmd.delete(alnobj)
    else:
        sele = '(%s) and not ((%s) %s (%s))' % (sele1, sele1, operator, sele2)
        cmd.select(name, sele)
    if not quiet:
        if byres:
            seleiter = 'byca ' + name
            expr = 'print "/%s/%s/%s/%s`%s" % (model,segi,chain,resn,resi)'
        else:
            seleiter = name
            expr = 'print "/%s/%s/%s/%s`%s/%s" % (model,segi,chain,resn,resi,name)'
        cmd.iterate(seleiter, expr)
    return name
예제 #50
0
def align_all(subset=[]):
    """
  Superimpose all open models onto the first one.
  This may not work well with selections.
  """
    AllObj = cmd.get_names("all")
    for x in AllObj[1:]:
        print(AllObj[0], x)

        subset_tag = ''
        if isinstance(subset, int):
            subset_tag = ' and resi %d' % subset
        elif isinstance(subset, list) and len(subset) > 0:
            subset_tag = ' and resi %d' % (subset[0])
            for m in range(1, len(subset)):
                subset_tag += '+%d' % subset[m]
        elif isinstance(subset, str) and len(subset) > 0:
            subset_tag = ' and %s' % subset
        cmd.align(x + subset_tag, AllObj[0] + subset_tag)
        cmd.zoom()
예제 #51
0
def rmsdx(cycles=5, matrix_fn='matrix.txt'):
    """
    Args:

    cycles (int): refinement cycles of PyMOL align, default: 5
    matrix_fn (string): a file to save the matrix
                        matrix is pretty much saved in space-separated values 
                        so you can load it to pandas with

                        df = pd.read_csv('matrix.txt', sep=' ', index_col=False)
                        df = df.set_index(df.columns)
                        print(df)
                                      Bact_7DCO_S  Bact_5gm6_S
                        Bact_7DCO_S         0.000        0.562

    Returns:

    string: matrix 
            and matrix_fn file ;-)

    """
    models = cmd.get_names_of_type("object:molecule")
    print(' # of models:', len(models))

    f = open(matrix_fn, 'w')
    #t = '# ' # for numpy
    t = ''  # for pandas
    for r1 in models:
        # print r1,
        t += str(r1) + ' '  # here ' ' could be changed to , or \t
    t = t.strip() + '\n'

    c = 1
    for r1 in models:
        for r2 in models:
            if r1 == r2:
                rmsd = 0
            else:
                print(r1, r2)
                values = cmd.align(r1, r2, cycles=cycles)
                # RaR [1]       RbR [3]
                # RaR  #AA  CoR               RbR  #AbR RS   AR'
                # (0.668652355670929, 241, 5, 1.1646124124526978, 293, 199.0, 38)
                rmsd = round(values[0], 3)
            t += str(rmsd) + ' '
        #print('...', c, r1)
        c += 1
        t += '\n'

    f.write(t)
    f.close()

    print(t.strip())  # matrix
    return t
예제 #52
0
def perform_alignment(template, test_pdb, output_file="output_rmsd.csv"):
    """
    Perform and alignment using PyMOL's python API
    """
    opened_file = open(output_file, "a")
    cmd.load(template, "template")
    cmd.load(test_pdb, "other")
    rms = cmd.align("template", "other")[0]
    to_write_row = template[0:-4] + "," + test_pdb[0:-4] + "," + str(
        rms) + "\n"
    opened_file.write(to_write_row)
    cmd.delete("other")
예제 #53
0
    def test(self):
        cmd.read_pdbstr(v_pdbstr_anisou, 'm1')

        with testing.mktemp('.mae') as maefilename:
            cmd.save(maefilename, 'm1')
            cmd.delete('*')
            cmd.load(maefilename, 'm1')

        self.assertEqual(cmd.get_pdbstr('m1'), v_pdbstr_anisou)

        cmd.read_pdbstr(v_pdbstr_rotated, 'm2')
        cmd.align('m1', 'm2')

        with testing.mktemp('.mae') as maefilename:
            cmd.save(maefilename, 'm1')
            cmd.delete('*')
            cmd.load(maefilename, 'm1')

        # Attention: Not sure if rotation is numerically stable across
        # platforms. Fuzzy comparison might be needed.
        self.assertEqual(cmd.get_pdbstr('m1'), v_pdbstr_rotated)
예제 #54
0
def join_states(name, selection="all", discrete=-1, zoom=0, quiet=1):
    """
DESCRIPTION

    The reverse of split_states

ARGUMENTS

    name = string: name of object to create or modify
 
    selection = string: atoms to include in the new object

    discrete = -2: match atoms by sequence alignment
    discrete = -1: Assume identical input objects (matching all atom
        identifiers) but also check for missing atoms and only include atoms
        that are present in all input objects {default}
    discrete = 0: Assume identical input objects
    discrete = 1: Input object may be (totally) different
    """
    discrete, quiet = int(discrete), int(quiet)
    if discrete == -2:
        from .selecting import wait_for

        aln_obj = cmd.get_unused_name("_")
    models = cmd.get_object_list("(" + selection + ")")
    for i in range(len(models)):
        if discrete == -1 and i > 0:
            cmd.remove("(%s) and not (alt A+ and (%s) in (%s))" % (name, name, models[i]))
            cmd.create(name, "(%s) in (%s)" % (models[i], name), 1, i + 1, 0, 0, quiet)
        elif discrete == -2 and i > 0:
            cmd.align(models[i], name, cycles=0, transform=0, object=aln_obj)
            wait_for(aln_obj)
            cmd.remove("(%s) and not (%s)" % (name, aln_obj))
            cmd.create(name, name, 1, i + 1, 0, 0, quiet)
            cmd.update(name, "(%s) and (%s)" % (models[i], aln_obj), i + 1, 1, 0, quiet)
            cmd.delete(aln_obj)
        else:
            cmd.create(name, models[i], 1, i + 1, discrete == 1, 0, quiet)
    if int(zoom):
        cmd.zoom(name, state=0)
예제 #55
0
    def test(self, matrix_mode):
        cmd.viewport(100,100)
        cmd.set('matrix_mode', matrix_mode)
        cmd.set('ambient', 1.0)

        cmd.read_pdbstr(v_pdbstr_anisou, 'm1', zoom=0)
        cmd.read_pdbstr(v_pdbstr_rotated, 'm2', zoom=0)
        self._rep()

        cmd.set_view(views[0])
        ref = self.get_imagearray()
        self.assertImageHasColor('yellow')

        cmd.align('m1', 'm2')
        cmd.set_view(views[1])
        self.assertImageEqual(ref, count=100, delta=1, msg='ANISOU not aligned on display')

        pdbstr = cmd.get_pdbstr('m1')
        cmd.delete('*')
        cmd.read_pdbstr(pdbstr, 'm1', zoom=0)
        self._rep()
        self.assertImageEqual(ref, count=100, msg='ANISOU not aligned in PDB')
예제 #56
0
def alignedSequence():
	if not os.path.isdir("/Users/michaelHumphrey/FilesWithSequences"):
		os.mkdir("/Users/michaelHumphrey/FilesWithSequences")
	files = glob("/Users/michaelHumphrey/homologousToOGC/*.pdb")
	files.sort()
	for i in files:
		cmd.load(i)
		protObjName = i[(len(i) - 8):]
		protObj = re.sub('\.pdb$', '', protObjName)
		alignObjectName = '%s_on_domainA' % (protObj)
		rmsd = cmd.align(protObj, 'domainA', object=alignObjectName)
		stored.residues = []
		stored.resi = []
		cmd.iterate('(%s & n. ca)' % (alignObjectName), 'stored.residues.append(resn)')
		cmd.iterate('(%s & n. ca)' % (alignObjectName), 'stored.resi.append(resi)')
		stored.resiFirstHalf = []
		stored.resiSecondHalf = []
		for rez1 in range(len(stored.resi)/2):
			stored.resiFirstHalf.append(stored.resi[rez1])
		for rez2 in range((len(stored.resi)/2), len(stored.resi)):
			stored.resiSecondHalf.append(stored.resi[rez2])
		stored.residuesFirstHalf = []
		stored.residuesSecondHalf = []
		for residues1 in range(len(stored.residues)/2):
			stored.residuesFirstHalf.append(stored.residues[residues1])
		for residues2 in range((len(stored.residues)/2), len(stored.residues)):
			stored.residuesSecondHalf.append(stored.residues[residues2])
		aminoAcids = ['ALA', 'ARG', 'ASN', 'ASP', 'CYS', 'GLN' , 'GLU', 'GLY', 'HIS', 'ILE', 'LEU', 'LYS', 'MET', 'PHE', 'PRO', 'SER', 'THR', 'TRP', 'TYR', 'VAL']
		domainAResidueCount = [0] * len(aminoAcids)
		otherPDBResiduesCount = [0] * len(aminoAcids)
		for k in range(len(stored.residuesFirstHalf)):
			for j in range(len(aminoAcids)):
				if stored.residuesFirstHalf[k] == aminoAcids[j]:
					domainAResidueCount[j] += 1
		for k in range(len(stored.residuesSecondHalf)):
			for j in range(len(aminoAcids)):
				if stored.residuesSecondHalf[k] == aminoAcids[j]:
					otherPDBResiduesCount[j] += 1
		sequencesFile = open(os.path.join("/Users/michaelHumphrey/FilesWithSequences", "sequencesFile.txt"), "a")
		sequencesFile.write('%s\t%s\n' % (alignObjectName, rmsd[0]))
		for resid1, re1, resid2, re2 in zip(stored.residuesFirstHalf, stored.resiFirstHalf, stored.residuesSecondHalf, stored.resiSecondHalf):
			sequencesFile.write("%s\t%s\t%s\t%s\n" % (resid1, re1, resid2, re2))
		sequencesFile.write('\n')
		for residues1, residues2, residues3, residues4 in zip(aminoAcids, domainAResidueCount, aminoAcids, otherPDBResiduesCount):
			sequencesFile.write("%s\t%s\t%s\t%s\n" % (residues1, residues2, residues3, residues4))
		sequencesFile.write('\n')
		sequencesFile.close()
		cmd.delete(protObj)
		cmd.delete(alignObjectName)
예제 #57
0
def gdt_ts(mobile, target, cutoffs='1 2 4 8', quiet=1):
    '''
DESCRIPTION

    Global Distance Test Total Score (GDT_TS)
    '''
    cutoffs = list(map(float, cutoffs.split()))
    quiet = int(quiet)
    mobile = '(' + mobile + ') and guide'
    target = '(' + target + ') and guide'
    ts = 0
    N = min(cmd.count_atoms(mobile), cmd.count_atoms(target))
    for cutoff in cutoffs:
        x = cmd.align(mobile, target, cutoff=cutoff, transform=0)
        p = float(x[1]) / N
        if not quiet:
            print(' GDT_TS: GDT_P%.1f = %.2f' % (cutoff, p))
        ts += p
    ts /= len(cutoffs)
    if not quiet:
        print(' GDT_TS: Total Score = %.2f' % (ts))
    return ts
예제 #58
0
def dyndom(mobile, target, window=5, domain=20, ratio=1.0, exe='', transform=1,
        quiet=1, mobile_state=1, target_state=1, match='align', preserve=0):
    '''
DESCRIPTION

    DynDom wrapper

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

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

USAGE

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

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

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

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

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

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

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

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

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

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

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

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

    if transform and fixed_name is not None:
        cmd.align(fixed_name, target)
예제 #59
0
def loadInterfacePDB(file,name=None,native=None,wt=None):

	print " Loading interface PDB %s"%(file)

	if name is None:
		name = name = os.path.basename(file)
	if name.endswith('.pdb'):
		name = name[:-4] 

	# Call Will's packing PDB loading function
	# Note: proteins will be cartoons, cavities will be spheres
	# Rosetta radii will be enabled
	name = loadPackingPDB(file,name,native)

	cavselname  = name+"cavities"
	protselname = name+"protein"
	cmd.hide("lines",protselname)

	backbone_colorlist = ['green', 'yellow', 'violet', 'cyan',    \
		   'salmon', 'lime', 'slate', 'magenta', 'orange', 'marine', \
		   'olive', 'forest', 'firebrick', 'chocolate' ]
	curr_bb_color = 0

 	carbon_colorlist = ['teal', 'wheat', 'grey', 'pink' ]
	curr_carbon_color = 0

	# Derive selections for the interface, color by chain
	cmd.select("interface", "none")
	cmd.select("heavy_interface", "none")
	selectPolarProtons("polar_protons")
	selectApolarProtons("apolar_protons")
	alphabet = list(('abcdefghijklmnopqrstuvwxyz').upper())
	for letter in alphabet:
		chainname = "chain"+letter
		cmd.select( chainname, "chain %s and not hetatm and not symbol w"%(letter) )

		# Check whether any protein atoms exist with this chain ID
		# JK Later, put in a special "non-interface" case for L/H antibody chains
		if cmd.count_atoms("chain%s"%(letter))>0:
			interfacename = "interface"+letter
			cmd.select("not_this_chain", "not hetatm and not symbol w and not %s"%(chainname) )
			cmd.select(interfacename, "byres %s and (not_this_chain around 4.0)"%(chainname) )
			cmd.select("heavy_%s"%(interfacename), "%s and not apolar_protons"%(interfacename))
			cmd.select("interface", "interface or %s"%(interfacename) )
			cmd.select("heavy_interface", "heavy_interface or heavy_%s"%(interfacename) )
			cmd.delete("not_this_chain")

			cmd.color(backbone_colorlist[curr_bb_color], chainname)
			curr_bb_color = curr_bb_color+1
			if(curr_bb_color == len(backbone_colorlist)):
				curr_bb_color = 0

			colorCPK(interfacename,carbon_colorlist[curr_carbon_color])
			curr_carbon_color = curr_carbon_color+1
			if(curr_carbon_color == len(carbon_colorlist)):
				curr_carbon_color = 0
			cmd.color("white", "%s and polar_protons"%(interfacename))

		else:
			cmd.delete(chainname)

	cmd.delete("apolar_protons")
	cmd.delete("polar_protons")

	# Show the interface in sticks, colored cpk
	#cmd.hide( "cartoon", "interface" )
	cmd.show( "sticks", "heavy_interface" )
	cmd.zoom("interface")

	cmd.show( "cartoon", "(not interface) or byres(neighbor(interface)) or byres(neighbor(byres(neighbor(interface))))" )

	# Show interface waters as small purple spheres
	cmd.select( "interface_water", "(symbol w or resn HOH) and (interface around 8.0)")
	if cmd.count_atoms("interface_water")>0:
		# Put the waters in a separate object, so that we can scale their radii
		newwatername = name+"waters"
		cmd.create(newwatername, "interface_water")
		cmd.remove("interface_water")
		cmd.color("purple", newwatername)
		cmd.show( "spheres", newwatername )
		#cmd.set( "sphere_scale", 0.5, newwatername )
		cmd.set( "sphere_scale", 0.1, newwatername )
	else:
		cmd.delete("interface_water")

	# Show interface ligands as pink sticks
	cmd.select( "interface_hetero", "(not symbol w and not resn HOH) and (hetatm and not symbol w and not resn WSS) and (interface around 4.5)")
	if cmd.count_atoms("interface_hetero")>0:
		cmd.color("pink", "interface_hetero")
		cmd.show( "sticks", "interface_hetero" )
	else:
		cmd.delete("interface_hetero")

	cmd.select("none")
   	cmd.load( wt, "wt" ) 
   	cmd.create( "wt_A", "wt and chain A" ) 
   	cmd.create( "wt_B", "wt and chain B" ) 
   	cmd.select("none") 
   	cmd.create( "des_A", "not wt and chain A" ) 
   	cmd.show( "surface", "des_A" ) 
   	cmd.create( "des_B", "not wt and chain B") 
   	cmd.show( "surface", "des_B" ) 
   	cmd.align( "wt_A", "des_A" ) 
   	cmd.align( "wt_B", "des_B" ) 
#   cmd.show( "lines", "wt_A" ) 
#   cmd.show( "lines", "wt_B" ) 
  	cmd.set( "transparency", 1 ) 
	cmd.zoom("interface") 
	return name