コード例 #1
0
ファイル: test_spec2d.py プロジェクト: weaverba137/pydl
 def test_filter_thru(self):
     fname = get_pkg_data_filename('t/spPlate-4055-55359-0020.fits')
     with fits.open(fname) as hdulist:
         flux = hdulist[0].data
         npix = hdulist[0].header['NAXIS1']
         ntrace = hdulist[0].header['NAXIS2']
         crval1 = hdulist[0].header['COEFF0']
         cd1_1 = hdulist[0].header['COEFF1']
     assert flux.shape == (ntrace, npix)
     loglam0 = crval1 + cd1_1*np.arange(npix, dtype=flux.dtype)
     waveimg = 10**(np.tile(loglam0, 20).reshape(flux.shape))
     assert waveimg.shape == flux.shape
     f = filter_thru(flux, waveimg=waveimg)
     idl_data_file = get_pkg_data_filename('t/filter_thru_idl_data.txt')
     idl_data = np.loadtxt(idl_data_file, dtype='f', delimiter=',').T
     assert f.shape == (20, 5)
     assert np.allclose(f, idl_data, atol=1.0e-6)
     #
     # Test bad input.
     #
     with raises(ValueError):
         f = filter_thru(flux)
     with raises(ValueError):
         f = filter_thru(flux, waveimg=waveimg, filter_prefix='sdss')
     return
コード例 #2
0
def test_coeff(basename):
    nmax = 6
    lmax = 10 # HACK: these are hard-set in Fortran

    pos_path = os.path.abspath(get_pkg_data_filename('data/{}-samples.dat.gz'.format(basename)))
    coeff_path = os.path.abspath(get_pkg_data_filename('data/computed-{0}.coeff'.format(basename)))
    coeff = np.atleast_2d(np.loadtxt(coeff_path))

    xyz = np.ascontiguousarray(np.loadtxt(pos_path, skiprows=1))
    S,T = compute_coeffs_discrete(xyz, mass=np.zeros(xyz.shape[0])+1./xyz.shape[0],
                                  nmax=nmax, lmax=lmax, r_s=1.)

    S_f77 = np.zeros((nmax+1,lmax+1,lmax+1))
    T_f77 = np.zeros((nmax+1,lmax+1,lmax+1))
    for row in coeff:
        n,l,m,cc,sc = row

        # transform from H&O 1992 coefficients to Lowing 2011 coefficients
        if l != 0:
            fac = np.sqrt(4*np.pi) * np.sqrt((2*l+1) / (4*np.pi) * factorial(l-m) / factorial(l+m))
            cc /= fac
            sc /= fac

        S_f77[int(n),int(l),int(m)] = -cc
        T_f77[int(n),int(l),int(m)] = -sc

    assert np.allclose(S_f77, S)
コード例 #3
0
ファイル: core.py プロジェクト: autocorr/astroquery
    def list_votable_fields(self):
        """
        Lists all the fields that can be fetched for a VOTable.

        Examples
        --------
        >>> from astroquery.simbad import Simbad
        >>> Simbad.list_votable_fields()
        --NOTES--...
        """
        # display additional notes:
        notes_file = get_pkg_data_filename(os.path.join('data', 'votable_fields_notes.json'))
        with open(notes_file, "r") as f:
            notes = json.load(f)
        print ("--NOTES--\n")
        for i, line in list(enumerate(notes)):
            print ("{lineno}. {msg}\n".format(lineno=i+1, msg=line))

        # load the table
        votable_fields_table = Table.read(get_pkg_data_filename
                                          (os.path.join('data',
                                                        'votable_fields_table.txt')),
                                         format='ascii')
        print (votable_fields_table)

        print("\nFor more information on a field :\nSimbad.get_field_description "
              "('field_name')")
コード例 #4
0
ファイル: core.py プロジェクト: abigailStev/astroquery
    def list_votable_fields(self):
        """
        Lists all the fields that can be fetched for a VOTable.

        Examples
        --------
        >>> from astroquery.simbad import Simbad
        >>> Simbad.list_votable_fields()
        --NOTES--...
        """
        # display additional notes:
        notes_file = get_pkg_data_filename(
            os.path.join('data', 'votable_fields_notes.json'))
        with open(notes_file, "r") as f:
            notes = json.load(f)
        print("--NOTES--\n")
        for i, line in list(enumerate(notes)):
            print("{lineno}. {msg}\n".format(lineno=i + 1, msg=line))

        dict_file = get_pkg_data_filename(
            os.path.join('data', 'votable_fields_dict.json'))
        with open(dict_file, "r") as f:
            fields_dict = json.load(f)

        print("Available VOTABLE fields:\n")
        for field in list(sorted(fields_dict.keys())):
            print("{}".format(field))
        print("For more information on a field:\n"
              "Simbad.get_field_description ('field_name') \n"
              "Currently active VOTABLE fields:\n {0}"
              .format(self._VOTABLE_FIELDS))
コード例 #5
0
ファイル: test_ds9_language.py プロジェクト: astropy/regions
def test_file(filename):
    filename = get_pkg_data_filename(filename)
    regs = read_ds9(filename, errors='warn')

    coordsys = os.path.basename(filename).split(".")[1]

    actual = ds9_objects_to_string(regs, coordsys=str(coordsys), fmt='.2f',
                                   radunit=None if coordsys=='physical' else 'arcsec').strip()

    reffile = get_pkg_data_filename('data/{coordsys}{strip}_reference.reg'
                                    .format(coordsys=coordsys,
                                            strip=("_strip"
                                                   if "strip" in filename
                                                   else "")))

    with open(reffile, 'r') as fh:
        desired = fh.read().strip()

    # since metadata is not required to preserve order, we have to do a more
    # complex comparison
    desired_lines = [set(line.split(" ")) for line in desired.split("\n")]
    actual_lines = [set(line.split(" ")) for line in actual.split("\n")]
    for split_line in actual_lines:
        assert split_line in desired_lines

    for split_line in desired_lines:
        assert split_line in actual_lines
コード例 #6
0
    def list_votable_fields(self):
        """
        Lists all the fields that can be fetched for a VOTable.

        Examples
        --------
        >>> from astroquery.simbad import Simbad
        >>> Simbad.list_votable_fields()
        --NOTES--...
        """
        # display additional notes:
        notes_file = get_pkg_data_filename(
            os.path.join('data', 'votable_fields_notes.json'))
        with open(notes_file, "r") as f:
            notes = json.load(f)
        print("--NOTES--\n")
        for i, line in list(enumerate(notes)):
            print("{lineno}. {msg}\n".format(lineno=i + 1, msg=line))

        if not hasattr(self,'_votable_fields_table'):
            # load the table
            votable_fields_table = Table.read(
                get_pkg_data_filename(os.path.join('data',
                                                   'votable_fields_table.txt')),
                format='ascii')
            self._votable_fields_table = votable_fields_table
        else:
            votable_fields_table = self._votable_fields_table
            
        print("Available VOTABLE fields:\n")
        votable_fields_table.pprint(max_lines=100)
        print("For more information on a field :\n"
              "Simbad.get_field_description ('field_name') \n"
              "Currently active VOTABLE fields:\n {0}"
              .format(self._VOTABLE_FIELDS))
コード例 #7
0
ファイル: test_trace.py プロジェクト: weaverba137/pydl
    def setup(self):
        # extracted from spFrame-b1-00057618.fits

        self.sdss = fits.open(get_pkg_data_filename('t/sdss_traceset.fits'))
        # extracted from spFrame-r1-00180406.fits
        self.boss = fits.open(get_pkg_data_filename('t/boss_traceset.fits'))
        return
