Example #1
0
def main():
    """Main function"""
    usage = "usage: %prog [options]"

    parser = OptionParser(usage)

    parser.set_description("To test the Logger class.")

    parser.add_option("-v", "--verbose", dest="verbose", help="Verbose mode", action="store_true", default=False)

    parser.add_option("-p", "--port", dest="port", help="Http Port (Default: 4041)", type="int", default=4041)

    (options, args) = parser.parse_args()

    if len(args) != 1:
        parser.error("Error: incorrect number of arguments, try --help")

    parser = PdfParser(args[0], "", "")
    # info = parser.get_logical_structure()
    # print info
    toc = parser.get_logical_structure()
    import pprint

    pprint.pprint(toc)
    info = parser.get_metadata()
    pprint.pprint(info)
Example #2
0
def main():
    from optparse import OptionParser

    p = OptionParser()
    p.set_usage('dedoppler <FULL_PATH_TO_FITS_FILE>')
    p.set_description(__doc__)

    p.add_option('-m', '--min_drift', dest='min_drift', type='float', default=0.0,
            help='Set the minimum drift rate to search. Unit: Hz/sec. Default:0.0')
    p.add_option('-M', '--max_drift', dest='max_drift', type='float', default=10.0,
            help='Set the drift rate to search. Unit: Hz/sec. Default: 10.0')
    p.add_option('-s', '--snr', dest='snr', type='float', default=10.0, help='SNR threshold. Unit: ?. Default: 10.0')
    p.add_option('-b', '--bw', dest='bw', type='float', default=1, help='Specify the amount of \'compression\' to be done in frequency domain to search for more \'spread out\' signals. Unit:?. Default: ?')
    p.add_option('-r', '--rfithresh', dest='rfithresh', type='float', default=25.0, help='Specify the RFI threshold. Unit:?. Default: 25.0')
    p.add_option('-p', '--path', dest='split_dir', type='str', default='/tmp',
            help='In the case that the input FITS file size is too big to handle at once, we\'ll need to split it into smaller FITS files. This option specify where to put those FITS files. Default: /tmp ')
    p.add_option('-o', '--output', dest='out', type='str', default='', help='')
    p.add_option('-w', '--width', dest='slice_width', type='int', default=512, help='')
    p.add_option('-l', '--loglevel', dest='loglevel', type='str', default='debug', help='Specify log level')

    opts, args = p.parse_args(sys.argv[1:])

    if len(args)!=1:
        print 'Please specify a FITS file \nExiting.'
        sys.exit()
    else:
        fitsfile = args[0]

    logging.basicConfig(
        format='%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s', level = logging.DEBUG)

    mydedopptask = dedopp.DedopplerTask(fitsfile = fitsfile, max_drift = opts.max_drift, min_drift = opts.min_drift, snr = opts.snr, bw = opts.bw, rfithresh = opts.rfithresh, split_dir = opts.split_dir)

    mydedopptask.search()
Example #3
0
def main():
    from optparse import OptionParser
    from quixote.util import import_object
    parser = OptionParser()
    parser.set_description(run.__doc__)
    default_host = 'localhost'
    parser.add_option(
        '--host', dest="host", default=default_host, type="string",
        help="Host interface to listen on. (default=%s)" % default_host)
    default_port = 3000
    parser.add_option(
        '--port', dest="port", default=default_port, type="int",
        help="Port to listen on. (default=%s)" % default_port)
    default_maxchild = 5
    parser.add_option(
        '--max-children', dest="maxchild", default=default_maxchild,
        type="string",
        help="Maximum number of children to spawn. (default=%s)" %
            default_maxchild)
    parser.add_option(
        '--script-name', dest="script_name", default=None, type="string",
        help="Value of SCRIPT_NAME (only needed if using mod_scgi)")
    default_factory = 'quixote.demo.create_publisher'
    parser.add_option(
        '--factory', dest="factory",
        default=default_factory,
        help="Path to factory function to create the site Publisher. "
             "(default=%s)" % default_factory)
    (options, args) = parser.parse_args()
    run(import_object(options.factory), host=options.host, port=options.port,
        script_name=options.script_name, max_children=options.maxchild)
Example #4
0
def main():
    """Main function"""
    usage = "usage: %prog [options]"

    parser = OptionParser(usage)

    parser.set_description ("To test the Logger class.")

    parser.add_option ("-v", "--verbose", dest="verbose",
                       help="Verbose mode",
                       action="store_true", default=False)

    parser.add_option ("-p", "--port", dest="port",
                       help="Http Port (Default: 4041)",
                       type="int", default=4041)

    (options, args) = parser.parse_args()

    if len(args) != 0:
        parser.error("Error: incorrect number of arguments, try --help")

    from wsgiref.simple_server import make_server
    application = WebProcessorApp()
    server = make_server('', options.port, application)
    server.serve_forever()
Example #5
0
def main():
    from optparse import OptionParser
    from os import listdir
    from os.path import join, isdir, isfile, basename

    parser = OptionParser()
    parser.set_description(
        'Check python source files for unknown name errors '
        'and for unused imports. '
        'The arguments name files to check or '
        'directories to check recursively. '
        'If no arguments are given, the current directory '
        'is checked. '
        'If there is a recursion, it excludes ".svn", "build", '
        'and "dist" directories, and includes files that end '
        'in ".py" or ".qpy".')
    (options, args) = parser.parse_args()
    if args:
        todo = args
    else:
        todo = ['.']
    while todo:
        arg = todo.pop()
        if basename(arg) in ['.svn', 'dist', 'build']:
            continue
        elif (isfile(arg) and
              arg in sys.argv or
              (arg.endswith('.py') or
               arg.endswith('.qpy'))):
            check(arg)
        elif isdir(arg):
            todo.extend([join(arg, item) for item in listdir(arg)])
Example #6
0
def main():
 parser = OptionParser(usage="usage: %prog [options] [filename]", version="%prog 1.0", epilog="post")
 parser.add_option("-t", "--trans",
                  action="store_true", dest="trans", default=False,
                  help="transfer a local file to the Haze server")
 parser.add_option("-g", "--gets",
                  action="store_true", dest="gets", default=False,
                  help="get a file from the Haze Server")
 parser.set_description(des)
 (options, args) = parser.parse_args()
 alen = len(args)
 print "options:", options, " args:", args
 print base
##########################################################
 if not options.trans and not options.gets and alen >0:
  parser.print_help()
 elif options.trans and not options.gets:
  scpcommand='scp -r ' + ' '.join(args) + ' [email protected]:' + tbase
  print scpcommand
  os.system(scpcommand)
 elif options.gets and not options.trans:
  scpcommand='scp -r [email protected]:' + getMulti(args, base = tbase) + ' .'
  print scpcommand
  os.system(scpcommand)
 else:
  scpcommand='scp -r [email protected]:"' + base + '/DUTLIB.jar ' + base +'/LabLucene1.0.jar" lib/'
  print scpcommand
  os.system(scpcommand)
Example #7
0
def buildOptParser():
    from optparse import OptionParser

    parser = OptionParser()
    parser.set_description("This is the proxy to PRS functionality, also invoked "+\
                           "locally, e.g. for calibration requests.")

    parser.add_option("-v", "--verbose", 
                      dest="verbosity", action="store_true",
                      help="increase HTTP client messaging on adcc GET requests.")

    parser.add_option("-i", "--invoked", 
                      dest = "invoked", action = "store_true",
                      help = "Used by processes that invoke prsproxy, so "+\
                      "that PRS proxy knows when to exit. If not present, the "+\
                      "prsproxy registers itself and will only exit by user "+\
                      "control (or by os-level signal).")

    parser.add_option("--startup-report", 
                      dest = "adccsrn", default=None, 
                      help = "Specify a file name for the adcc startup report")

    parser.add_option("--preload", 
                      dest="preload", action="store_true",
                      help = "Useful in proxy mode, where some information "+\
                      "otherwise produced during the first relevant request "+\
                      "is prepared prior to starting the HTTPServer.")

    parser.add_option("--reload", 
                      dest="reload", action="store_true",
                      help = "Just like --preload, but uses last, cached "+\
                      "(pickled) directory scan.")

    parser.add_option("-r", "--reduce-port", 
                      dest = "reduceport", default=54530, type="int",
                      help="When invoked by reduce, this is used to inform "+\
                      "the prsproxy of the port on which reduce listens for "+\
                      "xmlrpc commands.")

    parser.add_option("-p", "--reduce-pid", 
                      dest ="reducepid", default=None, type="int",
                      help = "When invoked by reduce, this option is used to "+\
                      "inform the prsproxy of the reduce application's PID.")

    parser.add_option("-l", "--listen-port", 
                      dest = "listenport", default=53530, type="int", 
                      help="prsproxy listener port for the xmlrpc "+\
                      "server.")

    parser.add_option("-w", "--http-port", 
                      dest = "httpport", default=8777, type="int",
                      help="Response port for the web interface. "+\
                      "i.e. http://localhost:<http-port>/")

    args, pos_args = parser.parse_args()

    # No positional arguments to this interface.
    return args
    def __init__(self, parent):
        self._init_ctrls(parent)
        optParse=OptionParser()
        optParse.add_option('-A','--ADV',action='store_const',dest='userlevel',const=1,default=0,help='Set User to Advanced',metavar='USERLEVEL')
        optParse.add_option('-X','--EXP',action='store_const',dest='userlevel',const=2,default=0,help='Set User to Expert',metavar='USERLEVEL')
        optParse.add_option('-H','--HOST',dest='host',type='string',help='Override hostname for computer',default=socket.gethostname(),metavar='HOST')
        optParse.add_option('-D','--DEBUG',action='store_true',dest='debug',help='Run program in debug mode',default=False,metavar='DEBUG')
        optParse.add_option('-L','--LOG',action='store_true',dest='log',help='Pump screen output to a log',default=False,metavar='LOG')

        optParse.add_option('-R','--RO',action='store_true',dest='readonly',help='Epics Variables are Read Only',default=False,metavar='READONLY')
        
        
        optParse.set_description('The graphical tool for the sample alignment code')
        
        optParse.print_help()
        (opt,args)=optParse.parse_args()
        
        if opt.log:
            newPipe=__LoggingPipe__('Autoalign')
            globals()['sys'].stdout=newPipe
            globals()['sys'].stderr=newPipe
        
        
        dSize=(2048,2048)
        self.traceGraph = kPlot(name=u'traceGraph', parent=self, pos=wx.Point(16, 104),
         size=wx.Size(456-16*2, 464), style=0,xAxis=(-dSize[0]/2,dSize[0]/2),yAxis=(-dSize[1]/2,dSize[1]/2),title='Sample Alignment')
        self.histoPlot = kPlot(name=u'histoPlot', parent=self, pos=wx.Point(16, 104+16+464),
         size=wx.Size(464*2+16, 200), style=0,title='Histogram')
        self.cmbMaterial = dictComboBox(dict=X_ROBOT_X02DA_AALib.sampleThreshLib,
              name=u'cmbMaterial', parent=self, pos=wx.Point(224, 16),
              size=wx.Size(112, 27), style=0, value=u'Material...')
        self.cmbMaterial.SetLabel(u'')
        self.stime=time.time()
        self.txtGlob.SetValue('$HOME/*/*/tif/*.tif')
        # old search string '$HOME/Data10/disk2/*/tif/*.tif'
        self.graphTimer=wx.Timer(self,-1)
        self.timerCycle=5000
        self.graphTimer.Start(self.timerCycle)
        self.Bind(wx.EVT_TIMER,self.mainTimerEvent) 
        self.cImg=100
        self.cKey=''
        self.cThresh=self.threshVal.GetValue()/10.0
        self.cThresh=1.0
        self.OnTxtGlobTextEnter([])
        self.dRange=[]
        self.batchEye=-2
        self.previewMode=0
        self.myStage=alignStage()
        self.oldImageName=''
        self.oldFlatName=''
        self.oldThresh=[]
        self.oldMat=''
        self.searchRunning=0
        #self.fltSelection.SetItems(self.imgList.keys())
        #self.doLoadImage()	
        self.flatIsLoaded=False
Example #9
0
def main():
    MAKE_REGEX = (
            r"^\s+\[.+\]|"
            r"^make\[\d+\]: (`|Entering |Leaving |Nothing )|"
            r"^make -r |"
            r"^\w+ finished$|"
            r"^(\S*/)?\bgcc\s"
            )

    parser = OptionParser(version="%prog" + __VERSION__,
            formatter=Formatter())
    parser.set_usage(usage)
    parser.set_description(description)
    parser.add_option("-a", "--append", action="store_true", dest="append",
            help="append to given files, do not overwrite")
    parser.add_option("-v", "--verbose", action="store_const", dest="verbose",
            const=logging.DEBUG,
            help="verbose output for debugging")
    parser.add_option("-q", "--quiet", action="store_const", dest="verbose",
            const=logging.WARNING,
            help="suppress informational output")
    parser.add_option("--regex", action="append", dest="regexList",
            default=[],
            metavar="REGEX",
            help="append a 'status' regular expression (e.g., " +
                "'^#.*' for comment lines)")
    parser.add_option("--make", action="append_const", dest="regexList",
            const=MAKE_REGEX,
            help="short for --regex '" + MAKE_REGEX +
                "'; useful for the output of a " +
                "`make` invocation")
    parser.add_option("--strip", action="store_true", dest="strip",
            default=False,
            help="strip out informational output that doesn't " +
                "immediately precede non-informational output, rather " +
                "than display and overwrite it in place")

    global options
    (options, args) = parser.parse_args()

    if options.verbose is None:
        logger.setLevel(logging.INFO)
    else:
        logger.setLevel(options.verbose)

    logger.debug('Finished option processing, options=%r' % options)

    logger.debug('arguments:')

    for arg in args:
        logger.debug('arg: %s' % arg)

    regex = r'|'.join(options.regexList)
    tee(regex, args, append=options.append)

    logger.debug('Finished.')
