Example #1
0
def talk_to_me(update, context):

    text = update.message.text
    planet_name = text.split()[-1]

    if planet_name == 'Mars':
        mars = ephem.Mars()
        mars.compute(ephem.Date(datetime.date.today()))
        result = ephem.constellation(mars)
        update.message.reply_text(result)

    if planet_name == 'Jupiter':
        jupiter = ephem.Jupiter()
        jupiter.compute(ephem.Date(datetime.date.today()))
        result = ephem.constellation(jupiter)
        update.message.reply_text(result)

    if planet_name == 'Mercury':
        mercury = ephem.Mercury()
        mercury.compute(ephem.Date(datetime.date.today()))
        result = ephem.constellation(mercury)
        update.message.reply_text(result)

    else:
        print(text)
        update.message.reply_text(text)
Example #2
0
def planet(bot, update):
    date = datetime.date.today()
    text_at = update.message.text.split(' ')[1].capitalize()
    if text_at == 'Sun':
        const = ephem.constellation(ephem.Sun(date))
    elif text_at == 'Mercury':
        const = ephem.constellation(ephem.Mercury(date))
    elif text_at == 'Venus':
        const = ephem.constellation(ephem.Venus(date))
    elif text_at == 'Earth':
        const = 'Неизвестная планета'
    elif text_at == 'Moon':
        const = ephem.constellation(ephem.Mars(date))
    elif text_at == 'Mars':
        const = ephem.constellation(ephem.Mars(date))
    elif text_at == 'Jupiter':
        const = ephem.constellation(ephem.Jupiter(date))
    elif text_at == 'Saturn':
        const = ephem.constellation(ephem.Saturn(date))
    elif text_at == 'Uranus':
        const = ephem.constellation(ephem.Uranus(date))
    elif text_at == 'Neptune':
        const = ephem.constellation(ephem.Neptune(date))
    elif text_at == 'Pluto':
        const = ephem.constellation(ephem.Pluto(date))
    else:
        const = 'Данные не доступны'
    update.message.reply_text(const)
Example #3
0
def planet(update, context):
    get_or_create_user(db, update.effective_user, update.message.chat.id)
    print(context.args)
    logging.info(context.args)
    if context.args[0].lower() == 'марс':
        logging.info('вызвана команда /planet Марс')
        now = datetime.datetime.now()
        mars = ephem.Mars(now)
        stars = ephem.constellation(mars)
        star_planet = (f'Сегодняшняя дата {now.strftime("%d-%m-%Y %H:%M")}.\n'
                       f'Планета Марс находится в созвездии {stars[1]}')
        update.message.reply_text(star_planet, reply_markup=main_keyboard())
    elif context.args[0].lower() == 'юпитер':
        logging.info('вызвана команда /planet Юпитер')
        now = datetime.datetime.now()
        jupiter = ephem.Jupiter(now)
        stars = ephem.constellation(jupiter)
        star_planet = (f'Сегодняшняя дата {now.strftime("%d-%m-%Y %H:%M")}.\n'
                       f'Планета Юпитер находится в созвездии {stars[1]}')
        update.message.reply_text(star_planet, reply_markup=main_keyboard())
    elif context.args[0].lower() == 'венера':
        logging.info('вызвана команда /planet Венера')
        now = datetime.datetime.now()
        venus = ephem.Venus(now)
        stars = ephem.constellation(venus)
        star_planet = (f'Сегодняшняя дата {now.strftime("%d-%m-%Y %H:%M")}.\n'
                       f'Планета Венера находится в созвездии {stars[1]}')
        update.message.reply_text(star_planet, reply_markup=main_keyboard())
    else:
        logging.info('вызвана команда неизвестная планета')
        update.message.reply_text('Такой планеты нет в моём списке!',
                                  reply_markup=main_keyboard())
Example #4
0
def planet(bot, update):
    print('planet')
    user_text = update.message.text.split()
    print(user_text)
    update.message.reply_text(user_text[1])
    user_text[1] = user_text[1].lower()

    if user_text[1] == 'mercury':
        m = ephem.Mercury(datetime.datetime.now())

    elif user_text[1] == 'venus':
        m = ephem.Venus(datetime.datetime.now())

    elif user_text[1] == 'mars':
        m = ephem.Mars(datetime.datetime.now())

    elif user_text[1] == 'jupiter':
        m = ephem.Jupiter(datetime.datetime.now())

    elif user_text[1] == 'saturn':
        m = ephem.Saturn(datetime.datetime.now())

    elif user_text[1] == 'uranus':
        m = ephem.Uranus(datetime.datetime.now())

    elif user_text[1] == 'neptune':
        m = ephem.Neptune(datetime.datetime.now())

    print(ephem.constellation(m))
    update.message.reply_text(ephem.constellation(m))
Example #5
0
def constellation_planet (bot,update):
  platent_u = "/planet Mars"
  planet = platent_u.split()[1].capitalize()

  if planet=="Mars":
    search_planet = ephem.Mars('2020/05/26')
    ephem.constellation(search_planet)
Example #6
0
def coordinate_of_planet(bot, update):
    user_text = update.message.text.split()
    try:
        datetime.datetime.strptime(user_text[2], '%Y/%m/%d')
        coord_planet = getattr(ephem,
                               user_text[1].lower().capitalize())(user_text[2])
        coordinate = ephem.constellation(coord_planet)
        print(coordinate)
        update.message.reply_text(
            "{} расположен/а в созвездии {} на {}".format(
                user_text[1].lower().capitalize(), coordinate, user_text[2]))
    except IndexError:
        try:
            now = datetime.datetime.now()
            coord_planet = getattr(ephem, user_text[1].lower().capitalize())(
                now.strftime("%Y/%m/%d"))
            coordinate = ephem.constellation(coord_planet)
            print(coordinate)
            update.message.reply_text(
                "{} расположен/а в созвездии {} на {}".format(
                    user_text[1].lower().capitalize(), coordinate,
                    now.strftime("%Y/%m/%d")))
        except (IndexError, AttributeError):
            update.message.reply_text("Вам необходимо ввести планету")
    except ValueError:
        update.message.reply_text(
            "Введите запрос в таком формате: /planet Nameplanet(Mars) YYYY/mm/dd"
        )
Example #7
0
def planet_ephem(bot, update, args):
    date = datetime.datetime.now().strftime('%Y/%m/%d')

    if args[0] == 'Jupiter':
        planet_constellation = ephem.constellation(ephem.Jupiter(date))   #/planet Jupiter
    elif args[0] == 'Mars':
        planet_constellation = ephem.constellation(ephem.Mars(date))      #/planet Mars
    elif args[0] == 'Mercury':
        planet_constellation = ephem.constellation(ephem.Mercury(date))   #/planet Mercury
    elif args[0] == 'Moon':
        planet_constellation = ephem.constellation(ephem.Moon(date))      #/planet Moon
    elif args[0] == 'Neptune':
        planet_constellation = ephem.constellation(ephem.Neptune(date))   #/planet Neptune
    elif args[0] == 'Pluto':
        planet_constellation = ephem.constellation(ephem.Pluto(date))     #/planet Pluto
    elif args[0] == 'Saturn':
        planet_constellation = ephem.constellation(ephem.Saturn(date))    #/planet Saturn
    elif args[0] == 'Sun':
        planet_constellation = ephem.constellation(ephem.Sun(date))       #/planet Sun
    elif args[0] == 'Uranus':
        planet_constellation = ephem.constellation(ephem.Uranus(date))    #/planet Uranus
    elif args[0] == 'Venus':
        planet_constellation = ephem.constellation(ephem.Venus(date))     #/planet Venus
    
    text = planet_constellation

    update.message.reply_text(" Планета {0} находится в созвездии {1} на дату {2}".format(args[0], text[1], date ))
Example #8
0
def get_constellation(bot, update):
    user_text = update.message.text
    planet_name = user_text.split(' ')[1]
    if planet_name == 'Mars':
        date = datetime.datetime.now()
        planet = ephem.Mars(date.strftime('%Y/%m/%d'))
    print(ephem.constellation(planet))
    update.message.reply_text(ephem.constellation(planet))
def planet(bot, update):
    logging.info('User: %s, Chat id: %s, Message: %s', update.message.chat.first_name, update.message.chat.id,
                 update.message.text)
    planet = update.message.text.split()
    print(planet[1])
    const = ephem.Mars('05/10/2019')
    print(ephem.constellation(const))
    update.message.reply_text(ephem.constellation(const))
Example #10
0
def constellation_planet(bot, update):
    planet = ((update["message"]["text"].split()[1]).capitalize)

    if planet == "Mars":
        search_planet = ephem.Mars('2020/05/26')
        constellation = ephem.constellation(Mars)
        print(constellation)
        update.message.reply_text(ephem.constellation("Mars"))[1]
Example #11
0
def planet_user(bot, update):
    text = 'Для ввода названия планеты используйте "/planet [название планеты на англ]"'
    #planet = update.message.text.rsplit()
    planets = [
        'Sun', 'Moon', 'Mercury', 'Venus', 'Mars', 'Jupiter', 'Saturn',
        'Uranus', 'Neptune', 'Pluto'
    ]
    user_input_planet = update.message.text[8:].capitalize()
    if user_input_planet in planets:
        d = datetime.datetime.now().strftime('%Y')
        if user_input_planet == 'Sun':
            planet_answer = ephem.constellation(
                ephem.Sun(datetime.datetime.now().strftime('%Y')))
            bot.sendMessage(update.message.chat_id, planet_answer)
        elif user_input_planet == 'Moon':
            planet_answer = ephem.constellation(
                ephem.Moon(datetime.datetime.now().strftime('%Y')))
            bot.sendMessage(update.message.chat_id, planet_answer)
        elif user_input_planet == 'Mercury':
            planet_answer = ephem.constellation(
                ephem.Mercury(datetime.datetime.now().strftime('%Y')))
            bot.sendMessage(update.message.chat_id, planet_answer)
        elif user_input_planet == 'Venus':
            planet_answer = ephem.constellation(
                ephem.Venus(datetime.datetime.now().strftime('%Y')))
            bot.sendMessage(update.message.chat_id, planet_answer)
        elif user_input_planet == 'Mars':
            planet_answer = ephem.constellation(
                ephem.Mars(datetime.datetime.now().strftime('%Y')))
            bot.sendMessage(update.message.chat_id, planet_answer)
        elif user_input_planet == 'Jupiter':
            planet_answer = ephem.constellation(
                ephem.Jupiter(datetime.datetime.now().strftime('%Y')))
            bot.sendMessage(update.message.chat_id, planet_answer)
        elif user_input_planet == 'Saturn':
            planet_answer = ephem.constellation(
                ephem.Saturn(datetime.datetime.now().strftime('%Y')))
            bot.sendMessage(update.message.chat_id, planet_answer)
        elif user_input_planet == 'Uranus':
            planet_answer = ephem.constellation(
                ephem.Uranus(datetime.datetime.now().strftime('%Y')))
            bot.sendMessage(update.message.chat_id, planet_answer)
        elif user_input_planet == 'Neptune':
            planet_answer = ephem.constellation(
                ephem.Neptune(datetime.datetime.now().strftime('%Y')))
            bot.sendMessage(update.message.chat_id, planet_answer)
        elif user_input_planet == 'Pluto':
            planet_answer = ephem.constellation(
                ephem.Pluto(datetime.datetime.now().strftime('%Y')))
            bot.sendMessage(update.message.chat_id, planet_answer)
    else:
        planet_answer = "Неправильно введено название планеты"
        bot.sendMessage(update.message.chat_id, planet_answer)


#print(ephem.constellation(m))
#constellation = ephem.constellation(planet)
    logging.info(text)
Example #12
0
def get_constellation(bot, update):
    planet_nm = update.message.text.split()[1]
    planet_name = planet_nm.capitalize()
    print(planet_name)
    date = datetime.today()
    planet_obj = getattr(ephem, planet_name)(date)
    print(planet_name + ' in ' + ephem.constellation(planet_obj)[1])
    update.message.reply_text(planet_name + ' in ' +
                              ephem.constellation(planet_obj)[1])
Example #13
0
def find_planet(bot, update):
    d = datetime.datetime.now().strftime('%Y/%m/%d')
    planet = update.message.text.split()[1]
    update.message.reply_text(planet)
    if planet == 'Moon':
        moon = ephem.Moon(d)
        update.message.reply_text(ephem.constellation(moon))
    if planet == 'Mars':
        mars = ephem.Mars(d)
        update.message.reply_text(ephem.constellation(mars))
Example #14
0
def find_planet(bot, update, planet):
    pl = getattr(ephem, planet)()
    pl.compute(datetime.datetime.now().strftime('%Y/%m/%d'))

    print(ephem.constellation(pl))

    en = ephem.constellation(pl)
    en_ru = translation(en[1], en)

    update.message.reply_text(en_ru)
Example #15
0
def talk_about_planet(bot, update):
    user_text = update.message.text

    planet = user_text.capitalize()
    print('Вопрос о планете ' + planet)

    if planet == 'Sun':
        place = ephem.constellation(ephem.Sun(datetime.datetime.now()))
    elif planet == 'Moon':
        place = ephem.constellation(ephem.Moon(datetime.datetime.now()))
    elif planet == 'Earth':
        place = ephem.constellation(ephem.Earth(datetime.datetime.now()))
    elif planet == 'Mercury':
        place = ephem.constellation(ephem.Mercury(datetime.datetime.now()))
    elif planet == 'Mars':
        place = ephem.constellation(ephem.Mars(datetime.datetime.now()))
    elif planet == 'Venus':
        place = ephem.constellation(ephem.Venus(datetime.datetime.now()))
    elif planet == 'Jupiter':
        place = ephem.constellation(ephem.Jupiter(datetime.datetime.now()))
    elif planet == 'Uranus':
        place = ephem.constellation(ephem.Uranus(datetime.datetime.now()))
    elif planet == 'Neptune':
        place = ephem.constellation(ephem.Neptune(datetime.datetime.now()))
    else:
        place = 'NO'

    print(place)
    if place == 'NO':
        answer_text = 'Не могу дать ответ'
    else:
        answer_text = planet + ' находится в ' + place[1]

    print(answer_text)
    update.message.reply_text(answer_text)