コード例 #8
0
ファイル: test_accp_fortran.py プロジェクト: adrn/gala
def test_gradient(basename):
    pos_path = os.path.abspath(get_pkg_data_filename('data/positions.dat.gz'))
    coeff_path = os.path.abspath(get_pkg_data_filename('data/{0}.coeff'.format(basename)))
    accp_path = os.path.abspath(get_pkg_data_filename('data/{0}-accp.dat.gz'.format(basename)))

    xyz = np.loadtxt(pos_path, skiprows=1)
    coeff = np.atleast_2d(np.loadtxt(coeff_path, skiprows=1))
    accp = np.loadtxt(accp_path)

    nmax = coeff[:,0].astype(int).max()
    lmax = coeff[:,1].astype(int).max()

    cos_coeff = np.zeros((nmax+1, lmax+1, lmax+1))
    sin_coeff = np.zeros((nmax+1, lmax+1, lmax+1))
    for row in coeff:
        n, l, m, cc, sc = row

        # transform from H&O 1992 coefficients to Lowing 2011 coefficients
        if l != 0:
            fac = np.sqrt(4*np.pi) * np.sqrt((2*l+1) / (4*np.pi) * factorial(l-m) / factorial(l+m))
            cc /= fac
            sc /= fac

        cos_coeff[int(n), int(l), int(m)] = cc
        sin_coeff[int(n), int(l), int(m)] = sc

    grad = gradient(xyz, G=1., M=1., r_s=1.,
                    Snlm=cos_coeff, Tnlm=sin_coeff)

    # I output the acceleration from SCF when I make the files
    #   so I have no idea why I don't need a minus sign here...
    scf_grad = accp[:, :3]
    np.testing.assert_allclose(grad, scf_grad, rtol=1E-6)
コード例 #9
0
ファイル: test_accp_fortran.py プロジェクト: adrn/gala
def test_potential(basename):
    coeff_path = os.path.abspath(get_pkg_data_filename('data/{0}.coeff'.format(basename)))
    accp_path = os.path.abspath(get_pkg_data_filename('data/{0}-accp.dat.gz'.format(basename)))

    coeff = np.atleast_2d(np.loadtxt(coeff_path, skiprows=1))
    accp = np.loadtxt(accp_path)

    pos_path = os.path.abspath(get_pkg_data_filename('data/positions.dat.gz'))
    xyz = np.loadtxt(pos_path, skiprows=1)

    nmax = coeff[:, 0].astype(int).max()
    lmax = coeff[:, 1].astype(int).max()

    cos_coeff = np.zeros((nmax+1, lmax+1, lmax+1))
    sin_coeff = np.zeros((nmax+1, lmax+1, lmax+1))
    for row in coeff:
        n, l, m, cc, sc = row

        # transform from H&O 1992 coefficients to Lowing 2011 coefficients
        if l != 0:
            fac = np.sqrt(4*np.pi) * np.sqrt((2*l+1) / (4*np.pi) * factorial(l-m) / factorial(l+m))
            cc /= fac
            sc /= fac

        cos_coeff[int(n), int(l), int(m)] = cc
        sin_coeff[int(n), int(l), int(m)] = sc

    potv = potential(xyz, G=1., M=1., r_s=1.,
                     Snlm=cos_coeff, Tnlm=sin_coeff)

    # for some reason, SCF potential is -potential
    scf_potv = -accp[:, -1]
    np.testing.assert_allclose(potv, scf_potv, rtol=1E-6)
コード例 #10
0
ファイル: test_accp_fortran.py プロジェクト: adrn/gala
def test_density(basename):
    pos_path = os.path.abspath(get_pkg_data_filename('data/positions.dat.gz'))
    coeff_path = os.path.abspath(get_pkg_data_filename('data/{0}.coeff'.format(basename)))
    accp_path = os.path.abspath(get_pkg_data_filename('data/{0}-accp.dat.gz'.format(basename)))

    xyz = np.ascontiguousarray(np.loadtxt(pos_path, skiprows=1).T)
    coeff = np.atleast_2d(np.loadtxt(coeff_path, skiprows=1))

    nmax = coeff[:,0].astype(int).max()
    lmax = coeff[:,1].astype(int).max()

    cos_coeff = np.zeros((nmax+1, lmax+1, lmax+1))
    sin_coeff = np.zeros((nmax+1, lmax+1, lmax+1))
    for row in coeff:
        n, l, m, cc, sc = row

        # transform from H&O 1992 coefficients to Lowing 2011 coefficients
        if l != 0:
            fac = np.sqrt(4*np.pi) * np.sqrt((2*l+1) / (4*np.pi) * factorial(l-m) / factorial(l+m))
            cc /= fac
            sc /= fac

        cos_coeff[int(n), int(l), int(m)] = cc
        sin_coeff[int(n), int(l), int(m)] = sc

    dens = density(xyz, M=1., r_s=1.,
                   Snlm=cos_coeff, Tnlm=sin_coeff)
コード例 #11
0
ファイル: vo_test.py プロジェクト: Cadair/astropy
def test_no_resource_check():
    output = io.StringIO()

    with catch_warnings():
        # We can't test xmllint, because we can't rely on it being on the
        # user's machine.
        result = validate(get_pkg_data_filename('data/no_resource.xml'),
                          output, xmllint=False)

    assert result is False

    output.seek(0)
    output = output.readlines()

    # Uncomment to generate new groundtruth
    # with open('no_resource.txt', 'wt', encoding='utf-8') as fd:
    #     fd.write(u''.join(output))

    with open(
        get_pkg_data_filename('data/no_resource.txt'),
            'rt', encoding='utf-8') as fd:
        truth = fd.readlines()

    truth = truth[1:]
    output = output[1:-1]

    sys.stdout.writelines(
        difflib.unified_diff(truth, output, fromfile='truth', tofile='output'))

    assert truth == output
コード例 #12
0
ファイル: test_pydl.py プロジェクト: weaverba137/pydl
 def test_file_lines(self):
     #
     # Find the test files
     #
     line_numbers = (1, 42, 137)
     plainfiles = [get_pkg_data_filename('t/this-file-contains-{0:d}-lines.txt'.format(l)) for l in line_numbers]
     gzfiles = [get_pkg_data_filename('t/this-file-contains-{0:d}-lines.txt.gz'.format(l)) for l in line_numbers]
     for i, p in enumerate(plainfiles):
         n = file_lines(p)
         assert n == line_numbers[i]
     for i, p in enumerate(gzfiles):
         n = file_lines(p, compress=True)
         assert n == line_numbers[i]
     #
     # Test list passing
     #
     n = file_lines(plainfiles)
     assert tuple(n) == line_numbers
     n = file_lines(gzfiles, compress=True)
     assert tuple(n) == line_numbers
     #
     # Make sure empty files work
     #
     n = file_lines(get_pkg_data_filename('t/this-file-is-empty.txt'))
     assert n == 0
コード例 #13
0
ファイル: load.py プロジェクト: rbuehler/gammapy
    def filenames():
        """Dictionary of available file names."""
        result = dict()
        result['psf'] = get_pkg_data_filename('data/fermi/psf.fits')
        result['counts'] = get_pkg_data_filename('data/fermi/fermi_counts.fits.gz')
        result['diffuse_model'] = get_pkg_data_filename('data/fermi/gll_iem_v02_cutout.fits')

        return result
