コード例 #1
0
ファイル: ColorBar.py プロジェクト: fallingelf/ginga
    def __init__(self, logger, rgbmap=None, link=False, settings=None):
        Callback.Callbacks.__init__(self)

        self.logger = logger
        self.link_rgbmap = link
        if not rgbmap:
            rgbmap = RGBMap.RGBMapper(logger)
        # Create settings and set defaults
        if settings is None:
            settings = Settings.SettingGroup(logger=self.logger)
        self.settings = settings

        self._start_x = 0
        self._sarr = None

        cbar = Viewers.CanvasView(logger=self.logger)
        width, height = 1, self.settings.get('cbar_height', 36)
        cbar.set_desired_size(width, height)
        cbar.enable_autozoom('off')
        cbar.enable_autocuts('off')

        # In web backend, JPEG rendering makes for mushy text
        ## settings = cbar.get_settings()
        ## settings.set(html5_canvas_format='png')

        # to respond quickly to contrast adjustment
        #cbar.defer_lagtime = 0.005
        cbar.set_bg(0.4, 0.4, 0.4)
        # for debugging
        cbar.set_name('colorbar')
        self.cbar_view = cbar

        # add callbacks for contrast adjustment, etc.
        cbar.add_callback('configure', self.resize_cb)
        cbar.add_callback('cursor-down', self.cursor_press_cb)
        cbar.add_callback('cursor-move', self.cursor_drag_cb)
        cbar.add_callback('cursor-up', self.cursor_release_cb)
        cbar.add_callback('draw-up', self.draw_release_cb)
        cbar.add_callback('none-move', self.none_move_cb)
        cbar.add_callback('zoom-scroll', self.scroll_cb)
        cbar.add_callback('zoom-pinch', self.pinch_cb)

        #cbar.configure(width, height)
        iw = Viewers.GingaViewerWidget(viewer=cbar)
        self.widget = iw
        iw.resize(width, height)

        fontsize = self.settings.get('fontsize', 12)
        canvas = self.cbar_view.get_canvas()
        self.cbar = utils.ColorBar(offset=0,
                                   height=height,
                                   rgbmap=rgbmap,
                                   fontsize=fontsize)
        canvas.add(self.cbar, tag='colorbar')

        self.set_rgbmap(rgbmap)

        # For callbacks
        for name in ('motion', 'scroll'):
            self.enable_callback(name)
コード例 #2
0
ファイル: TableView.py プロジェクト: pawel-kw/ginga
    def __init__(self, logger=None, settings=None):
        Callback.Callbacks.__init__(self)

        if logger is not None:
            self.logger = logger
        else:
            self.logger = logging.Logger('TableViewBase')

        # Create settings and set defaults
        if settings is None:
            settings = Settings.SettingGroup(logger=self.logger)
        self.settings = settings

        # for debugging
        self.name = str(self)

        self.settings.addDefaults(color_alternate_rows=True,
                                  max_rows_for_col_resize=5000)

        # For callbacks
        for name in (
                'table-set',
                'configure',
        ):
            self.enable_callback(name)
コード例 #3
0
ファイル: FitsImage.py プロジェクト: astrofrog/ginga
    def save_profile(self, **params):
        if self.image == None:
            return
        profile = self.image.get('profile', None)
        if (profile == None):
            # If image has no profile then create one
            profile = Settings.SettingGroup()
            self.image.set(profile=profile)

        self.logger.debug("saving to image profile: params=%s" % (str(params)))
        profile.set(**params)
コード例 #4
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)
コード例 #5
0
 def get_image_profile(self, image):
     profile = image.get('profile', None)
     if profile is None:
         profile = Settings.SettingGroup()
         image.set(profile=profile)
     return profile
