def _initBlast(self, program, db, queryName, querySeq, evalue, matrix, passes): self.program = program self.db = db self.queryName = queryName self.params = (querySeq, evalue, matrix, passes) from WebServices.AppService_types import ns0 from WebServices.opal_client import OpalService inputFile = ns0.InputFileType_Def("inputFile") inputFile._name = "query.fa" inputFile._contents = self.makeFasta(queryName, querySeq) service = "BlastproteinServicePort" argList = "-P %s -d %s -i %s -o %s -e %s -M %s -p %s" % ( program, db, inputFile._name, self.outputFile, evalue, matrix, passes) try: self.opal = OpalService(service) except: import traceback, sys print "Traceback from Blast request:" traceback.print_exc(file=sys.stdout) print """ Typically, if you get a TypeError, it's a problem on the remote server and it should be fixed shortly. If you get a different error or get TypeError consistently for more than a day, please report the problem using the Report a Bug... entry in the Help menu. Please include the traceback printed above as part of the problem description.""" from chimera import NonChimeraError raise NonChimeraError("Blast web service appears " "to be down. See Reply Log " "for more details.") self.opal.launchJob(argList, _inputFile=[inputFile]) from chimera.tasks import Task self.task = Task(self._title(), self.cancelCB, self.statusCB)
def getOutputs(self): if self.status is None: raise RuntimeError("No job has been launched yet") from AppService_client import getOutputsRequest import socket req = getOutputsRequest(self.jobID) try: resp = self.appServicePort.getOutputs(req) except socket.error, e: from chimera import NonChimeraError raise NonChimeraError(str(e))
def wait(self): baseDialog.ModelessDialog.enter(self) self._toplevel.grab_set() self._grabbed = True from chimera.update import UPDATE_INTERVAL self._toplevel.after(UPDATE_INTERVAL, self._modalWait) self._toplevel.mainloop() if self._aborted: from chimera import NonChimeraError raise NonChimeraError("Raytrace cancelled by user") return self.returncode
def destroy(self): if self.jobID is None: self.status = None return from AppService_client import destroyRequest import socket req = destroyRequest(self.jobID) try: status = self.appServicePort.destroy(req) except socket.error, e: from chimera import NonChimeraError raise NonChimeraError(str(e))
def launchJobBlocking(self, cmdLine, **kw): if self.jobID is not None: raise RuntimeError("Job has been launched already") from AppService_client import launchJobBlockingRequest import socket req = launchJobBlockingRequest() req._argList = cmdLine for key, value in kw.iteritems(): setattr(req, key, value) try: resp = self.appServicePort.launchJobBlocking(req) except socket.error, e: from chimera import NonChimeraError raise NonChimeraError(str(e))
def wait(self): import chimera from chimera import tkgui from chimera.update import UPDATE_INTERVAL from time import sleep interval = UPDATE_INTERVAL / 1000.0 # msec -> sec self.statusCB() while self.returncode is None and not self._aborted: sleep(interval) self.statusCB() tkgui.update_windows() if self._aborted: from chimera import NonChimeraError raise NonChimeraError("Raytrace cancelled by user") return self.returncode
def Apply(self): from AddCharge import addNonstandardResCharges, ChargeError prefs[CHARGE_METHOD] = self.chargeMethod.getvalue() for resName, opt in self.options.items(): try: addNonstandardResCharges(self.unchargedResidues[resName], int(opt.getvalue()), status=self.status, method=prefs[CHARGE_METHOD].lower(), gaffType=self.gaffType, showCharges=self.showCharges) except ChargeError, v: from chimera import NonChimeraError raise NonChimeraError(v) del self.unchargedResidues[resName]
def launchJob(self, cmdLine, **kw): if self.jobID is not None or self.busy: raise RuntimeError("Job has been launched already") import chimera from AppService_client import launchJobRequest import socket req = launchJobRequest() req._argList = cmdLine for key, value in kw.iteritems(): setattr(req, key, value) if chimera.nogui: try: resp = self.appServicePort.launchJob(req) except socket.error, e: from chimera import NonChimeraError raise NonChimeraError(str(e)) self.jobID = resp._jobID self._saveStatus(resp._status)
def queryStatus(self): #import sys #print >> sys.__stderr__, "calling from queryStatus", self.busy if self.busy: return if self.status is None: raise RuntimeError("No job has been launched yet") import chimera from AppService_client import queryStatusRequest import socket req = queryStatusRequest(self.jobID) if chimera.nogui: try: status = self.appServicePort.queryStatus(req) except socket.error, e: from chimera import NonChimeraError raise NonChimeraError(str(e)) self._saveStatus(status)
def __init__(self, pdbpath, expath, name, fig): from WebServices.AppService_types import ns0 from WebServices.opal_client import OpalService self.pdbpath = pdbpath self.expath = expath self.name = name self.figure = fig pdbFile = ns0.InputFileType_Def("inputFile") pdbFile._name = "pdbfile" f = open(pdbpath) pdbFile._contents = f.read() f.close() files = [pdbFile] argList = "pdbfile" if expath: exFile = ns0.InputFileType_Def("inputFile") exFile._name = "exfile" f = open(expath) exFile._contents = f.read() f.close() files.append(exFile) argList += " exfile" try: self.opal = OpalService("SAXSService") except: import traceback, sys print "Traceback from SAXS request:" traceback.print_exc(file=sys.stdout) print """ Typically, if you get a TypeError, it's a problem on the remote server and it should be fixed shortly. If you get a different error or get TypeError consistently for more than a day, please report the problem using the Report a Bug... entry in the Help menu. Please include the traceback printed above as part of the problem description.""" from chimera import NonChimeraError raise NonChimeraError("SAXS web service appears " "to be down. See Reply Log " "for more details.") self.opal.launchJob(argList, _inputFile=files) from chimera.tasks import Task self.task = Task("SAXS " + self.name, self.cancelCB, self.statusCB)
def fetch_file(url, name, minimum_file_size=None, save_dir='', save_name='', uncompress=False, ignore_cache=False): """a fetched non-local file that doesn't get cached will be removed when Chimera exits if 'ignore_cache' is True, then cached values will be ignored, though the retrieved values will still be cached if appropriate """ from chimera.replyobj import status status('Fetching %s\n' % (name, )) if save_name and not ignore_cache: path = fetch_local_file(save_dir, save_name) if path: return path, {} from chimera import tasks task = tasks.Task("Fetch %s" % name, modal=True) def report_cb(barrived, bsize, fsize): if fsize > 0: percent = min(100.0, (100.0 * barrived * bsize) / fsize) prog = '%.0f%% of %s' % (percent, byte_text(fsize)) else: prog = '%s received' % (byte_text(barrived * bsize), ) task.updateStatus(prog) # TODO: In Python 2.5 socket.error is not an IOError, but in Python 2.6 # it is. Remove socket error when Chimera uses Python 2.6. import urllib, socket try: path, headers = urllib.urlretrieve(url, reporthook=report_cb) except (IOError, socket.error), v: from chimera import NonChimeraError raise NonChimeraError('Error fetching %s: %s' % (name, str(v)))
def read_pqs(id): site = 'ftp.ebi.ac.uk' url_pattern = 'ftp://%s/pub/databases/msd/pqs/macmol/%s' from chimera.replyobj import status # Fetch file(s). models = fetch_pqs(site, url_pattern, id) if len(models) == 0: for suffix in range(1, 100): mlist = fetch_pqs(site, url_pattern, id, '_%d' % suffix) if len(mlist) == 0: break models.extend(mlist) if len(models) == 0: from chimera import NonChimeraError status('\n') raise NonChimeraError('PQS file %s not available.' % id) status('\n') return models
# TODO: In Python 2.5 socket.error is not an IOError, but in Python 2.6 # it is. Remove socket error when Chimera uses Python 2.6. import urllib, socket try: path, headers = urllib.urlretrieve(url, reporthook=report_cb) except (IOError, socket.error), v: from chimera import NonChimeraError raise NonChimeraError('Error fetching %s: %s' % (name, str(v))) task.finished() # Remove from tasks panel # Check if page is too small, indicating error return. if minimum_file_size != None: import os if os.stat(path).st_size < minimum_file_size: from chimera import NonChimeraError raise NonChimeraError('%s not available.' % name) if uncompress and path.endswith('.gz'): status('Uncompressing %s\n' % name) gunzip(path, path[:-3]) status('\n') path = path[:-3] if save_name: spath = save_fetched_file(path, save_dir, save_name) if spath: path = spath if not (url.startswith("file:") or (save_name and spath)): from OpenSave import osTemporaryFile import os tmpPath = osTemporaryFile(suffix=os.path.splitext(path)[1])
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)
self.finished() # 'finished' is called to clean house. def finished(self): # Temporary files will be removed when Chimera exits, but # may be removed here to minimize their lifetime on disk. # The task instance must be notified so that it is labeled # completed in the task panel. self.task.finished() # Set instance variables to None to release references. self.task = None self.molecule = None self.subproc = None # Below is the main program. First, we find the path to # the "grep" program. Then, we run CountAtoms for each molecule. from CGLutil import findExecutable grepPath = findExecutable.findExecutable("grep") if grepPath is None: from chimera import NonChimeraError raise NonChimeraError("Cannot find path to grep") # Add "numAtoms" and "numHetatms" attributes to all open molecules. import chimera from chimera import Molecule for m in chimera.openModels.list(modelTypes=[Molecule]): CountAtoms(m, grepPath)
def display(widgetOrURL, package=chimera, newWindow=False): """Display given html help file. display(widgetOrURL, package=chimera, newWindow=False) => None The url may be either a string, or a "widget" that has been registered. In the latter case it is mapped according to how it was registered. """ try: # compensate for Pmw megawidgets not being Tk widgets widgetOrURL = widgetOrURL.component('hull') except: pass if isinstance(widgetOrURL, basestring): url = widgetOrURL elif hasattr(widgetOrURL, 'winfo_parent'): # show help associated with widget or parent widget while widgetOrURL: if _helpMap.has_key(widgetOrURL): url, package = _helpMap[widgetOrURL] break parent = widgetOrURL.winfo_parent() if not isinstance(parent, str): widgetOrURL = parent elif parent == "": widgetOrURL = None else: widgetOrURL = widgetOrURL._nametowidget(parent) if not widgetOrURL: replyobj.warning('internal error -- no help found for widget\n') return elif isinstance(widgetOrURL, tuple): url, package = widgetOrURL if isinstance(package, basestring): package = __import__(package) else: replyobj.warning("internal error -- no help avaiable for: %s\n" % widgetOrURL) return protocol, location, path, parameters, query, fragment = \ urlparse.urlparse(url, allow_fragments=True) path = urllib.quote(path) parameters = urllib.quote(parameters) query = urllib.quote(query) fragment = urllib.quote(fragment) if path and path[0] != '/': file = os.path.join(package.__path__[0], "helpdir", path) if os.path.exists(file): protocol = 'file' if sys.platform == 'darwin': # # Setting location to localhost is needed on # Mac OS X with Internet Explorer because # urlunparse() produces urls like # file:/index.blah instead of # file:///index.html or # file://localhost/index.html # required by the browser. # location = 'localhost' path = urllib.pathname2url(file) if path[0:3] == '///': path = path[2:] url = urlparse.urlunparse( (protocol, location, path, parameters, query, fragment)) else: # Fetch development version of docs -- a released # version would have the help files included. protocol = 'http' url = urlparse.urljoin('http://www.cgl.ucsf.edu/chimera/docs/', url) replyobj.status("See web browser for %s\n" % url, blankAfter=10) import webbrowser try: webbrowser.open(url, newWindow) except webbrowser.Error: from chimera import NonChimeraError raise NonChimeraError( "Could not locate a web browser to use.\n" "\nTry setting your BROWSER environment variable to\n" "the command-line name of the web browser you want\n" "to use and restart Chimera.") except OSError, e: from chimera import NonChimeraError import errno if e.errno == errno.ENOENT: if protocol == 'file' \ and not os.path.exists(urllib.url2pathname(path)): raise # Bug starting webbrowser (firefox, bug 1512), # Windows usually opens it eventually raise NonChimeraError( "Error or delay starting default web browser.\n" "\n" "Wait a little and if the default web browser\n" "doesn't start up, start it by hand, and try\n" "again.") raise NonChimeraError("Unable to start web browswer.\n" "Open <%s> in your web browswer.\n" "(%s)" % (path, e))
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()