コード例 #1
0
ファイル: tle_parser.py プロジェクト: zhufengGNSS/pyRTKLib
def rise_set_yydoy(df_tle: pd.DataFrame, yydoy: str, dir_tle: str, logger: logging.Logger) -> pd.DataFrame:
    """
    rise_set_yydoy calculates the rise/set times for GNSS PRNs
    """
    cFuncName = colored(os.path.basename(__file__), 'yellow') + ' - ' + colored(sys._getframe().f_code.co_name, 'green')

    # get the datetime that corresponds to yydoy
    date_yydoy = datetime.strptime(yydoy, '%y%j')
    logger.info('{func:s}: calculating rise / set times for {date:s} ({yy:s}/{doy:s})'.format(date=colored(date_yydoy.strftime('%d-%m-%Y'), 'green'), yy=yydoy[:2], doy=yydoy[2:], func=cFuncName))

    # load a time scale and set RMA as Topo
    # loader = sf.Loader(dir_tle, expire=True)  # loads the needed data files into the tle dir
    ts = sf.load.timescale()
    RMA = sf.Topos('50.8438 N', '4.3928 E')
    logger.info('{func:s}: Earth station RMA = {topo!s}'.format(topo=colored(RMA, 'green'), func=cFuncName))

    t0 = ts.utc(int(date_yydoy.strftime('%Y')), int(date_yydoy.strftime('%m')), int(date_yydoy.strftime('%d')))
    date_tomorrow = date_yydoy + timedelta(days=1)
    t1 = ts.utc(int(date_tomorrow.strftime('%Y')), int(date_tomorrow.strftime('%m')), int(date_tomorrow.strftime('%d')))

    # go over the PRN / NORADs that have TLE corresponding to the requested date
    for row, prn in enumerate(df_tle['PRN']):
        logger.info('{func:s}:   for NORAD {norad:s} ({prn:s})'.format(norad=colored(df_tle['NORAD'][row], 'green'), prn=colored(prn, 'green'), func=cFuncName))
        # create a EarthSatellites from the TLE lines for this PRN
        gnss_sv = EarthSatellite(df_tle['TLE1'][row], df_tle['TLE2'][row])
        logger.info('{func:s}:       created earth satellites {sat!s}'.format(sat=colored(gnss_sv, 'green'), func=cFuncName))

        t, events = gnss_sv.find_events(RMA, t0, t1, altitude_degrees=5.0)

        for ti, event in zip(t, events):
            name = ('rise above 5d', 'culminate', 'set below 5d')[event]
            logger.info('{func:s}:         {jpl!s} -- {name!s}'.format(jpl=ti.utc_jpl(), name=name, func=cFuncName))
コード例 #2
0
def get_sun_data(lat, lon, flight_date):
    sky_fmt = "%Y-%m-%dT%H:%M:%SZ"

    ts = api.load.timescale()
    e = api.load('de421.bsp')

    sunrise = None
    sunset = None

    bluffton = api.Topos(lat, lon)
    # first get sunrise and sunset times
    t, y = almanac.find_discrete(
        ts.utc(flight_date.date()),
        ts.utc(flight_date.date() + datetime.timedelta(days=1)),
        almanac.sunrise_sunset(e, bluffton))
    for ti, yi in zip(t, y):
        if yi:
            sunrise = ti.utc_iso()
        else:
            sunset = ti.utc_iso()

    return (datetime.datetime.strptime(
        sunrise, sky_fmt).replace(tzinfo=datetime.timezone.utc) -
            datetime.timedelta(minutes=30),
            datetime.datetime.strptime(
                sunset, sky_fmt).replace(tzinfo=datetime.timezone.utc) +
            datetime.timedelta(minutes=30))
