Пример #1
0
    def test_redshift(self):
        """Test SourceSpectrum apply_redshift() method."""
        # Zero redshift should return the same spectrum.
        sp_z0 = self.sp.apply_redshift(0)
        np.testing.assert_array_equal(sp_z0.wave.value, self.sp.wave.value)
        np.testing.assert_array_equal(sp_z0.flux.value, self.sp.flux.value)
        assert sp_z0.wave.unit == self.sp.wave.unit
        assert sp_z0.flux.unit == self.sp.flux.unit
        assert sp_z0.metadata['expr'] != self.sp.metadata['expr']
        assert sp_z0.metadata['FILENAME'] == self.sp.metadata['FILENAME']

        # Non-zero redshift (length)
        sp_zlen = sp_z0.apply_redshift(1.65)
        np.testing.assert_array_equal(
            sp_zlen.wave.value, sp_z0.wave.value * 2.65)
        np.testing.assert_array_equal(sp_zlen.flux.value, sp_z0.flux.value)

        # Non-zero redshift (frequency).
        # Should give same result as length after conversion.
        sp_z0.convert_wave(u.Hz)
        sp_zfrq = sp_z0.apply_redshift(1.65)
        np.testing.assert_array_equal(sp_zfrq.flux.value, sp_z0.flux.value)
        sp_zfrq.convert_wave(sp_zlen.wave.unit)
        np.testing.assert_allclose(
            sp_zfrq.wave.value, sp_zlen.wave.value, rtol=1e-6)
        assert sp_zfrq.metadata['expr'] == sp_zlen.metadata['expr']

        # Exceptions
        with pytest.raises(exceptions.SynphotError):
            sp_zlen = sp_z0.apply_redshift([1, 2, 3])
        with pytest.raises(exceptions.SynphotError):
            sp_zlen = sp_z0.apply_redshift(u.Quantity(2))
Пример #2
0
def test_load_bad(tmpdir):
    meta = dict(group_name='g', band_name='b')
    # Missing wavelength column.
    table = astropy.table.QTable(meta=meta)
    table['response'] = [1, 1]
    name = str(tmpdir.join('bad.ecsv'))
    table.write(name, format='ascii.ecsv', overwrite=True)
    with pytest.raises(RuntimeError):
        load_filter(name)
    # Missing response column.
    table = astropy.table.QTable(meta=meta)
    table['wavelength'] = [1, 2] * u.Angstrom
    name = str(tmpdir.join('bad.ecsv'))
    table.write(name, format='ascii.ecsv', overwrite=True)
    with pytest.raises(RuntimeError):
        load_filter(name)
    # Missing wavelength units.
    table = astropy.table.QTable(meta=meta)
    table['wavelength'] = [1, 2]
    table['response'] = [1, 1]
    name = str(tmpdir.join('bad.ecsv'))
    table.write(name, format='ascii.ecsv', overwrite=True)
    with pytest.raises(RuntimeError):
        load_filter(name)
    # Unexpected response units.
    table = astropy.table.QTable(meta=meta)
    table['wavelength'] = [1, 2] * u.Angstrom
    table['response'] = [1, 1] * u.erg
    name = str(tmpdir.join('bad.ecsv'))
    table.write(name, format='ascii.ecsv', overwrite=True)
    with pytest.raises(RuntimeError):
        load_filter(name)
Пример #3
0
 def test_payload_invalid_item2(self):
     with pytest.raises(TypeError):
         self.payload['l']
     payload = self.Payload(self.payload.words.copy(), bps=8,
                            sample_shape=(2,), complex_data=False)
     with pytest.raises(TypeError):
         payload['l'] = 1
Пример #4
0
def test_set_We(particle_dists):
    """
    test sync calculation
    """
    from ..models import Synchrotron, PionDecay

    ECPL, PL, BPL = particle_dists

    sy = Synchrotron(ECPL, B=1 * u.G, **electron_properties)
    pp = PionDecay(ECPL)

    W = 1e49 * u.erg

    Eemax = 100 * u.TeV
    for Eemin in [1 * u.GeV, 10 * u.GeV, None]:
        for Eemax in [100 * u.TeV, None]:
            sy.set_We(W, Eemin, Eemax)
            assert_allclose(W, sy.compute_We(Eemin, Eemax))
            sy.set_We(W, Eemin, Eemax, amplitude_name='amplitude')
            assert_allclose(W, sy.compute_We(Eemin, Eemax))

            pp.set_Wp(W, Eemin, Eemax)
            assert_allclose(W, pp.compute_Wp(Eemin, Eemax))
            pp.set_Wp(W, Eemin, Eemax, amplitude_name='amplitude')
            assert_allclose(W, pp.compute_Wp(Eemin, Eemax))

    with pytest.raises(AttributeError):
        sy.set_We(W, amplitude_name='norm')

    with pytest.raises(AttributeError):
        pp.set_Wp(W, amplitude_name='norm')
Пример #5
0
def test_load_filter():
    load_filter('sdss2010-r', load_from_cache=False, verbose=True)
    load_filter('sdss2010-r', load_from_cache=True, verbose=True)
    with pytest.raises(ValueError):
        load_filter('none')
    with pytest.raises(ValueError):
        load_filter('none.dat')
Пример #6
0
def test_create_deviation(ccd_data, u_image, u_gain, u_readnoise,
                          expect_succes):
    ccd_data.unit = u_image
    if u_gain:
        gain = 2.0 * u_gain
    else:
        gain = None
    readnoise = 5 * u_readnoise
    if expect_succes:
        ccd_var = create_deviation(ccd_data, gain=gain, readnoise=readnoise)
        assert ccd_var.uncertainty.array.shape == (10, 10)
        assert ccd_var.uncertainty.array.size == 100
        assert ccd_var.uncertainty.array.dtype == np.dtype(float)
        if gain:
            expected_var = np.sqrt(2 * ccd_data.data + 5 ** 2) / 2
        else:
            expected_var = np.sqrt(ccd_data.data + 5 ** 2)
        np.testing.assert_array_equal(ccd_var.uncertainty.array,
                                      expected_var)
        assert ccd_var.unit == ccd_data.unit
        # uncertainty should *not* have any units -- does it?
        with pytest.raises(AttributeError):
            ccd_var.uncertainty.array.unit
    else:
        with pytest.raises(u.UnitsError):
            ccd_var = create_deviation(ccd_data, gain=gain, readnoise=readnoise)