コード例 #14
0
ファイル: core.py プロジェクト: adrn/SFD
def ebv(coordinate, order=1):
    """
    Return SFD E(B-V) at the input coordinate(s).

    Parameters
    ----------
    coordinate : :class:`~astropy.coordinates.SkyCoord`, :class:`~astropy.coordinates.BaseCoordinateFrame`
        The coordinate(s) to compute extinction at.
    order : int (optional)
        Passed to :func:`~scipy.ndimage.map_coordinates`.

    Returns
    -------
    EBV : :class:`~numpy.ndarray`
        Extinction at each input coordinate.

    Example
    -------
    TODO
    h, w = 1000, 4000
    b, l = numpy.mgrid[0:h,0:w]
    l = 180.-(l+0.5) / float(w) * 360.
    b = 90. - (b+0.5) / float(h) * 180.
    ebv = dust.getval(l, b)
    imshow(ebv, aspect='auto', norm=matplotlib.colors.LogNorm())
    """

    ngp_filename = get_pkg_data_filename("data/SFD_dust_4096_ngp.fits")
    sgp_filename = get_pkg_data_filename("data/SFD_dust_4096_sgp.fits")

    # convert input coordinate to Galactic frame
    gal = coordinate.transform_to(coord.Galactic)
    l = gal.l.wrap_at(180*u.degree).degree
    b = gal.b.degree

    # output extinctions
    EBV = np.zeros_like(l, dtype='f4') + np.nan

    b_gtr_zero = b >= 0.
    b_les_zero = np.logical_not(b_gtr_zero)
    if np.any(b_gtr_zero): # north
        hdulist = fits.open(ngp_filename)

        w = wcs.WCS(hdulist[0].header)
        x, y = w.wcs_world2pix(l[b_gtr_zero], b[b_gtr_zero], 0)
        EBV[b_gtr_zero] = map_coordinates(hdulist[0].data, [y, x], order=order, mode='nearest')
        hdulist.close()

    if np.any(b_les_zero): # south
        hdulist = fits.open(sgp_filename)

        w = wcs.WCS(hdulist[0].header)
        x, y = w.wcs_world2pix(l[b_les_zero], b[b_les_zero], 0)
        EBV[b_les_zero] = map_coordinates(hdulist[0].data, [y, x], order=order, mode='nearest')
        hdulist.close()

    return EBV
コード例 #15
0
ファイル: test_tables.py プロジェクト: pyvirtobs/pyvo
    def test_multiple_targettables(self):
        with pytest.warns(W12):
            vosi.parse_tables(get_pkg_data_filename(
                "data/tables/multiple_targettables.xml"))

        with pytest.raises(W12):
            vosi.parse_tables(get_pkg_data_filename(
                "data/tables/multiple_targettables.xml"),
                pedantic=True)
コード例 #16
0
ファイル: test_tables.py プロジェクト: pyvirtobs/pyvo
    def test_no_schemas(self):
        with pytest.warns(W14):
            vosi.parse_tables(
                get_pkg_data_filename("data/tables/no_schemas.xml"))

        with pytest.raises(W14):
            vosi.parse_tables(
                get_pkg_data_filename("data/tables/no_schemas.xml"),
                pedantic=True)
コード例 #17
0
ファイル: test_pm_cov_transform.py プロジェクト: adrn/gala
def setup_function(fn):
    ra, dec, pmra, pmdec = np.load(get_pkg_data_filename('c_pm.npy'))
    c = coord.SkyCoord(ra=ra*u.deg, dec=dec*u.deg,
                       pm_ra_cosdec=pmra*u.mas/u.yr,
                       pm_dec=pmdec*u.mas/u.yr)
    cov = np.load(get_pkg_data_filename('pm_cov.npy'))

    fn.c = c
    fn.cov = cov
コード例 #18
0
ファイル: test_tables.py プロジェクト: pyvirtobs/pyvo
    def test_tap_size(self):
        with pytest.warns(W03):
            vosi.parse_tables(get_pkg_data_filename(
                "data/tables/sizenegative.xml"))

        with pytest.raises(W03):
            vosi.parse_tables(get_pkg_data_filename(
                "data/tables/sizenegative.xml"),
                pedantic=True)
コード例 #19
0
ファイル: test_tables.py プロジェクト: pyvirtobs/pyvo
    def test_wrong_flag(self):
        with pytest.warns(W04):
            vosi.parse_tables(get_pkg_data_filename(
                "data/tables/wrong_flag.xml"))

        with pytest.raises(W04):
            vosi.parse_tables(get_pkg_data_filename(
                "data/tables/wrong_flag.xml"),
                pedantic=True)
コード例 #20
0
ファイル: test_tables.py プロジェクト: pyvirtobs/pyvo
    def test_multiple_schema_descriptions(self):
        with pytest.warns(W06):
            vosi.parse_tables(get_pkg_data_filename(
                "data/tables/multiple_schema_descriptions.xml"))

        with pytest.raises(W06):
            vosi.parse_tables(
                get_pkg_data_filename(
                    "data/tables/multiple_schema_descriptions.xml"),
                pedantic=True)
コード例 #21
0
ファイル: test_tables.py プロジェクト: pyvirtobs/pyvo
    def test_multiple_foreignkey_utypes(self):
        with pytest.warns(W09):
            vosi.parse_tables(get_pkg_data_filename(
                "data/tables/multiple_foreignkey_utypes.xml"))

        with pytest.raises(W09):
            vosi.parse_tables(
                get_pkg_data_filename(
                    "data/tables/multiple_foreignkey_utypes.xml"),
                pedantic=True)
コード例 #22
0
ファイル: test_core.py プロジェクト: PBarmby/reproject
def test_reproject_celestial_slices_2d():

    header_in = fits.Header.fromtextfile(get_pkg_data_filename('../../tests/data/gc_ga.hdr'))
    header_out = fits.Header.fromtextfile(get_pkg_data_filename('../../tests/data/gc_eq.hdr'))

    array_in = np.ones((700, 690))

    wcs_in = WCS(header_in)
    wcs_out = WCS(header_out)

    array_out = reproject_celestial(array_in, wcs_in, wcs_out, (660, 680))
コード例 #23
0
ファイル: test_io.py プロジェクト: TheRakken/gary
def test_read():
    potential = load(get_pkg_data_filename("Plummer.yml"))
    assert np.allclose(potential.parameters["m"], 100000000000.0)
    assert np.allclose(potential.parameters["b"], 0.26)

    potential = load(get_pkg_data_filename("HarmonicOscillator1D.yml"))
    assert potential.units is None

    potential = load(get_pkg_data_filename("Composite.yml"))
    assert "disk" in potential.keys()
    assert "halo" in potential.keys()
    assert str(potential) == "CompositePotential"
コード例 #24
0
def test_reproject():
    hdr1 = fits.Header.fromfile(get_pkg_data_filename('data/simple_wcs.hdr'))
    hdr2 = fits.Header.fromfile(get_pkg_data_filename('data/simple_wcs2.hdr'))
    w1 = fitswcs.WCS(hdr1)
    w2 = fitswcs.WCS(hdr2)
    gw2 = wcs.WCS(output_frame='icrs',
                  forward_transform=gwutil.make_fitswcs_transform(hdr2))
    func1 = reproject(w1, w2)
    func2 = reproject(w1, gw2)
    x1, y1 = func1(1, 2)
    x2, y2 = func2(1, 2)
    utils.assert_allclose(x1, x2, atol=10**-7)
    utils.assert_allclose(y1, y2, atol=10**-7)
コード例 #25
0
    def setup_class(self):

        self.header_in = fits.Header.fromtextfile(get_pkg_data_filename('../../tests/data/gc_ga.hdr'))
        self.header_out = fits.Header.fromtextfile(get_pkg_data_filename('../../tests/data/gc_eq.hdr'))

        self.header_out['NAXIS'] = 2
        self.header_out['NAXIS1'] = 600
        self.header_out['NAXIS2'] = 550

        self.array_in = np.ones((100, 100))

        self.wcs_in = WCS(self.header_in)
        self.wcs_out = WCS(self.header_out)
コード例 #26
0
ファイル: __init__.py プロジェクト: Cadair/gammapy
def fermi_galactic_center():
    """Fermi high-energy counts image of the Galactic center region.
    
    TODO: document energy band, region, content of the files. 
    
    Returns
    -------
    filenames : dict
        Dictionary with filenames for keys 'psf', 'counts'
    """
    filenames = dict()
    filenames['psf'] = get_pkg_data_filename('fermi/psf.fits')
    filenames['counts'] = get_pkg_data_filename('fermi/fermi_counts.fits.gz')

    return filenames
