1#!@WHICHPYTHON@
2"""
3    APBS input form [fill in later]
4"""
5
6__date__ = "22 June 2007"
7__author__ = "Samir Unni"
8__version__ = "0.0.1"
9
10import string, sys, os, time, errno, shutil, tempfile, urllib, copy, pickle, glob
11#sys.path.append("/home/samir/public_html/pdb2pqr")
12import src
13import cgi, cgitb
14import locale
15from sys import stdout, stderr, stdin
16from src.aconf import *
17from src.server import setID
18#from initVars import *
19#from generateForm import generateForm
20#from apbsInputMake import *
21#from apbsExec import apbsExec
22#from apbsExec import apbsOpalExec
23from sgmllib import SGMLParser
24from src.utilities import (getTrackingScriptString,
25                           getEventTrackingString,
26                           startLogFile,
27                           resetLogFile)
28
29def apbsOpalExec(logTime, form, apbsOptions):
30
31    sys.path.append(os.path.dirname(APBS_LOCATION))
32    from ApbsClient import execApbs, initRemoteVars, enoughMemory
33
34    #style = "%spdb2pqr.css" # HARDCODED
35
36    #apbsLog = "apbs_runtime_output.log"
37
38    #apbsErrs = "apbs_errors.log"
39
40    # Copies PQR file to temporary directory
41    pqrFileName = form["pdb2pqrid"].value + '.pqr'
42    #shutil.copyfile('../pdb2pqr/tmp/%s' % pqrFileName, './tmp/%s/%s' % (logTime, pqrFileName))
43
44
45    # Removes water from molecule if requested by the user
46    if form.has_key("removewater"):
47        if form["removewater"].value == "on":
48            os.chdir('./tmp/%s' % logTime)
49            inpath = pqrFileName
50            infile = open(inpath, "r")
51            outpath = inpath[:-4] + '-nowater' + inpath[-4:]
52            outfile = open(outpath, "w")
53            newinpath = inpath[:-4] + '-water' + inpath[-4:]
54            newoutpath = inpath
55
56            while 1:
57                line = infile.readline()
58                if line == '':
59                    break
60                if "WAT" in line:
61                    pass
62                elif "HOH" in line:
63                    pass
64                else:
65                    outfile.write(line)
66            infile.close()
67            outfile.close()
68
69            shutil.move(inpath, newinpath)
70            shutil.move(outpath, newoutpath)
71            os.chdir('../../')
72
73    #argv=[os.path.abspath("tmp/%s/%s.in") % (logTime, "apbsinput")] # HARDCODED??
74    argv=[os.path.abspath("%s%s%s/apbsinput.in" % (INSTALLDIR, TMPDIR, logTime))]
75    vars={'service_url' : APBS_OPAL_URL}
76
77    # Check for enough memory
78    if(not enoughMemory(argv[-1])):
79        return 'notenoughmem'
80
81    appServicePortArray = execApbs(vars=vars, argv=argv)
82
83    # if the version number doesn't match, execApbs returns False
84    if(appServicePortArray == False):
85        return False
86
87    appServicePort = appServicePortArray[0]
88
89    #aspFile = open('./tmp/%s/%s-asp' % (logTime, logTime),'w')
90    #pickle.dump(appServicePort, aspFile)
91    #aspFile.close()
92
93    resp = appServicePortArray[1]
94
95    return resp._jobID
96
97def apbsExec(logTime, form, apbsOptions):
98
99    tempPage = "results.html"
100
101    # Temporary index.py html page - refreshes in 30 seconds
102
103    #apbsLog = "apbs_runtime_output.log"
104
105    #apbsErrs = "apbs_errors.log"
106
107    # Copies PQR file to temporary directory
108    pqrFileName = form["pdb2pqrid"].value + '.pqr'
109    #shutil.copyfile('../pdb2pqr/tmp/%s' % pqrFileName, './tmp/%s/%s' % (logTime, pqrFileName))
110
111
112    # Removes water from molecule if requested by the user
113    try:
114        if form["removewater"].value == "on":
115            os.chdir('./tmp/%s' % logTime)
116            inpath = pqrFileName
117            infile = open(inpath, "r")
118            outpath = inpath[:-4] + '-nowater' + inpath[-4:]
119            outfile = open(outpath, "w")
120            newinpath = inpath[:-4] + '-water' + inpath[-4:]
121            newoutpath = inpath
122
123            while 1:
124                line = infile.readline()
125                if line == '':
126                    break
127                if "WAT" in line:
128                    pass
129                elif "HOH" in line:
130                    pass
131                else:
132                    outfile.write(line)
133            infile.close()
134            outfile.close()
135
136            shutil.move(inpath, newinpath)
137            shutil.move(outpath, newoutpath)
138            os.chdir('../../')
139
140    except KeyError:
141        pass
142
143    pid = os.fork()
144    if pid:
145        print redirector(logTime)
146        sys.exit()
147    else:
148        currentdir = os.getcwd()
149        os.chdir("/")
150        os.setsid()
151        os.umask(0)
152        os.chdir(currentdir)
153        os.close(1)
154        os.close(2)
155        #os.chdir('./tmp/%s' % logTime)
156        os.chdir('%s%s%s' % (INSTALLDIR, TMPDIR, logTime))
157        # LAUNCHING APBS HERE
158        startLogFile(logTime, 'apbs_status', "running\n")
159#        statusfile = open('%s%s%s/apbs_status' % (INSTALLDIR, TMPDIR, logTime),'w')
160#        statusfile.write("running\n")
161#        statusfile.close()
162
163
164        apbs_stdin, apbs_stdout, apbs_stderr = os.popen3('%s apbsinput.in' % APBS_LOCATION)
165
166        startLogFile(logTime, 'apbs_stdout.txt', apbs_stdout.read())
167#        stdoutFile=open('%s%s%s/apbs_stdout.txt' % (INSTALLDIR, TMPDIR, logTime), 'w')
168#        stdoutFile.write(apbs_stdout.read())
169#        stdoutFile.close()
170
171        startLogFile(logTime, 'apbs_stderr.txt', apbs_stderr.read())
172#        stderrFile=open('%s%s%s/apbs_stderr.txt' % (INSTALLDIR, TMPDIR, logTime), 'w')
173#        stderrFile.write(apbs_stderr.read())
174#        stderrFile.close()
175
176        startLogFile(logTime, 'apbs_end_time', str(time.time()))
177#        endtimefile=open('%s%s%s/apbs_end_time' % (INSTALLDIR, TMPDIR, logTime), 'w')
178#        endtimefile.write(str(time.time()))
179#        endtimefile.close()
180
181        jobDir = '%s%s%s/' % (INSTALLDIR, TMPDIR, logTime)
182        statusStr = "complete\n"
183        statusStr += jobDir + 'apbsinput.in\n'
184        statusStr += jobDir + '%s.pqr\n' % logTime
185        statusStr += jobDir + 'io.mc\n'
186        for filename in glob.glob(jobDir+"%s-*.dx" % logTime):
187            statusStr += (filename+"\n")
188        statusStr += jobDir + 'apbs_stdout.txt\n'
189        statusStr += jobDir + 'apbs_stderr.txt\n'
190        startLogFile(logTime, 'apbs_status', statusStr)
191
192#        statusfile=open('%s%s%s/apbs_status' % (INSTALLDIR, TMPDIR, logTime),'w')
193#        statusfile.write("complete\n")
194#        statusfile.write("%s%s%s/apbsinput.in\n" % (INSTALLDIR, TMPDIR, logTime))
195#        statusfile.write("%s%s%s/%s.pqr\n" % (INSTALLDIR, TMPDIR, logTime, logTime))
196#        statusfile.write("%s%s%s/io.mc\n" % (INSTALLDIR, TMPDIR, logTime))
197#        for filename in glob.glob("%s%s%s/%s-*.dx" % (INSTALLDIR, TMPDIR, logTime, logTime)):
198#            statusfile.write(filename+"\n")
199#        statusfile.write("%s%s%s/apbs_stdout.txt\n" % (INSTALLDIR, TMPDIR, logTime))
200#        statusfile.write("%s%s%s/apbs_stderr.txt\n" % (INSTALLDIR, TMPDIR, logTime))
201#        statusfile.close()
202        sys.exit()
203
204def generateForm(file, initVars, pdb2pqrID, type):
205    """CGI form generation code"""
206    cgifile = "apbs_cgi.cgi"
207    cginame = "thisform"
208    file.write("""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
209                <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
210            <head>
211                <title>APBS input</title>
212                <link href="pdb2pqr.css" type="text/css" rel="stylesheet" />
213                <script type=\"text/javascript\">
214                    function showHide(elemShow, elemHide) {
215                        document.getElementById(elemHide).style.display = 'none';
216                        //document.getElementById(elemShow).style.display = 'block';
217                        //document.getElementById(elemShow).style.visibility= 'visible';
218                        document.getElementById(elemShow).style.display = '';
219                    }
220
221                    function toggle(element) {
222                        if(document.getElementById(element).style.display == 'none') {
223                            document.getElementById(element).style.display = '';
224                        }
225                        else {
226                            document.getElementById(element).style.display = 'none';
227                        }
228                    }
229
230                    function getElementsByClass(searchClass,node,tag) {
231                        var classElements = new Array();
232                        if ( node == null )
233                            node = document;
234                        if ( tag == null )
235                            tag = '*';
236                        var els = node.getElementsByTagName(tag);
237                        var elsLen = els.length;
238                        //var pattern = new RegExp("(^|\\\\\\\\s)"+searchClass+"(\\\\\\\\s|$)");
239                        for (i = 0, j = 0; i < elsLen; i++) {
240                            //if ( pattern.test(els[i].className) ) {
241                            if( els[i].className.indexOf(searchClass) != -1) {
242                                classElements[j] = els[i];
243                                j++;
244                            }
245                        }
246                        return classElements;
247                    }
248
249                    function disableCalcType(calcTypeToDisable) {
250                        //var elements = getElementsByClass(calcTypeToDisable, null, 'div');
251                        var elements = getElementsByClass(calcTypeToDisable);
252                        for(var i=0; i<elements.length; i++) {
253                            elements[i].style.display = 'none';
254                        }
255                    }
256
257                    function showCalcType(calcType) {
258                        //var calcTypesToDisable = ['mg-auto','mg-para','mg-manual','fe-manual','mg-dummy'];
259                        var calcTypesToDisable = ['mg-auto','mg-para','mg-manual','fe-manual','mg-dummy'];
260                        for(var i=0; i<calcTypesToDisable.length; i++) {
261                            if(calcTypesToDisable[i]!=calcType) {
262                                disableCalcType(calcTypesToDisable[i]);
263                            }
264                        }
265
266                        //var elements = getElementsByClass(calcType, null, 'div');
267                        var elements = getElementsByClass(calcType);
268                        for(var i=0; i<elements.length; i++) {
269                            //elements[i].style.display = 'block';
270                            elements[i].style.display = '';
271                            //elements[i].style.visibility = 'visible';
272                        }
273                    }
274
275                    function findCheckedCalc() {
276                        for(var i=0; i<document.%s.type.length; i++) {
277                            if(document.%s.type[i].checked) {
278                                type = document.%s.type[i];
279                                return type;
280                            }
281                        }
282                    }
283
284                    function configInitCheckedCalc() {
285                        showCalcType('%s');
286                    }
287
288                    function executeOnPageLoad(myfunc) {
289                        if(window.addEventListener) {
290                            window.addEventListener('load', myfunc, false);
291                        }
292
293                        else if(window.attachEvent) {
294                            window.attachEvent('onload', myfunc);
295                        }
296                    }
297
298                    executeOnPageLoad(configInitCheckedCalc);
299
300                    window.onload = function() {
301  		// Check if hash exists
302                        if(window.location.hash) {
303    		// Remove the "#" from the hash
304                            hash = window.location.hash.substr(1);
305   		 // Display element with id == hash
306                        document.getElementById(hash).style.display = "block";
307                        }
308                    }
309
310                </script>
311            </head>
312    <body>
313        <!-- ... body of document ... -->
314        <h2>APBS web solver</h2>
315    """ % (cginame, cginame, cginame, initVars['calculationType'])) # hardcoded css link
316    file.write("<h3>Calculation on <a href=\"tmp/%s/%s\" target=\"_blank\">%s</a> with default values provided by PDB2PQR:</h3><br />\n" % (pdb2pqrID, initVars['pqrname'],initVars['pdbID']))
317    # Write out the form element
318    print "<form action=\"%s\" method=\"post\" enctype=\"multipart/form-data\" name=\"%s\" id=\"%s\">" % (cgifile, cginame, cginame)
319    print "<input type=\"submit\" value=\"Launch\"/><br /><br />"
320    print """
321            If you prefer to run APBS with custom values, click here:
322            <input type=\"checkbox\" name=\"customvalues\" onClick=\"toggle(\'params\');"/>
323            <br /><br />
324
325            <div id=\"params\" style=\"display:none\">
326            Please specify the type of calculation (all parameters for the specified calculation must be fullfilled, unless indicated otherwise):
327            <br />
328
329    """
330
331    print "<input type=\"radio\" name=\"type\" value=\"mg-auto\" onClick=\"showCalcType(\'mg-auto\');\"",
332    if initVars['calculationType'] == "mg-auto":
333        print " checked=\"checked\"",
334
335    print "/> Automatically-configured sequential focusing multigrid calculation <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#mg-auto\" target=\"_blank\"><font title=\"mg-auto\" >(<span class=\"tooltip\">?</span>)</font></a>"
336
337    print "<br />"
338    print "<input type=\"radio\" name=\"type\" value=\"mg-para\" onClick=\"showCalcType(\'mg-para\');\"",
339
340    if initVars['calculationType'] == "mg-para":
341        print " checked=\"checked\"",
342    #print "disabled=\"disabled\""
343
344    print """/> Automatically-configured parallel focusing multigrid calculation <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#mg-para\" target=\"_blank\"><font title=\"mg-para\">(<span class=\"tooltip\">?</span>)</font></a>"""
345
346    print "<br />"
347    print "<input type=\"radio\" name=\"type\" value=\"mg-manual\" onClick=\"showCalcType(\'mg-manual\');\"",
348    if initVars['calculationType'] == "mg-manual":
349        print " checked=\"checked\"",
350
351    #print "disabled=\"disabled\""
352
353    print """/> Manually-configured multigrid calculation <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#mg-manual\" target=\"_blank\"><font title=\"mg-manual\">(<span class=\"tooltip\">?</span>)</font></a>"""
354
355
356    print "<br />"
357    print "<input type=\"radio\" name=\"type\" value=\"fe-manual\" onClick=\"showCalcType(\'fe-manual\');\"",
358    if initVars['calculationType'] == "fe-manual":
359        print " checked=\"checked\"",
360
361    #print "disabled=\"disabled\""
362
363    print """/> Manually-configured adaptive finite element calculation <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#fe-manual\" target=\"_blank\"><font title=\"fe-manual\">(<span class=\"tooltip\">?</span>)</font></a>"""
364
365
366    print "<br />"
367
368    print "<input type=\"radio\" name=\"type\" value=\"mg-dummy\" onClick=\"showCalcType(\'mg-dummy\');\"",
369    if initVars['calculationType'] == "mg-dummy":
370        print " checked=\"checked\"",
371
372    #print "disabled=\"disabled\""
373
374    print """/> Surface and charge distribution property calculations (does not require solution of the PBE) <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#mg-dummy\" target=\"_blank\"><font title=\"mg-dummy\">(<span class=\"tooltip\">?</span>)</font></a>"""
375
376    print "<ul><li><input type=\"checkbox\" name=\"removewater\" value=\"on\" checked=\"checked\"/> Remove water from calculations and visualizations</li></ul>"
377
378    print """
379                <div class=\"mg-auto mg-para mg-manual mg-dummy\">
380                <ul>"""
381
382    print """
383                <table class=\"apbs\" border=\"1\">
384                    <tr>
385                        <th></th>
386                        <th>x-direction</th>
387                        <th>y-direction</th>
388                        <th>z-direction</th>
389                    </tr>
390                    <tbody class=\"mg-auto mg-para mg-manual mg-dummy\">
391                    <tr>
392                        <td>Number of grid points<br />per processor for grid-<br />based discretization <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-dime\" target=\"_blank\"><font title=\"dime\">(<span class=\"tooltip\">?</span>)</font></a></td>
393                        <td><input type=\"text\" name=\"dimenx\" size=\"10\" maxlength=\"20\""""
394    if initVars.has_key('dime'):
395        print "value=\"%d\"" % initVars['dime'][0]
396    print "/></td>"
397    print "<td><input type=\"text\" name=\"dimeny\" size=\"10\" maxlength=\"20\""
398    if initVars.has_key('dime'):
399        print "value=\"%d\"" % initVars['dime'][1]
400    print "/></td>"
401    print "<td><input type=\"text\" name=\"dimenz\" size=\"10\" maxlength=\"20\""
402    if initVars.has_key('dime'):
403        print "value=\"%d\"" % initVars['dime'][2]
404    print "/></td></tr></tbody>"
405    # next row
406    print "<tbody class=\"mg-auto mg-para mg-dummy\">"
407    print "<tr>"
408    print "<td>Coarse mesh domain<br />lengths in a focusing<br />calculation <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-cglen\" target=\"_blank\"><font title=\"cglen\">(<span class=\"tooltip\">?</span>)</font></a></td>"
409    print "<td><input type=\"text\" name=\"cglenx\" size=\"10\" maxlength=\"20\""
410    if initVars.has_key('coarseGridLength'):
411        print "value=\"%g\"" % initVars['coarseGridLength'][0]
412    print "/>"
413    print "<td><input type=\"text\" name=\"cgleny\" size=\"10\" maxlength=\"20\""
414    if initVars.has_key('coarseGridLength'):
415        print "value=\"%g\"" % initVars['coarseGridLength'][1]
416    print "/>"
417    print "<td><input type=\"text\" name=\"cglenz\" size=\"10\" maxlength=\"20\""
418    if initVars.has_key('coarseGridLength'):
419        print "value=\"%g\"" % initVars['coarseGridLength'][2]
420    print "/></td></tr></tbody>"
421    # next row
422    print "<tbody class=\"mg-auto mg-para\">"
423    print "<tr>"
424    print "<td>Fine mesh domain<br />lengths in a focusing<br />calculation <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-fglen\" target=\"_blank\"><font title=\"fglen\">(<span class=\"tooltip\">?</span>)</font></a></td>"
425    print "<td><input type=\"text\" name=\"fglenx\" size=\"10\" maxlength=\"20\""
426    if initVars.has_key('fineGridLength'):
427        print "value=\"%g\"" % initVars['fineGridLength'][0]
428    print "/>"
429    print "<td><input type=\"text\" name=\"fgleny\" size=\"10\" maxlength=\"20\""
430    if initVars.has_key('fineGridLength'):
431        print "value=\"%g\"" % initVars['fineGridLength'][1]
432    print "/>"
433    print "<td><input type=\"text\" name=\"fglenz\" size=\"10\" maxlength=\"20\""
434    if initVars.has_key('fineGridLength'):
435        print "value=\"%g\"" % initVars['fineGridLength'][2]
436    print "/></td></tr></tbody>"
437
438    # next row
439    print "<tbody class=\"mg-para\">"
440    print "<tr>"
441    print "<td>Number of proces-<br />sors in a parallel<br />focusing calculation <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-pdime\" target=\"_blank\"><font title=\"pdime\">(<span class=\"tooltip\">?</span>)</font></a></td>"
442    print "<td><input type=\"text\" name=\"pdimex\" size=\"10\" maxlength=\"20\""
443    if initVars.has_key('pdime'):
444        print "value=\"%g\"" % initVars['pdime'][0]
445    print "/>"
446    print "<td><input type=\"text\" name=\"pdimey\" size=\"10\" maxlength=\"20\""
447    if initVars.has_key('pdime'):
448        print "value=\"%g\"" % initVars['pdime'][1]
449    print "/>"
450    print "<td><input type=\"text\" name=\"pdimez\" size=\"10\" maxlength=\"20\""
451    if initVars.has_key('pdime'):
452        print "value=\"%g\"" % initVars['pdime'][2]
453    print "/></td></tr></tbody>"
454
455    # next row
456    print "<tbody class=\"mg-manual\">"
457    print "<tr>"
458    print "<td>Mesh domain<br />lengths <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-glen\" target=\"_blank\"><font title=\"glen\">(<span class=\"tooltip\">?</span>)</font></a></td>"
459    print "<td><input type=\"text\" name=\"glenx\" size=\"10\" maxlength=\"20\""
460    if initVars.has_key('glen'):
461        print "value=\"%g\"" % initVars['glen'][0]
462    print "/>"
463    print "<td><input type=\"text\" name=\"gleny\" size=\"10\" maxlength=\"20\""
464    if initVars.has_key('glen'):
465        print "value=\"%g\"" % initVars['glen'][1]
466    print "/>"
467    print "<td><input type=\"text\" name=\"glenz\" size=\"10\" maxlength=\"20\""
468    if initVars.has_key('glen'):
469        print "value=\"%g\"" % initVars['glen'][2]
470    print "/></td></tr></tbody>"
471
472
473
474    print "</table></div></ul>"
475
476    print """           <div class=\"mg-para\"><ul>
477                <li>Amount of overlap to include between the individual processors' meshes <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-ofrac\" target=\"_blank\"><font title=\"ofrac\">(<span class=\"tooltip\">?</span>)</font></a>:"""
478    print "<input type=\"text\" name=\"ofrac\" size=\"10\" maxlength=\"20\""
479    if initVars.has_key('processorMeshOverlap'):
480        print "value=\"%f\"" % initVars['processorMeshOverlap']
481    print "/></li><br />"
482
483    print "<li><input type=\"checkbox\" name=\"asyncflag\" onClick=toggle(\"async\") "
484    if initVars['asyncflag']:
485        print " checked=\"checked\""
486    print """/> Perform the tasks in a parallel run asynchronously <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-async\" target=\"_blank\"><font title=\"asyncflag\">(<span class=\"tooltip\">?</span>)</font></a></li>"""
487    print "<blockquote>"
488    print "<div id=\"async\" style=\"display:none\">"
489    print "<li>Rank for a processor to masquerade as <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-async\" target=\"_blank\"><font title=\"async\">(<span class=\"tooltip\">?</span>)</font></a>:"
490    print "<input type=\"text\" name=\"async\" size=\"10\" maxlength=\"20\""
491    if initVars.has_key('async'):
492        print " value=\"%i\"" % initVars['async']
493    print "/></li>"
494    print "</blockquote>"
495
496
497    print "</li></ul></div>"
498
499    print "<div class=\"mg-manual mg-dummy\">"
500    print "<ul><li>Depth of the multilevel hierarchy used in the multigrid solver <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-nlev\" target=\"_blank\"><font title=\"nlev\">(<span class=\"tooltip\">?</span>)</font></a>:"
501    print "<input type=\"text\" name=\"nlev\" size=\"10\" maxlength=\"20\""
502    if initVars.has_key('nlev'):
503        print " value=\"%i\"" % initVars['nlev']
504    print "/></li></ul></div>"
505
506    print """           <div class=\"mg-manual mg-dummy\"><ul>
507
508                <li>Center of the grid <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-cgcent\" target=\"_blank\"><font title=\"gcent\">(<span class=\"tooltip\">?</span>)</font></a>:</li></ul>
509                <blockquote><ul><li>"""
510    print "<input type=\"radio\" name=\"gcent\" value=\"mol\" onClick=\"showHide(\'gcentmol\',\'gcentcoord\');\""
511
512    if initVars['gridCenterMethod'] == "molecule":
513        print "checked=\"checked\""
514
515    print "/> Center the grid on a molecule.</li></ul>"
516
517    print "<div id=\"gcentmol\""
518    if initVars['gridCenterMethod'] != "molecule":
519        print " style=\"display: none;\""
520    print"""><blockquote>
521                    <ul>
522                        <li>Enter molecule ID:"""
523
524    print "<input type=\"text\" name=\"gcentid\" size=\"10\" maxlength=\"20\""
525    if initVars['gridCenterMethod'] == "molecule" and initVars.has_key('gridCenterMoleculeID'):
526        print "value=\"%d\"" % initVars['gridCenterMoleculeID']
527    print "/>"
528
529    print """
530                        </li>
531                    </ul>
532                    </blockquote></div>
533                    """
534
535    print "<ul><li><input type=\"radio\" name=\"gcent\" value=\"coord\" onClick=\"showHide(\'gcentcoord\',\'gcentmol\');\""
536
537    if initVars['gridCenterMethod'] == "coordinate":
538        print "checked"
539
540    print "/> Manually enter coordinates for center of grid:</li></ul>"
541
542    print "<div id=\"gcentcoord\""
543    if initVars['gridCenterMethod'] != "coordinate":
544        print "style=\"display: none;\""
545    print """><blockquote>
546                    <ul>
547                        <li>"""
548
549    print "x-coordinate: <input type=\"text\" name=\"gxcent\" size=\"10\" maxlength=\"20\""
550    if initVars.has_key('gridCenter'):
551        print "value=\"%d\"" % initVars['gridCenter'][0]
552    print "/>"
553
554
555    print """
556                        </li>
557                        <li>"""
558
559    print "y-coordinate: <input type=\"text\" name=\"gycent\" size=\"10\" maxlength=\"20\""
560    if initVars.has_key('gridCenter'):
561        print "value=\"%d\"" % initVars['gridCenter'][1]
562    print "/>"
563
564    print """
565                        </li>
566                        <li>"""
567
568    print "z-coordinate: <input type=\"text\" name=\"gzcent\" size=\"10\" maxlength=\"20\""
569    if initVars.has_key('gridCenter'):
570        print "value=\"%d\"" % initVars['gridCenter'][2]
571    print "/>"
572    print "</li></ul></blockquote></div>"
573    print "</blockquote>"
574    print "</div>"
575
576    print """
577
578       <div class=\"mg-auto mg-para\"><ul>
579                <li>Center of the coarse grid <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-cgcent\" target=\"_blank\"><font title=\"cgcent\">(<span class=\"tooltip\">?</span>)</font></a>:</li></ul>
580                                <blockquote><ul><li>"""
581
582    print "<input type=\"radio\" name=\"cgcent\" value=\"mol\" onClick=\"showHide(\'cgcentmol\',\'cgcentcoord\');\""
583
584    if initVars['coarseGridCenterMethod'] == "molecule":
585        print "checked=\"checked\""
586
587    print "/> Center the grid on a molecule.</li></ul>"
588
589    print "<div id=\"cgcentmol\""
590    if initVars['coarseGridCenterMethod'] != "molecule":
591        print " style=\"display: none;\""
592    print"""><blockquote>
593                    <ul>
594                        <li>Enter molecule ID:"""
595
596    print "<input type=\"text\" name=\"cgcentid\" size=\"10\" maxlength=\"20\""
597    if initVars['coarseGridCenterMethod'] == "molecule" and initVars.has_key('coarseGridCenterMoleculeID'):
598        print "value=\"%d\"" % initVars['coarseGridCenterMoleculeID']
599    print "/>"
600
601    print """
602                        </li>
603                    </ul>
604                    </blockquote>
605                    </div>
606                    """
607
608    print "<ul><li><input type=\"radio\" name=\"cgcent\" value=\"coord\" onClick=\"showHide(\'cgcentcoord\',\'cgcentmol\');\""
609
610    if initVars['coarseGridCenterMethod'] == "coordinate":
611        print "checked"
612
613    print "/> Manually enter coordinates for center of grid:</li></ul>"
614
615    print "<div id=\"cgcentcoord\""
616    if initVars['coarseGridCenterMethod'] != "coordinate":
617        print "style=\"display: none;\""
618    print """><blockquote>
619                    <ul>
620                        <li>"""
621
622    print "x-coordinate: <input type=\"text\" name=\"cgxcent\" size=\"10\" maxlength=\"20\""
623    if initVars.has_key('coarseGridCenter'):
624        print "value=\"%d\"" % initVars['coarseGridCenter'][0]
625    print "/>"
626
627
628    print """
629                        </li>
630                        <li>"""
631
632    print "y-coordinate: <input type=\"text\" name=\"cgycent\" size=\"10\" maxlength=\"20\""
633    if initVars.has_key('coarseGridCenter'):
634        print "value=\"%d\"" % initVars['coarseGridCenter'][1]
635    print "/>"
636
637    print """
638                        </li>
639                        <li>"""
640
641    print "z-coordinate: <input type=\"text\" name=\"cgzcent\" size=\"10\" maxlength=\"20\""
642    if initVars.has_key('coarseGridCenter'):
643        print "value=\"%d\"" % initVars['coarseGridCenter'][2]
644    print "/>"
645    print """</li></ul></blockquote>
646                    </blockquote>"""
647            #"""</div>"""
648
649    print """
650
651
652                <ul>
653                <li>Center of the fine grid <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-fgcent\" target=\"_blank\"><font title=\"fgcent\">(<span class=\"tooltip\">?</span>)</font></a>:</li></ul>
654                <blockquote>
655                <ul><li>"""
656
657    print "<input type=\"radio\" name=\"fgcent\" value=\"mol\" onClick=\"showHide(\'fgcentmol\',\'fgcentcoord\');\""
658
659    if initVars['fineGridCenterMethod'] == "molecule":
660        print "checked=\"checked\""
661
662    print "/> Center the grid on a molecule.</li></ul>"
663    print "<div id=\"fgcentmol\""
664    if initVars['fineGridCenterMethod'] != "molecule":
665        print "style=\"display: none\""
666
667    print """
668                    ><blockquote>
669                    <ul>
670                        <li>Enter molecule ID:"""
671
672    print "<input type=\"text\" name=\"fgcentid\" size=\"10\" maxlength=\"20\""
673    if initVars['fineGridCenterMethod'] == "molecule" and initVars.has_key('fineGridCenterMoleculeID'):
674        print "value=\"%d\"" % initVars['fineGridCenterMoleculeID']
675    print "/>"
676
677    print """
678                        </li>
679                    </ul>
680                    </blockquote></div>"""
681
682    print "<ul><li><input type=\"radio\" name=\"fgcent\" value=\"coord\" onClick=\"showHide(\'fgcentcoord\',\'fgcentmol\');\""
683    if initVars['fineGridCenterMethod'] == "coordinate":
684        print "checked"
685    print "/> Manually enter coordinates for the center of the grid.</li></ul>"
686    print "<div id=\"fgcentcoord\""
687    if initVars['fineGridCenterMethod'] != "coordinate":
688        print "style=\"display: none;\""
689
690    print """
691                    ><blockquote>
692                    <ul>
693                        <li>"""
694
695    print "x-coordinate: <input type=\"text\" name=\"fgxcent\" size=\"10\" maxlength=\"20\""
696    if initVars.has_key('fineGridCenter'):
697        print "value=\"%d\"" % initVars['fineGridCenter'][0]
698    print "/>"
699    print """
700                        </li>
701                        <li>"""
702
703    print "y-coordinate: <input type=\"text\" name=\"fgycent\" size=\"10\" maxlength=\"20\""
704    if initVars.has_key('fineGridCenter'):
705        print "value=\"%d\"" % initVars['fineGridCenter'][1]
706    print "/>"
707
708    print """
709                        </li>
710                        <li>"""
711
712    print "z-coordinate: <input type=\"text\" name=\"fgzcent\" size=\"10\" maxlength=\"20\""
713    if initVars.has_key('fineGridCenter'):
714        print "value=\"%d\"" % initVars['fineGridCenter'][2]
715    print "/>"
716
717    print """
718                        </li>
719                </ul>
720                    </blockquote>
721                </blockquote>
722                    </div>"""#</div>"""
723
724
725    #print       """<ul>
726    #            <div class=\"mg-para mg-manual fe-manual mg-dummy\""""
727    #print """>
728    #            <li>Molecule for which the PBE is to be solved <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-mol\" target=\"_blank\"><font title=\"mol\">(<span class=\"tooltip\">?</span>)</font></a>:"""
729
730    #print "<input type=\"text\" name=\"mol\" size=\"10\" maxlength=\"20\""
731    #if initVars.molecule != None:
732    #    print "value=\"%d\"" % initVars.molecule
733    #print "/></li></div>"
734
735    #print """</ul>
736
737
738    print """   <ul>
739                <li>Type of PBE to be solved:</li></ul>"""
740
741    print """<blockquote>
742    <ul>"""
743    print "<li><input type=\"radio\" name=\"solvetype\" value=\"lpbe\""
744    if initVars['solveType'] == "linearized":
745        print "checked=\"checked\""
746    print "/> Linearized <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-lpbe\" target=\"_blank\"><font title=\"lpbe\">(<span class=\"tooltip\">?</span>)</font></a></li>"
747
748
749    print "<li><input type=\"radio\" name=\"solvetype\" value=\"npbe\""
750    if initVars['solveType'] == "nonlinearized":
751        print "checked=\"checked\""
752    print "/> Nonlinearized <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-npbe\" target=\"_blank\"><font title=\"npbe\">(<span class=\"tooltip\">?</span>)</font></a></li>"
753
754    print "<div class=\"fe-manual\""
755    #if initVars.defaultCalcType != "fe-manual":
756    #    print " style=\"display: none;\""
757    print "><li><input type=\"radio\" name=\"solvetype\" value=\"lrpbe\""
758    if initVars['solveType'] == "linearized regularized":
759        print "checked=\"checked\""
760    print "/> Linearized (regularized) <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-lrpbe\" target=\"_blank\"><font title=\"lrpbe\">(<span class=\"tooltip\">?</span>)</font></a></li>"
761
762
763    print "<li><input type=\"radio\" name=\"solvetype\" value=\"nrpbe\""
764    if initVars['solveType'] == "nonlinearized regularized":
765        print "checked=\"checked\""
766    print "/> Nonlinearized (regularized) <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-nrpbe\" target=\"_blank\"><font title=\"nrpbe\">(<span class=\"tooltip\">?</span>)</font></a></li></div>"
767
768    print """</ul>
769    </blockquote>"""
770
771    print "         <ul><li>Boundary condition definition <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-bcfl\" target=\"_blank\"><font title=\"bcfl\">(<span class=\"tooltip\">?</span>)</font></a>:</li></ul>"
772
773    print "<blockquote> <ul>"
774    print "<li><input type=\"radio\" name=\"bcfl\" value=\"zero\""
775    if initVars['boundaryConditions'] == "zero":
776        print "checked=\"checked\""
777    print "/> Zero <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-bcfl\" target=\"_blank\"><font title=\"zero\">(<span class=\"tooltip\">?</span>)</font></a></li>"
778
779
780    print "<li><input type=\"radio\" name=\"bcfl\" value=\"sdh\""
781    if initVars['boundaryConditions'] == "sdh":
782        print "checked=\"checked\""
783    print "/> Single Debye-Huckel <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-bcfl\" target=\"_blank\"><font title=\"sdh\">(<span class=\"tooltip\">?</span>)</font></a></li>"
784
785
786    print "<li><input type=\"radio\" name=\"bcfl\" value=\"mdh\""
787    if initVars['boundaryConditions'] == "mdh":
788        print "checked=\"checked\""
789    print "/> Multiple Debye-Huckel <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-bcfl\" target=\"_blank\"><font title=\"mdh\">(<span class=\"tooltip\">?</span>)</font></a></li>"
790
791
792    print "<li><input type=\"radio\" name=\"bcfl\" value=\"focus\""
793    if initVars['boundaryConditions'] == "focus":
794        print "checked=\"checked\""
795    print "/> Focusing <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-bcfl\" target=\"_blank\"><font title=\"focus\">(<span class=\"tooltip\">?</span>)</font></a></li>"
796    print "</ul></blockquote>"
797
798
799    print "<ul>"
800    print """       <li>Mobile ion species present in system (optional) <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-ion\" target=\"_blank\"><font title=\"ion\">(<span class=\"tooltip\">?</span>)</font></a>:</li></ul>"""
801
802    print """<ul>
803                <table class=\"apbs\" border=\"1\">
804                    <tr>
805                        <th></th>
806                        <th>Mobile ion species<br />charge (in e<sub>c</sub>) <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-ion\" target=\"_blank\"><font title=\"charge\">(<span class=\"tooltip\">?</span>)</font></a></th>
807                        <th>Mobile ion species<br />concentration (in M) <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-ion\" target=\"_blank\"><font title=\"conc\">(<span class=\"tooltip\">?</span>)</font></a></th>
808                        <th>Mobile ion species<br />radius (in A) <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-ion\" target=\"_blank\"><font title=\"radius\">(<span class=\"tooltip\">?</span>)</font></a></th>
809                    </tr>"""
810    # new row
811    for i in range(0,3):
812        print """<tr>
813                            <td>Ion %d</td>
814                            <td><input type=\"text\" name=\"charge%d\" size=\"10\" maxlength=\"20\"""" % ((i+1),i)
815        if initVars.has_key('mobileIonSpeciesCharge'):
816            print "value=\"%d\"" % initVars['mobileIonSpeciesCharge']
817        print "/></td>"
818        print """
819                            <td><input type=\"text\" name=\"conc%d\" size=\"10\" maxlength=\"20\"""" % i
820        if initVars.has_key('mobileIonSpeciesConcentration'):
821            print "value=\"%d\"" % initVars['mobileIonSpeciesConcentration']
822        print "/></td>"
823        print """
824                            <td><input type=\"text\" name=\"radius%d\" size=\"10\" maxlength=\"20\"""" % i
825        if initVars.has_key('mobileIonSpeciesRadius'):
826            print "value=\"%d\"" % initVars['mobileIonSpeciesRadius']
827        print "/></td>"
828    print "</tr></table></ul>"
829
830
831
832
833    #print """<blockquote><ul>
834    #            <li>Mobile ion species charge (in e<sub>c</sub>) <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-ion\" target=\"_blank\"><font title=\"charge\">(<span class=\"tooltip\">?</span>)</font></a>: """
835
836    #print "<input type=\"text\" name=\"charge\" size=\"10\" maxlength=\"20\""
837    #if initVars.defaultMobileIonSpeciesCharge != None:
838    #    print "value=\"%d\"" % initVars.defaultMobileIonSpeciesCharge
839    #print "/></li>"
840
841    #
842    #print "         <li>Mobile ion species concentration (in M) <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-ion\" target=\"_blank\"><font title=\"conc\">(<span class=\"tooltip\">?</span>)</font></a>:"
843    #
844    #print "<input type=\"text\" name=\"conc\" size=\"10\" maxlength=\"20\""
845    #if initVars.defaultMobileIonSpeciesConcentration != None:
846    #    print "value=\"%d\"" % initVars.defaultMobileIonSpeciesConcentration
847    #print "/></li>"
848
849    #print "         <li>Mobile ion species radius (in A) <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-ion\" target=\"_blank\"><font title=\"radius\">(<span class=\"tooltip\">?</span>)</font></a>:"
850    #
851    #print "<input type=\"text\" name=\"radius\" size=\"10\" maxlength=\"20\""
852    #if initVars.defaultMobileIonSpeciesRadius != None:
853    #    print "value=\"%d\"" % initVars.defaultMobileIonSpeciesRadius
854    #print "/></li>"
855    #print "</ul></blockquote>"
856
857
858    print "         <ul><li>Biomolecular dielectric constant <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-pdie\" target=\"_blank\"><font title=\"pdie\">(<span class=\"tooltip\">?</span>)</font></a>:"
859
860
861    print "<input type=\"text\" name=\"pdie\" size=\"10\" maxlength=\"20\""
862    if initVars.has_key('biomolecularDielectricConstant'):
863        print "value=\"%g\"" % initVars['biomolecularDielectricConstant']
864    print "/>"
865
866    print """       </li>
867                </ul>"""
868
869    print "         <ul><li>Dielectric constant of solvent <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-sdie\" target=\"_blank\"><font title=\"sdie\">(<span class=\"tooltip\">?</span>)</font></a>:"
870
871
872    print "         <input type=\"text\" name=\"sdie\" size=\"10\" maxlength=\"20\""
873    if initVars.has_key('dielectricSolventConstant'):
874        print "value=\"%g\"" % initVars['dielectricSolventConstant']
875
876    print """/></li>
877                </ul>
878
879                <ul>
880                <li>Method by which the biomolecular point charges are mapped onto the grid <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-chgm\" target=\"_blank\"><font title=\"chgm\">(<span class=\"tooltip\">?</span>)</font></a>:</li></ul>"""
881
882    print "<blockquote><ul>"
883    print "<li><input type=\"radio\" name=\"chgm\" value=\"spl0\""
884    if initVars.has_key('biomolecularPointChargeMapMethod') and initVars['biomolecularPointChargeMapMethod'] == "spl0":
885        print "checked"
886    print "/> Traditional trilinear interpolation <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-chgm\" target=\"_blank\"><font title=\"spl0\">(<span class=\"tooltip\">?</span>)</font></a></li>"
887
888
889    print "<li><input type=\"radio\" name=\"chgm\" value=\"spl2\""
890    if initVars.has_key('biomolecularPointChargeMapMethod') and initVars['biomolecularPointChargeMapMethod'] == "spl2":
891        print "checked=\"checked\""
892    print "/> Cubic B-spline discretization <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-chgm\" target=\"_blank\"><font title=\"spl2\">(<span class=\"tooltip\">?</span>)</font></a></li>"
893
894
895    print "<li><input type=\"radio\" name=\"chgm\" value=\"spl4\""
896    if initVars.has_key('biomolecularPointChargeMapMethod') and initVars['biomolecularPointChargeMapMethod'] == "spl4":
897        print "checked"
898    print "/> Quintic B-spline discretization <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-chgm\" target=\"_blank\"><font title=\"spl4\">(<span class=\"tooltip\">?</span>)</a></font></li>"
899    print "</ul></blockquote>"
900
901
902    print "         <ul><li>Number of grid points per square-angstrom to use in surface constructions <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-sdens\" target=\"_blank\"><font title=\"sdens\">(<span class=\"tooltip\">?</span>)</font></a>:"
903
904    print "<input type=\"text\" name=\"sdens\" size=\"10\" maxlength=\"20\""
905    if initVars.has_key('surfaceConstructionResolution'):
906        print "value=\"%g\"" % initVars['surfaceConstructionResolution']
907
908    print """   /></li></ul>
909
910
911            <ul><li>Model to use to construct the dielectric ion-accessibility coefficients <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-srfm\" target=\"_blank\"><font title=\"srfm\">(<span class=\"tooltip\">?</span>)</font></a>:</li></ul>"""
912
913
914    print "<blockquote> <ul>"
915    print "<li><input type=\"radio\" name=\"srfm\" value=\"mol\""
916    if initVars.has_key('dielectricIonAccessibilityModel') and initVars['dielectricIonAccessibilityModel'] == "mol":
917        print "checked=\"checked\""
918
919    print "/> Dielectric coefficient is defined based on a molecular surface definition; ion-accessibility coefficient is defined by an \"inflated\" van der Waals model <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-srfm\" target=\"_blank\"><font title=\"mol\">(<span class=\"tooltip\">?</span>)</font></a>.</li>"
920
921    print "<li><input type=\"radio\" name=\"srfm\" value=\"smol\""
922    if initVars.has_key('dielectricIonAccessibilityModel') and initVars['dielectricIonAccessibilityModel'] == "smol":
923        print "checked=\"checked\""
924
925    print "/> Dielectric and ion-accessiblity coefficients are defined as above, but then are then \"smoothed\" by a 9-point harmonic averaging to somewhat reduce sensitivity to the grid setup <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-srfm\" target=\"_blank\"><font title=\"smol\">(<span class=\"tooltip\">?</span>)</font></a>.</li>"
926
927    print "<li><input type=\"radio\" name=\"srfm\" value=\"spl2\""
928    if initVars.has_key('dielectricIonAccessibilityModel') and initVars['dielectricIonAccessibilityModel'] == "spl2":
929        print "checked=\"checked\""
930
931    print "/> Dielectric and ion-accessibility coefficients are defined by a cubic-spline surface <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-srfm\" target=\"_blank\"><font title=\"spl2\">(<span class=\"tooltip\">?</span>)</font></a>.</li>"
932
933    print "<li><input type=\"radio\" name=\"srfm\" value=\"spl4\""
934    if initVars.has_key('dielectricIonAccessibilityModel') and initVars['dielectricIonAccessibilityModel'] == "spl4":
935        print "checked=\"checked\""
936
937    print "/> Dielectric and ion-accessibility coefficients are defined by a 7th order polynomial <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-srfm\" target=\"_blank\"><font title=\"spl4\">(<span class=\"tooltip\">?</span>)</font></a>.</li>"
938    print "</ul></blockquote>"
939
940
941    print "         <ul><li>Radius of the solvent molecules <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-srad\" target=\"_blank\"><font title=\"srad\">(<span class=\"tooltip\">?</span>)</font></a>:"
942
943
944    print "<input type=\"text\" name=\"srad\" size=\"10\" maxlength=\"20\""
945    if initVars['solventRadius'] != None:
946        print "value=\"%g\"" % initVars['solventRadius']
947
948    print """/></li></ul>
949
950
951                <ul><li>Size of the support for spline-based surface definitions <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-swin\" target=\"_blank\"><font title=\"swin\">(<span class=\"tooltip\">?</span>)</font></a>:"""
952
953
954    print "<input type=\"text\" name=\"swin\" size=\"10\" maxlength=\"20\""
955    if initVars.has_key('surfaceDefSupportSize'):
956        print "value=\"%g\"" % initVars['surfaceDefSupportSize']
957
958    print """/></li></ul>
959
960
961                <ul><li>Temperature for PBE calculation (in K) <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-temp\" target=\"_blank\"><font title=\"temp\">(<span class=\"tooltip\">?</span>)</font></a>:"""
962
963
964    print "<input type=\"text\" name=\"temp\" size=\"10\" maxlength=\"20\""
965    if initVars.has_key('temperature'):
966        print "value=\"%g\"" % initVars['temperature']
967
968    print """/></li></ul>
969
970
971                <ul><li>Calculation of electrostatic energy from a PBE calculation <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-calcenergy\" target=\"_blank\"><font title=\"calcenergy\">(<span class=\"tooltip\">?</span>)</font></a>:</li></ul>"""
972
973
974    print "<blockquote><ul>"
975    print "<li><input type=\"radio\" name=\"calcenergy\" value=\"no\""
976    if initVars['calculationEnergy'] == "no":
977        print "checked"
978
979    print """/> Don\'t calculate any energies <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-calcenergy\" target=\"_blank\"><font title=\"no\">(<span class=\"tooltip\">?</span>)</font></a>.</li>"""
980
981    print "<li><input type=\"radio\" name=\"calcenergy\" value=\"total\""
982    if initVars['calculationEnergy'] == "total":
983        print "checked=\"checked\""
984
985    print """/> Calculate and return total electrostatic energy for the entire molecule <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-calcenergy\" target=\"_blank\"><font title=\"total\">(<span class=\"tooltip\">?</span>)</font></a>.</li>"""
986
987    print "<li><input type=\"radio\" name=\"calcenergy\" value=\"comps\""
988    if initVars['calculationEnergy'] == "comps":
989        print "checked=\"checked\""
990
991    print """/> Calculate and return total electrostatic energy for the entire molecule as well as electrostatic energy components for each atom <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-calcenergy\" target=\"_blank\"><font title=\"comps\">(<span class=\"tooltip\">?</span>)</font></a>.</li>
992
993    </ul></blockquote>
994
995
996                <ul><li>Calculation of electrostatic and apolar force outputs from a PBE calculation <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-calcforce\" target=\"_blank\"><font title=\"calcforce\">(<span class=\"tooltip\">?</span>)</font></a>:</li></ul>"""
997
998
999    print "<blockquote><ul>"
1000    print "<li><input type=\"radio\" name=\"calcforce\" value=\"no\""
1001    if initVars['calculationForce'] == "no":
1002        print "checked=\"checked\""
1003
1004    print """/> Don\'t calculate any forces <a href=\"href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-calcforce\" target=\"_blank\"><font title=\"no\">(<span class=\"tooltip\">?</span>)</font></a>.</li>"""
1005
1006    print "<li><input type=\"radio\" name=\"calcforce\" value=\"total\""
1007    if initVars['calculationForce'] == "total":
1008        print "checked=\"checked\""
1009
1010    print """/> Calculate and return total electrostatic and apolar forces for the entire molecule <a href=\"href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-calcforce\" target=\"_blank\"><font title=\"total\">(<span class=\"tooltip\">?</span>)</font></a>.</li>"""
1011
1012    print "<li><input type=\"radio\" name=\"calcforce\" value=\"comps\""
1013    if initVars['calculationForce'] == "comps":
1014        print "checked=\"checked\""
1015
1016    print """/> Calculate and return total electrostatic and apolar forces for the entire molecule as well as force components for each atom <a href=\"href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-calcforce\" target=\"_blank\"><font title=\"comps\">(<span class=\"tooltip\">?</span>)</font></a>.</li>
1017    </ul> </blockquote>"""
1018
1019    print """
1020
1021                <ul><li>Output of scalar data calculated during the PB run <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-write\" target=\"_blank\"><font title=\"write\">(<span class=\"tooltip\">?</span>)</font></a>:</li></ul>"""
1022
1023
1024    print "<blockquote><ul>"
1025    print "<li><input type=\"checkbox\" name=\"writecharge\""
1026    if initVars['writeBiomolecularChargeDistribution']:
1027        print "checked=\"checked\""
1028
1029    print """/> Write out the biomolecular charge distribution in units of e<sub>c</sub> (multigrid only) <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-write\" target=\"_blank\"><font title=\"charge\">(<span class=\"tooltip\">?</span>)</font></a>.</li>"""
1030
1031
1032    print "<li><input type=\"checkbox\" name=\"writepot\""
1033    if initVars['writeElectrostaticPotential']:
1034        print "checked=\"checked\""
1035
1036    print """/> Write out the electrostatic potential in units of k<sub>b</sub>T/e<sub>c</sub>  (multigrid and finite element) <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-write\" target=\"_blank\"><font title=\"pot\">(<span class=\"tooltip\">?</span>)</font></a>.</li>"""
1037
1038
1039    print "<li><input type=\"checkbox\" name=\"writesmol\""
1040    if initVars['writeMolecularSurfaceSolventAccessibility']:
1041        print "checked=\"checked\""
1042
1043    print """/> Write out the solvent accessibility defined by the molecular surface definition <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-write\" target=\"_blank\"><font title=\"smol\">(<span class=\"tooltip\">?</span>)</font></a>.</li>"""
1044
1045
1046    print "<li><input type=\"checkbox\" name=\"writesspl\""
1047    if initVars['writeSplineBasedSolventAccessibility']:
1048        print "checked=\"checked\""
1049
1050    print """/> Write out the spline-based solvent accessibility <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-write\" target=\"_blank\"><font title=\"sspl\">(<span class=\"tooltip\">?</span>)</font></a>.</li>"""
1051
1052
1053    print "<li><input type=\"checkbox\" name=\"writevdw\""
1054    if initVars['writeVanDerWaalsSolventAccessibility']:
1055        print "checked=\"checked\""
1056
1057    print """/> Write out the van der Waals-based solvent accessibility <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-write\" target=\"blank\"><font title=\"vdw\">(<span class=\"tooltip\">?</span>)</font></a>.</li>"""
1058
1059
1060    print "<li><input type=\"checkbox\" name=\"writeivdw\""
1061    if initVars['writeInflatedVanDerWaalsIonAccessibility']:
1062        print "checked=\"checked\""
1063
1064    print """/> Write out the inflated van der Waals-based ion accessibility <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-write\" target=\"_blank\"><font title=\"ivdw\">(<span class=\"tooltip\">?</span>)</font></a>.</li>"""
1065
1066
1067    print "<li><input type=\"checkbox\" name=\"writelap\""
1068    if initVars['writePotentialLaplacian']:
1069        print "checked=\"checked\""
1070
1071    print """/> Write out the Laplacian of the potential in units of k<sub>B</sub>T/e<sub>c</sub>/A<sup>2</sup> (multigrid only) <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-write\" target=\"_blank\"><font title=\"lap\">(<span class=\"tooltip\">?</span>)</font></a>.</li>"""
1072
1073
1074    print "<li><input type=\"checkbox\" name=\"writeedens\""
1075    if initVars['writeEnergyDensity']:
1076        print "checked=\"checked\""
1077
1078    print """/> Write out the \"energy density\" in units of k<sub>B</sub>T/e<sub>c</sub>/A<sup>2</sup> (multigrid only) <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-write\" target=\"_blank\"><font title=\"edens\">(<span class=\"tooltip\">?</span>)</font></a>.</li>"""
1079
1080
1081    print "<li><input type=\"checkbox\" name=\"writendens\""
1082    if initVars['writeMobileIonNumberDensity']:
1083        print "checked=\"checked\""
1084
1085    print """/> Write out the mobile ion number density for <i>m</i> ion species in units of M (multigrid only) <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-write\" target=\"_blank\"><font title=\"ndens\">(<span class=\"tooltip\">?</span>)</font></a>.</li>"""
1086
1087
1088    print "<li><input type=\"checkbox\" name=\"writeqdens\""
1089    if initVars['writeMobileChargeDensity']:
1090        print "checked=\"checked\""
1091
1092    print """/> Write out the mobile charge density for <i>m</i> ion species in units of e<sub>c</sub> M (multigrid only) <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-write\" target=\"_blank\"><font title=\"qdens\">(<span class=\"tooltip\">?</span>)</font></a>.</li>"""
1093
1094
1095    print "<li><input type=\"checkbox\" name=\"writedielx\""
1096    if initVars['writeDielectricMapShift'][0]:
1097        print "checked=\"checked\""
1098
1099    print """/> Write out the dielectric map shifted by <sup>1</sup>/<sub>2</sub> grid spacing in the x-direction <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-write\" target=\"_blank\"><font title=\"dielx\">(<span class=\"tooltip\">?</span>)</font></a>.</li>"""
1100
1101
1102    print "<li><input type=\"checkbox\" name=\"writediely\""
1103    if initVars['writeDielectricMapShift'][1]:
1104        print "checked=\"checked\""
1105
1106    print """/> Write out the dielectric map shifted by <sup>1</sup>/<sub>2</sub> grid spacing in the y-direction <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-write\" target=\"_blank\"><font title=\"diely\">(<span class=\"tooltip\">?</span>)</font></a>.</li>"""
1107
1108
1109    print "<li><input type=\"checkbox\" name=\"writedielz\""
1110    if initVars['writeDielectricMapShift'][2]:
1111        print "checked=\"checked\""
1112
1113    print """/> Write out the dielectric map shifted by <sup>1</sup>/<sub>2</sub> grid spacing in the z-direction <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-write\" target=\"_blank\"><font title=\"dielz\">(<span class=\"tooltip\">?</span>)</font></a>.</li>"""
1114
1115
1116    print "<li><input type=\"checkbox\" name=\"writekappa\""
1117    if initVars['writeIonAccessibilityKappaMap']:
1118        print "checked=\"checked\""
1119
1120    print """/> Write out the ion-accessibility kappa map <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-write\" target=\"_blank\"><font title=\"kappa\">(<span class=\"tooltip\">?</span>)</font></a>.</li>
1121    </ul></blockquote>
1122
1123
1124                <ul><li>Format for writing out the data <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-write\" target=\"_blank\"><font title=\"format\">(<span class=\"tooltip\">?</span>)</font></a>:</li></ul>"""
1125
1126    print "<blockquote><ul>"
1127    print "<li><input type=\"radio\" name=\"writeformat\" value=\"dx\""
1128    if initVars['format'] == "dx":
1129        print "checked=\"checked\""
1130
1131    print """/> OpenDX (multigrid and finite element) <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-write\" target=\"_blank\"><font title=\"dx\">(<span class=\"tooltip\">?</span>)</font></a></li>"""
1132
1133    print """
1134                <li><input type=\"radio\" name=\"writeformat\" value=\"avs\" disabled=\"disabled\"/> AVS UCD (finite element only) <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-write\" target=\"_blank\"><font title=\"avs\">(<span class=\"tooltip\">?</span>)</font></a></li>
1135                <li><input type=\"radio\" name=\"writeformat\" value=\"uhbd\" disabled=\"disabled\"/> UBHD (multigrid only) <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-write\" target=\"_blank\"><font title=\"uhbd\">(<span class=\"tooltip\">?</span>)</font></a></li>
1136                </ul></blockquote>
1137            </div>"""
1138
1139
1140
1141    #print """<ul><li>Choose type of operator to output <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-writemat\" target=\"_blank\"><font title=\"type\">(<span class=\"tooltip\">?</span>)</font></a>:</li></ul>"""
1142                 #ADD PYTHON CODE ABOVE WHEN OTHER OPTIONS ARE AVAILABLE
1143
1144    #print "<blockquote><ul>"
1145    #print """           <li><input type=\"radio\" name=\"writemat\" value=\"poisson\" disabled=\"disabled\"/> Poisson <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-writemat\" target=\"_blank\"><font title=\"poisson\">(<span class=\"tooltip\">?</span>)</font></a></li>
1146                #<li><input type=\"radio\" name=\"writemat\" value=\"pot\" disabled=\"disabled\"/> Gateaux derivative of the full PBE operator evaluated at the current solution <a href=\"http://www.poissonboltzmann.org/docs/apbs-overview/#elec-keyword-writemat\" target=\"_blank\"><font title=\"pot\">(<span class=\"tooltip\">?</span>)</font></a></li>
1147                #</ul>
1148                #</blockquote>
1149
1150                #""" #ADD PYTHON CODE ABOVE WHEN OPTIONS ARE AVAILABLE
1151
1152    print "<br />"
1153    if type=="local":
1154        print "<input type=\"hidden\" name=\"hiddencheck\" value=\"local\"/>"
1155    else:
1156        print "<input type=\"hidden\" name=\"hiddencheck\" value=\"opal\"/>"
1157
1158    print "<input type=\"hidden\" name=\"pdb2pqrid\"",
1159    print "value=\"%s\"" % pdb2pqrID,
1160    print "/>"
1161
1162    print "<input type=\"hidden\" name=\"mol\" value=\"1\"/>"
1163
1164    print """
1165        </form>
1166    <p>
1167        <a href="http://validator.w3.org/check?uri=referer"><img
1168                src="http://www.w3.org/Icons/valid-xhtml10"
1169                    alt="Valid XHTML 1.0 Transitional" height="31" width="88" /></a>
1170                  </p>
1171<script type="text/javascript">
1172var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
1173document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
1174</script>
1175<script type="text/javascript">
1176try {
1177var pageTracker = _gat._getTracker("UA-11026338-3");
1178pageTracker._trackPageview();
1179} catch(err) {}</script>
1180    </body>
1181</html>
1182
1183        """
1184
1185def unpickleVars(pdb2pqrID):
1186    """ Converts instance pickle from PDB2PQR into a dictionary for APBS """
1187    apbsOptions = {}
1188    #pfile = open("/home/samir/public_html/pdb2pqr/tmp/%s-input.p" % pdb2pqrID, 'r')
1189    pfile = open("%s%s%s/%s-input.p" % (INSTALLDIR, TMPDIR, pdb2pqrID, pdb2pqrID), 'r')
1190    inputObj = pickle.load(pfile)
1191    pfile.close()
1192    myElec = inputObj.elecs[0]
1193
1194    apbsOptions['pqrname'] = pdb2pqrID+'.pqr'
1195    apbsOptions['pdbID'] = inputObj.pqrname[:-4]
1196
1197    if myElec.cgcent[0:3] == "mol":
1198        apbsOptions['coarseGridCenterMethod'] = "molecule"
1199        apbsOptions['coarseGridCenterMoleculeID'] = locale.atoi(myElec.cgcent[4:])
1200    else:
1201        apbsOptions['coarseGridCenterMethod'] = "coordinate"
1202        apbsOptions['coarseGridCenter'] = myElec.cgcent
1203
1204    if myElec.fgcent[0:3] == "mol":
1205        apbsOptions['fineGridCenterMethod'] = "molecule"
1206        apbsOptions['fineGridCenterMoleculeID'] = locale.atoi(myElec.fgcent[4:])
1207    else:
1208        apbsOptions['fineGridCenterMethod'] = "coordinate"
1209        apbsOptions['fineGridCenter'] = myElec.fgcent
1210
1211    if myElec.gcent[0:3] == "mol":
1212        apbsOptions['gridCenterMethod'] = "molecule"
1213        apbsOptions['gridCenterMoleculeID'] = locale.atoi(myElec.gcent[4:])
1214    else:
1215        apbsOptions['gridCenterMethod'] = "coordinate"
1216        apbsOptions['gridCenter'] = myElec.gcent
1217
1218
1219    if myElec.lpbe == 1:
1220        apbsOptions['solveType'] = 'linearized'
1221    elif myElec.npbe == 1:
1222        apbsOptions['solveType'] = 'nonlinearized'
1223
1224    #TODO: Currently this is not used.
1225    if len(myElec.ion) == 0:
1226        apbsOptions['mobileIonSpecies[0]'] = None
1227    else:
1228        apbsOptions['mobileIonSpecies[1]'] = myElec.ion
1229
1230    if len(myElec.write) <= 1:
1231        apbsOptions['format'] = 'dx'
1232    else:
1233        apbsOptions['format'] = myElec.write[1]
1234
1235    apbsOptions['calculationType'] = myElec.method
1236    apbsOptions['dime'] = myElec.dime
1237    apbsOptions['pdime'] = myElec.pdime
1238    apbsOptions['async'] = myElec.async
1239    apbsOptions['asyncflag'] = myElec.asyncflag
1240    apbsOptions['nlev'] = myElec.nlev
1241    apbsOptions['glen'] = myElec.glen
1242    apbsOptions['coarseGridLength'] = myElec.cglen
1243    apbsOptions['fineGridLength'] = myElec.fglen
1244    apbsOptions['molecule'] = myElec.mol
1245    apbsOptions['boundaryConditions'] = myElec.bcfl
1246    apbsOptions['biomolecularDielectricConstant'] = myElec.pdie
1247    apbsOptions['dielectricSolventConstant'] = myElec.sdie
1248    apbsOptions['biomolecularPointChargeMapMethod'] = myElec.chgm
1249    apbsOptions['surfaceConstructionResolution'] = myElec.sdens
1250    apbsOptions['dielectricIonAccessibilityModel'] = myElec.srfm
1251    apbsOptions['solventRadius'] = myElec.srad
1252    apbsOptions['surfaceDefSupportSize'] = myElec.swin
1253    apbsOptions['temperature'] = myElec.temp
1254    apbsOptions['calculationEnergy'] = myElec.calcenergy
1255    apbsOptions['calculationForce'] = myElec.calcforce
1256    apbsOptions['processorMeshOverlap'] = myElec.ofrac
1257    apbsOptions['writeBiomolecularChargeDistribution'] = False
1258    apbsOptions['writeElectrostaticPotential'] = True
1259    apbsOptions['writeMolecularSurfaceSolventAccessibility'] = False
1260    apbsOptions['writeSplineBasedSolventAccessibility'] = False
1261    apbsOptions['writeVanDerWaalsSolventAccessibility'] = False
1262    apbsOptions['writeInflatedVanDerWaalsIonAccessibility'] = False
1263    apbsOptions['writePotentialLaplacian'] = False
1264    apbsOptions['writeEnergyDensity'] = False
1265    apbsOptions['writeMobileIonNumberDensity'] = False
1266    apbsOptions['writeMobileChargeDensity'] = False
1267    apbsOptions['writeDielectricMapShift'] = [False,False,False]
1268    apbsOptions['writeIonAccessibilityKappaMap'] = False
1269
1270    return apbsOptions
1271
1272def fieldStorageToDict(form):
1273    """ Converts the CGI input from the web interface to a dictionary """
1274    apbsOptions = {'writeCheck':0}
1275
1276    if form.has_key("writecharge") and form["writecharge"].value != "":
1277        apbsOptions['writeCheck'] += 1
1278        apbsOptions['writeCharge'] = True
1279    else:
1280        apbsOptions['writeCharge'] = False
1281
1282    if form.has_key("writepot") and form["writepot"].value != "":
1283        apbsOptions['writeCheck'] += 1
1284        apbsOptions['writePot'] = True
1285    else:
1286        apbsOptions['writePot'] = False
1287
1288    if form.has_key("writesmol") and form["writesmol"].value == "on":
1289        apbsOptions['writeCheck'] += 1
1290        apbsOptions['writeSmol'] = True
1291    else:
1292        apbsOptions['writeSmol'] = False
1293
1294    if form.has_key("asyncflag") and form["asyncflag"].value == "on":
1295        apbsOptions['async'] = locale.atoi(form["async"].value)
1296        apbsOptions['asyncflag'] = True
1297    else:
1298        apbsOptions['asyncflag'] = False
1299
1300    if form.has_key("writesspl") and form["writesspl"].value == "on":
1301        apbsOptions['writeCheck'] += 1
1302        apbsOptions['writeSspl'] = True
1303    else:
1304        apbsOptions['writeSspl'] = False
1305
1306    if form.has_key("writevdw") and form["writevdw"].value == "on":
1307        apbsOptions['writeCheck'] += 1
1308        apbsOptions['writeVdw'] = True
1309    else:
1310        apbsOptions['writeVdw'] = False
1311
1312    if form.has_key("writeivdw") and form["writeivdw"].value == "on":
1313        apbsOptions['writeCheck'] += 1
1314        apbsOptions['writeIvdw'] = True
1315    else:
1316        apbsOptions['writeIvdw'] = False
1317
1318    if form.has_key("writelap") and form["writelap"].value == "on":
1319        apbsOptions['writeCheck'] += 1
1320        apbsOptions['writeLap'] = True
1321    else:
1322        apbsOptions['writeLap'] = False
1323
1324    if form.has_key("writeedens") and form["writeedens"].value == "on":
1325        apbsOptions['writeCheck'] += 1
1326        apbsOptions['writeEdens'] = True
1327    else:
1328        apbsOptions['writeEdens'] = False
1329
1330    if form.has_key("writendens") and form["writendens"].value == "on":
1331        apbsOptions['writeCheck'] += 1
1332        apbsOptions['writeNdens'] = True
1333    else:
1334        apbsOptions['writeNdens'] = False
1335
1336    if form.has_key("writeqdens") and form["writeqdens"].value == "on":
1337        apbsOptions['writeCheck'] += 1
1338        apbsOptions['writeQdens'] = True
1339    else:
1340        apbsOptions['writeQdens'] = False
1341
1342    if form.has_key("writedielx") and form["writedielx"].value == "on":
1343        apbsOptions['writeCheck'] += 1
1344        apbsOptions['writeDielx'] = True
1345    else:
1346        apbsOptions['writeDielx'] = False
1347
1348    if form.has_key("writediely") and form["writediely"].value == "on":
1349        apbsOptions['writeCheck'] += 1
1350        apbsOptions['writeDiely'] = True
1351    else:
1352        apbsOptions['writeDiely'] = False
1353
1354    if form.has_key("writedielz") and form["writedielz"].value == "on":
1355        apbsOptions['writeCheck'] += 1
1356        apbsOptions['writeDielz'] = True
1357    else:
1358        apbsOptions['writeDielz'] = False
1359
1360    if form.has_key("writekappa") and form["writekappa"].value == "on":
1361        apbsOptions['writeCheck'] += 1
1362        apbsOptions['writeKappa'] = True
1363    else:
1364        apbsOptions['writeKappa'] = False
1365
1366    if apbsOptions['writeCheck'] > 4:
1367        print "Please select a maximum of four write statements."
1368        os._exit(99)
1369
1370    # READ section variables
1371    apbsOptions['readType'] = "mol"
1372    apbsOptions['readFormat'] = "pqr"
1373    apbsOptions['pqrPath'] = ""
1374    apbsOptions['pqrFileName'] = form['pdb2pqrid'].value+'.pqr'
1375
1376    #ELEC section variables
1377    apbsOptions['calcType'] = form["type"].value
1378
1379    apbsOptions['ofrac'] = locale.atof(form["ofrac"].value)
1380
1381    apbsOptions['dimeNX'] = locale.atoi(form["dimenx"].value)
1382    apbsOptions['dimeNY'] = locale.atoi(form["dimeny"].value)
1383    apbsOptions['dimeNZ'] = locale.atoi(form["dimenz"].value)
1384
1385    apbsOptions['cglenX'] = locale.atof(form["cglenx"].value)
1386    apbsOptions['cglenY'] = locale.atof(form["cgleny"].value)
1387    apbsOptions['cglenZ'] = locale.atof(form["cglenz"].value)
1388
1389    apbsOptions['fglenX'] = locale.atof(form["fglenx"].value)
1390    apbsOptions['fglenY'] = locale.atof(form["fgleny"].value)
1391    apbsOptions['fglenZ'] = locale.atof(form["fglenz"].value)
1392
1393    apbsOptions['glenX'] = locale.atof(form["glenx"].value)
1394    apbsOptions['glenY'] = locale.atof(form["gleny"].value)
1395    apbsOptions['glenZ'] = locale.atof(form["glenz"].value)
1396
1397    apbsOptions['pdimeNX'] = locale.atof(form["pdimex"].value)
1398    apbsOptions['pdimeNY'] = locale.atof(form["pdimey"].value)
1399    apbsOptions['pdimeNZ'] = locale.atof(form["pdimez"].value)
1400
1401    if form["cgcent"].value == "mol":
1402        apbsOptions['coarseGridCenterMethod'] = "molecule"
1403        apbsOptions['coarseGridCenterMoleculeID'] = locale.atoi(form["cgcentid"].value)
1404
1405    elif form["cgcent"].value == "coord":
1406        apbsOptions['coarseGridCenterMethod'] = "coordinate"
1407        apbsOptions['cgxCent'] = locale.atoi(form["cgxcent"].value)
1408        apbsOptions['cgyCent'] = locale.atoi(form["cgycent"].value)
1409        apbsOptions['cgzCent'] = locale.atoi(form["cgzcent"].value)
1410
1411    if form["fgcent"].value == "mol":
1412        apbsOptions['fineGridCenterMethod'] = "molecule"
1413        apbsOptions['fineGridCenterMoleculeID'] = locale.atoi(form["fgcentid"].value)
1414    elif form["fgcent"].value == "coord":
1415        apbsOptions['fineGridCenterMethod'] = "coordinate"
1416        apbsOptions['fgxCent'] = locale.atoi(form["fgxcent"].value)
1417        apbsOptions['fgyCent'] = locale.atoi(form["fgycent"].value)
1418        apbsOptions['fgzCent'] = locale.atoi(form["fgzcent"].value)
1419
1420    if form["gcent"].value == "mol":
1421        apbsOptions['gridCenterMethod'] = "molecule"
1422        apbsOptions['gridCenterMoleculeID'] = locale.atoi(form["gcentid"].value)
1423    elif form["gcent"].value == "coord":
1424        apbsOptions['gridCenterMethod'] = "coordinate"
1425        apbsOptions['gxCent'] = locale.atoi(form["gxcent"].value)
1426        apbsOptions['gyCent'] = locale.atoi(form["gycent"].value)
1427        apbsOptions['gzCent'] = locale.atoi(form["gzcent"].value)
1428
1429
1430    apbsOptions['mol'] = locale.atoi(form["mol"].value)
1431    apbsOptions['solveType'] = form["solvetype"].value
1432    apbsOptions['boundaryConditions'] = form["bcfl"].value
1433    apbsOptions['biomolecularDielectricConstant'] = locale.atof(form["pdie"].value)
1434    apbsOptions['dielectricSolventConstant'] = locale.atof(form["sdie"].value)
1435    apbsOptions['dielectricIonAccessibilityModel'] = form["srfm"].value
1436    apbsOptions['biomolecularPointChargeMapMethod'] = form["chgm"].value
1437    apbsOptions['surfaceConstructionResolution'] = locale.atof(form["sdens"].value)
1438    apbsOptions['solventRadius'] = locale.atof(form["srad"].value)
1439    apbsOptions['surfaceDefSupportSize'] = locale.atof(form["swin"].value)
1440    apbsOptions['temperature'] = locale.atof(form["temp"].value)
1441    apbsOptions['calcEnergy'] = form["calcenergy"].value
1442    apbsOptions['calcForce'] = form["calcforce"].value
1443
1444    for i in range(0,3):
1445        chStr = 'charge%i' % i
1446        concStr = 'conc%i' % i
1447        radStr = 'radius%i' % i
1448        if form[chStr].value != "":
1449            apbsOptions[chStr] = locale.atoi(form[chStr].value)
1450        if form[concStr].value != "":
1451            apbsOptions[concStr] = locale.atof(form[concStr].value)
1452        if form[radStr].value != "":
1453            apbsOptions[radStr] = locale.atof(form[radStr].value)
1454    apbsOptions['writeFormat'] = form["writeformat"].value
1455    #apbsOptions['writeStem'] = apbsOptions['pqrFileName'][:-4]
1456    apbsOptions['writeStem'] = form["pdb2pqrid"].value
1457
1458
1459    return apbsOptions
1460
1461
1462def pqrFileCreator(apbsOptions):
1463    """
1464        Creates a pqr file, using the data from the form
1465    """
1466    apbsOptions['tmpDirName'] = "%s%s%s/" % (INSTALLDIR, TMPDIR, apbsOptions['writeStem'])
1467    try:
1468        os.makedirs(apbsOptions['tmpDirName'])
1469    except OSError, err:
1470        if err.errno == errno.EEXIST:
1471            if os.path.isdir(apbsOptions['tmpDirName']):
1472                # print "Error (tmp directory already exists) - please try again"
1473                pass
1474            else:
1475                print "Error (file exists where tmp dir should be) - please try again"
1476                raise
1477        else:
1478            raise
1479
1480    apbsOptions['tempFile'] = "apbsinput.in"
1481    apbsOptions['tab'] = "    " # 4 spaces - used for writing to file
1482    input = open('%s/tmp/%s/%s' % (INSTALLDIR, apbsOptions['writeStem'], apbsOptions['tempFile']), 'w')
1483
1484
1485    # writing READ section to file
1486    input.write('read\n')
1487    input.write('%s%s %s %s%s' % (apbsOptions['tab'], apbsOptions['readType'], apbsOptions['readFormat'], apbsOptions['pqrPath'], apbsOptions['pqrFileName']))
1488    input.write('\nend\n')
1489
1490    # writing ELEC section to file
1491    input.write('elec\n')
1492    input.write('%s%s\n' % (apbsOptions['tab'], apbsOptions['calcType']))
1493    if apbsOptions['calcType']!="fe-manual":
1494        input.write('%sdime %d %d %d\n' % (apbsOptions['tab'], apbsOptions['dimeNX'], apbsOptions['dimeNY'], apbsOptions['dimeNZ']))
1495    if apbsOptions['calcType'] == "mg-para":
1496        input.write('%spdime %d %d %d\n' % (apbsOptions['tab'], apbsOptions['pdimeNX'], apbsOptions['pdimeNY'], apbsOptions['pdimeNZ']))
1497        input.write('%sofrac %g\n' % (apbsOptions['tab'], apbsOptions['ofrac']))
1498        if apbsOptions['asyncflag']:
1499            input.write('%sasync %d\n' % (apbsOptions['tab'], apbsOptions['async']))
1500
1501    if apbsOptions['calcType'] == "mg-manual":
1502        input.write('%sglen %g %g %g\n' % (apbsOptions['tab'], apbsOptions['glenX'], apbsOptions['glenY'], apbsOptions['glenZ']))
1503    if apbsOptions['calcType'] in ['mg-auto','mg-para','mg-dummy']:
1504        input.write('%scglen %g %g %g\n' % (apbsOptions['tab'], apbsOptions['cglenX'], apbsOptions['cglenY'], apbsOptions['cglenZ']))
1505    if apbsOptions['calcType'] in ['mg-auto','mg-para']:
1506        input.write('%sfglen %g %g %g\n' % (apbsOptions['tab'], apbsOptions['fglenX'], apbsOptions['fglenY'], apbsOptions['fglenZ']))
1507
1508        if apbsOptions['coarseGridCenterMethod']=='molecule':
1509            input.write('%scgcent mol %d\n' % (apbsOptions['tab'], apbsOptions['coarseGridCenterMoleculeID'] ))
1510        elif apbsOptions['coarseGridCenterMethod']=='coordinate':
1511            input.write('%scgcent %d %d %d\n' % (apbsOptions['tab'], apbsOptions['cgxCent'], apbsOptions['cgyCent'], apbsOptions['cgzCent']))
1512
1513        if apbsOptions['fineGridCenterMethod']=='molecule':
1514            input.write('%sfgcent mol %d\n' % (apbsOptions['tab'], apbsOptions['fineGridCenterMoleculeID']))
1515        elif apbsOptions['fineGridCenterMethod']=='coordinate':
1516            input.write('%sfgcent %d %d %d\n' % (apbsOptions['tab'], apbsOptions['fgxCent'], apbsOptions['fgyCent'], apbsOptions['fgzCent']))
1517
1518    if apbsOptions['calcType'] in ['mg-manual','mg-dummy']:
1519        if apbsOptions['gridCenterMethod']=='molecule':
1520            input.write('%sgcent mol %d\n' % (apbsOptions['tab'], apbsOptions['gridCenterMoleculeID'] ))
1521        elif apbsOptions['gridCenterMethod']=='coordinate':
1522            input.write('%sgcent %d %d %d\n' % (apbsOptions['tab'], apbsOptions['gxCent'], apbsOptions['gyCent'], apbsOptions['gzCent']))
1523
1524    input.write('%smol %d\n' % (apbsOptions['tab'], apbsOptions['mol']))
1525    input.write('%s%s\n' % (apbsOptions['tab'], apbsOptions['solveType']))
1526    input.write('%sbcfl %s\n' % (apbsOptions['tab'], apbsOptions['boundaryConditions']))
1527    input.write('%spdie %g\n' % (apbsOptions['tab'], apbsOptions['biomolecularDielectricConstant']))
1528    input.write('%ssdie %g\n' % (apbsOptions['tab'], apbsOptions['dielectricSolventConstant']))
1529    input.write('%ssrfm %s\n' % (apbsOptions['tab'], apbsOptions['dielectricIonAccessibilityModel']))
1530    input.write('%schgm %s\n' % (apbsOptions['tab'], apbsOptions['biomolecularPointChargeMapMethod']))
1531    input.write('%ssdens %g\n' % (apbsOptions['tab'], apbsOptions['surfaceConstructionResolution']))
1532    input.write('%ssrad %g\n' % (apbsOptions['tab'], apbsOptions['solventRadius']))
1533    input.write('%sswin %g\n' % (apbsOptions['tab'], apbsOptions['surfaceDefSupportSize']))
1534    input.write('%stemp %g\n' % (apbsOptions['tab'], apbsOptions['temperature']))
1535    input.write('%scalcenergy %s\n' % (apbsOptions['tab'], apbsOptions['calcEnergy']))
1536    input.write('%scalcforce %s\n' % (apbsOptions['tab'], apbsOptions['calcForce']))
1537    for i in range(0,3):
1538        chStr = 'charge%i' % i
1539        concStr = 'conc%i' % i
1540        radStr = 'radius%i' % i
1541        if apbsOptions.has_key(chStr) and apbsOptions.has_key(concStr) and apbsOptions.has_key(radStr):
1542            #ion charge {charge} conc {conc} radius {radius}
1543            input.write('%sion charge %d conc %g radius %g\n' % (apbsOptions['tab'],
1544                                                                 apbsOptions[chStr],
1545                                                                 apbsOptions[concStr],
1546                                                                 apbsOptions[radStr]))
1547
1548    if apbsOptions['writeCharge']:
1549        input.write('%swrite charge %s %s-charge\n' % (apbsOptions['tab'], apbsOptions['writeFormat'], apbsOptions['writeStem']))
1550
1551    if apbsOptions['writePot']:
1552        input.write('%swrite pot %s %s-pot\n' % (apbsOptions['tab'], apbsOptions['writeFormat'], apbsOptions['writeStem']))
1553
1554    if apbsOptions['writeSmol']:
1555        input.write('%swrite smol %s %s-smol\n' % (apbsOptions['tab'], apbsOptions['writeFormat'], apbsOptions['writeStem']))
1556
1557    if apbsOptions['writeSspl']:
1558        input.write('%swrite sspl %s %s-sspl\n' % (apbsOptions['tab'], apbsOptions['writeFormat'],  apbsOptions['writeStem']))
1559
1560    if apbsOptions['writeVdw']:
1561        input.write('%swrite vdw %s %s-vdw\n' % (apbsOptions['tab'], apbsOptions['writeFormat'], apbsOptions['writeStem']))
1562
1563    if apbsOptions['writeIvdw']:
1564        input.write('%swrite ivdw %s %s-ivdw\n' % (apbsOptions['tab'], apbsOptions['writeFormat'], apbsOptions['writeStem']))
1565
1566    if apbsOptions['writeLap']:
1567        input.write('%swrite lap %s %s-lap\n' % (apbsOptions['tab'], apbsOptions['writeFormat'], apbsOptions['writeStem']))
1568
1569    if apbsOptions['writeEdens']:
1570        input.write('%swrite edens %s %s-edens\n' % (apbsOptions['tab'], apbsOptions['writeFormat'], apbsOptions['writeStem']))
1571
1572    if apbsOptions['writeNdens']:
1573        input.write('%swrite ndens %s %s-ndens\n' % (apbsOptions['tab'], apbsOptions['writeFormat'], apbsOptions['writeStem']))
1574
1575    if apbsOptions['writeQdens']:
1576        input.write('%swrite qdens %s %s-qdens\n' % (apbsOptions['tab'], apbsOptions['writeFormat'], apbsOptions['writeStem']))
1577
1578    if apbsOptions['writeDielx']:
1579        input.write('%swrite dielx %s %s-dielx\n' % (apbsOptions['tab'], apbsOptions['writeFormat'], apbsOptions['writeStem']))
1580
1581    if apbsOptions['writeDiely']:
1582        input.write('%swrite diely %s %s-diely\n' % (apbsOptions['tab'], apbsOptions['writeFormat'], apbsOptions['writeStem']))
1583
1584    if apbsOptions['writeDielz']:
1585        input.write('%swrite dielz %s %s-dielz\n' % (apbsOptions['tab'], apbsOptions['writeFormat'], apbsOptions['writeStem']))
1586
1587    if apbsOptions['writeKappa']:
1588        input.write('%swrite kappa %s %s-kappa\n' % (apbsOptions['tab'], apbsOptions['writeFormat'], apbsOptions['writeStem']))
1589
1590    input.write('end\n')
1591    input.write('quit')
1592    input.close()
1593
1594
1595
1596
1597
1598def convertOpalToLocal(jobid,pdb2pqrOpalJobID):
1599    """
1600        takes a remote Opal page and saves the files to a local directory
1601    """
1602    appLocator = AppServiceLocator()
1603    resp = appLocator.getAppServicePort(PDB2PQR_OPAL_URL).getOutputs(getOutputsRequest(pdb2pqrOpalJobID))
1604
1605    # returns the variable to prepend the files
1606    #sys.path.append('/home/samir/public_html/pdb2pqr/src') # HARDCODED
1607    #from src import server
1608    #logTime = setID(time.time())
1609    #os.makedirs('%s%s%s' % (INSTALLDIR, TMPDIR, logTime))
1610    for file in resp._outputFile:
1611        fileName = file._name
1612        if fileName!="Standard Output" and fileName!="Standard Error":
1613            if fileName.rfind('-') != -1:
1614                fileName = jobid+fileName[fileName.rfind('-'):]
1615            elif fileName.rfind('.') != -1:
1616                fileName = jobid+fileName[fileName.rfind('.'):]
1617            urllib.urlretrieve(file._url, '%s%s%s/%s' % (INSTALLDIR, TMPDIR, jobid, fileName)) # HARDCODED
1618
1619def redirector(logTime):
1620    if (str(logTime) != "False") and (str(logTime) != "notenoughmem"):
1621        startLogFile(logTime, 'apbs_start_time', str(time.time()))
1622        resetLogFile(logTime, 'apbs_end_time')
1623#        starttimefile = open('%s%s%s/apbs_start_time' % (INSTALLDIR, TMPDIR, logTime), 'w')
1624#        starttimefile.write(str(time.time()))
1625#        starttimefile.close()
1626
1627    redirectWait = 3
1628
1629    redirectURL = "{website}querystatus.cgi?jobid={jobid}&calctype=apbs".format(website=WEBSITE,
1630                                                                                jobid=logTime)
1631
1632    string = """
1633<html>
1634    <head>
1635        {trackingscript}
1636		<link rel="stylesheet" href="css/foundation.css">
1637        <script type="text/javascript">
1638            {trackingevents}
1639        </script>
1640        <link rel="stylesheet" href="@website@pdb2pqr.css" type="text/css">
1641        <meta http-equiv="refresh" content="{wait};url={redirectURL}"/>
1642    </head>
1643    <body>
1644        <center> You are being automatically redirected to a new location.<br/>
1645        If your browser does not redirect you in {wait} seconds, or you do
1646        not wish to wait, <a href="{redirectURL}">click here</a> </center>.
1647    </body>
1648</html>""".format(trackingscript=getTrackingScriptString(jobid=logTime),
1649                  trackingevents = getEventTrackingString(category='apbs',
1650                                                          action='submission',
1651                                                          label=str(os.environ["REMOTE_ADDR"])),
1652                  redirectURL=redirectURL, wait=redirectWait)
1653    return string
1654
1655def mainInput() :
1656    """
1657        Main function
1658    """
1659    global have_opal
1660    file = stdout
1661    file.write("Content-type: text/html; charset=utf-8\n\n")
1662    cgitb.enable()
1663
1664    # Check cgi.FieldStorage() for checkbox indicating whether we were invoked frmo the form or from the URL
1665    form = cgi.FieldStorage()
1666
1667    firstRun = True
1668    pdb2pqrOpalChecked = False
1669    pdb2pqrChecked = False
1670
1671    if form.has_key("jobid"): # means it's not the first run
1672        firstRun = False
1673        if HAVE_PDB2PQR_OPAL:
1674            pdb2pqrOpalJobIDFile = open('%s%s%s/pdb2pqr_opal_job_id' % (INSTALLDIR, TMPDIR, form["jobid"].value))
1675            pdb2pqrOpalJobID = pdb2pqrOpalJobIDFile.read()
1676            pdb2pqrOpalJobIDFile.close()
1677            pdb2pqrID = form["jobid"].value
1678            logTime = form["jobid"].value
1679            convertOpalToLocal(form["jobid"].value, pdb2pqrOpalJobID)
1680            pdb2pqrOpalChecked = True
1681            pdb2pqrChecked = False
1682        else:
1683            pdb2pqrID = form["jobid"].value
1684            logTime = pdb2pqrID
1685            pdb2pqrChecked = True
1686            pdb2pqrOpalChecked = False
1687
1688    if form.has_key("hiddencheck"): # means this time apbs must be run
1689        firstRun = False
1690        if form["hiddencheck"].value == "local":
1691            typeOfRun="local"
1692        elif form["hiddencheck"].value == "opal":
1693            typeOfRun="opal"
1694
1695
1696    #redirects to pdb2pqr input page
1697    if firstRun:
1698        pdb2pqrLocation = '../pdb2pqr/html/server.html'
1699        print '<html>'
1700        print '<head>'
1701        print '<link rel="stylesheet" href="@website@pdb2pqr.css" type="text/css">'
1702        print '<meta http-equiv=\"refresh\" content=\"0;url=%s\"/>' % pdb2pqrLocation
1703        print '</head>'
1704        print '<body>'
1705        print '</body>'
1706        print '</html>'
1707
1708
1709    #generates web interface and displays it
1710    elif pdb2pqrChecked:
1711        initVars = unpickleVars(pdb2pqrID)
1712
1713        generateForm(file, initVars, pdb2pqrID, "local")
1714
1715    elif pdb2pqrOpalChecked:
1716        initVars = unpickleVars(pdb2pqrID)
1717
1718        generateForm(file, initVars, pdb2pqrID, "opal")
1719
1720    #runs apbs
1721    else:
1722        # logTime stores the prefix of the names for all the data files for a run
1723        logTime = form["pdb2pqrid"].value
1724
1725        tempPage = "results.html"
1726
1727        apbsOptions = fieldStorageToDict(form)
1728        pqrFileCreator(apbsOptions)
1729        if APBS_OPAL_URL == "":
1730            have_opal = False
1731        else:
1732            have_opal = True
1733
1734        aoFile = open('%s%s%s/%s-ao' % (INSTALLDIR, TMPDIR, logTime, logTime),'w')
1735        pickle.dump(apbsOptions, aoFile)
1736        aoFile.close()
1737
1738        if have_opal:
1739            apbsOpalJobID = apbsOpalExec(logTime, form, apbsOptions)
1740
1741            # if the version number doesn't match, apbsOpalExec returns False
1742            if(str(apbsOpalJobID) == 'False'):
1743                print redirector(False)
1744
1745            # Check if not enough memory
1746            elif(str(apbsOpalJobID) == 'notenoughmem'):
1747                print redirector('notenoughmem')
1748            else:
1749                print redirector(logTime)
1750
1751            startLogFile(logTime, 'apbs_opal_job_id', apbsOpalJobID)
1752#            apbsOpalJobIDFile = open('%s%s%s/apbs_opal_job_id' % (INSTALLDIR, TMPDIR, logTime),'w')
1753#            apbsOpalJobIDFile.write(apbsOpalJobID)
1754#            apbsOpalJobIDFile.close()
1755        else:
1756            apbsExec(logTime, form, apbsOptions)
1757
1758
1759if __name__ == "__main__" and os.environ.has_key("REQUEST_METHOD"):
1760    """ Determine if called from command line or CGI """
1761
1762    if APBS_OPAL_URL!="" or HAVE_PDB2PQR_OPAL:
1763        have_opal = True
1764        from AppService_client import queryStatusRequest
1765        from AppService_client import AppServiceLocator, queryStatusRequest, getOutputsRequest
1766    else:
1767        have_opal = False
1768    mainInput()
1769