Beispiel #1
0
    def __init__(self, width, height):
        logger = log.get_logger(null=True)

        # We just use a ginga widget to implement the readout
        readout = Viewers.CanvasView(logger=logger)
        readout.set_desired_size(width, height)
        bg = colors.lookup_color('#202030')
        readout.set_bg(*bg)

        self.viewer = readout
        self.readout = Widgets.wrap(readout.get_widget())
        self.readout.resize(width, height)

        canvas = readout.get_canvas()
        Text = canvas.get_draw_class('text')
        xoff, yoff = 4, 4
        self.text_obj = Text(xoff, height-yoff, text='',
                             color='lightgreen', fontsize=14,
                             coord='canvas')
        canvas.add(self.text_obj, redraw=False)

        self.maxx = 0
        self.maxy = 0
        self.maxv = 0

        self.fitsimage = None
Beispiel #2
0
def main(options, args):

    logger = log.get_logger("example2", options=options)
    ev_quit = threading.Event()

    thread_pool = Task.ThreadPool(options.numthreads, logger,
                                  ev_quit=ev_quit)
    thread_pool.startall()
    try:

        factory = ViewerFactory(logger, options.basedir, thread_pool)

        js_path = os.path.dirname(js.__file__)

        # run the app
        app = tornado.web.Application([
            (r"/js/(.*\.js)", tornado.web.StaticFileHandler, {"path":  js_path}),
            (r"/viewer", FileHandler,
              dict(name='Ginga', url='/viewer', factory=factory)),
             ("/viewer/socket", FitsViewer,
              dict(name='Ginga', factory=factory)),
            ],
               factory=factory, logger=logger)

        app.listen(options.port, options.host)
        print("ginga web now running at http://" + options.host + ":" + \
              str(options.port) + "/viewer")
        tornado.ioloop.IOLoop.instance().start()

    except KeyboardInterrupt:
        print("Interrupted!")
    finally:
        ev_quit.set()
        thread_pool.stopall()
Beispiel #3
0
 def new_client(self, dc=None, canvas=None):
     from ...qt import get_qapp
     get_qapp()
     dc = dc or self.collect
     l = log.get_logger(name='ginga', log_stderr=True)
     canvas = ImageViewCanvas(l, render='widget')
     return GingaClient(dc, canvas)
Beispiel #4
0
def main(options, args):

    #QtGui.QApplication.setGraphicsSystem('raster')
    app = QtGui.QApplication(args)

    logger = log.get_logger("example2", options=options)

    # Check whether user wants to use OpenCv
    if options.opencv:
        from ginga import trcalc
        try:
            trcalc.use('opencv')
        except Exception as e:
            logger.warning("failed to set OpenCv preference: %s" % (str(e)))

    # Check whether user wants to use OpenCL
    elif options.opencl:
        from ginga import trcalc
        try:
            trcalc.use('opencl')
        except Exception as e:
            logger.warning("failed to set OpenCL preference: %s" % (str(e)))

    w = FitsViewer(logger)
    w.resize(524, 540)
    w.show()
    app.setActiveWindow(w)
    w.raise_()
    w.activateWindow()

    if len(args) > 0:
        w.load_file(args[0])

    app.exec_()
Beispiel #5
0
def main(options, args):

    logger = log.get_logger("example2", options=options)

    if options.toolkit is None:
        logger.error("Please choose a GUI toolkit with -t option")

    # decide our toolkit, then import
    ginga_toolkit.use(options.toolkit)

    # event for synchronizing exit of all threads
    ev_quit = threading.Event()

    gv = GingaVision(logger, ev_quit, options)
    gv.top.resize(670, 540)
    gv.top.show()
    gv.top.raise_()

    # start video capture thread
    if len(args) > 0:
        filename = args[0]
    else:
        # default video input device
        filename = 0

    gv.main.nongui_do(gv.capture_video, filename)

    gv.main.mainloop()
    logger.info("program terminating...")
    sys.exit(0)
Beispiel #6
0
def main(options, args):
    
    logger = log.get_logger("ginga", options=options)

    # create a new plot with default tools, using figure
    fig = figure(x_range=[0,600], y_range=[0,600], plot_width=600, plot_height=600,
                 toolbar_location=None)

    viewer = ib.CanvasView(logger)
    viewer.set_figure(fig)

    def load_file(path):
        image = AstroImage(logger)
        image.load_file(path)
        viewer.set_image(image)

    def load_file_cb(attr_name, old_val, new_val):
        #print(attr_name, old_val, new_val)
        load_file(new_val)

    # add a entry widget and configure with the call back
    dstdir = options.indir
    path_w = TextInput(value=dstdir, title="File:")
    path_w.on_change('value', load_file_cb)

    if len(args) > 0:
        load_file(args[0])

    # put the path widget and viewer in a layout and add to the document
    curdoc().add_root(vplot(fig, path_w))
Beispiel #7
0
def main(options, args):
    # Create top level logger.
    logger = log.get_logger(name='qcheck', options=options)

    if options.input_filename:
        # This section is for reading an Excel file that has the usual
        # sheets in it (targets, envcfg, etc.)

        # Append any directory path supplied in options.input_filename
        # onto the end of the options.input_dir value.
        input_dir = os.path.join(options.input_dir, os.path.dirname(options.input_filename))
        # Parse the input filename so we can get the proposal name.
        input_filename = os.path.basename(options.input_filename)
        propname, ext = input_filename.split('.')
        if ext in filetypes.QueueFile.excel_ext:
            propdict = {}
            key = propname.upper()
            propdict[key] = entity.Program(key, hours=0, category='')
            progFile = filetypes.ProgramFile(input_dir, logger, propname, propdict)
        else:
            logger.error("File extension '%s' is not a valid file type. Must be one of %s." % (ext, filetypes.QueueFile.excel_ext))
            sys.exit(1)
    else:
        # This section is for reading a directory that contains CSV
        # files, i.e., targets.csv, inscfg.csv, etc.
        dirname = os.path.dirname(options.input_dir)
        propname = os.path.basename(options.input_dir)
        propdict = {}
        key = propname.upper()
        propdict[key] = entity.Program(key, hours=0, category='')
        progFile = filetypes.ProgramFile(dirname, logger, propname, propdict, file_ext='csv')

    logger.info('Warning count is %d' % progFile.warn_count)
    logger.info('Error count is   %d' % progFile.error_count)
Beispiel #8
0
def make_server(logger=None, basedir='.', numthreads=5,
                host='localhost', port=9909, use_opencv=False):

    if logger is None:
        logger = log.get_logger("ipg", null=True)
    ev_quit = threading.Event()

    if use_opencv:
        from ginga import trcalc
        try:
            trcalc.use('opencv')
        except Exception as e:
            logger.warning("Error using opencv: %s" % str(e))

    thread_pool = Task.ThreadPool(numthreads, logger,
                                  ev_quit=ev_quit)

    base_url = "http://%s:%d/app" % (host, port)
    app = Widgets.Application(logger=logger, base_url=base_url,
                              host=host, port=port)

    factory = ViewerFactory(logger, basedir, app, thread_pool)

    server = WebServer(app, thread_pool, factory,
                       host=host, port=port)

    return server
Beispiel #9
0
def main(options, args):

    logger = log.get_logger("example2", options=options)

    if options.toolkit is None:
        logger.error("Please choose a GUI toolkit with -t option")

    # decide our toolkit, then import
    ginga_toolkit.use(options.toolkit)

    viewer = FitsViewer(logger)

    viewer.top.resize(700, 540)

    if len(args) > 0:
        viewer.load_file(args[0])

    viewer.top.show()
    viewer.top.raise_()

    try:
        app = viewer.top.get_app()

        # TODO: unify these
        if hasattr(app, "start"):
            app.start()

        else:
            while True:
                app.process_events()

    except KeyboardInterrupt:
        print("Terminating viewer...")
        if viewer.top is not None:
            viewer.top.close()
Beispiel #10
0
def main(options, args):

    logger = log.get_logger("example2", options=options)

    if options.toolkit is None:
        logger.error("Please choose a GUI toolkit with -t option")

    # decide our toolkit, then import
    ginga_toolkit.use(options.toolkit)

    viewer = FitsViewer(logger)

    viewer.top.resize(700, 540)

    if len(args) > 0:
        viewer.load_file(viewer.viewer1, args[0])

    viewer.top.show()
    viewer.top.raise_()

    try:
        viewer.app.mainloop()

    except KeyboardInterrupt:
        print("Terminating viewer...")
        if viewer.top is not None:
            viewer.top.close()
Beispiel #11
0
def main(options, args):

    logger = log.get_logger("example2", options=options)

    # Check whether user wants to use OpenCv
    if options.opencv:
        from ginga import trcalc
        try:
            trcalc.use('opencv')
        except Exception as e:
            logger.warning("failed to set OpenCv preference: %s" % (str(e)))

    # Check whether user wants to use OpenCL
    elif options.opencl:
        from ginga import trcalc
        try:
            trcalc.use('opencl')
        except Exception as e:
            logger.warning("failed to set OpenCL preference: %s" % (str(e)))

    fv = FitsViewer(logger)
    root = fv.get_widget()
    root.show_all()

    if len(args) > 0:
        fv.load_file(args[0])

    gtk.main()
Beispiel #12
0
    def __init__(self, *objects):
        CanvasObjectBase.__init__(self)
        CompoundMixin.__init__(self)
        self.objects = list(objects)
        self.logger = get_logger('foo', log_stderr=True, level=10)

        self.kind = 'compound'
        self.editable = False
Beispiel #13
0
    def new_client(self, dc=None, canvas=None):
        from glue.utils.qt import get_qapp

        get_qapp()
        dc = dc or self.collect
        l = log.get_logger(name="ginga", log_stderr=True)
        canvas = ImageViewCanvas(l, render="widget")
        return GingaClient(dc, canvas)
Beispiel #14
0
    def __init__(self, *objects, **kwdargs):
        CanvasObjectBase.__init__(self, **kwdargs)
        CompoundMixin.__init__(self)
        self.objects = list(objects)
        self.logger = get_logger("foo", log_stderr=True, level=10)

        self.kind = "compound"
        self.editable = False