コード例 #27
0
ファイル: test_ds9_language.py プロジェクト: sargas/regions
def test_galactic(filename):
    filename = get_pkg_data_filename(filename)
    regs = read_ds9(filename)

    actual = ds9_objects_to_string(regs, coordsys='galactic', fmt='.2f', radunit='arcsec')

    # Use this to produce reference file for now
    # print(actual)
    # 1 / 0

    reference_file = get_pkg_data_filename('data/galactic_reference.reg')
    with open(reference_file, 'r') as fh:
        desired = fh.read()

    assert actual == desired
コード例 #28
0
ファイル: test_ds9_language.py プロジェクト: sargas/regions
def test_physical(filename):
    filename = get_pkg_data_filename(filename)
    regs = read_ds9(filename)

    actual = ds9_objects_to_string(regs, coordsys='physical', fmt='.2f')

    # Use this to produce reference file for now
    # print(actual)
    # 1 / 0

    reference_file = get_pkg_data_filename('data/physical_reference.reg')
    with open(reference_file, 'r') as fh:
        desired = fh.read()

    assert actual == desired
コード例 #29
0
ファイル: DQInspect.py プロジェクト: pllim/stginga
    def _load_dqparser(self, instrument):
        """Create new DQParser for given instrument."""
        dqdict = self.settings.get('dqdict', self._def_dqdict)

        if instrument not in dqdict:
            self.logger.warn(
                '{0} is not supported, using default'.format(instrument))
            return self._def_parser

        try:
            dqfile = get_pkg_data_filename(dqdict[instrument],
                                           package='stginga')
        except Exception as e:
            dqfile = dqdict[instrument]
            if os.path.isfile(dqfile):
                self.logger.info('Using external data {0}'.format(dqfile))
            else:
                self.logger.warn('{0} not found for {1}, using default'.format(
                    dqfile, instrument))
                dqfile = None
        else:
            self.logger.info('Using package data {0}'.format(dqfile))

        if dqfile is None:
            return self._def_parser

        try:
            dqp = utils.DQParser(dqfile)
        except Exception as e:
            self.logger.warn('Cannot extract DQ info from {0}, using '
                             'default'.format(dqfile))
            dqp = self._def_parser

        return dqp
コード例 #30
0
    def setUp(self):
        resultfile = get_pkg_data_filename(ssaresultfile)
        self.tbl = votableparse(resultfile)
        self.result = ssa.SSAResults(self.tbl)
        self.rec = self.result.getrecord(0)

        self.outdir = tempfile.mkdtemp()
コード例 #31
0
ファイル: table_test.py プロジェクト: jvictor42/astropy
 def test_pedantic_true(self):
     with pytest.raises(AstropyDeprecationWarning):
         with pytest.raises(VOWarning):
             parse(get_pkg_data_filename('data/gemini.xml'), pedantic=True)
コード例 #32
0
from astropy import units as u
from astropy.wcs import WCS
import pylab as pl
from astropy.io import fits
from astropy.utils.data import get_pkg_data_filename
import numpy as np
from matplotlib_scalebar.scalebar import ScaleBar

#Establishing file names & paths
nh3_11 = "/Users/Josh/W51/data/nh3_11_m0.fits"
par_maps = "/Users/Josh/W51/data/par_maps.fits"
################################################


base = get_pkg_data_filename(nh3_11)
base_hdu = fits.open(base)[0]
base_wcs = WCS(base_hdu.header)
cube = get_pkg_data_filename(par_maps)
cube_hdu = fits.open(cube)[0]
cube_wcs = WCS(cube_hdu.header)

ax = pl.subplot(projection=base_wcs.celestial)
ax.set(xlim=(30,265), ylim=(50,250))
ax.coords[0].set_ticks_visible(False)
ax.coords[1].set_ticks_visible(False)
ax.coords[0].set_ticklabel_visible(False)
ax.coords[1].set_ticklabel_visible(False)
pl.imshow(base_hdu.data, origin='lower')
ax.contour(cube_hdu.data[2,:,:], levels=[15.5,16,16.5,17,17.5,18], colors='white', alpha=0.8)

pl.show()
コード例 #33
0
ファイル: table_test.py プロジェクト: jvictor42/astropy
 def test_conf_verify_warn(self):
     with conf.set_temp('verify', 'warn'):
         with pytest.warns(VOWarning) as w:
             parse(get_pkg_data_filename('data/gemini.xml'))
         assert len(w) == 24
コード例 #34
0
ファイル: test_wcs.py プロジェクト: zkurtz/astropy
def test_validate_with_2_wcses():
    # From Issue #2053
    results = wcs.validate(get_pkg_data_filename("data/2wcses.hdr"))

    assert "WCS key 'A':" in str(results)
コード例 #35
0
ファイル: test_wcs.py プロジェクト: zkurtz/astropy
 def setup(self):
     fname = get_pkg_data_filename('data/header_with_time.fits')
     self.header = fits.Header.fromfile(fname)
     self.w = wcs.WCS(self.header, key='A')
コード例 #36
0
ファイル: test_class.py プロジェクト: nstarman/skypy
import numpy as np
from astropy.cosmology import Planck15
from astropy.units import allclose
from astropy import units as u
from astropy.utils.data import get_pkg_data_filename
import pytest

# load the external class result to test against
class_result_filename = get_pkg_data_filename('data/class_result.txt')
test_pzk = np.loadtxt(class_result_filename)

# try to import the requirement, if it doesn't exist, skip test
try:
    __import__('classy')
except ImportError:
    CLASS_NOT_FOUND = True
else:
    CLASS_NOT_FOUND = False


@pytest.mark.skipif(CLASS_NOT_FOUND, reason='classy not found')
def test_classy():
    '''
    Test a default astropy cosmology
    '''
    from skypy.power_spectrum import classy

    Pl15massless = Planck15.clone(name='Planck 15 massless neutrino', m_nu=[0., 0., 0.]*u.eV)

    redshift = [0.0, 1.0]
    wavenumber = np.logspace(-4.0, np.log10(2.0), 200)
コード例 #37
0
ファイル: test_parametric.py プロジェクト: kabartay/gammapy
    def test_info(self, psf):
        info_str = open(get_pkg_data_filename("data/psf_info.txt")).read()

        print(psf.info())
        assert psf.info() == info_str
コード例 #38
0
import numpy as np
from astropy.utils.data import get_pkg_data_filename
import pytest
from ..targetpixelfile import KeplerTargetPixelFile, KeplerQualityFlags


filename_tpf_all_zeros = get_pkg_data_filename("data/test-tpf-all-zeros.fits")
filename_tpf_one_center = get_pkg_data_filename("data/test-tpf-non-zero-center.fits")


def test_tpf_shapes():
    """Are the data array shapes of the TargetPixelFile object consistent?"""
    tpf = KeplerTargetPixelFile(filename_tpf_all_zeros)
    assert tpf.quality_mask.shape == tpf.hdu[1].data['TIME'].shape
    assert tpf.flux.shape == tpf.flux_err.shape

def test_tpf_zeros():
    """Does the LightCurve of a zero-flux TPF make sense?"""
    tpf = KeplerTargetPixelFile(filename_tpf_all_zeros, quality_bitmask=None)
    lc = tpf.to_lightcurve()
    # If you don't mask out bad data, time contains NaNs
    assert np.any(lc.time != tpf.time)  # Using the property that NaN does not equal NaN
    #When you do mask out bad data everything should work.
    tpf = KeplerTargetPixelFile(filename_tpf_all_zeros, quality_bitmask='hard')
    lc = tpf.to_lightcurve()
    assert len(lc.time) == len(lc.flux)
    assert np.all(lc.time == tpf.time)
    assert np.all(lc.flux == 0)
    # The default QUALITY bitmask should have removed all NaNs in the TIME
    assert ~np.any(np.isnan(tpf.time))
コード例 #39
0
def test_sff_corrector():
    """Does our code agree with the example presented in Vanderburg
    and Johnson (2014)?"""
    # The following csv file, provided by Vanderburg and Johnson
    # at https://www.cfa.harvard.edu/~avanderb/k2/ep60021426.html,
    # contains the results of applying SFF to EPIC 60021426.
    fn = get_pkg_data_filename('../../tests/data/ep60021426alldiagnostics.csv')
    data = np.genfromtxt(fn, delimiter=',', skip_header=1)
    mask = data[:, -2] == 0  # indicates whether the thrusters were on or off
    time = data[:, 0]
    raw_flux = data[:, 1]
    corrected_flux = data[:, 2]
    centroid_col = data[:, 3]
    centroid_row = data[:, 4]

    # NOTE: we need a small number of windows below because this test data set
    # is unusually short, i.e. has an unusually small number of cadences.
    lc = LightCurve(time=time, flux=raw_flux, flux_err=np.ones(len(raw_flux)) * 0.0001)
    sff = SFFCorrector(lc)
    corrected_lc = sff.correct(centroid_col=centroid_col,
                               centroid_row=centroid_row,
                               restore_trend=True,
                               windows=1)
    assert (np.isclose(corrected_flux, corrected_lc.flux, atol=0.001).all())
    assert len(sff.window_points) == 0  # expect 0 break points for 1 window

    # masking
    corrected_lc = sff.correct(centroid_col=centroid_col,
                               centroid_row=centroid_row,
                               windows=3,
                               restore_trend=True,
                               cadence_mask=mask)
    assert (np.isclose(corrected_flux, corrected_lc.flux, atol=0.001).all())
    assert len(sff.window_points) == 2  # expect 2 break points for 3 windows

    # masking and breakindex
    corrected_lc = sff.correct(centroid_col=centroid_col,
                               centroid_row=centroid_row,
                               windows=3,
                               restore_trend=True,
                               cadence_mask=mask)
    assert (np.isclose(corrected_flux, corrected_lc.flux, atol=0.001).all())

    # masking and breakindex and iters
    corrected_lc = sff.correct(centroid_col=centroid_col,
                               centroid_row=centroid_row, windows=3, restore_trend=True,
                               cadence_mask=mask, niters=3)
    assert (np.isclose(corrected_flux, corrected_lc.flux, atol=0.001).all())

    # masking and breakindex and bins
    corrected_lc = sff.correct(centroid_col=centroid_col,
                               centroid_row=centroid_row, windows=3, restore_trend=True,
                               cadence_mask=mask, bins=5)
    assert (np.isclose(corrected_flux, corrected_lc.flux, atol=0.001).all())
    assert np.all((sff.lc.flux_err/sff.corrected_lc.flux_err) == 1)


    # masking and breakindex and bins and propagate_errors
    corrected_lc = sff.correct(centroid_col=centroid_col,
                               centroid_row=centroid_row, windows=3, restore_trend=True,
                               cadence_mask=mask, bins=5, propagate_errors=True)
    assert (np.isclose(corrected_flux, corrected_lc.flux, atol=0.001).all())
    assert np.all((sff.lc.flux_err/sff.corrected_lc.flux_err) < 1)

    # test using KeplerLightCurve interface
    klc = KeplerLightCurve(time=time,
                           flux=raw_flux,
                           flux_err=np.ones(len(raw_flux)) * 0.0001,
                           centroid_col=centroid_col,
                           centroid_row=centroid_row)
    sff = klc.to_corrector("sff")
    klc = sff.correct(windows=3, restore_trend=True)
    assert (np.isclose(corrected_flux, klc.flux, atol=0.001).all())

    # Can plot
    sff.diagnose()
コード例 #40
0
 def setup_class(self):
     self.region_file = get_pkg_data_filename(
         'data/ds9.fits.reg', package='regions.io.ds9.tests')
     self.arr = np.ones((1024, 1024))
     self.raw_regions = Regions.read(self.region_file, format='ds9')
コード例 #41
0
ファイル: iers.py プロジェクト: matkadoor/astropy
__all__ = [
    'Conf', 'conf', 'earth_orientation_table', 'IERS', 'IERS_B', 'IERS_A',
    'IERS_Auto', 'FROM_IERS_B', 'FROM_IERS_A', 'FROM_IERS_A_PREDICTION',
    'TIME_BEFORE_IERS_RANGE', 'TIME_BEYOND_IERS_RANGE', 'IERS_A_FILE',
    'IERS_A_URL', 'IERS_A_URL_MIRROR', 'IERS_A_README', 'IERS_B_FILE',
    'IERS_B_URL', 'IERS_B_README', 'IERSRangeError', 'IERSStaleWarning',
    'LeapSeconds', 'IERS_LEAP_SECOND_FILE', 'IERS_LEAP_SECOND_URL',
    'IETF_LEAP_SECOND_URL'
]

# IERS-A default file name, URL, and ReadMe with content description
IERS_A_FILE = 'finals2000A.all'
IERS_A_URL = 'ftp://*****:*****@gdc.cddis.eosdis.nasa.gov/pub/products/iers/finals2000A.all'
IERS_A_URL_MIRROR = 'https://datacenter.iers.org/data/9/finals2000A.all'
IERS_A_README = get_pkg_data_filename('data/ReadMe.finals2000A')

# IERS-B default file name, URL, and ReadMe with content description
IERS_B_FILE = get_pkg_data_filename('data/eopc04_IAU2000.62-now')
IERS_B_URL = 'http://hpiers.obspm.fr/iers/eop/eopc04/eopc04_IAU2000.62-now'
IERS_B_README = get_pkg_data_filename('data/ReadMe.eopc04_IAU2000')

# LEAP SECONDS default file name, URL, and alternative format/URL
IERS_LEAP_SECOND_FILE = get_pkg_data_filename('data/Leap_Second.dat')
IERS_LEAP_SECOND_URL = 'https://hpiers.obspm.fr/iers/bul/bulc/Leap_Second.dat'
IETF_LEAP_SECOND_URL = 'https://www.ietf.org/timezones/data/leap-seconds.list'

