Exemplo n.º 1
0
def compare_splines_to_finals2000_error_bars():
    #url = 'http://astro.ukho.gov.uk/nao/lvm/Table-S15-v18.txt'
    url = 'http://astro.ukho.gov.uk/nao/lvm/Table-S15.2020.txt'
    with load.open(url) as f:
        names, columns = parse_S15_table(f)

    i, start_year, end_year, a0, a1, a2, a3 = columns

    with load.open('ci/finals2000A.all') as f:
        utc_mjd, dut1 = iers.parse_dut1_from_finals_all(f)
    delta_t_recent, leap_dates, leap_offsets = (iers._build_timescale_arrays(
        utc_mjd, dut1))

    print('Size of IERS table:', delta_t_recent.shape)
    print('Number of splines:', i.shape)

    #year = [-720, 400, 700]
    #year = np.arange(-720, 2010)
    #year = np.arange(1800, 2010)
    #year = np.arange(1980, 2010)
    year = np.arange(1980, 2010, 0.1)
    interpolate = Splines(start_year, end_year, a3, a2, a1, a0)
    s15_curve = interpolate(year)

    finals_tt, finals_delta_t = delta_t_recent
    ts = load.timescale()
    t = ts.utc(year)
    tt = t.tt

    interpolate = Splines(
        finals_tt[:-1],
        finals_tt[1:],
        finals_delta_t[1:] - finals_delta_t[:-1],
        finals_delta_t[:-1],
    )

    T0 = time()
    finals_curve = interpolate(tt)
    print(time() - T0, 's for interpolate()')

    T0 = time()
    finals_curve2 = np.interp(tt, finals_tt, finals_delta_t)
    print(time() - T0, 's for interp()')

    assert (finals_curve == finals_curve2).all()

    diff = max(abs(s15_curve - finals_curve))
    print('Max difference (seconds, arcseconds):', diff, diff * 15)
Exemplo n.º 2
0
def main(argv):
    # parser = argparse.ArgumentParser(description=put description here)
    # parser.add_argument('integers', metavar='N', type=int, nargs='+',
    #                     help='an integer for the accumulator')
    # parser.add_argument('--sum', dest='accumulate', action='store_const',
    #                     const=sum, default=max,
    #                     help='sum the integers (default: find the max)')
    # args = parser.parse_args(argv)
    # print(args.accumulate(args.integers))

    #draw_plot_comparing_USNO_and_IERS_data()

    f = load.open('finals.all')
    mjd_utc, dut1 = iers.parse_dut1_from_finals_all(f)
    delta_t_recent, leap_dates, leap_offsets = (iers.build_timescale_arrays(
        mjd_utc, dut1))

    ts = load.timescale()
    jd = mjd_utc + 2400000.5
    t = ts.tt_jd(jd)

    fig, ax = plt.subplots()
    ax.plot(t.tt, t.delta_t)
    ax.plot(delta_t_recent[0], delta_t_recent[1])
    ax.grid()
    fig.savefig('tmp.png')
Exemplo n.º 3
0
def morrison_and_stephenson_2004_table():
    """Table of smoothed Delta T values from Morrison and Stephenson, 2004."""
    import pandas as pd
    f = load.open('http://eclipse.gsfc.nasa.gov/SEcat5/deltat.html')
    tables = pd.read_html(f.read())
    df = tables[0]
    return pd.DataFrame({'year': df[0], 'delta_t': df[1]})
Exemplo n.º 4
0
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
Exemplo n.º 5
0
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
Exemplo n.º 6
0
def morrison_and_stephenson_2004_table():
    """Table of smoothed Delta T values from Morrison and Stephenson, 2004."""
    import pandas as pd
    f = load.open('http://eclipse.gsfc.nasa.gov/SEcat5/deltat.html')
    tables = pd.read_html(f.read())
    df = tables[0]
    return pd.DataFrame({'year': df[0], 'delta_t': df[1]})
