def test_supergalactic(): """ Check Galactic<->Supergalactic and Galactic<->ICRS conversion. """ # Check supergalactic North pole. npole = Galactic(l=47.37*u.degree, b=+6.32*u.degree) assert allclose(npole.transform_to(Supergalactic).sgb.deg, +90, atol=1e-9) # Check the origin of supergalactic longitude. lon0 = Supergalactic(sgl=0*u.degree, sgb=0*u.degree) lon0_gal = lon0.transform_to(Galactic) assert allclose(lon0_gal.l.deg, 137.37, atol=1e-9) assert allclose(lon0_gal.b.deg, 0, atol=1e-9) # Test Galactic<->ICRS with some positions that appear in Foley et al. 2008 # (http://adsabs.harvard.edu/abs/2008A%26A...484..143F) # GRB 021219 supergalactic = Supergalactic(sgl=29.91*u.degree, sgb=+73.72*u.degree) icrs = SkyCoord('18h50m27s +31d57m17s') assert supergalactic.separation(icrs) < 0.005 * u.degree # GRB 030320 supergalactic = Supergalactic(sgl=-174.44*u.degree, sgb=+46.17*u.degree) icrs = SkyCoord('17h51m36s -25d18m52s') assert supergalactic.separation(icrs) < 0.005 * u.degree
def test_lsr_sanity(): # random numbers, but zero velocity in ICRS frame icrs = ICRS(ra=15.1241*u.deg, dec=17.5143*u.deg, distance=150.12*u.pc, pm_ra_cosdec=0*u.mas/u.yr, pm_dec=0*u.mas/u.yr, radial_velocity=0*u.km/u.s) lsr = icrs.transform_to(LSR()) lsr_diff = lsr.data.differentials['s'] cart_lsr_vel = lsr_diff.represent_as(CartesianRepresentation, base=lsr.data) lsr_vel = ICRS(cart_lsr_vel) gal_lsr = lsr_vel.transform_to(Galactic()).cartesian.xyz assert allclose(gal_lsr.to(u.km/u.s, u.dimensionless_angles()), lsr.v_bary.d_xyz) # moving with LSR velocity lsr = LSR(ra=15.1241*u.deg, dec=17.5143*u.deg, distance=150.12*u.pc, pm_ra_cosdec=0*u.mas/u.yr, pm_dec=0*u.mas/u.yr, radial_velocity=0*u.km/u.s) icrs = lsr.transform_to(ICRS()) icrs_diff = icrs.data.differentials['s'] cart_vel = icrs_diff.represent_as(CartesianRepresentation, base=icrs.data) vel = ICRS(cart_vel) gal_icrs = vel.transform_to(Galactic()).cartesian.xyz assert allclose(gal_icrs.to(u.km/u.s, u.dimensionless_angles()), -lsr.v_bary.d_xyz)
def test_proj_separations(): """ Test angular separation functionality """ c1 = ICRS(ra=0 * u.deg, dec=0 * u.deg) c2 = ICRS(ra=0 * u.deg, dec=1 * u.deg) sep = c2.separation(c1) # returns an Angle object assert isinstance(sep, Angle) assert_allclose(sep.degree, 1.) assert_allclose(sep.arcminute, 60.) # these operations have ambiguous interpretations for points on a sphere with pytest.raises(TypeError): c1 + c2 with pytest.raises(TypeError): c1 - c2 ngp = Galactic(l=0 * u.degree, b=90 * u.degree) ncp = ICRS(ra=0 * u.degree, dec=90 * u.degree) # if there is a defined conversion between the relevant coordinate systems, # it will be automatically performed to get the right angular separation assert_allclose( ncp.separation(ngp.transform_to(ICRS())).degree, ncp.separation(ngp).degree) # distance from the north galactic pole to celestial pole assert_allclose( ncp.separation(ngp.transform_to(ICRS())).degree, 62.87174758503201)
def test_proj_separations(): """ Test angular separation functionality """ c1 = ICRS(ra=0*u.deg, dec=0*u.deg) c2 = ICRS(ra=0*u.deg, dec=1*u.deg) sep = c2.separation(c1) # returns an Angle object assert isinstance(sep, Angle) assert sep.degree == 1 assert_allclose(sep.arcminute, 60.) # these operations have ambiguous interpretations for points on a sphere with pytest.raises(TypeError): c1 + c2 with pytest.raises(TypeError): c1 - c2 ngp = Galactic(l=0*u.degree, b=90*u.degree) ncp = ICRS(ra=0*u.degree, dec=90*u.degree) # if there is a defined conversion between the relevant coordinate systems, # it will be automatically performed to get the right angular separation assert_allclose(ncp.separation(ngp.transform_to(ICRS)).degree, ncp.separation(ngp).degree) # distance from the north galactic pole to celestial pole assert_allclose(ncp.separation(ngp.transform_to(ICRS)).degree, 62.87174758503201)
def test_galactocentric(): # when z_sun=0, transformation should be very similar to Galactic icrs_coord = ICRS(ra=np.linspace(0, 360, 10) * u.deg, dec=np.linspace(-90, 90, 10) * u.deg, distance=1. * u.kpc) g_xyz = icrs_coord.transform_to(Galactic).cartesian.xyz with galactocentric_frame_defaults.set('pre-v4.0'): gc_xyz = icrs_coord.transform_to(Galactocentric(z_sun=0 * u.kpc)).cartesian.xyz diff = np.abs(g_xyz - gc_xyz) assert allclose(diff[0], 8.3 * u.kpc, atol=1E-5 * u.kpc) assert allclose(diff[1:], 0 * u.kpc, atol=1E-5 * u.kpc) # generate some test coordinates g = Galactic(l=[0, 0, 45, 315] * u.deg, b=[-45, 45, 0, 0] * u.deg, distance=[np.sqrt(2)] * 4 * u.kpc) with galactocentric_frame_defaults.set('pre-v4.0'): xyz = g.transform_to( Galactocentric(galcen_distance=1. * u.kpc, z_sun=0. * u.pc)).cartesian.xyz true_xyz = np.array([[0, 0, -1.], [0, 0, 1], [0, 1, 0], [0, -1, 0] ]).T * u.kpc assert allclose(xyz.to(u.kpc), true_xyz.to(u.kpc), atol=1E-5 * u.kpc) # check that ND arrays work # from Galactocentric to Galactic x = np.linspace(-10., 10., 100) * u.kpc y = np.linspace(-10., 10., 100) * u.kpc z = np.zeros_like(x) # from Galactic to Galactocentric l = np.linspace(15, 30., 100) * u.deg b = np.linspace(-10., 10., 100) * u.deg d = np.ones_like(l.value) * u.kpc with galactocentric_frame_defaults.set('latest'): g1 = Galactocentric(x=x, y=y, z=z) g2 = Galactocentric(x=x.reshape(100, 1, 1), y=y.reshape(100, 1, 1), z=z.reshape(100, 1, 1)) g1t = g1.transform_to(Galactic) g2t = g2.transform_to(Galactic) assert_allclose(g1t.cartesian.xyz, g2t.cartesian.xyz[:, :, 0, 0]) g1 = Galactic(l=l, b=b, distance=d) g2 = Galactic(l=l.reshape(100, 1, 1), b=b.reshape(100, 1, 1), distance=d.reshape(100, 1, 1)) g1t = g1.transform_to(Galactocentric) g2t = g2.transform_to(Galactocentric) np.testing.assert_almost_equal(g1t.cartesian.xyz.value, g2t.cartesian.xyz.value[:, :, 0, 0])
def test_galactocentric(): # when z_sun=0, transformation should be very similar to Galactic icrs_coord = ICRS(ra=np.linspace(0, 360, 10)*u.deg, dec=np.linspace(-90, 90, 10)*u.deg, distance=1.*u.kpc) g_xyz = icrs_coord.transform_to(Galactic).cartesian.xyz gc_xyz = icrs_coord.transform_to(Galactocentric(z_sun=0*u.kpc)).cartesian.xyz diff = np.abs(g_xyz - gc_xyz) assert allclose(diff[0], 8.3*u.kpc, atol=1E-5*u.kpc) assert allclose(diff[1:], 0*u.kpc, atol=1E-5*u.kpc) # generate some test coordinates g = Galactic(l=[0, 0, 45, 315]*u.deg, b=[-45, 45, 0, 0]*u.deg, distance=[np.sqrt(2)]*4*u.kpc) xyz = g.transform_to(Galactocentric(galcen_distance=1.*u.kpc, z_sun=0.*u.pc)).cartesian.xyz true_xyz = np.array([[0, 0, -1.], [0, 0, 1], [0, 1, 0], [0, -1, 0]]).T*u.kpc assert allclose(xyz.to(u.kpc), true_xyz.to(u.kpc), atol=1E-5*u.kpc) # check that ND arrays work # from Galactocentric to Galactic x = np.linspace(-10., 10., 100) * u.kpc y = np.linspace(-10., 10., 100) * u.kpc z = np.zeros_like(x) g1 = Galactocentric(x=x, y=y, z=z) g2 = Galactocentric(x=x.reshape(100, 1, 1), y=y.reshape(100, 1, 1), z=z.reshape(100, 1, 1)) g1t = g1.transform_to(Galactic) g2t = g2.transform_to(Galactic) assert_allclose(g1t.cartesian.xyz, g2t.cartesian.xyz[:, :, 0, 0]) # from Galactic to Galactocentric l = np.linspace(15, 30., 100) * u.deg b = np.linspace(-10., 10., 100) * u.deg d = np.ones_like(l.value) * u.kpc g1 = Galactic(l=l, b=b, distance=d) g2 = Galactic(l=l.reshape(100, 1, 1), b=b.reshape(100, 1, 1), distance=d.reshape(100, 1, 1)) g1t = g1.transform_to(Galactocentric) g2t = g2.transform_to(Galactocentric) np.testing.assert_almost_equal(g1t.cartesian.xyz.value, g2t.cartesian.xyz.value[:, :, 0, 0])
def test_setitem_exceptions(): from astropy.coordinates.builtin_frames import FK4, Galactic obstime = 'B1950' sc0 = FK4([1, 2]*u.deg, [3, 4]*u.deg) sc2 = FK4([10, 20]*u.deg, [30, 40]*u.deg, obstime=obstime) sc1 = Galactic(sc0.ra, sc0.dec) with pytest.raises(TypeError, match='can only set from object of same class: ' 'Galactic vs. FK4'): sc1[0] = sc2[0] sc1 = FK4(sc0.ra, sc0.dec, obstime='B2001') with pytest.raises(ValueError, match='can only set frame item from an equivalent frame'): sc1[0] = sc2[0] sc1 = FK4(sc0.ra[0], sc0.dec[0], obstime=obstime) with pytest.raises(TypeError, match="scalar 'FK4' frame object does not support " 'item assignment'): sc1[0] = sc2[0] sc1 = FK4(obstime=obstime) with pytest.raises(ValueError, match='cannot set frame which has no data'): sc1[0] = sc2[0] sc1 = FK4(sc0.ra, sc0.dec, obstime=[obstime, 'B1980']) with pytest.raises(ValueError, match='can only set frame item from an equivalent frame'): sc1[0] = sc2[0] # Wrong shape sc1 = FK4([sc0.ra], [sc0.dec], obstime=[obstime, 'B1980']) with pytest.raises(ValueError, match='can only set frame item from an equivalent frame'): sc1[0] = sc2[0]
def test_fk5_galactic(): """ Check that FK5 -> Galactic gives the same as FK5 -> FK4 -> Galactic. """ fk5 = FK5(ra=1*u.deg, dec=2*u.deg) direct = fk5.transform_to(Galactic()) indirect = fk5.transform_to(FK4()).transform_to(Galactic()) assert direct.separation(indirect).degree < 1.e-10 direct = fk5.transform_to(Galactic()) indirect = fk5.transform_to(FK4NoETerms()).transform_to(Galactic()) assert direct.separation(indirect).degree < 1.e-10
def test_api(): # transform observed Barycentric velocities to full-space Galactocentric with galactocentric_frame_defaults.set('latest'): gc_frame = Galactocentric() icrs = ICRS(ra=151. * u.deg, dec=-16 * u.deg, distance=101 * u.pc, pm_ra_cosdec=21 * u.mas / u.yr, pm_dec=-71 * u.mas / u.yr, radial_velocity=71 * u.km / u.s) icrs.transform_to(gc_frame) # transform a set of ICRS proper motions to Galactic icrs = ICRS(ra=151. * u.deg, dec=-16 * u.deg, pm_ra_cosdec=21 * u.mas / u.yr, pm_dec=-71 * u.mas / u.yr) icrs.transform_to(Galactic()) # transform a Barycentric RV to a GSR RV icrs = ICRS(ra=151. * u.deg, dec=-16 * u.deg, distance=1. * u.pc, pm_ra_cosdec=0 * u.mas / u.yr, pm_dec=0 * u.mas / u.yr, radial_velocity=71 * u.km / u.s) icrs.transform_to(Galactocentric())
def test_all_arg_options(kwargs): # Above is a list of all possible valid combinations of arguments. # Here we do a simple thing and just verify that passing them in, we have # access to the relevant attributes from the resulting object icrs = ICRS(**kwargs) gal = icrs.transform_to(Galactic()) repr_gal = repr(gal) for k in kwargs: if k == 'differential_type': continue getattr(icrs, k) if 'pm_ra_cosdec' in kwargs: # should have both assert 'pm_l_cosb' in repr_gal assert 'pm_b' in repr_gal assert 'mas / yr' in repr_gal if 'radial_velocity' not in kwargs: assert 'radial_velocity' not in repr_gal if 'radial_velocity' in kwargs: assert 'radial_velocity' in repr_gal assert 'km / s' in repr_gal if 'pm_ra_cosdec' not in kwargs: assert 'pm_l_cosb' not in repr_gal assert 'pm_b' not in repr_gal
def test_skyoffset_names(): origin1 = ICRS(45 * u.deg, 45 * u.deg) aframe1 = SkyOffsetFrame(origin=origin1) assert type(aframe1).__name__ == 'SkyOffsetICRS' origin2 = Galactic(45 * u.deg, 45 * u.deg) aframe2 = SkyOffsetFrame(origin=origin2) assert type(aframe2).__name__ == 'SkyOffsetGalactic'
def test_static_matrix_combine_paths(): """ Check that combined staticmatrixtransform matrices provide the same transformation as using an intermediate transformation. This is somewhat of a regression test for #7706 """ from astropy.coordinates.baseframe import BaseCoordinateFrame from astropy.coordinates.matrix_utilities import rotation_matrix class AFrame(BaseCoordinateFrame): default_representation = r.SphericalRepresentation default_differential = r.SphericalCosLatDifferential t1 = t.StaticMatrixTransform(rotation_matrix(30.*u.deg, 'z'), ICRS, AFrame) t1.register(frame_transform_graph) t2 = t.StaticMatrixTransform(rotation_matrix(30.*u.deg, 'z').T, AFrame, ICRS) t2.register(frame_transform_graph) class BFrame(BaseCoordinateFrame): default_representation = r.SphericalRepresentation default_differential = r.SphericalCosLatDifferential t3 = t.StaticMatrixTransform(rotation_matrix(30.*u.deg, 'x'), ICRS, BFrame) t3.register(frame_transform_graph) t4 = t.StaticMatrixTransform(rotation_matrix(30.*u.deg, 'x').T, BFrame, ICRS) t4.register(frame_transform_graph) c = Galactic(123*u.deg, 45*u.deg) c1 = c.transform_to(BFrame) # direct c2 = c.transform_to(AFrame).transform_to(BFrame) # thru A c3 = c.transform_to(ICRS).transform_to(BFrame) # thru ICRS assert quantity_allclose(c1.lon, c2.lon) assert quantity_allclose(c1.lat, c2.lat) assert quantity_allclose(c1.lon, c3.lon) assert quantity_allclose(c1.lat, c3.lat) for t_ in [t1, t2, t3, t4]: t_.unregister(frame_transform_graph)
def test_static_matrix_combine_paths(): """ Check that combined staticmatrixtransform matrices provide the same transformation as using an intermediate transformation. This is somewhat of a regression test for #7706 """ from astropy.coordinates.baseframe import BaseCoordinateFrame from astropy.coordinates.matrix_utilities import rotation_matrix class AFrame(BaseCoordinateFrame): default_representation = r.SphericalRepresentation default_differential = r.SphericalCosLatDifferential t1 = t.StaticMatrixTransform(rotation_matrix(30.*u.deg, 'z'), ICRS, AFrame) t1.register(frame_transform_graph) t2 = t.StaticMatrixTransform(rotation_matrix(30.*u.deg, 'z').T, AFrame, ICRS) t2.register(frame_transform_graph) class BFrame(BaseCoordinateFrame): default_representation = r.SphericalRepresentation default_differential = r.SphericalCosLatDifferential t3 = t.StaticMatrixTransform(rotation_matrix(30.*u.deg, 'x'), ICRS, BFrame) t3.register(frame_transform_graph) t4 = t.StaticMatrixTransform(rotation_matrix(30.*u.deg, 'x').T, BFrame, ICRS) t4.register(frame_transform_graph) c = Galactic(123*u.deg, 45*u.deg) c1 = c.transform_to(BFrame()) # direct c2 = c.transform_to(AFrame()).transform_to(BFrame()) # thru A c3 = c.transform_to(ICRS()).transform_to(BFrame()) # thru ICRS assert quantity_allclose(c1.lon, c2.lon) assert quantity_allclose(c1.lat, c2.lat) assert quantity_allclose(c1.lon, c3.lon) assert quantity_allclose(c1.lat, c3.lat) for t_ in [t1, t2, t3, t4]: t_.unregister(frame_transform_graph)
def test_galactic_fk4(): lines = get_pkg_data_contents('data/galactic_fk4.csv').split('\n') t = Table.read(lines, format='ascii', delimiter=',', guess=False) if N_ACCURACY_TESTS >= len(t): idxs = range(len(t)) else: idxs = np.random.randint(len(t), size=N_ACCURACY_TESTS) diffarcsec1 = [] diffarcsec2 = [] for i in idxs: # Extract row r = t[int(i)] # int here is to get around a py 3.x astropy.table bug # Galactic to FK4 c1 = Galactic(l=r['lon_in'] * u.deg, b=r['lat_in'] * u.deg) c2 = c1.transform_to(FK4(equinox=Time(r['equinox_fk4'], scale='utc'))) # Find difference diff = angular_separation(c2.ra.radian, c2.dec.radian, np.radians(r['ra_fk4']), np.radians(r['dec_fk4'])) diffarcsec1.append(np.degrees(diff) * 3600.) # FK4 to Galactic c1 = FK4(ra=r['lon_in'] * u.deg, dec=r['lat_in'] * u.deg, obstime=Time(r['obstime'], scale='utc'), equinox=Time(r['equinox_fk4'], scale='utc')) c2 = c1.transform_to(Galactic) # Find difference diff = angular_separation(c2.l.radian, c2.b.radian, np.radians(r['lon_gal']), np.radians(r['lat_gal'])) diffarcsec2.append(np.degrees(diff) * 3600.) np.testing.assert_array_less(diffarcsec1, TOLERANCE) np.testing.assert_array_less(diffarcsec2, TOLERANCE)
def test_galactic_fk4(): lines = get_pkg_data_contents('galactic_fk4.csv').split('\n') t = Table.read(lines, format='ascii', delimiter=',', guess=False) if N_ACCURACY_TESTS >= len(t): idxs = range(len(t)) else: idxs = np.random.randint(len(t), size=N_ACCURACY_TESTS) diffarcsec1 = [] diffarcsec2 = [] for i in idxs: # Extract row r = t[int(i)] # int here is to get around a py 3.x astropy.table bug # Galactic to FK4 c1 = Galactic(l=r['lon_in']*u.deg, b=r['lat_in']*u.deg) c2 = c1.transform_to(FK4(equinox=Time(r['equinox_fk4'], scale='utc'))) # Find difference diff = angular_separation(c2.ra.radian, c2.dec.radian, np.radians(r['ra_fk4']), np.radians(r['dec_fk4'])) diffarcsec1.append(np.degrees(diff) * 3600.) # FK4 to Galactic c1 = FK4(ra=r['lon_in']*u.deg, dec=r['lat_in']*u.deg, obstime=Time(r['obstime'], scale='utc'), equinox=Time(r['equinox_fk4'], scale='utc')) c2 = c1.transform_to(Galactic) # Find difference diff = angular_separation(c2.l.radian, c2.b.radian, np.radians(r['lon_gal']), np.radians(r['lat_gal'])) diffarcsec2.append(np.degrees(diff) * 3600.) np.testing.assert_array_less(diffarcsec1, TOLERANCE) np.testing.assert_array_less(diffarcsec2, TOLERANCE)
def test_faux_fk5_galactic(): from astropy.coordinates.builtin_frames.galactic_transforms import fk5_to_gal, _gal_to_fk5 class Galactic2(Galactic): pass dt = 1000 * u.s @frame_transform_graph.transform(FunctionTransformWithFiniteDifference, FK5, Galactic2, finite_difference_dt=dt, symmetric_finite_difference=True, finite_difference_frameattr_name=None) def fk5_to_gal2(fk5_coo, gal_frame): trans = DynamicMatrixTransform(fk5_to_gal, FK5, Galactic2) return trans(fk5_coo, gal_frame) @frame_transform_graph.transform(FunctionTransformWithFiniteDifference, Galactic2, ICRS, finite_difference_dt=dt, symmetric_finite_difference=True, finite_difference_frameattr_name=None) def gal2_to_fk5(gal_coo, fk5_frame): trans = DynamicMatrixTransform(_gal_to_fk5, Galactic2, FK5) return trans(gal_coo, fk5_frame) c1 = FK5(ra=150 * u.deg, dec=-17 * u.deg, radial_velocity=83 * u.km / u.s, pm_ra_cosdec=-41 * u.mas / u.yr, pm_dec=16 * u.mas / u.yr, distance=150 * u.pc) c2 = c1.transform_to(Galactic2()) c3 = c1.transform_to(Galactic()) # compare the matrix and finite-difference calculations assert quantity_allclose(c2.pm_l_cosb, c3.pm_l_cosb, rtol=1e-4) assert quantity_allclose(c2.pm_b, c3.pm_b, rtol=1e-4)
def test_create_orderered_data(): from astropy.coordinates.builtin_frames import ICRS, Galactic, AltAz TOL = 1e-10 * u.deg i = ICRS(1 * u.deg, 2 * u.deg) assert (i.ra - 1 * u.deg) < TOL assert (i.dec - 2 * u.deg) < TOL g = Galactic(1 * u.deg, 2 * u.deg) assert (g.l - 1 * u.deg) < TOL assert (g.b - 2 * u.deg) < TOL a = AltAz(1 * u.deg, 2 * u.deg) assert (a.az - 1 * u.deg) < TOL assert (a.alt - 2 * u.deg) < TOL with pytest.raises(TypeError): ICRS(1 * u.deg, 2 * u.deg, 1 * u.deg, 2 * u.deg) with pytest.raises(TypeError): sph = r.SphericalRepresentation(1 * u.deg, 2 * u.deg, 3 * u.kpc) ICRS(sph, 1 * u.deg, 2 * u.deg)
def test_xhip_galactic(hip, ra, dec, pmra, pmdec, glon, glat, dist, pmglon, pmglat, rv, U, V, W): i = ICRS(ra * u.deg, dec * u.deg, dist * u.pc, pm_ra_cosdec=pmra * u.marcsec / u.yr, pm_dec=pmdec * u.marcsec / u.yr, radial_velocity=rv * u.km / u.s) g = i.transform_to(Galactic()) # precision is limited by 2-deciimal digit string representation of pms assert quantity_allclose(g.pm_l_cosb, pmglon * u.marcsec / u.yr, atol=.01 * u.marcsec / u.yr) assert quantity_allclose(g.pm_b, pmglat * u.marcsec / u.yr, atol=.01 * u.marcsec / u.yr) # make sure UVW also makes sense uvwg = g.cartesian.differentials['s'] # precision is limited by 1-decimal digit string representation of vels assert quantity_allclose(uvwg.d_x, U * u.km / u.s, atol=.1 * u.km / u.s) assert quantity_allclose(uvwg.d_y, V * u.km / u.s, atol=.1 * u.km / u.s) assert quantity_allclose(uvwg.d_z, W * u.km / u.s, atol=.1 * u.km / u.s)
def test_distances(): """ Tests functionality for Coordinate class distances and cartesian transformations. """ ''' Distances can also be specified, and allow for a full 3D definition of a coordinate. ''' # try all the different ways to initialize a Distance distance = Distance(12, u.parsec) Distance(40, unit=u.au) Distance(value=5, unit=u.kpc) # need to provide a unit with pytest.raises(u.UnitsError): Distance(12) # standard units are pre-defined npt.assert_allclose(distance.lyr, 39.138765325702551) npt.assert_allclose(distance.km, 370281309776063.0) # Coordinate objects can be assigned a distance object, giving them a full # 3D position c = Galactic(l=158.558650 * u.degree, b=-43.350066 * u.degree, distance=Distance(12, u.parsec)) # or initialize distances via redshifts - this is actually tested in the # function below that checks for scipy. This is kept here as an example # c.distance = Distance(z=0.2) # uses current cosmology # with whatever your preferred cosmology may be # c.distance = Distance(z=0.2, cosmology=WMAP5) # Coordinate objects can be initialized with a distance using special # syntax c1 = Galactic(l=158.558650 * u.deg, b=-43.350066 * u.deg, distance=12 * u.kpc) # Coordinate objects can be instantiated with cartesian coordinates # Internally they will immediately be converted to two angles + a distance cart = CartesianRepresentation(x=2 * u.pc, y=4 * u.pc, z=8 * u.pc) c2 = Galactic(cart) sep12 = c1.separation_3d(c2) # returns a *3d* distance between the c1 and c2 coordinates # not that this does *not* assert isinstance(sep12, Distance) npt.assert_allclose(sep12.pc, 12005.784163916317, 10) ''' All spherical coordinate systems with distances can be converted to cartesian coordinates. ''' cartrep2 = c2.cartesian assert isinstance(cartrep2.x, u.Quantity) npt.assert_allclose(cartrep2.x.value, 2) npt.assert_allclose(cartrep2.y.value, 4) npt.assert_allclose(cartrep2.z.value, 8) # with no distance, the unit sphere is assumed when converting to cartesian c3 = Galactic(l=158.558650 * u.degree, b=-43.350066 * u.degree, distance=None) unitcart = c3.cartesian npt.assert_allclose( ((unitcart.x**2 + unitcart.y**2 + unitcart.z**2)**0.5).value, 1.0) # TODO: choose between these when CartesianRepresentation gets a definite # decision on whether or not it gets __add__ # # CartesianRepresentation objects can be added and subtracted, which are # vector/elementwise they can also be given as arguments to a coordinate # system # csum = ICRS(c1.cartesian + c2.cartesian) csumrep = CartesianRepresentation(c1.cartesian.xyz + c2.cartesian.xyz) csum = ICRS(csumrep) npt.assert_allclose(csumrep.x.value, -8.12016610185) npt.assert_allclose(csumrep.y.value, 3.19380597435) npt.assert_allclose(csumrep.z.value, -8.2294483707) npt.assert_allclose(csum.ra.degree, 158.529401774) npt.assert_allclose(csum.dec.degree, -43.3235825777) npt.assert_allclose(csum.distance.kpc, 11.9942200501)
def test_celestial_frame_to_wcs(): # Import astropy.coordinates here to avoid circular imports from astropy.coordinates import ICRS, ITRS, FK5, FK4, FK4NoETerms, Galactic, BaseCoordinateFrame class FakeFrame(BaseCoordinateFrame): pass frame = FakeFrame() with pytest.raises(ValueError) as exc: celestial_frame_to_wcs(frame) assert exc.value.args[0] == ("Could not determine WCS corresponding to " "the specified coordinate frame.") frame = ICRS() mywcs = celestial_frame_to_wcs(frame) mywcs.wcs.set() assert tuple(mywcs.wcs.ctype) == ('RA---TAN', 'DEC--TAN') assert mywcs.wcs.radesys == 'ICRS' assert np.isnan(mywcs.wcs.equinox) assert mywcs.wcs.lonpole == 180 assert mywcs.wcs.latpole == 0 frame = FK5(equinox='J1987') mywcs = celestial_frame_to_wcs(frame) assert tuple(mywcs.wcs.ctype) == ('RA---TAN', 'DEC--TAN') assert mywcs.wcs.radesys == 'FK5' assert mywcs.wcs.equinox == 1987. frame = FK4(equinox='B1982') mywcs = celestial_frame_to_wcs(frame) assert tuple(mywcs.wcs.ctype) == ('RA---TAN', 'DEC--TAN') assert mywcs.wcs.radesys == 'FK4' assert mywcs.wcs.equinox == 1982. frame = FK4NoETerms(equinox='B1982') mywcs = celestial_frame_to_wcs(frame) assert tuple(mywcs.wcs.ctype) == ('RA---TAN', 'DEC--TAN') assert mywcs.wcs.radesys == 'FK4-NO-E' assert mywcs.wcs.equinox == 1982. frame = Galactic() mywcs = celestial_frame_to_wcs(frame) assert tuple(mywcs.wcs.ctype) == ('GLON-TAN', 'GLAT-TAN') assert mywcs.wcs.radesys == '' assert np.isnan(mywcs.wcs.equinox) frame = Galactic() mywcs = celestial_frame_to_wcs(frame, projection='CAR') assert tuple(mywcs.wcs.ctype) == ('GLON-CAR', 'GLAT-CAR') assert mywcs.wcs.radesys == '' assert np.isnan(mywcs.wcs.equinox) frame = Galactic() mywcs = celestial_frame_to_wcs(frame, projection='CAR') mywcs.wcs.crval = [100, -30] mywcs.wcs.set() assert_allclose((mywcs.wcs.lonpole, mywcs.wcs.latpole), (180, 60)) frame = ITRS(obstime=Time('2017-08-17T12:41:04.43')) mywcs = celestial_frame_to_wcs(frame, projection='CAR') assert tuple(mywcs.wcs.ctype) == ('TLON-CAR', 'TLAT-CAR') assert mywcs.wcs.radesys == 'ITRS' assert mywcs.wcs.dateobs == '2017-08-17T12:41:04.430' frame = ITRS() mywcs = celestial_frame_to_wcs(frame, projection='CAR') assert tuple(mywcs.wcs.ctype) == ('TLON-CAR', 'TLAT-CAR') assert mywcs.wcs.radesys == 'ITRS' assert mywcs.wcs.dateobs == Time('J2000').utc.fits