Exemple #1
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")
def dump_rep(name):
    if 'PYMOL_GIT_MOD' in os.environ:
        import shutil
        try:
            shutil.copytree(
                os.path.join(os.environ['PYMOL_GIT_MOD'], 'pymol2glmol', 'js'),
                os.path.join(os.getcwd(), 'js'))
        except OSError:
            pass

    names = cmd.get_session()['names']
    cmd.set('pdb_retain_ids', 1)

    ret = ''
    for obj in names:
        if (obj == None):
            continue
        if (obj[2] == 0):  # not visible
            continue
        if (obj[1] == 0 and obj[4] == 1 and obj[0] == name):
            ret += parseObjMol(obj)
        if (obj[1] == 0
                and obj[4] == 4):  # currently all dist objects are exported
            ret += parseDistObj(obj)

    cmd.turn('z', 180)
    view = cmd.get_view()
    cmd.turn('z', 180)
    cx = -view[12]
    cy = -view[13]
    cz = -view[14]
    cameraZ = -view[11] - 150
    fov = float(cmd.get("field_of_view"))
    fogStart = float(cmd.get("fog_start"))
    slabNear = view[15] + view[11]
    slabFar = view[16] + view[11]
    ret += "\nview:%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f" % \
        (cx, cy, cz, cameraZ, slabNear, slabFar, fogStart, fov)
    for i in range(9):
        ret += ",%.3f" % view[i]

    bgcolor = cmd.get_setting_tuple('bg_rgb')[1]
    ret += "\nbgcolor:%02x%02x%02x" % (int(255 * float(bgcolor[0])), \
                                       int(255 * float(bgcolor[1])), int(255 * float(bgcolor[2])))
    if 'PYMOL_GIT_MOD' in os.environ:
        template = open(os.path.join(os.environ['PYMOL_GIT_MOD'], 'pymol2glmol', 'imported.html')).read().\
            replace("###INCLUDE_PDB_FILE_HERE###", cmd.get_pdbstr(name)).\
            replace('###INCLUDE_REPRESENTATION_HERE###', ret)
    else:
        template = open('imported.html').read().\
            replace("###INCLUDE_PDB_FILE_HERE###", cmd.get_pdbstr(name)).\
            replace('###INCLUDE_REPRESENTATION_HERE###', ret)

    f = open(name + '.html', 'w')
    f.write(template)
    f.close()
Exemple #3
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")
Exemple #4
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")
    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')
Exemple #6
0
def normalmodes_prody(selection, cutoff=15, first=7, last=10, guide=1,
        prefix='prody', states=7, factor=-1, quiet=1):
    '''
DESCRIPTION

    Anisotropic Network Model (ANM) analysis with ProDy.

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

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

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

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

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

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

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

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

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

    cmd.delete(tmpsele)

    if guide:
        cmd.set('ribbon_trace_atoms', 1, prefix + '*')
        cmd.show_as('ribbon', prefix + '*')
    else:
        cmd.show_as('lines', prefix + '*')
    def launch_search(self):
        """
        launches the search in the separate thread
        does some basic checking and gets selection
        """
        
        # gets the active selections from pymol
        active_selections = cmd.get_names('selections', 1)
        if len(active_selections) == 0:
            cmd.get_wizard().set_status('no selection')
        else:

            selection = active_selections[0]
            print "The active selections are " + str(selection)
            pdbstr = cmd.get_pdbstr(selection)
            print 'pdbstr is', pdbstr
            self.stop_search()
            
#            print cmd.get_wizard(), self.win.rmsd.get(), self.win.num_structs.get(), self.win.full_match, self.win.datab, pdbstr, self.win.serverURL, cmd.get_wizard().cmd, self.win.jobIDs

            self.win.searchThread = SearchThread(cmd.get_wizard(), self.win.rmsd.get(),
                                self.win.num_structs.get(), self.win.full_match,
                                self.win.datab, pdbstr, self.win.serverURL, cmd.get_wizard().cmd, self.win.jobIDs)
            self.win.searchThread.start()
            cmd.get_wizard().set_status('search launched')
            cmd.get_wizard().searchProgress = 0
        
        cmd.refresh_wizard()
Exemple #8
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"
Exemple #9
0
    def launch_search(self):
        """
        launches the search in the separate thread
        does some basic checking and gets selection
        """

        # gets the active selections from pymol
        active_selections = cmd.get_names('selections', 1)
        if len(active_selections) == 0:
            self.status = 'no selection'
        else:

            selection = active_selections[0]
            print "The active selections are" + str(selection)
            pdbstr = cmd.get_pdbstr(selection)
            print 'pdbstr is', pdbstr
            self.stop_search()
            self.searchThread = SearchThread(self, self.rmsd_cutoff,
                                             self.number_of_structures,
                                             self.full_match, self.database,
                                             pdbstr, self.url, self.cmd,
                                             self.dictionary)
            self.searchThread.start()
            self.status = 'search launched'
            self.searchProgress = 0
        self.cmd.refresh_wizard()
    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')
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 '#########################################'
Exemple #12
0
def save_pdb_with_anisou(filename, selection='(all)', state=1, quiet=1):
    '''
DESCRIPTION

     Save in PDB format including ANISOU records.

