Example #1
0
def astronomical_dates(year):
    y = str(year)
    march = ephem.next_spring_equinox(y).datetime().date()
    june = ephem.next_summer_solstice(y).datetime().date()
    sept = ephem.next_autumn_equinox(y).datetime().date()
    dec = ephem.next_winter_solstice(y).datetime().date()
    return dict(march=march, june=june, sept=sept, dec=dec)
Example #2
0
 def update(self):
     date = ephem.Date(datetime.now().date())
     self.seasondata.update({
         'Autumnal (Fall) Equinox':
         ephem.next_autumn_equinox(date).datetime().date()
     })
     self.moondata.update({
         'First Quarter':
         ephem.next_first_quarter_moon(date).datetime().date()
     })
     self.moondata.update(
         {'Full Moon': ephem.next_full_moon(date).datetime().date()})
     self.moondata.update({
         'Last Quarter':
         ephem.next_last_quarter_moon(date).datetime().date()
     })
     self.moondata.update(
         {'New Moon': ephem.next_new_moon(date).datetime().date()})
     self.seasondata.update({
         'Vernal (Spring) Equinox':
         ephem.next_spring_equinox(date).datetime().date()
     })
     self.seasondata.update({
         'Summer Solstice':
         ephem.next_summer_solstice(date).datetime().date()
     })
     self.seasondata.update({
         'Winter Solstice':
         ephem.next_winter_solstice(date).datetime().date()
     })
     moon_keys = sorted(self.moondata.keys(),
                        key=lambda y: (self.moondata[y]))
     moon_keys.reverse()
     b = {}
     state1 = True
     while moon_keys:
         a = moon_keys.pop()
         b.update({a: self.moondata[a]})
         if self.moondata[a] != datetime.now().date() and state1:
             self.nextphase = [
                 a, self.moondata[a],
                 daysaway(self.moondata[a])
             ]
             state1 = False
             if self.moondata[a] == datetime.now().date():
                 self.currentphase = a
             ##### elif
     self.moondata = b
     season_keys = sorted(self.seasondata.keys(),
                          key=lambda y: (self.seasondata[y]))
     season_keys.reverse()
     b = {}
     state2 = True
     while season_keys:
         a = season_keys.pop()
         b.update({a: self.seasondata[a]})
         if self.seasondata[a] != datetime.now().date() and state2:
             self.nextseason = [
                 a, self.seasondata[a],
                 daysaway(self.seasondata[a])
             ]
             state2 = False
     self.seasondata = b
     if self.nextphase[0] == 'Last Quarter' and datetime.now().date(
     ) < self.nextphase[1]:
         self.currentphase = 'Waning Gibbus'
     if self.nextphase[0] == 'Last Quarter' and datetime.now().date(
     ) == self.nextphase[1]:
         self.currentphase = 'Last Quarter'
     if self.nextphase[0] == 'New Moon' and datetime.now().date(
     ) < self.nextphase[1]:
         self.currentphase = 'Waning Crescent'
     if self.nextphase[0] == 'New Moon' and datetime.now().date(
     ) == self.nextphase[1]:
         self.currentphase = 'New Moon'
     if self.nextphase[0] == 'First Quarter' and datetime.now().date(
     ) < self.nextphase[1]:
         self.currentphase = 'Waxing Crescent'
     if self.nextphase[0] == 'First Quarter' and datetime.now().date(
     ) == self.nextphase[1]:
         self.currentphase = 'First Quarter'
     if self.nextphase[0] == 'Full Moon' and datetime.now().date(
     ) < self.nextphase[1]:
         self.currentphase = 'Waxing Gibbus'
     if self.nextphase[0] == 'Full Moon' and datetime.now().date(
     ) == self.nextphase[1]:
         self.currentphase = 'Full Moon'
