Пример #1
0
def get_phase_name(location: Optional[ephem.Observer] = None, wiggle_room: float = 1.5) -> str:
    """Return name of the phase of the moon."""
    if location:
        date = location.date
    else:
        date = ephem.now()
    if abs(ephem.next_first_quarter_moon(date) - date) < wiggle_room or \
            abs(ephem.previous_first_quarter_moon(date) - date) < wiggle_room:
        return 'first quarter moon'
    elif abs(ephem.next_full_moon(date) - date) < wiggle_room or \
            abs(ephem.previous_full_moon(date) - date) < wiggle_room:
        return 'full moon'
    elif abs(ephem.next_last_quarter_moon(date) - date) < wiggle_room or \
            abs(ephem.previous_last_quarter_moon(date) - date) < wiggle_room:
        return 'last quarter moon'
    elif abs(ephem.next_new_moon(date) - date) < wiggle_room or \
            abs(ephem.previous_new_moon(date) - date) < wiggle_room:
        return 'new moon'
    elif ephem.next_first_quarter_moon(date) - ephem.previous_new_moon(date) < 29:
        return 'waxing crescent'
    elif ephem.next_full_moon(date) - ephem.previous_first_quarter_moon(date) < 29:
        return 'waxing gibbous'
    elif ephem.next_last_quarter_moon(date) - ephem.previous_full_moon(date) < 29:
        return 'waning gibbous'
    elif ephem.next_new_moon(date) - ephem.previous_last_quarter_moon(date) < 29:
        return 'waning crescent'
    return ''
Пример #2
0
    def __init__(self, year, timezone='Europe/Copenhagen', outformat='text'):
        """Compute moon phases for a whole year"""
        # Backtrack and look ahead to be sure to catch moons around newyear
        start_date = ephem.Date((year - 1, 9, 1))
        end_date = ephem.Date((year + 1, 3, 1))
        self.moon_phases = {}
        new_moon = ephem.next_new_moon(start_date)
        first_quarter = ephem.next_first_quarter_moon(start_date)
        full_moon = ephem.next_full_moon(start_date)
        last_quarter = ephem.next_last_quarter_moon(start_date)
        while True:
            local_new_moon = utc2localtime(new_moon.datetime())
            local_first_quarter = utc2localtime(first_quarter.datetime())
            local_full_moon = utc2localtime(full_moon.datetime())
            local_last_quarter = utc2localtime(last_quarter.datetime())
            if local_new_moon.year == year:
                self.moon_phases[local_new_moon] = \
                    self.moon_phase_names('new_moon', outformat)
            if local_first_quarter.year == year:
                self.moon_phases[local_first_quarter] = \
                    self.moon_phase_names('first_quarter', outformat)
            if local_full_moon.year == year:
                self.moon_phases[local_full_moon] = \
                    self.moon_phase_names('full_moon', outformat)
            if local_last_quarter.year == year:
                self.moon_phases[local_last_quarter] = \
                    self.moon_phase_names('last_quarter', outformat)

            new_moon = ephem.next_new_moon(new_moon)
            first_quarter = ephem.next_first_quarter_moon(first_quarter)
            full_moon = ephem.next_full_moon(full_moon)
            last_quarter = ephem.next_last_quarter_moon(last_quarter)
            if (new_moon > end_date) and (first_quarter > end_date) and \
               (full_moon > end_date) and (last_quarter > end_date):
                break
Пример #3
0
def get_moons_in_year(year, month, day):
    """Returns a list of the full moons, first quarter moons, last quarter moons and new moons in a year."""
    moons = []

    date = ephem.Date(datetime.date(year, month, day))
    while date.datetime().year == year:
        date = ephem.next_full_moon(date)
        moons.append((date, 'Luna Llena'))

    date = ephem.Date(datetime.date(year, month, day))
    while date.datetime().year == year:
        date = ephem.next_first_quarter_moon(date)
        moons.append((date, 'Cuarto Creciente'))

    date = ephem.Date(datetime.date(year, month, day))
    while date.datetime().year == year:
        date = ephem.next_last_quarter_moon(date)
        moons.append((date, 'Cuarto Menguante'))

    date = ephem.Date(datetime.date(year, month, day))
    while date.datetime().year == year:
        date = ephem.next_new_moon(date)
        moons.append((date, 'Luna Nueva'))

    moons_sorted = sorted(moons, key=lambda x: x[0].datetime())

    moons_in_year = []

    for i in moons_sorted:
        moons_in_year.append((i[0].datetime().ctime(), i[1]))

    return moons_in_year
Пример #4
0
def getMoonPhases():
    date = ephem.now()
    new_moon = str(ephem.next_new_moon(date))
    first_quarter_moon = str(ephem.next_first_quarter_moon(date))
    full_moon = str(ephem.next_full_moon(date))
    last_quarter_moon = str(ephem.next_last_quarter_moon(date))
    return new_moon, first_quarter_moon, full_moon, last_quarter_moon
Пример #5
0
 def __init__(self):
     self.__logger = logging.getLogger(self.__class__.__name__)
     #find current moon phase
     now = ephem.now()
     new_date = ephem.next_new_moon(now)
     first_quarter_date = ephem.next_first_quarter_moon(now)
     full_date = ephem.next_full_moon(now)
     last_quarter_date = ephem.next_last_quarter_moon(now)
     delta = float('inf')
     if new_date - now < delta:
         delta = new_date - now
         self.__current_phase = MoonUpdater.LAST_QUARTER_MOON
         self.__current_phase_date = ephem.previous_last_quarter_moon(
             now).datetime()
     if first_quarter_date - now < delta:
         delta = first_quarter_date - now
         self.__current_phase = MoonUpdater.NEW_MOON
         self.__current_phase_date = ephem.previous_new_moon(now).datetime()
     if full_date - now < delta:
         delta = full_date - now
         self.__current_phase = MoonUpdater.FIRST_QUARTER_MOON
         self.__current_phase_date = ephem.previous_first_quarter_moon(
             now).datetime()
     if last_quarter_date - now < delta:
         delta = last_quarter_date - now
         self.__current_phase = MoonUpdater.FULL_MOON
         self.__current_phase_date = ephem.previous_full_moon(
             now).datetime()
Пример #6
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
Пример #7
0
def moon_phases(start, end, output_format):
    d = ephem.previous_full_moon(start)
    d = ephem.previous_full_moon(d)
    print("Starting from", d)

    def output_moon_phase(d, phasename, img, attr):
        if output_format == "sql":
            print("('%s', 'astronomy', 'naked eye', '%s', '%s', '%s', "
                  "'%s', 240, 240, '%s')," %
                  (phasename + " moon", datestr(d), datestr(d),
                   phasename + " moon", img, attr))
        else:
            print(datestr(d), ":", phasename + " moon")

    while d <= end:
        d = ephem.next_first_quarter_moon(d)
        output_moon_phase(
            d, "First quarter", 'astronomy/Phase-088.jpg',
            '<a href=\"http://commons.wikimedia.org/wiki/'
            'File:Phase-088.jpg\">Jay Tanner</a>')
        d = ephem.next_full_moon(d)
        output_moon_phase(
            d, "Full", 'astronomy/Phase-180.jpg',
            '<a href=\"http://commons.wikimedia.org/wiki/'
            'File:Phase-180.jpg\">Jay Tanner</a>')
        d = ephem.next_last_quarter_moon(d)
        output_moon_phase(
            d, "Last quarter", 'astronomy/Phase-270.jpg',
            '<a href=\"http://commons.wikimedia.org/wiki/'
            'File:Phase-270.jpg\">Jay Tanner</a>')
        d = ephem.next_new_moon(d)
        output_moon_phase(
            d, "New", 'astronomy/New_Moon.jpg',
            '<a href="https://commons.wikimedia.org/wiki/'
            'File:New_Moon.jpg">QuimGil</a>')
