Esempio n. 1
0
def test_sip_tpv_agreement():
    sip_header = get_pkg_data_contents(
        os.path.join("data", "siponly.hdr"), encoding='binary')
    tpv_header = get_pkg_data_contents(
        os.path.join("data", "tpvonly.hdr"), encoding='binary')

    w_sip = wcs.WCS(sip_header)
    w_tpv = wcs.WCS(tpv_header)

    assert_array_almost_equal(
        w_sip.all_pix2world([w_sip.wcs.crpix], 1),
        w_tpv.all_pix2world([w_tpv.wcs.crpix], 1))

    w_sip2 = wcs.WCS(w_sip.to_header())
    w_tpv2 = wcs.WCS(w_tpv.to_header())

    assert_array_almost_equal(
        w_sip.all_pix2world([w_sip.wcs.crpix], 1),
        w_sip2.all_pix2world([w_sip.wcs.crpix], 1))
    assert_array_almost_equal(
        w_tpv.all_pix2world([w_sip.wcs.crpix], 1),
        w_tpv2.all_pix2world([w_sip.wcs.crpix], 1))
    assert_array_almost_equal(
        w_sip2.all_pix2world([w_sip.wcs.crpix], 1),
        w_tpv2.all_pix2world([w_tpv.wcs.crpix], 1))
Esempio n. 2
0
 def callback(request, context):
     nonlocal first_batch
     if first_batch:
         first_batch = False
         return get_pkg_data_contents('data/datalink/cutout1.xml')
     else:
         return get_pkg_data_contents('data/datalink/cutout2.xml')
Esempio n. 3
0
def test_sip_tpv_agreement():
    sip_header = get_pkg_data_contents(
        os.path.join("data", "siponly.hdr"), encoding='binary')
    tpv_header = get_pkg_data_contents(
        os.path.join("data", "tpvonly.hdr"), encoding='binary')

    with pytest.warns(wcs.FITSFixedWarning):
        w_sip = wcs.WCS(sip_header)
        w_tpv = wcs.WCS(tpv_header)

        assert_array_almost_equal(
            w_sip.all_pix2world([w_sip.wcs.crpix], 1),
            w_tpv.all_pix2world([w_tpv.wcs.crpix], 1))

        w_sip2 = wcs.WCS(w_sip.to_header())
        w_tpv2 = wcs.WCS(w_tpv.to_header())

        assert_array_almost_equal(
            w_sip.all_pix2world([w_sip.wcs.crpix], 1),
            w_sip2.all_pix2world([w_sip.wcs.crpix], 1))
        assert_array_almost_equal(
            w_tpv.all_pix2world([w_sip.wcs.crpix], 1),
            w_tpv2.all_pix2world([w_sip.wcs.crpix], 1))
        assert_array_almost_equal(
            w_sip2.all_pix2world([w_sip.wcs.crpix], 1),
            w_tpv2.all_pix2world([w_tpv.wcs.crpix], 1))
Esempio n. 4
0
def test_printwcs():
    """
    Just make sure that it runs
    """
    h = get_pkg_data_contents('data/spectra/orion-freq-1.hdr', encoding='binary')
    w = wcs.WCS(h)
    w.printwcs()
    h = get_pkg_data_contents('data/3d_cd.hdr', encoding='binary')
    w = wcs.WCS(h)
    w.printwcs()
Esempio n. 5
0
def test_printwcs():
    """
    Just make sure that it runs
    """
    h = get_pkg_data_contents('data/spectra/orion-freq-1.hdr', encoding='binary')
    w = wcs.WCS(h)
    w.printwcs()
    h = get_pkg_data_contents('data/3d_cd.hdr', encoding='binary')
    w = wcs.WCS(h)
    w.printwcs()
Esempio n. 6
0
def _load_builtin_table_fields():
    key1 = ("PhotoObjAll", "http://skyserver.sdss.org/dr12/en/tools/search/x_sql.aspx")
    _cached_table_fields[key1] = _columns_json_to_table(json.loads(get_pkg_data_contents("data/PhotoObjAll_dr12.json")))
    # PhotoObj and PhotoObjAll are the same in DR12
    key2 = ("PhotoObj", "http://skyserver.sdss.org/dr12/en/tools/search/x_sql.aspx")
    _cached_table_fields[key2] = _cached_table_fields[key1]

    key1 = ("SpecObjAll", "http://skyserver.sdss.org/dr12/en/tools/search/x_sql.aspx")
    _cached_table_fields[key1] = _columns_json_to_table(json.loads(get_pkg_data_contents("data/SpecObjAll_dr12.json")))
    # SpecObj and SpecObjAll are the same in DR12
    key2 = ("SpecObj", "http://skyserver.sdss.org/dr12/en/tools/search/x_sql.aspx")
    _cached_table_fields[key2] = _cached_table_fields[key1]
Esempio n. 7
0
def _load_builtin_table_fields():
    _cached_table_fields['PhotoObjAll'] = _columns_json_to_table(
        json.loads(get_pkg_data_contents('data/PhotoObjAll_dr12.json')))
    # PhotoObj and PhotoObjAll are the same in DR12
    _cached_table_fields['PhotoObj'] = _cached_table_fields['PhotoObjAll']

    _cached_table_fields['SpecObjAll'] = _columns_json_to_table(
        json.loads(get_pkg_data_contents('data/SpecObjAll_dr12.json')))
    # SpecObj and SpecObjAll are the same in DR12
    _cached_table_fields['SpecObj'] = _cached_table_fields['SpecObjAll']

    return _cached_table_fields