def test_large_scale_density_spherical_annulus_exception_handling():
    """
    """
    npts1, npts2 = 100, 200
    sample = generate_locus_of_3d_points(npts1, xc=0.1, yc=0.1, zc=0.1, seed=fixed_seed)
    tracers = generate_locus_of_3d_points(npts2, xc=0.15, yc=0.1, zc=0.1, seed=fixed_seed)
    inner_radius, outer_radius = 0.1, 0.2

    with pytest.raises(HalotoolsError) as err:
        result = large_scale_density_spherical_annulus(
            sample, tracers, inner_radius, outer_radius)
    substr = "If period is None, you must pass in ``sample_volume``."
    assert substr in err.value.args[0]

    with pytest.raises(HalotoolsError) as err:
        result = large_scale_density_spherical_annulus(
            sample, tracers, inner_radius, outer_radius, period=[1, 1])
    substr = "Input ``period`` must either be a float or length-3 sequence"
    assert substr in err.value.args[0]

    with pytest.raises(HalotoolsError) as err:
        result = large_scale_density_spherical_annulus(
            sample, tracers, inner_radius, outer_radius, period=1, sample_volume=0.4)
    substr = "If period is not None, do not pass in sample_volume"
    assert substr in err.value.args[0]

    with pytest.raises(HalotoolsError) as err:
        result = large_scale_density_spherical_annulus(
            sample, tracers, 0.5, outer_radius, period=1, sample_volume=0.4)
    substr = "Input ``outer_radius`` must be larger than input ``inner_radius``"
    assert substr in err.value.args[0]
    def test_add_ptclcat_to_cache1(self):
        """ Verify the overwrite requirement is enforced
        """
        ptclcat = UserSuppliedPtclCatalog(Lbox=200,
            particle_mass=100, redshift=self.redshift,
            **self.good_ptclcat_args)

        basename = 'abc'
        fname = os.path.join(self.dummy_cache_baseloc, basename)
        _t = Table({'x': [0]})
        _t.write(fname, format='ascii')
        assert os.path.isfile(fname)

        dummy_string = '  '
        with pytest.raises(HalotoolsError) as err:
            ptclcat.add_ptclcat_to_cache(
                fname, dummy_string, dummy_string, dummy_string)
        substr = "Either choose a different fname or set ``overwrite`` to True"
        assert substr in err.value.args[0]

        with pytest.raises(HalotoolsError) as err:
            ptclcat.add_ptclcat_to_cache(
                fname, dummy_string, dummy_string, dummy_string,
                overwrite=True)
        assert substr not in err.value.args[0]
Пример #9
0
    def test_payload(self):
        with open(SAMPLE_FILE, 'rb') as fh:
            fh.seek(16)  # skip header
            payload = mark5b.Mark5BPayload.fromfile(fh, nchan=8, bps=2)
        assert payload._size == 10000
        assert payload.size == 10000
        assert payload.shape == (5000, 8)
        assert payload.dtype == np.float32
        assert np.all(payload[:3].astype(int) ==
                      np.array([[-3, -1, +1, -1, +3, -3, -3, +3],
                                [-3, +3, -1, +3, -1, -1, -1, +1],
                                [+3, -1, +3, +3, +1, -1, +3, -1]]))
        with io.BytesIO() as s:
            payload.tofile(s)
            s.seek(0)
            payload2 = mark5b.Mark5BPayload.fromfile(s, payload.nchan,
                                                     payload.bps)
            assert payload2 == payload
            with pytest.raises(EOFError):
                # Too few bytes.
                s.seek(100)
                mark5b.Mark5BPayload.fromfile(s, payload.nchan, payload.bps)

        payload3 = mark5b.Mark5BPayload.fromdata(payload.data, bps=payload.bps)
        assert payload3 == payload
        with pytest.raises(ValueError):
            mark5b.Mark5BPayload.fromdata(np.zeros((5000, 8), np.complex64),
                                          bps=2)
def test_behroozi10_redshift_safety():
    """
    """
    model = Behroozi10SmHm()

    result0 = model.mean_log_halo_mass(11)
    result1 = model.mean_log_halo_mass(11, redshift=4)
    result2 = model.mean_log_halo_mass(11, redshift=sim_defaults.default_redshift)
    assert result0 == result2
    assert result0 != result1

    result0 = model.mean_stellar_mass(prim_haloprop=1e12)
    result1 = model.mean_stellar_mass(prim_haloprop=1e12, redshift=4)
    result2 = model.mean_stellar_mass(prim_haloprop=1e12, redshift=sim_defaults.default_redshift)
    assert result0 == result2
    assert result0 != result1

    model = Behroozi10SmHm(redshift=sim_defaults.default_redshift)
    result0 = model.mean_log_halo_mass(11)
    with pytest.raises(HalotoolsError):
        result1 = model.mean_log_halo_mass(11, redshift=4)
    result2 = model.mean_log_halo_mass(11, redshift=model.redshift)
    assert result0 == result2

    result0 = model.mean_stellar_mass(prim_haloprop=1e12)
    with pytest.raises(HalotoolsError):
        result1 = model.mean_stellar_mass(prim_haloprop=1e12, redshift=4)
    result2 = model.mean_stellar_mass(prim_haloprop=1e12, redshift=model.redshift)
    assert result0 == result2
