def _get_stginga_plugins(): gpfx = 'stginga.plugins' # To load custom plugins in Ginga namespace global_plugins = [] local_plugins = [ Bunch(module='BackgroundSub', workspace='dialogs', pfx=gpfx, category='Custom', ptype='local'), Bunch(module='BadPixCorr', workspace='dialogs', pfx=gpfx, category='Custom', ptype='local'), Bunch(module='DQInspect', workspace='dialogs', pfx=gpfx, category='Custom', ptype='local'), Bunch(module='SNRCalc', workspace='dialogs', pfx=gpfx, category='Custom', ptype='local'), ] return global_plugins, local_plugins
def __init__(self, controller): super(ControlPanel, self).__init__(controller) self.input_dir = "inputs" self.weights_qf = None self.schedule_qf = None self.programs_qf = None self.ob_qf_dict = None self.tgtcfg_qf_dict = None self.envcfg_qf_dict = None self.inscfg_qf_dict = None self.telcfg_qf_dict = None self.ob_info = {} self.ob_list = [] self.qdb = None self.qa = None self.qq = None prefs = self.controller.get_preferences() self.settings = prefs.create_category('plugin_ControlPanel') self.settings.add_defaults(db_config_file='qdb.yml') self.settings.load(onError='silent') self.cfg_path = os.path.join(prefs.folder, self.settings.get('db_config_file')) self.spec_weights = Bunch(name='weightstab', module='WeightsTab', klass='WeightsTab', ptype='global', hidden=True, ws='report', tab='Weights', start=True) self.spec_schedule = Bunch(name='scheduletab', module='ScheduleTab', klass='ScheduleTab', ptype='global', hidden=True, ws='report', tab='Schedule', start=True) self.spec_programs = Bunch(name='programstab', module='ProgramsTab', klass='ProgramsTab', ptype='global', hidden=True, ws='report', tab='Programs', start=True)
def runginga(sys_argv): """Run this from command line. This does the following: * Set up custom STScI plugins. * Enforce Qt toolkit. * Pass command line arguments directly into Ginga. .. warning:: If the same plugin that is loaded here is also loaded via ``~/.ginga/ginga_config.py`` or command line, you will see duplicates! """ gpfx = 'ginga.qtw.plugins' # To load custom Qt plugins in Ginga namespace # Remove some Ginga default plugins. # Use this if we have custom plugins that replaces them. # Note: Unable to get this to work from within ginga_config.py # Example: # glb_plg_to_remove = ['WBrowser', 'RC', 'SAMP', 'IRAF'] glb_plg_to_remove = [] lcl_plg_to_remove = [] _remove_plugins(glb_plg_to_remove, gmain.global_plugins) _remove_plugins(lcl_plg_to_remove, gmain.local_plugins) # Add custom plugins. # If we use this, we do not have to use ginga_config.py global_plgs = [] local_plgs = [ Bunch(module='BackgroundSub', tab='BackgroundSub', ws='dialogs', pfx=gpfx), Bunch(module='DQInspect', tab='DQInspect', ws='dialogs', pfx=gpfx) ] gmain.global_plugins += global_plgs gmain.local_plugins += local_plgs # Enforce Qt (--toolkit or -t) new_argv = ['--toolkit=qt' if 'toolkit' in s else s for s in sys_argv] if '-t' in new_argv: new_argv[new_argv.index('-t') + 1] = 'qt' # Start Ginga gmain.reference_viewer(new_argv)
def get_schedule_data(self, time_start): # get the string for the date of observation in HST, which is what # is used in the Schedule tables if time_start.hour < 9: date_obs_local = (time_start - timedelta(hours=10)).strftime("%Y-%m-%d") else: date_obs_local = time_start.strftime("%Y-%m-%d") self.logger.info( "observation date (local) is '{}'".format(date_obs_local)) sdlr = self.model.get_scheduler() # find the record in the schedule table that matches our date; # we need to get the list of filters and so on from it rec = None for _rec in sdlr.schedule_recs: if _rec.date == date_obs_local: rec = _rec break if rec is None: errmsg = "Can't find a record in the Schedule table matching '{}'".format( date_obs_local) raise ValueError(errmsg) data = Bunch(rec.data) return data
def draw_start(self, canvas, event, data_x, data_y, viewer): if not self.candraw: return False self._draw_obj = None # get the drawing coordinate type (default 'data') crdtype = self.t_drawparams.get('coord', 'data') crdmap = viewer.get_coordmap(crdtype) x, y = crdmap.data_to(data_x, data_y) # create the drawing context self._draw_cxt = Bunch(start_x=x, start_y=y, points=[(x, y)], x=x, y=y, data_x=data_x, data_y=data_y, drawparams=self.t_drawparams, crdmap=crdmap, viewer=viewer, logger=self.logger) self._draw_update(data_x, data_y, self._draw_cxt) self.process_drawing() return True
def add_global_plugin(self, module_name, ws_name, path=None, klass=None, category='Global', tab_name=None, start_plugin=True, pfx=None): self.add_global_plugin_spec( Bunch(module=module_name, workspace=ws_name, tab=tab_name, path=path, klass=klass, category=category, start=start_plugin, pfx=pfx))
def draw_start(self, canvas, event, data_x, data_y, viewer): if not self.candraw: return False self._draw_obj = None self.clear_selected() # get the drawing coordinate type (default 'data') crdtype = self.t_drawparams.get('coord', 'data') crdmap = viewer.get_coordmap(crdtype) x, y = crdmap.data_to((data_x, data_y)) klass = self.dc.get(self.t_drawtype, None) # create the drawing context self._draw_cxt = Bunch(start_x=x, start_y=y, points=[(x, y)], x=x, y=y, data_x=data_x, data_y=data_y, drawparams=self.t_drawparams, crdmap=crdmap, viewer=viewer, draw_class=klass, logger=self.logger) self._draw_update(data_x, data_y, self._draw_cxt, force_update=True) return True
def add_local_plugin(self, module_name, ws_name, path=None, klass=None, pfx=None, category=None): """TO BE DEPRECATED--DO NOT USE. Use add_local_plugin_spec() instead. """ self.add_local_plugin_spec( Bunch(module=module_name, workspace=ws_name, category=category, path=path, klass=klass, pfx=pfx))
def more_clock_by_offset(self): location = self.location.get_text() time_offset = self.time_offset.get_value() sec_hour = 3600 timezone = Bunch(location=location, time_offset=time_offset * sec_hour) color = self.colors[self.color_index % len(self.colors)] self.color_index += 1 self.add_clock(timezone=timezone, color=color)
def add_draw_mode(self, name, **kwargs): try: bnch = self._mode_tbl[name] except KeyError: bnch = Bunch(name=name, **kwargs) self._mode_tbl[name] = bnch return bnch
def setup_myglobalplugin(): spec = Bunch(path=os.path.join(p_path, 'MyGlobalPlugin.py'), module='MyGlobalPlugin', klass='MyGlobalPlugin', tab='My Global', workspace='right', start=False) return spec
def setup_mylocalplugin(): spec = Bunch(path=os.path.join(p_path, 'MyLocalPlugin.py'), module='MyLocalPlugin', klass='MyLocalPlugin', ptype='local', workspace='dialogs', category="Analysis", menu="My Local", tab='My Local') return spec
def setup_XPOSE(): spec = Bunch(path=os.path.join(p_path, 'XPOSE.py'), module='XPOSE', klass='XPOSE', ptype='local', workspace='dialogs', category="Keck", menu="XPOSE", tab='XPOSE') return spec
def schedule_db(self): weights = Bunch( dict(w_delay=5.0, w_filterchange=0.3, w_slew=0.2, w_rank=0.3, w_priority=0.1)) # data should be shared by all schedule elements, I believe data = Bunch( dict(seeing=0.5, transparency=0.9, filters=['g', 'r', 'i', 'z', 'y', 'sh'], instruments=['HSC'], dome='open', categories=['open'])) schedule = [ Bunch( dict(date='2016-03-07', starttime='19:42:00', stoptime='05:23:00', data=data, note='')), ] # open the queue database db = q_db.QueueDatabase(self.logger, self.addr) qa = q_db.QueueAdapter(db) sdlr = self.model.get_scheduler() # these two read not from db sdlr.set_weights(weights) sdlr.set_schedule_info(schedule) programs = qa.get_table('program') sdlr.set_programs_info(programs) ob_tbl = qa.get_table('ob') oblist = ob_tbl.values() sdlr.set_oblist_info(oblist) sdlr.schedule_all()
def add_global_plugin(self, module_name, ws_name, path=None, klass=None, category='Global', tab_name=None, start_plugin=True, pfx=None): """TO BE DEPRECATED--DO NOT USE. Use add_global_plugin_spec() instead. """ self.add_global_plugin_spec( Bunch(module=module_name, workspace=ws_name, tab=tab_name, path=path, klass=klass, category=category, start=start_plugin, pfx=pfx))
def setup_myglobalplugin(): spec = Bunch(path=os.path.join(p_path, 'MyGlobalPlugin.py'), module='MyGlobalPlugin', klass='MyGlobalPlugin', ptype='global', workspace='right', start=False, category="Analysis", menu="My Global", tab='My Global') return spec
def add_local_plugin(self, module_name, ws_name, path=None, klass=None, pfx=None): self.local_plugins.append( Bunch(module=module_name, ws=ws_name, path=path, klass=klass, pfx=pfx))
def add_global_plugin(self, module_name, ws_name, tab_name=None, start_plugin=True): if tab_name == None: tab_name = module_name self.global_plugins.append( Bunch(module=module_name, ws=ws_name, tab=tab_name, start=start_plugin))
def __init__(self, controller): super(Builder, self).__init__(controller) self.show_bad = False self.slot = None self.stobj = None self.w = Bunch() prefs = self.controller.get_preferences() self.settings = prefs.create_category('plugin_Builder') self.settings.add_defaults(gen2_status_host='localhost', gen2_status_user=None, gen2_status_pass=None) self.settings.load(onError='silent')
def __init__(self, controller): super(ControlPanel, self).__init__(controller) self.input_dir = "inputs" self.weights_qf = None self.schedule_qf = None self.programs_qf = None self.ob_qf_dict = None self.tgtcfg_qf_dict = None self.envcfg_qf_dict = None self.inscfg_qf_dict = None self.telcfg_qf_dict = None self.qdb = None self.qa = None self.qq = None self.spec_weights = Bunch(name='weightstab', module='WeightsTab', klass='WeightsTab', ws='report', tab='Weights', start=True) self.spec_schedule = Bunch(name='scheduletab', module='ScheduleTab', klass='ScheduleTab', ws='report', tab='Schedule', start=True) self.spec_programs = Bunch(name='programstab', module='ProgramsTab', klass='ProgramsTab', ws='report', tab='Programs', start=True)
def add_local_plugin(self, module_name, ws_name, path=None, klass=None, pfx=None, category=None): self.add_plugin_spec( Bunch(module=module_name, workspace=ws_name, category=category, ptype='local', path=path, klass=klass, pfx=pfx))
def get_do_not_execute_ob_info(self, proplst): """ Get the keys for OBs that should not be executed because they are either FQA==good or have an IQA==good/marginal. `proplst` gives a set of proposals for which we want info. """ # Locate the executed_ob table tbl = self._qa.get_db_native_table('executed_ob') recs = tbl.find( { '$and': [{ 'ob_key.0': { '$in': proplst } }, { '$or': [{ 'fqa': 'good' }, { '$and': [{ 'fqa': '' }, { 'iqa': { '$in': ['good', 'marginal'] } }] }] }] }, {'ob_key': 1}) # Painful reconstruction of time already accumulated running the # programs for executed OBs. Needed to inform scheduler so that # it can correctly calculate when to stop allocating OBs for a # program that has reached its time limit. dne_obs = [] props = {} for rec in recs: ob_key = tuple(rec['ob_key']) dne_obs.append(ob_key) proposal = ob_key[0] ob = self.get_ob(ob_key) bnch = props.setdefault(proposal, Bunch(obcount=0, sched_time=0.0)) bnch.sched_time += ob.acct_time bnch.obcount += 1 return dne_obs, props
def get_do_not_execute_ob_info(self, proplst): """ Get the keys for OBs that should not be executed because they are either FQA==good or have an IQA==good/marginal. `proplst` gives a set of proposals for which we want info. """ # Locate the executed_ob table tbl = self._qa.get_db_native_table('executed_ob') recs = tbl.find( { '$and': [{ 'ob_key.0': { '$in': proplst } }, { '$or': [{ 'fqa': 'good' }, { '$and': [{ 'fqa': '' }, { 'iqa': { '$in': ['good', 'marginal'] } }] }] }] }, {'ob_key': 1}) # Painful reconstruction of time already accumulated running the # programs for executed OBs. Needed to inform scheduler so that # it can correctly calculate when to stop allocating OBs for a # program that has reached its time limit. dne_ob_keys = [tuple(rec['ob_key']) for rec in recs] props = {} ob_recs = self._ob_keys_to_obs(dne_ob_keys) for rec in ob_recs: proposal = rec['program'] bnch = props.setdefault(proposal, Bunch(obcount=0, sched_time=0.0)) # 2021-01-11 EJ # Added extra overhead charge bnch.sched_time += (rec['acct_time'] * common.extra_overhead_factor) bnch.obcount += 1 return dne_ob_keys, props
def createTab(self): # If we have already created (and possibly closed) this # proposal tab before, just reload it. Otherwise, we have to # create it from scratch. proposal = self.model.proposalForPropTab self.logger.info('Creating tab for proposal %s' % proposal) if self.view.gpmon.has_plugin(proposal): self.view.reload_plugin(proposal) else: spec = Bunch(module='ProposalTab', klass='ProposalTab', ws='report', tab=proposal, name=proposal, start=False, ptype='global', hidden=True) self.view.load_plugin(proposal, spec) self.view.start_plugin(proposal) # Raise the tab we just created self.view.ds.raise_tab(proposal)
def add_global_plugin(self, module_name, ws_name, path=None, klass=None, tab_name=None, start_plugin=True, pfx=None): if tab_name is None: tab_name = module_name self.global_plugins.append( Bunch(module=module_name, ws=ws_name, tab=tab_name, path=path, klass=klass, start=start_plugin, pfx=pfx))
def _get_stginga_plugins(): # TODO: When we use stable Ginga release, not the dev, we can remove this # and just have version check in setup.py if ginga_version < '2.5.20160222004742': warnings.warn('Your Ginga version {0} is old, stginga might not work ' 'properly'.format(ginga_version), AstropyUserWarning) gpfx = 'stginga.plugins' # To load custom plugins in Ginga namespace global_plugins = [] local_plugins = [ Bunch(module='MultiImage', ws='dialogs', pfx=gpfx), Bunch(module='MIPick', ws='dialogs', pfx=gpfx), Bunch(module='BackgroundSub', ws='dialogs', pfx=gpfx), Bunch(module='BadPixCorr', ws='dialogs', pfx=gpfx), Bunch(module='DQInspect', ws='dialogs', pfx=gpfx), Bunch(module='SNRCalc', ws='dialogs', pfx=gpfx), ] return global_plugins, local_plugins
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)
stretch=1), dict(row=[ 'ws', dict(name='toolbar', wstype='stack', height=40, group=2) ], stretch=0), dict(row=['hbox', dict(name='status')], stretch=0), ] ] plugins = [ # hidden plugins, started at program initialization Bunch(module='Operations', workspace='operations', start=True, hidden=True, category='System', menu="Operations [G]", ptype='global'), Bunch(module='Toolbar', workspace='toolbar', start=True, hidden=True, category='System', menu="Toolbar [G]", ptype='global'), Bunch(module='Pan', workspace='uleft', start=True, hidden=True, category='System',
def get_ginga_plugins(op_type): """Obtain relevant custom plugins from ``stginga`` and ``wss_tools`` for the given QUIP operation type. Parameters ---------- op_type : {'normalmode', 'segment_id', 'thumbnail'} QUIP operation type. Normal mode covers anything that is neither SEGMENT_ID nor THUMBNAIL. Returns ------- global_plugins : list List of custom Ginga global plugins to load. local_plugins : list List of custom Ginga local plugins to load. """ stg_pfx = 'stginga.plugins' wss_pfx = 'wss_tools.quip.plugins' global_plugins = [ Bunch(module='AboutQUIP', tab='AboutQUIP', workspace='left', category='Custom', ptype='global', pfx=wss_pfx) ] if op_type == 'segment_id': local_plugins = [] # Add special plugin for segment ID annotations global_plugins += [ Bunch(module='SegIDHelper', tab='SegIDHelper', workspace='left', category='Custom', ptype='global', pfx=wss_pfx) ] elif op_type == 'thumbnail': local_plugins = [ Bunch(module='MosaicAuto', workspace='dialogs', category='Custom', ptype='local', pfx=wss_pfx) ] else: # normalmode global_plugins += [ Bunch(module='SaveQUIP', tab='SaveQUIP', workspace='right', category='Custom', ptype='global', pfx=wss_pfx) ] local_plugins = [ Bunch(module='BackgroundSub', workspace='dialogs', category='Custom', ptype='local', pfx=stg_pfx), Bunch(module='BadPixCorr', workspace='dialogs', category='Custom', ptype='local', pfx=stg_pfx), Bunch(module='DQInspect', workspace='dialogs', category='Custom', ptype='local', pfx=stg_pfx), Bunch(module='SNRCalc', workspace='dialogs', category='Custom', ptype='local', pfx=wss_pfx) ] return global_plugins, local_plugins
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)