Esempio n. 8
0
def test_read_unicode(filename):
    from astropy.utils.data import get_pkg_data_contents

    contents = get_pkg_data_contents(os.path.join('data', filename), encoding='utf-8')
    assert isinstance(contents, str)
    contents = contents.splitlines()[1]
    assert contents == "האסטרונומי פייתון"

    contents = get_pkg_data_contents(os.path.join('data', filename), encoding='binary')
    assert isinstance(contents, bytes)
    x = contents.splitlines()[1]
    assert x == (b"\xff\xd7\x94\xd7\x90\xd7\xa1\xd7\x98\xd7\xa8\xd7\x95\xd7\xa0"
                 b"\xd7\x95\xd7\x9e\xd7\x99 \xd7\xa4\xd7\x99\xd7\x99\xd7\xaa\xd7\x95\xd7\x9f"[1:])
Esempio n. 9
0
def test_read_unicode(filename):
    from astropy.utils.data import get_pkg_data_contents

    contents = get_pkg_data_contents(os.path.join('data', filename), encoding='utf-8')
    assert isinstance(contents, str)
    contents = contents.splitlines()[1]
    assert contents == "האסטרונומי פייתון"

    contents = get_pkg_data_contents(os.path.join('data', filename), encoding='binary')
    assert isinstance(contents, bytes)
    x = contents.splitlines()[1]
    assert x == (b"\xff\xd7\x94\xd7\x90\xd7\xa1\xd7\x98\xd7\xa8\xd7\x95\xd7\xa0"
                 b"\xd7\x95\xd7\x9e\xd7\x99 \xd7\xa4\xd7\x99\xd7\x99\xd7\xaa\xd7\x95\xd7\x9f"[1:])
Esempio n. 10
0
def get_builtin_sites():
    """
    Load observatory database from data/observatories.json and parse them into
    a SiteRegistry.
    """
    jsondb = json.loads(get_pkg_data_contents('data/sites.json'))
    return SiteRegistry.from_json(jsondb)
def test_spectrum(filename):
    header = get_pkg_data_contents(os.path.join("data", "spectra", filename))
    wcsobj = wcs.WCS(header)
    with NumpyRNGContext(123456789):
        x = np.random.rand(2 ** 16, wcsobj.wcs.naxis)
        world = wcsobj.wcs_pix2world(x, 1)
        pix = wcsobj.wcs_world2pix(x, 1)
Esempio n. 12
0
    def phase(self, request, context):
        self.validator(request)
        jobid = int(job_re_path.match(request.path).group(1))

        if request.method == 'GET':
            phase = self._jobs[jobid].phase
            return phase
        elif request.method == 'POST':
            newphase = request.body.split('=')[-1]
            job = self._jobs[jobid]
            result = get_pkg_data_contents('data/tap/obscore-image.xml')

            if newphase == 'RUN':
                newphase = 'COMPLETED'
                result = Result(
                    **{
                        'id':
                        'result',
                        'size':
                        len(result),
                        'mime-type':
                        'application/x-votable+xml',
                        'xlink:href': (
                            'http://example.com/tap/async/{}/results/result'
                        ).format(jobid)
                    })

                try:
                    job.results[0] = result
                except (IndexError, TypeError):
                    job.results.append(result)

            job.phase = newphase
Esempio n. 13
0
    def wavebandtest_callback(request, content):
        data = dict(parse_qsl(request.body))
        query = data['QUERY']

        assert "1 = ivo_hashlist_has('optical', waveband" in query

        return get_pkg_data_contents('data/regtap.xml')
Esempio n. 14
0
    def wavebandtest_callback(request, content):
        data = dict(parse_qsl(request.body))
        query = data['QUERY']

        assert "1 = ivo_hashlist_has('optical', waveband" in query

        return get_pkg_data_contents('data/regtap.xml')
Esempio n. 15
0
def test_spcfix():
    # TODO: We need some data with broken spectral headers here to
    # really test
    header = get_pkg_data_contents('data/spectra/orion-velo-1.hdr',
                                   encoding='binary')
    w = _wcs.Wcsprm(header)
    assert w.spcfix() == -1
Esempio n. 16
0
def test_printwcs(capsys):
    """
    Just make sure that it runs
    """
    h = get_pkg_data_contents(
        'data/spectra/orion-freq-1.hdr', encoding='binary')
    with pytest.warns(wcs.FITSFixedWarning):
        w = wcs.WCS(h)
        w.printwcs()
        captured = capsys.readouterr()
        assert 'WCS Keywords' in captured.out
    h = get_pkg_data_contents('data/3d_cd.hdr', encoding='binary')
    w = wcs.WCS(h)
    w.printwcs()
    captured = capsys.readouterr()
    assert 'WCS Keywords' in captured.out
