def usage(): """ Display the usage information for this script """ size = Pz.Psize() usage = "\n" usage = usage + "Use this script to generate new APBS input files or split an existing\n" usage = usage + "parallel input file into multiple async files.\n\n" usage = usage + "Usage: inputgen.py [opts] <filename>\n" usage = usage + "Optional Arguments:\n" usage = usage + " --help : Display this text\n" usage = usage + " --split : Split an existing parallel input file to multiple\n" usage = usage + " async input files.\n" usage = usage + " --potdx : Create an input to compute an electrostatic potential map.\n" usage = usage + " --method=<value> : Force output file to write a specific APBS ELEC\n" usage = usage + " method. Options are para (parallel), auto\n" usage = usage + " (automatic), manual (manual), or async (asynchronous).\n" usage = usage + " solve. async will result in multiple input files.\n" usage = usage + " --cfac=<value> : Factor by which to expand molecular dimensions to\n" usage = usage + " get coarse grid dimensions.\n" usage = usage + " [default = %g]\n" % size.getConstant( "cfac") usage = usage + " --fadd=<value> : Amount to add to molecular dimensions to get fine\n" usage = usage + " grid dimensions.\n" usage = usage + " [default = %g]\n" % size.getConstant( "fadd") usage = usage + " --space=<value> : Desired fine mesh resolution\n" usage = usage + " [default = %g]\n" % size.getConstant( "space") usage = usage + " --gmemfac=<value> : Number of bytes per grid point required\n" usage = usage + " for sequential MG calculation\n" usage = usage + " [default = %g]\n" % size.getConstant( "gmemfac") usage = usage + " --gmemceil=<value> : Max MB allowed for sequential MG\n" usage = usage + " calculation. Adjust this to force the\n" usage = usage + " script to perform faster calculations (which\n" usage = usage + " require more parallelism).\n" usage = usage + " [default = %g]\n" % size.getConstant( "gmemceil") usage = usage + " --ofrac=<value> : Overlap factor between mesh partitions\n" usage = usage + " [default = %g]\n" % size.getConstant( "ofrac") usage = usage + " --redfac=<value> : The maximum factor by which a domain\n" usage = usage + " dimension can be reduced during focusing\n" usage = usage + " [default = %g]\n" % size.getConstant( "redfac") usage = usage + " --istrng=<value> : Ionic strength (M). Na+ anc Cl- ions will be used\n" sys.stderr.write(usage) sys.exit(2)
def mainCommand(argv): """ Main driver for running program from the command line. """ fieldNames = ('amber','charmm','parse', 'ty106','peopb','swanson') validForcefields = [] validForcefields.extend(fieldNames) validForcefields.extend((x.upper() for x in fieldNames)) description = 'This module takes a PDB file as input and performs ' +\ 'optimizations before yielding a new PQR-style file in PQR_OUTPUT_PATH.\n' +\ 'If PDB_PATH is an ID it will automatically be obtained from the PDB archive.' usage = 'Usage: %prog [options] PDB_PATH PQR_OUTPUT_PATH' parser = OptionParser(description=description, usage=usage, version='%prog (Version ' + __version__ + ')') group = OptionGroup(parser,"Manditory options", "One of the following options must be used.") group.add_option('--ff', dest='ff', metavar='FIELD_NAME', choices=validForcefields, help='The forcefield to use - currently amber, ' + 'charmm, parse, tyl06, peoepb and swanson ' + 'are supported.') group.add_option('--userff', dest='userff', metavar='USER_FIELD_FILE', help='The user created forcefield file to use. Requires --usernames overrides --ff') group.add_option('--clean', dest='clean', action='store_true', default=False, help='Do no optimization, atom addition, or parameter assignment, ' + 'just return the original PDB file in aligned format. ' + 'Overrides --ff and --userff') parser.add_option_group(group) group = OptionGroup(parser,"General options") group.add_option('--nodebump', dest='debump', action='store_false', default=True, help='Do not perform the debumping operation') group.add_option('--noopt', dest='opt', action='store_false', default=True, help='Do not perform hydrogen optimization') group.add_option('--chain', dest='chain', action='store_true', default=False, help='Keep the chain ID in the output PQR file') group.add_option('--assign-only', dest='assign_only', action='store_true', default=False, help='Only assign charges and radii - do not add atoms, debump, or optimize.') group.add_option('--ffout', dest='ffout', metavar='FIELD_NAME',choices=validForcefields, help='Instead of using the standard canonical naming scheme for residue and atom names, ' + 'use the names from the given forcefield - currently amber, ' + 'charmm, parse, tyl06, peoepb and swanson ' + 'are supported.') group.add_option('--usernames', dest='usernames', metavar='USER_NAME_FILE', help='The user created names file to use. Required if using --userff') group.add_option('--with-ph', dest='pH', action='store', type='float', help='Use propka to calculate pKas and apply them to the molecule given the pH value. ' + 'Actual PropKa results will be output to <output-path>.propka.') group.add_option('--apbs-input', dest='input', action='store_true', default=False, help='Create a template APBS input file based on the generated PQR file. Also creates a Python ' + 'pickle for using these parameters in other programs.') group.add_option('--ligand', dest='ligand', metavar='PATH', help='Calculate the parameters for the ligand in mol2 format at the given path. ' + 'Pdb2pka must be compiled.') group.add_option('--whitespace', dest='whitespace', action='store_true', default=False, help='Insert whitespaces between atom name and residue name, between x and y, and between y and z.') group.add_option('--typemap', dest='typemap', action='store_true', default=False, help='Create Typemap output.') group.add_option('--neutraln', dest='neutraln', action='store_true', default=False, help='Make the N-terminus of this protein neutral (default is charged). ' + 'Requires PARSE force field.') group.add_option('--neutralc', dest='neutralc', action='store_true', default=False, help='Make the C-terminus of this protein neutral (default is charged). ' + 'Requires PARSE force field.') group.add_option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Print information to stdout.') parser.add_option_group(group) extentionsGroup = extensions.setupExtensionsOptions(parser) (options, args) = parser.parse_args() if len(args) != 2: parser.error('Incorrect number (%d) of arguments!\nargv: %s, args: %s' % (len(args),argv, args)) # Append Numeric/Numpy path to sys.path if the user specified a non-standard location during configuration sys.argv=argv package_path = PACKAGE_PATH if package_path != "": sys.path.extend(package_path.split(":")) if (not options.pH is None) and (options.pH < 0.0 or options.pH > 14.0): parser.error('%i is not a valid pH! Please choose a pH between 0.0 and 14.0.' % options.pH) if options.assign_only or options.clean: options.debump = options.optflag = False userfffile = None usernamesfile = None if not options.clean: if not options.usernames is None: try: usernamesfile = open(options.usernames, 'rU') except IOError: parser.error('Unable to open user names file %s' % options.usernames) if not options.userff is None: try: userfffile = open(options.userff, 'rU') except IOError: parser.error('Unable to open user force field file %s' % options.userff) if options.usernames is None: parser.error('--usernames must be specified if using --userff') else: if options.ff is None: parser.error('One of the manditory options was not specified.\n' + 'Please specify either --ff, --userff, or --clean') if getFFfile(options.ff) == '': parser.error('Unable to find parameter files for forcefield %s!' % options.ff) if not options.ligand is None: try: options.ligand = open(options.ligand, 'rU') except IOError: parser.error('Unable to find ligand file %s!' % options.ligand) if options.neutraln and (options.ff != 'parse' or not options.userff is None): parser.error('--neutraln option only works with PARSE forcefield!') if options.neutralc and (options.ff != 'parse' or not options.userff is None): parser.error('--neutralc option only works with PARSE forcefield!') text = "\n--------------------------\n" text += "PDB2PQR - a Python-based structural conversion utility\n" text += "--------------------------\n" text += "Please cite your use of PDB2PQR as:\n" text += " Dolinsky TJ, Nielsen JE, McCammon JA, Baker NA.\n" text += " PDB2PQR: an automated pipeline for the setup, execution,\n" text += " and analysis of Poisson-Boltzmann electrostatics calculations.\n" text += " Nucleic Acids Research 32 W665-W667 (2004).\n\n" sys.stdout.write(text) path = args[0] file = getPDBFile(path) pdblist, errlist = readPDB(file) if len(pdblist) == 0 and len(errlist) == 0: #TODO: Why are we doing this? # try: # os.remove(path) # except OSError: # pass parser.error("Unable to find file %s!" % path) if len(errlist) != 0 and options.verbose: print "Warning: %s is a non-standard PDB file.\n" % path print errlist outpath = args[1] options.outname = outpath #In case no extensions were specified. if options.active_extentions is None: options.active_extentions = [] #Filter out the options specifically for extentions. #Passed into runPDB2PQR, but not used by any extention yet. extentionOpts = ExtentionOptions() if extentionsGroup is not None: for opt in extentionsGroup.option_list: if opt.dest == 'active_extentions': continue setattr(extentionOpts, opt.dest, getattr(options, opt.dest)) #TODO: The ideal would be to pass a file like object for the second # argument and get rid of the userff and username arguments to this function. # This would also do away with the redundent checks and such in # the Forcefield constructor. header, lines, missedligands = runPDB2PQR(pdblist, options.ff, outname = options.outname, ph = options.pH, verbose = options.verbose, extentions = options.active_extentions, ententionOptions = extentionOpts, clean = options.clean, neutraln = options.neutraln, neutralc = options.neutralc, ligand = options.ligand, assign_only = options.assign_only, chain = options.chain, debump = options.debump, opt = options.opt, typemap = options.typemap, userff = userfffile, usernames = usernamesfile, ffout = options.ffout) # Print the PQR file outfile = open(outpath,"w") outfile.write(header) # Adding whitespaces if --whitespace is in the options for line in lines: if options.whitespace: if line[0:4] == 'ATOM': newline = line[0:16] + ' ' + line[16:38] + ' ' + line[38:46] + ' ' + line[46:] outfile.write(newline) elif line[0:6] == 'HETATM': newline = line[0:16] + ' ' + line[16:38] + ' ' + line[38:46] + ' ' + line[46:] outfile.write(newline) else: outfile.write(line) outfile.close() if options.input: from src import inputgen from src import psize method = "mg-auto" size = psize.Psize() size.parseInput(outpath) size.runPsize(outpath) async = 0 # No async files here! input = inputgen.Input(outpath, size, method, async) input.printInputFiles() input.dumpPickle()
def upload_autofill(): EXTENSION_WHITELIST = set(['pqr']) json_response = None http_status_response = None app.config['UPLOAD_FOLDER'] = os.path.join(INSTALLDIR, TMPDIR) if request.method == 'POST': # print(dict(request.files).keys()) print(request) try: print(request.files.keys()) files = request.files['file'] if files: filename = secure_filename(files.filename) # filename = mime_type = files.content_type if files and allowed_file(files.filename, EXTENSION_WHITELIST): print("passed whitelist") new_job_id = jobutils.get_new_id() tmp_dir_path = os.path.join(INSTALLDIR, TMPDIR) job_dir_path = os.path.join(tmp_dir_path, new_job_id) upload_path = os.path.join(job_dir_path, '%s.pqr' % (new_job_id)) if not os.path.exists(job_dir_path): print("passed does_exists()") os.makedirs(job_dir_path) files.save(upload_path) # Lifted from main_cgi.py APBS handler, line 626 method = "mg-auto" size = psize.Psize() size.parseInput(upload_path) size.runPsize(upload_path) async = 0 # No async files here! myinput = inputgen.Input(upload_path, size, method, async, potdx=True) myinput.printInputFiles() myinput.dumpPickle() # return autofill(new_job_id, 'apbs') jobutils.send_to_storage_service( STORAGE_HOST, new_job_id, [ new_job_id + '.pqr', new_job_id + '.in', new_job_id + '-input.p', ], app.config['UPLOAD_FOLDER']) json_response = { 'upload_status': 'Success', 'job_id': new_job_id, } http_status_response = 201 # json_response = apbs_cgi.unpickleVars(new_job_id) else: raise Exception('File must be a PQR file') except Exception as e: # json_response = 'failed: %s' % (e) json_response = '%s' % (e) http_status_response = 500 ''' Prepare response to API request ''' response = make_response(JSONEncoder().encode(json_response)) response.headers['Content-Type'] = 'application/json' if request.method == 'OPTIONS': # json_response = 'this is OPTIONS' # print('this is OPTIONS') response = jobutils.get_request_options(response, 'POST') # response.headers['Access-Control-Allow-Headers'] = 'x-requested-with' # response.headers['Access-Control-Allow-Methods'] = 'POST' http_status_response = 204 if request.referrer: # Add origin header to response if origin is in whitelist request_origin_url = request.referrer.split('?')[0] if request_origin_url in ORIGIN_WHITELIST: print(request_origin_url) cleared_domain = request_origin_url[:request_origin_url. index('/apbs')] response.headers['Access-Control-Allow-Origin'] = cleared_domain return response, http_status_response
def mainCommand(argv): """ Main driver for running program from the command line. """ fieldNames = ('amber', 'charmm', 'parse', 'tyl06', 'peoepb', 'swanson') validForcefields = [] validForcefields.extend(fieldNames) validForcefields.extend((x.upper() for x in fieldNames)) description = 'This module takes a PDB file as input and performs ' +\ 'optimizations before yielding a new PQR-style file in PQR_OUTPUT_PATH.\n' +\ 'If PDB_PATH is an ID it will automatically be obtained from the PDB archive.' usage = 'Usage: %prog [options] PDB_PATH PQR_OUTPUT_PATH' parser = OptionParser(description=description, usage=usage, version='%prog (Version ' + __version__ + ')') group = OptionGroup(parser, "Manditory options", "One of the following options must be used.") group.add_option('--ff', dest='ff', metavar='FIELD_NAME', choices=validForcefields, help='The forcefield to use - currently amber, ' + 'charmm, parse, tyl06, peoepb and swanson ' + 'are supported.') group.add_option( '--userff', dest='userff', metavar='USER_FIELD_FILE', help= 'The user created forcefield file to use. Requires --usernames overrides --ff' ) group.add_option( '--clean', dest='clean', action='store_true', default=False, help='Do no optimization, atom addition, or parameter assignment, ' + 'just return the original PDB file in aligned format. ' + 'Overrides --ff and --userff') parser.add_option_group(group) group = OptionGroup(parser, "General options") group.add_option('--nodebump', dest='debump', action='store_false', default=True, help='Do not perform the debumping operation') group.add_option('--noopt', dest='opt', action='store_false', default=True, help='Do not perform hydrogen optimization') group.add_option('--chain', dest='chain', action='store_true', default=False, help='Keep the chain ID in the output PQR file') group.add_option( '--assign-only', dest='assign_only', action='store_true', default=False, help= 'Only assign charges and radii - do not add atoms, debump, or optimize.' ) group.add_option( '--ffout', dest='ffout', metavar='FIELD_NAME', choices=validForcefields, help= 'Instead of using the standard canonical naming scheme for residue and atom names, ' + 'use the names from the given forcefield - currently amber, ' + 'charmm, parse, tyl06, peoepb and swanson are supported.') group.add_option( '--usernames', dest='usernames', metavar='USER_NAME_FILE', help='The user created names file to use. Required if using --userff') group.add_option( '--apbs-input', dest='input', action='store_true', default=False, help= 'Create a template APBS input file based on the generated PQR file. Also creates a Python ' + 'pickle for using these parameters in other programs.') group.add_option( '--ligand', dest='ligand', metavar='PATH', help= 'Calculate the parameters for the ligand in mol2 format at the given path. ' + 'Pdb2pka must be compiled.') group.add_option( '--whitespace', dest='whitespace', action='store_true', default=False, help= 'Insert whitespaces between atom name and residue name, between x and y, and between y and z.' ) group.add_option('--typemap', dest='typemap', action='store_true', default=False, help='Create Typemap output.') group.add_option( '--neutraln', dest='neutraln', action='store_true', default=False, help='Make the N-terminus of this protein neutral (default is charged). ' 'Requires PARSE force field.') group.add_option( '--neutralc', dest='neutralc', action='store_true', default=False, help='Make the C-terminus of this protein neutral (default is charged). ' 'Requires PARSE force field.') group.add_option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Print information to stdout.') group.add_option( '--drop-water', dest='drop_water', action='store_true', default=False, help= 'Drop waters before processing protein. Currently recognized and deleted are the following water types: %s' % ', '.join(WAT.water_residue_names)) group.add_option( '--include-header', dest='include_header', action='store_true', default=False, help='Include pdb header in pqr file. ' 'WARNING: The resulting PQR file will not work with APBS versions prior to 1.5' ) parser.add_option_group(group) pka_group = OptionGroup(parser, "pH options") pka_group.add_option( '--ph-calc-method', dest='ph_calc_method', metavar='PH_METHOD', choices=('propka', 'pdb2pka'), help= 'Method used to calculate ph values. If a pH calculation method is selected, for each' ' titratable residue pH values will be calculated and the residue potentially modified' ' after comparison with the pH value supplied by --with_ph\n' 'propka - Use PROPKA to calculate pH values. Actual PROPKA results will be output to <output-path>.propka.\n' 'pdb2pka - Use PDB2PKA to calculate pH values. Requires the use of the PARSE force field.' ' Warning: Larger residues can take a very long time to run using this method. EXPERIMENTAL!' ) pka_group.add_option( '--with-ph', dest='ph', action='store', type='float', default=7.0, help= 'pH values to use when applying the results of the selected pH calculation method.' ' Defaults to %default') parser.add_option_group(pka_group) pdb2pka_group = OptionGroup(parser, "PDB2PKA method options") pdb2pka_group.add_option( '--pdb2pka-out', dest='pdb2pka_out', action='store', default='pdb2pka_output', help='Output directory for PDB2PKA results. Defaults to %default') pdb2pka_group.add_option( '--pdb2pka-resume', dest='pdb2pka_resume', action="store_true", default=False, help='Resume run from state saved in output directory.') pdb2pka_group.add_option( '--pdie', dest='pdb2pka_pdie', default=8, type='int', help='Protein dielectric constant. Defaults to %default') pdb2pka_group.add_option( '--sdie', dest='pdb2pka_sdie', default=80, type='int', help='Solvent dielectric constant. Defaults to %default') # pdb2pka_group.add_option('--maps', dest='maps', default=None, type='int', # help='<1 for using provided 3D maps; 2 for genereting new maps>') # pdb2pka_group.add_option('--xdiel', dest='xdiel', default=None, type='str', # help='<xdiel maps>') # pdb2pka_group.add_option('--ydiel', dest='ydiel', default=None, type='str', # help='<ydiel maps>') # pdb2pka_group.add_option('--zdiel', dest='zdiel', default=None, type='str', # help='<zdiel maps>') # pdb2pka_group.add_option('--kappa', dest='kappa', default=None, type='str', # help='<ion-accessibility map>') # pdb2pka_group.add_option('--smooth', dest='sd', default=None, type='float', # help='<st.dev [A] of Gaussian smooting of 3D maps at the boundary, bandthwith=3 st.dev>') # # Cut off energy for calculating non-charged-charged interaction energies # pdb2pka_group.add_option( '--pairene', dest='pdb2pka_pairene', type='float', default=1.0, help= 'Cutoff energy in kT for calculating non charged-charged interaction energies. Default: %default' ) parser.add_option_group(pdb2pka_group) propka_group = OptionGroup(parser, "PROPKA method options") propka_group.add_option( "--propka-reference", dest="propka_reference", default="neutral", choices=('neutral', 'low-pH'), help= "Setting which reference to use for stability calculations. See PROPKA 3.0 documentation." ) propka_group.add_option( '--propka-verbose', dest='propka_verbose', action='store_true', default=False, help='Print extra proPKA information to stdout. ' 'WARNING: This produces an incredible amount of output.') parser.add_option_group(propka_group) extensions.setupExtensionsOptions(parser) (options, args) = parser.parse_args(argv[1:]) commandLine = ' '.join(argv[1:]) if len(args) != 2: parser.error('Incorrect number (%d) of arguments!\nargs: %s' % (len(args), args)) if options.assign_only or options.clean: options.debump = options.optflag = False userfffile = None usernamesfile = None if not options.clean: if not options.usernames is None: try: usernamesfile = open(options.usernames, 'rU') except IOError: parser.error('Unable to open user names file %s' % options.usernames) if not options.userff is None: try: userfffile = open(options.userff, 'rU') except IOError: parser.error('Unable to open user force field file %s' % options.userff) if options.usernames is None: parser.error('--usernames must be specified if using --userff') else: if options.ff is None: parser.error( 'One of the manditory options was not specified.\n' + 'Please specify either --ff, --userff, or --clean') if getFFfile(options.ff) == '': parser.error( 'Unable to find parameter files for forcefield %s!' % options.ff) if options.ph < 0.0 or options.ph > 14.0: parser.error( '%i is not a valid pH! Please choose a pH between 0.0 and 14.0.' % options.pH) ph_calc_options = None if options.ph_calc_method == 'propka': ph_calc_options = utilities.createPropkaOptions( options.ph, verbose=options.propka_verbose, reference=options.propka_reference) if options.ph_calc_method == 'pdb2pka': if options.ff.lower() != 'parse': parser.error('PDB2PKA requires the PARSE force field.') ph_calc_options = { 'output_dir': options.pdb2pka_out, 'clean_output': not options.pdb2pka_resume, 'pdie': options.pdb2pka_pdie, 'sdie': options.pdb2pka_sdie, 'pairene': options.pdb2pka_pairene } if options.ligand is not None: try: options.ligand = open(options.ligand, 'rU') except IOError: parser.error('Unable to find ligand file %s!' % options.ligand) if options.neutraln and (options.ff is None or options.ff.lower() != 'parse'): parser.error('--neutraln option only works with PARSE forcefield!') if options.neutralc and (options.ff is None or options.ff.lower() != 'parse'): parser.error('--neutralc option only works with PARSE forcefield!') text = """ -------------------------- PDB2PQR - a Python-based structural conversion utility -------------------------- Please cite your use of PDB2PQR as: Dolinsky TJ, Nielsen JE, McCammon JA, Baker NA. PDB2PQR: an automated pipeline for the setup, execution, and analysis of Poisson-Boltzmann electrostatics calculations. Nucleic Acids Research 32 W665-W667 (2004). """ sys.stdout.write(text) path = args[0] pdbFile = getPDBFile(path) pdblist, errlist = readPDB(pdbFile) if len(pdblist) == 0 and len(errlist) == 0: parser.error("Unable to find file %s!" % path) if len(errlist) != 0 and options.verbose: print "Warning: %s is a non-standard PDB file.\n" % path print errlist outpath = args[1] options.outname = outpath #In case no extensions were specified or no extensions exist. if not hasattr(options, 'active_extensions') or options.active_extensions is None: options.active_extensions = [] #I see no point in hiding options from extensions. extensionOpts = options #TODO: The ideal would be to pass a file like object for the second # argument and add a third for names then # get rid of the userff and username arguments to this function. # This would also do away with the redundent checks and such in # the Forcefield constructor. try: header, lines, missedligands = runPDB2PQR( pdblist, options.ff, outname=options.outname, ph=options.ph, verbose=options.verbose, selectedExtensions=options.active_extensions, ph_calc_method=options.ph_calc_method, ph_calc_options=ph_calc_options, extensionOptions=extensionOpts, clean=options.clean, neutraln=options.neutraln, neutralc=options.neutralc, ligand=options.ligand, assign_only=options.assign_only, chain=options.chain, drop_water=options.drop_water, debump=options.debump, opt=options.opt, typemap=options.typemap, userff=userfffile, usernames=usernamesfile, ffout=options.ffout, commandLine=commandLine, include_old_header=options.include_header) except PDB2PQRError as er: print er sys.exit(2) # Print the PQR file outfile = open(outpath, "w") outfile.write(header) # Adding whitespaces if --whitespace is in the options for line in lines: if options.whitespace: if line[0:4] == 'ATOM': newline = line[0:6] + ' ' + line[6:16] + ' ' + line[ 16:38] + ' ' + line[38:46] + ' ' + line[46:] outfile.write(newline) elif line[0:6] == 'HETATM': newline = line[0:6] + ' ' + line[6:16] + ' ' + line[ 16:38] + ' ' + line[38:46] + ' ' + line[46:] outfile.write(newline) else: outfile.write(line) outfile.close() if options.input: from src import inputgen from src import psize method = "mg-auto" size = psize.Psize() size.parseInput(outpath) size.runPsize(outpath) async = 0 # No async files here! input = inputgen.Input(outpath, size, method, async, potdx=True) input.printInputFiles() input.dumpPickle() pickleToJSON(outpath)
def handleNonOpal(weboptions, storage_host): """ Handle non opal run. """ pdblist, errlist = readPDB(weboptions.pdbfile) 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 weboptions["opt"] == True: 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 %i atoms on the server (PDB2PQR " % MAXATOMS 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 weboptions: text += "pageTracker._trackPageview(\"/main_cgi/has_%s_%s.html\");" % (key, weboptions[key]) text += "pageTracker._trackPageview();" text += "} catch(err) {}</script>" text += "</BODY></HTML>" #print "Content-type: text/html\n" print text 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() statusfile = open('%s%s%s/pdb2pqr_status' % (INSTALLDIR, TMPDIR, name), 'w') statusfile.write('running') statusfile.close() # Recording CGI run information for PDB2PQR Opal pdb2pqrLogFile = open( '%s%s%s/pdb2pqr_log' % (INSTALLDIR, TMPDIR, name), 'w') pdb2pqrLogFile.write( str(weboptions.getOptions()) + '\n' + str(weboptions.ff)) # str(weboptions.ff)+'\n'+ # str(os.environ["REMOTE_ADDR"])) pdb2pqrLogFile.close() pid = os.fork() if pid: from PDB2PQR_web import jobutils redirect = redirector(name, weboptions) file_list = [ 'typemap', 'pdb2pqr_status', 'pdb2pqr_start_time', ] print('===========') print(weboptions.getCommandLine()) # for i in weboptions.getRunArguments(): # print(i) print('===========') if isinstance(file_list, list): try: jobutils.send_to_storage_service( storage_host, name, file_list, os.path.join(INSTALLDIR, TMPDIR)) except Exception as err: with open('storage_err', 'a+') as fin: fin.write(err) # print redirector(name, weboptions) return redirect 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) 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') run_arguements = weboptions.getRunArguments() if weboptions.runoptions.get('ph_calc_method', '') == 'pdb2pka': run_arguements['ph_calc_options'][ 'output_dir'] = '%s%s%s/pdb2pka_output' % (INSTALLDIR, TMPDIR, name) header, lines, missedligands = runPDB2PQR( pdblist, weboptions.ff, outname=pqrpath, commandLine=weboptions.getCommandLine(), **weboptions.getRunArguments()) 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) whitespace = weboptions.otheroptions['whitespace'] for line in lines: # Adding whitespaces if --whitespace is in the weboptions if whitespace: if line[0:4] == 'ATOM': newline = line[0:6] + ' ' + line[6:16] + ' ' + line[ 16:38] + ' ' + line[38:46] + ' ' + line[46:] pqrfile.write("%s\n" % string.strip(newline)) elif line[0:6] == 'HETATM': newline = line[0:6] + ' ' + line[6:16] + ' ' + line[ 16:38] + ' ' + line[38:46] + ' ' + line[46:] pqrfile.write("%s\n" % string.strip(newline)) else: pqrfile.write("%s\n" % string.strip(line)) pqrfile.close() if weboptions.otheroptions['apbs']: from src import inputgen from src import psize method = "mg-auto" size = psize.Psize() size.parseInput(pqrpath) size.runPsize(pqrpath) async = 0 # No async files here! myinput = inputgen.Input(pqrpath, size, method, async, potdx=True) myinput.printInputFiles() myinput.dumpPickle() endtime = time.time() - starttime #createResults(header, input, name, endtime, missedligands) #logRun(weboptions, endtime, len(lines), weboptions.ff, os.environ["REMOTE_ADDR"]) #printHeader("PDB2PQR Job Submission",have_opal,jobid=name) if 'ligand' in weboptions: outputligandfile = open( '%s%s%s/%s.mol2' % (INSTALLDIR, TMPDIR, name, name), 'w') outputligandfile.write(weboptions.ligandfilestring) outputligandfile.close() outputpdbfile = open( '%s%s%s/%s.pdb' % (INSTALLDIR, TMPDIR, name, name), 'w') outputpdbfile.write(weboptions.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() '''Upload associated APBS run files to the storage service''' from PDB2PQR_web import jobutils jobDir = os.path.join(INSTALLDIR, TMPDIR, name) sys.stdout = open('%s/debug_forked_stdout.out' % (jobDir), 'a+') sys.stderr = open('%s/debug_forked_stderr.out' % (jobDir), 'a+') file_list = os.listdir(jobDir) if isinstance(file_list, list): try: jobutils.send_to_storage_service( storage_host, name, file_list, os.path.join(INSTALLDIR, TMPDIR)) except Exception as err: with open('storage_err', 'a+') as fin: fin.write(err) sys.stdout.close() sys.stderr.close() #TODO: Better error reporting. #Also, get forked job to properly write error status on failure. except StandardError, details: #except StandardError as details: print traceback.format_exc() print sys.exc_info()[0] #print details createError(name, details)
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)
def mainCGI(): """ Main driver for running PDB2PQR from a web page """ import cgi import cgitb cgitb.enable() form = cgi.FieldStorage() options = {"extensions": {}} ff = form["FF"].value input = 0 if form.has_key("DEBUMP"): options["debump"] = 1 if form.has_key("OPT"): options["opt"] = 1 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"): file = getPDBFile(form["PDBID"].value) elif form.has_key("PDB"): file = 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 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("LIGAND"): options["ligand"] = StringIO(form["LIGAND"].value) pdblist, errlist = readPDB(file) 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 len(pdblist) > 10000 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 10000 atoms on the server. If you " 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 += "</BODY></HTML>" print "Content-type: text/html\n" print text sys.exit(2) try: starttime = time.time() name = setID(starttime) pqrpath = startServer(name) options["outname"] = pqrpath header, lines, missedligands = runPDB2PQR(pdblist, ff, options) file = open(pqrpath, "w") file.write(header) for line in lines: file.write("%s\n" % string.strip(line)) file.close() if input: from src import inputgen from src import psize method = "mg-auto" size = psize.Psize() size.parseInput(pqrpath) size.runPsize(pqrpath) async = 0 # No async files here! myinput = inputgen.Input(pqrpath, size, method, async) myinput.printInputFiles() endtime = time.time() - starttime createResults(header, input, name, endtime, missedligands) logRun(options, endtime, len(lines), ff, os.environ["REMOTE_ADDR"]) except StandardError, details: print "Content-type: text/html\n" print details createError(name, details)
options["outname"] = outpath header, lines, missedligands = runPDB2PQR(pdblist, ff, options) # Print the PQR file outfile = open(outpath, "w") outfile.write(header) for line in lines: outfile.write(line) outfile.close() if "input" in options: from src import inputgen from src import psize method = "mg-auto" size = psize.Psize() size.parseInput(outpath) size.runPsize(outpath) async = 0 # No async files here! input = inputgen.Input(outpath, size, method, async) input.printInputFiles() def mainCGI(): """ Main driver for running PDB2PQR from a web page """ import cgi import cgitb cgitb.enable()
def main(): global args, opts import getopt filename = "" shortOptList = "" longOptList = [ "help", "split", "potdx", "method=", "cfac=", "space=", "gmemceil=", "gmemfac=", "ofrac=", "redfac=", "istrng=" ] try: opts, args = getopt.getopt(sys.argv[1:], shortOptList, longOptList) except getopt.GetoptError as details: sys.stderr.write("Option error (%s)!\n" % details) usage() if len(args) != 1: sys.stderr.write("Invalid argument list!\n") usage() else: filename = args[0] method = "" size = Pz.Psize() async = 0 split = 0 istrng = 0 potdx = 0 for o, a in opts: if o == "--help": usage() if o == "--split": split = 1 if o == "--potdx": potdx = 1 if o == "--method": if a == "para": sys.stdout.write("Forcing a parallel calculation\n") method = "mg-para" elif a == "auto": sys.stdout.write("Forcing a sequential calculation\n") method = "mg-auto" elif a == "async": sys.stdout.write("Forcing an asynchronous calculation\n") method = "mg-para" async = 1 elif a == "manual": sys.stdout.write("Forcing a manual calculation\n") method = "mg-manual" else: sys.stdout.write("Incorrect method argument: %s\n" % a) sys.stdout.write("Defaulting to memory dependent result\n") if o == "--cfac": size.setConstant("cfac", float(a)) if o == "--space": size.setConstant("space", float(a)) if o == "--gmemfac": size.setConstant("gmemfac", int(a)) if o == "--gmemceil": size.setConstant("gmemceil", int(a)) if o == "--ofrac": size.setConstant("ofrac", float(a)) if o == "--redfac": size.setConstant("redfac", float(a)) if o == "--istrng": istrng = float(a) if split == 1: splitInput(filename) else: size.runPsize(filename) input = Input(filename, size, method, async, istrng, potdx) input.printInputFiles()
def mainCommand(argv): """ Main driver for running program from the command line. """ # Append Numeric/Numpy path to sys.path if the user specified a non-standard location during configuration global opts, args sys.argv = argv package_path = PACKAGE_PATH if package_path != "": sys.path.extend(package_path.split(":")) shortOptlist = "h,v" longOptlist = [ "help", "verbose", "ff=", "ffout=", "nodebump", "noopt", "with-ph=", "apbs-input", "chain", "clean", "assign-only", "ligand=", "whitespace", "typemap", "neutraln", "neutralc", "userff", "usernames" ] extensions = getAvailableExtensions(1) longOptlist += extensions.keys() try: opts, args = getopt.getopt(sys.argv[1:], shortOptlist, longOptlist) except getopt.GetoptError as details: sys.stderr.write("GetoptError: %s\n" % details) usage(2) if len(args) != 2: sys.stderr.write("Incorrect number (%d) of arguments!\n" % len(args)) sys.stderr.write("argv: %s, args: %s" % (argv, args)) usage(2) options = {"debump": 1, "opt": 1, "extensions": {}} outpath = None ff = None for o, a in opts: undashed = o[2:] if o in ("-v", "--verbose"): options["verbose"] = 1 elif o in ("-h", "--help"): usage(2) sys.exit() elif o == "--nodebump": del options["debump"] elif o == "--noopt": del options["opt"] elif o == "--apbs-input": options["input"] = 1 elif o == "--whitespace": options["whitespace"] = 1 elif o == "--typemap": options["typemap"] = 1 elif o == "--with-ph": try: ph = float(a) options["ph"] = ph if ph < 0.0 or ph > 14.0: raise ValueError except ValueError: text = "%s is not a valid pH! " % a text += "Please choose a pH between 0.0 and 14.0." raise ValueError(text) elif o == "--assign-only": del options["debump"] del options["opt"] options["assign-only"] = 1 elif o == "--clean": del options["debump"] del options["opt"] options["clean"] = 1 elif o == "--ff": if "userff" in opts: ff = "user-defined" else: ff = a # Check to make sure forcefield file is available defpath = getFFfile(ff) if defpath == "": raise ValueError( "Unable to find parameter files for forcefield %s!" % ff) elif o == "--neutraln": options["neutraln"] = 1 elif o == "--neutralc": options["neutralc"] = 1 elif o == "--chain": options["chain"] = 1 elif o == "--ffout": if a.lower() in [ "amber", "charmm", "parse", "tyl06", "peoepb", "swanson" ]: options["ffout"] = a else: raise ValueError("Invalid forcefield naming scheme %s!" % a) elif o == "--ligand": if os.path.isfile(a): options["ligand"] = open(a, 'rU') else: raise ValueError("Unable to find ligand file %s!\n" % a) elif undashed in extensions.keys(): options["extensions"][undashed] = extensions[undashed] if "--neutraln" in opts: if ff not in ["parse", "PARSE"]: raise ValueError( "neutraln option only works with PARSE forcefield!") if "--neutralc" in opts: if ff not in ["parse", "PARSE"]: raise ValueError( "neutralc option only works with PARSE forcefield!") if ff == None and "clean" not in options: raise ValueError("Forcefield not specified!") text = "\n--------------------------\n" text += "PDB2PQR - a Python-based structural conversion utility\n" text += "--------------------------\n" text += "Please cite your use of PDB2PQR as:\n" text += " Dolinsky TJ, Nielsen JE, McCammon JA, Baker NA.\n" text += " PDB2PQR: an automated pipeline for the setup, execution,\n" text += " and analysis of Poisson-Boltzmann electrostatics calculations.\n" text += " Nucleic Acids Research 32 W665-W667 (2004).\n\n" sys.stdout.write(text) path = args[0] file = getPDBFile(path) pdblist, errlist = readPDB(file) if len(pdblist) == 0 and len(errlist) == 0: try: os.remove(path) except OSError: pass raise ValueError("Unable to find file %s!\n" % path) if len(errlist) != 0 and "verbose" in options: print("Warning: %s is a non-standard PDB file.\n" % path) print(errlist) outpath = args[1] options["outname"] = outpath if "clean" not in options: header, lines, missedligands = runPDB2PQR(pdblist, ff, options) else: header, lines = runPDB2PQR(pdblist, ff, options) missedligands = None # Print the PQR file outfile = open(outpath, "w") outfile.write(header) # Adding whitespaces if --whitespace is in the options for line in lines: if "whitespace" in options: if line[0:4] == 'ATOM': newline = line[0:16] + ' ' + line[16:38] + ' ' + line[ 38:46] + ' ' + line[46:] outfile.write(newline) elif line[0:6] == 'HETATM': newline = line[0:16] + ' ' + line[16:38] + ' ' + line[ 38:46] + ' ' + line[46:] outfile.write(newline) else: outfile.write(line) outfile.close() if "input" in options: from src import inputgen as Inp from src import psize as Pz method = "mg-auto" size = Pz.Psize() size.parseInput(outpath) size.runPsize(outpath) async = 0 # No async files here! input = Inp.Input(outpath, size, method, async) input.printInputFiles() input.dumpPickle()