Example #1
0
def minimize(selection='all', forcefield='MMFF94s', method='conjugate gradients', nsteps=500, conv=0.0001, cutoff=False, cut_vdw=6.0, cut_elec=8.0):
    pdb_string = cmd.get_pdbstr(selection)
    name = cmd.get_legal_name(selection)
    obconversion = ob.OBConversion()
    obconversion.SetInAndOutFormats('pdb', 'pdb')
    mol = ob.OBMol()
    obconversion.ReadString(mol, pdb_string)
    mol.AddHydrogens()
    ff = ob.OBForceField.FindForceField(forcefield)  # GAFF, MMFF94s, MMFF94, UFF, Ghemical
    ff.Setup(mol)
    if cutoff == True:
        ff.EnableCutOff(True)
        ff.SetVDWCutOff(cut_vdw)
        ff.SetElectrostaticCutOff(cut_elec)
    if method == 'conjugate gradients':
        ff.ConjugateGradients(nsteps, conv)
    else:
        ff.SteepestDescent(nsteps, conv)
    ff.GetCoordinates(mol)
    nrg = ff.Energy()
    pdb_string = obconversion.WriteString(mol)
    cmd.delete(name)
    if name == 'all':
        name = 'all_'
    cmd.read_pdbstr(pdb_string, name)
    print '#########################################'
    print 'The Energy of %s is %8.2f %s       ' % (name, nrg, ff.GetUnit())
    print '#########################################'
Example #2
0
    def gpssPeptide(pdbCode, reinitialize):

        if _gpssLoadPdb(pdbCode, reinitialize):

            # Get ligand surfaces
            peptideInfo = urllib2.urlopen(
                "http://gpss.mcsg.anl.gov/webservices/" + "gpssServerPymol.php?pdbId=" + pdbCode + "&mode=peptideInfo"
            )
            # Get pocket atoms
            for peptideSurface in peptideInfo:
                peptideSurfaceFile = urllib2.urlopen(
                    "http://gpss.mcsg.anl.gov/webservices/"
                    + "gpssServerPymol.php?pdbId="
                    + pdbCode
                    + "&surfaceId="
                    + peptideSurface
                    + "&mode=peptideSurface"
                )
                peptideId = peptideSurface.split(".")
                objectId = "Peptide-" + peptideId[1]
                cmd.read_pdbstr(peptideSurfaceFile.read(), objectId)
                cmd.do("hide everything," + objectId)
                cmd.do("show surface," + objectId)
                cmd.do("set transparency=0.2," + objectId)
            cmd.do("zoom GPSS-" + pdbCode)
Example #3
0
 def pdbDisplay(self):
   '''creates an actual pdb object of the protein or just the part near the
   surface/group of interest'''
   pdbText = "\n".join(self.pdbDatas[-1].rawData)
   cmd.read_pdbstr(
       pdbText, self.pdbNames[-1] + "." + str(self.drawCount) + ".pdb")
   self.drawCount += 1
Example #4
0
    def gpssCastp(pdbCode, reinitialize):
        if _gpssLoadPdb(pdbCode, reinitialize):

            # Get pocket count
            castpInfo = urllib2.urlopen(
                "http://gpss.mcsg.anl.gov/webservices/" + "gpssServerPymol.php?pdbId=" + pdbCode + "&mode=castpInfo"
            )
            castpLength = int(castpInfo.readlines()[-1][13:16])

            # Get pocket atoms
            while castpLength > 0:
                castpSurfaceFile = urllib2.urlopen(
                    "http://gpss.mcsg.anl.gov/webservices/"
                    + "gpssServerPymol.php?pdbId="
                    + pdbCode
                    + "&surfaceId="
                    + str(castpLength)
                    + "&mode=castpSurface"
                )
                objectId = "CASTp-" + str(castpLength)
                cmd.read_pdbstr(castpSurfaceFile.read(), objectId)
                cmd.do("hide everything," + objectId)
                cmd.do("show surface," + objectId)
                cmd.do("set transparency=0.2," + objectId)
                castpLength -= 1

        cmd.do("zoom GPSS-" + pdbCode)
Example #5
0
    def gpssLigand(pdbCode, reinitialize):

        if _gpssLoadPdb(pdbCode, reinitialize):

            # Get ligand surfaces
            ligandInfo = urllib2.urlopen(
                "http://gpss.mcsg.anl.gov/webservices/" + "gpssServerPymol.php?pdbId=" + pdbCode + "&mode=ligandInfo"
            ).read()
            if ligandInfo:
                ligandInfoArray = ligandInfo.split(":")

                # Get pocket atoms
                for ligandSurface in ligandInfoArray:
                    ligandSurfaceFile = urllib2.urlopen(
                        "http://gpss.mcsg.anl.gov/webservices/"
                        + "gpssServerPymol.php?pdbId="
                        + pdbCode
                        + "&surfaceId="
                        + ligandSurface
                        + "&mode=ligandSurface"
                    )
                    ligandId = ligandSurface.split(".")
                    objectId = "Ligand-" + ligandId[1] + "." + ligandId[2] + "." + ligandId[3]
                    cmd.read_pdbstr(ligandSurfaceFile.read(), objectId)
                    cmd.do("hide everything," + objectId)
                    cmd.do("show surface," + objectId)
                    cmd.do("show sticks," + objectId + " and resn " + ligandId[1])

                cmd.do("zoom GPSS-" + pdbCode)
Example #6
0
    def gpssMetal(pdbCode, reinitialize):

        if _gpssLoadPdb(pdbCode, reinitialize):

            # Get ligand surfaces
            metalInfo = urllib2.urlopen(
                "http://gpss.mcsg.anl.gov/webservices/" + "gpssServerPymol.php?pdbId=" + pdbCode + "&mode=metalInfo"
            ).read()

            if metalInfo:
                metalInfoArray = metalInfo.split(":")

                # Get pocket atoms
                for metalSurface in metalInfoArray:
                    metalSurfaceFile = urllib2.urlopen(
                        "http://gpss.mcsg.anl.gov/webservices/"
                        + "gpssServerPymol.php?pdbId="
                        + pdbCode
                        + "&surfaceId="
                        + metalSurface
                        + "&mode=metalSurface"
                    )
                    metalId = metalSurface.split(".")
                    objectId = "Metal-" + metalId[1] + "." + metalId[2] + "." + metalId[3]
                    cmd.read_pdbstr(metalSurfaceFile.read(), objectId)
                    cmd.do("hide everything," + objectId)
                    cmd.do("show surface," + objectId)
                    cmd.do("show sphere," + objectId + " and resn " + metalId[1])

                    cmd.do("zoom GPSS-" + pdbCode)
def deepshifts_load(index,
                    objname=None,
                    host='localhost',
                    port=7000,
                    atom_props=None):
    '''
    deepshifts_load(index, objname=None, host='localhost', port=7000)
    '''

    # get data
    req = requests.get('http://{}:{}/index/{}?fmt=proteindatabank'.format(
        host, port, index))
    data = req.json()

    # load object
    if objname is None:
        objname = 'obj-' + str(index)
    cmd.read_pdbstr(data['request'], objname)
    cmd.set_title(objname, 1, data['energy'][0])

    # load properties
    if atom_props is None:
        atom_props = ''

    props = {p: data[p] for p in atom_props.split() if p in data}

    for prop, values in props.iteritems():
        #for n,value in enumerate(values):
        #    selection = 'id %d in %s'%(n, objname)
        #    cmd.set_atom_property(prop, value, selection)
        cmd.iterate(objname,
                    'p["{}"]=l.pop(0)'.format(prop),
                    space={'l': values})
    pprint.pprint(data)