コード例 #6
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)
コード例 #7
0
ファイル: main.py プロジェクト: aaronroodman/ginga
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)
コード例 #8
0
ファイル: RGBMap.py プロジェクト: danny-cohen/ginga
    def __init__(self, logger, dist=None, settings=None, bpp=None):
        Callback.Callbacks.__init__(self)

        self.logger = logger

        # Create settings and set defaults
        if settings is None:
            settings = Settings.SettingGroup(logger=self.logger)
        self.settings = settings
        self.t_ = settings
        self.settings_keys = ['color_map', 'intensity_map',
                              'color_array', 'shift_array',
                              'color_algorithm', 'color_hashsize',
                              ]

        # add our defaults
        self.t_.add_defaults(color_map='gray', intensity_map='ramp',
                             color_algorithm='linear',
                             color_hashsize=65535,
                             color_array=None, shift_array=None)
        self.t_.get_setting('color_map').add_callback('set',
                                                      self.color_map_set_cb)
        self.t_.get_setting('intensity_map').add_callback('set',
                                                          self.intensity_map_set_cb)
        self.t_.get_setting('color_array').add_callback('set',
                                                        self.color_array_set_cb)
        self.t_.get_setting('shift_array').add_callback('set',
                                                        self.shift_array_set_cb)
        self.t_.get_setting('color_hashsize').add_callback('set',
                                                           self.color_hashsize_set_cb)
        self.t_.get_setting('color_algorithm').add_callback('set',
                                                            self.color_algorithm_set_cb)

        # For color and intensity maps
        self.cmap = None
        self.imap = None
        self.arr = None
        self.iarr = None
        self.carr = None
        self.sarr = None
        self.scale_pct = 1.0

        # targeted bit depth per-pixel band of the output RGB array
        # (can be less than the data size of the output array)
        if bpp is None:
            bpp = 8
        self.bpp = bpp
        # maximum value that we can generate in this range
        self.maxc = int(2 ** self.bpp - 1)
        # data size per pixel band in the output RGB array
        self._set_dtype()

        # For scaling algorithms
        hashsize = self.t_.get('color_hashsize', 65536)
        if dist is None:
            color_alg_name = self.t_.get('color_algorithm', 'linear')
            color_dist_class = ColorDist.get_dist(color_alg_name)
            dist = color_dist_class(hashsize)
        self.dist = dist

        # For callbacks
        for name in ('changed', ):
            self.enable_callback(name)

        self.suppress_changed = self.suppress_callback('changed', 'last')

        carr = self.t_.get('color_array', None)
        sarr = self.t_.get('shift_array', None)

        cm_name = self.t_.get('color_map', 'gray')
        self.set_color_map(cm_name)

        im_name = self.t_.get('intensity_map', 'ramp')
        self.set_intensity_map(im_name)

        # Initialize color array
        if carr is not None:
            self.set_carr(carr)
        else:
            self.calc_cmap()

        # Initialize shift array
        if sarr is not None:
            self.set_sarr(sarr)
        else:
            self.reset_sarr(callback=False)
コード例 #9
0
ファイル: ginga_viewer.py プロジェクト: zonca/imexam
    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)
