def main(): args = sys.argv[1:] if not args: print('usage: deprecations.py (a|b...)') sys.exit(2) arg = args[0] if arg == 'a': from skyfield.api import earth, mars, now earth(now()).observe(mars).radec() elif arg == 'b': from skyfield.api import earth earth.topos('42.3583 N', '71.0636 W') elif arg == 'c': from skyfield.api import load eph = load('de421.bsp') earth = eph['earth'] earth(100) elif arg == 'd': from skyfield.api import JulianDate JulianDate(utc=(1980, 1, 1)) elif arg == 'e': from skyfield.api import load eph = load('de421.bsp') earth = eph['earth'] earth.at(utc=(1980, 1, 1))
def _get_twighligh_component(session_plan, comp): ts = load.timescale() _, latitude, longitude, _ = _get_location_info_from_session_plan( session_plan) observer = wgs84.latlon(latitude, longitude) tz_info = _get_session_plan_tzinfo(session_plan) ldate1 = tz_info.localize(session_plan.for_date + timedelta(hours=12)) ldate2 = tz_info.localize(session_plan.for_date + timedelta(hours=36)) t1 = ts.from_datetime(ldate1) t2 = ts.from_datetime(ldate2) eph = load('de421.bsp') t, y = almanac.find_discrete(t1, t2, almanac.dark_twilight_day(eph, observer)) index1 = None index2 = None for i in range(len(y)): if y[i] == comp: if index1 is None: index1 = i + 1 elif index2 is None: index2 = i if index1 is None or index2 is None: return None, None return t[index1].astimezone(tz_info), t[index2].astimezone(tz_info)
def galactic_Sun_north_directions( recv_time, user_longlatdist=geographic_position): user_longlatdist = np.array(user_longlatdist)#46.07983746062874, 26.232615661106784, 659.5100082775696 with load.open(hipparcos.URL) as f: df = hipparcos.load_dataframe(f) planets = load('de421.bsp') earth = planets['earth'] user_position = earth + Topos('{} N'.format(user_longlatdist[0]), '{} E'.format(user_longlatdist[1])) #user_longlatdist user_longlatdist[0],user_longlatdist[1] terrestrial_time = format_time(recv_time) ts = load.timescale() t = ts.tt(terrestrial_time[0], terrestrial_time[1], terrestrial_time[2], terrestrial_time[3], terrestrial_time[4], terrestrial_time[5]) sun = planets['sun'] astrometric_sun = user_position.at(t).observe(sun) alt_sun, az_sun, distance_sun = astrometric_sun.apparent().altaz()#astrometric.apparent().altaz() = astrometric_denebola.apparent().altaz() print('Location: ', '{} N'.format(user_longlatdist[0]), '{} E'.format(user_longlatdist[1])) print('Sun (alt/az): ',alt_sun, az_sun) sun_position = pm.aer2ecef( az_sun.degrees, alt_sun.degrees, distance_sun.m, user_longlatdist[0], user_longlatdist[1], user_longlatdist[2]) # Északi Galaktikus Pólus (RA: 12h 51.42m; D: 27° 07.8′, epocha J2000.0) coma_berenices = Star(ra_hours=(12, 51, 25.2), dec_degrees=(27, 7, 48.0)) astrometric_berenice = user_position.at(t).observe(coma_berenices) alt_b, az_b, distance_b = astrometric_berenice.apparent().altaz() print('Coma Berenice (alt/az): ',alt_b, az_b) berenice_position = pm.aer2ecef( az_b.degrees, alt_b.degrees, distance_b.m, user_longlatdist[0], user_longlatdist[1], user_longlatdist[2]) stars_pos=[sun_position, berenice_position] return stars_pos
def get_star_position( recv_time, star_name, star_name2, user_longlatdist=geographic_position): # if not star_name: # star_name = 57632 #Denebola # if not star_name2: # star_name2 = 109074 #Sadalmelik user_longlatdist = np.array(user_longlatdist)#46.07983746062874, 26.232615661106784, 659.5100082775696 with load.open(hipparcos.URL) as f: df = hipparcos.load_dataframe(f) planets = load('de421.bsp') earth = planets['earth'] user_position = earth + Topos('{} N'.format(user_longlatdist[0]), '{} E'.format(user_longlatdist[1])) #user_longlatdist user_longlatdist[0],user_longlatdist[1] terrestrial_time = format_time(recv_time) ts = load.timescale() t = ts.tt(terrestrial_time[0], terrestrial_time[1], terrestrial_time[2], terrestrial_time[3], terrestrial_time[4], terrestrial_time[5]) denebola = Star.from_dataframe(df.loc[star_name]) astrometric_denebola = user_position.at(t).observe(denebola) alt_d, az_d, distance_d = astrometric_denebola.apparent().altaz()#astrometric.apparent().altaz() = astrometric_denebola.apparent().altaz() print('Location: ', '{} N'.format(user_longlatdist[0]), '{} E'.format(user_longlatdist[1])) print('S1 (alt/az): ',alt_d, az_d) star_pos_d = pm.aer2ecef( az_d.degrees,alt_d.degrees, distance_d.m,user_longlatdist[0],user_longlatdist[1],user_longlatdist[2]) sadalmelik = Star.from_dataframe(df.loc[star_name2]) astrometric_sadalmelik = user_position.at(t).observe(sadalmelik) alt_s, az_s, distance_s = astrometric_sadalmelik.apparent().altaz() print('S2 (alt/az): ',alt_s, az_s) star_pos_s = pm.aer2ecef( az_s.degrees,alt_s.degrees, distance_s.m,user_longlatdist[0],user_longlatdist[1],user_longlatdist[2]) stars_pos=[star_pos_d,star_pos_s] return stars_pos
def test_vectors(): ts = load.timescale() t = ts.tt(2017, 1, 23, 10, 44) planets = load('de421.bsp') earth = planets['earth'] mars = planets['mars'] v = earth assert str(v) == """\ Sum of 2 vectors: + Segment 'de421.bsp' 0 SOLAR SYSTEM BARYCENTER -> 3 EARTH BARYCENTER + Segment 'de421.bsp' 3 EARTH BARYCENTER -> 399 EARTH""" assert repr(v) == "\ <VectorSum of 2 vectors 0 SOLAR SYSTEM BARYCENTER -> 399 EARTH>" assert str(v.at(t)) == "\ <Barycentric position and velocity at date t center=0 target=399>" v = earth - mars assert str(v) == """\ Sum of 4 vectors: - Segment 'de421.bsp' 4 MARS BARYCENTER -> 499 MARS - Segment 'de421.bsp' 0 SOLAR SYSTEM BARYCENTER -> 4 MARS BARYCENTER + Segment 'de421.bsp' 0 SOLAR SYSTEM BARYCENTER -> 3 EARTH BARYCENTER + Segment 'de421.bsp' 3 EARTH BARYCENTER -> 399 EARTH""" assert repr(v) == "\ <VectorSum of 4 vectors 499 MARS -> 399 EARTH>" assert str(v.at(t)) == "\
def test_comet(): text = (b' CJ95O010 1997 03 29.6333 0.916241 0.994928 130.6448' b' 283.3593 88.9908 20200224 -2.0 4.0 C/1995 O1 (Hale-Bopp)' b' MPC106342\n') ts = load.timescale(builtin=True) t = ts.utc(2020, 5, 31) eph = load('de421.bsp') e = eph['earth'].at(t) for loader in mpc.load_comets_dataframe, mpc.load_comets_dataframe_slow: df = loader(BytesIO(text)) row = df.iloc[0] k = mpc.comet_orbit(row, ts, GM_SUN) p = e.observe(eph['sun'] + k) ra, dec, distance = p.radec() # The file authorities/mpc-hale-bopp in the repository is the # source of these angles. TODO: can we tighten this bound and # drive it to fractions of an arcsecond? ra_want = Angle(hours=(23, 59, 16.6)) dec_want = Angle(degrees=(-84, 46, 58)) assert abs(ra_want.arcseconds() - ra.arcseconds()) < 2.0 assert abs(dec_want.arcseconds() - dec.arcseconds()) < 0.2 assert abs(distance.au - 43.266) < 0.0005 assert k.target == 'C/1995 O1 (Hale-Bopp)'
def test_cirs_sofa(): ts = api.load.timescale() earth = api.load('de421.bsp')['earth'] test_data = [ [45.0, 46.0, 2458327], [200.0, -22.0, 2458327], [45.0, 46.0, 2459327] ] # Results output by SOFA. Calculated using the source code above. sofa_results = [ [45.074343838325, 46.067831092355], [200.013551320030, -22.096008994214], [45.077698288877, 46.082296559677] ] tol = 1e-5 / 3600.0 # 10 micro arc-seconds for ((ra_icrs, dec_icrs, tdb), (ra_sofa, dec_sofa)) in zip(test_data, sofa_results): ss = Star(ra_hours=(ra_icrs / 15.0), dec_degrees=dec_icrs) st = ts.tdb(jd=tdb) with low_precision_ERA(): ra_cirs, dec_cirs, _ = earth.at(st).observe(ss).apparent().cirs_radec(st) assert np.allclose(ra_cirs._degrees, ra_sofa, rtol=0.0, atol=tol) assert np.allclose(dec_cirs._degrees, dec_sofa, rtol=0.0, atol=tol)
def testDE(defile): print(defile) planets = load(defile) codes = [code for code in planets.codes if code != 0] ts = load.timescale() for code in codes: compare_obj(planets, code, 2021, 1, 30, 3, 6, 0)
def main(argv): # Defaults inputFile = 'catalogTest.txt' outputFile = 'scheduleTest.txt' start = "20200601" observerLatitude = 0.0 observerLongitude = 0.0 passes = True trajectory = True ts = api.load.timescale(builtin=True) eph = api.load('de421.bsp') groundStation = Topos(observerLatitude, observerLongitude) ts = load.timescale() times = ts.utc(2020, 6, 1, 18, range(700)) print("Times: ", times[0], len(times), times[-1]) catalog = readTLE(inputFile) passes, observations = computeSchedule(eph, catalog, groundStation, times, passes, trajectory) print("Passes: ", len(passes)) print("Observations:", len(passes))
def test_altaz_needs_topos(ts): e = api.load('de421.bsp') earth = e['earth'] moon = e['moon'] apparent = earth.at(ts.utc(2016)).observe(moon).apparent() with assert_raises(ValueError, 'from a specific Earth location'): apparent.altaz()
def test_radec_and_altaz_angles_and_rates(): # HORIZONS test data in Skyfield repository: authorities/radec-altaz-rates ts = load.timescale() t = ts.utc(2021, 2, 3) # Start with a sanity check: verify that RA and dec agree. top = wgs84.latlon(35.1844866, 248.347300, elevation_m=2106.9128) planets = load('de421.bsp') a = (planets['earth'] + top).at(t).observe(planets['mars']).apparent() frame = framelib.true_equator_and_equinox_of_date dec, ra, distance, dec_rate, ra_rate, range_rate = ( a.frame_latlon_and_rates(frame)) arcseconds = 3600.0 assert abs((ra.degrees - 40.75836) * arcseconds) < 0.04 assert abs((dec.degrees - 17.16791) * arcseconds) < 0.005 assert abs(distance.m - 1.21164331503552 * AU_M) < 120.0 # Angle rates of change. assert round(dec_rate.arcseconds.per_hour, 5) == 25.61352 assert round(ra_rate.arcseconds.per_hour * cos(dec.radians), 4) == round(75.15571, 4) # TODO: get last digit to agree? assert abs(range_rate.km_per_s - 16.7926932) < 2e-5
def test_callisto_astrometric(ts): e = api.load('jup310.bsp') a = e['earth'].at(ts.utc(2053, 10, 8, 23, 59, 59)).observe(e['callisto']) ra, dec, distance = a.radec() compare(ra._degrees, 217.1839292, 0.001 * arcsecond) compare(dec.degrees, -13.6892791, 0.001 * arcsecond) compare(distance.au, 6.31079291776184, 0.1 * meter)
def mp_planetGHA(d, ts, obj): # used in planetstab out = [None, None, None] # return [planet_sha, planet_transit] + processing time eph = load(config.ephemeris[config.ephndx][0]) # load chosen ephemeris earth = eph['earth'] if obj == 'venus': venus = eph['venus'] if obj == 'jupiter': jupiter = eph['jupiter barycenter'] if obj == 'saturn': saturn = eph['saturn barycenter'] if obj == 'mars': if config.ephndx >= 3: mars = eph['mars barycenter'] else: mars = eph['mars'] # calculate planet GHA DEC = None DEG = None if obj == 'aries': GHA = mp_ariesGHA(d, ts) elif obj == 'venus': GHA, DEC, DEG = mp_venusGHA(d, ts, earth, venus) elif obj == 'mars': GHA, DEC, DEG = mp_marsGHA(d, ts, earth, mars) elif obj == 'jupiter': GHA, DEC, DEG = mp_jupiterGHA(d, ts, earth, jupiter) elif obj == 'saturn': GHA, DEC, DEG = mp_saturnGHA(d, ts, earth, saturn) out[0] = GHA out[1] = DEC out[2] = DEG return out
def session_plan_set_moonless_astro_twilight(session_plan_id): session_plan = SessionPlan.query.filter_by(id=session_plan_id).first() _check_session_plan(session_plan) t1, t2 = _get_twighligh_component(session_plan, 1) if t1 and t2: ts = load.timescale() _, latitude, longitude, _ = _get_location_info_from_session_plan( session_plan) observer = wgs84.latlon(latitude, longitude) tz_info = _get_session_plan_tzinfo(session_plan) ldate_start = tz_info.localize(session_plan.for_date + timedelta(hours=0)) ldate_end = tz_info.localize(session_plan.for_date + timedelta(hours=48)) start_t = ts.from_datetime(ldate_start) end_t = ts.from_datetime(ldate_end) eph = load('de421.bsp') f = almanac.risings_and_settings(eph, eph['Moon'], observer) t, y = almanac.find_discrete(start_t, end_t, f) if t1 and t2: rise_sets = [] moon_rise, moon_set = None, None for i in range(len(y)): if y[i]: moon_rise = t[i].astimezone(tz_info) else: moon_set = t[i].astimezone(tz_info) rise_sets.append((moon_rise, moon_set)) moon_rise, moon_set = None, None if moon_rise or moon_set: rise_sets.append((moon_rise, moon_set)) for moon_rise, moon_set in rise_sets: if not moon_rise: moon_rise = ldate_start if not moon_set: moon_set = ldate_end if moon_set < t1 or moon_rise > t2: continue if moon_rise < t1 and moon_set > t2: t1, t2 = None, None break if moon_rise > t1: t2 = moon_rise else: t1 = moon_set if t1 and t2 and t1 > t2: t1, t2 = None, None if t1 and t2: session['planner_time_from'] = t1.strftime(SCHEDULE_TIME_FORMAT) session['planner_time_to'] = t2.strftime(SCHEDULE_TIME_FORMAT) session['is_backr'] = True return redirect( url_for('main_sessionplan.session_plan_schedule', session_plan_id=session_plan.id))
def test_sending_jd_that_is_not_a_julian_date(): earth = api.load('de421.bsp')['earth'] with assert_raises( ValueError, r"please provide the at\(\) method" " with a Time instance as its argument," " instead of the value 'blah'"): earth.at('blah')
def test_ecliptic_frame(ts): e = api.load('de421.bsp') jup = e['jupiter barycenter'] astrometric = e['sun'].at(ts.utc(1980, 1, 1, 0, 0)).observe(jup) hlat, hlon, d = astrometric.ecliptic_latlon() compare(hlat.degrees, 1.013, 0.001) compare(hlon.degrees, 151.3229, 0.001)
def test_galactic_frame(ts): e = api.load('de421.bsp') astrometric = e['earth'].at(ts.utc(1980, 1, 1, 0, 0)).observe(e['moon']) glat, glon, d = astrometric.galactic_latlon() print(glat, glat.degrees, glon, glon.degrees) compare(glat.degrees, -8.047315, 0.005) # TODO: awful! Track this down. compare(glon.degrees, 187.221794, 0.005)
def test_callisto_astrometric(): e = api.load("jup310.bsp") a = e["earth"].at(utc=(2053, 10, 9)).observe(e["callisto"]) ra, dec, distance = a.radec() compare(ra._degrees, 217.1839292, 0.001 * arcsecond) compare(dec.degrees, -13.6892791, 0.001 * arcsecond) compare(distance.au, 6.31079291776184, 0.1 * meter)
def test_hadec(): # If the DE430 ephemeris excerpt is avaiable, this test can run # locally against the HA number from first line of # `moon_topo_4_6_2017_mkb_sf_v5_hadec.csv.txt` at: # https://github.com/skyfielders/python-skyfield/issues/510 #planets = api.load('de430_1850-2150.bsp') #expected_ha = -0.660078756021 # But in CI, we use DE421 for space and speed. planets = api.load('de421.bsp') expected_ha = -0.660078752 ts = api.load.timescale() ts.polar_motion_table = [0.0], [0.009587], [0.384548] t = ts.utc(2017, 4, 6) topos = api.wgs84.latlon(-22.959748, -67.787260, elevation_m=5186.0) earth = planets['Earth'] moon = planets['Moon'] a = (earth + topos).at(t).observe(moon).apparent() ha, dec, distance = a.hadec() difference_mas = (ha.hours - expected_ha) * 15 * 3600 * 1e3 assert abs(difference_mas) < 0.03 # Drive-by test of position repr. assert repr(a) == ('<Apparent ICRS position and velocity at date t' ' center=WGS84 latitude -22.9597 N longitude -67.7873 E' ' elevation 5186.0 m target=301>')
def test_earth_deflection(): # The NOVAS library includes the Earth's gravitational deflection of # light for both topocentric observers and observers in Earth orbit, # but shuts this effect off once the object is behind the Earth 20% # of the way from its limb towards its center. This test determines # whether Skyfield puts the resulting discontinuity in the same # place as the NOVAS library does. # # For more details see: # https://github.com/skyfielders/astronomy-notebooks/blob/master/Skyfield-Notes/Fixing-earth-deflection.ipynb t = load.timescale(delta_t=0.0) t = t.tt(2016, 7, 2, arange(10.5628, 10.5639, 0.0002)) planets = load('de405.bsp') earth = planets['earth'] mars = planets['mars'] lowell = earth + Topos(latitude_degrees=35.2029, longitude_degrees=-111.6646) ra, dec, distance = lowell.at(t).observe(mars).apparent().radec() h = ra.hours hprime = diff(h) assert hprime[0] > 1.8e-8 assert hprime[1] > 1.8e-8 assert hprime[2] < 1.3e-8 # moment when nadir angle crosses 0.8 assert hprime[3] > 1.8e-8 assert hprime[4] > 1.8e-8
def test_ecliptic_frame(): e = api.load('de421.bsp') jup = e['jupiter barycenter'] astrometric = e['sun'].at(utc=(1980, 1, 1, 0, 0)).observe(jup) hlat, hlon, d = astrometric.ecliptic_latlon() compare(hlat.degrees, 1.013, 0.001) compare(hlon.degrees, 151.3229, 0.001)
def test_fk4_frame(ts): e = api.load("de421.bsp") astrometric = e["earth"].at(ts.utc(1980, 1, 1, 0, 0)).observe(e["moon"]) ra, dec, d = astrometric._to_spice_frame("B1950") print(ra._degrees, dec.degrees) compare(ra._degrees, 82.36186, 0.00006) # TODO: why is this not 0.00001? compare(dec.degrees, 18.53432, 0.00006)
def test_ecliptic_frame(ts): e = api.load("de421.bsp") jup = e["jupiter barycenter"] astrometric = e["sun"].at(ts.utc(1980, 1, 1, 0, 0)).observe(jup) hlat, hlon, d = astrometric.ecliptic_latlon() compare(hlat.degrees, 1.013, 0.001) compare(hlon.degrees, 151.3229, 0.001)
def test_callisto_geometry(ts): e = api.load("jup310.bsp") a = e["earth"].geometry_of("callisto").at(ts.tdb(jd=2471184.5)) compare(a.position.au, [-4.884815926454119e00, -3.705745549073268e00, -1.493487818022234e00], 0.001 * meter) compare( a.velocity.au_per_d, [9.604665478763035e-03, -1.552997751083403e-02, -6.678445860769302e-03], 0.000001 * meter )
def test_galactic_frame(ts): e = api.load("de421.bsp") astrometric = e["earth"].at(ts.utc(1980, 1, 1, 0, 0)).observe(e["moon"]) glat, glon, d = astrometric.galactic_latlon() print(glat, glat.degrees, glon, glon.degrees) compare(glat.degrees, -8.047315, 0.005) # TODO: awful! Track this down. compare(glon.degrees, 187.221794, 0.005)
def test_cirs_sofa(): ts = api.load.timescale() earth = api.load('de421.bsp')['earth'] test_data = [ [45.0, 46.0, 2458327], [200.0, -22.0, 2458327], [45.0, 46.0, 2459327] ] # Results output by SOFA. Calculated using the source code above. sofa_results = [ [45.074343838325, 46.067831092355], [200.013551320030, -22.096008994214], [45.077698288877, 46.082296559677] ] tol = 1e-5 / 3600.0 # 10 micro arc-seconds for ((ra_icrs, dec_icrs, tdb), (ra_sofa, dec_sofa)) in zip(test_data, sofa_results): ss = Star(ra_hours=(ra_icrs / 15.0), dec_degrees=dec_icrs) st = ts.tdb(jd=tdb) ra_cirs, dec_cirs, _ = earth.at(st).observe(ss).apparent().cirs_radec(st) assert np.allclose(ra_cirs._degrees, ra_sofa, rtol=0.0, atol=tol) assert np.allclose(dec_cirs._degrees, dec_sofa, rtol=0.0, atol=tol)
def test_galactic_frame(): e = api.load('de421.bsp') astrometric = e['earth'].at(utc=(1980, 1, 1, 0, 0)).observe(e['moon']) glat, glon, d = astrometric.galactic_latlon() print(glat, glat.degrees, glon, glon.degrees) compare(glat.degrees, -8.047315, 0.005) # TODO: awful! Track this down. compare(glon.degrees, 187.221794, 0.005)
def test_fk4_frame(): e = api.load('de421.bsp') astrometric = e['earth'].at(utc=(1980, 1, 1, 0, 0)).observe(e['moon']) ra, dec, d = astrometric.to_spice_frame('B1950') print(ra._degrees, dec.degrees) compare(ra._degrees, 82.36186, 0.00006) # TODO: why is this not 0.00001? compare(dec.degrees, 18.53432, 0.00006)
def test_fk4_frame(ts): e = api.load('de421.bsp') astrometric = e['earth'].at(ts.utc(1980, 1, 1, 0, 0)).observe(e['moon']) ra, dec, d = astrometric._to_spice_frame('B1950') print(ra._degrees, dec.degrees) compare(ra._degrees, 82.36186, 0.00006) # TODO: why is this not 0.00001? compare(dec.degrees, 18.53432, 0.00006)
def planet_info(planet_name): """View a planet info.""" planet = _find_planet(planet_name) if planet is None: abort(404) form = PlanetFindChartForm() ts = load.timescale(builtin=True) eph = load('de421.bsp') earth = eph['earth'] if not form.date_from.data or not form.date_to.data: today = datetime.today() form.date_from.data = today form.date_to.data = today + timedelta(days=7) if (form.date_from.data is None) or (form.date_to.data is None) or form.date_from.data >= form.date_to.data: t = ts.now() planet_ra_ang, planet_dec_ang, distance = earth.at(t).observe(planet.eph).radec() trajectory_b64 = None else: d1 = date(form.date_from.data.year, form.date_from.data.month, form.date_from.data.day) d2 = date(form.date_to.data.year, form.date_to.data.month, form.date_to.data.day) t = ts.now() planet_ra_ang, planet_dec_ang, distance = earth.at(t).observe(planet.eph).radec() if d1 != d2: time_delta = d2 - d1 if time_delta.days > 365: d2 = d1 + timedelta(days=365) dt = get_trajectory_time_delta(d1, d2) trajectory = [] while d1 <= d2: t = ts.utc(d1.year, d1.month, d1.day) ra, dec, distance = earth.at(t).observe(planet.eph).radec() trajectory.append((ra.radians, dec.radians, d1.strftime('%d.%m.'))) if d1 == d2: break d1 += dt # timedelta(days=1) if d1 > d2: d1 = d2 t = ts.utc(d1.year, d1.month, d1.day) trajectory_json = json.dumps(trajectory) trajectory_b64 = base64.b64encode(trajectory_json.encode('utf-8')) else: trajectory_b64 = None planet_ra = planet_ra_ang.radians planet_dec = planet_dec_ang.radians if not common_ra_dec_fsz_from_request(form): form.ra.data = planet_ra form.dec.data = planet_dec chart_control = common_prepare_chart_data(form) return render_template('main/solarsystem/planet_info.html', fchart_form=form, type='info', planet=planet, planet_ra=planet_ra, planet_dec=planet_dec, chart_control=chart_control, trajectory=trajectory_b64)
def get_asteroid(name, timestamp): # https://rhodesmill.org/skyfield/example-plots.html#drawing-a-finder-chart-for-comet-neowise # https://astroquery.readthedocs.io/en/latest/mpc/mpc.html designation = name try: asteroids = Asteroid.objects.filter(designation__icontains=name) designation = asteroids[0].designation except: pass with load.open(settings.MY_ASTEROIDS_URL) as f: minor_planets = mpc.load_mpcorb_dataframe(f) bad_orbits = minor_planets.semimajor_axis_au.isnull() minor_planets = minor_planets[~bad_orbits] # Index by designation for fast lookup. minor_planets = minor_planets.set_index('designation', drop=False) row = minor_planets.loc[designation] ts = load.timescale() eph = load('de421.bsp') sun, earth = eph['sun'], eph['earth'] asteroid = sun + mpc.mpcorb_orbit(row, ts, GM_SUN) t = ts.utc(timestamp.year, timestamp.month, timestamp.day, timestamp.hour, timestamp.minute) ra, dec, distance_from_sun = sun.at(t).observe(asteroid).radec() ra, dec, distance_from_earth = earth.at(t).observe(asteroid).radec() # https://towardsdatascience.com/space-science-with-python-a-very-bright-opposition-62e248abfe62 # how do I calculate the current phase_angle between sun and earth as seen from the asteroid ra_sun, dec_sun, d = asteroid.at(t).observe(sun).radec() ra_earth,dec_earth, d = asteroid.at(t).observe(earth).radec() phase_angle_in_degrees = abs(ra_sun.hours - ra_earth.hours) phase_angle = phase_angle_in_degrees * math.pi / 180 visual_magnitude = app_mag(abs_mag=row['magnitude_H'], \ phase_angle=phase_angle, \ slope_g=row['magnitude_G'], \ d_ast_sun=distance_from_sun.au, \ d_ast_earth=distance_from_earth.au) result = {} result['name'] = name result['designation'] = designation result['timestamp'] = str(timestamp) result['ra'] = str(ra) result['dec'] = str(dec) result['ra_decimal'] = str(ra.hours * 15) result['dec_decimal'] = str(dec.degrees) result['distance_from_earth'] = str(distance_from_earth.au) result['distance_from_sun'] = str(distance_from_sun.au) result['magnitude_h'] = row['magnitude_H'] result['magnitude_g'] = row['magnitude_G'] result['visual_magnitude'] = visual_magnitude result['last_observation_date'] = row['last_observation_date'] # result['row'] = row return result,asteroid
def get_MercRet(): # fetch data from the United States Naval Observatory and the International Earth Rotation Service planets = load('de421.bsp') # define planets earth and mercury earth, mercury = planets['earth'], planets['mercury'] # Load a timescale so that we can translate between different systems for expressing time ts = load.timescale() # Set times 1 and 2 as terrestrial time t1 = datetime.datetime.utcnow() - datetime.timedelta(minutes=5) precise_second_t1 = float(t1.strftime("%-S.%f")) # Sanity check for times #print(t1.year, t1.month, t1.day, t1.hour, t1.minute, precise_second_t1) #print(t2.year, t2.month, t2.day, t2.hour, t2.minute, precise_second_t2) # setting times 1 and 2 as terrestrial times ttime1 = ts.utc(t1.year, t1.month, t1.day, t1.hour, t1.minute, precise_second_t1) ttime2 = ts.now() # sanity check for times 1 and 2 terrestrial time for when mercury is not in retrograde #ttime1 = ts.utc(2020, 4, 1, 12, 0, 0) #ttime2 = ts.utc(2020, 4, 1, 12, 5, 0) # get atrometric measurements from earth to mercury at times 1 and 2 astrometric1 = earth.at(ttime1).observe(mercury) astrometric2 = earth.at(ttime2).observe(mercury) """ set values from astrometric arrays ra = right ascension dec = decline ditance = distance """ ra1, dec1, distance1 = astrometric1.radec() ra2, dec2, distance2 = astrometric2.radec() # Split arrays to pull only the numeric values arr1 = re.sub(r'[a-zA-Z]+', '', str(ra1)).split() arr2 = re.sub(r'[a-zA-Z]+', '', str(ra2)).split() ftr = [3600, 60, 1] # Get Angle outputs in seconds time1_seconds = sum([a * b for a, b in zip(ftr, map(float, arr1))]) time2_seconds = sum([a * b for a, b in zip(ftr, map(float, arr2))]) # get difference in RAs between times RA_diff = float(time2_seconds - time1_seconds) # interpret output of differences in RAs if RA_diff < 0.000000: MercRet = "The right ascension of Mercury is negative: Mercury is in retrograde" elif RA_diff > 0.000000: MercRet = "The right ascension of Mercury is positive: Mercury is not in retrograde" else: MercRet = "The stars are not aligned. I cannot tell if Mercury is in retrograde at the present time. Please come back later." return MercRet
def test_boston_geometry(): e = api.load("jup310.bsp") t = api.load.timescale(delta_t=67.185390 + 0.5285957).tdb(2015, 3, 2) boston = e["earth"].topos((42, 21, 24.1), (-71, 3, 24.8), x=0.003483, y=0.358609) a = boston.geometry_of("earth").at(t) compare( a.position.km, [-1.764697476371664e02, -4.717131288041386e03, -4.274926422016179e03], 0.0027 ) # TODO: try to get this < 1 meter
def test_moon_from_boston_geometry(): e = api.load("de430t.bsp") t = api.load.timescale(delta_t=67.185390 + 0.5285957).tdb(2015, 3, 2) boston = e["earth"].topos((42, 21, 24.1), (-71, 3, 24.8), x=0.003483, y=0.358609) a = boston.geometry_of("moon").at(t) compare( a.position.au, [-1.341501206552443e-03, 2.190483327459023e-03, 6.839177007993498e-04], 1.7 * meter ) # TODO: improve this
def test_fraction_illuminated(): ts = api.load.timescale() t0 = ts.utc(2018, 9, range(9, 19), 5) e = api.load('de421.bsp') i = almanac.fraction_illuminated(e, 'moon', t0[-1]).round(2) assert i == 0.62 i = almanac.fraction_illuminated(e, 'moon', t0).round(2) assert (i == (0, 0, 0.03, 0.08, 0.15, 0.24, 0.33, 0.43, 0.52, 0.62)).all()
def test_close_start_and_end(): ts = api.load.timescale() t0 = ts.utc(2018, 9, 23, 1) t1 = ts.utc(2018, 9, 23, 2) e = api.load('de421.bsp') t, y = almanac.find_discrete(t0, t1, almanac.seasons(e)) strings = t.utc_strftime('%Y-%m-%d %H:%M') assert strings == ['2018-09-23 01:54']
def test_unloaded_bpc(): pc = PlanetaryConstants() pc.read_text(load('moon_080317.tf')) try: pc.build_frame_named('MOON_PA_DE421') except LookupError as e: assert str(e) == ('you have not yet loaded a binary PCK file' ' that has a segment for frame 31006')
def test_ecliptic_for_epoch_of_date(ts): e = api.load('de421.bsp') mars = e['mars barycenter'] astrometric = e['earth'].at(ts.utc(1956, 1, 14, 6, 0, 0)).observe(mars) apparent = astrometric.apparent() hlat, hlon, d = apparent.ecliptic_latlon(epoch='date') compare(hlat.degrees, 0.4753402, 0.00001) compare(hlon.degrees, 240.0965633, 0.0002)
def distance_planets_earth(): # distance diff planets from earth ts = load.timescale() t = ts.now() planets = load('de421.bsp') v = planets['SUN'].at(t) - planets['earth'].at(t) distance = v.distance().km return jsonify({"distace":distance})
def dist_mars(self, year, month, day): data = load('de421.bsp') ts = load.timescale() t = ts.utc(year, month, day, 0, 0) #(year,month,day,hour,minute,second) mars, earth = data['Mars barycenter'], data['Earth'] mpos, epos = mars.at(t).position.km, earth.at(t).position.km return math.sqrt(((mpos - epos)**2).sum())
def __init__(self): with load.open(hipparcos.URL) as f: self.df = hipparcos.load_dataframe(f) self.planets = load('de421.bsp') self.earth = self.planets['earth'] self.ts = load.timescale() self.position = self.earth
def test_ephemeris_contains_method(ts): e = api.load('de421.bsp') assert (399 in e) is True assert (398 in e) is False assert ('earth' in e) is True assert ('Earth' in e) is True assert ('EARTH' in e) is True assert ('ceres' in e) is False
def test_close_start_and_end(): ts = api.load.timescale() t0 = ts.utc(2018, 9, 23, 1) t1 = ts.utc(2018, 9, 23, 2) e = api.load('de421.bsp') t, y = almanac.find_discrete(t0, t1, almanac.seasons(e)) t.tt += half_minute strings = t.utc_strftime('%Y-%m-%d %H:%M') assert strings == ['2018-09-23 01:54']
def test_callisto_geometry(): e = api.load('jup310.bsp') a = e['earth'].geometry_of('callisto').at(tdb=2471184.5) compare(a.position.au, [-4.884815926454119E+00, -3.705745549073268E+00, -1.493487818022234E+00], 0.001 * meter) compare(a.velocity.au_per_d, [9.604665478763035E-03, -1.552997751083403E-02, -6.678445860769302E-03], 0.000001 * meter)
def test_boston_geometry(): e = api.load('jup310.bsp') jd = api.JulianDate(tdb=(2015, 3, 2), delta_t=67.185390 + 0.5285957) boston = e['earth'].topos((42, 21, 24.1), (-71, 3, 24.8), x=0.003483, y=0.358609) a = boston.geometry_of('earth').at(jd) compare(a.position.km, [-1.764697476371664E+02, -4.717131288041386E+03, -4.274926422016179E+03], 0.0027) # TODO: try to get this < 1 meter
def test_moon_from_boston_geometry(): e = api.load('de430.bsp') jd = api.JulianDate(tdb=(2015, 3, 2), delta_t=67.185390 + 0.5285957) boston = e['earth'].topos((42, 21, 24.1), (-71, 3, 24.8), x=0.003483, y=0.358609) a = boston.geometry_of('moon').at(jd) compare(a.position.au, [-1.341501206552443E-03, 2.190483327459023E-03, 6.839177007993498E-04], 1.7 * meter) # TODO: improve this
def test_callisto_astrometric(ts): e = api.load("jup310.bsp") # This date was utc(2053, 10, 9), but new leap seconds keep breaking # the test, so: a = e["earth"].at(ts.tt(jd=2471184.5007775929)).observe(e["callisto"]) ra, dec, distance = a.radec() compare(ra._degrees, 217.1839292, 0.001 * arcsecond) compare(dec.degrees, -13.6892791, 0.001 * arcsecond) compare(distance.au, 6.31079291776184, 0.1 * meter)
def test_moon_from_boston_astrometric(): e = api.load("de430t.bsp") t = api.load.timescale(delta_t=67.185390 + 0.5285957).tdb(2015, 3, 2) boston = e["earth"].topos((42, 21, 24.1), (-71, 3, 24.8), x=0.003483, y=0.358609) a = boston.at(t).observe(e["moon"]) ra, dec, distance = a.radec() compare(ra._degrees, 121.4796470, 0.001 * arcsecond) compare(dec.degrees, 14.9108450, 0.001 * arcsecond) compare(distance.au, 0.00265828588792, 1.4 * meter) # TODO: improve this
def test_moon_from_boston_astrometric(): e = api.load('de430.bsp') jd = api.JulianDate(tdb=(2015, 3, 2), delta_t=67.185390 + 0.5285957) boston = e['earth'].topos((42, 21, 24.1), (-71, 3, 24.8), x=0.003483, y=0.358609) a = boston.at(jd).observe(e['moon']) ra, dec, distance = a.radec() compare(ra._degrees, 121.4796470, 0.001 * arcsecond) compare(dec.degrees, 14.9108450, 0.001 * arcsecond) compare(distance.au, 0.00265828588792, 1.4 * meter) # TODO: improve this
def test_chebyshev_subtraction(): planets = load('de421.bsp') v = planets['earth barycenter'] - planets['sun'] assert str(v) == """\ Sum of 2 vectors: - Segment 'de421.bsp' 0 SOLAR SYSTEM BARYCENTER -> 10 SUN + Segment 'de421.bsp' 0 SOLAR SYSTEM BARYCENTER -> 3 EARTH BARYCENTER""" assert repr(v) == "\
def test_moon_phases(): ts = api.load.timescale() t0 = ts.utc(2018, 9, 11) t1 = ts.utc(2018, 9, 30) e = api.load('de421.bsp') t, y = almanac.find_discrete(t0, t1, almanac.moon_phases(e)) t.tt += half_minute strings = t.utc_strftime('%Y-%m-%d %H:%M') assert strings == ['2018-09-16 23:15', '2018-09-25 02:52'] assert (y == (1, 2)).all()
def test_ecliptic_for_epoch_of_date_array(ts): e = api.load('de421.bsp') sun = e['sun'] astrometric = e['earth'].at(ts.utc(2005, 10, 1, [7, 8], 0, 0)).observe(sun) apparent = astrometric.apparent() hlat, hlon, d = apparent.ecliptic_latlon(epoch='date') compare(hlat.degrees[0], 0.0000488, 0.00001) compare(hlat.degrees[1], 0.0000474, 0.00001) compare(hlon.degrees[0], 188.2011122, 0.0002) compare(hlon.degrees[1], 188.2420983, 0.0002)
def test_sunrise_sunset(): ts = api.load.timescale() t0 = ts.utc(2018, 9, 12, 4) t1 = ts.utc(2018, 9, 13, 4) e = api.load('de421.bsp') bluffton = api.Topos('40.8939 N', '83.8917 W') t, y = almanac.find_discrete(t0, t1, almanac.sunrise_sunset(e, bluffton)) t.tt += half_minute strings = t.utc_strftime('%Y-%m-%d %H:%M') assert strings == ['2018-09-12 11:13', '2018-09-12 23:50'] assert (y == (1, 0)).all()
def test_seasons(): ts = api.load.timescale() t0 = ts.utc(2018, 9, 20) t1 = ts.utc(2018, 12, 31) e = api.load('de421.bsp') t, y = almanac.find_discrete(t0, t1, almanac.seasons(e)) t.tt += half_minute strings = t.utc_strftime('%Y-%m-%d %H:%M') print(strings) assert strings == ['2018-09-23 01:54', '2018-12-21 22:23'] assert (y == (2, 3)).all()
def test_from_altaz_parameters(): e = api.load('de421.bsp') usno = e['earth'].topos('38.9215 N', '77.0669 W', elevation_m=92.0) p = usno.at(tt=api.T0) a = api.Angle(degrees=10.0) with assert_raises(ValueError, 'the alt= parameter with an Angle'): p.from_altaz(alt='Bad value', alt_degrees=0, az_degrees=0) with assert_raises(ValueError, 'the az= parameter with an Angle'): p.from_altaz(az='Bad value', alt_degrees=0, az_degrees=0) p.from_altaz(alt=a, alt_degrees='bad', az_degrees=0) p.from_altaz(az=a, alt_degrees=0, az_degrees='bad')
def test_iss_altitude_computed_with_bcrs(iss_transit): dt, their_altitude = iss_transit cst = timedelta(hours=-6) #, minutes=1) dt = dt - cst t = api.load.timescale(delta_t=67.2091).utc(dt) lines = iss_tle.splitlines() s = EarthSatellite(lines, None) earth = api.load('de421.bsp')['earth'] lake_zurich = earth.topos(latitude_degrees=42.2, longitude_degrees=-88.1) # Compute using Solar System coordinates: alt, az, d = lake_zurich.at(t).observe(s).altaz() print(dt, their_altitude, alt.degrees, their_altitude - alt.degrees) assert abs(alt.degrees - their_altitude) < 2.5 # TODO: tighten this up?