Esempio n. 17
0
def test_skycoord_to_pixel(mode):

    # Import astropy.coordinates here to avoid circular imports
    from astropy.coordinates import SkyCoord

    header = get_pkg_data_contents('data/maps/1904-66_TAN.hdr',
                                   encoding='binary')
    wcs = WCS(header)

    ref = SkyCoord(0.1 * u.deg, -89. * u.deg, frame='icrs')

    xp, yp = skycoord_to_pixel(ref, wcs, mode=mode)

    # WCS is in FK5 so we need to transform back to ICRS
    new = pixel_to_skycoord(xp, yp, wcs, mode=mode).transform_to('icrs')

    assert_allclose(new.ra.degree, ref.ra.degree)
    assert_allclose(new.dec.degree, ref.dec.degree)

    # Make sure you can specify a different class using ``cls`` keyword
    class SkyCoord2(SkyCoord):
        pass

    new2 = pixel_to_skycoord(xp, yp, wcs, mode=mode,
                             cls=SkyCoord2).transform_to('icrs')

    assert new2.__class__ is SkyCoord2
    assert_allclose(new2.ra.degree, ref.ra.degree)
    assert_allclose(new2.dec.degree, ref.dec.degree)
Esempio n. 18
0
    def auxtest_callback(request, context):
        data = dict(parse_qsl(request.body))
        query = data['QUERY']

        assert "ivo://ivoa.net/std/tap#aux" in query

        return get_pkg_data_contents('data/regtap.xml')
Esempio n. 19
0
def test_inconsistent_sip():
    """
    Test for #4814
    """
    hdr = get_pkg_data_contents("data/sip-broken.hdr")
    with pytest.warns(None) as wrng:
        w = wcs.WCS(hdr)
    _check_v71_dateref_warnings(wrng)
    with pytest.warns(AstropyWarning):
        newhdr = w.to_header(relax=None)
    # CTYPE should not include "-SIP" if relax is None
    with pytest.warns(None) as wrng:
        wnew = wcs.WCS(newhdr)
    _check_v71_dateref_warnings(wrng)
    assert all(not ctyp.endswith('-SIP') for ctyp in wnew.wcs.ctype)
    newhdr = w.to_header(relax=False)
    assert('A_0_2' not in newhdr)
    # CTYPE should not include "-SIP" if relax is False
    with pytest.warns(None) as wrng:
        wnew = wcs.WCS(newhdr)
    _check_v71_dateref_warnings(wrng)
    assert all(not ctyp.endswith('-SIP') for ctyp in wnew.wcs.ctype)
    with pytest.warns(AstropyWarning):
        newhdr = w.to_header(key="C")
    assert('A_0_2' not in newhdr)
    # Test writing header with a different key
    with pytest.warns(None) as wrng:
        wnew = wcs.WCS(newhdr, key='C')
    _check_v71_dateref_warnings(wrng)
    assert all(not ctyp.endswith('-SIP') for ctyp in wnew.wcs.ctype)
    with pytest.warns(AstropyWarning):
        newhdr = w.to_header(key=" ")
    # Test writing a primary WCS to header
    with pytest.warns(None) as wrng:
        wnew = wcs.WCS(newhdr)
    _check_v71_dateref_warnings(wrng)
    assert all(not ctyp.endswith('-SIP') for ctyp in wnew.wcs.ctype)
    # Test that "-SIP" is kept into CTYPE if relax=True and
    # "-SIP" was in the original header
    newhdr = w.to_header(relax=True)
    with pytest.warns(None) as wrng:
        wnew = wcs.WCS(newhdr)
    _check_v71_dateref_warnings(wrng)
    assert all(ctyp.endswith('-SIP') for ctyp in wnew.wcs.ctype)
    assert('A_0_2' in newhdr)
    # Test that SIP coefficients are also written out.
    assert wnew.sip is not None
    # ######### broken header ###########
    # Test that "-SIP" is added to CTYPE if relax=True and
    # "-SIP" was not in the original header but SIP coefficients
    # are present.
    with pytest.warns(None) as wrng:
        w = wcs.WCS(hdr)
    _check_v71_dateref_warnings(wrng)
    w.wcs.ctype = ['RA---TAN', 'DEC--TAN']
    newhdr = w.to_header(relax=True)
    with pytest.warns(None) as wrng:
        wnew = wcs.WCS(newhdr)
    _check_v71_dateref_warnings(wrng)
    assert all(ctyp.endswith('-SIP') for ctyp in wnew.wcs.ctype)
Esempio n. 20
0
def test_skycoord_to_pixel_swapped():

    # Regression test for a bug that caused skycoord_to_pixel and
    # pixel_to_skycoord to not work correctly if the axes were swapped in the
    # WCS.

    # Import astropy.coordinates here to avoid circular imports
    from astropy.coordinates import SkyCoord

    header = get_pkg_data_contents('data/maps/1904-66_TAN.hdr',
                                   encoding='binary')
    wcs = WCS(header)

    wcs_swapped = wcs.sub([WCSSUB_LATITUDE, WCSSUB_LONGITUDE])

    ref = SkyCoord(0.1 * u.deg, -89. * u.deg, frame='icrs')

    xp1, yp1 = skycoord_to_pixel(ref, wcs)
    xp2, yp2 = skycoord_to_pixel(ref, wcs_swapped)

    assert_allclose(xp1, xp2)
    assert_allclose(yp1, yp2)

    # WCS is in FK5 so we need to transform back to ICRS
    new1 = pixel_to_skycoord(xp1, yp1, wcs).transform_to('icrs')
    new2 = pixel_to_skycoord(xp1, yp1, wcs_swapped).transform_to('icrs')

    assert_allclose(new1.ra.degree, new2.ra.degree)
    assert_allclose(new1.dec.degree, new2.dec.degree)