Example #16
0
def planet1(bot, update):
	text = 'Введите название планеты '
	print(text)
	update.message.reply_text(text)
	#bot.send_message(text)
	text = message.text
	planet_choose = update.message.text
	print ('Бля,...', planet_choose)
	#planet_choose = update.message.text
	dt1 = dt.today()
	#planet_choose = input('Выберите планету: ')
	if planet_choose.lower() == 'mercury':
		planet = ep.constellation(ep.Mercury(dt1))
	elif planet_choose.lower() =='venus':
		planet =ep.constellation(ep.Venus(dt1))
	elif planet_choose.lower() =='earth':
		planet = ep.constellation(ep.Earth(dt1))
	elif planet_choose.lower() =='mars':
		planet =ep.constellation(ep.Mars(dt1))
			#print(planet)
	elif planet_choose.lower() =='jupiter':
		planet =ep.constellation(ep.Jupiter(dt1))
	elif planet_choose.lower() =='saturn':
		planet =ep.constellation(ep.Saturn(dt1))
	elif planet_choose.lower() =='uranus':
		planet = ep.constellation(ep.Uranus(dt1))
	elif planet_choose.lower() =='neptune':
		planet = ep.constellation(ep.Neptune(dt1))
	elif planet_choose.lower() =='pluto':
		planet = ep.constellation(ep.Pluto(dt1))
	else:
		print (planet_choose)
		planet = 'Нет таких планет'
	print(planet)
	update.message.reply_text(planet)
Example #17
0
def planet_definition(bot, update):
    today_str = datetime.datetime.today()
    text_split = update.message.text.split()
    text = text_split[1].capitalize()
    if text == 'Mercury':
        const = ephem.constellation(ephem.Mercury(today_str))
        print(const)
    elif text == 'Venus':
        const = ephem.constellation(ephem.Venus(today_str))
        print(const)
    elif text == 'Earth':
        const = ephem.constellation(ephem.Earth(today_str))
        print(const)
Example #18
0
def constellation_of_planet (bot,update):
    user_text = update.message.text.replace('/planet ','').capitalize()
    today_date = datetime.datetime.today().strftime('%Y/%m/%d')
    if user_text=='Mars':
        today_location_of_planet=ephem.Mars(datetime.date.today())
        update.message.reply_text(ephem.constellation(today_location_of_planet))
    elif user_text=='Mercury':
        today_location_of_planet=ephem.Mercury(datetime.date.today())
        update.message.reply_text(ephem.constellation(today_location_of_planet))
    elif user_text=='Venus':
        today_location_of_planet=ephem.Venus(datetime.date.today())
        update.message.reply_text(ephem.constellation(today_location_of_planet))
    elif user_text=='Jupiter':    
        today_location_of_planet=ephem.Jupiter(datetime.date.today())
        update.message.reply_text(ephem.constellation(today_location_of_planet))
    elif user_text=='Saturn':    
        today_location_of_planet=ephem.Saturn(datetime.date.today())
        update.message.reply_text(ephem.constellation(today_location_of_planet))
    elif user_text=='Uranus':    
        today_location_of_planet=ephem.Uranus(datetime.date.today())
        update.message.reply_text(ephem.constellation(today_location_of_planet))
    elif user_text=='Neptune':    
        today_location_of_planet=ephem.Neptune(datetime.date.today())
        update.message.reply_text(ephem.constellation(today_location_of_planet)) 
    elif user_text=='Pluto':    
        today_location_of_planet=ephem.Pluto(datetime.date.today())
        update.message.reply_text(ephem.constellation(today_location_of_planet))              
    else:
        update.message.reply_text('Ошибка! Введите название планеты на английском.')
Example #19
0
def get_planet_name(bot, update):
    planet_list = [
        'Mars', 'Mercury', 'Saturn', 'Venus', 'Uranus', 'Jupiter', 'Sun',
        'Neptune', 'Pluto', 'Moon'
    ]
    t = update.message.text
    logging.info(f'вызван get_planet_name + {update.message.text}')
    tlist = t.split()
    planet = list(set(planet_list) & set(tlist))
    today = date.today().strftime('%Y/%m/%d')

    if len(planet) == 1:
        if 'Mars' in planet:
            planet_today = ephem.Mars(today)
            const = ephem.constellation(planet_today)
        elif 'Mercury' in planet:
            planet_today = ephem.Mercury(today)
            const = ephem.constellation(planet_today)
        elif 'Saturn' in planet:
            planet_today = ephem.Saturn(today)
            const = ephem.constellation(planet_today)
        elif "Venus" in planet:
            planet_today = ephem.Venus(today)
            const = ephem.constellation(planet_today)
        elif 'Uranus' in planet:
            planet_today = ephem.Uranus(today)
            const = ephem.constellation(planet_today)
        elif 'Jupiter' in planet:
            planet_today = ephem.Jupiter(today)
            const = ephem.constellation(planet_today)
        elif 'Sun' in planet:
            planet_today = ephem.Sun(today)
            const = ephem.constellation(planet_today)
        elif 'Neptune' in planet:
            planet_today = ephem.Neptune(today)
            const = ephem.constellation(planet_today)
        elif 'Pluto' in planet:
            planet_today = ephem.Pluto(today)
            const = ephem.constellation(planet_today)
        elif 'Moon' in planet:
            planet_today = ephem.Moon(today)
            const = ephem.constellation(planet_today)
    elif len(planet) > 1:
        const = 'Введите не больше 1 планеты'
    else:
        const = 'Вы не ввели название планеты, либо я не знаю таких планет'
    text = const

    update.message.reply_text(text)
    logging.info(f'определено созвездие: {text}')
Example #20
0
def ephem_const_today():
    user_input_planet = input('Введине название планеты: ')
    user_input_planet = str(user_input_planet)
    print(today)
    if user_input_planet == 'Mars':
        known_planet = ephem.Mars(today)
        constellation_of_known_planet_today = ephem.constellation(known_planet)
        return constellation_of_known_planet_today
    elif user_input_planet == 'Venus':
        known_planet = ephem.Venus(today)
        constellation_of_known_planet_today = ephem.constellation(known_planet)
        return constellation_of_known_planet_today
    else:
        return 'Такой планеты ({}) в базе не найдено'.format(user_input_planet)
Example #21
0
def planet(bot, update):
    user_text = update.message.text
    if user_text.split()[1] == 'Mercury':
        update.message.reply_text(
            ephem.constellation(ephem.Mercury(date.today())))
    elif user_text.split()[1] == 'Venus':
        update.message.reply_text(
            ephem.constellation(ephem.Venus(date.today())))
    elif user_text.split()[1] == 'Mars':
        update.message.reply_text(ephem.constellation(ephem.Mars(
            date.today())))
    elif user_text.split()[1] == 'Jupiter':
        update.message.reply_text(
            ephem.constellation(ephem.Jupiter(date.today())))
    elif user_text.split()[1] == 'Saturn':
        update.message.reply_text(
            ephem.constellation(ephem.Saturn(date.today())))
    elif user_text.split()[1] == 'Uranus':
        update.message.reply_text(
            ephem.constellation(ephem.Uranus(date.today())))
    elif user_text.split()[1] == 'Neptune':
        update.message.reply_text(
            ephem.constellation(ephem.Neptune(date.today())))
    elif user_text.split()[1] == 'Pluto':
        update.message.reply_text(
            ephem.constellation(ephem.Pluto(date.today())))
    else:
        update.message.reply_text('Не знаю такую планету')
def ask_planet(
    update, context
):  # функция которая должна отвечать пользователю если он ввел название планеты
    user_text = update.message.text  # получаем от пользователя сообщение
    user_text = user_text.split(' ')  # делаем список из сообщения пользователя

    if user_text[0] == "\planet":  #Перебираем планеты
        date = datetime.datetime(now)  # обозначили что нужна сегодняшняя дата
        if user_text == 'Mars':  # если тест от пользователя приравнен к слову Mars
            mars = ephem.Mars(
                date
            )  # то в переменную mars кладется расположение планеты сегодня
            update.message.reply_text(ephem.constellation(
                mars))  # выводится сообщение пользователю о созвездии
        if user_text == 'Venus':
            venus = ephem.Venus(date)
            update.message.reply_text(ephem.constellation(venus))
        if user_text == 'Mercury':
            mercury = ephem.Mercury(date)
            update.message.reply_text(ephem.constellation(mercury))
        if user_text == 'Jupiter':
            jupiter = ephem.Jupiter(date)
            update.message.reply_text(ephem.constellation(jupiter))
        if user_text == 'Saturn':
            saturn = ephem.Saturn(date)
            update.message.reply_text(ephem.constellation(saturn))
        if user_text == 'Uranus':
            uranus = ephem.Uranus(date)
            update.message.reply_text(ephem.constellation(uranus))
        if user_text == 'Neptune':
            neptune = ephem.Neptune(date)
            update.message.reply_text(ephem.constellation(neptune))
        if user_text == 'Pluto':
            pluto = ephem.Pluto(date)
            update.message.reply_text(ephem.constellation(pluto))
Example #23
0
def talk_planet(bot, update):
    
    # Получаем от юзера сообщение
    user_text = update.message.text

    # складываем в список полученное сообщение, разделяя пробелом
    user_text = user_text.split(' ')

    # Проверяем полученое сообщение
    if user_text[0] == '/planet':

        # Определяем календарную дату
        date = datetime.datetime.now()

        # Определяем название планеты и выводим в сообщение в каком созвездии сегодня находится планета.
        if user_text[1] == 'Sun':
            sun = ephem.Sun(date)
            update.message.reply_text(ephem.constellation(sun))
        elif user_text[1] == 'Mars':
            mars = ephem.Mars(date)
            update.message.reply_text(ephem.constellation(mars))
        elif user_text[1] == 'Mercury':
            mercury = ephem.Mercury(date)
            update.message.reply_text(ephem.constellation(mercury))
        elif user_text[1] == 'Venus':
            venus = ephem.Venus(date)
            update.message.reply_text(ephem.constellation(venus))
        elif user_text[1] == 'Jupiter':
            jupiter = ephem.Jupiter(date)
            update.message.reply_text(ephem.constellation(jupiter))
        elif user_text[1] == 'Saturn':
            saturn = ephem.Saturn(date)
            update.message.reply_text(ephem.constellation(saturn))
        elif user_text[1] == 'Uranus':
            uranus = ephem.Uranus(date)
            update.message.reply_text(ephem.constellation(uranus))
        elif user_text[1] == 'Neptune':
            neptune = ephem.Neptune(date)
            update.message.reply_text(ephem.constellation(neptune))
        elif user_text[1] == 'Pluto':
            pluto = ephem.Pluto(date)
            update.message.reply_text(ephem.constellation(pluto))
        else:
            update.message.reply_text("""Вы ввели не верное название планеты. Введите любую планету из этого списка:
            - Sun
            - Mars
            - Mercury
            - Venus
            - Jupiter
            - Saturn
            - Uranus
            - Neptune
            - Pluto
            """)