SEE ALSO

    save
    '''
    state, quiet = int(state), int(quiet)

    pdbstr = cmd.get_pdbstr(selection, state)
    atom_it = iter(cmd.get_model(selection, state).atom)

    def mergeaniso():
        for line in pdbstr.splitlines(True):
            yield line
            if line[:6] in ['ATOM  ', 'HETATM']:
                u_str = ''.join('%7.0f' % (u * 1e4)
                                for u in atom_it.next().u_aniso)
                yield 'ANISOU' + line[6:28] + u_str + line[70:]

    pdbstr = ''.join(mergeaniso())

    filename = cmd.exp_path(filename)
    f = open(filename, 'w')
    f.write(pdbstr)
    f.close()

    if not quiet:
        print(' Save with ANISOU: wrote "%s"' % (filename))
Exemple #13
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 fSumWMCFirst(molecule, SGNameAngle, chain, residue, MCNeighbour, DieElecMC, MCchargeC, MCchargeO, printMC):
    # print "First", MCNeighbour
    SumWMCFirst = 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
    # Mainchain C
    Cnameselect = "/" + molecule + "//" + chain + "/" + str(MCNeighbour) + "/C"
    ResDist = cmd.dist(residue + 'distFirstC', SGnameselect, Cnameselect)
    WMC = fWMC(MCchargeC, DieElecMC, ResDist)
    SumWMCFirst = SumWMCFirst + WMC
    if printMC == 'yes':
        print("MC C ", MCNeighbour, " ", MCchargeC, " ", DieElecMC, " ", ResDist, " ", WMC)
    # Mainchain O
    Onameselect = "/" + molecule + "//" + chain + "/" + str(MCNeighbour) + "/O"
    ResDist = cmd.dist(residue + 'distFirstO', SGnameselect, Onameselect)
    WMC = fWMC(MCchargeO, DieElecMC, ResDist)
    SumWMCFirst = SumWMCFirst + WMC
    if printMC == 'yes':
        print("MC O ", MCNeighbour, " ", MCchargeO, " ", DieElecMC, " ", ResDist, " ", WMC)
    cmd.delete(residue + 'distFirstC')
    cmd.delete(residue + 'distFirstO')
    cmd.delete("MC")
    return SumWMCFirst
Exemple #15
0
    def launch_search(self):
        """
        launches the search in the separate thread
        does some basic checking and gets selection
        """

        # gets the active selections from pymol
        active_selections = cmd.get_names('selections', 1)
        if len(active_selections) == 0:
            cmd.get_wizard().set_status('no selection')
        else:

            selection = active_selections[0]
            print "The active selections are " + str(selection)
            pdbstr = cmd.get_pdbstr(selection)
            print 'pdbstr is', pdbstr
            self.stop_search()

            #            print cmd.get_wizard(), self.win.rmsd.get(), self.win.num_structs.get(), self.win.full_match, self.win.datab, pdbstr, self.win.serverURL, cmd.get_wizard().cmd, self.win.jobIDs

            self.win.searchThread = SearchThread(cmd.get_wizard(),
                                                 self.win.rmsd.get(),
                                                 self.win.num_structs.get(),
                                                 self.win.full_match,
                                                 self.win.datab, pdbstr,
                                                 self.win.serverURL,
                                                 cmd.get_wizard().cmd,
                                                 self.win.jobIDs)
            self.win.searchThread.start()
            cmd.get_wizard().set_status('search launched')
            cmd.get_wizard().searchProgress = 0

        cmd.refresh_wizard()
 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
Exemple #17
0
def assign_atom_types(selection='all'):
    """
    TODO document me!

    read http://openbabel.org/dev-api/classOpenBabel_1_1OBAtom.shtml#ae09ed28481ac044dab3f31c8605b44a9
    for available functions provided by openbabel to extract atom properties. There is a GetType() function
    but I found that function very limited.
    """
    atom_types = []
    pdb_string = cmd.get_pdbstr(selection)
    mol = ob.OBMol()
    obconversion = ob.OBConversion()
    obconversion.SetInAndOutFormats('pdb', 'pdb')
    obconversion.ReadString(mol, pdb_string)
    rings = mol.GetSSSR()
    for at in ob.OBMolAtomIter(mol):
        ring_member = [ring.IsMember(at) for ring in rings]
        neighbors = [
            neighbor.GetAtomicNum() for neighbor in ob.OBAtomAtomIter(at)
        ]
        atom_types.append(
            (at.GetIndex(), at.GetAtomicNum(), at.GetHvyValence(),
             any(ring_member), at.IsAromatic(), at.MemberOfRingCount(),
             (neighbors)))
    return atom_types
Exemple #18
0
def normalmodes_prody(selection, cutoff=15, first=7, last=10, guide=1,
        prefix='prody', states=7, factor=-1, quiet=1):
    '''
DESCRIPTION

    Anisotropic Network Model (ANM) analysis with ProDy.

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

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

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

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

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

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

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

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

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

    cmd.delete(tmpsele)

    if guide:
        cmd.set('ribbon_trace_atoms', 1, prefix + '*')
        cmd.show_as('ribbon', prefix + '*')
    else:
        cmd.show_as('lines', prefix + '*')
Exemple #19
0
    def launch_search(self):
        """
        launches the search in the separate thread
        does some basic checking and gets selection
        """
        
        # gets the active selections from pymol
        active_selections = cmd.get_names('selections', 1)
        if len(active_selections) == 0:
            self.status = 'no selection'
        else:

            selection = active_selections[0]
            print "The active selections are " + str(selection)
            pdbstr = cmd.get_pdbstr(selection)
            print 'pdbstr is', pdbstr
            self.stop_search()
            self.searchThread = SearchThread(self,
                self.rmsd_cutoff,
                self.number_of_structures,
                self.full_match,
                self.database,
                pdbstr,
                self.url,
                self.cmd,
                self.dictionary)
            self.searchThread.start()
            self.status = 'search launched'
            self.searchProgress = 0
        self.cmd.refresh_wizard()
Exemple #20
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)
Exemple #21
0
def fSumWMCFirst(molecule, SGNameAngle, chain, residue, MCNeighbour, DieElecMC,
                 MCchargeC, MCchargeO, printMC):
    # print "First", MCNeighbour
    SumWMCFirst = 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
    # Mainchain C
    Cnameselect = "/" + molecule + "//" + chain + "/" + str(MCNeighbour) + "/C"
    ResDist = cmd.dist(residue + 'distFirstC', SGnameselect, Cnameselect)
    WMC = fWMC(MCchargeC, DieElecMC, ResDist)
    SumWMCFirst = SumWMCFirst + WMC
    if printMC == 'yes':
        print("MC C ", MCNeighbour, " ", MCchargeC, " ", DieElecMC, " ",
              ResDist, " ", WMC)
    # Mainchain O
    Onameselect = "/" + molecule + "//" + chain + "/" + str(MCNeighbour) + "/O"
    ResDist = cmd.dist(residue + 'distFirstO', SGnameselect, Onameselect)
    WMC = fWMC(MCchargeO, DieElecMC, ResDist)
    SumWMCFirst = SumWMCFirst + WMC
    if printMC == 'yes':
        print("MC O ", MCNeighbour, " ", MCchargeO, " ", DieElecMC, " ",
              ResDist, " ", WMC)
    cmd.delete(residue + 'distFirstC')
    cmd.delete(residue + 'distFirstO')
    cmd.delete("MC")
    return SumWMCFirst