Beispiel #15
0
def main(options, args):

    #logger = log.get_logger("ginga", options=options)
    logger = log.get_logger("ginga", level=20, log_file="/tmp/ginga.log")

    #TOOLS = "pan,wheel_zoom,box_select,tap"
    TOOLS = "box_select"

    # create a new plot with default tools, using figure
    fig = figure(x_range=[0, 600], y_range=[0, 600],
                 plot_width=600, plot_height=600, tools=TOOLS)

    viewer = ib.CanvasView(logger)
    viewer.set_figure(fig)

    bd = viewer.get_bindings()
    bd.enable_all(True)

    ## box_select_tool = fig.select(dict(type=BoxSelectTool))
    ## box_select_tool.select_every_mousemove = True
    #tap_tool = fig.select_one(TapTool).renderers = [cr]

    # open a session to keep our local document in sync with server
    #session = push_session(curdoc())

    #curdoc().add_periodic_callback(update, 50)

    def load_file(path):
        image = load_data(path, logger=logger)
        viewer.set_image(image)

    def load_file_cb(attr_name, old_val, new_val):
        #print(attr_name, old_val, new_val)
        load_file(new_val)

    def zoom_ctl_cb(attr_name, old_val, new_val):
        if new_val >= 0:
            new_val += 2
        viewer.zoom_to(int(new_val))
        scale = viewer.get_scale()
        logger.info("%f" % scale)
        viewer.onscreen_message("%f" % (scale), delay=0.3)

    # add a entry widget and configure with the call back
    #dstdir = options.indir
    dstdir = ""
    path_w = TextInput(value=dstdir, title="File:")
    path_w.on_change('value', load_file_cb)

    slide = Slider(start=-20, end=20, step=1, value=1)
    slide.on_change('value', zoom_ctl_cb)

    layout = column(fig, path_w, slide)
    curdoc().add_root(layout)

    if len(args) > 0:
        load_file(args[0])
Beispiel #16
0
 def __init__(self, logger=None):
     self.timer_lock = threading.RLock()
     self.timer_cnt = 0
     self.timer = {}
     self.base_interval_msec = default_timer_interval_msec
     self._timeout = None
     if logger is None:
         # substitute a null logger if user didn't provide one
         logger = log.get_logger(name='timerfactory', null=True,
                                 level=50)
     self.logger = logger
Beispiel #17
0
def main(options, args):

    logger = log.get_logger("example2", options=options)

    fv = FitsViewer(logger)
    top = fv.get_widget()

    if len(args) > 0:
        fv.load_file(args[0])

    top.mainloop()
Beispiel #18
0
def main(options, args):
    # Create top level logger.
    logger = log.get_logger(name='t_schedule', options=options)

    sdl = StandAlone_Scheduler(logger, options.input_dir,
                               options.host, options.port)

    sdl.init_db()
    #sdl.schedule_files()
    #sdl.schedule_db()

    sys.exit(0)
Beispiel #19
0
    def __init__(self, host='localhost', port=9909, logger=None, numthreads=5):
        self.tornado_app = None
        self.viewers = {}
        self.host = host
        self.port = port

        if logger is None:
            logger = log.get_logger("nbinteract_server", null=True)
        self.logger = logger

        self.thread_pool = Task.ThreadPool(numthreads, logger)
        self.app = Widgets.Application(logger=self.logger,
                                       base_url=self.base_url)
Beispiel #20
0
    def __init__(self, session, parent=None):

        self.logger = log.get_logger(
            name="ginga",
            level=20,
            null=True,
            # uncomment for debugging
            # log_stderr=True
        )

        self.canvas = ImageViewCanvas(self.logger, render="widget")

        # prevent widget from grabbing focus
        try:
            self.canvas.set_enter_focus(False)
        except AttributeError:
            self.canvas.set_follow_focus(False)

        # enable interactive features
        bindings = self.canvas.get_bindings()
        bindings.enable_all(True)
        self.canvas.add_callback("none-move", self.motion_readout)
        self.canvas.add_callback("draw-event", self._apply_roi_cb)
        self.canvas.add_callback("draw-down", self._clear_roi_cb)
        self.canvas.enable_draw(False)
        self.canvas.enable_autozoom("off")
        self.canvas.set_zoom_algorithm("rate")
        self.canvas.set_zoomrate(1.4)

        bm = self.canvas.get_bindmap()
        bm.add_callback("mode-set", self.mode_set_cb)
        self.mode_w = None
        self.mode_actns = {}

        # Create settings and set defaults
        settings = self.canvas.get_settings()
        self.settings = settings
        settings.getSetting("cuts").add_callback("set", self.cut_levels_cb)
        settings.set(autozoom="off", autocuts="override", autocenter="override")

        # make color bar, with color maps shared from ginga canvas
        self.colorbar = ColorBar.ColorBar(self.logger)
        rgbmap = self.canvas.get_rgbmap()
        rgbmap.add_callback("changed", self.rgbmap_cb, self.canvas)
        self.colorbar.set_rgbmap(rgbmap)

        # make coordinates/value readout
        self.readout = Readout.Readout(-1, -1)
        self.roi_tag = None

        super(GingaWidget, self).__init__(session, parent)
Beispiel #21
0
def main(options, args):
    
    #QtGui.QApplication.setGraphicsSystem('raster')
    app = QtGui.QApplication(args)

    logger = log.get_logger(name="example1", options=options)
    viewer = FitsViewer(logger)
    viewer.resize(524, 540)
    viewer.show()
    app.setActiveWindow(viewer)

    if len(args) > 0:
        viewer.load_file(args[0])

    app.exec_()
Beispiel #22
0
def main(options, args):

    logger = log.get_logger("ipg", options=options)

    server = make_server(logger=logger, basedir=options.basedir,
                         numthreads=options.numthreads, host=options.host,
                         port=options.port, use_opencv=options.use_opencv)

    try:
        server.start(use_thread=False)

    except KeyboardInterrupt:
        logger.info("Interrupted!")
        server.stop()

    logger.info("Server terminating...")
Beispiel #23
0
def main(options, args):

    app = QtGui.QApplication(args)

    logger = log.get_logger(name="example2", options=options)
    w = FitsViewer(logger)
    w.resize(524, 540)
    w.show()
    app.setActiveWindow(w)
    w.raise_()
    w.activateWindow()

    if len(args) > 0:
        w.load_file(args[0])

    app.exec_()
Beispiel #24
0
def main(options, args):

    QtGui.QApplication.setGraphicsSystem("raster")
    app = QtGui.QApplication(args)
    app.connect(app, QtCore.SIGNAL("lastWindowClosed()"), app, QtCore.SLOT("quit()"))

    logger = log.get_logger(name="example1", options=options)
    viewer = FitsViewer(logger)
    viewer.resize(524, 540)
    viewer.show()
    app.setActiveWindow(viewer)

    if len(args) > 0:
        viewer.load_file(args[0])

    app.exec_()
Beispiel #25
0
def main(options, args):

    logger = log.get_logger("example2", options=options)

    if options.toolkit is None:
        logger.error("Please choose a GUI toolkit with -t option")

    # decide our toolkit, then import
    ginga_toolkit.use(options.toolkit)

    if options.use_opencv:
        from ginga import trcalc
        try:
            trcalc.use('opencv')
        except Exception as e:
            logger.warning("Error using OpenCv: %s" % str(e))

    if options.use_opencl:
        from ginga import trcalc
        try:
            trcalc.use('opencl')
        except Exception as e:
            logger.warning("Error using OpenCL: %s" % str(e))

    viewer = FitsViewer(logger)

    if options.renderer is not None:
        render_class = render.get_render_class(options.renderer)
        viewer.fitsimage.set_renderer(render_class(viewer.fitsimage))

    viewer.top.resize(700, 540)

    if len(args) > 0:
        viewer.load_file(args[0])

    viewer.top.show()
    viewer.top.raise_()

    try:
        app = viewer.top.get_app()
        app.mainloop()

    except KeyboardInterrupt:
        print("Terminating viewer...")
        if viewer.top is not None:
            viewer.top.close()
Beispiel #26
0
def main(options, args):

    logger = log.get_logger("example2", options=options)

    if options.toolkit is None:
        logger.error("Please choose a GUI toolkit with -t option")

    # decide our toolkit, then import
    ginga_toolkit.use(options.toolkit)

    if options.use_opencv:
        from ginga import trcalc
        try:
            trcalc.use('opencv')
        except Exception as e:
            logger.warning("Error using OpenCv: %s" % str(e))

    if options.use_opencl:
        from ginga import trcalc
        try:
            trcalc.use('opencl')
        except Exception as e:
            logger.warning("Error using OpenCL: %s" % str(e))

    viewer = FitsViewer(logger)

    if options.renderer is not None:
        render_class = render.get_render_class(options.renderer)
        viewer.fitsimage.set_renderer(render_class(viewer.fitsimage))

    viewer.top.resize(700, 540)

    if len(args) > 0:
        viewer.load_file(args[0])

    viewer.top.show()
    viewer.top.raise_()

    try:
        app = viewer.top.get_app()
        app.mainloop()

    except KeyboardInterrupt:
        print("Terminating viewer...")
        if viewer.top is not None:
            viewer.top.close()
Beispiel #27
0
    def __init__(self, obj, host='localhost', port=9000, ev_quit=None,
                 logger=None):
        super(RemoteServer, self).__init__()

        self.robj = obj
        # What port to listen for requests
        self.port = port
        # If blank, listens on all interfaces
        self.host = host

        if logger is None:
            logger = log.get_logger(null=True)
        self.logger = logger

        if ev_quit is None:
            ev_quit = threading.Event()
        self.ev_quit = ev_quit