Example #3
0
    def update_daily_info(self):
        # current time, used in many of following calculations
        rn = datetime.datetime.now(tz=pytz.timezone(self.otto_info['tz']))

        # get sun times for 3 days
        otto_sun_yesterday = astral.sun.sun(self.otto_obs,
                                            datetime.datetime.today() -
                                            datetime.timedelta(days=1),
                                            tzinfo=self.otto_info['tz'])
        otto_sun_today = astral.sun.sun(self.otto_obs,
                                        datetime.datetime.today(),
                                        tzinfo=self.otto_info['tz'])
        otto_sun_tomorrow = astral.sun.sun(self.otto_obs,
                                           datetime.datetime.today() +
                                           datetime.timedelta(days=1),
                                           tzinfo=self.otto_info['tz'])

        # compute day lengths
        day_length_yesterday = otto_sun_yesterday[
            'sunset'] - otto_sun_yesterday['sunrise']
        self.day_length_yesterday_str = self.daylen_tostr(day_length_yesterday)
        day_length_today = otto_sun_today['sunset'] - otto_sun_today['sunrise']
        self.day_length_today_str = self.daylen_tostr(day_length_today)
        day_length_tomorrow = otto_sun_tomorrow['sunset'] - otto_sun_tomorrow[
            'sunrise']
        self.day_length_tomorrow_str = self.daylen_tostr(day_length_tomorrow)

        # compute how much longer today was vs yesterday, change delta text color
        self.yesterday_today_delta_str = self.daydelta_tostr(
            day_length_today - day_length_yesterday)
        if self.yesterday_today_delta_str[1] == '+':
            self.ids.yest_delta.color = (0, 1, 0, self.alpha)
        else:
            self.ids.yest_delta.color = (1, 0, 0, self.alpha)

        # compute how much longer tomorrow will be vs today, change delta text color
        self.today_tomorrow_delta_str = self.daydelta_tostr(
            day_length_tomorrow - day_length_today)
        if self.today_tomorrow_delta_str[1] == '+':
            self.ids.tom_delta.color = (0, 1, 0, self.alpha)
        else:
            self.ids.tom_delta.color = (1, 0, 0, self.alpha)

        # update today's date
        self.date = rn.strftime('%Y.%m.%d')

        # compute PST or PDT completion percentage
        daylight_trans_dates = [
            x.date() for x in pytz.timezone('US/Pacific')._utc_transition_times
            if x.year >= rn.year - 1 and x.year <= rn.year + 1
        ]  # has daylight times last year to next year
        if rn.date(
        ) < daylight_trans_dates[2]:  # before this year's spring forward)
            # useful dates are last year's fall back and this year's spring forward. currently PST
            pst_duration_days = daylight_trans_dates[2] - daylight_trans_dates[
                1]
            pst_completed_days = rn.date() - daylight_trans_dates[1]
            self.pdt_or_pst_completion_str = f'PST is {pst_completed_days/pst_duration_days*100:.2f}% done.'
        elif rn.date(
        ) < daylight_trans_dates[3]:  # between [spring forward and fall back)
            # useful dates: this year's spring forward, fall back. currently PDT :)
            pdt_duration_days = daylight_trans_dates[3] - daylight_trans_dates[
                2]
            pdt_completed_days = rn.date() - daylight_trans_dates[2]
            self.pdt_or_pst_completion_str = f'PDT is {pdt_completed_days/pdt_duration_days*100:.2f}% done.'
        else:  # you're after this year's fall back]
            # useful dates: this year's fall back, next year's spring forward. currently PST
            pst_duration_days = daylight_trans_dates[4] - daylight_trans_dates[
                3]
            pst_completed_days = rn.date() - daylight_trans_dates[3]
            self.pdt_or_pst_completion_str = f'PST is {pst_completed_days/pst_duration_days*100:.2f}% done.'

        # find next 2 important yearly transitions. include time changes, equinoxes, solstices
        year_transitions = [['spring forward', daylight_trans_dates[2]],
                            ['fall back', daylight_trans_dates[3]]]
        year_transitions.append([
            'spring equinox',
            ephem.next_spring_equinox(str(rn.year)).datetime().date()
        ])
        year_transitions.append([
            'summer solstice',
            ephem.next_summer_solstice(str(rn.year)).datetime().date()
        ])
        year_transitions.append([
            'fall equinox',
            ephem.next_fall_equinox(str(rn.year)).datetime().date()
        ])
        year_transitions.append([
            'winter solstice',
            ephem.next_winter_solstice(str(rn.year)).datetime().date()
        ])
        year_transitions.append(['spring forward', daylight_trans_dates[4]])
        year_transitions.append([
            'spring equinox',
            ephem.next_spring_equinox(str(rn.year + 1)).datetime().date()
        ])
        # sort the transitions. (are these astronomical events always guaranteed to be in the same order?)
        year_transitions.sort(key=lambda x: x[1])
        year_transitions = [x for x in year_transitions if rn.date() <= x[1]]
        self.year_transition_1 = f'{year_transitions[0][0]}  {year_transitions[0][1].strftime("%Y.%m.%d")}  ' \
                                 f'Δ{(year_transitions[0][1] - rn.date()).days}d'
        self.year_transition_2 = f'{year_transitions[1][0]}  {year_transitions[1][1].strftime("%Y.%m.%d")}  ' \
                                 f'Δ{(year_transitions[1][1] - rn.date()).days}d'
Example #4
0
def compute_vernal_equinox_obs(dt):
    """ computes vernal equinox and observes using weekend_to_monday
    """
    equinox = ephem.next_spring_equinox(str(dt.year)).datetime().date()
    return obs_sunday_drop_sunday(Timestamp(equinox))
Example #5
0
def compute_vernal_equinox_obs(dt):
    """ computes vernal equinox and observes using weekend_to_monday
    """
    equinox = ephem.next_spring_equinox(str(dt.year)).datetime().date()
    return obs_sunday_drop_sunday(Timestamp(equinox))
