Пример #1
0
    def launchJobNB(self, commandline, inFilesPath, numProcs = None, email = None, \
                    passwd=None):
        """ launchJobNB(commandline, inFilesPath[, numProcs, email, passwd]) -> JobStatus

        It invokes the execution of the remote application and return. 

        commandline: is a string containing the command line that should be executed
        inFilesPath: is a list of strings containing relative or absolute path to the 
            files need to be uploaded for the execution of the application
        numProcs: is the number of processors that should be used to run the parallel 
            application (this option is valid only for parallel applicaiton)
        email: is a string containing the email used to send notification when the 
            application execution will finish
        passwd: is a string containing the passwd used to authenticate with the server
        
        @returns: a JobStatus Oject which can be used to monitor its execution"""

        inputFiles = []
        if inFilesPath != None:
            for i in inFilesPath:
                inputFile = ns0.InputFileType_Def('inputFile')
                inputFile._name = os.path.basename(i)
                if i.startswith("http:") or i.startswith("https:"):
                    #this is a URL
                    inputFile._location = i
                elif self.isOpal2():
                    #use attachment this is opal2 server
                    if os.name == 'dos' or os.name == 'nt':
                        inputFile._attachment = open(i, "rb")
                    else:
                        inputFile._attachment = open(i, "r")
                else:
                    #it's not a opal2 server don't user attachment
                    infile = open(i, "r")
                    inputFile._contents = infile.read()
                    infile.close()
                inputFiles.append(inputFile)

        req = launchJobRequest()
        req._argList = commandline
        req._inputFile = inputFiles
        if email:
            req._sendNotification = True
            req._userEmail = email
        if passwd:
            req._password = passwd
        if numProcs :
            req._numProcs = numProcs
        jobStatus = self.appServicePort.launchJob(req)
        return JobStatus(self, jobStatus._jobID)
Пример #2
0
 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)
Пример #3
0
	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)
Пример #4
0
    def launchJobNB(self, commandline, inFilesPath, numProcs = None, email = None, \
                    passwd=None):
        """ invoke the execution of the remote scientific application
        using Opal a return right away
        
        @returns: a jobStatus Oject which can be used to monitor its execution"""

        inputFiles = []
        if inFilesPath != None:
            for i in inFilesPath:
                inputFile = ns0.InputFileType_Def('inputFile')
                inputFile._name = os.path.basename(i)
                if i.startswith("http:") or i.startswith("https:"):
                    #this is a URL
                    inputFile._location = i
                elif self.isOpal2():
                    #use attachment this is opal2 server
                    if os.name == 'dos' or os.name == 'nt':
                        inputFile._attachment = open(i, "rb")
                    else:
                        inputFile._attachment = open(i, "r")
                else:
                    #it's not a opal2 server don't user attachment
                    infile = open(i, "r")
                    inputFile._contents = infile.read()
                    infile.close()
                inputFiles.append(inputFile)

        req = launchJobRequest()
        req._argList = commandline
        req._inputFile = inputFiles
        if email:
            req._sendNotification = True
            req._userEmail = email
        if passwd:
            req._password = passwd
        if numProcs :
            req._numProcs = numProcs
        jobStatus = self.appServicePort.launchJob(req)
        return JobStatus(self, jobStatus._jobID)
Пример #5
0
def mainCGI():
    """
        Main driver for running PDB2PQR from a web page
    """
    print "Content-type: text/html\n"
    import cgi
    import cgitb

    cgitb.enable()
    form = cgi.FieldStorage()
    ff = form["FF"].value 
    input = 0

    apbs_input = form.has_key("INPUT")
    typemap = form.has_key("TYPEMAP")
    neutraln = form.has_key("NEUTRALN")
    neutralc = form.has_key("NEUTRALC")

    if HAVE_PDB2PQR_OPAL=="1":
        have_opal = True
        # Opal-specific import statments
        from AppService_client import AppServiceLocator, getAppMetadataRequest, launchJobRequest, launchJobBlockingRequest, getOutputAsBase64ByNameRequest
        from AppService_types import ns0
        from ZSI.TC import String
    else:
        have_opal = False

    if have_opal:
        options = {}
        options["ff"] = ff
        fffile = None
        namesfile = None
    else:
        options = {"extensions":{}}
 
  
    if form.has_key("DEBUMP"):
        options["debump"] = 1
    else:
        options["debump"] = 0
    if form.has_key("OPT"):
        options["opt"] = 1
    else:
        options["opt"] = 0
    if form.has_key("PROPKA"):
        try:
            ph = float(form["PH"].value)
            if ph < 0.0 or ph > 14.0: raise ValueError
            options["ph"] = ph
        except ValueError:
             text = "The entered pH of %.2f is invalid!  " % form["PH"].value
             text += "Please choose a pH between 0.0 and 14.0."
             #print "Content-type: text/html\n"
             print text
             sys.exit(2)
    if form.has_key("PDBID"):
        pdbfile = getPDBFile(form["PDBID"].value)
        pdbfilename = form["PDBID"].value
    elif form.has_key("PDB"):
        pdbfile = StringIO(form["PDB"].value)
        pdbfilename = form["PDB"].filename
        pdbfilename = re.split(r'[/\\]',pdbfilename)[-1]
    if form.has_key("INPUT"):
        input = 1
        options["apbs"] = 1
    if form.has_key("USERFF"):
        if have_opal:
            ffname = form["USERFF"].filename
            ffname = re.split(r'[/\\]',ffname)[-1]
            if ffname[-4:] == ".DAT":
               ffname = ffname[:-4]
            fffile = StringIO(form["USERFF"].value)
            namesfile = StringIO(form["USERNAMES"].value)
            options["ff"] = ffname
            options["userff"] = fffile
            options["usernames"] = namesfile
        else:
            userff = StringIO(form["USERFF"].value)
            usernames = StringIO(form["USERNAMES"].value)
            options["ff"] = "user-defined"
            options["userff"] = userff
            options["usernames"] = usernames
    if form.has_key("FFOUT"):
        if form["FFOUT"].value != "internal":
            options["ffout"] = form["FFOUT"].value
    if form.has_key("CHAIN"):
        options["chain"] = 1
    if form.has_key("WHITESPACE"):
        options["whitespace"] = 1
    if form.has_key("TYPEMAP"):
        options["typemap"] = 1
    if form.has_key("NEUTRALN"):
        options["neutraln"] = 1
    if form.has_key("NEUTRALC"):
        options["neutralc"] = 1
    if form.has_key("LIGAND"):
        if have_opal:
            ligandfilename=str(form["LIGAND"].filename)
            ligandfilename=re.split(r'[/\\]',ligandfilename)[-1]

        # for Windows-style newline compatibility
        templigandfilename = tempfile.mkstemp()[1]
        templigandfile = open(templigandfilename,'w')
        templigandfile.write(form["LIGAND"].value)
        templigandfile.close()
        templigandfile = open(templigandfilename,'rU')
        if have_opal:
            options["ligand"] = templigandfile.read()
        else:
            templigandstring = templigandfile.read() # this variable is used again later to write this file to output
            options["ligand"] = StringIO(templigandstring)
            
        templigandfile.close()
        
    if not have_opal:
        pdbfilestring = pdbfile.read()
        pdblist, errlist = readPDB(StringIO(pdbfilestring))
        dummydef = Definition()
        dummyprot = Protein(pdblist, dummydef)
        if len(pdblist) == 0 and len(errlist) == 0:
            text = "Unable to find PDB file - Please make sure this is "
            text += "a valid PDB file ID!"
            #print "Content-type: text/html\n"
            print text
            sys.exit(2)
        elif dummyprot.numAtoms() > MAXATOMS and "opt" in options:
            text = "<HTML><HEAD>"
            text += "<TITLE>PDB2PQR Error</title>"
            text += "<link rel=\"stylesheet\" href=\"%s\" type=\"text/css\">" % STYLESHEET
            text += "</HEAD><BODY><H2>PDB2PQR Error</H2><P>"
            text += "Due to server limits, we are currently unable to optimize "
            text += "proteins of greater than MAXATOMS atoms on the server (PDB2PQR "
            text += "found %s atoms in the selected PDB file).  If you " % dummyprot.numAtoms()
            text += "want to forgo optimization please try the server again.<P>"
            text += "Otherwise you may use the standalone version of PDB2PQR that "
            text += "is available from the <a href=\"http://pdb2pqr.sourceforge.net\">"
            text += "PDB2PQR SourceForge project page</a>."
            text += "<script type=\"text/javascript\">"
            text += "var gaJsHost = ((\"https:\" == document.location.protocol) ? \"https://ssl.\" : \"http://www.\");"
            text += "document.write(unescape(\"%3Cscript src=\'\" + gaJsHost + \"google-analytics.com/ga.js\' type=\'text/javascript\'%3E%3C/script%3E\"));"
            text += "</script>"
            text += "<script type=\"text/javascript\">"
            text += "try {"
            text += "var pageTracker = _gat._getTracker(\"UA-11026338-3\");"
            for key in options:
                text += "pageTracker._trackPageview(\"/main_cgi/has_%s_%s.html\");" % (key, options[key])
            text += "pageTracker._trackPageview();"
            text += "} catch(err) {}</script>"
            text += "</BODY></HTML>"
            #print "Content-type: text/html\n"
            print text
            sys.exit(2)

    try:
        if have_opal:
            ligandFile=None
            ffFile=None
            namesFile=None
        #else:
        starttime = time.time()
        name = setID(starttime)

        os.makedirs('%s%s%s' % (INSTALLDIR, TMPDIR, name))
        apbsInputFile = open('%s%s%s/apbs_input' % (INSTALLDIR, TMPDIR, name),'w')
        apbsInputFile.write(str(apbs_input))
        apbsInputFile.close()
        typemapInputFile = open('%s%s%s/typemap' % (INSTALLDIR, TMPDIR, name),'w')
        typemapInputFile.write(str(typemap))
        typemapInputFile.close()

        if have_opal:
            myopts=""
            for key in options:
                if key=="opt":
                    if options[key]==0:
                        # user does not want optimization
                        key="noopt"
                    else:
                        # pdb2pqr optimizes by default, don't bother with flag
                        continue
                elif key=="debump":
                    if options[key]==0:
                        # user does not want debumping
                        key="nodebump"
                    else:
                        # pdb2pqr debumps by default, so change this flag to --nodebump
                        continue
                elif key=="ph":
                    val=options[key]
                    key="with-ph=%s" % val
                elif key=="ffout":
                    val=options[key]
                    key="ffout=%s" % val
                elif key=="ligand":
                    val=ligandfilename
                    key="ligand=%s" % val
                    ligandFile = ns0.InputFileType_Def('inputFile')
                    ligandFile._name = val
                    ligandFile._contents = options["ligand"]
                elif key=="apbs":
                    key="apbs-input"
                elif key=="chain":
                    key="chain"
                elif key=="whitespace":
                    key="whitespace"
                elif key=="typemap":
                    key="typemap"
                elif key=="ff":
                    val=options[key]
                    key="ff=%s" % val
                    if fffile:
                      ffFile = ns0.InputFileType_Def('inputFile')
                      ffFile._name = val + ".DAT"
                      ffFileString = fffile.read()
                      ffFile._contents = ffFileString
                    if namesfile:
                      namesFile = ns0.InputFileType_Def('inputFile')
                      namesFile._name = val + ".names"
                      namesFileString = namesfile.read()
                      namesFile._contents = namesFileString
                if key not in ["userff", "usernames"]:
                    myopts+="--"+str(key)+" "
            myopts+=str(pdbfilename)+" "
            if pdbfilename[-4:]==".pdb":
                myopts+="%s.pqr" % str(pdbfilename[:-4])
            else:
                myopts+="%s.pqr" % str(pdbfilename)
            appLocator = AppServiceLocator()
            appServicePort = appLocator.getAppServicePort(PDB2PQR_OPAL_URL)
            # launch job
            req = launchJobRequest()
            req._argList = myopts
            inputFiles = []
            pdbOpalFile = ns0.InputFileType_Def('inputFile')
            pdbOpalFile._name = pdbfilename
            pdbOpalFile._contents = pdbfile.read()
            pdbfile.close()
            inputFiles.append(pdbOpalFile)
            if ligandFile:
              inputFiles.append(ligandFile)
            if ffFile:
              inputFiles.append(ffFile)
            if namesFile:
              inputFiles.append(namesFile)
            req._inputFile=inputFiles
            try:
                resp=appServicePort.launchJob(req)
            except Exception, e:
                printHeader("PDB2PQR Job Submission - Error")
                print "<BODY>\n<P>"
                print "There was an error with your job submission<br>"
                print "</P>"
                print "<script type=\"text/javascript\">"
                print "var gaJsHost = ((\"https:\" == document.location.protocol) ? \"https://ssl.\" : \"http://www.\");"
                print "document.write(unescape(\"%3Cscript src=\'\" + gaJsHost + \"google-analytics.com/ga.js\' type=\'text/javascript\'%3E%3C/script%3E\"));"
                print "</script>"
                print "<script type=\"text/javascript\">"
                print "try {"
                print "var pageTracker = _gat._getTracker(\"UA-11026338-3\");"
                for key in options:
                    print "pageTracker._trackPageview(\"/main_cgi/has_%s_%s.html\");" % (key, options[key])
                print "pageTracker._trackPageview();"
                print "} catch(err) {}</script>"
                print "</BODY>"
                print "</HTML>"
                sys.exit(2)
            #printHeader("PDB2PQR Job Submission",have_opal,jobid=resp._jobID)
            pdb2pqrOpalJobIDFile = open('%s%s%s/pdb2pqr_opal_job_id' % (INSTALLDIR, TMPDIR, name), 'w')
            pdb2pqrOpalJobIDFile.write(resp._jobID)
            pdb2pqrOpalJobIDFile.close()
            print redirector(name)
            if options.has_key("userff"):
                options["userff"] = ffFileString
            if options.has_key("usernames"):
                options["usernames"] = namesFileString
            # Recording CGI run information for PDB2PQR Opal
            pdb2pqrOpalLogFile = open('%s%s%s/pdb2pqr_opal_log' % (INSTALLDIR, TMPDIR, name), 'w')
            pdb2pqrOpalLogFile.write(str(options)+'\n'+str(ff)+'\n'+str(os.environ["REMOTE_ADDR"]))
            pdb2pqrOpalLogFile.close()

        else:
Пример #6
0
def handleOpal(weboptions):
    '''
        Handle opal based run.
    '''
    # Opal-specific import statements
    from AppService_client import AppServiceLocator, launchJobRequest
    from AppService_types import ns0

    inputFiles = []

    if 'userff' in weboptions:
        ffFile = ns0.InputFileType_Def('inputFile')
        ffFile._name = weboptions.userfffilename
        ffFile._contents = weboptions.userffstring
        inputFiles.append(ffFile)

    if 'usernames' in weboptions:
        namesFile = ns0.InputFileType_Def('inputFile')
        namesFile._name = weboptions.usernamesfilename
        namesFile._contents = weboptions.usernamesstring
        inputFiles.append(namesFile)

    if 'ligand' in weboptions:
        ligandFile = ns0.InputFileType_Def('inputFile')
        ligandFile._name = weboptions.ligandfilename
        ligandFile._contents = weboptions.ligandfilestring
        inputFiles.append(ligandFile)

    pdbOpalFile = ns0.InputFileType_Def('inputFile')
    pdbOpalFile._name = weboptions.pdbfilename
    pdbOpalFile._contents = weboptions.pdbfilestring
    inputFiles.append(pdbOpalFile)

    # launch job
    appLocator = AppServiceLocator()
    appServicePort = appLocator.getAppServicePort(PDB2PQR_OPAL_URL)

    req = launchJobRequest()
    req._argList = weboptions.getCommandLine()
    req._inputFile = inputFiles

    try:
        resp = appServicePort.launchJob(req)
    except Exception, e:
        printHeader("PDB2PQR Job Submission - Error")
        print "<BODY>\n<P>"
        print "There was an error with your job submission<br>"
        print "</P>"
        print "<script type=\"text/javascript\">"
        print "var gaJsHost = ((\"https:\" == document.location.protocol) ? \"https://ssl.\" : \"http://www.\");"
        print "document.write(unescape(\"%3Cscript src=\'\" + gaJsHost + \"google-analytics.com/ga.js\' type=\'text/javascript\'%3E%3C/script%3E\"));"
        print "</script>"
        print "<script type=\"text/javascript\">"
        print "try {"
        print "var pageTracker = _gat._getTracker(\"UA-11026338-3\");"
        for key in weboptions:
            print "pageTracker._trackPageview(\"/main_cgi/has_%s_%s.html\");" % (
                key, weboptions[key])
        print "pageTracker._trackPageview();"
        print "} catch(err) {}</script>"
        print "</BODY>"
        print "</HTML>"
        sys.exit(2)