Esempio n. 21
0
def test_wcs_keyword_removal_for_wcs_test_files():
    """
    Test, for the WCS test files, that keyword removall works as
    expected. Those cover a much broader range of WCS types than
    test_wcs_keywords_removed_from_header
    """
    from astropy.nddata.ccddata import _generate_wcs_and_update_header
    from astropy.nddata.ccddata import _KEEP_THESE_KEYWORDS_IN_HEADER

    keepers = set(_KEEP_THESE_KEYWORDS_IN_HEADER)
    wcs_headers = get_pkg_data_filenames('../../wcs/tests/data',
                                         pattern='*.hdr')

    for hdr in wcs_headers:
        # Skip the files that are expected to be bad...
        if 'invalid' in hdr or 'nonstandard' in hdr or 'segfault' in hdr:
            continue
        header_string = get_pkg_data_contents(hdr)
        wcs = WCS(header_string)
        header = wcs.to_header(relax=True)
        new_header, new_wcs = _generate_wcs_and_update_header(header)
        # Make sure all of the WCS-related keywords have been removed.
        assert not (set(new_header) &
                    set(new_wcs.to_header(relax=True)) -
                    keepers)
        # Check that the new wcs is the same as the old.
        new_wcs_header = new_wcs.to_header(relax=True)
        for k, v in new_wcs_header.items():
            if isinstance(v, str):
                assert header[k] == v
            else:
                np.testing.assert_almost_equal(header[k], v)
Esempio n. 22
0
def test_skycoord_to_pixel_swapped():

    # Regression test for a bug that caused skycoord_to_pixel and
    # pixel_to_skycoord to not work correctly if the axes were swapped in the
    # WCS.

    # Import astropy.coordinates here to avoid circular imports
    from astropy.coordinates import SkyCoord

    header = get_pkg_data_contents('maps/1904-66_TAN.hdr', encoding='binary')
    wcs = WCS(header)

    wcs_swapped = wcs.sub([WCSSUB_LATITUDE, WCSSUB_LONGITUDE])

    ref = SkyCoord(0.1 * u.deg, -89. * u.deg, frame='icrs')

    xp1, yp1 = skycoord_to_pixel(ref, wcs)
    xp2, yp2 = skycoord_to_pixel(ref, wcs_swapped)

    assert_allclose(xp1, xp2)
    assert_allclose(yp1, yp2)

    # WCS is in FK5 so we need to transform back to ICRS
    new1 = pixel_to_skycoord(xp1, yp1, wcs).transform_to('icrs')
    new2 = pixel_to_skycoord(xp1, yp1, wcs_swapped).transform_to('icrs')

    assert_allclose(new1.ra.degree, new2.ra.degree)
    assert_allclose(new1.dec.degree, new2.dec.degree)
Esempio n. 23
0
def test_spcfix():
    # TODO: We need some data with broken spectral headers here to
    # really test
    header = get_pkg_data_contents(
        'data/spectra/orion-velo-1.hdr', encoding='binary')
    w = _wcs.Wcsprm(header)
    assert w.spcfix() == -1
Esempio n. 24
0
def test_wcs_keyword_removal_for_wcs_test_files():
    """
    Test, for the WCS test files, that keyword removall works as
    expected. Those cover a much broader range of WCS types than
    test_wcs_keywords_removed_from_header
    """
    from astropy.nddata.ccddata import _generate_wcs_and_update_header
    from astropy.nddata.ccddata import _KEEP_THESE_KEYWORDS_IN_HEADER

    keepers = set(_KEEP_THESE_KEYWORDS_IN_HEADER)
    wcs_headers = get_pkg_data_filenames('../../wcs/tests/data',
                                         pattern='*.hdr')

    for hdr in wcs_headers:
        # Skip the files that are expected to be bad...
        if 'invalid' in hdr or 'nonstandard' in hdr or 'segfault' in hdr:
            continue
        header_string = get_pkg_data_contents(hdr)
        wcs = WCS(header_string)
        header = wcs.to_header(relax=True)
        new_header, new_wcs = _generate_wcs_and_update_header(header)
        # Make sure all of the WCS-related keywords have been removed.
        assert not (set(new_header)
                    & set(new_wcs.to_header(relax=True)) - keepers)
        # Check that the new wcs is the same as the old.
        new_wcs_header = new_wcs.to_header(relax=True)
        for k, v in new_wcs_header.items():
            if isinstance(v, str):
                assert header[k] == v
            else:
                np.testing.assert_almost_equal(header[k], v)
Esempio n. 25
0
def test_skycoord_to_pixel(mode):

    # Import astropy.coordinates here to avoid circular imports
    from astropy.coordinates import SkyCoord

    header = get_pkg_data_contents('maps/1904-66_TAN.hdr', encoding='binary')
    wcs = WCS(header)

    ref = SkyCoord(0.1 * u.deg, -89. * u.deg, frame='icrs')

    xp, yp = skycoord_to_pixel(ref, wcs, mode=mode)

    # WCS is in FK5 so we need to transform back to ICRS
    new = pixel_to_skycoord(xp, yp, wcs, mode=mode).transform_to('icrs')

    assert_allclose(new.ra.degree, ref.ra.degree)
    assert_allclose(new.dec.degree, ref.dec.degree)

    # Make sure you can specify a different class using ``cls`` keyword
    class SkyCoord2(SkyCoord):
        pass

    new2 = pixel_to_skycoord(xp, yp, wcs, mode=mode,
                             cls=SkyCoord2).transform_to('icrs')

    assert new2.__class__ is SkyCoord2
    assert_allclose(new2.ra.degree, ref.ra.degree)
    assert_allclose(new2.dec.degree, ref.dec.degree)
