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 EarthLocation(self, jd): """ Returns positions as an EarthLocation object, which can be feed directly into :func:`astropy.time.Time.light_travel_time`. Parameters: jd (ndarray): Time in Julian Days where position of TESS should be calculated. Returns: :class:`astropy.coordinates.EarthLocation`: EarthLocation object that can be passed directly into :py:class:`astropy.time.Time`. .. codeauthor:: Rasmus Handberg <*****@*****.**> """ # Get positions as 2D array: positions = self.position(jd, relative_to='EARTH') # Transform into appropiate Geocentric frame: obstimes = Time(jd, format='jd', scale='tdb') cartrep = coord.CartesianRepresentation(positions, xyz_axis=1, unit=u.km) gcrs = coord.GCRS(cartrep, obstime=obstimes) itrs = gcrs.transform_to(coord.ITRS(obstime=obstimes)) # Create EarthLocation object return coord.EarthLocation.from_geocentric(*itrs.cartesian.xyz, unit=u.km)
def satellite_position(): """not used""" # Hardcoded for one satellite satellite_name = "ODIN" satellite_line1 = '1 26702U 01007A 19291.79098765 -.00000023 00000-0 25505-5 0 9996' satellite_line2 = '2 26702 97.5699 307.6930 0011485 26.4207 333.7604 15.07886437 19647' current_time = datetime.datetime.now() satellite = twoline2rv(satellite_line1, satellite_line2, wgs72) position, velocity = satellite.propagate( current_time.year, current_time.month, current_time.day, current_time.hour, current_time.minute, current_time.second) now = Time.now() # position of satellite in GCRS or J20000 ECI: cartrep = coord.CartesianRepresentation(x=position[0], y=position[1], z=position[2], unit=u.m) gcrs = coord.GCRS(cartrep, obstime=now) itrs = gcrs.transform_to(coord.ITRS(obstime=now)) loc = coord.EarthLocation(*itrs.cartesian.xyz) return jsonify({ 'eci': {'x': position[0], 'y': position[1], 'z': position[2]}, 'geodetic': {'latitude': loc.lat.deg, 'longitude': loc.lon.deg, 'height': loc.height.to(u.m).value} })
def astropy_horizontal_to_ECI(self, r, el, az, loc, utc_date): obstime = time.Time(utc_date, scale="utc") elaz = self.astropy_get_AltAz(r, el, az, loc, utc_date) gcrs = elaz.transform_to(coord.GCRS(obstime=obstime)) return [ gcrs.cartesian.x.value, gcrs.cartesian.y.value, gcrs.cartesian.z.value ]
def itrs2gcrs(years, months, dates, hours, minutes, seconds, pos, vel, utc_time, gcrs_filename): """ This function is to transform the coordinates and velocities from itrs into gcrs """ date_list = [] for index, element in enumerate( zip(years, months, dates, hours, minutes, seconds)): date_list.append(str(int(element[0])) + '-' + str(int(element[1])) + '-' + str(int(element[2])) + ' ' + \ str(int(element[3])) + ':' + str(int(element[4])) + ':' + str(element[5])) a_date = atime(date_list) pos = pos * u.km vel = vel * u.km itrs1 = coor.ITRS(x=pos[:, 0], y=pos[:, 1], z=pos[:, 2], representation_type='cartesian', obstime=a_date) gcrs1 = itrs1.transform_to(coor.GCRS(obstime=a_date)) itrs2 = coor.ITRS(x=vel[:, 0], y=vel[:, 1], z=vel[:, 2], representation_type='cartesian', obstime=a_date) gcrs2 = itrs2.transform_to(coor.GCRS(obstime=a_date)) gcrs_xyz1 = np.asarray(gcrs1.cartesian.xyz) gcrs_xyz2 = np.asarray(gcrs2.cartesian.xyz) dd_igrf = dd.from_pandas(pd.DataFrame({ 'utc_time': utc_time, 'gcrs_x': gcrs_xyz1[0], 'gcrs_y': gcrs_xyz1[1], 'gcrs_z': gcrs_xyz1[2], 'gcrs_rvx': gcrs_xyz2[0], 'gcrs_rvy': gcrs_xyz2[1], 'gcrs_rvz': gcrs_xyz2[2] }), npartitions=1) write_gcrs_file_header(gcrs_filename, dd_igrf) dd_igrf.to_csv(gcrs_filename, single_file=True, sep='\t', index=False, mode='a+')
def get_coord_in_ecef(xyz): from astropy import coordinates as coord from astropy import units as u from astropy.time import Time now = Time(TIME) # position of satellite in GCRS or J20000 ECI: cartrep = coord.CartesianRepresentation(*xyz, unit=u.m) gcrs = coord.GCRS(cartrep, obstime=now) itrs = gcrs.transform_to(coord.ITRS(obstime=now)) loc = coord.EarthLocation(*itrs.cartesian.xyz) return [loc.lat, loc.lon, loc.height]
def GCRS2ITRS(r, v, jd, fr): now = Time(jd + fr, format="jd") itrs = coord.GCRS(r[0] * u.m, r[1] * u.m, r[2] * u.m, v[0] * u.m / u.s, v[1] * u.m / u.s, v[2] * u.m / u.s, obstime=now, representation_type='cartesian') gcrs = itrs.transform_to(coord.ITRS(obstime=now)) r, v = gcrs.cartesian.xyz.value, gcrs.velocity.d_xyz.value return r, v * 1000
def calc_uvw_astropy(datetime, radec, xyz, telescope='VLA', takeants=None): """ Calculates and returns uvw in meters for a given time and pointing direction. datetime is time (astropy.time.Time) to calculate uvw. radec is (ra,dec) as tuple in radians. Can optionally specify a telescope other than the VLA. """ if telescope == 'JVLA' or 'VLA': telescope = 'VLA' phase_center = coordinates.SkyCoord(*radec, unit='rad', frame='icrs') if takeants is not None: antpos = coordinates.EarthLocation(x=xyz[takeants, 0], y=xyz[takeants, 1], z=xyz[takeants, 2], unit='m') else: antpos = coordinates.EarthLocation(x=xyz[:, 0], y=xyz[:, 1], z=xyz[:, 2], unit='m') if isinstance(datetime, str): datetime = time.Time(datetime.replace('/', '-', 2).replace('/', ' '), format='iso') tel_p, tel_v = coordinates.EarthLocation.of_site( telescope).get_gcrs_posvel(datetime) antpos_gcrs = coordinates.GCRS(antpos.get_gcrs_posvel(datetime)[0], obstime=datetime, obsgeoloc=tel_p, obsgeovel=tel_v) uvw_frame = phase_center.transform_to(antpos_gcrs).skyoffset_frame() antpos_uvw = antpos_gcrs.transform_to(uvw_frame).cartesian nant = len(antpos_uvw) antpairs = [(i, j) for j in range(nant) for i in range(j)] nbl = len(antpairs) u = np.empty(nbl, dtype='float32') v = np.empty(nbl, dtype='float32') w = np.empty(nbl, dtype='float32') for ibl, ant in enumerate(antpairs): bl = antpos_uvw[ant[1]] - antpos_uvw[ant[0]] u[ibl] = bl.y.value v[ibl] = bl.z.value w[ibl] = bl.x.value return u, v, w
def source_lmn_rad(self, obstime, include_sun=True): gcrs = acc.GCRS(obstime=obstime, obsgeoloc=self.obsgeoloc) gcrs_dict = { name: icrs.transform_to(gcrs) for name, icrs in self.sources.items() } if include_sun: sun = acc.get_sun(obstime) gcrs_dict['Sun'] = sun.transform_to(gcrs) lmn_dict = { name: scc.pqr_from_icrs(numpy.array([gcrs.ra.rad, gcrs.dec.rad]), obstime=obstime, pqr_to_itrs_matrix=self.pqr_to_itrs_matrix) for name, gcrs in gcrs_dict.items() } return lmn_dict
def ecef_to_eci(ecef_positions, ecef_velocities, posix_times): """Converts one or multiple Cartesian vectors in the ECEF to a GCRS frame at the given time. When converting multiple objects, each object should have a ECEF position, ECEF velocity and a reference time in the same index of the appropriate input list Args: ecef_positions (list of tuples): A list of the Cartesian coordinate tuples of the objects in the ECCF frame (m) ecef_velocities (list of tuples): A list of the velocity tuples of the objects in the EECF frame (m/s) time_posix (int): A list of times to be used as reference frame time for objects Returns: A list of tuples, each tuple has the following format: (Position Vector3D(x,y,z), Velocity Vector3D(x,y,z)) Position Vector: x = GCRS X-coordinate (m) y = GCRS Y-coordinate (m) z = GCRS Z-coordinate (m) Velocity Vector x = GCRS X-velocity (m/s) y = GCRS Y-velocity (m/s) z = GCRS Z-velocity (m/s) Note: Unlike the rest of the software that uses J2000 FK5, the ECI frame used here is GCRS; This can potentially introduce around 200m error for locations on surface of Earth. """ posix_times = Time(posix_times, format='unix') cart_diff = coordinates.CartesianDifferential(ecef_velocities, unit='m/s', copy=False) cart_rep = coordinates.CartesianRepresentation(ecef_positions, unit='m', differentials=cart_diff, copy=False) ecef = coordinates.ITRS(cart_rep, obstime=posix_times) gcrs = ecef.transform_to(coordinates.GCRS(obstime=posix_times)) # pylint: disable=no-member positions = array(transpose(gcrs.cartesian.xyz.value), ndmin=2) velocities = array(transpose(gcrs.cartesian.differentials.values()[0].d_xyz .to(units.m / units.s).value), ndmin=2) # pylint: enable=no-member ret_pairs = [(Vector3D(*pos), Vector3D(*vel)) for pos, vel in zip(positions, velocities)] return ret_pairs
def create_test_frames(): """Creates an array of frames to be used for testing.""" # Suppress warnings from astropy that are caused by having 'dubious' dates # that are too far in the future. It's not a concern for the purposes of # unit tests. See issue #5809 on the astropy GitHub for discussion. from astropy._erfa import ErfaWarning warnings.simplefilter("ignore", ErfaWarning) 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( # A default galcen_coord is used since none is provided here galcen_distance=5.0 * u.m, 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))), cf.StokesFrame(), cf.TemporalFrame(time.Time("2011-01-01")) ] return frames
def satlla_from_TLE(line1, line2): start = timer() satellite = twoline2rv(line1, line2, wgs72) stop = timer() print("3 i . Duration : %f s" % (stop - start)) start = timer() # try to propagate for a period of time propTimeSecs = np.pi*2/satellite.no*60 timeDivisor = 10 STARTTIME = satellite.epoch stop = timer() print("3 ii . Duration : %f s" % (stop - start)) # STOPTIME = STARTTIME + datetime.timedelta(seconds = propTimeSecs) start = timer() r = np.zeros((int(propTimeSecs/timeDivisor), 3)) v = np.zeros((int(propTimeSecs/timeDivisor), 3)) lat = np.zeros((int(propTimeSecs/timeDivisor), 1)) lon = np.zeros((int(propTimeSecs/timeDivisor), 1)) stop = timer() print("3 iii. Duration : %f s" % (stop - start)) #print(STARTTIME) #print(STOPTIME) start = timer() print("%s / %s = %s" % (propTimeSecs, timeDivisor, propTimeSecs/timeDivisor)) for i in range(int(propTimeSecs/timeDivisor)): # propagate orbit and convert to LLA CURRTIME = STARTTIME + datetime.timedelta(seconds=i*timeDivisor) r[i,], v[i,] = satellite.propagate(CURRTIME.year, CURRTIME.month, CURRTIME.day, CURRTIME.hour, CURRTIME.minute, CURRTIME.second) cartRep = coord.CartesianRepresentation(x=r[i,0], y=r[i,1], z=r[i,2], unit=u.km) gcrs = coord.GCRS(cartRep, obstime=CURRTIME) # cast xyz coordinate in ECI frame itrs = gcrs.transform_to(coord.ITRS(obstime=CURRTIME)) lat[i], lon[i] = itrs.spherical.lat.value , itrs.spherical.lon.value stop = timer() print("3 iv . Duration : %f s" % (stop - start)) return r, v, lat, lon
position_stk error_tot = np.sqrt(error.dot(error.T)) * 1e3 if error_tot > 100: warnings.warn("Satellite position off by more than 100 m") velocity_stk = np.array([-1.524601, -0.038234, 7.512187]) error = np.array([position_ecef.v_x.value,position_ecef.v_y.value,position_ecef.v_z.value]) - \ velocity_stk error_tot = np.sqrt(error.dot(error.T)) * 1e3 if error_tot > 500: warnings.warn("Satellite velocity off by more than 500 m/s") position_ecef.transform_to( coord.GCRS(obstime=d)).set_representation_cls('cartesian') position_eci_stk = np.array([-2508.510645, 6457.675701, 205.086445]) error = np.array([position_ecef.cartesian.x.value,position_ecef.cartesian.y.value,position_ecef.cartesian.z.value]) - \ position_eci_stk error_tot = np.sqrt(error.dot(error.T)) * 1e3 if error_tot > 100: warnings.warn("Satellite position off by more than 100 m") velocity_stk_eci = np.array([1.031261, 0.146421, 7.510402]) error = np.array([position_ecef.velocity.d_x.value,position_ecef.velocity.d_y.value,position_ecef.velocity.d_z.value]) - \ velocity_stk_eci error_tot = np.sqrt(error.dot(error.T)) * 1e3 if error_tot > 500: warnings.warn("Satellite velocity off by more than 500 m/s")
def latlon_from_cartrep(cartRep, CURRTIME): gcrs = coord.GCRS(cartRep, obstime=CURRTIME) # cast xyz coordinate in ECI frame itrs = gcrs.transform_to(coord.ITRS(obstime=CURRTIME)) return itrs.spherical.lat.value, itrs.spherical.lon.value
def air_density(years, months, date_i): dd_aird_i = dd.read_csv( urlpath='..//output//taiji-01-0222-air-drag-gcrs-2019-09.txt', header=None, engine='c', skiprows=35, storage_options=dict(auto_mkdir=False), sep='\s+', names=[ 'gps_time', 'xacc', 'yacc', 'zacc', 'xacc_s', 'yacc_s', 'zacc_s' ], dtype=np.float64, encoding='gb2312') utc_time = dd_aird_i.gps_time.compute().to_numpy() dates = np.floor((utc_time - utc_time[0]) / 86400.).astype(np.int) + date_i hours = np.floor((utc_time - utc_time[0] - (dates - date_i) * 86400.) / 3600.).astype(np.int) minutes = np.floor((utc_time - utc_time[0] - hours * 3600.0 - (dates - date_i) * 86400.) / 60.).astype(np.int) seconds = np.mod((utc_time - utc_time[0] - hours * 3600.0 - (dates - date_i) * 86400. - minutes * 60.0), 60.).astype(np.int) date_list = [] years = np.ones(dates.__len__()) * years months = np.ones(dates.__len__()) * months for index, element in enumerate( zip(years, months, dates, hours, minutes, seconds)): date_list.append( str(int(element[0])) + '-' + str(int(element[1])) + '-' + str(int(element[2])) + ' ' + str(int(element[3])) + ':' + str(int(element[4])) + ':' + str(element[5])) a_date = atime(date_list) xacc = dd_aird_i.xacc.compute().to_numpy() yacc = dd_aird_i.yacc.compute().to_numpy() zacc = dd_aird_i.zacc.compute().to_numpy() gcrs = coor.GCRS(x=xacc, y=yacc, z=zacc, representation_type='cartesian', obstime=a_date) itrs = gcrs.transform_to(coor.ITRS(obstime=a_date)) itrs = np.asarray(itrs.cartesian.xyz) plt.style.use(['science', 'no-latex', 'high-vis']) fig, ax = plt.subplots(figsize=(15, 8)) plt.plot(utc_time, itrs[0], linewidth=2, label='xacc_gcrs') plt.plot(utc_time, itrs[1], linewidth=2, label='yacc_gcrs') plt.plot(utc_time, itrs[2], linewidth=2, label='zacc_gcrs') plt.tick_params(labelsize=25, width=2.9) ax.yaxis.get_offset_text().set_fontsize(24) ax.xaxis.get_offset_text().set_fontsize(24) plt.xlabel('GPS time [s]', fontsize=20) plt.ylabel('$Air \quad drag \quad accelaration [km/s^2]$', fontsize=20) # plt.legend(fontsize=20, loc='best') plt.legend(fontsize=20, loc='lower left', bbox_to_anchor=(0, 1, 1, .1), ncol=3, mode='expand') plt.grid(True, which='both', ls='dashed', color='0.5', linewidth=0.6) plt.gca().spines['left'].set_linewidth(2) plt.gca().spines['top'].set_linewidth(2) plt.gca().spines['right'].set_linewidth(2) plt.gca().spines['bottom'].set_linewidth(2) plt.savefig('..//images//air_drag_itrs.png', dpi=500) plt.show()