Пример #8
0
def phases(start):
    j = ephem.Moon()
    #start = '2015-10-1'
    moon_phases = {}
    for x in range(20):
        if x > 0:
            new_moon = ephem.next_new_moon(third_quarter)
            j.compute(new_moon)
            print j.earth_distance * ephem.meters_per_au / 1000, j.phase
        else:
            year_c = str(start)
            new_moon = ephem.next_new_moon(year_c)
        first_quarter = ephem.next_first_quarter_moon(new_moon)
        full_moon = ephem.next_full_moon(first_quarter)
        # j = ephem.Moon()
        j.compute(full_moon)
        print j.earth_distance * ephem.meters_per_au / 1000, j.phase
        third_quarter = ephem.next_last_quarter_moon(full_moon)
        moon_phases[x] = new_moon, first_quarter, full_moon, third_quarter
        print 'New Moon     :', new_moon
        # print 'First Quarter:', first_quarter
        print 'Full Moon    :', full_moon
        # print 'Third Quarter:', third_quarter
        #print '------------------------'
    #print moon_phases
    moon_phase_pd = pd.DataFrame(moon_phases)#, index=['new_moon', 'first_quarter', 'full_moon', 'third_quarter'])
    moon_phase_pd = moon_phase_pd.T
    print moon_phase_pd
    
    moon_phase_pd.to_csv('astro/data/planet_stations/moon_phases.csv')

    return (moon_phases)
Пример #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
Пример #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
Пример #11
0
def get_moon_phase(observer):
    target_date_utc = observer.date
    target_date_local = ephem.localtime(target_date_utc).date()
    next_full = ephem.localtime(ephem.next_full_moon(target_date_utc)).date()
    next_new = ephem.localtime(ephem.next_new_moon(target_date_utc)).date()
    next_last_quarter = ephem.localtime(
        ephem.next_last_quarter_moon(target_date_utc)).date()
    next_first_quarter = ephem.localtime(
        ephem.next_first_quarter_moon(target_date_utc)).date()
    previous_full = ephem.localtime(
        ephem.previous_full_moon(target_date_utc)).date()
    previous_new = ephem.localtime(
        ephem.previous_new_moon(target_date_utc)).date()
    previous_last_quarter = ephem.localtime(
        ephem.previous_last_quarter_moon(target_date_utc)).date()
    previous_first_quarter = ephem.localtime(
        ephem.previous_first_quarter_moon(target_date_utc)).date()

    if target_date_local in (next_full, previous_full):
        return 'Full'
    elif target_date_local in (next_new, previous_new):
        return 'New'
    elif target_date_local in (next_first_quarter, previous_first_quarter):
        return 'First Quarter'
    elif target_date_local in (next_last_quarter, previous_last_quarter):
        return 'Last Quarter'
    elif previous_new < next_first_quarter < next_full < next_last_quarter < next_new:
        return 'Waxing Crescent'
    elif previous_first_quarter < next_full < next_last_quarter < next_new < next_first_quarter:
        return 'Waxing Gibbous'
    elif previous_full < next_last_quarter < next_new < next_first_quarter < next_full:
        return 'Waning Gibbous'
    elif previous_last_quarter < next_new < next_first_quarter < next_full < next_last_quarter:
        return 'Waning Crescent'
Пример #12
0
def phases(start):
    j = ephem.Moon()
    #start = '2015-10-1'
    moon_phases = {}
    for x in range(12):
        if x > 0:
            new_moon = ephem.next_new_moon(third_quarter)
            j.compute(new_moon)
            #print j.earth_distance * ephem.meters_per_au / 1000, j.phase
        else:
            year_c = str(start)
            new_moon = ephem.next_new_moon(year_c)
        first_quarter = ephem.next_first_quarter_moon(new_moon)
        full_moon = ephem.next_full_moon(first_quarter)
        # j = ephem.Moon()
        j.compute(full_moon)
        #print j.earth_distance * ephem.meters_per_au / 1000, j.phase
        third_quarter = ephem.next_last_quarter_moon(full_moon)

        moon_phases[x] = {'new moon' : str(new_moon), 'first quarter' : str(first_quarter), 'full moon' : str(full_moon), 'third quarter' : str(third_quarter)}
        #print 'New Moon     :', new_moon
        #print 'First Quarter:', first_quarter
        #print 'Full Moon    :', full_moon
        #print 'Third Quarter:', third_quarter
        #print '------------------------'
    #print moon_phases
    moon_phase_pd = pd.DataFrame(moon_phases)#, index=['new_moon', 'first_quarter', 'full_moon', 'third_quarter'])
    moon_phase_pd = moon_phase_pd.T
    #print moon_phase_pd
    
    moon_phase_pd.to_csv('astro/data/planet_stations/moon_phases.csv')

    return (moon_phases)
Пример #13
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
Пример #14
0
 def __init__(self, moonphase, date):
     self.info_pass = ""
     if moonphase == "full":
         self.moon = ephem.next_full_moon(date)
     elif moonphase == "new":
         self.moon = ephem.next_new_moon(date)
     elif moonphase == "first_quarter":
         self.moon = ephem.next_first_quarter_moon(date)
     elif moonphase == "last_quarter":
         self.moon = ephem.next_last_quarter_moon(date)
Пример #15
0
 def next_moon_phase_date(self):
     if self.__current_phase == MoonUpdater.NEW_MOON:
         return ephem.next_first_quarter_moon(
             self.__current_phase_date).datetime()
     elif self.__current_phase == MoonUpdater.FIRST_QUARTER_MOON:
         return ephem.next_full_moon(self.__current_phase_date).datetime()
     elif self.__current_phase == MoonUpdater.FULL_MOON:
         return ephem.next_last_quarter_moon(
             self.__current_phase_date).datetime()
     elif self.__current_phase == MoonUpdater.LAST_QUARTER_MOON:
         return ephem.next_new_moon(self.__current_phase_date).datetime()
Пример #16
0
def lunar_start(year, month, day):
    #  🌑 🌒 🌓 🌔 🌕 🌖 🌗 🌘 🌑
    # >>> ephem.next_full_moon((2013, 11, 17)).tuple()[:3]
    # (2013, 11, 17)
    if (year, month, day) == ephem.next_full_moon((year, month, day)).tuple()[:3]:
        return u"🌕"
    elif (year, month, day) == ephem.next_first_quarter_moon((year, month, day)).tuple()[:3]:
        return u"🌓"
    elif (year, month, day) == ephem.next_last_quarter_moon((year, month, day)).tuple()[:3]:
        return u"🌗"
    elif (year, month, day) == ephem.next_new_moon((year, month, day)).tuple()[:3]:
        return u"🌑"
Пример #17
0
    def findNextFourPhases(self):
        '''
        This function returns a sorted tuple of the next four phases with the key being the short 
        name for the phase. The value is a modified Julian date for the phase.
        @return: A list of tuples sorted by the value date.
        '''
        phases = {}
        phases["new"] = ephem.next_new_moon(self._observer.date)
        phases["fq"] = ephem.next_first_quarter_moon(self._observer.date)
        phases["full"] = ephem.next_full_moon(self._observer.date)
        phases["tq"] = ephem.next_last_quarter_moon(self._observer.date)

        return sorted(phases.items(), key=lambda x: x[1])
Пример #18
0
 def findNextFourPhases(self):
     '''
     This function returns a sorted tuple of the next four phases with the key being the short 
     name for the phase. The value is a modified Julian date for the phase.
     @return: A list of tuples sorted by the value date.
     '''
     phases = {}
     phases["new"] = ephem.next_new_moon(self._observer.date)
     phases["fq"] = ephem.next_first_quarter_moon(self._observer.date)
     phases["full"] = ephem.next_full_moon(self._observer.date)
     phases["tq"] = ephem.next_last_quarter_moon(self._observer.date)
     
     return sorted(phases.items(), key=lambda x:x[1])
Пример #19
0
def moon_is(adate):
  " Find the next moon shape, returns FM .. NM."
  # TODO(mohsin) This is expensive, should cache it for whole month.
  # ephem.previous_new_moon(date)
  # ephem.previous_first_quarter_moon(date)
  # ephem.previous_full_moon(date)
  # ephem.previous_last_quarter_moon(date)
  date = ephem.Date(adate)
  if cmp_ymd(ephem.next_new_moon(date)          , date): return 'NM'
  if cmp_ymd(ephem.next_first_quarter_moon(date), date): return 'FQ'
  if cmp_ymd(ephem.next_full_moon(date)         , date): return 'FM'
  if cmp_ymd(ephem.next_last_quarter_moon(date) , date):  return 'LQ'
  return ''
