Beispiel #1
0
def visibility(ra, dec, observatory, time):

    source = SkyCoord(ra=Angle(ra * u.deg), dec=(dec * u.deg))
    location = observatory.position

    time = Time(time)

    altaz = source.transform_to(AltAz(obstime=time, location=location))
    altaz_sun = get_sun(time).transform_to(
        AltAz(obstime=time, location=location))
    altaz_moon = get_moon(time).transform_to(
        AltAz(obstime=time, location=location))

    delta_time = np.linspace(0, 24, 200) * u.hour

    frame = AltAz(obstime=time + delta_time, location=location)
    frame_night = source.transform_to(frame)
    frame_sun_night = get_sun(time + delta_time).transform_to(frame)
    frame_moon_night = get_moon(time + delta_time).transform_to(frame)
    moon_distance = np.mean(
        source.separation(
            SkyCoord(
                get_moon(time + delta_time).ra,
                get_moon(time + delta_time).dec)))
    sun_distance = np.mean(
        source.separation(
            SkyCoord(
                get_sun(time + delta_time).ra,
                get_sun(time + delta_time).dec)))
    date = ephem.Date(time.value)
    moon_phase = (date - ephem.previous_new_moon(date)) / (
        ephem.next_new_moon(date) - ephem.previous_new_moon(date))

    return altaz, delta_time, frame_night, frame_sun_night, moon_distance, sun_distance, moon_phase
Beispiel #2
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 ''
Beispiel #3
0
def s2l(solarDate: ephem.Date, location: ephem.Observer,
        timezone: int) -> LUNAR_contract:
    solarDate += timezone * ephem.hour  # so we are working in the correct timezone

    lunar_leap = False

    previousNewMoon = ephem.previous_new_moon(solarDate)
    lunarDay = solarDate.day - ephem.Date(previousNewMoon).datetime().day + 1

    # Dong chi nam truoc
    previousWinterSolstice = ephem.previous_winter_solstice(solarDate)
    # Dong chi nam sau
    nextWinterSolstice = ephem.next_winter_solstice(solarDate)

    dayInLunarYear = ephem.previous_new_moon(
        nextWinterSolstice) - ephem.previous_new_moon(previousWinterSolstice)

    diff = int(dayInLunarYear / 29.)

    lunarMonth = diff + 11

    lunarYear = solarDate.year

    if dayInLunarYear > 365:
        lunar_leap = (lunarMonth == find_lunar_month_between(
            previousWinterSolstice, nextWinterSolstice))

    print(dayInLunarYear, previousWinterSolstice, nextWinterSolstice)
    return tuple(date(lunarYear, lunarMonth, lunarDay), lunar_leap)
Beispiel #4
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])
Beispiel #5
0
def moon_age(now=None):
    if now is None:
        now = ephem.now()
    pmoon = ephem.previous_new_moon(now)
    nmoon = ephem.next_new_moon(now)
    deltamoon = nmoon - pmoon
    since_new = now - ephem.previous_new_moon(now)
    till_new = now - ephem.next_new_moon(now)
    print(since_new, deltamoon / 2.0)
    if since_new > deltamoon / 2.0:
        age = till_new
    else:
        age = since_new

    return age
Beispiel #6
0
 def age(self):
     '''
     This function returns the age of the Moon (time since New).
     @return: The age of the Moon in days.
     '''
     prev_new = ephem.previous_new_moon(self._observer.date)
     return self._observer.date - prev_new
Beispiel #7
0
def moon_info():
    "A bit more useful information about the Moon"
    now = ephem.now()
    previous_new = ephem.previous_new_moon(now)
    moon_age = 24 * (now - previous_new)
    if moon_age <= 72:
        yield "☽ Young Moon: {:.1f} hours".format(moon_age)
    else:
        next_new = ephem.next_new_moon(now)
        moon_age = 24 * (next_new - now)
        if moon_age <= 72:
            yield "☽ Old Moon {:.1f} hours".format(moon_age)
    # where is the moon now
    moon.compute(now)
    distance = miles_from_au(moon.earth_distance)
    phase = moon.phase
    # where is the Moon one minute later
    now += ephem.minute
    moon.compute(now)
    ps = "⬆" if moon.phase > phase else "⬇"
    moved = miles_from_au(moon.earth_distance) - distance
    ds = "⬆" if moved > 0 else "⬇"
    mph = abs(60 * moved)
    yield "☽Phase {:.2f}%{}, {:,.1f} miles, {}{:.1f}mph".format(
        phase, ps, distance, ds, mph)
Beispiel #8
0
def equation_of_time(date):
    """returns equation of time, the suns transit time, 
    the moons transit-, antitransittime, age and percent illumination
    """
    obs = ephem.Observer()
    obs.date = date

    s = ephem.Sun()
    m = ephem.Moon()
    s.compute(date)
    m.compute(date)
    transs = str(obs.next_transit(s, start=date))[-8:-3]
    antim = str(obs.next_antitransit(m, start=date))[-8:-3]
    transm = str(obs.next_transit(m, start=date))[-8:-3]

    m.compute(date + 0.5)
    phase = int(round(m.phase))
    age = int(round((date + 0.5) - ephem.previous_new_moon(date + 0.5)))

    s.compute(date - 0.1)
    obs.date = date - 0.1
    eqt00 = ephem.hours(round((obs.next_antitransit(s) - date) * 86400) / 86400 * 2 * math.pi)
    eqt00 = str(eqt00)[-8:-3]
    eqt12 = ephem.hours(round((obs.next_transit(s) - (date + 0.5)) * 86400) / 86400 * 2 * math.pi)
    eqt12 = str(eqt12)[-8:-3]

    return eqt00, eqt12, transs, transm, antim, age, phase
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'
Beispiel #10
0
def phase_on_day(date):
    nnm = ephem.next_new_moon(date)
    pnm = ephem.previous_new_moon(date)

    lunation = (date - pnm) / (nnm - pnm)

    return lunation
Beispiel #11
0
def equation_of_time(date):
    """returns equation of time, the suns transit time, 
    the moons transit-, antitransittime, age and percent illumination
    """
    obs = ephem.Observer()
    obs.date = date
    
    s = ephem.Sun()
    m = ephem.Moon()
    s.compute(date)
    m.compute(date)
    transs = str(obs.next_transit(s,start=date))[-8:-3]
    antim = str(obs.next_antitransit(m,start=date))[-8:-3]
    transm = str(obs.next_transit(m,start=date))[-8:-3]
    
    m.compute(date+0.5)
    phase = int(round(m.phase))
    age = int(round((date+0.5)-ephem.previous_new_moon(date+0.5)))
    
    s.compute(date-0.1)
    obs.date = date-0.1
    eqt00 = ephem.hours(round((obs.next_antitransit(s)-date)*86400)/86400*2*math.pi)
    eqt00 = str(eqt00)[-8:-3]
    eqt12 = ephem.hours(round((obs.next_transit(s)-(date+0.5))*86400)/86400*2*math.pi)
    eqt12 = str(eqt12)[-8:-3]
    
    return eqt00,eqt12,transs,transm,antim,age,phase
Beispiel #12
0
 def age(self):
     '''
     This function returns the age of the Moon (time since New).
     @return: The age of the Moon in days.
     '''
     prev_new = ephem.previous_new_moon(self._observer.date)
     return self._observer.date - prev_new
Beispiel #13
0
 def timeFromNewMoon(self):
     '''
     This function calculates the time from the previous new moon.
     @returns: The time from new moon in decimal hours.
     '''
     prev_new_moon = ephem.previous_new_moon(self._observer.date)
     return MoonInfo.DAYS_TO_HOURS * (self._observer.date - prev_new_moon)