Example #24
0
def planet_search(bot,update):
    planets=['Sun', 'Moon', 'Mercury', 'Venus', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune', 'Pluto']
    user_input_cap=update.message.text[8:].capitalize()
    print('поиск планеты')
    print('планета, которую ввел пользователь', user_input_cap)
    for index in planets:
        print(index)
        if user_input_cap==index:
            d=datetime.datetime.now().strftime('%Y')
            if user_input_cap=='Sun':
                planet_answer=ephem.constellation(ephem.Sun(datetime.datetime.now().strftime('%Y')))
                bot.sendMessage(update.message.chat_id,planet_answer)
                print(planet_answer)
            elif user_input_cap=='Moon':
                planet_answer=ephem.constellation(ephem.Moon(datetime.datetime.now().strftime('%Y')))
                bot.sendMessage(update.message.chat_id,planet_answer)  
                print(planet_answer)
            elif user_input_cap=='Mercury':
                planet_answer=ephem.constellation(ephem.Mercury(datetime.datetime.now().strftime('%Y')))
                bot.sendMessage(update.message.chat_id,planet_answer)
                print(planet_answer) 
            elif user_input_cap=='Venus':
                planet_answer=ephem.constellation(ephem.Venus(datetime.datetime.now().strftime('%Y')))
                bot.sendMessage(update.message.chat_id,planet_answer) 
                print(planet_answer)
            elif user_input_cap=='Mars':
                planet_answer=ephem.constellation(ephem.Mars(datetime.datetime.now().strftime('%Y')))
                bot.sendMessage(update.message.chat_id,planet_answer) 
                print(planet_answer) 
            elif user_input_cap=='Jupiter':
                planet_answer=ephem.constellation(ephem.Jupiter(datetime.datetime.now().strftime('%Y')))
                bot.sendMessage(update.message.chat_id,planet_answer) 
                print(planet_answer) 
            elif user_input_cap=='Saturn':
                planet_answer=ephem.constellation(ephem.Saturn(datetime.datetime.now().strftime('%Y')))
                bot.sendMessage(update.message.chat_id,planet_answer)  
                print(planet_answer)
            elif user_input_cap=='Uranus':
                planet_answer=ephem.constellation(ephem.Uranus(datetime.datetime.now().strftime('%Y')))
                bot.sendMessage(update.message.chat_id,planet_answer) 
                print(planet_answer) 
            elif user_input_cap=='Neptune':
                planet_answer=ephem.constellation(ephem.Neptune(datetime.datetime.now().strftime('%Y')))
                bot.sendMessage(update.message.chat_id,planet_answer) 
                print(planet_answer) 
            elif user_input_cap=='Pluto':
                planet_answer=ephem.constellation(ephem.Pluto(datetime.datetime.now().strftime('%Y')))
                bot.sendMessage(update.message.chat_id,planet_answer)
                print(planet_answer)
Example #25
0
def planet(bot, update):
    text = 'Вызван /planet'
    print(text)
    update.message.reply_text(text)
    today = str(date.today())
    today.replace('-', '/')
    user_text = update.message.text
    print(user_text)
    user_list = user_text.split(' ')
    for plan in planet_list:
        if plan in user_list:
            planet_object = getattr(ephem, plan)
            res = planet_object(today)
            ephem.constellation(res)
            update.message.reply_text(ephem.constellation(res))
Example #26
0
def solar_system(solar, planets):
    for objects in solar:
        if objects['planet'] == planets:
            if planets == 'Марс':
                mars = ephem.Mars(sysdate)
                return (ephem.constellation(mars))
            elif planets == 'Юпитер':
                jupiter = ephem.Jupiter(sysdate)
                return (ephem.constellation(jupiter))
            elif planets == 'Луна':
                moon = ephem.Moon(sysdate)
                return (ephem.constellation(moon))
            elif planets == 'Сатурн':
                saturn = ephem.Saturn(sysdate)
                return (ephem.constellation(saturn))
Example #27
0
    def drawStarInfo(self, star, screen, pos):
        (x, y) = pos
        starObj = star.body 
        # RA will be the longest line
        (width, height) = self.smallFont.size(
                                    "Right Ascension: " + str(starObj.a_ra))
        fontHeight = height
        pygame.draw.rect(screen, self.BLACK, 
                            pygame.Rect(x, y+fontHeight, width, height*4 + 8))

        # Magnitude
        mag = self.smallFont.render("Magnitude: " + str(starObj.mag), 1, 
                                                                self.WHITE)
        screen.blit(mag, (x, y+height+2))
        # RA
        ra=self.smallFont.render("Right Ascension: "+str(starObj.a_ra),1,
                                                                    self.WHITE)
        screen.blit(ra, (x, y+2*height+2))
        # Dec
        dec = self.smallFont.render("Declination: "+str(starObj.dec), 1, 
                                                                    self.WHITE)
        screen.blit(dec, (x, y+3*height+2))
        # Constellation - ephem.constellation(obj)[1] returns the name of
        # the constellation the star is within
        const = self.smallFont.render("Constellation: " +
                        ephem.constellation(starObj)[1], 1, self.WHITE)
        screen.blit(const, (x, y+4*height+2))
Example #28
0
 def const(self):
    '''Returns the constellation the object is current in
    as a 3-letter code.'''
    MWO = genMWO(self.epoch)
    star = self.genobj()
    star.compute(MWO)
    return ephem.constellation(star)[0]
Example #29
0
def find_constellation(best_planet_choice):
    time_now = ephem.now()
    planet_obj = getattr(ephem, best_planet_choice)
    user_find_planet = planet_obj()                                
    user_find_planet.compute(time_now)
    _, full_name = ephem.constellation(user_find_planet)
    return full_name
Example #30
0
def search_planet(bot, update):

    planet = update.message.text.split()[-1]
    now_date = time.strftime('%Y/%m/%d')
    print(planet, now_date)
    if planet == 'Mercury':
        ep_planet = ephem.Mercury(now_date)
    elif planet == 'Venus':
        ep_planet = ephem.Venus(now_date)
    elif planet == 'Mars':
        ep_planet = ephem.Mars(now_date)
    elif planet == 'Jupiter':
        ep_planet = ephem.Jupiter(now_date)
    elif planet == 'Saturn':
        ep_planet = ephem.Saturn(now_date)
    elif planet == 'Uranus':
        ep_planet = ephem.Uranus(now_date)
    elif planet == 'Neptune':
        ep_planet = ephem.Neptune(now_date)
    else:
        print('Ввод неверный')
    const = ephem.constellation(ep_planet)
    print(const)
    user_text_const = f'Планета {planet} сегодня находится в созвездии {const}'
    print(user_text_const)
    update.message.reply_text(user_text_const)
Example #31
0
def user_planet(bot, update):
    user_text = update.message.text.split(' ')[1]
    if user_text == 'Moon':
        p = ephem.Moon(datetime.date.today())
    elif user_text == 'Saturn':
        p = ephem.Saturn(datetime.date.today())
    elif user_text == 'Jupiter':
        p = ephem.Jupiter(datetime.date.today())
    else:
        p = 0
    try:
        answer = ephem.constellation(p)
    except Exception:
        answer = "Нет данных об этом небесном теле."
    planet_names = {
        'Aries': 'Овен',
        'Taurus': 'Телец',
        'Gemini': 'Близнецы',
        'Cancer': 'Рак',
        'Leo': 'Лев',
        'Virgo': 'Дева',
        'Libra': 'Весы',
        'Scorpio': 'Скорпион',
        'Sagittarius': 'Стрелец',
        'Capricornus': 'Козерог',
        'Aquarius': 'Водолей',
        'Pisces': 'Рыбы',
    }
    update.message.reply_text(
        f'На текущую дату, небесное тело находится в созвездии {planet_names[answer[1]]}.'
    )
Example #32
0
def planets_chat(bot, update):
    name_planet = update.message.text
    logging.info(name_planet)
    if name_planet == 'Mars':
        sky = ephem.Mars()
    elif name_planet == 'Mercury':
        sky = ephem.Mercury()
    elif name_planet == 'Venus':
        sky = ephem.Venus()
    elif name_planet == 'Earth':
        sky = ephem.Earth()
    elif name_planet == 'Jupiter':
        sky = ephem.Jupiter()
    elif name_planet == 'Saturn':
        sky = ephem.Saturn()
    elif name_planet == 'Uranus':
        sky = ephem.Uranus()
    elif name_planet == 'Neptune':
        sky = ephem.Neptune()
    elif name_planet == 'Pluto':
        sky = ephem.Pluto()
    else:
        update.message.reply_text('Wrong name planet')
    sky.compute(datetime.date.today())
    update.message.reply_text(ephem.constellation(sky))
Example #33
0
 def as_columns(self):
     return (
         "{:>12}".format(_(self.angle)),
         "{1} {0.body1.name}".format(self, get_symbol(self.body1)),
         "{1} {0.body2.name}".format(self, get_symbol(self.body2)),
         "{}".format(ephem.constellation(self.body2)[1]),
     )
Example #34
0
def getconstellation(starobj, observatory):
    RA = starobj.dictionary['RA_STRING'].strip().replace(' ',':')
    Dec = starobj.dictionary['DEC_STRING'].strip().replace(' ',':')
    star = ephem.FixedBody()
    star._ra = ephem.hours(RA)
    star._dec = ephem.degrees(Dec)
    star.compute(observatory)
    return ephem.constellation(star)
Example #35
0
 def moon(self, mess, args):
     """moon [date] [location] - show Moon ephemeris
     """
     body = ephem.Moon()
     reply = self._doBodyEphem(mess, args, u'\u263D', body, with_constell_mag=False)
     reply += '  Phase ' +  ("%0.1f" % body.phase)
     reply += '  [ ' +  ephem.constellation(body)[1] + ' ]'
     return reply
Example #36
0
def print_stars():
    for name in sorted(stars):
        star = ephem.star(name)
        star.compute()
        print(
            "{0.mag:+.1f} {0.name:20} {1:>16} {2:>16} {3}".format(
                star,
                _(star.ra, astro.utils.HMS),
                _(star.dec),
                ephem.constellation(star)[1]))
Example #37
0
 def constellation(self):
     p_object = self.ephem_object
     if p_object:
         p_object.compute()
         try:
             abbrv = ephem.constellation(p_object)[0]
             return Constellation.objects.get(abbreviation=abbrv)
         except:
             return None
     else:
         return None
Example #38
0
  def planet(self, planet):
    today = datetime.date.today()
    now = datetime.datetime(today.year,today.month,today.day,8,0,0)

    rise    = ephem.localtime(self.observer.next_rising( planet))
    sset    = ephem.localtime(self.observer.next_setting(planet))
    transit = ephem.localtime(self.observer.next_transit(planet))
    
    rise_time    =     rise.strftime("%I:%M:%S %p").lower()
    set_time     =     sset.strftime("%I:%M:%S %p").lower()
    transit_time =  transit.strftime("%I:%M:%S %p").lower()
    
    constellation = ephem.constellation(planet)[1].lower()
    
    return rise_time, set_time, transit_time, constellation
Example #39
0
def comet_ephemeris(text, start_date, end_date):
    comet = ephem.readdb(text)

    here = ephem.Observer()
    here.lat, here.lon, here.elev = '33:45:10', '-84:23:37', 320.0

    comet_name = text.split(",")[0]
    print comet_name + \
        ": date, right ascension, declination, and magnitude:"

    here.date = ephem.date(start_date)
    end = ephem.date(end_date)
    while here.date < end:
        comet.compute(here)
        print here.date, comet.ra, comet.dec, comet.mag, \
            ephem.constellation(comet)[1]
        here.date += 5
Example #40
0
def ang2const(lon,lat,coord='gal'):
    import ephem

    scalar = np.isscalar(lon)
    lon = np.array(lon,copy=False,ndmin=1)
    lat = np.array(lat,copy=False,ndmin=1)

    if coord.lower() == 'cel':
        ra,dec = lon,lat
    elif coord.lower() == 'gal':
        ra,dec = gal2cel(lon,lat)
    else:
        msg = "Unrecognized coordinate"
        raise Exception(msg)

    x,y = np.radians([ra,dec])
    const = [ephem.constellation(coord) for coord in zip(x,y)]
    if scalar: return const[0]
    return const
    def find_sun_constell(self,dt):
        """finds Sun's  constellation """
        d = ephem.Date(dt.date())
        
        
        sitka = ephem.Observer()
        
       
        sitka.date = d

        sitka.lat = self.lat

        sitka.lon = self.lon

        m = ephem.Sun(d)
        
        s = ephem.constellation(m)[1]
        
        return s    
Example #42
0
    def _doBodyEphem(self, mess, args, unic_symb, body, with_constell_mag=True, rising_first=True):
        """ Return next rise/setting for specified body.
        """
        body.compute()

        jid, loc, dt = self._parseJidLocTime(mess, args)
        next_rising, next_setting, riset = self._getNextRiseSetting(jid, body, dt=dt, loc=loc, horizon='0.0')

        if riset == SkybberBot.RISET_OK:
            if rising_first:
                result = unic_symb + ' ' + SkybberBot.UNICODE_RISE + utils.formatLocalTime(next_rising) + '  ' + SkybberBot.UNICODE_SET + utils.formatLocalTime(next_setting)
            else:
                result = unic_symb + ' ' + SkybberBot.UNICODE_SET + utils.formatLocalTime(next_setting) + '  ' + SkybberBot.UNICODE_RISE + utils.formatLocalTime(next_rising)
        else:
            result = self._fmtRiSetFailMsg(body, riset)
        if with_constell_mag:
            result += '  ' + str(body.mag) + 'm'
            result += '  [ ' +  ephem.constellation(body)[1] + ' ]'
        return result
Example #43
0
    def GetStarInfo(self, starName):
        try:
            s = ephem.star(starName)
            s.compute(self.myObserver)

            star_rightascension = s._ra
            star_declination = s._dec
            star_magnitude = s.mag
            star_elongation = s.elong  # angle to sun
            star_circumpolar = s.circumpolar  # stays above horizon?
            star_neverup = s.neverup  # never rises?
            star_altitude = s.alt
            star_azimuth = s.az
            star_compass = AU.AzimuthToCompassDirection(star_azimuth)
            star_constellation = str(ephem.constellation(s)[1])
            star_visible = True if star_altitude > 0 else False

            dictionaryData = {}
            dictionaryData["Name"] = str(starName)
            dictionaryData["RightAscension"] = str(star_rightascension)
            dictionaryData["Declination"] = str(star_declination)
            dictionaryData["Magnitude"] = str(star_magnitude)
            dictionaryData["Elongation"] = str(star_elongation)
            dictionaryData["Circumpolar"] = star_circumpolar
            dictionaryData["NeverUp"] = star_neverup
            dictionaryData["Altitude"] = str(star_altitude)
            dictionaryData["Azimuth"] = str(star_azimuth)
            dictionaryData["Compass"] = str(star_compass)
            dictionaryData["IsVisible"] = star_visible

            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 "{ }"
Example #44
0
    def GetSunInfo(self):
        try:
            sun = ephem.Sun()
            sun.compute(self.myObserver)

            sun_altitude = sun.alt
            sun_visible = True if sun_altitude > 0 else False
            sun_azimuth = sun.az
            sun_compass = AU.AzimuthToCompassDirection(sun_azimuth)
            sun_constellation = ephem.constellation(sun)[1]

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

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

            dictionaryData = {}
            dictionaryData["Name"] = "Sun"
            dictionaryData["Altitude"] = str(sun_altitude)
            dictionaryData["IsVisible"] = sun_visible
            dictionaryData["Azimuth"] = str(sun_azimuth)
            dictionaryData["Compass"] = str(sun_compass)
            dictionaryData["InConstellation"] = str(sun_constellation)
            dictionaryData["NextRiseUT"] = str(rise_time_ut)
            dictionaryData["NextRiseLocal"] = str(rise_time_local)
            dictionaryData["NextSetUT"] = str(set_time_ut)
            dictionaryData["NextSetLocal"] = str(set_time_local)

            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)
            print ""
Example #45
0
    def _doInnerBodyEphem(self, mess, args, unic_symb, body, with_constell_mag=True):
        body.compute()

        elong = math.degrees(body.elong)

        jid, loc, dt = self._parseJidLocTime(mess, args)
        next_rising, next_setting, riset = self._getNextRiseSetting(jid, body, dt=dt, loc=loc, horizon='0.0')

        if riset == SkybberBot.RISET_OK:
            if elong > 0.0:
                result = unic_symb + ' ' + SkybberBot.UNICODE_RISE + utils.formatLocalTime(next_setting)
            else:
                result = unic_symb + ' ' + SkybberBot.UNICODE_RISE + utils.formatLocalTime(next_rising)
        else:
            result = self._fmtRiSetFailMsg(body, riset)

        result += '  Elong ' + ("%0.2f" % elong)

        if with_constell_mag:
            result += '  ' + str(body.mag) + 'm'
            result += '  [ ' +  ephem.constellation(body)[1] + ' ]'
        return result
Example #46
0
    def GetObjectInfo(self, objectName, rightAscension, declination, magnitude=0):
        """
		Calculate local info for custom objects, given Right Ascension and Declination info.
		
		XEphem format for fixed object:
		 "ObjectName,f,right_ascension,declination,magnitude"
		   Right Ascension is given as hours:minutes:seconds
		   Declination is given as degrees:minutes:seconds
		Example:
		 "KIC 8462852,f,20:6:15,44:27:25,11"
		"""

        ephemeris = objectName + "," + "f" + "," + rightAscension + "," + declination + "," + str(magnitude)

        customObject = ephem.readdb(ephemeris)
        customObject.compute(self.myObserver)

        object_altitude = customObject.alt
        object_azimuth = customObject.az
        object_compass = AU.AzimuthToCompassDirection(object_azimuth)
        object_constellation = ephem.constellation(customObject)[1]
        object_visible = True if object_altitude > 0 else False
        object_magnitude = customObject.mag

        dictionaryData = {}
        dictionaryData["Name"] = objectName
        dictionaryData["Altitude"] = str(object_altitude)
        dictionaryData["IsVisible"] = object_visible
        dictionaryData["Azimuth"] = str(object_azimuth)
        dictionaryData["Compass"] = str(object_compass)
        dictionaryData["InConstellation"] = object_constellation
        dictionaryData["Magnitude"] = object_magnitude

        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
