def get_season(date, hemisphere, season_tracking_type):
    """Calculate the current season."""

    if hemisphere == "equator":
        return None

    if season_tracking_type == TYPE_ASTRONOMICAL:
        spring_start = ephem.next_equinox(str(date.year)).datetime()
        summer_start = ephem.next_solstice(str(date.year)).datetime()
        autumn_start = ephem.next_equinox(spring_start).datetime()
        winter_start = ephem.next_solstice(summer_start).datetime()
    else:
        spring_start = datetime(2017, 3, 1).replace(year=date.year)
        summer_start = spring_start.replace(month=6)
        autumn_start = spring_start.replace(month=9)
        winter_start = spring_start.replace(month=12)

    if spring_start <= date < summer_start:
        season = STATE_SPRING
    elif summer_start <= date < autumn_start:
        season = STATE_SUMMER
    elif autumn_start <= date < winter_start:
        season = STATE_AUTUMN
    elif winter_start <= date or spring_start > date:
        season = STATE_WINTER

    # If user is located in the southern hemisphere swap the season
    if hemisphere == NORTHERN:
        return season
    return HEMISPHERE_SEASON_SWAP.get(season)
Exemple #2
0
def get_season(date, hemisphere, season_tracking_type):
    """Calculate the current season."""
    import ephem

    if hemisphere == 'equator':
        return None

    if season_tracking_type == TYPE_ASTRONOMICAL:
        spring_start = ephem.next_equinox(str(date.year)).datetime()
        summer_start = ephem.next_solstice(str(date.year)).datetime()
        autumn_start = ephem.next_equinox(spring_start).datetime()
        winter_start = ephem.next_solstice(summer_start).datetime()
    else:
        spring_start = datetime(2017, 3, 1).replace(year=date.year)
        summer_start = spring_start.replace(month=6)
        autumn_start = spring_start.replace(month=9)
        winter_start = spring_start.replace(month=12)

    if spring_start <= date < summer_start:
        season = STATE_SPRING
    elif summer_start <= date < autumn_start:
        season = STATE_SUMMER
    elif autumn_start <= date < winter_start:
        season = STATE_AUTUMN
    elif winter_start <= date or spring_start > date:
        season = STATE_WINTER

    # If user is located in the southern hemisphere swap the season
    if hemisphere == NORTHERN:
        return season
    return HEMISPHERE_SEASON_SWAP.get(season)
Exemple #3
0
def equinoxes(day):
    spring_equinox = ephem.next_equinox(str(day.year))
    autumn_equinox = ephem.next_equinox(spring_equinox)
    if day == spring_equinox.datetime().date():
        yield "Pavasario lygiadienis"
    elif day == autumn_equinox.datetime().date():
        yield "Rudens lygiadienis"
Exemple #4
0
def calculate_equinoxes(year, timezone='UTC'):
    """ calculate equinox with time zone """
    tz = pytz.timezone(timezone)

    d1 = ephem.next_equinox(str(year))
    d = ephem.Date(str(d1))
    equinox1 = d.datetime() + tz.utcoffset(d.datetime())

    d2 = ephem.next_equinox(d1)
    d = ephem.Date(str(d2))
    equinox2 = d.datetime() + tz.utcoffset(d.datetime())

    return (equinox1.date(), equinox2.date())
Exemple #5
0
def find_alignments(observer, waypoints, year=None):
    '''Find all the alignments with solstice/equinox sun/moon rise/set.
       Returns a dict: { 'vernal equinox': { 'moon': { 'rise': 94.17... } } }
       of azimuth angles in decimal degrees
    '''
    azimuths = {}

    if not year:
        year = datetime.now().year
    start_date = ephem.Date('1/1/%d' % year)

    observer.date = ephem.next_equinox(start_date)
    azimuths['vernal equinox'] = find_azimuths(observer)

    observer.date = ephem.next_solstice(observer.date)
    azimuths['summer solstice'] = find_azimuths(observer)

    observer.date = ephem.next_equinox(observer.date)
    azimuths['autumnal equinox'] = find_azimuths(observer)

    observer.date = ephem.next_solstice(observer.date)
    azimuths['winter solstice'] = find_azimuths(observer)

    pprint(azimuths)

    # How many degrees is close enough?
    DEGREESLOP = 2.

    # Now go through all the angles between waypoints and see if
    # any of them correspond to any of the astronomical angles.
    matches = []
    for wp1 in waypoints:
        for wp2 in waypoints:
            if wp1 == wp2:
                continue
            angle = angle_between(wp1, wp2)

            # Does that angle match any of our astronomical ones?
            for season in azimuths:
                for body in azimuths[season]:
                    for event in azimuths[season][body]:
                        if abs(azimuths[season][body][event] -
                               angle) < DEGREESLOP:
                            matches.append([
                                wp1[0], wp2[0],
                                '%s %s%s' % (season, body, event)
                            ])

    print("Matches:")
    pprint(matches)
Exemple #6
0
    def calculate_equinoxes(self, year, timezone='UTC'):
        """ calculate equinox with time zone """

        tz = pytz.timezone(timezone)

        d1 = ephem.next_equinox(str(year))
        d = ephem.Date(str(d1))
        equinox1 = d.datetime() + tz.utcoffset(d.datetime())

        d2 = ephem.next_equinox(d1)
        d = ephem.Date(str(d2))
        equinox2 = d.datetime() + tz.utcoffset(d.datetime())

        return (equinox1.date(), equinox2.date())
Exemple #7
0
    def get_next_date_special(self, date_tuple, utc_offset=0):
        """
        Returns next ephemeris date the given time.
        The date tuple should be in the local time.
        return date tupple
        """
        cpm = None;
        if self.string_tab == '@fullmoon':
            cpm = ephem.next_full_moon(date_tuple)
        elif self.string_tab == '@newmoon':
            cpm = ephem.next_new_moon(date_tuple)
        elif self.string_tab == '@firstquarter':
            cpm = ephem.next_first_quarter_moon(date_tuple)
        elif self.string_tab == '@lastquarter':
            cpm = ephem.next_last_quarter_moon(date_tuple)
        elif self.string_tab == '@equinox':
            cpm = ephem.next_equinox(date_tuple)
        elif self.string_tab == '@solstice':
            cpm = ephem.next_solstice(date_tuple)
        elif self.string_tab in ['@dawn', '@dusk']:
            bobs = ephem.Sun()
            date = "{0}/{1}/{2}".format(date_tuple[0], date_tuple[1], date_tuple[2])
            if self.string_tab == '@dawn':
                cpm = self._city.next_rising(bobs, start=date)
            else:
                cpm = self._city.next_setting(bobs, start=date)

        if cpm:
            return cpm.tuple()[:-1]
        return None
Exemple #8
0
    def _check_trigger_special(self, date_tuple, utc_offset=0):
        """
        Returns boolean indicating if the trigger is active at the given time.
        The date tuple should be in the local time.
        """
        cpm = False

        if self.string_tab == '@fullmoon':
            cpm = ephem.next_full_moon(date_tuple)
        elif self.string_tab == '@newmoon':
            cpm = ephem.next_new_moon(date_tuple)
        elif self.string_tab == '@firstquarter':
            cpm = ephem.next_first_quarter_moon(date_tuple)
        elif self.string_tab == '@lastquarter':
            cpm = ephem.next_last_quarter_moon(date_tuple)
        elif self.string_tab == '@equinox':
            cpm = ephem.next_equinox(date_tuple)
        elif self.string_tab == '@solstice':
            cpm = ephem.next_solistice(date_tuple)
        elif self.string_tab in ['@dawn', '@dusk']:
            bobs = ephem.Sun()
            if self.string_tab == '@dawn':
                cpm = self._city.next_rising(bobs)
            else:
                cpm = self._city.next_setting(bobs)

        if cpm:
            """ Do compare """
            print cpm
            return True
        else:
            return False
