Esempio n. 1
0
    def testStereo(self):
        cmd.fragment('ala')
        cmd.remove('hydro')

        # default: S configuration
        labels = []
        cmd.iterate('name CA', 'labels.append(stereo)', space=locals())
        self.assertEqual(labels, ['S'])

        # load R configuration (moves CB)
        ala_conf_R = {
            'N': (-0.67690, -1.23030, -0.49050),
            'CA': (-0.00090, 0.06370, -0.49050),
            'C': (1.49910, -0.11030, -0.49050),
            'O': (2.03010, -1.22730, -0.50150),
            #   'CB' : (-0.50890,  0.85570,  0.72650), # S configuration
            'CB': (-0.33784, 0.82664, -1.78310),  # R configuration
        }
        cmd.alter_state(1,
                        'ala',
                        '(x,y,z) = ala_conf_R.get(name)',
                        space=locals())
        labels = []
        cmd.iterate('name CA', 'labels.append(stereo)', space=locals())
        self.assertEqual(labels, ['R'])
Esempio n. 2
0
 def _testLabelByAtomType(self):
     cmd.load(self.datafile('1oky.pdb.gz'))
     cmd.remove("alt 'B'")
     cmd.label('resn STU', 'text_type')
     c3labels = []
     cmd.iterate("resn STU", "c3labels.append(label == 'C.3')", space=locals())
     self.assertEquals(sum(c3labels), 8)
Esempio n. 3
0
File: B07.py Progetto: Almad/pymol
def load():
   cmd.set("valence")
   r = 0
   list = glob("pdb/*/*")

#   list = ["pdb/06/pdb406d"]
#   while list[0]!="pdb/f8/pdb1f8u":
#      list.pop(0)
   for file in list:
      cmd.delete('pdb')
      cmd.load(file,'pdb')
      cmd.remove("not alt ''+A")
      cmd.fix_chemistry("all","all")
      cmd.h_add()
      sys.__stderr__.write(file)
      sys.__stderr__.flush()
      ch = Champ()
      model = cmd.get_model('pdb')
      idx = ch.insert_model(model)

      ch.pattern_orient_bonds(idx)
      print " %5d"%cmd.count_atoms(),"%5d"%len(ch.pattern_get_string(idx)),
      ch.pattern_detect_chirality(idx)
      pat = ch.pattern_get_string(idx)
      print "%5d"%len(pat),pat[0:22]+"..."+pat[-10:]
Esempio n. 4
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
Esempio n. 5
0
def fetch_scop(code, name='', **kwargs):
    if name == '':
        name = code
    kwargs['async'] = 0
    r = fetch(code[1:5], name, **kwargs)
    if cmd.is_error(r):
        return r
    try:
        import Bio.SCOP
        import MySQLdb
        conn = MySQLdb.connect(**mysql_kwargs)
        scop = Bio.SCOP.Scop(db_handle=conn)
        d = scop.getDomainBySid(code)
        if len(d.residues.fragments) > 0:
            rsele = ''
            for frag in d.residues.fragments:
                chain, start, stop = frag
                rsele += ' (chain ' + chain
                if start and stop:
                    rsele += ' and resi %s-%s' % (start, stop)
                rsele += ')'
            cmd.remove(name + ' and not (' + rsele + ')')
    except:
        print(' Warning: SCOP domain resiude range handling failed')
        return -1
Esempio n. 6
0
def cheshift(pdb_path,cs_path):
    """Conects to CheShift to send and receive data"""
    pdb_filename = pdb_path.split('/')[-1]
    pdb_filenamenoext = re.sub(r'[^A-Za-z0-9-.]', '', pdb_filename.split('.')[0])
    cs_filename = cs_path.split('/')[-1]
# Send data to CheShift.com and captures the name of the new web page.
    br = mechanize.Browser()
    br.set_handle_refresh(False)
    br.set_proxies(proxy_values)
    try:
        br.open('http://www.cheshift.com/visual_test.html')
        br.select_form(nr=0)
        br.form.add_file(open(pdb_path), "chemical/x-pdb", pdb_filename,
        name = 'uploaded')
        br.form.add_file(open(cs_path), "text/plain", cs_filename, name='CS_file')
        br.form.set_value([ref_value.get()],name='radiogroup')
        br.form.set_all_readonly(False)
        response = br.submit().geturl()
        subfix = response.split('/')[-1].split('.')[0]
    except:
        Pmw.MessageDialog(title='Error',message_text=('Something went wrong while processing your request\n Please check your files and try again\n\nIf you could not find the problem please send and e-mail to [email protected]'))

# Checks if the colored PDB file was created or if something went wrong
    test = 0
    while True:
        try:# If the colored PDB was created, creates a local temporal PDB file
# and loads that file into PyMOL.
            result = br.open('http://www.cheshift.com/jobs/%s/%s_b.pdb?r=%d' % (subfix, pdb_filenamenoext, test)).read()
            fd = tempfile.NamedTemporaryFile(bufsize=0,delete=False)
            fd.write(result)
            fd.close()
            pdb_tmp = fd.name
            pdblist = []
            for line in open(pdb_tmp).readlines():
                if 'ATOM' in line:
                    pdblist.append(line)
            first = int(pdblist[0][22:26])
            last = int(pdblist[-1][22:26])
            cmd.reinitialize()
            rename = ('%s_b.pdb' % (pdb_filenamenoext))
            cmd.load(pdb_tmp, rename)
            #CheShift does not provide results for the first or last residue
            cmd.remove('resi %s' % first) 
            cmd.remove('resi %s' % last)
            colorize()
            break
        except:
            test += 1
            try:# check for posible errors
                result = br.open('http://www.cheshift.com/jobs/%s/error.txt?r=%d' % (subfix, test)).read().split() # behind a proxy you need to add a "dummy" modifier to the requested file (?r=%d'). Otherwise you will just be checking the cached file and not the actual file.
                if int(result[0]) == 0:
                    Pmw.MessageDialog(title = 'Error',message_text=('The residue at position %s is missing from your PDB file\n Please fix the problem and try again' % (result[1])))
                elif int(result[0]) == 1:
                    Pmw.MessageDialog(title = 'Error',message_text = ('The residue %s%s in your PDB file does not match\n with residue %s%s in your chemical shift file.\n\n Please check your files and try again' % (result[1], result[3], result[2], result[3])))
                else:
                    Pmw.MessageDialog(title = 'Error',message_text=('Something went wrong while processing your request\n Please check your files and try again\n\nIf you could not find the problem please write to us'))
                break
            except:
                pass
        time.sleep(5)
Esempio n. 7
0
def process_molecule_mae(file_header, mol, suspend_undo):
    global already_processed
    global undo_each_molecule
    tot = []
    tot.extend(file_header)
    tot.extend(mol)
    molstr = string.join(tot,'')

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

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

    cmd.delete(tmpname)
    if undo_each_molecule:
        cmd.set("suspend_undo", suspend_undo, updates=0)
        cmd.push_undo("", just_coordinates=0, finish_undo=1)
    return True
Esempio n. 8
0
    def test(self):
        cmd.fab('AG')
        cmd.remove('hydro')
        cmd.h_add('resn ALA')

        # with this bug: count = 6
        self.assertEqual(11, cmd.count_atoms('byres (last hydro)'))
def load_rep(target, offtarget):
    tprot = target[0]
    tprot_type = target[1]
    tligs = target[2:]

    cmd.load(tprot, tprot_type)
    for lig in tligs:
        cmd.load(lig, '%s_poses' % tprot_type[0])
    ligand_cartoon('(%s_poses or %s)' % (tprot_type[0], tprot_type))
    cmd.set_name('polar_contacts', '%s_polar_contacts' % tprot_type[0])
    util.cbag('(%s_poses or %s)' % (tprot_type[0], tprot_type))
    if offtarget:
        oprot = offtarget[0]
        oprot_type = offtarget[1]
        oligs = offtarget[2:]

        cmd.load(oprot, 'Off-Target')
        for lig in oligs:
            cmd.load(lig, 'O_poses')
        ligand_cartoon('(O_poses or Off-Target)')
        cmd.set_name('polar_contacts', 'O_polar_contacts')
        util.cbam('(O_poses or Off-Target)')
    # cmd.bg_color('white')
    # representation(rep)
    cmd.remove("all & hydro & not nbr. (don.|acc.)")
Esempio n. 10
0
def homogenizechains(sel1,sel2):
   cmd.remove("hydro")
   cmd.remove("resn HOH")
   cmd.remove("(HET and not resn MSE+CSW)")
   a = cmd.get_model("%s and name ca"%(sel1))
   b = cmd.get_model("%s and name ca"%(sel2))
   sa = "".join([name1[x.resn] for x in a.atom])
   sb = "".join([name1[x.resn] for x in b.atom])
   if sa==sb: return True
   ra = [myint(x.resi) for x in a.atom]
   rb = [myint(x.resi) for x in b.atom]
#   if max(ra) - min(ra) + 1 != len(ra): print "missing residue numbers",max(ra),min(ra),len(ra)
#   if max(rb) - min(rb) + 1 != len(rb): print "missing residue numbers",rb
   mla,mua,mlb,mub = lcs(sa,sb)
   bla,bua,blb,bub = lcs(sa[  :mla],sb[  :mlb])
   ala,aua,alb,aub = lcs(sa[mua+1:],sb[mub+1:])
   ra = ra[mla:(mua+1)]
   rb = rb[mlb:(mub+1)]
   if len(ra[bla:(bua+1)]) > 10:
      ra = ra[bla:(bua+1)] + ra[mla:(mua+1)] + ra[ala:(aua+1)]
      rb = rb[blb:(bub+1)] + rb[mlb:(mub+1)] + rb[alb:(aub+1)]
   if len(ra[ala:(aua+1)]) > 10:
      ra += ra[ala:(aua+1)]
      rb += rb[alb:(aub+1)]      
   for c,i in getres("%s"%(sel1)):
      if not i in ra: cmd.remove("%s and resi %i"%(sel1,i))
   for c,i in getres("%s"%(sel2)):
      if not i in rb: cmd.remove("%s and resi %i"%(sel2,i))   
   return False
Esempio n. 11
0
def alignc4(sele,alignsele=None,tgtaxis=Vec(0,0,1),chains=["A","B","C","D"]):
	if alignsele is None: alignsele = sele
	cmd.remove(sele+" and resn HOH")
	axis = c3axis(sele,alignsele,chains)
	# print "axis of rotation:",axis
	alignaxis(sele,tgtaxis,axis,Vec(0,0,0))
	return True
Esempio n. 12
0
    def reload_system(self, ln: str, smis: oechem.OEMol, old_pdb: str, is_oe_already: bool = False):
        with self.logger("reload_system") as logger:
            logger.log("Loading {} with new smiles {}".format(old_pdb, ln))
            with tempfile.TemporaryDirectory() as dirpath:
                ofs = oechem.oemolostream("{}/newlig.mol2".format(dirpath))
                oechem.OEWriteMolecule(ofs, smis)
                ofs.close()
                cmd.reinitialize()
                cmd.load(old_pdb)
                cmd.remove("not polymer")
                cmd.load("{}/newlig.mol2".format(dirpath), "UNL")
                cmd.alter("UNL", "resn='UNL'")
                cmd.alter("UNL", "chain='A'")
                self.config.pdb_file_name = self.config.tempdir() + "reloaded.pdb"
                cmd.save(self.config.pdb_file_name)
                cmd.save(self.config.tempdir() + "apo.pdb")

                with open(self.config.pdb_file_name, 'r') as f:
                    self.pdb = app.PDBFile(f)
                self.positions, self.topology = self.pdb.getPositions(), self.pdb.getTopology()

                if self.config.explicit and self.config.method == 'amber':
                    self.system, self.topology, self.positions = self.__setup_system_ex_amber(
                        pdbfile=self.config.pdb_file_name)
                elif self.config.explicit:
                    self.system, self.topology, self.positions = self.__setup_system_ex_mm()
                else:
                    self.system, self.topology, self.positions = self.__setup_system_im( pdbfile=self.config.pdb_file_name)

        return self.system
Esempio n. 13
0
 def testUndoAfterRemoveAtomOnDiscrete(self, discr):
     cmd.set('suspend_undo', 0)
     cmd.load(self.datafile('ligs3d.sdf'), discrete=discr)
     natms = cmd.count_atoms()
     cmd.remove("index 1")
     cmd.undo()
     self.assertEqual(natms, cmd.count_atoms())
Esempio n. 14
0
def findSurfaceAtoms(selection="all", cutoff=2.5, quiet=1):
    """
DESCRIPTION

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

USAGE

    findSurfaceAtoms [ selection, [ cutoff ]]

SEE ALSO

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

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

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

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

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

    cmd.delete(tmpObj)

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

    return selName
Esempio n. 15
0
    def additional_cleanup(self):
        """Cleanup of various representations"""

        cmd.remove('not alt ""+A')  # Remove alternate conformations
        cmd.hide('labels', 'Interactions')  # Hide labels of lines
        cmd.disable('%sCartoon' % self.protname)
        cmd.hide('everything', 'hydrogens')
Esempio n. 16
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)]
Esempio n. 17
0
def slowpacking(pdb):
    "Derive mean packing density of pdb as pd.Series."
    cmd.delete('all')
    cmd.load(pdb)
    cmd.remove('solvent')
    # Only heavy atoms
    cmd.remove('hydro')
    # Compute SAS per atom
    cmd.set('dot_solvent')
    cmd.get_area('all', load_b=1)
    N = float(cmd.select('interior', 'b = 0'))

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

    # Count
    counts = pd.Series(0, index=RADS)
    for a, b in product(internal_coords, all_coords):
        es = euclid_step(a, b)
        if es is not None:
            counts.loc[es] += 1
    counts = counts.cumsum()
    # Mean per center atom
    meancounts = counts / N
    # Normalize to density
    volumina = pd.Series(4 / 3.0 * sp.pi * (RADS ** 3), index=RADS)
    density = meancounts / volumina
    # Correct for center
    density -= 1 / (4/3 * sp.pi * RADS ** 3)
    # Results
    counts.index = ["{}_correctcount".format(i) for i in counts.index]
    density.index = ["{}_density".format(i) for i in density.index]
    return pd.concat(([counts, density]))
Esempio n. 18
0
	def 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)
Esempio n. 19
0
def morph_movie(morph,
                view,
                color,
                base_name,
                frameno_offset=0,
                morph_reverse=False):
    number_of_states = cmd.count_states(morph)
    # after this I will have each state available as its own object, called "{morphname}_000x" (padded to length of 4)
    # x starts with 1 --> not clear - that might depend on the numbering in the input file
    cmd.split_states(morph)
    last_frame = frameno_offset
    for statenum in range(0, number_of_states + 1):
        if morph_reverse:
            statenum = max(1, cmd.count_states(morph) - statenum)
        else:
            statenum = min(statenum + 1, cmd.count_states(morph))
        state_name = morph + "_" + str(statenum).zfill(4)
        clump_representation([state_name], color, state_name),
        cmd.set_view(view)
        cmd.png(base_name + str(last_frame).zfill(3),
                width=1920,
                height=1080,
                ray=True)
        clump_cleanup([state_name], state_name)
        cmd.remove(state_name)
        last_frame += 1

    return last_frame
Esempio n. 20
0
def test_add_missing_atoms():
    cmd.reinitialize()
    cmd.load(DATA_PATH / '2x19-frag-mse.pdb')
    cmd.remove("not backbone")
    assert cmd.count_atoms("resi 132") == 4
    psico.modelling.add_missing_atoms('resi 132+133', cycles=10)
    assert cmd.count_atoms("resi 132") == 8
Esempio n. 21
0
def fetch_cath(code, name='', **kwargs):
    if name == '':
        name = code
    kwargs['async'] = 0
    r = fetch(code[:4], name, **kwargs)
    if cmd.is_error(r):
        return r
    if code[5:7] == '00':
        if code[4] != '0':
            cmd.remove(name + ' and not chain ' + code[4])
    else:
        try:
            if len(cath_domains) == 0:
                cath_parse_domall()
            d = cath_domains[code]
            rsele = ''
            for frag in d:
                chain, start, stop = frag
                rsele += ' (chain ' + chain
                if start and stop:
                    rsele += ' and resi %s-%s' % (start, stop)
                rsele += ')'
            cmd.remove(name + ' and not (' + rsele + ')')
        except:
            print(' Warning: CATH domain resiude range handling failed')
            return -1
Esempio n. 22
0
def fetch_cath(code, name='', **kwargs):
    if name == '':
        name = code
    r = fetch(code[:4], name, async=0, **kwargs)
    if cmd.is_error(r):
        return r
    if code[5:7] == '00':
        if code[4] != '0':
            cmd.remove(name + ' and not chain ' + code[4])
    else:
        try:
            if len(cath_domains) == 0:
                cath_parse_domall()
            d = cath_domains[code]
            rsele = ''
            for frag in d:
                chain, start, stop = frag
                rsele += ' (chain ' + chain
                if start and stop:
                    rsele += ' and resi %s-%s' % (start, stop)
                rsele += ')'
            cmd.remove(name + ' and not (' + rsele + ')')
        except:
            print ' Warning: CATH domain resiude range handling failed'
            return -1
def prepareprot_scaffold(preload, presave, receptor, postload, postsave,
                         algchoice):
    canproceed = False

    cmd.load(preload + receptor + postload)
    all_chains = cmd.get_chains(receptor)
    print(
        f'Which chains would you like to keep for protein {receptor}. It has following chains: ',
        all_chains)
    selectedchain = input(
        "Type the chain names seperated by space, \nif you want all chains, type 'all': "
    )
    chainstoremove = set(all_chains) - set(selectedchain.split(' '))
    if set(selectedchain.split(' ')).issubset(set(all_chains)):
        for chain in chainstoremove:
            cmd.remove('chain ' + chain)
            print(f'Chain {chain} removed.')
        canproceed = True
    elif selectedchain == 'all':
        print('All chains selected.')
        canproceed = True
    else:
        print(
            'Wrong chain selection. Type it like "A B 6" if you have three chains named A, B and 6'
        )

    if canproceed:
        cmd.remove('resn HOH')
        #cmd.h_add(selection='acceptors or donors')
        cmd.save(presave + receptor + postsave)
        subprocess.call(
            shlex.split(f'./prepareprot.sh {receptor} {algchoice}'))
def findSurfaceAtoms(selection="all", cutoff=2.5, quiet=1):
    """
DESCRIPTION

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

USAGE

    findSurfaceAtoms [ selection, [ cutoff ]]

SEE ALSO

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

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

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

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

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

    cmd.delete(tmpObj)

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

    return selName
Esempio n. 25
0
def fetch_scop(code, name='', **kwargs):
    if name == '':
        name = code
    kwargs['async'] = 0
    r = fetch(code[1:5], name, **kwargs)
    if cmd.is_error(r):
        return r
    try:
        import Bio.SCOP
        import MySQLdb
        conn = MySQLdb.connect(**mysql_kwargs)
        scop = Bio.SCOP.Scop(db_handle=conn)
        d = scop.getDomainBySid(code)
        if len(d.residues.fragments) > 0:
            rsele = ''
            for frag in d.residues.fragments:
                chain, start, stop = frag
                rsele += ' (chain ' + chain
                if start and stop:
                    rsele += ' and resi %s-%s' % (start, stop)
                rsele += ')'
            cmd.remove(name + ' and not (' + rsele + ')')
    except:
        print(' Warning: SCOP domain resiude range handling failed')
        return -1
Esempio n. 26
0
def pymol_mutate(file_name, chain, res_index):
    pymol.finish_launching()
    cmd.delete('all')
    selection = chain + '/' + res_index + '/'
    mutant = 'CYS'
    cmd.wizard("mutagenesis")
    pdb = file_name[:-4]
    cmd.load(file_name)
    cmd.remove('not (alt ''+A)')

    cmd.select('mut', 'resi ' + res_index + ' and chain ' + chain)
    if cmd.count_atoms('mut') == 0:
        return False

    cmd.refresh_wizard()
    cmd.get_wizard().set_mode(mutant)
    cmd.get_wizard().do_select(selection)
    nStates = cmd.count_states("mutation")
    for i in range(1, nStates + 1):
        cmd.get_wizard().do_select(selection)
        cmd.frame(i)
        cmd.get_wizard().apply()
        cmd.save("rec_" + str(res_index) + "_" + str(i) + ".pdb")

    cmd.set_wizard()
    cmd.remove(file_name[:-4])
    return True
Esempio n. 27
0
def fetch_scop(code, name="", **kwargs):
    if name == "":
        name = code
    r = fetch(code[1:5], name, async=0, **kwargs)
    if cmd.is_error(r):
        return r
    try:
        import Bio.SCOP
        import MySQLdb

        conn = MySQLdb.connect(**mysql_kwargs)
        scop = Bio.SCOP.Scop(db_handle=conn)
        d = scop.getDomainBySid(code)
        if len(d.residues.fragments) > 0:
            rsele = ""
            for frag in d.residues.fragments:
                chain, start, stop = frag
                rsele += " (chain " + chain
                if start and stop:
                    rsele += " and resi %s-%s" % (start, stop)
                rsele += ")"
            cmd.remove(name + " and not (" + rsele + ")")
    except:
        print " Warning: SCOP domain resiude range handling failed"
        return -1
Esempio n. 28
0
def fetch_cath(code, name="", **kwargs):
    if name == "":
        name = code
    r = fetch(code[:4], name, async=0, **kwargs)
    if cmd.is_error(r):
        return r
    if code[5:7] == "00":
        if code[4] != "0":
            cmd.remove(name + " and not chain " + code[4])
    else:
        try:
            if len(cath_domains) == 0:
                cath_parse_domall()
            d = cath_domains[code]
            rsele = ""
            for frag in d:
                chain, start, stop = frag
                rsele += " (chain " + chain
                if start and stop:
                    rsele += " and resi %s-%s" % (start, stop)
                rsele += ")"
            cmd.remove(name + " and not (" + rsele + ")")
        except:
            print " Warning: CATH domain resiude range handling failed"
            return -1
Esempio n. 29
0
 def testUndoAfterRemoveAtomOnDiscrete(self, discr):
     cmd.set('suspend_undo', 0)
     cmd.load(self.datafile('ligs3d.sdf'), discrete=discr)
     natms = cmd.count_atoms()
     cmd.remove("index 1")
     cmd.undo()
     self.assertEqual(natms, cmd.count_atoms())
Esempio n. 30
0
def process_molecule_sdf(mol, suspend_undo):
    global already_processed
    global undo_each_molecule
    nameorig = mol[0]
    name = nameorig.strip()
    if name in already_processed:
        return True
    already_processed = set(already_processed | set([name]))
    tmpname = "_temp_%s" % name
    molstr = string.join(mol,'')
    cmd.delete(tmpname)
    try:
        importing.read_sdfstr(molstr, tmpname,object_props='*')
        natoms = cmd.count_atoms(tmpname)
    except:
        return False
    if undo_each_molecule:
        cmd.push_undo( "( %s )" % name, just_coordinates=0)
        cmd.set("suspend_undo", 1, updates=0)
    cmd.remove(name)

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

    cmd.delete(tmpname)
    if undo_each_molecule:
        cmd.set("suspend_undo", suspend_undo, updates=0)
        cmd.push_undo("", just_coordinates=0, finish_undo=1)
    return True
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
Esempio n. 32
0
def fSumWMCresidue(molecule, SGNameAngle, chain, residue, MCNeighbour,
                   DieElecMC, MCchargeC, MCchargeO, MCchargeN, MCchargeH,
                   AmideName, printMC):
    # print "residue", MCNeighbour
    SumWMCresidue = 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
    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 + 'distResH', SGnameselect, Hnameselect)
    WMC = fWMC(MCchargeH, DieElecMC, ResDist)
    SumWMCresidue = SumWMCresidue + WMC
    if printMC == 'yes':
        print("MC H ", MCNeighbour, " ", MCchargeH, " ", DieElecMC, " ",
              ResDist, " ", WMC)
    # Mainchain C
    Cnameselect = "/" + molecule + "//" + chain + "/" + str(MCNeighbour) + "/C"
    ResDist = cmd.dist(residue + 'distResC', SGnameselect, Cnameselect)
    WMC = fWMC(MCchargeC, DieElecMC, ResDist)
    SumWMCresidue = SumWMCresidue + WMC
    if printMC == 'yes':
        print("MC C ", MCNeighbour, " ", MCchargeC, " ", DieElecMC, " ",
              ResDist, " ", WMC)
    # Mainchain O
    Onameselect = "/" + molecule + "//" + chain + "/" + str(MCNeighbour) + "/O"
    ResDist = cmd.dist(residue + 'distResO', SGnameselect, Onameselect)
    WMC = fWMC(MCchargeO, DieElecMC, ResDist)
    SumWMCresidue = SumWMCresidue + WMC
    if printMC == 'yes':
        print("MC O ", MCNeighbour, " ", MCchargeO, " ", DieElecMC, " ",
              ResDist, " ", WMC)
    # Mainchain N
    Nnameselect = "/" + molecule + "//" + chain + "/" + str(MCNeighbour) + "/N"
    ResDist = cmd.dist(residue + 'distResN', SGnameselect, Nnameselect)
    WMC = fWMC(MCchargeN, DieElecMC, ResDist)
    SumWMCresidue = SumWMCresidue + WMC
    if printMC == 'yes':
        print("MC N ", MCNeighbour, " ", MCchargeN, " ", DieElecMC, " ",
              ResDist, " ", WMC)
    cmd.delete(residue + 'distResH')
    cmd.delete(residue + 'distResC')
    cmd.delete(residue + 'distResO')
    cmd.delete(residue + 'distResN')
    cmd.show("nb_spheres", AmideName)
    cmd.delete("MC")
    return SumWMCresidue
Esempio n. 33
0
def read_siftp(filename):
  
  try:
    #first line in file contains averaged sift

    with open(filename, 'r') as f:
        siftline =  f.readline()
    
    min_aa, sift = siftline.split(':')
    sift = sift.split(' ')
    print sift
    
    for interaction in range(9):
      selection = []
      for index in range(len(sift[interaction::9])):
          if index == len(sift[interaction::9]) - 1:
              print len(sift[interaction::9])
              print 'index',index,
              print 'interaction',sift[interaction::9][index]
          if sift[interaction::9][index].strip() != '0':
              if interaction == 8:
                  print sift[interaction::9][index]
                  print int(min_aa) + index
                  print sift[index:index + 9]
              selection.append(str(int(min_aa)+index))
      if len(selection) > 0:
          cmd.select ( InteractionButton[interaction]+'_'+InteractionName[interaction], 'resi ' + "+".join(selection) )
      if interaction == 0:
          cmd.show ( 'sticks', InteractionButton[interaction]+'_'+InteractionName[interaction] )
    
      cmd.remove ( 'hydro' )
      print InteractionButton[interaction]+'_'+InteractionName[interaction], 'resi ' + "+".join(selection) 
      del selection

    with open(filename) as f:
        f.readline()
        #print 'here we go'
        for line in f.readlines():
            try:
                #print line
                resi= line.split()[0]
                fp = line.split()[1:]
                fp =  ''.join(fp)
                #print resi,fp
                if fp != '000000000':
                    #print 'yes',fp
                    cmd.select('residue '+resi,'resi '+ resi)
                    cmd.show('sticks','resi '+ resi)
                    cmd.label('residue '+resi,'resi')
                else:
                    #cmd.select('residue '+resi,'resi '+ resi)
                    #cmd.label('residue '+resi,'"no"')
                    #print 'no',fp
                    pass
            except:
                pass
    
  except Exception, e:
    print "Failed to open file %s\n%s" % (filename, e)
Esempio n. 34
0
def findSurfaceResidues(objSel="(all)",
                        cutoff=2.5,
                        doShow=False,
                        verbose=False):
    """
	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)

    return exposed
Esempio n. 35
0
def fetch_chain(code, name='', **kwargs):
    if name == '':
        name = code
    chain = code[4] if len(code) == 5 else code[5]
    r = fetch(code[:4], name, async=0, **kwargs)
    if cmd.is_error(r):
        return r
    cmd.remove(name + ' and not chain ' + chain)
Esempio n. 36
0
def test_get_seq():
    cmd.reinitialize()
    cmd.load(DATA_PATH / '2x19-frag-mse.pdb')
    assert psico.modelling.get_seq("all") == "LSMMPD"
    cmd.remove("resi 134")
    assert psico.modelling.get_seq("all") == "LS/MPD"
    cmd.alter("resi 137", "resn = 'XXX'")
    assert psico.modelling.get_seq("all", unknown="#") == "LS/MP#"
Esempio n. 37
0
def apply_symmetry(R, t, inchain, outchain):
    cmd.copy('symm', f'inpdb')
    coords = cmd.get_coords('symm')
    cmd.remove(f'symm and not chain {inchain}')
    coords_symm = (R.dot(coords.T)).T + t
    cmd.load_coords(coords_symm, 'symm')
    myspace = {'outchain': outchain}
    cmd.alter('symm', 'chain=f"{outchain}"', space=myspace)
Esempio n. 38
0
def test_stub2ala():
    cmd.reinitialize()
    cmd.fab('EFG', 'm1')
    cmd.remove('not (backbone or name CB)')
    psico.editing.stub2ala()
    my_values = []
    cmd.iterate('guide', 'my_values.append(resn)', space=locals())
    assert my_values == ['ALA', 'ALA', 'GLY']
Esempio n. 39
0
def fetch_chain(code, name='', **kwargs):
    if name == '':
        name = code
    chain = code[4] if len(code) == 5 else code[5]
    r = fetch(code[:4], name, async=0, **kwargs)
    if cmd.is_error(r):
        return r
    cmd.remove(name + ' and not chain ' + chain)
def removeions():
    cmd.select(
        "Ions",
        "((resn PO4) | (resn SO4) | (resn ZN) | (resn CA) | (resn MG) | (resn CL)) & hetatm"
    )
    cmd.remove("Ions")
    cmd.delete("Ions")
    return
    def _do_mutation(self):
        '''
        After selection, propose what the fragment will look like where
        applied.
        Exception: _do_mutation should be wrapped in a try-exception block
                   when called
        '''
        cmd = self.cmd

        cmd.delete(FRAG_NAME)
        cmd.refresh_wizard()

        if any(
                cmd.count_atoms("(%s) & name %s" % (SRC_SELE, name)) != 1
                for name in ("C1'", "C2'", "C3'", "C4'", "O4'")):
            self.clear()
            raise pymol.wizarding.WizardError(
                'Improper selection of nucleic acid.')

        frag_type_lower = self._mode_labels[self.mode].lower()
        cmd.fragment(frag_type_lower, FRAG_NAME, origin=0)
        self._update_reps()
        cmd.color("white", "%s & elem C" % FRAG_NAME)
        cmd.iterate("first (%s)" % SRC_SELE,
                    'stored.name = model+"/"+segi+"/"+chain+"/"+resn+"`"+resi',
                    space=self._space)
        self.res_text = self._space['stored'].name

        cmd.alter("?%s & name C1'" % SRC_SELE,
                  "stored.identifiers = (segi, chain, resi, ss, color)",
                  space=self._space)
        self._status = Status.MUTAGENIZING
        self.get_prompt()

        cmd.iterate("(%s & name C1')" % SRC_SELE,
                    "stored.resn = resn",
                    space=self._space)
        src_type_lower = self._space['stored'].resn.lower()
        self._src_O_atom_name, self._src_Cp_atom_name, self._src_N_atom_name, \
        self._src_C_atom_name = self._get_chi_dihedral_atoms(src_type_lower)

        self._frag_O_atom_name, self._frag_Cp_atom_name, self._frag_N_atom_name, \
        self._frag_C_atom_name = self._get_chi_dihedral_atoms(frag_type_lower)

        cmd.pair_fit("(%s & name %s)" % (FRAG_NAME, self._frag_O_atom_name),
                     "(%s & name %s)" % (SRC_SELE, self._src_O_atom_name),
                     "(%s & name %s)" % (FRAG_NAME, self._frag_Cp_atom_name),
                     "(%s & name %s)" % (SRC_SELE, self._src_Cp_atom_name),
                     "(%s & name %s)" % (FRAG_NAME, self._frag_N_atom_name),
                     "(%s & name %s)" % (SRC_SELE, self._src_N_atom_name))

        self._transfer_dihedral()

        for a in self._sugar_phos_atoms:
            cmd.remove("(%s & name %s)" % (FRAG_NAME, a))

        if self._auto_center == "ON":
            cmd.center(FRAG_NAME, animate=1)
def representation(mode='cartoon'):
    cmd.bg_color('white')
    cmd.remove('hydro')
    if mode == 'cartoon':
        ligand_cartoon()
    elif mode == 'ribbon':
        ligands()
    elif mode == 'surface':
        ligand_sites()
Esempio n. 43
0
 def adapt_for_peptides(self):
     """Adapt visualization for peptide ligands and interchain contacts"""
     cmd.hide('sticks', self.ligname)
     cmd.set('cartoon_color', 'lightorange', self.ligname)
     cmd.show('cartoon', self.ligname)
     cmd.show('sticks', "byres *-L")
     cmd.util.cnc(self.ligname)
     cmd.remove('%sCartoon and chain %s' % (self.protname, self.plcomplex.chain))
     cmd.set('cartoon_side_chain_helper', 0)
Esempio n. 44
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
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)
Esempio n. 46
0
def screenshotProteins():
    # proteinsPath = ".\pdbs"

    # set style parameters
    # cmd.set("ray_opaque_background", 0)
    # cmd.remove("solvent")
    cmd.set("ambient", 0.3)
    cmd.set("antialias", 1)
    cmd.bg_color("white")
    # cmd.set("direct", 1.0)
    # cmd.set("ribbon_radius", 0.2)
    # cmd.set("cartoon_highlight_color", "grey50")
    # cmd.set("ray_trace_mode", 1)
    # cmd.set("stick_radius", 0.2)
    # cmd.set("mesh_radius", 0.02)

    # loop thru folders
    # for dir in os.walk(proteinsPath):
    # proteinPath = dir[0]

    # loop thru pdbs
    # for file in os.listdir(proteinPath):
    # if file.endswith('.pdb'):

    csvFileName = "docked-protein-homomers.csv"

    # to loop through csv

    file = open(csvFileName, "r")
    reader = csv.reader(file, delimiter=",")
    k = 1
    for row in reader:
        for item in row:
            print(k, item)

            cmd.reinitialize()

            # load the pdb file
            cmd.fetch(item, path="./pdbs", type='pdb')
            #pdbPath= "./pdbs/" + item + ".cif"
            #cmd.load(pdbPath)
            color = pickAColor()
            cmd.color(color)
            cmd.show("cartoon")
            cmd.remove("solvent")

            # take a screenshot
            screenshotFileName = item + ".png"
            screenshotPath = os.path.join('screenshots', screenshotFileName)
            cmd.png(screenshotPath, 128, 128, ray=1)

            # clear
            cmd.delete("all")

            k = k + 1
Esempio n. 47
0
def get_coords(pdbfilename, object, device, selection=None):
    if selection is None:
        selection = f'{object} and name CA'
    else:
        selection = f'{object} and name CA and {selection}'
    cmd.load(pdbfilename, object=object)
    cmd.remove(f'not ({selection}) and {object}')
    coords = cmd.get_coords(selection=object)
    coords = torch.from_numpy(coords)
    coords = coords.to(device)
    return coords
Esempio n. 48
0
def generate_grid(rna,
                  outname="test",
                  grid_size=2,
                  padding=2.0,
                  mindist=2.5,
                  maxdist=5.0,
                  debug=False):
    # goto working directory

    # setup 3D grid
    extent = cmd.get_extent(selection=rna)
    x = np.arange(extent[0][0] - padding, extent[1][0] + padding, grid_size)
    y = np.arange(extent[0][1] - padding, extent[1][1] + padding, grid_size)
    z = np.arange(extent[0][2] - padding, extent[1][2] + padding, grid_size)
    xx, yy, zz = np.meshgrid(x, y, z)
    nx, ny, nz = xx.shape[0], xx.shape[1], xx.shape[2]

    # place pseudoatoms along grid
    k = 1
    for ix in tqdm(range(nx)):
        for iy in range(ny):
            for iz in range(nz):
                cmd.pseudoatom("tmpPoint",
                               hetatm=1,
                               name="C",
                               resn="UNK",
                               resi=k,
                               chain="ZZ",
                               pos=[
                                   float(xx[ix, iy, iz]),
                                   float(yy[ix, iy, iz]),
                                   float(zz[ix, iy, iz])
                               ])
                # prune
                cmd.remove("resn UNK and resi %s within %s of polymer" %
                           (k, mindist))
                cmd.remove("resn UNK and resi %s beyond %s of polymer" %
                           (k, maxdist))

    # write out grid file
    coor = "%s_grid.xyz" % (outname)
    xyz = cmd.get_coords('tmpPoint', 1)
    df = pd.DataFrame.from_records(xyz)
    df.insert(0, "element", "C")
    df.to_csv(coor, index=False, header=False, sep=" ")

    # write out complex
    cmd.create("complex", "%s tmpPoint" % rna)
    coor = "%s_grid.pdb" % (outname)
    cmd.save(coor, "complex")

    if debug:
        cmd.show("surface", "polymer")
        cmd.show("spheres", "resn UNK")
Esempio n. 49
0
 def test(self):
     cmd.set('suspend_undo')
     cmd.fragment('gly', 'm1')
     cmd.remove('not ID 0+1')
     cmd.create('m1', 'm1', 1, 2)
     cmd.rotate('x', 90, 'm1', 2)
     steps = 5
     cmd.morph('mout', 'm1', refinement=0, steps=steps, method='rigimol')
     self.assertEqual(steps, cmd.count_states('mout'))
     self.assertEqual(cmd.count_atoms('m1'),
                      cmd.count_atoms('mout'))
Esempio n. 50
0
def test_update_identifiers():
    cmd.reinitialize()
    cmd.fab('ACD', 'm1')
    cmd.fab('ACD', 'm2')
    cmd.remove('m1 and not backbone')
    cmd.alter('m1', '(segi, chain) = ("Segi", "Chain")')
    psico.editing.update_identifiers('m2', 'm1', identifiers='segi chain')
    assert cmd.get_chains('m2') == ['Chain']
    my_values = []
    cmd.iterate('m2', 'my_values.append(segi)', space=locals())
    assert set(my_values) == set(["Segi"])
Esempio n. 51
0
 def testRegression2207(self):
     '''
     The initial fix for PYMOL-1697 crashed this example
     (PYMOL-2207)
     '''
     cmd.load(self.datafile('1oky-frag.pdb'))
     cmd.create('1oky-frag', 'resi 80-100', 1, 2)
     cmd.remove('resi 85-95')
     # keep ray efford low
     cmd.viewport(50, 50)
     # caused segfault
     img = self.get_imagearray(ray=1)
Esempio n. 52
0
    def apply(self):
        '''
        Permanently applies the mutation upon the selected residue
        Overrides method from Wizard class
        '''
        cmd = self.cmd
        if self._status == Status.NO_SELECTION:
            return

        #Remove all atoms that are not in the sugar/phosphate group
        #Needed for non-canonical bases
        cmd.select("_tmp_sele_invert", "(none)")
        for a in self._sugar_phos_atoms:
            cmd.select("_tmp_sele_invert",
                       "_tmp_sele_invert | (%s & name %s)" % (SRC_SELE, a))

        cmd.select("_tmp_sele_invert",
                   "%s and not _tmp_sele_invert" % SRC_SELE)

        cmd.remove("_tmp_sele_invert")

        try:
            new_name = cmd.get_object_list(SRC_SELE)[0]
        except IndexError:
            print(" Mutagenesis: object not found.")
            return

        frag_name_three = self._mode_labels[self.mode]
        frag_name_one = self._base3_to_1[frag_name_three.lower()]

        # FUSE
        cmd.fuse(
            "%s & name %s" % (FRAG_NAME, self._frag_N_atom_name),
            "/%s/%s/%s/%s & name %s" %
            (new_name, self._stored.identifiers[0],
             self._stored.identifiers[1], self._stored.identifiers[2],
             self._src_Cp_atom_name), 1)

        #Check to see if DNA
        dnaPrefix = ''
        if cmd.count_atoms("%s & name O2'" % SRC_SELE) == 0:
            dnaPrefix = 'D'

        cmd.alter(
            "/%s/%s/%s/%s" %
            (new_name, self._stored.identifiers[0],
             self._stored.identifiers[1], self._stored.identifiers[2]),
            "(resn) = '%s%s'" % (dnaPrefix, frag_name_one.upper()),
            space=self._space)

        cmd.unpick()
        self.clear()
Esempio n. 53
0
def fSumWMCresidue(molecule, SGNameAngle, chain, residue, MCNeighbour, DieElecMC, MCchargeC, MCchargeO, MCchargeN, MCchargeH, AmideName, printMC):
    # print "residue", MCNeighbour
    SumWMCresidue = 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
    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 + 'distResH', SGnameselect, Hnameselect)
    WMC = fWMC(MCchargeH, DieElecMC, ResDist)
    SumWMCresidue = SumWMCresidue + WMC
    if printMC == 'yes':
        print("MC H ", MCNeighbour, " ", MCchargeH, " ", DieElecMC, " ", ResDist, " ", WMC)
    # Mainchain C
    Cnameselect = "/" + molecule + "//" + chain + "/" + str(MCNeighbour) + "/C"
    ResDist = cmd.dist(residue + 'distResC', SGnameselect, Cnameselect)
    WMC = fWMC(MCchargeC, DieElecMC, ResDist)
    SumWMCresidue = SumWMCresidue + WMC
    if printMC == 'yes':
        print("MC C ", MCNeighbour, " ", MCchargeC, " ", DieElecMC, " ", ResDist, " ", WMC)
    # Mainchain O
    Onameselect = "/" + molecule + "//" + chain + "/" + str(MCNeighbour) + "/O"
    ResDist = cmd.dist(residue + 'distResO', SGnameselect, Onameselect)
    WMC = fWMC(MCchargeO, DieElecMC, ResDist)
    SumWMCresidue = SumWMCresidue + WMC
    if printMC == 'yes':
        print("MC O ", MCNeighbour, " ", MCchargeO, " ", DieElecMC, " ", ResDist, " ", WMC)
    # Mainchain N
    Nnameselect = "/" + molecule + "//" + chain + "/" + str(MCNeighbour) + "/N"
    ResDist = cmd.dist(residue + 'distResN', SGnameselect, Nnameselect)
    WMC = fWMC(MCchargeN, DieElecMC, ResDist)
    SumWMCresidue = SumWMCresidue + WMC
    if printMC == 'yes':
        print("MC N ", MCNeighbour, " ", MCchargeN, " ", DieElecMC, " ", ResDist, " ", WMC)
    cmd.delete(residue + 'distResH')
    cmd.delete(residue + 'distResC')
    cmd.delete(residue + 'distResO')
    cmd.delete(residue + 'distResN')
    cmd.show("nb_spheres", AmideName)
    cmd.delete("MC")
    return SumWMCresidue
Esempio n. 54
0
def polyala(selection='all', quiet=1):
    '''
DESCRIPTION

    Mutate any residue to Alanine (except Glycines)

SEE ALSO

    stub2ala
    '''
    quiet = int(quiet)
    cmd.remove('polymer and (%s) and not name C+N+O+CA+CB+OXT' % (selection))
    cmd.alter('polymer and (%s) and not resn GLY' % (selection), 'resn = "ALA"')
    cmd.sort()
Esempio n. 55
0
def mark_res():
    """ mark_res <pdb_file> <highlight_residue>
    select the chain and residue that ICP dipeptide locate and highlight it.
    """
    #list of pdb id, chain id, and residues informations for ICP. the lower case pdbs are from blast,
    #upercase PDBs are from SGD pdb homologous search.
    pdb_input_lists = [('1fa0', 'A', '177-178', '117-147'),
                       ('1u5t', 'A', '42-43'),
                       ('1yke', 'A', '103-104', '43-73'),
                       ('2b1e', 'A', '294-295', '234-264'),
                       ('2PFV', 'A', '294-295', '234-264'),
                       ('1MNM', 'C', '177-178', '117-147'),
                       ('2ckz', 'D', '11-12'),
                       ('2pk9', 'D', '150-151+245-246', '90-120+185-215'),
                       ('2pmi', 'D', '150-151+245-246', '90-120+185-215'),
                       ('2xfv', 'A', '7-8'),
                       ('3esl', 'A', '191-192', '131-161'),
                       ('3n7n', 'E', '20-21'),
                       ('3t5v', 'E', '288-289', '228-258'),
                       ('4bh6', 'A', '365-366', '305-335')]
    #iterate pdbs
    for pdb_info in pdb_input_lists:
        pdb_id = pdb_info[0]
        chain_id = pdb_info[1]
        res_id = pdb_info[2]
        up_region = pdb_info[3] if len(pdb_info) == 4 else '0'
        pdb_file = pdb_id + ".pdb"
        chain_selection = "chain " + chain_id
        res_selection = "res " + res_id
        up_region_selection = "res " + up_region

        #command chains to process the pdb files.
        cmd.load(pdb_file)
        cmd.remove("solvent")
        cmd.color("gray80")
        cmd.show("cartoon")
        cmd.hide("line")
        cmd.select("monomer", chain_selection)
        cmd.color("cyan", "monomer")
        cmd.select("icp_dipep", chain_selection + " and " + res_selection)
        cmd.select("up_region", chain_selection + " and " + up_region_selection)
        cmd.select("none")
        cmd.color("red", "icp_dipep")
        cmd.color("yellow", "up_region")
        cmd.zoom(chain_selection)
        # cmd.zoom("all")
        cmd.png(pdb_id + ".png")
        cmd.save(pdb_id + ".pse")

        cmd.delete("all")
Esempio n. 56
0
    def testAtomLevelSettingsOnRemove2(self):
        if cmd.get_setting_int('suspend_undo'):
            self.skipTest("need suspend_undo=0")

        cmd.load(self.datafile("1molecule.mae"))
        cmd.load(self.datafile("1molecule.mae"))
        cmd.label("index 10", "'Test Label'")
        plv = [ 5., 0., 0.]
        cmd.alter("index 10", "s.label_placement_offset = %s" % plv)
        cmd.remove("index 10")
        cmd.undo()
        stored.offset = None
        cmd.iterate("index 10", "stored.offset = list(s.label_placement_offset)")
        self.assertEqual(stored.offset, plv)