Example #1
0
def _main():
    """Run from command line."""
    if len(sys.argv) <= 1:
        print('USAGE: quip operation_file.xml [--mosaic-thumb-size=500] '
              '[--n-cores=8] [--nocopy] [--help]')
    elif '--help' in sys.argv:
        from ginga.rv.main import reference_viewer
        reference_viewer(['ginga', '--help'])
    elif '--version' in sys.argv:
        try:
            from ..version import version
        except ImportError:
            version = 'unknown'
        print(f'{__taskname__} v{version}')
    else:
        main(sys.argv[1:])
Example #2
0
def _main():
    """Run from command line."""
    if len(sys.argv) <= 1:
        print('USAGE: quip operation_file.xml [--mosaic-thumb-size=100] '
              '[--nocopy] [--help]')
    elif '--help' in sys.argv:
        from ginga.rv.main import reference_viewer
        reference_viewer(['ginga', '--help'])
    elif '--version' in sys.argv:
        try:
            from ..version import version
        except ImportError:
            version = 'unknown'
        print('{0} v{1}'.format(__taskname__, version))
    else:
        main(sys.argv[1:])
Example #3
0
def run_stginga(sys_argv):
    """Run this from command line.

    This does the following:

    * Set up custom STScI plugins.
    * Automatically starts necessary core Ginga global plugins.
    * 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 might see duplicates!

    """
    from .plugin_info import _get_stginga_plugins

    # 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
    stglobal_plugins, stlocal_plugins = _get_stginga_plugins()
    gmain.global_plugins += stglobal_plugins
    gmain.local_plugins += stlocal_plugins

    # Enforce Qt (--toolkit or -t) -- DISABLED
    # 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'

    # Auto start core global plugins
    for gplgname in ('ChangeHistory', ):
        gplg = _locate_plugin(gmain.global_plugins, gplgname)
        gplg.start = True

    # Start Ginga
    gmain.reference_viewer(sys_argv)