Beispiel #28
0
def main(options, args):

    logger = log.get_logger("example2", options=options)

    if options.use_opencv:
        from ginga import trcalc
        try:
            trcalc.use('opencv')
        except Exception as e:
            logger.warning("Error using OpenCv: %s" % str(e))

    if options.use_opencl:
        from ginga import trcalc
        try:
            trcalc.use('opencl')
        except Exception as e:
            logger.warning("Error using OpenCL: %s" % str(e))

    base_url = "http://%s:%d/app" % (options.host, options.port)

    # establish our widget application
    app = Widgets.Application(logger=logger,
                              host=options.host,
                              port=options.port)

    #  create top level window
    window = app.make_window("Ginga web example2")

    # our own viewer object, customized with methods (see above)
    viewer = FitsViewer(logger, window)
    #server.add_callback('shutdown', viewer.quit)

    #window.resize(700, 540)

    if len(args) > 0:
        viewer.load_file(args[0])

    #window.show()
    #window.raise_()

    try:
        app.start()

    except KeyboardInterrupt:
        logger.info("Terminating viewer...")
        window.close()
Beispiel #29
0
    def __init__(self, obj, host='localhost', port=9000, ev_quit=None,
                 logger=None):
        super(RemoteServer, self).__init__()

        self.robj = obj
        # What port to listen for requests
        self.port = port
        # If blank, listens on all interfaces
        self.host = host

        if logger is None:
            logger = log.get_logger(null=True)
        self.logger = logger

        if ev_quit is None:
            ev_quit = threading.Event()
        self.ev_quit = ev_quit
Beispiel #30
0
    def __init__(self, session, parent=None):

        self.logger = log.get_logger(name='ginga', level=20, null=True,
                                     # uncomment for debugging
                                     #log_stderr=True
                                     )

        self.canvas = ImageViewCanvas(self.logger, render='widget')

        # prevent widget from grabbing focus
        self.canvas.set_follow_focus(False)

        # enable interactive features
        bindings = self.canvas.get_bindings()
        bindings.enable_all(True)
        self.canvas.add_callback('none-move', self.motion_readout)
        self.canvas.add_callback('draw-event', self._apply_roi_cb)
        self.canvas.add_callback('draw-down', self._clear_roi_cb)
        self.canvas.enable_draw(False)
        self.canvas.enable_autozoom('off')
        self.canvas.set_zoom_algorithm('rate')
        self.canvas.set_zoomrate(1.4)

        bm = self.canvas.get_bindmap()
        bm.add_callback('mode-set', self.mode_set_cb)
        self.mode_w = None
        self.mode_actns = {}

        # Create settings and set defaults
        settings = self.canvas.get_settings()
        self.settings = settings
        settings.getSetting('cuts').add_callback('set', self.cut_levels_cb)
        settings.set(autozoom='off', autocuts='override',
                     autocenter='override')

        # make color bar, with color maps shared from ginga canvas
        self.colorbar = ColorBar.ColorBar(self.logger)
        rgbmap = self.canvas.get_rgbmap()
        rgbmap.add_callback('changed', self.rgbmap_cb, self.canvas)
        self.colorbar.set_rgbmap(rgbmap)

        # make coordinates/value readout
        self.readout = Readout.Readout(-1, -1)
        self.roi_tag = None

        super(GingaWidget, self).__init__(session, parent)
Beispiel #31
0
def main(options, args):
    
    logger = log.get_logger("ginga", options=options)

    TOOLS = "pan,wheel_zoom,box_select,tap"
    
    # create a new plot with default tools, using figure
    fig = figure(x_range=[0,600], y_range=[0,600], plot_width=600, plot_height=600,
                 tools=TOOLS)

    viewer = ib.CanvasView(logger)
    viewer.set_figure(fig)

    ## box_select_tool = fig.select(dict(type=BoxSelectTool))
    ## box_select_tool.select_every_mousemove = True
    #tap_tool = fig.select_one(TapTool).renderers = [cr]

    # open a session to keep our local document in sync with server
    session = push_session(curdoc())

    #curdoc().add_periodic_callback(update, 50)

    def load_file(path):
        image = AstroImage(logger)
        image.load_file(path)
        viewer.set_image(image)

    def load_file_cb(attr_name, old_val, new_val):
        #print(attr_name, old_val, new_val)
        load_file(new_val)

    # add a entry widget and configure with the call back
    dstdir = options.indir
    path_w = TextInput(value=dstdir, title="File:")
    path_w.on_change('value', load_file_cb)

    curdoc().add_root(vplot(fig, path_w))

    if len(args) > 0:
        load_file(args[0])

    # open the document in a browser
    session.show() 

    # run forever
    session.loop_until_closed() 
Beispiel #32
0
def main(options, args):

    logger = log.get_logger(name="mosaic", options=options)

    img_mosaic = mosaic(logger, args, fov_deg=options.fov)

    if options.outfile:
        outfile = options.outfile
        io_fits.use('astropy')

        logger.info("Writing output to '%s'..." % (outfile))
        try:
            os.remove(outfile)
        except OSError:
            pass

        img_mosaic.save_as_file(outfile)
Beispiel #33
0
def main(options, args):

    QtGui.QApplication.setGraphicsSystem('raster')
    app = QtGui.QApplication(args)
    app.connect(app, QtCore.SIGNAL('lastWindowClosed()'),
                app, QtCore.SLOT('quit()'))

    logger = log.get_logger(name="example3", options=options)
    w = FitsViewer(logger)
    w.resize(1024, 540)
    w.show()
    app.setActiveWindow(w)

    if len(args) > 0:
        w.load_file(args[0])

    app.exec_()
Beispiel #34
0
def main(options, args):

    logger = log.get_logger(name="mosaic", options=options)

    img_mosaic = mosaic(logger, args, fov_deg=options.fov)

    if options.outfile:
        outfile = options.outfile
        io_fits.use('astropy')

        logger.info("Writing output to '%s'..." % (outfile))
        try:
            os.remove(outfile)
        except OSError:
            pass

        img_mosaic.save_as_file(outfile)
Beispiel #35
0
    def __init__(self, session, parent=None):

        self.logger = log.get_logger(name='ginga', log_stderr=True)

        self.canvas = ImageViewCanvas(self.logger, render='widget')

        # prevent widget from grabbing focus
        self.canvas.set_follow_focus(False)
        self.canvas.enable_overlays(True)

        # enable interactive features
        bindings = self.canvas.get_bindings()
        bindings.enable_all(True)
        self.canvas.set_callback('none-move', self.motion_readout)
        self.canvas.set_callback('draw-event', self._apply_roi_cb)
        self.canvas.set_callback('draw-down', self._clear_roi_cb)
        self.canvas.enable_draw(False)
        self.canvas.enable_autozoom('off')
        self.canvas.set_zoom_algorithm('rate')
        self.canvas.set_zoomrate(1.4)

        bm = self.canvas.get_bindmap()
        bm.add_callback('mode-set', self.mode_set_cb)
        self.mode_w = None
        self.mode_actns = {}

        # Create settings and set defaults
        settings = self.canvas.get_settings()
        self.settings = settings
        settings.getSetting('cuts').add_callback('set', self.cut_levels_cb)
        settings.set(autozoom='off',
                     autocuts='override',
                     autocenter='override')

        # make color bar, with color maps shared from ginga canvas
        self.colorbar = ColorBar.ColorBar(self.logger)
        rgbmap = self.canvas.get_rgbmap()
        rgbmap.add_callback('changed', self.rgbmap_cb, self.canvas)
        self.colorbar.set_rgbmap(rgbmap)

        # make coordinates/value readout
        self.readout = Readout.Readout(-1, -1)
        self.roi_tag = None

        super(GingaWidget, self).__init__(session, parent)
Beispiel #36
0
def main(options, args):

    logger = log.get_logger("ipg", options=options)

    server = make_server(logger=logger, basedir=options.basedir,
                         numthreads=options.numthreads, host=options.host,
                         port=options.port, use_opencv=options.use_opencv)
    viewer = server.get_viewer('v1')

    logger.info("Starting server with one viewer, connect at %s" % viewer.url)
    try:
        server.start(use_thread=False)

    except KeyboardInterrupt:
        logger.info("Interrupted!")
        server.stop()

    logger.info("Server terminating ...")
Beispiel #37
0
def main(options, args):

    #QtGui.QApplication.setGraphicsSystem('raster')
    app = QtGui.QApplication(args)

    logger = log.get_logger("example2", options=options)

    w = FitsViewer(logger)
    w.resize(524, 540)
    w.show()
    app.setActiveWindow(w)
    w.raise_()
    w.activateWindow()

    if len(args) > 0:
        w.load_file(args[0])

    app.exec_()
Beispiel #38
0
def get_viewer():
    # Set to True to get diagnostic logging output
    use_logger = False
    logger = log.get_logger(null=not use_logger, log_stderr=True)

    # create a regular matplotlib figure
    fig = plt.figure()

    # create a ginga object, initialize some defaults and
    # tell it about the figure
    viewer = CustomMplViewer(logger)
    viewer.enable_autocuts('on')
    viewer.set_autocut_params('zscale')
    viewer.set_figure(fig)

    # enable all interactive ginga features
    viewer.get_bindings().enable_all(True)

    return viewer
Beispiel #39
0
def main(options, args):

    logname = 'promsdb'
    logger = log.get_logger(logname, options=options)

    try:
        s = ProMSdb(logger, options.dblog)
    except ProMSdbError as e:
        result = str(e)
        success = False
        logger.info('result %s success %s' % (result, success))
        exit(1)

    if options.id:
        res = s.user_in_proms(options.id)
        logger.info('user_in_proms result is %s' % res)
    if options.id and options.passwd:
        res = s.user_auth_in_proms(options.id, options.passwd)
        logger.info('user_auth_in_proms result is %s' % res)
Beispiel #40
0
    def __init__(self, chartDev):

        self.chartDev = chartDev
        use_logger = False
        logger = log.get_logger(null=not use_logger, log_stderr=True)
        self.logger = logger
        # create a ginga object and tell it about the figure
        self.chartDev.fig.clf()
        fi = ImageViewCanvas(logger)
        fi.enable_autocuts('on')
        fi.set_autocut_params('zscale')
        fi.set_figure(self.chartDev.fig)
        fi.ui_setActive(True)
        self.fitsimage = fi
        setup_Qt(chartDev, fi)

        # enable all interactive features
        fi.get_bindings().enable_all(True)
        self.fitsimage = fi