Example #8
0
def getSasa(sel="sele", normalized=0, probeSize=1.4):
    name = "SASA %3.1f" % probeSize
    if (normalized):
        name = "normSASA %3.1f" % probeSize

    cmd.read_pdbstr(
        PythonMSL.getSasa(cmd.get_pdbstr(sel), normalized, probeSize), name)
    def gpssMetal(pdbCode,reinitialize):
        
        if _gpssLoadPdb(pdbCode,reinitialize):

            # Get ligand surfaces
            metalInfo = urllib2.urlopen('http://gpss.mcsg.anl.gov/webservices/'+
                                        'gpssServerPymol.php?pdbId='+
                                        pdbCode + '&mode=metalInfo').read()

            if metalInfo:
                metalInfoArray = metalInfo.split(':')

                # Get pocket atoms
                for metalSurface in metalInfoArray:
                    metalSurfaceFile = urllib2.urlopen('http://gpss.mcsg.anl.gov/webservices/'+
                                                       'gpssServerPymol.php?pdbId='+ pdbCode +
                                                       '&surfaceId=' + metalSurface +
                                                       '&mode=metalSurface')
                    metalId = metalSurface.split('.')
                    objectId = 'Metal-' + metalId[1] + '.' + metalId[2] + '.' + metalId[3]
                    cmd.read_pdbstr(metalSurfaceFile.read(),objectId)
                    cmd.do('hide everything,' + objectId)
                    cmd.do('show surface,' + objectId)
                    cmd.do('show sphere,' + objectId + ' and resn ' + metalId[1])

                    cmd.do('zoom GPSS-'+pdbCode)
    def gpssLigand(pdbCode,reinitialize):
        
        if _gpssLoadPdb(pdbCode,reinitialize):

            # Get ligand surfaces
            ligandInfo = urllib2.urlopen('http://gpss.mcsg.anl.gov/webservices/'+
                                          'gpssServerPymol.php?pdbId='+
                                          pdbCode + '&mode=ligandInfo').read()
            if ligandInfo:
                ligandInfoArray = ligandInfo.split(':')

                # Get pocket atoms
                for ligandSurface in ligandInfoArray:
                    ligandSurfaceFile = urllib2.urlopen('http://gpss.mcsg.anl.gov/webservices/'+
                                                        'gpssServerPymol.php?pdbId='+ pdbCode +
                                                        '&surfaceId=' + ligandSurface +
                                                        '&mode=ligandSurface')
                    ligandId = ligandSurface.split('.')
                    objectId = 'Ligand-' + ligandId[1] + '.' + ligandId[2] + '.' + ligandId[3]
                    cmd.read_pdbstr(ligandSurfaceFile.read(),objectId)
                    cmd.do('hide everything,' + objectId)
                    cmd.do('show surface,' + objectId)
                    cmd.do('show sticks,' + objectId + ' and resn ' + ligandId[1])
                    
                cmd.do('zoom GPSS-'+pdbCode)
Example #11
0
def silent_load(filename, *tags, **kwds): # tags = empty loads all the strucutres. (kwds needed to eat a superflous _self parameter)
    """silent_load filename, [tags]

    Load the given tags from the given Rosetta binary-format silent file into appropriately named structures in Pymol.
    Tags can be zero or more comma separated tag. If no tags are given, load all availible tags.
    Python-style regex expansion can be used to match multiple tags. Regexes must match the entire tag to be accepted.
    """
    # Add start and end so we don't get partial matches.
    # Strip out whitespace and quote marks (shouldn't occur in tags or regex, but might occur due to terminal quoting)
    rextags = [ re.compile( "^" + t.strip().strip('"'+"'") + "$") for t in tags ]
    with open(filename) as f:
        while True:
            line = f.readline()
            if not line:
                break  # end of file
            line = line.strip()
            if not line:
                continue
            #In practice, ANNOTATED_SEQEUENCE always comes before coordiantes
            if line.startswith("ANNOTATED_SEQUENCE:"):
                tag = line.split()[-1]
                if checktags(tag, rextags):
                    PDBLINES = load_struct(tag, line, f)
                    if PDBLINES:
                        if cmd is not None:
                            # Load the PDB into Pymol
                            print("-- Loading structure " + tag)
                            cmd.read_pdbstr( PDBLINES, tag )
                        else:
                            outfilename = tag+".pdb"
                            print("-- Saving file " + outfilename)
                            with open(outfilename,'w') as of:
                                of.write(PDBLINES)
                            pass
Example #12
0
def minimize(selection='all',
             forcefield='MMFF94s',
             method='cg',
             nsteps=2000,
             conv=1E-6,
             cutoff=False,
             cut_vdw=6.0,
             cut_elec=8.0):
    pdb_string = cmd.get_pdbstr(selection)
    name = cmd.get_legal_name(selection)
    obconversion = ob.OBConversion()
    obconversion.SetInAndOutFormats('pdb', 'pdb')
    mol = ob.OBMol()
    obconversion.ReadString(mol, pdb_string)
    ff = ob.OBForceField.FindForceField(forcefield)
    ff.Setup(mol)
    if cutoff == True:
        ff.EnableCutOff(True)
        ff.SetVDWCutOff(cut_vdw)
        ff.SetElectrostaticCutOff(cut_elec)
    if method == 'cg':
        ff.ConjugateGradients(nsteps, conv)
    else:
        ff.SteepestDescent(nsteps, conv)
    ff.GetCoordinates(mol)
    nrg = ff.Energy()
    pdb_string = obconversion.WriteString(mol)
    cmd.delete(name)
    if name == 'all':
        name = 'all_'
    cmd.read_pdbstr(pdb_string, name)
    return nrg
 def addH(self):
     if reduceExe:
         seles = self.h_sel.getvalue()
         for sele in seles:
             if sele != '':
                 pdbStr = cmd.get_pdbstr(sele)
                 args = '"' + reduceExe + '"' + ' -BUILD -DB ' + '"' + reduceDB + '" -'
                 print args + " "
                 p = subprocess.Popen(args,
                                      shell=True,
                                      stdin=subprocess.PIPE,
                                      stdout=subprocess.PIPE,
                                      stderr=subprocess.PIPE)
                 newpdb = p.communicate(pdbStr)[0]
                 mynewsel = sele + '_H'
                 if self.h_newSel.getvalue() != '':
                     mynewsel = self.h_newSel.getvalue()
                 if self.replVar.get() == 1:
                     mynewsel = sele
                     cmd.delete(sele)
                 cmd.read_pdbstr(newpdb, mynewsel)
             else:
                 print "Could not determine selection"
     else:
         print reduceError
Example #14
0
def jsoner(sel):
	lens=[]
	states=[]
	q1=cmd.get_model(sel)
	lens.append(len(q1.atom))
	states.append(1)
	proc = Popen("goreduce", shell=True, stdin=PIPE, stdout=PIPE)
	options=json.dumps({"SelNames":[sel],"AtomsPerSel":lens,"StatesPerSel":states})  #, "IntOptions":[[5, 11]] })
	proc.stdin.write(options+"\n")
	for i in q1.atom:
		atom,coords=gochem.Atom2gcRef(i)
		proc.stdin.write(atom+"\n")
		proc.stdin.write(coords+"\n")
	proc.stdin.close()
#	if  proc.wait() != 1:
#		print "There were some errors"
#	for j in proc.stderr:
#		print(json.loads(j))
#	proc.stderr.close()	
#	for i in proc.stdout:
#		print json.loads(i)
	info = gochem.get_info(proc)
	mod=gochem.get_model(proc,info,0)

	cmd.load_model(mod,sel+"_Htmp",discrete=1,zoom=1)
	modR=cmd.get_pdbstr(sel+"_Htmp")
	cmd.read_pdbstr(modR,sel+"_H")
	cmd.delete(sel+"_Htmp")
	print "Jumalauta y wea"