Beispiel #14
0
def getSunMoon(locationInfo):
    night = False
    meteoLocation = ephem.Observer()
    meteoLocation.lon = str(locationInfo['longitude'])
    meteoLocation.lat = str(locationInfo['latitude'])
    meteoLocation.elevation = locationInfo['elevation']
    d = datetime.datetime.utcnow()
    localTime = ephem.localtime(ephem.Date(d))
    information("local time: " + str(localTime))
    information("universal time: " + str(d))
    meteoLocation.date = ephem.Date(d)
    sun = ephem.Sun(meteoLocation)
    moon = ephem.Moon(meteoLocation)
    # information("Sun azimuth: %s altitude: %s"%(sun.az, sun.alt))
    altitude = sun.alt * 180 / 3.14125
    information("Sun elevation is: %.2f" % altitude)
    currentDate = ephem.Date(d)
    timeToNewMoon = ephem.next_new_moon(currentDate) - currentDate
    timeSinceLastNewMoon = currentDate - ephem.previous_new_moon(currentDate)
    period = timeToNewMoon + timeSinceLastNewMoon
    phase = timeSinceLastNewMoon / period
    information("Moon elevation is: %.2f and illumination is: %.2f" %
                (moon.alt * 180 / 3.14125, moon.phase))
    if altitude < -5:
        # information("will take night exposure...")
        night = True

    results = {
        "night": night,
        "sunElevation": altitude,
        "moonIllumination": moon.phase,
        "moonElevation": (moon.alt * 180 / 3.14125)
    }
    return results
Beispiel #15
0
def get_phase_on_day():
  """Returns a symbolic value and name for the current moon phase"""

  date=ephem.Date(datetime.datetime.now())

  nnm = ephem.next_new_moon    (date)
  pnm = ephem.previous_new_moon(date)

  lunation=(date-pnm)/(nnm-pnm)

  if lunation >= 0 and lunation <= 0.125:
      return "🌚 new"
  elif lunation >= 0.126 and lunation <= 0.25:
      return "🌒 waxing crescent"
  elif lunation >= 0.26 and lunation <= 0.375:
      return "🌓 first quarter"
  elif lunation >= 0.376 and lunation <= 0.5:
      return "🌔 waxing gibbous"
  elif lunation >= 0.51 and lunation <= 0.625:
      return lunation
      return "� full"
  elif lunation >= 0.626 and lunation <= 0.75:
      return "🌖 waning gibbous"
  elif lunation >= 0.76 and lunation <= 0.875:
      return "🌗 last quarter"
  elif lunation >= 0.876 and lunation <= 1.0:
      return "🌘 waning crescent"
Beispiel #16
0
def get_phase_on_day(year, month, day):
    date = ephem.Date(datetime.date(year, month, day))
    nnm = ephem.next_new_moon(date)
    pnm = ephem.previous_new_moon(date)
    lunation = (date - pnm) / (nnm - pnm)

    return lunation
Beispiel #17
0
 def timeFromNewMoon(self):
     '''
     This function calculates the time from the previous new moon.
     @returns: The time from new moon in decimal hours.
     '''
     prev_new_moon = ephem.previous_new_moon(self._observer.date)
     return MoonInfo.DAYS_TO_HOURS * (self._observer.date - prev_new_moon)
Beispiel #18
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()
Beispiel #19
0
def SunMoonInfo(Long, Lat, Elev, GMT_hours, f):
    #lookup coords from table Observatories
    #todo: add observatory elevation
    moon = ephem.Moon()
    moon.compute(ephem.now())

    observer = ephem.Observer()
    observer.lon, observer.lat, observer.elevation = Long, Lat, Elev  #'-87:49:55','42:08:09'

    #calc twilight by specifying below true horizon
    observer.horizon = '-9'  #value I use for sky brightness cutoff
    t1 = observer.previous_rising(ephem.Sun()) + (GMT_hours / 24.)
    t2 = observer.next_setting(ephem.Sun()) + (GMT_hours / 24.)
    twilight_morn = cleanup(str(ephem.Date(t1)))
    twilight_eve = cleanup(str(ephem.Date(t2)))

    #calc actual sunrise/set using true horizon
    observer.horizon = '0'
    s1 = observer.previous_rising(ephem.Sun()) + (GMT_hours / 24.)
    s2 = observer.next_setting(ephem.Sun()) + (GMT_hours / 24.)
    sunrise = cleanup(str(ephem.Date(s1)))
    sunset = cleanup(str(ephem.Date(s2)))

    #CHANGE ALL THIS TO WRITE TO FILE FOR THIS OBSERVATORY: use f.write(html stuff) ************************
    f.write("<p>&nbsp;</p>\n")
    f.write('<p class="courier">' + HardSpaces("Twilight: " + twilight_morn) +
            "</p>\n")
    f.write('<p class="courier">' + HardSpaces("Sunrise:  " + sunrise) +
            "</p>\n")
    f.write('<p class="courier">' + HardSpaces("Sunset:   " + sunset) +
            "</p>\n")
    f.write('<p class="courier">' + HardSpaces("Twilight: " + twilight_eve) +
            "</p>\n")

    f.write("<p>&nbsp;</p>\n")
    m1 = observer.previous_rising(ephem.Moon()) + (GMT_hours / 24.)
    m2 = observer.next_setting(ephem.Moon()) + (GMT_hours / 24.)
    m3 = ephem.previous_new_moon(ephem.now()) + (GMT_hours / 24.)
    f.write('<p class="courier">' +
            HardSpaces("Moonrise: " + cleanup(str(ephem.Date(m1)))) + "\n")
    f.write('<p class="courier">' +
            HardSpaces("Moonset:  " + cleanup(str(ephem.Date(m2)))) + "\n")
    f.write('<p class="courier">' + "Moon age: " +
            str(ephem.now() - ephem.previous_new_moon(ephem.now()))[0:4] +
            " days, %2.0f%% illuminated" % moon.phase + "</p>\n")
    #f.write( "New Moon: " + str(ephem.Date(m3))[0:10]  + "\n")
    f.write("<p>&nbsp;</p>\n")
Beispiel #20
0
 def age(self):
     '''
     This function returns the age of the Moon (time since New).
     @return: The age of the Moon in days.
     '''
     prev_new = ephem.previous_new_moon(self._observer.date)
     age = self._observer.date - prev_new
     return utils.StrFmt.floatString(age, 2)
Beispiel #21
0
 def getStart(self, year):
     start = ephem.date(str(year) + '/1/1')
     start = ephem.next_vernal_equinox(start)
     start = ephem.previous_new_moon(start)
     self.location.date = start
     moon.compute(self.location)
     start = self.location.next_rising(moon)
     return start
Beispiel #22
0
    def moonphase(self, MJD):

        ephemdate = ephem.Date((Time(MJD, format = 'mjd', scale = 'utc').isot).replace("T", " "))
        ephemnextnewmoon = ephem.next_new_moon(ephemdate)
        ephempreviousnewmoon = ephem.previous_new_moon(ephemdate)
        moonphase = min(ephemnextnewmoon - ephemdate, ephemdate - ephempreviousnewmoon)
        
        return moonphase
Beispiel #23
0
    def age(self):
        """The moon's age in days.

        Returns
        -------
        float
        """
        prev_new = ephem.previous_new_moon(self.observer.date)
        return self.observer.date - prev_new
Beispiel #24
0
def equation_of_time(date):  # used in twilighttab (section 3)
    # returns equation of time, the sun's transit time,
    # the moon's transit-, antitransit-time, age and percent illumination.
    # (Equation of Time = Mean solar time - Apparent solar time)

    py_date = date.tuple()
    py_obsdate = datetime.date(py_date[0], py_date[1], py_date[2])
    d = ephem.date(date - 30 * ephem.second)
    obs = ephem.Observer()
    obs.date = d
    ephem_sun.compute(d)
    ephem_moon.compute(d)
    transs = '--:--'
    antim = '--:--'
    transm = '--:--'

    next_s_tr = obs.next_transit(ephem_sun, start=d)
    if next_s_tr - obs.date < 1:
        transs = hhmm(next_s_tr)

    next_m_atr = obs.next_antitransit(ephem_moon, start=d)
    if next_m_atr - obs.date < 1:
        antim = hhmm(next_m_atr)

    next_m_tr = obs.next_transit(ephem_moon, start=d)
    if next_m_tr - obs.date < 1:
        transm = hhmm(next_m_tr)