Пример #7
0
def mainCGI():
    """
        Main driver for running PDB2PQR from a web page
    """
    global ligandFile, pdbfilestring, templigandstring, ffFileString, name, pdblist, namesFileString, launchJobRequest, AppServiceLocator, pdbfilename, namesfile, fffile, ns0, ligandfilename, pdbfile, namesFile, ffFile
    print("Content-type: text/html\n")
    import cgi
    import cgitb

    cgitb.enable()
    form = cgi.FieldStorage()
    ff = form["FF"].value
    input = 0

    apbs_input = "INPUT" in form
    typemap = "TYPEMAP" in form
    neutraln = "NEUTRALN" in form
    neutralc = "NEUTRALC" in form

    if HAVE_PDB2PQR_OPAL == "1":
        have_opal = True
        # Opal-specific import statments
        from AppService_client import AppServiceLocator, launchJobRequest
        from AppService_types import ns0
        from ZSI.TC import String
    else:
        have_opal = False

    if have_opal:
        options = {"ff": ff}
        fffile = None
        namesfile = None
    else:
        options = {"extensions": {}}

    if "DEBUMP" in form:
        options["debump"] = 1
    else:
        options["debump"] = 0
    if "OPT" in form:
        options["opt"] = 1
    else:
        options["opt"] = 0
    if "PROPKA" in form:
        try:
            ph = float(form["PH"].value)
            if ph < 0.0 or ph > 14.0: raise ValueError
            options["ph"] = ph
        except ValueError:
            text = "The entered pH of %.2f is invalid!  " % form["PH"].value
            text += "Please choose a pH between 0.0 and 14.0."
            # print "Content-type: text/html\n"
            print(text)
            sys.exit(2)
    if "PDBID" in form:
        pdbfile = getPDBFile(form["PDBID"].value)
        pdbfilename = form["PDBID"].value
    elif "PDB" in form:
        pdbfile = StringIO(form["PDB"].value)
        pdbfilename = form["PDB"].filename
        pdbfilename = pdbfilename.split(r'[/\\]')[-1]
    if "INPUT" in form:
        input = 1
        options["apbs"] = 1
    if "USERFF" in form:
        if have_opal:
            ffname = form["USERFF"].filename
            ffname = ffname.split(r'[/\\]')[-1]
            if ffname[-4:] == ".DAT":
                ffname = ffname[:-4]
            fffile = StringIO(form["USERFF"].value)
            namesfile = StringIO(form["USERNAMES"].value)
            options["ff"] = ffname
            options["userff"] = fffile
            options["usernames"] = namesfile
        else:
            userff = StringIO(form["USERFF"].value)
            usernames = StringIO(form["USERNAMES"].value)
            options["ff"] = "user-defined"
            options["userff"] = userff
            options["usernames"] = usernames
    if "FFOUT" in form:
        if form["FFOUT"].value != "internal":
            options["ffout"] = form["FFOUT"].value
    if "CHAIN" in form:
        options["chain"] = 1
    if "WHITESPACE" in form:
        options["whitespace"] = 1
    if "TYPEMAP" in form:
        options["typemap"] = 1
    if "NEUTRALN" in form:
        options["neutraln"] = 1
    if "NEUTRALC" in form:
        options["neutralc"] = 1
    if "LIGAND" in form:
        if have_opal:
            ligandfilename = str(form["LIGAND"].filename)
            ligandfilename = ligandfilename.split(r'[/\\]')[-1]

        # for Windows-style newline compatibility
        templigandfilename = tempfile.mkstemp()[1]
        templigandfile = open(templigandfilename, 'w')
        templigandfile.write(form["LIGAND"].value)
        templigandfile.close()
        templigandfile = open(templigandfilename, 'rU')
        if have_opal:
            options["ligand"] = templigandfile.read()
        else:
            templigandstring = templigandfile.read()  # this variable is used again later to write this file to output
            options["ligand"] = StringIO(templigandstring)

        templigandfile.close()

    if not have_opal:
        pdbfilestring = pdbfile.read()
        pdblist, errlist = readPDB(StringIO(pdbfilestring))
        dummydef = Definition()
        dummyprot = Protein(pdblist, dummydef)
        if len(pdblist) == 0 and len(errlist) == 0:
            text = "Unable to find PDB file - Please make sure this is "
            text += "a valid PDB file ID!"
            # print "Content-type: text/html\n"
            print(text)
            sys.exit(2)
        elif dummyprot.numAtoms() > MAXATOMS and "opt" in options:
            text = "<HTML><HEAD>"
            text += "<TITLE>PDB2PQR Error</title>"
            text += "<link rel=\"stylesheet\" href=\"%s\" type=\"text/css\">" % STYLESHEET
            text += "</HEAD><BODY><H2>PDB2PQR Error</H2><P>"
            text += "Due to server limits, we are currently unable to optimize "
            text += "proteins of greater than MAXATOMS atoms on the server (PDB2PQR "
            text += "found %s atoms in the selected PDB file).  If you " % dummyprot.numAtoms()
            text += "want to forgo optimization please try the server again.<P>"
            text += "Otherwise you may use the standalone version of PDB2PQR that "
            text += "is available from the <a href=\"http://pdb2pqr.sourceforge.net\">"
            text += "PDB2PQR SourceForge project page</a>."
            text += "<script type=\"text/javascript\">"
            text += "var gaJsHost = ((\"https:\" == document.location.protocol) ? \"https://ssl.\" : \"http://www.\");"
            text += "document.write(unescape(\"%3Cscript src=\'\" + gaJsHost + \"google-analytics.com/ga.js\' type=\'text/javascript\'%3E%3C/script%3E\"));"
            text += "</script>"
            text += "<script type=\"text/javascript\">"
            text += "try {"
            text += "var pageTracker = _gat._getTracker(\"UA-11026338-3\");"
            for key in options:
                text += "pageTracker._trackPageview(\"/main_cgi/has_%s_%s.html\");" % (key, options[key])
            text += "pageTracker._trackPageview();"
            text += "} catch(err) {}</script>"
            text += "</BODY></HTML>"
            # print "Content-type: text/html\n"
            print(text)
            sys.exit(2)

    try:
        if have_opal:
            ligandFile = None
            ffFile = None
            namesFile = None
        # else:
        starttime = time.time()
        name = setID(starttime)

        os.makedirs('%s%s%s' % (INSTALLDIR, TMPDIR, name))
        apbsInputFile = open('%s%s%s/apbs_input' % (INSTALLDIR, TMPDIR, name), 'w')
        apbsInputFile.write(str(apbs_input))
        apbsInputFile.close()
        typemapInputFile = open('%s%s%s/typemap' % (INSTALLDIR, TMPDIR, name), 'w')
        typemapInputFile.write(str(typemap))
        typemapInputFile.close()

        if have_opal:
            myopts = ""
            for key in options:
                if key == "opt":
                    if options[key] == 0:
                        # user does not want optimization
                        key = "noopt"
                    else:
                        # pdb2pqr optimizes by default, don't bother with flag
                        continue
                elif key == "debump":
                    if options[key] == 0:
                        # user does not want debumping
                        key = "nodebump"
                    else:
                        # pdb2pqr debumps by default, so change this flag to --nodebump
                        continue
                elif key == "ph":
                    val = options[key]
                    key = "with-ph=%s" % val
                elif key == "ffout":
                    val = options[key]
                    key = "ffout=%s" % val
                elif key == "ligand":
                    val = ligandfilename
                    key = "ligand=%s" % val
                    ligandFile = ns0.InputFileType_Def('inputFile')
                    ligandFile._name = val
                    ligandFile._contents = options["ligand"]
                elif key == "apbs":
                    key = "apbs-input"
                elif key == "chain":
                    key = "chain"
                elif key == "whitespace":
                    key = "whitespace"
                elif key == "typemap":
                    key = "typemap"
                elif key == "ff":
                    val = options[key]
                    key = "ff=%s" % val
                    if fffile:
                        ffFile = ns0.InputFileType_Def('inputFile')
                        ffFile._name = val + ".DAT"
                        ffFileString = fffile.read()
                        ffFile._contents = ffFileString
                    if namesfile:
                        namesFile = ns0.InputFileType_Def('inputFile')
                        namesFile._name = val + ".names"
                        namesFileString = namesfile.read()
                        namesFile._contents = namesFileString
                if key not in ["userff", "usernames"]:
                    myopts += "--" + str(key) + " "
            myopts += str(pdbfilename) + " "
            if pdbfilename[-4:] == ".pdb":
                myopts += "%s.pqr" % str(pdbfilename[:-4])
            else:
                myopts += "%s.pqr" % str(pdbfilename)
            appLocator = AppServiceLocator()
            appServicePort = appLocator.getAppServicePort(PDB2PQR_OPAL_URL)
            # launch job
            req = launchJobRequest()
            req._argList = myopts
            inputFiles = []
            pdbOpalFile = ns0.InputFileType_Def('inputFile')
            pdbOpalFile._name = pdbfilename
            pdbOpalFile._contents = pdbfile.read()
            pdbfile.close()
            inputFiles.append(pdbOpalFile)
            if ligandFile:
                inputFiles.append(ligandFile)
            if ffFile:
                inputFiles.append(ffFile)
            if namesFile:
                inputFiles.append(namesFile)
            req._inputFile = inputFiles
            try:
                resp = appServicePort.launchJob(req)
            except Exception as e:
                printHeader("PDB2PQR Job Submission - Error")
                print("<BODY>\n<P>")
                print("There was an error with your job submission<br>")
                print("</P>")
                print("<script type=\"text/javascript\">")
                print(
                    "var gaJsHost = ((\"https:\" == document.location.protocol) ? \"https://ssl.\" : \"http://www.\");")
                print(
                    "document.write(unescape(\"%3Cscript src=\'\" + gaJsHost + \"google-analytics.com/ga.js\' type=\'text/javascript\'%3E%3C/script%3E\"));")
                print("</script>")
                print("<script type=\"text/javascript\">")
                print("try {")
                print("var pageTracker = _gat._getTracker(\"UA-11026338-3\");")
                for key in options:
                    print("pageTracker._trackPageview(\"/main_cgi/has_%s_%s.html\");" % (key, options[key]))
                print("pageTracker._trackPageview();")
                print("} catch(err) {}</script>")
                print("</BODY>")
                print("</HTML>")
                sys.exit(2)
            # printHeader("PDB2PQR Job Submission",have_opal,jobid=resp._jobID)
            pdb2pqrOpalJobIDFile = open('%s%s%s/pdb2pqr_opal_job_id' % (INSTALLDIR, TMPDIR, name), 'w')
            pdb2pqrOpalJobIDFile.write(resp._jobID)
            pdb2pqrOpalJobIDFile.close()
            print(redirector(name))
            if "userff" in options:
                options["userff"] = ffFileString
            if "usernames" in options:
                options["usernames"] = namesFileString
            # Recording CGI run information for PDB2PQR Opal
            pdb2pqrOpalLogFile = open('%s%s%s/pdb2pqr_opal_log' % (INSTALLDIR, TMPDIR, name), 'w')
            pdb2pqrOpalLogFile.write(str(options) + '\n' + str(ff) + '\n' + str(os.environ["REMOTE_ADDR"]))
            pdb2pqrOpalLogFile.close()

        else:
            # pqrpath = startServer(name)
            statusfile = open('%s%s%s/pdb2pqr_status' % (INSTALLDIR, TMPDIR, name), 'w')
            statusfile.write('running')
            statusfile.close()

            pid = os.fork()
            if pid:
                print(redirector(name))
                sys.exit()
            else:
                currentdir = os.getcwd()
                os.chdir("/")
                os.setsid()
                os.umask(0)
                os.chdir(currentdir)
                os.close(1)  # not sure if these
                os.close(2)  # two lines are necessary
                pqrpath = '%s%s%s/%s.pqr' % (INSTALLDIR, TMPDIR, name, name)
                options["outname"] = pqrpath
                options["verbose"] = ""
                orig_stdout = sys.stdout
                orig_stderr = sys.stderr
                sys.stdout = open('%s%s%s/pdb2pqr_stdout.txt' % (INSTALLDIR, TMPDIR, name), 'w')
                sys.stderr = open('%s%s%s/pdb2pqr_stderr.txt' % (INSTALLDIR, TMPDIR, name), 'w')
                header, lines, missedligands = runPDB2PQR(pdblist, ff, options)
                sys.stdout.close()
                sys.stderr.close()
                sys.stdout = orig_stdout
                sys.stderr = orig_stderr

                endtimefile = open('%s%s%s/pdb2pqr_end_time' % (INSTALLDIR, TMPDIR, name), 'w')
                endtimefile.write(str(time.time()))
                endtimefile.close()

                pqrfile = open(pqrpath, "w")
                pqrfile.write(header)
                for line in lines:  # type: object
                    # Adding whitespaces if --whitespace is in the options
                    if "whitespace" in options.keys() and options["whitespace"] == 1:
                        if line[0:4] == 'ATOM':
                            newline = line[0:16] + ' ' + line[16:38] + ' ' + line[38:46] + ' ' + line[46:]
                            pqrfile.write("%s\n" % newline.strip())
                        elif line[0:6] == 'HETATM':
                            newline = line[0:16] + ' ' + line[16:38] + ' ' + line[38:46] + ' ' + line[46:]
                            pqrfile.write("%s\n" % newline.strip())
                    else:
                        pqrfile.write("%s\n" % line.strip())
                pqrfile.close()

                if input:
                    from src import inputgen as Inp
                    from src import psize as Pz
                    method = "mg-auto"
                    size = Pz.Psize()
                    size.parseInput(pqrpath)
                    size.runPsize(pqrpath)
                    async = 0  # No async files here!
                    myinput = Inp.Input(pqrpath, size, method, async)
                    myinput.printInputFiles()
                    myinput.dumpPickle()

                endtime = time.time() - starttime
                # createResults(header, input, name, endtime, missedligands)
                logRun(options, endtime, len(lines), ff, os.environ["REMOTE_ADDR"])
                # printHeader("PDB2PQR Job Submission",have_opal,jobid=name)
                if "LIGAND" in form:
                    outputligandfile = open('%s%s%s/%s.mol2' % (INSTALLDIR, TMPDIR, name, name), 'w')
                    outputligandfile.write(templigandstring)
                    outputligandfile.close()
                outputpdbfile = open('%s%s%s/%s.pdb' % (INSTALLDIR, TMPDIR, name, name), 'w')
                outputpdbfile.write(pdbfilestring)
                outputpdbfile.close()

                statusfile = open('%s%s%s/pdb2pqr_status' % (INSTALLDIR, TMPDIR, name), 'w')
                statusfile.write('complete\n')
                filelist = glob.glob('%s%s%s/%s*' % (INSTALLDIR, TMPDIR, name, name))
                for filename in filelist:
                    statusfile.write(filename + '\n')
                statusfile.close()


    except SystemError.StandardError as details:
        print(details)
        createError(name, details)
