def preprocess_star_cat(input_cata, station): ''' Makes sure the star catalog contains all the required information: index alt-az, calculated alt-az, deltas... input_cata: astropy Table or votable path observer_station: EarthLocation object ''' if isinstance(input_cata, Table): input_table = input_cata else: # Read the data input_table = Table.read(input_cata, format='votable') # try to remove alt-az columns if they exist possible_newcols = [alt_cata_col_, az_cata_col_, delta_az_cata_col_, delta_alt_cata_col_, alt_fitted_col_, delta_alt_cata_col_] for c in possible_newcols: if c in input_table.colnames: input_table.remove_columns(c) times = Time(Time(input_table['jd_mid_obs'], format='jd', scale='utc').isot) cata_data = ICRS(ra=input_table['RA_cat_deg']*u.deg, dec=input_table['DEC_cat_deg']*u.deg) cata_data_altaz = cata_data.transform_to(AltAz(obstime=times,location=station)) fitted_data = ICRS(ra=input_table['RA_deg']*u.deg, dec=input_table['DEC_deg']*u.deg) fitted_data_altaz = fitted_data.transform_to(AltAz(obstime=times,location=station)) alt_cata_col = Column(data=cata_data_altaz.alt, name=alt_cata_col_) az_cata_col = Column(data=cata_data_altaz.az, name=az_cata_col_) alt_fitted_col = Column(data=fitted_data_altaz.alt, name=alt_fitted_col_) az_fitted_col = Column(data=fitted_data_altaz.az, name=az_fitted_col_) delta_alt_cata_col = Column(data=fitted_data_altaz.alt-cata_data_altaz.alt, name=delta_alt_cata_col_) delta_az_cata_col = Column(data=fitted_data_altaz.az-cata_data_altaz.az, name=delta_az_cata_col_) new_cols = [alt_cata_col, az_cata_col, delta_az_cata_col, delta_alt_cata_col, alt_fitted_col, az_fitted_col] input_table.add_columns(new_cols) return input_table
def _to_altaz(self, c1, c2, times, csys): """ """ # Make sure to have corresponding dimensions elements = [times.mjd, c1, c2] if all(map(np.isscalar, elements)): time = [times] c1 = [c1] c2 = [c2] elif all(hasattr(i, '__len__') for i in elements): if len(set(len(i) for i in elements)) == 1: pass else: raise ValueError('Different lengths found') else: raise ValueError( 'times, c1 and c2 are mixed with scalars and lists') # Convert coordinates if csys.lower() == 'radec': radec = ICRS(ra=c1 * u.deg, dec=c2 * u.deg) altaz_frame = AltAz(obstime=times, location=nenufar_loc) altaz = radec.transform_to(altaz_frame) az = altaz.az.deg el = altaz.alt.deg elif csys.lower() == 'altaz': az = c1 el = c2 else: raise ValueError('{} not understood'.format(csys)) return az, el
def to_altaz(ra, dec, time, location=None): """ Transform altaz coordinates to ICRS equatorial system :param radec: Equatorial coordinates :type altaz: :class:`astropy.coordinates.ICRS` :param time: Time at which the local coordinates should be computed. It can either be provided as an :class:`astropy.time.Time` object or a string in ISO or ISOT format. :type time: str, :class:`astropy.time.Time` :returns: :class:`astropy.coordinates.AltAz` object :rtype: :class:`astropy.coordinates.AltAz` :Example: >>> from nenupysim.astro import eq_coord >>> radec = eq_coord( ra=51, dec=39, ) """ if location is None: location = nenufar_loc() if not isinstance(location, EarthLocation): raise TypeError('time is not an astropy EarthLocation.') altaz_frame = AltAz(obstime=time, location=location) eq = ICRS(ra=ra * u.deg, dec=dec * u.deg) altaz = eq.transform_to(altaz_frame) return altaz
def convert_radec_file_to_altaz(input_file, obs_cfg_file, output_file, alt_key='altitude', az_key='azimuth', ra_key='ra', dec_key='dec'): ''' Convert RA DEC file to Alt-Az input_file: File containing equatorial coordinates obs_cfg_file: Oberver config file output_file: file to save keys: column header keywords ''' if ra_key.lower() == 'ha': ra_unit = u.hour else: ra_unit = u.deg input_table = Table.read(input_file, format='ascii.csv', guess=False, delimiter=',') station, obstime = parse_observer_cfg_file(obs_cfg_file) equatorial_data = ICRS(ra=input_table[ra_key]*ra_unit, dec=input_table[dec_key]*u.deg) horizontal_data = equatorial_data.transform_to(AltAz(obstime=obstime,location=station)) alt_col = Column(data=horizontal_data.alt, name=alt_key) az_col = Column(data=horizontal_data.az, name=az_key) output_table = Table([az_col, alt_col]) output_table.write(output_file, format='ascii.csv', delimiter=',', overwrite=True)
def test_coord_get(): # Test default (instance=None) obs = Helioprojective.observer assert obs is "earth" # Test get obstime = "2013-04-01" obs = Helioprojective(observer="earth", obstime=obstime).observer earth = get_earth(obstime) assert isinstance(obs, HeliographicStonyhurst) assert_quantity_allclose(obs.lon, earth.lon) assert_quantity_allclose(obs.lat, earth.lat) assert_quantity_allclose(obs.radius, earth.radius) # Test get obstime = "2013-04-01" obs = Helioprojective(obstime=obstime).observer earth = get_earth(obstime) assert isinstance(obs, HeliographicStonyhurst) assert_quantity_allclose(obs.lon, earth.lon) assert_quantity_allclose(obs.lat, earth.lat) assert_quantity_allclose(obs.radius, earth.radius) # Test get mars obstime = Time(parse_time("2013-04-01")) obs = Helioprojective(observer="mars", obstime=obstime).observer out_icrs = ICRS(get_body_barycentric("mars", obstime)) mars = out_icrs.transform_to(HeliographicStonyhurst(obstime=obstime)) assert isinstance(obs, HeliographicStonyhurst) assert_quantity_allclose(obs.lon, mars.lon) assert_quantity_allclose(obs.lat, mars.lat) assert_quantity_allclose(obs.radius, mars.radius)
def test_icrs_gcrscirs_sunish(testframe): """ check that the ICRS barycenter goes to about the right distance from various ~geocentric frames (other than testframe) """ # slight offset to avoid divide-by-zero errors icrs = ICRS(0*u.deg, 0*u.deg, distance=10*u.km) gcrs = icrs.transform_to(GCRS(obstime=testframe.obstime)) assert (EARTHECC - 1)*u.au < gcrs.distance.to(u.au) < (EARTHECC + 1)*u.au cirs = icrs.transform_to(CIRS(obstime=testframe.obstime)) assert (EARTHECC - 1)*u.au < cirs.distance.to(u.au) < (EARTHECC + 1)*u.au itrs = icrs.transform_to(ITRS(obstime=testframe.obstime)) assert (EARTHECC - 1)*u.au < itrs.spherical.distance.to(u.au) < (EARTHECC + 1)*u.au
def test_icrs_gcrscirs_sunish(testframe): """ check that the ICRS barycenter goes to about the right distance from various ~geocentric frames (other than testframe) """ # slight offset to avoid divide-by-zero errors icrs = ICRS(0*u.deg, 0*u.deg, distance=10*u.km) gcrs = icrs.transform_to(GCRS(obstime=testframe.obstime)) assert (EARTHECC - 1)*u.au < gcrs.distance.to(u.au) < (EARTHECC + 1)*u.au cirs = icrs.transform_to(CIRS(obstime=testframe.obstime)) assert (EARTHECC - 1)*u.au < cirs.distance.to(u.au) < (EARTHECC + 1)*u.au itrs = icrs.transform_to(ITRS(obstime=testframe.obstime)) assert (EARTHECC - 1)*u.au < itrs.spherical.distance.to(u.au) < (EARTHECC + 1)*u.au
def test_coord_get(): # Test default (instance=None) obs = Helioprojective.observer assert obs is "earth" # Test get obstime = "2013-04-01" obs = Helioprojective(observer="earth", obstime=obstime).observer earth = get_earth(obstime) assert isinstance(obs, HeliographicStonyhurst) assert_quantity_allclose(obs.lon, earth.lon) assert_quantity_allclose(obs.lat, earth.lat) assert_quantity_allclose(obs.radius, earth.radius) # Test get obstime = "2013-04-01" obs = Helioprojective(obstime=obstime).observer earth = get_earth(obstime) assert isinstance(obs, HeliographicStonyhurst) assert_quantity_allclose(obs.lon, earth.lon) assert_quantity_allclose(obs.lat, earth.lat) assert_quantity_allclose(obs.radius, earth.radius) # Test get mars obstime = Time(parse_time("2013-04-01")) obs = Helioprojective(observer="mars", obstime=obstime).observer out_icrs = ICRS(get_body_barycentric("mars", obstime)) mars = out_icrs.transform_to(HeliographicStonyhurst(obstime=obstime)) assert isinstance(obs, HeliographicStonyhurst) assert_quantity_allclose(obs.lon, mars.lon) assert_quantity_allclose(obs.lat, mars.lat) assert_quantity_allclose(obs.radius, mars.radius)
def from_body_ephem(cls, body, epoch=None): """Return osculating `Orbit` of a body at a given time. """ if not epoch: epoch = time.Time.now().tdb elif epoch.scale != 'tdb': epoch = epoch.tdb warn( "Input time was converted to scale='tdb' with value " "{}. Use Time(..., scale='tdb') instead.".format( epoch.tdb.value), TimeScaleWarning) r, v = get_body_barycentric_posvel(body.name, epoch) if body == Moon: moon_icrs = ICRS(x=r.x, y=r.y, z=r.z, v_x=v.x, v_y=v.y, v_z=v.z, representation=CartesianRepresentation, differential_type=CartesianDifferential) moon_gcrs = moon_icrs.transform_to(GCRS(obstime=epoch)) moon_gcrs.representation = CartesianRepresentation r = CartesianRepresentation( [moon_gcrs.x, moon_gcrs.y, moon_gcrs.z]) v = CartesianRepresentation( [moon_gcrs.v_x, moon_gcrs.v_y, moon_gcrs.v_z]) return cls.from_vectors(body.parent, r.xyz.to(u.km), v.xyz.to(u.km / u.day), epoch)
def test_array_coordinates_transformations(arrshape, distance): """ Test transformation on coordinates with array content (first length-2 1D, then a 3D array) """ # M31 coordinates from test_transformations raarr = np.ones(arrshape) * 10.6847929 decarr = np.ones(arrshape) * 41.2690650 if distance is not None: distance = np.ones(arrshape) * distance print(raarr, decarr, distance) c = ICRS(ra=raarr * u.deg, dec=decarr * u.deg, distance=distance) g = c.transform_to(Galactic()) assert g.l.shape == arrshape npt.assert_array_almost_equal(g.l.degree, 121.17440967) npt.assert_array_almost_equal(g.b.degree, -21.57299631) if distance is not None: assert g.distance.unit == c.distance.unit # now make sure round-tripping works through FK5 c2 = c.transform_to(FK5()).transform_to(ICRS()) npt.assert_array_almost_equal(c.ra.radian, c2.ra.radian) npt.assert_array_almost_equal(c.dec.radian, c2.dec.radian) assert c2.ra.shape == arrshape if distance is not None: assert c2.distance.unit == c.distance.unit # also make sure it's possible to get to FK4, which uses a direct transform function. fk4 = c.transform_to(FK4()) npt.assert_array_almost_equal(fk4.ra.degree, 10.0004, decimal=4) npt.assert_array_almost_equal(fk4.dec.degree, 40.9953, decimal=4) assert fk4.ra.shape == arrshape if distance is not None: assert fk4.distance.unit == c.distance.unit # now check the reverse transforms run cfk4 = fk4.transform_to(ICRS()) assert cfk4.ra.shape == arrshape
def test_array_coordinates_transformations(arrshape, distance): """ Test transformation on coordinates with array content (first length-2 1D, then a 3D array) """ # M31 coordinates from test_transformations raarr = np.ones(arrshape) * 10.6847929 decarr = np.ones(arrshape) * 41.2690650 if distance is not None: distance = np.ones(arrshape) * distance print(raarr, decarr, distance) c = ICRS(ra=raarr*u.deg, dec=decarr*u.deg, distance=distance) g = c.transform_to(Galactic) assert g.l.shape == arrshape npt.assert_array_almost_equal(g.l.degree, 121.17440967) npt.assert_array_almost_equal(g.b.degree, -21.57299631) if distance is not None: assert g.distance.unit == c.distance.unit # now make sure round-tripping works through FK5 c2 = c.transform_to(FK5).transform_to(ICRS) npt.assert_array_almost_equal(c.ra.radian, c2.ra.radian) npt.assert_array_almost_equal(c.dec.radian, c2.dec.radian) assert c2.ra.shape == arrshape if distance is not None: assert c2.distance.unit == c.distance.unit # also make sure it's possible to get to FK4, which uses a direct transform function. fk4 = c.transform_to(FK4) npt.assert_array_almost_equal(fk4.ra.degree, 10.0004, decimal=4) npt.assert_array_almost_equal(fk4.dec.degree, 40.9953, decimal=4) assert fk4.ra.shape == arrshape if distance is not None: assert fk4.distance.unit == c.distance.unit # now check the reverse transforms run cfk4 = fk4.transform_to(ICRS) assert cfk4.ra.shape == arrshape
def test_radec_to_munu(): from astropy import units as u from astropy.coordinates import ICRS from .. import SDSSMuNu radec = ICRS(ra=0.0*u.deg,dec=0.0*u.deg) munu = radec.transform_to(SDSSMuNu(stripe=10)) assert munu.mu.value == 0.0 assert munu.nu.value == 0.0 assert munu.incl.value == 0.0
def eq2gal(self,ra,dec): try: ra = Angle(ra) dec = Angle(dec) c = ICRS(ra=ra, dec=dec) return c.transform_to(Galactic) except Exception as e: print(e) return 0
def test_icrs_cirs(): """ Check a few cases of ICRS<->CIRS for consistency. Also includes the CIRS<->CIRS transforms at different times, as those go through ICRS """ usph = golden_spiral_grid(200) dist = np.linspace(0., 1, len(usph)) * u.pc inod = ICRS(usph) iwd = ICRS(ra=usph.lon, dec=usph.lat, distance=dist) cframe1 = CIRS() cirsnod = inod.transform_to(cframe1) # uses the default time # first do a round-tripping test inod2 = cirsnod.transform_to(ICRS()) assert_allclose(inod.ra, inod2.ra) assert_allclose(inod.dec, inod2.dec) # now check that a different time yields different answers cframe2 = CIRS(obstime=Time('J2005')) cirsnod2 = inod.transform_to(cframe2) assert not allclose(cirsnod.ra, cirsnod2.ra, rtol=1e-8) assert not allclose(cirsnod.dec, cirsnod2.dec, rtol=1e-8) # parallax effects should be included, so with and w/o distance should be different cirswd = iwd.transform_to(cframe1) assert not allclose(cirswd.ra, cirsnod.ra, rtol=1e-8) assert not allclose(cirswd.dec, cirsnod.dec, rtol=1e-8) # and the distance should transform at least somehow assert not allclose(cirswd.distance, iwd.distance, rtol=1e-8) # now check that the cirs self-transform works as expected cirsnod3 = cirsnod.transform_to(cframe1) # should be a no-op assert_allclose(cirsnod.ra, cirsnod3.ra) assert_allclose(cirsnod.dec, cirsnod3.dec) cirsnod4 = cirsnod.transform_to(cframe2) # should be different assert not allclose(cirsnod4.ra, cirsnod.ra, rtol=1e-8) assert not allclose(cirsnod4.dec, cirsnod.dec, rtol=1e-8) cirsnod5 = cirsnod4.transform_to(cframe1) # should be back to the same assert_allclose(cirsnod.ra, cirsnod5.ra) assert_allclose(cirsnod.dec, cirsnod5.dec)
def test_icrs_cirs(): """ Check a few cases of ICRS<->CIRS for consistency. Also includes the CIRS<->CIRS transforms at different times, as those go through ICRS """ ra, dec, dist = randomly_sample_sphere(200) inod = ICRS(ra=ra, dec=dec) iwd = ICRS(ra=ra, dec=dec, distance=dist*u.pc) cframe1 = CIRS() cirsnod = inod.transform_to(cframe1) # uses the default time # first do a round-tripping test inod2 = cirsnod.transform_to(ICRS) assert_allclose(inod.ra, inod2.ra) assert_allclose(inod.dec, inod2.dec) # now check that a different time yields different answers cframe2 = CIRS(obstime=Time('J2005', scale='utc')) cirsnod2 = inod.transform_to(cframe2) assert not allclose(cirsnod.ra, cirsnod2.ra, rtol=1e-8) assert not allclose(cirsnod.dec, cirsnod2.dec, rtol=1e-8) # parallax effects should be included, so with and w/o distance should be different cirswd = iwd.transform_to(cframe1) assert not allclose(cirswd.ra, cirsnod.ra, rtol=1e-8) assert not allclose(cirswd.dec, cirsnod.dec, rtol=1e-8) # and the distance should transform at least somehow assert not allclose(cirswd.distance, iwd.distance, rtol=1e-8) # now check that the cirs self-transform works as expected cirsnod3 = cirsnod.transform_to(cframe1) # should be a no-op assert_allclose(cirsnod.ra, cirsnod3.ra) assert_allclose(cirsnod.dec, cirsnod3.dec) cirsnod4 = cirsnod.transform_to(cframe2) # should be different assert not allclose(cirsnod4.ra, cirsnod.ra, rtol=1e-8) assert not allclose(cirsnod4.dec, cirsnod.dec, rtol=1e-8) cirsnod5 = cirsnod4.transform_to(cframe1) # should be back to the same assert_allclose(cirsnod.ra, cirsnod5.ra) assert_allclose(cirsnod.dec, cirsnod5.dec)
def test_icrs_cirs(): """ Check a few cases of ICRS<->CIRS for consistency. Also includes the CIRS<->CIRS transforms at different times, as those go through ICRS """ ra, dec, dist = randomly_sample_sphere(200) inod = ICRS(ra=ra, dec=dec) iwd = ICRS(ra=ra, dec=dec, distance=dist * u.pc) cframe1 = CIRS() cirsnod = inod.transform_to(cframe1) # uses the default time # first do a round-tripping test inod2 = cirsnod.transform_to(ICRS) assert_allclose(inod.ra, inod2.ra) assert_allclose(inod.dec, inod2.dec) # now check that a different time yields different answers cframe2 = CIRS(obstime=Time('J2005', scale='utc')) cirsnod2 = inod.transform_to(cframe2) assert not allclose(cirsnod.ra, cirsnod2.ra, rtol=1e-8) assert not allclose(cirsnod.dec, cirsnod2.dec, rtol=1e-8) # parallax effects should be included, so with and w/o distance should be different cirswd = iwd.transform_to(cframe1) assert not allclose(cirswd.ra, cirsnod.ra, rtol=1e-8) assert not allclose(cirswd.dec, cirsnod.dec, rtol=1e-8) # and the distance should transform at least somehow assert not allclose(cirswd.distance, iwd.distance, rtol=1e-8) # now check that the cirs self-transform works as expected cirsnod3 = cirsnod.transform_to(cframe1) # should be a no-op assert_allclose(cirsnod.ra, cirsnod3.ra) assert_allclose(cirsnod.dec, cirsnod3.dec) cirsnod4 = cirsnod.transform_to(cframe2) # should be different assert not allclose(cirsnod4.ra, cirsnod.ra, rtol=1e-8) assert not allclose(cirsnod4.dec, cirsnod.dec, rtol=1e-8) cirsnod5 = cirsnod4.transform_to(cframe1) # should be back to the same assert_allclose(cirsnod.ra, cirsnod5.ra) assert_allclose(cirsnod.dec, cirsnod5.dec)
def test_regression_3920(): """ Issue: https://github.com/astropy/astropy/issues/3920 """ loc = EarthLocation.from_geodetic(0*u.deg, 0*u.deg, 0) time = Time('2010-1-1') aa = AltAz(location=loc, obstime=time) sc = SkyCoord(10*u.deg, 3*u.deg) assert sc.transform_to(aa).shape == tuple() # That part makes sense: the input is a scalar so the output is too sc2 = SkyCoord(10*u.deg, 3*u.deg, 1*u.AU) assert sc2.transform_to(aa).shape == tuple() # in 3920 that assert fails, because the shape is (1,) # check that the same behavior occurs even if transform is from low-level classes icoo = ICRS(sc.data) icoo2 = ICRS(sc2.data) assert icoo.transform_to(aa).shape == tuple() assert icoo2.transform_to(aa).shape == tuple()
def test_regression_3920(): """ Issue: https://github.com/astropy/astropy/issues/3920 """ loc = EarthLocation.from_geodetic(0*u.deg, 0*u.deg, 0) time = Time('2010-1-1') aa = AltAz(location=loc, obstime=time) sc = SkyCoord(10*u.deg, 3*u.deg) assert sc.transform_to(aa).shape == tuple() # That part makes sense: the input is a scalar so the output is too sc2 = SkyCoord(10*u.deg, 3*u.deg, 1*u.AU) assert sc2.transform_to(aa).shape == tuple() # in 3920 that assert fails, because the shape is (1,) # check that the same behavior occurs even if transform is from low-level classes icoo = ICRS(sc.data) icoo2 = ICRS(sc2.data) assert icoo.transform_to(aa).shape == tuple() assert icoo2.transform_to(aa).shape == tuple()
async def mtptg_telemetry(self) -> None: while self.run_telemetry_loop: if (self.controllers.mtptg.evt_summaryState.data.summaryState == salobj.State.ENABLED): now = Time.now() await self.controllers.mtptg.tel_timeAndDate.set_write( timestamp=now.unix_tai, utc=now.utc.mjd, lst=now.sidereal_time("mean", self.location.lon).value, ) if self.tracking: radec_icrs = ICRS( Angle( self.controllers.mtptg.evt_currentTarget.data.ra, unit=u.radian, ), Angle( self.controllers.mtptg.evt_currentTarget.data. declination, unit=u.radian, ), ) coord_frame_altaz = AltAz(location=self.location, obstime=now) alt_az = radec_icrs.transform_to(coord_frame_altaz) await self.controllers.mtptg.evt_currentTarget.set_write( timestamp=now.tai.mjd, azDegs=alt_az.az.deg, elDegs=alt_az.alt.deg, ) self.controllers.mtmount.tel_azimuth.set( **{self.mtmount_demand_position_name: alt_az.az.deg}) self.controllers.mtmount.tel_elevation.set( **{self.mtmount_demand_position_name: alt_az.alt.deg}) self.controllers.mtrotator.tel_rotation.set( demandPosition=self.controllers.mtptg. evt_currentTarget.data.rotPA) self.controllers.mtmount.evt_target.set( elevation=alt_az.alt.deg, azimuth=alt_az.az.deg, ) await asyncio.sleep(HEARTBEAT_INTERVAL)
def vec2pix(l, b): if galactic: f = ICRS(l * u.rad, b * u.rad) g = f.transform_to(Galactic) l, b = g.l.rad, g.b.rad theta = np.pi / 2 - b phi = l if interp: return get_interp_val(data, theta, phi, nest=nest) return data[ang2pix(nside, theta, phi, nest=nest)]
def test_icrs_altaz_moonish(testframe): """ Check that something expressed in *ICRS* as being moon-like goes to the right AltAz distance """ # we use epv00 instead of get_sun because get_sun includes aberration earth_pv_helio, earth_pv_bary = erfa.epv00(*get_jd12(testframe.obstime, 'tdb')) earth_icrs_xyz = earth_pv_bary[0]*u.au moonoffset = [0, 0, MOONDIST.value]*MOONDIST.unit moonish_icrs = ICRS(CartesianRepresentation(earth_icrs_xyz + moonoffset)) moonaa = moonish_icrs.transform_to(testframe) # now check that the distance change is similar to earth radius assert 1000*u.km < np.abs(moonaa.distance - MOONDIST).to(u.au) < 7000*u.km
def test_icrs_altaz_moonish(testframe): """ Check that something expressed in *ICRS* as being moon-like goes to the right AltAz distance """ # we use epv00 instead of get_sun because get_sun includes aberration earth_pv_helio, earth_pv_bary = epv00(*get_jd12(testframe.obstime, 'tdb')) earth_icrs_xyz = earth_pv_bary[0]*u.au moonoffset = [0, 0, MOONDIST.value]*MOONDIST.unit moonish_icrs = ICRS(CartesianRepresentation(earth_icrs_xyz + moonoffset)) moonaa = moonish_icrs.transform_to(testframe) # now check that the distance change is similar to earth radius assert 1000*u.km < np.abs(moonaa.distance - MOONDIST).to(u.au) < 7000*u.km
def ProperMotionTransform(ra_coord, dec_coord, pmra_coord, pmdec_coord): # pmra_coord_cosdec = pmra_coord*np.cos(dec_coord*np.pi/180.) pmra_coord_cosdec = pmra_coord icrs = ICRS(ra=ra_coord * units.degree, dec=dec_coord * units.degree, pm_ra_cosdec=pmra_coord_cosdec * units.mas / units.yr, pm_dec=pmdec_coord * units.mas / units.yr) galactic = icrs.transform_to(Galactic) pml = (galactic.pm_l_cosb) / np.cos( galactic.b.radian) / (units.mas / units.yr) pmb = galactic.pm_b / (units.mas / units.yr) return (pml, pmb)
def astropy_icrstogal_rotation_matrix(): """ Figure the ICRS to Galatic coordinates rotation matrix. Returns ------- The 3x3 matrix representing the rotation from ICRS Cartesian to Galactic Cartesian coordinates. """ # ICRS basis vectors basis_icrs = ICRS(ra = [0,np.pi/2,0]*u.rad, dec = [0,0,np.pi/2]*u.rad) # Rotate to Galactic basis_gal = basis_icrs.transform_to(Galactic()) # Calculate and return matrix components return np.array([np.cos(basis_gal.l.to(u.rad))*np.cos(basis_gal.b.to(u.rad)), np.sin(basis_gal.l.to(u.rad))*np.cos(basis_gal.b.to(u.rad)), np.sin(basis_gal.b.to(u.rad))])
def get_elev(ra_source, dec_source, xyz_antenna, time): #this one is by Michael Janssen """ given right ascension and declination of a sky source [ICRS: ra->(deg,arcmin,arcsec) and dec->(hour,min,sec)] and given the position of the telescope from the vex file [Geocentric coordinates (m)] and the time of the observation (e.g. '2012-7-13 23:00:00') [UTC:yr-m-d], returns the elevation of the telescope. Note that every parameter can be an array (e.g. the time) """ from astropy import units as u from astropy.coordinates import EarthLocation, AltAz, ICRS, Angle #angle conversions: ra_src = Angle(ra_source, unit=u.rad) dec_src = Angle(dec_source, unit=u.rad) source_position = ICRS(ra=ra_src, dec=dec_src) antenna_position = EarthLocation(x=xyz_antenna[0]*u.m, y=xyz_antenna[1]*u.m, z=xyz_antenna[2]*u.m) altaz_system = AltAz(location=antenna_position, obstime=time) trans_to_altaz = source_position.transform_to(altaz_system) elevation = trans_to_altaz.alt return elevation.rad
def get_body_heliographic_stonyhurst(body, time='now'): """ Return a `~sunpy.coordinates.frames.HeliographicStonyhurst` frame for the location of a solar-system body at a specified time. Parameters ---------- body : `str` The solar-system body for which to calculate positions time : various Time to use as `~astropy.time.Time` or in a parse_time-compatible format Returns ------- out : `~sunpy.coordinates.frames.HeliographicStonyhurst` Location of the solar-system body in the `~sunpy.coordinates.HeliographicStonyhurst` frame """ obstime = _astropy_time(time) body_icrs = ICRS(get_body_barycentric(body, obstime)) body_hgs = body_icrs.transform_to(HGS(obstime=obstime)) return body_hgs
def get_body_heliographic_stonyhurst(body, time='now'): """ Return a `~sunpy.coordinates.frames.HeliographicStonyhurst` frame for the location of a solar-system body at a specified time. Parameters ---------- body : `str` The solar-system body for which to calculate positions time : various Time to use as `~astropy.time.Time` or in a parse_time-compatible format Returns ------- out : `~sunpy.coordinates.frames.HeliographicStonyhurst` Location of the solar-system body in the `~sunpy.coordinates.HeliographicStonyhurst` frame """ obstime = parse_time(time) body_icrs = ICRS(get_body_barycentric(body, obstime)) body_hgs = body_icrs.transform_to(HGS(obstime=obstime)) return body_hgs
def stars(in_file, plots_flag): # Create structured datatype correspond to given format # and load data file in_type = np.dtype([('ra' , 'f'), ('dec' , 'f'), ('d' , 'f'), ('vlos' , 'f'), ('pmra' , 'f'), ('pmdec', 'f')]) data = np.loadtxt(in_file,dtype=in_type,skiprows=1) # astropy.SkyCoords doesn't support automatically converting the velocity components # so we need to transform the data manually icrs = ICRS(ra=data['ra'] * u.degree, dec=data['dec'] * u.degree, distance=data['d'] * u.kpc, pm_ra_cosdec=(data['pmra'] * u.mas / u.yr), #* np.cos(data['dec'] * u.degree)), pm_dec=data['pmdec'] * u.mas / u.yr, radial_velocity=data['vlos'] * u.km / u.s) # Cartesian galactocentric coordinates v_sun = CartesianDifferential(11.1, 12.248 + 238, 7.25, unit=u.km / u.s) gal_cen = icrs.transform_to(Galactocentric(galcen_v_sun=v_sun, galcen_distance=8.0 * u.kpc, z_sun=0 * u.kpc)) # Output the 6D Cartesian coordinates out_file = '6d.txt' out_data = np.column_stack((gal_cen.x, gal_cen.y, gal_cen.z, gal_cen.v_x, gal_cen.v_y, gal_cen.v_z)) cols = ('x[kpc]', 'y[kpc]', 'z[kpc]', 'v_x[km/s]', 'v_y[km/s]', 'v_z[km/s]') np.savetxt(out_file, out_data, fmt='%9.4f', header=' '.join(cols)) print('6D coordinates written to {}'.format(out_file)) # r = distance # theta = latitude # phi = azimuth/longitude # NB This is opposite to how spherical coordinates are normally defined! # Spherical galactocentric coordinates gal_cen_sph = gal_cen.copy() gal_cen_sph.representation = 'spherical' # Calculate spherical velocity components and make units sensible vr = (gal_cen_sph.d_distance .to(u.km/u.s)) vtheta = ((gal_cen_sph.d_lat * gal_cen_sph.distance) .to(u.rad * u.km/u.s) / u.rad) vphi = ((gal_cen_sph.d_lon * gal_cen_sph.distance * np.cos(gal_cen_sph.lat)) .to(u.rad * u.km/u.s) / u.rad) # Calculate standard deviations (sigma) for three velocity components vr_dev = np.std(vr) vtheta_dev = np.std(vtheta) vphi_dev = np.std(vphi) # Calculate the velocity anisotropy parameter beta v_anis = vel_anisotropy(vr, vtheta, vphi) # Calculate the rotation velocity # Assumed that this is the expectation value of vphi v_rot = np.mean(vphi) # Report the results print('Velocity dispersion and anisotropy results:') print(""" sigma_r = {} sigma_theta = {} sigma_phi = {} v_rot = {} beta = {}""".format(vr_dev, vtheta_dev, vphi_dev, v_rot, v_anis)) # Spit out some plots if the command line flag was given if plots_flag: #from matplotlib import rc #rc('text', usetex=True) # plot positions fig = plt.figure() ax = plt.gca() ax.set_title('XY positions scatterplot') ax.set_aspect('equal') ax.set_xlabel('x [kpc]') ax.set_ylabel('y [kpc]') plt.scatter(gal_cen.x, gal_cen.y, s=2) # radius histogram hist_fig = plt.figure() ax = plt.gca() ax.set_title('Histogram of radial distances') ax.set_xlabel('Radial distance [kpc]') ax.set_ylabel('Count') plt.hist(gal_cen_sph.distance, bins='auto') # xyz histogram xyz_hist_fig = plt.figure() ax = plt.gca() ax.set_title('Histogram of Cartesian position components') ax.set_xlabel('Position [kpc]') ax.set_ylabel('Count') plt.hist(np.array(gal_cen.x), bins=50, alpha=0.4, label='x') plt.hist(np.array(gal_cen.y), bins=50, alpha=0.4, label='y') plt.hist(np.array(gal_cen.z), bins=50, alpha=0.4, label='z') plt.legend() # velocities vel_fig = plt.figure() ax = plt.gca() ax.set_title('Histogram of spherical velocity components') ax.set_xlabel('Velocity [km/s]') ax.set_ylabel('Count') plt.hist(np.array(vr), bins=50, range=(-500, 500),alpha=0.4,label='vr') plt.hist(np.array(vtheta), bins=50, range=(-500, 500), alpha=0.4,label='vtheta') plt.hist(np.array(vphi), bins=50, range=(-500, 500),alpha=0.4,label='vphi') #plt.hist(np.array(vtheta), bins=50, alpha=0.4,label='vtheta') #plt.hist(np.array(vphi), bins=50, alpha=0.4,label='vphi') plt.legend() cart_vel_fig = plt.figure() ax = plt.gca() ax.set_title('Histogram of Cartesian velocity components') ax.set_xlabel('Velocity [km/s]') ax.set_ylabel('Count') plt.hist(np.array(gal_cen.v_x), bins=50, range=(-500, 500),alpha=0.4,label='vx') plt.hist(np.array(gal_cen.v_y), bins=50, range=(-500, 500), alpha=0.4,label='vy') plt.hist(np.array(gal_cen.v_z), bins=50, range=(-500, 500),alpha=0.4,label='vz') #plt.hist(np.array(vtheta), bins=50, alpha=0.4,label='vtheta') #plt.hist(np.array(vphi), bins=50, alpha=0.4,label='vphi') plt.legend() print("Plots have been opened. Close them all to terminate the program.") plt.show()
Array of shape (icrs_coords.ra.size, 5, 5) containing the Jacobians. """ ra = icrs_coords.ra.to(u.rad) dec = icrs_coords.dec.to(u.rad) l = gal_coords.l.to(u.rad) b = gal_coords.b.to(u.rad) A = astropy_icrstogal_rotation_matrix() picrs = np.array([-np.sin(ra), np.cos(ra), np.zeros_like(ra)]) qicrs = np.array([-np.cos(ra)*np.sin(dec), -np.sin(ra)*np.sin(dec), np.cos(dec)]) pgal = np.array([-np.sin(l), np.cos(l), np.zeros_like(l)]) qgal = np.array([-np.cos(l)*np.sin(b), -np.sin(ra)*np.sin(b), np.cos(b)]) J = np.zeros((ra.size, 5, 5)) J[:,2,2] = 1.0 for i in range(ra.size): G = np.matmul(A, np.stack([picrs[:,i], qicrs[:,i]]).T) G = np.matmul(np.stack([pgal[:,i], qgal[:,i]]), G) J[i,0:2,0:2] = G J[i,3:5,3:5] = G return J if __name__ in ('__main__'): print(astropy_icrstogal_rotation_matrix()) icrscoo = ICRS(ra = [0,np.pi/2,0,np.pi/3]*u.rad, dec = [0,0,np.pi/2,-np.pi/4]*u.rad) galcoo = icrscoo.transform_to(Galactic()) astropy_icrstogal_jacobian(icrscoo, galcoo)
dcrad2 = np.array([comp_dec*np.pi/180.0]) radif = rarad2-rarad1 angle = np.arctan(np.sin(radif),np.cos(dcrad1)*np.tan(dcrad2)-np.sin(dcrad1)*np.cos(radif)) sep = 60*(np.arccos(np.sin(targ_dec*np.pi/180.0)*np.sin(comp_dec*np.pi/180) + np.cos(comp_dec*np.pi/180)*np.cos(targ_dec*np.pi/180)*np.cos(comp_ra*np.pi/180 - targ_ra*np.pi/180)))*180.0/np.pi c1 = SkyCoord(targ_ra*u.deg,targ_dec*u.deg) c2 = SkyCoord(comp_ra*u.deg,comp_dec*u.deg) pa = c1.position_angle(c2).degree if args.precess and not args.apass: targ_coords_ICRS = ICRS(ra=targ_ra*u.degree,dec=targ_dec*u.degree,pm_ra_cosdec=table[0]['pmRA']*u.mas/u.yr,pm_dec=table[0]['pmDE']*u.mas/u.yr) comp_coords_ICRS = ICRS(ra=comp_ra*u.degree,dec=comp_dec*u.degree,pm_ra_cosdec=table[which_comp]['pmRA']*u.mas/u.yr,pm_dec=table[which_comp]['pmRA']*u.mas/u.yr) targ_coors_precessed = targ_coords_ICRS.transform_to(FK5(equinox=args.precess)) comp_coors_precessed = comp_coords_ICRS.transform_to(FK5(equinox=args.precess)) corrected_targ = SkyCoord(targ_coors_precessed.ra,targ_coors_precessed.dec) corrected_comp = SkyCoord(comp_coors_precessed.ra,comp_coors_precessed.dec) corrected_pa = corrected_targ.position_angle(corrected_comp).degree corrected_mid_ra = (corrected_targ.ra + corrected_comp.ra)/2. corrected_mid_dec = (corrected_targ.dec + corrected_comp.dec)/2. corrected_mid = SkyCoord(ra=corrected_mid_ra,dec=corrected_mid_dec) corrected_sep = 60*(np.arccos(np.sin(corrected_targ.dec*np.pi/180.0)*np.sin(corrected_comp.dec*np.pi/180) + np.cos(corrected_comp.dec*np.pi/180)*np.cos(corrected_targ.dec*np.pi/180)*np.cos(corrected_comp.ra*np.pi/180 - corrected_targ.ra*np.pi/180)))*180.0/np.pi
def obs2xyz(cooFil='cowleyLine.txt', Verbose=True, outFil='test.fits'): """Uses astropy to convert observed ICRS coordinates to Galactic coordinates (with proper motions) and (Galactocentric) Cartesian coordinates. Arguments: cooFil = text file giving input coordinates. Column names are read from this file. Verbose=True -- set this to print to the terminal a selection of the converted data outFil -- filename for the output. (I like .fits format because it preserves metadata and units) """ # First read in the data try: tCoo = Table.read(cooFil, format='ascii') except: print("cooDemo.obs2xyz WARN - problem reading file %s" % (cooFil)) return # we attach our guess for units in-place to the table (moved to a # separate method for clarity here). guessUnits(tCoo) # ... convert parallax to distance tCoo['distance'] = tCoo['parallax'].to(u.parsec, equivalencies=u.parallax()) # set up a proper motion (RA) scaled by cos(delta) tCoo['mu_RAcosDec'] = tCoo['mu_RA'] * np.cos(tCoo['DEC'].to(u.radian)) # print the table, including units #if Verbose: # print(tCoo) # ... and now we are in business. Set up our frame object... icrs = ICRS(ra=tCoo['RA'], dec=tCoo['DEC'], \ distance=tCoo['distance'], \ pm_ra_cosdec=tCoo['mu_RAcosDec'], pm_dec=tCoo['mu_dec'], \ radial_velocity=tCoo['RV=rho']) # Now, to find the coordinates and velocities in different formats # (Cartesian, say), we just look up the relevant attributes for # the ICRS object we've created. Here we shunt the cartesian # coordinates and velocities into our output table: tCoo['X'] = icrs.cartesian.x tCoo['Y'] = icrs.cartesian.y tCoo['Z'] = icrs.cartesian.z # ... then the velocities tCoo['vX'] = icrs.velocity.d_x tCoo['vY'] = icrs.velocity.d_y tCoo['vZ'] = icrs.velocity.d_z # We can also transform these to different frames. Here are two lsr = icrs.transform_to(LSR) galactic = icrs.transform_to(Galactic) galcen = icrs.transform_to(Galactocentric) # Now, we populate the output table with our chosen coords and # velocities in these frames. Here are the outputs in Galactic # coordinates... tCoo['l'] = galactic.l tCoo['b'] = galactic.b tCoo['pm_l_cosb'] = galactic.pm_l_cosb tCoo['pm_b'] = galactic.pm_b #print(icrs.velocity) # ... and here are the cartesian coords and velocities in galactocentric # coordinates tCoo['X'] = galcen.cartesian.x tCoo['Y'] = galcen.cartesian.y tCoo['Z'] = galcen.cartesian.z tCoo['U'] = galcen.velocity.d_x tCoo['V'] = galcen.velocity.d_y tCoo['W'] = galcen.velocity.d_z tCoo.write('test.fits', format='fits', overwrite=True) # if verbose, we write some columns of interest if Verbose: # make the formats for certain columns a bit more reasonable for sCoo in ['l','b','distance', 'X','Y','Z','U','V','W', \ 'pm_l_cosb', 'pm_b']: tCoo[sCoo].format = '%7.4f' for sCoo in ['l', 'b']: tCoo[sCoo].format = '%.6f' print(tCoo['RV=rho','parallax','RA','DEC','mu_RA','mu_dec', \ 'l','b','pm_l_cosb','pm_b','distance',\ 'X','Y','Z','U','V','W']) print("####") print("INFO - Quantities used:") print("Input assumed ICRS, so J2000.0 equinox") print( "Galactic coords use the IAU 1958 definition (see https://docs.astropy.org/en/stable/api/astropy.coordinates.Galactic.html)" ) print("Galactic center distance:", galcen.galcen_distance, \ "Solar motion:", galcen.galcen_v_sun, \ ", z_sun:", galcen.z_sun) print("(Column units for input data guessed.)")
def test_radec_to_munu(self): radec = ICRS(ra=0.0 * u.deg, dec=0.0 * u.deg) munu = radec.transform_to(SDSSMuNu(stripe=10)) assert munu.mu.value == 0.0 assert munu.nu.value == 0.0 assert munu.incl.value == 0.0
def make_plot(args): """ Take the steps to make the plot. Parameters ---------- args: dict Command line arguments Returns ------- Nothing """ infile = './data/' + args['inputFile'] basename = 'PMmap-' + args['inputFile'].split('.')[0] default_proj = ccrs.PlateCarree() sky_proj = ccrs.Mollweide() backgr = plt.imread( '../star-trail-animation/sky-images/GaiaSky-colour-2k.png') nside = hp.order2nside(args['hplevel']) hpcol = 'healpix_{0}'.format(args['hplevel']) edr3data = Table.read(infile) alpha, delta = hp.pix2ang(nside, edr3data[hpcol], lonlat=True, nest=True) pmra = edr3data['avg_pmra'] pmdec = edr3data['avg_pmdec'] icrs = ICRS(ra=alpha * u.degree, dec=delta * u.degree, pm_ra_cosdec=pmra * u.mas / u.yr, pm_dec=pmdec * u.mas / u.yr) galactic = icrs.transform_to(Galactic) pmtot = np.sqrt(galactic.pm_l_cosb.value**2 + galactic.pm_b.value**2) fig = plt.figure(figsize=(16, 9), dpi=120, frameon=False, tight_layout={'pad': 0.01}) gs = GridSpec(1, 1, figure=fig) ax = fig.add_subplot(gs[0, 0], projection=sky_proj) ax.imshow(np.fliplr(backgr), transform=default_proj, zorder=-1, origin='upper') pmcmap = cm.viridis veccolor = plt.cm.get_cmap('tab10').colors[9] linecolor = plt.cm.get_cmap('tab10').colors[9] if args['quiver']: vscale = np.median(pmtot) / 10 ax.quiver(galactic.l.value, galactic.b.value, galactic.pm_l_cosb.value, galactic.pm_b.value, transform=default_proj, angles='xy', scale=vscale, scale_units='dots', color=veccolor, headwidth=1, headlength=3, headaxislength=2.5) else: if args['colourstreams']: ax.streamplot(galactic.l.value, galactic.b.value, galactic.pm_l_cosb.value, galactic.pm_b.value, transform=default_proj, linewidth=2.0, density=2, color=pmtot, cmap=pmcmap, maxlength=0.5, arrowsize=1, arrowstyle=ArrowStyle.Fancy(head_length=1.0, head_width=.4, tail_width=.4)) elif args['lwcode'] > 0: ax.streamplot(galactic.l.value, galactic.b.value, galactic.pm_l_cosb.value, galactic.pm_b.value, transform=default_proj, linewidth=args['lwcode'] * pmtot / np.median(pmtot), density=2, color=linecolor, maxlength=0.5, arrowsize=1, arrowstyle=ArrowStyle.Fancy(head_length=1.0, head_width=.4, tail_width=.4)) else: ax.streamplot(galactic.l.value, galactic.b.value, galactic.pm_l_cosb.value, galactic.pm_b.value, transform=default_proj, linewidth=1.5, density=2, color=linecolor, maxlength=0.5, arrowsize=1, arrowstyle=ArrowStyle.Fancy(head_length=1.0, head_width=.4, tail_width=.4)) ax.invert_xaxis() if args['pdfOutput']: plt.savefig(basename + '.pdf') elif args['pngOutput']: plt.savefig(basename + '.png') else: plt.show()
def test_radec_to_munu(self): radec = ICRS(ra=0.0*u.deg, dec=0.0*u.deg) munu = radec.transform_to(SDSSMuNu(stripe=10)) assert munu.mu.value == 0.0 assert munu.nu.value == 0.0 assert munu.incl.value == 0.0
vb_errp = np.percentile(vb_samples, 84, axis=1) - vb vb_errm = vb - np.percentile(vb_samples, 16, axis=1) gaia_mc["vb"] = vb gaia_mc["vb_err"] = vb_err # print("Calculating vl") # vl_samples = calc_vl(gaia_mc) # vl, vl_err = np.median(vl_samples, axis=1), np.std(vl_samples, axis=1) # vl_errp = np.percentile(vl_samples, 84, axis=1) - vl # vl_errm = vl - np.percentile(vl_samples, 16, axis=1) # gaia_mc["vl"] = vl # gaia_mc["vl_err"] = vl_err # Calculate b icrs = ICRS(ra=gaia_mc.ra.values * u.degree, dec=gaia_mc.dec.values * u.degree) lb = icrs.transform_to(Galactic) b = lb.b * u.degree l = lb.l * u.degree gaia_mc["b"] = b.value gaia_mc["l"] = l.value print("Calculating VZ") mrv = gaia_mc.radial_velocity.values != 0.00 vz, vz_err = calc_vz(gaia_mc) vz[~mrv] = np.ones(len(vz[~mrv])) * np.nan vz_err[~mrv] = np.ones(len(vz_err[~mrv])) * np.nan gaia_mc["vz"] = vz gaia_mc["vz_err"] = vz_err # Calculate v_ra and v_dec d = gaia_mc.r_est.values * u.pc
inc=32.521 * u.deg, epoch=date_launch) #Moon Orbit aqcuisition and conversion to GCRS EPOCH = date_arrival moon = Orbit.from_body_ephem(Moon, EPOCH) moon_icrs = ICRS(x=moon.r[0], y=moon.r[1], z=moon.r[2], v_x=moon.v[0], v_y=moon.v[1], v_z=moon.v[2], representation=CartesianRepresentation, differential_cls=CartesianDifferential) moon_gcrs = moon_icrs.transform_to(GCRS(obstime=EPOCH)) moon_gcrs.representation = CartesianRepresentation moon_gcrs moon = Orbit.from_vectors( Earth, [moon_gcrs.x, moon_gcrs.y, moon_gcrs.z] * u.km, [moon_gcrs.v_x, moon_gcrs.v_y, moon_gcrs.v_z] * (u.km / u.s), epoch=EPOCH) ss0 = apollo ssf = moon #Solve for Lambert's Problem (Determining Translunar Trajectory) (v0, v), = iod.lambert(Earth.k, ss0.r, ssf.r, tof) ss0_trans = Orbit.from_vectors(Earth, ss0.r, v0, date_launch)