コード例 #3
0
def get_sunrise_sunset(latitude, longitude, date, timezone):
    """
    :type timezone: datetime.tzinfo
    :type date: datetime.date
    :type latitude: float
    :type longitude: float
    :return Tuple of datetime (sunrise, sunset), or None instead of a datetime
            if it doesn't occur that day.
    """
    # TODO: 4 AM is used in the documentation, but does it work everywhere?
    #       https://rhodesmill.org/skyfield/almanac.html#sunrise-and-sunset
    t0 = ts.utc(date.year, date.month, date.day, 4)
    t1 = ts.utc(date.year, date.month, date.day + 1, 4)

    location = api.Topos(latitude_degrees=latitude, longitude=longitude)

    # The result t will be an array of times, and y will be True if the sun
    # rises at the corresponding time and False if it sets.
    times, are_sunrise = almanac.find_discrete(
        t0, t1, almanac.sunrise_sunset(e, location))

    sunrise = None
    sunset = None
    for time, is_sunrise in zip(times, are_sunrise):
        if is_sunrise:
            # Not expecting multiple sunrises per day.
            assert sunrise is None
            sunrise = time.astimezone(timezone)
        else:
            # Not expecting multiple sunsets per day.
            assert sunset is None
            sunset = time.astimezone(timezone)

    return sunrise, sunset
コード例 #4
0
ファイル: runserver.py プロジェクト: GEOFBOT/FlaskAzure
def get_data(time, lat, long):  # , azi, alt, radius):
    """Returns star data near a certain position"""
    # As of yet, does literally none of that.
    try:
        lat = float(lat)
        long = float(long)
    except ValueError:
        print('wow')
        abort(404)

    location = earth + skyapi.Topos(lat, long)
    dt = datetime.fromtimestamp(time)
    dt = dt.replace(tzinfo=skyapi.utc)
    t = ts.utc(dt)

    return jsonify({
        'type':
        'FeatureCollection',
        'features': [{
            'geometry': {
                'type': 'Point',
                'coordinates': [star_az, star_alt],
            },
            'type': 'Feature',
            'properties': {
                'mag': 1.337
            }
        } for star_az, star_alt in star_data(STARS, location, t)]
    })
コード例 #5
0
 def setup(self):
     super().setup()
     # setup the skyfield objects
     planets = skyfield_api.load('de421.bsp')
     earth = planets['earth']
     self._skyfield_sun = planets['sun']
     self._skyfield_position = earth + skyfield_api.Topos(**self.position)
