Exemple #1
0
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 find_twilight(location, t_timescale_nights_local_list):
    planets = load("de421.bsp")
    topo = Topos(location["latitude"],
                 location["longitude"],
                 elevation_m=location["elevation"])
    result = []
    for t_night in t_timescale_nights_local_list:
        t_start = t_night[0]
        t_end = t_night[-1]
        f = almanac.dark_twilight_day(planets, topo)
        ts, twilight_types = almanac.find_discrete(t_start, t_end, f)
        t_night_start = None
        t_night_end = None
        for t, twilight_type in zip(ts, twilight_types):
            #print(twilight_type, t, t.utc_iso(), ' Start of', almanac.TWILIGHTS[twilight_type])
            # exclude all twilight, just full dark night
            # relies on start of night, twilight, day, etc being in order
            if twilight_type == 0:  # start of night
                t_night_start = t
            elif not (
                    t_night_start is None
            ) and twilight_type == 1:  # start of astro twilight after start of night
                t_night_end = t
                break
        result.append((t_night_start, t_night_end))
    return result
    def __init__(self,
                 latitude,
                 longitude,
                 local_time_zone=None,
                 result_time_zone='UTC'):

        AstronomicalCalculator._init_if_needed()

        self._lat = latitude
        self._lon = longitude

        self._local_time_zone = local_time_zone
        if isinstance(self.local_time_zone, str):
            self._local_time_zone = pytz.timezone(self._local_time_zone)

        self._result_time_zone = result_time_zone
        if self._result_time_zone is None:
            self._result_time_zone = pytz.utc
        elif isinstance(self._result_time_zone, str):
            self._result_time_zone = pytz.timezone(self._result_time_zone)

        self._topos = Topos(latitude_degrees=self._lat,
                            longitude_degrees=self._lon,
                            elevation_m=0)

        self._loc = self._earth + self._topos

        self._solar_altitude_period_function = \
            almanac.dark_twilight_day(self._ephemeris, self._topos)
Exemple #4
0
def find_night_events(aos, los, location, time_zone, window):
    """
    Reduce events in the form of aos and los to events which occur at night

        Parameters:
            aos: array of aos for each satellite
            los: arrau of los for each satellite
            location: coordinates for observing
            time_zone: time_zone name
            window: observation window
        Returns:
            dark_aos: array of aos for events which occur at night
            dark_los: array of los for events which occur at night
    """

    # this is all required to find astronomical events
    midday = dt.datetime(window[0][0], window[0][1], int(np.floor(window[0][2])),
                         12, tzinfo = timezone(time_zone))
    next_midday = midday + dt.timedelta(days=1)

    ts = load.timescale()
    t0 = ts.from_datetime(midday)
    t1 = ts.from_datetime(next_midday)
    eph = load('de421.bsp')
    sight = Topos(location[0].strip('-') + 'S', location[1] + 'E')

    # load night conditions
    f = almanac.dark_twilight_day(eph, sight)
    # find dawn/dusk events
    astro_t, astro_events = almanac.find_discrete(t0, t1, f)

    astro_dusk = astro_t[2]
    astro_dawn = astro_t[4]

    dark_aos = []
    dark_los = []

    # find events which fall within dawn/dusk
    for satellite_aos, satellite_los in zip(aos, los):
        dark_start = []
        dark_end = []
        for start, end in zip(satellite_aos, satellite_los):
            if (astro_dusk.tt <= start <= astro_dawn.tt) \
            and (astro_dusk.tt <= end <= astro_dawn.tt):
                dark_start.append(start)
                dark_end.append(end)
        dark_aos.append(dark_start)
        dark_los.append(dark_end)

    return dark_aos, dark_los
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()
Exemple #6
0
def calc_comet(comet_df, obstime, earthcoords, numdays=0, alt_table=False):
    # Generating a position.
    cometvec = sun + mpc.comet_orbit(comet_df, ts, GM_SUN)

    cometpos = earth.at(obstime).observe(cometvec)
    ra, dec, distance = cometpos.radec()
    print("RA", ra, "   DEC", dec, "   Distance", distance)

    if earthcoords:
        if len(earthcoords) > 2:
            elev = earthcoords[2]
        else:
            elev = 0
        obstopos = Topos(latitude_degrees=earthcoords[0],
                         longitude_degrees=earthcoords[1],
                         elevation_m=elev)
        print("\nObserver at", obstopos.latitude, "N  ", obstopos.longitude,
              "E  ", "Elevation", obstopos.elevation.m, "m")
        obsvec = earth + obstopos

        alt, az, distance = \
            obsvec.at(obstime).observe(cometvec).apparent().altaz()
        print("Altitude", alt, "     Azumuth", az, distance)

        alm_twilights = almanac.dark_twilight_day(eph, obstopos)
        # dawn, dusk = find_twilights(obstime, alm_twilights)
        # print(WHICH_TWILIGHT, ": Dawn", svt2str(dawn), "Dusk", svt2str(dusk))

        if numdays:
            print("\nRises and sets over", numdays, "days:")
            datetime1 = obstime.utc_datetime() - timedelta(hours=2)
            t0 = ts.utc(datetime1)
            t1 = ts.utc(datetime1 + timedelta(days=numdays))

            alm = almanac.risings_and_settings(eph, cometvec, obstopos)
            t, y = almanac.find_discrete(t0, t1, alm)

            print_rises_sets(obsvec, cometvec, alm, t0, t1)

        if alt_table:
            print()
            oneday = timedelta(days=1)
            while True:
                print_alt_table(obstime, cometvec, obsvec, alm_twilights)
                numdays -= 1
                if numdays <= 0:
                    break
                # Add a day: there doesn't seem to be a way to do this
                # while staying within skyview's Time object.
                obstime = ts.utc(obstime.utc_datetime() + oneday)
