def test_rotating_vector_into_frame(): et_seconds = 259056665.1855896 ts = load.timescale() t = ts.tdb_jd(T0 + et_seconds / 3600. / 24.0) pc = PlanetaryConstants() pc.read_text(load('moon_080317.tf')) pc.read_binary(load('moon_pa_de421_1900-2050.bpc')) # Example from "moon_080317.tf" (the raw vector is taken from a # tweaked version of the script in the file that uses "J2000"): vector = ICRF( np.array([ 2.4798273371071659e+05, -2.6189996683651494e+05, -1.2455830876097400e+05 ]) / AU_KM) vector.t = t meter = 1e-3 frame = pc.build_frame_named('MOON_PA_DE421') result = vector.frame_xyz(frame) assert max(abs(result.km - [379908.634, 33385.003, -12516.8859])) < meter relative_frame = pc.build_frame_named('MOON_ME_DE421') result = vector.frame_xyz(relative_frame) assert max(abs(result.km - [379892.825, 33510.118, -12661.5278])) < meter
def test_separation_from_on_two_array_values(): p0 = ICRF(([1,1], [0,0], [0,0])) p1 = ICRF(([0,-1], [1,0], [0,0])) sep = p0.separation_from(p1) d = sep._degrees assert len(d) == 2 assert d[0] == 90.0 assert d[1] == 180.0
def test_subtraction(): p0 = ICRF((10, 20, 30), (40, 50, 60), center=0, target=499) p1 = ICRF((1, 2, 3), (4, 5, 6), center=0, target=399) p = p0 - p1 assert p.center == 399 assert p.target == 499 assert isinstance(p, Geocentric) assert tuple(p.position.au) == (9, 18, 27) assert tuple(p.velocity.au_per_d) == (36, 45, 54)
def test_frame_rotations_for_mean_of_date(): ts = api.load.timescale() t = ts.utc(2020, 11, 21) p = ICRF((1.1, 1.2, 1.3), t=t) lat, lon, distance1 = p.frame_latlon(true_equator_and_equinox_of_date) # Verify that the frame_latlon() coordinates match those from the # more conventional radec() call. ra, dec, distance2 = p.radec(epoch='date') assert abs(lat.arcseconds() - dec.arcseconds()) < 1e-6 assert abs(lon.arcseconds() - ra.arcseconds()) < 1e-6 assert abs(distance1.au - distance2.au) < 1e-15 # Now that we know the coordinates are good, we can use them to # rebuild a trusted x,y,z vector with which to test frame_xyz(). x1, y1, z1 = from_spherical(distance1.au, lat.radians, lon.radians) x2, y2, z2 = p.frame_xyz(true_equator_and_equinox_of_date).au assert abs(x1 - x2) < 1e-15 assert abs(y1 - y2) < 1e-15 assert abs(z1 - z2) < 1e-15
def test_J2000_ecliptic_coordinates_with_and_without_a_time_array(): p0 = ICRF((1, 0, 0)) p1 = ICRF((0, 1, 0)) p2 = ICRF(((1, 0), (0, 1), (0, 0))) lat0, lon0, distance0 = p0.ecliptic_latlon(epoch=None) lat1, lon1, distance1 = p1.ecliptic_latlon(epoch=None) lat2, lon2, distance2 = p2.ecliptic_latlon(epoch=None) assert lat2.degrees[0] == lat0.degrees assert lat2.degrees[1] == lat1.degrees assert lon2.degrees[0] == lon0.degrees assert lon2.degrees[1] == lon1.degrees assert distance2.au[0] == distance0.au assert distance2.au[1] == distance1.au
def get_probe_coords(hip_id, distance): # set timezone + load planet info utcTZ = timezone("UTC") local_tz = get_localzone() ts = load.timescale() planets = load('de421.bsp') # get time of observation and locations of observation t = ts.from_datetime(datetime(2020, 11, 9, 00, 00, tzinfo=utcTZ)) sun = planets['sun'] earth = planets['earth'] # load in the hipparcos data with load.open(hipparcos.URL) as f: df = hipparcos.load_dataframe(f) # # match on star coords # ra_inds = [] # for ind, cat_ra in enumerate(df['ra_degrees'].values): # if isclose(cat_ra, ra_star, rel_tol=1e-2): # ra_inds.append(ind) # dec_inds = [] # for ind, cat_dec in enumerate(df['dec_degrees'].values): # if isclose(cat_dec, dec_star, rel_tol=1e-2): # dec_inds.append(ind) # # find where ra & dec match within tolerance # sets = set(ra_inds).intersection(set(dec_inds)) # inds = [x for x in iter(sets)] # print(inds) # just take the first one for now the_star = Star.from_dataframe(df.loc[hip_id]) # "observe" the star from Earth starPosObj = earth.at(t).observe(the_star) ra, dec, dist = starPosObj.radec() # get coords of opposite point on the sky ra = ((ra._degrees + 180.0) % 360) * (24.0 / 360.0) dec = -1.0 * dec._degrees # get coords of the probe and return ra dec in degree probe = position_of_radec(ra, dec, distance, t=t) sunPosObj = earth.at(t).observe(sun) inverseSunCoord = -1.0 * sunPosObj.position.au probeCoord = probe.position.au probeDir = ICRF(probeCoord + inverseSunCoord).radec() return probeDir[0]._degrees, probeDir[1]._degrees
def test_dynamic_ecliptic_coordinates_with_and_without_a_time_array(): ts = api.load.timescale() t = ts.utc(1980) p0 = ICRF((1, 0, 0)) p1 = ICRF((0, 1, 0)) p2 = ICRF(((1, 0), (0, 1), (0, 0))) lat0, lon0, distance0 = p0.ecliptic_latlon(epoch=t) lat1, lon1, distance1 = p1.ecliptic_latlon(epoch=t) lat2, lon2, distance2 = p2.ecliptic_latlon(epoch=t) assert lat2.degrees[0] == lat0.degrees assert lat2.degrees[1] == lat1.degrees assert lon2.degrees[0] == lon0.degrees assert lon2.degrees[1] == lon1.degrees assert distance2.au[0] == distance0.au assert distance2.au[1] == distance1.au
def test_separation_from_on_an_array_and_a_scalar(): p0 = ICRF(([1,0], [0,1], [0,0])) p1 = ICRF((0, 0, 1)) sep = p0.separation_from(p1) d = sep._degrees assert len(d) == 2 assert d[0] == 90.0 assert d[1] == 90.0 # And the other way around: sep = p1.separation_from(p0) d = sep._degrees assert len(d) == 2 assert d[0] == 90.0 assert d[1] == 90.0
def test_J2000_ecliptic_coordinates_with_and_without_a_time_array(): p0 = ICRF((1,0,0)) p1 = ICRF((0,1,0)) p2 = ICRF(((1, 0), (0, 1), (0, 0))) lat0, lon0, distance0 = p0.ecliptic_latlon(epoch=None) lat1, lon1, distance1 = p1.ecliptic_latlon(epoch=None) lat2, lon2, distance2 = p2.ecliptic_latlon(epoch=None) assert lat2.degrees[0] == lat0.degrees assert lat2.degrees[1] == lat1.degrees assert lon2.degrees[0] == lon0.degrees assert lon2.degrees[1] == lon1.degrees assert distance2.au[0] == distance0.au assert distance2.au[1] == distance1.au
def test_dynamic_ecliptic_coordinates_with_and_without_a_time_array(): ts = api.load.timescale() t = ts.utc(1980) p0 = ICRF((1,0,0)) p1 = ICRF((0,1,0)) p2 = ICRF(((1, 0), (0, 1), (0, 0))) lat0, lon0, distance0 = p0.ecliptic_latlon(epoch=t) lat1, lon1, distance1 = p1.ecliptic_latlon(epoch=t) lat2, lon2, distance2 = p2.ecliptic_latlon(epoch=t) assert lat2.degrees[0] == lat0.degrees assert lat2.degrees[1] == lat1.degrees assert lon2.degrees[0] == lon0.degrees assert lon2.degrees[1] == lon1.degrees assert distance2.au[0] == distance0.au assert distance2.au[1] == distance1.au
#!/usr/bin/env python from skyfield.positionlib import ICRF from skyfield.api import load, Topos ts = load.timescale() t = ts.now() observer = Topos(latitude_degrees=52.8344, longitude_degrees=6.3785, elevation_m=10.0) p = ICRF([0.0, 0.0, 0.0], observer_data=observer, t=t) q = p.from_altaz(alt_degrees=30.0, az_degrees=30.0) print(p, q)
def test_separation_from_on_scalar(): p0 = ICRF((1, 0, 0)) p1 = ICRF((0, 1, 0)) assert str(p0.separation_from(p1)) == '90deg 00\' 00.0"'
#!/usr/bin/env python from skyfield.positionlib import ICRF from skyfield.api import load,Topos ts=load.timescale() t=ts.now() observer=Topos(latitude_degrees=52.8344,longitude_degrees=6.3785,elevation_m=10.0) p=ICRF([0.0,0.0,0.0],observer_data=observer,t=t) q=p.from_altaz(alt_degrees=30.0,az_degrees=30.0) print(p,q)
def test_ecliptic_xyz_with_no_epoch(): p = ICRF(_deep) x, y, z = p.ecliptic_xyz().au assert x.shape == y.shape == z.shape == (1, 1)
vrad = np.sqrt(C3temp + 2. * GMsun / frad) frad += vrad * dayskip #ftheta += dftheta #fphi += dfphi x, y, z = to_car(frad, ftheta, fphi) pos.append( np.array([x, y, z]) ) #pos[-1]+np.array([dx,dy,dz]))#pos[-1]+[x*float(i-ind[crs.places[-1]]) for x in di[-1]]) vel.append(vel[-1]) #vel = ? px.append(pos[-1][0]) py.append(pos[-1][1]) pz.append(pos[-1][2]) dprobe.append(np.sqrt(pos[-1].dot(pos[-1]))) ##This also now works! ISP = ICRF(pos, vel, t=tp, center=0) #print(ISP.t[ind[m]]) #ICRF positions don't support slicing #print(ISP.position.au[ind[m]]) #Need to think about viewing - angular size and separation from the Sun sizes = {p: [None] * len(t) for p in planetsonly} #angular size in arcseconds angles = {p: [None] * len(t) for p in planetsonly} #angle in degrees between sun and planet p mag = {p: [None] * len(t) for p in planetsonly} #apparent V-band magnitude of planet p camera = {p: [x[:] for x in [[None] * 3] * len(t)] for p in planetsonly} #angle in degrees between sun and planet p #out_of_frame = {p:[None]*len(t) for p in planetsonly} #records size when planet p is more than 90 degrees away from Sun #in_frame = {p:[None]*len(t) for p in planetsonly} #records size when planet p is less than 90 degrees away from Sun #alpha = {p:[None]*len(t) for p in planetsonly} #angle in degrees between sun and observer from planet p
def test_subtraction(): p0 = ICRF((10,20,30), (40,50,60)) p1 = ICRF((1,2,3), (4,5,6)) p = p0 - p1 assert tuple(p.position.au) == (9, 18, 27) assert tuple(p.velocity.au_per_d) == (36, 45, 54)
def make(cls, pos: ICRF) -> "EclipticPosition": lat, lon, _, latR, lonR, __ = pos.frame_latlon_and_rates(ecliptic_frame) return EclipticPosition(lat, latR, lon, lonR)
def write_PV_to_file(tle_obj_vec: list[dict], t0: datetime, tf: datetime, timestep: float, filepath: str = "sats-TLE-example.json") -> None: import json from collections import OrderedDict import numpy as np from sgp4.api import Satrec, SatrecArray, jday from skyfield.api import load from skyfield.sgp4lib import TEME from skyfield.units import Velocity, Distance from skyfield.framelib import ecliptic_J2000_frame from skyfield.positionlib import ICRF json_posveldata = OrderedDict() # all TLEs (w/ diff epochs) will be propagated to current time. epoch_error_flag = False time_vec = [t0] t = t0 while t < tf: t += datetime.timedelta(seconds=timestep) time_vec.append(t) years, months, days, hours, minutes, seconds = zip(*[(t.year, t.month, t.day, t.hour, t.minute, t.second) for t in time_vec]) years, months, days, hours, minutes, seconds = np.array(years), np.array( months), np.array(days), np.array(hours), np.array(minutes), np.array( seconds) jds, frs = jday(years, months, days, hours, minutes, seconds) satrecs_vec = [] for item in tle_obj_vec: sat_name = item["NORAD_CAT_ID"] epoch = datetime.datetime.fromisoformat(item["EPOCH"]) if (tf > (epoch + datetime.timedelta(days=5))) or ( tf < (epoch - datetime.timedelta(days=5))): # raise TypeError(f" Final propagation date {tf} is more than 5 days away from latest TLE epoch ({epoch}), for satellite {sat_name}} ") epoch_error_flag = True sat = Satrec.twoline2rv(item["TLE_LINE1"], item["TLE_LINE2"]) satrecs_vec.append(sat) json_posveldata[sat_name] = {"P": [], "V": []} satrecs = SatrecArray(satrecs_vec) errors, rs, vs = satrecs.sgp4(jds, frs) # r,v in TEME frame ts = load.timescale() for idxsat, satdata in enumerate(json_posveldata.values()): for idxtime, (jdi, fri) in enumerate(zip(jds, frs)): # convert to J2000 ttime = ts.ut1_jd(jdi + fri) rvicrf = ICRF.from_time_and_frame_vectors( t=ttime, frame=TEME, distance=Distance(km=rs[idxsat][idxtime]), velocity=Velocity(km_per_s=vs[idxsat][idxtime])) # rvj2000 = rvicrf.frame_xyz_and_velocity(ecliptic_J2000_frame) # pos_timestep_j2000, vel_timestep_j2000 = rvj2000[0].m, rvj2000[1].m_per_s pos_timestep_j2000, vel_timestep_j2000 = rvicrf.position.m, rvicrf.velocity.m_per_s satdata["P"].append(pos_timestep_j2000.tolist()) satdata["V"].append(vel_timestep_j2000.tolist()) # satdata["P"] = rs[idxsat].tolist() #TEME # satdata["V"] = vs[idxsat].tolist() #TEME if errors.any(): print("SGP4 errors found.") # check errror type. if epoch_error_flag: print( f"Warning: Results obtained might be inaccurate. Final propagation date {tf} is more than 5 days away from latest TLE epoch ({epoch}), for satellite {sat_name} " ) with open(filepath, "w") as file: json.dump(json_posveldata, file, indent=6) print(f"PV File written successfully at {filepath}.")
from skyfield.api import Topos, load from skyfield.api import EarthSatellite from skyfield.positionlib import ICRF from skyfield.positionlib import Geometric from skyfield.positionlib import Barycentric ts = load.timescale() thisx = 4085.0136322698854 thisy = -1852.4897691900894 thisz = -4916.7862179899175 vec = ICRF([thisx,thisy,thisz]) vec.t = ts.utc(2020, 3, 18, 3, 36, 35.0) vecG1 = Geometric([thisx,thisy,thisz]) vecG1.t = ts.utc(2020, 3, 18, 3, 36, 35.0) satellites = load.tle_file('fullcatalog.txt') print( 'Loaded', len(satellites), 'satellites') firsttime = ts.utc(2020, 3, 18, 3, 36, 35.0) for sat in satellites: geocentric = sat.apparent(firsttime) thatx, thaty, thatz = geocentric.position.km print(geocentric.position.km) #if (thatx == thisx):