コード例 #6
0
    def __init__(self, name, tle, location):
        self.name = name.strip()
        self.tle = tle
        self.timezone = timezone("Etc/UTC")
        current_time = datetime.datetime.utcnow()
        lat = location.split(",")[0].strip()
        lon = location.split(",")[1].strip()

        self.sats = api.load.tle('temp_tle.txt')
        self.sat = self.sats[self.name]

        minutes = range(60 * 24 * 2)
        ts = api.load.timescale()
        self.t = ts.utc(current_time.year, current_time.month,
                        current_time.day, current_time.hour, minutes)
        place = api.Topos(latitude=lat, longitude=lon)
        orbit = (self.sat - place).at(self.t)
        self.alt, self.az, distance = orbit.altaz()

        above_horizon = self.alt.degrees > 0

        boundaries, = np.diff(above_horizon).nonzero()
        self.passes = boundaries.reshape(len(boundaries) // 2, 2)

        self.pass_times = []
        for p in range(len(self.passes)):
            i, j = self.passes[p]
            azimuth = self.az.degrees
            altitude = self.alt.degrees
            azimuth = int(max(azimuth[i:j]))
            altitude = int(max(altitude[i:j]))
            rise = str(self.t[i].astimezone(self.timezone))[:-6]
            sets = str(self.t[j].astimezone(
                self.timezone))[:-6] + "-> " + str(altitude) + "°"
            self.pass_times.append(rise + " - " + sets)
コード例 #7
0
ファイル: solactus_alpha.py プロジェクト: ahuang11/solactus
def _compute_loc_sunset(input_str):
    geolocator = Nominatim(user_agent='sunset_app', timeout=3)
    geoloc = geolocator.geocode(input_str)
    lat, lon = geoloc.latitude, geoloc.longitude

    loc = api.Topos('{0} N'.format(lat), '{0} E'.format(lon))

    t0 = ts.utc(2020, 7, 1)
    t1 = ts.utc(2021, 7, 1)
    t, y = almanac.find_discrete(t0, t1, almanac.sunrise_sunset(e, loc))

    df = pd.DataFrame({'datetime': t.utc_iso(), 'sun_down': y})
    df['datetime'] = pd.to_datetime(df['datetime'])
    tz = GeoNames(username='******').reverse_timezone(
        (geoloc.latitude, geoloc.longitude))
    try:
        df['datetime'] = df['datetime'].dt.tz_localize('utc').dt.tz_convert(
            tz.pytz_timezone)
    except TypeError:
        df['datetime'] = df['datetime'].dt.tz_convert(tz.pytz_timezone)
    df['date'] = df['datetime'].dt.date
    df['time'] = df['datetime'].dt.time
    df['hour'] = (df['time'].astype(str).str.split(
        ':', expand=True).astype(int).apply(
            lambda row: row[0] + row[1] / 60. + row[2] / 3600., axis=1))
    df['hour_24'] = 240
    df['daylight'] = np.abs(df['hour'].diff().shift(-1))
    return df, geoloc
コード例 #8
0
 def testSunrise(self):
     timisoaraLoc = api.Topos('45.4758 N', '21.1738 E')
     t0 = ts.utc(2018, 9, 12, 4)
     t1 = ts.utc(2018, 9, 13, 4)
     t, y = almanac.find_discrete(t0, t1, almanac.sunrise_sunset(eph, timisoaraLoc))
     print("****************")
     print(t.utc_iso())
     print(y)
コード例 #9
0
def test_boston_geometry():
    k = Kernel(download(de430_url))
    jd = api.JulianDate(tdb=(2015, 3, 2), delta_t=67.185390 + 0.5285957)
    boston = api.Topos((42, 21, 24.1), (-71, 3, 24.8), x=0.003483, y=0.358609)
    a = boston.geometry_of(k.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
コード例 #10
0
def compute(target,
            kernel=de421,
            name=None,
            topo=None,
            t=None,
            planet=None,
            precision_radec=3,
            precision_azalt=5,
            klass=None,
            json=None):
    ts = sf.load.timescale()
    if isinstance(target, str):
        name = target
        target = kernel[target]

    if topo is None:
        topo = ['33.7490 N', '84.3880 W']  # Atlanta.
    topo = sf.Topos(*topo)

    if t is None:
        t = [2019, 9, 6, 17, 0, 0]
    t = ts.utc(*t)
    if name is None:
        name = target.target_name

    if planet is None and isinstance(target.target, int):
        planet = target.target

    earth = de421['earth']
    obs = (earth + topo).at(t)
    pos = obs.observe(target)  # Astrometric position
    apparent = obs.observe(target).apparent()  # Apparent position
    geo = earth.at(t).observe(target)
    radec = apparent.radec(epoch='date')
    altaz = pos.apparent().altaz()
    # skyfield use JD, ephemeride uses Modified JD.
    ut1 = t.ut1 - 2400000.5
    utc = ut1 - t.dut1 / (60 * 60 * 24)
    ret = dict(
        name=name,
        planet=planet,
        ut1=ut1,
        utc=utc,
        longitude=topo.longitude.degrees,
        latitude=topo.latitude.degrees,
        pos=list(apparent.position.au),
        ra=radec[0]._degrees,
        dec=radec[1].degrees,
        alt=altaz[0].degrees,
        az=altaz[1].degrees,
        geo=list(geo.position.au),
        precision_radec=precision_radec,
        precision_azalt=precision_azalt,
    )
    if json is not None:
        ret['klass'] = klass
        ret['json'] = json
    return ret
コード例 #11
0
def test_moon_from_boston_geometry():
    k = Kernel(download(de430_url))
    jd = api.JulianDate(tdb=(2015, 3, 2), delta_t=67.185390 + 0.5285957)
    boston = api.Topos((42, 21, 24.1), (-71, 3, 24.8), x=0.003483, y=0.358609)
    a = boston.geometry_of(k.moon).at(jd)
    compare(
        a.position.au,
        [-1.341501206552443E-03, 2.190483327459023E-03, 6.839177007993498E-04],
        1.7 * meter)  # TODO: improve this
コード例 #12
0
def test_moon_from_boston_astrometric():
    k = Kernel(download(de430_url))
    jd = api.JulianDate(tdb=(2015, 3, 2), delta_t=67.185390 + 0.5285957)
    boston = api.Topos((42, 21, 24.1), (-71, 3, 24.8), x=0.003483, y=0.358609)
    a = boston.observe(k.moon).at(jd)
    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
コード例 #13
0
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))
    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()