Exemple #9
0
    def _check_trigger_special(self, date_tuple, utc_offset=0):
        """
        Returns boolean indicating if the trigger is active at the given time.
        The date tuple should be in the local time.
        """
        cpm = False;

        if self.string_tab == '@fullmoon':
            cpm = ephem.next_full_moon(date_tuple)
        elif self.string_tab == '@newmoon':
            cpm = ephem.next_new_moon(date_tuple)
        elif self.string_tab == '@firstquarter':
            cpm = ephem.next_first_quarter_moon(date_tuple)
        elif self.string_tab == '@lastquarter':
            cpm = ephem.next_last_quarter_moon(date_tuple)
        elif self.string_tab == '@equinox':
            cpm = ephem.next_equinox(date_tuple)
        elif self.string_tab == '@solstice':
            cpm = ephem.next_solistice(date_tuple)
        elif self.string_tab in ['@dawn', '@dusk']:
            bobs = ephem.Sun()
            if self.string_tab == '@dawn':
                cpm = self._city.next_rising(bobs)
            else:
                cpm = self._city.next_setting(bobs)

        if cpm:
            """ Do compare """
            print cpm
            return True
        else:
            return False
Exemple #10
0
    def get_next_date_special(self, date_tuple, utc_offset=0):
        """
        Returns next ephemeris date the given time.
        The date tuple should be in the local time.
        return date tupple
        """
        cpm = None
        if self.string_tab == '@fullmoon':
            cpm = ephem.next_full_moon(date_tuple)
        elif self.string_tab == '@newmoon':
            cpm = ephem.next_new_moon(date_tuple)
        elif self.string_tab == '@firstquarter':
            cpm = ephem.next_first_quarter_moon(date_tuple)
        elif self.string_tab == '@lastquarter':
            cpm = ephem.next_last_quarter_moon(date_tuple)
        elif self.string_tab == '@equinox':
            cpm = ephem.next_equinox(date_tuple)
        elif self.string_tab == '@solstice':
            cpm = ephem.next_solstice(date_tuple)
        elif self.string_tab in ['@dawn', '@dusk']:
            bobs = ephem.Sun()
            date = "{0}/{1}/{2}".format(date_tuple[0], date_tuple[1],
                                        date_tuple[2])
            if self.string_tab == '@dawn':
                cpm = self._city.next_rising(bobs, start=date)
            else:
                cpm = self._city.next_setting(bobs, start=date)

        if cpm:
            return cpm.tuple()[:-1]
        return None
Exemple #11
0
    def calculate_equinoxes(self, year):
        """ calculate equinox with time zone """

        import ephem
        import pytz

        tz = pytz.timezone('Asia/Tokyo')

        d1 = ephem.next_equinox(str(year))
        d = ephem.Date(str(d1))
        equinox1 = d.datetime() + tz.utcoffset(d.datetime())

        d2 = ephem.next_equinox(d1)
        d = ephem.Date(str(d2))
        equinox2 = d.datetime() + tz.utcoffset(d.datetime())

        return (equinox1.date(), equinox2.date())
Exemple #12
0
def sol(year):
    """Soltice and Equinox data
       Output format
       77.89 (Spring Equinox 04:30) event %% 2016/3/20 04:30:03Z
    """
    events = [
        ('Spring Equinox', ephem.next_equinox(year)),
        ('Summer Soltice', ephem.next_solstice(year)),
        ('Fall Equinox', ephem.next_equinox(year + '/6/1')),
        ('Winter Soltice', ephem.next_solstice(year + '/9/1')),
    ]

    for day in events:
        (angle, time_str, local, dayofyear) = get_angle_localtime(day[1])
        print("{:6.2f} ({} {}) event %% {} ".format(angle, day[0], time_str,
                                                    local))
        SolEqn.append(dayofyear)
Exemple #13
0
def easter(day):
    if day.weekday() in frozenset([sunday, monday]) and 3 <= day.month <= 4:
        spring_equinox = ephem.next_equinox(str(day.year))
        full_moon = ephem.next_full_moon(spring_equinox)
        easter_day = full_moon.datetime().date() + timedelta(days=1)
        while easter_day.weekday() != sunday:
            easter_day += timedelta(days=1)
        if day in [easter_day, easter_day + timedelta(days=1)]:
            yield "Valstybinė šventė: Velykos"
Exemple #14
0
def astro_equinox_solstice(order):
    lstdic = dict()
    resultat = list()
    s1 = ephem.next_solstice(ephem.now())
    e1 = ephem.next_equinox(ephem.now())

    lstdic[ephem.localtime(s1).strftime('%Y-%m-%d %H:%M')] = "So"
    lstdic[ephem.localtime(
        ephem.next_solstice(s1)).strftime('%Y-%m-%d %H:%M')] = "So"
    lstdic[ephem.localtime(e1).strftime('%Y-%m-%d %H:%M')] = "Eq"
    lstdic[ephem.localtime(
        ephem.next_equinox(e1)).strftime('%Y-%m-%d %H:%M')] = "Eq"

    alldateslist = lstdic.keys()
    for eventdate in sorted(lstdic.keys()):
        resultat.append(lstdic[eventdate] + " :" + eventdate)
        logMsg(lstdic[eventdate] + " :" + eventdate)
    return resultat
Exemple #15
0
def is_equinox(date):
    """Returns a Boolean if the given day does not land on a equinox, or a
    PyEphem Date if the given day does land on a equinox.

    Keyword arguments:
    date -- a YYYY-MM-DD string.
    """

    next_equinox = ephem.next_equinox(date)
    return helpers.set_date_to_midnight(next_equinox) == ephem.Date(date)
Exemple #16
0
 def draw_equinox(start, whicheq, offsets):
     equinox = ephem.next_equinox(start)
     self.observer.date = self.gmt_for_time_on_date(equinox, (12, 0, 0))
     self.sun.compute(self.observer)
     x, y = self.project(self.sun.az, self.sun.alt)
     self.draw_dot(self.specialgc, x, y, 7)
     x1 = x + offsets[0] * 20
     self.drawing_area.window.draw_line(self.specialgc, x, y, x1, y)
     eqstr = "%s equinox\n%s" % (whicheq, str(equinox).split(' ')[0])
     self.draw_string(eqstr, x1, y, self.specialgc, offsets)
Exemple #17
0
 def _get_season(self):
     return min(
         (ephem.localtime(ephem.next_equinox(self.day_as_dt)) -
          self.day_as_dt).days,
         (self.day_as_dt -
          ephem.localtime(ephem.previous_equinox(self.day_as_dt))).days,
         (ephem.localtime(ephem.next_solstice(self.day_as_dt)) -
          self.day_as_dt).days,
         (self.day_as_dt -
          ephem.localtime(ephem.previous_solstice(self.day_as_dt))).days)