Пример #8
0
def handleOpal(weboptions):
    '''
        Handle opal based run.
    '''
    # Opal-specific import statements
    from AppService_client import AppServiceLocator, launchJobRequest
    from AppService_types import ns0

    inputFiles = []
    
    if 'userff' in weboptions:
        ffFile = ns0.InputFileType_Def('inputFile')
        ffFile._name = weboptions.userfffilename
        ffFile._contents = weboptions.userffstring
        inputFiles.append(ffFile)
        
    if 'usernames' in weboptions:
        namesFile = ns0.InputFileType_Def('inputFile')
        namesFile._name = weboptions.usernamesfilename
        namesFile._contents = weboptions.usernamesstring
        inputFiles.append(namesFile)
        
    if 'ligand' in weboptions:
        ligandFile = ns0.InputFileType_Def('inputFile')
        ligandFile._name = weboptions.ligandfilename
        ligandFile._contents = weboptions.ligandfilestring
        inputFiles.append(ligandFile)
        
    pdbOpalFile = ns0.InputFileType_Def('inputFile')
    pdbOpalFile._name = weboptions.pdbfilename
    pdbOpalFile._contents = weboptions.pdbfilestring
    inputFiles.append(pdbOpalFile)
     
    # launch job   
    appLocator = AppServiceLocator()
    appServicePort = appLocator.getAppServicePort(PDB2PQR_OPAL_URL)
    
    req = launchJobRequest()
    req._argList = weboptions.getCommandLine()
    req._inputFile=inputFiles

    try:
        resp=appServicePort.launchJob(req)
    except Exception as e:
        printHeader("PDB2PQR Job Submission - Error")
        print("<BODY>\n<P>")
        print("There was an error with your job submission<br>")
        print("</P>")
        print("<script type=\"text/javascript\">")
        print("var gaJsHost = ((\"https:\" == document.location.protocol) ? \"https://ssl.\" : \"http://www.\");")
        print("document.write(unescape(\"%3Cscript src=\'\" + gaJsHost + \"google-analytics.com/ga.js\' type=\'text/javascript\'%3E%3C/script%3E\"));")
        print("</script>")
        print("<script type=\"text/javascript\">")
        print("try {")
        print("var pageTracker = _gat._getTracker(\"UA-11026338-3\");")
        for key in weboptions:
            print("pageTracker._trackPageview(\"/main_cgi/has_%s_%s.html\");" % (key, weboptions[key]))
        print("pageTracker._trackPageview();")
        print("} catch(err) {}</script>")
        print("</BODY>")
        print("</HTML>")
        sys.exit(2)
    
    try:
        starttime = time.time()
        name = setID(starttime)
        
        #Some job parameters logging.
        os.makedirs('%s%s%s' % (INSTALLDIR, TMPDIR, name))
        apbsInputFile = open('%s%s%s/apbs_input' % (INSTALLDIR, TMPDIR, name),'w')
        apbsInputFile.write(str(weboptions["apbs"]))
        apbsInputFile.close()
        
        typemapInputFile = open('%s%s%s/typemap' % (INSTALLDIR, TMPDIR, name),'w')
        typemapInputFile.write(str(weboptions["typemap"]))
        typemapInputFile.close()
        
        pdb2pqrOpalJobIDFile = open('%s%s%s/pdb2pqr_opal_job_id' % (INSTALLDIR, TMPDIR, name), 'w')
        pdb2pqrOpalJobIDFile.write(resp._jobID)
        pdb2pqrOpalJobIDFile.close()
        
        print(redirector(name, weboptions))
        
        # Recording CGI run information for PDB2PQR Opal
        pdb2pqrOpalLogFile = open('%s%s%s/pdb2pqr_log' % (INSTALLDIR, TMPDIR, name), 'w')
        pdb2pqrOpalLogFile.write(str(weboptions.getOptions())+'\n'+
                                 str(os.environ["REMOTE_ADDR"]))
        pdb2pqrOpalLogFile.close()

    except Exception as details:
        print(details)
        createError(name, details)