Beispiel #41
0
def main(params):

    ginga_logger = log.get_logger("ginga", options=params)

    ginga_logger.addHandler(
        logging.FileHandler(filename=tempfile.NamedTemporaryFile(
            prefix='ginga', delete=False).name))

    if params.use_opencv:
        from ginga import trcalc
        try:
            trcalc.use('opencv')
        except Exception as ex:
            ginga_logger.warning("Error using OpenCL: {}".format(ex))

    if params.use_opencl:
        from ginga import trcalc
        try:
            trcalc.use('opencl')
        except Exception as ex:
            ginga_logger.warning("Error using OpenCL: {}".format(ex))

    app = Widgets.Application(logger=ginga_logger,
                              host=params.host,
                              port=params.port)

    #  create top level window
    window = app.make_window("Validate", wid='Validate')

    daomop_logger = logging.getLogger('daomop')

    if hasattr(params, 'loglevel'):
        daomop_logger.setLevel(params.loglevel)

    # our own viewer object, customized with methods (see above)
    ValidateGui(daomop_logger, window)

    try:
        app.start()

    except KeyboardInterrupt:
        ginga_logger.info("Terminating viewer...")
        window.close()
Beispiel #42
0
def main(options, args):

    QtGui.QApplication.setGraphicsSystem('raster')
    app = QtGui.QApplication(args)
    app.connect(app, QtCore.SIGNAL('lastWindowClosed()'), app,
                QtCore.SLOT('quit()'))

    logger = log.get_logger(name="example2", options=options)
    w = FitsViewer(logger)
    w.resize(524, 540)
    w.show()
    app.setActiveWindow(w)
    w.raise_()
    w.activateWindow()

    if len(args) > 0:
        w.load_file(args[0])

    app.exec_()
Beispiel #43
0
def main(options, args):
    # Create top level logger.
    logger = log.get_logger(name='qcheck', options=options)

    if options.input_filename:
        # This section is for reading an Excel file that has the usual
        # sheets in it (targets, envcfg, etc.)

        # Append any directory path supplied in options.input_filename
        # onto the end of the options.input_dir value.
        input_dir = os.path.join(options.input_dir,
                                 os.path.dirname(options.input_filename))
        # Parse the input filename so we can get the proposal name.
        input_filename = os.path.basename(options.input_filename)
        propname, ext = input_filename.split('.')
        if ext in filetypes.QueueFile.excel_ext:
            propdict = {}
            key = propname.upper()
            propdict[key] = entity.Program(key, hours=0, category='')
            progFile = filetypes.ProgramFile(input_dir, logger, propname,
                                             propdict)
        else:
            logger.error(
                "File extension '%s' is not a valid file type. Must be one of %s."
                % (ext, filetypes.QueueFile.excel_ext))
            sys.exit(1)
    else:
        # This section is for reading a directory that contains CSV
        # files, i.e., targets.csv, inscfg.csv, etc.
        dirname = os.path.dirname(options.input_dir)
        propname = os.path.basename(options.input_dir)
        propdict = {}
        key = propname.upper()
        propdict[key] = entity.Program(key, hours=0, category='')
        progFile = filetypes.ProgramFile(dirname,
                                         logger,
                                         propname,
                                         propdict,
                                         file_ext='csv')

    logger.info('Warning count is %d' % progFile.warn_count)
    logger.info('Error count is   %d' % progFile.error_count)
Beispiel #44
0
def main(options, args):

    app = QtGui.QApplication(sys.argv)

    # ginga needs a logger.
    # If you don't want to log anything you can create a null logger by
    # using null=True in this call instead of log_stderr=True
    logger = log.get_logger("fvlog", log_stderr=True)

    w1 = FitsViewer(logger)
    w1.resize(800, 133)
    w1.show()
    app.setActiveWindow(w1)
    w1.raise_()
    w1.activateWindow()

    if len(args) > 0:
        w1.load_file(args[0])

    app.exec_()
Beispiel #45
0
    def pre_init(self, fitsfile=os.path.join(script_dir, "test.fits")):
        #App design
        self.format_string = formats
        self.interface_file = os.path.join(script_dir,
                                           "WebbFITSViewer_interface.yaml")

        #Tunable settings
        self.pan_scale = 0.05
        self.initial_zoom = 1.0
        self.zoom_speed = 0.02

        #initialize the Ginga backend
        self.logger = log.get_logger("ginga",
                                     level=20,
                                     log_file="/tmp/ginga.log")
        self.autocuts = AutoCuts.Histogram(self.logger)
        self.selected_data = None
        self.box_corners = []

        self.pre_fitsfile = fitsfile
Beispiel #46
0
def main(options, args):

    app = QtGui.QApplication(sys.argv)

    # ginga needs a logger.
    # If you don't want to log anything you can create a null logger by
    # using null=True in this call instead of log_stderr=True
    logger = log.get_logger("example1", log_stderr=True, level=40)

    w = FitsViewer(logger)
    w.resize(524, 540)
    w.show()
    app.setActiveWindow(w)
    w.raise_()
    w.activateWindow()

    if len(args) > 0:
        w.load_file(args[0])

    app.exec_()
Beispiel #47
0
    def __init__(self):
        """Default constructor."""

        #logger = log.get_logger(log_stderr=True, level=20)
        logger = log.get_logger(null=True)

        # Initialize base class
        GingaCanvas.__init__(self, logger=logger)

        # Keep track of all patches
        self.patches = {}
        #self.zorder=10

        self.get_bindings().enable_all(True)
        self.enable_draw(True)
        self.enable_edit(True)

        self.set_drawtype('line', color='green', cap='ball', linewidth=2)
        #self.add_callback('draw-event', self.draw_cb)
        #self.add_callback('edit-event', self.edit_cb)
        self.add_callback('drag-drop', self.drop_file)
Beispiel #48
0
def make_server(logger=None,
                basedir='.',
                numthreads=5,
                host='localhost',
                port=9909,
                viewer_class=None,
                use_opencv=False):

    if logger is None:
        logger = log.get_logger("ipg", null=True)
    ev_quit = threading.Event()

    if use_opencv:
        from ginga import trcalc
        try:
            trcalc.use('opencv')
        except Exception as e:
            logger.warning("Error using opencv: %s" % str(e))

    thread_pool = Task.ThreadPool(numthreads, logger, ev_quit=ev_quit)

    base_url = "http://%s:%d/app" % (host, port)
    app = Widgets.Application(logger=logger,
                              base_url=base_url,
                              host=host,
                              port=port)

    factory = ViewerFactory(logger, app, thread_pool)

    server = WebServer(app,
                       thread_pool,
                       factory,
                       host=host,
                       port=port,
                       viewer_class=viewer_class)

    return server