Пример #11
0
def test_should_not_create_dir():
	""" Require that attempting to create a cache subdirectory 
	for an unsupported simulation and/or halo-finder raises an IOError. 
	"""
	with pytest.raises(IOError) as exc:
		parent_dir = cache_config.get_catalogs_dir('raw_halos')
		nonsense_dirname = 'JoseCanseco'
		func = cache_config.cache_subdir_for_simulation
		s1 = func(parent_dir, nonsense_dirname)

	exception_string = ("It is not permissible to create a subdirectory of " + 
		"Halotools cache \nfor simulations which have no class defined in " + 
		"the halotools/sim_manager/supported_sims module. \n")
	assert exc.value.args[0] == exception_string

	with pytest.raises(IOError) as exc:
		parent_dir = cache_config.get_catalogs_dir('raw_halos')
		nonsense_dirname = 'JoseCanseco'
		func = cache_config.cache_subdir_for_halo_finder
		s1 = func(parent_dir, 'bolshoi', nonsense_dirname)
	exception_string = ("It is not permissible to create a subdirectory of "
                "Halotools cache \nfor a combination of "
                "simulation + halo-finder which has no corresponding class defined in "
                "the halotools/sim_manager/supported_sims module. \n")
	assert exc.value.args[0] == exception_string
Пример #12
0
    def test_add_entry_to_cache_log(self):
        cache = HaloTableCache(read_log_from_standard_loc=False)
        assert len(cache.log) == 0

        with pytest.raises(TypeError) as err:
            cache.add_entry_to_cache_log('abc', update_ascii=False)
        substr = "You can only add instances of HaloTableCacheLogEntry to the cache log"
        assert substr in err.value.args[0]

        cache.add_entry_to_cache_log(self.good_log_entry, update_ascii=False)
        assert len(cache.log) == 1

        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")
            cache.add_entry_to_cache_log(self.good_log_entry, update_ascii=False)
            substr = "cache log already contains the entry"
            assert substr in str(w[-1].message)
        assert len(cache.log) == 1

        cache.add_entry_to_cache_log(self.good_log_entry2, update_ascii=False)
        assert len(cache.log) == 2

        with pytest.raises(InvalidCacheLogEntry) as err:
            cache.add_entry_to_cache_log(self.bad_log_entry, update_ascii=False)
        substr = "The input filename does not exist."
        assert substr in err.value.args[0]
Пример #13
0
 def test_payload(self):
     with open(SAMPLE_FILE, 'rb') as fh:
         fh.seek(0xa88)
         header = mark4.Mark4Header.fromfile(fh, ntrack=64, decade=2010)
         payload = mark4.Mark4Payload.fromfile(fh, header)
     assert payload.size == (20000 - 160) * 64 // 8
     assert payload.shape == ((20000 - 160) * 4, 8)
     assert payload.dtype == np.float32
     assert np.all(payload.data[0].astype(int) ==
                   np.array([-1, +1, +1, -3, -3, -3, +1, -1]))
     assert np.all(payload.data[1].astype(int) ==
                   np.array([+1, +1, -3, +1, +1, -3, -1, -1]))
     with io.BytesIO() as s:
         payload.tofile(s)
         s.seek(0)
         payload2 = mark4.Mark4Payload.fromfile(s, header)
         assert payload2 == payload
         with pytest.raises(EOFError):
             # Too few bytes.
             s.seek(100)
             mark4.Mark4Payload.fromfile(s, header)
     payload3 = mark4.Mark4Payload.fromdata(payload.data, header)
     assert payload3 == payload
     with pytest.raises(ValueError):
         # Wrong number of channels.
         mark4.Mark4Payload.fromdata(np.empty((payload.shape[0], 2)),
                                     header)
     with pytest.raises(ValueError):
         # Too few data.
         mark4.Mark4Payload.fromdata(payload.data[:100], header)
Пример #14
0
    def test_run_advanced(self, tmpdir):
        temp_path = os.path.join(str(tmpdir), "temp")
        log_path = os.path.join(str(tmpdir), "log")
        paths = {"temp": temp_path, "log": log_path}
        pipe = pipeline.Pipeline(paths=paths, create_paths=True)
        pipe.add_step(test_func1, ["func1"], var1=3, var2=4)
        pipe.add_step(test_func2, ["func2"], var1=25, var2=10)
        pipe.add_step(test_func2, ["func2"], var1=1, var2=0)
        pipe.add_step(test_func3, var1=1, var2=0)

        with pytest.raises(pipeline.PipelineError):
            pipe.run()
        pipe = dill.load(open(os.path.join(paths["log"], "pipeline.p"), "rb"))
        assert pipe.run_step_idx == 2
        assert pipe.steps[0].results == {"next_id": 4, "status": "success", "step_id": 0, "sum": 7}

        with pytest.raises(ZeroDivisionError):
            for step in pipe.steps:
                step.results = None
            pipe.run(resume=True, ignore_errors=True)

        new_pipe = dill.load(open(os.path.join(paths["log"], "pipeline.p"), "rb"))
        result = new_pipe.run(start_idx=1, ignore_errors=True, ignore_exceptions=True)
        assert result["status"] == "success"
        assert new_pipe.steps[0].results == None
        assert new_pipe.steps[1].results == {"diff": 2.5, "status": "success"}
        assert new_pipe.steps[2].results == {"error": "Division by 0", "status": "error"}
        assert new_pipe.steps[3].results["status"] == "error"
Пример #15
0
def test_DataStore_filenames(data_manager):
    """Check if filenames are constructed correctly"""
    data_store = data_manager['hess-hap-hd-prod01-std_zeta_fullEnclosure']

    filename = data_store.filename(obs_id=23037, filetype='aeff')
    assert filename == '/Users/deil/work/_Data/hess/fits/hap-hd/fits_prod01/std_zeta_fullEnclosure/run023000-023199/run023037/hess_aeff_023037.fits.gz'

    filename = data_store.filename(obs_id=23037, filetype='aeff', abspath=False)
    assert filename == 'run023000-023199/run023037/hess_aeff_023037.fits.gz'

    with pytest.raises(IndexError) as exc:
        data_store.filename(obs_id=89565, filetype='aeff')
    msg = 'File not in table: OBS_ID = 89565, TYPE = aeff'
    assert exc.value.args[0] == msg

    with pytest.raises(ValueError):
        data_store.filename(obs_id=89565, filetype='effective area')

    data_store = data_manager['hess-paris-prod02']

    filename = data_store.filename(obs_id=23037, filetype='aeff')
    assert filename == '/Users/deil/work/_Data/hess/fits/parisanalysis/fits_prod02/pa/Model_Deconvoluted_Prod26/Mpp_Std/run023000-023199/run023037/hess_aeff_2d_023037.fits.gz'

    filename = data_store.filename(obs_id=23037, filetype='aeff', abspath=False)
    assert filename == 'run023000-023199/run023037/hess_aeff_2d_023037.fits.gz'