Exemplo n.º 7
0
def get_all_comets():
    global all_comets
    global all_comets_expiration
    global creation_running
    now = datetime.now()
    if all_comets is None or now > all_comets_expiration:
        all_comets_expiration = now + timedelta(days=1)
        with load.open(mpc.COMET_URL, reload=True) as f:
            # fix problem in coma in CometEls.txt
            lines = f.readlines()
            s = ''
            for line in lines:
                s += line.decode('ascii').replace(',', ' ')
            sio = BytesIO(s.encode('ascii'))
            # end of fix
            all_comets = mpc.load_comets_dataframe_slow(sio)
            all_comets = (all_comets.sort_values('reference')
                          .groupby('designation', as_index=False).last()
                          .set_index('designation', drop=False))
            all_comets['comet_id'] = np.where(all_comets['designation_packed'].isnull(), all_comets['designation'], all_comets['designation_packed'])
            all_comets['comet_id'] = all_comets['comet_id'].str.replace('/', '')
            all_comets['comet_id'] = all_comets['comet_id'].str.replace(' ', '')

        # brightness file expires after 5 days
        fname = os.path.join(current_app.config.get('USER_DATA_DIR'), 'comets_brightness.txt')

        if (not os.path.isfile(fname) or datetime.fromtimestamp(os.path.getctime(fname)) + timedelta(days=5) < all_comets_expiration) and not creation_running:
            all_comets.loc[:, 'mag'] = 22.0
            creation_running = True
            thread = threading.Thread(target=_create_comet_brighness_file, args=(all_comets, fname,))
            thread.start()
        else:
            _load_comet_brightness(all_comets, fname)
    return all_comets
Exemplo n.º 8
0
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
Exemplo n.º 9
0
    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
Exemplo n.º 10
0
def compare_old_and_new_delta_t():
    with load.open('ci/finals2000A.all') as f:
        utc_mjd, dut1 = iers.parse_dut1_from_finals_all(f)
    delta_t_recent, leap_dates, leap_offsets = (iers._build_timescale_arrays(
        utc_mjd, dut1))
    plot_delta_t_functions(
        build_legacy_delta_t(delta_t_recent),
        build_new_delta_t(delta_t_recent),
    )
Exemplo n.º 11
0
def import_mpcorb_minor_planets(mpcorb_file):
    with load.open(mpcorb_file) as f:
        all_minor_planets = mpc.load_mpcorb_dataframe(f)
        bad_orbits = all_minor_planets.semimajor_axis_au.isnull()
        all_minor_planets = all_minor_planets[~bad_orbits]
        all_minor_planets['minor_planet_id'] = all_minor_planets[
            'designation_packed']

        minor_planets = []

        for index, mpc_mp in all_minor_planets.iterrows():
            int_designation = int(mpc_mp['designation_packed'])
            minor_planet = MinorPlanet.query.filter_by(
                int_designation=int_designation).first()
            if minor_planet is None:
                minor_planet = MinorPlanet()
            minor_planet.int_designation = int_designation
            minor_planet.magnitude_H = mpc_mp['magnitude_H']
            minor_planet.magnitude_G = mpc_mp['magnitude_G']
            minor_planet.epoch = mpc_mp['epoch_packed']
            minor_planet.mean_anomaly_degrees = mpc_mp['mean_anomaly_degrees']
            minor_planet.argument_of_perihelion_degrees = mpc_mp[
                'argument_of_perihelion_degrees']
            minor_planet.longitude_of_ascending_node_degrees = mpc_mp[
                'longitude_of_ascending_node_degrees']
            minor_planet.inclination_degrees = mpc_mp['inclination_degrees']
            minor_planet.eccentricity = mpc_mp['eccentricity']
            minor_planet.mean_daily_motion_degrees = mpc_mp[
                'mean_daily_motion_degrees']
            minor_planet.semimajor_axis_au = mpc_mp['semimajor_axis_au']
            minor_planet.uncertainty = mpc_mp['uncertainty']
            minor_planet.reference = mpc_mp['reference']
            minor_planet.observations = mpc_mp['observations']
            minor_planet.oppositions = mpc_mp['oppositions']
            minor_planet.observation_period = mpc_mp['observation_period']
            minor_planet.rms_residual_arcseconds = mpc_mp[
                'rms_residual_arcseconds']
            minor_planet.coarse_perturbers = mpc_mp['coarse_perturbers']
            minor_planet.precise_perturbers = mpc_mp['precise_perturbers']
            minor_planet.computer_name = mpc_mp['computer_name']
            minor_planet.hex_flags = mpc_mp['hex_flags']
            minor_planet.designation = mpc_mp['designation']
            minor_planet.last_observation_date = mpc_mp[
                'last_observation_date']
            minor_planets.append(minor_planet)

    try:
        line_cnt = 1
        for minor_planet in minor_planets:
            progress(line_cnt, len(minor_planets), 'Importing minor planets')
            line_cnt += 1
            db.session.add(minor_planet)
        print('')
        db.session.commit()
    except IntegrityError as err:
        print('\nIntegrity error {}'.format(err))
        db.session.rollback()
