Exemple #1
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("count", "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")
Exemple #2
0
    def testAlterState(self):
        cmd.fragment('ala')
        cmd.create('ala', 'ala', 1, 2)
        v_count = cmd.count_atoms('all')

        v_mock = [
            list(map(float, list(range(i * 3, (i + 1) * 3))))
            for i in range(v_count)
        ]

        v_xyz_1_pre = cmd.get_model('all', state=1).get_coord_list()
        v_xyz_2_pre = cmd.get_model('all', state=2).get_coord_list()

        cmd.alter_state(2,
                        'all',
                        '(x,y,z) = next(xyz_iter)',
                        space={
                            'xyz_iter': iter(v_mock),
                            'next': next
                        })

        v_xyz_1_post = cmd.get_model('all', state=1).get_coord_list()
        v_xyz_2_post = cmd.get_model('all', state=2).get_coord_list()

        self.assertEqual(v_xyz_1_post, v_xyz_1_pre)
        self.assertEqual(v_xyz_2_post, v_mock)
Exemple #3
0
def check_disulphide_criteria(pdb, resnum_i, resnum_j, f):
	selection_i = "resi " + str(resnum_i)
	selection_j = "resi " + str(resnum_j)

	for frame_i in [1, 2]:
		rotamer_i_pymol_prefix = "/" + "rotamer_" + str(resnum_i) + "_" + str(frame_i) + "///" + resnum_i + "/"

		chi1_i = cmd.get_dihedral(rotamer_i_pymol_prefix + "N", rotamer_i_pymol_prefix + "CA", rotamer_i_pymol_prefix + "CB", rotamer_i_pymol_prefix + "SG")
		theta_i = cmd.get_angle(rotamer_i_pymol_prefix + "CA", rotamer_i_pymol_prefix + "CB", rotamer_i_pymol_prefix + "SG")

		for frame_j in [1, 2]:
			rotamer_j_pymol_prefix = "/" + "rotamer_" + str(resnum_j) + "_" + str(frame_j) + "///" + resnum_j + "/"
	
			chi1_j = cmd.get_dihedral(rotamer_j_pymol_prefix + "N", rotamer_j_pymol_prefix + "CA", rotamer_j_pymol_prefix + "CB", rotamer_j_pymol_prefix + "SG")
			theta_j = cmd.get_angle(rotamer_j_pymol_prefix + "CA", rotamer_j_pymol_prefix + "CB", rotamer_j_pymol_prefix + "SG")

			chi3 = cmd.get_dihedral(rotamer_i_pymol_prefix + "CB", rotamer_i_pymol_prefix + "SG", rotamer_j_pymol_prefix + "SG", rotamer_j_pymol_prefix + "CB")

			#Energy = compute_energy(chi1_i, chi1_j, theta_i, theta_j, chi3)

			s_gamma_distance = cmd.get_distance(rotamer_i_pymol_prefix + "SG", rotamer_j_pymol_prefix + "SG")	
			if (s_gamma_distance < 3 and ((chi3 > -110 and chi3 < -60) or (chi3 > 70 and chi3 < 130))):
				print rotamer_i_pymol_prefix, rotamer_j_pymol_prefix, s_gamma_distance, chi3
				f.write("%s\t%s\t%f\t%f\n" % (rotamer_i_pymol_prefix, rotamer_j_pymol_prefix, s_gamma_distance, chi3))
				rotamer_i = "rotamer_" + str(resnum_i) + "_" + str(frame_i)
				rotamer_j = "rotamer_" + str(resnum_j) + "_" + str(frame_j)
				cmd.enable(rotamer_i)
				cmd.enable(rotamer_j)
				cmd.distance(rotamer_i_pymol_prefix + "SG", rotamer_j_pymol_prefix + "SG")
				cmd.create(rotamer_i + rotamer_j, rotamer_i_pymol_prefix + "or" + rotamer_j_pymol_prefix)
Exemple #4
0
def split_chains(selection='(all)', prefix=None):
    '''
DESCRIPTION

    Create a single object for each chain in selection

SEE ALSO

    split_states, http://pymolwiki.org/index.php/Split_object
    '''
    count = 0
    models = cmd.get_object_list('(' + selection + ')')
    for model in models:
        for chain in cmd.get_chains('(%s) and model %s' % (selection, model)):
            if chain == '':
                chain = "''"
            count += 1
            if not prefix:
                name = '%s_%s' % (model, chain)
            else:
                name = '%s%04d' % (prefix, count)
            cmd.create(
                name,
                '(%s) and model %s and chain %s' % (selection, model, chain))
        cmd.disable(model)
Exemple #5
0
    def Update(self):
        
        try:
            # Copy the initial protein (Frame 1) into the working state
            cmd.create(self.TargetObj, self.TargetName, 1, self.State)
            cmd.refresh()

            # Display the last frame
            cmd.frame(self.State)
            #print "Switched to frame " + str(self.State)

        except:
            self.CriticalError("Object " + str(self.TargetName) + " no longer exists")
        
        
        if not self.UpdateLigandAnchorPoint() and not self.UpdateLigandFlexibility():
        
            self.selSideChains = self.UpdateSideChainConformations()
            
            if self.WriteOutLigand() or self.EditView() or \
               self.top.UpdateDataList(self.Line, self.TOP, self.top.Reference, self.dictCoord):
                self.Delete_Object()

        self.Delete_Object()
        
        return
Exemple #6
0
    def Update(self):

        try:
            # Copy the initial protein (Frame 1) into the working state
            cmd.create(self.TargetObj, self.TargetName, 1, self.State)
            cmd.refresh()

            # Display the last frame
            cmd.frame(self.State)
            #print "Switched to frame " + str(self.State)

        except:
            self.CriticalError("Object " + str(self.TargetName) +
                               " no longer exists")

        if not self.UpdateLigandAnchorPoint(
        ) and not self.UpdateLigandFlexibility():

            self.selSideChains = self.UpdateSideChainConformations()

            if self.WriteOutLigand() or self.EditView() or \
               self.top.UpdateDataList(self.Line, self.TOP, self.top.Reference, self.dictCoord):
                self.Delete_Object()

        self.Delete_Object()

        return
Exemple #7
0
def normalmodes_prody(selection, cutoff=15, first=7, last=10, guide=1,
        prefix='prody', states=7, factor=-1, quiet=1):
    '''
DESCRIPTION

    Anisotropic Network Model (ANM) analysis with ProDy.

    Based on:
    http://www.csb.pitt.edu/prody/examples/dynamics/enm/anm.html
    '''
    try:
        import prody
    except ImportError:
        print('Failed to import prody, please add to PYTHONPATH')
        raise CmdException

    first, last, guide = int(first), int(last), int(guide)
    states, factor, quiet = int(states), float(factor), int(quiet)
    assert first > 6

    if guide:
        selection = '(%s) and guide and alt A+' % (selection)
    tmpsele = cmd.get_unused_name('_')
    cmd.select(tmpsele, selection)

    f = StringIO(cmd.get_pdbstr(tmpsele))
    conf = prody.parsePDBStream(f)

    modes = prody.ANM()
    modes.buildHessian(conf, float(cutoff))
    modes.calcModes(last - first + 1)

    if factor < 0:
        from math import log
        natoms = modes.numAtoms()
        factor = log(natoms) * 10
        if not quiet:
            print(' set factor to %.2f' % (factor))

    for mode in range(first, last + 1):
        name = prefix + '%d' % mode
        cmd.delete(name)

        if not quiet:
            print(' normalmodes: object "%s" for mode %d' % (name, mode))

        for state in range(1, states+1):
            xyz_it = iter(modes[mode-7].getArrayNx3() * (factor *
                    ((state-1.0)/(states-1.0) - 0.5)))
            cmd.create(name, tmpsele, 1, state, zoom=0)
            cmd.alter_state(state, name, '(x,y,z) = xyz_it.next() + (x,y,z)',
                    space=locals())

    cmd.delete(tmpsele)

    if guide:
        cmd.set('ribbon_trace_atoms', 1, prefix + '*')
        cmd.show_as('ribbon', prefix + '*')
    else:
        cmd.show_as('lines', prefix + '*')
    def testMultifilesave(self):
        import glob

        for name in ['ala', 'gly', 'his', 'arg']:
            cmd.fragment(name)

        # multistate
        for i in range(2, 11):
            cmd.create('ala', 'ala', 1, i)

        for fmt in ['{}-{:02}.cif', '{}-{state}.cif']:
            with testing.mkdtemp() as dirname:
                cmd.multifilesave(os.path.join(dirname, fmt), 'ala', 0)
                filenames = [os.path.basename(p) for p in glob.glob(os.path.join(dirname, '*.cif'))]
                self.assertEqual(len(filenames), 10)
                self.assertTrue('ala-03.cif' in filenames)

        with testing.mkdtemp() as dirname:
            cmd.multifilesave(os.path.join(dirname, '{}.pdb'), 'a* g*')
            filenames_full = sorted(glob.glob(os.path.join(dirname, '*.pdb')))
            filenames = [os.path.basename(p) for p in filenames_full]
            self.assertEqual(filenames, ['ala.pdb', 'arg.pdb', 'gly.pdb'])

            cmd.delete('*')
            cmd.load(filenames_full[0])
            self.assertEqual(cmd.count_atoms(), 10)

            cmd.delete('*')
            cmd.load(filenames_full[1])
            self.assertEqual(cmd.count_atoms(), 24)