# Status/source values returned by IERS.ut1_utc
FROM_IERS_B = 0
FROM_IERS_A = 1
FROM_IERS_A_PREDICTION = 2
コード例 #42
0
    def test_all(self):
        capabilities = vosi.parse_capabilities(
            get_pkg_data_filename("data/capabilities.xml"))

        assert equals(capabilities[0].standardid,
                      "ivo://ivoa.net/std/VOSI#availability")
        assert type(capabilities[0].interfaces[0]) == vs.ParamHTTP
        assert capabilities[0].interfaces[0].accessurls[0].use == "full"
        assert equals(capabilities[0].interfaces[0].accessurls[0].content,
                      "http://example.org/tap/availability")

        assert equals(capabilities[1].standardid,
                      "ivo://ivoa.net/std/VOSI#capabilities")
        assert type(capabilities[1].interfaces[0]) == vs.ParamHTTP
        assert capabilities[1].interfaces[0].accessurls[0].use == "full"
        assert equals(capabilities[1].interfaces[0].accessurls[0].content,
                      "http://example.org/tap/capabilities")

        assert capabilities[2].standardid == "ivo://ivoa.net/std/VOSI#tables"
        assert type(capabilities[2].interfaces[0]) == vs.ParamHTTP
        assert capabilities[2].interfaces[0].accessurls[0].use == "full"
        assert equals(capabilities[2].interfaces[0].accessurls[0].content,
                      "http://example.org/tap/tables")

        assert type(capabilities[3]) == tr.TableAccess
        assert capabilities[3].standardid == "ivo://ivoa.net/std/TAP"
        assert capabilities[3].interfaces[0].accessurls[0].use == "base"
        assert equals(capabilities[3].interfaces[0].accessurls[0].content,
                      "http://example.org/tap")

        assert equals(capabilities[3].datamodels[0].ivo_id,
                      "ivo://ivoa.net/std/ObsCore#table-1.1")
        assert capabilities[3].datamodels[0].content == "Obscore-1.1"

        assert equals(capabilities[3].datamodels[1].ivo_id,
                      "ivo://ivoa.net/std/RegTAP#1.0")
        assert capabilities[3].datamodels[1].content == "Registry 1.0"

        assert capabilities[3].languages[0].name == "ADQL"
        assert equals(capabilities[3].languages[0].versions[0].ivo_id,
                      "ivo://ivoa.net/std/ADQL#v2.0")
        assert capabilities[3].languages[0].versions[0].content == "2.0"
        assert capabilities[3].languages[0].description == "ADQL 2.0"

        assert equals(
            capabilities[3].languages[0].languagefeaturelists[0].type,
            "ivo://ivoa.net/std/TAPRegExt#features-udf")
        assert equals(
            capabilities[3].languages[0].languagefeaturelists[0][0].form,
            "form 1")
        assert equals(
            capabilities[3].languages[0].languagefeaturelists[0]
            [0].description, "description 1")
        assert equals(
            capabilities[3].languages[0].languagefeaturelists[0][1].form,
            "form 2")
        assert equals(
            capabilities[3].languages[0].languagefeaturelists[0].features[1].
            description, "description 2")

        assert equals(
            capabilities[3].languages[0].languagefeaturelists[1].type,
            "ivo://ivoa.net/std/TAPRegExt#features-adqlgeo")
        assert equals(
            capabilities[3].languages[0].languagefeaturelists[1].features[0].
            form, "BOX")
        assert equals(
            capabilities[3].languages[0].languagefeaturelists[1].features[1].
            form, "POINT")

        assert equals(capabilities[3].outputformats[0].ivo_id,
                      "ivo://ivoa.net/std/TAPRegExt#output-votable-binary")
        assert capabilities[3].outputformats[0].mime == "text/xml"

        assert capabilities[3].outputformats[1].ivo_id is None
        assert capabilities[3].outputformats[1].mime == "text/html"

        assert equals(capabilities[3].uploadmethods[0].ivo_id,
                      "ivo://ivoa.net/std/TAPRegExt#upload-https")
        assert equals(capabilities[3].uploadmethods[1].ivo_id,
                      "ivo://ivoa.net/std/TAPRegExt#upload-inline")

        assert capabilities[3].retentionperiod.default == 172800
        assert capabilities[3].executionduration.default == 3600

        assert capabilities[3].outputlimit.default.unit == "row"
        assert capabilities[3].outputlimit.default.content == 2000

        assert capabilities[3].outputlimit.hard.unit == "row"
        assert capabilities[3].outputlimit.hard.content == 10000000

        assert capabilities[3].uploadlimit.hard.unit == "byte"
        assert capabilities[3].uploadlimit.hard.content == 100000000
コード例 #43
0
p0 = 1.013250e5 * u.Pa
rho0 = 1.2250 * u.K
T0 = 288.15 * u.K
g0 = 9.80665 * u.m / u.s ** 2
S = 110.4 * u.K
Ti = 273.15 * u.K
beta = 1.458e-6 * u.kg / u.s / u.m / u.K ** (0.5)
_gamma = 1.4
sigma = 3.65e-10 * u.m
N = 6.02257e26 * (u.kg * u.mol) ** -1
R = 8314.32 * u.J / u.kg / u.K
R_air = 287.053 * u.J / u.kg / u.K
alpha = 34.1632 * u.K / u.km

# Reading layer parameters file
coesa_file = get_pkg_data_filename("data/coesa62.dat")
coesa62_data = ascii.read(coesa_file)
b_levels = coesa62_data["b"].data
zb_levels = coesa62_data["Zb [km]"].data * u.km
hb_levels = coesa62_data["Hb [km]"].data * u.km
Tb_levels = coesa62_data["Tb [K]"].data * u.K
Lb_levels = coesa62_data["Lb [K/km]"].data * u.K / u.km
pb_levels = coesa62_data["pb [mbar]"].data * u.mbar