def main():
    optParse = OptionParser()
    optParse.add_option(
        "-A",
        "--ADV",
        action="store_const",
        dest="userlevel",
        const=1,
        default=0,
        help="Set User to Advanced",
        metavar="USERLEVEL",
    )
    optParse.add_option(
        "-X",
        "--EXP",
        action="store_const",
        dest="userlevel",
        const=2,
        default=0,
        help="Set User to Expert",
        metavar="USERLEVEL",
    )
    optParse.add_option(
        "-H",
        "--HOST",
        dest="host",
        type="string",
        help="Override hostname for computer",
        default=socket.gethostname(),
        metavar="HOST",
    )
    optParse.add_option(
        "-D",
        "--DEBUG",
        action="store_true",
        dest="debug",
        help="Run program in debug mode",
        default=False,
        metavar="DEBUG",
    )
    optParse.add_option(
        "-R",
        "--RO",
        action="store_true",
        dest="readonly",
        help="Epics Variables are Read Only",
        default=False,
        metavar="READONLY",
    )

    optParse.set_description("The graphical frontend for the Robot Control and Sample Alignment")

    optParse.print_help()
    (opt, args) = optParse.parse_args()
    pass
Example #11
0
def constructOptionParser():
    """
    returns a pre-setup optparser
    """
    parser = OptionParser(formatter=PreformattedDescriptionFormatter())

    parser.set_description('Retrieves eland config file from hts_frontend web frontend.')

    parser.epilog = """
Config File:
  * %s (System wide)
  * %s (User specific; overrides system)
  * command line overrides all config file options

  Example Config File:

    [%s]
    config_host: http://somewhere.domain:port
    genome_dir: /path to search for genomes
    post_run: runfolder -o <destdir> %%(runfolder)s

""" % (CONFIG_SYSTEM, CONFIG_USER, GERALD_CONFIG_SECTION)

    #Special formatter for allowing preformatted description.
    ##parser.format_epilog(PreformattedDescriptionFormatter())

    parser.add_option("-u", "--url",
                      action="store", type="string", dest="url")

    parser.add_option("-o", "--output-file",
                      action="store", type="string", dest="output_filepath",
                      help="config file destination. If runfolder is specified defaults "
                           "to <runfolder>/config-auto.txt" )

    parser.add_option("-f", "--flowcell",
                      action="store", type="string", dest="flowcell")

    parser.add_option("-g", "--genome_dir",
                      action="store", type="string", dest="genome_dir")

    parser.add_option("-r", "--runfolder",
                      action="store", type="string",
                      help="specify runfolder for post_run command ")

    parser.add_option("--sample-sheet", default=None,
                      help="path to save demultiplexing sample sheet")

    parser.add_option("--operator", default='', help="Name of sequencer operator")
    parser.add_option("--recipe", default="Unknown",
                      help="specify recipe name")

    parser.add_option('-v', '--verbose', action='store_true', default=False,
                       help='increase logging verbosity')
    return parser
Example #12
0
def main():
    email = ''
    password = ''
    author = ''

    # parse passord file
    cParser = SafeConfigParser()
    is_exists = cParser.read(PasswdFile)
    if is_exists and cParser.has_section('blogger.py'):
        if cParser.has_option('blogger.py', 'email'):
            email = cParser.get('blogger.py', 'email')
        if cParser.has_option('blogger.py', 'password'):
            password = cParser.get('blogger.py', 'password')
        if cParser.has_option('blogger.py', 'author'):
            author = cParser.get('blogger.py', 'author')

    # parse command-line options
    oParser = OptionParser()

    oParser.add_option("-e", "--email", dest="email", help="E-mail address")
    oParser.add_option("-p", "--password", dest="password", help="Password")
    oParser.add_option("-u", "--author", dest="author", help="Blog author")
    oParser.add_option("-d", "--draft", dest="is_draft", action="store_true",
        help="post draft data")
    oParser.add_option("-f", "--file", dest="blogFile", help="Blog data file")

    oParser.set_defaults(email=email, password=password, author=author)
    oParser.set_description('follow options can be set by ~/.password.')

    option, args = oParser.parse_args()

    email = option.email
    password = option.password
    author = option.author

    if '' in (email, password, author):
        oParser.print_help()
        sys.exit(1)

    blogger = Blogger(email, password)
    if option.blogFile:
        title, content, label = createBlogData(file(option.blogFile))
    else:
        title, content, label = createBlogData()

    if title and content:
        blogger.createPost(title, content, author, label, option.is_draft)
    else:
        print 'No Blog data, do nothing'
        sys.exit(1)
Example #13
0
def client_main():
    from optparse import OptionParser
    parser = OptionParser()
    parser.set_description("Opens a client connection to a Durus server.")
    parser.add_option(
        '--file', dest="file", default=None,
        help="If this is not given, the storage is through a Durus server.")
    parser.add_option(
        '--port', dest="port", default=DEFAULT_PORT,
        type="int",
        help="Port the server is on. (default=%s)" % DEFAULT_PORT)
    parser.add_option(
        '--host', dest="host", default=DEFAULT_HOST,
        help="Host of the server. (default=%s)" % DEFAULT_HOST)
    parser.add_option(
        '--address', dest="address", default=None,
        help=(
            "Address of the server.\n"
            "If given, this is the path to a Unix domain socket for "
            "the server."))
    parser.add_option(
        '--storage-class', dest='storage', default=None,
        help='Storage class (e.g. durus.file_storage.FileStorage).')
    parser.add_option(
        '--cache_size', dest="cache_size", default=10000, type="int",
        help="Size of client cache (default=10000)")
    parser.add_option(
        '--repair', dest='repair', action='store_true',
        help=('Repair the filestorage by truncating to remove anything '
              'that is malformed.  Without this option, errors '
              'will cause the program to report and terminate without '
              'attempting any repair.'))
    parser.add_option(
        '--readonly', dest='readonly', action='store_true',
        help='Open the file in read-only mode.')
    parser.add_option(
        '--startup', dest='startup',
        default=os.environ.get('DURUSSTARTUP', ''),
        help=('Full path to a python startup file to execute on startup.'
              '(default=DURUSSTARTUP from environment, if set)')
        )
    (options, args) = parser.parse_args()
    if options.address is None:
        address = (options.host, options.port)
    else:
        address = options.address
    interactive_client(options.file, address,
                       options.cache_size, options.readonly, options.repair,
                       options.startup, options.storage)
Example #14
0
def main():
  usage = "usage: %prog [options] <input_files> "

  parser = OptionParser(usage)
  parser.set_description("Add a prefix and/or suffix to each element of a list.")

  parser.add_option("-d",
                    "--dir",
                    dest="dir",
                    help="Base directory",
                    type="string",
                    default=None)
  parser.add_option("-e",
                    "--ext",
                    dest="ext",
                    help="File extension",
                    type="string",
                    default=None)
  parser.add_option("-c",
                    "--check",
                    dest="check",
                    help="Check that each file exists",
                    action="store_true")


  (options, args) = parser.parse_args()


  for line in fileinput.input(args):
    line = line.strip().strip('\r\n')
    if options.dir != None:
      line = os.path.join(options.dir, line)

    if options.ext != None:
      line = line + options.ext

    if options.check and not os.path.exists(line):
      print >> sys.stderr, "No such file: " + line
      sys.exit(1)
      
    try:
      print line
    except IOError as e:
      if e.errno == 32:
        sys.exit(0)
      else:
        raise
def main(args):
    
	parser = OptionParser(usage="usage: %prog [OPTIONS] [TESTS]")
	parser.set_description(main.__doc__)

    	parser.add_option('--iterations', '-n',
    action="store", default=None,
    help="n iterations of Fibonacci Sequence", )

	#parse option
	(options, args) = parser.parse_args(args=args[1:])

	global Options
	Options = options

        x=run(Options.iterations);
        print x
Example #16
0
def main():
    parser = OptionParser()
    parser.set_description("Stress test a Durus Server")
    parser.add_option(
        "--port", dest="port", default=DEFAULT_PORT, type="int", help="Port to listen on. (default=%s)" % DEFAULT_PORT
    )
    parser.add_option(
        "--host", dest="host", default=DEFAULT_HOST, help="Host to listen on. (default=%s)" % DEFAULT_HOST
    )
    parser.add_option(
        "--cache_size", dest="cache_size", default=4000, type="int", help="Size of client cache (default=4000)"
    )
    parser.add_option(
        "--max-loops", dest="loops", default=None, type="int", help="Maximum number of loops before exiting."
    )

    (options, args) = parser.parse_args()
    from durus.logger import logger

    logger.setLevel(5)
    storage = ClientStorage(host=options.host, port=options.port)
    connection = Connection(storage, cache_size=options.cache_size)
    try:
        if "obj" not in connection.get_root():
            init_db(connection)
            verify_db(connection, all=True)
            connection.commit()
    except ConflictError:
        connection.abort()
    n = options.loops
    while n is None or n > 0:
        if n is not None:
            n -= 1
        try:
            if hasattr(sys, "gettotalrefcount"):
                sys.stdout.write("refs = %s\n" % sys.gettotalrefcount())
            if randbool():
                connection.abort()
            verify_db(connection)
            mutate_db(connection)
            connection.commit()
            maybe_sleep()
        except ConflictError:
            sys.stdout.write("conflict\n")
            connection.abort()
            maybe_sleep()
Example #17
0
    def getOpts(self):
        self.CONFIGITEMS['Debug'] = ('', '--debug', False, \
                                  'Prints debugging information to the stdout')

        # %prog expands to os.path.basename(sys.argv[0])
        usage  = "usage: %prog [options]"
        parser = OptionParser(usage=usage, version="%prog 1.0")
        parser.set_description(self.DESC)

        for key in self.CONFIGITEMS:
            (shortCmd, longCmd, argReq, helpText) = self.CONFIGITEMS[key]

            if argReq:
                parser.add_option(shortCmd, longCmd, dest=key, help=helpText)
            else:
                parser.add_option(shortCmd, longCmd, dest=key, action="store_true",  help=helpText)

        (self.OPTIONS, args) = parser.parse_args()
Example #18
0
def main():
 parser = OptionParser(usage="usage: %prog [options] [filename]", version="%prog 1.0")
 parser.add_option("-t", "--trans",
                  action="store_true", dest="trans", default=False,
                  help="transfer a local file to the Haze server")
 parser.add_option("-g", "--gets",
                  action="store_true", dest="gets", default=False,
                  help="get a file from the Haze Server")
 des = "Remove the relevant docs that are in supplied qrel, only for the Relevanc Feedback Track"
 parser.set_description(des)
 (options, args) = parser.parse_args()
 print "options:", options
 print "args:", args
 len = len(args)
 if len == 1:
  remove(args[0])
 elif len == 2: 
  remove(args[0], qrel=args[1])
Example #19
0
def get_server_parser(doc):
    parser = OptionParser()
    parser.set_description(doc)
    default_host = 'localhost'
    parser.add_option(
        '--host', dest="host", default=default_host, type="string",
        help="Host interface to listen on. (default=%s)" % default_host)
    default_port = 8080
    parser.add_option(
        '--port', dest="port", default=default_port, type="int",
        help="Port to listen on. (default=%s)" % default_port)
    default_factory = 'quixote.demo.create_publisher'
    parser.add_option(
        '--factory', dest="factory",
        default=default_factory,
        help="Path to factory function to create the site Publisher. "
             "(default=%s)" % default_factory)
    return parser
Example #20
0
def getOptions():
    ##### Configuration options #####

    usage = "usage: %prog [options] ics_file1 ics_file2"
    parser = OptionParser(usage=usage, version=version)
    parser.set_description("ics_diff will print a comparison of two iCalendar files ")

    parser.add_option("-i", "--ignore-dtstamp", dest="ignore", action="store_true",
                      default=False, help="ignore DTSTAMP lines [default: False]")

    (cmdline_options, args) = parser.parse_args()
    if len(args) < 2:
        print("error: too few arguments given")
        print
        print(parser.format_help())
        return False, False

    return cmdline_options, args
Example #21
0
def main():
    # Basic option parsing 
    p = OptionParser()
    p.set_usage('beam_pattern_viewer.py [filename] [options]')
    p.set_description(__doc__)
    (options, args) = p.parse_args()
    
    print "Starting OSKAR antenna config tool..."
    global main_gui
    app = QtGui.QApplication(sys.argv)
    
    try:
        filename = args[0]
        main_gui = OskarGui(filename)
    except:
        main_gui = OskarGui()
    app.exec_()
    sys.exit()    