コード例 #10
0
ファイル: FitsImage.py プロジェクト: astrofrog/ginga
    def __init__(self, logger=None, rgbmap=None, settings=None):
        Callback.Callbacks.__init__(self)

        if logger != None:
            self.logger = logger
        else:
            self.logger = logging.Logger('FitsImageBase')

        # RGB mapper
        if rgbmap:
            self.rgbmap = rgbmap
        else:
            rgbmap = RGBMap.RGBMapper()
            self.rgbmap = rgbmap

        # Object that calculates auto cut levels
        self.autocuts = AutoCuts.AutoCuts(self.logger)

        # Dummy 1-pixel image
        self.image = AstroImage.AstroImage(numpy.zeros((1, 1)),
                                           logger=self.logger)
        # for debugging
        self.name = str(self)

        # Create settings and set defaults
        if settings == None:
            settings = Settings.SettingGroup(logger=self.logger)
        self.t_ = settings

        # for color mapping
        self.t_.addDefaults(color_map='ramp',
                            intensity_map='ramp',
                            color_algorithm='linear',
                            color_hashsize=65535)
        for name in ('color_map', 'intensity_map', 'color_algorithm',
                     'color_hashsize'):
            self.t_.getSetting(name).add_callback('set', self.cmap_changed_cb)

        # Initialize RGBMap
        cmap_name = self.t_.get('color_map', 'ramp')
        try:
            cm = cmap.get_cmap(cmap_name)
        except KeyError:
            cm = cmap.get_cmap('ramp')
        rgbmap.set_cmap(cm)
        imap_name = self.t_.get('intensity_map', 'ramp')
        try:
            im = imap.get_imap(imap_name)
        except KeyError:
            im = imap.get_imap('ramp')
        rgbmap.set_imap(im)
        hash_size = self.t_.get('color_hashsize', 65535)
        rgbmap.set_hash_size(hash_size)
        hash_alg = self.t_.get('color_algorithm', 'linear')
        rgbmap.set_hash_algorithm(hash_alg)

        rgbmap.add_callback('changed', self.rgbmap_cb)

        # for cut levels
        self.t_.addDefaults(locut=0.0, hicut=0.0)
        for name in ('locut', 'hicut'):
            self.t_.getSetting(name).add_callback('set', self.cut_levels_cb)

        # for auto cut levels
        self.autocuts_options = ('on', 'override', 'off')
        self.t_.addDefaults(
            autocuts='override',
            autocut_method='histogram',
            autocut_hist_pct=AutoCuts.default_autocuts_hist_pct,
            autocut_bins=AutoCuts.default_autocuts_bins)
        for name in ('autocuts', 'autocut_method', 'autocut_hist_pct',
                     'autocut_bins'):
            self.t_.getSetting(name).add_callback('set', self.auto_levels_cb)

        # for zooming
        self.t_.addDefaults(zoomlevel=1.0,
                            zoom_algorithm='step',
                            scale_x_base=1.0,
                            scale_y_base=1.0,
                            zoom_rate=math.sqrt(2.0))
        for name in ('zoom_rate', 'zoom_algorithm', 'scale_x_base',
                     'scale_y_base'):
            self.t_.getSetting(name).add_callback('set',
                                                  self.zoomalg_change_cb)

        # max/min scaling
        self.t_.addDefaults(scale_max=10000.0, scale_min=0.00001)

        # autozoom options
        self.autozoom_options = ('on', 'override', 'off')
        self.t_.addDefaults(autozoom='on')

        # for panning
        self.t_makebg = False
        self.t_.addDefaults(reverse_pan=False, autocenter=True)

        # for transforms
        self.t_.addDefaults(flip_x=False, flip_y=False, swap_xy=False)
        for name in ('flip_x', 'flip_y', 'swap_xy'):
            self.t_.getSetting(name).add_callback('set', self.transform_cb)

        # desired rotation angle
        self.t_.addDefaults(rot_deg=0.0)
        self.t_.getSetting('rot_deg').add_callback('set',
                                                   self.rotation_change_cb)

        # misc
        self.t_.addDefaults(use_embedded_profile=True, auto_orient=False)

        # PRIVATE IMPLEMENTATION STATE

        # image window width and height (see set_window_dimensions())
        self._imgwin_wd = 1
        self._imgwin_ht = 1
        self._imgwin_set = False
        # center (and reference) pixel in the screen image (in pixel coords)
        self._ctr_x = 1
        self._ctr_y = 1
        # data indexes at the reference pixel (in data coords)
        self._org_x = 0
        self._org_y = 0

        # pan position
        self._pan_x = 0.0
        self._pan_y = 0.0

        # Origin in the data array of what is currently displayed (LL, UR)
        self._org_x1 = 0
        self._org_y1 = 0
        self._org_x2 = 0
        self._org_y2 = 0
        # offsets in the screen image for drawing (in screen coords)
        self._dst_x = 0
        self._dst_y = 0
        self._invertY = True
        # offsets in the screen image (in data coords)
        self._off_x = 0
        self._off_y = 0

        # desired scale factors
        self._scale_x = 1.0
        self._scale_y = 1.0
        # actual scale factors produced from desired ones
        self._org_scale_x = 0
        self._org_scale_y = 0

        self._cutout = None
        self._rotimg = None
        self._prergb = None
        self._rgbarr = None

        self.orientMap = {
            # tag: (flip_x, flip_y, swap_xy)
            1: (False, True, False),
            2: (True, True, False),
            3: (True, False, False),
            4: (False, False, False),
            5: (True, False, True),
            6: (True, True, True),
            7: (False, True, True),
            8: (False, False, True),
        }

        # For callbacks
        # TODO: we should be able to deprecate a lot of these with the new
        # settings callbacks
        for name in ('cut-set', 'zoom-set', 'pan-set', 'transform', 'rotate',
                     'image-set', 'configure', 'autocuts', 'autozoom'):
            self.enable_callback(name)
コード例 #11
0
    mymon = Monitor.Monitor(myMonName, logger, numthreads=options.numthreads)

    threadPool = mymon.get_threadPool()

    sndsink = SoundSink.SoundSource(monitor=mymon,
                                    logger=logger,
                                    channels=['sound'])

    # Get settings folder
    if os.environ.has_key('CONFHOME'):
        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)

    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)

    model = Model.StatusModel(logger)

    # Start up the control/display engine
    statmon = StatMon(logger, threadPool, mm, prefs, sndsink, ev_quit, model)
コード例 #12
0
ファイル: ipg.py プロジェクト: rupak0577/ginga
def start(kapp):
    global app_ref

    if use_null_logger:
        logger = log.NullLogger()
    else:
        logger = logging.getLogger("ipg")
        logger.setLevel(logging.INFO)
        fmt = logging.Formatter(STD_FORMAT)
        stderrHdlr = logging.StreamHandler()
        stderrHdlr.setFormatter(fmt)
        logger.addHandler(stderrHdlr)
        fileHdlr = logging.FileHandler("ipg.log")
        fileHdlr.setFormatter(fmt)
        logger.addHandler(fileHdlr)
    kapp.logger = logger

    # 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.createCategory('general')
    settings.load(onError='silent')
    settings.setDefaults(useMatplotlibColormaps=False)
    bindprefs = prefs.createCategory('bindings')
    bindprefs.load(onError='silent')

    # 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)
    childDir = os.path.join(basedir, 'plugins')
    sys.path.insert(0, childDir)

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

        ipg_config.pre_gui_config(kapp)
    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))

    # create Qt app
    # Note: workaround for pyside bug where QApplication is not deleted
    app = QtGui.QApplication.instance()
    if not app:
        app = QtGui.QApplication([])
        app.connect(app, QtCore.SIGNAL('lastWindowClosed()'), app,
                    QtCore.SLOT('quit()'))

    # here is our little launcher
    w = StartMenu(logger, app, kapp, prefs)
    app_ref = w
    w.show()
    app.setActiveWindow(w)

    #app.exec_()
    # Very important, IPython-specific step: this gets GUI event loop
    # integration going, and it replaces calling app.exec_()
    kapp.start()
    return w