コード例 #14
0
def test_itrf_vector():
    ts = api.load.timescale(builtin=True)
    t = ts.utc(2019, 11, 2, 3, 53)
    top = api.Topos(latitude_degrees=45,
                    longitude_degrees=0,
                    elevation_m=constants.AU_M - constants.ERAD)
    x, y, z = top.at(t).itrf_xyz().au
    assert abs(x - 0.7071) < 1e-4
    assert abs(y - 0.0) < 1e-14
    assert abs(z - 0.7071) < 1e-4
コード例 #15
0
def test_sat_almanac_Tricky():
    # Various tricky satellites
    # Integral: 3 days high eccentricity.
    # ANIK-F1R  Geo always visible from Boston
    # PALAPA D  Geo never visible from Boston
    # Ariane 5B GTO
    # Swift Low-inclination LEO never visible from Boston
    # Grace-FO 2  Low polar orbit
    tles = """\
        INTEGRAL
        1 27540U 02048A   20007.25125384  .00001047  00000-0  00000+0 0  9992
        2 27540  51.8988 127.5680 8897013 285.8757   2.8911  0.37604578 17780
        ANIK F-1R
        1 28868U 05036A   20011.46493281 -.00000066  00000-0  00000+0 0  9999
        2 28868   0.0175  50.4632 0002403 284.1276 195.8977  1.00270824 52609
        PALAPA D
        1 35812U 09046A   20008.38785173 -.00000341 +00000-0 +00000-0 0  9999
        2 35812 000.0518 095.9882 0002721 218.8296 045.1595 01.00269700038098
        Ariane 5B
        1 44802U 19080C   20010.68544515  .00001373  00000-0  27860-3 0  9997
        2 44802   5.1041 192.7327 7266711 217.6622  57.0965  2.30416801  1028
        Swift
        1 28485U 04047A   20010.76403232 +.00000826 +00000-0 +25992-4 0  9999
        2 28485 020.5579 055.7027 0010957 208.9479 151.0347 15.04516653829549
        GRACE-FO 2
        1 43477U 18047B   20011.66650462 +.00000719  00000-0 +29559-4 0    08
        2 43477  88.9974 159.0391 0019438 141.4770 316.8932 15.23958285 91199
    """.splitlines()
    expected = {
        'INTEGRAL': 36,
        'ANIK F-1R': 14,
        'PALAPA D': 0,
        'Ariane 5B': 36,
        'Swift': 0,
        'GRACE-FO 2': 90
    }
    for iline0 in range(0, len(tles) - 3, 3):
        sat = api.EarthSatellite(tles[1 + iline0].strip(),
                                 tles[2 + iline0].strip(),
                                 name=tles[iline0].strip())
        topos = api.Topos('42.3581 N', '71.0636 W')  # Boston
        timescale = api.load.timescale()
        t0 = timescale.tai(2020, 1, 1)
        t1 = timescale.tai(2020, 1, 15)
        horizon = 20
        nexpected = expected[sat.name]

        times, yis = almanac.find_satellite_events(t0,
                                                   t1,
                                                   sat,
                                                   topos,
                                                   horizon=20)
        assert (verify_sat_almanac(times, yis, sat, topos, horizon, nexpected))
コード例 #16
0
def test_is_sunlit():
    # Yes, a positionlib method; but it made sense to test it here.
    ts = api.load.timescale()
    t = ts.utc(2018, 7, 3, 0, range(0, 60, 10))
    s = EarthSatellite(*iss_tle0.splitlines())
    eph = load('de421.bsp')
    expected = [True, False, False, False, True, True]
    assert list(s.at(t).is_sunlit(eph)) == expected

    # What if we observe from a topos rather than the geocenter?
    topos = api.Topos('40.8939 N', '83.8917 W')
    assert list((s - topos).at(t).is_sunlit(eph)) == expected