Exemple #9
0
def show_ref(frame):
    cmd.create("Ref_full", "resid %i and resname DMPC" % (REF_BEAD + 1))
    cmd.hide("lines", "Ref_full")
    cmd.show("spheres", "Ref_full")

    cmd.create("Ref_Headgroup", "resid %i and name P" % (REF_BEAD + 1))
    cmd.hide("lines", "Ref_Headgroup")
    cmd.show("spheres", "Ref_Headgroup")
    cmd.set("sphere_scale", 2.0, "Ref_Headgroup")
    cmd.color("orange", "Ref_Headgroup")
    cmd.set("sphere_transparency", 0.5, "Ref_Headgroup")

    position = frame.bead_coords[REF_BEAD] * 10
    x, y, z = position
    cgo_ref = [COLOR, 1.0, 0.6, 0.1, SPHERE, x, y, z, 3.0]
    cgo_ref = draw_vector(position,
                          -frame.directions[REF_BEAD],
                          cgo_obj=cgo_ref,
                          color=(1.0, 1.0, 0.22),
                          alpha=1.0)
    cmd.load_cgo(cgo_ref, "Ref_simplified")

    position = frame.bead_coords[REF_BEAD] * 10
    x, y, z = position
    cgo_ref = [COLOR, 1.0, 0.6, 0.1, SPHERE, x, y, z, 3.0]
    cgo_ref = draw_vector(position,
                          -frame.directions[REF_BEAD],
                          cgo_obj=cgo_ref,
                          color=(1.0, 1.0, 0.22),
                          alpha=1.0)
    cmd.load_cgo(cgo_ref, "Ref_simplified")
Exemple #10
0
        def save_flip_selections():
            '''Save the user-selected flips to a new PDB object.'''
            o = main.get_object(mpobj.get())
            flipkin = self.flipkin_radio.getvalue()
            reduce_obj = o.pdb['reduce']
            flipkin_obj = o.pdb[flipkin]
            userflips_obj = o.pdb['userflips']
            # Create a new userflips object even if it already exists in case
            # previous selections have been changed.
            v = cmd.get_view()
            cmd.create(userflips_obj, reduce_obj)
            cmd.set_view(v)

            for i, v in enumerate(o.views[flipkin]):
                # If reduce value and user value are different, copy the
                # coordinates from the current flipkin molecule
                if v['reduce_chk_val'].get() != v['user_chk_val'].get():
                    # Do it the hard way, by combining objects.  This is plenty
                    # fast (we typically won't have too many flips to switch)
                    # and doesn't result in atom name mismatch errors for
                    # differently protonated HIS residues the way the
                    # load_coords method does.
                    flipped_sel = '({} and chain {} and resi {})'.format(
                            flipkin_obj, v['chain'], v['resi'])
                    userflips_sel = '({} and not (chain {} and resi {}))'.format(
                            userflips_obj, v['chain'], v['resi'])
                    combined_sel = '{} or {}'.format(
                            userflips_sel, flipped_sel)
                    v = cmd.get_view()
                    cmd.create(userflips_obj, combined_sel)
                    cmd.set_view(v)
                    msg = 'added flip for {} to {}'.format(flipped_sel,
                            userflips_obj)
                    logger.debug(msg)
            o.solo_pdb('userflips')
Exemple #11
0
def findSurfaceResidues(objSel="(all)",
                        cutoff=2.5,
                        doShow=False,
                        verbose=False):
    tmpObj = "__tmp"
    cmd.create(tmpObj, objSel + " and polymer")
    if verbose != False:
        print("WARNING: I'm setting dot_solvent.  You may not care for this.")
    cmd.set("dot_solvent")
    cmd.get_area(selection=tmpObj, load_b=1)
    cmd.remove(tmpObj + " and b < " + str(cutoff))

    stored.tmp_dict = {}
    cmd.iterate(tmpObj, "stored.tmp_dict[(chain,resv)]=1")
    exposed = stored.tmp_dict.keys()
    exposed.sort()

    randstr = str(random.randint(0, 10000))
    selName = "exposed_atm_" + randstr
    if verbose != False:
        print("Exposed residues are selected in: " + selName)
    cmd.select(selName, objSel + " in " + tmpObj)
    selNameRes = "exposed_res_" + randstr
    cmd.select(selNameRes, "byres " + selName)

    if doShow != False:
        cmd.show_as("spheres", objSel + " and poly")
        cmd.color("white", objSel)
        cmd.color("red", selName)
    cmd.delete(tmpObj)
    return exposed
Exemple #12
0
def fatslim_apl_prot():
    global REF_BEAD
    setup()

    FILENAME = BILAYER_PROT
    REF_BEAD = BILAYER_PROT_REF

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

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

    # Show leaflets
    show_leaflets(frame)

    # Show stuff related to APL
    show_apl(frame)

    print("Bilayer with protein loaded!")
Exemple #13
0
	def myalign(method):
		newmobile = cmd.get_unused_name(mobile_obj + '_' + method)
		cmd.create(newmobile, mobile_obj)
		start = time.time()
		cmd.do('%s mobile=%s in %s, target=%s' % (method, newmobile, mobile, target))
		if not quiet:
			print 'Finished: %s (%.2f sec)' % (method, time.time() - start)
Exemple #14
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)]
Exemple #15
0
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')
Exemple #16
0
    def plot(self, outfile):
        ctrl_id, case_id, snp_df_sub = self.score_on_var()
        df = pd.merge(snp_df_sub, self.snps2aa, on='id')

        #pymol.finish_launching()
        cmd.reinitialize()
        cmd.fetch(self.pdb)
        cmd.alter(self.pdb, 'b = 0.5')
        cmd.show_as('cartoon', self.pdb)
        cmd.color('white', self.pdb)

        for i, row in df.iterrows():
            resi = row['structure_position']
            chain = row['chain']
            pheno = row['es']
            selec = 'snp%s' % i
            selec_atom = 'snp_atom%s' % i
            cmd.select(selec,
                       'name ca and resi %s and chain %s' % (resi, chain))
            cmd.create(selec_atom, selec)
            cmd.set("sphere_scale", 0.8)
            cmd.show('sphere', selec_atom)
            cmd.alter(selec_atom, 'b=%s' % pheno)
            cmd.spectrum("b",
                         "blue_white_red",
                         selec_atom,
                         maximum=1.0,
                         minimum=0.0)
        cmd.bg_color("white")
        cmd.zoom()
        cmd.orient()
        cmd.save('%s.pse' % outfile)
        cmd.png('%s.png' % outfile, width=2400, height=2400, dpi=300, ray=1)