Пример #16
0
 def test_seek(self):
     with sf.open(self.files) as fh:
         fh.seek(self.offsets[1])
         assert fh.file_nr == 1
         assert fh.tell() == self.offsets[1]
         fh.seek(self.offsets[1] + 1)
         assert fh.file_nr == 1
         fh.seek(self.offsets[2])
         assert fh.file_nr == 2
         fh.seek(self.offsets[3])
         assert fh.tell() == self.size
         assert fh.file_nr == 2
         fh.seek(self.size)
         assert fh.file_nr == 2
         fh.seek(10, 2)
         assert fh.file_nr == 2
         assert fh.tell() == self.size + 10
         with pytest.raises(OSError):
             fh.seek(-3)
         fh.seek(-3, 2)
         assert fh.tell() == self.size - 3
         assert fh.file_nr == 2
         fh.seek(-5, 1)
         assert fh.tell() == self.size - 3 - 5
         assert fh.file_nr == 1
         with pytest.raises(ValueError):
             fh.seek(-5, -1)
         with pytest.raises(ValueError):
             fh.seek(-5, 3)
     # cannot seek closed file
     with pytest.raises(ValueError):
         fh.seek(10)
Пример #17
0
def test_parse_output_projection(tmpdir):

    header = fits.Header.fromtextfile(get_pkg_data_filename('data/gc_ga.hdr'))
    wcs = WCS(header)

    # As header

    with pytest.raises(ValueError) as exc:
        parse_output_projection(header)
    assert exc.value.args[0] == "Need to specify shape since output header does not contain complete shape information"

    parse_output_projection(header, shape_out=(200, 200))

    header['NAXIS'] = 2
    header['NAXIS1'] = 200
    header['NAXIS2'] = 300

    parse_output_projection(header)

    # As WCS

    with pytest.raises(ValueError) as exc:
        parse_output_projection(wcs)
    assert exc.value.args[0] == "Need to specify shape when specifying output_projection as WCS object"

    parse_output_projection(wcs, shape_out=(200, 200))
Пример #18
0
    def test_write(self, tmpdir):
        self._setup(tmpdir)
        with sf.open(self.files, 'wb', file_size=10) as fh:
            fh.write(self.data[:5])
            assert fh.tell() == 5
            assert fh.file_nr == 0
            assert self.files_exist() == [True, False, False]
            fh.write(self.data[5:20])
            assert fh.tell() == 20
            assert fh.file_nr == 1
            assert self.files_exist() == [True, True, False]
            fh.write(self.data[20:])
            assert fh.tell() == len(self.data)
            assert fh.file_nr == 2

        # Cannot write to closed file.
        with pytest.raises(ValueError):
            fh.write(b' ')

        assert self.files_exist() == [True, True, True]
        with sf.open(self.files, 'rb') as fh:
            assert fh.read() == self.data

        with pytest.raises(OSError):
            with sf.open(self.files, 'wb', file_size=10) as fh:
                fh.write(b' ' * (len(self.files) * 10 + 1))
Пример #19
0
    def test_memmap(self, tmpdir):
        self._setup(tmpdir)
        data = self.uint8_data
        with sf.open(self.files, 'w+b', file_size=10) as fh:
            mm = fh.memmap(shape=(5,))
            assert fh.tell() == 5
            mm[:] = data[:5]
            mm2 = fh.memmap(offset=5, shape=(5,))
            mm2[:4] = data[5:9]
            mm2[-1] = data[-1]
            mm3 = fh.memmap(shape=(5,))
            mm3[:] = data[10:15]
            with pytest.raises(ValueError):
                fh.memmap(shape=(6,))  # beyond file.
            with pytest.raises(ValueError):
                fh.memmap()  # Need to pass in shape
            with pytest.raises(ValueError):
                fh.memmap(offset=4)  # Cannot seek
            mm4 = fh.memmap(dtype=np.uint16, shape=(2,))
            mm4[:] = data[15:19].view(np.uint16)

        assert self.files_exist() == [True, True, False]
        with sf.open(self.files[:2], 'rb') as fh:
            check = fh.read()
        assert len(check) == 19
        assert check[:9] == self.data[:9]
        assert check[9] == self.data[-1]
        assert check[10:] == self.data[10:19]
Пример #20
0
def test_build_data_table():
    ene = np.logspace(-2,2,20) * u.TeV
    flux = (ene/(1*u.TeV))**-2 * u.Unit('1/(cm2 s TeV)')
    flux_error_hi = 0.2 * flux
    flux_error_lo = 0.1 * flux
    ul = np.zeros(len(ene))
    ul[0] = 1

    dene = generate_energy_edges(ene)

    table = build_data_table(ene, flux, flux_error_hi=flux_error_hi, flux_error_lo=flux_error_lo, ul=ul)
    table = build_data_table(ene, flux, flux_error_hi=flux_error_hi, flux_error_lo=flux_error_lo, ul=ul, cl=0.99)
    table = build_data_table(ene, flux, flux_error=flux_error_hi, energy_width=dene[0])
    table = build_data_table(ene, flux, flux_error=flux_error_hi, energy_lo=(ene-dene[0]), energy_hi=(ene+dene[1]))

    # no flux_error
    with pytest.raises(TypeError):
        table = build_data_table(ene, flux)

    # errors in energy physical type validation
    with pytest.raises(TypeError):
        table = build_data_table(ene.value, flux, flux_error=flux_error_hi)

    with pytest.raises(TypeError):
        table = build_data_table(ene.value*u.Unit('erg/(cm2 s)'), flux, flux_error=flux_error_hi)