#-----------------------------
    obs = ephem.Observer()
    obs.date = date

    ephem_moon.compute(date + 0.5)
    pct = int(round(ephem_moon.phase))  # percent of moon surface illuminated
    age = int(round((date + 0.5) - ephem.previous_new_moon(date + 0.5)))
    phase = ephem_moon.elong.norm + 0.0  # moon phase as float (0:new to π:full to 2π:new)

    ephem_sun.compute(date - 0.1)
    obs.date = date - 0.1

    # round to the second; convert back to days
    x = round(
        (obs.next_antitransit(ephem_sun) - date) * 86400) * 2 * math.pi / 86400
    eqt00 = ephem.hours(x)
    eqt00 = str(eqt00)[-8:-3]
    if x >= 0:
        eqt00 = r"\colorbox{{lightgray!80}}{{{}}}".format(eqt00)

    y = round((obs.next_transit(ephem_sun) -
               (date + 0.5)) * 86400) * 2 * math.pi / 86400
    eqt12 = ephem.hours(y)
    eqt12 = str(eqt12)[-8:-3]
    if y >= 0:
        eqt12 = r"\colorbox{{lightgray!80}}{{{}}}".format(eqt12)

    return eqt00, eqt12, transs, transm, antim, age, pct
Beispiel #25
0
def extract_year(target_year, point, lat, lon):
    url = "https://www.data.jma.go.jp/gmd/kaiyou/data/db/tide/suisan/txt/" + \
        str(target_year) + "/" + point + ".txt"
    data = {}
    with urllib.request.urlopen(url) as response:
        for line in response:
            strline = line.decode("utf-8")
            date_data = {}
            month = int(strline[74:76].strip())
            year = int("20" + strline[72:74].strip())
            day = int(strline[76:78].strip())
            # point = strline[78:80]
            tidedata = strline[0:72]
            date_data["tide"] = [
                int(tidedata[i * 3:i * 3 + 3])
                for i in range(len(tidedata) // 3)
            ]
            high_data = strline[80:108]
            high_time = [
                high_data[i * 7:i * 7 + 2] + ":" +
                high_data[i * 7 + 2:i * 7 + 4] for i in range(2)
            ]
            date_data["high_time"] = [
                "--:--" if i == "99:99" else i.replace(" ", "0")
                for i in high_time
            ]
            high_tide = [high_data[i * 7 + 4:i * 7 + 7] for i in range(2)]
            date_data["high_tide"] = [
                "--" if i == "999" else int(i) for i in high_tide
            ]
            low_data = strline[108:136]
            low_time = [
                low_data[i * 7:i * 7 + 2] + ":" + low_data[i * 7 + 2:i * 7 + 4]
                for i in range(2)
            ]
            date_data["low_time"] = [
                "--:--" if i == "99:99" else i.replace(" ", "0")
                for i in low_time
            ]
            low_tide = [low_data[i * 7 + 4:i * 7 + 7] for i in range(2)]
            date_data["low_tide"] = [
                "--" if i == "999" else int(i) for i in low_tide
            ]
            here = ephem.Observer()
            here.lat, here.lon = str(lat), str(lon)
            here.date = datetime(year, month, day, 3)  # noon JST
            sun = ephem.Sun()
            date_data["sunrise"] = ephem.localtime(
                here.previous_rising(sun)).strftime("%H:%M")
            date_data["sunset"] = ephem.localtime(
                here.next_setting(sun)).strftime("%H:%M")
            moon_age = here.date - ephem.previous_new_moon(here.date)
            date_data["tidetype"] = convert_tidetype_into_moonage(moon_age)
            date_data["date"] = datetime(year, month, day).strftime("%m/%d")
            data[datetime(year, month, day).strftime("%Y/%m/%d")] = date_data
    return data
Beispiel #26
0
 def _phase(self, offset=None):  # offset in minutes
     date = datetime.datetime.utcnow()
     cycle = 29.530588861
     if offset:
         date += dateutil.relativedelta.relativedelta(minutes=offset)
     self._obs.date = date
     self._orb.compute(self._obs)
     last = ephem.previous_new_moon(self._obs.date)
     frac = (self._obs.date - last) / cycle
     return int(round(frac * 8))
Beispiel #27
0
 def _phase(self, offset=None):  # offset in minutes
     date = datetime.datetime.utcnow()
     cycle = 29.530588861
     if offset:
         date += dateutil.relativedelta.relativedelta(minutes=offset)
     self._obs.date = date
     self._orb.compute(self._obs)
     last = ephem.previous_new_moon(self._obs.date)
     frac = (self._obs.date - last) / cycle
     return int(round(frac * 8))
Beispiel #28
0
    def fractional_age(self):
        """The moon's fractional age. Always less than 1.0.

        Returns
        -------
        float
        """
        prev_new = ephem.previous_new_moon(self.observer.date)
        next_new = ephem.next_new_moon(self.observer.date)
        return (self.observer.date - prev_new) / (next_new - prev_new)
Beispiel #29
0
    def time_from_new_moon(self):
        """The time (hours) from the previous new moon.

        This function calculates the time from the previous new moon.

        Returns
        -------
        float
        """
        previous_new_moon = ephem.previous_new_moon(self.observer.date)
        return MoonInfo.DAYS_TO_HOURS * (self.observer.date - previous_new_moon)
Beispiel #30
0
def getMoonPhase( n ):
    '''Returns the current moon phase as a percentage, starting from the new moon.'''
    datetime = n.format( )

    previous = RPNDateTime.convertFromEphemDate( ephem.previous_new_moon( datetime ) )
    next = RPNDateTime.convertFromEphemDate( ephem.next_new_moon( datetime ) )

    cycle = next - previous
    current = n - previous

    return current.total_seconds( ) / cycle.total_seconds( )
Beispiel #31
0
def get_phase_on_day(year, month, day):
    """Returns a floating-point number from 0-1. where 0=new, 0.25 = first_quarter, 0.5=full, 0.75 = last_quarter, 1=new"""

    date = ephem.Date(datetime.date(year, month, day))

    nnm = ephem.next_new_moon(date)
    pnm = ephem.previous_new_moon(date)

    lunation = (date - pnm) / (nnm - pnm)

    return lunation
Beispiel #32
0
def process_plan (target_list, time_string=''):
	#declare observing sites
	observatory = ephem.Observer()
	observatory.lat = observer_latitude
	observatory.lon = observer_logitude
	observatory.elev = observer_elevation
	observatory.pressure = 0

	if time_string != '':
		observatory.date = ephem.Date(time_string)- (observer_timezone * ephem.hour)

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

	###### Reporting Section

	print "Report for: %s " %(ut_to_local_string(observatory.date))
	print "---------------------------------" 

	observatory.horizon = '-18'
	moon_days = observatory.date - ephem.previous_new_moon(observatory.date)
	print "Astronomical twilight:\n\tNext ending: %s" %(ut_to_local_string(observatory.next_setting(ephem.Sun(),use_center=True)))
	print "\tNext beginning: %s" %(ut_to_local_string(observatory.next_rising(ephem.Sun(),use_center=True)))
	print "Moon age: %3.2f days -- Ilumination: %3.1f%%" % (moon_days, moon.phase)
	print "\tNext Moon rise: %s" % (ut_to_local_string(observatory.next_rising(moon)))
	print "\tNext Moon set: %s" % (ut_to_local_string(observatory.next_setting(moon)))
	observatory.horizon = '0'
	print "---------------------------------\n"

	for target in target_list:
	
		varstar = plan_to_ephem(target)
		varstar.compute(observatory)

		print "Target: %s" %(varstar.name)
		try:
			print "Altitude: %3.2f" % (math.degrees(varstar.alt))
			print "Azimuth: %3.2f" % (math.degrees(varstar.az))
			print "Next rise: %s" % (ut_to_local_string(observatory.next_rising(varstar)))
			print "Next set: %s" % (ut_to_local_string(observatory.next_setting(varstar)))
		except ephem.AlwaysUpError:
			print "Object is circumpolar"
		except ephem.NeverUpError:
			print "*** Transit is below horizon ***"
		transit = observatory.next_transit(varstar)	
		print "Next transit: %s " % (ut_to_local_string(transit))
		temp_date = observatory.date
		observatory.date = transit
		varstar.compute(observatory)
		moon.compute(observatory)
		print "Transit altitude: %3.2f deg" % (math.degrees(varstar.alt))
		print "Lunar separation: %s" % (ephem.separation(varstar, moon))
		observatory.date = temp_date
		print "\n"
Beispiel #33
0
    def _generate_moon(self, year, month, day):
        date = ephem.Date(datetime.date(year, month, day))

        preceding_new_moon = ephem.previous_new_moon(date)
        following_new_moon = ephem.next_new_moon(date)

        lunation = (date - preceding_new_moon) / (following_new_moon -
                                                  preceding_new_moon)

        VIEW_BOX_SIZE = 100
        return '<svg width="100%" viewBox="0 0 {0} {0}">{1}</svg>'.format(
            VIEW_BOX_SIZE, self._make_path(lunation, VIEW_BOX_SIZE))
Beispiel #34
0
def get_moon_phase_on_day(dtime):
    '''Returns a floating-point number from 0-1. where 0=new, 0.5=full, 1=new'''

    date = ephem.Date(dtime)
    #print(date)
    nnm = ephem.next_new_moon(date)
    pnm = ephem.previous_new_moon(date)
    #print("Prev ", pnm)
    #print("Next ", nnm)
    lunation = (date - pnm) / (nnm - pnm)

    return lunation
Beispiel #35
0
def compute_ephem(line1, line2, line3, time, time_step):
    #This function returns the time of the ephemeris (dtime), the ephemeris
    #of the satellite (Sc.ra.deg, Sc.dec.deg) (RA, DEC, elevation), whether the
    #satellite is in eclipse (e) (0=no,1=yes), the ephemeris of the moon
    #(Mc.ra.deg, Mc.dec.deg) (RA, DEC), the ephemeris of the sun (Suc.ra.deg,
    #Suc.dec.deg) (RA, DEC), and lunar phase (mp) (radians; 0=full, +/-pi =
    #new). All ephemerides are given in geocentric coordinates.

    import numpy as np
    from datetime import datetime, timedelta
    import math
    import ephem
    from astropy import units as u
    from astropy.coordinates import SkyCoord

    dt = time + timedelta(minutes = time_step)
    #Compute satellite and moon ephemerides
    sat_ephem = ephem.readtle(line1, line2, line3)
    sat_ephem.compute(dt)
    m = ephem.Moon(dt)
    m.compute(dt)
    su = ephem.Sun(dt)
    su.compute(dt)

    #Print ephemerides for manual checking.
    #print('Moon: %s %s' % (m.g_ra, m.g_dec))
    #print('Sun: %s %s' % (su.g_ra, su.g_dec))
    #print('Sat: %s %s' % (sat_ephem.a_ra, sat_ephem.a_dec))

    #Convert ephemeris to degrees
    Sc = SkyCoord(str(sat_ephem.a_ra) + ' ' + str(sat_ephem.a_dec),
                  unit=(u.hourangle, u.deg))
    Mc = SkyCoord(str(m.g_ra) + ' ' + str(m.g_dec),
                  unit=(u.hourangle, u.deg))
    Suc = SkyCoord(str(su.g_ra) + ' ' + str(su.g_dec),
                   unit=(u.hourangle, u.deg))

    #Compute lunar phase in absolute phase angle (radians)
    dtime = ephem.Date(dt)
    nnm = ephem.next_new_moon    (dtime)
    pnm = ephem.previous_new_moon(dtime)
    lunation=(dtime-pnm)/(nnm-pnm)
    mp = abs(lunation - 0.5)*2*math.pi

    #Determine if satellite is in eclipse
    if sat_ephem.eclipsed == False:
        e = 0
    if sat_ephem.eclipsed == True:
        e = 1

    #Returnt calculated values as a 10-element list
    return([dtime, Sc.ra.deg, Sc.dec.deg, sat_ephem.elevation, e,
            Mc.ra.deg, Mc.dec.deg, Suc.ra.deg, Suc.dec.deg, mp])
Beispiel #36
0
def getMoonPhase( n ):
    if not isinstance( n, RPNDateTime ):
        raise ValueError( '\'moon_phase\' expects a date-time argument' )

    datetime = n.to( 'utc' ).format( )

    previous = RPNDateTime.convertFromEphemDate( ephem.previous_new_moon( datetime ) ).getLocalTime( )
    next = RPNDateTime.convertFromEphemDate( ephem.next_new_moon( datetime ) ).getLocalTime( )

    cycle = next - previous
    current = n - previous

    return current.total_seconds( ) / cycle.total_seconds( )
Beispiel #37
0
 def cycle_pour_jour(date_string):
     """
     In: une date sous forme de string
     Out: la place du jour dans un cycle lunaire sur 28 jours
     """
     splitted_date_string = date_string.split("/")
     jour = int(splitted_date_string[0])
     mois = int(splitted_date_string[1])
     an = int(splitted_date_string[2])
     date = ephem.Date(datetime.date(an, mois, jour))
     nnm = ephem.next_new_moon(date)
     pnm = ephem.previous_new_moon(date)
     lunation = (date - pnm) / (nnm - pnm)
     return lunation * 28
Beispiel #38
0
    def moon_age(self, timestamp):
        """Return the age of the moon at the given time."""
        d1 = pyEphem.next_new_moon(timestamp).datetime()
        d2 = pyEphem.previous_new_moon(timestamp).datetime()

        # Check format of provided time. If it wasn't a timestamp, make it one.
        if isinstance(timestamp, datetime.datetime) is False:
            timestamp = timestamp.datetime()

        # Find the total time since new moon and then convert to days
        if (d1 - timestamp) < (timestamp - d2):
            return (timestamp - d1).total_seconds() / 3600. / 24.
        else:
            return (timestamp - d2).total_seconds() / 3600. / 24.
Beispiel #39
0
def getMoonPhase( n ):
    '''Returns the current moon phase as a percentage, starting from the new moon.'''
    if not isinstance( n, RPNDateTime ):
        raise ValueError( '\'moon_phase\' expects a date-time argument' )

    datetime = n.format( )

    previous = RPNDateTime.convertFromEphemDate( ephem.previous_new_moon( datetime ) )
    next = RPNDateTime.convertFromEphemDate( ephem.next_new_moon( datetime ) )

    cycle = next - previous
    current = n - previous

    return current.total_seconds( ) / cycle.total_seconds( )
Beispiel #40
0
def moonAge(time):
    """Return the age of the moon at the given time."""
    d1 = pyEphem.next_new_moon(time).datetime()
    d2 = pyEphem.previous_new_moon(time).datetime()

    # Check to see if the time was already a datetime. If not,
    # make it one
    if isinstance(time, datetime.datetime) is False:
        time = time.datetime()

    if (d1 - time) < (time - d2):
        return abs((d1 - time).total_seconds() / 3600. / 24.)
    else:
        return ((time - d2).total_seconds() / 3600. / 24.)
Beispiel #41
0
    def moon_age(self, timestamp):
        """Return the age of the moon at the given time."""
        d1 = pyEphem.next_new_moon(timestamp).datetime()
        d2 = pyEphem.previous_new_moon(timestamp).datetime()

        # Check format of provided time. If it wasn't a timestamp, make it one.
        if isinstance(timestamp, datetime.datetime) is False:
            timestamp = timestamp.datetime()

        # Find the total time since new moon and then convert to days
        if (d1 - timestamp) < (timestamp - d2):
            return (timestamp - d1).total_seconds() / 3600. / 24.
        else:
            return (timestamp - d2).total_seconds() / 3600. / 24.
Beispiel #42
0
 def _phase(self, offset=None):
     """
     Applies only for moon, returns the moon phase related to a cycle of approx. 29.5 days
     for the current time plus an offset
     :param offset: an offset given in minutes
     """
     date = datetime.datetime.utcnow()
     cycle = 29.530588861
     if offset:
         date += dateutil.relativedelta.relativedelta(minutes=offset)
     self._obs.date = date
     self._orb.compute(self._obs)
     last = ephem.previous_new_moon(self._obs.date)
     frac = (self._obs.date - last) / cycle
     return int(round(frac * 8))
def PrintGeneralInfo():
    moon = ephem.Moon()
    moon.compute(ephem.now())

    observer = ephem.Observer()
    observer.lon, observer.lat = '-87:49:55', '42:08:09'
    observer.horizon = '-9'  #value I use for sky brightness cutoff

    twilight_morn = cleanup(
        str(ephem.localtime(observer.previous_rising(ephem.Sun()))))
    twilight_eve = cleanup(
        str(ephem.localtime(observer.next_setting(ephem.Sun()))))

    observer.horizon = '0'
    sunrise = cleanup(
        str(ephem.localtime(observer.previous_rising(ephem.Sun()))))
    sunset = cleanup(str(ephem.localtime(observer.next_setting(ephem.Sun()))))

    print(" ")
    print("Twilight: " + twilight_morn)
    print("Sunrise:  " + sunrise)
    print("Sunset:   " + sunset)
    print("Twilight: " + twilight_eve)

    print(" ")
    print(
        "Moonrise: " +
        cleanup(str(ephem.localtime(observer.previous_rising(ephem.Moon())))))
    print("Moonset:  " +
          cleanup(str(ephem.localtime(observer.next_setting(ephem.Moon())))))
    print("Moon age: " +
          str(ephem.now() - ephem.previous_new_moon(ephem.now()))[0:4] +
          " days, %2.0f%% illuminated" % moon.phase)
    print("New Moon: " +
          str(ephem.localtime(ephem.previous_new_moon(ephem.now())))[0:10])
    print('(all times local Chgo)\n\n')
Beispiel #44
0
 def _get_phase_on_day(self, date = datetime.date.today()):
     '''Returns a floating-point number from 0-1. where 0=new, 0.5=full, 1=new'''
     #Ephem stores its date numbers as floating points, which the following uses
     #to conveniently extract the percent time between one new moon and the next
     #This corresponds (somewhat roughly) to the phase of the moon.
     
     #Use Year, Month, Day as arguments
     date=ephem.Date(date)    
     nnm = ephem.next_new_moon    (date)
     pnm = ephem.previous_new_moon(date)     
     lunation=(date-pnm)/(nnm-pnm)
     
     #Note that there is a ephem.Moon().phase() command, but this returns the
     #percentage of the moon which is illuminated. This is not really what we want.
     
     return lunation
def get_current_moon_phase():
    """
    Get the current moon phase
    """
    # get the dates of the last and next new moon
    moon_observer.date = datetime.now()
    phase_end = ephem.next_new_moon(moon_observer.date)
    phase_start = ephem.previous_new_moon(moon_observer.date)

    
    # based on that figure out what part of the phase we are in. Phase goes from [0,1)
    phase = (moon_observer.date - phase_start) / (phase_end - phase_start)
    # 8 moon phases, so do this for easy indexing
    phase *= 8 
    # round to the nearest phase and wrap aroudn for the 7.5-7.9 range mapping to 0
    phase = round(phase) % 8
    
    return "The current moon phase is {0}".format(moon_phases[int(phase)])
Beispiel #46
0
    def calculate_moon_phase(self):

        m = ephem.Moon()
        m.compute(self.observer)

        nnm = ephem.next_new_moon(self.observer.date)
        pnm = ephem.previous_new_moon(self.observer.date)
        # for use w. moon_phases.ttf A -> just past  newmoon,
        # Z just before newmoon
        # '0' is full, '1' is new
        # note that we cannot use m.phase as this is the percentage of the moon
        # that is illuminated which is not the same as the phase!
        lunation = (self.observer.date - pnm) / (nnm - pnm)
        symbol = lunation * 26
        # print("Lunation as a 1/26 is: %f" % symbol)
        if symbol < 0.5 or symbol > 25.5:
            symbol = '*'  # new moon
        else:
            symbol = chr(ord('A') + int(symbol + 0.5) - 1)
        return symbol
Beispiel #47
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
Beispiel #48
0
def main(observer):
    date = ephem.now()
    moon = ephem.Moon(date)
    # Young or old Moon (within 72 hours of new)
    previous_new = ephem.previous_new_moon(date)
    age = 24 * (date - previous_new)
    if age <= 72:
        print("Young Moon: {:.1f} hours".format(age))
    else:
        next_new = ephem.next_new_moon(date)
        age = 24 * (next_new - date)
        if age <= 72:
            print("Old Moon: {:.1f} hours".format(age))

    print("Phase {0.moon_phase:.2%}".format(moon))
    distance = miles_from_au(moon.earth_distance)
    moon.compute(ephem.Date(date + ephem.hour))
    moved = miles_from_au(moon.earth_distance) - distance
    print(
        'Earth distance:    {:13,.0f} miles, {:+5.0f} mph'.format(
            distance, moved))
    observer.date = date
    moon.compute(observer)
    m2 = moon.copy()
    distance = miles_from_au(moon.earth_distance)
    observer.date = ephem.Date(date + ephem.hour)
    moon.compute(observer)
    moved = miles_from_au(moon.earth_distance) - distance
    print(
        'Observer distance: {:13,.0f} miles, {:+5.0f} mph'.format(
            distance, moved))
    print("Azimuth {}".format(_(m2.az)))
    print("Altitude {}".format(_(m2.alt)))
    print("Declination {}".format(_(m2.dec)))
    print("\n")
    for event in moon_phase_events():
        print(str(event))
Beispiel #49
0
def sf_sun_moon(date):
    sf = ep.Observer()
#sf.pressure = 0
#sf.horizon = '-0:34'
    sf.lat, sf.lon = '37.46', '-122.26'
    sf.date = date + ' 20:00' # noon PST
    sun_rise = (sf.previous_rising(ep.Sun()))
    sun_set = (sf.next_setting(ep.Sun()))
    sf.date = date + ' 09:00' # 1am PST
    moon_rise = (sf.previous_rising(ep.Moon()))
#    print 'mrise', moon_rise
    moon_set = (sf.next_setting(ep.Moon()))
#    print 'mset', moon_set
    sun = ep.localtime(sun_set) - ep.localtime(sun_rise)
    sun_min = sun.total_seconds() / 60
    moon = ep.localtime(moon_set) - ep.localtime(moon_rise)
#    print 'moon', moon
    moon_min = moon.total_seconds() / 60
#    print 'moonmin', moon_min
    
    nnm = ep.next_new_moon(date)
    pnm = ep.previous_new_moon(nnm)
    lunation=(sf.date-pnm)/(nnm-pnm)
    return sun_min, lunation
Beispiel #50
0
gatech = ephem.Observer()
gatech.lon = '-84.39733'
gatech.lat = '33.775867'
gatech.elevation = 320
gatech.date = '1984/5/30 16:22:56'
v = ephem.Venus(gatech)
print v.alt, v.az

m = ephem.Moon('1980/6/1')
print ephem.constellation(m)
print ephem.delta_t('1980')

ephem.julian_date('2000/1/1')

print ephem.previous_new_moon(ephem.now())
print ephem.next_new_moon(ephem.now())
# localtime
print ephem.localtime(ephem.next_new_moon(ephem.now()))

print ephem.previous_full_moon(ephem.now())
print ephem.next_full_moon(ephem.now())
# localtime
print ephem.localtime(ephem.next_full_moon(ephem.now()))

rigel = ephem.star('Rigel')
print rigel._ra, rigel._dec

# astronomical constants
print ephem.meters_per_au
print ephem.earth_radius
Beispiel #51
0
	output = True
	JSON = False
	if arg.json:
		output = False
		JSON = True

	if arg.date == 'now':	
		currentDate = ephem.Date(datetime.datetime.utcnow())
	else:
		currentDate = ephem.Date(arg.date)	
	if output: print currentDate
	moon.compute(currentDate)
	if output: print "Illuminated:", moon.phase
	if output: print "Next new moon:", ephem.next_new_moon(currentDate)
	timeToNewMoon = ephem.next_new_moon(currentDate) - currentDate
	timeSinceLastNewMoon = currentDate - ephem.previous_new_moon(currentDate)
	period = timeToNewMoon + timeSinceLastNewMoon
	phase = timeSinceLastNewMoon / period
	if output: 
		print timeSinceLastNewMoon, phase
		print timeToNewMoon
	
	if phase>0.5:
		mode = "waning"
	else:
		mode = "waxing" 
	if output: print "%1.0f%% illuminated, %s"%(moon.phase, mode)
	
	if JSON:
		response = {}
		response['illuminated'] = moon.phase
Beispiel #52
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)
Beispiel #53
0
def moonphase(year, month, day, do_print=False):
    h = year // 100             # integer division for the century
    yy = year % 100             # year within the century

    # The "golden number" for this year is the year modulo 19, but
    # adjusted to be centered around 0 -- i.e., -9 to 9 instead
    # of 0 to 19.  This improves the accuracy of the approximation
    # to within +/- 1 day.
    g = (yy + 9) % 19 - 9

    # There is an interesting 6 century near-repetition in the
    # century correction.  It would be interesting to find a
    # algorithm that handles the different corrections between
    # centuries 17|23|29, 20|26, 21|27, and 24|30.

    try:
        c = {17:7,
             18:1, 19:-4, 20:-8, 21:16, 22:11, 23:6,
             24:1, 25:-4, 26:-9, 27:15, 28:11, 29:6,
             30:0}[h]
    except KeyError:
        print("No century correction available for {}00-{}99".format(h,h))
        return

    # Golden number correction:  modulo 30, from -29 to 29.
    gc = g * 11
    while ( gc < -29 ): gc += 30;
    if (gc > 0): gc %= 30;

    # January/February correction:
    if month < 3:
       mc = 2
    else:
       mc = 0

    phase = (month + mc + day + gc + c + 30 ) % 30

    if (do_print):
        # It's nice to see what the Golden correction for the year
        # plus the century correction is.  This lets us quickly calculate the
        # correction for any other date in the same year.
        gcpc = (gc + c) % 30
        if gcpc <= 0:
            gcpc_alt = gcpc + 30
        else:
            gcpc_alt = gcpc - 30

        print("yy =", yy)
        print("g =", g)
        print("month + day + mc =", month + day + mc)
        print("gc =", gc)
        print("c =", c)
        print("Dates in the year", year,
              "have moon phase correction gc + c =",
              gcpc, "or", gcpc_alt)
        print(("\n\t{:04}/{:02}/{:02} has "
               "estimated moon phase = {}\n").format(year,
                                                   month,
                                                   day,
                                                   phase))
        if phase < 2:
            print("\tNew moon [or slightly after]")
        elif phase < 7:
            print("\tWaxing crescent")
        elif phase < 9:
            print("\tFirst quarter")
        elif phase < 14:
            print("\tWaxing gibbous")
        elif phase < 16:
            print("\tFull moon")
        elif phase < 22:
            print("\tWaning gibbous")
        elif phase < 24:
            print("\tLast quarter")
        elif phase < 29:
            print("\tWaning (de)crescent")
        elif phase < 31:
            print("\tNew moon [or slightly before]")

        try:
            # If you have the ephem package installed, you
            # can compare the estimate to the actual lunar phase
            import ephem
            thisdate = ephem.Date('{:04}/{:02}/{:02} 00:00:01'.format(year, month, day))
            prevmoon = ephem.previous_new_moon(thisdate)
            nextmoon = ephem.next_new_moon(thisdate)
            prevfull = ephem.previous_full_moon(thisdate)
            nextfull = ephem.next_full_moon(thisdate)
            prevymd = prevmoon.tuple()[:3]
            nextymd = nextmoon.tuple()[:3]
            pfymd = prevfull.tuple()[:3]
            nfymd = nextfull.tuple()[:3]
            print("\n\t{}".format(prevmoon), "UTC = Previous New Moon")
            print("\t{}".format(nextmoon), "UTC = Next New Moon")
            print("\t{}".format(prevfull), "UTC = Previous Full Moon")
            print("\t{}".format(nextfull), "UTC = Next Full Moon")
            try:
                from convertdate import julianday
                thisjdc = julianday.from_gregorian(year, month, day)
                prevjdc = julianday.from_gregorian(*prevymd)
                nextjdc = julianday.from_gregorian(*nextymd)
                pfjdc = julianday.from_gregorian(*pfymd)
                nfjdc = julianday.from_gregorian(*nfymd)
                print("\t{:2} days since prev new moon".format(int(thisjdc - prevjdc)))
                print("\t{:2} days until next new moon".format(int(nextjdc - thisjdc)))
                print("\t{:2} days since prev full moon".format(int(thisjdc - pfjdc)))
                print("\t{:2} days until next full moon".format(int(nfjdc - thisjdc)))
            except:
                print("julianday doesn't work")
                pass
        except:
            pass

        try:
            # If you have convertdate installed, you can compare the lunar
            # phase to the hebrew calendar date:
            from convertdate import hebrew
            hyear, hmonth, hday = hebrew.from_gregorian(year, month, day)
            print("\n\tHebrew date = {} {}, {}\n".format( hday,
                                                          hmonths[hmonth],
                                                          hyear ))
        except:
            pass
    return phase