Exemple #17
0
    def test_h_add_state(self):
        nheavy = 4
        nhydro = 5
        nfull = nheavy + nhydro

        cmd.fragment('gly', 'm1')
        cmd.remove('hydro')
        self.assertEqual(nheavy, cmd.count_atoms())
        cmd.h_add()
        self.assertEqual(nfull, cmd.count_atoms())

        # multi-state
        cmd.remove('hydro')
        cmd.create('m1', 'm1', 1, 2)
        cmd.create('m1', 'm1', 1, 3)
        cmd.h_add(state=2)
        self.assertEqual(nfull, cmd.count_atoms())
        self.assertEqual(nheavy, cmd.count_atoms('state 1'))
        self.assertEqual(nfull, cmd.count_atoms('state 2'))
        self.assertEqual(nheavy, cmd.count_atoms('state 3'))

        # discrete multi-state
        cmd.remove('hydro')
        cmd.create('m2', 'm1', 1, 1, discrete=1)
        cmd.create('m2', 'm2', 1, 2, discrete=1)
        cmd.create('m2', 'm2', 1, 3, discrete=1)
        self.assertEqual(nheavy * 3, cmd.count_atoms('m2'))
        cmd.h_add('m2 & state 2') # TODO , state=2)
        self.assertEqual(nfull + nheavy * 2, cmd.count_atoms('m2'))
        self.assertEqual(nheavy, cmd.count_atoms('m2 & state 1'))
        self.assertEqual(nfull, cmd.count_atoms('m2 & state 2'))
        self.assertEqual(nheavy, cmd.count_atoms('m2 & state 3'))
        cmd.h_add('m2')
        self.assertEqual(nfull * 3, cmd.count_atoms('m2'))
    def testSimple(self):
        cmd.fab('A', 'm1')
        cmd.fab('A', 'm2')
        v1 = 'foo'
        v2 = 'bar'
        v3 = 'com'
        
        # single state
        cmd.set_property('filename', v1, 'm1')
        self.assertTrue('foo' == v1)
        self.assertTrue(cmd.get_property('filename', 'm1') == v1)
        self.assertTrue(cmd.get_property('filename', 'm2') == None)

        # multiple objects
        cmd.set_property('filename', v1)
        self.assertTrue(cmd.get_property('filename', 'm2') == v1)

        # two states
        cmd.create('m1', 'm1', 1, 2)
        self.assertTrue(cmd.count_states() == 2)

        # set for all states
        cmd.set_property('filename', v1, 'm1')
        self.assertTrue(cmd.get_property('filename', 'm1', 2) == v1)

        # set for particular state
        cmd.set_property('filename', v2, 'm1', 2)
        self.assertTrue(cmd.get_property('filename', 'm1', 1) == v1)
        self.assertTrue(cmd.get_property('filename', 'm1', 2) == v2)

        # set for current state
        cmd.frame(2)
        cmd.set_property('filename', v3, 'm1', -1)
        self.assertTrue(cmd.get_property('filename', 'm1', 1) == v1)
        self.assertTrue(cmd.get_property('filename', 'm1', 2) == v3)
Exemple #19
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" )
Exemple #20
0
 def readHostFromSeleAround(self):
     try:
         stateNo = cmd.get_state()
         radius = self.seleRadius.get()
         cmd.create("host", "byres ( sele around " + radius + ")", stateNo)
     except:
         print("lo kurla")
Exemple #21
0
    def testSimple(self):
        cmd.fab('A', 'm1')
        cmd.fab('A', 'm2')
        v1 = 'foo'
        v2 = 'bar'
        v3 = 'com'
        
        # single state
        cmd.set_property('filename', v1, 'm1')
        self.assertTrue('foo' == v1)
        self.assertTrue(cmd.get_property('filename', 'm1') == v1)
        self.assertTrue(cmd.get_property('filename', 'm2') == None)

        # multiple objects
        cmd.set_property('filename', v1)
        self.assertTrue(cmd.get_property('filename', 'm2') == v1)

        # two states
        cmd.create('m1', 'm1', 1, 2)
        self.assertTrue(cmd.count_states() == 2)

        # set for all states
        cmd.set_property('filename', v1, 'm1')
        self.assertTrue(cmd.get_property('filename', 'm1', 2) == v1)

        # set for particular state
        cmd.set_property('filename', v2, 'm1', 2)
        self.assertTrue(cmd.get_property('filename', 'm1', 1) == v1)
        self.assertTrue(cmd.get_property('filename', 'm1', 2) == v2)

        # set for current state
        cmd.frame(2)
        cmd.set_property('filename', v3, 'm1', -1)
        self.assertTrue(cmd.get_property('filename', 'm1', 1) == v1)
        self.assertTrue(cmd.get_property('filename', 'm1', 2) == v3)
Exemple #22
0
def builderMicelle(detergent, r, numberOfDetergents):
    i = 0
    numberOfDetergents = (int)(numberOfDetergents)
    #FIXME: if number of detergents > 360, molecules may clash in space
    if numberOfDetergents > 360:
        x1 = range(-180, 180)
        x2 = range(0, 360)
        theta = ([random.choice(x1) for _ in range(numberOfDetergents)])
        phi = ([random.choice(x2) for _ in range(numberOfDetergents)])
    else:
        theta = random.sample(range(-180, 180), numberOfDetergents)
        phi = random.sample(range(0, 360), numberOfDetergents)
    for t, p in zip(theta, phi):
        i += 1
        cmd.copy(f"seg{i}", detergent)
        # randomly sample on a sphere
        cmd.translate(f"[0,{r},0]", f"seg{i}")
        cmd.rotate("x", f"{t}", f"seg{i}")
        cmd.rotate("z", f"{p}", f"seg{i}")
    s = f"micelle_{detergent}_{(int)(r)}_{(int)(numberOfDetergents)}"
    cmd.create(f"{s}", "seg*")
    cmd.delete("seg*")
    #center(f"{s}")
    #cmd.show_as("sticks","org")
    # could be streched if necessary
    # affineStretch(s, 10)
    return s
Exemple #23
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
Exemple #24
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
Exemple #25
0
def create_ds_uns(lines, name):
    uns = {'uns_sc': [], 'uns_bb': []}
    for line in lines:
        type = line[3:8]
        if type == 'SCACC' or type == 'SCDON':
            uns['uns_sc'].append(UnsAtom(line))
        elif type == 'BBACC' or type == 'BBDON':
            uns['uns_bb'].append(UnsAtom(line))

    for type, list in list(uns.items()):
        if list == []: continue
        selstr = string.join([
            '/%s//%s/%s/%s' % (name, atom.chain, atom.resi, atom.atom)
            for atom in list
        ], ' or ')
        typename = '%s_%s' % (type, name)
        cmd.select(typename, selstr)

    # copy unsatisfieds into a separate object (allows unique transparency, among other things)
    for type in uns:
        typename = '%s_%s' % (type, name)
        cmd.disable(typename)
        obj = '%s_obj' % typename
        cmd.create(obj, typename)
        cmd.show('spheres', obj)
        cmd.set('sphere_scale', '0.75', obj)
        cmd.set('sphere_transparency', '0.5', obj)
