コード例 #1
0
def test_fit_toy_potential():
    # integrate orbit in both toy potentials, make sure correct one is chosen
    true_m = 2.81E11
    true_b = 11.
    true_potential = IsochronePotential(m=true_m, b=true_b, units=galactic)
    orbit = true_potential.integrate_orbit([15., 0, 0, 0, 0.2, 0],
                                           dt=2.,
                                           n_steps=10000)

    potential = fit_toy_potential(orbit)
    for k, v in true_potential.parameters.items():
        assert quantity_allclose(v, potential.parameters[k], rtol=1E-2)

    # -----------------------------------------------------------------
    true_omegas = np.array([0.011, 0.032, 0.045])
    true_potential = HarmonicOscillatorPotential(omega=true_omegas,
                                                 units=galactic)
    orbit = true_potential.integrate_orbit([15., 1, 2, 0, 0, 0],
                                           dt=2.,
                                           n_steps=10000)

    potential = fit_toy_potential(orbit)

    assert quantity_allclose(potential.parameters['omega'],
                             true_potential.parameters['omega'],
                             rtol=1E-2)
コード例 #2
0
ファイル: test_analysis.py プロジェクト: astropy/specutils
def test_gaussian_sigma_width_regions():

    np.random.seed(42)

    frequencies = np.linspace(0, 100, 10000) * u.GHz
    g1 = models.Gaussian1D(amplitude=5*u.Jy, mean=10*u.GHz, stddev=0.8*u.GHz)
    g2 = models.Gaussian1D(amplitude=5*u.Jy, mean=2*u.GHz, stddev=0.3*u.GHz)
    g3 = models.Gaussian1D(amplitude=5*u.Jy, mean=70*u.GHz, stddev=10*u.GHz)

    compound = g1 + g2 + g3
    spectrum = Spectrum1D(spectral_axis=frequencies, flux=compound(frequencies))

    region1 = SpectralRegion(5*u.GHz, 15*u.GHz)
    result1 = gaussian_sigma_width(spectrum, regions=region1)

    exp1 = g1.stddev
    assert quantity_allclose(result1, exp1, atol=0.25*exp1)

    region2 = SpectralRegion(1*u.GHz, 3*u.GHz)
    result2 = gaussian_sigma_width(spectrum, regions=region2)

    exp2 = g2.stddev
    assert quantity_allclose(result2, exp2, atol=0.25*exp2)

    region3 = SpectralRegion(40*u.GHz, 100*u.GHz)
    result3 = gaussian_sigma_width(spectrum, regions=region3)

    exp3 = g3.stddev
    assert quantity_allclose(result3, exp3, atol=0.25*exp3)

    # Test using a list of regions
    result_list = gaussian_sigma_width(spectrum, regions=[region1, region2, region3])
    for model, result in zip((g1, g2, g3), result_list):
        exp = model.stddev
        assert quantity_allclose(result, exp, atol=0.25*exp)
コード例 #3
0
def test_parameter_convert():
    n_trials = 128

    # right now, round-trip tests
    Ps = np.exp(np.random.uniform(np.log(1.), np.log(1E4), n_trials)) * u.day
    Ks = np.random.uniform(0.1, 100, n_trials) * u.km / u.s
    eccs = np.random.random(n_trials)

    for P, K, ecc in zip(Ps, Ks, eccs):
        _mf, _asini = SimulatedRVOrbit.P_K_ecc_to_mf_asini_ecc(P, K, ecc)
        _P, _K = SimulatedRVOrbit.mf_asini_ecc_to_P_K(_mf, _asini, ecc)
        assert quantity_allclose(P, _P)
        assert quantity_allclose(K, _K)

    # right now, round-trip test
    mfs = np.exp(np.random.normal(np.log(2.5), 2., n_trials)) * u.Msun
    asinis = np.exp(np.random.uniform(np.log(1), np.log(1000),
                                      n_trials)) * u.au
    eccs = np.random.random(n_trials)

    for mf, asini, ecc in zip(mfs, asinis, eccs):
        _P, _K = SimulatedRVOrbit.mf_asini_ecc_to_P_K(mf, asini, ecc)
        _mf, _asini = SimulatedRVOrbit.P_K_ecc_to_mf_asini_ecc(_P, _K, ecc)

        assert quantity_allclose(mf, _mf)
        assert quantity_allclose(asini, _asini)
コード例 #4
0
def test_bounding_region(simulated_spectra):
    np.random.seed(42)

    spectrum = simulated_spectra.s1_um_mJy_e1
    uncertainty = StdDevUncertainty(
        0.1 * np.random.random(len(spectrum.flux)) * u.mJy)
    spectrum.uncertainty = uncertainty

    region = SpectralRegion([(0.6 * u.um, 0.8 * u.um),
                             (0.86 * u.um, 0.89 * u.um)])

    extracted_spectrum = extract_bounding_spectral_region(spectrum, region)

    # Confirm the end points are correct
    assert quantity_allclose(extracted_spectrum.spectral_axis[[0, -1]],
                             [0.6035353535353536, 0.8858585858585859] * u.um)

    flux_expected = [
        FLUX_ARRAY + [
            948.81864554, 1197.84859443, 1069.75268943, 1118.27269184,
            1301.7695563, 1206.62880648, 1518.16549319, 1256.84259015,
            1638.76791267, 1562.05642302, 1337.65312465, 1263.48914109,
            1589.81797876, 1548.46068415
        ]
    ] * u.mJy

    assert quantity_allclose(extracted_spectrum.flux, flux_expected)

    # also ensure this works if the multi-region is expressed as a single
    # Quantity
    region2 = SpectralRegion([(0.6, 0.8), (0.86, 0.89)] * u.um)
    extracted_spectrum2 = extract_bounding_spectral_region(spectrum, region2)
    assert quantity_allclose(extracted_spectrum2.spectral_axis[[0, -1]],
                             [0.6035353535353536, 0.8858585858585859] * u.um)
    assert quantity_allclose(extracted_spectrum2.flux, flux_expected)
コード例 #5
0
def test_gaussian_sigma_width_regions():

    np.random.seed(42)

    frequencies = np.linspace(0, 100, 10000) * u.GHz
    g1 = models.Gaussian1D(amplitude=5*u.Jy, mean=10*u.GHz, stddev=0.8*u.GHz)
    g2 = models.Gaussian1D(amplitude=5*u.Jy, mean=2*u.GHz, stddev=0.3*u.GHz)
    g3 = models.Gaussian1D(amplitude=5*u.Jy, mean=70*u.GHz, stddev=10*u.GHz)

    compound = g1 + g2 + g3
    spectrum = Spectrum1D(spectral_axis=frequencies, flux=compound(frequencies))

    region1 = SpectralRegion(5*u.GHz, 15*u.GHz)
    result1 = gaussian_sigma_width(spectrum, regions=region1)

    exp1 = g1.stddev
    assert quantity_allclose(result1, exp1, atol=0.25*exp1)

    region2 = SpectralRegion(1*u.GHz, 3*u.GHz)
    result2 = gaussian_sigma_width(spectrum, regions=region2)

    exp2 = g2.stddev
    assert quantity_allclose(result2, exp2, atol=0.25*exp2)

    region3 = SpectralRegion(40*u.GHz, 100*u.GHz)
    result3 = gaussian_sigma_width(spectrum, regions=region3)

    exp3 = g3.stddev
    assert quantity_allclose(result3, exp3, atol=0.25*exp3)

    # Test using a list of regions
    result_list = gaussian_sigma_width(spectrum, regions=[region1, region2, region3])
    for model, result in zip((g1, g2, g3), result_list):
        exp = model.stddev
        assert quantity_allclose(result, exp, atol=0.25*exp)
コード例 #6
0
def test_velocity_rot_frame(name, Omega, tol):
    # _i = inertial
    # _r = rotating

    r0 = 1.245246
    potential = HernquistPotential(m=1., c=0.2, units=dimensionless)
    vc = potential.circular_velocity([r0, 0, 0]).value[0]
    w0 = PhaseSpacePosition(pos=[r0, 0, 0.], vel=[0, vc, 0.])
    Omega = Omega * [1., 1., vc / r0]

    H_r = Hamiltonian(potential,
                      ConstantRotatingFrame(Omega=Omega, units=dimensionless))
    H = Hamiltonian(potential, StaticFrame(units=dimensionless))

    orbit_i = H.integrate_orbit(w0,
                                dt=0.1,
                                n_steps=1000,
                                Integrator=DOPRI853Integrator)
    orbit_r = H_r.integrate_orbit(w0,
                                  dt=0.1,
                                  n_steps=1000,
                                  Integrator=DOPRI853Integrator)

    orbit_i2r = orbit_i.to_frame(
        ConstantRotatingFrame(Omega=Omega, units=dimensionless))
    orbit_r2i = orbit_r.to_frame(StaticFrame(units=dimensionless))

    assert quantity_allclose(orbit_i.xyz, orbit_r2i.xyz, atol=tol)
    assert quantity_allclose(orbit_i.v_xyz, orbit_r2i.v_xyz, atol=tol)

    assert quantity_allclose(orbit_r.xyz, orbit_i2r.xyz, atol=tol)
    assert quantity_allclose(orbit_r.v_xyz, orbit_i2r.v_xyz, atol=tol)