Example #6
0
    def __init__(self, latitude: str, longitude: str, timezone: str, year: str,
                 name: str):
        """Take the all necessary location/year/body name information and
        construct plot-ready astronomical body time series for calendar.
        Attributes are all set and ready for queries/plotting after __init__.
        
        Arguments:
        latitude = latitude in decimal degrees as a string, i.e. '36.9577'
        longitude = longitude in decimal degrees as a string, i.e. '-122.0402'
        timezone = tzdata/IANA time zone as a string, i.e. 'America/Los_Angeles'
        year = the year desired for the calendar, as a string, i.e. '2016'
        name = the name of the astronomical body as a string, first letter
               capitalized, i.e. 'Sun' or 'Moon'
        """
        self.latitude = latitude
        self.longitude = longitude
        self.timezone = timezone
        self.year = year
        self.name = name
        
        observer = ephem.Observer()
        observer.lat = ephem.degrees(latitude)
        observer.long = ephem.degrees(longitude)
        observer.elevation = 0
        begin, end = utc_year_bounds(timezone, year)
        step = 10 * ephem.minute #resolution of full timeseries of body heights
        
        alltimes, allheights = fill_in_heights(begin, end, step,
                                             observer, name, append_NaN=False)        
        '''Convert to pandas timeseries and localize the time index.'''
        assert(len(allheights) == len(alltimes))
        hei = pd.Series(allheights, alltimes)
        hei.index = hei.index.tz_localize('UTC')
        hei.index = hei.index.tz_convert(timezone)
        self.altitudes = hei

# ----------------- Special attributes for Sun and Moon ----------------

        '''Equinox and solstice events for Sun'''
        if name == 'Sun':
            spring = ephem.next_spring_equinox(year)
            summer = ephem.next_summer_solstice(year)
            fall = ephem.next_fall_equinox(year)
            winter = ephem.next_winter_solstice(year)
            event_times = [spring.datetime(), summer.datetime(), 
                           fall.datetime(), winter.datetime()]
            event_names = ['spring equinox', 'summer solstice', 'fall equinox',
                           'winter solstice']
            events = pd.Series(event_names, event_times)
            events.index = events.index.tz_localize('UTC')
            events.index = events.index.tz_convert(timezone)
            self.events = events

        '''Daily phase (% illuminated, 28-day icon ID) for Moon'''
        if name == 'Moon':
            moon = ephem.Moon()
            illuminated = []
            observer.date = begin + 22 * ephem.hour  # 10 pm local time Jan 1
            moon.compute(observer)
            while observer.date < end:
                illuminated.append(moon.moon_phase)
                observer.date += 1
                moon.compute(observer)
            daily_times = pd.date_range(year + '-01-01', year + '-12-31', 
                                      tz = timezone)
            assert(len(illuminated) == len(daily_times))
            self.percent_illuminated = pd.Series(illuminated, daily_times)
            
            cycle_days = []            
            moon_day = begin + 22 * ephem.hour   # 10 pm local time Jan 1
            while moon_day < end:
                    cycle_days.append(get_lunation_day(moon_day))
                    moon_day += 1
            assert(len(cycle_days) == len(daily_times))
            self.phase_day_num = pd.Series(cycle_days, daily_times)
            
            exact_names = []
            exact_times = []
            nowdate = begin
            if cycle_days[0] < 14:
                next_full = ephem.next_full_moon(nowdate)
                exact_times.append(next_full.datetime())
                exact_names.append('full')
                nowdate = next_full
            while nowdate < end:
                next_new = ephem.next_new_moon(nowdate)
                exact_times.append(next_new.datetime())
                exact_names.append('new')
                nowdate = next_new
                next_full = ephem.next_full_moon(nowdate)
                exact_times.append(next_full.datetime())
                exact_names.append('full')
                nowdate = next_full
            half_phases = pd.Series(exact_names, exact_times)
            half_phases.index = half_phases.index.tz_localize('UTC')
            half_phases.index = half_phases.index.tz_convert(timezone)
            self.half_phases = half_phases
import ephem
year = 1923
while year <= 1924:
    print(year)
    eq1 = ephem.next_spring_equinox(str(year))
    eq3 = ephem.next_autumn_equinox(str(year))
    eq2 = ephem.next_summer_solstice(str(year))
    eq4 = ephem.next_winter_solstice(str(year))
    eq5 = ephem.next_spring_equinox(str(year + 1))
    print("spring equinox: %s" % eq1)
    da = eq1
    while da < eq2:
        fm = ephem.next_full_moon(da)
        if fm > eq2:
            break
        print("  full moon: %s" % fm)
        da = fm
    print("summer solstice: %s" % eq2)
    da = eq2
    while da < eq3:
        fm = ephem.next_full_moon(da)
        if fm > eq3:
            break
        print("  full moon: %s" % fm)
        da = fm
    print("autumn equinox: %s" % eq3)
    while da < eq4:
        fm = ephem.next_full_moon(da)
        if fm > eq4:
            break
        print("  full moon: %s" % fm)