Beispiel #49
0
    def main(self, options, args):
        """
        Main routine for running the reference viewer.

        `options` is a OptionParser object that has been populated with
        values from parsing the command line.  It should at least include
        the options from add_default_options()

        `args` is a list of arguments to the viewer after parsing out
        options.  It should contain a list of files or URLs to load.
        """

        # Create a logger
        logger = log.get_logger(name='ginga', options=options)

        # Get settings (preferences)
        basedir = paths.ginga_home
        if not os.path.exists(basedir):
            try:
                os.mkdir(basedir)
            except OSError as e:
                logger.warning("Couldn't create ginga settings area (%s): %s" %
                               (basedir, str(e)))
                logger.warning("Preferences will not be able to be saved")

        # Set up preferences
        prefs = Settings.Preferences(basefolder=basedir, logger=logger)
        settings = prefs.create_category('general')
        settings.set_defaults(useMatplotlibColormaps=False,
                              widgetSet='choose',
                              WCSpkg='choose',
                              FITSpkg='choose',
                              recursion_limit=2000,
                              icc_working_profile=None,
                              font_scaling_factor=None,
                              save_layout=True,
                              channel_prefix="Image")
        settings.load(onError='silent')

        # default of 1000 is a little too small
        sys.setrecursionlimit(settings.get('recursion_limit'))

        # So we can find our plugins
        sys.path.insert(0, basedir)
        package_home = os.path.split(sys.modules['ginga.version'].__file__)[0]
        child_dir = os.path.join(package_home, 'rv', 'plugins')
        sys.path.insert(0, child_dir)
        plugin_dir = os.path.join(basedir, 'plugins')
        sys.path.insert(0, plugin_dir)

        gc = os.path.join(basedir, "ginga_config.py")
        have_ginga_config = os.path.exists(gc)

        # User configuration, earliest possible intervention
        if have_ginga_config:
            try:
                import ginga_config

                if hasattr(ginga_config, 'init_config'):
                    ginga_config.init_config(self)

            except Exception as e:
                try:
                    (type, value, tb) = sys.exc_info()
                    tb_str = "\n".join(traceback.format_tb(tb))

                except Exception:
                    tb_str = "Traceback information unavailable."

                logger.error("Error processing Ginga config file: %s" %
                             (str(e)))
                logger.error("Traceback:\n%s" % (tb_str))

        # Choose a toolkit
        if options.toolkit:
            toolkit = options.toolkit
        else:
            toolkit = settings.get('widgetSet', 'choose')

        if toolkit == 'choose':
            try:
                ginga_toolkit.choose()
            except ImportError as e:
                print("UI toolkit choose error: %s" % str(e))
                sys.exit(1)
        else:
            ginga_toolkit.use(toolkit)

        tkname = ginga_toolkit.get_family()
        logger.info("Chosen toolkit (%s) family is '%s'" %
                    (ginga_toolkit.toolkit, tkname))

        # these imports have to be here, otherwise they force the choice
        # of toolkit too early
        from ginga.rv.Control import GingaShell, GuiLogHandler

        if settings.get('useMatplotlibColormaps', False):
            # Add matplotlib color maps if matplotlib is installed
            try:
                from ginga import cmap
                cmap.add_matplotlib_cmaps(fail_on_import_error=False)
            except Exception as e:
                logger.warning("failed to load matplotlib colormaps: %s" %
                               (str(e)))

        # Set a working RGB ICC profile if user has one
        working_profile = settings.get('icc_working_profile', None)
        rgb_cms.working_profile = working_profile

        # User wants to customize the WCS package?
        if options.wcspkg:
            wcspkg = options.wcspkg
        else:
            wcspkg = settings.get('WCSpkg', 'choose')

        try:
            from ginga.util import wcsmod
            if wcspkg != 'choose':
                assert wcsmod.use(wcspkg) is True
        except Exception as e:
            logger.warning("failed to set WCS package preference: %s" %
                           (str(e)))

        # User wants to customize the FITS package?
        if options.fitspkg:
            fitspkg = options.fitspkg
        else:
            fitspkg = settings.get('FITSpkg', 'choose')

        try:
            from ginga.util import io_fits, loader
            if fitspkg != 'choose':
                assert io_fits.use(fitspkg) is True
                # opener name is not necessarily the same
                opener = loader.get_opener(io_fits.fitsLoaderClass.name)
                # set this opener as the priority one
                opener.priority = -99

        except Exception as e:
            logger.warning("failed to set FITS package preference: %s" %
                           (str(e)))

        # Check whether user wants to use OpenCv
        use_opencv = settings.get('use_opencv', False)
        if use_opencv or options.opencv:
            from ginga import trcalc
            try:
                trcalc.use('opencv')
            except Exception as e:
                logger.warning("failed to set OpenCv preference: %s" %
                               (str(e)))

        # Check whether user wants to use OpenCL
        use_opencl = settings.get('use_opencl', False)
        if use_opencl or options.opencl:
            from ginga import trcalc
            try:
                trcalc.use('opencl')
            except Exception as e:
                logger.warning("failed to set OpenCL preference: %s" %
                               (str(e)))

        # Create the dynamic module manager
        mm = ModuleManager.ModuleManager(logger)

        # Create and start thread pool
        ev_quit = threading.Event()
        thread_pool = Task.ThreadPool(options.numthreads,
                                      logger,
                                      ev_quit=ev_quit)
        thread_pool.startall()

        # Create the Ginga main object
        ginga_shell = GingaShell(logger,
                                 thread_pool,
                                 mm,
                                 prefs,
                                 ev_quit=ev_quit)

        # user wants to set font scaling.
        # NOTE: this happens *after* creation of shell object, since
        # Application object constructor will also set this
        font_scaling = settings.get('font_scaling_factor', None)
        if font_scaling is not None:
            logger.debug(
                "overriding font_scaling_factor to {}".format(font_scaling))
            from ginga.fonts import font_asst
            font_asst.default_scaling_factor = font_scaling

        layout_file = None
        if not options.norestore and settings.get('save_layout', False):
            layout_file = os.path.join(basedir, 'layout')

        ginga_shell.set_layout(self.layout, layout_file=layout_file)

        # User configuration (custom star catalogs, etc.)
        if have_ginga_config:
            try:
                if hasattr(ginga_config, 'pre_gui_config'):
                    ginga_config.pre_gui_config(ginga_shell)
            except Exception as e:
                try:
                    (type, value, tb) = sys.exc_info()
                    tb_str = "\n".join(traceback.format_tb(tb))

                except Exception:
                    tb_str = "Traceback information unavailable."

                logger.error("Error importing Ginga config file: %s" %
                             (str(e)))
                logger.error("Traceback:\n%s" % (tb_str))

        # Build desired layout
        ginga_shell.build_toplevel()

        # Did user specify a particular geometry?
        if options.geometry:
            ginga_shell.set_geometry(options.geometry)

        # make the list of disabled plugins
        if options.disable_plugins is not None:
            disabled_plugins = options.disable_plugins.lower().split(',')
        else:
            disabled_plugins = settings.get('disable_plugins', [])
            if not isinstance(disabled_plugins, list):
                disabled_plugins = disabled_plugins.lower().split(',')

        # Add GUI log handler (for "Log" global plugin)
        guiHdlr = GuiLogHandler(ginga_shell)
        guiHdlr.setLevel(options.loglevel)
        fmt = logging.Formatter(log.LOG_FORMAT)
        guiHdlr.setFormatter(fmt)
        logger.addHandler(guiHdlr)

        # Load any custom modules
        if options.modules is not None:
            modules = options.modules.split(',')
        else:
            modules = settings.get('global_plugins', [])
            if not isinstance(modules, list):
                modules = modules.split(',')

        for long_plugin_name in modules:
            if '.' in long_plugin_name:
                tmpstr = long_plugin_name.split('.')
                plugin_name = tmpstr[-1]
                pfx = '.'.join(tmpstr[:-1])
            else:
                plugin_name = long_plugin_name
                pfx = None
            menu_name = "%s [G]" % (plugin_name)
            spec = Bunch(name=plugin_name,
                         module=plugin_name,
                         ptype='global',
                         tab=plugin_name,
                         menu=menu_name,
                         category="Custom",
                         workspace='right',
                         pfx=pfx)
            self.add_plugin_spec(spec)

        # Load any custom local plugins
        if options.plugins is not None:
            plugins = options.plugins.split(',')
        else:
            plugins = settings.get('local_plugins', [])
            if not isinstance(plugins, list):
                plugins = plugins.split(',')

        for long_plugin_name in plugins:
            if '.' in long_plugin_name:
                tmpstr = long_plugin_name.split('.')
                plugin_name = tmpstr[-1]
                pfx = '.'.join(tmpstr[:-1])
            else:
                plugin_name = long_plugin_name
                pfx = None
            spec = Bunch(module=plugin_name,
                         workspace='dialogs',
                         ptype='local',
                         category="Custom",
                         hidden=False,
                         pfx=pfx)
            self.add_plugin_spec(spec)

        # Add non-disabled plugins
        enabled_plugins = [
            spec for spec in self.plugins
            if spec.module.lower() not in disabled_plugins
        ]
        ginga_shell.set_plugins(enabled_plugins)

        # start any plugins that have start=True
        ginga_shell.boot_plugins()
        ginga_shell.update_pending()

        # TEMP?
        tab_names = [
            name.lower() for name in ginga_shell.ds.get_tabnames(group=None)
        ]
        if 'info' in tab_names:
            ginga_shell.ds.raise_tab('Info')
        if 'synopsis' in tab_names:
            ginga_shell.ds.raise_tab('Synopsis')
        if 'thumbs' in tab_names:
            ginga_shell.ds.raise_tab('Thumbs')

        # Add custom channels
        if options.channels is not None:
            channels = options.channels.split(',')
        else:
            channels = settings.get('channels', self.channels)
            if not isinstance(channels, list):
                channels = channels.split(',')

        if len(channels) == 0:
            # should provide at least one default channel?
            channels = [settings.get('channel_prefix', "Image")]

        # populate the initial channel lineup
        for item in channels:
            if isinstance(item, str):
                chname, wsname = item, None
            else:
                chname, wsname = item
            ginga_shell.add_channel(chname, workspace=wsname)

        ginga_shell.change_channel(chname)

        # User configuration (custom star catalogs, etc.)
        if have_ginga_config:
            try:
                if hasattr(ginga_config, 'post_gui_config'):
                    ginga_config.post_gui_config(ginga_shell)

            except Exception as e:
                try:
                    (type, value, tb) = sys.exc_info()
                    tb_str = "\n".join(traceback.format_tb(tb))

                except Exception:
                    tb_str = "Traceback information unavailable."

                logger.error("Error processing Ginga config file: %s" %
                             (str(e)))
                logger.error("Traceback:\n%s" % (tb_str))

        # Redirect warnings to logger
        for hdlr in logger.handlers:
            logging.getLogger('py.warnings').addHandler(hdlr)

        # Display banner the first time run, unless suppressed
        show_banner = True
        try:
            show_banner = settings.get('showBanner')

        except KeyError:
            # disable for subsequent runs
            settings.set(showBanner=False)
            if not os.path.exists(settings.preffile):
                settings.save()

        if (not options.nosplash) and (len(args) == 0) and show_banner:
            ginga_shell.banner(raiseTab=True)

        # Handle inputs like "*.fits[ext]" that sys cmd cannot auto expand.
        expanded_args = []
        for imgfile in args:
            if '*' in imgfile:
                if '[' in imgfile and imgfile.endswith(']'):
                    s = imgfile.split('[')
                    ext = '[' + s[1]
                    imgfile = s[0]
                else:
                    ext = ''
                for fname in glob.iglob(imgfile):
                    expanded_args.append(fname + ext)
            else:
                expanded_args.append(imgfile)

        # Assume remaining arguments are fits files and load them.
        if not options.separate_channels:
            chname = channels[0]
            ginga_shell.gui_do(ginga_shell.open_uris,
                               expanded_args,
                               chname=chname)
        else:
            i = 0
            num_channels = len(channels)
            for imgfile in expanded_args:
                if i < num_channels:
                    chname = channels[i]
                    i = i + 1
                else:
                    channel = ginga_shell.add_channel_auto()
                    chname = channel.name
                ginga_shell.gui_do(ginga_shell.open_uris, [imgfile],
                                   chname=chname)

        try:
            try:
                # if there is a network component, start it
                if hasattr(ginga_shell, 'start'):
                    logger.info("starting network interface...")
                    task = Task.FuncTask2(ginga_shell.start)
                    thread_pool.addTask(task)

                # Main loop to handle GUI events
                logger.info("entering mainloop...")
                ginga_shell.mainloop(timeout=0.001)

            except KeyboardInterrupt:
                logger.error("Received keyboard interrupt!")

        finally:
            logger.info("Shutting down...")
            ev_quit.set()

        sys.exit(0)
Beispiel #50
0
    if top is not None:
        top.delete()
    sys.exit()


def popup_dialog(parent):
    dia = Widgets.Dialog(title="Dialog Title",
                         buttons=[('ok', 0), ('cancel', 1)],
                         parent=parent,
                         modal=True)
    cntr = dia.get_content_area()
    cntr.add_widget(Widgets.Label("My Dialog Content"))
    dia.show()


logger = log.get_logger('test', log_stderr=True, level=20)

app = Widgets.Application(logger=logger)
if hasattr(app, 'script_imports'):
    app.script_imports.append('jqx')
app.add_callback('shutdown', quit)
top = app.make_window("Ginga Wrapped Widgets Example: %s" % (wname))
top.add_callback('close', quit)

vbox = Widgets.VBox()
vbox.set_border_width(2)
vbox.set_spacing(1)

dia = None