コード例 #7
0
def test_wcs1d_fits_hdus(tmpdir, hdu):
    """Test writing of Spectrum1D in WCS1D format to different IMAGE_HDUs."""
    # Header dictionary for constructing WCS
    hdr = {
        'CTYPE1': 'wavelength',
        'CUNIT1': 'um',
        'CRPIX1': 1,
        'CRVAL1': 1,
        'CDELT1': 0.01
    }
    # Create a small data set
    flu = u.W / (u.m**2 * u.nm)
    flux = np.arange(1, 11)**2 * 1.e-14 * flu

    spectrum = Spectrum1D(flux=flux, wcs=WCS(hdr))
    tmpfile = str(tmpdir.join('_tst.fits'))
    spectrum.write(tmpfile, hdu=hdu, format='wcs1d-fits')

    # Read it in and check against the original
    with fits.open(tmpfile) as hdulist:
        assert hdulist[hdu].is_image
        assert hdulist[hdu].header['NAXIS'] == 1
        assert hdulist[hdu].header['NAXIS1'] == flux.shape[0]
        assert u.Unit(hdulist[hdu].header['CUNIT1']) == u.Unit(hdr['CUNIT1'])
        assert quantity_allclose(hdulist[hdu].data * flu, flux)

    # Test again with automatic format selection by filename pattern
    tmpfile = str(tmpdir.join('_wcs.fits'))
    spectrum.write(tmpfile, hdu=hdu)
    with fits.open(tmpfile) as hdulist:
        assert hdulist[hdu].is_image
        assert quantity_allclose(hdulist[hdu].data * flu, flux)
コード例 #8
0
ファイル: transformations.py プロジェクト: sudozer/sunpy
def hpc_to_hpc(heliopcoord, heliopframe):
    """
    This converts from HPC to HPC, with different observer location parameters.
    It does this by transforming through HGS.
    """
    # TODO: Revert this.
    from astropy.tests.helper import quantity_allclose
    if (heliopcoord.observer == heliopframe.observer or
        (quantity_allclose(heliopcoord.observer.lat, heliopframe.observer.lat)
         and quantity_allclose(heliopcoord.observer.lon,
                               heliopframe.observer.lon)
         and quantity_allclose(heliopcoord.observer.radius,
                               heliopframe.observer.radius))):
        return heliopframe.realize_frame(heliopcoord._data)

    if not isinstance(heliopframe.observer, BaseCoordinateFrame):
        raise ConvertError(
            "Cannot transform between helioprojective frames "
            "without `obstime` being specified for observer {}.".format(
                heliopframe.observer))
    if not isinstance(heliopcoord.observer, BaseCoordinateFrame):
        raise ConvertError(
            "Cannot transform between helioprojective frames "
            "without `obstime` being specified for observer {}.".format(
                heliopcoord.observer))

    hgs = heliopcoord.transform_to(HeliographicStonyhurst)
    hgs.observer = heliopframe.observer
    hpc = hgs.transform_to(heliopframe)

    return hpc
コード例 #9
0
ファイル: test_loaders.py プロジェクト: orifox/specutils
def test_tabular_fits_2d(tmpdir, spectral_axis):
    wlu = {
        'wavelength': u.AA,
        'frequency': u.GHz,
        'energy': u.eV,
        'wavenumber': u.cm**-1
    }
    # Create a small data set with 2D flux + uncertainty
    disp = np.arange(1, 1.1, 0.01) * wlu[spectral_axis]
    flux = np.ones(
        (3, len(disp))) * np.arange(1,
                                    len(disp) + 1)**2 * 1.e-14 * u.Jy
    unc = StdDevUncertainty(0.01 * np.random.rand(3, len(disp)))
    if spectral_axis not in ('wavelength', ):
        disp = np.flip(disp)

    spectrum = Spectrum1D(flux=flux, spectral_axis=disp, uncertainty=unc)
    tmpfile = str(tmpdir.join('_tst.fits'))
    spectrum.write(tmpfile, format='tabular-fits')

    # Read it in and check against the original
    spec = Spectrum1D.read(tmpfile)
    assert spec.flux.unit == spectrum.flux.unit
    assert spec.spectral_axis.unit == spectrum.spectral_axis.unit
    assert spec.flux.shape == flux.shape
    assert spec.uncertainty.array.shape == flux.shape
    assert quantity_allclose(spec.spectral_axis, spectrum.spectral_axis)
    assert quantity_allclose(spec.flux, spectrum.flux)
    assert quantity_allclose(spec.uncertainty.quantity,
                             spectrum.uncertainty.quantity)
コード例 #10
0
def test_tabular_fits_writer(tmpdir, spectral_axis):
    wlu = {'wavelength': u.AA, 'frequency': u.GHz, 'energy': u.eV,
           'wavenumber': u.cm**-1}
    # Create a small data set
    disp = np.arange(1,1.1,0.01)*wlu[spectral_axis]
    flux = np.ones(len(disp))*1.e-14*u.Jy
    unc = StdDevUncertainty(0.01*flux)
    spectrum = Spectrum1D(flux=flux, spectral_axis=disp, uncertainty=unc)
    tmpfile = str(tmpdir.join('_tst.fits'))
    spectrum.write(tmpfile, format='tabular-fits')

    # Read it in and check against the original
    table = Table.read(tmpfile, format='fits')
    assert table[spectral_axis].unit == spectrum.spectral_axis.unit
    assert table['flux'].unit == spectrum.flux.unit
    assert table['uncertainty'].unit == spectrum.uncertainty.unit
    assert quantity_allclose(table[spectral_axis], spectrum.spectral_axis)
    assert quantity_allclose(table['flux'], spectrum.flux)
    assert quantity_allclose(table['uncertainty'], spectrum.uncertainty.quantity)

    # Test spectrum with different flux unit
    flux = np.random.normal(0., 1.e-9, disp.shape[0]) * u.W * u.m**-2 * u.AA**-1
    unc = StdDevUncertainty(0.1 * np.sqrt(np.abs(flux.value)) * flux.unit)
    spectrum = Spectrum1D(flux=flux, spectral_axis=disp, uncertainty=unc)

    # Try to overwrite the file
    with pytest.raises(OSError, match=r'File exists:'):
        spectrum.write(tmpfile, format='tabular-fits')
    spectrum.write(tmpfile, format='tabular-fits', overwrite=True)

    table = Table.read(tmpfile)
    assert table['flux'].unit == spectrum.flux.unit
コード例 #11
0
def test_velocity_trend():
    rnd = np.random.RandomState(seed=42)

    coeffs = [
        0 * u.km / u.s, 0 * u.km / u.s / u.day, 1e-2 * u.km / u.s / u.day**2
    ]
    trend = PolynomialRVTrend(coeffs, t0=Time('J2018.0'))
    pars = get_random_orbit_pars(rnd, trend)
    pars['a'] = 0 * u.au
    orbit = KeplerOrbit(**pars)

    t = Time('J2018.0') + np.linspace(-100, 100, 256) * u.day
    rv = orbit.radial_velocity(t)
    assert quantity_allclose(rv[0], rv[-1])
    assert quantity_allclose(rv[0], 100. * u.km / u.s)

    # OK THIS SUCKS (copy pasta)
    coeffs = [
        0 * u.km / u.s, 1 * u.km / u.s / u.day, 0 * u.km / u.s / u.day**2
    ]
    trend = PolynomialRVTrend(coeffs, t0=Time('J2018.0'))
    pars = get_random_orbit_pars(rnd, trend)
    pars['a'] = 0 * u.au
    orbit = KeplerOrbit(**pars)

    t = Time('J2018.0') + np.linspace(-100, 100, 256) * u.day
    rv = orbit.radial_velocity(t)
    assert quantity_allclose(rv[0], -rv[-1])
    assert quantity_allclose(rv[0], -100. * u.km / u.s)
コード例 #12
0
ファイル: test_tgas.py プロジェクト: Johannes-Sahlmann/gaia
def test_convenience():
    tgas = TGASData(tgas_filename)

    # TODO: how to actually test below?

    # get_distance()
    d1 = tgas.get_distance()
    d2 = tgas.get_distance(lutz_kelker=True)
    assert not quantity_allclose(d1, d2)

    # get_vtan()
    v1 = tgas.get_vtan()
    v2 = tgas.get_vtan(lutz_kelker=True)
    assert not quantity_allclose(v1, v2)

    # get_coord()
    c1 = tgas.get_coord()
    c2 = tgas.get_coord(lutz_kelker=True)
    assert not quantity_allclose(c1.cartesian.xyz, c2.cartesian.xyz)

    # parallax_snr
    assert len(tgas.parallax_snr) == len(tgas)

    # distance
    assert isinstance(tgas.distance, coord.Distance)