Пример #9
0
def handleOpal(weboptions):
    '''
        Handle opal based run.
    '''
    # Opal-specific import statements
    from AppService_client import AppServiceLocator, launchJobRequest
    from AppService_types import ns0

    inputFiles = []

    if 'userff' in weboptions:
        ffFile = ns0.InputFileType_Def('inputFile')
        ffFile._name = weboptions.userfffilename
        ffFile._contents = weboptions.userffstring
        inputFiles.append(ffFile)

    if 'usernames' in weboptions:
        namesFile = ns0.InputFileType_Def('inputFile')
        namesFile._name = weboptions.usernamesfilename
        namesFile._contents = weboptions.usernamesstring
        inputFiles.append(namesFile)

    if 'ligand' in weboptions:
        ligandFile = ns0.InputFileType_Def('inputFile')
        ligandFile._name = weboptions.ligandfilename
        ligandFile._contents = weboptions.ligandfilestring
        inputFiles.append(ligandFile)

    pdbOpalFile = ns0.InputFileType_Def('inputFile')
    pdbOpalFile._name = weboptions.pdbfilename
    pdbOpalFile._contents = weboptions.pdbfilestring
    inputFiles.append(pdbOpalFile)

    # launch job
    appLocator = AppServiceLocator()
    appServicePort = appLocator.getAppServicePort(PDB2PQR_OPAL_URL)

    req = launchJobRequest()
    req._argList = weboptions.getCommandLine()
    req._inputFile = inputFiles

    try:
        resp = appServicePort.launchJob(req)
    except Exception as e:
        printHeader("PDB2PQR Job Submission - Error")
        print("<BODY>\n<P>")
        print("There was an error with your job submission<br>")
        print("</P>")
        print("<script type=\"text/javascript\">")
        print(
            "var gaJsHost = ((\"https:\" == document.location.protocol) ? \"https://ssl.\" : \"http://www.\");"
        )
        print(
            "document.write(unescape(\"%3Cscript src=\'\" + gaJsHost + \"google-analytics.com/ga.js\' type=\'text/javascript\'%3E%3C/script%3E\"));"
        )
        print("</script>")
        print("<script type=\"text/javascript\">")
        print("try {")
        print("var pageTracker = _gat._getTracker(\"UA-11026338-3\");")
        for key in weboptions:
            print("pageTracker._trackPageview(\"/main_cgi/has_%s_%s.html\");" %
                  (key, weboptions[key]))
        print("pageTracker._trackPageview();")
        print("} catch(err) {}</script>")
        print("</BODY>")
        print("</HTML>")
        sys.exit(2)

    try:
        starttime = time.time()
        name = setID(starttime)

        #Some job parameters logging.
        os.makedirs('%s%s%s' % (INSTALLDIR, TMPDIR, name))
        apbsInputFile = open('%s%s%s/apbs_input' % (INSTALLDIR, TMPDIR, name),
                             'w')
        apbsInputFile.write(str(weboptions["apbs"]))
        apbsInputFile.close()

        typemapInputFile = open('%s%s%s/typemap' % (INSTALLDIR, TMPDIR, name),
                                'w')
        typemapInputFile.write(str(weboptions["typemap"]))
        typemapInputFile.close()

        pdb2pqrOpalJobIDFile = open(
            '%s%s%s/pdb2pqr_opal_job_id' % (INSTALLDIR, TMPDIR, name), 'w')
        pdb2pqrOpalJobIDFile.write(resp._jobID)
        pdb2pqrOpalJobIDFile.close()

        print(redirector(name, weboptions))

        # Recording CGI run information for PDB2PQR Opal
        pdb2pqrOpalLogFile = open(
            '%s%s%s/pdb2pqr_log' % (INSTALLDIR, TMPDIR, name), 'w')
        pdb2pqrOpalLogFile.write(
            str(weboptions.getOptions()) + '\n' +
            str(os.environ["REMOTE_ADDR"]))
        pdb2pqrOpalLogFile.close()

    except Exception as details:
        print(details)
        createError(name, details)
Пример #10
0
def mainCGI():
    """
        Opal driver for running PDB2PQR from a web page
    """
    serviceURL = OPALURL
    
    cgitb.enable()
    form = cgi.FieldStorage()
    
    options = {}
 
    ff = form["FF"].value 
    options["ff"] = ff
    fffile = None
    input = 0
  
    if form.has_key("DEBUMP"): options["debump"] = 1
    else: options["debump"] = 0
    if form.has_key("OPT"): options["opt"] = 1
    else: options["opt"] = 0
    if form.has_key("PROPKA"):
        try:
            ph = float(form["PH"].value)
            if ph < 0.0 or ph > 14.0: raise ValueError
            options["ph"] = ph
        except ValueError:
             text = "The entered pH of %.2f is invalid!  " % form["PH"].value
             text += "Please choose a pH between 0.0 and 14.0."
#             print "Content-type: text/html\n"
             print text
             sys.exit(2)
    if form.has_key("PDBID"):
        filename = form["PDBID"].value
        infile = getPDBFile(form["PDBID"].value)
    elif form.has_key("PDB"):
        filename = form["PDB"].filename
        filename=re.split(r'[/\\]',filename)[-1]
        infile = StringIO(form["PDB"].value)
    if form.has_key("INPUT"):
        input = 1
        options["apbs"] = 1
    if form.has_key("USERFF"):
#        userff = StringIO(form["USERFF"].value)
#        ff = "user-defined"
#        options["userff"] = userff
        ffname = form["USERFF"].filename
        ffname = re.split(r'[/\\]',ffname)[-1]
        fffile = StringIO(form["USERFF"].value)
        options["ff"] = ffname
    if form.has_key("FFOUT"):
        if form["FFOUT"].value != "internal":
            options["ffout"] = form["FFOUT"].value
    if form.has_key("CHAIN"):
        options["chain"] = 1
    if form.has_key("WHITESPACE"):
        options["whitespace"] = 1
    if form.has_key("LIGAND"):
        ligandfilename=str(form["LIGAND"].filename)
        ligandfilename=re.split(r'[/\\]',ligandfilename)[-1]
        options["ligand"] = StringIO(form["LIGAND"].value)
        
    try:
#        starttime = time.time()
#        name = setID(starttime)
        name = filename
        ligandFile=None
        ffFile=None
        # begin SOAP changes
        # need to switch options from a dictionary to something resembling a command line query
        # such as --chain
        myopts=""
        for key in options:
            if key=="opt":
                if options[key]==0:
                    # user does not want optimization
                    key="noopt"
                else:
                    # pdb2pqr optimizes by default, don't bother with flag
                    continue
            elif key=="debump":
                if options[key]==0:
                    # user does not want debumping
                    key="nodebump"
                else:
                    # pdb2pqr debumps by default, so change this flag to --nodebump
                    continue
            elif key=="ph":
                val=options[key]
                key="with-ph=%s" % val
            elif key=="ffout":
                val=options[key]
                key="ffout=%s" % val
            elif key=="ligand":
                val=ligandfilename
                key="ligand=%s" % val
                ligandFile = ns0.InputFileType_Def('inputFile')
                ligandFile._name = val
                ligandFileTemp = open(options["ligand"], "r")
                ligandFileString = ligandFileTemp.read()
                ligandFileTemp.close()
                ligandFile._contents = ligandFileString
            elif key=="apbs":
                key="apbs-input"
            elif key=="chain":
                key="chain"
            elif key=="whitespace":
                key="whitespace"
            elif key=="ff":
                val=options[key]
                key="ff=%s" % val
                if fffile:
                  ffFile = ns0.InputFileType_Def('inputFile')
                  ffFile._name = val
                  ffFileTemp = open(fffile, "r")
                  ffFileString = ffFileTemp.read()
                  ffFileTemp.close()
                  ffFile._contents = ffFileString
            myopts+="--"+str(key)+" "
        myopts+=str(filename)+" "
        myopts+="%s.pqr" % str(name)
        appLocator = AppServiceLocator()
        appServicePort = appLocator.getAppServicePort(serviceURL)
        # launch job
        req = launchJobRequest()
        req._argList = myopts
        inputFiles = []
        pdbFile = ns0.InputFileType_Def('inputFile')
        pdbFile._name = filename
        pdbFile._contents = infile.read()
        infile.close()
        inputFiles.append(pdbFile)
        if ligandFile:
          inputFiles.append(ligandFile)
        if ffFile:
          inputFiles.append(ffFile)
        req._inputFile=inputFiles
        try:
          resp=appServicePort.launchJob(req)
        except Exception, e:
          printheader("PDB2PQR Job Submission - Error")
          print "<BODY>\n<P>"
          print "There was an error with your job submission<br>"
          print "</P>\n</BODY>"
          print "</HTML>"
          sys.exit(2)
        printheader("PDB2PQR Job Submission",resp._jobID)
Пример #11
0
def handleOpal(weboptions):
    '''
        Handle opal based run.
    '''
    # Opal-specific import statements
    from AppService_client import AppServiceLocator, getAppMetadataRequest, launchJobRequest, launchJobBlockingRequest, getOutputAsBase64ByNameRequest
    from AppService_types import ns0

    inputFiles = []
    
    if 'userff' in weboptions:
        ffFile = ns0.InputFileType_Def('inputFile')
        ffFile._name = weboptions.userfffilename
        ffFile._contents = weboptions.userffstring
        inputFiles.append(ffFile)
        
    if 'usernames' in weboptions:
        namesFile = ns0.InputFileType_Def('inputFile')
        namesFile._name = weboptions.usernamesfilename
        namesFile._contents = weboptions.usernamesstring
        inputFiles.append(namesFile)
        
    if 'ligand' in weboptions:
        ligandFile = ns0.InputFileType_Def('inputFile')
        ligandFile._name = weboptions.ligandfilename
        ligandFile._contents = weboptions.ligandfilestring
        inputFiles.append(ligandFile)
        
    pdbOpalFile = ns0.InputFileType_Def('inputFile')
    pdbOpalFile._name = weboptions.pdbfilename
    pdbOpalFile._contents = weboptions.pdbfilestring
    inputFiles.append(pdbOpalFile)
     
    # launch job   
    appLocator = AppServiceLocator()
    appServicePort = appLocator.getAppServicePort(PDB2PQR_OPAL_URL)
    
    req = launchJobRequest()
    req._argList = weboptions.getCommandLine()
    req._inputFile=inputFiles

    try:
        resp=appServicePort.launchJob(req)
    except Exception, e:
        printHeader("PDB2PQR Job Submission - Error")
        print "<BODY>\n<P>"
        print "There was an error with your job submission<br>"
        print "</P>"
        print "<script type=\"text/javascript\">"
        print "var gaJsHost = ((\"https:\" == document.location.protocol) ? \"https://ssl.\" : \"http://www.\");"
        print "document.write(unescape(\"%3Cscript src=\'\" + gaJsHost + \"google-analytics.com/ga.js\' type=\'text/javascript\'%3E%3C/script%3E\"));"
        print "</script>"
        print "<script type=\"text/javascript\">"
        print "try {"
        print "var pageTracker = _gat._getTracker(\"UA-11026338-3\");"
        for key in weboptions:
            print "pageTracker._trackPageview(\"/main_cgi/has_%s_%s.html\");" % (key, weboptions[key])
        print "pageTracker._trackPageview();"
        print "} catch(err) {}</script>"
        print "</BODY>"
        print "</HTML>"
        sys.exit(2)
Пример #12
0
def mainCGI():
    """
        Main driver for running PDB2PQR from a web page
    """
    print "Content-type: text/html\n"
    import cgi
    import cgitb

    cgitb.enable()
    form = cgi.FieldStorage()
    ff = form["FF"].value
    input = 0

    apbs_input = form.has_key("INPUT")
    typemap = form.has_key("TYPEMAP")
    neutraln = form.has_key("NEUTRALN")
    neutralc = form.has_key("NEUTRALC")

    if HAVE_PDB2PQR_OPAL == "1":
        have_opal = True
        # Opal-specific import statments
        from AppService_client import AppServiceLocator, getAppMetadataRequest, launchJobRequest, launchJobBlockingRequest, getOutputAsBase64ByNameRequest
        from AppService_types import ns0
        from ZSI.TC import String
    else:
        have_opal = False

    if have_opal:
        options = {}
        options["ff"] = ff
        fffile = None
        namesfile = None
    else:
        options = {"extensions": {}}

    if form.has_key("DEBUMP"):
        options["debump"] = 1
    else:
        options["debump"] = 0
    if form.has_key("OPT"):
        options["opt"] = 1
    else:
        options["opt"] = 0
    if form.has_key("PROPKA"):
        try:
            ph = float(form["PH"].value)
            if ph < 0.0 or ph > 14.0: raise ValueError
            options["ph"] = ph
        except ValueError:
            text = "The entered pH of %.2f is invalid!  " % form["PH"].value
            text += "Please choose a pH between 0.0 and 14.0."
            #print "Content-type: text/html\n"
            print text
            sys.exit(2)
    if form.has_key("PDBID"):
        pdbfile = getPDBFile(form["PDBID"].value)
        pdbfilename = form["PDBID"].value
    elif form.has_key("PDB"):
        pdbfile = StringIO(form["PDB"].value)
        pdbfilename = form["PDB"].filename
        pdbfilename = re.split(r'[/\\]', pdbfilename)[-1]
    if form.has_key("INPUT"):
        input = 1
        options["apbs"] = 1
    if form.has_key("USERFF"):
        if have_opal:
            ffname = form["USERFF"].filename
            ffname = re.split(r'[/\\]', ffname)[-1]
            if ffname[-4:] == ".DAT":
                ffname = ffname[:-4]
            fffile = StringIO(form["USERFF"].value)
            namesfile = StringIO(form["USERNAMES"].value)
            options["ff"] = ffname
            options["userff"] = fffile
            options["usernames"] = namesfile
        else:
            userff = StringIO(form["USERFF"].value)
            usernames = StringIO(form["USERNAMES"].value)
            options["ff"] = "user-defined"
            options["userff"] = userff
            options["usernames"] = usernames
    if form.has_key("FFOUT"):
        if form["FFOUT"].value != "internal":
            options["ffout"] = form["FFOUT"].value
    if form.has_key("CHAIN"):
        options["chain"] = 1
    if form.has_key("WHITESPACE"):
        options["whitespace"] = 1
    if form.has_key("TYPEMAP"):
        options["typemap"] = 1
    if form.has_key("NEUTRALN"):
        options["neutraln"] = 1
    if form.has_key("NEUTRALC"):
        options["neutralc"] = 1
    if form.has_key("LIGAND"):
        if have_opal:
            ligandfilename = str(form["LIGAND"].filename)
            ligandfilename = re.split(r'[/\\]', ligandfilename)[-1]

        # for Windows-style newline compatibility
        templigandfilename = tempfile.mkstemp()[1]
        templigandfile = open(templigandfilename, 'w')
        templigandfile.write(form["LIGAND"].value)
        templigandfile.close()
        templigandfile = open(templigandfilename, 'rU')
        if have_opal:
            options["ligand"] = templigandfile.read()
        else:
            templigandstring = templigandfile.read(
            )  # this variable is used again later to write this file to output
            options["ligand"] = StringIO(templigandstring)

        templigandfile.close()

    if not have_opal:
        pdbfilestring = pdbfile.read()
        pdblist, errlist = readPDB(StringIO(pdbfilestring))
        dummydef = Definition()
        dummyprot = Protein(pdblist, dummydef)
        if len(pdblist) == 0 and len(errlist) == 0:
            text = "Unable to find PDB file - Please make sure this is "
            text += "a valid PDB file ID!"
            #print "Content-type: text/html\n"
            print text
            sys.exit(2)
        elif dummyprot.numAtoms() > MAXATOMS and "opt" in options:
            text = "<HTML><HEAD>"
            text += "<TITLE>PDB2PQR Error</title>"
            text += "<link rel=\"stylesheet\" href=\"%s\" type=\"text/css\">" % STYLESHEET
            text += "</HEAD><BODY><H2>PDB2PQR Error</H2><P>"
            text += "Due to server limits, we are currently unable to optimize "
            text += "proteins of greater than MAXATOMS atoms on the server (PDB2PQR "
            text += "found %s atoms in the selected PDB file).  If you " % dummyprot.numAtoms(
            )
            text += "want to forgo optimization please try the server again.<P>"
            text += "Otherwise you may use the standalone version of PDB2PQR that "
            text += "is available from the <a href=\"http://pdb2pqr.sourceforge.net\">"
            text += "PDB2PQR SourceForge project page</a>."
            text += "<script type=\"text/javascript\">"
            text += "var gaJsHost = ((\"https:\" == document.location.protocol) ? \"https://ssl.\" : \"http://www.\");"
            text += "document.write(unescape(\"%3Cscript src=\'\" + gaJsHost + \"google-analytics.com/ga.js\' type=\'text/javascript\'%3E%3C/script%3E\"));"
            text += "</script>"
            text += "<script type=\"text/javascript\">"
            text += "try {"
            text += "var pageTracker = _gat._getTracker(\"UA-11026338-3\");"
            for key in options:
                text += "pageTracker._trackPageview(\"/main_cgi/has_%s_%s.html\");" % (
                    key, options[key])
            text += "pageTracker._trackPageview();"
            text += "} catch(err) {}</script>"
            text += "</BODY></HTML>"
            #print "Content-type: text/html\n"
            print text
            sys.exit(2)

    try:
        if have_opal:
            ligandFile = None
            ffFile = None
            namesFile = None
        #else:
        starttime = time.time()
        name = setID(starttime)

        os.makedirs('%s%s%s' % (INSTALLDIR, TMPDIR, name))
        apbsInputFile = open('%s%s%s/apbs_input' % (INSTALLDIR, TMPDIR, name),
                             'w')
        apbsInputFile.write(str(apbs_input))
        apbsInputFile.close()
        typemapInputFile = open('%s%s%s/typemap' % (INSTALLDIR, TMPDIR, name),
                                'w')
        typemapInputFile.write(str(typemap))
        typemapInputFile.close()

        if have_opal:
            myopts = ""
            for key in options:
                if key == "opt":
                    if options[key] == 0:
                        # user does not want optimization
                        key = "noopt"
                    else:
                        # pdb2pqr optimizes by default, don't bother with flag
                        continue
                elif key == "debump":
                    if options[key] == 0:
                        # user does not want debumping
                        key = "nodebump"
                    else:
                        # pdb2pqr debumps by default, so change this flag to --nodebump
                        continue
                elif key == "ph":
                    val = options[key]
                    key = "with-ph=%s" % val
                elif key == "ffout":
                    val = options[key]
                    key = "ffout=%s" % val
                elif key == "ligand":
                    val = ligandfilename
                    key = "ligand=%s" % val
                    ligandFile = ns0.InputFileType_Def('inputFile')
                    ligandFile._name = val
                    ligandFile._contents = options["ligand"]
                elif key == "apbs":
                    key = "apbs-input"
                elif key == "chain":
                    key = "chain"
                elif key == "whitespace":
                    key = "whitespace"
                elif key == "typemap":
                    key = "typemap"
                elif key == "ff":
                    val = options[key]
                    key = "ff=%s" % val
                    if fffile:
                        ffFile = ns0.InputFileType_Def('inputFile')
                        ffFile._name = val + ".DAT"
                        ffFileString = fffile.read()
                        ffFile._contents = ffFileString
                    if namesfile:
                        namesFile = ns0.InputFileType_Def('inputFile')
                        namesFile._name = val + ".names"
                        namesFileString = namesfile.read()
                        namesFile._contents = namesFileString
                if key not in ["userff", "usernames"]:
                    myopts += "--" + str(key) + " "
            myopts += str(pdbfilename) + " "
            if pdbfilename[-4:] == ".pdb":
                myopts += "%s.pqr" % str(pdbfilename[:-4])
            else:
                myopts += "%s.pqr" % str(pdbfilename)
            appLocator = AppServiceLocator()
            appServicePort = appLocator.getAppServicePort(PDB2PQR_OPAL_URL)
            # launch job
            req = launchJobRequest()
            req._argList = myopts
            inputFiles = []
            pdbOpalFile = ns0.InputFileType_Def('inputFile')
            pdbOpalFile._name = pdbfilename
            pdbOpalFile._contents = pdbfile.read()
            pdbfile.close()
            inputFiles.append(pdbOpalFile)
            if ligandFile:
                inputFiles.append(ligandFile)
            if ffFile:
                inputFiles.append(ffFile)
            if namesFile:
                inputFiles.append(namesFile)
            req._inputFile = inputFiles
            try:
                resp = appServicePort.launchJob(req)
            except Exception, e:
                printHeader("PDB2PQR Job Submission - Error")
                print "<BODY>\n<P>"
                print "There was an error with your job submission<br>"
                print "</P>"
                print "<script type=\"text/javascript\">"
                print "var gaJsHost = ((\"https:\" == document.location.protocol) ? \"https://ssl.\" : \"http://www.\");"
                print "document.write(unescape(\"%3Cscript src=\'\" + gaJsHost + \"google-analytics.com/ga.js\' type=\'text/javascript\'%3E%3C/script%3E\"));"
                print "</script>"
                print "<script type=\"text/javascript\">"
                print "try {"
                print "var pageTracker = _gat._getTracker(\"UA-11026338-3\");"
                for key in options:
                    print "pageTracker._trackPageview(\"/main_cgi/has_%s_%s.html\");" % (
                        key, options[key])
                print "pageTracker._trackPageview();"
                print "} catch(err) {}</script>"
                print "</BODY>"
                print "</HTML>"
                sys.exit(2)
            #printHeader("PDB2PQR Job Submission",have_opal,jobid=resp._jobID)
            pdb2pqrOpalJobIDFile = open(
                '%s%s%s/pdb2pqr_opal_job_id' % (INSTALLDIR, TMPDIR, name), 'w')
            pdb2pqrOpalJobIDFile.write(resp._jobID)
            pdb2pqrOpalJobIDFile.close()
            print redirector(name)
            if options.has_key("userff"):
                options["userff"] = ffFileString
            if options.has_key("usernames"):
                options["usernames"] = namesFileString
            # Recording CGI run information for PDB2PQR Opal
            pdb2pqrOpalLogFile = open(
                '%s%s%s/pdb2pqr_opal_log' % (INSTALLDIR, TMPDIR, name), 'w')
            pdb2pqrOpalLogFile.write(
                str(options) + '\n' + str(ff) + '\n' +
                str(os.environ["REMOTE_ADDR"]))
            pdb2pqrOpalLogFile.close()

        else:
Пример #13
0
def execApbs(vars=None, argv=None):
	""" Executes APBS and regulates checking of job status and retrieval of data if job is successfully completed. """
	if argv is None:
		# i.e. if it is a local run
		argv = sys.argv
		webRun = False
	else:
		webRun = True
		custom_service_url = None
		if vars != None:
			if vars.has_key('service_url'):
				custom_service_url = vars['service_url']
		vars = initRemoteVars(argv)
		if custom_service_url != None:
			vars['service_url'] = custom_service_url
	global service_url	
	#*argument parser
	# command-line arguments
	vars['inFile'] = argv[-1]
	
	# parses input file
	if(vars['inFile'].find("/")==-1):
		directory=""
	else:
		directory = os.path.dirname(vars['inFile'])+'/'
		vars['inFile'] = os.path.basename(vars['inFile'])
		
	nprocs = 1
	if not vars.has_key('service_url'):
		# find out if it's sequential or parallel
		tempFile = open(directory+vars['inFile'], 'r')
		version_check_flag = True
		for line in tempFile:
			# remove whitespace
			line=line.strip()
			if(line[:5]=='pdime'):
				dimension_array = line.split()
				nprocs = int(dimension_array[1])*int(dimension_array[2])*int(dimension_array[3])
				global parallel_service_url
				vars['service_url'] = parallel_service_url
				version_check_flag = False
			if(line[:5]=='async'):
				vars['service_url'] = service_url
				version_check_flag = True
				break
		if version_check_flag:
			vars['service_url'] = service_url
			
		tempFile.close()
	else:
		version_check_flag = True     # Enable version checking for custom defined Opal service as well 
		service_url = vars['service_url']
	# Retrieve a reference to the AppServicePort
	#*this is also from the path to the service
	appServicePort = AppServiceLocator().getAppServicePort(vars['service_url'])
	
	# Set up remote job launch
	req = launchJobRequest()
	# Checks version compatibility (but currently only works for sequential calculations)
	if version_check_flag:
		opal_version = AppServicePortTypeSoapBindingSOAP(vars['service_url']).getAppMetadata(getAppMetadataRequest())._usage.split()[-1]
		if opal_version != local_version:
			stderr.write("WARNING! WARNING! WARNING! WARNING! WARNING! WARNING! WARNING!\n")
			stderr.write("It appears that the remote server version of APBS (%s) does not match\nthe local version (%s)!\n" % (opal_version,local_version))
			stderr.write("Proceed at your own risk!!\n")
			stderr.write("WARNING! WARNING! WARNING! WARNING! WARNING! WARNING! WARNING!\n")
			if webRun:
				return False
	
	if(vars.has_key('argList')):
		vars['argList'] = vars['argList'] + " " + vars['inFile']
	else:
		vars['argList']=vars['inFile']
		
	req._argList = vars['argList']
	req._numProcs = nprocs
	# append all input files in this manner - in this case we have two of them
	
	inputFiles = []
	#*this is where apbs.in is read in
	inputFiles.append(ns0.InputFileType_Def('inputFile'))
	#*this must be the same as req._argList is defined to be
	inputFiles[-1]._name = vars['inFile']
	tempFile = open(directory+vars['inFile'], 'r')
	inputFiles[-1]._contents = tempFile.read()
	tempFile.close()
    
	# this is where the rest of the files to read in are determined
	start = False
	tempFile = open(directory+vars['inFile'], 'r')
	for line in tempFile:
		# remove whitespace
		line=line.strip()
		if(line=="end"):
			break
		if(start and line.find("#")!=0):
			# eliminates lines with just comments
			# remove comment
			if(line.find("#")!=-1):
				line = line[:line.find("#")]
			# re-remove whitespace (left after comment removal)
			line=line.strip()
			# remove everything except file name
			count = -1
			while line[count]!=' ':
				count = count-1
			fileName=line[count+1:]
			inputFiles.append(ns0.InputFileType_Def('inputFile'))
			inputFiles[-1]._name=fileName
			tempFile2 = open(directory+fileName, "r")
			inputFiles[-1]._contents = tempFile2.read()
			tempFile2.close()
		if(line=="read"):
			start = True
	
	tempFile.close()
	
	# req's inputFile variable is the array of input files created in the lines directly above
	req._inputFile = inputFiles
	
	if vars['typeOfRun']=='remote':
		appServicePort.launchJob(req)
		return [appServicePort, appServicePort.launchJob(req)]
	
	# Launch job, and retrieve job ID
	print "Launching remote APBS job"
	try:
		resp = appServicePort.launchJob(req)
	except ZSI.FaultException, errstr:
		stderr.write("Error! Failed to execute Opal job. Please send the entire output to the APBS development team.\n")
		stderr.write("%s\n" % errstr.fault.AsSoap())
		sys.exit(13)
Пример #14
0
)
from AppService_types import ns0
from os import mkdir
from time import sleep
from ZSI.TC import String

# Set the location of our service
# A list of NBCR services can be found at http://ws.nbcr.net/opal2/dashboard?command=serviceList
serviceURL = "http://ws.nbcr.net/opal2/services/MEME_4.4.0"

# Instantiate a new service object to interact with.  Pass it the service location
appLocator = AppServiceLocator()
appServicePort = appLocator.getAppServicePort(serviceURL)

# Instantiate a new non-blocking job request
req = launchJobRequest()

# Set the command-line arguments for the job.
# Use DNA alphabet, and find 3 motifs.
req._argList = "meme crp0.fasta -dna -mod zoops -nmotifs 3"

# Get contents of local file to be used as input
fastaFile = open("./crp0.fasta", "r")
fastaFileContents = fastaFile.read()
fastaFile.close()

# Set name and content of remote input file.
# Only one input file is used, the FASTA file.
inputFiles = []
inputFile = ns0.InputFileType_Def("inputFile")
inputFile._name = "crp0.fasta"
Пример #15
0
        def ws_compute(self):
            if self._port_list[0][3]['url'] != None:
                url = self._port_list[0][3]['url']
                adv = self._port_list[0][3]['adv']
            else:
                url = ""
                print "ERROR: There are no input arguments provided for this web service"

            cmdline = ""
            numProcs = None
            tagged = []
            untagged = []
            flags = []
            files = []

            for i in self._port_list:
                pn = i[0]
                meta = i[3]

                if ((self.hasInputFromPort(pn) and self.getInputFromPort(pn) != "") or meta['default'] != None) and adv == True:
#                    print "META"
#                    print meta

                    if meta['type'] == 'FLAG':
                        if self.hasInputFromPort(pn):
                            if self.getInputFromPort(pn) == True:
                                flags.append(meta['arg'])
                        elif meta['default'] == 'True':
                            flags.append(meta['arg'])
                    elif meta['type'] == 'TAGGED':
                        if self.hasInputFromPort(pn):
                            val = self.getInputFromPort(pn)
                        elif meta['default'] != None:
                            val = meta['default']

                        if meta['file'] == True:
                            file_an = core.modules.basic_modules.File.translate_to_string(val)
                            file_bn = os.path.basename(file_an)
                            tagged.append(meta['arg'] + file_bn)
                            files.append(file_an)
                        else:
                            tagged.append(meta['arg'] + val)
                    elif meta['type'] == 'UNTAGGED':
                        if self.hasInputFromPort(pn):
                            val = self.getInputFromPort(pn)
                        elif meta['default'] != None:
                            val = meta['default']

                        if meta['file'] == True:
                            file_an = core.modules.basic_modules.File.translate_to_string(val)
                            file_bn = os.path.basename(file_an)
                            untagged.append(file_bn)
                            files.append(file_an)
                        else:
                            untagged.append(val)
                            
                    cmdline = ""

                    for i in flags:
                        cmdline += i + " "
                    for i in tagged:
                        cmdline += i + " "
                    for i in untagged:
                        cmdline += i + " "

            inputFiles = []

            for i in files:
                inputFile = ns0.InputFileType_Def('inputFile')
                inputFile._name = os.path.basename(i)                     
                inputFile._attachment = open(i, "r")
                inputFiles.append(inputFile)

            if cmdline == "":
                if self.hasInputFromPort('commandLine'):
                    cmdline = self.getInputFromPort('commandLine')
                if self.hasInputFromPort('numProcs'):
                    numProcs = self.getInputFromPort('numProcs')
                if self.hasInputFromPort("inFiles"):
                    inFilesPath = self.getInputFromPort("inFiles")
                    if inFilesPath != None:
                        for i in inFilesPath:
                            inputFile = ns0.InputFileType_Def('inputFile')
                            inputFile._name = os.path.basename(i)                     
                            inputFile._attachment = open(i, "r")
                            inputFiles.append(inputFile)
            
            print os.path.basename(url) + " from " + os.path.dirname(url) + " is going to run with arguments:\n     " + cmdline 

            appLocator = AppServiceLocator()
            appServicePort = appLocator.getAppServicePort(url)
            req = launchJobRequest()
            req._argList = cmdline
            req._inputFile = inputFiles
            if numProcs != None:
                req._numProcs = numProcs
            resp = appServicePort.launchJob(req)
            self.jobID = resp._jobID
            print "Job outputs URL: " + resp._status._baseURL # urlparse.urljoin(url, '/' + self.jobID)
            status = resp._status._code

            while (status != 4 and status != 8):
                status = appServicePort.queryStatus(queryStatusRequest(self.jobID))._code
                time.sleep(5)
             
            if (status == 8):
                resp = appServicePort.getOutputs(getOutputsRequest(self.jobID))
                outurls = [str(resp._stdOut), str(resp._stdErr)]
                if (resp._outputFile != None):
                    for i in resp._outputFile:
                        outurls.append(str(i._url))
                    print "Opal job completed successfully"
            else:
                print "ERROR: Opal job failed"
                resp = appServicePort.getOutputs(getOutputsRequest(self.jobID))
                outurls = [str(resp._stdOut), str(resp._stdErr)]

            self.setResult("outurls", tuple(outurls))
Пример #16
0
     launchJobBlockingRequest, getOutputAsBase64ByNameRequest
from AppService_types import ns0
from os import mkdir
from time import sleep
from ZSI.TC import String

# Set the location of our service
# A list of NBCR services can be found at http://ws.nbcr.net/opal2/dashboard?command=serviceList
serviceURL = "http://ws.nbcr.net/opal2/services/MEME_4.4.0"

# Instantiate a new service object to interact with.  Pass it the service location
appLocator = AppServiceLocator()
appServicePort = appLocator.getAppServicePort(serviceURL)
    
# Instantiate a new non-blocking job request
req = launchJobRequest()

# Set the command-line arguments for the job.
# Use DNA alphabet, and find 3 motifs.
req._argList = "meme crp0.fasta -dna -mod zoops -nmotifs 3"

# Get contents of local file to be used as input
fastaFile = open("./crp0.fasta", "r")
fastaFileContents = fastaFile.read()
fastaFile.close()

# Set name and content of remote input file.
# Only one input file is used, the FASTA file.
inputFiles = []
inputFile = ns0.InputFileType_Def('inputFile')
inputFile._name = 'crp0.fasta'
Пример #17
0
def execApbs(vars=None, argv=None):
    """ Executes APBS and regulates checking of job status and retrieval of data if job is successfully completed. """
    if argv is None:
        # i.e. if it is a local run
        argv = sys.argv
        webRun = False
    else:
        webRun = True
        custom_service_url = None
        if vars != None:
            if vars.has_key('service_url'):
                custom_service_url = vars['service_url']
        vars = initRemoteVars(argv)
        if custom_service_url != None:
            vars['service_url'] = custom_service_url
    global service_url
    #*argument parser
    # command-line arguments
    vars['inFile'] = argv[-1]

    # parses input file
    if (vars['inFile'].find("/") == -1):
        directory = ""
    else:
        directory = os.path.dirname(vars['inFile']) + '/'
        vars['inFile'] = os.path.basename(vars['inFile'])

    nprocs = 1
    if not vars.has_key('service_url'):
        # find out if it's sequential or parallel
        tempFile = open(directory + vars['inFile'], 'r')
        version_check_flag = True
        for line in tempFile:
            # remove whitespace
            line = line.strip()
            if (line[:5] == 'pdime'):
                dimension_array = line.split()
                nprocs = int(dimension_array[1]) * int(
                    dimension_array[2]) * int(dimension_array[3])
                global parallel_service_url
                vars['service_url'] = parallel_service_url
                version_check_flag = False
            if (line[:5] == 'async'):
                vars['service_url'] = service_url
                version_check_flag = True
                break
        if version_check_flag:
            vars['service_url'] = service_url

        tempFile.close()
    else:
        version_check_flag = True  # Enable version checking for custom defined Opal service as well
        service_url = vars['service_url']
    # Retrieve a reference to the AppServicePort
    #*this is also from the path to the service
    appServicePort = AppServiceLocator().getAppServicePort(vars['service_url'])

    # Set up remote job launch
    req = launchJobRequest()
    # Checks version compatibility (but currently only works for sequential calculations)
    if version_check_flag:
        opal_version = AppServicePortTypeSoapBindingSOAP(
            vars['service_url']).getAppMetadata(
                getAppMetadataRequest())._usage.split()[-1]
        if opal_version != local_version:
            stderr.write(
                "WARNING! WARNING! WARNING! WARNING! WARNING! WARNING! WARNING!\n"
            )
            stderr.write(
                "It appears that the remote server version of APBS (%s) does not match\nthe local version (%s)!\n"
                % (opal_version, local_version))
            stderr.write("Proceed at your own risk!!\n")
            stderr.write(
                "WARNING! WARNING! WARNING! WARNING! WARNING! WARNING! WARNING!\n"
            )
            if webRun:
                return False

    if (vars.has_key('argList')):
        vars['argList'] = vars['argList'] + " " + vars['inFile']
    else:
        vars['argList'] = vars['inFile']

    req._argList = vars['argList']
    req._numProcs = nprocs
    # append all input files in this manner - in this case we have two of them

    inputFiles = []
    #*this is where apbs.in is read in
    inputFiles.append(ns0.InputFileType_Def('inputFile'))
    #*this must be the same as req._argList is defined to be
    inputFiles[-1]._name = vars['inFile']
    tempFile = open(directory + vars['inFile'], 'r')
    inputFiles[-1]._contents = tempFile.read()
    tempFile.close()

    # this is where the rest of the files to read in are determined
    start = False
    tempFile = open(directory + vars['inFile'], 'r')
    for line in tempFile:
        # remove whitespace
        line = line.strip()
        if (line == "end"):
            break
        if (start and line.find("#") != 0):
            # eliminates lines with just comments
            # remove comment
            if (line.find("#") != -1):
                line = line[:line.find("#")]
            # re-remove whitespace (left after comment removal)
            line = line.strip()
            # remove everything except file name
            count = -1
            while line[count] != ' ':
                count = count - 1
            fileName = line[count + 1:]
            inputFiles.append(ns0.InputFileType_Def('inputFile'))
            inputFiles[-1]._name = fileName
            tempFile2 = open(directory + fileName, "r")
            inputFiles[-1]._contents = tempFile2.read()
            tempFile2.close()
        if (line == "read"):
            start = True

    tempFile.close()

    # req's inputFile variable is the array of input files created in the lines directly above
    req._inputFile = inputFiles

    if vars['typeOfRun'] == 'remote':
        appServicePort.launchJob(req)
        return [appServicePort, appServicePort.launchJob(req)]

    # Launch job, and retrieve job ID
    print "Launching remote APBS job"
    try:
        resp = appServicePort.launchJob(req)
    except ZSI.FaultException, errstr:
        stderr.write(
            "Error! Failed to execute Opal job. Please send the entire output to the APBS development team.\n"
        )
        stderr.write("%s\n" % errstr.fault.AsSoap())
        sys.exit(13)