コード例 #13
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)
コード例 #14
0
    def __init__(self, logger=None, settings=None):
        Callback.Callbacks.__init__(self)

        if logger is not None:
            self.logger = logger
        else:
            self.logger = logging.Logger('PlotView')

        # Create settings and set defaults
        if settings is None:
            settings = Settings.SettingGroup(logger=self.logger)
        self.settings = settings
        self.settings.add_defaults(plot_bg='white', show_marker=False,
                                   linewidth=1, linestyle='-',
                                   linecolor='blue', markersize=6,
                                   markerwidth=0.5, markercolor='red',
                                   markerstyle='o', file_suffix='.png')

        # for debugging
        self.name = str(self)

        if not have_mpl:
            raise ImportError('Install matplotlib to use this plugin')

        top = Widgets.VBox()
        top.set_border_width(4)

        self.line_plot = plots.Plot(logger=self.logger,
                                    width=400, height=400)
        bg = self.settings.get('plot_bg', 'white')
        if plots.MPL_GE_2_0:
            kwargs = {'facecolor': bg}
        else:
            kwargs = {'axisbg': bg}
        self.line_plot.add_axis(**kwargs)
        self.plot_w = Plot.PlotWidget(self.line_plot)
        self.plot_w.resize(400, 400)

        # enable interactivity in the plot
        self.line_plot.connect_ui()
        self.line_plot.enable(zoom=True, pan=True)
        self.line_plot.add_callback('limits-set', self.limits_cb)

        ax = self.line_plot.ax
        ax.grid(True)

        top.add_widget(self.plot_w, stretch=1)

        captions = (('Log X', 'checkbutton', 'Log Y', 'checkbutton',
                     'Show Marker', 'checkbutton'),
                    ('X Low:', 'label', 'x_lo', 'entry',
                     'X High:', 'label', 'x_hi', 'entry',
                     'Reset X', 'button'),
                    ('Y Low:', 'label', 'y_lo', 'entry',
                     'Y High:', 'label', 'y_hi', 'entry',
                     'Reset Y', 'button'),
                    ('Save', 'button'))
        # for now...
        orientation = 'vertical'
        w, b = Widgets.build_info(captions, orientation=orientation)
        self.w = b

        top.add_widget(w, stretch=0)

        b.log_x.set_state(self.line_plot.logx)
        b.log_x.add_callback('activated', self.log_x_cb)
        b.log_x.set_tooltip('Plot X-axis in log scale')

        b.log_y.set_state(self.line_plot.logy)
        b.log_y.add_callback('activated', self.log_y_cb)
        b.log_y.set_tooltip('Plot Y-axis in log scale')

        b.x_lo.add_callback('activated', lambda w: self.set_xlim_cb())
        b.x_lo.set_tooltip('Set X lower limit')

        b.x_hi.add_callback('activated', lambda w: self.set_xlim_cb())
        b.x_hi.set_tooltip('Set X upper limit')

        b.y_lo.add_callback('activated', lambda w: self.set_ylim_cb())
        b.y_lo.set_tooltip('Set Y lower limit')

        b.y_hi.add_callback('activated', lambda w: self.set_ylim_cb())
        b.y_hi.set_tooltip('Set Y upper limit')

        b.reset_x.add_callback('activated', lambda w: self.reset_xlim_cb())
        b.reset_x.set_tooltip('Autoscale X limits')

        b.reset_y.add_callback('activated', lambda w: self.reset_ylim_cb())
        b.reset_y.set_tooltip('Autoscale Y limits')

        b.show_marker.set_state(self.settings.get('show_marker', False))
        b.show_marker.add_callback('activated', self.set_marker_cb)
        b.show_marker.set_tooltip('Mark data points')

        # Button to save plot
        self.save_plot = b.save
        self.save_plot.set_tooltip('Save table plot')
        self.save_plot.add_callback('activated', lambda w: self.save_cb())
        self.save_plot.set_enabled(False)

        self.widget = top

        # For callbacks
        for name in ['image-set']:
            self.enable_callback(name)