Example #4
0
def main(args):
    """Driver for command line script.

    First argument must be the QUIP Operation XML file.
    Other command line options are as accepted by Ginga, *except* for:

    * ``--mosaic-thumb-size`` can be used to specify desired width in pixels
      for individual images to be mosaicked in ``THUMBNAIL`` mode.
      If not given, the default width is 500 pixels. For Segment ID,
      the value is 256 regardless of this setting.
    * ``--n-cores`` can be used to specify the number of CPU cores used when
      rescaling images in ``THUMBNAIL`` mode. If not given, all available
      cores will be used.
    * ``--nocopy`` can be used with QUIP to instruct
      it to *not* copy its Ginga files to user's HOME directory.
    * ``--log=filename``, if given in command line, will be ignored
      because QUIP always writes Ginga's log to ``ginga.log`` in the
      output directory provided by QUIP Operation XML file.

    Parameters
    ----------
    args : list of str
        Command line arguments.

    Raises
    ------
    OSError
        Input XML does not exist.

    ValueError
        Input XML fails to validate built-in schema.
        Validation is skipped for Windows.

    """
    from stginga.gingawrapper import _locate_plugin
    global QUIP_DIRECTIVE, QUIP_LOG

    inputxml = args.pop(0)

    if not os.path.exists(inputxml):
        raise OSError(f'{inputxml} does not exist')

    # Validate input XML (compare return code and display stderr if fails).
    # Skipped for Windows because no xmllint.
    if not _iswin:
        schema_v = qio.validate_input_xml(inputxml)
        if schema_v[0] != 0:
            raise ValueError(schema_v[2])

    if '--nocopy' in args:
        nocopy = True
        args.pop(args.index('--nocopy'))
    else:
        nocopy = False

    # Copy Ginga files to HOME directory
    if not nocopy:
        copy_ginga_files()

    thumb_width = 500
    n_cores = None

    for i, a in enumerate(args):
        # Ignore any custom log file provided by user
        if a.startswith('--log='):
            args.pop(i)
        # Custom width for THUMBNAIL mode
        elif a.startswith('--mosaic-thumb-size='):
            args.pop(i)
            try:
                thumb_width = int(a.split('=')[1])
            except Exception:
                pass  # Use default
        # Num cores for THUMBNAIL mode
        elif a.startswith('--n-cores='):
            args.pop(i)
            try:
                n_cores = int(a.split('=')[1])
            except Exception:
                pass  # Use default

    # Extract info from input XML
    QUIP_DIRECTIVE = qio.input_xml(inputxml)
    gingalog = os.path.join(QUIP_DIRECTIVE['OUTPUT']['OUTPUT_DIRECTORY'],
                            'ginga.log')
    images = QUIP_DIRECTIVE['IMAGES']['IMAGE_PATH']
    op_type = QUIP_DIRECTIVE['OPERATION_TYPE'].lower()

    # Create hidden temporary directory, in case we need it later.
    # This is NOT automatically deleted.
    tempdir = os.path.join(os.path.dirname(os.path.abspath(inputxml)),
                           _tempdirname)
    if not os.path.exists(tempdir):
        os.mkdir(tempdir)

    # Initialize info for log XML.
    # Do this here for time stamp and avoid circular import.
    QUIP_LOG = qio.QUIPLog()

    # No point keeping Ginga log from last run
    if os.path.exists(gingalog):
        os.remove(gingalog)

    if op_type == 'thumbnail':
        cfgmode = 'mosaicmode'
        ginga_config_py_sfx = op_type
        sci_ext = ('SCI', 1)

        # Science array can have different EXTNAME values:
        #   SCI (JWST/HST) or IMAGE (test)
        # Assume first image is representative of all the rest.
        with fits.open(images[0]) as pf:
            if sci_ext not in pf:
                sci_ext = ('IMAGE', 1)

        # Auto guess the number of CPU cores needed.
        if n_cores is None:
            n_cores = min(multiprocessing.cpu_count(), len(images))

        if STGINGA_GT_1_2:
            shrink_extra_kwargs = {'sci_ext': sci_ext, 'use_dq': True}
        else:
            shrink_extra_kwargs = {'ext': sci_ext}

        images = shrink_input_images(images,
                                     new_width=thumb_width,
                                     n_cores=n_cores,
                                     outpath=tempdir,
                                     **shrink_extra_kwargs)

    elif op_type == 'segment_id':
        cfgmode = 'mosaicmode'
        ginga_config_py_sfx = op_type
        images = _segid_mosaics(images, outpath=tempdir, sw_sca_size=256)

    else:  # different kinds of analysis
        cfgmode = 'normalmode'
        ginga_config_py_sfx = cfgmode

    # Add custom plugins.
    # NOTE: There was a bug with setting this in ginga_config.py,
    #       so we do this here instead.
    global_plugins, local_plugins = get_ginga_plugins(ginga_config_py_sfx)
    gmain.plugins += global_plugins
    gmain.plugins += local_plugins

    # Set Ginga config file(s)
    set_ginga_config(mode=cfgmode, gcfg_suffix=ginga_config_py_sfx)

    # Auto start core global plugins
    for gplgname in ('ChangeHistory', ):
        gplg = _locate_plugin(gmain.plugins, gplgname)
        gplg.start = True

    # Start Ginga
    sys_args = ['ginga', f'--log={gingalog}'] + args + images
    gmain.reference_viewer(sys_args)
Example #5
0
def main(args):
    """Driver for command line script.

    First argument must be the QUIP Operation XML file.
    Other command line options are as accepted by Ginga, *except* for:

    * ``--mosaic-thumb-size`` can be used to specify desired width in pixels
      for individual images to be mosaicked in ``THUMBNAIL`` mode.
      If not given, the default width is 100 pixels.
    * ``--nocopy`` can be used with QUIP to instruct
      it to *not* copy its Ginga files to user's HOME directory.
    * ``--log=filename``, if given in command line, will be ignored
      because QUIP always writes Ginga's log to ``ginga.log`` in the
      output directory provided by QUIP Operation XML file.

    Parameters
    ----------
    args : list of str
        Command line arguments.

    Raises
    ------
    OSError
        Input XML does not exist.

    ValueError
        Input XML fails to validate built-in schema.
        Validation is skipped for Windows.

    """
    from stginga.gingawrapper import _locate_plugin
    global QUIP_DIRECTIVE, QUIP_LOG

    inputxml = args.pop(0)

    if not os.path.exists(inputxml):
        raise OSError('{0} does not exist'.format(inputxml))

    # Validate input XML (compare return code and display stderr if fails).
    # Skipped for Windows because no xmllint.
    if not _iswin:
        schema_v = qio.validate_input_xml(inputxml)
        if schema_v[0] != 0:
            raise ValueError(schema_v[2])

    if '--nocopy' in args:
        nocopy = True
        args.pop(args.index('--nocopy'))
    else:
        nocopy = False

    # Copy Ginga files to HOME directory
    if not nocopy:
        copy_ginga_files()

    thumb_width = 100

    for i, a in enumerate(args):
        # Ignore any custom log file provided by user
        if a.startswith('--log='):
            args.pop(i)
        # Custom width for THUMBNAIL mode
        elif a.startswith('--mosaic-thumb-size='):
            args.pop(i)
            try:
                thumb_width = int(a.split('=')[1])
            except Exception:
                pass  # Use default

    # Extract info from input XML
    QUIP_DIRECTIVE = qio.input_xml(inputxml)
    gingalog = os.path.join(
        QUIP_DIRECTIVE['OUTPUT']['OUTPUT_DIRECTORY'], 'ginga.log')
    images = QUIP_DIRECTIVE['IMAGES']['IMAGE_PATH']
    op_type = QUIP_DIRECTIVE['OPERATION_TYPE'].lower()

    # Create hidden temporary directory, in case we need it later.
    # This is NOT automatically deleted.
    tempdir = os.path.join(
        os.path.dirname(os.path.abspath(inputxml)), _tempdirname)
    if not os.path.exists(tempdir):
        os.mkdir(tempdir)

    # Initialize info for log XML.
    # Do this here for time stamp and avoid circular import.
    QUIP_LOG = qio.QUIPLog()

    # No point keeping Ginga log from last run
    if os.path.exists(gingalog):
        os.remove(gingalog)

    if op_type == 'thumbnail':
        cfgmode = 'mosaicmode'
        ginga_config_py_sfx = op_type

        # Science array can have different EXTNAME values.
        # Try SCI first (JWST/HST), then IMAGE (test).
        try:
            images = shrink_input_images(
                images, ext=('SCI', 1), new_width=thumb_width,
                outpath=tempdir)
        except KeyError:
            images = shrink_input_images(
                images, ext=('IMAGE', 1), new_width=thumb_width,
                outpath=tempdir)

    elif op_type == 'segment_id':
        cfgmode = 'mosaicmode'
        ginga_config_py_sfx = op_type
        images = _segid_mosaics(images, outpath=tempdir)

    else:  # different kinds of analysis
        cfgmode = 'normalmode'
        ginga_config_py_sfx = cfgmode

    # Add custom plugins.
    # NOTE: There was a bug with setting this in ginga_config.py,
    #       so we do this here instead.
    global_plugins, local_plugins = get_ginga_plugins(ginga_config_py_sfx)
    gmain.plugins += global_plugins
    gmain.plugins += local_plugins

    # Set Ginga config file(s)
    set_ginga_config(mode=cfgmode, gcfg_suffix=ginga_config_py_sfx)

    # Auto start core global plugins
    for gplgname in ('ChangeHistory', ):
        gplg = _locate_plugin(gmain.plugins, gplgname)
        gplg.start = True

    # Start Ginga
    sys_args = ['ginga', '--log={0}'.format(gingalog)] + args + images
    gmain.reference_viewer(sys_args)