if wname == 'label':
Beispiel #51
0
    def __init__(self, exam=None, close_on_del=True, logger=None, port=None):
        """initialize a general ginga viewer object.

        Parameters
        ----------

        exam: imexam object
            This is the imexamine object which contains the examination
            functions

        close_on_del: bool
            If True, the window connection shuts down when the object is
            deleted

        logger: logger object
            Ginga viewers all need a logger, if none is provided it will
            create one

        port: int
            This is used as the communication port for the HTML5 viewer. The
            user can choose to have multiple windows open at the same time
            as long as they have different port designations. If no port is
            specified, this class will choose an open port.

        """
        global _matplotlib_cmaps_added
        self._port = port
        self.exam = exam
        self._close_on_del = close_on_del
        # dictionary where each key is a frame number, and the values are a
        # dictionary of details about the image loaded in that frame
        self._viewer = dict()
        self._current_frame = 1
        self._current_slice = None

        # ginga view object, created in subclass
        self.ginga_view = None

        # set up possible color maps
        self._define_cmaps()

        # for synchronizing on keystrokes
        self._rlock = threading.RLock()  # this creates a thread lock
        self._keyvals = list()
        self._capturing = False

        # ginga objects need a logger, create a null one if we are not
        # handed one in the constructor
        self._log_level = 40
        if logger is None:
            logger = log.get_logger(level=self._log_level, log_stderr=True)
        self.logger = logger

        # Establish settings (preferences) for ginga viewers
        basedir = paths.ginga_home
        self.prefs = Settings.Preferences(basefolder=basedir,
                                          logger=self.logger)

        # general preferences shared with other ginga viewers
        self.settings = self.prefs.createCategory('general')
        self.settings.load(onError='silent')
        self.settings.setDefaults(useMatplotlibColormaps=False,
                                  autocuts='on',
                                  autocut_method='zscale')

        # add matplotlib colormaps to ginga's own set if user has this
        # preference set
        if self.settings.get('useMatplotlibColormaps', False) and \
                (not _matplotlib_cmaps_added):
            # Add matplotlib color maps if matplotlib is installed
            try:
                cmap.add_matplotlib_cmaps()
                _matplotlib_cmaps_added = True
            except Exception as e:
                print(f"Failed to load matplotlib colormaps: {repr(e)}")

        # bindings preferences shared with other ginga viewers
        bind_prefs = self.prefs.createCategory('bindings')
        bind_prefs.load(onError='silent')

        # viewer preferences unique to imexam ginga viewers
        viewer_prefs = self.prefs.createCategory('imexam')
        viewer_prefs.load(onError='silent')

        # create the viewer specific to this backend
        self._create_viewer(bind_prefs, viewer_prefs)

        # TODO: at some point, it might be better to simply add a custom
        # mode called "imexam"--that is a more robust way to do things
        # but we'd have to register the imexam key bindings in a different way
        # bm = self.ginga_view.get_bindmap()
        # bm.add_mode('i', 'imexam', mode_type='locked',
        #             msg="Entering imexam mode...")
        # modifiers_set = bindmap.get_modifiers()
        # bm.map_event('imexam', modifiers_set, trigger, evname)

        # enable all interactive ginga features
        bindings = self.ginga_view.get_bindings()
        bindings.enable_all(True)

        # Add a callback to take us into imexam mode
        top_canvas = self.ginga_view.get_canvas()
        top_canvas.add_callback('key-press', self._key_press_normal)

        # Add a callback to our private canvas to take us out of imexam mode
        self.canvas.enable_draw(False)
        self.canvas.add_callback('key-press', self._key_press_imexam)
        self.canvas.set_surface(self.ginga_view)
        self.canvas.ui_setActive(True)
Beispiel #52
0
    parser.add_argument(
        '--sepath',
        dest='sepath',
        default=None,
        help=
        'path to source extractor config files (e.g. ~/github/HalphaImaging/astromatic/ - this is default if no path is given.)'
    )
    parser.add_argument(
        '--config',
        dest='config',
        default=None,
        help='source extractor config file.  default is default.sex.HDI.mask')

    args = parser.parse_args()

    logger = log.get_logger("masklog", log_stderr=True, level=40)
    app = QtWidgets.QApplication(sys.argv)
    #MainWindow = QtWidgets.QMainWindow()
    MainWindow = QtWidgets.QWidget()
    if args.image is not None:
        ui = maskwindow(MainWindow,
                        logger,
                        image=args.image,
                        haimage=args.haimage,
                        sepath=args.sepath,
                        config=args.config)
    else:
        ui = maskwindow(MainWindow, logger)
    #ui.setupUi(MainWindow)
    #ui.test()
Beispiel #53
0
    def main(self, options, args):
        # Create top level logger.
        svcname = 'qplan'
        logger = log.get_logger(name=svcname, options=options)

        logger.info("starting qplan %s" % (version.version))

        ev_quit = threading.Event()

        thread_pool = Task.ThreadPool(logger=logger,
                                      ev_quit=ev_quit,
                                      numthreads=options.numthreads)

        if options.toolkit is not None:
            ginga_toolkit.use(options.toolkit)
        else:
            ginga_toolkit.choose()

        tkname = ginga_toolkit.get_family()
        logger.info("Chosen toolkit (%s) family is '%s'" %
                    (ginga_toolkit.toolkit, tkname))

        from qplan.View import Viewer
        # must import AFTER Viewer
        from ginga.rv.Control import GuiLogHandler

        class QueuePlanner(Controller, Viewer):
            def __init__(self, logger, thread_pool, module_manager,
                         preferences, ev_quit, model):

                Viewer.__init__(self, logger, ev_quit)
                Controller.__init__(self, logger, thread_pool, module_manager,
                                    preferences, ev_quit, model)

        # Get settings folder
        if 'CONFHOME' in os.environ:
            basedir = os.path.join(os.environ['CONFHOME'], svcname)
        else:
            basedir = os.path.join(os.environ['HOME'], '.' + svcname)
        if not os.path.exists(basedir):
            os.mkdir(basedir)
        prefs = Settings.Preferences(basefolder=basedir, logger=logger)

        settings = prefs.create_category('general')
        settings.load(onError='silent')
        settings.set_defaults(output_dir=options.output_dir, save_layout=False)

        mm = ModuleManager.ModuleManager(logger)

        ## # Add any custom modules
        ## if options.modules:
        ##     modules = options.modules.split(',')
        ##     for mdlname in modules:
        ##         #self.mm.loadModule(name, pfx=pluginconfpfx)
        ##         self.mm.loadModule(name)

        observer = site.get_site(options.sitename)

        scheduler = Scheduler(logger, observer)

        model = QueueModel(logger, scheduler)

        if options.completed is not None:
            import json
            logger.info("reading executed OBs from '{}' ...".format(
                options.completed))
            # user specified a set of completed OB keys
            with open(options.completed, 'r') as in_f:
                buf = in_f.read()
            d = json.loads(buf)
            model.completed_obs = {(propid, obcode): d[propid][obcode]
                                   for propid in d for obcode in d[propid]}

        # Start up the control/display engine
        qplanner = QueuePlanner(logger, thread_pool, mm, prefs, ev_quit, model)
        qplanner.set_input_dir(options.input_dir)
        qplanner.set_input_fmt(options.input_fmt)

        layout_file = None
        if not options.norestore and settings.get('save_layout', False):
            layout_file = os.path.join(basedir, 'layout')

        # Build desired layout
        qplanner.build_toplevel(default_layout, layout_file=layout_file)
        for w in qplanner.ds.toplevels:
            w.show()

        # load plugins
        for spec in plugins:
            qplanner.load_plugin(spec.name, spec)

        # start any plugins that have start=True
        qplanner.boot_plugins()

        qplanner.ds.raise_tab('Control Panel')

        guiHdlr = GuiLogHandler(qplanner)
        #guiHdlr.setLevel(options.loglevel)
        guiHdlr.setLevel(logging.INFO)
        fmt = logging.Formatter(log.LOG_FORMAT)
        guiHdlr.setFormatter(fmt)
        logger.addHandler(guiHdlr)

        qplanner.update_pending()

        # Did user specify geometry
        if options.geometry:
            qplanner.set_geometry(options.geometry)

        # Raise window
        w = qplanner.w.root
        w.show()

        server_started = False

        # Create threadpool and start it
        try:
            # Startup monitor threadpool
            thread_pool.startall(wait=True)

            try:
                # if there is a network component, start it
                if hasattr(qplanner, 'start'):
                    task = Task.FuncTask2(qplanner.start)
                    thread_pool.addTask(task)

                # Main loop to handle GUI events
                qplanner.mainloop(timeout=0.001)

            except KeyboardInterrupt:
                logger.error("Received keyboard interrupt!")

        finally:
            logger.info("Shutting down...")
            thread_pool.stopall(wait=True)

        sys.exit(0)
Beispiel #54
0
 def setup_class(self):
     self.logger = log.get_logger("TestAstroImage", null=True)
     self.image = AstroImage.AstroImage(logger=self.logger)
