def test_simple(): c = coord.ICRS(coord.Angle(217.2141, u.degree), coord.Angle(-11.4351, u.degree)) c.transform_to(GD1Koposov10) c = coord.Galactic(coord.Angle(217.2141, u.degree), coord.Angle(-11.4351, u.degree)) c.transform_to(GD1Koposov10) c = GD1Koposov10(217.2141 * u.degree, -11.4351 * u.degree) c.transform_to(coord.ICRS) c.transform_to(coord.Galactic) c = coord.Galactic(coord.Angle(217.2141, u.degree), coord.Angle(-11.4351, u.degree)) s = c.transform_to(GD1Koposov10) # with distance c = GD1Koposov10(coord.Angle(217.2141, u.degree), coord.Angle(-11.4351, u.degree), distance=15 * u.kpc) c.transform_to(coord.ICRS) c2 = c.transform_to(coord.Galactic) assert np.allclose(c2.distance.value, c.distance.value) # TODO: remove this in next version # For now: make sure old class still works from astropy.tests.helper import catch_warnings with catch_warnings(DeprecationWarning) as w: c = GD1(217.2141 * u.degree, -11.4351 * u.degree) assert len(w) > 0 c2 = c.transform_to(coord.Galactic) c3 = c2.transform_to(GD1) assert np.allclose(c3.phi1.degree, c.phi1.degree) assert np.allclose(c3.phi2.degree, c.phi2.degree)
def show_milkyway(self, b=None, nbins=100, l_start=-241, l_stop=116, **kwargs): """ """ from astropy import coordinates, units nbins = 100 if b is None: gal = coordinates.Galactic( np.linspace(l_start, l_stop, nbins) * units.deg, np.zeros(nbins) * units.deg).transform_to(coordinates.ICRS) prop = dict(ls="-", color="0.7", alpha=0.5) self.ax.plot(*self.radec_to_plot(gal.ra, gal.dec), **{ **prop, **kwargs }) else: gal_dw = coordinates.Galactic( np.linspace(l_start, l_stop, 100) * units.deg, +b * np.ones(nbins) * units.deg).transform_to(coordinates.ICRS) gal_up = coordinates.Galactic( np.linspace(l_start, l_stop, 100) * units.deg, -b * np.ones(nbins) * units.deg).transform_to(coordinates.ICRS) ra_dw, dec_dw = self.radec_to_plot(gal_dw.ra, gal_dw.dec) ra_up, dec_up = self.radec_to_plot(gal_up.ra, gal_up.dec) prop = dict(facecolor="0.7", alpha=0.2) self.ax.fill_between(ra_dw, dec_dw, dec_up, **{**prop, **kwargs})
def posang(l1, b1, l2, b2, system='galactic', units='degrees', **kwargs): """ Return the position angle between two points assuming a rectilinear coordinate system (I think; at the very least I am making no corrections for wcs). INPUT: longitude1, latitude1, longitude2, latitude2 Defaults to GALACTIC coordinates. **kwargs are passed to coords.Position """ if system.lower() == 'galactic': pos1 = coordinates.Galactic(l1, b1, unit=('deg', 'deg')) pos2 = coordinates.Galactic(l2, b2, unit=('deg', 'deg')) elif system.lower() in ('radec', 'fk5', 'icrs'): pos1 = coordinates.ICRS(l1, b1, unit=('deg', 'deg')) pos2 = coordinates.ICRS(l2, b2, unit=('deg', 'deg')) ra1, dec1 = pos1.icrs.ra.deg, pos1.icrs.dec.deg ra2, dec2 = pos2.icrs.ra.deg, pos2.icrs.dec.deg radiff = (ra1 - ra2) / 180. * pi angle = arctan2( sin(radiff), cos(dec1 * pi / 180.) * tan(dec2 * pi / 180.) - sin(dec1 * pi / 180.) * cos(radiff)) if units == 'degrees': return angle / pi * 180 elif units == 'radians': return angle else: raise ValueError("Invalid units: %s" % units)
def test_vhel_to_vgsr(): filename = get_pkg_data_filename('idl_vgsr_vhel.txt') data = np.genfromtxt(filename, names=True, skip_header=2) # one row row = data[0] l = coord.Angle(row["lon"] * u.degree) b = coord.Angle(row["lat"] * u.degree) c = coord.Galactic(l, b) vhel = row["vhelio"] * u.km / u.s vlsr = [row["vx"], row["vy"], row["vz"]] * u.km / u.s # this is right vcirc = row["vcirc"] * u.km / u.s vsun = vlsr + [0, 1, 0] * vcirc vgsr = vhel_to_vgsr(c, vhel, vsun=vsun) np.testing.assert_almost_equal(vgsr.value, row['vgsr'], decimal=4) # now check still get right answer passing in ICRS coordinates vgsr = vhel_to_vgsr(c.transform_to(coord.ICRS), vhel, vsun=vsun) np.testing.assert_almost_equal(vgsr.value, row['vgsr'], decimal=4) # all together now l = coord.Angle(data["lon"] * u.degree) b = coord.Angle(data["lat"] * u.degree) c = coord.Galactic(l, b) vhel = data["vhelio"] * u.km / u.s vgsr = vhel_to_vgsr(c, vhel, vsun=vsun) np.testing.assert_almost_equal(vgsr.value, data['vgsr'], decimal=4) # now check still get right answer passing in ICRS coordinates vgsr = vhel_to_vgsr(c.transform_to(coord.ICRS), vhel, vsun=vsun) np.testing.assert_almost_equal(vgsr.value, data['vgsr'], decimal=4)
def test_vgsr_to_vhel(): filename = get_pkg_data_filename('idl_vgsr_vhel.txt') data = np.genfromtxt(filename, names=True, skip_header=2) # one row row = data[0] l = coord.Angle(row["lon"] * u.degree) b = coord.Angle(row["lat"] * u.degree) c = coord.Galactic(l, b) vgsr = row["vgsr"] * u.km / u.s vlsr = [row["vx"], row["vy"], row["vz"]] * u.km / u.s # this is right vcirc = row["vcirc"] * u.km / u.s vsun = vlsr + [0, 1, 0] * vcirc vhel = vgsr_to_vhel(c, vgsr, vsun=vsun) assert np.allclose(vhel.value, row['vhelio'], atol=1e-3) # now check still get right answer passing in ICRS coordinates vhel = vgsr_to_vhel(c.transform_to(coord.ICRS), vgsr, vsun=vsun) assert np.allclose(vhel.value, row['vhelio'], atol=1e-3) # all together now l = coord.Angle(data["lon"] * u.degree) b = coord.Angle(data["lat"] * u.degree) c = coord.Galactic(l, b) vgsr = data["vgsr"] * u.km / u.s vhel = vgsr_to_vhel(c, vgsr, vsun=vsun) assert np.allclose(vhel.value, data['vhelio'], atol=1e-3) # now check still get right answer passing in ICRS coordinates vhel = vgsr_to_vhel(c.transform_to(coord.ICRS), vgsr, vsun=vsun) assert np.allclose(vhel.value, data['vhelio'], atol=1e-3)
def test_simple(): c = coord.ICRS(coord.Angle(217.2141, u.degree), coord.Angle(-11.4351, u.degree)) c.transform_to(Sagittarius) c = coord.Galactic(coord.Angle(217.2141, u.degree), coord.Angle(-11.4351, u.degree)) c.transform_to(Sagittarius) c = Sagittarius(coord.Angle(217.2141, u.degree), coord.Angle(-11.4351, u.degree)) c.transform_to(coord.ICRS) c.transform_to(coord.Galactic) c = coord.Galactic(coord.Angle(217.2141, u.degree), coord.Angle(-11.4351, u.degree)) s = c.transform_to(Sagittarius) # with distance c = Sagittarius(coord.Angle(217.2141, u.degree), coord.Angle(-11.4351, u.degree), distance=15 * u.kpc) c.transform_to(coord.ICRS) c2 = c.transform_to(coord.Galactic) assert c2.distance.value == c.distance.value
def __init__(self): self._month_transit = np.linspace(0., 365., 13) self._days_of_year = np.linspace(0., 365., 366) ep_rot_1 = np.array([0.9931, 0.1170, -0.01032]) # 1st quadrant ep_rot_2 = np.array([-0.0670, 0.4927, -0.8676]) # 2nd quadrant ep_rot_1_b = np.arcsin(ep_rot_1[2]) ep_rot_1_l = np.arccos(ep_rot_1[0] / np.cos(ep_rot_1_b)) ep_rot_2_b = np.arcsin(ep_rot_2[2]) ep_rot_2_l = np.arccos(ep_rot_2[0] / np.cos(ep_rot_2_b)) ep_rot_1_gal = coord.Galactic(l=ep_rot_1_l * u.rad, b=ep_rot_1_b * u.rad, distance=1000. * u.kpc) ep_rot_2_gal = coord.Galactic(l=ep_rot_2_l * u.rad, b=ep_rot_2_b * u.rad, distance=1000. * u.kpc) ep_rot_1_galcen = ep_rot_1_gal.transform_to(coord.Galactocentric) ep_rot_2_galcen = ep_rot_2_gal.transform_to(coord.Galactocentric) self._ep_rot_1_galcen_vec = np.array([ep_rot_1_galcen.transform_to(coord.Galactocentric).x/(1000.*u.kpc), \ ep_rot_1_galcen.transform_to(coord.Galactocentric).y/(1000.*u.kpc), \ ep_rot_1_galcen.transform_to(coord.Galactocentric).z/(1000.*u.kpc)]) self._ep_rot_2_galcen_vec = np.array([ep_rot_2_galcen.transform_to(coord.Galactocentric).x/(1000.*u.kpc), \ ep_rot_2_galcen.transform_to(coord.Galactocentric).y/(1000.*u.kpc), \ ep_rot_2_galcen.transform_to(coord.Galactocentric).z/(1000.*u.kpc)]) return
def test_query_region_async(patch_get): response = ukidss.core.Ukidss.query_region_async(coord.Galactic( l=10.625, b=-0.38, unit=(u.deg, u.deg)), radius=6 * u.arcsec, get_query_payload=True) assert response['radius'] == 0.1 response = ukidss.core.Ukidss.query_region_async(coord.Galactic( l=10.625, b=-0.38, unit=(u.deg, u.deg)), radius=6 * u.arcsec) assert response is not None
def draw_single_pointing_expo(n, l_p, b_p, D_linear, frac_dust, pm, radius_plate, dust=True): """ Draws positions R, z, l, b, D in single pointings arguments n = initial number of points to sample from l_p = longitude pointing (deg) b_p = latitude pointing (deg) Dmin_p, D_maxp = min and max distances in pointing Rd = scale length (approximate) hz = scale height (approximate) frankel 2018 """ # Galactocentric dist & height along the pointing c = coord.Galactic(l=l_p * un.degree, b=b_p * un.degree, distance=D_linear * un.kpc) cc = c.transform_to(coord.Galactocentric) x, y, z = cc.x.value, cc.y.value, cc.z.value R_along = np.sqrt(x * x + y * y) z_along = z # distribution evaluation p = nu_Rz(R_along, z_along, pm) * D_linear * D_linear # dust if dust == True: p *= frac_dust # cumulative distribution: F_cumul = f_cumul(D_linear, p) u = np.random.rand(n) * np.max(F_cumul) D = np.interp(u, F_cumul, D_linear) l_s, b_s, D = cone.make_cone_lbd(D, l_p, b_p, radius_plate) cs = coord.Galactic(l=l_s * un.degree, b=b_s * un.degree, distance=D * un.kpc) ccs = cs.transform_to(coord.Galactocentric) xs, ys, zs = ccs.x.value, ccs.y.value, ccs.z.value R = np.sqrt(xs * xs + ys * ys) z = zs return R, z, l_s, b_s, D, np.max(F_cumul)
def test_get_images_async(patch_post, patch_parse_coordinates): response = magpis.core.Magpis.get_images_async(coord.Galactic( 10.5, 0.0, unit=(u.deg, u.deg)), image_size=2 * u.deg, survey="gps6epoch3", get_query_payload=True) npt.assert_approx_equal(response['ImageSize'], 120, significant=3) assert response['Survey'] == 'gps6epoch3' response = magpis.core.Magpis.get_images_async( coord.Galactic(10.5, 0.0, unit=(u.deg, u.deg))) assert response is not None
def test_vgsr_to_vhel_misc(): # make sure it works with longitude in 0-360 or -180-180 l1 = coord.Angle(190. * u.deg) l2 = coord.Angle(-170. * u.deg) b = coord.Angle(30. * u.deg) c1 = coord.Galactic(l1, b) c2 = coord.Galactic(l2, b) vgsr = -110. * u.km / u.s vhel1 = vgsr_to_vhel(c1, vgsr) vhel2 = vgsr_to_vhel(c2, vgsr) np.testing.assert_almost_equal(vhel1.value, vhel2.value, decimal=9)
def test_vgsr_to_vhel_misc(): # make sure it works with longitude in 0-360 or -180-180 l1 = coord.Angle(190. * u.deg) l2 = coord.Angle(-170. * u.deg) b = coord.Angle(30. * u.deg) c1 = coord.Galactic(l1, b) c2 = coord.Galactic(l2, b) vgsr = -110. * u.km / u.s vhel1 = vgsr_to_vhel(c1, vgsr) vhel2 = vgsr_to_vhel(c2, vgsr) assert np.allclose(vhel1.value, vhel2.value)
def _mcmc_sample_to_coord(self, p): _, orbit_pars = self._unpack_orbit(0, p) rep = coord.SphericalRepresentation(lon=[0.] * u.radian, lat=[orbit_pars['phi2']] * u.radian, distance=[orbit_pars['d']] * u.kpc) return coord.Galactic(orbitfit.rotate_sph_coordinate(rep, self.R.T))
def set_transformed_coordinates(table): """ Set GeocentricTrueEcliptic and Galactic coordinate tranformations from `astropy.coordinates`. """ from astropy import coordinates import astropy.units as u coo = coordinates.SkyCoord(ra=table['ra'] * u.deg, dec=table['dec'] * u.deg) table.rd = coo ecl = coo.transform_to(coordinates.GeocentricTrueEcliptic()) table['ecl_lat'] = ecl.lat table['ecl_lat'].format = '.1f' table['ecl_lon'] = ecl.lon table['ecl_lon'].format = '.1f' gal = coo.transform_to(coordinates.Galactic()) table['gal_l'] = gal.l table['gal_l'].format = '.1f' table['gal_b'] = gal.b table['gal_b'].format = '.1f'
def test_get_images_2(self): images = ukidss.core.Ukidss.get_images(coord.Galactic(l=49.489, b=-0.27, unit=(u.deg, u.deg)), image_width=5 * u.arcmin) assert images is not None
def test_frames(tmpdir): frames = [ cf.CelestialFrame(reference_frame=coord.ICRS()), cf.CelestialFrame(reference_frame=coord.FK5( equinox=time.Time('2010-01-01'))), cf.CelestialFrame(reference_frame=coord.FK4( equinox=time.Time('2010-01-01'), obstime=time.Time('2015-01-01'))), cf.CelestialFrame(reference_frame=coord.FK4NoETerms( equinox=time.Time('2010-01-01'), obstime=time.Time('2015-01-01'))), cf.CelestialFrame(reference_frame=coord.Galactic()), cf.CelestialFrame( reference_frame=coord.Galactocentric(galcen_distance=5.0 * u.m, galcen_ra=45 * u.deg, galcen_dec=1 * u.rad, z_sun=3 * u.pc, roll=3 * u.deg)), cf.CelestialFrame( reference_frame=coord.GCRS(obstime=time.Time('2010-01-01'), obsgeoloc=[1, 3, 2000] * u.pc, obsgeovel=[2, 1, 8] * (u.m / u.s))), cf.CelestialFrame(reference_frame=coord.CIRS( obstime=time.Time('2010-01-01'))), cf.CelestialFrame(reference_frame=coord.ITRS( obstime=time.Time('2022-01-03'))), cf.CelestialFrame(reference_frame=coord.PrecessedGeocentric( obstime=time.Time('2010-01-01'), obsgeoloc=[1, 3, 2000] * u.pc, obsgeovel=[2, 1, 8] * (u.m / u.s))) ] tree = {'frames': frames} helpers.assert_roundtrip_tree(tree, tmpdir)
def main(pool, distance=20, filename='output_file.txt', nside=64): #calculate pole centers hp = HEALPix(nside=nside, order='ring', frame=coord.Galactic()) centers = hp.healpix_to_skycoord(np.arange(0, hp.npix)) #only keep poles above equator to not redo calculate with opposite pole centers = centers[centers.b >= 0.0 * u.deg] #pad centers to match to number of processors ncenters = centers.shape[0] nprocs = pool.size if nprocs == 0.: nprocs = 1 ncenters_per_proc = np.ceil(ncenters / float(nprocs)) npads = nprocs * ncenters_per_proc - ncenters skypad = coord.SkyCoord(np.zeros(int(npads)), np.zeros(int(npads)), frame='galactic', unit=u.deg) centers = coord.concatenate((centers, skypad)) #reshape centers so each worker gets a block of them centers = centers.reshape(nprocs, int(ncenters_per_proc)) print('number of workers: ', nprocs) print('number of poles: ', ncenters) print('number of poles per worker: ', ncenters_per_proc) print('number of poles added as padding: ', npads) print('shape of poles array: ', np.shape(centers)) #instantiate worker with filename results will be saved to worker = Worker(filename, args.dist) #you better work ! for r in pool.map(worker, list(centers), callback=worker.callback): pass
def reflex(c): #c = coord.(c) v_sun = coord.Galactocentric.galcen_v_sun observed = c.transform_to(coord.Galactic) rep = observed.cartesian.without_differentials() rep = rep.with_differentials(observed.cartesian.differentials['s'] + v_sun) return coord.Galactic(rep).transform_to(c.frame)
def gal2cel(regfile): """ Converts a region file from galactic to celestial coordinates including position angle reference from the center of the box (right now only works on box regions) Requires pyregion with the ShapeList.write() function implemented... not clear if that exists in 1.0 """ reg = pyregion.open(regfile) for R in reg: if R.name == 'box': x, y, dx, dy, angle = R.coord_list #posn = coords.Position([x,y],system='galactic') #ra,dec = posn.j2000() posn = coordinates.Galactic(x * u.deg, y * u.deg) ra, dec = posn.fk5.ra.deg, posn.fk5.dec.deg newang = posang.posang(x - dx, y, x + dx, y, system='galactic') coord_list = [ra, dec, dx, dy, angle - newang - 90] R.coord_format = 'fk5' R.coord_list = coord_list R.params = coord_list reg.write(regfile[:-4] + "_fk5.reg")
def test_ogle_list(patch_post): """ Test multiple pointings using a list of astropy coordinate instances """ co = coord.Galactic(0, 3, unit=(u.degree, u.degree)) co_list = [co, co, co] ogle.core.Ogle.query_region(coord=co_list)
def test_vhel_to_vgsr_misc(): vhel = 110*u.km/u.s c1 = coord.Galactic(15*u.deg, -0.6*u.deg) # make sure throws error if tuple elements are not Quantities with pytest.raises(TypeError): vhel_to_vgsr(c1, vhel.value)
def test_table(): """ Test the transformation code against table 2 values from Newberg et al. 2010 (below) """ names = ["l", "b", "db", "Lambda", "Beta", "g0", "dg0"] table = """255 48.5 0.7 22.34 0.08 17.1 0.1 245 52.0 0.7 15.08 0.56 0. 0. 235 53.5 0.7 8.86 0.21 0. 0. 225 54.0 0.7 2.95 -0.23 17.6 0.2 215 54.0 0.7 -2.93 -0.33 17.9 0.1 205 53.5 0.7 -8.85 -0.09 18.0 0.1 195 52.0 0.7 -15.08 0.05 0. 0. 185 50.5 0.7 -21.42 1.12 18.6 0.1 175 47.5 0.7 -28.59 1.88 0. 0. 171 45.8 1.0 -31.81 2.10 0. 0.""" table = ascii.read(table, names=names) for line in table: galactic = coord.Galactic(l=line['l'] * u.deg, b=line['b'] * u.deg) orp = galactic.transform_to(Orphan) true_orp = Orphan(Lambda=line['Lambda'] * u.deg, Beta=line['Beta'] * u.deg) # TODO: why does this suck so badly? assert true_orp.separation(orp) < 20 * u.arcsec
def test_get_images_2(self): images = vista.core.Vista.get_images(coord.Galactic(l=330.1, b=-0.1, unit=(u.deg, u.deg)), image_width=5 * u.arcmin) assert images is not None
def test_init_center(): stupid_gal = GreatCircleICRSFrame( pole=coord.Galactic._ngp_J2000.transform_to(coord.ICRS), center=coord.Galactocentric.galcen_coord) gal = coord.Galactic(50*u.deg, 20*u.deg) gal2 = gal.transform_to(stupid_gal) assert np.isclose(gal.l.degree, gal2.phi1.degree) assert np.isclose(gal.b.degree, gal2.phi2.degree)
def test_query_region(patch_get, patch_get_readable_fileobj): table = ukidss.core.Ukidss.query_region(coord.Galactic(l=10.625, b=-0.38, unit=(u.deg, u.deg)), radius=6 * u.arcsec) assert isinstance(table, Table) assert len(table) > 0
def test_query_region(self): table = vista.core.Vista.query_region(coord.Galactic(l=340.5, b=-0.38, unit=(u.deg, u.deg)), radius=6 * u.arcsec) assert isinstance(table, Table) assert len(table) > 0
def test_get_images(self): image = magpis.core.Magpis.get_images(coord.Galactic(10.5, 0.0, unit=(u.deg, u.deg)), image_size='1 arcmin') assert image is not None assert image[0].data.shape == (8, 8)
def get_nir_cat(self, clobber=False, use_twomass=True): """ Get the NIR catalog Catalog (necessary for zero-point determination) is saved into self.data_dir as self.name+"_"+self.nir_survey+"cat.fits" """ print("Fetching NIR catalog from server...") if use_twomass: if (not os.path.isfile(self.nir_cal_cat)) or clobber: from astroquery.irsa import Irsa Irsa.ROW_LIMIT = 2000. table = Irsa.query_region(coordinates.Galactic(l=self.glon, b=self.glat, unit=(u.deg, u.deg)), catalog="fp_psc", spatial="Box", width=self.nir_im_size) #print(table) #IPAC table does not take overwrite? But FITS does? So inconsistent and bad table.write(self.nir_cal_cat, format='votable', overwrite=clobber) else: print( "NIR catalog already downloaded. Use clobber=True to fetch new versions." ) else: if (not os.path.isfile(self.nir_cat)) or clobber: if self.nir_survey == "VISTA": from astroquery.vista import Vista as NIR if self.nir_survey == "UKIDSS": from astroquery.ukidss import Ukidss as NIR table = NIR.query_region(coordinates.Galactic(l=self.glon, b=self.glat, unit=(u.deg, u.deg)), radius=self.nir_im_size) table.write(self.nir_cat, format="fits", overwrite=clobber) else: print( "NIR catalog already downloaded. Use clobber=True to fetch new versions." )
def test_transform(): rep = coord.CartesianRepresentation(x=1, y=2, z=3, unit=u.pc) ref_c1 = ReferencePlaneFrame(rep) with pytest.raises(ValueError): ref_c1.transform_to(coord.ICRS) with pytest.raises(ValueError): ref_c2 = ReferencePlaneFrame(rep, origin=coord.Galactic())
def test_vgsr_to_vhel_misc(): # make sure it works with longitude in 0-360 or -180-180 l1 = coord.Angle(190.*u.deg) l2 = coord.Angle(-170.*u.deg) b = coord.Angle(30.*u.deg) c1 = coord.Galactic(l1, b) c2 = coord.Galactic(l2, b) vgsr = -110.*u.km/u.s vhel1 = vgsr_to_vhel(c1,vgsr) vhel2 = vgsr_to_vhel(c2,vgsr) np.testing.assert_almost_equal(vhel1.value, vhel2.value, decimal=9) # make sure throws error if tuple elements are not Quantities with pytest.raises(TypeError): vgsr_to_vhel(c1, vgsr.value)