Пример #21
0
    def test_memmap(self):
        with sf.open(self.files) as fh:
            mm = fh.memmap(offset=0, shape=(5,))
            assert fh.tell() == 5
            assert (mm == self.uint8_data[:5]).all()
            mm = fh.memmap(shape=(5,))
            assert fh.tell() == 10
            assert (mm == self.uint8_data[5:10]).all()
            with pytest.raises(ValueError):
                fh.memmap(offset=7, shape=(5,))
            offset = self.offsets[1]
            fh.seek(offset)
            mm = fh.memmap(shape=5)
            assert (mm == self.uint8_data[offset:offset+5]).all()
            fh.seek(-2, 2)
            mm = fh.memmap()
            assert (mm == self.uint8_data[-2:]).all()
            fh.seek(-4, 2)
            mm = fh.memmap(mode='r', dtype=np.uint16)
            assert (mm == self.uint8_data[-4:].view(np.uint16)).all()
            fh.seek(-3, 2)
            with pytest.raises(ValueError):
                fh.memmap(dtype=np.uint16)

        with pytest.raises(ValueError):  # file closed.
            fh.memmap(offset=0, shape=(5,))
Пример #22
0
def test_celestial_mismatch_3d():
    """
    Make sure an error is raised if the input image has celestial WCS
    information and the output does not (and vice-versa). This example will
    use the _reproject_full route.
    """

    hdu_in = fits.open(os.path.join(DATA, 'equatorial_3d.fits'))[0]

    header_out = hdu_in.header.copy()
    header_out['CTYPE1'] = 'APPLES'
    header_out['CTYPE2'] = 'ORANGES'
    header_out['CTYPE3'] = 'BANANAS'

    data = hdu_in.data
    wcs1 = WCS(hdu_in.header)
    wcs2 = WCS(header_out)

    with pytest.raises(ValueError) as exc:
        array_out, footprint_out = reproject_interp((data, wcs1), wcs2, shape_out=(1, 2, 3))
    assert exc.value.args[0] == "Input WCS has celestial components but output WCS does not"

    with pytest.raises(ValueError) as exc:
        array_out, footprint_out = reproject_interp((data, wcs2), wcs1, shape_out=(1, 2, 3))
    assert exc.value.args[0] == "Output WCS has celestial components but input WCS does not"
Пример #23
0
def test_time_inputs():
    """
    Test validation and conversion of inputs for equinox and obstime attributes.
    """
    from astropy.time import Time
    from astropy.coordinates.builtin_frames import FK4

    c = FK4(1 * u.deg, 2 * u.deg, equinox='J2001.5', obstime='2000-01-01 12:00:00')
    assert c.equinox == Time('J2001.5')
    assert c.obstime == Time('2000-01-01 12:00:00')

    with pytest.raises(ValueError) as err:
        c = FK4(1 * u.deg, 2 * u.deg, equinox=1.5)
    assert 'Invalid time input' in str(err)

    with pytest.raises(ValueError) as err:
        c = FK4(1 * u.deg, 2 * u.deg, obstime='hello')
    assert 'Invalid time input' in str(err)

    # A vector time should work if the shapes match, but we don't automatically
    # broadcast the basic data (just like time).
    FK4([1, 2] * u.deg, [2, 3] * u.deg, obstime=['J2000', 'J2001'])
    with pytest.raises(ValueError) as err:
        FK4(1 * u.deg, 2 * u.deg, obstime=['J2000', 'J2001'])
    assert 'shape' in str(err)
Пример #24
0
def test_different_wcs_types():
    inp_cube = np.arange(3, dtype='float').repeat(4*5).reshape(3,4,5)
    header_in = fits.Header.fromtextfile(get_pkg_data_filename('../../tests/data/cube.hdr'))

    header_out = header_in.copy()
    header_out['CTYPE3'] = 'VRAD'
    header_out['CUNIT3'] = 'm/s'
    header_in['CTYPE3'] = 'VELO'
    header_in['CUNIT3'] = 'm/s'
    
    wcs_in = WCS(header_in)
    wcs_out = WCS(header_out)

    with pytest.raises(ValueError) as ex:
        out_cube, out_cube_valid = _reproject_celestial(inp_cube, wcs_in, wcs_out, (2, 4, 5))
    assert str(ex.value) == ("The input and output spectral coordinate types "
                             "are not equivalent.")

    header_in['CTYPE3'] = 'FREQ'
    header_in['CUNIT3'] = 'Hz'
    wcs_in = WCS(header_in)

    with pytest.raises(ValueError) as ex:
        out_cube, out_cube_valid = _reproject_celestial(inp_cube, wcs_in, wcs_out, (2, 4, 5))
    assert str(ex.value) == ("The input and output WCS are not equivalent")
Пример #25
0
def test_invalid_source():
    buff = io.BytesIO()

    ff = asdf.AsdfFile(_get_small_tree())
    ff.write_to(buff)

    buff.seek(0)
    ff2 = asdf.AsdfFile.read(buff)

    ff2.blocks.get_block(0)

    with pytest.raises(ValueError):
        ff2.blocks.get_block(2)

    with pytest.raises(IOError):
        ff2.blocks.get_block("http://127.0.0.1/")

    with pytest.raises(TypeError):
        ff2.blocks.get_block(42.0)

    with pytest.raises(ValueError):
        ff2.blocks.get_source(42.0)

    block = ff2.blocks.get_block(0)
    assert ff2.blocks.get_source(block) == 0
Пример #26
0
def test_query_region_radius_error(patch_post, coordinates, radius, equinox, epoch):
    with pytest.raises(u.UnitsError):
        result1 = simbad.core.Simbad.query_region(coordinates, radius=radius,
                                                  equinox=equinox, epoch=epoch)
    with pytest.raises(u.UnitsError):
        result2 = simbad.core.Simbad().query_region(coordinates, radius=radius,
                                                    equinox=equinox, epoch=epoch)
    def test_initializing_from_table_file_that_does_not_exist(self,
                                                              triage_setup,
                                                              tmpdir):
        log = tmpdir.join('tmp.log')

        self._setup_logger(log.strpath)

        # Do we get a warning if we try reading a file that doesn't exist,
        # but where we can initialize from a directory?
        ic = image_collection.ImageFileCollection(
            location=triage_setup.test_dir,
            info_file='iufadsdhfasdifre')

        with open(log.strpath) as f:
            warnings = f.readlines()

        assert (len(warnings) == 1)
        is_in = ['unable to open table file' in w  for w in warnings]
        assert all(is_in)
        # Do we raise an error if the table name is bad AND the location
        # is None?
        with pytest.raises(IOError):
            ic = image_collection.ImageFileCollection(location=None,
                                         info_file='iufadsdhfasdifre')
        # Do we raise an error if the table name is bad AND
        # the location is given but is bad?
        with pytest.raises(OSError):
            ic = image_collection.ImageFileCollection(location='dasifjoaurun',
                                         info_file='iufadsdhfasdifre')
Пример #28
0
def test_equivalent_frames():
    from astropy.coordinates import SkyCoord
    from astropy.coordinates.builtin_frames import ICRS, FK4, FK5, AltAz

    i = ICRS()
    i2 = ICRS(1*u.deg, 2*u.deg)
    assert i.is_equivalent_frame(i)
    assert i.is_equivalent_frame(i2)
    with pytest.raises(TypeError):
        assert i.is_equivalent_frame(10)
    with pytest.raises(TypeError):
        assert i2.is_equivalent_frame(SkyCoord(i2))

    f0 = FK5()  # this J2000 is TT
    f1 = FK5(equinox='J2000')
    f2 = FK5(1*u.deg, 2*u.deg, equinox='J2000')
    f3 = FK5(equinox='J2010')
    f4 = FK4(equinox='J2010')

    assert f1.is_equivalent_frame(f1)
    assert not i.is_equivalent_frame(f1)
    assert f0.is_equivalent_frame(f1)
    assert f1.is_equivalent_frame(f2)
    assert not f1.is_equivalent_frame(f3)
    assert not f3.is_equivalent_frame(f4)

    aa1 = AltAz()
    aa2 = AltAz(obstime='J2010')

    assert aa2.is_equivalent_frame(aa2)
    assert not aa1.is_equivalent_frame(i)
    assert not aa1.is_equivalent_frame(aa2)
Пример #29
0
def test_ic_seed_fluxes(particle_dists):
    """
    test per seed flux computation
    """
    from ..models import InverseCompton

    _, PL, _ = particle_dists

    ic = InverseCompton(
        PL,
        seed_photon_fields=['CMB',
                            ['test', 5000 * u.K, 0],
                            ['test2', 5000 * u.K, 10 * u.eV / u.cm**3],
                            ['test3', 5000 * u.K, 10 * u.eV / u.cm**3, 90 *
                             u.deg],],)

    ene = np.logspace(-3, 0, 5) * u.TeV

    for idx, name in enumerate(['CMB', 'test', 'test2', 'test3',]):
        icname = ic.sed(ene, seed=name)
        icnumber = ic.sed(ene, seed=idx)
        assert_allclose(icname, icnumber)

    with pytest.raises(ValueError):
        _ = ic.sed(ene, seed='FIR')

    with pytest.raises(ValueError):
        _ = ic.sed(ene, seed=10)
Пример #30
0
def test_spectral_mismatch_3d():
    """
    Make sure an error is raised if there are mismatches between the presence
    or type of spectral axis.
    """

    hdu_in = fits.open(os.path.join(DATA, 'equatorial_3d.fits'))[0]

    header_out = hdu_in.header.copy()
    header_out['CTYPE3'] = 'FREQ'
    header_out['CUNIT3'] = 'Hz'

    data = hdu_in.data
    wcs1 = WCS(hdu_in.header)
    wcs2 = WCS(header_out)

    with pytest.raises(ValueError) as exc:
        array_out, footprint_out = reproject_interp((data, wcs1), wcs2, shape_out=(1, 2, 3))
    assert exc.value.args[0] == "The input (VOPT) and output (FREQ) spectral coordinate types are not equivalent."

    header_out['CTYPE3'] = 'BANANAS'
    wcs2 = WCS(header_out)

    with pytest.raises(ValueError) as exc:
        array_out, footprint_out = reproject_interp((data, wcs1), wcs2, shape_out=(1, 2, 3))
    assert exc.value.args[0] == "Input WCS has a spectral component but output WCS does not"

    with pytest.raises(ValueError) as exc:
        array_out, footprint_out = reproject_interp((data, wcs2), wcs1, shape_out=(1, 2, 3))
    assert exc.value.args[0] == "Output WCS has a spectral component but input WCS does not"
def test_representation():
    """
    Test the getter and setter properties for `representation`
    """
    from astropy.coordinates.builtin_frames import ICRS

    # Create the frame object.
    icrs = ICRS(ra=1*u.deg, dec=1*u.deg)
    data = icrs.data

    # Create some representation objects.
    icrs_cart = icrs.cartesian
    icrs_spher = icrs.spherical

    # Testing when `_representation` set to `CartesianRepresentation`.
    icrs.representation_type = r.CartesianRepresentation

    assert icrs.representation_type == r.CartesianRepresentation
    assert icrs_cart.x == icrs.x
    assert icrs_cart.y == icrs.y
    assert icrs_cart.z == icrs.z
    assert icrs.data == data

    # Testing that an ICRS object in CartesianRepresentation must not have spherical attributes.
    for attr in ('ra', 'dec', 'distance'):
        with pytest.raises(AttributeError) as err:
            getattr(icrs, attr)
        assert 'object has no attribute' in str(err.value)

    # Testing when `_representation` set to `CylindricalRepresentation`.
    icrs.representation_type = r.CylindricalRepresentation

    assert icrs.representation_type == r.CylindricalRepresentation
    assert icrs.data == data

    # Testing setter input using text argument for spherical.
    icrs.representation_type = 'spherical'

    assert icrs.representation_type is r.SphericalRepresentation
    assert icrs_spher.lat == icrs.dec
    assert icrs_spher.lon == icrs.ra
    assert icrs_spher.distance == icrs.distance
    assert icrs.data == data

    # Testing that an ICRS object in SphericalRepresentation must not have cartesian attributes.
    for attr in ('x', 'y', 'z'):
        with pytest.raises(AttributeError) as err:
            getattr(icrs, attr)
        assert 'object has no attribute' in str(err.value)

    # Testing setter input using text argument for cylindrical.
    icrs.representation_type = 'cylindrical'

    assert icrs.representation_type is r.CylindricalRepresentation
    assert icrs.data == data

    with pytest.raises(ValueError) as err:
        icrs.representation_type = 'WRONG'
    assert 'but must be a BaseRepresentation class' in str(err.value)

    with pytest.raises(ValueError) as err:
        icrs.representation_type = ICRS
    assert 'but must be a BaseRepresentation class' in str(err.value)
Пример #32
0
 def test_init_with_inf_segment(self):
     segment_size = np.inf
     with pytest.raises(ValueError):
         assert AveragedPowerspectrum(self.lc, segment_size)
Пример #33
0
 def test_init_with_none_segment(self):
     segment_size = None
     with pytest.raises(TypeError):
         assert AveragedPowerspectrum(self.lc, segment_size)
Пример #34
0
 def test_init_without_segment(self):
     with pytest.raises(TypeError):
         assert AveragedPowerspectrum(self.lc)
Пример #35
0
 def test_classical_significances_fails_in_rms(self):
     ps = Powerspectrum(lc=self.lc, norm="frac")
     with pytest.raises(ValueError):
         ps.classical_significances()
Пример #36
0
 def test_fractional_rms_fails_when_rms_not_leahy(self):
     with pytest.raises(Exception):
         ps = Powerspectrum(lc=self.lc, norm="rms")
         rms_ps, rms_err = ps.compute_rms(min_freq=ps.freq[0],
                                          max_freq=ps.freq[-1])
Пример #37
0
def test_EffectiveAreaTable2D_generic():
    # This tests NDData subclassing. Not needed for other IRF classes

    # Exercise __init__  method
    energy = np.logspace(0, 1, 4) * u.TeV
    offset = [0.2, 0.3] * u.deg
    effective_area = np.arange(6).reshape(3, 2) * u.cm * u.cm
    meta = dict(name='example')
    aeff = EffectiveAreaTable2D(offset=offset,
                                energy=energy,
                                data=effective_area,
                                meta=meta)
    assert (aeff.axes[0].data == energy).all()
    assert (aeff.axes[1].data == offset).all()
    assert (aeff.data == effective_area).all()
    assert aeff.meta.name == 'example'

    wrong_data = np.arange(8).reshape(4, 2) * u.cm * u.cm

    with pytest.raises(ValueError):
        aeff.data = wrong_data
        aeff = EffectiveAreaTable(offset=offset,
                                  energy=energy,
                                  data=wrong_data)

    # Test evaluate function
    # Check that nodes are evaluated correctly
    e_node = 1
    off_node = 0
    offset = aeff.offset.nodes[off_node]
    energy = aeff.energy.nodes[e_node]
    actual = aeff.evaluate(offset=offset, energy=energy, method='nearest')
    desired = aeff.data[e_node, off_node]
    assert_allclose(actual, desired)

    actual = aeff.evaluate(offset=offset, energy=energy, method='linear')
    desired = aeff.data[e_node, off_node]
    assert_allclose(actual, desired)

    # Check that values between node make sense
    energy2 = aeff.energy.nodes[e_node + 1]
    upper = aeff.evaluate(offset=offset, energy=energy)
    lower = aeff.evaluate(offset=offset, energy=energy2)
    e_val = (energy + energy2) / 2
    actual = aeff.evaluate(offset=offset, energy=e_val)
    assert_equal(lower > actual and actual > upper, True)

    # Test return shape
    # Case 0; offset = scalar, energy = scalar, done

    # Case 1: offset = scalar, energy = None
    offset = 0.234 * u.deg
    actual = aeff.evaluate(offset=offset).shape
    desired = aeff.energy.nodes.shape
    assert_equal(actual, desired)

    # Case 2: offset = scalar, energy = 1Darray

    offset = 0.564 * u.deg
    nbins = 10
    energy = np.logspace(3, 4, nbins) * u.GeV
    actual = aeff.evaluate(offset=offset, energy=energy).shape
    desired = np.zeros(nbins).shape
    assert_equal(actual, desired)

    # Case 3: offset = None, energy = scalar
    energy = 1.1 * u.TeV
    actual = aeff.evaluate(energy=energy).shape
    desired = tuple([aeff.offset.nbins])
    assert_equal(actual, desired)

    # Case 4: offset = 1Darray, energy = scalar
    energy = 1.5 * u.TeV
    nbins = 4
    offset = np.linspace(0, 1, nbins) * u.deg
    actual = aeff.evaluate(offset=offset, energy=energy).shape
    desired = np.zeros(nbins).shape
    assert_equal(actual, desired)

    # case 5: offset = 1Darray, energy = 1Darray
    nbinse = 5
    nbinso = 3
    offset = np.linspace(0.2, 0.3, nbinso) * u.deg
    energy = np.logspace(0, 1, nbinse) * u.TeV
    actual = aeff.evaluate(offset=offset, energy=energy).shape
    desired = np.zeros([nbinse, nbinso]).shape
    assert_equal(actual, desired)

    # case 6: offset = 2Darray, energy = 1Darray
    nbinse = 4
    nx, ny = (12, 3)
    offset = np.linspace(0.2, 0.3, nx * ny).reshape(nx, ny) * u.deg
    energy = np.logspace(0, 1, nbinse) * u.TeV
    actual = aeff.evaluate(offset=offset, energy=energy).shape
    desired = np.zeros([nbinse, nx, ny]).shape
    assert_equal(actual, desired)

    # Misc functions
    assert 'EffectiveAreaTable2D' in str(aeff)
Пример #38
0
def test_set_vector_invalid_order(attribute):
    o = OpticalProperties()
    with pytest.raises(ValueError) as exc:
        setattr(o, attribute, [0.3, 0.1, 0.2])
    assert exc.value.args[
        0] == attribute + ' should be monotonically increasing'
Пример #39
0
def test_set_vector_invalid_type2(attribute):
    o = OpticalProperties()
    with pytest.raises(ValueError) as exc:
        setattr(o, attribute, 0.5)
    assert exc.value.args[0] == attribute + ' should be a 1-D sequence'
Пример #40
0
def test_range_nu_invalid2():
    o = OpticalProperties()
    with pytest.raises(ValueError) as exc:
        o.nu = [-1., 0.5, 0.8]
    assert exc.value.args[0] == 'nu should be strictly positive'
Пример #41
0
def test_range_mu_invalid2():
    o = OpticalProperties()
    with pytest.raises(ValueError) as exc:
        o.mu = [-1., 0., 1.3]
    assert exc.value.args[0] == 'mu should be in the range [-1:1]'
Пример #42
0
def test_set_vector_invalid_shape2(attribute):
    o = OpticalProperties()
    with pytest.raises(ValueError) as exc:
        setattr(o, attribute, np.array([[0., 1.], [0.5, 1.]]))
    assert exc.value.args[0] == attribute + ' should be a 1-D sequence'
Пример #43
0
def test_range_chi_invalid1():
    o = OpticalProperties()
    with pytest.raises(ValueError) as exc:
        o.chi = [-1., 0.5, 0.8]
    assert exc.value.args[0] == 'chi should be positive'
Пример #44
0
def test_set_array_invalid_order2(attribute):
    o = OpticalProperties()
    o.mu = [-0.5, 0.5]
    with pytest.raises(ValueError) as exc:
        setattr(o, attribute, np.ones((3, 2)))
    assert exc.value.args[0] == 'nu needs to be set before ' + attribute
Пример #45
0
def test_spectra_timeout(patch_get, patch_get_readable_fileobj_slow):
    with pytest.raises(TimeoutError):
        sdss.SDSS.get_spectra(plate=2345, fiberID=572)
Пример #46
0
def test_range_albedo_invalid2():
    o = OpticalProperties()
    with pytest.raises(ValueError) as exc:
        o.albedo = [0., 0.5, 1.1]
    assert exc.value.args[0] == 'albedo should be in the range [0:1]'
def test_raises_correct_exception():
    default_model = Zheng07Cens()
    with pytest.raises(HalotoolsError) as err:
        _ = default_model.mean_occupation(x=4)
    substr = "You must pass either a ``table`` or ``prim_haloprop`` argument"
    assert substr in err.value.args[0]
Пример #48
0
def test_images_timeout(patch_get, patch_get_readable_fileobj_slow):
    with pytest.raises(TimeoutError):
        sdss.SDSS.get_images(run=1904, camcol=3, field=164)
Пример #49
0
 def test_simulate_with_incorrect_arguments(self):
     with pytest.raises(ValueError):
         self.simulator.simulate(1, 2, 3, 4)
Пример #50
0
def test_query_timeout(patch_get_slow, coord=coords):
    with pytest.raises(TimeoutError):
        sdss.SDSS.query_region(coords, timeout=1)
Пример #51
0
def test_open_invalid_filename(tmpdir):
    fname = tmpdir.join('test.fits')

    with pytest.raises(IOError):
        d = Donuts(str(fname))
Пример #52
0
 def test_incorrect_simulate_channel(self):
     """Test simulating a channel that already exists."""
     self.simulator.simulate_channel('3.5-4.5', 2)
     with pytest.raises(KeyError):
         self.simulator.simulate_channel('3.5-4.5', 2)
     self.simulator.delete_channel('3.5-4.5')
def test_process_radial_bins2():
    input_rbins = np.arange(5)[::-1]
    period = None
    PBCs = False
    with pytest.raises(ValueError) as err:
        rbins = _process_radial_bins(input_rbins, period, PBCs)
Пример #54
0
 def test_simulate_wrong_model(self):
     """
     Simulate with a model that does not exist.
     """
     with pytest.raises(ValueError):
         self.simulator.simulate('unsupported', [0.6, 0.2, 0.6, 0.5])
Пример #55
0
def test_missing_properties(tmpdir):
    d = SphericalDust()
    with pytest.raises(Exception) as e:
        d.write(tmpdir.join(random_id()).strpath)
    assert e.value.args[
        0] == "The following attributes of the optical properties have not been set: nu, chi, albedo, mu, P1, P2, P3, P4"
def test_process_radial_bins3():
    input_rbins = np.linspace(0.1, 2, 5)
    period = 1
    PBCs = True
    with pytest.raises(ValueError) as err:
        rbins = _process_radial_bins(input_rbins, period, PBCs)
Пример #57
0
 def test_fit_fails_when_object_is_not_posterior_or_likelihood(self):
     x = np.ones(10)
     y = np.ones(10)
     pe = ParameterEstimation()
     with pytest.raises(TypeError):
         res = pe.fit(x, y)
Пример #58
0
def test_sample1_cell_size():
    period, search_length, approx_cell_size = 1, 0.5, 0.1
    with pytest.raises(ValueError) as err:
        _ = sample1_cell_size(period, search_length, approx_cell_size)
    substr = "Input ``search_length`` cannot exceed period/3"
    assert substr in err.value.args[0]
Пример #59
0
 def test_fit_fails_with_incorrect_number_of_parameters(self):
     pe = PSDParEst(self.ps)
     t0 = [1, 2]
     with pytest.raises(ValueError):
         res = pe.fit(self.lpost, t0)
Пример #60
0
 def test_fit_fails_without_lpost_or_t0(self):
     pe = ParameterEstimation()
     with pytest.raises(TypeError):
         res = pe.fit()