class COESA62(COESA):
    """ Holds the model for U.S Standard Atmosphere 1962. """

    def __init__(self):
        """ Constructor for the class. """
        super().__init__(
コード例 #44
0
from astropy.io import fits
from astropy import wcs
from astropy.io.fits.card import UNDEFINED
import astropy.units as u
from astropy.utils.exceptions import AstropyWarning

from ..targetpixelfile import KeplerTargetPixelFile, TargetPixelFileFactory
from ..targetpixelfile import TessTargetPixelFile, TargetPixelFile
from ..lightcurve import TessLightCurve
from ..utils import LightkurveWarning, LightkurveDeprecationWarning
from ..io import read
from ..search import search_tesscut

from .test_synthetic_data import filename_synthetic_flat

filename_tpf_all_zeros = get_pkg_data_filename("data/test-tpf-all-zeros.fits")
filename_tpf_one_center = get_pkg_data_filename("data/test-tpf-non-zero-center.fits")
filename_tess = get_pkg_data_filename("data/tess25155310-s01-first-cadences.fits.gz")

TABBY_Q8 = ("https://archive.stsci.edu/missions/kepler/lightcurves"
            "/0084/008462852/kplr008462852-2011073133259_llc.fits")
TABBY_TPF = ("https://archive.stsci.edu/missions/kepler/target_pixel_files"
             "/0084/008462852/kplr008462852-2011073133259_lpd-targ.fits.gz")
TESS_SIM = ("https://archive.stsci.edu/missions/tess/ete-6/tid/00/000"
            "/004/176/tess2019128220341-0000000417699452-0016-s_tp.fits")
asteroid_TPF = get_pkg_data_filename("data/asteroid_test.fits")


@pytest.mark.remote_data
def test_load_bad_file():
    '''Test if a light curve can be opened without exception.'''
コード例 #45
0
def map2alm(
    maps,
    lmax=None,
    mmax=None,
    iter=3,
    pol=True,
    use_weights=False,
    datapath=None,
    gal_cut=0,
    use_pixel_weights=False,
    verbose=True,
):
    """Computes the alm of a Healpix map. The input maps must all be
    in ring ordering.

    For recommendations about how to set `lmax`, `iter`, and weights, see the
    `Anafast documentation <https://healpix.sourceforge.io/html/fac_anafast.htm>`

    Pixel values are weighted before applying the transform:

    * when you don't specify any weights, the uniform weight value 4*pi/n_pix is used
    * with ring weights enabled (use_weights=True), pixels in every ring
      are weighted with a uniform value similar to the one above, ring weights are
      included in healpy
    * with pixel weights (use_pixel_weights=True), every pixel gets an individual weight

    Pixel weights provide the most accurate transform, so you should always use them if
    possible. However they are not included in healpy and will be automatically downloaded
    and cached in ~/.astropy the first time you compute a trasform at a specific nside.

    If datapath is specified, healpy will first check that local folder before downloading
    the weights.
    The easiest way to setup the folder is to clone the healpy-data repository:

    git clone --depth 1 https://github.com/healpy/healpy-data
    cd healpy-data
    bash download_weights_8192.sh

    and set datapath to the root of the repository.

    Parameters
    ----------
    maps : array-like, shape (Npix,) or (n, Npix)
      The input map or a list of n input maps. Must be in ring ordering.
    lmax : int, scalar, optional
      Maximum l of the power spectrum. Default: 3*nside-1
    mmax : int, scalar, optional
      Maximum m of the alm. Default: lmax
    iter : int, scalar, optional
      Number of iteration (default: 3)
    pol : bool, optional
      If True, assumes input maps are TQU. Output will be TEB alm's.
      (input must be 1 or 3 maps)
      If False, apply spin 0 harmonic transform to each map.
      (input can be any number of maps)
      If there is only one input map, it has no effect. Default: True.
    use_weights: bool, scalar, optional
      If True, use the ring weighting. Default: False.
    datapath : None or str, optional
      If given, the directory where to find the pixel weights.
      See in the docstring above details on how to set it up.
    gal_cut : float [degrees]
      pixels at latitude in [-gal_cut;+gal_cut] are not taken into account
    use_pixel_weights: bool, optional
      If True, use pixel by pixel weighting, healpy will automatically download the weights, if needed
    verbose : bool, optional
      Deprecated, has not effect.

    Returns
    -------
    alms : array or tuple of array
      alm or a tuple of 3 alm (almT, almE, almB) if polarized input.

    Notes
    -----
    The pixels which have the special `UNSEEN` value are replaced by zeros
    before spherical harmonic transform. They are converted back to `UNSEEN`
    value, so that the input maps are not modified. Each map have its own,
    independent mask.
    """
    maps = ma_to_array(maps)
    info = maptype(maps)
    nside = pixelfunc.get_nside(maps)
    check_max_nside(nside)

    pixel_weights_filename = None
    if use_pixel_weights:
        if use_weights:
            raise RuntimeError("Either use pixel or ring weights")
        filename = "full_weights/healpix_full_weights_nside_%04d.fits" % nside
        if datapath is not None:
            pixel_weights_filename = os.path.join(datapath, filename)
            if os.path.exists(pixel_weights_filename):
                log.info("Accessing pixel weights from %s", pixel_weights_filename)
            else:
                raise RuntimeError(
                    "You specified datapath but pixel weights file"
                    "is missing at {}".format(pixel_weights_filename)
                )
        if pixel_weights_filename is None:
            with data.conf.set_temp("dataurl", DATAURL), data.conf.set_temp(
                "dataurl_mirror", DATAURL_MIRROR
            ), data.conf.set_temp("remote_timeout", 30):
                pixel_weights_filename = data.get_pkg_data_filename(
                    filename, package="healpy"
                )

    if pol or info in (0, 1):
        alms = _sphtools.map2alm(
            maps,
            niter=iter,
            datapath=datapath,
            use_weights=use_weights,
            lmax=lmax,
            mmax=mmax,
            gal_cut=gal_cut,
            pixel_weights_filename=pixel_weights_filename,
        )
    else:
        # info >= 2 and pol is False : spin 0 spht for each map
        alms = [
            _sphtools.map2alm(
                mm,
                niter=iter,
                datapath=datapath,
                use_weights=use_weights,
                lmax=lmax,
                mmax=mmax,
                gal_cut=gal_cut,
                pixel_weights_filename=pixel_weights_filename,
            )
            for mm in maps
        ]
    return np.array(alms)
コード例 #46
0
 def test_str(self, ref):
     actual = str(self.cat[ref["idx"]])
     expected = open(get_pkg_data_filename(ref["str_ref_file"])).read()
     assert actual == expected
コード例 #47
0
ファイル: test_wcs.py プロジェクト: zkurtz/astropy
def test_all_world2pix(fname=None,
                       ext=0,
                       tolerance=1.0e-4,
                       origin=0,
                       random_npts=25000,
                       adaptive=False,
                       maxiter=20,
                       detect_divergence=True):
    """Test all_world2pix, iterative inverse of all_pix2world"""

    # Open test FITS file:
    if fname is None:
        fname = get_pkg_data_filename('data/j94f05bgq_flt.fits')
        ext = ('SCI', 1)
    if not os.path.isfile(fname):
        raise OSError(
            "Input file '{:s}' to 'test_all_world2pix' not found.".format(
                fname))
    h = fits.open(fname)
    w = wcs.WCS(h[ext].header, h)
    h.close()
    del h

    crpix = w.wcs.crpix
    ncoord = crpix.shape[0]

    # Assume that CRPIX is at the center of the image and that the image has
    # a power-of-2 number of pixels along each axis. Only use the central
    # 1/64 for this testing purpose:
    naxesi_l = list((7. / 16 * crpix).astype(int))
    naxesi_u = list((9. / 16 * crpix).astype(int))

    # Generate integer indices of pixels (image grid):
    img_pix = np.dstack(
        [i.flatten() for i in np.meshgrid(*map(range, naxesi_l, naxesi_u))])[0]

    # Generage random data (in image coordinates):
    with NumpyRNGContext(123456789):
        rnd_pix = np.random.rand(random_npts, ncoord)

    # Scale random data to cover the central part of the image
    mwidth = 2 * (crpix * 1. / 8)
    rnd_pix = crpix - 0.5 * mwidth + (mwidth - 1) * rnd_pix

    # Reference pixel coordinates in image coordinate system (CS):
    test_pix = np.append(img_pix, rnd_pix, axis=0)
    # Reference pixel coordinates in sky CS using forward transformation:
    all_world = w.all_pix2world(test_pix, origin)

    try:
        runtime_begin = datetime.now()
        # Apply the inverse iterative process to pixels in world coordinates
        # to recover the pixel coordinates in image space.
        all_pix = w.all_world2pix(all_world,
                                  origin,
                                  tolerance=tolerance,
                                  adaptive=adaptive,
                                  maxiter=maxiter,
                                  detect_divergence=detect_divergence)
        runtime_end = datetime.now()
    except wcs.wcs.NoConvergence as e:
        runtime_end = datetime.now()
        ndiv = 0
        if e.divergent is not None:
            ndiv = e.divergent.shape[0]
            print(f"There are {ndiv} diverging solutions.")
            print("Indices of diverging solutions:\n{}".format(e.divergent))
            print("Diverging solutions:\n{}\n".format(
                e.best_solution[e.divergent]))
            print("Mean radius of the diverging solutions: {}".format(
                np.mean(np.linalg.norm(e.best_solution[e.divergent], axis=1))))
            print("Mean accuracy of the diverging solutions: {}\n".format(
                np.mean(np.linalg.norm(e.accuracy[e.divergent], axis=1))))
        else:
            print("There are no diverging solutions.")

        nslow = 0
        if e.slow_conv is not None:
            nslow = e.slow_conv.shape[0]
            print("There are {} slowly converging solutions.".format(nslow))
            print("Indices of slowly converging solutions:\n{}".format(
                e.slow_conv))
            print("Slowly converging solutions:\n{}\n".format(
                e.best_solution[e.slow_conv]))
        else:
            print("There are no slowly converging solutions.\n")

        print("There are {} converged solutions.".format(
            e.best_solution.shape[0] - ndiv - nslow))
        print("Best solutions (all points):\n{}".format(e.best_solution))
        print(f"Accuracy:\n{e.accuracy}\n")
        print("\nFinished running 'test_all_world2pix' with errors.\n"
              "ERROR: {}\nRun time: {}\n".format(e.args[0],
                                                 runtime_end - runtime_begin))
        raise e

    # Compute differences between reference pixel coordinates and
    # pixel coordinates (in image space) recovered from reference
    # pixels in world coordinates:
    errors = np.sqrt(np.sum(np.power(all_pix - test_pix, 2), axis=1))
    meanerr = np.mean(errors)
    maxerr = np.amax(errors)
    print("\nFinished running 'test_all_world2pix'.\n"
          "Mean error = {:e}  (Max error = {:e})\n"
          "Run time: {}\n".format(meanerr, maxerr,
                                  runtime_end - runtime_begin))

    assert (maxerr < 2.0 * tolerance)
コード例 #48
0
def wcs():
    filename = get_pkg_data_filename('data/example_header.fits')
    header = fits.getheader(filename)
    return WCS(header)
コード例 #49
0
ファイル: test_wcs.py プロジェクト: zkurtz/astropy
def test_load_fits_path():
    fits_name = get_pkg_data_filename('data/sip.fits')
    w = wcs.WCS(fits_name)
コード例 #50
0
def test_xz(filename):
    t_comp = read(get_pkg_data_filename(filename))
    t_uncomp = read(get_pkg_data_filename(filename.replace('.xz', '')))
    assert t_comp.dtype.names == t_uncomp.dtype.names
    assert np.all(t_comp.as_array() == t_uncomp.as_array())
コード例 #51
0
 def test_str(self):
     actual = str(self.cat["3FHL J2301.9+5855e"])  # an extended source
     expected = open(get_pkg_data_filename("data/3fhl_j2301.9+5855e.txt")).read()
     assert actual == expected
コード例 #52
0
#
# Plot DS9 regions in a Ginga viewer
#
# NOTE: You need the Astropy "regions" package for this to work.
#
from ginga import toolkit

toolkit.use('qt5')

from astropy.utils.data import get_pkg_data_filename
import regions

from ginga.gw import sv
from ginga.util import ap_region

vf = sv.ViewerFactory()
v = vf.make_viewer(name="Ginga regions example", width=1000, height=1000)

image_file = get_pkg_data_filename('tutorials/FITS-images/HorseHead.fits')
v.load(image_file)

ds9_file = get_pkg_data_filename('data/plot_image.reg',
                                 package='regions.io.ds9.tests')
regs = regions.read_ds9(ds9_file)

canvas = v.add_canvas()
for i, reg in enumerate(regs):
    ap_region.add_region(canvas, reg)

vf.mainloop()
コード例 #53
0
ファイル: table_test.py プロジェクト: jvictor42/astropy
 def test_conf_verify_exception(self):
     with conf.set_temp('verify', 'exception'):
         with pytest.raises(VOWarning):
             parse(get_pkg_data_filename('data/gemini.xml'))
コード例 #54
0
 def setup_class(self):
     bandfile = get_pkg_data_filename(
         os.path.join('data', 'hst_acs_hrc_f555w.fits'))
     self.bp = SpectralElement.from_file(bandfile)
コード例 #55
0
ファイル: table_test.py プロジェクト: jvictor42/astropy
 def test_conf_verify_ignore(self):
     with conf.set_temp('verify', 'ignore'):
         parse(get_pkg_data_filename('data/gemini.xml'))
コード例 #56
0
 def setup_class(self):
     specfile = get_pkg_data_filename(
         os.path.join('data', 'hst_acs_hrc_f555w_x_grw70d5824.fits'))
     self.sp = SourceSpectrum.from_file(specfile)
コード例 #57
0
ファイル: table_test.py プロジェクト: jvictor42/astropy
 def test_pedantic_false(self):
     with pytest.warns(VOWarning) as w:
         parse(get_pkg_data_filename('data/gemini.xml'), pedantic=False)
     assert len(w) == 25
コード例 #58
0
import numpy as np
from astropy.cosmology import Planck15
from astropy.units import allclose
from astropy.utils.data import get_pkg_data_filename
import pytest

# load the external camb result to test against
camb_result_filename = get_pkg_data_filename('data/camb_result.txt')
test_pkz = np.loadtxt(camb_result_filename, delimiter=',')

# try to import the requirement, if it doesn't exist, skip test
try:
    __import__('camb')
except ImportError:
    CAMB_NOT_FOUND = True
else:
    CAMB_NOT_FOUND = False


@pytest.mark.skipif(CAMB_NOT_FOUND, reason='CAMB not found')
def test_camb():
    '''
    Test a default astropy cosmology
    '''
    from skypy.power_spectrum import camb

    # test shape and compare with the mocked power spectrum
    redshift = [0.0, 1.0]
    wavenumber = np.logspace(-4.0, np.log10(2.0), 200)
    pkz = camb(wavenumber, redshift, Planck15, 2.e-9, 0.965)
    assert pkz.shape == (len(redshift), len(wavenumber))
コード例 #59
0
    def test_info(self, psf):
        filename = get_pkg_data_filename("data/psf_info.txt")
        info_str = open(filename, "r").read()

        assert psf.info() == info_str
コード例 #60
0
def test_flattened_hernquist():
    """
    This test compares the coefficients against some computed in the mathematica
    notebook 'flattened-hernquist.nb'. nmax and lmax here must match nmax and lmax
    in that notebook.
    """

    coeff_path = os.path.abspath(get_pkg_data_filename('data/Snlm-mathematica.csv'))

    G = 1.
    M = 1
    a = 1.
    q = 0.9

    # Note: this must be the same as in the mathematica notebook
    nmax = 8
    lmax = 8

    (Snlm,Serr),(Tnlm,Terr) = compute_coeffs(flattened_hernquist_density,
                                             nmax=nmax, lmax=lmax, skip_odd=True, skip_m=True,
                                             M=M, r_s=a, args=(M,a,q))

    for l in range(1, lmax+1, 2):
        for m in range(lmax+1):
            assert Snlm[0,l,m] == 0.

    m_Snl0 = np.loadtxt(coeff_path, delimiter=',')
    m_Snl0 = m_Snl0[:,::2] # every other l

    assert np.allclose(Snlm[0,::2,0], m_Snl0[0])

    # check that random points match in gradient and density
    np.random.seed(42)
    n_test = 1024
    r = 10.*np.cbrt(np.random.uniform(0.1**3,1,size=n_test)) # 1 to 10
    t = np.arccos(2*np.random.uniform(size=n_test) - 1)
    ph = np.random.uniform(0, 2*np.pi, size=n_test)
    x = r*np.cos(ph)*np.sin(t)
    y = r*np.sin(ph)*np.sin(t)
    z = r*np.cos(t)
    xyz = np.vstack((x, y, z))

    # confirmed by testing...
    tru_dens = flattened_hernquist_density(xyz[0], xyz[1], xyz[2], M, a, q)
    bfe_dens = density(np.ascontiguousarray(xyz.T), Snlm, Tnlm, M, a)
    assert np.all((np.abs(bfe_dens - tru_dens) / tru_dens) < 0.05) # <5%

    tru_grad = np.array([flattened_hernquist_gradient(xyz[0,i], xyz[1,i], xyz[2,i], G, M, a, q)
                        for i in range(xyz.shape[1])]).T
    bfe_grad = gradient(np.ascontiguousarray(xyz.T), Snlm, Tnlm, G, M, a).T

    # check what typical errors are
    # for j in range(3):
    #     pl.hist(np.abs((bfe_grad[j]-tru_grad[j])/tru_grad[j]))

    for j in range(3):
        assert np.all(np.abs((bfe_grad[j]-tru_grad[j])/tru_grad[j]) < 0.005) # 0.5%

    return

    # ------------------------------------------------------------------------
    # plots:

    # coefficients
    fig,ax = pl.subplots(1,1,figsize=(10,8))
    n,l = np.mgrid[:nmax+1, :lmax+1]
    c = ax.scatter(n.ravel(), l.ravel(), c=Snlm[:,:,0].ravel(), s=64,
                   norm=mpl.colors.SymLogNorm(1E-5), cmap='RdBu_r',
                   vmin=-100, vmax=100, linewidths=1., edgecolors='#666666')

    ax.xaxis.set_ticks(np.arange(0,nmax+1,1))
    ax.yaxis.set_ticks(np.arange(0,lmax+1,1))

    ax.set_xlim(-0.5, nmax+0.5)
    ax.set_ylim(-0.5, lmax+0.5)

    ax.set_xlabel('$n$')
    ax.set_ylabel('$l$')

    tickloc = np.concatenate((-10.**np.arange(2,-5-1,-1),
                              10.**np.arange(-5,2+1,1)))
    fig.colorbar(c, ticks=tickloc, format='%.0e')
    fig.tight_layout()

    # contour plot in r,t at ph=0

    rgrid = np.logspace(-1, 1., 128)
    tgrid = np.linspace(0, np.pi, 128)

    r,t = np.meshgrid(rgrid,tgrid)
    x = r*np.sin(t)
    z = r*np.cos(t)

    _xyz = np.vstack((x.ravel(),np.zeros_like(x.ravel()),z.ravel()))
    bfe_dens = density(np.ascontiguousarray(_xyz.T), Snlm, Tnlm, M, a)
    true_dens = flattened_hernquist_density(_xyz[0], _xyz[1], _xyz[2], M, a, q)

    fig,ax = pl.subplots(1, 1, figsize=(8,8))

    levels = 10**np.linspace(-4.5, 1, 16)
    ax.contour(np.log10(r), t, true_dens.reshape(x.shape),
               levels=levels, colors='k',
               locator=mpl.ticker.LogLocator(), label='True')
    ax.contour(np.log10(r), t, bfe_dens.reshape(x.shape),
               levels=levels, colors='r',
               locator=mpl.ticker.LogLocator(), label='BFE')

    ax.legend()
    fig.tight_layout()

    pl.show()