예제 #1
0
def test_minversion():
    from types import ModuleType
    test_module = ModuleType(str("test_module"))
    test_module.__version__ = '0.12.2'
    good_versions = ['0.12', '0.12.1', '0.12.0.dev', '0.12dev']
    bad_versions = ['1', '1.2rc1']
    for version in good_versions:
        assert minversion(test_module, version)
    for version in bad_versions:
        assert not minversion(test_module, version)
예제 #2
0
def test_minversion():
    from types import ModuleType
    test_module = ModuleType(str("test_module"))
    test_module.__version__ = '0.12.2'
    good_versions = ['0.12', '0.12.1', '0.12.0.dev', '0.12dev']
    bad_versions = ['1', '1.2rc1']
    for version in good_versions:
        assert minversion(test_module, version)
    for version in bad_versions:
        assert not minversion(test_module, version)
예제 #3
0
    def _write_mosaic(self, key, outfile):
        """Write out mosaic data (or any new data generated within Ginga)
        to single-extension FITS.

        """
        maxsize = self.settings.get('max_mosaic_size', 1e8)  # Default 10k x 10k
        channel = self.fv.get_channel(self.chname)
        image = channel.datasrc[key]

        # Prevent writing very large mosaic
        if (image.width * image.height) > maxsize:
            s = 'Mosaic too large to be written {0}'.format(image.shape)
            self.w.status.set_text(s)
            self.logger.error(s)
            return

        # Insert mosaic data and header into output HDU
        hdu = fits.PrimaryHDU(image.get_data())
        self._write_header(image, hdu)

        # Write history to PRIMARY
        self._write_history(key, hdu)

        # Write to file
        if minversion(astropy, '1.3'):
            hdu.writeto(outfile, overwrite=True)
        else:
            hdu.writeto(outfile, clobber=True)
예제 #4
0
        def _mosaic_one(rootname):
            imlist = root_list[rootname]
            outname = os.path.join(outpath, f'{rootname}_{outsuffix}.fits')

            # Avoid regenerating mosaic if already exist.
            # This also avoids crashing at the very end.
            if not clobber and os.path.exists(outname):
                if debug:
                    print(f'Using existing {outname}')
                return outname

            mosaic = self.get_single_mosaic_array(imlist)
            if mosaic is None:
                if debug:
                    print(f'No mosaic for {imlist}')
                return ''

            hdu = fits.PrimaryHDU(mosaic)

            # Inherit some keywords from primary header from 1st image in list
            prihdr = fits.getheader(imlist[0])
            for key in ('ROOTNAME', 'TARGNAME', 'INSTRUME', 'FILTER', 'PUPIL',
                        'DATE-OBS', 'TIME-OBS'):
                if key not in prihdr:
                    continue
                hdu.header[key] = prihdr[key]

            hdu.header.add_history(f"Mosaic from {','.join(imlist)}")
            if minversion(astropy, '1.3'):
                hdu.writeto(outname, overwrite=clobber)
            else:
                hdu.writeto(outname, clobber=clobber)
            return outname
예제 #5
0
    def write_corrected(self, output, clobber=False):
        """Write out the destriped data."""

        # un-apply the flatfield if necessary
        if self.flatcorr != 'COMPLETE':
            self.science = self.science / self.invflat
            self.err = self.err / self.invflat

        # un-apply the post-flash if necessary
        if self.flshcorr != 'COMPLETE':
            self.science = self.science + self.flash

        # un-apply the dark if necessary
        if self.darkcorr != 'COMPLETE':
            self.science = self.science + self.dark

        # reverse the amp merge
        if (self.ampstring == 'ABCD'):
            tmp_1, tmp_2 = np.split(self.science, 2, axis=1)
            self.hdulist['sci', 1].data = tmp_1.copy()
            self.hdulist['sci', 2].data = tmp_2[::-1, :].copy()

            tmp_1, tmp_2 = np.split(self.err, 2, axis=1)
            self.hdulist['err', 1].data = tmp_1.copy()
            self.hdulist['err', 2].data = tmp_2[::-1, :].copy()
        else:
            self.hdulist['sci', 1].data = self.science.copy()
            self.hdulist['err', 1].data = self.err.copy()

        # Write the output
        if minversion(astropy, '1.3'):
            self.hdulist.writeto(output, overwrite=clobber)
        else:
            self.hdulist.writeto(output, clobber=clobber)
예제 #6
0
    def _write_mosaic(self, key, outfile):
        """Write out mosaic data (or any new data generated within Ginga)
        to single-extension FITS.

        """
        maxsize = self.settings.get('max_mosaic_size',
                                    1e8)  # Default 10k x 10k
        channel = self.fv.get_channel(self.chname)
        image = channel.datasrc[key]

        # Prevent writing very large mosaic
        if (image.width * image.height) > maxsize:
            s = 'Mosaic too large to be written {0}'.format(image.shape)
            self.w.status.set_text(s)
            self.logger.error(s)
            return

        # Insert mosaic data and header into output HDU
        hdu = fits.PrimaryHDU(image.get_data())
        self._write_header(image, hdu)

        # Write history to PRIMARY
        self._write_history(key, hdu)

        # Write to file
        if minversion(astropy, '1.3'):
            hdu.writeto(outfile, overwrite=True)
        else:
            hdu.writeto(outfile, clobber=True)
예제 #7
0
    def set_plot_axes(self):
        data = self.data()[0]
        # Set axes labels for the spectrum viewer

        if not minversion(astropy, '4.3'):
            spectral_axis_unit_type = data.spectral_axis.unit.physical_type.title(
            )
        else:
            # physical_type changed from str to class in astropy 4.3
            spectral_axis_unit_type = str(
                data.spectral_axis.unit.physical_type).title()
        # flux_unit_type = data.flux.unit.physical_type.title()
        flux_unit_type = "Flux density"

        if data.spectral_axis.unit.is_equivalent(u.m):
            spectral_axis_unit_type = "Wavelength"
        elif data.spectral_axis.unit.is_equivalent(u.pixel):
            spectral_axis_unit_type = "pixel"

        label_0 = f"{spectral_axis_unit_type} [{data.spectral_axis.unit.to_string()}]"
        self.figure.axes[0].label = label_0
        self.figure.axes[
            1].label = f"{flux_unit_type} [{data.flux.unit.to_string()}]"

        # Make it so y axis label is not covering tick numbers.
        self.figure.axes[1].label_offset = "-50"

        # Set Y-axis to scientific notation
        self.figure.axes[1].tick_format = '0.1e'
예제 #8
0
    def write_corrected(self, output, clobber=False):
        """Write out the destriped data."""

        # un-apply the flatfield if necessary
        if self.flatcorr != 'COMPLETE':
            self.science = self.science / self.invflat
            self.err = self.err / self.invflat

        # un-apply the post-flash if necessary
        if self.flshcorr != 'COMPLETE':
            self.science = self.science + self.flash

        # un-apply the dark if necessary
        if self.darkcorr != 'COMPLETE':
            self.science = self.science + self.dark

        # reverse the amp merge
        if (self.ampstring == 'ABCD'):
            tmp_1, tmp_2 = np.split(self.science, 2, axis=1)
            self.hdulist['sci', 1].data = tmp_1.copy()
            self.hdulist['sci', 2].data = tmp_2[::-1, :].copy()

            tmp_1, tmp_2 = np.split(self.err, 2, axis=1)
            self.hdulist['err', 1].data = tmp_1.copy()
            self.hdulist['err', 2].data = tmp_2[::-1, :].copy()
        else:
            self.hdulist['sci', 1].data = self.science.copy()
            self.hdulist['err', 1].data = self.err.copy()

        # Write the output
        if minversion(astropy, '1.3'):
            self.hdulist.writeto(output, overwrite=clobber)
        else:
            self.hdulist.writeto(output, clobber=clobber)
예제 #9
0
def setup_module():
    """Create objects once and re-use throughout this module."""
    global img_dict

    if minversion(astropy, '3.1'):
        USE_APE14 = True
    else:
        USE_APE14 = False

    img_dict = {}
    for modname in _wcsmods:
        if modname == 'astropy_ape14' and not USE_APE14:
            continue
        if not wcsmod.use(modname, raise_err=False):
            continue
        img_dict[modname] = {}
        for dim in _hdr.keys():
            w = wcsmod.WCS(_logger)
            with warnings.catch_warnings():
                warnings.simplefilter("ignore")
                w.load_header(_hdr[dim])
            img = AstroImage.AstroImage(logger=_logger)
            img.wcs = w
            if dim == '2d':
                img.revnaxis = []
                img.naxispath = []
            else:  # 3d
                img.revnaxis = [0]
                img.naxispath = [0]
            img_dict[modname][dim] = img
예제 #10
0
 def compare(cls, reference_file, test_file, atol=None, rtol=None):
     import astropy
     from astropy.io.fits.diff import FITSDiff
     from astropy.utils.introspection import minversion
     if minversion(astropy, '2.0'):
         diff = FITSDiff(reference_file, test_file, rtol=rtol)
     else:
         diff = FITSDiff(reference_file, test_file, tolerance=rtol)
     return diff.identical, diff.report()
예제 #11
0
 def compare(cls, reference_file, test_file, atol=None, rtol=None):
     import astropy
     from astropy.io.fits.diff import FITSDiff
     from astropy.utils.introspection import minversion
     if minversion(astropy, '2.0'):
         diff = FITSDiff(reference_file, test_file, rtol=rtol)
     else:
         diff = FITSDiff(reference_file, test_file, tolerance=rtol)
     return diff.identical, diff.report()
예제 #12
0
def test_minversion():
    import numpy
    good_versions = ['1.16', '1.16.1', '1.16.0.dev', '1.16dev']
    bad_versions = ['100000', '100000.2rc1']
    for version in good_versions:
        assert minversion(numpy, version)
        assert minversion("numpy", version)
    for version in bad_versions:
        assert not minversion(numpy, version)
        assert not minversion("numpy", version)

    assert minversion(yaml, '3.1')
    assert minversion('yaml', '3.1')
예제 #13
0
# -*- coding: utf-8 -*-
"""
Readers, Writers, and I/O Miscellany.
"""

__all__ = ["file_reader", "file_writer"]  # from `mypackage`

# e.g. a file reader and writer for ``myformat``
# this will be used in ``astropy_io.py``
from .core import file_reader, file_writer

# Register read and write methods into Astropy:
# determine if it is 1) installed and 2) the correct version (v5.0+)
try:
    from astropy.utils.introspection import minversion
except ImportError:
    ASTROPY_GE_5 = False
else:
    ASTROPY_GE_5 = minversion("astropy", "5.0")

if ASTROPY_GE_5:
    # Astropy is installed and v5.0+ so we import the following modules
    # to register "myformat" with Cosmology read/write and "mypackage"
    # with Cosmology to/from_format.
    from . import astropy_convert, astropy_io
예제 #14
0
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Module to handle backward-compatibility."""

import astropy
from astropy.utils.introspection import minversion

try:
    import specutils  # noqa
except ImportError:
    HAS_SPECUTILS = False
else:
    HAS_SPECUTILS = True

try:
    import dust_extinction  # noqa
except ImportError:
    HAS_DUST_EXTINCTION = False
else:
    HAS_DUST_EXTINCTION = True


__all__ = ['ASTROPY_LT_4_1', 'ASTROPY_LT_4_0', 'HAS_SPECUTILS',
           'HAS_DUST_EXTINCTION']

ASTROPY_LT_4_1 = not minversion(astropy, '4.1')
ASTROPY_LT_4_0 = not minversion(astropy, '4.0')
예제 #15
0
from astropy.utils.introspection import minversion
from astropy.wcs import NoConvergence
from astropy.wcs.wcsapi import BaseHighLevelWCS
from echo import delay_callback
from glue.config import colormaps
from glue.core import BaseData, Data
from glue.core.link_helpers import LinkSame
from glue.core.subset import Subset, MaskSubsetState
from glue.plugins.wcs_autolinking.wcs_autolinking import WCSLink, NoAffineApproximation

from jdaviz.core.events import SnackbarMessage
from jdaviz.core.helpers import ConfigHelper

__all__ = ['Imviz']

ASTROPY_LT_4_3 = not minversion('astropy', '4.3')
RESERVED_MARKER_SET_NAMES = ['all']


class Imviz(ConfigHelper):
    """Imviz Helper class"""
    _default_configuration = 'imviz'

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # Markers
        self._marktags = set()
        self._default_mark_tag_name = 'default-marker-name'
        # marker shape not settable: https://github.com/glue-viz/glue/issues/2202
        self.marker = {'color': 'red', 'alpha': 1.0, 'markersize': 5}
예제 #16
0
from astropy.stats import biweight_midvariance, sigma_clipped_stats
from astropy.utils.exceptions import AstropyUserWarning

# OPTIONAL
try:
    import skimage
    from astropy.utils.introspection import minversion
    from scipy import stats
    from skimage import transform
    from skimage import morphology as morph
    from skimage import exposure
    from skimage.feature import canny
except ImportError:
    HAS_OPDEP = False
else:
    if minversion(skimage, '0.11'):
        HAS_OPDEP = True
    else:
        HAS_OPDEP = False

try:
    import matplotlib.pyplot as plt
except ImportError:
    plt = None
    warnings.warn('matplotlib not found, plotting is disabled',
                  AstropyUserWarning)

__version__ = '0.3.2'
__vdate__ = '24-May-2016'
__author__ = 'David Borncamp, Pey Lian Lim'
__all__ = ['detsat', 'make_mask', 'update_dq']
예제 #17
0
파일: satdet.py 프로젝트: jryon/acstools
import time
import warnings
from functools import partial
from multiprocessing import Process, Queue

# THIRD PARTY
import astropy
import numpy as np
from astropy.io import fits
# from astropy.stats import biweight_location
from astropy.stats import sigma_clipped_stats
from astropy.utils.exceptions import AstropyUserWarning
from astropy.utils.introspection import minversion

# See https://github.com/astropy/astropy/issues/6364
if minversion(astropy, '2.0'):
    from astropy.stats import biweight_scale
    biweight_midvariance = partial(biweight_scale, modify_sample_size=False)
else:
    from astropy.stats import biweight_midvariance

# OPTIONAL
try:
    import skimage
    from scipy import stats
    from skimage import transform
    from skimage import morphology as morph
    from skimage import exposure
    from skimage.feature import canny
except ImportError:
    HAS_OPDEP = False
예제 #18
0
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Module to handle backward-compatibility."""

import astropy
from astropy.utils.introspection import minversion

__all__ = ['ASTROPY_LT_2_0']

ASTROPY_LT_2_0 = not minversion(astropy, '2.0')
예제 #19
0
import re
import shutil
import sys
import time
from difflib import unified_diff
from io import StringIO

try:
    from astropy.io import fits
    from astropy.io.fits import FITSDiff, HDUDiff
    from astropy.utils.introspection import minversion
    HAS_ASTROPY = True
except ImportError:
    HAS_ASTROPY = False

if HAS_ASTROPY and minversion('astropy', '3.1'):
    ASTROPY_LT_3_1 = False
else:
    ASTROPY_LT_3_1 = True

__all__ = ['BigdataError', 'check_url', 'get_bigdata_root', 'get_bigdata',
           'compare_outputs', 'generate_upload_params',
           'generate_upload_schema']

RE_URL = re.compile(r"\w+://\S+")

UPLOAD_SCHEMA = {"files": [
                    {"pattern": "",
                     "target": "",
                     "props": None,
                     "recursive": "false",
예제 #20
0
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Tests for `astroquery.vo_conesearch.validator.inspect`."""

# STDLIB
import os

# ASTROPY
import astropy
from astropy.utils.data import get_pkg_data_filename
from astropy.utils.introspection import minversion

ASTROPY_LT_4_3 = not minversion(astropy, '4.3')

if ASTROPY_LT_4_3:
    from astropy.utils.data import _find_pkg_data_path as get_pkg_data_path
else:
    from astropy.utils.data import get_pkg_data_path

# LOCAL
from .. import inspect
from ... import conf as cs_conf

__doctest_skip__ = ['*']


class TestConeSearchResults:
    """Inspection of ``TestConeSearchValidation`` results."""
    def setup_class(self):
        self.datadir = 'data'
        test_vos_path = get_pkg_data_path(self.datadir) + os.sep
예제 #21
0
# -*- coding: utf-8 -*-
"""
Readers, Writers, and I/O Miscellany.
"""

__all__ = ["file_reader", "file_writer"]  # from `mypackage`

# e.g. a file reader and writer for ``myformat``
# this will be used in ``astropy_io.py``
from .core import file_reader, file_writer

# Register read and write methods into Astropy:
# determine if it is 1) installed and 2) the correct version (v5.0+)
try:
    import astropy
    from astropy.utils.introspection import minversion
except ImportError:
    ASTROPY_GE_5 = False
else:
    ASTROPY_GE_5 = minversion(astropy, "5.0")

if ASTROPY_GE_5:
    # Astropy is installed and v5.0+ so we import the following modules
    # to register "myformat" with Cosmology read/write and "mypackage"
    # with Cosmology to/from_format.
    from . import astropy_convert, astropy_io  # noqa: F401, F403
예제 #22
0
파일: plots.py 프로젝트: mwcraig/ginga
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
#
import numpy
from astropy.utils.introspection import minversion

import matplotlib as mpl
from matplotlib.figure import Figure

from ginga.util import iqcalc
from ginga.misc import Callback

# fix issue of negative numbers rendering incorrectly with default font
mpl.rcParams['axes.unicode_minus'] = False

MPL_GE_2_0 = minversion(mpl, '2.0')


class Plot(Callback.Callbacks):

    def __init__(self, figure=None, logger=None, width=500, height=500):
        Callback.Callbacks.__init__(self)

        if figure is None:
            figure = Figure()
            dpi = figure.get_dpi()
            if dpi is None or dpi < 0.1:
                dpi = 100
            wd_in, ht_in = float(width)/dpi, float(height)/dpi
            figure.set_size_inches(wd_in, ht_in)
        self.fig = figure
예제 #23
0
    def open_file(self, filespec, memmap=None, **kwargs):

        info = iohelper.get_fileinfo(filespec)
        if not info.ondisk:
            raise FITSError("File does not appear to be on disk: %s" %
                            (info.url))

        self.fileinfo = info
        filepath = info.filepath

        self.logger.debug("Loading file '%s' ..." % (filepath))
        fits_f = pyfits.open(filepath, 'readonly', memmap=memmap)
        self.fits_f = fits_f

        # this seems to be necessary now for some fits files...
        try:
            fits_f.verify('fix')

        except Exception as e:
            # Let's hope for the best!
            self.logger.warn("Problem verifying fits file '%s': %s" %
                             (filepath, str(e)))

        try:
            # this can fail for certain FITS files, with a "name undefined"
            # error bubbling up from astropy
            _hduinfo = fits_f.info(output=False)

        except Exception as e:
            # if so, this insures that name will be translated into the
            # HDU index below
            _hduinfo = tuple((None, '') for i in range(len(fits_f)))

        idx = 0
        extver_db = {}
        self.hdu_info = []
        self.hdu_db = {}

        for tup in _hduinfo:
            name = tup[1]
            # figure out the EXTVER for this HDU
            extver = extver_db.setdefault(name, 0)
            extver += 1
            extver_db[name] = extver

            # prepare a record of pertinent info about the HDU for
            # lookups by numerical index or (NAME, EXTVER)
            d = Bunch.Bunch(index=idx, name=name, extver=extver)
            if len(tup) > 5:
                import astropy
                from astropy.utils.introspection import minversion
                if minversion(astropy, '2.0'):
                    d.setvals(htype=tup[3], dtype=tup[6])
                else:
                    d.setvals(htype=tup[2], dtype=tup[5])
            self.hdu_info.append(d)
            # different ways of accessing this HDU:
            # by numerical index
            self.hdu_db[idx] = d
            # by (hduname, extver)
            self.hdu_db[(name, extver)] = d
            idx += 1

        self.extver_db = extver_db
예제 #24
0
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Module to handle backward-compatibility."""

import astropy
from astropy.utils.introspection import minversion

__all__ = ['ASTROPY_LT_2_0', 'ASTROPY_LT_4_0']

ASTROPY_LT_2_0 = not minversion(astropy, '2.0')
ASTROPY_LT_4_0 = not minversion(astropy, '4.0')
예제 #25
0
파일: satdet.py 프로젝트: pllim/acstools
# See https://github.com/astropy/astropy/issues/6364
from astropy.stats import biweight_scale
biweight_midvariance = partial(biweight_scale, modify_sample_size=False)

# OPTIONAL
try:
    import skimage
    from scipy import stats
    from skimage import transform
    from skimage import morphology as morph
    from skimage import exposure
    from skimage.feature import canny
except ImportError:
    HAS_OPDEP = False
else:
    if minversion(skimage, '0.11'):
        HAS_OPDEP = True
    else:
        HAS_OPDEP = False

try:
    import matplotlib.pyplot as plt
except ImportError:
    plt = None
    warnings.warn('matplotlib not found, plotting is disabled',
                  AstropyUserWarning)

__version__ = '0.3.3'
__vdate__ = '11-Jul-2017'
__author__ = 'David Borncamp, Pey Lian Lim'
__all__ = ['detsat', 'make_mask', 'update_dq']
예제 #26
0
파일: utils.py 프로젝트: ejeschke/stginga
def scale_image(infile, outfile, zoom_factor, ext=('SCI', 1), clobber=False,
                debug=False):
    """Rescale the image size in the given extension
    by the given zoom factor and adjust WCS accordingly.

    Both PC and CD matrices are supported. Distortion is not
    taken into account; therefore, this does not work on an
    image with ``CTYPE`` that ends in ``-SIP``.

    Output image is a single-extension FITS file with only
    the given extension header and data.

    .. note::

        WCS transformation provided by Mihai Cara.

        Some warnings are suppressed.

    Parameters
    ----------
    infile, outfile : str
        Input and output filenames.

    zoom_factor : float or sequence
        See :func:`scipy.ndimage.interpolation.zoom`.

    ext : int, str, or tuple
        Extension to extract.

    clobber : bool
        If `True`, overwrite existing output file.

    debug : bool
        If `True`, print extra information to screen.

    Raises
    ------
    ValueError
        Unsupported number of dimension or invalid WCS.

    """
    if not clobber and os.path.exists(outfile):
        if debug:
            warnings.warn('{0} already exists'.format(outfile),
                          AstropyUserWarning)
        return  # Instead of raising error at the very end

    with fits.open(infile) as pf:
        prihdr = pf['PRIMARY'].header
        hdr = pf[ext].header
        data = pf[ext].data

    # Inherit some keywords from primary header
    for key in ('ROOTNAME', 'TARGNAME', 'INSTRUME', 'DETECTOR',
                'FILTER', 'PUPIL', 'DATE-OBS', 'TIME-OBS'):
        if (key in hdr) or (key not in prihdr):
            continue
        hdr[key] = prihdr[key]

    if data.ndim != 2:
        raise ValueError('Unsupported ndim={0}'.format(data.ndim))

    # Scale the data.
    # Supress UserWarning about scipy 0.13.0 using round() instead of int().
    with warnings.catch_warnings():
        warnings.simplefilter('ignore', UserWarning)
        data = zoom(data, zoom_factor)

    # Adjust WCS

    slice_factor = int(1 / zoom_factor)
    old_wcs = wcs.WCS(hdr)  # To account for distortion, add "pf" as 2nd arg

    # Supress RuntimeWarning about ignoring cdelt because cd is present.
    with warnings.catch_warnings():
        warnings.simplefilter('ignore', RuntimeWarning)
        # Update if cropping
        new_wcs = old_wcs.slice(
            (np.s_[::slice_factor], np.s_[::slice_factor]))

    if old_wcs.wcs.has_pc():  # PC matrix
        wshdr = new_wcs.to_header()

    elif old_wcs.wcs.has_cd():  # CD matrix

        # Supress RuntimeWarning about ignoring cdelt because cd is present
        with warnings.catch_warnings():
            warnings.simplefilter('ignore', RuntimeWarning)
            new_wcs.wcs.cd *= new_wcs.wcs.cdelt

        new_wcs.wcs.set()
        wshdr = new_wcs.to_header()

        for i in range(1, 3):
            for j in range(1, 3):
                key = 'PC{0}_{1}'.format(i, j)
                if key in wshdr:
                    wshdr.rename_keyword(key, 'CD{0}_{1}'.format(i, j))

    else:
        raise ValueError('Missing CD or PC matrix for WCS')

    # Update header
    if 'XTENSION' in hdr:
        del hdr['XTENSION']
    if 'SIMPLE' in hdr:
        hdr['SIMPLE'] = True
    else:
        hdr.insert(0, ('SIMPLE', True))
    hdr.extend(
        [c if c[0] not in hdr else c[0:] for c in wshdr.cards], update=True)

    if debug:
        old_wcs.printwcs()
        new_wcs.printwcs()

    # Write to output file
    hdu = fits.PrimaryHDU(data)
    hdu.header = hdr
    if minversion(astropy, '1.3'):
        hdu.writeto(outfile, overwrite=clobber)
    else:
        hdu.writeto(outfile, clobber=clobber)
예제 #27
0
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Test Structured units and quantities specifically with the ERFA ufuncs.
"""
import erfa
import numpy as np
import pytest
from erfa import ufunc as erfa_ufunc
from numpy.testing import assert_array_equal

from astropy import units as u
from astropy.tests.helper import assert_quantity_allclose
from astropy.utils.introspection import minversion

ERFA_LE_2_0_0 = not minversion(erfa, '2.0.0.1')


class TestPVUfuncs:
    def setup_class(self):
        self.pv_unit = u.Unit('AU,AU/day')
        self.pv_value = np.array([([1., 0., 0.], [0., 0.0125, 0.]),
                                  ([0., 1., 0.], [-.0125, 0., 0.])],
                                 dtype=erfa_ufunc.dt_pv)
        self.pv = self.pv_value << self.pv_unit

    def test_cpv(self):
        pv_copy = erfa_ufunc.cpv(self.pv)
        assert_array_equal(pv_copy, self.pv)
        assert not np.may_share_memory(pv_copy, self.pv)

    def test_p2pv(self):
예제 #28
0
from pathlib import Path
from astropy.utils.introspection import minversion


def get_asdf_tests():
    asdf_dir = Path(__file__).parent.resolve()
    paths = Path(asdf_dir).rglob("test_*.py")

    return [str(p.relative_to(asdf_dir)) for p in paths]


collect_ignore = get_asdf_tests()
try:
    import asdf
except ImportError:
    pass
else:
    if not minversion(asdf, "3.0.0"):
        collect_ignore = []
예제 #29
0
except AttributeError:
    pass

__all__ = [
    'main', 'get_ginga_plugins', 'copy_ginga_files', 'set_ginga_config',
    'shrink_input_images'
]
__taskname__ = 'QUIP'
_operational = 'false'  # 'true' or 'false'
_tempdirname = 'quipcache'  # Sub-dir to store temporary intermediate files
_iswin = platform.system() == 'Windows'
_home = None
QUIP_DIRECTIVE = None  # Store info from input XML
QUIP_LOG = None  # Store info for output log XML

STGINGA_GT_1_2 = minversion('stginga', '1.2.1')

# Set HOME directory
if 'HOME' in os.environ:
    _home = os.environ['HOME']
elif _iswin:
    _home = os.path.join(os.environ['HOMEDRIVE'], os.environ['HOMEPATH'])
else:
    raise ValueError('Cannot find HOME directory')


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:
예제 #30
0
"""Module to handle compatibility with dependencies like Astropy."""
from __future__ import absolute_import, division, print_function

import astropy
from astropy.utils.introspection import minversion

__all__ = ['ASTROPY_LT_1_3']

ASTROPY_LT_1_3 = not minversion(astropy, '1.3')