Exemple #18
0
        def draw_equinox(start, whicheq, offsets):
            equinox = ephem.next_equinox(start)
            self.observer.date = self.gmt_for_time_on_date(equinox, (12, 0, 0))
            self.sun.compute(self.observer)
            x, y = self.project(self.sun.az, self.sun.alt)
            print("%s equinox: %s" % (whicheq, str(self.observer.date)))
            self.draw_dot(x, y, self.special_dot_size)

            if labels:
                x1 = x + offsets[0] * 20
                self.draw_line(x, y, x1, y)
                eqstr = "%s equinox\n%s" % (whicheq, str(equinox).split(' ')[0])
                self.draw_string(eqstr, x1, y, offsets)
Exemple #19
0
        def draw_equinox(start, whicheq, offsets):
            equinox = ephem.next_equinox(start)
            self.observer.date = self.gmt_for_time_on_date(equinox, (12, 0, 0))
            self.sun.compute(self.observer)
            x, y = self.project(self.sun.az, self.sun.alt)
            print("%s equinox: %s" % (whicheq, str(self.observer.date)))
            self.draw_dot(x, y, self.special_dot_size)

            if labels:
                x1 = x + offsets[0] * 20
                self.draw_line(x, y, x1, y)
                eqstr = "%s equinox\n%s" % (whicheq, str(equinox).split(' ')[0])
                self.draw_string(eqstr, x1, y, offsets)
Exemple #20
0
def gen_minchiate_dates(start, end):
    # Minchiate tournaments are six weeks and twelve weeks after each equinox
    # and solstice, with the cutoff time being midnight Saturday.
    astro = min(ephem.next_solstice(start), ephem.next_equinox(start))
    six_date = (this_or_next_weekday(astro.datetime(), 5) +
                datetime.timedelta(weeks=5))
    if six_date <= end:
        yield six_date
        twelve_date = six_date + datetime.timedelta(weeks=6)
        if twelve_date <= end:
            yield twelve_date
            # Get the next equinox/solstice and keep going
            for item in gen_minchiate_dates(astro, end):
                yield item
Exemple #21
0
#!/usr/bin/env python
# coding: utf-8
"""
Gera um arquivo Remind com estações do ano.
"""

import ephem
from pytz import timezone


def formata_data(r):
    return timezone('UTC').localize(r.datetime()).astimezone(
        timezone('Brazil/East')).date()


if __name__ == '__main__':
    arq = open('estacoes.remind', 'w')
    for ano in range(2000, 2051):
        ano = str(ano)
        print(ano)
        estacoes = [
            (ephem.next_solstice(ano), 'Inverno'),
            (ephem.next_solstice(ano + '/7'), 'Verão'),
            (ephem.next_equinox(ano), 'Outono'),
            (ephem.next_equinox(ano + '/7'), 'Primavera'),
        ]
        for data, msg in estacoes:
            arq.write('REM {data} MSG {msg}\n'.format(data=formata_data(data),
                                                      msg=msg))
    arq.close()
Exemple #22
0
    if s > ve:
        ve = ephem.next_vernal_equinox( s )
        lm = 0

    lm+=1
    if p is not None:
        dif = ( s - p )

    p = s

    print "%d\t%d\t-\t%s" % (lm, dif, ephem.localtime(s) )


    #print "%d - %d,%d, date: %s, next sunrise: %s" % (lm, dif2, dif, d, s )



dl = "-7"
for idx in range(0,2):
    dl = ephem.next_equinox(dl)
    moon = ephem.Moon(dl)
    d = dl.datetime()

    abr,const_name = ephem.constellation( moon )
    #print "constellation: %s dow: %s date: %s - GEOCENTRIC(%d,%d), Phase: %d " % ( const_name, daysofweek[d.weekday()], dl, moon.hlat,moon.hlon, moon.moon_phase )
    print """
Date: %s : %s
Moon Phase: %f / Constellation: %s
Lat: %f, Long: %f""" % ( dl , daysofweek[d.weekday()],moon.moon_phase,const_name,moon.hlat, moon.hlon, )
Exemple #23
0
def find_alignments(observer, waypoints, year, allpoints=False):
    '''Find all the alignments with solstice/equinox sun/moon rise/set.
       Returns a dict: { 'vernal equinox': { 'moon': { 'rise': 94.17... } } }
       of azimuth angles in decimal degrees
    '''
    azimuths = {}

    # start_date = ephem.Date('%d/1/1' % year)
    print("Year", year, type(year))
    start_date = ephem.Date((year, 1, 1))
    # date= ephem.date((-59000,1,1))

    observer.date = ephem.next_equinox(start_date)
    azimuths['vernal equinox'] = find_azimuths(observer)

    observer.date = ephem.next_solstice(observer.date)
    azimuths['summer solstice'] = find_azimuths(observer)

    observer.date = ephem.next_equinox(observer.date)
    azimuths['autumnal equinox'] = find_azimuths(observer)

    observer.date = ephem.next_solstice(observer.date)
    azimuths['winter solstice'] = find_azimuths(observer)

    # pprint(azimuths)

    # How many degrees is close enough?
    DEGREESLOP = 2.

    # If allpoints is set, check angles among all pairs of points.
    # Otherwise, only check angles from observer to other points.
    if allpoints:
        print("Looking for alignments among all points")
        observer_points = waypoints
    else:
        observer_points = [ [ observer.name,
                              observer.lat / ephem.degree,
                              observer.lon / ephem.degree,
                              observer.elevation ] ]

    # Now go through all the angles between waypoints and see if
    # any of them correspond to any of the astronomical angles.
    matches = []
    for wp1 in observer_points:
        print("\nChecking observer", wp1)
        for wp2 in waypoints:
            if wp1 == wp2:
                continue
            angle = bearing_to(wp1, wp2)
            print("  ... vs", wp2, angle)

            # Does that angle match any of our astronomical ones?
            for season in azimuths:  # vernal equinox, etc.
                for body in azimuths[season]:  # sun, full moon
                    for event in azimuths[season][body]:  # rise, set
                        event_az = azimuths[season][body][event]['az']
                        if abs(event_az - angle) < DEGREESLOP:
                            matches.append({
                                'observer': wp1[0],
                                'target': wp2[0],
                                'event': '%s %s%s' % (season, body, event),
                                'azimuth': event_az,
                                'slop': event_az - angle,
                                'time': azimuths[season][body][event]['time'],
                                'latitude': wp2[1],
                                'longitude': wp2[2],
                            })

    return matches
Exemple #24
0
local.horizon='0:34'

nextSet = ephem.localtime(local.next_setting(sun))
nextRise = ephem.localtime(local.next_rising(sun))
prevSet = ephem.localtime(local.previous_setting(sun))
prevRise = ephem.localtime(local.previous_rising(sun))

print("Previous sunrise in KC was: ",ephem.localtime(local.previous_rising(sun)))
#logger.debug("Previous sunrise in KC was: ",ephem.localtime(local.previous_rising(sun)))
print("Previous sunset in KC was: ",ephem.localtime(local.previous_setting(sun)))
print("Next sunrise in KC will be: ",ephem.localtime(local.next_rising(sun)))
print("Next sunset in KC will be: ",ephem.localtime(local.next_setting(sun)))
print("Next Full Moon will be: " ,ephem.localtime(ephem.next_full_moon(now)))
print("Next New Moon will be: " ,ephem.localtime(ephem.next_new_moon(now)))
print("Next Solstice will be: " ,ephem.localtime(ephem.next_solstice(now)))
print("Next Equinox will be: " ,ephem.localtime(ephem.next_equinox(now)))
print("Sunrise:" ,local.next_rising(ephem.Sun()).datetime())
print("Sunset:" ,local.next_setting(ephem.Sun()).datetime())
next_sunrise_datetime = local.next_rising(ephem.Sun()).datetime()
next_sunset_datetime = local.next_setting(ephem.Sun()).datetime()

# If it is daytime, we will see a sunset sooner than a sunrise.
it_is_day = next_sunset_datetime < next_sunrise_datetime
print("It's day." if it_is_day else "It's night.")

# If it is nighttime, we will see a sunrise sooner than a sunset.
it_is_night = next_sunrise_datetime < next_sunset_datetime
print("It's night." if it_is_night else "It's day.")

#if nextSet < nextRise:
#	print("Day Time")
Exemple #25
0
nextSet = ephem.localtime(local.next_setting(sun))
nextRise = ephem.localtime(local.next_rising(sun))
prevSet = ephem.localtime(local.previous_setting(sun))
prevRise = ephem.localtime(local.previous_rising(sun))

print("Previous sunrise in KC was: ",
      ephem.localtime(local.previous_rising(sun)))
#logger.debug("Previous sunrise in KC was: ",ephem.localtime(local.previous_rising(sun)))
print("Previous sunset in KC was: ",
      ephem.localtime(local.previous_setting(sun)))
print("Next sunrise in KC will be: ", ephem.localtime(local.next_rising(sun)))
print("Next sunset in KC will be: ", ephem.localtime(local.next_setting(sun)))
print("Next Full Moon will be: ", ephem.localtime(ephem.next_full_moon(now)))
print("Next New Moon will be: ", ephem.localtime(ephem.next_new_moon(now)))
print("Next Solstice will be: ", ephem.localtime(ephem.next_solstice(now)))
print("Next Equinox will be: ", ephem.localtime(ephem.next_equinox(now)))
print("Sunrise:", local.next_rising(ephem.Sun()).datetime())
print("Sunset:", local.next_setting(ephem.Sun()).datetime())
next_sunrise_datetime = local.next_rising(ephem.Sun()).datetime()
next_sunset_datetime = local.next_setting(ephem.Sun()).datetime()

# If it is daytime, we will see a sunset sooner than a sunrise.
it_is_day = next_sunset_datetime < next_sunrise_datetime
print("It's day." if it_is_day else "It's night.")

# If it is nighttime, we will see a sunrise sooner than a sunset.
it_is_night = next_sunrise_datetime < next_sunset_datetime
print("It's night." if it_is_night else "It's day.")

#if nextSet < nextRise:
#	print("Day Time")
Exemple #26
0
def getVernalEquinox( n ):
    result = RPNDateTime.convertFromEphemDate( ephem.next_equinox( str( n ) ) )
    return result.getLocalTime( )
Exemple #27
0
 def getNextSolstice(self):
     dateNowString = datetime.datetime.utcnow().strftime("%Y/%m/%d %H:%M")
     solsticeEphem = ephem.next_equinox(dateNowString)
     return self._convertEphemTimeToLocalTime(solsticeEphem)
Exemple #28
0
def get_data(object_list: List[Tuple[ephem.Body, str]],
             location: Optional[ephem.Observer] = None) -> list:
    """Create data dictionary for object list."""
    body_data = {}
    if location:
        body_data['query_date'] = location.date.datetime()
    for o, body_type in object_list:
        if location:
            o.compute(location)
        else:
            o.compute()
        data = {
            # Split name if multiple designations are given. The separator is a pipe (|).
            'name': o.name.split('|') if o.name.find('|') >= 0 else o.name,
            'ra': format_ra(o.ra),
            'dec': format_angle(o.dec),
            'size': o.size,
            'mag': o.mag,
            'elong': o.elong,
        }
        if location: # altitude and azimuth only available with a valid location
            data['alt'] = format_angle(o.alt)
            data['az'] = format_angle(o.az)
        if body_type == 'star': # spectral type is (usually) available with a star body type
            data['spectral_type'] = o._spect
        if body_type == 'solar_system': # special properties available for solar system objects
            data['earth_dist'] = {
                'au': o.earth_distance,
                'km': o.earth_distance * 149597870.700,
                'mi': o.earth_distance * 149597870700 / 1604.344
            }
            data['constellation'] = ephem.constellation(o)
            # date for calculations below
            date = location.date if location else ephem.now()
            if o.name != 'Sun': # we don't need "phase" or "sun_dist" for the sun itself
                data['sun_dist'] = {
                    'au': o.sun_distance,
                    'km': o.sun_distance * 149597870.700,
                    'mi': o.sun_distance * 149597870700 / 1604.344
                }
                data['phase'] = o.phase
            if o.name == 'Moon': # special properties available for the moon
                data['illuminated_surface'] = o.moon_phase * 100
                data['phase_name'] = get_phase_name(location)
                data['next_new_moon'] = (ephem.next_new_moon(date)).datetime()
                data['next_first_quarter'] = (ephem.next_first_quarter_moon(date)).datetime()
                data['next_full_moon'] = (ephem.next_full_moon(date)).datetime()
                data['next_last_quarter'] = (ephem.next_last_quarter_moon(date)).datetime()
            if o.name == 'Sun': # special properties available for the sun
                data['next_solstice'] = (ephem.next_solstice(date)).datetime()
                data['next_equinox'] = (ephem.next_equinox(date)).datetime()
        elif body_type == 'satellite': # special properties available for satellites
            data['elev'] = {'m' :o.elevation, 'mi': o.elevation / 1604.344}
            data['eclipsed'] = o.eclipsed
            if location:
                data['range'] = {'m': o.range, 'mi': o.range / 1604.344}
                data['range_velocity'] = o.range_velocity
                rise_time, rise_az, max_alt_time, max_alt, set_time, set_az = location.next_pass(o)
                data['next_pass'] = {
                    'rise_time': rise_time.datetime(),
                    'rise_az': format_angle(rise_az),
                    'max_altitude_time': max_alt_time.datetime(),
                    'max_altitude': format_angle(max_alt),
                    'set_time': set_time.datetime(),
                    'set_az': format_angle(set_az),
                }
        elif body_type == 'planetary_moon': # special properties available for planetary moons
            data['visible'] = o.earth_visible
            data['pos'] = o.x, o.y, o.z
        # computed last, since these calculations change time, body position
        if body_type not in ['satellite', 'planetary_moon'] and location:
            # compute antitransit time of object
            antitransit = location.previous_antitransit(o)
            data['rise_time'] = (location.next_rising(o, start = antitransit)).datetime()
            data['rise_az'] = format_angle(o.az)
            data['transit_time'] = (location.next_transit(o, start = antitransit)).datetime()
            data['transit_alt'] = format_angle(o.alt)
            data['set_time'] = (location.next_setting(o, start = antitransit)).datetime()
            data['set_az'] = format_angle(o.az)
        if o.name == 'Sun':
            # computed last, since these calculations change the horizon
            location.horizon = '-18'
            astro_dawn = location.next_rising(o, start = antitransit)
            astro_dusk = location.next_setting(o, start = antitransit)
            location.horizon = '-12'
            nautical_dawn  = location.next_rising(o, start = antitransit)
            nautical_dusk = location.next_setting(o, start = antitransit)
            location.horizon = '-6'
            civil_dawn = location.next_rising(o, start = antitransit)
            civil_dusk = location.next_setting(o, start = antitransit)
            # The US Naval Observatory uses -34' as a constant for sunrise/sunset,
            # rather than using atmospheric refraction.
            # Setting pressure to 0 has the effect of ignoring effects of refraction.
            # Save pressure for reset after calculations.
            pressure, location.pressure = location.pressure, 0
            location.horizon = '-0:34'
            usno_dawn = location.next_rising(o, start = antitransit)
            usno_dusk = location.next_setting(o, start = antitransit)
            data['astronomical_dawn'] = astro_dawn.datetime()
            data['nautical_dawn'] = nautical_dawn.datetime()
            data['civil_dawn'] = civil_dawn.datetime()
            data['USNO_sunrise'] = usno_dawn.datetime()
            data['USNO_sunset'] = usno_dusk.datetime()
            data['civil_dusk'] = civil_dusk.datetime()
            data['nautical_dusk'] = nautical_dusk.datetime()
            data['astronomical_dusk'] = astro_dusk.datetime()
            #reset pressure and horizon
            location.pressure = pressure
            location.horizon = 0
        body_data[o.name] = data
    return body_data
Exemple #29
0
def extended_denmark(years=False,
                     sun=False,
                     moon=False,
                     week=False,
                     time=False,
                     outformat='text'):
    """Extends the official public holidays of Denmark"""

    # Populate the holiday list with the default DK holidays
    holidays_dk = holidays.Denmark(years=years)

    # Extend with other dates
    for year in years:
        if week:
            weeknumbers = WeekNumber(year)
            for key in weeknumbers.weeknumbers:
                holidays_dk.append({key: weeknumbers.weeknumbers[key]})

        if sun:
            sun_rise_sun_set = SunRiseSunSet(year, outformat=outformat)
            for key in sorted(sun_rise_sun_set.sun_rise_sun_set):
                holidays_dk.append(
                    {key: sun_rise_sun_set.sun_rise_sun_set[key]})

        if moon:
            moon_phases = MoonPhases(year, outformat=outformat)
            for key in sorted(moon_phases.moon_phases):
                holidays_dk.append({key: moon_phases.moon_phases[key]})

        # Equinoxes and solstices
        spring_equinox = ephem.next_equinox(str(year))
        summer_solstice = ephem.next_solstice(spring_equinox)
        fall_equinox = ephem.next_equinox(summer_solstice)
        winter_solstice = ephem.next_solstice(fall_equinox)
        # Bright nights, nights when sun is not under 18 deg below horizon
        brightnights = bright_nights(year)
        holidays_dk.append({brightnights[0]: 'Lyse nætter begynder'})
        holidays_dk.append({brightnights[1]: 'Lyse nætter slutter'})

        if time:
            holidays_dk.append({
                utc2localtime(spring_equinox.datetime()):
                'Forårsjævndøgn %s' %
                utc2localtime(spring_equinox.datetime(), format='hhmm')
            })
            holidays_dk.append({
                utc2localtime(summer_solstice.datetime()):
                'Sommersolhverv %s' %
                utc2localtime(summer_solstice.datetime(), format='hhmm')
            })
            holidays_dk.append({
                utc2localtime(fall_equinox.datetime()):
                'Efterårsjævndøgn %s' %
                utc2localtime(fall_equinox.datetime(), format='hhmm')
            })
            holidays_dk.append({
                utc2localtime(winter_solstice.datetime()):
                'Vintersolhverv %s' %
                utc2localtime(winter_solstice.datetime(), format='hhmm')
            })
        else:
            holidays_dk.append({
                utc2localtime(spring_equinox.datetime()):
                'Forårsjævndøgn'
            })
            holidays_dk.append(
                {utc2localtime(summer_solstice.datetime()): 'Sommersolhverv'})
            holidays_dk.append({
                utc2localtime(fall_equinox.datetime()):
                'Efterårsjævndøgn'
            })
            holidays_dk.append(
                {utc2localtime(winter_solstice.datetime()): 'Vintersolhverv'})

        # Add other Danish holidays and events
        holidays_dk.append({datetime.date(year, 1, 6): 'Helligtrekonger'})
        holidays_dk.append({datetime.date(year, 2, 2): 'Kyndelmisse'})
        holidays_dk.append({datetime.date(year, 2, 14): 'Valentinsdag'})
        holidays_dk.append(
            {datetime.date(year, 3, 8): 'Kvindernes internationale kampdag'})
        holidays_dk.append({easter(year) + rd(weekday=SU(-8)): 'Fastelavn'})
        holidays_dk.append({easter(year) + rd(weekday=SU(-2)): 'Palmesøndag'})
        holidays_dk.append(
            {datetime.date(year, 4, 9): 'Danmarks besættelse (1940)'})
        holidays_dk.append({
            datetime.date(year, 3, 31) + rd(weekday=SU(-1)):
            'Sommertid begynder'
        })  # Last sunday in March
        holidays_dk.append(
            {datetime.date(year, 5, 1) + rd(weekday=SU(+2)): 'Mors dag'})
        holidays_dk.append(
            {datetime.date(year, 5, 1): 'Arbejdernes internationale kampdag'})
        holidays_dk.append({datetime.date(year, 5, 9): 'Europadag'})
        holidays_dk.append({datetime.date(year, 6, 15): 'Valdemarsdag'})
        holidays_dk.append({datetime.date(year, 6, 23): 'Sankthansaften'})
        holidays_dk.append({datetime.date(year, 6, 24): 'Sankthansdag'})
        holidays_dk.append(
            {datetime.date(year, 5, 4): 'Danmarks befrielsesaften'})
        holidays_dk.append(
            {datetime.date(year, 5, 5): 'Danmarks befrielse (1945)'})
        holidays_dk.append({datetime.date(year, 6, 5): 'Fars dag'})
        holidays_dk.append({datetime.date(year, 6, 5): 'Grundlovsdag'})
        holidays_dk.append({datetime.date(year, 10, 31): 'Halloween'})
        holidays_dk.append({datetime.date(year, 11, 10): 'Mortensaften'})
        holidays_dk.append({datetime.date(year, 11, 11): 'Mortensdag'})
        holidays_dk.append({
            datetime.date(year, 11, 1) + rd(weekday=SU(+1)):
            'Allehelgensdag'
        })
        holidays_dk.append({
            datetime.date(year, 10, 31) + rd(weekday=SU(-1)):
            'Sommertid slutter'
        })  # Last sunday in October
        holidays_dk.append({datetime.date(year, 12, 13): 'Sankta Lucia'})
        for i in range(4):
            holidays_dk.append({
                datetime.date(year, 12, 24) + rd(weekday=SU(-(i + 1))):
                '%s. søndag i advent' % abs(4 - i)
            })

        holidays_dk.append({datetime.date(year, 12, 24): 'Juleaftensdag'})
        holidays_dk.append({datetime.date(year, 12, 31): 'Nytårsaftensdag'})

    return holidays_dk