Example #22
0
def run_durus_main():
    parser = OptionParser()
    parser.set_description('Run a Durus Server')
    parser.add_option(
        '--port', dest='port', default=DEFAULT_PORT, type='int',
        help='Port to listen on. (default=%s)' % DEFAULT_PORT)
    parser.add_option(
        '--file', dest='file', default=None,
        help='If this is not given, the storage is in a new temporary file.')
    parser.add_option(
        '--host', dest='host', default=DEFAULT_HOST,
        help='Host to listen on. (default=%s)' % DEFAULT_HOST)
    logginglevel = logger.getEffectiveLevel()
    parser.add_option(
        '--logginglevel', dest='logginglevel', default=logginglevel, type='int',
        help=('Logging level. Lower positive numbers log more. (default=%s)' %
              logginglevel))
    parser.add_option(
        '--logfile', dest='logfile', default=None,
        help=('Log file. (default=stderr)'))
    parser.add_option(
        '--repair', dest='repair', action='store_true',
        help=('Repair the filestorage by truncating to remove anything '
              'that is malformed.  Without this option, errors '
              'will cause the program to report and terminate without '
              'attempting any repair.'))
    parser.add_option(
        '--readonly', dest='readonly', action='store_true',
        help='Open the file in read-only mode.')
    parser.add_option(
        '--stop', dest='stop', action='store_true',
        help='Instead of starting the server, try to stop a running one.')
    (options, args) = parser.parse_args()
    if not options.stop:
        start_durus(options.logfile,
                    options.logginglevel,
                    options.file,
                    options.repair,
                    options.readonly,
                    options.host,
                    options.port)
    else:
        stop_durus(options.host,
                   options.port)
Example #23
0
def main():
    from optparse import OptionParser

    p = OptionParser()
    p.set_usage('plot_results <FULL_PATH_TO_TEXT_FILE>')
    p.set_description(__doc__)

    opts, args = p.parse_args(sys.argv[1:])

    if len(args)!=1:
        print 'Please specify an input file \nExiting.'
        sys.exit()
    else:
        filename = args[0]


    logging.basicConfig(format='%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s', level = logging.DEBUG)

    plot_tophits(filename)
Example #24
0
def main():
    
    # Basic option parsing 
    p = OptionParser()
    p.set_usage('fits_pattern_viewer.py [filename] [options]')
    p.set_description(__doc__)
    (options, args) = p.parse_args()

    print "Starting %s..."%progname
    global main_gui
    app = QtGui.QApplication(sys.argv)
    
    try:
        filename = args[0]
        main_gui = InterFitsGui(filename, save_autos=False)
    except:
        main_gui = InterFitsGui()
    app.exec_()
    sys.exit()    
def main():
    
    # Basic option parsing 
    p = OptionParser()
    p.set_usage('fits_pattern_viewer.py [filename] [options]')
    p.set_description(__doc__)
    (options, args) = p.parse_args()

    print "Starting HIPSR SD-FITS viewer..."
    global main_gui
    app = QtGui.QApplication(sys.argv)
    
    try:
        filename = args[0]
        main_gui = HipsrGui(filename)
    except:
        main_gui = HipsrGui()
    app.exec_()
    sys.exit()    
def main():
	parser = OptionParser()
	parser.set_usage(parser.get_prog_name() + " -a exp1.searchConfig.xml exp2.searchConfig\n" 
				+ " OR " + parser.get_prog_name() + " -m exp1.YYY.csv exp2.YYY.csv [...]")
	parser.set_description("""Combines BehaviorSearch .csv files (that were created using the same search configuration.)

In -a (auto mode), it will use the *.searchConfig.xml files you specify to find all of the matching CSV search results files, and combine them
into a new file, named based on the common filename stem of the combined files. (i.e. the files: xxxx_00.yyy.csv, xxxx_01.yyy.csv,  => xxxx.yyy.csv)

In -m (manual mode), only those CSV files that you manually specify will be combined, and the results will go to stdout.
(Note that you can specify wildcards, such as "data*.xml") 
""")
	parser.add_option("-m", "--manual", action="store_true", dest="manual", help="manual mode")
	parser.add_option("-a", "--autosort", action="store_true", dest="autosort", help="(auto-sort mode) use XXX.searchConfig.xml files to automatically choose which CSV files should be combined.")
	parser.add_option("-p", "--preserve", action="store_true", dest="preserve", help="keep the original search number indexes, instead of renumbering consecutively.")
	parser.add_option("-d", "--delete", action="store_true", dest="delete", help="delete the input files, after combining")

	options , filepatterns = parser.parse_args()
	if (options.manual == options.autosort):
		print "ERROR: You must specify EITHER -m (manual) or -a (autosort) mode."
		print
		parser.print_help()
		sys.exit(0)

	if (len(filepatterns) == 0):
		parser.print_help()
		sys.exit(0)
		
	filenames = []
	for fPat in filepatterns:
		filenames.extend(glob.glob(fPat))
	
	filenames = uniq(filenames)
	
	if (len(filenames) < 1):
		parser.print_help()
		sys.exit(1)

	if (options.autosort):
		autosort_and_combine(filenames, options.preserve, options.delete)
	else: # (options.manual == True)
		combine(filenames, options.preserve, options.delete, sys.stdout)
Example #27
0
def get_parser():
    """return an OptionParser object for TracLegos"""

    parser = OptionParser()

    # command line parser options
    parser.add_option("-c", "--conf",
                      dest="conf", action="append", default=[],
                      help="site configuration files")
    parser.add_option("-d", "--directory",
                      dest="directory", default=".",
                      help="trac projects directory")
    parser.add_option("-i", "--inherit", dest="inherit", default=None,
                      help=".ini file to inherit from")
    parser.add_option("-s", "--repository",  dest="repository",
                      help="repository type to use")
    parser.add_option("-t", dest="templates", action="append", default=[],
                      help="trac.ini templates to be applied in order")
    parser.add_option("--db", "--database",
                      dest="database", default=None,
                      help="database type to use")
    parser.add_option("-w", "--wiki", dest="wiki",
                      action="append", default=[],
                      help="directories containing Trac wiki pages to import")

    # options to yield information
    parser.add_option("--list-templates", dest="listprojects",
                      action="store_true", default=False,
                      help="list available TracProject PasteScript templates")
    parser.add_option("--list-repositories", dest="listrepositories",
                      action="store_true", default=False,
                      help="list repository types available for setup by TracLegos")
    parser.add_option("--list-databases", dest="listdatabases",
                      action="store_true", default=False,
                      help="list available database types available for setup by TracLegos")
    parser.add_option("--list-variables", dest="printmissing",
                      action="store_true", default=False,
                      help="print variable names missing for a given configuration")

    parser.set_usage("%prog [options] project <project2> <...> var1=1 var2=2 ...")
    parser.set_description("assemble a trac project from components")
    return parser
Example #28
0
def convert_main():
    from optparse import OptionParser
    parser = OptionParser()
    parser.set_description(
        "Reads a ZODB Filestorage file and creates a new Durus "
        "FileStorage file containing the same current object records.")
    parser.add_option(
        '--zodb_file', dest="zodb_file", 
        help="The ZODB FileStorage to convert.")
    parser.add_option(
        '--durus_file', dest="durus_file",
        help=("The Durus FileStorage to create. "
              "This file will be overwritten if it already exists, "
              "so be careful."))
    (options, args) = parser.parse_args()
    if (options.zodb_file and options.durus_file and
        options.zodb_file != options.durus_file):
        convert(options.zodb_file, options.durus_file)
    else:
        parser.print_help()
Example #29
0
def get_options():
    ##### Configuration options #####

    usage = """usage: %prog [options] ics_file [timezone]"""
    parser = OptionParser(usage=usage, version=version)
    parser.set_description("change_tz will convert the timezones in an ics file. ")

    parser.add_option(
        "-u", "--only-utc", dest="utc", action="store_true", default=False, help="Only change UTC events."
    )
    parser.add_option("-l", "--list", dest="list", action="store_true", default=False, help="List available timezones")

    (cmdline_options, args) = parser.parse_args()
    if not args and not cmdline_options.list:
        print "error: too few arguments given"
        print
        print parser.format_help()
        return False, False

    return cmdline_options, args
Example #30
0
def pack_storage_main():
    parser = OptionParser()
    parser.set_description("Packs a Durus storage.")
    parser.add_option(
        '--file', dest="file", default=None,
        help="If this is not given, the storage is through a Durus server.")
    parser.add_option(
        '--port', dest="port", default=DEFAULT_PORT,
        type="int",
        help="Port the server is on. (default=%s)" % DEFAULT_PORT)
    parser.add_option(
        '--host', dest="host", default=DEFAULT_HOST,
        help="Host of the server. (default=%s)" % DEFAULT_HOST)
    (options, args) = parser.parse_args()
    if options.file is None:
        wait_for_server(options.host, options.port)
        storage = ClientStorage(host=options.host, port=options.port)
    else:
        storage = get_storage(options.file)
    connection = Connection(storage)
    connection.pack()
Example #31
0
def main():

	"""
reads rosetta-formatted energy values to create an Interaction graph
	"""

	parser = OptionParser()
	parser.add_option("-f", dest="file", help="file")
	parser.add_option("-o", dest="outfile", help="outfile")
	parser.set_description(main.__doc__)
	(options,args) = parser.parse_args()

	nrotamers = 0
	none = 0
	ntwo = 0

	if not options.file or not options.outfile:
		parser.print_help()
		sys.exit()

	try:
		FILE = open(options.file)
	except:
		print "unable to open file"
		sys.exit()

	#ene = ["e1", "e2", "e3", "e4", "e5", "e6"]
	ene = ["e1", "e2", "e3"]

	try:
		OUTPUT = open(options.outfile, 'w')
	except:
		print "unable to open outfile"
		sys.exit()


	bNeigh = False;
	bInfo = False;
	rotamer = {}
	one_body = {}
	two_body = {}
	func = 0
	cfun = -1
	one = False
	two = False
	for line in FILE:
		line = string.rstrip(line)
		if line == "neighbor info":
			bNeigh = True
			OUTPUT.write("NEIGHBOR_INFO\n")
			print "reading neighbors"
			continue

		if line == "rotamer info":
			bInfo = True
			bNeigh = False
			OUTPUT.write("ROTAMER_INFO\n")
			print "reading rotamers"
			continue

		cols = line.split()
		if len(cols) < 2:
			continue

		if cols[0] == "function":
			ie  = ene[func]
			func += 1
			cfun += 1
			bInfo = False
			print "reading function",func
			continue

		if cols[1] == "body" and cols[0] == "2":
			two = True
			print "reading 2-body"
			continue

		if cols[1] == "body" and cols[0] == "1":
			one = True
			two = False
			print "reading 1-body"
			continue

		if bNeigh:
			OUTPUT.write(line + "\n")

		if bInfo:
			nrotamers += 1
			rotindex = int(cols[0])
			rotamer[rotindex] = {}
			one_body[rotindex] = {}
			rotamer[rotindex]["seqpos"] = cols[1]
			rotamer[rotindex]["aatype"] = cols[2]
			rotamer[rotindex]["rotnum"] = cols[3]
			rotamer[rotindex]["chi1"]   = cols[4]
			rotamer[rotindex]["chi2"]   = cols[5]
			rotamer[rotindex]["chi3"]   = cols[6]
			rotamer[rotindex]["chi4"]   = cols[7]
			two_body[rotindex] = {}
			OUTPUT.write(line + "\n")

		if two:
			ntwo += 1
			rotindex = int(cols[0])
			partner  = int(cols[1])

			if not two_body[rotindex].has_key(partner):
				two_body[rotindex][partner] = [0]*6
				#for i in range(6):
				#	two_body[rotindex][partner][ene[i]] = "0"

			two_body[rotindex][partner][cfun] = cols[2]

		if one:
			none += 1
			rotindex = int(cols[0])
			one_body[rotindex][ene[0]] = cols[1]
			#one_body[rotindex][ene[1]] = cols[2]
			#one_body[rotindex][ene[2]] = cols[3]
			#one_body[rotindex][ene[3]] = cols[4]
			#one_body[rotindex][ene[4]] = cols[5]
			#one_body[rotindex][ene[5]] = cols[6]
			one_body[rotindex][ene[1]] = cols[2]
			if len(cols) > 3:
				one_body[rotindex][ene[2]] = cols[3]

	FILE.close()

	print "number of rotamers =",nrotamers
	print "number of 1 body =",none
	print "number of 2 body =",ntwo

	# --- sort one body energies --- #		
	OUTPUT.write("ONE_BODY:\n")
	sl = rotamer.keys()
	sl.sort()
	for mykey in sl:
		line = ""
		line += str(mykey) + " " 

		#for i in range(6):
		for i in range(3):
			line += one_body[mykey][ene[i]] + " "

		OUTPUT.write(line + "\n")

	# --- sort two body energies --- #
	OUTPUT.write("TWO_BODY:\n")
	for mykey in sl:
		# ---   sort partners   --- #
		pl = two_body[mykey].keys()
		pl.sort()
		for plkey in pl:
			line = ""
			line += str(mykey) + " " + str(plkey) + " "
			#for i in range(6):
			for i in range(3):
				line += str(two_body[mykey][plkey][i]) + " "
			
			OUTPUT.write(line + "\n")
		

	OUTPUT.close()
Example #32
0
def main():
    """
reads in and writes a pdbfile while renumbering the atoms and residues
	"""

    parser = OptionParser()
    parser.add_option("-p", dest="pdbfile", help="pdbfile")
    parser.add_option("-P", dest="pdblist", help="pdblist")
    parser.add_option("-o", dest="outfile", help="outfile")
    parser.add_option("-O", dest="outlist", help="outlist")
    parser.add_option("-r",
                      dest="replace",
                      help="replace",
                      action="store_true")
    parser.add_option("--no_atom_renumber",
                      dest="no_atrenum",
                      help="don't renumber atoms",
                      action="store_true")
    parser.add_option("--no_res_renumber",
                      dest="no_resrenum",
                      help="don't renumber residues",
                      action="store_true")
    parser.add_option("--start_residue",
                      dest="start_res",
                      help="starting residue")
    parser.set_description(main.__doc__)
    (options, args) = parser.parse_args()

    pdbfiles = []
    if options.pdblist:
        pdbfiles = files_from_list(options.pdblist)
    elif options.pdbfile:
        pdbfiles.append(options.pdbfile)
    else:
        parser.print_help()
        sys.exit()

    start_res = 0
    bAtRenum = True
    bResRenum = True
    if options.no_atrenum:
        bAtRenum = False
    if options.no_resrenum:
        bResRenum = False
    if options.start_residue:
        start_res = int(options.start_residue)

    outfiles = []
    if options.outlist:
        outfiles = files_from_list(options.outlist)
    elif options.outfile:
        outfiles.append(options.outfile)
    elif options.replace:
        for file in pdbfiles:
            outfiles.append(file)
    else:
        parser.print_help()
        sys.exit()

    npdb = len(pdbfiles)
    nout = len(outfiles)

    if npdb != nout:
        print "number of pdbfiles and output files differ"
        sys.exit()

    protein = Molecule()
    for i in range(len(pdbfiles)):
        protein.readPDB(pdbfiles[i])
        protein.writePDB(outfiles[i],
                         resRenumber=bResRenum,
                         atomRenumber=bAtRenum,
                         start_res=start_res)
        protein.clear()
Example #33
0
def main():

	"""
	prints a list of positions of catalytic residues in TIM structures
	"""

	parser = OptionParser()
	parser.add_option("-p", dest="pdbfile", help="pdbfile")
	parser.add_option("-P", dest="pdblist", help="pdblist")
	parser.add_option("-U", dest="unique_id", help="unique id")
	parser.add_option("-t", dest="TIM", help="TIM file")
	parser.add_option("-c", dest="catres", help="catres")
	parser.set_description(main.__doc__)
	(options,args) = parser.parse_args()

	pdbfiles = []
	ids      = []
	if options.pdblist:
		pdbfiles = files_from_list(options.pdblist)
	elif options.pdbfile:
		pdbfiles.append(options.pdbfile)
	elif options.unique_id:
		try:
			unique = open(options.unique_id)
		except:
			print "unable to open list of unique ids"
			sys.exit()

		for line in unique.readlines():
			cols = line.split()
			ids.append(cols[1])
	else:
		parser.print_help()
		sys.exit()

	if not options.TIM or not options.catres:
		parser.print_help()
		sys.exit()

	cresi = int(options.catres) - 1

	timmeh = TIM()
	timmeh.readTIM(options.TIM)

	protein = Enzyme()
	taken = {}

	if len(pdbfiles) > 0:
		for pdbfile in pdbfiles:
			protein.readPDB(pdbfile)
			
			if cresi >= len(protein.catalytic):
				print "accessing catalytic residue out of bounds"
				sys.exit()

			resi = int(protein.catalytic[cresi].file_id)
			myseg = timmeh.correspondingSegment(resi)

			if not myseg in taken.keys():
				taken[myseg] = 1
			else:
				taken[myseg] += 1

			protein.clear()

	if len(ids) > 0:
		for id in ids:
			wrd = id.split("_")

			if cresi >= len(wrd):
				print "accessing catalytic residue out of bounds"
				sys.exit()

			resi = int(wrd[cresi][1:])
			myseg = timmeh.correspondingSegment(resi)

			if not myseg in taken.keys():
				taken[myseg] = 1
			else:
				taken[myseg] += 1


	for key in taken.keys():
		print key,"-",taken[key]
Example #34
0
def main():
    """
modifies a grid to include a selection in a pdbfile or list of pdbfiles
	"""

    parser = OptionParser()
    parser.add_option("-p", dest="pdbfile", help="pdbfile")
    parser.add_option("-P", dest="pdblist", help="pdblist")
    parser.add_option("-g", dest="grid", help="grid")
    parser.add_option("-o", dest="outfile", help="outfile")
    parser.add_option("-s", dest="selection", help="selection")
    parser.set_description(main.__doc__)
    (options, args) = parser.parse_args()

    pdbfiles = []
    if options.pdblist:
        try:
            LIST = open(options.pdblist, 'r')
        except:
            print "unable to open pdblist"
            sys.exit()

        for line in LIST.readlines():
            line = string.rstrip(line)
            pdbfiles.append(line)
    elif options.pdbfile:
        pdbfiles.append(options.pdbfile)
    else:
        parser.print_help()
        sys.exit()

    if not options.grid or not options.outfile:
        parser.print_help()
        sys.exit()

    try:
        OUTPUT = open(options.outfile, 'w')
    except:
        print "unable to create outfile"
        sys.exit()

    if options.selection:
        selection = Selection()
        selection.makeSelection(options.selection)

    protein = Molecule()

    mygrid = grid()
    mygrid.read(options.grid)

    for pdbfile in pdbfiles:
        protein.readPDB(pdbfile)
        if options.selection:
            newmol = selection.apply_selection(protein)
        else:
            newmol = protein.clone()

        atomlist = atomsInGrid(mygrid, newmol)
        OUTPUT.write(pdbfile + ": " + str(len(atomlist)) + "\n")
        print pdbfile, len(atomlist)

        protein.clear()
        newmol.clear()

    OUTPUT.close()
Example #35
0
#!/usr/bin/env python

import os
import sys
import pwd
import signal
import subprocess

from getpass import getuser
from optparse import OptionParser

# parsing the command line
parser = OptionParser()
parser.set_description("""'superclean' is a script used to clean the current \
working directory of files, hidden directories, and processes that may have \
occured from running reduce.py. An option must be selected from the list \
below.
""")
parser.add_option("-a",
                  "--adcc",
                  dest="adcc_process",
                  action="store_true",
                  default=False,
                  help="stop all user adcc processes currently running")
parser.add_option("-c",
                  "--cache",
                  dest="cache",
                  action="store_true",
                  default=False,
                  help="clear the cache directory (.reducecache)")