Esempio n. 26
0
        def phase(self, request, context):
            jobid = int(job_re_path.match(request.path).group(1))

            if request.method == 'GET':
                phase = self._jobs[jobid].phase
                return phase
            elif request.method == 'POST':
                newphase = request.body.split('=')[-1]
                job = self._jobs[jobid]
                result = get_pkg_data_contents('data/tap/obscore-image.xml')

                if newphase == 'RUN':
                    newphase = 'COMPLETED'
                    result = Result(**{
                        'id': 'result',
                        'size': len(result),
                        'mime-type': 'application/x-votable+xml',
                        'xlink:href': (
                            'http://example.com/tap/async/{}/results/result'
                        ).format(jobid)
                    })

                    try:
                        job.results[0] = result
                    except (IndexError, TypeError):
                        job.results.append(result)

                job.phase = newphase
Esempio n. 27
0
def test_unit_normalization():
    """
    From github issue #1918
    """
    header = get_pkg_data_contents('data/unit.hdr', encoding='binary')
    w = wcs.WCS(header)
    assert w.wcs.cunit[2] == 'm/s'
Esempio n. 28
0
def get_builtin_sites():
    """
    Load observatory database from data/observatories.json and parse them into
    a SiteRegistry.
    """
    jsondb = json.loads(get_pkg_data_contents('data/sites.json'))
    return SiteRegistry.from_json(jsondb)
Esempio n. 29
0
def test_sub_3d_with_sip():
    # See #10527
    header = get_pkg_data_contents('data/irac_sip.hdr', encoding='binary')
    header = fits.Header.fromstring(header)
    header['NAXIS'] = 3
    header.set('NAXIS3', 64, after=header.index('NAXIS2'))
    w = wcs.WCS(header, naxis=2)
    assert w.naxis == 2
Esempio n. 30
0
def test_map(filename):
    header = get_pkg_data_contents(os.path.join("data/maps", filename))
    wcsobj = wcs.WCS(header)

    with NumpyRNGContext(123456789):
        x = np.random.rand(2**12, wcsobj.wcs.naxis)
        wcsobj.wcs_pix2world(x, 1)
        wcsobj.wcs_world2pix(x, 1)
Esempio n. 31
0
def test_fixes2():
    """
    From github issue #1854
    """
    header = get_pkg_data_contents(
        'data/nonstandard_units.hdr', encoding='binary')
    with pytest.raises(wcs.InvalidTransformError):
        w = wcs.WCS(header, fix=False)
Esempio n. 32
0
def test_fixes2():
    """
    From github issue #1854
    """
    header = get_pkg_data_contents(
        'data/nonstandard_units.hdr', encoding='binary')
    with pytest.raises(wcs.InvalidTransformError):
        wcs.WCS(header, fix=False)
Esempio n. 33
0
def test_unit_normalization():
    """
    From github issue #1918
    """
    header = get_pkg_data_contents(
        'data/unit.hdr', encoding='binary')
    w = wcs.WCS(header)
    assert w.wcs.cunit[2] == 'm/s'
Esempio n. 34
0
def test_error_message():
    header = get_pkg_data_contents('data/invalid_header.hdr',
                                   encoding='binary')

    with pytest.raises(wcs.InvalidTransformError):
        # Both lines are in here, because 0.4 calls .set within WCS.__init__,
        # whereas 0.3 and earlier did not.
        w = wcs.WCS(header, _do_set=False)
        c = w.all_pix2world([[536.0, 894.0]], 0)
Esempio n. 35
0
 def run():
     header = get_pkg_data_contents('data/nonstandard_units.hdr',
                                    encoding='binary')
     try:
         wcs.WCS(header, translate_units='dhs')
     except wcs.InvalidTransformError:
         pass
     else:
         assert False, "Expected InvalidTransformError"
Esempio n. 36
0
 def run():
     header = get_pkg_data_contents(
         'data/nonstandard_units.hdr', encoding='binary')
     try:
         w = wcs.WCS(header, translate_units='dhs')
     except wcs.InvalidTransformError:
         pass
     else:
         assert False, "Expected InvalidTransformError"
Esempio n. 37
0
def test_get_pkg_data_contents():
    from astropy.utils.data import get_pkg_data_fileobj, get_pkg_data_contents

    with get_pkg_data_fileobj('data/local.dat') as f:
        contents1 = f.read()

    contents2 = get_pkg_data_contents('data/local.dat')

    assert contents1 == contents2
Esempio n. 38
0
def test_scamp_sip_distortion_parameters():
    """
    Test parsing of WCS parameters with redundant SIP and SCAMP distortion
    parameters.
    """
    header = get_pkg_data_contents('data/validate.fits', encoding='binary')
    w = wcs.WCS(header)
    # Just check that this doesn't raise an exception.
    w.all_pix2world(0, 0, 0)
Esempio n. 39
0
def test_get_pkg_data_contents():
    from astropy.utils.data import get_pkg_data_fileobj, get_pkg_data_contents

    with get_pkg_data_fileobj('data/local.dat') as f:
        contents1 = f.read()

    contents2 = get_pkg_data_contents('data/local.dat')

    assert contents1 == contents2