Exemple #26
0
def mkpntx(s1, s2):
    x = com(s1) - com(s2)
    if abs(x.x) > 0.1 or abs(x.y) > 0.1:
        print "DIE!", x
        return
    z = x.z
    c = Vec(0, z / 2 / math.tan(36.0 * math.pi / 180), z / 2)
    cmd.delete("p1")
    cmd.delete("p2")
    cmd.delete("p3")
    cmd.delete("p4")
    cmd.delete("p5")
    cmd.create("p1", s1)
    cmd.create("p2", s1)
    cmd.create("p3", s1)
    cmd.create("p4", s1)
    cmd.create("p5", s1)
    rot("p1", Vec(1, 0, 0), 0 * 72, c)
    rot("p2", Vec(1, 0, 0), 1 * 72, c)
    rot("p3", Vec(1, 0, 0), 2 * 72, c)
    rot("p4", Vec(1, 0, 0), 3 * 72, c)
    rot("p5", Vec(1, 0, 0), 4 * 72, c)
    cmd.color("green", "p1 and elem C")
    cmd.color("cyan", "p2 and elem C")
    cmd.color("yellow", "p3 and elem C")
    cmd.color("magenta", "p4 and elem C")
    cmd.color("orange", "p5 and elem C")
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')
Exemple #28
0
def builderNanodisc(protein, membrane, scaffold, prefixName, runNumber, x=0, y=0, refine=False):
    """
    builds a MP-nanodisc systems
    scaffold in this case is a double belt of MSP
    """
    # Checking time of builder function execution
    if protein != None:
        print('protein is: ' + protein)
    print('scaffold is: ' + scaffold)
    print('membrane is: ' + membrane)
    empty = False
    if protein is None: empty = True
    if not empty:
        tmp_prot = "tmp_prot" + str(runNumber)
        cmd.copy(tmp_prot, protein)  # store initial
        cmd.translate("[{},{},0]".format(x, y), tmp_prot)
    print("State of empty/not-empty: {}".format(empty))
    # copies to delete later
    tmp_scaffold = "tmp_scaffold" + str(runNumber)
    tmp_memb = "tmp_memb" + str(runNumber)
    tmp_origin = "origin" + str(runNumber)
    cmd.copy(tmp_scaffold, scaffold)  # store initial
    cmd.copy(tmp_memb, membrane)  # store initial

    center(tmp_memb)
    center(tmp_scaffold)
    cmd.pseudoatom(tmp_origin, pos=[0, 0, 0])
    cmd.origin(tmp_origin)
    #outRadius = findAverDist(tmp_scaffold) #doubles time for each run
    outRadius = TMdistCheck(tmp_scaffold, 0.2)
    print("Max distance from origin to scaffold in xy plane: {}".format(outRadius))
    # remove lipids beyond border encased by MSP
    cmd.remove("br. org and {} beyond {} of {}".format(tmp_memb, outRadius, tmp_origin))

    # remove lipids clashing with tmp_protein core
    if not empty:
        avXY = TMdistCheck(tmp_prot, 0.2)
        if avXY == -1: return "bad model"
        minXY = avXY / 2.0
        # remove lipids inside pore
        cmd.remove("br. org and {} within {} of {}".format(tmp_memb, minXY, tmp_origin))
        print("Mean distance if TM cross-section in xy plane: {}".format(avXY))

    if empty:
        cmd.remove("br. org and {} within 0.4 of {} and not hydro".format(tmp_memb, tmp_scaffold))
        s = "empty_{}_{}".format(membrane, scaffold)
    else:
        cmd.remove("br. org and {} within 0.3 of pol. and not hydro".format(tmp_memb))
        s = "{}_{}_{}".format(protein, membrane, scaffold)
    if refine: s += "{}_{}".format(int(x), int(y))
    if prefixName:
        s = "{}{}".format(prefixName, s)
    cmd.create(s, "({},{}, {})".format(protein, tmp_scaffold, tmp_memb))
    cmd.save(s + ".pdb", s)

    cmd.delete(tmp_memb)
    cmd.delete(tmp_scaffold)
    cmd.delete(tmp_prot)
    cmd.delete(tmp_origin)
    return s
Exemple #29
0
def normalmodes_prody(selection, cutoff=15, first=7, last=10, guide=1,
        prefix='prody', states=7, factor=-1, quiet=1):
    '''
DESCRIPTION

    Anisotropic Network Model (ANM) analysis with ProDy.

    Based on:
    http://www.csb.pitt.edu/prody/examples/dynamics/enm/anm.html
    '''
    try:
        import prody
    except ImportError:
        print('Failed to import prody, please add to PYTHONPATH')
        raise CmdException

    first, last, guide = int(first), int(last), int(guide)
    states, factor, quiet = int(states), float(factor), int(quiet)
    assert first > 6

    if guide:
        selection = '(%s) and guide and alt A+' % (selection)
    tmpsele = cmd.get_unused_name('_')
    cmd.select(tmpsele, selection)

    f = StringIO(cmd.get_pdbstr(tmpsele))
    conf = prody.parsePDBStream(f)

    modes = prody.ANM()
    modes.buildHessian(conf, float(cutoff))
    modes.calcModes(last - first + 1)

    if factor < 0:
        from math import log
        natoms = modes.numAtoms()
        factor = log(natoms) * 10
        if not quiet:
            print(' set factor to %.2f' % (factor))

    for mode in range(first, last + 1):
        name = prefix + '%d' % mode
        cmd.delete(name)

        if not quiet:
            print(' normalmodes: object "%s" for mode %d' % (name, mode))

        for state in range(1, states+1):
            xyz_it = iter(modes[mode-7].getArrayNx3() * (factor *
                    ((state-1.0)/(states-1.0) - 0.5)))
            cmd.create(name, tmpsele, 1, state, zoom=0)
            cmd.alter_state(state, name, '(x,y,z) = next(xyz_it) + (x,y,z)',
                    space={'xyz_it': xyz_it, 'next': next})

    cmd.delete(tmpsele)

    if guide:
        cmd.set('ribbon_trace_atoms', 1, prefix + '*')
        cmd.show_as('ribbon', prefix + '*')
    else:
        cmd.show_as('lines', prefix + '*')
Exemple #30
0
def getxform(sel1, sel2):
    cmd.create("TEMPORARY", sel1)
    sel1 = "TEMPORARY"
    c1a = com(sel1 + " and resi 1 and name C")
    c1b = com(sel2 + " and resi 1 and name C")
    v = c1b - c1a
    trans(sel1, v)
    c2a = (com(sel1 + " and resi 2 and name C") - c1b).normalized()
    c2b = (com(sel2 + " and resi 2 and name C") - c1b).normalized()
    axis1 = c2a.cross(c2b)
    ang1 = math.acos(c2a.dot(c2b))
    rot(sel1, axis1, 180.0 / math.pi * ang1, c1b)
    axis2 = (com(sel2 + " and resi 2 and name C") - c1b).normalized()
    P = projection_matrix(axis2)
    c3a = (com(sel1 + " and resi 3 and name C") - c1b)
    c3b = (com(sel2 + " and resi 3 and name C") - c1b)
    # print c1b
    # print com(sel1+" and resi 3 and name C")
    # print com(sel2+" and resi 3 and name C")
    # print c3a,"|||",c3b,"|||",  c3a.dot(axis2), c3b.dot(axis2)
    c3a -= P * c3a
    c3b -= P * c3b
    axis2 = c3a.cross(c3b).normalized()
    # print c3a,"|||",c3b,"|||",  c3a.dot(axis2), c3b.dot(axis2)
    ang2 = math.acos(c3a.normalized().dot(c3b.normalized()))
    # print ang2*180.0/math.pi
    rot(sel1, axis2, 180.0 / math.pi * ang2, c1b)
    M = rotation_matrix_radians(axis2, ang2) * rotation_matrix_radians(
        axis1, ang1)
    axis, ang = M.axisofrot()
    # trans(sel1,-v)
    # rot(sel1,axis,-ang,sel1+" and resi 1 and name C")
    # cmd.delete("TEMPORARY")
    return v, axis, ang * 180.0 / math.pi
Exemple #31
0
 def myalign(method):
     newmobile = cmd.get_unused_name(mobile_obj + '_' + method)
     cmd.create(newmobile, mobile_obj)
     start = time.time()
     cmd.do('%s mobile=%s in %s, target=%s' % (method, newmobile, mobile, target))
     if not quiet:
         print('Finished: %s (%.2f sec)' % (method, time.time() - start))
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
Exemple #33
0
def objectify_chain_arr(chainid_arr=list):
    for chain in chainid_arr:
        cmd.select("chain_{}_selection".format(chain),
                   "chain {}".format(chain))
        cmd.create("object_{}".format(chain),
                   "chain_{}_selection".format(chain))
        cmd.delete("chain_{}_selection".format(chain))
Exemple #34
0
def flipAtomName(targetResidueSelection):
    """
  switch the atom names of specific residues
  """
    # Create flipped residue
    cmd.create("flippedRes", targetResidueSelection + " and not alt B")
    targetResidueCa = cmd.get_model("flippedRes and name CA")
    for g in targetResidueCa.atom:
        #   print g.resn
        if g.resn == 'ARG':
            switchName("flippedRes", "NH1", "NH2")
        elif g.resn == 'HIS':
            switchName("flippedRes", "ND1", "CD2")
            switchName("flippedRes", "CE1", "NE2")
        elif g.resn == 'ASP':
            switchName("flippedRes", "OD1", "OD2")
        elif g.resn == 'PHE':
            switchName("flippedRes", "CD1", "CD2")
            switchName("flippedRes", "CE1", "CE2")
        elif g.resn == 'GLN':
            switchName("flippedRes", "OE1", "NE2")
        elif g.resn == 'GLU':
            switchName("flippedRes", "OE1", "OE2")
        elif g.resn == 'LEU':
            switchName("flippedRes", "CD1", "CD2")
        elif g.resn == 'ASN':
            switchName("flippedRes", "OD1", "ND2")
        elif g.resn == 'TYR':
            switchName("flippedRes", "CD1", "CD2")
            switchName("flippedRes", "CE1", "CE2")
        elif g.resn == 'VAL':
            switchName("flippedRes", "CG1", "CG2")
    cmd.sort()
    # cmd.label("flippedRes","name")
    return "flippedRes"