Пример #20
0
def make_moon_stuff(outer_canv, inner_canv, begin_day, no_days, chart,
        obs):
    small_moon_rad = 0.12
    large_moon_rad = 0.16
    moon = ephem.Moon()
    moon2 = ephem.Moon()
    for doy in range(no_days) :
        obs.date = begin_day + doy
        mpc = obs.date + 0.5 # moon phase check
        moon_set = obs.next_setting(moon)
        moon2.compute(moon_set)
        X = moon2.moon_phase
        # Waxing moon (moonsets)
        x, y = to_chart_coord(moon_set, chart)
        if (fabs(ephem.next_full_moon(mpc) - mpc) < 0.5 or
            fabs(ephem.previous_full_moon(mpc) - mpc) < 0.5) :
            # full moon
            outer_canv.stroke(path.circle(x,y,large_moon_rad),[mooncolorlight,pyx.deco.filled([mooncolorlight])])
        elif ((X < 0.55 and X > 0.45) or 
              fabs(ephem.next_first_quarter_moon(mpc) - mpc) < 0.5 or
              fabs(ephem.previous_first_quarter_moon(mpc) - mpc) < 0.5) :
            # first quarter
            outer_canv.stroke(first_quarter_moon(large_moon_rad, x,y),[mooncolordark,pyx.deco.filled([mooncolordark])])
        elif (fabs(ephem.next_new_moon(mpc) - mpc) < 0.5 or
              fabs(ephem.previous_new_moon(mpc) - mpc) < 0.5):
            # new moon
            outer_canv.stroke(path.circle(x,y,large_moon_rad),[mooncolorlight,pyx.deco.filled([mooncolordark])])
        else :
            inner_canv.fill(waxing_moon(X, small_moon_rad, x, y),
                    [style.linejoin.bevel,mooncolordark])
        # Waning moon (moonrises)
        moon_rise = obs.next_rising(moon)
        moon2.compute(moon_rise)
        X = moon2.moon_phase
        x, y = to_chart_coord(moon_rise, chart)
        if (fabs(ephem.next_full_moon(mpc) - mpc) < 0.5 or
            fabs(ephem.previous_full_moon(mpc) - mpc) < 0.5) :
            # full moon
            outer_canv.stroke(path.circle(x,y,large_moon_rad),[mooncolorlight,pyx.deco.filled([mooncolorlight])])
        elif ((X < 0.55 and X > 0.45) or 
              fabs(ephem.next_last_quarter_moon(mpc) - mpc) < 0.5 or
              fabs(ephem.previous_last_quarter_moon(mpc) - mpc) < 0.5) :
            # last quarter
            outer_canv.stroke(last_quarter_moon(large_moon_rad, x,y),[mooncolorlight,pyx.deco.filled([mooncolorlight])])
        elif (fabs(ephem.next_new_moon(mpc) - mpc) < 0.5 or
              fabs(ephem.previous_new_moon(mpc) - mpc) < 0.5):
            # new moon
            outer_canv.stroke(path.circle(x,y,large_moon_rad),[mooncolorlight,pyx.deco.filled([mooncolordark])])
        else :
            inner_canv.fill(waning_moon(X, small_moon_rad, x, y),
                    [style.linejoin.bevel,mooncolorlight])
Пример #21
0
    def __init__(self, year, timezone='Europe/Copenhagen',
                 outformat='text'):
        """Compute moon phases for a whole year"""
        # Backtrack and look ahead to be sure to catch moons around newyear
        start_date = ephem.Date((year-1, 9, 1))
        end_date = ephem.Date((year+1, 3, 1))
        self.moon_phases = {}
        new_moon = ephem.next_new_moon(start_date)
        first_quarter = ephem.next_first_quarter_moon(start_date)
        full_moon = ephem.next_full_moon(start_date)
        last_quarter = ephem.next_last_quarter_moon(start_date)
        while True:
            local_new_moon = utc2localtime(new_moon.datetime())
            local_first_quarter = utc2localtime(first_quarter.datetime())
            local_full_moon = utc2localtime(full_moon.datetime())
            local_last_quarter = utc2localtime(last_quarter.datetime())
            if local_new_moon.year == year:
                self.moon_phases[local_new_moon] = \
                    self.moon_phase_names('new_moon', outformat)
            if local_first_quarter.year == year:
                self.moon_phases[local_first_quarter] = \
                    self.moon_phase_names('first_quarter', outformat)
            if local_full_moon.year == year:
                self.moon_phases[local_full_moon] = \
                    self.moon_phase_names('full_moon', outformat)
            if local_last_quarter.year == year:
                self.moon_phases[local_last_quarter] = \
                    self.moon_phase_names('last_quarter', outformat)

            new_moon = ephem.next_new_moon(new_moon)
            first_quarter = ephem.next_first_quarter_moon(first_quarter)
            full_moon = ephem.next_full_moon(full_moon)
            last_quarter = ephem.next_last_quarter_moon(last_quarter)
            if (new_moon > end_date) and (first_quarter > end_date) and \
               (full_moon > end_date) and (last_quarter > end_date):
                break
Пример #22
0
    def next_four_phases(self):
        """The next for phases in date sorted order (closest phase first).

        Returns
        -------
        list[(str, float)]
            Set of moon phases specified by an abbreviated phase name and Modified Julian Date.
        """
        phases = {}
        phases["new_moon"] = ephem.next_new_moon(self.observer.date)
        phases["first_quarter"] = ephem.next_first_quarter_moon(self.observer.date)
        phases["full_moon"] = ephem.next_full_moon(self.observer.date)
        phases["last_quarter"] = ephem.next_last_quarter_moon(self.observer.date)

        sorted_phases = sorted(phases.items(), key=itemgetter(1))
        sorted_phases = [(phase[0], mjd_to_date_tuple(phase[1])) for phase in sorted_phases]

        return sorted_phases
Пример #23
0
def moonPhase(date):
    mydate = ephem.date(
        date.replace(hour=00, minute=0, second=0, microsecond=0))
    nnm = ephem.next_new_moon(mydate)
    nqm = ephem.next_first_quarter_moon(mydate)
    nfm = ephem.next_full_moon(mydate)
    nlm = ephem.next_last_quarter_moon(mydate)
    quarter = ""
    if nfm > nqm:
        quarter = "Waxing Crescent"
    if nqm > nfm:
        quarter = "Waxing Gibbous"
    if nfm > nlm:
        quarter = "Waning Gibbous"
    if nlm > nnm:
        quarter = "Waning Crescent"
    if nnm.datetime().replace(hour=0, minute=0, second=0,
                              microsecond=0) == date.replace(hour=0,
                                                             minute=0,
                                                             second=0,
                                                             microsecond=0):
        quarter = "New %s" % nnm.datetime().strftime("%H:%M:%S")
    if nfm.datetime().replace(hour=0, minute=0, second=0,
                              microsecond=0) == date.replace(hour=0,
                                                             minute=0,
                                                             second=0,
                                                             microsecond=0):
        quarter = "Full %s " % nfm.datetime().strftime("%H:%M:%S")
    if nqm.datetime().replace(hour=0, minute=0, second=0,
                              microsecond=0) == date.replace(hour=0,
                                                             minute=0,
                                                             second=0,
                                                             microsecond=0):
        quarter = "First quarter %s " % nqm.datetime().strftime("%H:%M:%S")
    if nlm.datetime().replace(hour=0, minute=0, second=0,
                              microsecond=0) == date.replace(hour=0,
                                                             minute=0,
                                                             second=0,
                                                             microsecond=0):
        quarter = "Last quarter %s " % nlm.datetime().strftime("%H:%M:%S")

    return quarter