Exemple #30
0
def ecliptlong(year, month, day, do_print=False):
   # See https://en.wikipedia.org/wiki/Position_of_the_Sun#Ecliptic_coordinates
   # Days since Jan 1, 2000:
    n = sum(list(gcal2jd(year,month,day)) + [0.5]) - 2451545.0
    L = 280.460 + 0.9856474 * n
    while L > 360.:
        L -= 360.
    while L < 0.:
        L += 360.

    L_rad = (L / 180.) * pi
    g = 357.528 + 0.9856003 * n
    while g > 360.:
        g -= 360.
    while g < 0.:
        g += 360.
    g_rad = (g / 180.) * pi

    lam = L + 1.915 * sin(g_rad) + 0.020 * sin(2*g_rad)

    while lam > 360.:
        lam -= 360.

    if (do_print):
        seasons = { 0:'SPRING',
                    1:'SUMMER',
                    2:'AUTUMN',
                    3:'WINTER' }

        astrosign = lam / 30.
        octant = lam / 45.
        season = seasons[int(octant//2) % 4]
        xquarter = seasons[((octant+1)%8)//2]
        print("For day = {:04}/{:02}/{:02}:".format(year, month,day))
        print("ecliptic longitude =", lam)
        print("astrological sign position =", astrosign)
        print("ecliptic octant =", octant)
        print("astronomical season =", season)
        print("cross-quarter season =", xquarter)
        try:
            from convertdate import persian
            pyear, pmonth, pday = persian.from_gregorian(year, month, day)
            print("Persian date = {} {}, {}".format(pday,
                                                    {1:'aries',
                                                     2:'taurus',
                                                     3:'gemini',
                                                     4:'cancer',
                                                     5:'leo',
                                                     6:'virgo',
                                                     7:'libra',
                                                     8:'scorpio',
                                                     9:'sagittarius',
                                                     10:'capricorn',
                                                     11:'aquarius',
                                                     12:'pisces'}[pmonth],
                                                    pyear))
        except:
            pass
        try:
            import ephem
            sun = ephem.Sun()
            ymdstr = "{:04}/{:02}/{:02}".format(year, month, day)
            sun.compute(ymdstr, ymdstr)
            eph_lam = float(ephem.Ecliptic(sun).lon) / pi * 180.
            eph_sign = eph_lam / 30.
            print("ephem ecliptic longitude =", eph_lam)
            print("ephem astrological sign position =", eph_sign)
            print("ephem previous solstice =",
                  ephem.previous_solstice(ymdstr))
            print("ephem previous equinox =",
                  ephem.previous_equinox(ymdstr))
            print("ephem next solstice =",
                  ephem.next_solstice(ymdstr))
            print("ephem next equinox =",
                  ephem.next_equinox(ymdstr))
        except:
            pass

    return lam
def extended_denmark(years=False, sun=False, moon=False, week=False,
                     time=False, outformat='text'):
    """Extends the official public holidays of Denmark"""

    # Populate the holiday list with the default DK holidays
    holidays_dk = holidays.Denmark(years=years)

    # Extend with other dates
    for year in years:
        if week:
            weeknumbers = WeekNumber(year)
            for key in weeknumbers.weeknumbers:
                holidays_dk.append({key: weeknumbers.weeknumbers[key]})

        if sun:
            sun_rise_sun_set = SunRiseSunSet(year)
            for key in sorted(sun_rise_sun_set.sun_rise_sun_set):
                holidays_dk.append({key:
                                       sun_rise_sun_set.sun_rise_sun_set[key]})

        if moon:
            moon_phases = MoonPhases(year, outformat=outformat)
            for key in sorted(moon_phases.moon_phases):
                holidays_dk.append({key: moon_phases.moon_phases[key]})

        # Equinoxes and solstices
        spring_equinox = ephem.next_equinox(str(year))
        summer_solstice = ephem.next_solstice(spring_equinox)
        fall_equinox = ephem.next_equinox(summer_solstice)
        winter_solstice = ephem.next_solstice(fall_equinox)
        # Bright nights, nights when sun is not under 18 deg below horizon
        brightnights = bright_nights(year)
        holidays_dk.append({brightnights[0]: 'Lyse nætter begynder'})
        holidays_dk.append({brightnights[1]: 'Lyse nætter slutter'})

        if time:
            holidays_dk.append({utc2localtime(spring_equinox.datetime()):
                           'Forårsjævndøgn %s' %
                       utc2localtime(spring_equinox.datetime(),
                                     format='hhmm')})
            holidays_dk.append({utc2localtime(summer_solstice.datetime()):
                           'Sommersolhverv %s' %
                       utc2localtime(summer_solstice.datetime(),
                                     format='hhmm')})
            holidays_dk.append({utc2localtime(fall_equinox.datetime()):
                           'Efterårsjævndøgn %s' %
                       utc2localtime(fall_equinox.datetime(),
                                     format='hhmm')})
            holidays_dk.append({utc2localtime(winter_solstice.datetime()):
                           'Vintersolhverv %s' %
                       utc2localtime(winter_solstice.datetime(),
                                     format='hhmm')})
        else:
            holidays_dk.append({utc2localtime(spring_equinox.datetime()): 'Forårsjævndøgn'})
            holidays_dk.append({utc2localtime(summer_solstice.datetime()): 'Sommersolhverv'})
            holidays_dk.append({utc2localtime(fall_equinox.datetime()): 'Efterårsjævndøgn'})
            holidays_dk.append({utc2localtime(winter_solstice.datetime()): 'Vintersolhverv'})

        # Add other Danish holidays and events
        holidays_dk.append({datetime.date(year, 1, 6): 'Helligtrekonger'})
        holidays_dk.append({datetime.date(year, 2, 2): 'Kyndelmisse'})
        holidays_dk.append({datetime.date(year, 2, 14): 'Valentinsdag'})
        holidays_dk.append({datetime.date(year, 3, 8): 'Kvindernes internationale kampdag'})
        holidays_dk.append({easter(year) + rd(weekday=SU(-8)): 'Fastelavn'})
        holidays_dk.append({easter(year) + rd(weekday=SU(-2)): 'Palmesøndag'})
        holidays_dk.append({datetime.date(year, 4, 9): 'Danmarks besættelse (1940)'})
        holidays_dk.append({datetime.date(year, 3, 31) + rd(weekday=SU(-1)): 'Sommertid begynder'}) # Last sunday in March
        holidays_dk.append({datetime.date(year, 5, 1) + rd(weekday=SU(+2)): 'Mors dag'})
        holidays_dk.append({datetime.date(year, 5, 1): 'Arbejdernes internationale kampdag'})
        holidays_dk.append({datetime.date(year, 5, 9): 'Europadag'})
        holidays_dk.append({datetime.date(year, 6, 15): 'Valdemarsdag'})
        holidays_dk.append({datetime.date(year, 6, 23): 'Sankthansaften'})
        holidays_dk.append({datetime.date(year, 6, 24): 'Sankthansdag'})
        holidays_dk.append({datetime.date(year, 5, 4): 'Danmarks befrielsesaften'})
        holidays_dk.append({datetime.date(year, 5, 5): 'Danmarks befrielse (1945)'})
        holidays_dk.append({datetime.date(year, 6, 5): 'Fars dag'})
        holidays_dk.append({datetime.date(year, 6, 5): 'Grundlovsdag'})
        holidays_dk.append({datetime.date(year, 10, 31): 'Halloween'})
        holidays_dk.append({datetime.date(year, 11, 10): 'Mortensaften'})
        holidays_dk.append({datetime.date(year, 11, 11): 'Mortensdag'})
        holidays_dk.append({datetime.date(year, 11, 1) + rd(weekday=SU(+1)): 'Allehelgensdag'})
        holidays_dk.append({datetime.date(year, 10, 31) + rd(weekday=SU(-1)): 'Sommertid slutter'}) # Last sunday in October
        holidays_dk.append({datetime.date(year, 12, 13): 'Sankta Lucia'})
        for i in range(4):
            holidays_dk.append({datetime.date(year, 12, 24) +
                                rd(weekday=SU(-(i+1))):
                                    '%s. søndag i advent' % abs(4-i)})

        holidays_dk.append({datetime.date(year, 12, 24): 'Juleaftensdag'})
        holidays_dk.append({datetime.date(year, 12, 31): 'Nytårsaftensdag'})

    return holidays_dk
def background_thread():
    while True:
        # update location
        location = get_location()

        # init observer
        home = ephem.Observer()

        # set geo position
        home.lat = location[0]
        home.lon = location[1]
        home.elevation = float(location[2])

        # update time
        t = datetime.datetime.utcnow()
        home.date = t

        polaris_data = get_polaris_data(home)

        socketio.emit(
            'celestialdata', {
                'latitude':
                "%s" % home.lat,
                'longitude':
                "%s" % home.lon,
                'elevation':
                "%.2f" % home.elevation,
                'city':
                location[3],
                'alias':
                location[4],
                'mode':
                location[5],
                'polaris_hour_angle':
                polaris_data[0],
                'polaris_next_transit':
                "%s" % polaris_data[1],
                'polaris_alt':
                "%.2f°" % numpy.degrees(polaris_data[2]),
                'moon_phase':
                "%s" % get_moon_phase(home),
                'moon_light':
                "%d" % ephem.Moon(home).phase,
                'moon_rise':
                "%s" % get_body_positions(home, ephem.Moon(home))[0],
                'moon_transit':
                "%s" % get_body_positions(home, ephem.Moon(home))[1],
                'moon_set':
                "%s" % get_body_positions(home, ephem.Moon(home))[2],
                'moon_az':
                "%.2f°" % numpy.degrees(ephem.Moon(home).az),
                'moon_alt':
                "%.2f°" % numpy.degrees(ephem.Moon(home).alt),
                'moon_ra':
                "%s" % ephem.Moon(home).ra,
                'moon_dec':
                "%s" % ephem.Moon(home).dec,
                'moon_new':
                "%s" % ephem.localtime(
                    ephem.next_new_moon(t)).strftime("%Y-%m-%d %H:%M:%S"),
                'moon_full':
                "%s" % ephem.localtime(
                    ephem.next_full_moon(t)).strftime("%Y-%m-%d %H:%M:%S"),
                'sun_at_start':
                get_sun_twilights(home)[2][0],
                'sun_ct_start':
                get_sun_twilights(home)[0][0],
                'sun_rise':
                "%s" % get_body_positions(home, ephem.Sun(home))[0],
                'sun_transit':
                "%s" % get_body_positions(home, ephem.Sun(home))[1],
                'sun_set':
                "%s" % get_body_positions(home, ephem.Sun(home))[2],
                'sun_ct_end':
                get_sun_twilights(home)[0][1],
                'sun_at_end':
                get_sun_twilights(home)[2][1],
                'sun_az':
                "%.2f°" % numpy.degrees(ephem.Sun(home).az),
                'sun_alt':
                "%.2f°" % numpy.degrees(ephem.Sun(home).alt),
                'sun_ra':
                "%s" % ephem.Sun(home).ra,
                'sun_dec':
                "%s" % ephem.Sun(home).dec,
                'sun_equinox':
                "%s" % ephem.localtime(
                    ephem.next_equinox(t)).strftime("%Y-%m-%d %H:%M:%S"),
                'sun_solstice':
                "%s" % ephem.localtime(
                    ephem.next_solstice(t)).strftime("%Y-%m-%d %H:%M:%S"),
                'mercury_rise':
                "%s" % get_body_positions(home, ephem.Mercury(home))[0],
                'mercury_transit':
                "%s" % get_body_positions(home, ephem.Mercury(home))[1],
                'mercury_set':
                "%s" % get_body_positions(home, ephem.Mercury(home))[2],
                'mercury_az':
                "%.2f°" % numpy.degrees(ephem.Mercury(home).az),
                'mercury_alt':
                "%.2f°" % numpy.degrees(ephem.Mercury(home).alt),
                'venus_rise':
                "%s" % get_body_positions(home, ephem.Venus(home))[0],
                'venus_transit':
                "%s" % get_body_positions(home, ephem.Venus(home))[1],
                'venus_set':
                "%s" % get_body_positions(home, ephem.Venus(home))[2],
                'venus_az':
                "%.2f°" % numpy.degrees(ephem.Venus(home).az),
                'venus_alt':
                "%.2f°" % numpy.degrees(ephem.Venus(home).alt),
                'mars_rise':
                "%s" % get_body_positions(home, ephem.Mars(home))[0],
                'mars_transit':
                "%s" % get_body_positions(home, ephem.Mars(home))[1],
                'mars_set':
                "%s" % get_body_positions(home, ephem.Mars(home))[2],
                'mars_az':
                "%.2f°" % numpy.degrees(ephem.Mars(home).az),
                'mars_alt':
                "%.2f°" % numpy.degrees(ephem.Mars(home).alt),
                'jupiter_rise':
                "%s" % get_body_positions(home, ephem.Jupiter(home))[0],
                'jupiter_transit':
                "%s" % get_body_positions(home, ephem.Jupiter(home))[1],
                'jupiter_set':
                "%s" % get_body_positions(home, ephem.Jupiter(home))[2],
                'jupiter_az':
                "%.2f°" % numpy.degrees(ephem.Jupiter(home).az),
                'jupiter_alt':
                "%.2f°" % numpy.degrees(ephem.Jupiter(home).alt),
                'saturn_rise':
                "%s" % get_body_positions(home, ephem.Saturn(home))[0],
                'saturn_transit':
                "%s" % get_body_positions(home, ephem.Saturn(home))[1],
                'saturn_set':
                "%s" % get_body_positions(home, ephem.Saturn(home))[2],
                'saturn_az':
                "%.2f°" % numpy.degrees(ephem.Saturn(home).az),
                'saturn_alt':
                "%.2f°" % numpy.degrees(ephem.Saturn(home).alt),
                'uranus_rise':
                "%s" % get_body_positions(home, ephem.Uranus(home))[0],
                'uranus_transit':
                "%s" % get_body_positions(home, ephem.Uranus(home))[1],
                'uranus_set':
                "%s" % get_body_positions(home, ephem.Uranus(home))[2],
                'uranus_az':
                "%.2f°" % numpy.degrees(ephem.Uranus(home).az),
                'uranus_alt':
                "%.2f°" % numpy.degrees(ephem.Uranus(home).alt),
                'neptune_rise':
                "%s" % get_body_positions(home, ephem.Neptune(home))[0],
                'neptune_transit':
                "%s" % get_body_positions(home, ephem.Neptune(home))[1],
                'neptune_set':
                "%s" % get_body_positions(home, ephem.Neptune(home))[2],
                'neptune_az':
                "%.2f°" % numpy.degrees(ephem.Neptune(home).az),
                'neptune_alt':
                "%.2f°" % numpy.degrees(ephem.Neptune(home).alt)
            })
        socketio.sleep(10)
Exemple #33
0
        ve = ephem.next_vernal_equinox(s)
        lm = 0

    lm += 1
    if p is not None:
        dif = (s - p)

    p = s

    print "%d\t%d\t-\t%s" % (lm, dif, ephem.localtime(s))

    #print "%d - %d,%d, date: %s, next sunrise: %s" % (lm, dif2, dif, d, s )

dl = "-7"
for idx in range(0, 2):
    dl = ephem.next_equinox(dl)
    moon = ephem.Moon(dl)
    d = dl.datetime()

    abr, const_name = ephem.constellation(moon)
    #print "constellation: %s dow: %s date: %s - GEOCENTRIC(%d,%d), Phase: %d " % ( const_name, daysofweek[d.weekday()], dl, moon.hlat,moon.hlon, moon.moon_phase )
    print """
Date: %s : %s
Moon Phase: %f / Constellation: %s
Lat: %f, Long: %f""" % (
        dl,
        daysofweek[d.weekday()],
        moon.moon_phase,
        const_name,
        moon.hlat,
        moon.hlon,
Exemple #34
0

#define days & years
today = date.today()  
working_date = datetime.today()
#define solstices & equinoxes
last_solstice = ephem.previous_solstice(today) #calculate solstice date
last_solstice = last_solstice.datetime() #convert to datetime

previous_equinox = ephem.previous_equinox(today) #calculate equinox date
previous_equinox = previous_equinox.datetime() #convert to datetime

next_solstice = ephem.next_solstice(today) #calculate solstice date
next_solstice = next_solstice.datetime() #convert to datetime

next_equinox = ephem.next_equinox(today) #calculate equinox date
next_equinox = next_equinox.datetime() #convert to datetime

#calculate cross-quarter high days
def cross_quarter(last, next):
    midpoint=abs((next-last))/2
    midpoint=next-midpoint
    if last < midpoint < next: #this insures that midpoint falls between
        return midpoint        #the two endpoints 
    else:
        midpoint=abs((next-last))/2
        midpoint=last-midpoint
        return midpoint    

a_crossquarter = cross_quarter(last_solstice, previous_equinox)
b_crossquarter = cross_quarter(previous_equinox, next_solstice)
Exemple #35
0
def getAutumnalEquinox( n ):
    result = RPNDateTime.convertFromEphemDate( ephem.next_equinox( str( n ) + '-07-01' ) )
    return result.getLocalTime( )
Exemple #36
0
def getAutumnalEquinox( n ):
    '''Returns the date of the next autumnal equinox after n.'''
    result = RPNDateTime.convertFromEphemDate( ephem.next_equinox( str( n ) + '-07-01' ) )
    return result.getLocalTime( )
Exemple #37
0
"""if I am going to package this for anyone else to use, i am going to need to package pyephem as well"""

#define days & years
today = date.today()
working_date = datetime.today()
#define solstices & equinoxes
last_solstice = ephem.previous_solstice(today)  #calculate solstice date
last_solstice = last_solstice.datetime()  #convert to datetime

previous_equinox = ephem.previous_equinox(today)  #calculate equinox date
previous_equinox = previous_equinox.datetime()  #convert to datetime

next_solstice = ephem.next_solstice(today)  #calculate solstice date
next_solstice = next_solstice.datetime()  #convert to datetime

next_equinox = ephem.next_equinox(today)  #calculate equinox date
next_equinox = next_equinox.datetime()  #convert to datetime


#calculate cross-quarter high days
def cross_quarter(last, next):
    midpoint = abs((next - last)) / 2
    midpoint = next - midpoint
    if last < midpoint < next:  #this insures that midpoint falls between
        return midpoint  #the two endpoints
    else:
        midpoint = abs((next - last)) / 2
        midpoint = last - midpoint
        return midpoint

# -*- coding: utf-8 -*-
"""
Created on Sat Jun 13 14:02:04 2020
https://rhodesmill.org/pyephem/quick.html#equinoxes-solstices
@author: PC
"""

import ephem

d1 = ephem.next_equinox('2000')
print(d1)
d2 = ephem.next_solstice(d1)
print(d2)
t = d2 - d1
print("Spring lasted %.1f days" % t)

print(ephem.previous_solstice('2000'))
print(ephem.next_solstice('2000'))

print(ephem.previous_equinox('2000'))
print(ephem.next_equinox('2000'))

print(ephem.previous_vernal_equinox('2000'))
print(ephem.next_vernal_equinox('2000'))
Exemple #39
0
    climate51[ "%02i%02i" % (  lts.month, lts.day)] = row[1]

ccursor.execute("""SELECT day, high from alldata_ia where
 station = 'IA8706' and month in (2,3,4)""")
data = {}
for row in ccursor:
    lts = row[0]
    data[ "%s%02i%02i" % ( lts.year, lts.month, lts.day)] = row[1]
data['20130328'] = 48
data['20130329'] = 100

years = []
start = []
end = []
for yr in range(1900,2014):
    d1 = ephem.next_equinox(str(yr))
    ts = datetime.datetime.strptime(str(d1), '%Y/%m/%d %H:%M:%S')
    ts = ts.replace(tzinfo=pytz.timezone("UTC"))
    lts = ts.astimezone( pytz.timezone("America/Chicago"))
    
    if (data["%s%02i%02i" % ( lts.year, lts.month, lts.day)] >
        climate51["%02i%02i" % (  lts.month, lts.day)]):
        continue
    years.append( yr )
    lts2 = lts
    print yr,
    print lts,
    while (data["%s%02i%02i" % ( lts2.year, lts2.month, lts2.day)] <
        climate51["%02i%02i" % (  lts2.month, lts2.day)]):
        lts2 -= datetime.timedelta(days=1)
    start.append( int((lts2 + datetime.timedelta(days=1)).strftime("%j")) )
Exemple #40
0
def find_alignments(observer, waypoints, year, allpoints=False):
    '''Find all the alignments with solstice/equinox sun/moon rise/set.
       Returns a dict: { 'vernal equinox': { 'moon': { 'rise': 94.17... } } }
       of azimuth angles in decimal degrees
    '''
    azimuths = {}

    # start_date = ephem.Date('%d/1/1' % year)
    start_date = ephem.Date((year, 1, 1))
    # date= ephem.date((-59000,1,1))

    observer.date = ephem.next_equinox(start_date)
    azimuths['vernal equinox'] = find_azimuths(observer)

    observer.date = ephem.next_solstice(observer.date)
    azimuths['summer solstice'] = find_azimuths(observer)

    observer.date = ephem.next_equinox(observer.date)
    azimuths['autumnal equinox'] = find_azimuths(observer)

    observer.date = ephem.next_solstice(observer.date)
    azimuths['winter solstice'] = find_azimuths(observer)

    # pprint(azimuths)

    # How many degrees is close enough?
    DEGREESLOP = 2.

    # If allpoints is set, check angles among all pairs of points.
    # Otherwise, only check angles from observer to other points.
    if allpoints:
        print("Looking for alignments among all points")
        observer_points = waypoints
    else:
        observer_points = [ [ observer.name,
                              observer.lat / ephem.degree,
                              observer.lon / ephem.degree,
                              observer.elevation ] ]

    # Now go through all the angles between waypoints and see if
    # any of them correspond to any of the astronomical angles.
    matches = []
    for wp1 in observer_points:
        print("\nChecking observer", wp1)
        for wp2 in waypoints:
            if wp1 == wp2:
                continue
            angle = bearing_to(wp1, wp2)
            print("  ... vs", wp2, angle)

            # Does that angle match any of our astronomical ones?
            for season in azimuths:  # vernal equinox, etc.
                for body in azimuths[season]:  # sun, full moon
                    for event in azimuths[season][body]:  # rise, set
                        event_az = azimuths[season][body][event]['az']
                        if abs(event_az - angle) < DEGREESLOP:
                            matches.append({
                                'observer': wp1[0],
                                'target': wp2[0],
                                'event': '%s %s%s' % (season, body, event),
                                'azimuth': event_az,
                                'slop': event_az - angle,
                                'time': azimuths[season][body][event]['time'],
                                'latitude': wp2[1],
                                'longitude': wp2[2],
                            })

    return matches