Beispiel #55
0
    def main(self, options, args):
        """
        Main routine for running the reference viewer.

        `options` is a OptionParser object that has been populated with
        values from parsing the command line.  It should at least include
        the options from add_default_options()

        `args` is a list of arguments to the viewer after parsing out
        options.  It should contain a list of files or URLs to load.
        """

        # Create a logger
        logger = log.get_logger(name='ginga', options=options)

        # Get settings (preferences)
        basedir = paths.ginga_home
        if not os.path.exists(basedir):
            try:
                os.mkdir(basedir)
            except OSError as e:
                logger.warn("Couldn't create ginga settings area (%s): %s" %
                            (basedir, str(e)))
                logger.warn("Preferences will not be able to be saved")

        # Set up preferences
        prefs = Settings.Preferences(basefolder=basedir, logger=logger)
        settings = prefs.createCategory('general')
        settings.load(onError='silent')
        settings.setDefaults(useMatplotlibColormaps=False,
                             widgetSet='choose',
                             WCSpkg='choose',
                             FITSpkg='choose',
                             recursion_limit=2000)

        # default of 1000 is a little too small
        sys.setrecursionlimit(settings.get('recursion_limit'))

        # So we can find our plugins
        sys.path.insert(0, basedir)
        moduleHome = os.path.split(sys.modules['ginga.version'].__file__)[0]
        childDir = os.path.join(moduleHome, 'misc', 'plugins')
        sys.path.insert(0, childDir)
        pluginDir = os.path.join(basedir, 'plugins')
        sys.path.insert(0, pluginDir)

        # Choose a toolkit
        if options.toolkit:
            toolkit = options.toolkit
        else:
            toolkit = settings.get('widgetSet', 'choose')

        if toolkit == 'choose':
            try:
                from ginga.qtw import QtHelp
            except ImportError:
                try:
                    from ginga.gtkw import GtkHelp
                except ImportError:
                    print("You need python-gtk or python-qt to run Ginga!")
                    sys.exit(1)
        else:
            ginga_toolkit.use(toolkit)

        tkname = ginga_toolkit.get_family()
        logger.info("Chosen toolkit (%s) family is '%s'" %
                    (ginga_toolkit.toolkit, tkname))

        # these imports have to be here, otherwise they force the choice
        # of toolkit too early
        from ginga.gw.GingaGw import GingaView
        from ginga.Control import GingaControl, GuiLogHandler

        # Define class dynamically based on toolkit choice
        class GingaShell(GingaControl, GingaView):
            def __init__(self,
                         logger,
                         thread_pool,
                         module_manager,
                         prefs,
                         ev_quit=None):
                GingaView.__init__(self, logger, ev_quit, thread_pool)
                GingaControl.__init__(self,
                                      logger,
                                      thread_pool,
                                      module_manager,
                                      prefs,
                                      ev_quit=ev_quit)

        if settings.get('useMatplotlibColormaps', False):
            # Add matplotlib color maps if matplotlib is installed
            try:
                from ginga import cmap
                cmap.add_matplotlib_cmaps()
            except Exception as e:
                logger.warn("failed to load matplotlib colormaps: %s" %
                            (str(e)))

        # User wants to customize the WCS package?
        if options.wcspkg:
            wcspkg = options.wcspkg
        else:
            wcspkg = settings.get('WCSpkg', 'choose')

        try:
            from ginga.util import wcsmod
            assert wcsmod.use(wcspkg) == True
        except Exception as e:
            logger.warn("failed to set WCS package preference: %s" % (str(e)))

        # User wants to customize the FITS package?
        if options.fitspkg:
            fitspkg = options.fitspkg
        else:
            fitspkg = settings.get('FITSpkg', 'choose')

        try:
            from ginga.util import io_fits
            assert io_fits.use(fitspkg) == True
        except Exception as e:
            logger.warn("failed to set FITS package preference: %s" % (str(e)))

        # Check whether user wants to use OpenCv
        use_opencv = settings.get('use_opencv', False)
        if use_opencv or options.opencv:
            from ginga import trcalc
            try:
                trcalc.use('opencv')
            except Exception as e:
                logger.warn("failed to set OpenCv preference: %s" % (str(e)))

        # Create the dynamic module manager
        mm = ModuleManager.ModuleManager(logger)

        # Create and start thread pool
        ev_quit = threading.Event()
        thread_pool = Task.ThreadPool(options.numthreads,
                                      logger,
                                      ev_quit=ev_quit)
        thread_pool.startall()

        # Create the Ginga main object
        ginga_shell = GingaShell(logger,
                                 thread_pool,
                                 mm,
                                 prefs,
                                 ev_quit=ev_quit)
        ginga_shell.set_layout(self.layout)

        gc = os.path.join(basedir, "ginga_config.py")
        have_ginga_config = os.path.exists(gc)

        # User configuration (custom star catalogs, etc.)
        if have_ginga_config:
            try:
                import ginga_config

                ginga_config.pre_gui_config(ginga_shell)
            except Exception as e:
                try:
                    (type, value, tb) = sys.exc_info()
                    tb_str = "\n".join(traceback.format_tb(tb))

                except Exception:
                    tb_str = "Traceback information unavailable."

                logger.error("Error importing Ginga config file: %s" %
                             (str(e)))
                logger.error("Traceback:\n%s" % (tb_str))

        # Build desired layout
        ginga_shell.build_toplevel()

        # Did user specify a particular geometry?
        if options.geometry:
            ginga_shell.set_geometry(options.geometry)

        # make the list of disabled plugins
        disabled_plugins = []
        if not (options.disable_plugins is None):
            disabled_plugins = options.disable_plugins.lower().split(',')

        # Add desired global plugins
        for spec in self.global_plugins:
            if not spec.module.lower() in disabled_plugins:
                ginga_shell.add_global_plugin(spec)

        # Add GUI log handler (for "Log" global plugin)
        guiHdlr = GuiLogHandler(ginga_shell)
        guiHdlr.setLevel(options.loglevel)
        fmt = logging.Formatter(log.LOG_FORMAT)
        guiHdlr.setFormatter(fmt)
        logger.addHandler(guiHdlr)

        # Load any custom modules
        if options.modules:
            modules = options.modules.split(',')
            for longPluginName in modules:
                if '.' in longPluginName:
                    tmpstr = longPluginName.split('.')
                    pluginName = tmpstr[-1]
                    pfx = '.'.join(tmpstr[:-1])
                else:
                    pluginName = longPluginName
                    pfx = None
                spec = Bunch(name=pluginName,
                             module=pluginName,
                             tab=pluginName,
                             ws='right',
                             pfx=pfx)
                ginga_shell.add_global_plugin(spec)

        # Load modules for "local" (per-channel) plug ins
        for spec in self.local_plugins:
            if not spec.module.lower() in disabled_plugins:
                ginga_shell.add_local_plugin(spec)

        # Load any custom plugins
        if options.plugins:
            plugins = options.plugins.split(',')
            for longPluginName in plugins:
                if '.' in longPluginName:
                    tmpstr = longPluginName.split('.')
                    pluginName = tmpstr[-1]
                    pfx = '.'.join(tmpstr[:-1])
                else:
                    pluginName = longPluginName
                    pfx = None
                spec = Bunch(module=pluginName,
                             ws='dialogs',
                             hidden=False,
                             pfx=pfx)
                ginga_shell.add_local_plugin(spec)

        ginga_shell.update_pending()

        # TEMP?
        tab_names = list(
            map(lambda name: name.lower(),
                ginga_shell.ds.get_tabnames(group=None)))
        if 'info' in tab_names:
            ginga_shell.ds.raise_tab('Info')
        if 'thumbs' in tab_names:
            ginga_shell.ds.raise_tab('Thumbs')

        # Add custom channels
        channels = options.channels.split(',')
        for chname in channels:
            ginga_shell.add_channel(chname)
        ginga_shell.change_channel(channels[0])

        # User configuration (custom star catalogs, etc.)
        if have_ginga_config:
            try:
                ginga_config.post_gui_config(ginga_shell)
            except Exception as e:
                try:
                    (type, value, tb) = sys.exc_info()
                    tb_str = "\n".join(traceback.format_tb(tb))

                except Exception:
                    tb_str = "Traceback information unavailable."

                logger.error("Error processing Ginga config file: %s" %
                             (str(e)))
                logger.error("Traceback:\n%s" % (tb_str))

        # Redirect warnings to logger
        for hdlr in logger.handlers:
            logging.getLogger('py.warnings').addHandler(hdlr)

        # Display banner the first time run, unless suppressed
        showBanner = True
        try:
            showBanner = settings.get('showBanner')

        except KeyError:
            # disable for subsequent runs
            settings.set(showBanner=False)
            settings.save()

        if (not options.nosplash) and (len(args) == 0) and showBanner:
            ginga_shell.banner(raiseTab=True)

        # Assume remaining arguments are fits files and load them.
        for imgfile in args:
            ginga_shell.nongui_do(ginga_shell.load_file, imgfile)

        try:
            try:
                # if there is a network component, start it
                if hasattr(ginga_shell, 'start'):
                    task = Task.FuncTask2(ginga_shell.start)
                    thread_pool.addTask(task)

                # Main loop to handle GUI events
                logger.info("Entering mainloop...")
                ginga_shell.mainloop(timeout=0.001)

            except KeyboardInterrupt:
                logger.error("Received keyboard interrupt!")

        finally:
            logger.info("Shutting down...")
            ev_quit.set()

        sys.exit(0)