Пример #24
0
def is_major_phase(date):
    """Returns a code if the date coincides with a major Moon phase, i.e. first
    quarter, full Moon, last quarter or new Moon.

    Keyword arguments:
    date -- a PyEphem Date object.
    """

    # Calculate the exact date and time of each upcoming major Moon phase.
    next_new_moon = ephem.next_new_moon(date)
    next_first_quarter_moon = ephem.next_first_quarter_moon(date)
    next_full_moon = ephem.next_full_moon(date)
    next_last_quarter_moon = ephem.next_last_quarter_moon(date)

    # Format the major Moon phase dates by resetting their hour, minute and
    # second values to zero, positioning each day at midnight so that they can
    # be directly compared against the date argument.
    next_new_moon_date = helpers.set_date_to_midnight(next_new_moon)
    next_first_quarter_moon_date = helpers.set_date_to_midnight(
        next_first_quarter_moon)
    next_full_moon_date = helpers.set_date_to_midnight(next_full_moon)
    next_last_quarter_moon_date = helpers.set_date_to_midnight(
        next_last_quarter_moon)

    # Convert the `date` arugment to an Ephem Date for comparison.
    date = ephem.Date(date)

    # Return the appropriate code based on if there is a match. No matches will
    # return `None`.
    if (next_new_moon_date == date):
        return 'new_moon'

    if (next_first_quarter_moon_date == date):
        return 'first_quarter'

    if (next_full_moon_date == date):
        return 'full_moon'

    if (next_last_quarter_moon_date == date):
        return 'last_quarter'

    return None
Пример #25
0
def get_lunation_day(today, number_of_phase_ids=28):
    '''Given a date (of type ephem.Date), return a lunar cycle day ID number
    (integer in [0:(number_of_phase_ids - 1)]), corresponding to the lunation
    for the given date. 0 = new moon.
    
    Arguments:
        today (ephem.date): the date for which to get the lunation day number

    Optional:
        number_of_phase_ids (integer, default = 28): the number of unique
            lunar cycle day identifiers, e.g. the number of moon phase icons
            available to display the lunation each day.
            
    Returns:
        integer in range(0, number_of_phase_ids - 1), today's lunation phase
            ID number.
    
    The lunation day is calibrated to the quarter phases
    calculated by pyephem, but it does not always agree exactly with
    percent illumination, which is a different calculation entirely.'''
    last_new = ephem.previous_new_moon(today)
    next_new = ephem.next_new_moon(today)
    num = number_of_phase_ids - 1
    first_approx = round((today - last_new) / (next_new - last_new) * num)
    if first_approx < np.ceil(num / 4):
        next_fq = ephem.next_first_quarter_moon(last_new)
        if today < next_fq:
            return round((today - last_new) / (next_fq - last_new)
                        * (num / 4))
    if first_approx < np.ceil(num / 2):
        next_full = ephem.next_full_moon(last_new)
        if today < next_full:
            return round((today - last_new) / (next_full - last_new)
                        * (num / 2))
    if first_approx < np.ceil(num * 3 / 4):
        next_lq = ephem.next_last_quarter_moon(last_new)
        if today < next_lq:
            return round((today - last_new) / (next_lq - last_new)
                        * (num * 3 / 4))
    return first_approx
Пример #26
0
    def gen_moon_phases(self, start, until, lunar_phase=None):
        '''Return an interator of moon phases over the given dates.'''
        phase_date = start

        while phase_date < until:
            elong = self.get_degrees(ephem.Moon(phase_date).elong)
            if elong < -90:
                nxt_phase = ephem.next_last_quarter_moon(phase_date)
                phase = RuleLunar.moon_3q
            elif elong < 0:
                nxt_phase = ephem.next_new_moon(phase_date)
                phase = RuleLunar.moon_new
            elif elong < 90:
                nxt_phase = ephem.next_first_quarter_moon(phase_date)
                phase = RuleLunar.moon_1q
            else:
                nxt_phase = ephem.next_full_moon(phase_date)
                phase = RuleLunar.moon_full
            phase_date = self.get_datetime(nxt_phase)
            if phase_date < until and (not lunar_phase
                                       or lunar_phase == phase):
                yield phase, phase_date
            phase_date += datetime.timedelta(days=1)
Пример #27
0
def new_moon(bot, update):

    dfu = update.message.text

    moon = {
        "Предыдущий цикл": {
            "Последняя четверть луны": ephem.previous_last_quarter_moon(dfu),
            "Новолуние": ephem.previous_new_moon(dfu),
            "Первая четверть луны": ephem.previous_first_quarter_moon(dfu),
            "Полнолуние": ephem.previous_full_moon(dfu),
        },
        "Следующий цикл": {
            "Последняя четверть луны": ephem.next_last_quarter_moon(dfu),
            "Новолуние": ephem.next_new_moon(dfu),
            "Первая четверть луны": ephem.next_first_quarter_moon(dfu),
            "Полнолуние": ephem.next_full_moon(dfu),
        }
    }

    for key in moon:
        bot.sendMessage(update.message.chat_id, text=key)
        for row_key in moon[key]:
            bot.sendMessage(update.message.chat_id,
                            text=(row_key, ":", moon[key][row_key]))