Esempio n. 40
0
def _load_builtin_table_fields():
    key1 = ('PhotoObjAll',
            conf.skyserver_baseurl + '/dr12/en/tools/search/x_sql.aspx')
    _cached_table_fields[key1] = _columns_json_to_table(
        json.loads(get_pkg_data_contents('data/PhotoObjAll_dr12.json')))
    # PhotoObj and PhotoObjAll are the same in DR12
    key2 = ('PhotoObj',
            conf.skyserver_baseurl + '/dr12/en/tools/search/x_sql.aspx')
    _cached_table_fields[key2] = _cached_table_fields[key1]

    key1 = ('SpecObjAll',
            conf.skyserver_baseurl + '/dr12/en/tools/search/x_sql.aspx')
    _cached_table_fields[key1] = _columns_json_to_table(
        json.loads(get_pkg_data_contents('data/SpecObjAll_dr12.json')))
    # SpecObj and SpecObjAll are the same in DR12
    key2 = ('SpecObj',
            conf.skyserver_baseurl + '/dr12/en/tools/search/x_sql.aspx')
    _cached_table_fields[key2] = _cached_table_fields[key1]
Esempio n. 41
0
def test_scamp_sip_distortion_parameters():
    """
    Test parsing of WCS parameters with redundant SIP and SCAMP distortion
    parameters.
    """
    header = get_pkg_data_contents('data/validate.fits', encoding='binary')
    w = wcs.WCS(header)
    # Just check that this doesn't raise an exception.
    w.all_pix2world(0, 0, 0)
Esempio n. 42
0
    def datamodeltest_callback(request, content):
        data = dict(parse_qsl(request.body))
        query = data['QUERY']

        assert ("WHERE idet.detail_xpath = '/capability/dataModel/@ivo-id"
                in query)
        assert "idet.detail_value, 'ivo://ivoa.net/std/tap%')" in query

        return get_pkg_data_contents('data/regtap.xml')
Esempio n. 43
0
def test_error_message():
    header = get_pkg_data_contents(
        'data/invalid_header.hdr', encoding='binary')

    with pytest.raises(wcs.InvalidTransformError):
        # Both lines are in here, because 0.4 calls .set within WCS.__init__,
        # whereas 0.3 and earlier did not.
        w = wcs.WCS(header, _do_set=False)
        c = w.all_pix2world([[536.0, 894.0]], 0)
Esempio n. 44
0
def _load_builtin_table_fields():
    key1 = ('PhotoObjAll',
            'http://skyserver.sdss.org/dr12/en/tools/search/x_sql.aspx')
    _cached_table_fields[key1] = _columns_json_to_table(
        json.loads(get_pkg_data_contents('data/PhotoObjAll_dr12.json')))
    # PhotoObj and PhotoObjAll are the same in DR12
    key2 = ('PhotoObj',
            'http://skyserver.sdss.org/dr12/en/tools/search/x_sql.aspx')
    _cached_table_fields[key2] = _cached_table_fields[key1]

    key1 = ('SpecObjAll',
            'http://skyserver.sdss.org/dr12/en/tools/search/x_sql.aspx')
    _cached_table_fields[key1] = _columns_json_to_table(
        json.loads(get_pkg_data_contents('data/SpecObjAll_dr12.json')))
    # SpecObj and SpecObjAll are the same in DR12
    key2 = ('SpecObj',
            'http://skyserver.sdss.org/dr12/en/tools/search/x_sql.aspx')
    _cached_table_fields[key2] = _cached_table_fields[key1]
Esempio n. 45
0
def test_wcs_keyword_removal_for_wcs_test_files():
    """
    Test, for the WCS test files, that keyword removal works as
    expected. Those cover a much broader range of WCS types than
    test_wcs_keywords_removed_from_header.

    Includes regression test for #8597
    """
    from astropy.nddata.ccddata import _generate_wcs_and_update_header
    from astropy.nddata.ccddata import (_KEEP_THESE_KEYWORDS_IN_HEADER,
                                        _CDs, _PCs)

    keepers = set(_KEEP_THESE_KEYWORDS_IN_HEADER)
    wcs_headers = get_pkg_data_filenames('../../wcs/tests/data',
                                         pattern='*.hdr')

    for hdr in wcs_headers:
        # Skip the files that are expected to be bad...
        if ('invalid' in hdr or 'nonstandard' in hdr or 'segfault' in hdr or
            'chandra-pixlist-wcs' in hdr):
            continue
        header_string = get_pkg_data_contents(hdr)
        header = fits.Header.fromstring(header_string)

        wcs = WCS(header_string)
        header_from_wcs = wcs.to_header(relax=True)

        new_header, new_wcs = _generate_wcs_and_update_header(header)
        new_wcs_header = new_wcs.to_header(relax=True)

        # Make sure all of the WCS-related keywords generated by astropy
        # have been removed.
        assert not (set(new_header) &
                    set(new_wcs_header) -
                    keepers)

        # Check that new_header contains no remaining WCS information.
        # Specifically, check that
        # 1. The combination of new_header and new_wcs does not contain
        #    both PCi_j and CDi_j keywords. See #8597.

        # Check for 1
        final_header = new_header + new_wcs_header
        final_header_set = set(final_header)

        if _PCs & final_header_set:
            assert not (_CDs & final_header_set)
        elif _CDs & final_header_set:
            assert not (_PCs & final_header_set)

        # Check that the new wcs is the same as the old.
        for k, v in new_wcs_header.items():
            if isinstance(v, str):
                assert header_from_wcs[k] == v
            else:
                np.testing.assert_almost_equal(header_from_wcs[k], v)
Esempio n. 46
0
def generate_cfg_example(config_name, cfgpath='examples/configs', **kwargs):
    """Generate config file documentation for a given config name.

    If found, it will be a Python code block of the contents.
    If not found, it will have a generic message that the config
    is not available.

    Parameters
    ----------
    config_name : str
        Config name that is attached to the configuration file.
        This is the same as input for ``prefs.createCategory()``.
        For example, ``'general'``, ``'channel_Image'``, or
        ``'plugin_Zoom'``.

    cfgpath : str
        Where it is within package data.

    kwargs : dict
        Optional keywords for :func:`~astropy.utils.data.get_pkg_data_contents`.

    Returns
    -------
    docstr : str
        Docstring to be inserted into documentation.

    """
    cfgname = config_name + '.cfg'

    try:
        cfgdata = get_pkg_data_contents(os.path.join(cfgpath, cfgname),
                                        **kwargs)
    except Exception as e:
        warnings.warn(str(e), AstropyUserWarning)
        return ''

    homepath = '~'  # Symbol for HOME for doc only, not actual code
    userfile = os.path.join(homepath, '.ginga', cfgname)

    docstring = io.StringIO()
    docstring.write("""It is customizable using ``{0}``, where ``{1}``
is your HOME directory:

.. code-block:: Python

""".format(userfile, homepath))

    for line in cfgdata.split('\n'):
        line = line.strip()

        if len(line) == 0:
            docstring.write('\n')  # Prevent trailing spaces
        else:
            docstring.write('  {0}\n'.format(line))

    return docstring.getvalue()
Esempio n. 47
0
def test_get_pc():
    header = get_pkg_data_contents('data/3d_cd.hdr', encoding='binary')
    w = _wcs.Wcsprm(header)
    pc = w.get_pc()
    try:
        pc[0, 0] = 42
    except (RuntimeError, ValueError):
        pass
    else:
        raise AssertionError()
Esempio n. 48
0
def test_outside_sky():
    """
    From github issue #107
    """
    header = get_pkg_data_contents('data/outside_sky.hdr', encoding='binary')
    w = wcs.WCS(header)

    assert np.all(np.isnan(w.wcs_pix2world([[100., 500.]], 0)))  # outside sky
    assert np.all(np.isnan(w.wcs_pix2world([[200., 200.]], 0)))  # outside sky
    assert not np.any(np.isnan(w.wcs_pix2world([[1000., 1000.]], 0)))
Esempio n. 49
0
    def datamodeltest_callback(request, content):
        data = dict(parse_qsl(request.body))
        query = data['QUERY']

        assert (
            "WHERE idet.detail_xpath = '/capability/dataModel/@ivo-id" in query
        )
        assert "idet.detail_value, 'ivo://ivoa.net/std/tap%')" in query

        return get_pkg_data_contents('data/regtap.xml')
Esempio n. 50
0
def test_warning_about_defunct_keywords():
    header = get_pkg_data_contents('data/defunct_keywords.hdr', encoding='binary')
    # Make sure the warnings come out every time...
    for _ in range(2):
        with pytest.warns(wcs.FITSFixedWarning) as w:
            wcs.WCS(header)

        assert len(w) == 4
        for item in w:
            assert 'PCi_ja' in str(item.message)
Esempio n. 51
0
def test_wcs_keyword_removal_for_wcs_test_files():
    """
    Test, for the WCS test files, that keyword removal works as
    expected. Those cover a much broader range of WCS types than
    test_wcs_keywords_removed_from_header.

    Includes regression test for #8597
    """
    from astropy.nddata.ccddata import _generate_wcs_and_update_header
    from astropy.nddata.ccddata import (_KEEP_THESE_KEYWORDS_IN_HEADER,
                                        _CDs, _PCs)

    keepers = set(_KEEP_THESE_KEYWORDS_IN_HEADER)
    wcs_headers = get_pkg_data_filenames('../../wcs/tests/data',
                                         pattern='*.hdr')

    for hdr in wcs_headers:
        # Skip the files that are expected to be bad...
        if 'invalid' in hdr or 'nonstandard' in hdr or 'segfault' in hdr:
            continue
        header_string = get_pkg_data_contents(hdr)
        header = fits.Header.fromstring(header_string)

        wcs = WCS(header_string)
        header_from_wcs = wcs.to_header(relax=True)

        new_header, new_wcs = _generate_wcs_and_update_header(header)
        new_wcs_header = new_wcs.to_header(relax=True)

        # Make sure all of the WCS-related keywords generated by astropy
        # have been removed.
        assert not (set(new_header) &
                    set(new_wcs_header) -
                    keepers)

        # Check that new_header contains no remaining WCS information.
        # Specifically, check that
        # 1. The combination of new_header and new_wcs does not contain
        #    both PCi_j and CDi_j keywords. See #8597.

        # Check for 1
        final_header = new_header + new_wcs_header
        final_header_set = set(final_header)

        if _PCs & final_header_set:
            assert not (_CDs & final_header_set)
        elif _CDs & final_header_set:
            assert not (_PCs & final_header_set)

        # Check that the new wcs is the same as the old.
        for k, v in new_wcs_header.items():
            if isinstance(v, str):
                assert header_from_wcs[k] == v
            else:
                np.testing.assert_almost_equal(header_from_wcs[k], v)
Esempio n. 52
0
def generate_cfg_example(config_name, **kwargs):
    """Generate config file documentation for a given config name.

    If found, it will be a Python code block of the contents.
    If not found, it will have a generic message that the config
    is not available.

    Parameters
    ----------
    config_name : str
        Config name that is attached to the configuration file.
        This is the same as input for ``prefs.createCategory()``.
        For example, ``'general'``, ``'channel_Image'``, or
        ``'plugin_Zoom'``.

    kwargs : dict
        Optional keywords for :func:`~astropy.utils.data.get_pkg_data_contents`.

    Returns
    -------
    docstr : str
        Docstring to be inserted into documentation.

    """
    cfgpath = 'examples/configs'  # Where it is in pkg data
    cfgname = config_name + '.cfg'

    try:
        cfgdata = get_pkg_data_contents(
            os.path.join(cfgpath, cfgname), **kwargs)
    except Exception as e:
        warnings.warn(str(e), AstropyUserWarning)
        return ''

    homepath = '~'  # Symbol for HOME for doc only, not actual code
    userfile = os.path.join(homepath, '.ginga', cfgname)

    docstring = io.StringIO()
    docstring.write("""It is customizable using ``{0}``, where ``{1}``
is your HOME directory:

.. code-block:: Python

""".format(userfile, homepath))

    for line in cfgdata.split('\n'):
        line = line.strip()

        if len(line) == 0:
            docstring.write('\n')  # Prevent trailing spaces
        else:
            docstring.write('  {0}\n'.format(line))

    return docstring.getvalue()
Esempio n. 53
0
    def servicetypetest_callback(request, context):
        data = dict(parse_qsl(request.body))
        query = data['QUERY']

        assert "'ivo://ivoa.net/std/conesearch'" not in query
        assert "'ivo://ivoa.net/std/sia'" not in query
        assert "'ivo://ivoa.net/std/ssa'" not in query
        assert "'ivo://ivoa.net/std/slap'" not in query
        assert "'ivo://ivoa.net/std/tap'" in query

        return get_pkg_data_contents('data/regtap.xml')
Esempio n. 54
0
def test_outside_sky():
    """
    From github issue #107
    """
    header = get_pkg_data_contents(
        'data/outside_sky.hdr', encoding='binary')
    w = wcs.WCS(header)

    assert np.all(np.isnan(w.wcs_pix2world([[100., 500.]], 0)))  # outside sky
    assert np.all(np.isnan(w.wcs_pix2world([[200., 200.]], 0)))  # outside sky
    assert not np.any(np.isnan(w.wcs_pix2world([[1000., 1000.]], 0)))
Esempio n. 55
0
def test_tpv_copy():
    # See #3904

    tpv_header = get_pkg_data_contents(
        os.path.join("data", "tpvonly.hdr"), encoding='binary')

    w_tpv = wcs.WCS(tpv_header)

    ra, dec = w_tpv.wcs_pix2world([0, 100, 200], [0, -100, 200], 0)
    assert ra[0] != ra[1] and ra[1] != ra[2]
    assert dec[0] != dec[1] and dec[1] != dec[2]
Esempio n. 56
0
 def test_spectra(self):
     for filename in self._file_list:
         # use the base name of the file, so we get more useful messages
         # for failing tests.
         filename = os.path.basename(filename)
         # Now find the associated file in the installed wcs test directory.
         header = get_pkg_data_contents(
             os.path.join("data", "spectra", filename), encoding='binary')
         # finally run the test.
         all_wcs = wcs.find_all_wcs(header)
         assert len(all_wcs) == 9
Esempio n. 57
0
 def test_maps(self):
     for filename in self._file_list:
         # use the base name of the file, so we get more useful messages
         # for failing tests.
         filename = os.path.basename(filename)
         # Now find the associated file in the installed wcs test directory.
         header = get_pkg_data_contents(
             os.path.join("data", "maps", filename), encoding='binary')
         # finally run the test.
         wcsobj = wcs.WCS(header)
         world = wcsobj.wcs_pix2world([[97, 97]], 1)
         assert_array_almost_equal(world, [[285.0, -66.25]], decimal=1)
         pix = wcsobj.wcs_world2pix([[285.0, -66.25]], 1)
         assert_array_almost_equal(pix, [[97, 97]], decimal=0)
Esempio n. 58
0
def test_out_of_bounds():
    # See #2107
    header = get_pkg_data_contents('data/zpn-hole.hdr', encoding='binary')
    w = wcs.WCS(header)

    ra, dec = w.wcs_pix2world(110, 110, 0)

    assert np.isnan(ra)
    assert np.isnan(dec)

    ra, dec = w.wcs_pix2world(0, 0, 0)

    assert not np.isnan(ra)
    assert not np.isnan(dec)
Esempio n. 59
0
def test_sip():
    # See #2107
    header = get_pkg_data_contents('data/irac_sip.hdr', encoding='binary')
    w = wcs.WCS(header)

    x0, y0 = w.sip_pix2foc(200, 200, 0)

    assert_allclose(72, x0, 1e-3)
    assert_allclose(72, y0, 1e-3)

    x1, y1 = w.sip_foc2pix(x0, y0, 0)

    assert_allclose(200, x1, 1e-3)
    assert_allclose(200, y1, 1e-3)