Beispiel #56
0
def main(options, args):

    # default of 1000 is a little too small
    sys.setrecursionlimit(2000)

    # Create a logger
    logger = log.get_logger(name='ginga', options=options)

    # Get settings (preferences)
    basedir = paths.ginga_home
    if not os.path.exists(basedir):
        try:
            os.mkdir(basedir)
        except OSError as e:
            logger.warn("Couldn't create ginga settings area (%s): %s" %
                        (basedir, str(e)))
            logger.warn("Preferences will not be able to be saved")

    # Set up preferences
    prefs = Settings.Preferences(basefolder=basedir, logger=logger)
    settings = prefs.createCategory('general')
    settings.load(onError='silent')
    settings.setDefaults(useMatplotlibColormaps=False,
                         widgetSet='choose',
                         WCSpkg='choose',
                         FITSpkg='choose')

    # So we can find our plugins
    sys.path.insert(0, basedir)
    moduleHome = os.path.split(sys.modules['ginga.version'].__file__)[0]
    childDir = os.path.join(moduleHome, 'misc', 'plugins')
    sys.path.insert(0, childDir)
    pluginDir = os.path.join(basedir, 'plugins')
    sys.path.insert(0, pluginDir)

    # Choose a toolkit
    if options.toolkit:
        toolkit = options.toolkit
    else:
        toolkit = settings.get('widgetSet', 'choose')

    ginga_toolkit.use(toolkit)
    tkname = ginga_toolkit.get_family()

    if tkname == 'gtk':
        from ginga.gtkw.GingaGtk import GingaView
    elif tkname == 'qt':
        from ginga.qtw.GingaQt import GingaView
    else:
        try:
            from ginga.qtw.GingaQt import GingaView
        except ImportError:
            try:
                from ginga.gtkw.GingaGtk import GingaView
            except ImportError:
                print("You need python-gtk or python-qt4 to run Ginga!")
                sys.exit(1)

    # Define class dynamically based on toolkit choice
    class Ginga(GingaControl, GingaView):
        def __init__(self,
                     logger,
                     threadPool,
                     module_manager,
                     prefs,
                     ev_quit=None):
            GingaView.__init__(self, logger, ev_quit)
            GingaControl.__init__(self,
                                  logger,
                                  threadPool,
                                  module_manager,
                                  prefs,
                                  ev_quit=ev_quit)

    if settings.get('useMatplotlibColormaps', False):
        # Add matplotlib color maps if matplotlib is installed
        try:
            from ginga import cmap
            cmap.add_matplotlib_cmaps()
        except Exception as e:
            logger.warn("failed to load matplotlib colormaps: %s" % (str(e)))

    # User wants to customize the WCS package?
    if options.wcs:
        wcspkg = options.wcs
    else:
        wcspkg = settings.get('WCSpkg', 'choose')

    try:
        from ginga.util import wcsmod
        assert wcsmod.use(wcspkg) == True
    except Exception as e:
        logger.warn("failed to set WCS package preference: %s" % (str(e)))

    # User wants to customize the FITS package?
    if options.fits:
        fitspkg = options.fits
    else:
        fitspkg = settings.get('FITSpkg', 'choose')

    try:
        from ginga.util import io_fits
        assert io_fits.use(fitspkg) == True
    except Exception as e:
        logger.warn("failed to set FITS package preference: %s" % (str(e)))

    # Create the dynamic module manager
    mm = ModuleManager.ModuleManager(logger)

    # Create and start thread pool
    ev_quit = threading.Event()
    threadPool = Task.ThreadPool(options.numthreads, logger, ev_quit=ev_quit)
    threadPool.startall()

    # Create the Ginga main object
    ginga = Ginga(logger, threadPool, mm, prefs, ev_quit=ev_quit)
    ginga.set_layout(default_layout)

    # User configuration (custom star catalogs, etc.)
    try:
        import ginga_config

        ginga_config.pre_gui_config(ginga)
    except Exception as e:
        try:
            (type, value, tb) = sys.exc_info()
            tb_str = "\n".join(traceback.format_tb(tb))

        except Exception:
            tb_str = "Traceback information unavailable."

        logger.error("Error importing Ginga config file: %s" % (str(e)))
        logger.error("Traceback:\n%s" % (tb_str))

    # Build desired layout
    ginga.build_toplevel()

    # Did user specify a particular geometry?
    if options.geometry:
        ginga.setGeometry(options.geometry)

    # Add desired global plugins
    for spec in global_plugins:
        ginga.add_global_plugin(spec)

    # Add GUI log handler (for "Log" global plugin)
    guiHdlr = GuiLogHandler(ginga)
    guiHdlr.setLevel(options.loglevel)
    fmt = logging.Formatter(log.LOG_FORMAT)
    guiHdlr.setFormatter(fmt)
    logger.addHandler(guiHdlr)

    # Load any custom modules
    if options.modules:
        modules = options.modules.split(',')
        for pluginName in modules:
            spec = Bunch(name=pluginName,
                         module=pluginName,
                         tab=pluginName,
                         ws='right')
            ginga.add_global_plugin(spec)

    # Load modules for "local" (per-channel) plug ins
    for spec in local_plugins:
        ginga.add_local_plugin(spec)

    # Load any custom plugins
    if options.plugins:
        plugins = options.plugins.split(',')
        for pluginName in plugins:
            spec = Bunch(module=pluginName, ws='dialogs', hidden=False)
            ginga.add_local_plugin(spec)

    ginga.update_pending()

    # TEMP?
    ginga.ds.raise_tab('Info')
    ginga.ds.raise_tab('Thumbs')

    # Add custom channels
    channels = options.channels.split(',')
    for chname in channels:
        datasrc = Datasrc.Datasrc(length=options.bufsize)
        ginga.add_channel(chname, datasrc)
    ginga.change_channel(channels[0])

    # User configuration (custom star catalogs, etc.)
    try:
        ginga_config.post_gui_config(ginga)
    except Exception as e:
        try:
            (type, value, tb) = sys.exc_info()
            tb_str = "\n".join(traceback.format_tb(tb))

        except Exception:
            tb_str = "Traceback information unavailable."

        logger.error("Error processing Ginga config file: %s" % (str(e)))
        logger.error("Traceback:\n%s" % (tb_str))

    # Display banner the first time run, unless suppressed
    showBanner = True
    try:
        showBanner = settings.get('showBanner')

    except KeyError:
        # disable for subsequent runs
        settings.set(showBanner=False)
        settings.save()

    if (not options.nosplash) and (len(args) == 0) and showBanner:
        ginga.banner()

    # Assume remaining arguments are fits files and load them.
    for imgfile in args:
        ginga.nongui_do(ginga.load_file, imgfile)

    try:
        try:
            # Main loop to handle GUI events
            logger.info("Entering mainloop...")
            ginga.mainloop(timeout=0.001)

        except KeyboardInterrupt:
            logger.error("Received keyboard interrupt!")

    finally:
        logger.info("Shutting down...")
        ev_quit.set()

    sys.exit(0)
Beispiel #57
0
        objs.append(viewer.dc.Path(pts, **kwargs))

    return viewer.dc.CompoundObject(*objs)

def plot_sphere(viewer, r):
    # sphere
    u = np.linspace(0, np.pi, 30)
    v = np.linspace(0, 2 * np.pi, 30)
    x = np.outer(np.sin (u), np.sin (v)) * r
    y = np.outer(np.sin (u), np.cos (v)) * r
    z = np.outer(np.cos (u), np.ones_like (v)) * r

    wf = get_wireframe(viewer, x, y, z, color='cyan', alpha=0.3)
    viewer.canvas.add(wf)

logger = log.get_logger('example', level=20, log_stderr=True)

app = Widgets.Application(logger)

v = Viewer(app)
v.top.resize(512, 512)
v.top.show()

# put viewer in camera mode
bm = v.vw.get_bindmap()
bm.set_mode('camera', mode_type='locked')

# toggle 3D view
bd = v.vw.get_bindings()
bd.kp_camera_toggle3d(v.vw, None, 0, 0)
Beispiel #58
0
    def btn_up(self, canvas, button, data_x, data_y):
        ra, dec = self.get_wcs(data_x, data_y)
        print("button %s released at data %d,%d ra=%s dec=%s" %
              (button, data_x, data_y, ra, dec))
        return False

    def draw_event(self, canvas, tag):
        obj = canvas.get_object_by_tag(tag)
        data_x, data_y = obj.x, obj.y
        ra, dec = self.get_wcs(data_x, data_y)
        print("A %s was drawn at data %d,%d ra=%s dec=%s" %
              (obj.kind, data_x, data_y, ra, dec))
        return True


# create a regular matplotlib figure
fig = plt.figure()

# Here is our object
logger = log.get_logger(null=not use_logger, log_stderr=True)
foo = MyGingaFigure(logger, fig)

# load an image, if one was provided
if len(sys.argv) > 1:
    foo.load(sys.argv[1])

# Press 'x' to turn on capture of events. Press it again to resume normal
#   processing of events.
# Press 'c' to clear the canvas of drawn points.
plt.show()
Beispiel #59
0
        self.residual_data = fits.getdata(self.output_image,3)
        self.model_frame.load_image(self.model_data)
        self.residual_frame.load_image(self.residual_data)
        pass
        ### THIS SHOULD BE MOVED TO PARENT PROGRAM
        ### BECAUSE HOW U DISPLAY RESULTS WILL VARY WITH USAGE
    def closeEvent(self, event):
        # send signal that window is closed


        event.accept()
        
if __name__ == "__main__":
    #catalog = '/Users/rfinn/research/NSA/nsa_v0_1_2.fits'
    #gcat = galaxy_catalog(catalog)
    #from halphamain import cutout_image
    #from halphamain import cutout_image
    logger = log.get_logger("galfitlog", log_stderr=True, level=40)
    app = QtWidgets.QApplication(sys.argv)
    #MainWindow = QtWidgets.QMainWindow()
    MainWindow = QtWidgets.QWidget()
    ui = galfitwindow(MainWindow, logger, image='MKW8-18216-R.fits', mask_image = 'MKW8-18216-R-mask.fits',
                      psf='MKW8_R.coadd-psf.fits',psf_oversampling=2.)
    #ui.setupUi(MainWindow)
    #ui.test()

    MainWindow.show()
    sys.exit(app.exec_())

    
Beispiel #60
0
def main(options, args):

    #logger = log.get_logger("ginga", options=options)
    logger = log.get_logger("ginga", level=20, log_file="/tmp/ginga.log")

    #TOOLS = "pan,wheel_zoom,box_select,tap"
    TOOLS = "box_select"

    # create a new plot with default tools, using figure
    fig = figure(x_range=[0, 600],
                 y_range=[0, 600],
                 plot_width=600,
                 plot_height=600,
                 tools=TOOLS)

    viewer = ib.CanvasView(logger)
    viewer.set_figure(fig)

    bd = viewer.get_bindings()
    bd.enable_all(True)

    ## box_select_tool = fig.select(dict(type=BoxSelectTool))
    ## box_select_tool.select_every_mousemove = True
    #tap_tool = fig.select_one(TapTool).renderers = [cr]

    # open a session to keep our local document in sync with server
    #session = push_session(curdoc())

    #curdoc().add_periodic_callback(update, 50)

    def load_file(path):
        image = AstroImage(logger=logger)
        image.load_file(path)
        viewer.set_image(image)

    def load_file_cb(attr_name, old_val, new_val):
        #print(attr_name, old_val, new_val)
        load_file(new_val)

    def zoom_ctl_cb(attr_name, old_val, new_val):
        if new_val >= 0:
            new_val += 2
        viewer.zoom_to(int(new_val))
        scale = viewer.get_scale()
        logger.info("%f" % scale)
        viewer.onscreen_message("%f" % (scale), delay=0.3)

    # add a entry widget and configure with the call back
    #dstdir = options.indir
    dstdir = ""
    path_w = TextInput(value=dstdir, title="File:")
    path_w.on_change('value', load_file_cb)

    slide = Slider(start=-20, end=20, step=1, value=1)
    slide.on_change('value', zoom_ctl_cb)

    layout = column(fig, path_w, slide)
    curdoc().add_root(layout)

    if len(args) > 0:
        load_file(args[0])