def save_pdb_with_anisou(filename, selection='(all)', state=1, quiet=1):
    '''
DESCRIPTION

     Save in PDB format including ANISOU records.

SEE ALSO

    save
    '''
    state, quiet = int(state), int(quiet)

    pdbstr = cmd.get_pdbstr(selection, state)
    atom_it = iter(cmd.get_model(selection, state).atom)

    def mergeaniso():
        for line in pdbstr.splitlines(True):
            yield line
            if line[:6] in ['ATOM  ', 'HETATM']:
                u_str = ''.join('%7.0f' % (u * 1e4) for u in atom_it.next().u_aniso)
                yield 'ANISOU' + line[6:28] + u_str + line[70:]

    pdbstr = ''.join(mergeaniso())

    filename = cmd.exp_path(filename)
    f = open(filename, 'w')
    f.write(pdbstr)
    f.close()

    if not quiet:
        print(' Save with ANISOU: wrote "%s"' % (filename))
Exemple #23
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
Exemple #24
0
def get_selection_details(selection):
    selection_details = {}
    selection_details['raw'] = cmd.get_pdbstr(selection).split('\n')[1]
    selection_details['aa_type'] = selection_details['raw'].split()[3]
    selection_details['chain'] = selection_details['raw'].split()[4]
    selection_details['seq_position'] = selection_details['raw'].split()[5]
    selection_details['pdb_object_name'] = cmd.get_object_list(selection)[0]
    return selection_details
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 '#########################################'
Exemple #26
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
Exemple #27
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 "#########################################"
Exemple #28
0
 def get_pdbstr(self, pdb='reduce'):
     '''Return a PDB string for the specified structure object.'''
     # TODO this needs some work
     name = self.pdb[pdb]
     if name in cmd.get_names():
         return cmd.get_pdbstr(name)
     else:
         msg = 'Sorry, no object loaded called {}!'.format(name)
         logger.warning(msg)
         return None
Exemple #29
0
 def get_pdbstr(self, pdb='reduce'):
     '''Return a PDB string for the specified structure object.'''
     # TODO this needs some work
     name = self.pdb[pdb]
     if name in cmd.get_names():
         return cmd.get_pdbstr(name)
     else:
         msg = 'Sorry, no object loaded called {}!'.format(name)
         logger.warning(msg)
         return None
Exemple #30
0
def get_sasa_mmtk(selection, state=-1, hydrogens='auto', quiet=1):
    '''
DESCRIPTION

    Get solvent accesible surface area using MMTK.MolecularSurface

    http://dirac.cnrs-orleans.fr/MMTK/

    This command is very picky with missing atoms and wrong atom naming.

SEE ALSO

    stub2ala, get_sasa, get_sasa_ball
    '''
    try:
        import MMTK
    except ImportError:
        print(' ImportError: please install MMTK')
        raise CmdException

    from MMTK.PDB import PDBConfiguration
    from MMTK.Proteins import Protein
    from MMTK.MolecularSurface import surfaceAndVolume

    try:
        from cStringIO import StringIO
    except ImportError:
        from io import StringIO

    selection = selector.process(selection)
    state, quiet = int(state), int(quiet)
    radius = cmd.get_setting_float('solvent_radius')

    if hydrogens == 'auto':
        if cmd.count_atoms('(%s) and hydro' % selection) > 0:
            hydrogens = 'all'
        else:
            hydrogens = 'no_hydrogens'
    elif hydrogens == 'none':
        hydrogens = 'no_hydrogens'

    conf = PDBConfiguration(StringIO(cmd.get_pdbstr(selection)))
    system = Protein(conf.createPeptideChains(hydrogens))

    try:
        area, volume = surfaceAndVolume(system, radius * 0.1)
    except:
        print(' Error: MMTK.MolecularSurface.surfaceAndVolume failed')
        raise CmdException

    if not quiet:
        print(' get_sasa_mmtk: %.3f Angstroms^2 (volume: %.3f Angstroms^3).' %
              (area * 1e2, volume * 1e3))
    return area * 1e2
Exemple #31
0
def get_sequence(target, chain=""):
	"""Determine protein sequence from PDB ATOM fields"""

	if chain == "": chain = " "

	pdb = cmd.get_pdbstr(target).split("\n")

	seq3 = [line[17:20] for line in pdb if line[13:16] == "CA " and line[21] == chain]
	seq1 = [three_to_one[code] for code in seq3 if code] 

	return "".join(seq1)
Exemple #32
0
def get_sasa_mmtk(selection, state=-1, hydrogens='auto', quiet=1):
    '''
DESCRIPTION

    Get solvent accesible surface area using MMTK.MolecularSurface

    http://dirac.cnrs-orleans.fr/MMTK/

    This command is very picky with missing atoms and wrong atom naming.

SEE ALSO

    stub2ala, get_sasa, get_sasa_ball
    '''
    try:
        import MMTK
    except ImportError:
        print(' ImportError: please install MMTK')
        raise CmdException

    from MMTK.PDB import PDBConfiguration
    from MMTK.Proteins import Protein
    from MMTK.MolecularSurface import surfaceAndVolume

    try:
        from cStringIO import StringIO
    except ImportError:
        from io import StringIO

    selection = selector.process(selection)
    state, quiet = int(state), int(quiet)
    radius = cmd.get_setting_float('solvent_radius')

    if hydrogens == 'auto':
        if cmd.count_atoms('(%s) and hydro' % selection) > 0:
            hydrogens = 'all'
        else:
            hydrogens = 'no_hydrogens'
    elif hydrogens == 'none':
        hydrogens = 'no_hydrogens'

    conf = PDBConfiguration(StringIO(cmd.get_pdbstr(selection)))
    system = Protein(conf.createPeptideChains(hydrogens))

    try:
        area, volume = surfaceAndVolume(system, radius * 0.1)
    except:
        print(' Error: MMTK.MolecularSurface.surfaceAndVolume failed')
        raise CmdException

    if not quiet:
        print(' get_sasa_mmtk: %.3f Angstroms^2 (volume: %.3f Angstroms^3).' % (area * 1e2, volume * 1e3))
    return area * 1e2
    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)
Exemple #34
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
Exemple #35
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)
Exemple #36
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
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
Exemple #38
0
def get_sequence(target, chain=""):
    """Determine protein sequence from PDB ATOM fields"""

    if chain == "": chain = " "

    pdb = cmd.get_pdbstr(target).split("\n")

    seq3 = [
        line[17:20] for line in pdb
        if line[13:16] == "CA " and line[21] == chain
    ]
    seq1 = [three_to_one[code] for code in seq3 if code]

    return "".join(seq1)
Exemple #39
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
Exemple #40
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
 def test(self, nodup):
     cmd.set('pdb_conect_nodup', nodup)
     cmd.fragment('cyclopentadiene')
     lines = cmd.get_pdbstr().splitlines()
     bonds = defaultdict(int)
     for line in lines:
         if line.startswith('CONECT'):
             indices = list(map(int, line[6:].split()))
             for i in indices[1:]:
                 bonds[indices[0], i] += 1
     counts = bonds.values()
     if nodup:
         self.assertTrue(all(v == 1 for v in counts))
     else:
         self.assertTrue(any(v > 1 for v in counts))
Exemple #42
0
 def test(self, nodup):
     cmd.set('pdb_conect_nodup', nodup)
     cmd.fragment('cyclopentadiene')
     lines = cmd.get_pdbstr().splitlines()
     bonds = defaultdict(int)
     for line in lines:
         if line.startswith('CONECT'):
             indices = list(map(int, line[6:].split()))
             for i in indices[1:]:
                 bonds[indices[0], i] += 1
     counts = bonds.values()
     if nodup:
         self.assertTrue(all(v == 1 for v in counts))
     else:
         self.assertTrue(any(v > 1 for v in counts))
def _convert_molecules_to_pdb() -> t.List[str]:
    '''
    convert_molecules_to_pdb  gives a list containing one pdb string for each molecule
    #TODO: Write/find a conversion fucntion that I can use on the u.Atoms as the Logic handler knows them
    :warning: atoms willbeassigned different IDS than they currently have in interface_Pymol!!!!!
    :return: List of pdb string for each molecule in interface_Pymol
    :rtype: t.List[str]
    '''

    pymol_objects = cmd.get_object_list()
    pdb_molecules = [
        cmd.get_pdbstr(obj) for obj in pymol_objects if obj[:4] == "mol_"
    ]

    return pdb_molecules
def _convert_molecules_to_pdb() -> t.List[str]:
    """
     convert_molecules_to_pdb  gives a list containing one pdb string for each molecule
        @Warnings  atoms willbeassigned different IDS than they currently have in interface_Pymol!!!!!

    Returns
    -------
    t.List[str]
         List of pdb string for each molecule in interface_Pymol
    """

    pymol_objects = cmd.get_object_list()
    pdb_molecules = [
        cmd.get_pdbstr(obj) for obj in pymol_objects if obj[:4] == "mol_"
    ]

    return pdb_molecules
Exemple #45
0
def resipick(selectedChain=False,cutoff=10, doShow=False, verbose=False):
    
	objSel="(all)"

    # Obtain pdb information
	tmpObj = "__tmp"
	cmd.create(tmpObj, objSel + " and polymer")

	fullObj = "full_str"
	cmd.create(fullObj, objSel + " and polymer")


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

	#print selectedChain
    # Remove unselected chains
	if selectedChain:
		cmd.remove(tmpObj + " and not chain "+ selectedChain)


    # 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()

    # create sels
	selResi = "exposed_res"
	cmd.select(selResi, "byres " + objSel + " in " + tmpObj)

    # show exposed_resi's sels
	resiStr = cmd.get_pdbstr(selResi)

	if doShow != False:
		cmd.show_as("spheres", objSel + " and poly")
		cmd.color("yellow", selResi)

	cmd.delete(tmpObj)
	cmd.delete(fullObj)
	cmd.delete(selResi)
	return resiStr
Exemple #46
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
Exemple #47
0
def resipick(selectedChain=False,cutoff=10, doShow=False, verbose=False):
    '''对导入的PDB文件选取可及表面积为 cutoff (默认为10)外的表位残基'''
    objSel="(all)"

    # 获取当前pdb文件
    tmpObj = "__tmp"
    cmd.create(tmpObj, objSel + " and polymer")

    fullObj = "full_str"
    cmd.create(fullObj, objSel + " and polymer")


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

    print selectedChain
    #移除非选中的链
    if selectedChain:
    	cmd.remove(tmpObj + " and not chain "+ selectedChain)


    # 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()

    # 创建 sels
    selResi = "exposed_res"
    cmd.select(selResi, "byres " + objSel + " in " + tmpObj)

    # 呈现 exposed_resi 的序列 sels
    resiStr = cmd.get_pdbstr(selResi)

    if doShow != False:
        cmd.show_as("spheres", objSel + " and poly")
        cmd.color("blue", selResi)

    cmd.delete(tmpObj)
    return resiStr
Exemple #48
0
def assign_atom_types(selection='all'):
    """
    TODO document me!
    
    read http://openbabel.org/dev-api/classOpenBabel_1_1OBAtom.shtml#ae09ed28481ac044dab3f31c8605b44a9
    for available functions provided by openbabel to extract atom properties. There is a GetType() function
    but I found that function very limited.
    """
    atom_types = []
    pdb_string = cmd.get_pdbstr(selection)
    mol = ob.OBMol()
    obconversion = ob.OBConversion()
    obconversion.SetInAndOutFormats('pdb', 'pdb')
    obconversion.ReadString(mol, pdb_string)
    rings = mol.GetSSSR()
    for at in ob.OBMolAtomIter(mol):
        ring_member = [ring.IsMember(at) for ring in rings]
        neighbors = [neighbor.GetAtomicNum() for neighbor in ob.OBAtomAtomIter(at)]
        atom_types.append((at.GetIndex(), at.GetAtomicNum(), at.GetHvyValence(), any(ring_member), at.IsAromatic(), at.MemberOfRingCount(), (neighbors)))
    return atom_types
Exemple #49
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)
Exemple #50
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)
    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')
Exemple #52
0
    def st_lock_mech(self, bool):
        if bool == False:
            
            
            active_selections = cmd.get_names('selections', 1)
            selection = active_selections[0]
            self.pdbstr_c = cmd.get_pdbstr(selection)
            split_pdbstr = self.pdbstr_c.split()
            
            self.res_list_two = [-1]
            
            i = 5
            self.res_string_two = ''
            while i < len(split_pdbstr):
                
                if split_pdbstr[i] != self.res_list_two[-1]:
                    self.res_list_two.append(split_pdbstr[i])
                    
                    self.res_string_two += str(self.find_aa(split_pdbstr[i-2]))

                i += 12
            
            
            self.res_list_two = self.res_list_two[1:]
            
            for num in self.res_list_two:
                if num in self.res_list_one:
                    print 'residue selections must not overlap'
                    break
                elif num == self.res_list_two[-1] and num not in self.res_list_one:
                    self.strand_two_selection = self.res_list_two
                    print self.strand_two_selection
                    self.st_lock.config(text=self.res_string_two)

    
        else:
            self.st_lock.config(text="lock")
        self.lock_two = not bool
Exemple #53
0
def save_pdb(filename, selection="(all)", state=-1, symm=1, ss=1, aniso=0, quiet=1):
    """
DESCRIPTION

    Save the coordinates of a selection as pdb including the
    secondary structure information and, if possible, the unit
    cell. The latter requires the selction of a single object

USAGE

    save_pdb filename, selection [, state [, symm [, ss [, aniso ]]]]

ARGUMENTS

    filename = string: file path to be written

    selection = string: atoms to save {default: (all)}
                Note: to include the unit cell information you
                need to select a single object

    state = integer: state to save {default: -1 (current state)}

    symm = 0 or 1: save symmetry info if possible {default: 1}

    ss = 0 or 1: save secondary structure info {default: 1}

    aniso = 0 or 1: save ANISO records {default: 0}

SEE ALSO

    save
    """
    selection = selector.process(selection)
    state, quiet = int(state), int(quiet)
    symm, ss = int(symm), int(ss)

    filename = cmd.exp_path(filename)
    f = open(filename, "w")
    print >> f, "REMARK 200 Generated with PyMOL and psico".ljust(80)

    # Write the CRYST1 line if possible
    if symm:
        try:
            obj1 = cmd.get_object_list(selection)[0]
            sym = cmd.get_symmetry(obj1)
            if len(sym) != 7:
                raise
            f.write("CRYST1%9.3f%9.3f%9.3f%7.2f%7.2f%7.2f %-10s%4d\n" % tuple(sym + [1]))
            if not quiet:
                print " Info: Wrote unit cell and space group info"
        except:
            if not quiet:
                print " Info: No crystal information"

    # Write secondary structure
    if ss:
        try:
            sss = get_pdb_sss(selection, state, quiet)
            if not sss:
                raise
            f.write(sss)
            if not quiet:
                print " Info: Wrote secondary structure info"
        except:
            if not quiet:
                print " Info: No secondary structure information"

    # Write coordinates of selection
    pdbstr = cmd.get_pdbstr(selection, state)

    # fix END records
    if state == 0 and cmd.get_version()[1] < 1.6:
        pdbstr = "\n".join(line for line in pdbstr.splitlines() if line != "END") + "\nEND\n"

    # anisotropic b-factors
    if int(aniso) and cmd.get_model("first (%s)" % selection).atom[0].u_aniso[0] != 0.0:

        def mergeaniso():
            atom_it = iter(cmd.get_model(selection, state).atom)
            for line in pdbstr.splitlines(True):
                yield line
                if line[:6] in ["ATOM  ", "HETATM"]:
                    yield "ANISOU" + line[6:28] + "".join("%7.0f" % (u * 1e4) for u in atom_it.next().u_aniso) + line[
                        70:
                    ]

        pdbstr = "".join(mergeaniso())

    f.write(pdbstr)
    f.close()

    if not quiet:
        print "Wrote PDB to '" + filename + "'"
def cyspka(molecule, chain, residue, SeeProgress='yes', pH=7.2, MoveSGatom='no', SGatom=str((0, 0, 0))):
    # If SeeProgress='yes', computation time will take 10-20% extra, but nice to follow.
    cmd.refresh()
    RotationRange = 360
    RotationDegree = 1
    # For error checking, the energies can be printed out
    printMC = 'no'
    printSC = 'no'
    # Parameters
    DieElecSpheDist = 7.0
    DieElecWaterDist = 1.4
    DieElecWater = 78.5
    DieElecCore = 4.0
    BornPenaltyB = 1.0
    AvogadroR = 8.31446216
    Temp = 298
    DeltapKMCSC = 0
    pK1 = 9.25
    pK2 = 8.0
    NotPopuDist = 2.4
    PopEnergyPenalty = 10000000
    # Side chain discrete charges
    DieElecSC = 40.0
    SCchargeASP = -1
    SCchargeGLU = -1
    SCchargeOXT = -1
    SCchargeARG = +1
    SCchargeHIS = +1
    SCchargeLYS = +1
    SCchargeMET1 = +1
    # Main chain partial charges
    NrMainchainNeighBours = 5
    DieElecMC = 22.0
    MCchargeC = +0.55
    MCchargeO = -0.55
    MCchargeN = -0.35
    MCchargeH = +0.35
    MCchargeProCA = +0.1
    MCchargeProCD = +0.1
    MCchargeProN = -0.2

    # Loading an Cys residue, give it a logic name, and aligning it. The oxygen atom can not be aligned in many cases, and are skipped.
    # We use only this molecule, to find the initial position of the SG atom, and to rotate the SG atom around the CA-CB bond. The molecule atom positions are not used for electric potential calculatons.
    Cysmolecule = str(molecule) + str(residue) + "Cys"
    cmd.fragment("cys")
    cmd.set_name('cys', Cysmolecule)
    # We use pair_fir, since align and super gets unstable with so few atoms
    pairfitCys(Cysmolecule, molecule, chain, residue)
    # Give nice representations quickly
    cmd.show("sticks", Cysmolecule)
    cmd.select(str(molecule) + str(residue) + "Res", "/" + molecule + "//" + chain + "/" + residue)
    print("/" + molecule + "//" + chain + "/" + residue)
    cmd.show("sticks", str(molecule) + str(residue) + "Res")
    cmd.disable(str(molecule) + str(residue) + "Res")
    # Find out what is the residuename we are investigating for
    Respdbstr = cmd.get_pdbstr(str(molecule) + str(residue) + "Res")
    Ressplit = Respdbstr.split()
    residueName = Ressplit[3]

    print("")
    print("# Hello, PyMOLers. It should take around 1 minute per residue.")
    print("# molecule: %s , chain: %s, residue: %s %s, pH: %s " % (molecule, chain, residueName, residue, pH))

    # Determine the range of neighbour residues possible.
    Maxresidues = cmd.count_atoms("/" + molecule + "//" + chain + " and name CA")
    for i in range(NrMainchainNeighBours + 1):
        if int(residue) - i >= 1:
            Minresidue = int(residue) - i
        else:
            break
    for i in range(NrMainchainNeighBours + 1):
        if int(residue) + i <= Maxresidues:
            Maxresidue = int(residue) + i
        else:
            break

    # Get the position and the vector for the CA->CB bond.
    dihedN = "/" + Cysmolecule + "//" + "/" + "/N"
    dihedCA = "/" + Cysmolecule + "//" + "/" + "/CA"
    dihedCB = "/" + Cysmolecule + "//" + "/" + "/CB"
    dihedSG = "/" + Cysmolecule + "//" + "/" + "/SG"
    dihedralPosCA = cmd.get_atom_coords(dihedCA)
    dihedralPosSG = cmd.get_atom_coords(dihedSG)
    dihedralVector = AtomVector(dihedCA, dihedCB)

    # To compare with article, we can move the SGatom to a starting position. The rotation is still determined around the CA-CB bond.
    if MoveSGatom == 'yes':
        SGatom = [float(SGatom[1:-1].split(",")[0]), float(SGatom[1:-1].split(",")[1]), float(SGatom[1:-1].split(",")[2])]
        Translate = [(SGatom[0] - dihedralPosSG[0]), (SGatom[1] - dihedralPosSG[1]), (SGatom[2] - dihedralPosSG[2])]
        cmd.translate(Translate, dihedSG, state=0, camera=0)
        dihedralPosSG = cmd.get_atom_coords(dihedSG)
    # Create a pymol molecule, that in the end will hold and show all SG atoms. Gives the representation of the rotameric states.
    SGName = str(molecule) + str(residue) + "SG"
    cmd.create(SGName, "None")
    # Create a pymol molecule, that in the end will hold and show all Amide protons. Gives a nice representation, and easy to delete.
    AmideName = str(molecule) + str(residue) + "NH"
    cmd.create(AmideName, "None")
    # Check if there are any nearby SG atoms, which could make a SG-SG dimer formation. The
    breakDimer = "no"
    breakDimer = CheckDimer(dihedSG, molecule, chain, residue)
    # Create a list for appending the calculated energies.
    ListofEnergies = []
    ListofRotamerDiscarded = []
    # print "Angle before rotation", cmd.get_dihedral(dihedN,dihedCA,dihedCB,dihedSG)
    # Enter into the loop of rotameric states
    for i in range(int(math.floor(RotationRange / RotationDegree))):
        Angle = i * RotationDegree
        # Create pymol molecule/SG atom for which we will calculate for.
        SGNameAngle = str(residue) + "SG" + str(Angle)
        cmd.create(SGNameAngle, dihedSG)
        # Calculate new coordinates for rotation around CA->CB bond. Then translate the created SG atom.
        SGNewPos = fRotateAroundLine(dihedralPosSG, dihedralPosCA, dihedralVector, Angle)
        Translate = [(SGNewPos[0] - dihedralPosSG[0]), (SGNewPos[1] - dihedralPosSG[1]), (SGNewPos[2] - dihedralPosSG[2])]
        cmd.translate(Translate, SGNameAngle, state=0, camera=0)
        # If one wants to "see it happen" while its making the states. But it will take extra computation time.
        if SeeProgress == 'yes':
            cmd.refresh()
        # Calculate number of neighbours within 2.4 Angstrom. Amide hydrogens are not considered, and are actually not build yet.
        nameselect = "(((/" + molecule + "//" + chain + " and not /" + molecule + "//" + chain + "/" + residue + ") or /" + molecule + "//" + chain + "/" + residue + "/N+CA+C+O)  within " + str(NotPopuDist) + " of /" + SGNameAngle + "//" + "/" + "/SG) and not resn HOH"
        # print nameselect
        cmd.select("NotPop", nameselect)
        NotPopNr = cmd.count_atoms("NotPop")
        # print Angle, NotPopNr, cmd.get_dihedral(dihedN,dihedCA,dihedCB,SGNameAngle)
        # If no neighbours, then proceed calculating
        if NotPopNr == 0:
            SumAllWMC = 0.0
            # Now calculate the electric potential due to the side chains.
            SumWSC = fSumWSC(molecule, SGNameAngle, chain, residue, DieElecSC, SCchargeASP, SCchargeGLU, SCchargeOXT, SCchargeARG, SCchargeHIS, SCchargeLYS, SCchargeMET1, printSC)
            # Now we calculate for the flanking 5 peptide groups on each side of the Cysteine CA atom.
            # For the first residue, only calculate for the tailing C,O atom in the peptide bond. No test for Proline.
            SumWMCFirst = fSumWMCFirst(molecule, SGNameAngle, chain, residue, Minresidue, DieElecMC, MCchargeC, MCchargeO, printMC)
            # For the residue itself, we dont test for PRO, since it should be a Cysteine.
            SumWMCresidue = fSumWMCresidue(molecule, SGNameAngle, chain, residue, int(residue), DieElecMC, MCchargeC, MCchargeO, MCchargeN, MCchargeH, AmideName, printMC)
            # For the last residue, we test for Proline. We only calculate for the N,H atom, or if Proline, N,CA and CD atom.
            SumWMCLast = fSumWMCLast(molecule, SGNameAngle, chain, residue, Maxresidue, DieElecMC, MCchargeN, MCchargeH, MCchargeProCA, MCchargeProCD, MCchargeProN, AmideName, printMC)
            # Then loop over rest of the residues in the chain.
            for j in (list(range(Minresidue + 1, int(residue))) + list(range(int(residue) + 1, Maxresidue))):
                MCNeighbour = j
                # print "Looking at neighbour", j
                SumWMC = fSumWMC(molecule, SGNameAngle, chain, residue, MCNeighbour, DieElecMC, MCchargeC, MCchargeO, MCchargeN, MCchargeH, MCchargeProCA, MCchargeProCD, MCchargeProN, AmideName, printMC)
                SumAllWMC = SumAllWMC + SumWMC
                # print "Rotation: %s Neighbour: %s " % (Angle, j)
            # Since the SG atom is negative, we multiply with -1.
            SumMCSC = -1 * (SumWSC + SumWMCFirst + SumWMCresidue + SumWMCLast + SumAllWMC)
            # Makes the neighbour count. Everything in 'molecule" within 7 ang of aligned SG atom. Not counting 'residue'. Adding 5 for 'residue' N,CA,C,O,CB
            ListNeighbourCount = fNeighbourCount(molecule, SGNameAngle, chain, residue, DieElecSpheDist)
            # Calculate the weighted electric potential and alter the b factor for coloring. Then add the rotated SG into bucket of SG atoms.
            SG_MCSC_Weight = fBoltzSingleState(SumMCSC, AvogadroR, Temp) * SumMCSC
            cmd.alter(SGNameAngle, 'b="%s"' % SG_MCSC_Weight)
            cmd.alter(SGNameAngle, 'name="S%s"' % Angle)
            cmd.create(SGName, SGName + " + " + SGNameAngle)
            # Then save the calculated values
            ListofEnergies.append([Angle, SumMCSC, ListNeighbourCount, NotPopNr, SG_MCSC_Weight, cmd.get_atom_coords(SGNameAngle)])
            cmd.delete(SGNameAngle)
        else:
            SumMCSCPenalty = PopEnergyPenalty
            ListNeighbourCount = fNeighbourCount(molecule, SGNameAngle, chain, residue, DieElecSpheDist)
            ListofRotamerDiscarded.append([Angle, SumMCSCPenalty, ListNeighbourCount, NotPopNr, 0, cmd.get_atom_coords(SGNameAngle)])
            cmd.delete(SGNameAngle)
    # Now show all the SG atoms as the available rotameric states.
    cmd.show("nb_spheres", SGName)
    cmd.delete("NotPop")
    cmd.spectrum("b", selection=SGName)
    AvailRotStates = len(ListofEnergies)
    # print "Available Rotational States: ", AvailRotStates

    # Do the calculations according to eq 5.
    # Find the partition function
    BoltzPartition = 0.0
    for i in range(len(ListofEnergies)):
        Boltz = fBoltzSingleState(ListofEnergies[i][1], AvogadroR, Temp)
        BoltzPartition = BoltzPartition + Boltz
    # Find the summed function
    BoltzSumNi = 0.0
    for i in range(len(ListofEnergies)):
        BoltzNi = fBoltzSingleState(ListofEnergies[i][1], AvogadroR, Temp) * ListofEnergies[i][1]
        BoltzSumNi = BoltzSumNi + BoltzNi

    # Check if there was any possible rotamers

    nostates = "no"
    if len(ListofEnergies) == 0:
        print("####################################################")
        print("########### WARNING: No states available ###########")
        print("########### Did you mutate a Glycine?    ###########")
        print("####################################################")
        BoltzSumNi = 0
        BoltzPartition = 0
        BoltzMCSC = 0
        DeltapKMCSC = 99
        NeighbourCount = 0
        nostates = "yes"
    else:
        # Final calculation
        BoltzMCSC = (BoltzSumNi) / (BoltzPartition)
        DeltapKMCSC = fDeltapK(BoltzMCSC, AvogadroR, Temp)

    # Find average number of neighbours
    NCSum = 0.0
    NCWeightedSum = 0.0
    for i in range(len(ListofEnergies)):
        NCi = ListofEnergies[i][2]
        NCSum = NCSum + NCi
        NCWeightedi = fBoltzSingleState(ListofEnergies[i][1], AvogadroR, Temp) * ListofEnergies[i][2] / BoltzPartition
        NCWeightedSum = NCWeightedSum + NCWeightedi
    # print "Weighted neighbour", int(round(NCWeightedSum))
    #NeighbourCount = int(round(NCSum/len(ListofEnergies)))
        NeighbourCount = round(NCWeightedSum, 1)
    # If we found dimers
    if breakDimer == "yes":
        print("####################################################")
        print("########### WARNING: Dimer formation?    ###########")
        print("####################################################")
        BoltzSumNi = 0
        BoltzPartition = 0
        BoltzMCSC = 0
        DeltapKMCSC = 99
        NeighbourCount = 0

    # Calculate the BornPenalty based on the neighbour count. It's a wrapper script for equation 13, 12, 11.
    EnergyBornPenalty = fEnergyBornPenalty(DieElecSpheDist, DieElecWaterDist, NeighbourCount, DieElecWater, DieElecCore, BornPenaltyB)
    DeltapKB = fDeltapK(EnergyBornPenalty, AvogadroR, Temp)

    # Do the calculations according to eq 3 and 9.
    pKm1 = fpKm1(DeltapKMCSC, pK1)
    pKm2 = fpKm2(DeltapKMCSC, DeltapKB, pK2)
    FracCysm1 = fFracCys(pKm1, pH)
    FracCysm2 = fFracCys(pKm2, pH)

    # Lets make a result file, and write out the angle, the SumMCSC, and the number of neighbours for this state.
    Currentdir = os.getcwd()
    Newdir = os.path.join(os.getcwd(), "Results")
    if not os.path.exists(Newdir):
        os.makedirs(Newdir)
    filename = os.path.join(".", "Results", "Result_" + molecule + "_" + chain + "_" + residue + ".txt")
    filenamelog = os.path.join(".", "Results", "Result_log.log")
    logfile = open(filenamelog, "a")
    outfile = open(filename, "w")
    timeforlog = strftime("%Y %b %d %a %H:%M:%S", localtime())
    logfile.write("# " + timeforlog + "\n")
    logfile.write("# molecule: %s , chain: %s, residue: %s %s, pH: %s " % (molecule, chain, residueName, residue, pH) + "\n")
    logfile.write("# BoltzSumNi:  BoltzPartition:  BoltzMCSC" + "\n")
    logfile.write(("# %.4f  %.4f  %.4f" + '\n') % (BoltzSumNi, BoltzPartition, BoltzMCSC))
    logfile.write("#    Res  NC    States  pKmcsc  pK1   pKB     pK2  pKm1     pKm2    f(C-)m1   f(C-)m2" + "\n")
    logfile.write(("; %s %s   %s  %s     %.4f  %s  %.4f  %s  %.4f  %.4f  %.6f  %.6f" + '\n') % (residueName, residue, NeighbourCount, AvailRotStates, DeltapKMCSC, pK1, DeltapKB, pK2, pKm1, pKm2, FracCysm1, FracCysm2))
    if nostates == "yes":
        logfile.write("##### ERROR; No states available ###" + "\n")
    if breakDimer == "yes":
        logfile.write("##### ERROR; Dimer formation ###" + "\n")
    logfile.write('\n')
    outfile.write("# molecule: %s , chain: %s, residue: %s %s, pH: %s " % (molecule, chain, residueName, residue, pH) + "\n")
    outfile.write("# BoltzSumNi:  BoltzPartition:  BoltzMCSC" + "\n")
    outfile.write(("# %.4f  %.4f  %.4f" + '\n') % (BoltzSumNi, BoltzPartition, BoltzMCSC))
    outfile.write("#    Res  NC    States  pKmcsc  pK1   pKB     pK2  pKm1     pKm2    f(C-)m1   f(C-)m2" + "\n")
    outfile.write(("; %s %s   %s  %s     %.4f  %s  %.4f  %s  %.4f  %.4f  %.6f  %.6f" + '\n') % (residueName, residue, NeighbourCount, AvailRotStates, DeltapKMCSC, pK1, DeltapKB, pK2, pKm1, pKm2, FracCysm1, FracCysm2))
    if nostates == "yes":
        outfile.write("##### ERROR; No states available ###" + "\n")
    if breakDimer == "yes":
        outfile.write("##### ERROR; Dimer formation ###" + "\n")
    outfile.write('\n')
    outfile.write("#Ang  SumMCSC   NC rNC MCSC_Weight       SG[X,Y,Z]" + "\n")
    for i in range(len(ListofEnergies)):
        outfile.write("%4.1d %10.3f %2.1d %1.1d %10.3f [%8.3f, %8.3f, %8.3f]" % (ListofEnergies[i][0], ListofEnergies[i][1], ListofEnergies[i][2], ListofEnergies[i][3], ListofEnergies[i][4], ListofEnergies[i][5][0], ListofEnergies[i][5][1], ListofEnergies[i][5][2]) + '\n')
    for i in range(len(ListofRotamerDiscarded)):
        outfile.write("%4.1d %10.3f %2.1d %1.1d %10.3f [%8.3f, %8.3f, %8.3f]" % (ListofRotamerDiscarded[i][0], ListofRotamerDiscarded[i][1], ListofRotamerDiscarded[i][2], ListofRotamerDiscarded[i][3], ListofRotamerDiscarded[i][4], ListofRotamerDiscarded[i][5][0], ListofRotamerDiscarded[i][5][1], ListofRotamerDiscarded[i][5][2]) + '\n')
    outfile.close()

    # Now, we are done. Just print out. The ; is for a grep command to select these lines in the output.
    print("# residue: %s %s. Average NeighbourCount NC= %s " % (residueName, residue, NeighbourCount))
    print("# From residue %s to residue %s" % (Minresidue, Maxresidue))
    print("# BoltzSumNi:  BoltzPartition:  BoltzMCSC")
    print("# %.4f  %.4f  %.4f" % (BoltzSumNi, BoltzPartition, BoltzMCSC))
    print("# Result written in file: %s" % (filename))
    print("#    Res  NC    States  pKmcsc  pK1   pKB     pK2  pKm1     pKm2    f(C-)m1   f(C-)m2")
    print("; %s %s   %s  %s     %.4f  %s  %.4f  %s  %.4f  %.4f  %.6f  %.6f" % (residueName, residue, NeighbourCount, AvailRotStates, DeltapKMCSC, pK1, DeltapKB, pK2, pKm1, pKm2, FracCysm1, FracCysm2))
    if nostates == "yes":
        print("##### ERROR; No states available ###")
    if breakDimer == "yes":
        print("##### ERROR; Dimer formation ###")
Exemple #55
0
    elif 'calphaforcefield'.startswith(ff):
        forcefield = CalphaForceField(cutoff=cutoff/10.)
    elif 'amber94forcefield'.startswith(ff):
        from MMTK.ForceFields import Amber94ForceField
        forcefield = Amber94ForceField()
        model = 'all'
    else:
        raise NotImplementedError('unknown ff = ' + str(ff))
    if not quiet:
        print ' Forcefield:', forcefield.__class__.__name__

    if model == 'calpha':
        selection = '(%s) and polymer and name CA' % (selection)

    from cStringIO import StringIO
    f = StringIO(cmd.get_pdbstr(selection))
    conf = PDBConfiguration(f)
    items = conf.createPeptideChains(model)

    universe = InfiniteUniverse(forcefield)
    universe.protein = Protein(*items)

    nbasis = max(10, universe.numberOfAtoms()/5)
    cutoff, nbasis = estimateCutoff(universe, nbasis)
    if not quiet:
        print " Calculating %d low-frequency modes." % nbasis

    if cutoff is None:
        modes = NormalModes(universe)
    else:
        subspace = FourierBasis(universe, cutoff)
Exemple #56
0
def sst(selection='(all)', raw='', state=-1, quiet=1):
    '''
DESCRIPTION

    Secondary structure assignment with SST.
    http://lcb.infotech.monash.edu.au/sstweb/

SEE ALSO

    dss, dssp, stride
    '''
    try:
        import urllib2
    except ImportError:
        import urllib.request as urllib2

    state, quiet = int(state), int(quiet)

    ss_map = {
        'C': 'L',
        'E': 'S',
        'G': 'H',
        'H': 'H',
        'I': 'H',
        'g': 'H',
        'h': 'H',
        'i': 'H',
        '3': 'L',
        '4': 'L',
        '5': 'L',
        'T': 'L',
        '-': 'L',
        '|': 'L',
        ':': 'H',
    }
    ss_dict = {}
    boundary = '192.168.1.80.500.9981.1375391031.267.10'

    for model in cmd.get_object_list(selection):
        pdbstr = cmd.get_pdbstr('%s & guide & (%s)' % (model, selection), state)

        body = '\r\n'.join([
            '--' + boundary,
            'Content-Disposition: file; name="pdb_file"; filename="abc.pdb"',
            'Content-Type: text/plain',
            '',
            pdbstr,
            '--' + boundary + '--',
            '',
        ])

        try:
            request = urllib2.Request(
                    'http://lcb.infotech.monash.edu.au/sstweb/formaction_pdbfile.php')
            request.add_header('User-agent', 'PyMOL ' + cmd.get_version()[0] + ' ' +
                    cmd.sys.platform)
            request.add_header('Content-type', 'multipart/form-data; boundary=%s' % boundary)
            request.add_header('Content-length', len(body))
            request.add_data(body)
            lines = urllib2.urlopen(request).readlines()
        except urllib2.URLError:
            print(' Error: URL request failed')
            raise CmdException

        lines = iter(lines)

        for line in lines:
            if line.startswith('..........RESIDUE LEVEL'):
                break
        else:
            if not quiet:
                print(' Warning: SST assignment failed')
            return

        next(lines)

        for line in lines:
            if line.startswith('...................................END'):
                break
            chain = line[2].strip()
            resi = line[3:9].strip()
            ss = line[21]
            ss_dict[model,chain,resi] = ss

    _common_ss_alter(selection, ss_dict, ss_map, raw)