Example #15
0
def localSamplingBR(
        system="all",
        fragSel="sele and name CA",
        bbqTable="/home/dwkulp/software/msl/tables/PiscesBBQTable.txt",
        numResults=25):
    cmd.read_pdbstr(
        PythonMSL.localSamplingBR(cmd.get_pdbstr(system),
                                  cmd.get_pdbstr(fragSel), numResults),
        "fragmentsBR")
Example #16
0
def create_model(self, name=None):
    """Creates PyMOL object connected with current structure (adds entry to Registry)"""
    if name is None:
        name = self.derived_from.name + "_" + \
            self.__class__.__name__[
                :4].lower() + str(Registry.get_next_number())
    Registry.add(self, name, 0, structure_flag=True)
    cmd.read_pdbstr(self.create_pdbstring(enumerate_atoms=True, transformed=True).read(), name, state=1)    # pylint: disable=protected-access
    cmd.set_title(name, 0, "PD")
Example #17
0
def conf_search(selection="all", forcefield="MMFF94s", method="Weighted", nsteps=500, conformers=25, lowest_conf=5):
    pdb_string = cmd.get_pdbstr(selection)
    name = cmd.get_legal_name(selection)
    obconversion = ob.OBConversion()
    obconversion.SetInAndOutFormats("pdb", "pdb")
    mol = ob.OBMol()
    obconversion.ReadString(mol, pdb_string)
    mol.AddHydrogens()
    ff = ob.OBForceField.FindForceField(forcefield)  ## GAFF, MMFF94s, MMFF94, UFF, Ghemical
    ff.Setup(mol)
    if method == "Weighted":
        ff.WeightedRotorSearch(conformers, nsteps)
    elif method == "Random":
        ff.RandomRotorSearch(conformers, nsteps)
    else:
        ff.SystematicRotorSearch(nsteps)
    if name == "all":
        name = "all_"
    if method in ["Weighted", "Random"]:
        ff.GetConformers(mol)
        print "##############################################"
        print "   Conformer    |         Energy      |  RMSD"
        nrg_unit = ff.GetUnit()
        rmsd = 0
        ff.GetCoordinates(mol)
        nrg = ff.Energy()
        conf_list = []
        for i in range(conformers):
            mol.SetConformer(i)
            ff.Setup(mol)
            nrg = ff.Energy()
            conf_list.append((nrg, i))
        conf_list.sort()
        lenght_conf_list = len(conf_list)
        if lowest_conf > lenght_conf_list:
            lowest_conf = lenght_conf_list
        for i in range(lowest_conf):
            nrg, orden = conf_list[i]
            name_n = "%s%02d" % (name, i)
            cmd.delete(name_n)
            mol.SetConformer(orden)
            pdb_string = obconversion.WriteString(mol)
            cmd.read_pdbstr(pdb_string, name_n)
            if i != 0:
                rmsd = cmd.fit(name_n, "%s00" % name, quiet=1)
            print "%15s | %10.2f%9s |%6.1f" % (name_n, nrg, nrg_unit, rmsd)
        print "##############################################"
    else:
        ff.GetCoordinates(mol)
        nrg = ff.Energy()
        pdb_string = obconversion.WriteString(mol)
        cmd.delete(name)
        cmd.read_pdbstr(pdb_string, name)
        print "#########################################"
        print "The Energy of %s is %8.2f %s       " % (name, nrg, ff.GetUnit())
        print "#########################################"
Example #18
0
def conf_search(selection='all', forcefield='MMFF94s', method='Weighted', nsteps=500, conformers=25, lowest_conf=5):
    pdb_string = cmd.get_pdbstr(selection)
    name = cmd.get_legal_name(selection)
    obconversion = ob.OBConversion()
    obconversion.SetInAndOutFormats('pdb', 'pdb')
    mol = ob.OBMol()
    obconversion.ReadString(mol, pdb_string)
    mol.AddHydrogens()
    ff = ob.OBForceField.FindForceField(forcefield)  # GAFF, MMFF94s, MMFF94, UFF, Ghemical
    ff.Setup(mol)
    if method == 'Weighted':
        ff.WeightedRotorSearch(conformers, nsteps)
    elif method == 'Random':
        ff.RandomRotorSearch(conformers, nsteps)
    else:
        ff.SystematicRotorSearch(nsteps)
    if name == 'all':
        name = 'all_'
    if method in ['Weighted', 'Random']:
        ff.GetConformers(mol)
        print '##############################################'
        print '   Conformer    |         Energy      |  RMSD'
        nrg_unit = ff.GetUnit()
        rmsd = 0
        ff.GetCoordinates(mol)
        nrg = ff.Energy()
        conf_list = []
        for i in range(conformers):
            mol.SetConformer(i)
            ff.Setup(mol)
            nrg = ff.Energy()
            conf_list.append((nrg, i))
        conf_list.sort()
        lenght_conf_list = len(conf_list)
        if lowest_conf > lenght_conf_list:
            lowest_conf = lenght_conf_list
        for i in range(lowest_conf):
            nrg, orden = conf_list[i]
            name_n = '%s%02d' % (name, i)
            cmd.delete(name_n)
            mol.SetConformer(orden)
            pdb_string = obconversion.WriteString(mol)
            cmd.read_pdbstr(pdb_string, name_n)
            if i != 0:
                rmsd = cmd.fit(name_n, '%s00' % name, quiet=1)
            print '%15s | %10.2f%9s |%6.1f' % (name_n, nrg, nrg_unit, rmsd)
        print '##############################################'
    else:
        ff.GetCoordinates(mol)
        nrg = ff.Energy()
        pdb_string = obconversion.WriteString(mol)
        cmd.delete(name)
        cmd.read_pdbstr(pdb_string, name)
        print '#########################################'
        print 'The Energy of %s is %8.2f %s       ' % (name, nrg, ff.GetUnit())
        print '#########################################'
Example #19
0
def localSamplingCCD(
        system="all",
        fragSel="sele and name CA",
        bbqTable="/export/home/brettth/projectsS/code/tree/mslib/trunk/tables/PiscesBBQTable.txt",
        angle=10,
        numResults=25):
    cmd.read_pdbstr(
        PythonMSL.localSamplingCCD(cmd.get_pdbstr(system),
                                   cmd.get_pdbstr(fragSel), numResults, angle,
                                   bbqTable), "fragmentsCCD")
 def remote(self,pdbCode):
     pdbCode = pdbCode.upper()
     try:
         pdbFile = urllib.urlopen('http://www.rcsb.org/pdb/cgi/export.cgi/' +
                                    pdbCode + '.pdb.gz?format=PDB&pdbId=' +
                                    pdbCode + '&compression=gz')
         cmd.read_pdbstr(zlib.decompress(pdbFile.read()[22:], -zlib.MAX_WBITS), pdbCode)
     except:
         print("Unexpected error: "+sys.exc_info()[0])
         tkinter.messagebox.showerror('Invalid Code',
                                'You entered an invalid pdb code:' + pdbCode)
Example #21
0
def load_chimerax(filename):
    """
        Load a UCSF ChimeraX file written by SwissDock

        Parameters
        ----------
        filename : str
            chimerax file (XML file with URL of target and ligands cluster)
    """

    # UCSF Chimera Web Data Format
    # www.cgl.ucsf.edu/chimera/docs/ContributedSoftware/webdata/chimerax.html

    docked = get_docked()

    print(f" PyViewDock: Loading \"{filename}\"")

    # read ChimeraX file as XML
    try:
        chimerax_xml = ET.parse(filename).getroot()
        target_url = chimerax_xml.find('web_files').find('file').get('loc')
        commands = chimerax_xml.find('commands').find('py_cmd').text
        cluster_url = re.findall('"(http[^"]+pdb)"', commands)[0]
        target_filename = target_url.split('/')[-1]
        cluster_filename = cluster_url.split('/')[-1]
        if not all(
            [target_url, cluster_url, target_filename, cluster_filename]):
            raise ValueError
    except FileNotFoundError:
        print(" PyViewDock: Failed reading 'chimerax' file. File not found.")
    except:
        print(" PyViewDock: Failed reading 'chimerax' file. Invalid format.")
    else:
        # fetch files from server
        try:
            target_pdb = urlopen(target_url).read().decode('utf-8')
            cluster_pdb = urlopen(cluster_url).readlines()
            cluster_pdb = [i.decode('utf-8') for i in cluster_pdb]
            cmd.read_pdbstr(target_pdb, 'target')
            docked.load_dock4(cluster_pdb, 'cluster', 0)
        except HTTPError:
            print(
                " PyViewDock: Failed reading 'chimerax' file. Bad server response. Too old?"
            )
            # find local files that match names in .chimerax directory
            chimerax_directory = os.path.dirname(os.path.realpath(filename))
            target_file = os.path.join(chimerax_directory, target_filename)
            cluster_file = os.path.join(chimerax_directory, cluster_filename)
            if os.path.isfile(target_file) and os.path.isfile(target_file):
                print(
                    f" PyViewDock: Files found locally ({target_filename}, {cluster_filename}). Loading..."
                )
                importing.load(target_file)
                load_dock4(cluster_file)
Example #22
0
def minimize(selection='tmp',
             forcefield='MMFF94',
             method='steepest descent',
             nsteps=2000,
             conv=1E-6,
             cutoff=False,
             cut_vdw=6.0,
             cut_elec=8.0,
             rigid_geometry=True):
    """
    Use openbabel to minimize the energy of a molecule.
    """
    pdb_string = cmd.get_pdbstr(selection)
    name = cmd.get_legal_name(selection)
    obconversion = ob.OBConversion()
    obconversion.SetInAndOutFormats('pdb', 'pdb')
    mol = ob.OBMol()
    obconversion.ReadString(mol, pdb_string)
    if rigid_geometry:
        constraints = ob.OBFFConstraints()
        for angle in ob.OBMolAngleIter(mol):
            b, a, c = [mol.GetAtom(x + 1) for x in angle]
            value = mol.GetAngle(a, b, c)
            b, a, c = [x + 1 for x in angle]
            constraints.AddAngleConstraint(a, b, c, value)
        for i in ob.OBMolBondIter(mol):
            a, b = (i.GetBeginAtomIdx(), i.GetEndAtomIdx())
            value = i.GetLength()
            constraints.AddDistanceConstraint(a, b, value)
        ff = ob.OBForceField.FindForceField(forcefield)
        ff.Setup(mol, constraints)
        ff.SetConstraints(constraints)
    else:
        ff = ob.OBForceField.FindForceField(forcefield)
        ff.Setup(mol)
    if cutoff:
        ff.EnableCutOff(True)
        ff.SetVDWCutOff(cut_vdw)
        ff.SetElectrostaticCutOff(cut_elec)
    if method == 'conjugate gradients':
        ff.ConjugateGradients(nsteps, conv)
    else:
        ff.SteepestDescent(nsteps, conv)
    ff.GetCoordinates(mol)
    nrg = ff.Energy()
    pdb_string = obconversion.WriteString(mol)
    cmd.delete(name)
    if name == 'all':
        name = 'all_'
    cmd.delete(selection)
    cmd.read_pdbstr(pdb_string, selection)
    return nrg
Example #23
0
    def wrapped_load_structure(self, code, *args, **kwargs):
        """Wrapped load_structure method: loads structures from databases or from local copy of PDB file.

        Creates PyMOL objects and returns a list of PyDesc structures connected with those objects.
        Arguments:
        code -- str, pdb code; check PyDesc documentation for more information.
        """
        list_of_structures = current_load_structure(self, code, *args, **kwargs)
        for structure_index, structure_obj in enumerate(list_of_structures):
            cmd.read_pdbstr(structure_obj.create_pdbstring(transformed=False).read(), structure_obj.name, state=structure_index + 1)  # pylint: disable=protected-access
            Registry.add(structure_obj, structure_obj.name, structure_index + 1, structure_flag=True)
            cmd.set_title(structure_obj.name, structure_index + 1, "PD")
        return list_of_structures
Example #24
0
def localSamplingPDB(
        system="all",
        fragSel="sele and name CA",
        fragDB="/var/lib/python-support/python2.6/pmg_tk/startup/lbbs/nr1000.fragdb",
        numRes=-1,
        rmsdTol=0.0,
        bbqTable="/var/lib/python-support/python2.6/pmg_tk/startup/lbbs/PiscesBBQTable.txt",
        numResults=25):
    cmd.read_pdbstr(
        PythonMSL.localSamplingPDB(cmd.get_pdbstr(system),
                                   cmd.get_pdbstr(fragSel), fragDB, numRes,
                                   rmsdTol, numResults, bbqTable),
        "fragmentsPDB")
Example #25
0
def LoadNew(model, name, template=None, PDBstr=False, state=0, discrete=0):
    if PDBstr:
        tmpname = name + "_tmp"
        cmd.load_model(model, tmpname, discrete=discrete, zoom=1)
        modR = cmd.get_pdbstr(tmpname)
        cmd.read_pdbstr(modR, name)
        cmd.delete(tmpname)
        return
    if template:
        model.bond = template.bond
    else:
        add_bonds(model)
    cmd.load_model(model, name, state=state, discrete=discrete)
Example #26
0
def resiCBpick(seletedChain=False):
    '''处理表位残基序列,获取其中的CB原子信息,该函数依赖 resiPick()'''

    cblist = []
    i = resipick(seletedChain)
    cb = "cb_left"
    test = "test"
    cmd.read_pdbstr(i, test)
    cmd.select(cb, "name cb " + " in " +
               test)
    cblist = cmd.get_pdbstr('cb')

    return cblist
Example #27
0
    def _gpssLoadPdb(pdbCode,reinitialize):

        pdbCode = pdbCode.lower()
        
        GPSSpdbCode = 'GPSS_' + pdbCode

        _gpssVersionCheck('0.3');

        if cmd.get_names().count(GPSSpdbCode) < 1:
                
            if reinitialize==1:
                cmd.do('reinitialize')
                
            pdbFile = urllib2.urlopen('http://gpss.mcsg.anl.gov/webservices/'+
                                      'gpssServerPymol.php?pdbId='+
                                      pdbCode + '&mode=pdbFile').read()
            
            
            if pdbFile:
                pdbFile = urllib2.urlopen('http://gpss.mcsg.anl.gov/webservices/'+
                                          'gpssServerPymol.php?pdbId='+
                                          pdbCode + '&mode=pdbFile')
                cmd.read_pdbstr(pdbFile.read(),GPSSpdbCode)
            
                # Make structure pretty
                # David Borhani, 14-JAN-2009
                # Changed to color by chain, show lines only, keep user's bg color.
                #cmd.do('set bg_rgb=[1,1,1]')
                #cmd.do('hide everything')
                cmd.hide('everything', GPSSpdbCode)
                #cmd.do('dss')
                cmd.dss(GPSSpdbCode)
                #util.cbc(selection='(GPSS-' + pdbCode + ')',first_color=7,quiet=1,legacy=1,_self=cmd)
                #sel_string = '("' + GPSSpdbCode + '")'
                #cmd.do('util.cbc(selection=' + sel_string + ',first_color=9,quiet=1,legacy=1)')
                cmd.do('util.cbc(selection=("' + GPSSpdbCode + '"),first_color=9,quiet=1,legacy=1)')
                #cmd.do('show lines, ' + GPSSpdbCode)
                cmd.show('lines', GPSSpdbCode)
                #cmd.do('show cartoon, ' + GPSSpdbCode)
                #cmd.do('color gray')
                return True
            else:
                tkMessageBox.showerror('GPSS                                    ',
                                       pdbCode + ' was not found on the GPSS server.')

            #cmd.do('zoom GPSS-'+pdbCode)
            cmd.zoom(GPSSpdbCode, animate=0)

        else:

            return True
Example #28
0
def resiCApick(seletedChain=False):
    
	calist = []
	i = resipick(seletedChain)
	ca = "ca_left"
	test = "test"
	cmd.read_pdbstr(i, test)
	cmd.select(ca, "name ca " + " in " + test)
	calist = cmd.get_pdbstr('ca')
    
    
	cmd.delete(test)
	cmd.delete(ca)
	return calist
Example #29
0
def resiCApick(seletedChain=False):
    '''处理表位残基序列,获取其中的CA原子信息,该函数依赖 resiPick()'''
    calist = []
    i = resipick(seletedChain)
    ca = "ca_left"
    test = "test"
    cmd.read_pdbstr(i, test)
    cmd.select(ca, "name ca " + " in " +
               test)
    calist = cmd.get_pdbstr('ca')
    
    #resiPick的结果包含了全序列和残基序列,需要将位于后部的残基序列单独提取

    return calist
Example #30
0
    def testSaveANISO(self):
        cmd.read_pdbstr(v_pdbstr_anisou, 'm1')
        v = cmd.get_pdbstr()
        self.assertEqual(v, v_pdbstr_anisou, 'ANISOU records missing:\n' + v)

        cmd.rotate('y', 30, object='m1')
        cmd.translate([20, 0, 0], object='m1')
        cmd.rotate('z', 20, object='m1')

        v = cmd.get_pdbstr()
        self.assertEqual(v, v_pdbstr_rotated, 'ANISOU not rotated in PDB string' + v)

        v = cmd.get_model('m1').atom[0].u_aniso
        self.assertArrayEqual(v, [0.183853, 0.378995, 0.309052, -0.103350, 0.125751, 0.050349],
                1e-5, 'ANISOU not rotated in chempy model')
    def gpssDna(pdbCode,reinitialize):
        
        if _gpssLoadPdb(pdbCode,reinitialize):

            # Get sites
            dna = urllib2.urlopen('http://gpss.mcsg.anl.gov/webservices/'+
                                  'gpssServerPymol.php?pdbId='+
                                  pdbCode + '&mode=dnaSurface').read()
            if dna:
                objectId = 'DNA-'+pdbCode;
                cmd.read_pdbstr(dna,objectId)
                cmd.do('hide everything,' + objectId)
                cmd.do('show surface,' + objectId)
                cmd.do('set transparency=0.2,'+ objectId) 
                cmd.do('zoom GPSS-'+pdbCode)
Example #32
0
    def gpssDna(pdbCode, reinitialize):

        if _gpssLoadPdb(pdbCode, reinitialize):

            # Get sites
            dna = urllib2.urlopen(
                "http://gpss.mcsg.anl.gov/webservices/" + "gpssServerPymol.php?pdbId=" + pdbCode + "&mode=dnaSurface"
            ).read()
            if dna:
                objectId = "DNA-" + pdbCode
                cmd.read_pdbstr(dna, objectId)
                cmd.do("hide everything," + objectId)
                cmd.do("show surface," + objectId)
                cmd.do("set transparency=0.2," + objectId)
                cmd.do("zoom GPSS-" + pdbCode)
Example #33
0
    def gpssSitesCsa(pdbCode, reinitialize):

        if _gpssLoadPdb(pdbCode, reinitialize):

            # Get sites
            sites = urllib2.urlopen(
                "http://gpss.mcsg.anl.gov/webservices/" + "gpssServerPymol.php?pdbId=" + pdbCode + "&mode=sitesCsa"
            ).read()
            if sites:
                objectId = "SITES-CSA-" + pdbCode
                cmd.read_pdbstr(sites, objectId)
                cmd.do("hide everything," + objectId)
                cmd.do("show spheres," + objectId)
                cmd.do("color yellow," + objectId)
                cmd.do("zoom GPSS-" + pdbCode)
    def gpssSitesCsa(pdbCode,reinitialize):
        
        if _gpssLoadPdb(pdbCode,reinitialize):

            # Get sites
            sites = urllib2.urlopen('http://gpss.mcsg.anl.gov/webservices/'+
                                    'gpssServerPymol.php?pdbId='+
                                    pdbCode + '&mode=sitesCsa').read()
            if sites:
                objectId = 'SITES-CSA-'+pdbCode;
                cmd.read_pdbstr(sites,objectId)
                cmd.do('hide everything,' + objectId)
                cmd.do('show spheres,' + objectId)
                cmd.do('color yellow,' + objectId)
                cmd.do('zoom GPSS-'+pdbCode)
Example #35
0
def minimize(selection='tmp', forcefield='MMFF94', method='steepest descent', nsteps= 2000, conv=1E-6, cutoff=False, cut_vdw=6.0, cut_elec=8.0, rigid_geometry=True):
    """
    Write Me!
    """
    pdb_string = cmd.get_pdbstr(selection)
    name = cmd.get_legal_name(selection)
    obconversion = ob.OBConversion()
    obconversion.SetInAndOutFormats('pdb', 'pdb')
    mol = ob.OBMol()
    obconversion.ReadString(mol, pdb_string)
    if rigid_geometry:
        constraints = ob.OBFFConstraints()
        for angle in ob.OBMolAngleIter(mol):
            b, a, c = [mol.GetAtom(x+1) for x in angle] 
            value = mol.GetAngle(a, b, c)
            b, a, c = [x+1 for x in angle]
            constraints.AddAngleConstraint(a, b, c, value)
        for i in ob.OBMolBondIter(mol):
            a, b = (i.GetBeginAtomIdx(), i.GetEndAtomIdx())
            value = i.GetLength()
            constraints.AddDistanceConstraint(a, b, value)
        ff = ob.OBForceField.FindForceField(forcefield)
        ff.Setup(mol, constraints)
        ff.SetConstraints(constraints)
    else:
        ff = ob.OBForceField.FindForceField(forcefield)
        ff.Setup(mol)
    if cutoff:
        ff.EnableCutOff(True)
        ff.SetVDWCutOff(cut_vdw)
        ff.SetElectrostaticCutOff(cut_elec)
    if method == 'conjugate gradients':
        ff.ConjugateGradients(nsteps, conv)
    else:
        ff.SteepestDescent(nsteps, conv)
    ff.GetCoordinates(mol)
    nrg = ff.Energy()
    pdb_string = obconversion.WriteString(mol)
    cmd.delete(name)
    if name == 'all':
        name = 'all_'
    cmd.delete(selection)
    cmd.read_pdbstr(pdb_string, selection)
    return nrg
Example #36
0
    def test(self):
        cmd.read_pdbstr(v_pdbstr_anisou, 'm1')

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

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

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

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

        # Attention: Not sure if rotation is numerically stable across
        # platforms. Fuzzy comparison might be needed.
        self.assertEqual(cmd.get_pdbstr('m1'), v_pdbstr_rotated)
    def gpssPeptide(pdbCode,reinitialize):
        
        if _gpssLoadPdb(pdbCode,reinitialize):

            # Get ligand surfaces
            peptideInfo = urllib2.urlopen('http://gpss.mcsg.anl.gov/webservices/'+
                                          'gpssServerPymol.php?pdbId='+
                                          pdbCode + '&mode=peptideInfo')
            # Get pocket atoms
            for peptideSurface in peptideInfo:
                peptideSurfaceFile = urllib2.urlopen('http://gpss.mcsg.anl.gov/webservices/'+
                                                     'gpssServerPymol.php?pdbId='+ pdbCode +
                                                     '&surfaceId=' + peptideSurface +
                                                     '&mode=peptideSurface')
                peptideId = peptideSurface.split('.')
                objectId = 'Peptide-' + peptideId[1]
                cmd.read_pdbstr(peptideSurfaceFile.read(),objectId)
                cmd.do('hide everything,' + objectId)
                cmd.do('show surface,' + objectId)
                cmd.do('set transparency=0.2,'+ objectId) 
            cmd.do('zoom GPSS-'+pdbCode)
Example #38
0
def gzload(id):
    # if filename doesn't exist, try it as a PDBID
    if not os.path.exists(id):
        filename = pdbutils.pdbfilename(id)
        label = id
    else:
        filename = id
        label = os.path.basename(filename)

    # Abort if file doesn't exist
    if not filename or not os.path.exists(filename):
        print "Error: id=%(id)s Can not find %(filename)s" % vars()
        return

    # read the data
    fh = gzip.open(filename)
    data = fh.read()
    fh.close()

    # load it into pymol
    cmd.read_pdbstr(data,label)
Example #39
0
def reduce_object(obj, flip=1):
    """Add hydrogens to a copy of a loaded PyMOL object with Reduce.

    TODO: more doc here

    """
    # Run reduce with specified flips
    pdbstr = cmd.get_pdbstr(obj)
    reduced_pdbstr = generate_reduce_output(pdbstr, flip_type=flip)

    # Fail gracefully if no output is generated.
    if not reduced_pdbstr:
        msg = "Failed to generate Reduce output for {}.".format(obj)
        logger.error(msg)
        return

    withflips = " with flips" if flip else ""
    logger.info("Generated Reduce output{} for '{}'.".format(withflips, obj))

    # Process the output string for flips
    flips_list = process_reduce_output(reduced_pdbstr)
    logger.info("Processed Reduce output to extract list of flips.")

    # Store flips list and raw reduced_pdbstr in MPObject
    o = get_or_create_object(obj)
    o.flips = flips_list
    o.reduce_output = reduced_pdbstr

    # Store current group_auto_mode setting
    gam = cmd.get('group_auto_mode')
    cmd.set('group_auto_mode', 2)

    # Load the output PDB into a copy of the original and disable the original.
    name = o.pdb['reduce']
    cmd.create(name, obj)  # duplicate original to preserve representation
    cmd.read_pdbstr(reduced_pdbstr, name, state=1)
    cmd.disable(obj)

    # Restore original group_auto_mode
    cmd.set('group_auto_mode', gam)
Example #40
0
    def test(self, matrix_mode):
        cmd.viewport(100, 100)
        cmd.set('matrix_mode', matrix_mode)
        cmd.set('ambient', 1.0)

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

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

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

        pdbstr = cmd.get_pdbstr('m1')
        cmd.delete('*')
        cmd.read_pdbstr(pdbstr, 'm1', zoom=0)
        self._rep()
        self.assertImageEqual(ref, count=100, msg='ANISOU not aligned in PDB')
Example #41
0
def reduce_object(obj, flip=1):
    """Add hydrogens to a copy of a loaded PyMOL object with Reduce.

    TODO: more doc here

    """
    # Run reduce with specified flips
    pdbstr = cmd.get_pdbstr(obj)
    reduced_pdbstr = generate_reduce_output(pdbstr, flip_type=flip)

    # Fail gracefully if no output is generated.
    if not reduced_pdbstr:
        msg = "Failed to generate Reduce output for {}.".format(obj)
        logger.error(msg)
        return

    withflips = " with flips" if flip else ""
    logger.info("Generated Reduce output{} for '{}'.".format(withflips, obj))

    # Process the output string for flips
    flips_list = process_reduce_output(reduced_pdbstr)
    logger.info("Processed Reduce output to extract list of flips.")

    # Store flips list and raw reduced_pdbstr in MPObject
    o = get_or_create_object(obj)
    o.flips = flips_list
    o.reduce_output = reduced_pdbstr

    # Store current group_auto_mode setting
    gam = cmd.get('group_auto_mode')
    cmd.set('group_auto_mode', 2)

    # Load the output PDB into a copy of the original and disable the original.
    name = o.pdb['reduce']
    cmd.create(name, obj)  # duplicate original to preserve representation
    cmd.read_pdbstr(reduced_pdbstr, name, state=1)
    cmd.disable(obj)

    # Restore original group_auto_mode
    cmd.set('group_auto_mode', gam)
Example #42
0
    def _gpssLoadPdb(pdbCode, reinitialize):

        pdbCode = pdbCode.lower()

        _gpssVersionCheck("0.3")

        if cmd.get_names().count("GPSS-" + pdbCode) < 1:

            if reinitialize == 1:
                cmd.do("reinitialize")

            pdbFile = urllib2.urlopen(
                "http://gpss.mcsg.anl.gov/webservices/" + "gpssServerPymol.php?pdbId=" + pdbCode + "&mode=pdbFile"
            ).read()

            if pdbFile:
                pdbFile = urllib2.urlopen(
                    "http://gpss.mcsg.anl.gov/webservices/" + "gpssServerPymol.php?pdbId=" + pdbCode + "&mode=pdbFile"
                )
                cmd.read_pdbstr(pdbFile.read(), "GPSS-" + pdbCode)

                # Make structure pretty
                cmd.do("set bg_rgb=[1,1,1]")
                cmd.do("hide everything")
                cmd.do("dss")
                cmd.do("show cartoon, GPSS-" + pdbCode)
                cmd.do("color gray")
                return True
            else:
                tkMessageBox.showerror(
                    "GPSS                                    ", pdbCode + " was not found on the GPSS server."
                )

            cmd.do("zoom GPSS-" + pdbCode)

        else:

            return True
    def _gpssLoadPdb(pdbCode,reinitialize):

        pdbCode = pdbCode.lower()

        _gpssVersionCheck('0.1');

        if cmd.get_names().count('GPSS-'+pdbCode) < 1:
                
            if reinitialize==1:
                cmd.do('reinitialize')
                
            pdbFile = urllib2.urlopen('http://gpss.mcsg.anl.gov/webservices/'+
                                      'gpssServerPymol.php?pdbId='+
                                      pdbCode + '&mode=pdbFile').read()
            
            
            if pdbFile:
                pdbFile = urllib2.urlopen('http://gpss.mcsg.anl.gov/webservices/'+
                                          'gpssServerPymol.php?pdbId='+
                                          pdbCode + '&mode=pdbFile')
                cmd.read_pdbstr(pdbFile.read(),'GPSS-'+pdbCode)
            
                # Make structure pretty
                cmd.do('set bg_rgb=[1,1,1]')
                cmd.do('hide everything')
                cmd.do('dss')
                cmd.do('show cartoon, GPSS-' + pdbCode)
                cmd.do('color gray')
                return True
            else:
                tkMessageBox.showerror('GPSS                                    ',
                                       pdbCode + ' was not found on the GPSS server.')

            cmd.do('zoom GPSS-'+pdbCode)

        else:

            return True
    def gpssCastp(pdbCode,reinitialize):
        if _gpssLoadPdb(pdbCode,reinitialize):

            # Get pocket count
            castpInfo = urllib2.urlopen('http://gpss.mcsg.anl.gov/webservices/'+
                                        'gpssServerPymol.php?pdbId='+
                                        pdbCode + '&mode=castpInfo')
            castpLength = int(castpInfo.readlines()[-1][13:16])
            
            # Get pocket atoms
            while castpLength > 0:
                castpSurfaceFile = urllib2.urlopen('http://gpss.mcsg.anl.gov/webservices/'+
                                                   'gpssServerPymol.php?pdbId='+
                                                   pdbCode + '&surfaceId='+str(castpLength)+
                                                   '&mode=castpSurface')
                objectId = 'CASTp-'+str(castpLength)
                cmd.read_pdbstr(castpSurfaceFile.read(),objectId)
                cmd.do('hide everything,' + objectId)
                cmd.do('show surface,' + objectId)
                cmd.do('set transparency=0.2,'+ objectId) 
                castpLength-=1
                
        cmd.do('zoom GPSS-'+pdbCode)
Example #45
0
 def displayPdb(self, tstD, tstName, group=False, pointGroupCacheTemp=None):
   '''creates an actual pdb object of the protein or just the part near the
   surface/group of interest'''
   if not group:  # just display the whole thing
     pdbText = "\n".join(tstD.dict['PDB_RECORD'])
     cmd.read_pdbstr(pdbText, tstName + "." + str(self.drawCount) + ".pdb")
   else:
     pointNearbyAtomList = tstD.dict['POINT_NEARBY_ATOM']
     import sets
     atomSet = sets.Set()  # old since pymol is based on 2.3 forever
     for pointNearbyAtom in pointNearbyAtomList:
       try:
         point = pointNearbyAtom[0]
         groups = pointGroupCacheTemp[point]
         if group in groups:
           atomSet.update(pointNearbyAtom[1:])
       except TypeError:
         pass  # means a point had no nearby atoms, which can happen given dist
       #print point, groups, atomSet
     pdbStr = ""
     for atomLine in atomSet:
       pdbStr += tstD.dict['PDB_RECORD'][int(atomLine)-1] + "\n"
     cmd.read_pdbstr(
         pdbStr, tstName + "." + str(self.drawCount) + ".pdb." + str(group))
Example #46
0
File: rpc.py Project: jandom/rdkit
def rpcLoadPDB(data, objName, colorScheme='', replace=1):
  """ loads a molecule from a pdb string
 
    Arguments:
      data: the mol block
      objName: name of the object to create
      colorScheme: (OPTIONAL) name of the color scheme to use
        for the molecule (should be either 'std' or one of the
        color schemes defined in pymol.utils)
      replace: (OPTIONAL) if an object with the same name already
        exists, delete it before adding this one
 
 
  """
  from pymol import util
  if replace:
    cmd.delete(objName)
  res = cmd.read_pdbstr(data, objName)
  colorObj(objName, colorScheme)
  if res is not None:
    return res
  else:
    return ''
Example #47
0
def rpcLoadPDB(data, objName, colorScheme='', replace=1):
    """ loads a molecule from a pdb string
 
    Arguments:
      data: the mol block
      objName: name of the object to create
      colorScheme: (OPTIONAL) name of the color scheme to use
        for the molecule (should be either 'std' or one of the
        color schemes defined in pymol.utils)
      replace: (OPTIONAL) if an object with the same name already
        exists, delete it before adding this one
 
 
  """
    from pymol import util
    if replace:
        cmd.delete(objName)
    res = cmd.read_pdbstr(data, objName)
    colorObj(objName, colorScheme)
    if res is not None:
        return res
    else:
        return ''
Example #48
0
    def test(self, matrix_mode):
        cmd.viewport(100,100)
        cmd.set('matrix_mode', matrix_mode)
        cmd.set('ambient', 1.0)

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

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

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

        pdbstr = cmd.get_pdbstr('m1')
        cmd.delete('*')
        cmd.read_pdbstr(pdbstr, 'm1', zoom=0)
        self._rep()
        self.assertImageEqual(ref, count=100, msg='ANISOU not aligned in PDB')
Example #49
0
    def load_dock4(self, cluster, object, mode):
        """
            Load a SwissDock's cluster of ligands from string list in PDB >Dock4 format

            Parameters
            ----------
            cluster : list of str
                list of string lines from cluster of structures in PDB format
            object : str
                name to be include the new object
            mode : {0, 1, 2}
                0 - all molecules to same object
                1 - only first molecule of each cluster to object (ClusterRank==0)
                2 - all molecules to multiple objects according to clusters
        """

        cluster = [line.strip() for line in cluster if line.strip()]

        self.__init__()

        # read all structures remarks/coordinates
        i = 0
        pdb = []
        remark_re = re.compile(r'(?i)^REMARK\b\s+(\w+)\s*:\s*(-?\d+\.?\d*)')
        while i < len(cluster):

            pdb_keyword = cluster[i].split()[0].upper()

            # process docking information in REMARKs
            if pdb_keyword == 'REMARK':
                remarks = dict()
                # loop over REMARKs until no compliant found
                while remark_re.match(cluster[i]):
                    match = remark_re.match(cluster[i])
                    key = str(match.group(1))
                    value = float(match.group(2)) if key not in (
                        'Cluster', 'ClusterRank') else int(match.group(2))
                    remarks[key] = value
                    i += 1

            # take whole molecule PDB coordinate lines
            elif pdb_keyword in ('ATOM', 'HETATM'):
                i_0 = i
                while cluster[i].split()[0].upper() in ('ATOM', 'HETATM'):
                    i += 1
                pdb_molecule = "\n".join(cluster[i_0:i]) + '\nENDMDL\n'

                # append to main attribute at the end of molecule
                pdb.append(pdb_molecule)
                self.entries.append({
                    'remarks': remarks,
                    'internal': deepcopy(self.internal_empty)
                })

            else:
                i += 1

        # equalize remarks for all entries
        for n, i in enumerate(self.entries):
            for j in self.remarks:
                i['remarks'].setdefault(j, None)
            # set internals
            i['internal']['object'] = object
            i['internal']['state'] = n + 1

        # check if defined Cluster and ClusterRank
        if mode in (
                '1', '2'
        ) and not 'Cluster' in self.remarks or not 'ClusterRank' in self.remarks:
            print(
                " PyViewDock: Failed splitting while loading. Missing 'Cluster' or 'ClusterRank'."
            )
            return

        # load only first of every cluster (ClusterRank == 0)
        if mode == '1':
            entries_tmp, pdb_tmp = [], []
            n_state = 0
            for e, p in zip(self.entries, pdb):
                if e['remarks']['ClusterRank'] == 0:
                    pdb_tmp.append(p)
                    entries_tmp.append(e)
                    n_state += 1
                    entries_tmp[-1]['internal']['state'] = n_state

            self.entries, pdb = deepcopy(entries_tmp), deepcopy(pdb_tmp)
            cmd.read_pdbstr("".join(pdb), object)

        # load all in different objects by Cluster
        elif mode == '2':
            pdb_tmp = dict()
            for e, p in zip(self.entries, pdb):
                object_new = object + '-' + str(e['remarks']['Cluster'])
                pdb_tmp.setdefault(object_new, []).append(p)
                e['internal']['object'] = object_new
                e['internal']['state'] = len(pdb_tmp[object_new]) + 1
            for object_new, p in pdb_tmp.items():
                cmd.read_pdbstr("".join(p), object_new)

        # load all in one object
        else:
            cmd.read_pdbstr("".join(pdb), object)