Beispiel #54
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()
Beispiel #55
0
def add_ephem_data_to_header(hdr, time_overwrite, debug=False):

    logger = logging.getLogger("SunMoonData")

    logger_debug = logger.debug
    if (debug): logger_debug = logger.info

    #
    # Read in the target coordinates
    #
    ra = hdr['RA']
    dec = hdr['DEC']
    target = ephem.Equatorial(hdr['RA'], hdr['DEC'])


    #
    # Convert the timing information from the header 
    # into a format that pyephem understands
    #
    date_format = "%Y-%m-%dT%H:%M:%S.%f"
    ephem_format = "%Y/%m/%d %H:%M:%S"
    time_format = "%H:%M:%S.%f"
    expmeas = hdr['EXPMEAS'] if 'EXPMEAS' in hdr \
        else hdr['EXPTIME']

    date_string = hdr['DATE-OBS'] if time_overwrite is None else time_overwrite
    date_obs = datetime.datetime.strptime(date_string, date_format)


    date_mid = date_obs + datetime.timedelta(seconds=(0.5*expmeas))
    date_end = date_obs + datetime.timedelta(seconds=expmeas)
    mjd = hdr['MJD-OBS']

    time_difference = 7*ephem.hour

    #
    # Create objects for sun, moon, and WIYN
    #
    sun = ephem.Sun()
    moon = ephem.Moon()

    wiyn = ephem.Observer()
    wiyn.lat = wiyn_lat
    wiyn.lon = wiyn_lon
    wiyn.elevation = wiyn_elevation
    wiyn.date = datetime.datetime.strftime(date_mid, ephem_format)


    logger_debug("Current time (UTC): %s" % (wiyn.date))
    logger_debug("Current coordinates: %s %s" % (target.ra, target.dec))

    # #
    # # Compute some stats for astronomical twilight
    # #
    # wiyn_astrotwilight = ephem.Observer()
    # wiyn_astrotwilight.lat = wiyn_lat
    # wiyn_astrotwilight.lon = wiyn_lon
    # wiyn_astrotwilight.elevation = wiyn_elevation
    # wiyn_astrotwilight.horizon = '-18.'
    # # wiyn_astrotwilight.date = datetime.datetime.strftime(date_mid, ephem_format)
    # sun_astrotwi = ephem.Sun()
    # sun_astrotwi.compute(wiyn_astrotwilight)

    # logger_debug("next sunrise: %s" % (ephem.localtime(wiyn.next_rising(ephem.Sun()))))
    # logger_debug("next sunset : %s" % (ephem.localtime(wiyn.next_setting(ephem.Sun()))))
    # logger_debug("last sunset : %s" % (ephem.localtime(wiyn.previous_setting(ephem.Sun()))))
    # logger_debug("next transit: %s" % (ephem.localtime(wiyn.next_transit(ephem.Sun()))))

    logger_debug("next sunrise (UT/WIYN): %19s  /  %19s" % (
        wiyn.next_rising(ephem.Sun()), ephem.date(wiyn.next_rising(ephem.Sun())-time_difference)))
    logger_debug("next sunset  (UT/WIYN): %19s  /  %19s" % (
        wiyn.next_setting(ephem.Sun()), ephem.date(wiyn.next_setting(ephem.Sun())-time_difference)))
    logger_debug("last sunset  (UT/WIYN): %19s  /  %19s" % (
        wiyn.previous_setting(ephem.Sun()), ephem.date(wiyn.previous_setting(ephem.Sun())-time_difference)))
    logger_debug("next transit (UT/WIYN): %19s  /  %19s" % (
        wiyn.next_transit(ephem.Sun()), ephem.date(wiyn.next_transit(ephem.Sun())-time_difference)))

    # logger_debug("next sunrise (WIYN): %s" % (ephem.date(wiyn.next_rising(ephem.Sun())-time_difference)))
    # logger_debug("next sunset  (WIYN): %s" % (ephem.date(wiyn.next_setting(ephem.Sun())-time_difference)))
    # logger_debug("last sunset  (WIYN): %s" % (ephem.date(wiyn.previous_setting(ephem.Sun())-time_difference)))
    # logger_debug("next transit (WIYN): %s" % (ephem.date(wiyn.next_transit(ephem.Sun())-time_difference)))


    # Compute the sun's position at WIYN
    sun.compute(wiyn)
    logger_debug("SUN:  alt=%-10s az=%-10s   RA=%-10s DEC=%-10s" % (
        sun.alt, sun.az, sun.ra, sun.dec)) #, " alt/az=", numpy.degrees(sun.alt)

    # and the Moon's position at WIYN
    moon.compute(wiyn)
    logger_debug("MOON: alt=%-10s az=%-10s   RA=%-10s DEC=%-10s  PHASE:%s" % (
        moon.alt, moon.az, moon.ra, moon.dec, moon.moon_phase)) 

    # Compute the position of the target on sky
    body = ephem.FixedBody(target)
    body._ra = target.ra
    body._dec = target.dec
    body._epoch = target.epoch
    body.compute(wiyn)

    # print "object-moon", ephem.separation(body, moon)
    # print "object-sun", ephem.separation(body, sun)
    # print "sun-sun", ephem.separation(sun, sun)
    # print "body-eq", ephem.separation(body, body2), hdr['DEC']

    logger_debug("Writing data to FITS header")

    #
    # Compute positions for sun and moon, and separation to the target 
    #

    # positions for the sun
    hdr['SUN__RA']  = (numpy.degrees(sun.ra),
                       "R.A. of Sun during obs         [deg]")
    hdr['SUN__DEC'] = (numpy.degrees(sun.dec),
                       "declination of Sun during obs  [deg]")
    hdr['SUN__ALT'] = (numpy.degrees(sun.alt),
                       "altitude of Sun during obs     [deg]")
    hdr['SUN__AZ']  = (numpy.degrees(sun.az),
                       "azimuth of Sun during obs      [deg]")

    # Positions for the moon
    hdr['MOON_RA']  = (numpy.degrees(moon.ra),
                       "R.A. of Moon during obs        [deg]")
    hdr['MOON_DEC'] = (numpy.degrees(moon.dec),
                       "declination of Moon during obs [deg]")
    hdr['MOON_ALT'] = (numpy.degrees(moon.alt),
                       "altitude of Moon during obs    [deg]")
    hdr['MOON_AZ']  = (numpy.degrees(moon.az),
                       "azimuth of Moon during obs     [deg]")

    # separation between sun/moon and target
    hdr['SUN__D']   = (numpy.degrees(ephem.separation(body, sun)),
                       "angle between target and sun   [deg]")
    hdr['MOON_D']   = (numpy.degrees(ephem.separation(body, moon)),
                       "angle between target and moon  [deg]")
    logger_debug("Distance object-moon (sun): %7.3f (%7.3f)" % (
        ephem.separation(body, moon), ephem.separation(body, sun)))



    # print
    # print "last sun transit    ", wiyn.previous_transit(ephem.Sun())
    # print "last sun rise       ", wiyn.previous_rising(ephem.Sun())
    # print "last sun set        ", wiyn.previous_setting(ephem.Sun())
    # print "next sun transit    ", wiyn.next_transit(ephem.Sun())
    # print "next sun rise       ", wiyn.next_rising(ephem.Sun())
    # print "next sun set        ", wiyn.next_setting(ephem.Sun())
    # print "next sun rise (-18) ", wiyn_astrotwilight.next_rising(ephem.Sun())
    # print "next sun set (-18)  ", wiyn_astrotwilight.next_setting(ephem.Sun())
    # print "current             ", wiyn.date, float(wiyn.date)
    # print "time to sunset:     ", (wiyn.next_setting(ephem.Sun())-wiyn.date)*24.,"hours"
    # # print "time since sunrise: ", wiyn.date-wiyn.previous_rising(sun), (wiyn.date-wiyn.previous_rising(sun))*24.
    # # print "time to sunset:     ", (wiyn.next_setting(sun)-wiyn.date)*24.,"hours"
    # # print "time since sunrise: ", (wiyn.date-wiyn.previous_rising(sun))*24.,"hours"
    # print "sun altitude:       ", sun.alt, float(sun.alt), float(sun.az)
    # print

    #
    # Compute times since/until sunset and sunrise
    # Make sure to compute times to the closest sunrise and sunset, i.e. 
    # computations are different for the morning and afternoon
    #
    if (sun.alt > 0):
        # The sun is up, let's figure out if we are just beyond sunrise 
        # or just before sunset (i.e. it's morning or afternoon)
        time_since_last_noon = wiyn.previous_transit(ephem.Sun())
        time_to_next_noon = wiyn.next_transit(ephem.Sun())

        time_to_sunset = wiyn.next_setting(ephem.Sun())-wiyn.date
        time_since_sunrise = wiyn.date-wiyn.previous_rising(ephem.Sun())
        if (time_to_sunset < time_since_sunrise):
            # We are close to sunset
            hdr['SUN_RISE'] = (24.*(wiyn.next_rising(ephem.Sun())-wiyn.date), 
                                             'time until sunrise [hours]')
            hdr['SUN_SET'] = (24.*(wiyn.date-wiyn.next_setting(ephem.Sun())), 
                                            'time since sunset [hours]')
        else:
            # We are still before noon
            hdr['SUN_RISE'] = (24.*(wiyn.previous_rising(ephem.Sun())-wiyn.date), 
                                             'time until sunrise [hours]')
            hdr['SUN_SET'] = (24.*(wiyn.date-wiyn.previous_setting(ephem.Sun())), 
                                            'time since sunset [hours]')

    else:
        # Sun is below the horizon
        hdr['SUN_RISE'] = (24.*(wiyn.next_rising(ephem.Sun())-wiyn.date), 
                                         'time until sunrise [hours]')
        hdr['SUN_SET'] = (24.*(wiyn.previous_setting(ephem.Sun())-wiyn.date), 
                                        'time since sunset [hours]')


    #
    # Compute times since/until moon rise and set
    #
    if (moon.alt > 0):
        # Moon is up
        hdr['MOON_RSE'] = (24.*(wiyn.previous_rising(moon)-wiyn.date), 
                                         'time since moon rise [hours]')
        hdr['MOON_SET'] = (24.*(wiyn.next_setting(moon)-wiyn.date), 
                                         'time until moon set [hours]')

    else:
        # Moon is down
        hdr['MOON_RSE'] = (24.*(wiyn.next_rising(moon)-wiyn.date), 
                                         'time until moon rise [hours]')
        hdr['MOON_SET'] = (24.*(wiyn.previous_setting(moon)-wiyn.date), 
                                         'time since moon set [hours]')



    # time_since_ast_twilight = 24.*(wiyn.date-wiyn_astrotwilight.previous_setting(ephem.Sun()))
    # time_until_ast_twilight = 24.*(wiyn_astrotwilight.next_rising(ephem.Sun())-wiyn.date)
    # # if (numpy.degrees(sun.alt) > -18. and time_since_ast_twilight > 12.):
    # #     time_since_ast_twilight = 24.*(wiyn.date-wiyn_astrotwilight.next_setting(ephem.Sun()))
    # # if (numpy.degrees(sun.alt) > -18. and time_since_to_twilight > 16.):
    # #     time_until_ast_twilight = 24.*(wiyn_astrotwilight.previous_rising(ephem.Sun())-wiyn.date)

    # hdr['SUN_RS18'] = (time_until_ast_twilight,
    #                                  'time until astronomical twilight [hours]')
    # hdr['SUN_ST18'] = (time_since_ast_twilight,
    #                                  'time since astronomical twilight [hours]')

    #
    # Determine sky brightness
    #
    moon.compute(wiyn)
    sun.compute(wiyn)
    skybrite = None
    sun_alt = numpy.degrees(sun.alt)
    if (sun_alt < -18.):
        if (numpy.degrees(moon.alt) < -18):
            skybrite = 'dark'
        else:
            if (moon.moon_phase > 0.5):
                skybrite = "bright"
            else:
                skybrite = "grey"
    elif (sun_alt >= -18 and sun_alt < -12):
        skybrite = "astro.twilight"
    elif (sun_alt >= -12 and sun_alt < -6):
        skybrite = "naut.twilight"
    elif (sun_alt >= -6 and sun_alt < 0):
        skybrite = "civil.twilight"
    else:
        skybrite = 'daytime'
    hdr['SKYBRITE'] = (skybrite, "sky brightness quality")

    #
    # Compute lunar age, i.e. days since/until new moon
    #
    lunar_age = wiyn.date - ephem.previous_new_moon(wiyn.date)
    moon_phase = moon.moon_phase
    moon_month = ephem.next_new_moon(wiyn.date) - ephem.previous_new_moon(wiyn.date)
    if (moon_phase <= 0.02):
        moon_phase_string = "new moon"
    elif (moon_phase < 0.47 and lunar_age <  0.5 * moon_month):
        moon_phase_string = "waxing crescent"
    elif (moon_phase < 0.47 and lunar_age >= 0.5 * moon_month):
        moon_phase_string = "waning crescent"
    elif (moon_phase < 0.53 and lunar_age <  0.5 * moon_month):
        moon_phase_string = "first quarter"
    elif (moon_phase < 0.53 and lunar_age >= 0.5 * moon_month):
        moon_phase_string = "last quarter"
    elif (moon_phase < 0.98 and lunar_age <  0.5 * moon_month):
        moon_phase_string = "waxing gibbous"
    elif (moon_phase < 0.98 and lunar_age >= 0.5 * moon_month):
        moon_phase_string = "waning gibbous"
    elif (moon_phase >= 0.98):
        moon_phase_string = "full moon"

    #if (ephem.previous_full_moon(wiyn.date) > ephem.previous_new_moon(wiyn.date)):
    #    lunar_age = wiyn.date - ephem.next_new_moon(wiyn.date)
    hdr['LUNARAGE'] = (lunar_age, "days since last new moon")
    add_fits_header_title(hdr, "Almanach data", 'SUN__RA')

    # Moon phase: fraction of moon that's illuminated by the sun
    lunar_age = wiyn.date - ephem.previous_new_moon(wiyn.date)
    hdr['MOONILUM'] = (moon.moon_phase, "Fraction of moon illuminated")
    hdr['MOONPHSE'] = (moon_phase_string, "Moon phase")