コード例 #17
0
def test_dark_twilight_day():
    ts = api.load.timescale()
    t0 = ts.utc(2019, 11, 8, 4)
    t1 = ts.utc(2019, 11, 9, 4)
    e = api.load('de421.bsp')
    defiance = api.Topos('41.281944 N', '84.362778 W')
    t, y = almanac.find_discrete(t0, t1, almanac.dark_twilight_day(e, defiance))
    strings = t.utc_strftime('%Y-%m-%d %H:%M')
    assert strings == [
        '2019-11-08 10:42', '2019-11-08 11:15', '2019-11-08 11:48',
        '2019-11-08 12:17', '2019-11-08 22:25', '2019-11-08 22:54',
        '2019-11-08 23:27', '2019-11-08 23:59',
    ]
    assert (y == (1, 2, 3, 4, 3, 2, 1, 0)).all()
コード例 #18
0
def sunrise_sunset():
    e = api.load('de421.bsp')
    ts = api.load.timescale()
    bluffton = api.Topos('65.02 N', '25.47 E')  # Oulu coordinates
    t0 = ts.utc(2019, 3, 1, 0)
    t1 = ts.utc(2019, 4, 1, 0)
    t, y = almanac.find_discrete(t0, t1, almanac.sunrise_sunset(e, bluffton))

    sunrises = np.array(
        t.utc_iso()[::2])  # gets every element which index is even
    sunsets = np.array(
        t.utc_iso()[1::2])  # gets every element which index is odd
    # sunrises_sunsets = pd.DataFrame({'sunrises':sunrises, 'sunsets':sunsets})
    return sunrises, sunsets
コード例 #19
0
def test_iss_altitude_with_gcrs_vector_subtraction(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[1], lines[2], lines[0])
    lake_zurich = api.Topos(latitude_degrees=42.2, longitude_degrees=-88.1)

    alt, az, d = (s - lake_zurich).at(t).altaz()
    print(dt, their_altitude, alt.degrees, their_altitude - alt.degrees)
    assert abs(alt.degrees - their_altitude) < 2.5  # TODO: tighten this up?
コード例 #20
0
def test_iss_altitude_computed_with_gcrs(iss_transit):
    dt, their_altitude = iss_transit

    cst = timedelta(hours=-6)  #, minutes=1)
    dt = dt - cst
    jd = Timescale(delta_t=67.2091).utc(dt)

    lines = iss_tle.splitlines()
    s = EarthSatellite(lines, None)
    lake_zurich = api.Topos(latitude_degrees=42.2, longitude_degrees=-88.1)

    alt, az, d = lake_zurich.at(jd).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?
コード例 #21
0
ファイル: skyfield_sunrise.py プロジェクト: sevenjames/pylab
def find_sunrise(n=1):
    """
    Search the almanac for sunrise and sunset times in the next 24 hours.
    Does not actually compute the times.
    It looks them up in the precomputed ephemeris files provided by the JPL.
    Sunrise times are 'True', Sunset times are 'False'. Times are UTC. 
    """
    ts = api.load.timescale()
    ep = api.load('de421.bsp')
    location = api.Topos('41.85 N', '87.65 W')  # Chicago, USA
    t0 = ts.now()
    t1 = ts.utc(t0.utc_datetime() + timedelta(days=n))
    t, y = almanac.find_discrete(t0, t1, almanac.sunrise_sunset(ep, location))

    times = list(zip(t.utc_iso(), y))
    print(times)
コード例 #22
0
def _risesetextremes(lat, lon, tzstr, startYear, years, verbose=False):
    ts = api.load.timescale()
    load = api.Loader('/var/data')
    e = load('de430t.bsp')
    # earth = planets['earth']

    tz = timezone(tzstr)

    bluffton = api.Topos(lat, lon)
    t0 = ts.utc(startYear, 1, 1)
    t1 = ts.utc(startYear+years, 1, 1)
    t, y = almanac.find_discrete(t0, t1, almanac.sunrise_sunset(e, bluffton))



    if verbose: print ('done')

    result = dict()

    prevrise = None
    for ti, yi in zip(t, y):
        dt, _ = ti.astimezone_and_leap_second(tz)
        if yi:
            x = 'rise'
        else:
            x = 'set'

        year = str(dt.year)

        if year not in result.keys():
            result[year] = {'rises': [],
                            'rise_hr': [],
                            'sets': [],
                            'set_hr': [],
                            'sunlight': []
                            }
        hrs = dt.hour + dt.minute/60.0 + dt.second/3600.0
        result[year][f"{x}s"].append(dt)
        result[year][f"{x}_hr"].append(hrs)
        if yi:
            prevrise = ti
        else:
            if prevrise is not None:
                result[year]['sunlight'].append((ti - prevrise)*24.0)

    return result