Example #47
0
def calculateEphemerides(parFile):
    '''
        :INPUTS:
        parFile	 --	  path to the parameter file
        '''

    #parFile = 'umo.par'

    '''Parse the observatory .par file'''
    parFileText = open(os.path.join(os.path.dirname(oscaar.__file__),'extras','eph','observatories',parFile),'r').read().splitlines()

    def returnBool(value):
        '''Return booleans from strings'''
        if value == 'True': return True
        elif value == 'False': return False

    for line in parFileText:
        parameter = line.split(':')[0]
        if len(line.split(':')) > 1:
            value = line.split(':')[1].strip()
            if parameter == 'name': observatory_name = value
            elif parameter == 'latitude': observatory_latitude = value
            elif parameter == 'longitude': observatory_longitude = value
            elif parameter == 'elevation': observatory_elevation = float(value)
            elif parameter == 'temperature': observatory_temperature = float(value)
            elif parameter == 'min_horizon': observatory_minHorizon = value
            elif parameter == 'start_date': startSem = gd2jd(eval(value))
            elif parameter == 'end_date': endSem = gd2jd(eval(value))
            elif parameter == 'v_limit': v_limit = float(value)
            elif parameter == 'depth_limit': depth_limit = float(value)
            elif parameter == 'calc_transits': calcTransits = returnBool(value)
            elif parameter == 'calc_eclipses': calcEclipses = returnBool(value)
            elif parameter == 'html_out': htmlOut = returnBool(value)
            elif parameter == 'text_out': textOut = returnBool(value)
            elif parameter == 'twilight': twilightType = value

    from oscaar.extras.knownSystemParameters import getLatestParams
    exoplanetDB = getLatestParams.downloadAndPickle()

    ''' Set up observatory parameters '''
    observatory = ephem.Observer()
    observatory.lat =  observatory_latitude#'38:58:50.16'	## Input format-  deg:min:sec  (type=str)
    observatory.long = observatory_longitude#'-76:56:13.92' ## Input format-  deg:min:sec  (type=str)
    observatory.elevation = observatory_elevation   # m
    observatory.temp = observatory_temperature	  ## Celsius 
    observatory.horizon = observatory_minHorizon	## Input format-  deg:min:sec  (type=str)

    def trunc(f, n):
        '''Truncates a float f to n decimal places without rounding'''
        slen = len('%.*f' % (n, f))
        return str(f)[:slen]

    def RA(planet):
        '''Type: str, Units:  hours:min:sec'''
        return exoplanetDB[planet]['RA_STRING']
    def dec(planet):
        '''Type: str, Units:  deg:min:sec'''
        return exoplanetDB[planet]['DEC_STRING']
    def period(planet):
        '''Units:  days'''
        return np.float64(exoplanetDB[planet]['PER'])
    def epoch(planet):
        '''Tc at mid-transit. Units:  days'''
        if exoplanetDB[planet]['TT'] == '': return 0.0
        else: return np.float64(exoplanetDB[planet]['TT'])
    def duration(planet):
        '''Transit/eclipse duration. Units:  days'''
        if exoplanetDB[planet]['T14'] == '': return 0.0
        else: return float(exoplanetDB[planet]['T14'])
    def V(planet):
        '''V mag'''
        if exoplanetDB[planet]['V'] == '': return 0.0
        else: return float(exoplanetDB[planet]['V'])
    def KS(planet):
        '''KS mag'''
        if exoplanetDB[planet]['KS'] == '': return 0.0
        else: return float(exoplanetDB[planet]['KS'])

    def depth(planet):
        '''Transit depth'''
        if exoplanetDB[planet]['DEPTH'] == '': return 0.0
        else: return float(exoplanetDB[planet]['DEPTH'])

    def transitBool(planet):
        '''True if exoplanet is transiting, False if detected by other means'''
        if exoplanetDB[planet]['TRANSIT'] == '0': return 0
        elif exoplanetDB[planet]['TRANSIT'] == '1': return 1
    ########################################################################################
    ########################################################################################

    def datestr2list(datestr):
        ''' Take strings of the form: "2013/1/18 20:08:18" and return them as a
            tuple of the same parameters'''
        year,month,others = datestr.split('/')
        day, time = others.split(' ')
        hour,minute,sec = time.split(':')
        return (int(year),int(month),int(day),int(hour),int(minute),int(sec))

    def list2datestr(inList):
        '''Converse function to datestr2list'''
        inList = map(str,inList)
        return inList[0]+'/'+inList[1]+'/'+inList[2]+' '+inList[3].zfill(2)+':'+inList[4].zfill(2)+':'+inList[5].zfill(2)

    def list2datestrCSV(inList):
        '''Converse function to datestr2list'''
        inList = map(str,inList)
        return inList[0]+'/'+inList[1]+'/'+inList[2]+','+inList[3].zfill(2)+':'+inList[4].zfill(2)+':'+inList[5].zfill(2)


    def list2datestrHTML(inList,alt,direction):
        '''Converse function to datestr2list'''
        inList = map(str,inList)
        #return inList[1].zfill(2)+'/'+inList[2].zfill(2)+'<br />'+inList[3].zfill(2)+':'+inList[4].zfill(2)
        return inList[1].zfill(2)+'/<strong>'+inList[2].zfill(2)+'</strong>, '+inList[3].zfill(2)+':'+inList[4].split('.')[0].zfill(2)+'<br /> '+alt+'&deg; '+direction

    def simbadURL(planet):
        if exoplanetDB[planet]['SIMBADURL'] == '': return 'http://simbad.harvard.edu/simbad/'
        else: return exoplanetDB[planet]['SIMBADURL']

    def RADecHTML(planet):
        return '<a href="'+simbadURL(planet)+'">'+RA(planet).split('.')[0]+'<br />'+dec(planet).split('.')[0]+'</a>'

    def constellation(planet):
        return exoplanetDB[planet]['Constellation']

    def orbitReference(planet):
        return exoplanetDB[planet]['TRANSITURL']

    def nameWithLink(planet):
        return '<a href="'+orbitReference(planet)+'">'+planet+'</a>'

    def mass(planet):
        if exoplanetDB[planet]['MASS'] == '': return '---'
        else: return trunc(float(exoplanetDB[planet]['MASS']),2)

    def semimajorAxis(planet):
        #return trunc(0.004649*float(exoplanetDB[planet]['AR'])*float(exoplanetDB[planet]['RSTAR']),3)   ## Convert from solar radii to AU
        return trunc(float(exoplanetDB[planet]['SEP']),3)

    def radius(planet):
        return trunc(float(exoplanetDB[planet]['R']),2) ## Convert from solar radii to Jupiter radii

    def midTransit(Tc, P, start, end):
        '''Calculate mid-transits between Julian Dates start and end, using a 2500 
            orbital phase kernel since T_c (for 2 day period, 2500 phases is 14 years)
            '''
        Nepochs = np.arange(0,2500,dtype=np.float64)
        transitTimes = Tc + P*Nepochs
        transitTimesInSem = transitTimes[(transitTimes < end)*(transitTimes > start)]
        return transitTimesInSem

    def midEclipse(Tc, P, start, end):
        '''Calculate mid-eclipses between Julian Dates start and end, using a 2500 
            orbital phase kernel since T_c (for 2 day period, 2500 phases is 14 years)
            '''
        Nepochs = np.arange(0,2500,dtype=np.float64)
        transitTimes = Tc + P*(0.5 + Nepochs)
        transitTimesInSem = transitTimes[(transitTimes < end)*(transitTimes > start)]
        return transitTimesInSem

    '''Choose which planets from the database to include in the search, 
        assemble a list of them.'''
    planets = []
    for planet in exoplanetDB:
        if V(planet) != 0.0 and depth(planet) != 0.0 and float(V(planet)) <= v_limit and float(depth(planet)) >= depth_limit and transitBool(planet):
            planets.append(planet)

    if calcTransits: transits = {}
    if calcEclipses: eclipses = {}
    for day in np.arange(startSem,endSem+1):
        if calcTransits: transits[str(day)] = []
        if calcEclipses: eclipses[str(day)] = []
    planetsNeverUp = []


    def azToDirection(az):
        az = float(az)
        if (az >= 0 and az < 22.5) or (az >= 337.5 and az < 360): return 'N'
        elif az >= 22.5 and az < 67.5:  return 'NE'
        elif az >= 67.5 and az < 112.5:  return 'E'
        elif az >= 112.5 and az < 157.5:  return 'SE'
        elif az >= 157.5 and az < 202.5:  return 'S'
        elif az >= 202.5 and az < 247.5:  return 'SW'
        elif az >= 247.5 and az < 292.5:  return 'W'	
        elif az >= 292.5 and az < 337.5:  return 'NW'

    def ingressEgressAltAz(planet,observatory,ingress,egress):
        altitudes = []
        directions = []
        for time in [ingress,egress]:
            observatory.date = list2datestr(jd2gd(time))
            star = ephem.FixedBody()
            star._ra = ephem.hours(RA(planet))
            star._dec = ephem.degrees(dec(planet))
            star.compute(observatory)
            altitudes.append(str(ephem.degrees(star.alt)).split(":")[0])
            directions.append(azToDirection(str(ephem.degrees(star.az)).split(":")[0]))
        ingressAlt,egressAlt = altitudes
        ingressDir,egressDir = directions
        return ingressAlt,ingressDir,egressAlt,egressDir

    def aboveHorizonForEvent(planet,observatory,ingress,egress):
        altitudes = []
        for time in [ingress,egress]:
            observatory.date = list2datestr(jd2gd(time))
            star = ephem.FixedBody()
            star._ra = ephem.hours(RA(planet))
            star._dec = ephem.degrees(dec(planet))
            star.compute(observatory)
            #altitudes.append(str(ephem.degrees(star.alt)).split(":")[0])
            altitudes.append(float(repr(star.alt))/(2*np.pi) * 360)	## Convert altitudes to degrees
        if altitudes[0] > 0 and altitudes[1] > 0: return True
        else: return False

    def eventAfterTwilight(planet,observatory,ingress,egress,twilightType):
        altitudes = []
        for time in [ingress,egress]:
            observatory.date = list2datestr(jd2gd(time))
            sun = ephem.Sun()
            sun.compute(observatory)
            altitudes.append(float(repr(sun.alt))/(2*np.pi) * 360)	## Convert altitudes to degrees
        if altitudes[0] < float(twilightType) and altitudes[1] < float(twilightType): return True
        else: return False

    for planet in planets:		
        '''Compute all of the coming transits and eclipses for a long time out'''
        allTransitEpochs = midTransit(epoch(planet),period(planet),startSem,endSem)
        allEclipseEpochs = midEclipse(epoch(planet),period(planet),startSem,endSem)
        for day in np.arange(startSem,endSem+1,1.0):
            try:
                '''For each day, gather the transits and eclipses that happen'''
                transitEpochs = allTransitEpochs[(allTransitEpochs <= day+0.5)*(allTransitEpochs > day-0.5)]
                eclipseEpochs = allEclipseEpochs[(allEclipseEpochs <= day+0.5)*(allEclipseEpochs > day-0.5)]
                if calcTransits and len(transitEpochs) != 0:
                    transitEpoch = transitEpochs[0]
                    ingress = transitEpoch-duration(planet)/2
                    egress = transitEpoch+duration(planet)/2
                    
                    ''' Calculate positions of host stars'''
                    star = ephem.FixedBody()
                    star._ra = ephem.hours(RA(planet))
                    star._dec = ephem.degrees(dec(planet))
                    star.compute(observatory)
                    exoplanetDB[planet]['Constellation'] = ephem.constellation(star)[0]
                    
                    '''If star is above horizon and sun is below horizon during transit/eclipse:'''		
                    if aboveHorizonForEvent(planet,observatory,ingress,egress) and eventAfterTwilight(planet,observatory,ingress,egress,twilightType):
                        ingressAlt,ingressDir,egressAlt,egressDir = ingressEgressAltAz(planet,observatory,ingress,egress)
                        transitInfo = [planet,transitEpoch,duration(planet)/2,'transit',ingressAlt,ingressDir,egressAlt,egressDir]
                        transits[str(day)].append(transitInfo)		
                if calcEclipses and len(eclipseEpochs) != 0:
                    eclipseEpoch = eclipseEpochs[0]
                    ingress = eclipseEpoch-duration(planet)/2
                    egress = eclipseEpoch+duration(planet)/2
                    
                    ''' Calculate positions of host stars'''
                    star = ephem.FixedBody()
                    star._ra = ephem.hours(RA(planet))
                    star._dec = ephem.degrees(dec(planet))
                    star.compute(observatory)
                    exoplanetDB[planet]['Constellation'] = ephem.constellation(star)[0]
                    
                    if aboveHorizonForEvent(planet,observatory,ingress,egress) and eventAfterTwilight(planet,observatory,ingress,egress,twilightType):
                        ingressAlt,ingressDir,egressAlt,egressDir = ingressEgressAltAz(planet,observatory,ingress,egress)
                        eclipseInfo = [planet,eclipseEpoch,duration(planet)/2,'eclipse',ingressAlt,ingressDir,egressAlt,egressDir]
                        eclipses[str(day)].append(eclipseInfo)	
            
            except ephem.NeverUpError:
                if str(planet) not in planetsNeverUp:
                    print 'Note: planet %s is never above the horizon at this observing location.' % (planet)
                    planetsNeverUp.append(str(planet))

    def removeEmptySets(dictionary):
        '''Remove days where there were no transits/eclipses from the transit/eclipse list dictionary. 
            Can't iterate through the transits dictionary with a for loop because it would change length 
            as keys get deleted, so loop through with while loop until all entries are not empty sets'''
        dayCounter = startSem
        while any(dictionary[day] == [] for day in dictionary):	
            if dictionary[str(dayCounter)] == []:
                del dictionary[str(dayCounter)]
            dayCounter += 1

    if calcTransits: removeEmptySets(transits)
    if calcEclipses: removeEmptySets(eclipses)

    events = {}
    def mergeDictionaries(dict):
        for key in dict:
            if any(key == eventKey for eventKey in events) == False:	## If key does not exist in events,
                if np.shape(dict[key])[0] == 1:	## If new event is the only one on that night, add only it
                    events[key] = [dict[key][0]]
                else:			## If there were multiple events that night, add them each
                    events[key] = []
                    for event in dict[key]:
                        events[key].append(event)
            else:
                if np.shape(dict[key])[0] > 1: ## If there are multiple entries to append,
                    for event in dict[key]:
                        events[key].append(event)
                else:							## If there is only one to add,
                    events[key].append(dict[key][0])
    if calcTransits: mergeDictionaries(transits)
    if calcEclipses: mergeDictionaries(eclipses)

    if textOut: 
        allKeys = events.keys()
        allKeys = np.array(allKeys)[np.argsort(allKeys)]
        report = open(os.path.join(os.path.dirname(oscaar.__file__),'extras','eph','ephOutputs','eventReport.csv'),'w')
        firstLine = 'Planet,Event,Ingress Date, Ingress Time (UT) ,Altitude at Ingress,Azimuth at Ingress,Egress Date, Egress Time (UT) ,Altitude at Egress,Azimuth at Egress,V mag,Depth,Duration,RA,Dec,Const.,Mass,Semimajor Axis (AU),Radius (R_J)\n'
        report.write(firstLine)
        
        for key in allKeys:
            def writeCSVtransit():
                middle = ','.join([planet[0],str(planet[3]),list2datestrCSV(jd2gd(float(planet[1]-planet[2]))),planet[4],planet[5],\
                                   list2datestrCSV(jd2gd(float(planet[1]+planet[2]))),planet[6],planet[7],trunc(V(str(planet[0])),2),\
                                   trunc(depth(planet[0]),4),trunc(24.0*duration(planet[0]),2),RA(planet[0]),dec(planet[0]),constellation(planet[0]),\
                                   mass(planet[0]),semimajorAxis(planet[0]),radius(planet[0])])
                line = middle+'\n'
                report.write(line)
            
            def writeCSVeclipse():
                middle = ','.join([planet[0],str(planet[3]),list2datestrCSV(jd2gd(float(planet[1]-planet[2]))),planet[4],planet[5],\
                                   list2datestrCSV(jd2gd(float(planet[1]+planet[2]))),planet[6],planet[7],trunc(V(str(planet[0])),2),\
                                   trunc(depth(planet[0]),4),trunc(24.0*duration(planet[0]),2),RA(planet[0]),dec(planet[0]),constellation(planet[0]),\
                                   mass(planet[0]),semimajorAxis(planet[0]),radius(planet[0])])
                line = middle+'\n'
                report.write(line)
            
            if np.shape(events[key])[0] > 1:
                elapsedTime = []
                
                for i in range(1,len(events[key])):
                    nextPlanet = events[key][1]
                    planet = events[key][0]
                    double = False
                    '''If the other planet's ingress is before this one's egress, then'''
                    if ephem.Date(list2datestr(jd2gd(float(nextPlanet[1]-nextPlanet[2])))) -\
                        ephem.Date(list2datestr(jd2gd(float(planet[1]+planet[2])))) > 0.0:
                            double = True
                            elapsedTime.append(ephem.Date(list2datestr(jd2gd(float(nextPlanet[1]-nextPlanet[2])))) - \
                                               ephem.Date(list2datestr(jd2gd(float(planet[1]+planet[2])))))
                    
                    if ephem.Date(list2datestr(jd2gd(float(planet[1]-planet[2])))) - \
                        ephem.Date(list2datestr(jd2gd(float(nextPlanet[1]+nextPlanet[2])))) > 0.0:
                            '''If the other planet's egress is before this one's ingress, then'''
                            double = True
                            elapsedTime.append(ephem.Date(list2datestr(jd2gd(float(planet[1]-planet[2])))) - \
                                               ephem.Date(list2datestr(jd2gd(float(nextPlanet[1]+nextPlanet[2])))))
                
                for planet in events[key]:
                    if calcTransits and planet[3] == 'transit':
                        writeCSVtransit()
                    if calcEclipses and planet[3] == 'eclipse':
                        writeCSVeclipse()		  
            
            elif np.shape(events[key])[0] == 1:
                planet = events[key][0]
                if calcTransits and planet[3] == 'transit':
                    writeCSVtransit()
                if calcEclipses and planet[3] == 'eclipse':
                    writeCSVeclipse()
        # report.write('\n')
        
        report.close()
    #print exoplanetDB['HD 209458 b']
    print 'calculateEphemerides.py: Done'


    if htmlOut: 
        '''Write out a text report with the transits/eclipses. Write out the time of 
            ingress, egress, whether event is transit/eclipse, elapsed in time between
            ingress/egress of the temporally isolated events'''
        report = open(os.path.join(os.path.dirname(oscaar.__file__),'extras','eph','ephOutputs','eventReport.html'),'w')
        allKeys = events.keys()
        ## http://www.kryogenix.org/code/browser/sorttable/
        htmlheader = '\n'.join([
                                '<!doctype html>',\
                                '<html>',\
                                '	<head>',\
                                '		<meta http-equiv="content-type" content="text/html; charset=UTF-8" />',\
                                '		<title>Ephemeris</title>',\
                                '		<link rel="stylesheet" href="stylesheetEphem.css" type="text/css" />',\
                                '		 <script type="text/javascript">',\
                                '		  function changeCSS(cssFile, cssLinkIndex) {',\
                                '			var oldlink = document.getElementsByTagName("link").item(cssLinkIndex);',\
                                '			var newlink = document.createElement("link")',\
                                '			newlink.setAttribute("rel", "stylesheet");',\
                                '			newlink.setAttribute("type", "text/css");',\
                                '			newlink.setAttribute("href", cssFile);',\
                                
                                '			document.getElementsByTagName("head").item(0).replaceChild(newlink, oldlink);',\
                                '		  }',\
                                '		</script>',\
                                '	   <script src="./sorttable.js"></script>',\
                                '	</head>',\
                                '	<body>',\
                                '		<div id="textDiv">',\
                                '		<h1>Ephemerides for: '+observatory_name+'</h1>',\
                                '		<h2>Observing dates (UT): '+list2datestr(jd2gd(startSem)).split(' ')[0]+' - '+list2datestr(jd2gd(endSem)).split(' ')[0]+'</h2>'
                                '	   Click the column headers to sort. ',\
                                '		<table class="daynight" id="eph">',\
                                '		<tr><th colspan=2>Toggle Color Scheme</th></tr>',\
                                '		<tr><td><a href="#" onclick="changeCSS(\'stylesheetEphem.css\', 0);">Day</a></td><td><a href="#" onclick="changeCSS(\'stylesheetEphemDark.css\', 0);">Night</a></td></tr>',\
                                '		</table>'])
        
        tableheader = '\n'.join([
                                 '\n		<table class="sortable" id="eph">',\
                                 '		<tr> <th>Planet<br /><span class="small">[Link: Orbit ref.]</span></th>	  <th>Event</th>	<th>Ingress <br /><span class="small">(MM/DD<br />HH:MM, UT)</span></th> <th>Egress <br /><span class="small">(MM/DD<br />HH:MM, UT)</span></th>'+\
                                 '<th>V mag</th> <th>Depth<br />(mag)</th> <th>Duration<br />(hrs)</th> <th>RA/Dec<br /><span class="small">[Link: Simbad ref.]</span></th> <th>Const.</th> <th>Mass<br />(M<sub>J</sub>)</th>'+\
                                 '<th>Semimajor <br />Axis (AU)</th> <th>Radius<br />(R<sub>J</sub>)</th></tr>'])
        tablefooter = '\n'.join([
                                 '\n		</table>',\
                                 '		<br /><br />',])
        htmlfooter = '\n'.join([
                                '\n		<p class="headinfo">',\
                                '		Developed by Brett Morris with great gratitude for the help of <a href="http://rhodesmill.org/pyephem/">PyEphem</a>,<br/>',\
                                '		and for up-to-date exoplanet parameters from <a href="http://www.exoplanets.org/">exoplanets.org</a> (<a href="http://adsabs.harvard.edu/abs/2011PASP..123..412W">Wright et al. 2011</a>).<br />',\
                                '		</p>',\
                                '		</div>',\
                                '	</body>',\
                                '</html>'])
        report.write(htmlheader)
        report.write(tableheader)
        
        allKeys = np.array(allKeys)[np.argsort(allKeys)]
        for key in allKeys:
            def writeHTMLtransit():
                indentation = '		'
                middle = '</td><td>'.join([nameWithLink(planet[0]),str(planet[3]),list2datestrHTML(jd2gd(float(planet[1]-planet[2])),planet[4],planet[5]),\
                                           list2datestrHTML(jd2gd(float(planet[1]+planet[2])),planet[6],planet[7]),trunc(V(str(planet[0])),2),\
                                           trunc(depth(planet[0]),4),trunc(24.0*duration(planet[0]),2),RADecHTML(planet[0]),constellation(planet[0]),\
                                           mass(planet[0]),semimajorAxis(planet[0]),radius(planet[0])])
                line = indentation+'<tr><td>'+middle+'</td></tr>\n'
                report.write(line)
            
            def writeHTMLeclipse():
                indentation = '		'
                middle = '</td><td>'.join([nameWithLink(planet[0]),str(planet[3]),list2datestrHTML(jd2gd(float(planet[1]-planet[2])),planet[4],planet[5]),\
                                           list2datestrHTML(jd2gd(float(planet[1]+planet[2])),planet[6],planet[7]),trunc(V(str(planet[0])),2),\
                                           '---',trunc(24.0*duration(planet[0]),2),RADecHTML(planet[0]),constellation(planet[0]),\
                                           mass(planet[0]),semimajorAxis(planet[0]),radius(planet[0])])
                line = indentation+'<tr><td>'+middle+'</td></tr>\n'
                report.write(line)
            
            
            if np.shape(events[key])[0] > 1:
                elapsedTime = []
                
                for i in range(1,len(events[key])):
                    nextPlanet = events[key][1]
                    planet = events[key][0]
                    double = False
                    '''If the other planet's ingress is before this one's egress, then'''
                    if ephem.Date(list2datestr(jd2gd(float(nextPlanet[1]-nextPlanet[2])))) -\
                        ephem.Date(list2datestr(jd2gd(float(planet[1]+planet[2])))) > 0.0:
                            double = True
                            elapsedTime.append(ephem.Date(list2datestr(jd2gd(float(nextPlanet[1]-nextPlanet[2])))) - \
                                               ephem.Date(list2datestr(jd2gd(float(planet[1]+planet[2])))))
                    
                    if ephem.Date(list2datestr(jd2gd(float(planet[1]-planet[2])))) - \
                        ephem.Date(list2datestr(jd2gd(float(nextPlanet[1]+nextPlanet[2])))) > 0.0:
                            '''If the other planet's egress is before this one's ingress, then'''
                            double = True
                            elapsedTime.append(ephem.Date(list2datestr(jd2gd(float(planet[1]-planet[2])))) - \
                                               ephem.Date(list2datestr(jd2gd(float(nextPlanet[1]+nextPlanet[2])))))
                
                for planet in events[key]:
                    if calcTransits and planet[3] == 'transit':
                        writeHTMLtransit()
                    if calcEclipses and planet[3] == 'eclipse':
                        writeHTMLeclipse()		  
            elif np.shape(events[key])[0] == 1:
                planet = events[key][0]
                if calcTransits and planet[3] == 'transit':
                    writeHTMLtransit()
                if calcEclipses and planet[3] == 'eclipse':
                    writeHTMLeclipse()
        report.write(tablefooter)
        report.write(htmlfooter)
        report.close()
Example #48
0
import ephem
mars = ephem.Mars()
mars.compute('2013/12/27')
print mars.ra, mars.dec
print mars.earth_distance

m = ephem.Mars('1970')
print ephem.constellation(m)

m = ephem.Mars('2003/8/27')
print m.name, m.elong, m.size

j = ephem.Jupiter()
j.compute('1986/2/8')
print j.ra, j.dec
j.compute('1986/2/9', epoch='1950')
print j.a_ra, j.a_dec

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')
Example #49
0
 def test_constellation(self):
     oneb = readdb("Orion Nebula,f,5.59,-5.45,2,2000.0,")
     oneb.compute("1999/2/28")
     self.assertEqual(constellation(oneb), ("Ori", "Orion"))
Example #50
0
def calculateEphemerides(parFile,rootPath):
    '''
    :INPUTS:
        parFile     --      path to the parameter file
        rootPath    --      path to the exoplanet database pickle and raw .csv, and all other outputs
    '''

    pklDatabaseName = 'exoplanetDB.pkl'     ## Name of exoplanet database C-pickle
    pklDatabasePaths = glob(os.path.join(rootPath,pklDatabaseName))   ## list of files with the name pklDatabaseName in cwd
    csvDatabasePath = 'exoplanets.csv'  ## Path to the text file saved from exoplanets.org
    #parFile = 'umo.par'

    '''Parse the observatory .par file'''
    parFileText = open(parFile,'r').read().splitlines()

    def returnBool(value):
        '''Return booleans from strings'''
        if value == 'True': return True
        elif value == 'False': return False
        
    for line in parFileText:
        parameter = line.split(':')[0]
        if len(line.split(':')) > 1:
            value = line.split(':')[1].strip()
            if parameter == 'name': observatory_name = value
            elif parameter == 'latitude': observatory_latitude = value
            elif parameter == 'longitude': observatory_longitude = value
            elif parameter == 'elevation': observatory_elevation = float(value)
            elif parameter == 'temperature': observatory_temperature = float(value)
            elif parameter == 'min_horizon': observatory_minHorizon = value
            elif parameter == 'start_date': startSem = gd2jd(eval(value))
            elif parameter == 'end_date': endSem = gd2jd(eval(value))
            elif parameter == 'v_limit': v_limit = float(value)
            elif parameter == 'depth_limit': depth_limit = float(value)
            elif parameter == 'calc_transits': calcTransits = returnBool(value)
            elif parameter == 'calc_eclipses': calcEclipses = returnBool(value)
            elif parameter == 'html_out': htmlOut = returnBool(value)
            elif parameter == 'text_out': textOut = returnBool(value)
            elif parameter == 'twilight': twilightType = value
        
    '''First, check if there is an internet connection.'''
    def internet_on():
        '''If internet connection is available, return True.'''
        try:
            response=urllib2.urlopen('http://www.google.com',timeout=10)
            return True
        except urllib2.URLError as err: pass
        return False
    if internet_on():
        print "Internet connection detected."
    else:
        print "WARNING: This script assumes that you're connected to the internet. This script may crash if you do not have an internet connection."

    '''If there's a previously archived database pickle in this current working 
       directory then use it, if not, grab the data from exoplanets.org in one big CSV file and make one.
       If the old archive is >14 days old, grab a fresh version of the database from exoplanets.org.
    '''
    if glob(rootPath+csvDatabasePath) == []:
        print 'No local copy of exoplanets.org database. Downloading one...'
        rawCSV = urlopen('http://www.exoplanets.org/csv-files/exoplanets.csv').read()
        saveCSV = open(rootPath+csvDatabasePath,'w')
        saveCSV.write(rawCSV)
        saveCSV.close()
    else: 
        '''If the local copy of the exoplanets.org database is >14 days old, download a new one'''
        secondsSinceLastModification = time() - getmtime(rootPath+csvDatabasePath) ## in seconds
        daysSinceLastModification = secondsSinceLastModification/(60*60*24*30)
        if daysSinceLastModification > 14:
            print 'Your local copy of the exoplanets.org database is >14 days old. Downloading a fresh one...'
            rawCSV = urlopen('http://www.exoplanets.org/csv-files/exoplanets.csv').read()
            saveCSV = open(rootPath+csvDatabasePath,'w')
            saveCSV.write(rawCSV)
            saveCSV.close()
        else: print "Your local copy of the exoplanets.org database is <14 days old. That'll do."

    if len(pklDatabasePaths) == 0:
        print 'Parsing '+csvDatabasePath+', the CSV database from exoplanets.org...'
        rawTable = open(rootPath+csvDatabasePath).read().splitlines()
        labels = rawTable[0].split(',')
        labelUnits = rawTable[1].split(',')
        rawTableArray = np.zeros([len(rawTable),len(rawTable[0].split(","))])
        exoplanetDB = {}
        planetNameColumn = np.arange(len(rawTable[0].split(',')))[np.array(rawTable[0].split(','),dtype=str)=='NAME'][0]
        for row in range(2,len(rawTable)): 
            splitRow = rawTable[row].split(',')
            #exoplanetDB[splitRow[0]] = {}    ## Create dictionary for this row's planet
            exoplanetDB[splitRow[planetNameColumn]] = {}    ## Create dictionary for this row's planet
            for col in range(0,len(splitRow)):
                #exoplanetDB[splitRow[0]][labels[col]] = splitRow[col]
                exoplanetDB[splitRow[planetNameColumn]][labels[col]] = splitRow[col]
        #exoplanetDB['units'] = {}        ## Create entry for units of each subentry
        #for col in range(0,len(labels)):
        #    exoplanetDB['units'][labels[col]] = labelUnits[col]
        
        output = open(rootPath+pklDatabaseName,'wb')
        cPickle.dump(exoplanetDB,output)
        output.close()
    else: 
        print 'Using previously parsed database from exoplanets.org...'
        ''' Import data from exoplanets.org, parsed by
            exoplanetDataParser1.py'''
        inputFile = open(rootPath+pklDatabaseName,'rb')
        exoplanetDB = cPickle.load(inputFile)
        inputFile.close()

    ''' Set up observatory parameters '''
    observatory = ephem.Observer()
    observatory.lat =  observatory_latitude#'38:58:50.16'    ## Input format-  deg:min:sec  (type=str)
    observatory.long = observatory_longitude#'-76:56:13.92' ## Input format-  deg:min:sec  (type=str)
    observatory.elevation = observatory_elevation   # m
    observatory.temp = observatory_temperature      ## Celsius 
    observatory.horizon = observatory_minHorizon    ## Input format-  deg:min:sec  (type=str)

    def trunc(f, n):
        '''Truncates a float f to n decimal places without rounding'''
        slen = len('%.*f' % (n, f))
        return str(f)[:slen]
        
    def RA(planet):
        '''Type: str, Units:  hours:min:sec'''
        return exoplanetDB[planet]['RA_STRING']
    def dec(planet):
        '''Type: str, Units:  deg:min:sec'''
        return exoplanetDB[planet]['DEC_STRING']
    def period(planet):
        '''Units:  days'''
        return float(exoplanetDB[planet]['PER'])
    def epoch(planet):
        '''Tc at mid-transit. Units:  days'''
        if exoplanetDB[planet]['TT'] == '': return 0.0
        else: return float(exoplanetDB[planet]['TT'])
    def duration(planet):
        '''Transit/eclipse duration. Units:  days'''
        if exoplanetDB[planet]['T14'] == '': return 0.0
        else: return float(exoplanetDB[planet]['T14'])
    def V(planet):
        '''V mag'''
        if exoplanetDB[planet]['V'] == '': return 0.0
        else: return float(exoplanetDB[planet]['V'])
    def KS(planet):
        '''KS mag'''
        if exoplanetDB[planet]['KS'] == '': return 0.0
        else: return float(exoplanetDB[planet]['KS'])

    def depth(planet):
        '''Transit depth'''
        if exoplanetDB[planet]['DEPTH'] == '': return 0.0
        else: return float(exoplanetDB[planet]['DEPTH'])
        
    def transitBool(planet):
        '''True if exoplanet is transiting, False if detected by other means'''
        if exoplanetDB[planet]['TRANSIT'] == '0': return 0
        elif exoplanetDB[planet]['TRANSIT'] == '1': return 1
    ########################################################################################
    ########################################################################################

    def datestr2list(datestr):
        ''' Take strings of the form: "2013/1/18 20:08:18" and return them as a
            tuple of the same parameters'''
        year,month,others = datestr.split('/')
        day, time = others.split(' ')
        hour,minute,sec = time.split(':')
        return (int(year),int(month),int(day),int(hour),int(minute),int(sec))

    def list2datestr(inList):
        '''Converse function to datestr2list'''
        inList = map(str,inList)
        return inList[0]+'/'+inList[1]+'/'+inList[2]+' '+inList[3].zfill(2)+':'+inList[4].zfill(2)+':'+inList[5].zfill(2)

    def list2datestrHTML(inList,alt,direction):
        '''Converse function to datestr2list'''
        inList = map(str,inList)
        #return inList[1].zfill(2)+'/'+inList[2].zfill(2)+'<br />'+inList[3].zfill(2)+':'+inList[4].zfill(2)
        return inList[1].zfill(2)+'/<strong>'+inList[2].zfill(2)+'</strong>, '+inList[3].zfill(2)+':'+inList[4].split('.')[0].zfill(2)+'<br /> '+alt+'&deg; '+direction

    def simbadURL(planet):
        if exoplanetDB[planet]['SIMBADURL'] == '': return 'http://simbad.harvard.edu/simbad/'
        else: return exoplanetDB[planet]['SIMBADURL']

    def RADecHTML(planet):
        return '<a href="'+simbadURL(planet)+'">'+RA(planet).split('.')[0]+'<br />'+dec(planet).split('.')[0]+'</a>'

    def constellation(planet):
        return exoplanetDB[planet]['Constellation']

    def orbitReference(planet):
        return exoplanetDB[planet]['TRANSITURL']

    def nameWithLink(planet):
        return '<a href="'+orbitReference(planet)+'">'+planet+'</a>'

    def mass(planet):
        if exoplanetDB[planet]['MASS'] == '': return '---'
        else: return trunc(float(exoplanetDB[planet]['MASS']),2)

    def semimajorAxis(planet):
        #return trunc(0.004649*float(exoplanetDB[planet]['AR'])*float(exoplanetDB[planet]['RSTAR']),3)   ## Convert from solar radii to AU
        return trunc(float(exoplanetDB[planet]['SEP']),3)

    def radius(planet):
        return trunc(float(exoplanetDB[planet]['R']),2) ## Convert from solar radii to Jupiter radii

    def midTransit(Tc, P, start, end):
        '''Calculate mid-transits between Julian Dates start and end, using a 2500 
           orbital phase kernel since T_c (for 2 day period, 2500 phases is 14 years)
           '''
        Nepochs = np.arange(0,2500)
        transitTimes = Tc + P*Nepochs
        transitTimesInSem = transitTimes[(transitTimes < end)*(transitTimes > start)]
        return transitTimesInSem

    def midEclipse(Tc, P, start, end):
        '''Calculate mid-eclipses between Julian Dates start and end, using a 2500 
           orbital phase kernel since T_c (for 2 day period, 2500 phases is 14 years)
           '''
        Nepochs = np.arange(0,2500)
        transitTimes = Tc + P*(0.5 + Nepochs)
        transitTimesInSem = transitTimes[(transitTimes < end)*(transitTimes > start)]
        return transitTimesInSem

    '''Choose which planets from the database to include in the search, 
       assemble a list of them.'''
    planets = []
    for planet in exoplanetDB:
        if V(planet) != 0.0 and depth(planet) != 0.0 and float(V(planet)) <= v_limit and float(depth(planet)) >= depth_limit and transitBool(planet):
            planets.append(planet)

    if calcTransits: transits = {}
    if calcEclipses: eclipses = {}
    for day in np.arange(startSem,endSem+1):
        if calcTransits: transits[str(day)] = []
        if calcEclipses: eclipses[str(day)] = []
    planetsNeverUp = []


    def azToDirection(az):
        az = float(az)
        if (az >= 0 and az < 22.5) or (az >= 337.5 and az < 360): return 'N'
        elif az >= 22.5 and az < 67.5:  return 'NE'
        elif az >= 67.5 and az < 112.5:  return 'E'
        elif az >= 112.5 and az < 157.5:  return 'SE'
        elif az >= 157.5 and az < 202.5:  return 'S'
        elif az >= 202.5 and az < 247.5:  return 'SW'
        elif az >= 247.5 and az < 292.5:  return 'W'    
        elif az >= 292.5 and az < 337.5:  return 'NW'
    #    if (az >= 0 and az < 45) or (az >= 315 and az < 360): return 'N'
    #    elif az >= 45 and az < 135:  return 'E'
    #    elif az >= 135 and az < 225: return 'S'
    #    elif az >= 225 and az < 315: return 'W'

    def ingressEgressAltAz(planet,observatory,ingress,egress):
        altitudes = []
        directions = []
        for time in [ingress,egress]:
            observatory.date = list2datestr(jd2gd(time))
            star = ephem.FixedBody()
            star._ra = ephem.hours(RA(planet))
            star._dec = ephem.degrees(dec(planet))
            star.compute(observatory)
            altitudes.append(str(ephem.degrees(star.alt)).split(":")[0])
            directions.append(azToDirection(str(ephem.degrees(star.az)).split(":")[0]))
        ingressAlt,egressAlt = altitudes
        ingressDir,egressDir = directions
        return ingressAlt,ingressDir,egressAlt,egressDir

    for planet in planets:        
        for day in np.arange(startSem,endSem+1,1.0):
            ''' Calculate sunset/rise times'''
            observatory.horizon = twilightType    ## Astronomical twilight, Input format-  deg:min:sec  (type=str), http://rhodesmill.org/pyephem/rise-set.html#computing-twilight
            observatory.date = list2datestr(jd2gd(day))
            sun = ephem.Sun()
            try:
                sunrise = gd2jd(datestr2list(str(observatory.next_rising(sun, use_center=True))))
                sunset = gd2jd(datestr2list(str(observatory.next_setting(sun, use_center=True))))
                sunriseStr = str(observatory.next_rising(sun, use_center=True))
                sunsetStr = str(observatory.next_setting(sun, use_center=True))
                '''Calculate mid-transits that occur on this night'''    
                transitEpochs = midTransit(epoch(planet),period(planet),sunset,sunrise)
                eclipseEpochs = midEclipse(epoch(planet),period(planet),sunset,sunrise)
                if calcTransits and len(transitEpochs) != 0:
                    transitEpoch = transitEpochs[0]
                    ingress = transitEpoch-duration(planet)/2
                    egress = transitEpoch+duration(planet)/2
                    
                    ''' Calculate positions of host stars'''
                    observatory.horizon = observatory_minHorizon    ## Input format-  deg:min:sec  (type=str)
                    star = ephem.FixedBody()
                    star._ra = ephem.hours(RA(planet))
                    star._dec = ephem.degrees(dec(planet))
                    star.compute(observatory)
                    exoplanetDB[planet]['Constellation'] = ephem.constellation(star)[0]
                    bypassTag = False
                    try: 
                        starrise = gd2jd(datestr2list(str(observatory.next_rising(star))))
                        starset = gd2jd(datestr2list(str(observatory.next_setting(star))))
                    except ephem.AlwaysUpError:
                        '''If the star is always up, you don't need starrise and starset to 
                           know that the event should be included further calculations'''
                        print 'Woo! '+str(planet)+' is always above the horizon.'
                        bypassTag = True
                    
                    '''If star is above horizon and sun is below horizon:'''        
                    if (ingress > sunset and egress < sunrise) and (ingress > starrise and egress < starset) or bypassTag:
                        ingressAlt,ingressDir,egressAlt,egressDir = ingressEgressAltAz(planet,observatory,ingress,egress)
                        transitInfo = [planet,transitEpoch,duration(planet)/2,'transit',ingressAlt,ingressDir,egressAlt,egressDir]
                        transits[str(day)].append(transitInfo)
                        
                    #else: print 'Partial transit'
                if calcEclipses and len(eclipseEpochs) != 0:
                    eclipseEpoch = eclipseEpochs[0]
                    ingress = eclipseEpoch-duration(planet)/2
                    egress = eclipseEpoch+duration(planet)/2
                    
                    ''' Calculate positions of host stars'''
                    observatory.horizon = observatory_minHorizon    ## Input format-  deg:min:sec  (type=str)
                    star = ephem.FixedBody()
                    star._ra = ephem.hours(RA(planet))
                    star._dec = ephem.degrees(dec(planet))
                    star.compute(observatory)
                    exoplanetDB[planet]['Constellation'] = ephem.constellation(star)[0]
                    bypassTag = False                    
                    try:
                        starrise = gd2jd(datestr2list(str(observatory.next_rising(star))))
                        starset = gd2jd(datestr2list(str(observatory.next_setting(star))))
                    except ephem.AlwaysUpError:
                        '''If the star is always up, you don't need starrise and starset to 
                           know that the event should be included further calculations'''
                        print 'Woo! '+str(planet)+' is always above the horizon.'
                        bypassTag = True
                                        
                    '''If star is above horizon and sun is below horizon:'''
                    if (ingress > sunset and egress < sunrise) and (ingress > starrise and egress < starset) or bypassTag:
                        ingressAlt,ingressDir,egressAlt,egressDir = ingressEgressAltAz(planet,observatory,ingress,egress)
                        eclipseInfo = [planet,eclipseEpoch,duration(planet)/2,'eclipse',ingressAlt,ingressDir,egressAlt,egressDir]
                        eclipses[str(day)].append(eclipseInfo)
                    #else: print 'Partial eclipse'
            except ephem.NeverUpError:
                if str(planet) not in planetsNeverUp:
                    print 'WARNING: '+str(planet)+' is never above the horizon. Ignoring it.'
                    planetsNeverUp.append(str(planet))
    def removeEmptySets(dictionary):
        '''Remove days where there were no transits/eclipses from the transit/eclipse list dictionary. 
           Can't iterate through the transits dictionary with a for loop because it would change length 
           as keys get deleted, so loop through with while loop until all entries are not empty sets'''
        dayCounter = startSem
        while any(dictionary[day] == [] for day in dictionary):    
            if dictionary[str(dayCounter)] == []:
                del dictionary[str(dayCounter)]
            dayCounter += 1

    if calcTransits: removeEmptySets(transits)
    if calcEclipses: removeEmptySets(eclipses)

    events = {}
    def mergeDictionaries(dict):
        for key in dict:
            if any(key == eventKey for eventKey in events) == False:    ## If key does not exist in events,
                if np.shape(dict[key])[0] == 1:    ## If new event is the only one on that night, add only it
                    events[key] = [dict[key][0]]
                else:            ## If there were multiple events that night, add them each
                    events[key] = []
                    for event in dict[key]:
                        events[key].append(event)
            else:
                if np.shape(dict[key])[0] > 1: ## If there are multiple entries to append,
                    for event in dict[key]:
                        events[key].append(event)
                else:                            ## If there is only one to add,
                    events[key].append(dict[key][0])
    if calcTransits: mergeDictionaries(transits)
    if calcEclipses: mergeDictionaries(eclipses)

    if textOut: 
        '''Write out a text report with the transits/eclipses. Write out the time of 
           ingress, egress, whether event is transit/eclipse, elapsed in time between
           ingress/egress of the temporally isolated events'''
        report = open(os.path.join(rootPath,'eventReport.txt'),'w')
        allKeys = []
        for key in events:
            allKeys.append(key)

        allKeys = np.array(allKeys)[np.argsort(allKeys)]
        for key in allKeys:
            if np.shape(events[key])[0] > 1:
                elapsedTime = []
                
                for i in range(1,len(events[key])):
                    nextPlanet = events[key][1]
                    planet = events[key][0]
                    double = False
                    '''If the other planet's ingress is before this one's egress, then'''
                    if ephem.Date(list2datestr(jd2gd(float(nextPlanet[1]-nextPlanet[2])))) -\
                             ephem.Date(list2datestr(jd2gd(float(planet[1]+planet[2])))) > 0.0:
                        double = True
                        elapsedTime.append(ephem.Date(list2datestr(jd2gd(float(nextPlanet[1]-nextPlanet[2])))) - \
                             ephem.Date(list2datestr(jd2gd(float(planet[1]+planet[2])))))
                        
                    if ephem.Date(list2datestr(jd2gd(float(planet[1]-planet[2])))) - \
                             ephem.Date(list2datestr(jd2gd(float(nextPlanet[1]+nextPlanet[2])))) > 0.0:
                        '''If the other planet's egress is before this one's ingress, then'''
                        double = True
                        elapsedTime.append(ephem.Date(list2datestr(jd2gd(float(planet[1]-planet[2])))) - \
                             ephem.Date(list2datestr(jd2gd(float(nextPlanet[1]+nextPlanet[2])))))
                
                if double:
                    report.write(list2datestr(jd2gd(float(key)+1)).split(' ')[0]+'\t'+'>1 event'+'\t'+str(np.max(elapsedTime)*24.0)+'\t'+'\n')
                else:
                    report.write(list2datestr(jd2gd(float(key)+1)).split(' ')[0]+'\n')
                for planet in events[key]:
                    if calcTransits and planet[3] == 'transit':
                        report.write('\t'+str(planet[0])+'\t'+str(planet[3])+'\t'+list2datestr(jd2gd(float(planet[1]-planet[2]))).split('.')[0]+'\t'+list2datestr(jd2gd(float(planet[1]+planet[2]))).split('.')[0]+'\n')
                    if calcEclipses and planet[3] == 'eclipse':
                        report.write('\t'+str(planet[0])+'\t'+str(planet[3])+'\t'+list2datestr(jd2gd(float(planet[1]-planet[2]))).split('.')[0]+'\t'+list2datestr(jd2gd(float(planet[1]+planet[2]))).split('.')[0]+'\n')

                report.write('\n')
            elif np.shape(events[key])[0] == 1:
                planet = events[key][0]
                report.write(list2datestr(jd2gd(float(key)+1)).split(' ')[0]+'\n')
                if calcTransits and planet[3] == 'transit':
                        report.write('\t'+str(planet[0])+'\t'+str(planet[3])+'\t'+list2datestr(jd2gd(float(planet[1]-planet[2]))).split('.')[0]+'\t'+list2datestr(jd2gd(float(planet[1]+planet[2]))).split('.')[0]+'\n')
                if calcEclipses and planet[3] == 'eclipse':
                        report.write('\t'+str(planet[0])+'\t'+str(planet[3])+'\t'+list2datestr(jd2gd(float(planet[1]-planet[2]))).split('.')[0]+'\t'+list2datestr(jd2gd(float(planet[1]+planet[2]))).split('.')[0]+'\n')
                report.write('\n')
        report.close()

    if htmlOut: 
        '''Write out a text report with the transits/eclipses. Write out the time of 
           ingress, egress, whether event is transit/eclipse, elapsed in time between
           ingress/egress of the temporally isolated events'''
        report = open(os.path.join(rootPath,'eventReport.html'),'w')
        allKeys = []
        for key in events:
            allKeys.append(key)
        ## http://www.kryogenix.org/code/browser/sorttable/
        htmlheader = '\n'.join([
            '<!doctype html>',\
            '<html>',\
            '    <head>',\
            '        <meta http-equiv="content-type" content="text/html; charset=UTF-8" />',\
            '        <title>Ephemeris</title>',\
            '        <link rel="stylesheet" href="stylesheetEphem.css" type="text/css" />',\
            '         <script type="text/javascript">',\
            '          function changeCSS(cssFile, cssLinkIndex) {',\
            '            var oldlink = document.getElementsByTagName("link").item(cssLinkIndex);',\
            '            var newlink = document.createElement("link")',\
            '            newlink.setAttribute("rel", "stylesheet");',\
            '            newlink.setAttribute("type", "text/css");',\
            '            newlink.setAttribute("href", cssFile);',\
                 
            '            document.getElementsByTagName("head").item(0).replaceChild(newlink, oldlink);',\
            '          }',\
            '        </script>',\
            '       <script src="./sorttable.js"></script>',\
            '    </head>',\
            '    <body>',\
            '        <div id="textDiv">',\
            '        <h1>Ephemerides for: '+observatory_name+'</h1>',\
            '        <h2>Observing dates (UT): '+list2datestr(jd2gd(startSem)).split(' ')[0]+' - '+list2datestr(jd2gd(endSem)).split(' ')[0]+'</h2>'
            '       Click the column headers to sort. ',\
            '        <table class="daynight" id="eph">',\
            '        <tr><th colspan=2>Toggle Color Scheme</th></tr>',\
            '        <tr><td><a href="#" onclick="changeCSS(\'stylesheetEphem.css\', 0);">Day</a></td><td><a href="#" onclick="changeCSS(\'stylesheetEphemDark.css\', 0);">Night</a></td></tr>',\
            '        </table>'])

        tableheader = '\n'.join([
            '\n        <table class="sortable" id="eph">',\
            '        <tr> <th>Planet<br /><span class="small">[Link: Orbit ref.]</span></th>      <th>Event</th>    <th>Ingress <br /><span class="small">(MM/DD<br />HH:MM, UT)</span></th> <th>Egress <br /><span class="small">(MM/DD<br />HH:MM, UT)</span></th>'+\
                '<th>V mag</th> <th>Depth<br />(mag)</th> <th>Duration<br />(hrs)</th> <th>RA/Dec<br /><span class="small">[Link: Simbad ref.]</span></th> <th>Const.</th> <th>Mass<br />(M<sub>J</sub>)</th>'+\
                '<th>Semimajor <br />Axis (AU)</th> <th>Radius<br />(R<sub>J</sub>)</th></tr>'])
        tablefooter = '\n'.join([
            '\n        </table>',\
            '        <br /><br />',])
        htmlfooter = '\n'.join([
            '\n        <p class="headinfo">',\
            '        Developed by Brett Morris with great gratitude for the help of <a href="http://rhodesmill.org/pyephem/">PyEphem</a>,<br/>',\
            '        and for up-to-date exoplanet parameters from <a href="http://www.exoplanets.org/">exoplanets.org</a> (<a href="http://adsabs.harvard.edu/abs/2011PASP..123..412W">Wright et al. 2011</a>).<br />',\
            '        </p>',\
            '        </div>',\
            '    </body>',\
            '</html>'])
        report.write(htmlheader)
        report.write(tableheader)

        allKeys = np.array(allKeys)[np.argsort(allKeys)]
        for key in allKeys:
            def writeHTMLtransit():
                indentation = '        '
                middle = '</td><td>'.join([nameWithLink(planet[0]),str(planet[3]),list2datestrHTML(jd2gd(float(planet[1]-planet[2])),planet[4],planet[5]),\
                                           list2datestrHTML(jd2gd(float(planet[1]+planet[2])),planet[6],planet[7]),trunc(V(str(planet[0])),2),\
                                           trunc(depth(planet[0]),4),trunc(24.0*duration(planet[0]),2),RADecHTML(planet[0]),constellation(planet[0]),\
                                           mass(planet[0]),semimajorAxis(planet[0]),radius(planet[0])])
                line = indentation+'<tr><td>'+middle+'</td></tr>\n'
                report.write(line)
            
            def writeHTMLeclipse():
                indentation = '        '
                middle = '</td><td>'.join([nameWithLink(planet[0]),str(planet[3]),list2datestrHTML(jd2gd(float(planet[1]-planet[2])),planet[4],planet[5]),\
                                           list2datestrHTML(jd2gd(float(planet[1]+planet[2])),planet[6],planet[7]),trunc(V(str(planet[0])),2),\
                                           '---',trunc(24.0*duration(planet[0]),2),RADecHTML(planet[0]),constellation(planet[0]),\
                                           mass(planet[0]),semimajorAxis(planet[0]),radius(planet[0])])
                line = indentation+'<tr><td>'+middle+'</td></tr>\n'
                report.write(line)

        
            if np.shape(events[key])[0] > 1:
                elapsedTime = []
                
                for i in range(1,len(events[key])):
                    nextPlanet = events[key][1]
                    planet = events[key][0]
                    double = False
                    '''If the other planet's ingress is before this one's egress, then'''
                    if ephem.Date(list2datestr(jd2gd(float(nextPlanet[1]-nextPlanet[2])))) -\
                             ephem.Date(list2datestr(jd2gd(float(planet[1]+planet[2])))) > 0.0:
                        double = True
                        elapsedTime.append(ephem.Date(list2datestr(jd2gd(float(nextPlanet[1]-nextPlanet[2])))) - \
                             ephem.Date(list2datestr(jd2gd(float(planet[1]+planet[2])))))
                        
                    if ephem.Date(list2datestr(jd2gd(float(planet[1]-planet[2])))) - \
                             ephem.Date(list2datestr(jd2gd(float(nextPlanet[1]+nextPlanet[2])))) > 0.0:
                        '''If the other planet's egress is before this one's ingress, then'''
                        double = True
                        elapsedTime.append(ephem.Date(list2datestr(jd2gd(float(planet[1]-planet[2])))) - \
                             ephem.Date(list2datestr(jd2gd(float(nextPlanet[1]+nextPlanet[2])))))
                
                #if double:
                #    report.write(list2datestr(jd2gd(float(key)+1)).split(' ')[0]+'\t'+'>1 event'+'\t'+str(np.max(elapsedTime)*24.0)+'\t'+'\n')
                #else:
                #    report.write(list2datestr(jd2gd(float(key)+1)).split(' ')[0]+'\n')
                for planet in events[key]:
                    if calcTransits and planet[3] == 'transit':
                        writeHTMLtransit()
                    if calcEclipses and planet[3] == 'eclipse':
                        writeHTMLeclipse()          
                #report.write('\n')
            elif np.shape(events[key])[0] == 1:
                planet = events[key][0]
                #report.write(list2datestr(jd2gd(float(key)+1)).split(' ')[0]+'\n')
                if calcTransits and planet[3] == 'transit':
                        writeHTMLtransit()
                if calcEclipses and planet[3] == 'eclipse':
                        writeHTMLeclipse()
               # report.write('\n')
        report.write(tablefooter)
        report.write(htmlfooter)
        report.close()
    #print exoplanetDB['HD 209458 b']
    print 'calculateEphemerides.py: Done'
Example #51
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()
Example #52
0
import ephem

yh = ephem.readdb("C/2012 S1 (ISON),h,11/28.7747/2013,62.3990,295.6529,345.5644,1.000002,0.012444,2000,7.5,3.2")

date = '2013/10/31'

yh.compute(date)
print(yh.name)
print("%s %s" % (yh.ra, yh.dec))
print("%s %s" % (ephem.constellation(yh), yh.mag))

# define an observer
Rome = ephem.city('Rome')
rome_watcher = ephem.Observer()
rome_watcher.lat = Rome.lat
rome_watcher.lon = Rome.lon
rome_watcher.date = date

yh.compute(rome_watcher)

# print some useful data computed on the loaded body
print("Tracking object: %s on date: %s from: %s" % (yh.name, date, Rome.name))
print "%s is in constellation: %s with magnitude %s" % (yh.name, ephem.constellation(yh)[1], yh.mag)
print("Rome next rising: %s" % rome_watcher.next_rising(yh))
print("Rome next setting: %s" % rome_watcher.next_setting(yh))
print("Earth distance: %s AUs" % yh.earth_distance)
print("Sun distance: %s AUs" % yh.sun_distance)
print("Sun distance: %s AUs" % yh.sun_distance)
print yh.az
print yh.alt
Example #53
0
def _month_calendar(city, year, month, begweek):
  # Main function creating a month's calendar.
  # Return a matrix representing a month's calendar
  # Each row represents a week; days outside this month are zero
  # Each cell is a string
  # if city is provided, add extra rows for planet info.
  day1, ndays = month_range(year, month, begweek)
  rows = []
  r7 = list(range(7))
  day = 1 - day1
  while day <= ndays:
    row = ['']*7
    # planet info
    pi_moon = ['']*7
    pi_name = ['']*7
    pi_constel = ['']*7
    pi_rise = ['']*7
    pi_set = ['']*7
    pi_event = ['']*7
    for i in r7:
      if 1 <= day <= ndays:
        row[i] = repr(day)

        # Annotate (city, year, month, day) here.
        if city:
          date = datetime.datetime(year, month, day)

          # Each weekday we will process and print one of the planets.
          if   i==0: planet = ephem.Sun()
          elif i==1: planet = ephem.Mercury()
          elif i==2: planet = ephem.Mars()
          elif i==3: planet = ephem.Venus()
          elif i==4: planet = ephem.Jupiter()
          elif i==5: planet = ephem.Moon()
          elif i==6: planet = ephem.Saturn()
          planet.compute(date)
          pi_name[i] = planet.name + ' in'

          # Find the constel of the planet
          constel = ephem.constellation(planet)[1]
          if len(constel) > 10:
            constel = constel[:10]
          pi_constel[i] = constel

          rise = city.next_rising(planet, start=date).datetime()
          sett = city.next_setting(planet, start=date).datetime()

          # convert rise/set to localtime
          rise = pytz.utc.localize(rise).astimezone(city.pytz)
          sett = pytz.utc.localize(sett).astimezone(city.pytz)

          pi_rise[i] = "Rise %02d:%02d" % (rise.hour, rise.minute)
          pi_set[i]  = "Set  %02d:%02d" % (sett.hour, sett.minute)

          # Moon phases (FM, NM, LQ, FQ)
          moon_phase = moon_is_full(date)
          if moon_phase:
            pi_moon[i] = moon_phase
          # TODO look for solstice equinox

          evdate = "%04d/%02d/%02d" % (year, month, day)
          if evdate in events:
            pi_event[i] += events[evdate]
          evdate = "%02d/%02d" % (month, day)
          if evdate in events:
            pi_event[i] += events[evdate]

      day = day + 1
      # next day
    rows.append(row)
    if city:
      rows.append(pi_name)
      rows.append(pi_constel)
      rows.append(pi_rise)
      rows.append(pi_set)
      rows.append(pi_moon)
      rows.append(pi_event)
      # we added planet_info_lines = 6
    # next week
  # next month
  return rows
Example #54
0
    if s > ve:
        ve = ephem.next_vernal_equinox( s )
        lm = 0

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

    p = s

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


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



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

    abr,const_name = ephem.constellation( moon )
    #print "constellation: %s dow: %s date: %s - GEOCENTRIC(%d,%d), Phase: %d " % ( const_name, daysofweek[d.weekday()], dl, moon.hlat,moon.hlon, moon.moon_phase )
    print """
Date: %s : %s
Moon Phase: %f / Constellation: %s
Lat: %f, Long: %f""" % ( dl , daysofweek[d.weekday()],moon.moon_phase,const_name,moon.hlat, moon.hlon, )
Example #55
0
            warszawa.long = '21.01'
            print 'najdogodniejsza pora obserwacji', warszawa.next_transit(x)
            x.compute(warszawa)
        if miasto =='Kraków':
            krakow = ephem.Observer()
            krakow.lat = '50.03'
            krakow.long = '19.56'
            print 'najdogodniejsza pora obserwacji', krakow.next_transit(x)
            x.compute(krakow)
    else:
        x=0

    h=x.earth_distance #przypisanie zmiennej h wartosci odleglosci ciala od ziemi (podane w Au - jednostkach astronomicznych)
    h=h*150000000 #1 AU = ~150mln km przypisanie zmiennej h odleglosci podanej w km
    print 'dystans od ziemi', x.earth_distance, 'AU','okolo',h,'km' #podanie odleglosci w dwoch miarach
    if ephem.constellation(x) == ('Ari','Aries'): #zamiana anielskich skrotow i nazw gwiazdozbiorow na polskie odpowiedniki
        print 'Obecnie w gwiazdozbiorze Barana' #wypisanie nazwy gwiazdozbioru
    if ephem.constellation(x) == ('Tau','Taurus'):
        print 'obecnie w gwiazdozbiorze Byka'
    if ephem.constellation(x) == ('Gem','Gemini'):
        print 'Obecnie w gwiazdozbiorze Blizniat'
    if ephem.constellation(x) == ('Can','Cancer'):
        print 'Obecznie w gwiazdozbiorze Raka'
    if ephem.constellation(x) == ('Leo','Leo'):
        print ' Obecnie w gwiazdozbiorze Lwa'
    if ephem.constellation(x) == ('Vir','Virgo'):
        print 'Obecnie w giwazdozbiorze Panny'
    if ephem.constellation(x) == ('Lib','Libra'):
        print 'Obecnie w gwiazdozbiorze Wagi'
    if ephem.constellation(x) == ('Scr','Scorpio'):
        print 'Obecnie w gwiazdozbiorze Skorpiona'
Example #56
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 ""
Example #57
0
for planet in allplanets:
    # Calculate upcoming transits for all planets
    transit_epoch = float(exoplanetDB[planet]['TT'])
    period = float(exoplanetDB[planet]['PER'])
    upcoming_transits = midTransit(transit_epoch,period,start_date,end_date)

    # If there is one or more transit occurring within `buildDBforNdays` days,
    if len(upcoming_transits) > 0:
        # For each of those transits, assemble the tweet data!
        for transit in upcoming_transits:
            # Identify constellation containing transiting planet with PyEphem
            star = ephem.FixedBody()
            star._ra = ephem.hours(exoplanetDB[planet]['RA_STRING'])
            star._dec = ephem.degrees(exoplanetDB[planet]['DEC_STRING'])
            star.compute()
            const = ephem.constellation(star)[1] # This is the full cnstellation name

            # Fetch the radius of the planet
            radius = float(exoplanetDB[planet]['R'])
            transittime = transit

            # Identify the minute during which the mid-transit time occurs.
            # This is the basis for how the transt tweet will be stored, since
            # tweets will be updated once per minute via crontab
            transitminute = jd2gd(transit)[:-7]

            # Start building the tweet! The first part will say which planet
            # is transiting
            planetline = "%s is transiting now" % planet

            # If there is a measurd distance to this planet and the tweet is
Example #58
0
def dispPlanets():

    title_txt = "Planets"
    dispTitle(title_txt)

    # local inforamtion parameterized
    lat = params.lat[loc_idx]
    lon = params.lon[loc_idx]
    alt = params.alt[loc_idx]
    tz = params.tz[loc_idx]

    # use time of 5AM today for all calculations so that it always gets next rise and set times for this evening

    mytz = pytz.timezone(tz)
    eptz = pytz.timezone('utc')

    now = datetime.date.today()
    basetime = mytz.localize( datetime.datetime(now.year,now.month,now.day)+ datetime.timedelta(hours=5))
    eptbasetime = basetime.astimezone(eptz)
    # print "eptbasetime", eptabasetime

    # define planets
    mercury = ephem.Mercury()
    venus = ephem.Venus()
    mars = ephem.Mars()
    jupiter = ephem.Jupiter()
    saturn = ephem.Saturn()
    uranus = ephem.Uranus()
    neptune = ephem.Neptune()

    # setup current location
    here = ephem.Observer()
    here.lon = str(lon)
    here.lat = str(lat)
    here.elev = alt
    here.date = eptbasetime
    # print here

    # compute objects based upon current location
    mercury.compute(here)
    venus.compute(here)
    mars.compute(here)
    jupiter.compute(here)
    saturn.compute(here)
    uranus.compute(here)
    neptune.compute(here)

    mercury_const = ephem.constellation(mercury)[1]
    venus_const = ephem.constellation(venus)[1]
    mars_const = ephem.constellation(mars)[1]
    jupiter_const = ephem.constellation(jupiter)[1]
    saturn_const = ephem.constellation(saturn)[1]
    uranus_const = ephem.constellation(uranus)[1]
    neptune_const = ephem.constellation(neptune)[1]

    print "mercury const:", mercury_const
    print "venus const:", venus_const
    print "mars const:", mars_const
    print "jupiter const:", jupiter_const
    print "saturn const:", saturn_const
    print "uranus const:", uranus_const
    print "neptune const:", neptune_const


    xcol1 = 16
    xcol2 = 120
    y = 38 + 16
    
    planet_label = font.render( "Planet:", True, (0,255,255))
    screen.blit(planet_label, (xcol1,y))

    planet_label = font.render( "Constellation:", True, (0,255,255))
    screen.blit(planet_label, (xcol2,y))

    y = 38 + 2*16
    yinc = 16

    planet_label = font.render( "Mercury", True, (255,255,255))
    screen.blit(planet_label, (xcol1,y))
    planet_label = font.render( mercury_const, True, (255,255,255))
    screen.blit(planet_label, (xcol2,y))

    y = y + yinc

    planet_label = font.render( "Venus", True, (255,255,255))
    screen.blit(planet_label, (xcol1,y))
    planet_label = font.render( venus_const, True, (255,255,255))
    screen.blit(planet_label, (xcol2,y))

    y = y + yinc

    planet_label = font.render( "Mars", True, (255,255,255))
    screen.blit(planet_label, (xcol1,y))
    planet_label = font.render( mars_const, True, (255,255,255))
    screen.blit(planet_label, (xcol2,y))

    y = y + yinc
    
    planet_label = font.render( "Jupiter", True, (255,255,255))
    screen.blit(planet_label, (xcol1,y))
    planet_label = font.render( jupiter_const, True, (255,255,255))
    screen.blit(planet_label, (xcol2,y))
  
    y = y + yinc
    
    planet_label = font.render( "Saturn", True, (255,255,255))
    screen.blit(planet_label, (xcol1,y))
    planet_label = font.render( saturn_const, True, (255,255,255))
    screen.blit(planet_label, (xcol2,y))

    y = y + yinc

    planet_label = font.render( "Uranus", True, (255,255,255))
    screen.blit(planet_label, (xcol1,y))
    planet_label = font.render( uranus_const, True, (255,255,255))
    screen.blit(planet_label, (xcol2,y))

    y = y + yinc

    planet_label = font.render( "Neptune", True, (255,255,255))
    screen.blit(planet_label, (xcol1,y))
    planet_label = font.render( neptune_const, True, (255,255,255))
    screen.blit(planet_label, (xcol2,y))
Example #59
0
 def test_constellation(self):
     oneb = readdb('Orion Nebula,f,5.59,-5.45,2,2000.0,')
     oneb.compute('1999/2/28')
     self.assertEqual(constellation(oneb), ('Ori', 'Orion'))
Example #60
0
    def GetPlanetInfo(self, planetName):
        try:
            IsReady = False

            checkName = planetName.lower()

            if checkName == "mercury":
                p = ephem.Mercury()
                IsReady = True

            if checkName == "venus":
                p = ephem.Venus()
                IsReady = True

            if checkName == "mars":
                p = ephem.Mars()
                IsReady = True

            if checkName == "jupiter":
                p = ephem.Jupiter()
                IsReady = True

            if checkName == "saturn":
                p = ephem.Saturn()
                IsReady = True

            if checkName == "uranus":
                p = ephem.Uranus()
                IsReady = True

            if checkName == "neptune":
                p = ephem.Neptune()
                IsReady = True

            if checkName == "pluto":
                p = ephem.Pluto()
                IsReady = True

            if IsReady == True:
                p.compute(self.myObserver)

                planet_rightascension = p.ra
                planet_declination = p.dec
                planet_magnitude = p.mag
                planet_elongation = p.elong  # angle to sun
                planet_size = p.size  # arcseconds
                planet_circumpolar = p.circumpolar  # stays above horizon?
                planet_neverup = p.neverup  # never rises?
                planet_sundistance = p.sun_distance  # distance to sun
                planet_earthdistance = p.earth_distance  # distance to earth
                planet_phase = p.phase  # % illuminated

                planet_altitude = p.alt
                planet_azimuth = p.az
                planet_compass = AU.AzimuthToCompassDirection(planet_azimuth)
                planet_constellation = str(ephem.constellation(p)[1])
                planet_rise_ut = self.myObserver.next_rising(p)
                planet_set_ut = self.myObserver.next_setting(p)
                planet_rise_local = ephem.localtime(planet_rise_ut)
                planet_set_local = ephem.localtime(planet_set_ut)

                planet_visible = True if planet_altitude > 0 else False

            else:
                print planetName + " is not valid."

            dictionaryData = {}
            dictionaryData["Name"] = str(planetName)
            dictionaryData["RightAscension"] = str(planet_rightascension)
            dictionaryData["Declination"] = str(planet_declination)
            dictionaryData["Magnitude"] = str(planet_magnitude)
            dictionaryData["Elongation"] = str(planet_elongation)
            dictionaryData["Size"] = str(planet_size)
            dictionaryData["Circumpolar"] = planet_circumpolar
            dictionaryData["NeverUp"] = planet_neverup
            dictionaryData["SunDistance"] = str(planet_sundistance)
            dictionaryData["EarthDistance"] = str(planet_earthdistance)
            dictionaryData["Phase"] = str(planet_phase)
            dictionaryData["Altitude"] = str(planet_altitude)
            dictionaryData["IsVisible"] = planet_visible
            dictionaryData["Azimuth"] = str(planet_azimuth)
            dictionaryData["Compass"] = str(planet_compass)
            dictionaryData["InConstellation"] = str(planet_constellation)
            dictionaryData["NextRiseUT"] = str(planet_rise_ut)
            dictionaryData["NextRiseLocal"] = str(planet_rise_local)
            # dictionaryData['NextRiseUntil'] = str(rise_details)
            dictionaryData["NextSetUT"] = str(planet_set_ut)
            dictionaryData["NextSetLocal"] = str(planet_set_local)
            # dictionaryData['NextSetUntil'] = str(set_details)
            dictionaryData["CalcDateUT"] = str(self.myObserver.date)

            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)
            print ""