Beispiel #56
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import datetime
import ephem

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)
sun = ephem.Sun()
sun.compute(observer)

data['sun']['altitude'] = sun.alt
data['sun']['azimuth'] = sun.az

# MOON DATA
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())
Beispiel #58
0
print "target_day_hours:",datetime.timedelta(hours=12)
#print "last            :",datetime.timedelta(hours=12)-day_time
print "light on :",t2+datetime.timedelta(minutes=30)
print "lihgt off:",t2+datetime.timedelta(hours=12.5)-day_time

print ""

print "MOON DATA"
moon.compute(gifu)
moon_rize= gifu.next_rising(moon)
print ephem.localtime(moon_rize)
print moon.az
moon_noon= gifu.next_transit(moon)
print ephem.localtime(moon_noon)
print moon.alt
print moon.az
moon_set= gifu.next_setting(moon)
print ephem.localtime(moon_set)
print moon.az
print
#d = ephem.date(datetime.datetime.today())
today= ephem.date(datetime.datetime.today())
new_moon= ephem.previous_new_moon(today)
print "previous_new_moon"
print new_moon
print "moon_age"
print  today-new_moon
next_new_moon= ephem.next_new_moon(today)
print next_new_moon

m = ephem.Moon(site)
# Observer-based rise/set calculations modifies the body involved, so need to create
# 'disposable' ones we don't mind having modififed
s_loc = ephem.Sun(site)
m_loc = ephem.Moon(site)


print "\n*** Sun and Moon ***"
print "       BODY        | VIS |   ALT  |   AZ   |    RISE     |     SET     |  MAG  |"
print "-------------------+-----+--------+--------+-------------+-------------+-------+"
print_visinfo(s_loc,site)
print_visinfo(m_loc,site)
print "-------------------+-----+--------+--------+-------------+-------------+-------+"

print "\n*** Lunar Phase information: ***"
prev_new = ephem.previous_new_moon(now)
next_new = ephem.next_new_moon(now)
next_first = ephem.next_first_quarter_moon(now)
next_full = ephem.next_full_moon(now)
next_last = ephem.next_last_quarter_moon(now)

phase = m.moon_phase
lunation = (now-prev_new)/(next_new-prev_new)
# Elaborate on most recent lunar phase

print "Current lunar illumination is {:0.1f}%, lunation is {:0.4f}".format(phase*100,lunation)
if lunation < 0.25:
    print "Was just New Moon at {} UT".format(fmt_date(ephem.previous_new_moon(now)))
elif lunation < 0.5:
    print "Was just First Quarter at {} UT".format(fmt_date(ephem.previous_first_quarter_moon(now)))
elif lunation < 0.75: