def main(): print sys.argv if len(sys.argv) != 3 and len(sys.argv) != 4: # if no input print "ERROR: Wrong number of inputs" print "syntax: chimera --nogui --script \"chimera_dockprep.py pdbinput output_prefix keepH\"" print len(sys.argv) return #models = openModels.list(modelTypes=[chimera.Molecule]) input_pdb = sys.argv[1] output_prefix = sys.argv[2] if len(sys.argv) == 4: if (sys.argv[3] == 'yes'): keepH = True elif (sys.argv[3] == 'no'): keepH = False else: print("keepH must be yes or no, setting it to no.") keepH = False else: keepH = False print "pdb input = " + input_pdb print "output prefix = " + output_prefix #runCommand("open " + input_pdb) #models = chimera.openModels.list(modelTypes=[chimera.Molecule]) #model = models model = openModels.open(input_pdb) if not (keepH): runCommand("del @H,H?,H??,H???") # remove all hydrogens writeMol2(model, output_prefix+"before_dockprep.mol2") prep(model) runCommand("write 0 "+output_prefix+".pdb") writeMol2(model, output_prefix+".mol2") runCommand("del HC") # remove all non-polar hydrogens runCommand("write 0 "+output_prefix+"_polarH.pdb") runCommand("del @H,H?,H??,H???") # remove all hydrogens runCommand("write 0 "+output_prefix+"_noH.pdb")
def Apply(self): from chimera import dialogs kw = {'status': replyobj.status} paths = self.getPaths() if not paths: replyobj.error('No save location chosen.\n') return path = paths[0] models = self.modelList.getvalue() if not models: replyobj.error("No models chosen to save.\n") return if float(self.modelList.size()) > 1.5: if self.saveRelativeVar.get(): kw['relModel'] = self.relModelMenu.getvalue() else: if self.saveUntransformedVar.get(): kw['relModel'] = models[0] if self.writeGaffVar.get(): kw['gaffType'] = True from chimera import UserError kw['gaffFailError'] = UserError if self.rigidVar.get(): sel = selection.copyCurrent() sel.addImplied() selAtoms = sel.atoms() selBonds = sel.bonds() if selAtoms and selBonds: kw['anchor'] = sel sybylHydNaming = self.sybylHydNamesVar.get() if sybylHydNaming: self.prefs["hydrogen naming"] = "sybyl" else: self.prefs["hydrogen naming"] = "pdb" kw['hydNamingStyle'] = self.prefs["hydrogen naming"] kw['resNum'] = self.resNumsVar.get() from WriteMol2 import writeMol2 if len(models) < 2: replyobj.status("Writing %s to %s\n" % (models[0].name, path)) writeMol2(models, path, **kw) replyobj.status("Wrote %s to %s\n" % (models[0].name, path)) return saveOpt = self.multiSaveMenu.getvalue() for key, value in self.labelMap.items(): if saveOpt == value: break self.prefs["multiSaveMol2"] = key # write multiple models to multiple files if key == "multiple": if path.endswith(".mol2"): start, end = path[:-4], ".mol2" else: start, end = path, "" for m in models: modelPath = start + m.oslIdent()[1:] + end replyobj.status("Writing %s (%s) to %s\n" % (m.name, m.oslIdent(), modelPath)) writeMol2(m, modelPath, **kw) replyobj.status("Wrote %s (%s) to %s\n" % (m.name, m.oslIdent(), modelPath)) return kw["multimodelHandling"] = key # write multiple models to single file replyobj.status("Writing multiple models to %s\n" % path) writeMol2(models, path, **kw) replyobj.status("Wrote multiple models to %s\n" % path)
#chdir("receptors") # change to the receptors file directory for pdb in listdir("."): if pdb.endswith("_aligned.pdb"): continue if pdb.endswith("_noH.pdb"): continue if not pdb.endswith("_mod2.pdb"): #originally was .pdb before pdb2pqr.py continue #if pdb == "1gzm.pdb": # don't need to do the pdb used for align # continue runCommand("open " + pdb) runCommand("open 1gzm.pdb") runCommand("mmaker #1 #0") runCommand("write relative #1 #0 " + pdb[:-4] + "_aligned.pdb") runCommand("close all") pdb = pdb[:-4] + "_aligned.pdb" runCommand("open " + pdb) from DockPrep import prep models = chimera.openModels.list(modelTypes=[chimera.Molecule]) prep(models) from WriteMol2 import writeMol2 writeMol2(models, pdb[:-4]+ "_charged.mol2") runCommand("select H") runCommand("del sel") runCommand("write format pdb 0 " + pdb[:-4] + "_noH.pdb") runCommand("close all")
from chimera import runCommand from chimera import openModels, Molecule from os import chdir, listdir import chimera from WriteMol2 import writeMol2 import sys file = open("com.txt") for line in file: if line.find("centroid has center") != -1: #print "OPENED:%s" % line word = line.split() #print word x = float(word[3]) y = float(word[4]) z = float(word[5]) + 16 center = Point(x, y, z) runCommand("open " + sys.argv[1]) model0 = openModels.list(id=0, modelTypes=[Molecule])[0] c = BuildStructure.placeHelium('com', model=model0, position=center) runCommand("select He") runCommand("namesel helium") runCommand("select helium za>10") runCommand("del sel") runCommand("del helium") writeMol2(chimera.openModels.list(modelTypes=[chimera.Molecule]), sys.argv[1][:-4] + ".mol2") runCommand("close all")
def initiateSolvate(models, method, solvent, extent, center, status): import os import chimera from chimera import replyobj from chimera.molEdit import addAtom from WriteMol2 import writeMol2 from tempfile import mkdtemp for m in models: tempDir = mkdtemp() print 'tempDir: ', tempDir def _clean(): for fn in os.listdir(tempDir): os.unlink(os.path.join(tempDir, fn)) os.rmdir(tempDir) sleapIn = os.path.join(tempDir, "sleap.in.mol2") sleapOut= os.path.join(tempDir, "sleap.out.mol2") writeMol2([m], sleapIn, status=status) leaprc = os.path.join(tempDir, "solvate.cmd") writeLeaprc(tempDir, method, solvent, extent, center, leaprc) chimeraRoot = os.environ["CHIMERA"] amberHome = os.path.join(chimeraRoot, "bin", "amber10") command = [os.path.join(amberHome, "exe", "sleap"), "-f", leaprc] print 'command: ', command if status: status("Running sleap" ) from subprocess import Popen, STDOUT, PIPE # For some reason on Windows, if shell==False then antechamber # cannot run bondtype via system(). import sys if sys.platform == "win32": shell = True else: shell = False replyobj.info("Running sleap command: %s\n" % " ".join(command)) import os os.environ["AMBERHOME"]=amberHome sleapMessages = Popen(command, stdin=PIPE, stdout=PIPE, stderr=STDOUT, cwd=tempDir, shell=shell, bufsize=1).stdout while True: line = sleapMessages.readline() if not line: break replyobj.status("(solvate) %s" % line, log=True) if not os.path.exists(sleapOut): _clean() from chimera import NonChimeraError raise NonChimeraError("Failure running sleap \n" "Check reply log for details\n") if status: status("Reading sleap output\n") from chimera import Mol2io, defaultMol2ioHelper mol2io = Mol2io(defaultMol2ioHelper) mols = mol2io.readMol2file(sleapOut) if not mol2io.ok(): _clean() raise IOError(mol2io.error()) if not mols: _clean() raise RuntimeError("No molecules in sleap output") assert len(mols)==1 outm = mols[0] natom = len(m.atoms) nresd = len(m.residues) inAtoms = m.atoms outAtoms = outm.atoms # sort in coordIndex (i.e. input) order # (due to deletions, coordIndex values need _not_ be consecutive) serialSort = lambda a1, a2: cmp(a1.coordIndex, a2.coordIndex) inAtoms.sort(serialSort) outAtoms.sort(serialSort) if status: status("Translating %d atoms" % len(inAtoms)) for inA, outA in zip(inAtoms, outAtoms[:len(inAtoms)]): inA.setCoord(outA.coord()) # added solvent hydrogens may not have been categorized yet, so use # this less obvious way of gathering solvent atoms... existingSolvent = set() from chimera.elements import metals, alkaliMetals nonAlkaliMetals = metals - alkaliMetals for r in m.residues: if len(r.atoms) == 1 and r.atoms[0].element in nonAlkaliMetals: continue for a in r.atoms: if a.surfaceCategory in ["solvent", "ions"]: existingSolvent.update(r.atoms) break # copy mol2 comment which contain the info of the solvent: shape, size, etc if hasattr( outm, "mol2comments" ) and len(outm.mol2comments) > 0: m.solventInfo = outm.mol2comments[0] print "solvent info: ", m.solventInfo if existingSolvent: solventCharges = {} for r in outm.residues[nresd:]: solventNum = r.id.position - nresd if status: status("Creating solvent residue %d " % solventNum ) atomMap = {} nr = m.newResidue(r.type, ' ', solventNum, ' ') # mark residue for exclusion by AddCharge... nr._solvateCharged = True for a in r.atoms: na = addAtom(a.name, a.element, nr, a.coord(), serialNumber=a.serialNumber) na.charge = a.charge na.gaffType = a.mol2type atomMap[a] = na if a.name[0]=="H": na.element = 1 if a.name[0]=="C": na.element = 6 if a.name[0]=="N": na.element = 7 if a.name[0]=="O": na.element = 8 if a.name[0]=="P": na.element = 15 if a.name[0]=="S": na.element = 16 if a.name[0:2]=="Cl": na.element = 17 if existingSolvent: solventCharges[(r.type, a.name)] = a.charge if r.type == "WAT": solventCharges[ ("HOH", a.name)] = a.charge for a in r.atoms: na = atomMap[a] for n in a.neighbors: assert n.residue == r nn = atomMap[n] if nn in na.bondsMap: continue m.newBond(na, nn) if existingSolvent: unknowns = set() for sa in existingSolvent: key = (sa.residue.type, sa.name) try: sa.charge = solventCharges[key] except KeyError: unknowns.add(key) sa.residue._solvateCharged = True if unknowns: replyobj.warning("Could not determine charges for" " pre-existing solvent/ions from added solvent" "/ions for: " + ", ".join([" ".join(x) for x in unknowns])) _clean() from Midas import window window(models)
def initiateAddions(models, iontype, numion, status): import os import chimera from chimera import replyobj from chimera.molEdit import addAtom from WriteMol2 import writeMol2 from tempfile import mkdtemp for m in models: tempDir = mkdtemp() def _clean(): for fn in os.listdir(tempDir): os.unlink(os.path.join(tempDir, fn)) os.rmdir(tempDir) sleapIn = os.path.join(tempDir, "sleap.in.mol2") sleapOut= os.path.join(tempDir, "sleap.out.mol2") writeMol2([m], sleapIn, status=status, gaffType=True) leaprc = os.path.join(tempDir, "solvate.cmd") writeLeaprc(tempDir, iontype, numion, leaprc) chimeraRoot = os.environ["CHIMERA"] amberHome = os.path.join(chimeraRoot, "bin", "amber10") command = [os.path.join(amberHome, "exe", "sleap"), "-f", leaprc] if status: status("Running sleap" ) from subprocess import Popen, STDOUT, PIPE # For some reason on Windows, if shell==False then antechamber # cannot run bondtype via system(). import sys if sys.platform == "win32": shell = True else: shell = False replyobj.info("Running sleap command: %s\n" % " ".join(command)) import os os.environ["AMBERHOME"]=amberHome sleapMessages = Popen(command, stdin=PIPE, stdout=PIPE, stderr=STDOUT, cwd=tempDir, shell=shell, bufsize=1).stdout while True: line = sleapMessages.readline() if not line: break replyobj.status("(addions) %s" % line, log=True) if not os.path.exists(sleapOut): _clean() from chimera import NonChimeraError raise NonChimeraError("Failure running sleap \n" "Check reply log for details\n") if status: status("Reading sleap output\n") from chimera import Mol2io, defaultMol2ioHelper mol2io = Mol2io(defaultMol2ioHelper) mols = mol2io.readMol2file(sleapOut) if not mol2io.ok(): _clean() raise IOError(mol2io.error()) if not mols: _clean() raise RuntimeError("No molecules in sleap output") assert len(mols)==1 outm = mols[0] solute_nresd = get_solute_nresd(m) print "total, solute, solvent: ", len(m.residues), solute_nresd, len(m.residues)-solute_nresd if status: status( "Deleting old solvents" ) while len(m.residues) > solute_nresd: m.deleteResidue( m.residues[solute_nresd] ) inAtoms = m.atoms outAtoms = outm.atoms # sort in coordIndex (i.e. input) order # (due to deletions, coordIndex values need _not_ be consecutive) serialSort = lambda a1, a2: cmp(a1.coordIndex, a2.coordIndex) inAtoms.sort(serialSort) outAtoms.sort(serialSort) # sleap repositions solute... if status: status("Translating %d atoms" % len(inAtoms)) for inA, outA in zip(inAtoms, outAtoms[:len(inAtoms)]): inA.setCoord(outA.coord()) for r in outm.residues[solute_nresd:]: if status: status("Creating ions/solvent residue %d " % (r.id.position-solute_nresd) ) atomMap = {} nr = m.newResidue(r.type, ' ', 1, ' ') for a in r.atoms: na = addAtom(a.name, a.element, nr, a.coord(), serialNumber=a.serialNumber) na.charge = a.charge na.gaffType = a.mol2type if len(a.neighbors)==0: na.drawMode = chimera.Atom.Sphere atomMap[a] = na if a.name[0:2]=="Br": na.element = 35 elif a.name[0:2]=="Cl": na.element = 17 elif a.name[0:2]=="Cs": na.element = 47 elif a.name[0:2]=="Mg": na.element = 12 elif a.name[0:2]=="Na": na.element = 11 elif a.name[0:2]=="Rb": na.element = 48 elif a.name[0]=='F': na.element = 9 elif a.name[0]=='I': na.element = 53 elif a.name[0]=='K': na.element = 19 elif a.name[0]=="H": na.element = 1 elif a.name[0]=="C": na.element = 6 elif a.name[0]=="N": na.element = 7 elif a.name[0]=="O": na.element = 8 elif a.name[0]=="P": na.element = 15 elif a.name[0]=="S": na.element = 16 for a in r.atoms: na = atomMap[a] for n in a.neighbors: assert n.residue == r nn = atomMap[n] if nn in na.bondsMap: continue m.newBond(na, nn) _clean()
def writePrmtop(m, topfile, parmset, unchargedAtoms=None): import os import chimera from chimera import replyobj from WriteMol2 import writeMol2 from tempfile import mkdtemp status = replyobj.status if unchargedAtoms and parmset.lower().endswith("ua"): # united atom replyobj.warning("Some uncharged/untyped protons expected due" " to use of united-atom force field.\n") unchargedHeavy = [] skip = [] for uncharged in unchargedAtoms.values(): for uc in uncharged: if uc.element.number == 1: skip.append(uc) else: unchargedHeavy.append(uc) unchargedAtoms = unchargedHeavy else: skip = [] if unchargedAtoms: if chimera.nogui: raise ValueError("Some atoms don't have charges/types") from chimera.baseDialog import AskYesNoDialog d = AskYesNoDialog("Some atoms don't have charges/types" " assigned. Write prmtop anyway?") if d.run(chimera.tkgui.app) == "no": return tempDir = mkdtemp() def _clean(): for fn in os.listdir(tempDir): os.unlink(os.path.join(tempDir, fn)) os.rmdir(tempDir) sleapIn = os.path.join(tempDir, "sleap.in.mol2") writeMol2([m], sleapIn, status=status, gaffType=True, skip=skip) leaprc = os.path.join(tempDir, "solvate.cmd") writeLeaprc(tempDir, topfile, parmset, leaprc) chimeraRoot = os.environ["CHIMERA"] amberHome = os.path.join(chimeraRoot, "bin", "amber10") acHome = os.path.join(chimeraRoot, "bin", "antechamber") command = [os.path.join(amberHome, "exe", "sleap"), "-f", leaprc] print 'command: ', command if status: status("Running sleap" ) from subprocess import Popen, STDOUT, PIPE # For some reason on Windows, if shell==False then antechamber # cannot run bondtype via system(). import sys if sys.platform == "win32": shell = True else: shell = False replyobj.info("Running sleap command: %s\n" % " ".join(command)) import os os.environ["AMBERHOME"]=amberHome os.environ["ACHOME"]=acHome sleapMessages = Popen(command, stdin=PIPE, stdout=PIPE, stderr=STDOUT, cwd=tempDir, shell=shell, bufsize=1).stdout while True: line = sleapMessages.readline() if not line: break replyobj.status("(writeprmtop) %s" % line, log=True) if not os.path.exists(topfile): _clean() from chimera import NonChimeraError raise NonChimeraError("Failure running sleap \n" "Check reply log for details\n") else: replyobj.status("Wrote parmtop file %s\n" % topfile, log=True)
def _nonStdCharge(residues, netCharge, method, gaffType, status, showCharges): r = residues[0] if status: status("Copying residue %s\n" % r.type) # create a fake Molecule that we can write to a Mol2 file nm = chimera.Molecule() nm.name = r.type # write out the residue's atoms first, since those are the # ones we will be caring about nr = nm.newResidue(r.type, ' ', 1, ' ') from chimera.molEdit import addAtom atomMap = {} atomNames = set() ratoms = r.atoms # use same ordering of atoms as they had in input, to improve # consistency of antechamber charges ratoms.sort(lambda a1, a2: cmp(a1.coordIndex, a2.coordIndex)) for a in ratoms: atomMap[a] = addAtom(a.name, a.element, nr, a.coord()) atomNames.add(a.name) # add the intraresidue bonds and remember the interresidue ones nearby = set() for a in ratoms: na = atomMap[a] for n in a.neighbors: if n.residue != r: nearby.add(n) continue nn = atomMap[n] if nn in na.bondsMap: continue nm.newBond(na, nn) from chimera.idatm import typeInfo extras = set() while nearby: nb = nearby.pop() aname = _getAName(str(nb.element), atomNames) na = addAtom(aname, nb.element, nr, nb.coord()) atomMap[nb] = na extras.add(na) for nbn in nb.neighbors: if nbn in atomMap: nm.newBond(na, atomMap[nbn]) else: try: ti = typeInfo[nbn.idatmType] except KeyError: fc = 0 geom = 4 else: fc = estimateNetCharge([nbn]) geom = ti.geometry if fc or geom != 4: nearby.add(nbn) else: extras.update( _methylate(na, nbn, atomNames)) totalNetCharge = netCharge + estimateNetCharge(extras) from tempfile import mkdtemp import os, os.path tempDir = mkdtemp() def _clean(): for fn in os.listdir(tempDir): os.unlink(os.path.join(tempDir, fn)) os.rmdir(tempDir) from WriteMol2 import writeMol2 anteIn = os.path.join(tempDir, "ante.in.mol2") writeMol2([nm], anteIn, status=status) chimeraRoot = os.environ["CHIMERA"] anteHome = os.path.join(chimeraRoot, 'bin', 'antechamber') anteOut = os.path.join(tempDir, "ante.out.mol2") if method.lower().startswith("am1"): mth = "bcc" elif method.lower().startswith("gas"): mth = "gas" else: _clean() raise ValueError("Unknown charge method: %s" % method) command = [os.path.join(anteHome, "exe", "antechamber"), "-i", anteIn, "-fi", "mol2", "-o", anteOut, "-fo", "mol2", "-c", mth, "-nc", str(totalNetCharge), "-df", "0", "-j", "5", "-s", "2"] if status: status("Running ANTECHAMBER for residue %s\n" % r.type) from subprocess import Popen, STDOUT, PIPE # For some reason on Windows, if shell==False then antechamber # cannot run bondtype via system(). import sys if sys.platform == "win32": shell = True else: shell = False replyobj.info("Running ANTECHAMBER command: %s\n" % " ".join(command)) import os os.environ['ACHOME'] = anteHome anteMessages = Popen(command, stdin=PIPE, stdout=PIPE, stderr=STDOUT, cwd=tempDir, shell=shell, bufsize=1).stdout while True: line = anteMessages.readline() if not line: break replyobj.status("(%s) %s" % (r.type, line), log=True) if not os.path.exists(anteOut): _clean() raise ChargeError("Failure running ANTECHAMBER for residue %s\n" "Check reply log for details\n" % r.type) if status: status("Reading ANTECHAMBER output for residue %s\n" % r.type) from chimera import Mol2io, defaultMol2ioHelper mol2io = Mol2io(defaultMol2ioHelper) mols = mol2io.readMol2file(anteOut) if not mol2io.ok(): _clean() raise IOError(mol2io.error()) if not mols: _clean() raise RuntimeError("No molecules in ANTECHAMBER output for" " residue %s" % r.type) chargedAtoms = mols[0].atoms if len(chargedAtoms) != len(nm.atoms): _clean() raise RuntimeError("Wrong number of atoms (%d, should be %d)" " in ANTECHAMBER output for residue %s" % (r.type, len(chargedAtoms), len(nm.atoms))) if status: status("Assigning charges for residue %s\n" % r.type) # put charges in template templateAtoms = nm.atoms # can't rely on order... templateAtoms.sort(lambda a1, a2: cmp(a1.serialNumber, a2.serialNumber)) nonZero = False addedChargeSum = 0.0 _totalCharge = 0.0 for ta, ca in zip(templateAtoms, chargedAtoms): _totalCharge += ca.charge if ta in extras: addedChargeSum += ca.charge continue if ca.charge: nonZero = True if not nonZero: _clean() raise ChargeError("Failure running ANTECHAMBER for residue %s\n" "Check reply log for details\n" % r.type) # adjust charges to compensate for added atoms... adjustment = (addedChargeSum - (totalNetCharge - netCharge)) / ( len(templateAtoms) - len(extras)) for ta, ca in zip(templateAtoms, chargedAtoms): if ta in extras: continue ta.charge = ca.charge + adjustment if gaffType: ta.gaffType = ca.mol2type # map template charges onto first residue track = chimera.TrackChanges.get() for fa, ta in atomMap.items(): if ta in extras: continue fa.charge = ta.charge if showCharges: fa.label = "%+g" % fa.charge track.addModified(fa, ATTR_SET) if gaffType: fa.gaffType = ta.gaffType # map charges onto remaining residues for rr in residues[1:]: for fa, ra in zip(r.oslChildren(), rr.oslChildren()): ra.charge = fa.charge if showCharges: ra.label = "%+g" % ra.charge track.addModified(ra, ATTR_SET) if gaffType: ra.gaffType = fa.gaffType _clean() if status: status("Charges for residue %s determined\n" % r.type) replyobj.info("Charges for residue %s determined\n" % r.type) return True