Exemple #7
0
def calculate_twilight_times(obs, dt):
    '''
    calcualtes the starting point of each twilight
    :param obs: Skyfield Topos object, coordinates of observer
    :param dt: datetime object to centerl sun almanac data on
    :return:
    '''
    t0 = ts.utc(dt.year, dt.month, dt.day - 1)
    t1 = ts.utc(dt.year, dt.month, dt.day + 2)
    t, y = almanac.find_discrete(t0, t1, almanac.dark_twilight_day(e, obs))

    data = {}
    for ti, yi in zip(t, y):
        dt = ti.utc_datetime().astimezone(eastern)
        data[nearest_minute(dt)] = almanac.TWILIGHTS[yi]
    return data
    def _get_times(self, now: datetime) -> (datetime, datetime):
        midnight = now.replace(hour=0, minute=0, second=0, microsecond=0)
        next_midnight = midnight + timedelta(days=1)

        ts = load.timescale()
        t0 = ts.from_datetime(midnight)
        t1 = ts.from_datetime(next_midnight)
        eph = load_file(config['DE421_PATH'])
        bluffton = wgs84.latlon(config['COORDINATES']['N'] * N, config['COORDINATES']['E'] * E)
        f = almanac.dark_twilight_day(eph, bluffton)
        times, events = almanac.find_discrete(t0, t1, f)

        result = []
        previous_e = None
        for t, e in zip(times, events):
            if e == 4:
                result.append(t.astimezone(self.zone))
            if previous_e == 4:
                result.append(t.astimezone(self.zone))
            previous_e = e

        return result[0], result[1]
Exemple #9
0
def is_sun_visible(latitude=None, longitude=None, date_time=None, dawn_dusk=False):
    """
    Determine if sun is above horizon at for a list of times.

    Parameters
    ----------
    latitude : int, float
        Latitude in degrees north positive. Must be a scalar.
    longitude : int, float
        Longitude in degrees east positive. Must be a scalar.
    date_time : datetime.datetime, numpy.array.datetime64, list of datetime.datetime
        Datetime with timezone, datetime with no timezone in UTC, or numpy.datetime64
        format in UTC. Can be a single datetime object or list of datetime objects.
    dawn_dusk : boolean
        If set to True, will use skyfields dark_twilight_day function to calculate sun up
        Returns a list of int's instead of boolean.
        0 - Dark of Night
        1 - Astronomical Twilight
        2 - Nautical Twilight
        3 - Civil Twilight
        4 - Sun Is Up

    Returns
    -------
    result : list
        List matching size of date_time containing True/False if sun is above horizon.
    """

    sf_dates = None

    # Check if datetime object is scalar and if has no timezone.
    if isinstance(date_time, datetime):
        if date_time.tzinfo is None:
            sf_dates = [date_time.replace(tzinfo=pytz.UTC)]
        else:
            sf_dates = [date_time]

    # Check if datetime objects in list have timezone. If not add.
    if isinstance(date_time, (list, tuple)) and isinstance(date_time[0], datetime):
        if isinstance(date_time[0], datetime) and date_time[0].tzinfo is not None:
            sf_dates = date_time
        else:
            sf_dates = [ii.replace(tzinfo=pytz.UTC) for ii in date_time]

    # Convert datetime64 to datetime with timezone.
    if type(date_time).__module__ == np.__name__ and np.issubdtype(date_time.dtype, np.datetime64):
        sf_dates = datetime64_to_datetime(date_time)
        sf_dates = [ii.replace(tzinfo=pytz.UTC) for ii in sf_dates]

    if sf_dates is None:
        raise ValueError('The date_time values entered into is_sun_visible() '
                         'do not match input types.')

    ts = load.timescale()
    eph = load_file(skyfield_bsp_file)

    t0 = ts.from_datetimes(sf_dates)
    location = wgs84.latlon(latitude, longitude)
    if dawn_dusk:
        f = almanac.dark_twilight_day(eph, location)
    else:
        f = almanac.sunrise_sunset(eph, location)

    sun_up = f(t0)

    eph.close()

    return sun_up
Exemple #10
0
	    print ("Successfully created the directory %s " % path)


###########################


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


### Evening ###
print("\n\n ### EVENING ### \n\n")


#Determine when is sunset and twilight
t, y = almanac.find_discrete(ts.utc(start.replace(tzinfo=api.utc)), ts.utc(stop.replace(tzinfo=api.utc)), almanac.dark_twilight_day(e, loc))

for ti, yi in zip(t,y):
	if yi == 3:
		sunset = ti
	if yi == 1:
		twilight = ti

twilight = twilight.utc_datetime()

print("Astronomical Twilght is " + twilight.strftime('%Y-%m-%d %H:%M:%S') )


###########################

Exemple #11
0
time = dt.datetime.strptime(args.date, DATE_FORMAT)
midnight = time.replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=zone)
next_midnight = midnight + dt.timedelta(days=1)

ts = load.timescale(builtin=True)
t0 = ts.utc(midnight)
t1 = ts.utc(next_midnight)
eph = load("de421.bsp")
observer_location = Topos(
    latitude_degrees=round(float(args.latitude),
                           utils.constants.COORDINATES_PRECISION),
    longitude_degrees=round(float(args.longitude),
                            utils.constants.COORDINATES_PRECISION),
    elevation_m=int(args.elevation),
)
f = almanac.dark_twilight_day(eph, observer_location)
times, events = almanac.find_discrete(t0, t1, f)

twilight_events = []

for t, e in zip(times, events):
    time = t.astimezone(zone)
    name = almanac.TWILIGHTS[e]
    twilight_events.append({"time": time, "name": name})

dumps = json.dumps(
    {"events": twilight_events},
    indent=2,
    default=json_converter,
    ensure_ascii=False,
)
Exemple #12
0
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 22 07:24:58 2020

@author: 17816
"""
import sys, getopt
import argparse

from skyfield import api
from skyfield.api import EarthSatellite
from skyfield.api import Topos, load
from skyfield import almanac

observerLatitude = 0.0
observerLongitude = 0.0
ts = api.load.timescale(builtin=True)
eph = api.load('de421.bsp')

groundStation = Topos(observerLatitude, observerLongitude)

# Find start and end of astronomical twilight on specified day
print("Get local astromical dusk and dawn")
times = ts.utc(2020, 6, 1, 12, range(2 * 1440))
t0 = times[0]  # Start time
t1 = times[-1]  # End time
print("Times: ", t0.tt, t1.tt, len(times))
f = almanac.dark_twilight_day(eph, groundStation)
t, y = almanac.find_discrete(t0, t1, f)
for ti, yi in zip(t, y):
    print(yi, ti.tt, ti.utc, ' Start of', almanac.TWILIGHTS[yi])