コード例 #23
0
ファイル: DayInfo.py プロジェクト: claus007/daily2mqtt
def do_skyfield(utcnow):
    global ephi
    my_place = sfa.Topos(config['location']['longitude'], config['location']['latitude'])
    t0 = ts.utc(utcnow.year, utcnow.month, utcnow.day, utcnow.hour, utcnow.minute, utcnow.second)
    utcnow = utcnow + datetime.timedelta(hours=24)
    t1 = ts.utc(utcnow.year, utcnow.month, utcnow.day, utcnow.hour, utcnow.minute, utcnow.second)
    t, y = sf.almanac.find_discrete(t0, t1, sf.almanac.sunrise_sunset(ephi, my_place))

    for ti, yi in zip(t, y):
        x1 = (ti.utc_datetime()).replace(tzinfo=tz.tzutc())
        x1 = x1.astimezone(tz.tzlocal())
        if yi:
            ev = (x1.hour, x1.minute, 'Sunshine', 'True')
        else:
            ev = (x1.hour, x1.minute, 'Sunshine', 'False')
        logging.info("New event: %s" % str(ev))
        daily_events.append(ev)
コード例 #24
0
def test_cirs_era():

    ts = api.load.timescale()
    st = ts.utc(year=np.arange(1951, 2051))

    planets = api.load('de421.bsp')
    pos = planets['earth'] + api.Topos(longitude_degrees=0.0, latitude_degrees=0.0)

    # Get the TIO
    tio = pos.at(st).from_altaz(alt_degrees=90, az_degrees=180)

    # Get the TIOs RA in CIRS coordinates, and the Earth Rotation Angle
    tio_ra, tio_dec, _ = tio.cirs_radec(st)
    era = 360.0 * earth_rotation_angle(st.ut1)

    tol = (1e-8 / 3600.0)  # 10 nano arc-second precision
    assert np.allclose(tio_ra._degrees, era, rtol=0.0, atol=tol)
    assert np.allclose(tio_dec._degrees, 0.0, rtol=0.0, atol=tol)
コード例 #25
0
def test_sat_almanac_LEO():
    # Testcase from
    # https://github.com/skyfielders/astronomy-notebooks/blob/master/Solvers/Earth-Satellite-Passes.ipynb
    # with elevated horizon

    tle = ["TIANGONG 1",
           "1 37820U 11053A   14314.79851609  .00064249  00000-0  44961-3 0  5637",
           "2 37820  42.7687 147.7173 0010686 283.6368 148.1694 15.73279710179072"]
    sat = api.EarthSatellite(*tle[1:3], name=tle[0])
    topos = api.Topos('42.3581 N', '71.0636 W')
    timescale = api.load.timescale()
    t0 = timescale.tai(2014, 11, 10)
    t1 = timescale.tai(2014, 11, 11)
    horizon = 20
    nexpected = 12

    #times, yis = almanac.find_satellite_events(t0, t1, sat, topos, horizon=20)
    times, yis = sat.find_passes(topos, t0, t1, 20.0)
    assert(verify_sat_almanac(times, yis, sat, topos, horizon, nexpected))
コード例 #26
0
def test_cirs_meridian():

    ts = api.load.timescale()
    st = ts.utc(year=2051)

    planets = api.load('de421.bsp')
    pos = planets['earth'] + api.Topos(longitude_degrees=0.0, latitude_degrees=0.0)

    # Get a series of points along the meridian
    alt = np.arange(1, 90)
    meridian = pos.at(st).from_altaz(alt_degrees=alt, az_degrees=0.0)

    # Get the TIOs RA in CIRS coordinates, and the Earth Rotation Angle
    md_ra, md_dec, _ = meridian.cirs_radec(st)
    era = 360.0 * earth_rotation_angle(st.ut1)

    tol = (1e-7 / 3600.0)  # 100 nano arc-second precision
    assert np.allclose(md_ra._degrees, era, rtol=0.0, atol=tol)
    assert np.allclose(md_dec._degrees, 90 - alt, rtol=0.0, atol=tol)
コード例 #27
0
def sunrise_sunset(lat, lon):
    place = api.Topos(lat, lon)
    one_day = timedelta(days=1)
    start = datetime.today().astimezone().replace(hour=0,
                                                  minute=0,
                                                  second=0,
                                                  microsecond=0)
    end = start + one_day

    start = ts.utc(start)
    end = ts.utc(end)
    srss, sross = almanac.find_discrete(start, end,
                                        almanac.sunrise_sunset(ephem, place))

    tz = datetime.now().astimezone().tzinfo
    (sr, ss) = srss.astimezone(tz)

    t0_time = sr.strftime('%H%M')
    t0_srss = "SR" if sross[0] else "SS"
    t1_time = ss.strftime('%H%M')
    t1_srss = "SR" if sross[1] else "SS"
    return f"{t0_srss}{t0_time} {t1_srss}{t1_time}"
コード例 #28
0
ファイル: tasks.py プロジェクト: nchls/pi-coop
def get_sunrise_sunset_times():
    pownal = api.Topos('43.921554 N', '70.147969 W')
    ts = api.load.timescale(builtin=True)
    eph = api.load_file(settings.SKYFIELD_DATA_PATH)
    now = datetime.now().astimezone()
    today_start = datetime(now.year, now.month, now.day).astimezone()
    today_end = today_start + timedelta(days=1)
    today_start_ts = ts.utc(today_start)
    today_end_ts = ts.utc(today_end)
    traversals, is_sunrise = almanac.find_discrete(
        today_start_ts, today_end_ts, almanac.sunrise_sunset(eph, pownal))
    # If there are multiple sunrises in a day then we have bigger problems than opening the coop door at the right time
    sunrise_iso = traversals[0].utc_iso(
    ) if is_sunrise[0] else traversals[1].utc_iso()
    sunset_iso = traversals[1].utc_iso(
    ) if not is_sunrise[1] else traversals[0].utc_iso()
    sunrise_dtm = datetime.strptime(
        sunrise_iso,
        '%Y-%m-%dT%H:%M:%SZ').replace(tzinfo=timezone.utc).astimezone()
    sunset_dtm = datetime.strptime(
        sunset_iso,
        '%Y-%m-%dT%H:%M:%SZ').replace(tzinfo=timezone.utc).astimezone()
    return (sunrise_dtm, sunset_dtm)
コード例 #29
0
def is_light():
    """is_light returns True if the sun is up and False otherwise"""
    # load in data directory to avoid redownloading
    loader = Loader('~/skyfield_data')
    ts = loader.timescale()
    e = loader('de421.bsp')

    # set current location (melbourne does not appear in the default list)
    melbourne = api.Topos('37.951910 S', '145.152080 E')
    # get current time in UTC format
    now = datetime.datetime.utcnow()
    now = now.replace(tzinfo=utc)
    # set the interval for now and 24 hours from now
    t0 = ts.utc(now)
    t1 = ts.utc(now + timedelta(hours=24))

    # find the times and types of event (sunrise/sunset)
    t, y = almanac.find_discrete(t0, t1, almanac.sunrise_sunset(e, melbourne))

    #y[0] = True for sunrise (which means it is currently dark)

    light = not y[0]

    return light
コード例 #30
0
                    default=-60,
                    help="Threshold to identify the peaks")
parser.add_argument("--num_checks",
                    type=int,
                    default=10,
                    help="How many time offsets to use")
parser.add_argument(
    "--error",
    type=float,
    default=0.02,
    help="The allowed error rate betwe recovred and caculated PWM")
args = parser.parse_args()

# Starfield Globals
SATELLITES = sf.load.tle_file(args.db)
GROUND_CONTROL = sf.Topos(latitude_degrees=args.latitude,
                          longitude_degrees=args.longitude)
ts = sf.load.timescale()

# Configuration data
THRESHOLD = args.threshold
SAMPLES_PER_CYCLE = args.samples_per_cycle
TIME_PER_CYCLE = SAMPLES_PER_CYCLE / args.sample_rate
PWM_MIN = 0.03  # from the README.txt
PWM_MAX = 0.35


# read in all the samples
def file_size(fp):
    return os.fstat(fp.fileno()).st_size