コード例 #13
0
def test_hgs_hcrs():
    # This test checks the HGS->HCRS transformation by transforming from HGS to
    # HeliocentricMeanEcliptic (HME).  It will fail if there are errors in Astropy's
    # HCRS->ICRS or ICRS->HME transformations.

    # Use published HGS coordinates in the Astronomical Almanac (2013), pages C6-C7
    obstime = Time('2013-01-28')
    earth_hgs = SkyCoord(0 * u.deg,
                         -5.73 * u.deg,
                         0.9848139 * u.AU,
                         frame=HeliographicStonyhurst,
                         obstime=obstime)

    # Transform to HME at observation-time equinox
    earth_hme = earth_hgs.transform_to(
        HeliocentricMeanEcliptic(equinox=obstime))

    # Validate against published values from the Astronomical Almanac (2013), page C6 per page E2
    # The dominant source of inaccuracy is the limited precision of the published B0 used above
    assert quantity_allclose(earth_hme.lon,
                             Angle('308d13m30.51s') - 180 * u.deg,
                             atol=5 * u.arcsec)
    assert quantity_allclose(earth_hme.lat,
                             -Angle('-0.27s'),
                             atol=10 * u.arcsec)
    assert quantity_allclose(earth_hme.distance,
                             0.9848139 * u.AU,
                             atol=5e-7 * u.AU)
コード例 #14
0
ファイル: test_analysis.py プロジェクト: rosteen/specutils
def test_line_flux_masked():

    np.random.seed(42)

    N = 100

    wavelengths = np.linspace(0.4, 1.05, N) * u.um

    g = models.Gaussian1D(amplitude=2000 * u.mJy,
                          mean=0.56 * u.um,
                          stddev=0.01 * u.um)
    flux = g(wavelengths) + 1000 * u.mJy
    noise = 400 * np.random.random(flux.shape) * u.mJy
    flux += noise

    spectrum = Spectrum1D(spectral_axis=wavelengths, flux=flux)
    spectrum.uncertainty = StdDevUncertainty(noise)

    spectrum_masked = snr_threshold(spectrum, 10.)

    # Ensure we have at least 50% of the data being masked.
    assert len(np.where(spectrum_masked.mask)[0]) > N / 2

    result = line_flux(spectrum_masked)

    assert result.unit.is_equivalent(u.Jy * u.um)

    assert quantity_allclose(result.value, 720.52992, atol=0.001)

    # With flux conserving resampler
    result = line_flux(spectrum_masked,
                       mask_interpolation=FluxConservingResampler)
    assert quantity_allclose(result.value, 720.61116, atol=0.001)
コード例 #15
0
def test_angular_momentum():

    w = PhaseSpacePosition([1., 0., 0.], [0., 0., 1.])
    assert quantity_allclose(np.squeeze(w.angular_momentum()),
                             [0., -1, 0] * u.one)

    w = PhaseSpacePosition([1., 0., 0.], [0., 1., 0.])
    assert quantity_allclose(np.squeeze(w.angular_momentum()),
                             [0., 0, 1] * u.one)

    w = PhaseSpacePosition([0., 1., 0.], [0., 0., 1.])
    assert quantity_allclose(np.squeeze(w.angular_momentum()),
                             [1., 0, 0] * u.one)

    w = PhaseSpacePosition([1., 0, 0] * u.kpc, [0., 200., 0] * u.pc / u.Myr)
    assert quantity_allclose(np.squeeze(w.angular_momentum()),
                             [0, 0, 0.2] * u.kpc**2 / u.Myr)

    # multiple - known
    q = np.array([[1., 0., 0.], [1., 0., 0.], [0, 1., 0.]]).T
    p = np.array([[0, 0, 1.], [0, 1., 0.], [0, 0, 1]]).T
    L = PhaseSpacePosition(q, p).angular_momentum()
    true_L = np.array([[0., -1, 0], [0., 0, 1], [1., 0, 0]]).T * u.one
    assert L.shape == (3, 3)
    assert quantity_allclose(L, true_L)

    # multiple - random
    q = np.random.uniform(size=(3, 128))
    p = np.random.uniform(size=(3, 128))
    L = PhaseSpacePosition(q, p).angular_momentum()
    assert L.shape == (3, 128)
コード例 #16
0
ファイル: test_analysis.py プロジェクト: rosteen/specutils
def test_moment():

    np.random.seed(42)

    frequencies = np.linspace(100, 1, 10000) * u.GHz
    g = models.Gaussian1D(amplitude=1 * u.Jy,
                          mean=10 * u.GHz,
                          stddev=1 * u.GHz)
    noise = np.random.normal(0., 0.01, frequencies.shape) * u.Jy
    flux = g(frequencies) + noise

    spectrum = Spectrum1D(spectral_axis=frequencies, flux=flux)

    moment_0 = moment(spectrum, order=0)
    assert moment_0.unit.is_equivalent(u.Jy)
    assert quantity_allclose(moment_0, 252.96 * u.Jy, atol=0.01 * u.Jy)

    moment_1 = moment(spectrum, order=1)
    assert moment_1.unit.is_equivalent(u.GHz)
    assert quantity_allclose(moment_1, 10.08 * u.GHz, atol=0.01 * u.GHz)

    moment_2 = moment(spectrum, order=2)
    assert moment_2.unit.is_equivalent(u.GHz**2)
    assert quantity_allclose(moment_2, 13.40 * u.GHz**2, atol=0.01 * u.GHz**2)

    moment_3 = moment(spectrum, order=3)
    assert moment_3.unit.is_equivalent(u.GHz**3)
    assert quantity_allclose(moment_3,
                             1233.78 * u.GHz**3,
                             atol=0.01 * u.GHz**3)
コード例 #17
0
def test_sanity():

    rep1 = coord.CartesianRepresentation(x=[0, 1.], y=0, z=0, unit=u.pc)

    rep2 = coord.CartesianRepresentation(x=0, y=[0, 1.], z=0, unit=u.pc)

    rep3 = coord.CartesianRepresentation(x=0, y=0, z=[0, 1.], unit=u.pc)

    # Try for many origins:
    rnd = np.random.RandomState(seed=42)

    for _ in range(128):
        origin = coord.ICRS(ra=rnd.uniform(0, 360) * u.deg,
                            dec=rnd.uniform(-90, 90) * u.deg,
                            distance=rnd.uniform(10, 100) * u.pc)

        ref_c = ReferencePlaneFrame(rep1, origin=origin)
        icrs = ref_c.transform_to(coord.ICRS)
        assert icrs.dec[1] > icrs.dec[0]
        assert quantity_allclose(icrs.ra[0], icrs.ra[1])

        ref_c = ReferencePlaneFrame(rep2, origin=origin)
        icrs = ref_c.transform_to(coord.ICRS)
        assert icrs.ra[1] > icrs.ra[0]

        ref_c = ReferencePlaneFrame(rep3, origin=origin)
        icrs = ref_c.transform_to(coord.ICRS)
        assert icrs.distance[0] > icrs.distance[1]
        assert quantity_allclose(icrs.ra[0], icrs.ra[1])
        assert quantity_allclose(icrs.dec[0], icrs.dec[1])
コード例 #18
0
def test_create_spectral_coord_observer_target(observer, target):

    with nullcontext() if target is None else pytest.warns(
            AstropyUserWarning, match='No velocity defined on frame'):
        coord = SpectralCoord([100, 200, 300] * u.nm,
                              observer=observer,
                              target=target)

    if observer is None:
        assert coord.observer is None
    else:
        assert_frame_allclose(observer, coord.observer)

    if target is None:
        assert coord.target is None
    else:
        assert_frame_allclose(target, coord.target)

    assert coord.doppler_rest is None
    assert coord.doppler_convention is None

    if observer is None or target is None:
        assert quantity_allclose(coord.redshift, 0)
        assert quantity_allclose(coord.radial_velocity, 0 * u.km / u.s)
    elif (any(observer is lsrd for lsrd in LSRD_EQUIV)
          and any(target is lsrd for lsrd in LSRD_DIR_STATIONARY_EQUIV)):
        assert_quantity_allclose(coord.radial_velocity,
                                 -274**0.5 * u.km / u.s,
                                 atol=1e-4 * u.km / u.s)
        assert_quantity_allclose(coord.redshift,
                                 -5.5213158163147646e-05,
                                 atol=1e-9)
    else:
        raise NotImplementedError()
コード例 #19
0
def test_parameter_convert():
    n_trials = 128

    # right now, round-trip tests
    Ps = np.exp(np.random.uniform(np.log(1.), np.log(1E4), n_trials)) * u.day
    Ks = np.random.uniform(0.1, 100, n_trials)*u.km/u.s
    eccs = np.random.random(n_trials)

    for P,K,ecc in zip(Ps, Ks, eccs):
        _mf, _asini = SimulatedRVOrbit.P_K_ecc_to_mf_asini_ecc(P, K, ecc)
        _P, _K = SimulatedRVOrbit.mf_asini_ecc_to_P_K(_mf, _asini, ecc)
        assert quantity_allclose(P, _P)
        assert quantity_allclose(K, _K)

    # right now, round-trip test
    mfs = np.exp(np.random.normal(np.log(2.5), 2., n_trials)) * u.Msun
    asinis = np.exp(np.random.uniform(np.log(1), np.log(1000), n_trials)) * u.au
    eccs = np.random.random(n_trials)

    for mf,asini,ecc in zip(mfs, asinis, eccs):
        _P, _K = SimulatedRVOrbit.mf_asini_ecc_to_P_K(mf, asini, ecc)
        _mf, _asini = SimulatedRVOrbit.P_K_ecc_to_mf_asini_ecc(_P, _K, ecc)

        assert quantity_allclose(mf, _mf)
        assert quantity_allclose(asini, _asini)
コード例 #20
0
ファイル: test_anomaly.py プロジェクト: vcalderon2009/TwoBody
def test_anomaly_roundtrip(method):
    kw = dict(tol=1E-10, maxiter=128, method=method)

    # M -> E -> M
    M_grid = np.linspace(0, 2 * np.pi, N)
    e_grid = np.linspace(0, 1 - 1E-9, N)  # MAGIC NUMBER: 1E-9
    Ms, es = [x.ravel() for x in np.meshgrid(M_grid, e_grid)]

    for M, e in zip(Ms, es):
        E = eccentric_anomaly_from_mean_anomaly(M * u.rad, e, **kw)
        M2 = mean_anomaly_from_eccentric_anomaly(E, e)
        assert quantity_allclose(M * u.rad, M2, atol=1E-14 * u.rad)

    E = eccentric_anomaly_from_mean_anomaly(Ms * u.rad, es, **kw)
    M2 = mean_anomaly_from_eccentric_anomaly(E, es)
    assert quantity_allclose(Ms * u.rad, M2, atol=1E-14 * u.rad)

    # E -> M -> E
    E_grid = np.linspace(0, 2 * np.pi, N)
    e_grid = np.linspace(0, 1 - 1E-9, N)  # MAGIC NUMBER: 1E-9
    Es, es = [x.ravel() for x in np.meshgrid(E_grid, e_grid)]

    for E, e in zip(Es, es):
        M = mean_anomaly_from_eccentric_anomaly(E * u.rad, e)
        E2 = eccentric_anomaly_from_mean_anomaly(M, e, **kw)
        assert quantity_allclose(E * u.rad, E2, atol=1E-14 * u.rad)

    M = mean_anomaly_from_eccentric_anomaly(Es * u.rad, es)
    E2 = eccentric_anomaly_from_mean_anomaly(M, es, **kw)
    assert quantity_allclose(Es * u.rad, E2, atol=1E-14 * u.rad)
コード例 #21
0
ファイル: test_load.py プロジェクト: adrn/ophiuchus
def test_load():
    p_bar = load_potential('barred_mw')
    p_static = load_potential('static_mw')

    x = [4.1, -0.5, 0.1]
    assert not quantity_allclose(p_bar.value(x), p_static.value(x))
    assert not quantity_allclose(p_bar.gradient(x), p_static.gradient(x))
コード例 #22
0
def test_velocity_rot_frame(name, Omega, tol):
    # _i = inertial
    # _r = rotating

    r0 = 1.245246
    potential = HernquistPotential(m=1., c=0.2, units=dimensionless)
    vc = potential.circular_velocity([r0,0,0]).value[0]
    w0 = PhaseSpacePosition(pos=[r0, 0, 0.],
                            vel=[0, vc, 0.])
    Omega = Omega * [1., 1., vc/r0]

    H_r = Hamiltonian(potential, ConstantRotatingFrame(Omega=Omega, units=dimensionless))
    H = Hamiltonian(potential, StaticFrame(units=dimensionless))

    orbit_i = H.integrate_orbit(w0, dt=0.1, n_steps=1000, Integrator=DOPRI853Integrator)
    orbit_r = H_r.integrate_orbit(w0, dt=0.1, n_steps=1000, Integrator=DOPRI853Integrator)

    orbit_i2r = orbit_i.to_frame(ConstantRotatingFrame(Omega=Omega, units=dimensionless))
    orbit_r2i = orbit_r.to_frame(StaticFrame(units=dimensionless))

    assert quantity_allclose(orbit_i.xyz, orbit_r2i.xyz, atol=tol)
    assert quantity_allclose(orbit_i.v_xyz, orbit_r2i.v_xyz, atol=tol)

    assert quantity_allclose(orbit_r.xyz, orbit_i2r.xyz, atol=tol)
    assert quantity_allclose(orbit_r.v_xyz, orbit_i2r.v_xyz, atol=tol)
コード例 #23
0
ファイル: test_sampler.py プロジェクト: danhey/thejoker
    def test_rejection_sample(self):
        rnd = np.random.RandomState(42)

        # First, try just running rejection_sample()
        data = self.data['binary']
        joker = TheJoker(self.joker_params['binary'], random_state=rnd)

        with pytest.raises(ValueError):
            joker.rejection_sample(data)

        joker.rejection_sample(data, n_prior_samples=128)

        # Now try specifying the tempfile path
        data = self.data['binary']
        joker = TheJoker(self.joker_params['binary'],
                         random_state=rnd, tempfile_path=path.abspath('.'))

        _ = joker.rejection_sample(data, n_prior_samples=128)

        # Now re-run with jitter set, check that it's always the fixed value
        jitter = 5.*u.m/u.s
        params = JokerParams(P_min=8*u.day, P_max=128*u.day, jitter=jitter)
        joker = TheJoker(params)

        prior_samples = joker.sample_prior(128)
        assert quantity_allclose(prior_samples['jitter'], jitter)

        full_samples = joker.rejection_sample(data, n_prior_samples=128)
        assert quantity_allclose(full_samples['jitter'], jitter)

        samples, lnp, lnl = joker.rejection_sample(data,
                                                   n_prior_samples=128,
                                                   return_logprobs=True)
        assert len(lnp) == len(samples)
        assert len(lnl) == len(samples)
コード例 #24
0
def test_create_spectral_coord_observer_target(observer, target):

    coord = SpectralCoord([100, 200, 300] * u.nm,
                          observer=observer,
                          target=target)

    if observer is None:
        assert coord.observer is None
    else:
        assert_frame_allclose(observer, coord.observer)

    if target is None:
        assert coord.target is None
    else:
        assert_frame_allclose(target, coord.target)

    assert coord.doppler_rest is None
    assert coord.doppler_convention is None

    if observer is None or target is None:
        assert quantity_allclose(coord.redshift, 0)
        assert quantity_allclose(coord.radial_velocity, 0 * u.km / u.s)
    elif observer in LSRD_EQUIV and target in LSRD_DIR_STATIONARY_EQUIV:
        assert_quantity_allclose(coord.radial_velocity, -274**0.5 * u.km / u.s)
        assert_quantity_allclose(coord.redshift, -274**0.5 / 299792.458)
    else:
        raise NotImplementedError()
コード例 #25
0
ファイル: test_analysis.py プロジェクト: rosteen/specutils
def test_fwhm_masked():

    np.random.seed(42)

    # Create a masked (uncentered) spectrum for testing
    frequencies = np.linspace(0, 10, 1000) * u.GHz
    stddev = 0.8 * u.GHz
    g1 = models.Gaussian1D(amplitude=5 * u.Jy, mean=2 * u.GHz, stddev=stddev)
    mask = (np.random.randn(frequencies.shape[0]) + 1.) > 0

    spectrum = Spectrum1D(spectral_axis=frequencies,
                          flux=g1(frequencies),
                          mask=mask)

    result = fwhm(spectrum)

    expected = stddev * gaussian_sigma_to_fwhm
    assert quantity_allclose(result, expected, atol=0.01 * u.GHz)

    # Highest point at the first point
    wavelengths = np.linspace(1, 10, 100) * u.um
    flux = (1.0 / wavelengths.value) * u.Jy  # highest point first.

    spectrum = Spectrum1D(spectral_axis=wavelengths, flux=flux)
    result = fwhm(spectrum)
    # Note that this makes a little more sense than the previous version;
    # since the maximum value occurs at wavelength=1, and the half-value of
    # flux (0.5) occurs at exactly wavelength=2, the result should be
    # exactly 1 (2 - 1).
    assert result == 1.0 * u.um

    # Test the interpolation used in FWHM for wavelength values that are not
    # on the grid
    wavelengths = np.linspace(1, 10, 31) * u.um
    flux = (1.0 / wavelengths.value) * u.Jy  # highest point first.

    spectrum = Spectrum1D(spectral_axis=wavelengths, flux=flux)
    result = fwhm(spectrum)

    assert quantity_allclose(result, 1.01 * u.um)

    # Highest point at the last point
    wavelengths = np.linspace(1, 10, 100) * u.um
    flux = wavelengths.value * u.Jy  # highest point last.

    spectrum = Spectrum1D(spectral_axis=wavelengths, flux=flux)
    result = fwhm(spectrum)
    assert result == 5 * u.um

    # Flat spectrum
    wavelengths = np.linspace(1, 10, 100) * u.um
    flux = np.ones(wavelengths.shape) * u.Jy  # highest point last.

    spectrum = Spectrum1D(spectral_axis=wavelengths, flux=flux)
    result = fwhm(spectrum)
    assert result == 9 * u.um
コード例 #26
0
def test_hpc_hpc_null():
    hpc_in = Helioprojective(0*u.arcsec, 0*u.arcsec)
    hpc_out = Helioprojective()

    hpc_new = hpc_in.transform_to(hpc_out)

    assert hpc_new is not hpc_in
    assert quantity_allclose(hpc_new.Tx, hpc_in.Tx)
    assert quantity_allclose(hpc_new.Ty, hpc_in.Ty)
    assert hpc_out.observer == hpc_new.observer
コード例 #27
0
def test_hpc_hpc_null():
    hpc_in = Helioprojective(0 * u.arcsec, 0 * u.arcsec)
    hpc_out = Helioprojective()

    hpc_new = hpc_in.transform_to(hpc_out)

    assert hpc_new is not hpc_in
    assert quantity_allclose(hpc_new.Tx, hpc_in.Tx)
    assert quantity_allclose(hpc_new.Ty, hpc_in.Ty)
    assert hpc_out.observer == hpc_new.observer
コード例 #28
0
def test_iraf_linear(remote_data_path):

    spectrum_1d = Spectrum1D.read(remote_data_path, format='iraf')

    assert isinstance(spectrum_1d, Spectrum1D)
    assert quantity_allclose(spectrum_1d.wavelength[0],
                             u.Quantity(3514.56625402, unit='Angstrom'))
    assert quantity_allclose(spectrum_1d.wavelength[100],
                             u.Quantity(3514.56625402, unit='Angstrom') +
                             u.Quantity(0.653432383823 * 100, unit='Angstrom'))
コード例 #29
0
def test_noise_estimate_uncertainty():
    # an alternate test with a more complicated input spectrum

    np.random.seed(42)

    # Create values for spectrum.
    frequencies = np.linspace(1, 100, 10000) * u.um
    g = models.Gaussian1D(amplitude=1 * u.Jy, mean=10 * u.um, stddev=1 * u.um)
    noise = np.random.normal(0., 0.01, frequencies.shape) * u.Jy
    flux = g(frequencies) + noise
    spectrum = Spectrum1D(spectral_axis=frequencies, flux=flux)

    # Assign uncertainties using the default standard deviation
    spectral_region = SpectralRegion(50 * u.um, 80 * u.um)
    spectrum_with_uncertainty = noise_region_uncertainty(
        spectrum, spectral_region)

    indices = np.nonzero((frequencies >= 50 * u.um)
                         & (frequencies <= 80 * u.um))
    expected_uncertainty = np.std(flux[indices]) * np.ones(len(frequencies))

    assert quantity_allclose(spectrum_with_uncertainty.uncertainty.array,
                             expected_uncertainty.value)
    assert isinstance(spectrum_with_uncertainty.uncertainty, StdDevUncertainty)

    # Same idea, but now with variance.
    spectrum_with_uncertainty = noise_region_uncertainty(
        spectrum, spectral_region, np.var)

    indices = np.nonzero((frequencies >= 50 * u.um)
                         & (frequencies <= 80 * u.um))
    expected_uncertainty = np.var(flux[indices]) * np.ones(len(frequencies))

    assert quantity_allclose(spectrum_with_uncertainty.uncertainty.array,
                             expected_uncertainty.value)
    assert isinstance(spectrum_with_uncertainty.uncertainty,
                      VarianceUncertainty)

    # Same idea, but now with inverse variance.
    spectrum_with_uncertainty = noise_region_uncertainty(
        spectrum, spectral_region, lambda x: 1 / np.var(x))

    indices = np.nonzero((frequencies >= 50 * u.um)
                         & (frequencies <= 80 * u.um))
    expected_uncertainty = 1 / np.var(flux[indices]) * np.ones(
        len(frequencies))

    assert quantity_allclose(spectrum_with_uncertainty.uncertainty.array,
                             expected_uncertainty.value)
    assert isinstance(spectrum_with_uncertainty.uncertainty, InverseVariance)

    # Now try with something that does not return Std, Var or IVar type of noise estimation
    with pytest.raises(ValueError):
        noise_region_uncertainty(spectrum, spectral_region,
                                 lambda x: np.std(x)**3)
コード例 #30
0
def test_io(tmpdir, obj):
    import h5py

    filename = str(tmpdir.join('thing.hdf5'))
    with h5py.File(filename, 'w') as f:
        obj.to_hdf5(f)

    obj2 = PhaseSpacePosition.from_hdf5(filename)
    assert quantity_allclose(obj.xyz, obj2.xyz)
    assert quantity_allclose(obj.v_xyz, obj2.v_xyz)
    assert obj.frame == obj2.frame
コード例 #31
0
ファイル: test_greatcircle.py プロジェクト: adrn/gala
def test_pole_from_endpoints():
    c1 = coord.SkyCoord(0*u.deg, 0*u.deg)
    c2 = coord.SkyCoord(90*u.deg, 0*u.deg)
    pole = pole_from_endpoints(c1, c2)
    assert quantity_allclose(pole.dec, 90*u.deg)

    c1 = coord.SkyCoord(0*u.deg, 0*u.deg)
    c2 = coord.SkyCoord(0*u.deg, 90*u.deg)
    pole = pole_from_endpoints(c1, c2)
    assert quantity_allclose(pole.ra, 270*u.deg)
    assert quantity_allclose(pole.dec, 0*u.deg)
コード例 #32
0
ファイル: test_greatcircle.py プロジェクト: silky/gala
def test_pole_from_endpoints():
    c1 = coord.SkyCoord(0 * u.deg, 0 * u.deg)
    c2 = coord.SkyCoord(90 * u.deg, 0 * u.deg)
    pole = pole_from_endpoints(c1, c2)
    assert quantity_allclose(pole.dec, 90 * u.deg)

    c1 = coord.SkyCoord(0 * u.deg, 0 * u.deg)
    c2 = coord.SkyCoord(0 * u.deg, 90 * u.deg)
    pole = pole_from_endpoints(c1, c2)
    assert quantity_allclose(pole.ra, 270 * u.deg)
    assert quantity_allclose(pole.dec, 0 * u.deg)
コード例 #33
0
    def test_compare(self):

        sph = NFWPotential(m=6E11 * u.Msun, r_s=20 * u.kpc, units=galactic)
        fla = NFWPotential(m=6E11 * u.Msun,
                           r_s=20 * u.kpc,
                           c=0.8,
                           units=galactic)
        tri = NFWPotential(m=6E11 * u.Msun,
                           r_s=20 * u.kpc,
                           b=0.9,
                           c=0.8,
                           units=galactic)

        xyz = np.zeros((3, 128))
        xyz[0] = np.logspace(-1., 3, xyz.shape[1])

        assert quantity_allclose(sph.value(xyz), fla.value(xyz))
        assert quantity_allclose(sph.value(xyz), tri.value(xyz))

        assert quantity_allclose(sph.gradient(xyz), fla.gradient(xyz))
        assert quantity_allclose(sph.gradient(xyz), tri.gradient(xyz))

        # assert quantity_allclose(sph.density(xyz), fla.density(xyz)) # TODO: fla density not implemented
        # assert quantity_allclose(sph.density(xyz), tri.density(xyz)) # TODO: tri density not implemented

        # ---

        tri = NFWPotential(m=6E11 * u.Msun,
                           r_s=20 * u.kpc,
                           a=0.9,
                           c=0.8,
                           units=galactic)

        xyz = np.zeros((3, 128))
        xyz[1] = np.logspace(-1., 3, xyz.shape[1])

        assert quantity_allclose(sph.value(xyz), fla.value(xyz))
        assert quantity_allclose(sph.value(xyz), tri.value(xyz))

        assert quantity_allclose(sph.gradient(xyz), fla.gradient(xyz))
        assert quantity_allclose(sph.gradient(xyz), tri.gradient(xyz))

        # assert quantity_allclose(sph.density(xyz), fla.density(xyz)) # TODO: fla density not implemented
        # assert quantity_allclose(sph.density(xyz), tri.density(xyz)) # TODO: tri density not implemented

        # ---

        xyz = np.zeros((3, 128))
        xyz[0] = np.logspace(-1., 3, xyz.shape[1])
        xyz[1] = np.logspace(-1., 3, xyz.shape[1])

        assert quantity_allclose(sph.value(xyz), fla.value(xyz))
        assert quantity_allclose(sph.gradient(xyz), fla.gradient(xyz))
コード例 #34
0
ファイル: transformations.py プロジェクト: grahamkerr/sunpy
def _observers_are_equal(obs_1, obs_2, string_ok=False):
    if string_ok:
        if obs_1 == obs_2:
            return True
    if not (isinstance(obs_1, BaseCoordinateFrame)
            and isinstance(obs_2, BaseCoordinateFrame)):
        raise ValueError(
            "To compare two observers, both must be instances of BaseCoordinateFrame. "
            "Cannot compare two observers {} and {}.".format(obs_1, obs_2))
    return (quantity_allclose(obs_1.lat, obs_2.lat)
            and quantity_allclose(obs_1.lon, obs_2.lon)
            and quantity_allclose(obs_1.radius, obs_2.radius))
コード例 #35
0
ファイル: test_greatcircle.py プロジェクト: silky/gala
def test_sph_midpoint():
    c1 = coord.SkyCoord(0 * u.deg, 0 * u.deg)
    c2 = coord.SkyCoord(90 * u.deg, 0 * u.deg)
    midpt = sph_midpoint(c1, c2)
    assert quantity_allclose(midpt.ra, 45 * u.deg)
    assert quantity_allclose(midpt.dec, 0 * u.deg)

    c1 = coord.SkyCoord(0 * u.deg, 0 * u.deg)
    c2 = coord.SkyCoord(0 * u.deg, 90 * u.deg)
    midpt = sph_midpoint(c1, c2)
    assert quantity_allclose(midpt.ra, 0 * u.deg)
    assert quantity_allclose(midpt.dec, 45 * u.deg)
コード例 #36
0
ファイル: test_greatcircle.py プロジェクト: adrn/gala
def test_sph_midpoint():
    c1 = coord.SkyCoord(0*u.deg, 0*u.deg)
    c2 = coord.SkyCoord(90*u.deg, 0*u.deg)
    midpt = sph_midpoint(c1, c2)
    assert quantity_allclose(midpt.ra, 45*u.deg)
    assert quantity_allclose(midpt.dec, 0*u.deg)

    c1 = coord.SkyCoord(0*u.deg, 0*u.deg)
    c2 = coord.SkyCoord(0*u.deg, 90*u.deg)
    midpt = sph_midpoint(c1, c2)
    assert quantity_allclose(midpt.ra, 0*u.deg)
    assert quantity_allclose(midpt.dec, 45*u.deg)
コード例 #37
0
def test_linear_excise_invert_from_spectrum():
    spec = Spectrum1D(flux=np.random.sample(100) * u.Jy,
                      spectral_axis=np.arange(100) * u.AA)
    inc_regs = SpectralRegion(80 * u.AA, 90 * u.AA) + \
               SpectralRegion(50 * u.AA, 60 * u.AA)
    exc_regs = inc_regs.invert_from_spectrum(spec)

    excised_spec = linear_exciser(spec, exc_regs)

    assert quantity_allclose(np.diff(excised_spec[50:60].flux),
                             np.diff(excised_spec[51:61].flux))
    assert quantity_allclose(np.diff(excised_spec[80:90].flux),
                             np.diff(excised_spec[81:91].flux))
コード例 #38
0
def test_linear_excise_invert_from_spectrum():
    spec = Spectrum1D(flux=np.random.sample(100) * u.Jy,
                      spectral_axis=np.arange(100) * u.AA)
    inc_regs = SpectralRegion(80 * u.AA, 90 * u.AA) + \
               SpectralRegion(50 * u.AA, 60 * u.AA)
    exc_regs = inc_regs.invert_from_spectrum(spec)

    excised_spec = linear_exciser(spec, exc_regs)

    assert quantity_allclose(np.diff(excised_spec[50:60].flux),
                             np.diff(excised_spec[51:61].flux))
    assert quantity_allclose(np.diff(excised_spec[80:90].flux),
                             np.diff(excised_spec[81:91].flux))
コード例 #39
0
def test_hcrs_hgs():
    # Get the current Earth location in HCRS
    now = Time(parse_time('now'))
    earth_hcrs = SkyCoord(get_body_barycentric('earth', now), frame='icrs', obstime=now).hcrs

    # Convert from HCRS to HGS
    earth_hgs = earth_hcrs.transform_to(HeliographicStonyhurst)

    # The HGS longitude of the Earth should be zero within numerical error
    assert quantity_allclose(earth_hgs.lon, 0*u.deg, atol=1e-12*u.deg)

    # The HGS latitude and radius should be within valid ranges
    assert quantity_allclose(earth_hgs.lat, 0*u.deg, atol=7.3*u.deg)
    assert quantity_allclose(earth_hgs.radius, 1*u.AU, atol=0.017*u.AU)
コード例 #40
0
def test_hcrs_hgs():
    # Get the current Earth location in HCRS
    adate = parse_time('2015/05/01 01:13:00')
    earth_hcrs = SkyCoord(get_body_barycentric('earth', adate), frame='icrs', obstime=adate).hcrs

    # Convert from HCRS to HGS
    earth_hgs = earth_hcrs.transform_to(HeliographicStonyhurst)

    # The HGS longitude of the Earth should be zero within numerical error
    # Due to an issue with wrapping at +-360, we shift it to pass the test.
    assert quantity_allclose((earth_hgs.lon+1*u.deg) % (360*u.deg), 1*u.deg, atol=1e-12*u.deg)

    # The HGS latitude and radius should be within valid ranges
    assert quantity_allclose(earth_hgs.lat, 0*u.deg, atol=7.3*u.deg)
    assert quantity_allclose(earth_hgs.radius, 1*u.AU, atol=0.017*u.AU)
コード例 #41
0
ファイル: test_orbit.py プロジェクト: adrn/gala
def test_io(tmpdir, obj):
    import h5py

    filename = str(tmpdir.join('thing.hdf5'))
    with h5py.File(filename, 'w') as f:
        obj.to_hdf5(f)

    obj2 = Orbit.from_hdf5(filename)
    assert quantity_allclose(obj.xyz, obj2.xyz)
    assert quantity_allclose(obj.v_xyz, obj2.v_xyz)
    if obj.t:
        assert quantity_allclose(obj.t, obj2.t)

    assert obj.frame == obj2.frame
    assert obj.potential == obj2.potential
コード例 #42
0
ファイル: test_representation_nd.py プロジェクト: adrn/gala
def test_init_repr():

    # Passing in x1, x2
    rep = NDCartesianRepresentation([1., 1.])
    assert rep.xyz.shape == (2,)

    # Passing in x1, x2
    rep = NDCartesianRepresentation(np.random.random(size=(2, 8)))
    assert rep.xyz.shape == (2,8)
    rep[:1]

    for n in range(1, 6+1):
        print('N: '+str(n))

        xs = np.random.uniform(size=(n, 16)) * u.one
        rep = NDCartesianRepresentation(xs)
        for i in range(1, n+1):
            assert hasattr(rep, 'x'+str(i))

        xs2 = rep.xyz
        assert quantity_allclose(xs, xs2)

        rep2 = rep[:8]

        assert rep.shape == (16,)
        assert rep2.shape == (8,)
コード例 #43
0
ファイル: test_representation_nd.py プロジェクト: adrn/gala
def test_init_diff():

    # Passing in x1, x2
    rep = NDCartesianDifferential([1., 1.])
    assert rep.d_xyz.shape == (2,)
    with pytest.raises(TypeError):
        rep[:1]

    # Passing in x1, x2
    rep = NDCartesianDifferential(np.random.random(size=(2, 8)))
    assert rep.d_xyz.shape == (2,8)
    rep[:1]

    for n in range(1, 6+1):
        print('N: '+str(n))

        xs = np.random.uniform(size=(n, 16)) * u.one
        rep = NDCartesianDifferential(xs)
        for i in range(1, n+1):
            assert hasattr(rep, 'd_x'+str(i))

        xs2 = rep.d_xyz
        assert quantity_allclose(xs, xs2)

        rep2 = rep[:8]

        assert rep.shape == (16,)
        assert rep2.shape == (8,)
コード例 #44
0
ファイル: frames.py プロジェクト: bwgref/sunpy
    def calculate_distance(self):
        """
        This method calculates the third coordinate of the Helioprojective
        frame. It assumes that the coordinate point is on the disk of the Sun
        at the rsun radius.

        If a point in the frame is off limb then NaN will be returned.

        Returns
        -------
        new_frame : `~sunpy.coordinates.frames.HelioProjective`
            A new frame instance with all the attributes of the original but
            now with a third coordinate.
        """
        # Skip if we already are 3D
        if (isinstance(self._data, SphericalRepresentation) and
                not (self.distance.unit is u.one and quantity_allclose(self.distance, 1*u.one))):
            return self

        if not isinstance(self.observer, BaseCoordinateFrame):
            raise ConvertError("Cannot calculate distance to the solar disk "
                               "for observer '{}' "
                               "without `obstime` being specified.".format(self.observer))

        rep = self.represent_as(UnitSphericalRepresentation)
        lat, lon = rep.lat, rep.lon
        alpha = np.arccos(np.cos(lat) * np.cos(lon)).to(lat.unit)
        c = self.observer.radius**2 - self.rsun**2
        b = -2 * self.observer.radius * np.cos(alpha)
        d = ((-1*b) - np.sqrt(b**2 - 4*c)) / 2

        return self.realize_frame(SphericalRepresentation(lon=lon,
                                                          lat=lat,
                                                          distance=d))
コード例 #45
0
ファイル: test_unc.py プロジェクト: astropy/specutils
def test_noise_estimate_uncertainty():
    # an alternate test with a more complicated input spectrum

    np.random.seed(42)

    # Create values for spectrum.
    frequencies = np.linspace(1, 100, 10000) * u.um
    g = models.Gaussian1D(amplitude=1*u.Jy, mean=10*u.um, stddev=1*u.um)
    noise = np.random.normal(0., 0.01, frequencies.shape) * u.Jy
    flux = g(frequencies) + noise
    spectrum = Spectrum1D(spectral_axis=frequencies, flux=flux)

    # Assign uncertainties using the default standard deviation
    spectral_region = SpectralRegion(50*u.um, 80*u.um)
    spectrum_with_uncertainty = noise_region_uncertainty(spectrum, spectral_region)

    indices = np.nonzero((frequencies >= 50*u.um) & (frequencies <= 80*u.um))
    expected_uncertainty = np.std(flux[indices])*np.ones(len(frequencies))

    assert quantity_allclose(spectrum_with_uncertainty.uncertainty.array,
                             expected_uncertainty.value)
    assert isinstance(spectrum_with_uncertainty.uncertainty, StdDevUncertainty)

    # Same idea, but now with variance.
    spectrum_with_uncertainty = noise_region_uncertainty(spectrum, spectral_region, np.var)

    indices = np.nonzero((frequencies >= 50*u.um) & (frequencies <= 80*u.um))
    expected_uncertainty = np.var(flux[indices])*np.ones(len(frequencies))

    assert quantity_allclose(spectrum_with_uncertainty.uncertainty.array,
                             expected_uncertainty.value)
    assert isinstance(spectrum_with_uncertainty.uncertainty, VarianceUncertainty)

    # Same idea, but now with inverse variance.
    spectrum_with_uncertainty = noise_region_uncertainty(spectrum, spectral_region,
                                                         lambda x: 1/np.var(x))

    indices = np.nonzero((frequencies >= 50*u.um) & (frequencies <= 80*u.um))
    expected_uncertainty = 1/np.var(flux[indices])*np.ones(len(frequencies))

    assert quantity_allclose(spectrum_with_uncertainty.uncertainty.array,
                             expected_uncertainty.value)
    assert isinstance(spectrum_with_uncertainty.uncertainty, InverseVariance)

    # Now try with something that does not return Std, Var or IVar type of noise estimation
    with pytest.raises(ValueError) as e_info:
        spectrum_with_uncertainty = noise_region_uncertainty(spectrum, spectral_region, lambda x: np.std(x)**3)
コード例 #46
0
ファイル: test_io.py プロジェクト: adrn/gary-old
def test_write_lm10(tmpdir):
    tmp_filename = str(tmpdir.join("potential.yml"))

    # more complex
    potential = LM10Potential(disk=dict(m=5E12*u.Msun))
    potential_default = LM10Potential()
    v1 = potential.value([4., 0, 0])
    v2 = potential_default.value([4., 0, 0])

    with open(tmp_filename,'w') as f:
        save(potential, f)

    save(potential, tmp_filename)
    p = load(tmp_filename)
    assert quantity_allclose(p['disk'].parameters['m'], 5E12*u.Msun)
    assert quantity_allclose(v1, p.value([4.,0,0]))
    assert not quantity_allclose(v2, p.value([4.,0,0]))
コード例 #47
0
def test_extract_region_pixels():
    spectrum = Spectrum1D(spectral_axis=np.linspace(4000, 10000, 25)*u.AA,
                          flux=np.arange(25)*u.Jy)
    region = SpectralRegion(10*u.pixel, 12*u.pixel)

    extracted = extract_region(spectrum, region)

    assert quantity_allclose(extracted.flux, [10, 11]*u.Jy)
コード例 #48
0
ファイル: test_unc.py プロジェクト: astropy/specutils
def test_noise_region_unc_multi():
    nspec = pure_noise_spectrum()

    multi_region = SpectralRegion([(5000*u.AA, 6000*u.AA), (900*u.pixel, 980*u.pixel)])

    unc_spec = noise_region_uncertainty(nspec, multi_region)

    assert quantity_allclose(unc_spec.uncertainty, 1*u.mJy, atol=.01) #this is a guess at the atol... need to finalize with real data
コード例 #49
0
def test_extract_region_mismatched_units():
    spectrum = Spectrum1D(spectral_axis=np.arange(25)*u.nm,
                          flux=np.arange(25)*u.Jy)

    region = SpectralRegion(100*u.AA, 119*u.AA)

    extracted = extract_region(spectrum, region)

    assert quantity_allclose(extracted.flux, [10, 11]*u.Jy)
コード例 #50
0
def test_hgs_hcrs():
    # This test checks the HGS->HCRS transformation by transforming from HGS to
    # HeliocentricTrueEcliptic (HTE).  It will fail if there are errors in Astropy's
    # HCRS->ICRS or ICRS->HTE transformations.

    # Use published HGS coordinates in the Astronomical Almanac (2013), pages C6-C7
    obstime = Time('2013-01-28')
    earth_hgs = SkyCoord(0*u.deg, -5.73*u.deg, 0.9848139*u.AU, frame=HeliographicStonyhurst,
                         obstime=obstime)

    # Transform to HTE at observation-time equinox
    earth_hte = earth_hgs.transform_to(HeliocentricTrueEcliptic(equinox=obstime))

    # Validate against published values from the Astronomical Almanac (2013), page C6 per page E2
    # The dominant source of inaccuracy is the limited precision of the published B0 used above
    assert quantity_allclose(earth_hte.lon, Angle('308d13m30.51s') - 180*u.deg, atol=5*u.arcsec)
    assert quantity_allclose(earth_hte.lat, -Angle('-0.27s'), atol=10*u.arcsec)
    assert quantity_allclose(earth_hte.distance, 0.9848139*u.AU, atol=5e-7*u.AU)
コード例 #51
0
ファイル: test_greatcircle.py プロジェクト: adrn/gala
def test_cls_init():
    pole = coord.SkyCoord(ra=72.2643*u.deg, dec=-20.6575*u.deg)
    GreatCircleICRSFrame(pole=pole)
    GreatCircleICRSFrame(pole=pole, ra0=160*u.deg)

    points = coord.SkyCoord(ra=[-38.8, 4.7]*u.deg, dec=[-45.1, -51.7]*u.deg)
    fr = GreatCircleICRSFrame.from_endpoints(points[0], points[1])
    assert quantity_allclose(fr.pole.ra, 359.1*u.deg, atol=1e-1*u.deg)
    assert quantity_allclose(fr.pole.dec, 38.2*u.deg, atol=1e-1*u.deg)

    fr = GreatCircleICRSFrame.from_endpoints(points[0], points[1],
                                             ra0=100*u.deg)

    fr = GreatCircleICRSFrame.from_endpoints(points[0], points[1],
                                             rotation=100*u.deg)

    with pytest.raises(ValueError):
        GreatCircleICRSFrame(pole=pole, ra0=160*u.deg,
                             center=pole)
コード例 #52
0
ファイル: test_core.py プロジェクト: adrn/gala
def test_composite():
    p1 = MyPotential(m=1., x0=[1.,0.,0.], units=usys)
    p2 = MyPotential(m=1., x0=[-1.,0.,0.], units=usys)

    p = CompositePotential(one=p1, two=p2)
    assert quantity_allclose(p.energy([0.,0.,0.]), -2*usys['energy']/usys['mass'])
    assert quantity_allclose(p.acceleration([0.,0.,0.]), 0.*usys['acceleration'])

    p1 = MyPotential(m=1., x0=[1.,0.,0.], units=usys)
    p2 = MyPotential(m=1., x0=[-1.,0.,0.], units=[u.kpc, u.yr, u.Msun, u.radian])
    with pytest.raises(ValueError):
        p = CompositePotential(one=p1, two=p2)

    p1 = MyPotential(m=1., x0=[1.,0.,0.], units=usys)
    p2 = MyPotential(m=1., x0=[-1.,0.,0.], units=usys)
    p = CompositePotential(one=p1, two=p2)
    assert u.au in p.units
    assert u.yr in p.units
    assert u.Msun in p.units
コード例 #53
0
ファイル: test_actionangle.py プロジェクト: adrn/gala
def test_fit_toy_potential():
    # integrate orbit in both toy potentials, make sure correct one is chosen
    true_m = 2.81E11
    true_b = 11.
    true_potential = IsochronePotential(m=true_m, b=true_b, units=galactic)
    orbit = true_potential.integrate_orbit([15.,0,0,0,0.2,0], dt=2., n_steps=10000)

    potential = fit_toy_potential(orbit)
    for k,v in true_potential.parameters.items():
        assert quantity_allclose(v, potential.parameters[k], rtol=1E-2)

    # -----------------------------------------------------------------
    true_omegas = np.array([0.011, 0.032, 0.045])
    true_potential = HarmonicOscillatorPotential(omega=true_omegas, units=galactic)
    orbit = true_potential.integrate_orbit([15.,1,2,0,0,0], dt=2., n_steps=10000)

    potential = fit_toy_potential(orbit)

    assert quantity_allclose(potential.parameters['omega'],
                             true_potential.parameters['omega'], rtol=1E-2)
コード例 #54
0
ファイル: test_nbody.py プロジェクト: adrn/gala
    def test_directnbody_integrate(self):
        # TODO: this is really a unit test, but we should have some functional tests
        # that check that the orbit integration is making sense!

        # First, compare with/without mass with no external potential:
        nbody1 = DirectNBody(self.w0,
                             particle_potentials=[None, None],
                             units=self.usys)
        nbody2 = DirectNBody(self.w0,
                             particle_potentials=self.particle_potentials,
                             units=self.usys)

        orbits1 = nbody1.integrate_orbit(dt=1*self.usys['time'],
                                         t1=0, t2=1*u.Myr)
        orbits2 = nbody2.integrate_orbit(dt=1*self.usys['time'],
                                         t1=0, t2=1*u.Myr)

        dx0 = orbits1[:, 0].xyz - orbits2[:, 0].xyz
        dx1 = orbits1[:, 1].xyz - orbits2[:, 1].xyz
        assert quantity_allclose(np.abs(dx1), 0*u.pc, atol=1e-13*u.pc)
        assert np.abs(dx0).max() > 50*u.pc

        # Now compare with/without mass with external potential:
        nbody1 = DirectNBody(self.w0,
                             particle_potentials=[None, None],
                             units=self.usys,
                             external_potential=self.ext_pot)
        nbody2 = DirectNBody(self.w0,
                             particle_potentials=self.particle_potentials,
                             units=self.usys,
                             external_potential=self.ext_pot)

        orbits1 = nbody1.integrate_orbit(dt=1*self.usys['time'],
                                         t1=0, t2=1*u.Myr)
        orbits2 = nbody2.integrate_orbit(dt=1*self.usys['time'],
                                         t1=0, t2=1*u.Myr)

        dx0 = orbits1[:, 0].xyz - orbits2[:, 0].xyz
        dx1 = orbits1[:, 1].xyz - orbits2[:, 1].xyz
        assert quantity_allclose(np.abs(dx1), 0*u.pc, atol=1e-13*u.pc)
        assert np.abs(dx0).max() > 50*u.pc
コード例 #55
0
ファイル: test_transformations.py プロジェクト: adrn/gala
def _helper(fi, fr, w, t=None):

    pos_r,vel_r = static_to_constantrotating(fi, fr, w, t=t)
    if isinstance(w, Orbit):
        w2 = Orbit(pos=pos_r, vel=vel_r, t=t)
    else:
        w2 = PhaseSpacePosition(pos=pos_r, vel=vel_r)
    pos_i,vel_i = constantrotating_to_static(fr, fi, w2, t=t)

    assert quantity_allclose(pos_i, w.xyz)
    assert quantity_allclose(vel_i, w.v_xyz)

    pos_i,vel_i = constantrotating_to_static(fr, fi, w, t=t)
    if isinstance(w, Orbit):
        w2 = Orbit(pos=pos_i, vel=vel_i, t=t)
    else:
        w2 = PhaseSpacePosition(pos=pos_i, vel=vel_i)
    pos_r,vel_r = static_to_constantrotating(fi, fr, w2, t=t)

    assert quantity_allclose(pos_r, w.xyz)
    assert quantity_allclose(vel_r, w.v_xyz)
コード例 #56
0
ファイル: test_analysis.py プロジェクト: astropy/specutils
def test_gaussian_fwhm_uncentered(mean):

    np.random.seed(42)

    # Create an uncentered gaussian spectrum for testing
    frequencies = np.linspace(0, 10, 1000) * u.GHz
    g1 = models.Gaussian1D(amplitude=5*u.Jy, mean=mean*u.GHz, stddev=0.8*u.GHz)

    spectrum = Spectrum1D(spectral_axis=frequencies, flux=g1(frequencies))

    result = gaussian_fwhm(spectrum)

    expected = g1.stddev * gaussian_sigma_to_fwhm
    assert quantity_allclose(result, expected, atol=0.05*u.GHz)
コード例 #57
0
ファイル: transformations.py プロジェクト: Hypnus1803/sunpy
def hpc_to_hpc(heliopcoord, heliopframe):
    """
    This converts from HPC to HPC, with different observer location parameters.
    It does this by transforming through HGS.
    """
    if (heliopcoord.observer == heliopframe.observer or
        (quantity_allclose(heliopcoord.observer.lat, heliopframe.observer.lat) and
         quantity_allclose(heliopcoord.observer.lon, heliopframe.observer.lon) and
         quantity_allclose(heliopcoord.observer.radius, heliopframe.observer.radius))):
        return heliopframe.realize_frame(heliopcoord._data)

    if not isinstance(heliopframe.observer, BaseCoordinateFrame):
        raise ConvertError("Cannot transform between helioprojective frames "
                           "without `obstime` being specified for observer {}.".format(heliopframe.observer))
    if not isinstance(heliopcoord.observer, BaseCoordinateFrame):
        raise ConvertError("Cannot transform between helioprojective frames "
                           "without `obstime` being specified for observer {}.".format(heliopcoord.observer))

    hgs = heliopcoord.transform_to(HeliographicStonyhurst)
    hgs.observer = heliopframe.observer
    hpc = hgs.transform_to(heliopframe)

    return hpc
コード例 #58
0
ファイル: test_analysis.py プロジェクト: astropy/specutils
def test_gaussian_sigma_width():

    np.random.seed(42)

    # Create a (centered) gaussian spectrum for testing
    mean = 5
    frequencies = np.linspace(0, mean*2, 100) * u.GHz
    g1 = models.Gaussian1D(amplitude=5*u.Jy, mean=mean*u.GHz, stddev=0.8*u.GHz)

    spectrum = Spectrum1D(spectral_axis=frequencies, flux=g1(frequencies))

    result = gaussian_sigma_width(spectrum)

    assert quantity_allclose(result, g1.stddev, atol=0.01*u.GHz)
コード例 #59
0
ファイル: test_analysis.py プロジェクト: astropy/specutils
def test_equivalent_width_regions():

    np.random.seed(42)

    frequencies = np.linspace(1, 100, 10000) * u.GHz
    g = models.Gaussian1D(amplitude=1*u.Jy, mean=10*u.GHz, stddev=1*u.GHz)
    noise = np.random.normal(0., 0.001, frequencies.shape) * u.Jy
    flux = g(frequencies) + noise + 1*u.Jy

    spec = Spectrum1D(spectral_axis=frequencies, flux=flux)
    cont_norm_spec = spec / np.median(spec.flux)
    result = equivalent_width(cont_norm_spec, regions=SpectralRegion(3*u.GHz, 97*u.GHz))

    expected = -(np.sqrt(2*np.pi) * u.GHz)

    assert quantity_allclose(result, expected, atol=0.01*u.GHz)
コード例 #60
0
ファイル: test_analysis.py プロジェクト: astropy/specutils
def test_equivalent_width_continuum(continuum):

    np.random.seed(42)

    frequencies = np.linspace(1, 100, 10000) * u.GHz
    g = models.Gaussian1D(amplitude=1*u.Jy, mean=10*u.GHz, stddev=1*u.GHz)
    noise = np.random.normal(0., 0.01, frequencies.shape) * u.Jy
    flux = g(frequencies) + noise + continuum

    spectrum = Spectrum1D(spectral_axis=frequencies, flux=flux)

    result = equivalent_width(spectrum, continuum=continuum)

    assert result.unit.is_equivalent(spectrum.spectral_axis_unit)

    # Since this is an emission line, we expect the equivalent width value to
    # be negative
    expected = -(np.sqrt(2*np.pi) * u.GHz) / continuum.value

    assert quantity_allclose(result, expected, atol=0.01*u.GHz)