parser.add_option("-d",
# third party modules
from rdc import create_app
from rdc import default_config

# local modules

#---------------------------- Main Part ---------------------------------------

if __name__ == '__main__':

    usage = "usage: %prog [options]"

    parser = OptionParser(usage)

    parser.set_description("Run Wsgi application")

    parser.add_option("-v",
                      "--verbose",
                      dest="verbose",
                      help="Verbose mode",
                      action="store_true",
                      default=False)

    (options, args) = parser.parse_args()

    if len(args) != 0:
        parser.error("Error: incorrect number of arguments, try --help")
    os.environ[
        'RDC_SETTINGS'] = '/home/jojoweb/.virtualenvs/rdc/config/rdc.config'
    app = create_app()
Example #37
0
def main():
    """
	measures the rmsd variation in a loop
	"""

    parser = OptionParser()
    parser.add_option("-t", dest="target", help="target")
    parser.add_option("-p", dest="pdbfile", help="pdbfile")
    parser.add_option("-P", dest="pdblist", help="pdblist")
    parser.add_option("-o", dest="outfile", help="outfile")
    parser.add_option("-l", dest="loop", help="loop")
    parser.set_description(main.__doc__)
    (options, args) = parser.parse_args()

    pdbfiles = []
    if options.pdblist:
        try:
            LIST = open(options.pdblist)
        except:
            print "unable to open pdblist:", options.pdblist
            sys.exit()

        for line in LIST.readlines():
            line = string.rstrip(line)
            pdbfiles.append(line)
    elif options.pdbfile:
        pdbfiles.append(options.pdbfile)
    else:
        parser.print_help()
        sys.exit()

    if not options.target:
        parser.print_help()
        sys.exit()

    if not options.loop:
        parser.print_help()
        sys.exit()

    (bl, el) = options.loop.split("-")
    beg_loop = int(bl) - 1
    end_loop = int(el) + 1
    loopsel = ";resi=1-" + str(beg_loop) + "," + str(end_loop) + "-5000"

    target = Molecule()
    target.readPDB(options.target)

    selBB = "name= N  , CA , C  , O  "
    selLoop = selBB + loopsel

    myselBB = Selection()
    myselLoop = Selection()

    myselBB.makeSelection(selBB)
    myselLoop.makeSelection(selLoop)

    tarBB = myselBB.apply_selection(target)
    tarloop = myselLoop.apply_selection(target)

    probe = Molecule()
    for pdb in pdbfiles:
        probe.readPDB(pdb)
        probeloop = myselLoop.apply_selection(probe)
        probeBB = myselBB.apply_selection(probe)

        superimpose_molecule(tarloop, probeloop, probeBB)
        print "tarBB = ", tarBB.numAtoms()
        print "probeBB = ", probeBB.numAtoms()
        rms = fit(tarBB, probeBB)
        print "rms = ", rms

        probeloop.clear()
        probeBB.clear()
        probe.clear()
Example #38
0
def main():

	"""
Renumbers ligand atoms starting at 9000
Useful when trying to select ligand atoms by their atom id
	"""

	parser = OptionParser()
	parser.add_option("-p", dest="pdbfile", help="pdbfile")
	parser.add_option("-P", dest="pdblist", help="pdblist")
	parser.add_option("-o", dest="outfile", help="outfile")
	parser.add_option("-O", dest="outlist", help="outlist")
	parser.add_option("-r", dest="replace", help="replace", action="store_true")
	parser.set_description(main.__doc__)
	(options, args) = parser.parse_args()

	pdbfiles = []
	if options.pdblist:
		pdbfiles = files_from_list(options.pdblist)
	elif options.pdbfile:
		pdbfiles.append(options.pdbfile)
	else:
		parser.print_help()
		sys.exit()

	outfiles = []
	if options.outlist:
		outfiles = files_from_list(options.outlist)
	elif options.outfile:
		outfiles.append(options.outfile)
	elif options.replace:
		for file in pdbfiles:
			outfiles.append(file)
	else:
		parser.print_help()
		sys.exit()

	het = re.compile("HETATM")

	for i in range(len(pdbfiles)):
		try:
			PDBFILE = open(pdbfiles[i])
		except:
			print "can't open pdbfile"
			sys.exit()

		mylines = PDBFILE.readlines()
		PDBFILE.close()

		try:
			OUTFILE = open(outfiles[i],'w')
		except:
			print "can't write to outfile"
			sys.exit()

		nat = 9000
		for line in mylines:
			newline = line
			if het.match(line):
				nat += 1
				nat = min(nat,9999)
				newline = "HETATM %4s%s"%(str(nat),line[11:])

			OUTFILE.write(newline)

		OUTFILE.close()
Example #39
0
def main():

	"""
creates a grid given a template of a previous grid
This creates a gridlig and a gridbb
	"""

	parser = OptionParser()
	parser.add_option("-p", dest="pdbfile", help="pdbfile")
	parser.add_option("-s", dest="statefile", help="statefile")
	parser.add_option("-o", dest="outname", help="outname")
	parser.add_option("-l", dest="ligcutoff", help="gridlig cutoff", default=2.5)
	parser.add_option("-b", dest="bbcutoff", help="gridbb cutoff", default=2.0)
	parser.set_description(main.__doc__)
	(options, args) = parser.parse_args()

	if not options.pdbfile or not options.statefile or not options.outname:
		parser.print_help()
		sys.exit()

	# get output filename
	cols = options.outname.split(".")
	outgridlig = cols[0] + ".gridlig"
	outgridbb = cols[0] + ".gridbb"

	# get backbone from protein
	protein = Molecule()
	protein.readPDB(options.pdbfile)
	
	sele = Selection()
	sele.makeSelection("BB")
	bb = sele.apply_selection(protein).atomList()

	# read in previous statefile information
	try:
		STATEFILE = open(options.statefile)
	except:
		print "unable to open statefile"
		sys.exit()

	gridlig_file = ""
	gridbb_file  = ""
	for line in STATEFILE.readlines():
		cols = line.split()
		if cols[0] == "gridlig:":
			gridlig_file = cols[1]
		if cols[0] == "gridbb:":
			gridbb_file = cols[1]

	gridlig = grid()
	gridbb  = grid()

	gridlig.read(gridlig_file)
	gridbb.read(gridbb_file)

	gridlig.setFullOccupied()
	gridbb.setFullOccupied()

	ligcutoff = float(options.ligcutoff)
	bbcutoff = float(options.bbcutoff)
	gridTrimInclude(gridbb, bb, bbcutoff)
	gridTrimExclude(gridlig, bb, ligcutoff)

	gridlig.write(outgridlig)
	gridbb.write(outgridbb)
Example #40
0
            prevChr = read.reference_id

        #clean up
        samfile.close()
        if self._newMolecFH != None:
            self._newMolecFH.close()
        if self._outfilebam != None:
            self._outfilebam.close()


if __name__ == '__main__':

    # specify parser options
    parser = OptionParser()
    parser.set_description(
        "Takes a bam file via stdin and outputs molecules to a bed-like (1-based coordinates) TSV file. Read to genome bam file used must be sorted by BX tag and then by position."
    )
    parser.add_option(
        "-b",
        "--bam",
        dest="bam",
        help="Read to genome BAM file file instead of stdin (optional)",
        metavar="BAM")
    parser.add_option(
        "-d",
        "--dist",
        dest="dist",
        help=
        "Minimum distance between reads to be considered the same molecule [60000]",
        metavar="DIST")
    parser.add_option(
Example #41
0
def main():
    """
	takes a ligand and grafts it into another pdbfile after a superimposition
	"""

    parser = OptionParser()
    parser.add_option("-p", dest="pdbfile", help="pdbfile")
    parser.add_option("-P", dest="pdblist", help="pdblist")
    parser.add_option("-l", dest="ligand", help="ligand")
    parser.add_option("-s", dest="protein_selection", help="protein selection")
    parser.add_option("-t", dest="ligand_selection", help="ligand selection")
    parser.add_option("-o", dest="outfile", help="outfile")
    parser.add_option("-O", dest="outlist", help="outlist")
    parser.add_option("-r",
                      dest="replace",
                      help="replace",
                      action="store_true")
    parser.set_description(main.__doc__)
    (options, args) = parser.parse_args()

    # setup files
    pdbfiles = []
    if options.pdblist:
        pdbfiles = files_from_list(options.pdblist)
    elif options.pdbfile:
        pdbfiles.append(options.pdbfile)
    else:
        parser.print_help()
        sys.exit()

    outfiles = []
    if options.outlist:
        outfiles = files_from_list(options.outlist)
    elif options.outfile:
        outfiles.append(options.outfile)
    elif options.replace:
        outfiles = pdbfiles
    else:
        parser.print_help()
        sys.exit()

    if not options.ligand:
        parser.print_help()
        sys.exit()

    if len(pdbfiles) != len(outfiles):
        print "number of files differ"
        sys.exit()

    # get selections
    if not options.protein_selection or not options.ligand_selection:
        parser.print_help()
        sys.exit()

    sele = Selection()
    ligselection = "HET;" + options.ligand_selection
    sele.makeSelection(ligselection)
    ligMol = Molecule()
    ligMol.readPDB(options.ligand)
    ligand = sele.apply_selection(ligMol)

    if ligand.numResidues() != 1:
        print "ligand does not contain 1 residue"
        print ligand.numResidues()
        sys.exit()

    target = Molecule()
    sele.clear()
    sele.makeSelection(options.protein_selection)
    for i in range(len(pdbfiles)):
        print pdbfiles[i]
        target.readPDB(pdbfiles[i])
        tar = sele.apply_selection(target)
        ligMol2 = ligMol.clone()
        superimpose_molecule(tar, ligand, ligMol2)

        # graft new ligand onto existing target
        ligRes = ligMol2.chain[0].residue[0]
        ligChain = target.chain[1]
        ligChain.clear()
        ligChain.addResidue(ligRes)

        if target.numChains() > 2:
            for j in range(2, target.numChains()):
                target.chain[j].clear()

        target.writePDB(outfiles[i], resRenumber=False)
        target.clear()
        ligMol2.clear()
Example #42
0
    set = {}
    return [set.setdefault(e, e) for e in alist if e not in set]


def stripQuotes(s):
    return s.strip(" \n\t").strip('"')


if __name__ == '__main__':

    parser = OptionParser()
    parser.set_usage(parser.get_prog_name() +
                     " input_file_or_wildcard_pattern")
    parser.set_description(
        """For each input file (should be .finalBest.csv or finalCheckedBest.csv) 
creates a new .singleBest that contains only the single row that had the best fitness. 
 Uses 'rechecked' if the 'best-fitness-rechecked' column is present in the file."""
    )
    parser.add_option(
        "-m",
        "--minimize",
        action="store_true",
        dest="minimize",
        help=
        "choose the line with the smallest (rather than largest) fitness value."
    )
    #parser.add_option("-r", "--rechecked", action="store_true", dest="rechecked", help="use the rechecked fitness values to choose the best.")

    options, filepatterns = parser.parse_args()
    if (len(filepatterns) == 0):
        parser.print_help()
Example #43
0
def main():
    """
clusters matches after minimization
	"""

    parser = OptionParser()
    parser.add_option("-l", dest="list", help="list")
    parser.add_option("-o", dest="outfile", help="outfile")
    parser.add_option("-n", dest="number", help="number", default=5)
    parser.add_option("-v",
                      dest="verbose",
                      help="verbose",
                      action="store_true")
    parser.set_description(main.__doc__)
    (options, args) = parser.parse_args()

    if not options.list or not options.outfile:
        parser.print_help()
        sys.exit()

    try:
        OUTFILE = open(options.outfile, 'w')
    except:
        print "unable to create outfile"
        sys.exit()

    match_list = files_from_list(options.list)
    rbmin_list = []
    for file in match_list:
        base = get_basefile(file)
        rbmin = base + "_rbmin.pdb"
        rbmin_list.append(rbmin)

    # --- make clusters based on location --- #
    clusters = {}
    protein = Molecule()
    for i in range(len(match_list)):
        file = match_list[i]
        cols = file.split("_")
        grid = cols[1]
        if not grid in clusters.keys():
            clusters[grid] = {}

        protein.readPDB(file)
        cat = getCatalyticResidues(protein)

        seq = ""
        for c in cat:
            seq += c.name + c.file_id.strip() + "_"

        if not seq in clusters[grid].keys():
            clusters[grid][seq] = []

        clusters[grid][seq].append(rbmin_list[i])
        protein.clear()

    for grid in clusters.keys():
        if options.verbose:
            OUTFILE.write(grid + "\n")

        for seq in clusters[grid].keys():
            if options.verbose:
                OUTFILE.write("   seq: " + seq + "\n")

            mycluster = clusters[grid][seq]
            scores = {}
            for file in mycluster:
                ene = commands.getoutput("grep lig_sum " + file)
                cols = ene.split()
                sum = float(cols[1])
                scores[file] = sum

            i = scores.items()
            i.sort(lambda x, y: cmp(x[1], y[1]))
            nbest = 0
            for bestfile in i:
                if options.verbose:
                    OUTFILE.write("      " + bestfile[0] + " " +
                                  str(bestfile[1]) + "\n")
                else:
                    output = bestfile[0].replace("_rbmin", "")
                    OUTFILE.write(output + "\n")
                nbest += 1
                if nbest == int(options.number):
                    break

        if options.verbose:
            OUTFILE.write("----------------\n")

    OUTFILE.close()
# Check if $DISPLAY is set (for handling plotting on remote machines with no X-forwarding)
if os.environ.has_key('DISPLAY'):
    import matplotlib.pyplot as plt
else:
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt

pd.set_option('precision', 10)

if __name__ == '__main__':
    from optparse import OptionParser
    o = OptionParser()
    o.set_usage('%prog [options] DAT_OR_PKL')
    o.set_description(__doc__)
    o.add_option('-i', '--ignore', action='store_true',
        help='Ignore all flags and plot all')
    o.add_option('-u', '--unflagged', action='store_true',
        help='Only plot unflagged events')
    o.add_option('-S', '--savefig', default=None,
        help='Save figure to file, file type determined based on extension.')
    o.add_option('--nodisplay', action='store_true',
        help='Do not display the figure')
    o.add_option('--utc', dest='utc', action='store_true',
        help='Show UTC on X-axis')
    o.add_option('--utc_start', dest='utc_start', default=None,
        help='Start datetime string in UTC, format: YYYYMMDD_HHMMSS')
    o.add_option('--utc_end', dest='utc_end', default=None,
        help='End datetime string in UTC, format: YYYYMMDD_HHMMSS')
    o.add_option('--log', dest='log', action='store_true',
Example #45
0
def main():
    """
	grafts loops from a loop library onto a ligand dumpfile
	"""

    parser = OptionParser()
    parser.add_option("-p", dest="pdbfile", help="pdbfile")
    parser.add_option("-P", dest="pdblist", help="pdblist")
    parser.add_option("-s", dest="scaffold", help="scaffold")
    parser.add_option("-o", dest="outfile", help="outfile")
    parser.add_option("-O", dest="outlist", help="outlist")
    parser.add_option("-r",
                      dest="replace",
                      help="replace",
                      action="store_true")
    parser.add_option("-l", dest="loop_lib", help="loop_library")
    parser.set_description(main.__doc__)
    (options, args) = parser.parse_args()

    pdbfiles = []
    if options.pdblist:
        pdbfiles = files_from_list(options.pdblist)
    elif options.pdbfile:
        pdbfiles.append(options.pdbfile)
    else:
        parser.print_help()
        sys.exit()

    outfiles = []
    if options.outlist:
        outfiles = files_from_list(options.outlist)
    elif options.outfile:
        outfiles.append(options.outfile)
    elif options.replace:
        outfiles = pdbfiles
    else:
        parser.print_help()
        sys.exit()

    if not options.scaffold:
        parser.print_help()
        sys.exit()

    if not options.loop_lib:
        parser.print_help()
        sys.exit()

    protein = Molecule()
    protein.readPDB(options.scaffold)
    scaffold = protein.getChain("A")

    # read in loop library
    try:
        LOOP_LIB = open(options.loop_lib)
    except:
        print "unable to open loop library"
        sys.exit()

    cols = []
    for line in LOOP_LIB.readlines():
        line = string.rstrip(line)
        cols = line.split()
        print cols[0]

    sys.exit()
    mol = Molecule()
    for i in range(len(pdbfiles)):
        print pdbfiles[i]
        chainA = scaffold.clone()

        mol.readPDB(pdbfiles[i])
        chainB = mol.getChain("B")
        chainB.renumber(atomRenumber=False)

        mol.chain.insert(0, chainA)
        mol.writePDB(outfiles[i], resRenumber=False, atomRenumber=False)
        mol.clear()
Example #46
0
                 dest='update',
                 action='store_false',
                 default=True,
                 help='Do not update the plots (only plot a single capture).')

    #    p.add_option('-n', '--n_chans', dest='n_chans', type='int',default=512,
    #        help='Plot this number of channels. Default: 512')
    #    p.add_option('-l', '--plot_lin', dest='plot_lin', action='store_true',
    #        help='Plot on linear axes. Default: semilogy.')
    p.add_option('-p',
                 '--no_plot',
                 dest='plot',
                 action='store_false',
                 default=True,
                 help="Don't plot anything.")
    p.set_description(__doc__)
    opts, args = p.parse_args(sys.argv[1:])

    usrlog = ('Starting file at %i.' % (int(time.time()))).join(args)
    if usrlog == '': usrlog = str(int(time.time()))
    #plot_chans=opts.n_chans
    freq_range = opts.freq_range
    #ant=opts.ant
    n_top = opts.n_top
    verbose = opts.verbose
    plot_baseline = opts.baseline
    plot_diff = opts.diff
    #cal_mode=opts.cal
    config_file = opts.config_file
    play_filename = opts.play_file
Example #47
0
def cmdParse():
    usage = "%prog [options] args ... "
    version = "\nMailbox2Netdisk (v1.0) by [email protected] on May 5th, 2013\n"
    description = "Welcome to use this <Mailbox To Netdisk> tool.You can use your email's mailbox as a net disk by IMAP protocol.For your email accout's security, your email server must support IMAP SSL. To get new version ,please visit https://github.com/shadu120/mailbox2netdisk"
    parser = OptionParser(usage=usage, version=version)
    parser.set_description(description)
    parser.add_option(
        "-l",
        "--list",
        action="store_true",
        dest="list",
        help="list files in net disk,include the id of each file.")
    parser.add_option(
        "-c",
        "--continue",
        action="store_true",
        dest="continues",
        help=
        "continue to upload all the unfinished files for network disconnect or other reasons."
    )
    parser.add_option("-d",
                      "--download",
                      action="store",
                      dest="download",
                      type="int",
                      metavar="FILE_ID",
                      help="download a file from net disk by given file id")
    parser.add_option("-r",
                      "--remove",
                      action="store",
                      dest="remove",
                      type="int",
                      metavar="FILE_ID",
                      help="remove a file from net disk by given file id")
    parser.add_option("-u",
                      "--upload",
                      action="store",
                      dest="upload",
                      type="string",
                      metavar="FILE_NAME",
                      help="upload a file to net disk, eg: c:\\test\\test.mp3")

    group = OptionGroup(parser, "upload parameters",
                        "important parameters when \"-u\" is using.")
    group.add_option(
        "-f",
        "--folder",
        action="store",
        dest="folder",
        type="string",
        metavar="REMOTE_FOLDER",
        help=
        "which folder you want to store the file on net disk,eg: /video/, default is /.",
        default="/")
    group.add_option(
        "-s",
        "--size",
        action="store",
        dest="size",
        type="int",
        metavar="SIZE",
        help=
        "splited file size in MB, default is 2. this depends on your email attachment limits and your network quality",
        default=2)
    group.add_option(
        "-e",
        "--Encrypt",
        action="store_true",
        dest="encrypt",
        help=
        "encrypt the file before storing to net disk.RAR command tool should be installed first, such as \"C:\Program Files\WinRAR\RAR.exe\" or \"/usr/bin/rar\""
    )
    group.add_option(
        "-v",
        "--Verify",
        action="store_true",
        dest="verify",
        help=
        "verify the splited files after uploading.this will cost you much more time.Unfortunately, this fucntion has not been implemented now."
    )

    parser.add_option_group(group)
    (options, args) = parser.parse_args()

    if options.list:
        M2D().list()
    elif options.continues:
        M2D().uploadAll()
    elif options.download:
        if options.download > 0:
            M2D().download(options.download)
        else:
            print 'invalid file id'
    elif options.remove:
        if options.remove > 0:
            M2D().delete(options.remove)
        else:
            print 'invalid file id'
    elif options.upload:
        filename = getUnicodeArgv(options.upload)
        if not os.path.exists(filename) or not os.path.getsize(filename) > 0:
            print 'File not exists'
            return
        m2d = M2D()
        m2d.OriginalFileFullName = filename
        if not options.folder.endswith('/'):
            m2d.RemoteFolderName = options.folder + "/"
        else:
            m2d.RemoteFolderName = options.folder
        m2d.SingleFileMBSize = options.size
        m2d.bEncryptRemoteFile = (options.encrypt == True)
        m2d.upload()
    else:
        parser.print_help()
Example #48
0
            return ret
        material = self.JSON['results'][-1]['material']
        if len(material):
            for m in material:
                if m['id'] == 'minutes': ret = m['resources'][-1]['url']
        return ret


if __name__ == '__main__':
    from optparse import OptionParser
    fStr = ""
    parser = OptionParser()
    usage = "Usage: %prog [options]"
    description = "fetch Indico content from %s" % GLOB_HOSTNAME
    parser.set_usage(usage)
    parser.set_description(description)
    parser.add_option("--title",
                      dest='title',
                      default='Simulation Group Meetings',
                      help="title to be used in twiki")
    parser.add_option("--file",
                      dest='file',
                      default=None,
                      help="if set, write output to file")
    parser.add_option("--topic",
                      dest='topicParent',
                      default='DampeSimulation',
                      help="title to be used in twiki")
    parser.add_option("--meeting_title",
                      dest='mtitle',
                      default="DAMPESW Simulation ",
Example #49
0
class HelpPanel(object):
    def __init__(self):
        self.version="1.0.0"
        self.author='Joseph.XRays'
        self.blog='https://www.joxrays.com'

        super().__init__()
        self.output_logo()
        self.__optparser=OptionParser()
        self.set_usage()
        self.set_description()
        self.initialized_panel()
        self.__optBox=OptionBox()
        self.parser_options()

    def __getitem__(self, option):
        return self.__optBox.get_value(option)

    def set_description(self):
        self.__optparser.set_description('proxyGet is a spider script which can sniff the website free proxies and store in the local database.')
    def set_usage(self):
        self.__optparser.set_usage('proxyGet.py [-0/1/2/3/4] [-5/6/7/8] [Opts] [SQL_Opt] [-h/-v/--author]')

    def initialized_panel(self):
        self.__optparser.add_option('-v','--version',action='store_true',dest='version',help='display the version info')
        self.__optparser.add_option('-m','--max',action='store',metavar='N',dest='max_proxies',default=20,help='maximum number of proxies [:20] all:-1',type='int')
        self.__optparser.add_option('-r','--retry',action='store',metavar='CNT',dest='retry',default=2,help='the number of retries [:2]',type='int')
        self.__optparser.add_option('-t','--timeout',action='store',metavar='SEC',dest='timeout',default=5,help='the timeout for connecting to the url [:5]',type='int')
        self.__optparser.add_option('--author',action='store_true',dest='author',help='display the author info')
        self.__optparser.add_option('--overwrite',action='store_true',dest='overwrite',help='overwrite if the database exists')
        self.__optparser.add_option('-a','--async',action='store_true',dest='_async',help='asynchronous fetch proxies')
        self.__optparser.add_option('--from',action='store',metavar='PAGE_INDEX',dest='from_page_index',default=1,help='from page index [:1]',type='int')
        self.__optparser.add_option('--to',action='store',metavar='PAGE_INDEX',dest='to_page_index',default=1,help='to page index [:1]',type='int')

        self.__group_store_way=OptionGroup(self.__optparser,'Store in local databases or file,default sqlite3')
        self.__group_store_way.add_option('--sqlite3',dest='sqlite3',action='store_true',help='store the proxies in local  sqlite3 database')
        self.__group_store_way.add_option('--mysql',dest='mysql',action='store_true',help='store the proxies in local or remote mysql database')

        self.__extra_option=OptionGroup(self.__optparser,'Extra SQL options')
        # mysql option info
        self.__extra_option.add_option('--host',metavar='HOST',dest='mysql_host',default='localhost',help='specifies mysql local or remote host [:localhost]',action='store',type='string')
        self.__extra_option.add_option('--port',metavar='PORT',dest='mysql_port',default=3306,help='specifies mysql local or remote port [:3306]',action='store',type='int')
        self.__extra_option.add_option('--database',metavar='DB',dest='mysql_db',default='db_proxy',help='specifies mysql database name [:db_proxy]',action='store',type='string')
        self.__extra_option.add_option('-u','--user',metavar='U',dest='mysql_user',help='specifies mysql user',action='store',type='string')
        self.__extra_option.add_option('-p','--pwd',metavar='P',dest='mysql_pwd',help='specifies mysql password',action='store',type='string')
        # sqlite option info
        self.__extra_option.add_option('-f','--file',metavar='FILE',dest='sqlite_file_path',default='db/test.db',help='specifies sqlite3 database file path [:db/test.db]',action='store',type='string')
        # common option info
        self.__extra_option.add_option('--table',metavar='TB',dest='mysql_sqlite_tb',default='tb_proxy',help='specifies mysql or sqlite3 table name [:tb_proxy]',action='store',type='string')

        # different free proxy websites
        self.__website_type=OptionGroup(self.__optparser,'Website type and support proxy type')
        self.__website_type.add_option('-0',action='store_true',dest='proxy_type_xila',help='the proxy type is Xila -5/6/7/8')
        self.__website_type.add_option('-1',action='store_true',dest='proxy_type_nima',help='the proxy type is Nima -5/6/7/8')
        self.__website_type.add_option('-2',action='store_true',dest='proxy_type_xici',help='the proxy type is Xici -5/6/7/8')
        self.__website_type.add_option('-3',action='store_true',dest='proxy_type_kuai',help='the proxy type is Kuai -5/6')
        self.__website_type.add_option('-4',action='store_true',dest='proxy_type_yip7',help='the proxy type is 7Yip -7')

        # proxy type
        self.__proxy_subtype = OptionGroup(self.__optparser, 'Proxy type')
        self.__proxy_subtype.add_option('-5',action='store_true',dest='proxy_common',help='common proxy type')
        self.__proxy_subtype.add_option('-6',action='store_true',dest='proxy_high_anonymous',help='high anonymous proxy type')
        self.__proxy_subtype.add_option('-7',action='store_true',dest='proxy_http',help='http proxy type')
        self.__proxy_subtype.add_option('-8',action='store_true',dest='proxy_https',help='https proxy type')

        self.__optparser.add_option_group(self.__website_type)
        self.__optparser.add_option_group(self.__proxy_subtype)
        self.__optparser.add_option_group(self.__group_store_way)
        self.__optparser.add_option_group(self.__extra_option)
        (opt,args)=self.__optparser.parse_args()
        self.__opt=opt

    def parser_options(self):
        self.__optBox.add_key_value('proxy_type_xila',self.__opt.proxy_type_xila)
        self.__optBox.add_key_value('proxy_type_nima',self.__opt.proxy_type_nima)
        self.__optBox.add_key_value('proxy_type_xici',self.__opt.proxy_type_xici)
        self.__optBox.add_key_value('proxy_type_kuai',self.__opt.proxy_type_kuai)
        self.__optBox.add_key_value('proxy_type_yip7',self.__opt.proxy_type_yip7)

        self.__optBox.add_key_value('proxy_common',self.__opt.proxy_common)
        self.__optBox.add_key_value('proxy_high_anonymous',self.__opt.proxy_high_anonymous)
        self.__optBox.add_key_value('proxy_http',self.__opt.proxy_http)
        self.__optBox.add_key_value('proxy_https',self.__opt.proxy_https)

        self.__optBox.add_key_value('max_proxies',self.__opt.max_proxies)
        self.__optBox.add_key_value('retry',self.__opt.retry)
        self.__optBox.add_key_value('timeout',self.__opt.timeout)
        self.__optBox.add_key_value('author',self.__opt.author)
        self.__optBox.add_key_value('version',self.__opt.version)
        self.__optBox.add_key_value('overwrite',self.__opt.overwrite)
        self.__optBox.add_key_value('from_page_index',self.__opt.from_page_index)
        self.__optBox.add_key_value('to_page_index',self.__opt.to_page_index)
        self.__optBox.add_key_value('_async',self.__opt._async)

        self.__optBox.add_key_value('sqlite3',self.__opt.sqlite3)
        self.__optBox.add_key_value('mysql',self.__opt.mysql)

        self.__optBox.add_key_value('mysql_host',self.__opt.mysql_host)
        self.__optBox.add_key_value('mysql_port',self.__opt.mysql_port)
        self.__optBox.add_key_value('mysql_user',self.__opt.mysql_user)
        self.__optBox.add_key_value('mysql_pwd',self.__opt.mysql_pwd)
        self.__optBox.add_key_value('mysql_db',self.__opt.mysql_db)
        self.__optBox.add_key_value('mysql_sqlite_tb',self.__opt.mysql_sqlite_tb)
        self.__optBox.add_key_value('sqlite_file_path',self.__opt.sqlite_file_path)

        if self.__optBox['author']:
            self.display_author_info()
            exit(0)
        if self.__optBox['version']:
            CliMessage.print_with_status(f"proxyGet version: v{self.version}")
            exit(0)

        if self.__optBox['proxy_type_xila']:
            self.interface = proxyServer.XilaProxy
            self.collect = collectProxyList.Xila
        elif self.__optBox['proxy_type_nima']:
            self.interface = proxyServer.NimaProxy
            self.collect = collectProxyList.Nima
        elif self.__optBox['proxy_type_xici']:
            self.interface = proxyServer.XiciProxy
            self.collect = collectProxyList.Xici
        elif self.__optBox['proxy_type_kuai']:
            self.interface = proxyServer.KuaiProxy
            self.collect = collectProxyList.Kuai
        elif self.__optBox['proxy_type_yip7']:
            self.interface = proxyServer.Yip7Proxy
            self.collect = collectProxyList.Yip7
        else:
            CliMessage.print_with_status('please choose a website type!', Color.Red, None, None, 'failed')
            exit(-1)
        if self.interface != proxyServer.Yip7Proxy and self.interface != proxyServer.KuaiProxy:
            if self.__optBox['proxy_common']:
                self.url = self.interface().commmon_proxy()
            elif self.__optBox['proxy_high_anonymous']:
                self.url = self.interface().high_anonymous_proxy()
            elif self.__optBox['proxy_http']:
                self.url = self.interface().http_proxy()
            elif self.__optBox['proxy_https']:
                self.url = self.interface().https_proxy()
            else:
                CliMessage.print_with_status('please choose a proxy type!',Color.Red,None,None,'failed')
                exit(-1)
        elif self.interface==proxyServer.KuaiProxy:
            if self.__optBox['proxy_common']:
                self.url = self.interface().commmon_proxy()
            elif self.__optBox['proxy_high_anonymous']:
                self.url = self.interface().high_anonymous_proxy()
            else:
                CliMessage.print_with_status('please choose a proxy type!', Color.Red, None, None, 'failed')
                exit(-1)
        else:
            if self.__optBox['proxy_http']:
                self.url = self.interface().http_proxy()
            else:
                CliMessage.print_with_status('please choose a proxy type!',Color.Red,None,None,'failed')
                exit(-1)
    def display_author_info(self):
        CliMessage.print_with_status(f'Author: {self.author}',Color.Cyan)
        CliMessage.print_with_status(f'Blog: {self.blog}',Color.Green)
    def output_logo(self):
        CliMessage.print(Logo.text(),Color.random_fgcolor(),Color.Bold)
    @property
    def optionBox(self):
        return self.__optBox
Example #50
0
from __future__ import print_function
from optparse import OptionParser

# third party modules

#---------------------------- Main Part ---------------------------------------

if __name__ == '__main__':

    usage = "usage: %prog [options]"

    parser = OptionParser(usage)

    parser.set_description("""
    This script is done to test elasticserarch for Invenio.
    It should be replaced by unittests.
    Bascally it create a new index, index 100 records and perform a search
    query.
    """)

    (options, args) = parser.parse_args()
    from invenio.base.factory import create_app
    current_app = create_app()

    with current_app.test_request_context():
        print("-- Connect to the ES server --")
        es = current_app.extensions.get("elasticsearch")

        print("-- Delete old index --")
        es.delete_index()

        print("-- Create the index --")
Example #51
0
import sys
import os
import time
import random
import glob
from optparse import OptionParser
from rgbmatrix import RGBMatrix, RGBMatrixOptions
from PIL import Image, ImageDraw
from matrixdemos.scripts.get_file import get_file
from matrixdemos.scripts.utils import apply_alpha

usage = "usage: %prog [options] PATH"
parser = OptionParser(usage=usage)

parser.set_description(
    """Display a slideshow of images on the matrix, works with any size of matrix.
Set the directory of your images via the PATH argument, or a defualt set of images will be used."""
)

parser.add_option("-b",
                  "--bgcolor",
                  dest="bg",
                  default="black",
                  help="the background color")

parser.add_option("-l",
                  "--length",
                  dest="secs",
                  type=float,
                  help="set how long each slide is displayed",
                  default=3)
Example #52
0
def main():

    p = OptionParser()

    p.set_usage('%prog [options]')
    p.set_description(__doc__)
    p.add_option(
        '-p',
        '--skip_prog',
        dest='prog_fpga',
        action='store_false',
        default=True,
        help=
        'Skip FPGA programming (assumes already programmed).  Default: program the FPGAs'
    )
    p.add_option('-v',
                 '--verbosity',
                 dest='verbosity',
                 type='int',
                 default=1,
                 help='Verbosity level. Default: 1')
    p.add_option('-r',
                 '--roach',
                 dest='roach',
                 type='str',
                 default='srbsr2-1',
                 help='ROACH IP address or hostname. Default: srbsr2-1')
    p.add_option(
        '-b',
        '--boffile',
        dest='boffile',
        type='str',
        default='h1k_ver105_2013_Dec_02_1551.bof',
        help='Boffile to program. Default: h1k_ver105_2013_Dec_02_1551.bof')
    p.add_option('-N',
                 '--n_trials',
                 dest='n_trials',
                 type='int',
                 default=10,
                 help='Number of snap/fit trials. Default: 10')
    p.add_option(
        '-c',
        '--clockrate',
        dest='clockrate',
        type='float',
        default=1500.0,
        help=
        'Clock rate in MHz, for use when plotting frequency axes. If none is given, rate will be estimated from FPGA clock'
    )
    p.add_option(
        '-f',
        '--testfreq',
        dest='testfreq',
        type='float',
        default=18.3105,
        help='sine wave test frequency input in MHz. Default = 18.3105')
    p.add_option('-l',
                 '--ampl',
                 dest='ampl',
                 type='float',
                 default=3.0,
                 help='Power level of test tone input in dBm. Default = 3.0')
    p.add_option(
        '-g',
        '--gpibaddr',
        dest='gpibaddr',
        type='str',
        default='10.16.96.174',
        help=
        'IP Address of the GPIB.  Current default is set to tape room machine. Default = 10.16.96.174'
    )
    p.add_option('-s',
                 '--snapname',
                 dest='snapname',
                 type='str',
                 default='adcsnap',
                 help='snapname. Default = adcsnap')
    p.add_option(
        '-z',
        '--zdok',
        dest='zdok',
        type='int',
        default=2,
        help='ZDOK, 0 or 1, if input is 2, then refers to both. Default = 2')
    p.add_option('-d',
                 '--directory',
                 dest='dir',
                 type='str',
                 default='.',
                 help='name of directory to put all files')
    p.add_option('-o',
                 '--ogp',
                 dest='do_ogp',
                 type='int',
                 default=1,
                 help='Do OGP calibration? Default = 1')
    p.add_option(
        '-i',
        '--inl',
        dest='do_inl',
        type='int',
        default=1,
        help='Do INL calibration (OGP must be completed first)? Default = 1')
    p.add_option('-t',
                 '--test',
                 dest='test',
                 type='int',
                 default=1,
                 help='Test after calibration is completed. Default=1')
    p.add_option('-m',
                 '--manual',
                 dest='manual',
                 type='int',
                 default=1,
                 help='Manual control of the calibration process. Default=1')
    p.add_option('-S',
                 '--save',
                 dest='save',
                 type='int',
                 default=1,
                 help='To save the plots. Default=1 (save)')
    p.add_option(
        '-V',
        '--view',
        dest='view',
        type='int',
        default=1,
        help=
        'To show the plots interactively (will be forced to 0 if manual is off). Default=1 (show)'
    )
    p.add_option('-u',
                 '--update_conf',
                 dest='update_conf',
                 action='store_false',
                 default=True,
                 help='Update the <roach_name>-adc.conf file?')

    opts, args = p.parse_args(sys.argv[1:])

    # setup log file name:
    current_time = datetime.datetime.now().strftime('%Y-%m%d-%H%M%S')
    timestamp = "_%s_z%d_%s" % (opts.roach, opts.zdok, current_time)
    AdcCalLoggingFileHandler.timestamp = timestamp

    # load log config file
    var = "YGOR_TELESCOPE"
    confdir = '.' if not os.environ.has_key(var) else os.path.join(
        os.environ[var], "etc/config")
    conffile = "%s/%s" % (confdir, 'adc_cal_logging.conf')
    if not os.path.isfile(conffile):
        print "Cannot find config file for logging: %s" % conffile
        sys.exit(0)

    logging.config.fileConfig(conffile)
    logger = logging.getLogger('adc5gLogging')
    logger.info("Started")

    if not opts.verbosity:
        logger.setLevel(logging.INFO)

    logger.info("opts :\n\t" + str(opts))
    logger.info("args :\n\t" + str(args))
    logger.info("log file name:\n\t" + AdcCalLoggingFileHandler.logfilename)

    tmsg = 'Connecting to %s' % opts.roach
    logger.info(tmsg)
    r = corr.katcp_wrapper.FpgaClient(opts.roach)
    time.sleep(0.2)
    tmsg = 'ROACH is connected? ' + str(r.is_connected())
    logger.info(tmsg)

    if opts.prog_fpga:
        tmsg = 'Programming ROACH with boffile %s' % opts.boffile
        r.progdev(opts.boffile)
        time.sleep(0.5)
        logger.info(tmsg)

    tmsg = 'Estimating clock speed...'
    logger.info(tmsg)
    clk_est = r.est_brd_clk()
    tmsg = 'Clock estimated speed is %d MHz' % clk_est
    logger.info(tmsg)

    if opts.clockrate is None:
        clkrate = clk_est * 16
        print "SETTING clkrate to: ", clkrate
    else:
        clkrate = opts.clockrate

    # Before progressing furth, check that the Valon Synth
    # is actually set to the clkrate.
    # ValonKATCP is not a worker class belonging to ADCCalibrate
    # since ADCCalibrate is inherited code, while Valon is ours.
    valonSerial = "/dev/ttyS1"  # this should never change
    valonSynth = 0  # neither should this (0: A, 8: B)
    v = ValonKATCP(r, valonSerial)
    current_clkrate = v.get_frequency(valonSynth)
    tmsg = "Valon Synth set to frequency: %f MHz" % current_clkrate
    logger.info(tmsg)
    if abs(current_clkrate - clkrate) > 0.001:
        v.set_frequency(valonSynth, clkrate)
        time.sleep(1)
        current_clkrate = v.get_frequency(valonSynth)
        tmsg = "Valon Synth changed to frequency: %f MHz" % current_clkrate
        logger.info(tmsg)

    # Time to make our worker class
    cal = ADCCalibrate(dir=opts.dir,
                       roach_name=opts.roach,
                       gpib_addr=opts.gpibaddr,
                       clockrate=clkrate,
                       bof=opts.boffile,
                       config=opts.update_conf,
                       roach=r)

    cal.set_freq(opts.testfreq)
    cal.set_ampl(opts.ampl)

    if opts.prog_fpga:
        tmsg = 'Calibrating ADCs (MMCM)'
        logger.info(tmsg)
        cal.do_mmcm(opts.zdok)
        if opts.manual:
            if cal.user_input("Check the test ramps now?"):
                cal.check_ramp(opts.zdok, save=opts.save,
                               view=opts.view)  #, filename = fn)

    if opts.do_ogp or opts.test:
        if cal.gpib_test(opts.zdok,
                         opts.testfreq,
                         opts.ampl,
                         manual=opts.manual):
            tmsg = 'Current test tone power level: %.4f' % opts.ampl
            logger.debug(tmsg)
            tmsg = 'Current test tone frequency: %.4f' % opts.testfreq
            logger.debug(tmsg)
            cal.check_raw(opts.zdok,
                          save=opts.save,
                          view=(opts.manual and opts.view))
            if opts.manual:
                if cal.user_input("Adjust power level now?"):
                    cal.ampl_setup(opts.zdok, manual=True)
        else:
            tmsg = "Problem with synthesizer, aborting OGP calibration & testing..."
            logger.warning(tmsg)
            opts.do_ogp = 0
            opts.test = 0

    if opts.do_ogp:
        cal.do_ogp(opts.zdok, opts.testfreq, opts.n_trials)
        if opts.do_inl:
            cal.do_inl(opts.zdok)

    if opts.test:
        if opts.manual:
            logger.info("Startinging manual testing...")
            check_spec = cal.user_input("Check spectrum?")
            while (check_spec):
                cal.freq_setup(opts.zdok, manual=True)
                cal.ampl_setup(opts.zdok, manual=True)
                fn = cal.get_check_filename(
                    "post_adjustment_test_%.4fMHz" % cal.gpib.freq, opts.zdok)
                cal.check_spec(opts.zdok,
                               save=opts.save,
                               view=opts.view,
                               filename=fn)  #, filename=fn)
                check_spec = cal.user_input("Check spectrum?")
            if cal.user_input("Do frequency scan?"):
                cal.freq_scan(save=opts.save, view=opts.view)  #, filename=fn)
        else:
            logger.info("Starting automatic testing...")
            for i in range(0, 5):
                test_freq = random.random() * cal.clockrate
                cal.freq_setup(manual=False, freq=test_freq)
                fn = "post_adjustment_test_%.4fMHz" % cal.gpib.freq + cal.file_label
                cal.check_spec(save=opts.save, view=False, filename=fn)
            fn = 'freq_scan' + cal.file_label  #timestamp
            cal.freq_scan(save=opts.save, view=False, filename=fn)
Example #53
0
def main():
    """
points hydrogens on H-bond donors (SER and TYR) towards an H-bond acceptor)
	"""

    parser = OptionParser()
    parser.add_option("-p", dest="pdbfile", help="pdbfile")
    parser.add_option("-P", dest="pdblist", help="pdblist")
    #	parser.add_option("-o", dest="outfile", help="outfile")
    #	parser.add_option("-r", dest="replace", help="replace", action="store_true")
    parser.add_option("-d", dest="donor", help="donor residue")
    parser.add_option("-c", dest="catalytic", help="catalytic residue")
    parser.add_option("-a", dest="acceptor", help="acceptor atom")
    parser.set_description(main.__doc__)
    (options, args) = parser.parse_args()

    pdbfiles = []
    if options.pdblist:
        pdbfiles = files_from_list(options.pdblist)
    elif options.pdbfile:
        pdbfiles.append(options.pdbfile)
    else:
        parser.print_help()
        sys.exit()

    if not options.acceptor:
        parser.print_help()
        sys.exit()

    if not options.donor and not options.catalytic:
        parser.print_help()
        sys.exit()

    protein = Enzyme()
    sele = Selection()

    dmol = None
    for i in range(len(pdbfiles)):
        protein.readPDB(pdbfiles[i])
        #print pdbfiles[i]

        # --- get the donor --- #
        if options.donor:
            sele.makeSelection(options.donor)
            dmol = sele.apply_selection(protein)
            reslist = dmol.residueList()

            if len(reslist) != 1:
                #print "donor selection must specify one donor residue"
                #print reslist
                protein.clear()
                continue
                sys.exit()

            donor = reslist[0]
            sele.clear()
        elif options.catalytic:
            icat = int(options.catalytic) - 1
            donor = protein.catalytic[icat]
            if donor == None:
                print "can't find donor"
                sys.exit()

        # --- get the acceptor --- #
        sele.makeSelection(options.acceptor)
        amol = sele.apply_selection(protein)
        reslist = amol.residueList()
        sele.clear()

        if len(reslist) != 1:
            print "acceptor selection must specify one acceptor atom"
            sys.exit()

        if reslist[0].numAtoms() != 1:
            print "acceptor selection must specify one acceptor atom"
            sys.exit()

        acceptor = reslist[0].atom[0]

        # --- for now donor must be serine or tyrosine --- #
        if donor.name == "SER":
            H = donor.getAtom(" HG ")
            B = donor.getAtom(" OG ")
            C = donor.getAtom(" CB ")
            D = donor.getAtom(" CA ")
        elif donor.name == "TYR":
            H = donor.getAtom(" HH ")
            B = donor.getAtom(" OH ")
            C = donor.getAtom(" CZ ")
            D = donor.getAtom(" CE1")
        elif donor.name == "THR":
            H = donor.getAtom(" HG1")
            B = donor.getAtom(" OG1")
            C = donor.getAtom(" CB ")
            D = donor.getAtom(" CA ")
        elif donor.name == "CYS":
            H = donor.getAtom(" HG ")
            B = donor.getAtom(" SG ")
            C = donor.getAtom(" CB ")
            D = donor.getAtom(" CA ")
        else:
            print "unsupported donor residue"
            sys.exit()

        mytor = vector3d.torsion(acceptor.coord, B.coord, C.coord, D.coord)
        print pdbfiles[i], mytor
        #print mytor
        #		changeDihedral(H,B,C,D,mytor)

        #		protein.writePDB(outfiles[i], resRenumber=False, atomRenumber=False)
        protein.clear()
        if dmol != None:
            dmol.clear()
Example #54
0
def main():
    """
sets the appropriate element for atoms in a ligand.  (uses known rosetta
atomtypes)
	"""

    parser = OptionParser()
    parser.add_option("-p", dest="pdbfile", help="pdbfile")
    parser.add_option("-P", dest="pdblist", help="pdblist")
    parser.add_option("-r",
                      dest="replace",
                      help="replace",
                      action="store_true")
    parser.set_description(main.__doc__)
    (options, args) = parser.parse_args()

    pdbfiles = []
    if options.pdblist:
        pdbfiles = files_from_list(options.pdblist)
    elif options.pdbfile:
        pdbfiles.append(options.pdbfile)
    else:
        parser.print_help()
        sys.exit()

    if not options.replace:
        parser.print_help()
        sys.exit()

    outfiles = []
    for file in pdbfiles:
        outfiles.append(file)

    het = re.compile("HETATM")

    for i in range(len(pdbfiles)):
        try:
            PDBFILE = open(pdbfiles[i])
        except:
            print "can't open pdbfile"
            sys.exit()

        mylines = PDBFILE.readlines()
        PDBFILE.close()

        try:
            OUTFILE = open(pdbfiles[i], 'w')
        except:
            print "can't write to outfile"
            sys.exit()

        nat = 9000
        for line in mylines:
            newline = line
            if het.match(line):
                if line[12:16] == "CH1 ":
                    newline = line[0:66] + "           C" + "\n"
                if line[12:16] == "Nhis":
                    newline = line[0:66] + "           N" + "\n"
                if line[12:16] == "OOC ":
                    newline = line[0:66] + "           O" + "\n"
                if line[12:16] == "aroC":
                    newline = line[0:66] + "           C" + "\n"
                if line[12:16] == "OH  ":
                    newline = line[0:66] + "           O" + "\n"
                if line[12:16] == "COO ":
                    newline = line[0:66] + "           C" + "\n"
                if line[12:16] == "Haro":
                    newline = line[0:66] + "           H" + "\n"
                if line[12:16] == "Hapo":
                    newline = line[0:66] + "           H" + "\n"
                if line[12:16] == "Hpol":
                    newline = line[0:66] + "           H" + "\n"

            OUTFILE.write(newline)

        OUTFILE.close()
Example #55
0
def main():
    """
Superimposes a probe molecule onto a target molecule.
Selections for the target and probe may be given.
If a probe selection is given but not an explicit target selection
that selection is applied to BOTH molecules
	"""

    parser = OptionParser()
    parser.add_option("-l", dest="list", help="probe list")
    parser.add_option("-o", dest="outfile", help="output")
    parser.add_option("-O", dest="outlist", help="outlist")
    parser.add_option("-s", dest="selection", help="selection")
    parser.add_option("-S", dest="target_selection", help="target selection")
    parser.add_option("-t", dest="target", help="target")
    parser.add_option("-p", dest="probe", help="probe")
    parser.add_option("-v",
                      dest="verbose",
                      help="verbose",
                      action="store_true")
    parser.add_option("-r",
                      dest="remark",
                      help="add remark to pdb",
                      action="store_true")
    parser.set_description(main.__doc__)
    (options, args) = parser.parse_args()

    files = []
    if options.list:
        files = files_from_list(options.list)
    elif options.probe:
        files.append(options.probe)
    else:
        parser.print_help()
        sys.exit()

    if not options.target:
        parser.print_help()
        sys.exit()

    outfiles = []
    if options.outlist:
        outfiles = files_from_list(options.outlist)
    elif options.outfile:
        outfiles.append(options.outfile)
    else:
        parser.print_help()
        sys.exit()

    target = Molecule()
    target.readPDB(options.target)
    sele = Selection()
    if options.target_selection:
        sele.makeSelection(options.target_selection)
        target = sele.apply_selection(target)
    elif options.selection:
        sele.makeSelection(options.selection)
        target = sele.apply_selection(target)

    sele.clear()
    if options.selection:
        sele.makeSelection(options.selection)

    probe = Molecule()
    myrmsd = 0.0
    for i in range(len(files)):
        probe.readPDB(files[i])

        new_probe = probe
        if options.selection:
            new_probe = sele.apply_selection(probe)

        myrmsd = superimpose_molecule(target, new_probe, probe)

        if options.verbose:
            print files[i], "rmsd=", myrmsd

        if options.remark:
            probe.addRemark("REMARK RMSD = " + str(myrmsd))

        probe.writePDB(outfiles[i], resRenumber=False, atomRenumber=False)
        probe.clear()
Example #56
0
def main():
    """
superimposes and reports the rmsd between two pdbfiles
(REQUIRES EXTERNAL BINARY: superimpose)
	"""

    parser = OptionParser()
    parser.add_option("-l", dest="list", help="list")
    parser.add_option("-o", dest="outfile", help="output")
    parser.add_option("-s", dest="selection", help="selection")
    parser.add_option("-t", dest="target", help="target")
    parser.add_option("-p", dest="probe", help="probe")
    parser.set_description(main.__doc__)
    (options, args) = parser.parse_args()

    files = []
    if options.list:
        try:
            FILELIST = open(options.list, 'r')
        except:
            print "unable to open file list"
            sys.exit()

        for file in FILELIST.readlines():
            file = string.strip(file)
            files.append(file)
        FILELIST.close()
    elif options.probe:
        files.append(options.probe)
    else:
        parser.print_help()
        sys.exit()

    if not options.target:
        parser.print_help()
        sys.exit()

    if options.outfile == None:
        parser.print_help()
        sys.exit()

    tmp_target = "_tmptarget.pdb"
    tmp_probe = "_tmpprobe.pdb"
    if options.selection:
        makeSelection = "makeSelection.py -p " + options.target + " -o " + \
         tmp_target + " -s \"" + options.selection + "\""

        os.system(makeSelection)

    try:
        OUTFILE = open(options.outfile, 'w')
    except:
        print "unable to open outfile"
        sys.exit()

    for i in range(len(files)):
        firstName = options.target
        currentName = files[i]
        firstFile = options.target
        currFile = files[i]

        if options.selection:
            currentFile = tmp_probe
            firstFile = tmp_target

            makeSelection = "makeSelection.py -p " + files[i] + " -o " + \
             tmp_probe + " -s \"" + options.selection + "\""
            os.system(makeSelection)

        run = "rmsd " + firstFile + " " + currentFile
        sh = os.popen(run, 'r')
        line = sh.readline()
        rmsd = (string.split(line))[2]

        print "superimposing " + currentName + " to " + firstName + " => " + str(
            rmsd)
        OUTFILE.write(currentName + " " + firstName + " " + rmsd + "\n")

    OUTFILE.close()

    if options.selection:
        os.system("rm -f " + tmp_target)
        os.system("rm -f " + tmp_probe)
def main():
    """
forces hydrophobic mutation
NOTE: FOR NOW DOESN'T ALLOW R OR A
	"""

    parser = OptionParser()
    parser.add_option("-p", dest="pdbfile", help="pdbfile")
    parser.add_option("-P", dest="pdblist", help="pdblist")
    parser.add_option("-l",
                      dest="list",
                      help="list mutations",
                      action="store_true")
    parser.add_option("-s",
                      dest="summary",
                      help="summary",
                      action="store_true")
    parser.add_option("-d",
                      dest="dry_run",
                      help="dry_run",
                      action="store_true")
    parser.add_option("-R",
                      dest="charged",
                      help="charged only",
                      action="store_true")
    parser.set_description(main.__doc__)
    (options, args) = parser.parse_args()

    pdbfiles = []
    if options.pdblist:
        pdbfiles = files_from_list(options.pdblist)
    elif options.pdbfile:
        pdbfiles.append(options.pdbfile)
    else:
        parser.print_help()
        sys.exit()

    protein = Enzyme()
    for pdbfile in pdbfiles:
        npol_run = "contactingPolars.py -s 'resn=LG1;element!=V' --ignore_catalytic -p " + pdbfile
        if options.charged:
            npol_run += " -R"
        pol_run = "contactingPolars.py -s 'resn=LG1;name=OH  ,Nhis,OOC ,OCbb,COO ' --ignore_catalytic -p " + pdbfile
        if options.charged:
            pol_run += " -R"
        np = commands.getoutput(npol_run)
        pl = commands.getoutput(pol_run)

        npol = np.split("\n")
        pol = pl.split("\n")

        mutate = []
        for line in npol:
            if not (line in pol):
                cols = line.split()
                if not (int(cols[0]) in mutate):
                    mutate.append(int(cols[0]))

        protein.readPDB(pdbfile)

        toMutate = -1
        maxhb = -999
        for mut in mutate:
            myres = protein.getResidue(mut)
            if myres == None:
                print "cannot find residue"
                sys.exit()

            if myres.EhbSC > maxhb:
                maxhb = myres.EhbSC
                toMutate = mut

        protein.clear()
        if options.summary:
            print pdbfile, len(mutate)
            continue

        if options.list:
            for mut in mutate:
                print pdbfile, mut

        if options.dry_run:
            if toMutate > -1:
                print pdbfile, toMutate
            else:
                print pdbfile, "none"
            continue

        mut_run = "ligandResfile.py -p " + pdbfile + " -a --keep_nonpolar --no_non_native='AR' --force_hydrophobic " + str(
            toMutate)
        commands.getoutput(mut_run)
Example #58
0
                v = int(v)
            except ValueError:
                raise Exception('Bad value %s for %s in %s' % (v, k, stream))
            if v not in definitions[k]:
                raise Exception('Undefined value %s for %s in %s' %
                                (v, k, stream))
            if k in pragmas:
                raise Exception('Duplicate pragma %s defined in %s' %
                                (k, stream))
            pragmas[k] = v
    return pragmas

if __name__ == '__main__':
    usage = '%prog [OPTIONS] FILENAMES\n       %prog -l'
    parser = OptionParser(usage=usage)
    parser.set_description(__doc__.split('\n\n', 1)[0])
    parser.add_option('-f', '--filter', type='str', dest='filt',
                      default=None, metavar='PRAGMA:VALUE',
                      help='filter filenames for PRAGMA with VALUE')
    parser.add_option('-q', '--query', type='str', dest='query', default=None,
                      metavar='PRAGMA',
                      help='print the setting for PRAGMA only')
    parser.add_option('-l', '--list', action='store_true',
                      dest='list_settings', default=False,
                      help='print the list of pragmas definitions')
    parser.add_option('-d', '--def', type='str', dest='defs_file',
                      default='pragmas.conf.py', metavar='FILE',
                      help='use pragma definitions from FILE')
    (options, filenames) = parser.parse_args()

    definitions = PragmaDefinitions()
def main():
    """
changes the older matching header information to the new constraint header
(HETATMS are changed to LG1)
	"""

    parser = OptionParser()
    parser.add_option("-p", dest="pdbfile", help="pdbfile")
    parser.add_option("-P", dest="pdblist", help="pdblist")
    parser.add_option("-r",
                      dest="replace",
                      help="replace",
                      action="store_true")
    parser.set_description(main.__doc__)
    (options, args) = parser.parse_args()

    pdbfiles = []
    if options.pdblist:
        pdbfiles = files_from_list(options.pdblist)
    elif options.pdbfile:
        pdbfiles.append(options.pdbfile)
    else:
        parser.print_help()
        sys.exit()

    match_head = re.compile("REMARK BACKBONE TEMPLATE A")
    het = re.compile("HETATM")
    new_lig = "LG1"
    for pdbfile in pdbfiles:
        try:
            PDB = open(pdbfile)
        except:
            print "unable to open pdbfile:", pdbfile
            sys.exit()

        outfile = []
        for line in PDB.readlines():
            line = string.rstrip(line)
            newline = line
            if match_head.match(line):
                cols = line.split()
                resn = cols[4]
                resi = int(cols[5])
                cati = int(cols[11])
                newline = (
                    "REMARK BACKBONE TEMPLATE A LG1    0 MATCH MOTIF B %3s%6i%3i"
                    % (resn, resi, cati))

            if het.match(line):
                old_lig = line[17:20]
                newline = line.replace(old_lig, new_lig)

            outfile.append(newline)

        PDB.close()
        try:
            PDB = open(pdbfile, 'w')
        except:
            print "unable to create pdbfile:", pdbfile
            sys.exit()

        for line in outfile:
            PDB.write(line + "\n")
        PDB.close()
Example #60
0
    print "  ohttp.uri"
    print "  packets"
    print "  packets.ipt"
    print "  \"entropy(bd)\""
    print "  \"collision(bd)\""
    print "  \"minentropy(bd)\""


#
# main function
#
if __name__ == '__main__':

    parser = OptionParser()
    parser.set_description(
        "filter JSON flow data and print out matching flows, selected fields, or stats"
    )
    parser.add_option("--where", dest="filter", help="filter flows")
    parser.add_option("--select",
                      dest="selection",
                      help="select field to output")
    parser.add_option("--stats",
                      action="store_true",
                      help="print out statistics")
    parser.add_option("--summary",
                      action='store_true',
                      dest="summary",
                      help="print single line per flow ")
    parser.add_option("--translate",
                      action='store_true',
                      dest="translate",