Exemple #35
0
def create_chain_object(chain, rnasingclust, nomenclatureMap):
    nomMap = nomenclatureMap
    if rnasingclust != 'rna':
        ambiguous = True if len(nomMap[chain]) != 1 else False
    if rnasingclust == 'rna':
        cmd.select("rnasel_{}".format(chain), "chain {}".format(chain))
        cmd.create("rna_{}".format(chain), "rnasel_{}".format(chain))
        # cmd.delete("rnasel_{}".format(chain))
    elif rnasingclust == 'singular':
        if ambiguous:
            cmd.select("chain_{}".format(chain), "chain {}".format(chain))
            cmd.create("{}".format(chain), "chain_{}".format(chain))
            # cmd.delete("chain_{}".format(chain))
        else:
            cmd.select("chain_{}_{}".format(chain, nomMap[chain][0]),
                       "chain {}".format(chain))
            cmd.create("{}_{}".format(chain, nomMap[chain][0]),
                       "chain_{}_{}".format(chain, nomMap[chain][0]))
            # cmd.delete("chain_{}_{}".format(chain, nomMap[chain][0]))
    else:
        if ambiguous:
            cmd.select("chain_{}".format(chain), "chain {}".format(chain))
            cmd.create("{}_{}".format(rnasingclust, chain),
                       "chain_{}".format(chain))
            cmd.color(rnasingclust, "chain {}".format(chain))
            # cmd.delete("chain_{}".format(chain))
        else:
            cmd.select("chain_{}".format(chain), "chain {}".format(chain))
            cmd.create(
                "{}_{}_{}".format(chain, nomMap[chain][0], rnasingclust),
                "chain_{}".format(chain))
            cmd.color(rnasingclust, "chain {}".format(chain))
def draw_dist_pairs(drs_inp, molecule, draw_type="line"):
    f_drsinp = open(drs_inp, "r")
    obj = "network"
    cmd.create(obj, molecule)
    cmd.hide("everything", obj)
    for i, line in enumerate(f_drsinp):
        print "Pair No.: ", i
        if line.split()[1] != "LIST" and line.split()[1] != "STOP":
            chainid1, resid1, resname1, atomname1 = line.split(
            )[0], line.split()[1], line.split()[2], line.split()[3]
            chainid2, resid2, resname2, atomname2 = line.split(
            )[4], line.split()[5], line.split()[6], line.split()[7]
            print chainid1, resid1, resname1, atomname1, chainid2, resid2, resname2, atomname2
            if draw_type == "line":
                cmd.bond("%s and chain %s and resi %s and name %s"%(obj,chainid1,resid1,atomname1),\
                         "%s and chain %s and resi %s and name %s"%(obj,chainid2,resid2,atomname2) )
                cmd.show(
                    "lines", "%s and chain %s and resi %s and name %s" %
                    (obj, chainid1, resid1, atomname1))
                cmd.show(
                    "lines", "%s and chain %s and resi %s and name %s" %
                    (obj, chainid2, resid2, atomname2))
            elif draw_type == "dist":
                cmd.distance("dist%s"%i, "chain %s and resi %s and name %s"%(chainid1,str(resid1),atomname1),\
                                         "chain %s and resi %s and name %s"%(chainid2,str(resid2),atomname2) )
            print "chain %s and resi %s and name %s" % (chainid1, resid1,
                                                        atomname1)
        elif line.split()[1] == "STOP":
            print "Reached last line"
            break
Exemple #37
0
def tview(pdbid: str):

    species = str(int(log.get_struct(pdbid)['taxid'].values[0]))

    l22chain = log.get_struct(pdbid).uL22.values[0]
    l4chain = log.get_struct(pdbid).uL4.values[0]

    l22_res = int(log.get_struct(pdbid).constrictionResidueL22_id.values[0])
    l4_res = int(log.get_struct(pdbid).constrictionResidueL4_id.values[0])

    # cmd.delete('all')

    pdbid = pdbid.upper()

    TUNNELS = os.getenv("TUNNELS")
    SCOOP_RADIUS = os.getenv("SCOOP_RADIUS")
    TUNNEL_SCRIPT = os.path.join(TUNNELS, species, pdbid, 'pymol',
                                 'complex.py')

    inputstructpath = os.path.join(
        TUNNELS, species, pdbid, '{}_{}Ascoop.pdb'.format(pdbid, SCOOP_RADIUS))
    csvpaths = os.path.join(
        TUNNELS,
        species,
        pdbid,
        'csv',
    )

    cmd.load(inputstructpath)
    cmd.color('gray', 'all')

    if not os.path.exists(TUNNEL_SCRIPT):

        print("TUNNEL SCRIPT NOT FOUND.")
        return

    cmd.run(TUNNEL_SCRIPT)

    cmd.hide('everything', 'Tunnels')
    cmd.show('mesh', 'Tunnels')

    # tunnels    = os.listdir(csvpaths)
    # tunnumbers = map(lambda x: re.findall(r'\d+',x)[0], tunnels)
    # [cmd.delete(f'Tunnel{tunN}') if tunN not in choices else None for tunN in tunnumbers]
    # paint_tunnel(pdbid)

    sele_ptc(9606)
    # cmd.select('PTC', 'resi 2055 or resi 2056 or resi 2451 or resi 2452 or resi 2507 or resi 2506')
    # cmd.create('PTC',"PTC")
    # cmd.color('blue', 'PTC')

    cmd.select(
        'ConstrictionSite', 'c. {} and resi {} or c. {} and resi {}'.format(
            l22chain, l22_res, l4chain, l4_res))

    cmd.create('ConstrictionSite', "ConstrictionSite")
    cmd.show('everything', 'ConstrictionSite')
    cmd.color('magenta', 'ConstrictionSite')

    cmd.reset()
Exemple #38
0
def fatslim_apl_prot():
    global REF_BEAD
    setup()

    FILENAME = BILAYER_PROT
    REF_BEAD = BILAYER_PROT_REF

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

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

    # Show leaflets
    show_leaflets(frame)

    # Show stuff related to APL
    show_apl(frame)

    print("Bilayer with protein loaded!")
Exemple #39
0
    def paint_rna(strand: str):
        def update_rna_lining(strand, resid):
            cmd.select('sele_rna_lining',
                       'rna_lining or c. {} and resi {}'.format(strand, resid))
            cmd.create('rna_lining', 'sele_rna_lining')

        colormap = {
            'A': 'tv_green',
            'C': 'tv_green',
            'G': 'tv_green',
            'U': 'tv_green'
        }

        for nucleotide in report['adjacent_strands'][strand]:

            if nucleotide['resname'] in colormap.keys():
                # target = 'sele_{}_{}'.format(strand,nucleotide['resid'] )
                # cmd.select(target, "c. {} and resi {}".format(strand, nucleotide['resid']))
                # cmd.color(colormap[nucleotide['resname']],target)
                # cmd.set('cartoon_transparency', '0.4',target)
                # cmd.delete(target)

                update_rna_lining(strand, nucleotide['resid'])
            else:
                target = 'sele_{}_{}'.format(strand, nucleotide['resid'])
                cmd.select(
                    target, "c. {} and resi {}".format(strand,
                                                       nucleotide['resid']))
                cmd.create("{}".format(nucleotide['resname']), target)
                cmd.color("white", target)
                cmd.delete(target)
Exemple #40
0
 def test_atom_state_settings_3f(self, f, data):
     m1 = "pseudo01"
     lp1, lp2 = lp = map(f, data)
     cmd.pseudoatom(m1)
     cmd.pseudoatom(m1)
     cmd.create(m1, m1, 1, 2)
     stored.pos = {}
     stored.lp1 = lp1
     stored.lp2 = lp2
     stored.origp = None
     # get origp (should be 0.,0.,0.
     cmd.alter("(index 1)", "stored.origp = s['label_placement_offset']")
     # change atom-state setting to lp1 for atom in both states
     cmd.alter_state(0, "(index 1)", "s['label_placement_offset']=stored.lp1")
     # change atom-level setting for all atoms to something else
     cmd.alter("all", "s['label_placement_offset']=stored.lp2")
     # get atom-state settings
     cmd.iterate_state(0, "all", "stored.pos['%s-%s-%s' % (model, state, index)]=s['label_placement_offset']")
     # atom-state setting should be lp1 for atom 1
     self.assertEqual(tuple(lp1), stored.pos['%s-%s-%s' % (m1, 1, 1)])
     self.assertEqual(tuple(lp1), stored.pos['%s-%s-%s' % (m1, 2, 1)])
     # atom setting should override to lp2 for atom 2 in both states
     self.assertEqual(tuple(lp2), stored.pos['%s-%s-%s' % (m1, 1, 2)])
     self.assertEqual(tuple(lp2), stored.pos['%s-%s-%s' % (m1, 2, 2)])
     # unset all atom-level settings, atom-state settings should still exist
     cmd.alter("all", "s['label_placement_offset']=None")
     stored.pos = {}
     cmd.iterate_state(0, "all", "stored.pos['%s-%s-%s' % (model, state, index)]=s['label_placement_offset']")
     self.assertEqual(tuple(lp1), stored.pos['%s-%s-%s' % (m1, 1, 1)])
     self.assertEqual(tuple(lp1), stored.pos['%s-%s-%s' % (m1, 2, 1)])
     self.assertEqual(tuple(stored.origp), stored.pos['%s-%s-%s' % (m1, 1, 2)])
     self.assertEqual(tuple(stored.origp), stored.pos['%s-%s-%s' % (m1, 2, 2)])
Exemple #41
0
    def testIterateState(self):
        cmd.fragment('ala')
        cmd.create('ala', 'ala', 1, 2)
        self.assertEqual(2, cmd.count_states())

        v_count = cmd.count_atoms('all')
        expr = 'v_xyz.append(((model,index), (x,y,z)))'

        # current state
        v_xyz = []
        cmd.iterate_state(-1, 'all', expr, space=locals())
        self.assertEqual(len(v_xyz), v_count)

        # all states
        v_xyz = []
        cmd.iterate_state(0, 'all', expr, space=locals())
        self.assertEqual(len(v_xyz), v_count * 2)

        # atomic=0
        stored.v_xyz = []
        cmd.iterate_state(1, 'all', 'stored.v_xyz.append((x,y,z))', atomic=0)
        self.assertEqual(len(stored.v_xyz), v_count)

        space = {'self': self, 'NameError': NameError, 'v_list': []}
        cmd.iterate_state(
            1,
            'all',
            'v_list.append(self.assertRaises(NameError, lambda: (model, index)))',
            space=space)
        self.assertEqual(len(space['v_list']), v_count)
Exemple #42
0
 def readGuest(self):
     try:
         stateNo = cmd.get_state()
         cmd.create("guest", "sele", stateNo)
         cmd.select("guestFrozen", "none")
     except:
         print("lo kurla")
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
Exemple #44
0
 def addSele2Guest(self):
     try:
         stateNo = cmd.get_state()
         cmd.create("guest", "%guest or sele", stateNo)
     except:
         stateNo = cmd.get_state()
         cmd.create("guest", "sele", stateNo)
    def testMultifilesave(self):
        import glob

        for name in ['ala', 'gly', 'his', 'arg']:
            cmd.fragment(name)

        # multistate
        for i in range(2, 11):
            cmd.create('ala', 'ala', 1, i)

        for fmt in ['{}-{:02}.cif', '{}-{state}.cif']:
            with testing.mkdtemp() as dirname:
                cmd.multifilesave(os.path.join(dirname, fmt), 'ala', 0)
                filenames = [os.path.basename(p) for p in glob.glob(os.path.join(dirname, '*.cif'))]
                self.assertEqual(len(filenames), 10)
                self.assertTrue('ala-03.cif' in filenames)

        with testing.mkdtemp() as dirname:
            cmd.multifilesave(os.path.join(dirname, '{}.pdb'), 'a* g*')
            filenames_full = sorted(glob.glob(os.path.join(dirname, '*.pdb')))
            filenames = [os.path.basename(p) for p in filenames_full]
            self.assertEqual(filenames, ['ala.pdb', 'arg.pdb', 'gly.pdb'])

            cmd.delete('*')
            cmd.load(filenames_full[0])
            self.assertEqual(cmd.count_atoms(), 10)

            cmd.delete('*')
            cmd.load(filenames_full[1])
            self.assertEqual(cmd.count_atoms(), 24)
Exemple #46
0
 def addSele2Host(self):
     try:
         stateNo = cmd.get_state()
         cmd.create("host", "%host or sele", stateNo)
     except:
         stateNo = cmd.get_state()
         cmd.create("host", "sele", stateNo)
Exemple #47
0
    def testIterateState(self):
        cmd.fragment('ala')
        cmd.create('ala', 'ala', 1, 2)
        self.assertEqual(2, cmd.count_states())

        v_count = cmd.count_atoms('all')
        expr = 'v_xyz.append(((model,index), (x,y,z)))'

        # current state
        v_xyz = []
        cmd.iterate_state(-1, 'all', expr, space=locals())
        self.assertEqual(len(v_xyz), v_count)

        # all states
        v_xyz = []
        cmd.iterate_state(0, 'all', expr, space=locals())
        self.assertEqual(len(v_xyz), v_count * 2)

        # atomic=0
        stored.v_xyz = []
        cmd.iterate_state(1, 'all', 'stored.v_xyz.append((x,y,z))', atomic=0)
        self.assertEqual(len(stored.v_xyz), v_count)

        space = {'self': self, 'NameError': NameError, 'v_list': []}
        cmd.iterate_state(1, 'all',
                'v_list.append(self.assertRaises(NameError, lambda: (model, index)))',
                space=space)
        self.assertEqual(len(space['v_list']), v_count)
def findSurfaceResidues(objSel="(all)", cutoff=2.5, doShow=False, verbose=True):
	"""
	findSurfaceResidues
		finds those residues on the surface of a protein
		that have at least 'cutoff' exposed A**2 surface area.
 
	PARAMS
		objSel (string)
			the object or selection in which to find
			exposed residues
			DEFAULT: (all)
 
		cutoff (float)
			your cutoff of what is exposed or not. 
			DEFAULT: 2.5 Ang**2
 
		asSel (boolean)
			make a selection out of the residues found
 
	RETURNS
		(list: (chain, resv ) )
			A Python list of residue numbers corresponding
			to those residues w/more exposure than the cutoff.
 
	"""
	tmpObj="__tmp"
	cmd.create( tmpObj, objSel + " and polymer");
	if verbose!=False:
		print "WARNING: I'm setting dot_solvent.  You may not care for this."
	cmd.set("dot_solvent");
	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) )
 
	stored.tmp_dict = {}
	cmd.iterate(tmpObj, "stored.tmp_dict[(chain,resv)]=1")
	exposed = stored.tmp_dict.keys()
	exposed.sort()
 
        randstr = str(random.randint(0,10000))
	selName = "exposed_atm_" + randstr
	if verbose!=False:
		print "Exposed residues are selected in: " + selName
	cmd.select(selName, objSel + " in " + tmpObj ) 
        selNameRes = "exposed_res_" + randstr
        cmd.select(selNameRes, "byres " + selName )
 
 
	if doShow!=False:
		cmd.show_as("spheres", objSel + " and poly")
		cmd.color("white", objSel)
		cmd.color("red", selName)
 
	cmd.delete(tmpObj)
	
	print exposed
 
	return exposed
Exemple #49
0
def mkc2(sel, a=Vec(0, 0, 1), c=Vec(0, 0, 0)):
    cmd.delete("c1")
    cmd.delete("c2")
    cmd.create("c1", sel)
    cmd.create("c2", sel)
    rot("c2", a, 180, c)
    cmd.alter("c1", 'chain = "A"')
    cmd.alter("c2", 'chain = "B"')
Exemple #50
0
def mkhelix(sel, t, r, n):
    v = cmd.get_view()
    for i in range(1, n):
        cmd.delete("h%i" % i)
        cmd.create("h%i" % i, sel)
        rot("h%i" % i, Vec(0, 0, 1), i * r, Vec(0, 0, 0))
        trans("h%i" % i, Vec(0, 0, i * t))
    cmd.set_view(v)
Exemple #51
0
def stick_toon():
    glb.update()
    cmd.hide('all')
    cmd.show('lines')
    cmd.create('cartoon', 'all')
    cmd.show('cartoon', 'cartoon')
    cmd.color('salmon', 'cartoon')
    cmd.color('cyan', 'resn a+t+u+g+c')
Exemple #52
0
def fatslim_bilayer():
    global REF_BEAD
    REF_BEAD = BILAYER_REF
    setup()

    # Load file
    cmd.load("%s.pdb" % BILAYER)
    main_obj = "bilayer"
    cmd.disable(main_obj)
    traj = load_trajectory("%s.gro" % BILAYER, "%s.ndx" % BILAYER)
    traj.initialize()
    frame = traj[0]
    draw_pbc_box(main_obj)
    print("Bilayer Loaded!")

    # Show lipids
    cmd.create("lipids", "resname DMPC")
    cmd.hide("lines", "lipids")
    cmd.show("spheres", "lipids")

    # Show water
    cmd.create("water", "resname SOL")
    cmd.hide("lines", "water")
    cmd.set("solvent_radius", 2)
    cmd.show("surface", "water")
    cmd.color("skyblue", "water")
    cmd.set("transparency", 0.5, "water")
    # cmd.rebuild()
    # cmd.refresh()

    # Show positions
    show_positions(frame)

    # Show directions
    show_directions(frame)

    # Show ref bead and its neighbors
    show_ref(frame)

    show_ref_ns(frame)

    # Show normals
    show_normals(frame)

    # Identify leaflets
    show_leaflets(frame)

    # Calculate and show normals
    show_leaflet_normals(frame)

    # Show stuff related to thickness
    show_thickness(frame)

    # Show stuff related to APL
    show_apl(frame)

    # Zoom on leaflets
    cmd.zoom("all", 5)
Exemple #53
0
def propka(molecule="NIL",chain="*",resi="0",resn="NIL",method="upload",logtime=time.strftime("%m%d",time.localtime()),server_wait=3.0,version="v3.1",verbose="no",showresult="no",pkafile="NIL",makebonds="yes"):
	Script_Version="20110823"
	### First we have to be sure, we give reasonable arguments
	if pkafile!="NIL":
		method='file'
	assert method in ['upload', 'file'], "'method' has to be either: method=upload or method=file"
	### If molecule="all", then try to get the last molecule
	##assert molecule not in ['NIL'], "You always have to provide molecule name. Example: molecule=4ins"
	if molecule=="NIL":
		assert len(cmd.get_names())!=0, "Did you forget to load a molecule? There are no objects in pymol."
		molecule=cmd.get_names()[-1]
	### To print out to screen for selected residues. Can be separated with "." or make ranges with "-". Example: resi="4-8.10"
	if resi != "0": resi_range = ResiRange(resi)
	else: resi_range=[]
	### Also works for residue names. They are all converted to bigger letters. Example: resn="cys.Tyr"
	if resn != "NIL": resn_range = ResnRange(resn)
	else: resn_range = resn
	### Make chain range, and upper case.
	chain = ChainRange(chain)
	### Make result directory. We also the absolut path to the new directory.
	Newdir = createdirs()
	if method=="upload":
		### We try to load mechanize. If this fail, one can always get the .pka file manual and the run: method=file
		try: from modules import mechanize; importedmechanize='yes'
		except ImportError: print("Import error. Is a module missing?"); print(sys.exc_info()); print("Look if missing module is in your python path\n%s")%sys.path;importedmechanize='no'; import modules.mechanize as mechanize
		### The name for the new molecule
		newmolecule = "%s%s"%(molecule,logtime)
		### Create the new molecule from original loaded and for the specified chains. Save it, and disable the old molecule.
		cmd.create("%s"%newmolecule, "%s and chain %s"%(molecule,chain))
		cmd.save("%s%s.pdb"%(Newdir,newmolecule), "%s"%newmolecule)
		cmd.disable("%s"%molecule)
		if molecule=="all": cmd.enable("%s"%molecule); cmd.show("cartoon", "%s"%molecule)
		### Let the new molecule be shown in cartoon.
		cmd.hide("everything", "%s"%newmolecule)
		cmd.show("cartoon", "%s"%newmolecule)
		### Make the absolut path to the newly created .pdb file.
		PDB="%s%s.pdb"%(Newdir,newmolecule);source="upload"; PDBID=""
		### Request server, and get the absolut path to the result file.
		pkafile = getpropka(PDB,chain,resi,resn,source,PDBID,logtime,server_wait,version,verbose,showresult)
		### Open the result file and put in into a handy list.
		list_results,ligands_results = importpropkaresult(pkafile)
	if method=="file":
		assert pkafile not in ['NIL'], "You have to provide path to file. Example: pkafile=./Results_propka/4ins_2011.pka"
		assert ".pka" in pkafile, 'The propka result file should end with ".pka" \nExample: pkafile=./Results_propka/4ins_2011.pka \npkafile=%s'%(pkafile)
		### The name for the molecule we pass to the writing script of pymol commands
		newmolecule = "%s"%molecule
		cmd.hide("everything", "%s"%newmolecule)
		cmd.show("cartoon", "%s"%newmolecule)
		### We open the result file we have got in the manual way and put in into a handy list.
		list_results,ligands_results = importpropkaresult(pkafile)
		### Then we print the interesting residues to the screen.
		printpropkaresult(list_results, resi, resi_range, resn, resn_range, showresult, ligands_results)
	### Now create the pymol command file. This should label the protein. We get back the absolut path to the file, so we can execute it.
	result_pka_pymol_name = writepymolcmd(newmolecule,pkafile,verbose,makebonds)
	### Now run our command file. But only if we are running pymol.
	if runningpymol=='yes': cmd.do("run %s"%result_pka_pymol_name)
	##if runningpymol=='yes': cmd.do("@%s"%result_pka_pymol_name)
	return(list_results)
def symexpcell(prefix='mate', object=None, a=0, b=0, c=0):
	'''
DESCRIPTION
 
    Creates all symmetry-related objects for the specified object that
    occur with their bounding box center within the unit cell.
 
USAGE
 
    symexpcell prefix, object, [a, b, c]
 
ARGUMENTS
 
    prefix = string: prefix of new objects
 
    object = string: object for which to create symmetry mates
 
    a, b, c = integer: create neighboring cell {default: 0,0,0}
 
SEE ALSO
 
    symexp, http://www.pymolwiki.org/index.php/SuperSym
	'''
	if object is None:
		object = cmd.get_object_list()[0]
 
	sym = cmd.get_symmetry(object)
	cell_edges = sym[0:3]
	cell_angles = sym[3:6]
	spacegroup = sym[6]
 
	basis = cellbasis(cell_angles, cell_edges)
	basis = numpy.matrix(basis)
 
	extent = cmd.get_extent(object)
	center = sum(numpy.array(extent)) * 0.5
	center = numpy.matrix(center.tolist() + [1.0]).T
	center_cell = basis.I * center
 
	extra_shift = [[float(i)] for i in (a,b,c)]
 
	i = 0
	matrices = xray.sg_sym_to_mat_list(spacegroup)
	for mat in matrices:
		i += 1
 
		mat = numpy.matrix(mat)
		shift = numpy.floor(mat * center_cell)
		mat[0:3,3] -= shift[0:3,0]
		mat[0:3,3] += extra_shift
 
		mat = basis * mat * basis.I
		mat_list = list(mat.flat)
 
		name = '%s%d' % (prefix, i)
		cmd.create(name, object)
		cmd.transform_object(name, mat_list)
		cmd.color(i+1, name)
Exemple #55
0
 def testFit(self):
     cmd.fragment("gly", "m1")
     cmd.create("m2", "m1")
     rms = cmd.fit("m1", "m2")
     self.assertEqual(rms, 0.0)
     rms = cmd.rms("m1", "m2")
     self.assertEqual(rms, 0.0)
     rms = cmd.rms_cur("m1", "m2")
     self.assertEqual(rms, 0.0)
Exemple #56
0
 def testIntraFit(self):
     cmd.fragment("gly", "m1")
     cmd.create("m1", "m1", 1, 2)
     rms_list = cmd.intra_fit("m1")
     self.assertArrayEqual(rms_list, [-1.0, 0.0])
     rms_list = cmd.intra_rms("m1")
     self.assertArrayEqual(rms_list, [-1.0, 0.0])
     rms_list = cmd.intra_rms_cur("m1")
     self.assertArrayEqual(rms_list, [-1.0, 0.0])
Exemple #57
0
def makecx(sel="all", n=5):
    cmd.delete("C%i_*" % n)
    chains = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    for i in range(n):
        cmd.create("C%i_%i" % (n, i), sel + " and (not C%i_*)" % n)
    for i in range(n):
        rot("C%i_%i" % (n, i), Z, 360.0 * float(i) / float(n))
    for i in range(n):
        cmd.alter("C%i_%i" % (n, i), "chain = '%s'" % chains[i])
Exemple #58
0
 def testEnable(self):
     cmd.create('m1', 'none')
     cmd.create('m2', 'none')
     cmd.disable()
     self.assertEqual(cmd.get_names('public_objects', 1), [])
     cmd.enable('m1')
     self.assertEqual(cmd.get_names('public_objects', 1), ['m1'])
     cmd.enable()
     self.assertEqual(cmd.get_names('public_objects', 1), ['m1', 'm2'])
def surfaceatoms(molecule="NIL",show=True, verbose=True, cutoff=2.5):
	"""
	surfaceatoms
		finds those residues on the surface of a protein
		that have at least 'cutoff' exposed A**2 surface area.
 	PARAMS
		molecule (string)
			the object or selection in which to find
			exposed residues
			DEFAULT: (last molecule in pymol)
 		cutoff (float)
			your cutoff of what is exposed or not. 
			DEFAULT: 2.5 Ang**2
	RETURNS
		(list: (chain, resv ) )
			A Python list of residue numbers corresponding
			to those residues w/more exposure than the cutoff.
	"""
	if molecule=="NIL":
		assert len(cmd.get_names())!=0, "Did you forget to load a molecule? There are no objects in pymol."
		molecule=cmd.get_names()[-1]
	tmpObj="__tmp"
	cmd.create(tmpObj, "(%s and polymer) and not resn HOH"%molecule)
	if verbose!=False:
		print "WARNING: I'm setting dot_solvent.  You may not care for this."
	cmd.set("dot_solvent")
	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) )
 	stored.tmp_dict = {}
	cmd.iterate(tmpObj, "stored.tmp_dict[(chain,resv)]=1")
	exposed = stored.tmp_dict.keys()
	exposed.sort()
 
	selName = "%s_atoms"%molecule
	cmd.select(selName, molecule + " in " + tmpObj ) 
	if verbose!=False:
		print "Exposed residues are selected in: " + selName
	selNameRes = "%s_resi"%molecule
	cmd.select(selNameRes, "byres " + selName )
 
 	if show!=False:
		cmd.hide("everything", molecule)
		cmd.show("cartoon", "%s and not %s and not resn HOH"%(molecule,selNameRes))
		cmd.show("sticks", "%s"%selNameRes)
		cmd.util.cbaw(selNameRes)
		cmd.disable(selNameRes)
		#cmd.alter('%s'%(selName),'vdw=0.5') # affects repeated runs
                cmd.set('sphere_scale','0.3','%s'%(selName)) # does not affect repeated runs
		cmd.show("spheres", "%s"%selName)
		cmd.util.cbao(selName)
		cmd.disable(selName)
 
 	cmd.delete(tmpObj)
	print(exposed)
 	return(exposed)
Exemple #60
0
def fSumWMCLast(molecule, SGNameAngle, chain, residue, MCNeighbour, DieElecMC, MCchargeN, MCchargeH, MCchargeProCA, MCchargeProCD, MCchargeProN, AmideName, printMC):
	#print "Last", MCNeighbour
	SumWMCLast = 0.0
	SGnameselect = "/"+SGNameAngle+"//"+"/"+"/SG"
	NBnameselect = "/"+molecule+"//"+chain+"/"+str(MCNeighbour)
	cmd.select("MC", NBnameselect)
	MCpdbstr = cmd.get_pdbstr("MC")
	MCsplit = MCpdbstr.split()
	residueName = MCsplit[3]
	#print NBnameselect, residueName
	if residueName == "PRO":
		### Proline CA
		CAnameselect = "/"+molecule+"//"+chain+"/"+str(MCNeighbour)+"/CA"
		ResDist = cmd.dist(residue+'distLastProCA', SGnameselect,CAnameselect)
		WMC = fWMC(MCchargeProCA, DieElecMC, ResDist)
		SumWMCLast = SumWMCLast + WMC
		if printMC == 'yes': print "MC ProCA ", MCNeighbour, " ", MCchargeProCA, " ", DieElecMC, " ", ResDist, " ", WMC
		### Proline CD
		CDnameselect = "/"+molecule+"//"+chain+"/"+str(MCNeighbour)+"/CD"
		ResDist = cmd.dist(residue+'distLastProCD', SGnameselect,CDnameselect)
		WMC = fWMC(MCchargeProCD, DieElecMC, ResDist)
		SumWMCLast = SumWMCLast + WMC
		if printMC == 'yes': print "MC ProCD ", MCNeighbour, " ", MCchargeProCD, " ", DieElecMC, " ", ResDist, " ", WMC
		### Proline N
		Nnameselect = "/"+molecule+"//"+chain+"/"+str(MCNeighbour)+"/N"
		ResDist = cmd.dist(residue+'distLastProN', SGnameselect,Nnameselect)
		WMC = fWMC(MCchargeProN, DieElecMC, ResDist)
		SumWMCLast = SumWMCLast + WMC
		if printMC == 'yes': print "MC ProN ", MCNeighbour, " ", MCchargeProN, " ", DieElecMC, " ", ResDist, " ", WMC
	else:
		AmideProt = "/"+molecule+"//"+chain+"/"+str(MCNeighbour)+"/H01"
		Hnameselect = "/"+AmideName+"//"+chain+"/"+str(MCNeighbour)+"/H01"
		if cmd.count_atoms(AmideProt) == 0 and cmd.count_atoms(Hnameselect) == 0:
			HbuildSelect = "/"+molecule+"//"+chain+"/"+str(MCNeighbour)+"/N"
			cmd.h_add(HbuildSelect)
			cmd.create(AmideName, AmideName+" + "+AmideProt)
			cmd.remove(AmideProt)
		### Mainchain AmideH
		ResDist = cmd.dist(residue+'distLastH', SGnameselect,Hnameselect)
		WMC = fWMC(MCchargeH, DieElecMC, ResDist)
		SumWMCLast = SumWMCLast + WMC
		if printMC == 'yes': print "MC H ", MCNeighbour, " ", MCchargeH, " ", DieElecMC, " ", ResDist, " ", WMC
		### Mainchain N
		Nnameselect = "/"+molecule+"//"+chain+"/"+str(MCNeighbour)+"/N"
		ResDist = cmd.dist(residue+'distLastN', SGnameselect,Nnameselect)
		WMC = fWMC(MCchargeN, DieElecMC, ResDist)
		SumWMCLast = SumWMCLast + WMC
		if printMC == 'yes': print "MC N ", MCNeighbour, " ", MCchargeN, " ", DieElecMC, " ", ResDist, " ", WMC
	cmd.delete(residue+'distLastProCA')
	cmd.delete(residue+'distLastProCD')
	cmd.delete(residue+'distLastProN')
	cmd.delete(residue+'distLastH')
	cmd.delete(residue+'distLastN')
	cmd.show("nb_spheres", AmideName)
	cmd.delete("MC")
	return SumWMCLast