Exemplo n.º 12
0
def _get_mpc_minor_planets():
    global all_minor_planets
    if all_minor_planets is None:
        with load.open('data/MPCORB.9999.DAT') as f:
            all_minor_planets = mpc.load_mpcorb_dataframe(f)
            bad_orbits = all_minor_planets.semimajor_axis_au.isnull()
            all_minor_planets = all_minor_planets[~bad_orbits]
            all_minor_planets['minor_planet_id'] = all_minor_planets[
                'designation_packed']
    return all_minor_planets
Exemplo n.º 13
0
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
Exemplo n.º 14
0
def main():
    f = load.open(mpc.COMET_URL)

    t0 = time()
    c = mpc.load_comets_dataframe(f)
    print(time() - t0, 'seconds for load_comets_dataframe()')
    assert len(c) == 864

    f.seek(0)

    t0 = time()
    c = mpc.load_comets_dataframe_slow(f)
    print(time() - t0, 'seconds for load_comets_dataframe_slow()')
    assert len(c) == 864
Exemplo n.º 15
0
def load_all_mpc_comets():
    with load.open(mpc.COMET_URL, reload=True) as f:
        all_mpc_comets = mpc.load_comets_dataframe_slow(f)
        all_mpc_comets = (all_mpc_comets.sort_values('reference').groupby(
            'designation', as_index=False).last().set_index('designation',
                                                            drop=False))
        all_mpc_comets['comet_id'] = np.where(
            all_mpc_comets['designation_packed'].isnull(),
            all_mpc_comets['designation'],
            all_mpc_comets['designation_packed'])
        all_mpc_comets['comet_id'] = all_mpc_comets['comet_id'].str.replace(
            '/', '')
        all_mpc_comets['comet_id'] = all_mpc_comets['comet_id'].str.replace(
            ' ', '')
        return all_mpc_comets
Exemplo n.º 16
0
def work_on_delta_t_discontinuities():
    with load.open('ci/finals2000A.all') as f:
        utc_mjd, dut1 = iers.parse_dut1_from_finals_all(f)
    delta_t_recent, leap_dates, leap_offsets = (iers._build_timescale_arrays(
        utc_mjd, dut1))

    ts = load.timescale()
    t = ts.J(np.arange(-3000 * 12, 4000 * 12) / 12)
    #t = ts.J(np.arange(1700 * 12, 2000 * 12) / 12)

    fig, ax = plt.subplots(1, 1)
    fig.set(size_inches=(5, 5))
    ax.plot(t.J[:-1], np.diff(ts.delta_t_function(t.tt)))
    ax.grid()
    ax.set(xlabel='Year', ylabel='∆T month-to-month change')
    fig.tight_layout()
    fig.savefig('tmp.png')
Exemplo n.º 17
0
def main(argv):
    parser = argparse.ArgumentParser(description='Grep MPCORB.DAT.gz')
    parser.add_argument('designations',
                        nargs='+',
                        help='packed designations'
                        ' of the minor planets whose orbits you need')
    args = parser.parse_args(argv)

    designations = [re.escape(d.encode('ascii')) for d in args.designations]
    pattern = rb'^((?:%s) .*\n)' % rb'|'.join(designations)
    r = re.compile(pattern, re.M)

    data = load.open(mpc.MPCORB_URL).read()
    data = zlib.decompress(data, wbits=zlib.MAX_WBITS | 16)
    lines = r.findall(data)

    sys.stdout.buffer.write(b''.join(lines))
Exemplo n.º 18
0
def load_stars(max_magnitude, verbose=False):
    """Load the Hipparcos catalog data and find all applicable stars.  Returns a
    list of StarObs, one per star.
    """
    if verbose:
        print("[  CATALOG] Loading star catalog data.")
    with load.open(hipparcos.URL) as f:
        df = hipparcos.load_dataframe(f)

        df = df[df['magnitude'] <= max_magnitude]
        df = df[df['ra_degrees'].notnull()]

        if verbose:
            print(
                f'[  CATALOG] Found {len(df)} stars brighter than magnitude {max_magnitude:.4f}.'
            )
        return [
            StarObs(str(idx), Star.from_dataframe(df.loc[idx]),
                    df.loc[idx].magnitude) for idx in df.index
        ]
Exemplo n.º 19
0
def get_comet(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

    # name = "C/2020 F3 (NEOWISE)"
    # https://www.minorplanetcenter.net/iau/info/CometOrbitFormat.html
    with load.open(mpc.COMET_URL) as f:
        comets = mpc.load_comets_dataframe(f)

    comets = (comets.sort_values('reference')
              .groupby('designation', as_index=False).last()
              .set_index('designation', drop=False))

    row = comets.loc[name]
    print(row)
    ts = load.timescale()
    eph = load('de421.bsp')
    sun, earth = eph['sun'], eph['earth']

    comet = sun + mpc.comet_orbit(row, ts, GM_SUN)

    t = ts.utc(timestamp.year, timestamp.month, timestamp.day, timestamp.hour, timestamp.minute)
    ra, dec, distance = earth.at(t).observe(comet).radec()

    result = {}
    result['name'] = name
    result['designation'] = row['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'] = str(distance)
    result['magnitude_g'] = row['magnitude_g']
    result['magnitude_k'] = row['magnitude_k']
    result['visual_magnitude'] = row['magnitude_k']
    result['row'] = row
    return result,comet
Exemplo n.º 20
0
def init_sf():
    global ts, eph, earth, moon, sun, venus, mars, jupiter, saturn, df
    EOPdf = "finals2000A.all"  # Earth Orientation Parameters data file
    dfIERS = EOPdf

    if config.useIERS:
        if compareVersion(VERSION, "1.31") >= 0:
            if path.isfile(dfIERS):
                if load.days_old(EOPdf) > float(config.ageIERS):
                    load.download(EOPdf)
                ts = load.timescale(builtin=False)  # timescale object
            else:
                load.download(EOPdf)
                ts = load.timescale(builtin=False)  # timescale object
        else:
            ts = load.timescale()  # timescale object with built-in UT1-tables
    else:
        ts = load.timescale()  # timescale object with built-in UT1-tables

    if config.ephndx in set([0, 1, 2]):

        eph = load(config.ephemeris[config.ephndx][0])  # load chosen ephemeris
        earth = eph['earth']
        moon = eph['moon']
        sun = eph['sun']
        venus = eph['venus']
        mars = eph['mars']
        jupiter = eph['jupiter barycenter']
        saturn = eph['saturn barycenter']

    # load the Hipparcos catalog as a 118,218 row Pandas dataframe.
    with load.open(hipparcos.URL) as f:
        #hipparcos_epoch = ts.tt(1991.25)
        df = hipparcos.load_dataframe(f)

    return ts
Exemplo n.º 21
0
ts = load.timescale()
ephem = load('de421.bsp')
cet = timezone('CET')

sun, moon, earth = ephem['sun'], ephem['moon'], ephem['earth']

amsterdam = Topos('52.3679 N', '4.8984 E')
amstercentric = earth + amsterdam

t0 = ts.now()
t1 = ts.tt_jd(t0.tt + 1)
nu = t0.utc_datetime().astimezone(cet).time().strftime('%H:%M')

mindist=1.5
from skyfield.constants import GM_SUN_Pitjeva_2005_km3_s2 as GM_SUN
with load.open(mpc.COMET_URL,reload=True) as f:
    comets = mpc.load_comets_dataframe(f)
print('Found ',len(comets), ' comets')
comets = (comets.sort_values('reference')
          .groupby('designation', as_index=False).last()
          .set_index('designation', drop=False))
f = open('cometlist.txt', 'w')
for (c, cometdata) in comets.iterrows():
    comet = sun + mpc.comet_orbit(cometdata, ts, GM_SUN)
    ra, dec, distance = sun.at(t0).observe(comet).radec()
    print(c,' is at ',distance.au,'au')
    if (distance.au < mindist):
       f.write(c+"\n")
f.close()
Exemplo n.º 22
0
from skyfield.data import hipparcos
from skyfield.api import load
from inspect import getmembers
import pdb

planets = load("de421.bsp")
with load.open("hip_main.dat") as f:
    stars = hipparcos.load_dataframe(f)
for planet in planets:
    print(planet)
pdb.set_trace()
data = {planets: planets, stars: stars}
print(data)
Exemplo n.º 23
0
# need to be drawn once, so we take the middle comet date as the single
# time `t` we use for everything else.

ts = load.timescale()
t_comet = ts.utc(2020, 7, range(17, 27))
t = t_comet[len(t_comet) // 2]  # middle date

# An ephemeris from the JPL provides Sun and Earth positions.

eph = load('de421.bsp')
sun = eph['sun']
earth = eph['earth']

# The Minor Planet Center data file provides the comet orbit.

with load.open(mpc.COMET_URL) as f:
    comets = mpc.load_comets_dataframe(f)

comets = comets.set_index('designation', drop=False)
row = comets.loc['C/2020 F3 (NEOWISE)']
comet = sun + mpc.comet_orbit(row, ts, GM_SUN)

# The Hipparcos mission provides our star catalog.

with load.open(hipparcos.URL) as f:
    stars = hipparcos.load_dataframe(f)

# And the constellation outlines come from Stellarium.  We make a list
# of the stars at which each edge stars, and the star at which each edge
# ends.
# Altitude and azimuth in the sky of a
# specific geographic location

boston = earth + Topos('42.3583 N', '71.0603 W')
astro = boston.at(ts.utc(1980, 3, 1)).observe(mars)
app = astro.apparent()

alt, az, distance = app.altaz()
print(alt.dstr())
print(az.dstr())
print(distance)

# Measure a star

with load.open(hipparcos.URL) as f:
    df = hipparcos.load_dataframe(f)

barnards_star = Star.from_dataframe(df.loc[87937])

planets = load('de421.bsp')
earth = planets['earth']

ts = load.timescale()
t = ts.now()
astrometric = boston.at(t).observe(barnards_star)
app_b = astrometric.apparent()

alt_b, az_b, distance_b = app_b.altaz()
print("Bernard star")
print(alt_b.dstr())
Exemplo n.º 25
0
def usno_historic_delta_t():
    import pandas as pd
    f = load.open(_CDDIS + 'historic_deltat.data')
    df = pd.read_table(f, sep=b' +', engine='python', skiprows=[1])
    return pd.DataFrame({'year': df[b'Year'], 'delta_t': df[b'TDT-UT1']})
Exemplo n.º 26
0
def usno_historic_delta_t():
    import pandas as pd
    f = load.open('http://maia.usno.navy.mil/ser7/historic_deltat.data')
    df = pd.read_table(f, sep=rb' +', engine='python', skiprows=[1])
    return pd.DataFrame({'year': df[b'Year'], 'delta_t': df[b'TDT-UT1']})
def galactic_Sun_north_center_SD_directions(
        measurement_date,
        recv_time,
        user_longlatdist=geographic_position,
        prints=False):
    user_longlatdist = np.array(user_longlatdist)
    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_auto(measurement_date, 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()
    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()
    berenice_position = pm.aer2ecef(az_b.degrees, alt_b.degrees, distance_b.m,
                                    user_longlatdist[0], user_longlatdist[1],
                                    user_longlatdist[2])

    # Galaktikus Center (RA: 12h 51.42m; D: 27° 07.8′, epocha J2000.0) 17h 45.6m  −28.94°
    galactic_center = Star(ra_hours=(17, 45, 36.0),
                           dec_degrees=(-28, 56, 24.0))
    astrometric_center = user_position.at(t).observe(galactic_center)
    alt_c, az_c, distance_c = astrometric_center.apparent().altaz()
    center_position = pm.aer2ecef(az_c.degrees, alt_c.degrees, distance_c.m,
                                  user_longlatdist[0], user_longlatdist[1],
                                  user_longlatdist[2])

    nunki = Star.from_dataframe(df.loc[92855])
    astrometric_nunki = user_position.at(t).observe(nunki)
    alt_n, az_n, distance_n = astrometric_nunki.apparent().altaz(
    )  #astrometric.apparent().altaz() = astrometric_denebola.apparent().altaz()
    star_pos_n = pm.aer2ecef(az_n.degrees, alt_n.degrees, distance_n.m,
                             user_longlatdist[0], user_longlatdist[1],
                             user_longlatdist[2])

    capella = Star.from_dataframe(df.loc[24608])
    astrometric_capella = user_position.at(t).observe(capella)
    alt_ca, az_ca, distance_ca = astrometric_capella.apparent().altaz(
    )  #astrometric.apparent().altaz() = astrometric_denebola.apparent().altaz()
    star_pos_ca = pm.aer2ecef(az_ca.degrees, alt_ca.degrees, distance_ca.m,
                              user_longlatdist[0], user_longlatdist[1],
                              user_longlatdist[2])

    denebola = Star.from_dataframe(df.loc[57632])
    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()
    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[109074])
    astrometric_sadalmelik = user_position.at(t).observe(sadalmelik)
    alt_s, az_s, distance_s = astrometric_sadalmelik.apparent().altaz()
    star_pos_s = pm.aer2ecef(az_s.degrees, alt_s.degrees, distance_s.m,
                             user_longlatdist[0], user_longlatdist[1],
                             user_longlatdist[2])
    if prints:
        print('Time:  ', terrestrial_time)
        print('Location: ', '{} N'.format(user_longlatdist[0]),
              '{} E'.format(user_longlatdist[1]))
        print('Sun (alt/az):   ', alt_sun, az_sun)
        print('Coma Berenice (alt/az):   ', alt_b, az_b)
        print('Galactic Center (alt/az):   ', alt_c, az_c)
        print('Nunki (alt/az):   ', alt_n, az_n)
        print('Capella (alt/az):   ', alt_ca, az_ca)
        print('Denebola (alt/az):   ', alt_d, az_d)
        print('Sadalmelik (alt/az):   ', alt_s, az_s)

    stars_pos = [
        sun_position, berenice_position, center_position, star_pos_n,
        star_pos_ca, star_pos_d, star_pos_s
    ]
    return stars_pos
Exemplo n.º 28
0
"""Check Skyfield lunar eclipses against the huge NASA table of eclipses."""

from collections import Counter
from skyfield import eclipselib
from skyfield.api import load, GREGORIAN_START
import datetime as dt

with load.open('https://eclipse.gsfc.nasa.gov/5MCLE/5MKLEcatalog.txt') as f:
    data = f.read()

ts = load.timescale()
ts.julian_calendar_cutoff = GREGORIAN_START

table = []
lines = data.decode('ascii').splitlines()

for line in lines[14:]:
    year = int(line[7:12])
    if year < 1 or year >= 3000:
        #if year < 1900 or year > 1920:
        continue
    datestr = line[8:29]
    d = dt.datetime.strptime(datestr, '%Y %b %d  %H:%M:%S')
    t = ts.tt(d.year, d.month, d.day, d.hour, d.minute, d.second)
    table.append((t, line[51]))

time0 = table[0][0]
timeN = table[-1][0]

start_time = ts.tt_jd(time0.whole - 1, time0.tt_fraction)
end_time = ts.tt_jd(timeN.whole + 1, timeN.tt_fraction)
Exemplo n.º 29
0
def index(request):
    stars = []

    if request.body:
        req = json.loads(request.body)

        if req['type'] == 'GET_VISIBLE_STARS':
            planets = load('de421.bsp')
            earth = planets['earth']
            ts = load.timescale()
            dt = datetime.strptime(req['date'], '%Y-%m-%dT%H:%M:%S.%fZ')
            dt = dt.replace(tzinfo=timezone.utc)
            t = ts.utc(dt)
            observerLocation = earth + \
                Topos(latitude_degrees=req['lat'],
                        longitude_degrees=req['long'])

            with load.open(hipparcos.URL) as f:
                df = hipparcos.load_dataframe(f)
            
            for key in navigationStarsHip:
                starname = key
                hipNo = navigationStarsHip[key]
                star = Star.from_dataframe(df.loc[hipNo])

                apparent = observerLocation.at(t).observe(star).apparent()
                alt, az, dist = apparent.altaz()
                eachStar = {
                    'name': key,
                    'hip': navigationStarsHip[key],
                    'alt': alt.degrees,
                    'az': az.degrees,
                    'dist': dist.km
                }
                if eachStar['alt'] > 0 :
                    stars.append(eachStar)


        if req['type'] == 'GET_TBRG_STAR':
            planets = load('de421.bsp')
            earth = planets['earth']
            ts = load.timescale()
            dt = datetime.strptime(req['date'], '%Y-%m-%dT%H:%M:%S.%fZ')
            dt = dt.replace(tzinfo=timezone.utc)
            t = ts.utc(dt)
            observerLocation = earth + \
                Topos(latitude_degrees=req['lat'],
                        longitude_degrees=req['long'])

            with load.open(hipparcos.URL) as f:
                df = hipparcos.load_dataframe(f)

                starname = req['selectedStar']
                hipNo = navigationStarsHip[starname]
                star = Star.from_dataframe(df.loc[hipNo])
                apparent = observerLocation.at(t).observe(star).apparent()
                alt, az, dist = apparent.altaz()

                return JsonResponse({
                    'name': starname,
                    'hipNo': navigationStarsHip[starname],
                    'alt': alt.degrees,
                    'az': az.degrees,
                    'dist': dist.km
                })


        if (req['type'] == 'GET_TBRG_PLANET'):
            planets = load('de421.bsp')
            earth = planets['earth']
            ts = load.timescale()
            dt = datetime.strptime(req['date'], '%Y-%m-%dT%H:%M:%S.%fZ')
            dt = dt.replace(tzinfo=timezone.utc)
            t = ts.utc(dt)
            observerLocation = earth + \
                Topos(latitude_degrees=req['lat'],
                        longitude_degrees=req['long'])

            planet = planets[req['body']]
            apparent = observerLocation.at(t).observe(planet).apparent()
            alt, az, dist = apparent.altaz()
            return JsonResponse({
                "alt": alt.degrees,
                "az": az.degrees,
                "dist": dist.km
            })
Exemplo n.º 30
0
def usno_historic_delta_t():
    import pandas as pd
    f = load.open('http://maia.usno.navy.mil/ser7/historic_deltat.data')
    df = pd.read_table(f, sep=rb' +', engine='python', skiprows=[1])
    return pd.DataFrame({'year': df[b'Year'], 'delta_t': df[b'TDT-UT1']})
Exemplo n.º 31
0
def draw_plot_comparing_USNO_and_IERS_data():
    f = load.open('finals.all')
    year, month, day, dut1 = iers.parse_dut1_from_finals_all(f)

    # auto-detect leap seconds
    leap_seconds = np.diff(dut1) > 0.9
    #x = np.append(leap_seconds > 0.9, False)
    #x = np.prepend(leap_seconds > 0.9, False)
    #x = np.concatenate([leap_seconds > 0.9, [False]]).astype(bool)
    x = np.concatenate([
        [False],
        leap_seconds,
    ])
    print(x)
    print(x, sum(x))
    print(year[x])
    print(month[x])
    print(day[x])

    delta_t = dut1 - np.cumsum(x)

    ts = load.timescale()
    t = ts.utc(year, month, day)
    y_new = dut1
    y_old = t.dut1

    # and: figure out error cost of interpolating weeks or months
    all_points = np.arange(len(delta_t))
    samples = all_points[::600] + 0.001
    print(f'{len(samples)} samples')

    for skip in range(1, 40):
        index = np.arange(0, len(delta_t), skip)
        excerpt = delta_t[index]
        interpolated = np.interp(all_points, index, excerpt)
        difference_seconds = abs(interpolated - delta_t).max()
        difference_arcseconds = difference_seconds / 24.0 * 360.0
        storage = 4 * len(excerpt)

        t0 = time()
        np.interp(samples, index, excerpt)
        duration = time() - t0

        fmt = '{:2} days  {:10.6f} s   {:10.6f} arcseconds  {} bytes  {:.6f} s'
        print(
            fmt.format(
                skip,
                difference_seconds,
                difference_arcseconds,
                storage,
                duration,
            ))
    #print(dut1)

    fig, ax = plt.subplots()
    ax.set(xlabel='Year', title='UT1 minus UTC')
    # ax.plot(t.J, y_old, '-', label='deltat.dat')
    # ax.plot(t.J, y_new, ',', label='finals.all')
    ax.plot(delta_t)
    ax.plot(np.diff(delta_t))
    ax.grid()
    plt.legend()
    fig.savefig('tmp.png')

    print(len(y_new))
    np.savez_compressed(
        'test.npz',
        time=t.J,
        ut1_minus_utc=y_new,
    )
Exemplo n.º 32
0
def create_starmap(name, timestamp, days_past, days_future, fov, magnitude):

    # The comet is plotted on several dates `t_transient`.  But the stars only
    # need to be drawn once, so we take the middle comet date as the single
    # time `t` we use for everything else.

    try:
        # first try comets
        d, transient = algorithms.get_comet(name, timestamp)
    except:
        # then try asteroids
        d, transient = algorithms.get_asteroid(name, timestamp)

    ts = load.timescale()
    t_timestamp = ts.utc(timestamp.year, timestamp.month, timestamp.day,
                         timestamp.hour, timestamp.minute)

    t_transient = ts.utc(
        timestamp.year, timestamp.month,
        range(timestamp.day - days_past, timestamp.day + days_future))
    t = t_transient[len(t_transient) // 2]  # middle date

    # An ephemeris from the JPL provides Sun and Earth positions.

    eph = load('de421.bsp')
    earth = eph['earth']

    # The Hipparcos mission provides our star catalog.

    # with load.open(hipparcos.URL) as f:
    with load.open(settings.MY_HIPPARCOS_URL) as f:
        stars = hipparcos.load_dataframe(f)

    # And the constellation outlines come from Stellarium.  We make a list
    # of the stars at which each edge stars, and the star at which each edge
    # ends.

    url = ('https://raw.githubusercontent.com/Stellarium/stellarium/master'
           '/skycultures/western_SnT/constellationship.fab')

    with load.open(url) as f:
        constellations = stellarium.parse_constellations(f)

    edges = [edge for name, edges in constellations for edge in edges]
    edges_star1 = [star1 for star1, star2 in edges]
    edges_star2 = [star2 for star1, star2 in edges]

    # We will center the chart on the comet's middle position.

    center = earth.at(t).observe(transient)
    #star = Star(ra_hours=(17, 57, 48.49803), dec_degrees=(4, 41, 36.2072))
    #center = earth.at(t).observe(star)

    projection = build_stereographic_projection(center)
    field_of_view_degrees = float(fov)
    limiting_magnitude = magnitude

    # Now that we have constructed our projection, compute the x and y
    # coordinates that each star and the comet will have on the plot.

    star_positions = earth.at(t).observe(Star.from_dataframe(stars))
    stars['x'], stars['y'] = projection(star_positions)

    transient_x, transient_y = projection(
        earth.at(t_transient).observe(transient))

    # Create a True/False mask marking the stars bright enough to be
    # included in our plot.  And go ahead and compute how large their
    # markers will be on the plot.

    bright_stars = (stars.magnitude <= limiting_magnitude)
    magnitude = stars['magnitude'][bright_stars]
    marker_size = (0.5 + limiting_magnitude - magnitude)**2.0

    # The constellation lines will each begin at the x,y of one star and end
    # at the x,y of another.  We have to "rollaxis" the resulting coordinate
    # array into the shape that matplotlib expects.

    xy1 = stars[['x', 'y']].loc[edges_star1].values
    xy2 = stars[['x', 'y']].loc[edges_star2].values
    lines_xy = np.rollaxis(np.array([xy1, xy2]), 1)

    # Time to build the figure!

    fig, ax = plt.subplots(figsize=[12, 12])

    # Draw the constellation lines.

    ax.add_collection(LineCollection(lines_xy, colors='#00f2'))

    # Draw the stars.

    ax.scatter(stars['x'][bright_stars],
               stars['y'][bright_stars],
               s=marker_size,
               color='k')

    # Draw the comet positions, and label them with dates.

    transient_color = '#f00'
    offset = 0.0005

    ax.plot(transient_x, transient_y, '+', c=transient_color, zorder=3)

    for xi, yi, tstr in zip(transient_x, transient_y,
                            t_transient.utc_strftime('%m/%d')):
        tstr = tstr.lstrip('0')
        text = ax.text(xi + offset,
                       yi - offset,
                       tstr,
                       color=transient_color,
                       ha='left',
                       va='top',
                       fontsize=9,
                       weight='bold',
                       zorder=-1)
        text.set_alpha(0.5)

    # Finally, title the plot and set some final parameters.

    angle = np.pi - field_of_view_degrees / 360.0 * np.pi
    limit = np.sin(angle) / (1.0 - np.cos(angle))

    ax.set_xlim(-limit, limit)
    ax.set_ylim(-limit, limit)
    ax.xaxis.set_visible(False)
    ax.yaxis.set_visible(False)
    ax.set_aspect(1.0)
    ax.set_title('{} {} through {}'.format(
        d['designation'],
        t_transient[0].utc_strftime('%d %B %Y'),
        t_transient[-1].utc_strftime('%d %B %Y'),
    ))

    # Save.
    filename = 'starmap.png'
    path = os.path.join(settings.MEDIA_ROOT, filename)

    fig.savefig(path, bbox_inches='tight')

    image_url = os.path.join(settings.MEDIA_URL, filename)
    return image_url