Example #50
0
def load_gro(filename, object='', state=-1, quiet=1, zoom=-1):
    '''
DESCRIPTION

    Load a gro file (molecular structure in Gromos87 format).

    http://manual.gromacs.org/online/gro.html

    This command can handle larger ID and resi values than PDB files and thus
    is better (but slower) than converting a gro file to PDB format using
    editconf.

    Based on a script from Tsjerk Wassenaar, posted on pymol-users mailing list.
    http://www.mail-archive.com/[email protected]/msg09394.html
    '''
    from . import pymol_version
    if pymol_version >= 1.74:
        print(
            ' Notice: native gro file support available in PyMOL since 1.7.4')

    if object == '':
        object = os.path.basename(filename).rsplit('.', 1)[0]

    _pdbAtomLine = 'ATOM  %5i  %-3s %3s%2s%4i    %8.3f%8.3f%8.3f%6.2f%6.2f      %4s%2s  '
    _pdbBoxLine = 'CRYST1%9.3f%9.3f%9.3f%7.2f%7.2f%7.2f P 1           1'

    def pdbAtom(line):
        ''' Parses a gro atom line and returns a pdb ATOM line '''
        resi = int(line[:5])
        resn = line[5:10].strip()
        name = line[10:15].strip()
        ID = int(line[15:20])
        x, y, z = 10 * float(line[20:28]), 10 * float(line[28:36]), 10 * float(
            line[36:44])
        segi = '%02d%02d' % (ID / 100000, resi / 10000)
        ID, resi = ID % 100000, resi % 10000
        return _pdbAtomLine % (ID, name[:3], resn[:3], 'A', resi, x, y, z, 1,
                               0, segi, name[0])

    def pdbBox(line):
        ''' Parses a gro box line and returns a pdb CRYST1 line '''
        from math import degrees
        from chempy.cpv import length, get_angle

        v = [10 * float(i)
             for i in line.split()] + 6 * [0]  # Padding for rectangular boxes
        v1, v2, v3 = (v[0], v[3], v[4]), (v[5], v[1], v[6]), (v[7], v[8], v[2])

        a = length(v1)
        b = length(v2)
        c = length(v3)

        alpha = degrees(get_angle(v2, v3))
        beta = degrees(get_angle(v1, v3))
        gamma = degrees(get_angle(v1, v2))

        return _pdbBoxLine % (a, b, c, alpha, beta, gamma)

    pdb = ['']
    stream = open(filename)
    for model in range(1, 9999):
        title = stream.readline()
        natoms = stream.readline().strip()
        if natoms == '':
            break
        natoms = int(natoms)

        pdb.append('MODEL %8d' % model)
        for i in range(natoms):
            pdb.append(pdbAtom(stream.readline()))
        pdb.append('ENDMDL')

        boxline = stream.readline()
        if model == 1:
            pdb[0] = pdbBox(boxline)
    stream.close()
    pdb.extend(['END', ''])

    cmd.read_pdbstr('\n'.join(pdb),
                    object,
                    int(state),
                    quiet=int(quiet),
                    zoom=int(zoom))
    cmd.alter(
        object,
        '(ID,resi,segi) = (ID+100000*int(segi[:2]),resv+10000*int(segi[2:]),"")'
    )
Example #51
0
try:
    # Importing the PyMOL module will create the window.
    import pymol #@UnresolvedImport
    from pymol import cmd #@UnresolvedImport
except:
    print "Failed to import pymol; python will stack dump next:"

# Tell PyMOL we don't want any GUI features.
__main__.pymol_argv = [ 'pymol', '-Gi' ]

# Call the function below before using any PyMOL modules.

pymol.finish_launching()

cmd.stereo('walleye')
cmd.set('stereo_shift', 0.23)
cmd.set('stereo_angle', 1.0)

cmd.spectrum()

try:
    pdbCode = '1brv'
    pdbFile = urllib2.urlopen('file:///Users/jd/workspace35/cing/data/Tests/pdb/'+
         pdbCode + '/pdb' +
         pdbCode + '.ent')
    cmd.read_pdbstr(pdbFile.read(), pdbCode)
except:
    print "Unexpected error:", sys.exc_info()[0]

time.sleep(5)
#cmd.quit()
def load_pose_into_object(pose_name):
    '''Load the pose into the object.'''
    pdb_os = rosetta.std.ostringstream()
    poses[pose_name].dump_pdb(pdb_os)
    cmd.read_pdbstr(pdb_os.str(), pose_name)
    cmd.color('green', '{0} and (n. c*)'.format(pose_name))
Example #53
0
      COLOR,  0.2, 1.0, 0.2,
      SPHERE, 1.0+math.cos(a/10.0), 1.0+math.sin(a/20.0), 1.0+math.cos(a/10.0), 0.2+math.cos(a/5.0)/10.0,

      COLOR,  1.0, 0.2, 0.2,      
      SPHERE, 2.0-math.cos(a/10.0), 1.0+math.sin(0.5+a/10.0), 1.0+math.cos(a/10.0), 0.2+math.cos(a/5.0)/10.0,      
      ]
   obj = axes + balls
   cmd.load_cgo(obj,'cgo01',c)
   c = c + 1
   
   # counter label
   
   pdb_list = [
      "HETATM%5d  C   UNK     1    %8.3f%8.3f%8.3f  1.00 10.00\n"%(c,2.0,0,2.0),
      ]
   cmd.read_pdbstr(string.join(pdb_list,''),'lab1',c,discrete=1)
   cmd.label("(lab1 and id %d)"%c,"'frame %d %6.3f'"%(c,math.sin(a/10.0)))


cmd.hide("nonbonded","lab1")

# axes labels


pdb_list = [
"HETATM    1  X   UNK     1    %8.3f%8.3f%8.3f  1.00 10.00\n"%(3.2,0,0),
"HETATM    2  Y   UNK     2    %8.3f%8.3f%8.3f  1.00 10.00\n"%(0,3.2,0),
"HETATM    3  Z   UNK     3    %8.3f%8.3f%8.3f  1.00 10.00\n"%(0,0,3.2),]
cmd.read_pdbstr(string.join(pdb_list,''),'lab2')
cmd.hide('(lab2)')
cmd.label('lab2','name')
Example #54
0
def __init__(self=None):
    cmd.extend('webload', webload)


def webload(pdbid):
    import sys, os
    import StringIO
    import gzip
    import urllib

    label = pdbid
    url = _PDB_URL % vars()
    try:
        datafh = StringIO.StringIO(urllib.urlopen(url).read())
        data = gzip.GzipFile(fileobj=datafh).read()
    except Exception, e:
        print "Error: pdbid=%(pdbid)s" % vars(), e
        return

    if not data:
        print "Invalid PDB id %(pdbid)s" % vars()
        return

    # load it into pymol
    cmd.read_pdbstr(data, label)


if __name__ == 'pymol':
    __init__()
Example #55
0
 def push2pymol(self, name, state=1):
     cmd.read_pdbstr(self.pdbstr(), name, state)
Example #56
0
def quench(sel="sele", rounds=10):
    cmd.read_pdbstr(PythonMSL.quickQuench(cmd.get_pdbstr(sel), rounds),
                    "quench")
Example #57
0
    def testReadPdbstr(self):
        cmd.read_pdbstr(pdbstr, 'm1')
        self.assertEqual(7, cmd.count_atoms())

        cmd.read_pdbstr(pdbstr, 'm1')
        self.assertEqual(2, cmd.count_states())