Пример #28
0
def get_moons_in_year(year):
    """
    Returns a list of the full and new moons in a year. The list contains tuples
    of either the form (DATE,'full') or the form (DATE,'new')
    Data is truncated at hours and minutes; round to nearest Minute by
    adding 30 seconds to date
    """
    moons = []

    date = ephem.Date(datetime.date(year, 1, 1))
    end = ephem.Date(datetime.datetime(year, 12, 31, 23, 59))
    while date.datetime().year == year:
        date = ephem.next_full_moon(date)
        if date < end:
            moons.append(pom_format('Full Moon', date))

    date = ephem.Date(datetime.date(year, 1, 1))
    while date.datetime().year == year:
        date = ephem.next_new_moon(date)
        if date < end:
            moons.append(pom_format('New Moon', date))

    date = ephem.Date(datetime.date(year, 1, 1))
    while date.datetime().year == year:
        date = ephem.next_first_quarter_moon(date)
        if date < end:
            moons.append(pom_format('First Quarter', date))

    date = ephem.Date(datetime.date(year, 1, 1))
    while date.datetime().year == year:
        date = ephem.next_last_quarter_moon(date)
        if date < end:
            moons.append(pom_format('Last Quarter', date))

    moons.sort(key=lambda x: float(x.split()[0]))
    return moons
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 13 14:07:43 2020
https://rhodesmill.org/pyephem/quick.html#phases-of-the-moon
@author: PC
"""

import ephem

d1 = ephem.next_full_moon('1984')
print(d1)
d2 = ephem.next_new_moon(d1)
print(d2)

print(ephem.previous_new_moon('2020'))
print(ephem.next_new_moon('2020'))

print(ephem.previous_first_quarter_moon('2020'))
print(ephem.next_first_quarter_moon('2020'))

print(ephem.previous_full_moon('2020'))
print(ephem.next_full_moon('2020'))

print(ephem.previous_last_quarter_moon('2020'))
print(ephem.next_last_quarter_moon('2020'))
Пример #30
0
def main():

    sun = ephem.Sun()
    moon = ephem.Moon()

    # define observer
    home = ephem.Observer()
    home.date = ephem.date(datetime.utcnow())
    home.lat, home.lon = '50.46', '9.61'

    sun.compute(home)
    sunrise, sunset = (home.next_rising(sun),
                       home.next_setting(sun))
    moon.compute(home)
    moonrise, moonset = (home.next_rising(moon),
                       home.next_setting(moon))
    home.horizon = '-6'
    m6_start, m6_end = (home.next_rising(sun, use_center=True),
                        home.next_setting(sun, use_center=True))
    home.horizon = '-12'
    m12_start, m12_end = (home.next_rising(sun, use_center=True),
                          home.next_setting(sun, use_center=True))
    home.horizon = '-18'
    m18_start, m18_end = (home.next_rising(sun, use_center=True),
                          home.next_setting(sun, use_center=True))

    print home.date

    e = {}
    e[sunrise] =   " Sunrise:                      "
    e[sunset] =    " Sunset:                       "
    e[moonrise] =  " Moonrise:                     "
    e[moonset] =   " Moonset:                      "
    e[m6_start] =  " Civil twilight starts:        "
    e[m6_end] =    " Civil twilight ends:          "
    e[m12_start] = " Nautical twilight starts:     "
    e[m12_end] =   " Nautical twilight ends:       "
    e[m18_start] = " Astronomical twilight starts: "
    e[m18_end] =   " Astronomical twilight ends:   "

    for time in sorted(e.keys()):
        print e[time], ephem.localtime(time).ctime()

    # Here start the moon specific data

    print " ---"
    print " Moon phase: %d%% " % moon.phase

    e = {}
    e1 = ephem.previous_new_moon(home.date)
    e[e1] = " Previous new moon:            "
    e1 = ephem.previous_first_quarter_moon(home.date)
    e[e1] = " Previous first quarter moon:  "
    e1 = ephem.previous_full_moon(home.date)
    e[e1] = " Previous full moon:           "
    e1 = ephem.previous_last_quarter_moon(home.date)
    e[e1] = " Previous last quarter moon:   "

    e1 = ephem.next_new_moon(home.date)
    e[e1] = " Next new moon:                "
    e1 = ephem.next_first_quarter_moon(home.date)
    e[e1] = " Next first quarter moon:      "
    e1 = ephem.next_full_moon(home.date)
    e[e1] = " Next full moon:               "
    e1 = ephem.next_last_quarter_moon(home.date)
    e[e1] = " Next last quarter moon:       "

    for time in sorted(e.keys()):
        print e[time], ephem.localtime(time).ctime()
Пример #31
0
#!/usr/bin/python
# Print next moon quarter (requires PyEphem)
# 2014-07-08

import ephem

n = ephem.now()

# Unicode symbols are for inverted text (white on black):
p = [[ephem.next_full_moon(n),"🌑 Vollmond"],
[ephem.next_last_quarter_moon(n),"🌓 Letztes Viertel"],
[ephem.next_new_moon(n),"🌕 Neumond"],
[ephem.next_first_quarter_moon(n),"🌗 Erstes Viertel"]]

p.sort()

a = p[0]

h = 24*(a[0]-n)

def nat(h):
	h2 = round(h)
	if h > 24:
		d = h2//24
		if d > 1:
			dh = "%u Tagen" % d
		else:
			dh = "einem Tag"
		hh = h2 - 24*d
		if hh > 1:
			hhh = "%u Stunden" % hh
Пример #32
0
now = datetime.now()

#Past Moon phases
d5 = ephem.previous_new_moon(now)
d6 = ephem.previous_first_quarter_moon(now)
d7 = ephem.previous_full_moon(now)
d8 = ephem.previous_last_quarter_moon(now)
print
print (d5), "	| Previous new Moon"
print (d6), "	| Previous quarter Moon"
print (d7), "	| Previous full Moon"
print (d8), "	| Previous last quarter Moon"
print

#Next Moon phases
d1 = ephem.next_full_moon(now)
d2 = ephem.next_new_moon(now)
d3 = ephem.next_first_quarter_moon(now)
d4 = ephem.next_last_quarter_moon(now)
print (d2), "	| Next new Moon"
print (d3), "	| Next quarter Moon"
print (d1), "	| Next full Moon"
print (d4), "	| Next last quarter Moon"
print

m=ephem.Moon(now)
print "Moon is actually:", (ephem.constellation(m))

quit()
Пример #33
0
moonrise = observer.previous_rising(ephem.Moon())
moonnoon    = observer.next_transit   (ephem.Moon())
moonset  = observer.next_setting   (ephem.Moon())
data['moon']['rise'] = calendar.timegm(moonrise.datetime().utctimetuple())
data['moon']['noon']    = calendar.timegm(moonnoon.datetime().utctimetuple())
data['moon']['set']  = calendar.timegm(moonset.datetime().utctimetuple())
data['moon']['radius'] = ephem.moon_radius

previous_new_moon = ephem.previous_new_moon(time)
next_new_moon = ephem.next_new_moon(time)
previous_first_quarter_moon = ephem.previous_first_quarter_moon(time)
next_first_quarter_moon = ephem.next_first_quarter_moon(time)
previous_full_moon = ephem.previous_full_moon(time)
next_full_moon = ephem.next_full_moon(time)
previous_last_quarter_moon = ephem.previous_last_quarter_moon(time)
next_last_quarter_moon = ephem.next_last_quarter_moon(time)

data['moon']['previous_new_moon'] = calendar.timegm(previous_new_moon.datetime().utctimetuple())
data['moon']['next_new_moon'] = calendar.timegm(next_new_moon.datetime().utctimetuple())
data['moon']['previous_first_quarter_moon'] = calendar.timegm(previous_first_quarter_moon.datetime().utctimetuple())
data['moon']['next_first_quarter_moon'] = calendar.timegm(next_first_quarter_moon.datetime().utctimetuple())
data['moon']['previous_full_moon'] = calendar.timegm(previous_full_moon.datetime().utctimetuple())
data['moon']['next_full_moon'] = calendar.timegm(next_full_moon.datetime().utctimetuple())
data['moon']['previous_last_quarter_moon'] = calendar.timegm(previous_last_quarter_moon.datetime().utctimetuple())
data['moon']['next_last_quarter_moon'] = calendar.timegm(next_last_quarter_moon.datetime().utctimetuple())

moon = ephem.Moon()
moon.compute(observer)

data['moon']['phase'] = moon.moon_phase
data['moon']['altitude'] = moon.alt
Пример #34
0
    def onHeartbeat(self):
        Domoticz.Debug("onHeartbeat")
        self.__runAgain -= 1
        if self.__runAgain <= 0:
            self.__runAgain = self.__HEARTBEATS2MIN * self.__MINUTES
            #
            utc_now = datetime.datetime.utcnow()
            target_date = datetime.datetime.now().date()
            #
            self.__observer.date = utc_now
            self.__sun.compute(self.__observer)
            #
            ################################################################################
            # Sun data
            ################################################################################
            #
            # -------------------------------------------------------------------------------
            # Sun altitude
            # -------------------------------------------------------------------------------
            value = round(deg(self.__sun.alt), 2)
            UpdateDevice(unit.SUN_ALT, int(value), str(value))
            #
            # -------------------------------------------------------------------------------
            # Sun azimuth
            # -------------------------------------------------------------------------------
            value = round(deg(self.__sun.az), 2)
            UpdateDevice(unit.SUN_AZ, int(value), str(value))
            #
            # -------------------------------------------------------------------------------
            # Sun distance
            # -------------------------------------------------------------------------------
            value = round(self.__sun.earth_distance * ephem.meters_per_au / 1000)
            UpdateDevice(unit.SUN_DIST, int(value), str(value))
            #
            # -------------------------------------------------------------------------------
            # Sun transit
            # -------------------------------------------------------------------------------
            value = (
                ephem.localtime(self.__observer.next_transit(self.__sun)) + self.__SEC30
            )
            UpdateDevice(
                unit.SUN_TRANSIT, 0, "{}".format(value.strftime(self.__DT_FORMAT))
            )
            #
            # -------------------------------------------------------------------------------
            # Sun rise & set today
            # -------------------------------------------------------------------------------
            self.__observer.date = target_date
            self.__sun.compute(self.__observer)
            i = 0
            for t in self.__TWILIGHTS:
                # Zero the horizon
                self.__observer.horizon = t[0]
                try:
                    next_rising = (
                        ephem.localtime(
                            self.__observer.next_rising(self.__sun, use_center=t[1])
                        )
                        + self.__SEC30
                    )
                    UpdateDevice(
                        unit.SUN_RISE + i,
                        0,
                        "{}".format(next_rising.strftime(self.__DT_FORMAT)),
                    )
                except:
                    UpdateDevice(
                        unit.SUN_RISE + i,
                        0,
                        "{}".format("No time available"),
                    )
                try:
                    next_setting = (
                        ephem.localtime(
                            self.__observer.next_setting(self.__sun, use_center=t[1])
                        )
                        + self.__SEC30
                    )
                    UpdateDevice(
                        unit.SUN_SET + i,
                        0,
                        "{}".format(next_setting.strftime(self.__DT_FORMAT)),
                    )
                except:
                    UpdateDevice(
                        unit.SUN_RISE + i,
                        0,
                        "{}".format("No time available"),
                    )
                if i == 0:
                    value = (next_setting - next_rising).total_seconds()
                    hh = divmod(value, 3600)
                    mm = divmod(hh[1], 60)
                    min = int(divmod(value, 60)[0])
                    UpdateDevice(
                        unit.DAY_LENGTH_M,
                        min,
                        "{}".format(min),
                    )
                    UpdateDevice(
                        unit.DAY_LENGTH_T,
                        0,
                        "{:02}:{:02}".format(int(hh[0]), int(mm[0])),
                    )

                i += 1
            #
            # Reset horizon for further calculations
            self.__observer.horizon = "0"
            #
            ################################################################################
            # Moon data
            ################################################################################
            #
            self.__observer.date = utc_now
            self.__moon.compute(self.__observer)
            #
            # -------------------------------------------------------------------------------
            # Moon rise
            # -------------------------------------------------------------------------------
            value = (
                ephem.localtime(self.__observer.next_rising(self.__moon)) + self.__SEC30
            )
            UpdateDevice(
                unit.MOON_RISE, 0, "{}".format(value.strftime(self.__DT_FORMAT))
            )
            #
            # -------------------------------------------------------------------------------
            # Moon set
            # -------------------------------------------------------------------------------
            value = (
                ephem.localtime(self.__observer.next_setting(self.__moon))
                + self.__SEC30
            )
            UpdateDevice(
                unit.MOON_SET, 0, "{}".format(value.strftime(self.__DT_FORMAT))
            )
            #
            # -------------------------------------------------------------------------------
            # Moon altitude
            # -------------------------------------------------------------------------------
            self.__moon.compute(self.__observer)
            #
            value = round(deg(self.__moon.alt), 2)
            UpdateDevice(unit.MOON_ALT, int(value), str(value))
            #
            # -------------------------------------------------------------------------------
            # Moon azimuth
            # -------------------------------------------------------------------------------
            value = round(deg(self.__moon.az), 2)
            UpdateDevice(unit.MOON_AZ, int(value), str(value))
            #
            # -------------------------------------------------------------------------------
            # Moon distance
            # -------------------------------------------------------------------------------
            value = round(self.__moon.earth_distance * ephem.meters_per_au / 1000)
            UpdateDevice(unit.MOON_DIST, int(value), str(value))
            #
            # -------------------------------------------------------------------------------
            # Next new moon
            # -------------------------------------------------------------------------------
            next_new = ephem.localtime(ephem.next_new_moon(utc_now))
            value = next_new + self.__SEC30
            UpdateDevice(
                unit.MOON_NEXT_NEW, 0, "{}".format(value.strftime(self.__DT_FORMAT))
            )
            #
            # -------------------------------------------------------------------------------
            # Next first quarter
            # -------------------------------------------------------------------------------
            next_first_quarter = ephem.localtime(ephem.next_first_quarter_moon(utc_now))
            value = next_first_quarter + self.__SEC30
            UpdateDevice(
                unit.MOON_NEXT_FIRST_QUARTER,
                0,
                "{}".format(value.strftime(self.__DT_FORMAT)),
            )
            #
            # -------------------------------------------------------------------------------
            # Next full moon
            # -------------------------------------------------------------------------------
            next_full = ephem.localtime(ephem.next_full_moon(utc_now))
            value = next_full + self.__SEC30
            UpdateDevice(
                unit.MOON_NEXT_FULL,
                0,
                "{}".format(value.strftime(self.__DT_FORMAT)),
            )
            #
            # -------------------------------------------------------------------------------
            # Next last quarter
            # -------------------------------------------------------------------------------
            next_last_quarter = ephem.localtime(ephem.next_last_quarter_moon(utc_now))
            value = next_last_quarter + self.__SEC30
            UpdateDevice(
                unit.MOON_NEXT_LAST_QUARTER,
                0,
                "{}".format(value.strftime(self.__DT_FORMAT)),
            )
            #
            # -------------------------------------------------------------------------------
            # Moon phase
            # -------------------------------------------------------------------------------
            next_full = next_full.date()
            next_new = next_new.date()
            next_last_quarter = next_last_quarter.date()
            next_first_quarter = next_first_quarter.date()
            previous_full = ephem.localtime(ephem.previous_full_moon(utc_now)).date()
            previous_new = ephem.localtime(ephem.previous_new_moon(utc_now)).date()
            previous_last_quarter = ephem.localtime(
                ephem.previous_last_quarter_moon(utc_now)
            ).date()
            previous_first_quarter = ephem.localtime(
                ephem.previous_first_quarter_moon(utc_now)
            ).date()
            #
            # Domoticz.Debug("target_date: {}".format(target_date))
            # Domoticz.Debug("next_full: {}".format(next_full))
            # Domoticz.Debug("next_new: {}".format(next_new))
            # Domoticz.Debug("next_last_quarter: {}".format(next_last_quarter))
            # Domoticz.Debug("next_first_quarter: {}".format(next_first_quarter))
            # Domoticz.Debug("previous_full: {}".format(previous_full))
            # Domoticz.Debug("previous_new: {}".format(previous_new))
            # Domoticz.Debug("previous_last_quarter: {}".format(previous_last_quarter))
            # Domoticz.Debug("previous_first_quarter: {}".format(previous_first_quarter))

            if target_date in (next_new, previous_new):
                phase = 0
            elif target_date in (next_first_quarter, previous_first_quarter):
                phase = 2
            elif target_date in (next_full, previous_full):
                phase = 4
            elif target_date in (next_last_quarter, previous_last_quarter):
                phase = 6
            elif (
                previous_new
                < next_first_quarter
                < next_full
                < next_last_quarter
                < next_new
            ):
                phase = 1
            elif (
                previous_first_quarter
                < next_full
                < next_last_quarter
                < next_new
                < next_first_quarter
            ):
                phase = 3
            elif (
                previous_full
                < next_last_quarter
                < next_new
                < next_first_quarter
                < next_full
            ):
                phase = 5
            elif (
                previous_last_quarter
                < next_new
                < next_first_quarter
                < next_full
                < next_last_quarter
            ):
                phase = 7
            else:
                phase = 4
            UpdateDevice(unit.MOON_PHASE, 0, self.__MOON_PHASE_DESCRIPTIONS[phase])
            UpdateDeviceImage(
                unit.MOON_PHASE, images.PREFIX_IMAGE + images.PREFIX_PHASE + str(phase)
            )
            #
            self.__moon.compute(self.__observer)
            #
            # -------------------------------------------------------------------------------
            # Moon illumination
            # -------------------------------------------------------------------------------
            value = round(deg(self.__moon.moon_phase), 2)
            UpdateDevice(unit.MOON_ILLUMINATION, int(value), str(value))
            UpdateDeviceImage(
                unit.MOON_ILLUMINATION,
                images.PREFIX_IMAGE + images.PREFIX_PHASE + str(phase),
            )
            #
        else:
            Domoticz.Debug(
                "onHeartbeat called, run again in {} heartbeats.".format(
                    self.__runAgain
                )
            )
Пример #35
0
    def do_thread_loop(self):
        while(self.running):
            if ( self.mqtt_connected ):    
                nowtime=datetime.datetime.now()
                if(nowtime.year != self.year):
                    self.year = nowtime.year
                    self.mqttc.publish("/raw/clock/year", self.year, retain=True)
                if(nowtime.month != self.month):
                    self.month = nowtime.month
                    self.mqttc.publish("/raw/clock/month", self.month, retain=True)
                if(nowtime.day != self.day):
                    self.day = nowtime.day
                    self.mqttc.publish("/raw/clock/day", self.day, retain=True)
                    self.weekday=nowtime.weekday()
                    self.mqttc.publish("/raw/clock/weekday", self.weekday, retain=True)
                    self.utc_sunrise=self.observer.next_rising(self.sun)
#                    self.mqttc.publish("/raw/clock/utc_sunrise", str(self.utc_sunrise), retain=True)
                    self.sunrise=ephem.localtime(self.observer.next_rising(self.sun))
                    self.mqttc.publish("/raw/clock/sunrise", str(self.sunrise), retain=True)
                    self.utc_sunset=self.observer.next_setting(self.sun)
#                    self.mqttc.publish("/raw/clock/utc_sunset", str(self.utc_sunset), retain=True)
                    self.sunset=ephem.localtime(self.observer.next_setting(self.sun))
                    self.mqttc.publish("/raw/clock/sunset", str(self.sunset), retain=True)
                    self.utc_moonrise=self.observer.next_rising(self.moon)
#                    self.mqttc.publish("/raw/clock/utc_moonrise", str(self.utc_moonrise), retain=True)
                    self.moonrise=ephem.localtime(self.observer.next_rising(self.moon))
                    self.mqttc.publish("/raw/clock/moonrise", str(self.moonrise), retain=True)
                    self.utc_moonset=self.observer.next_setting(self.moon)
#                    self.mqttc.publish("/raw/clock/utc_moonset", str(self.utc_moonset), retain=True)
                    self.moonset=ephem.localtime(self.observer.next_setting(self.moon))
                    self.mqttc.publish("/raw/clock/moonset", str(self.moonset), retain=True)
                    self.nextnewmoon=ephem.next_new_moon(nowtime)
                    self.mqttc.publish("/raw/clock/nextnewmoon", str(self.nextnewmoon), retain=True) 
                    self.nextfirstquartermoon=ephem.next_first_quarter_moon(nowtime)
                    self.mqttc.publish("/raw/clock/nextfirstquartermoon", str(self.nextfirstquartermoon), retain=True)
                    self.nextlastquartermoon=ephem.next_last_quarter_moon(nowtime)
                    self.mqttc.publish("/raw/clock/nextlastquartermoon", str(self.nextlastquartermoon), retain=True)
                    self.nextfullmoon=ephem.next_full_moon(nowtime)
                    self.mqttc.publish("/raw/clock/nextfullmoon", str(self.nextfullmoon), retain=True)                   
                if(nowtime.hour != self.mil_hour):
                    self.mil_hour = nowtime.hour
                    self.hour = self.mil_hour % 12
                    if (self.hour == 0):
                        self.hour = 12
                    self.mqttc.publish("/raw/clock/hour", self.hour, retain=True)
                    self.mqttc.publish("/raw/clock/militaryhour", self.mil_hour, retain=True)
                    if(self.mil_hour > 11):
                        self.ampm = "PM"
                    else:
                        self.ampm = "AM"
                    if((self.mil_hour == 12) or (self.mil_hour == 0)):
                        self.mqttc.publish("/raw/clock/ampm", self.ampm, retain=True)
                if(nowtime.minute != self.minute):
                    self.minute = nowtime.minute
                    self.mqttc.publish("/raw/clock/minute", self.minute, retain=True)
                if(nowtime < self.sunrise):        # is this right???
                    temp = "set" 
                elif(nowtime > self.sunset):
                    temp="set"
                else:
                    temp="rise"
                if(temp != self.sunstate):
                    self.sunstate=temp
                    self.mqttc.publish("/raw/clock/sunstate", self.sunstate, retain=True)
                if ( self.interval ):
                    print "Waiting ", self.interval, " seconds for next update."
                    time.sleep(self.interval)
Пример #36
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
Пример #37
0
while True:
    user_answer = (input("date: ").lower())

    moon = {
        "Предыдущий цикл": {
            "Последняя четверть луны":
            ephem.previous_last_quarter_moon(user_answer),
            "Новолуние":
            ephem.previous_new_moon(user_answer),
            "Первая четверть луны":
            ephem.previous_first_quarter_moon(user_answer),
            "Полнолуние":
            ephem.previous_full_moon(user_answer),
        },
        "Следующий цикл": {
            "Последняя четверть луны":
            ephem.next_last_quarter_moon(user_answer),
            "Новолуние": ephem.next_new_moon(user_answer),
            "Первая четверть луны": ephem.next_first_quarter_moon(user_answer),
            "Полнолуние": ephem.next_full_moon(user_answer),
        }
    }

    for key in moon:
        print(key)
        for row_key in moon[key]:
            print(row_key, ":", moon[key][row_key])

    if user_answer == "exit":
        break
Пример #38
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'
Пример #39
0
#!/usr/bin/python
# Print next moon quarter (requires PyEphem)
# 2017-10-29

import ephem

n = ephem.now()

p = [[ephem.next_full_moon(n),"🌕 Vollmond"],
[ephem.next_last_quarter_moon(n),"🌗 Letztes Viertel"],
[ephem.next_new_moon(n),"🌑 Neumond"],
[ephem.next_first_quarter_moon(n),"🌓 Erstes Viertel"]]

p.sort()

a = p[0]

h = 24*(a[0]-n)

def nat(h):
	h2 = round(h)
	if h > 24:
		d = h2//24
		if d > 1:
			dh = "%u Tagen" % d
		else:
			dh = "einem Tag"
		hh = h2 - 24*d
		if hh > 1:
			hhh = "%u Stunden" % hh
		else:
Пример #40
0
    if planet.transit_time != None:
        print(" Transit time: %.2d:%.2d:%.2d" %
              (ephem.localtime(planet.transit_time).hour,
               ephem.localtime(planet.transit_time).minute,
               ephem.localtime(planet.transit_time).second))
    else:
        print("")

    if planet.name == "Moon":
        print(color + "Next new Moon: %s" % ephem.next_new_moon(x))
        print(color +
              "Next first quarter Moon: %s" % ephem.next_first_quarter_moon(x))
        print(color + "Next full Moon: %s" % ephem.next_full_moon(x))
        print(color +
              "Next last quarter Moon: %s" % ephem.next_last_quarter_moon(x))
        print(color + "Moon distance from earth: %.2f meters\n" %
              (planet.earth_distance * ephem.meters_per_au))
    if planet.name == "Sun":
        if planet.alt > 0:
            print("Sunset: %s" %
                  (ephem.localtime(observer.next_setting(planet))))
        else:
            print("Sunset: %s" %
                  (ephem.localtime(observer.previous_setting(planet))))
        print("Sunrise: %s" %
              (ephem.localtime(observer.previous_rising(planet))))
        print("")

print(bcolors.ENDC)
Пример #41
0
    def GetMoonInfo(self):
        try:
            now = datetime.datetime.now()

            moon = ephem.Moon()
            moon.compute(self.myObserver)

            moon_altitude = moon.alt
            moon_azimuth = moon.az
            moon_compass = AU.AzimuthToCompassDirection(moon_azimuth)
            moon_constellation = ephem.constellation(moon)[1]

            moon_visible = True if moon_altitude > 0 else False

            rise_time_ut = self.myObserver.next_rising(moon)
            rise_time_local = str(ephem.localtime(rise_time_ut))

            set_time_ut = self.myObserver.next_setting(moon)
            set_time_local = str(ephem.localtime(set_time_ut))

            altitude_string = str(moon_altitude)
            rise_details = ""
            set_details = ""
            if moon_altitude <= 0:
                altitude_string += " (Not visible)"

                time_until_rise = ephem.localtime(rise_time_ut) - datetime.datetime.now()
                hours_until_rise = time_until_rise.seconds / 60 / 60
                minutes_until_rise = time_until_rise.seconds / 60

                if hours_until_rise > 0:
                    minutes_until_rise -= hours_until_rise * 60
                    rise_details += str(hours_until_rise)
                    if hours_until_rise > 1:
                        rise_details += " hours"
                    else:
                        rise_details += " hour"
                rise_details += " " + str(minutes_until_rise) + " minutes from now"
            else:
                altitude_string = altitude_string + " (Visible)"

            time_until_set = ephem.localtime(set_time_ut) - datetime.datetime.now()
            hours_until_set = time_until_set.seconds / 60 / 60
            minutes_until_set = time_until_set.seconds / 60
            if hours_until_set > 0:
                minutes_until_set -= hours_until_set * 60
                set_details += str(hours_until_set)
                if hours_until_set > 1:
                    set_details += " hours"
                else:
                    set_details += " hour"
            set_details += " " + str(minutes_until_set) + " minutes from now"

            next_rise_local = str(ephem.localtime(rise_time_ut))
            if rise_details <> "":
                next_rise_local += " (" + rise_details + ")"

            next_set_local = str(ephem.localtime(set_time_ut))
            if set_details <> "":
                next_set_local += " (" + set_details + ")"

            dictionaryData = {}
            dictionaryData["Name"] = "Moon"
            dictionaryData["Altitude"] = str(moon_altitude)
            dictionaryData["IsVisible"] = moon_visible
            dictionaryData["Azimuth"] = str(moon_azimuth)
            dictionaryData["Compass"] = str(moon_compass)
            dictionaryData["InConstellation"] = moon_constellation
            dictionaryData["NextRiseUT"] = str(rise_time_ut)
            dictionaryData["NextRiseLocal"] = str(rise_time_local)
            dictionaryData["NextRiseUntil"] = str(rise_details)
            dictionaryData["NextSetUT"] = str(set_time_ut)
            dictionaryData["NextSetLocal"] = str(set_time_local)
            dictionaryData["NextSetUntil"] = str(set_details)
            dictionaryData["Phase"] = str(moon.phase)
            dictionaryData["NextFirstQuarter"] = str(ephem.next_first_quarter_moon(now))
            dictionaryData["NextFull"] = str(ephem.next_full_moon(now))
            dictionaryData["NextLastQuarter"] = str(ephem.next_last_quarter_moon(now))
            dictionaryData["NextNew"] = str(ephem.next_new_moon(now))

            if self.prettyprint == True:
                json_string = json.dumps(dictionaryData, sort_keys=True, indent=4, separators=(",", ": "))
            else:
                json_string = json.dumps(dictionaryData, sort_keys=True, separators=(",", ": "))

            return json_string

        except Exception as ex:
            print str(ex)
            return ""
Пример #42
0
 def do_thread_loop(self):
     while (self.running):
         if (self.mqtt_connected):
             nowtime = datetime.datetime.now()
             if (nowtime.year != self.year):
                 self.year = nowtime.year
                 self.mqttc.publish("/raw/clock/year",
                                    self.year,
                                    retain=True)
             if (nowtime.month != self.month):
                 self.month = nowtime.month
                 self.mqttc.publish("/raw/clock/month",
                                    self.month,
                                    retain=True)
             if (nowtime.day != self.day):
                 self.day = nowtime.day
                 self.mqttc.publish("/raw/clock/day", self.day, retain=True)
                 self.weekday = nowtime.weekday()
                 self.mqttc.publish("/raw/clock/weekday",
                                    self.weekday,
                                    retain=True)
                 self.utc_sunrise = self.observer.next_rising(self.sun)
                 #                    self.mqttc.publish("/raw/clock/utc_sunrise", str(self.utc_sunrise), retain=True)
                 self.sunrise = ephem.localtime(
                     self.observer.next_rising(self.sun))
                 self.mqttc.publish("/raw/clock/sunrise",
                                    str(self.sunrise),
                                    retain=True)
                 self.utc_sunset = self.observer.next_setting(self.sun)
                 #                    self.mqttc.publish("/raw/clock/utc_sunset", str(self.utc_sunset), retain=True)
                 self.sunset = ephem.localtime(
                     self.observer.next_setting(self.sun))
                 self.mqttc.publish("/raw/clock/sunset",
                                    str(self.sunset),
                                    retain=True)
                 self.utc_moonrise = self.observer.next_rising(self.moon)
                 #                    self.mqttc.publish("/raw/clock/utc_moonrise", str(self.utc_moonrise), retain=True)
                 self.moonrise = ephem.localtime(
                     self.observer.next_rising(self.moon))
                 self.mqttc.publish("/raw/clock/moonrise",
                                    str(self.moonrise),
                                    retain=True)
                 self.utc_moonset = self.observer.next_setting(self.moon)
                 #                    self.mqttc.publish("/raw/clock/utc_moonset", str(self.utc_moonset), retain=True)
                 self.moonset = ephem.localtime(
                     self.observer.next_setting(self.moon))
                 self.mqttc.publish("/raw/clock/moonset",
                                    str(self.moonset),
                                    retain=True)
                 self.nextnewmoon = ephem.next_new_moon(nowtime)
                 self.mqttc.publish("/raw/clock/nextnewmoon",
                                    str(self.nextnewmoon),
                                    retain=True)
                 self.nextfirstquartermoon = ephem.next_first_quarter_moon(
                     nowtime)
                 self.mqttc.publish("/raw/clock/nextfirstquartermoon",
                                    str(self.nextfirstquartermoon),
                                    retain=True)
                 self.nextlastquartermoon = ephem.next_last_quarter_moon(
                     nowtime)
                 self.mqttc.publish("/raw/clock/nextlastquartermoon",
                                    str(self.nextlastquartermoon),
                                    retain=True)
                 self.nextfullmoon = ephem.next_full_moon(nowtime)
                 self.mqttc.publish("/raw/clock/nextfullmoon",
                                    str(self.nextfullmoon),
                                    retain=True)
             if (nowtime.hour != self.mil_hour):
                 self.mil_hour = nowtime.hour
                 self.hour = self.mil_hour % 12
                 if (self.hour == 0):
                     self.hour = 12
                 self.mqttc.publish("/raw/clock/hour",
                                    self.hour,
                                    retain=True)
                 self.mqttc.publish("/raw/clock/militaryhour",
                                    self.mil_hour,
                                    retain=True)
                 if (self.mil_hour > 11):
                     self.ampm = "PM"
                 else:
                     self.ampm = "AM"
                 if ((self.mil_hour == 12) or (self.mil_hour == 0)):
                     self.mqttc.publish("/raw/clock/ampm",
                                        self.ampm,
                                        retain=True)
             if (nowtime.minute != self.minute):
                 self.minute = nowtime.minute
                 self.mqttc.publish("/raw/clock/minute",
                                    self.minute,
                                    retain=True)
             if (nowtime < self.sunrise):  # is this right???
                 temp = "set"
             elif (nowtime > self.sunset):
                 temp = "set"
             else:
                 temp = "rise"
             if (temp != self.sunstate):
                 self.sunstate = temp
                 self.mqttc.publish("/raw/clock/sunstate",
                                    self.sunstate,
                                    retain=True)
             if (self.interval):
                 print "Waiting ", self.interval, " seconds for next update."
                 time.sleep(self.interval)
Пример #43
0
osaka = ephem.Observer()
osaka.lat = '34.6914'
osaka.lon = '135.4917'
osaka.date = datetime.datetime.utcnow()

# 月
moon = ephem.Moon()

# 次回 月の出・月の入り等を表示
print("次の月の出  : ", ephem.localtime(osaka.next_rising(moon)))
print("次の月の入り : ", ephem.localtime(osaka.next_setting(moon)))

print("次の新月 : ", ephem.localtime(ephem.next_new_moon(osaka.date)))
print("次の上弦 : ", ephem.localtime(ephem.next_first_quarter_moon(osaka.date)))
print("次の満月 : ", ephem.localtime(ephem.next_full_moon(osaka.date)))
print("次の下弦 : ", ephem.localtime(ephem.next_last_quarter_moon(osaka.date)))
print("現在の月齢 : ", osaka.date - ephem.previous_new_moon(osaka.date))

# 月と太陽の離角を計算
moon.compute(osaka)
moon_elong = np.rad2deg(moon.elong)

# 描画領域を準備
fig = plt.figure(figsize=(5, 5))
ax = fig.gca(projection='3d')

# x, y, z軸の範囲設定
ax.set_xlim([-1., 1.])
ax.set_ylim([-1., 1.])
ax.set_zlim([-1., 1.])
Пример #44
0
sunset  = observer.next_setting   (ephem.Sun()) #Sunset

data['sunrise'] = str(ephem.localtime(sunrise))
data['noon']    = str(ephem.localtime(noon))
data['sunset']  = str(ephem.localtime(sunset))

# observer.horizon = '-6' # civil twilight
# civilian_twilight_start = observer.previous_rising(ephem.Sun())
# civilian_twilight_end = observer.next_setting(ephem.Sun())

# observer.horizon = '-12' # nautical twilight
# nautical_twilight_start = observer.previous_rising(ephem.Sun())
# nautical_twilight_end = observer.next_setting(ephem.Sun())

# observer.horizon = '-18' # astronomical twilight
# astronomical_twilight_start = observer.previous_rising(ephem.Sun())
# astronomical_twilight_end = observer.next_setting(ephem.Sun())

data['moon'] = {}
data['moon']['radius'] = ephem.moon_radius
data['moon']['previous_new_moon'] = str(ephem.localtime(ephem.previous_new_moon(time)))
data['moon']['next_new_moon'] = str(ephem.localtime(ephem.next_new_moon(time)))
data['moon']['previous_first_quarter_moon'] = str(ephem.localtime(ephem.previous_first_quarter_moon(time)))
data['moon']['next_first_quarter_moon'] = str(ephem.localtime(ephem.next_first_quarter_moon(time)))
data['moon']['previous_full_moon'] = str(ephem.localtime(ephem.previous_full_moon(time)))
data['moon']['next_full_moon'] = str(ephem.localtime(ephem.next_full_moon(time)))
data['moon']['previous_last_quarter_moon'] = str(ephem.localtime(ephem.previous_last_quarter_moon(time)))
data['moon']['next_last_quarter_moon'] = str(ephem.localtime(ephem.next_last_quarter_moon(time)))

print json.dumps(data)