diff --git a/asteroidpy/__init__.py b/asteroidpy/__init__.py index ca87ab8..62b2104 100644 --- a/asteroidpy/__init__.py +++ b/asteroidpy/__init__.py @@ -1,22 +1,24 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- -import asteroidpy.interface import configparser -import cProfile, pstats +import cProfile +import pstats + +import asteroidpy.interface PROFILE = True config = configparser.ConfigParser() + def main(): """Main function""" - if (PROFILE): + if PROFILE: profiler = cProfile.Profile() profiler.enable() interface.interface(config) profiler.disable() - stats= pstats.Stats(profiler).sort_stats('ncalls') - stats.dump_stats('asteroidpy.prof') + stats = pstats.Stats(profiler).sort_stats("ncalls") + stats.dump_stats("asteroidpy.prof") else: interface.interface(config) - diff --git a/asteroidpy/configuration.py b/asteroidpy/configuration.py index 7a911c0..98d497e 100644 --- a/asteroidpy/configuration.py +++ b/asteroidpy/configuration.py @@ -13,7 +13,7 @@ def save_config(config): ------- """ - with open(os.path.expanduser('~')+'/'+'.asteroidpy', 'w') as f: + with open(os.path.expanduser("~") + "/" + ".asteroidpy", "w") as f: config.write(f) @@ -29,15 +29,17 @@ def initialize(config): ------- """ - config['General'] = {'lang': 'en'} - config['Observatory'] = {'place': '', - 'latitude': 0.0, - 'longitude': 0.0, - 'altitude': 0.0, - 'obs_name': '', - 'observer_name': '', - 'mpc_code': 'XXX'} - print('inizializzato') + config["General"] = {"lang": "en"} + config["Observatory"] = { + "place": "", + "latitude": 0.0, + "longitude": 0.0, + "altitude": 0.0, + "obs_name": "", + "observer_name": "", + "mpc_code": "XXX", + } + print("inizializzato") save_config(config) @@ -53,13 +55,13 @@ def load_config(config): ------- """ - dir_path = os.path.dirname(os.path.expanduser('~')) + dir_path = os.path.dirname(os.path.expanduser("~")) i = 0 for root, dirs, files in os.walk(dir_path): - if '.asteroidpy' in files: - config.read(os.path.expanduser('~')+'/'+'.asteroidpy') + if ".asteroidpy" in files: + config.read(os.path.expanduser("~") + "/" + ".asteroidpy") break - elif (i != 0 and i != 1): + elif i != 0 and i != 1: initialize(config) i += 1 @@ -79,7 +81,7 @@ def change_language(config, lang): """ load_config(config) - config['General']['lang'] = lang + config["General"]["lang"] = lang save_config(config) @@ -102,9 +104,9 @@ def change_obs_coords(config, place, lat, long): """ load_config(config) - config['Observatory']['place'] = place - config['Observatory']['latitude'] = str(lat) - config['Observatory']['longitude'] = str(long) + config["Observatory"]["place"] = place + config["Observatory"]["latitude"] = str(lat) + config["Observatory"]["longitude"] = str(long) save_config(config) @@ -123,7 +125,7 @@ def change_obs_altitude(config, alt): """ load_config(config) - config['Observatory']['altitude'] = str(alt) + config["Observatory"]["altitude"] = str(alt) save_config(config) @@ -142,7 +144,7 @@ def change_mpc_code(config, code): """ load_config(config) - config['Observatory']['mpc_code'] = str(code) + config["Observatory"]["mpc_code"] = str(code) save_config(config) @@ -161,7 +163,7 @@ def change_obs_name(config, name): """ load_config(config) - config['Observatory']['obs_name'] = str(name) + config["Observatory"]["obs_name"] = str(name) save_config(config) @@ -180,7 +182,7 @@ def change_observer_name(config, name): """ load_config(config) - config['Observatory']['observer_name'] = str(name) + config["Observatory"]["observer_name"] = str(name) save_config(config) @@ -197,13 +199,13 @@ def print_obs_config(config): """ load_config(config) - print('Località: %s' % config['Observatory']['place']) - print('Latitudine: %s' % config['Observatory']['latitude']) - print('Longitudine: %s' % config['Observatory']['longitude']) - print('Altitudine: %s' % config['Observatory']['altitude']) - print('Osservatore: %s' % config['Observatory']['observer_name']) - print('Nome Osservatorio: %s' % config['Observatory']['obs_name']) - print('Codice MPC: %s' % config['Observatory']['mpc_code']) + print("Località: %s" % config["Observatory"]["place"]) + print("Latitudine: %s" % config["Observatory"]["latitude"]) + print("Longitudine: %s" % config["Observatory"]["longitude"]) + print("Altitudine: %s" % config["Observatory"]["altitude"]) + print("Osservatore: %s" % config["Observatory"]["observer_name"]) + print("Nome Osservatorio: %s" % config["Observatory"]["obs_name"]) + print("Codice MPC: %s" % config["Observatory"]["mpc_code"]) def virtual_horizon_configuration(config, horizon): @@ -221,8 +223,8 @@ def virtual_horizon_configuration(config, horizon): """ load_config(config) - config['Observatory']['nord_altitude'] = horizon['nord'] - config['Observatory']['south_altitude'] = horizon['south'] - config['Observatory']['east_altitude'] = horizon['east'] - config['Observatory']['west_altitude'] = horizon['west'] + config["Observatory"]["nord_altitude"] = horizon["nord"] + config["Observatory"]["south_altitude"] = horizon["south"] + config["Observatory"]["east_altitude"] = horizon["east"] + config["Observatory"]["west_altitude"] = horizon["west"] save_config(config) diff --git a/asteroidpy/interface.py b/asteroidpy/interface.py index f13ddcd..1140f20 100644 --- a/asteroidpy/interface.py +++ b/asteroidpy/interface.py @@ -1,5 +1,6 @@ import datetime import gettext + import asteroidpy.configuration as configuration import asteroidpy.scheduling as scheduling @@ -23,7 +24,7 @@ def get_integer(message): userInt = int(input(message)) return userInt except ValueError: - print('You must enter an integer') + print("You must enter an integer") def get_float(message): @@ -43,7 +44,7 @@ def get_float(message): userFloat = float(input(message)) return userFloat except ValueError: - print('You must enter a number') + print("You must enter a number") def local_coords(config): @@ -52,36 +53,35 @@ def local_coords(config): Parameters ---------- config : - + Returns ------- """ configuration.load_config(config) - lat = config['Observatory']['latitude'] - long = config['Observatory']['longitude'] + lat = config["Observatory"]["latitude"] + long = config["Observatory"]["longitude"] return [lat, long] def select_specific_time(): """Returns specific time""" - print(_('Provide me with the observation start time parameters (UTC)')) - day = get_integer(_('Day -> ')) - month = get_integer(_('Month -> ')) - year = get_integer(_('Year -> ')) - hour = get_integer(_('Hour -> ')) - minutes = get_integer(_('Minutes -> ')) - seconds = get_integer(_('Seconds -> ')) - time = datetime.datetime( - year, month, day, hour, minutes, seconds) + print(_("Provide me with the observation start time parameters (UTC)")) + day = get_integer(_("Day -> ")) + month = get_integer(_("Month -> ")) + year = get_integer(_("Year -> ")) + hour = get_integer(_("Hour -> ")) + minutes = get_integer(_("Minutes -> ")) + seconds = get_integer(_("Seconds -> ")) + time = datetime.datetime(year, month, day, hour, minutes, seconds) return time def WIP(): """Prints a simply Work in Progress""" - print(_('Work in Progress')) - print('\n\n\n\n\n\n\n\n') + print(_("Work in Progress")) + print("\n\n\n\n\n\n\n\n") def change_obs_coords_menu(config): @@ -96,9 +96,9 @@ def change_obs_coords_menu(config): ------- """ - place = input(_('Locality -> ')) - latitude = get_float(_('Latitude -> ')) - longitude = get_float(_('Longitude -> ')) + place = input(_("Locality -> ")) + latitude = get_float(_("Latitude -> ")) + longitude = get_float(_("Longitude -> ")) configuration.change_obs_coords(config, place, latitude, longitude) @@ -114,7 +114,7 @@ def change_obs_altitude_menu(config): ------- """ - altitude = get_integer(_('Altitude -> ')) + altitude = get_integer(_("Altitude -> ")) configuration.change_obs_altitude(config, altitude) @@ -130,7 +130,7 @@ def change_observer_name_menu(config): ------- """ - name = input(_('Observer name -> ')) + name = input(_("Observer name -> ")) configuration.change_observer_name(config, name) @@ -146,7 +146,7 @@ def change_obs_name_menu(config): ------- """ - name = input(_('Observatory name -> ')) + name = input(_("Observatory name -> ")) configuration.change_obs_name(config, name) @@ -162,20 +162,24 @@ def change_mpc_code_menu(config): ------- """ - code = input(_('MPC Code -> ')) + code = input(_("MPC Code -> ")) configuration.change_mpc_code(config, code) def print_observatory_config_menu(): """Prints Observatory config text menu""" - print(_('''Choose an option + print( + _( + """Choose an option 1 - Change coordinates 2 - Change altitude 3 - Change the name of the observer 4 - Change the name of the observatory 5 - Change the MPC code 6 - Change Virtual Horizon - 0 - Back to configuration menu''')) + 0 - Back to configuration menu""" + ) + ) def observatory_config_menu(config): @@ -191,13 +195,13 @@ def observatory_config_menu(config): """ choice = 99 - while (choice != 0): - print(_('Configuration -> Observatory')) - print('==============================\n') + while choice != 0: + print(_("Configuration -> Observatory")) + print("==============================\n") configuration.print_obs_config(config) print_observatory_config_menu() - choice = get_integer(_('choice -> ')) - print('\n\n\n\n\n') + choice = get_integer(_("choice -> ")) + print("\n\n\n\n\n") if choice == 1: change_obs_coords_menu(config) if choice == 2: @@ -224,12 +228,12 @@ def change_language(config): ------- """ - lang = '' - print(_('Select a language')) - print('1 - English') - lang_chosen = get_integer(_('Language -> ')) + lang = "" + print(_("Select a language")) + print("1 - English") + lang_chosen = get_integer(_("Language -> ")) if lang_chosen == 1: - lang = 'en' + lang = "en" configuration.change_language(config, lang) @@ -246,15 +250,15 @@ def general_config_menu(config): """ choice = 99 - while (choice != 0): - print(_('Configuration -> General')) - print('==============================') - print('\n') - print(_('Choose a submenu')) - print(_('1 - Language')) - print(_('0 - Back to configuration menu')) - choice = get_integer(_('choice -> ')) - print('\n\n\n\n\n') + while choice != 0: + print(_("Configuration -> General")) + print("==============================") + print("\n") + print(_("Choose a submenu")) + print(_("1 - Language")) + print(_("0 - Back to configuration menu")) + choice = get_integer(_("choice -> ")) + print("\n\n\n\n\n") if choice == 1: change_language(config) @@ -272,16 +276,16 @@ def config_menu(config): """ choice = 99 - while (choice != 0): - print(_('Configuration')) - print('==============================') - print('\n') - print(_('Choose a submenu')) - print(_('1 - General')) - print(_('2 - Observatory')) - print(_('0 - Back to main menu')) - choice = eval(input(_('choice -> '))) - print('\n\n\n\n\n') + while choice != 0: + print(_("Configuration")) + print("==============================") + print("\n") + print(_("Choose a submenu")) + print(_("1 - General")) + print(_("2 - Observatory")) + print(_("0 - Back to main menu")) + choice = eval(input(_("choice -> "))) + print("\n\n\n\n\n") if choice == 1: general_config_menu(config) if choice == 2: @@ -302,9 +306,8 @@ def observing_target_list_menu(config): """ authenticity_token = "W5eBzzw9Clj4tJVzkz0z%2F2EK18jvSS%2BffHxZpAshylg%3D" coordinates = local_coords(config) - select_time = input(_( - 'Do you want to know the asteroids visible right now? [y/N]')) - if (select_time == 's' or select_time == 'y'): + select_time = input(_("Do you want to know the asteroids visible right now? [y/N]")) + if select_time == "s" or select_time == "y": time = datetime.datetime.utcnow() else: time = select_specific_time() @@ -313,39 +316,40 @@ def observing_target_list_menu(config): lunar_elongation = get_integer(_("Minimal lunar elongation -> ")) minimal_height = get_integer(_("Minimal altitude-> ")) max_objects = get_integer(_("Maximum number of objects -> ")) - object_request = get_integer(_( - 'Select type of object\n1 - Asteroids\n2 - NEAs\n3 - Comets\nChoice -> ')) - if (object_request == 2): - object_type = 'neo' - elif (object_request == 3): - object_type = 'cmt' + object_request = get_integer( + _("Select type of object\n1 - Asteroids\n2 - NEAs\n3 - Comets\nChoice -> ") + ) + if object_request == 2: + object_type = "neo" + elif object_request == 3: + object_type = "cmt" else: - object_type = 'mp' + object_type = "mp" payload = { - 'utf8': '%E2%9C%93', - 'authenticity_token': authenticity_token, - 'latitude': coordinates[0], - 'longitude': coordinates[1], - 'year': time.year, - 'month': time.month, - 'day': time.day, - 'hour': time.hour, - 'minute': time.minute, - 'duration': duration, - 'max_objects': max_objects, - 'min_alt': minimal_height, - 'solar_elong': solar_elongation, - 'lunar_elong': lunar_elongation, - 'object_type': object_type, - 'submit': 'Submit' + "utf8": "%E2%9C%93", + "authenticity_token": authenticity_token, + "latitude": coordinates[0], + "longitude": coordinates[1], + "year": time.year, + "month": time.month, + "day": time.day, + "hour": time.hour, + "minute": time.minute, + "duration": duration, + "max_objects": max_objects, + "min_alt": minimal_height, + "solar_elong": solar_elongation, + "lunar_elong": lunar_elongation, + "object_type": object_type, + "submit": "Submit", } target_list = scheduling.observing_target_list(config, payload) browser_view = input(_("Do you want to view in Browser? (y/N) -> ")) - if (browser_view in ["y", "Y"]): + if browser_view in ["y", "Y"]: target_list.show_in_browser(jsviewer=True) else: print(target_list) - print('\n\n\n\n') + print("\n\n\n\n") def neocp_confirmation_menu(config): @@ -360,18 +364,19 @@ def neocp_confirmation_menu(config): ------- """ - min_score = get_integer(_('Minimum score -> ')) - max_magnitude = get_float(_('Maximum magnitude -> ')) - min_altitude = get_integer(_('Minimum altitude -> ')) + min_score = get_integer(_("Minimum score -> ")) + max_magnitude = get_float(_("Maximum magnitude -> ")) + min_altitude = get_integer(_("Minimum altitude -> ")) browser_view = input(_("Do you want to view in Browser? (y/N) -> ")) neocp = scheduling.neocp_confirmation( - config, min_score, max_magnitude, min_altitude) + config, min_score, max_magnitude, min_altitude + ) # titles=['Designation', 'Score', 'R.A.', 'Dec.', 'Alt.', 'V', 'NObs', 'Arc', 'Not Seen Days'] - if (browser_view in ["y", "Y"]): + if browser_view in ["y", "Y"]: neocp.show_in_browser(jsviewer=True) else: print(neocp) - print('\n\n\n\n') + print("\n\n\n\n") # print(neocp) @@ -389,32 +394,45 @@ def twilight_sun_moon_menu(config): """ result_times = scheduling.twilight_times(config) print( - _(f"Civil Twilight: {result_times['CivilM'].strftime('%H:%M:%S')} - {result_times['CivilE'].strftime('%H:%M:%S')}")) + _( + f"Civil Twilight: {result_times['CivilM'].strftime('%H:%M:%S')} - {result_times['CivilE'].strftime('%H:%M:%S')}" + ) + ) print( - _(f"Nautical Twilight: {result_times['NautiM'].strftime('%H:%M:%S')} - {result_times['NautiE'].strftime('%H:%M:%S')}")) + _( + f"Nautical Twilight: {result_times['NautiM'].strftime('%H:%M:%S')} - {result_times['NautiE'].strftime('%H:%M:%S')}" + ) + ) print( - _(f"Astronomical Twilight: {result_times['AstroM'].strftime('%H:%M:%S')} - {result_times['AstroE'].strftime('%H:%M:%S')}")) - print('\n') + _( + f"Astronomical Twilight: {result_times['AstroM'].strftime('%H:%M:%S')} - {result_times['AstroE'].strftime('%H:%M:%S')}" + ) + ) + print("\n") ephemeris = scheduling.sun_moon_ephemeris(config) print(_(f"Sunrise: {ephemeris['Sunrise'].strftime('%H:%M:%S')}")) print(_(f"Sunset: {ephemeris['Sunset'].strftime('%H:%M:%S')}")) print(_(f"Moonrise: {ephemeris['Moonrise'].strftime('%H:%M:%S')}")) print(_(f"Moonset: {ephemeris['Sunrise'].strftime('%H:%M:%S')}")) print(_(f"Moon Illumination: {ephemeris['MoonIll']}")) - print('\n\n\n\n') + print("\n\n\n\n") def print_scheduling_menu(): """Prints scheduling menu""" - print(_('Observation scheduling')) - print('==============================\n') - print(_('''Choose a submenu + print(_("Observation scheduling")) + print("==============================\n") + print( + _( + """Choose a submenu 1 - Weather forecast 2 - Observing target List 3 - NEOcp list 4 - Object Ephemeris 5 - Twilight Times - 0 - Back to main menu\n''')) + 0 - Back to main menu\n""" + ) + ) def scheduling_menu(config): @@ -430,10 +448,10 @@ def scheduling_menu(config): """ choice = 99 - while (choice != 0): + while choice != 0: print_scheduling_menu() - choice = get_integer(_('choice -> ')) - print('\n\n\n\n\n') + choice = get_integer(_("choice -> ")) + print("\n\n\n\n\n") if choice == 1: scheduling.weather(config) if choice == 2: @@ -459,16 +477,16 @@ def main_menu(config): """ choice = 99 - while (choice != 0): - print(_('Welcome to AsteroidPY v. 0.1')) - print('==============================') - print('\n') - print(_('Choose a submenu')) - print(_('1 - Configuration')) - print(_('2 - Observation scheduling')) - print(_('0 - Exit')) - choice = get_integer(_('choice -> ')) - print('\n\n\n\n\n') + while choice != 0: + print(_("Welcome to AsteroidPY v. 0.1")) + print("==============================") + print("\n") + print(_("Choose a submenu")) + print(_("1 - Configuration")) + print(_("2 - Observation scheduling")) + print(_("0 - Exit")) + choice = get_integer(_("choice -> ")) + print("\n\n\n\n\n") if choice == 1: config_menu(config) if choice == 2: @@ -493,10 +511,10 @@ def interface(config): def print_change_horizon_menu(): """Prints Virtual Horizon menu""" horizon = {} - horizon['nord'] = input(_('Nord Altitude -> ')) - horizon['south'] = input(_('South Altitude -> ')) - horizon['east'] = input(_('East Altitude -> ')) - horizon['west'] = input(_('West Altitude -> ')) + horizon["nord"] = input(_("Nord Altitude -> ")) + horizon["south"] = input(_("South Altitude -> ")) + horizon["east"] = input(_("East Altitude -> ")) + horizon["west"] = input(_("West Altitude -> ")) return horizon @@ -515,6 +533,7 @@ def change_horizon(config): horizon = print_change_horizon_menu() configuration.virtual_horizon_configuration(config, horizon) + def object_ephemeris_menu(config): """Prints Object Ephemeris menu and calls scheduling.object_ephemeris @@ -527,13 +546,17 @@ def object_ephemeris_menu(config): ------- """ - object_name = input(_('Object Name -> ')) - print(_( '''Stepping + object_name = input(_("Object Name -> ")) + print( + _( + """Stepping m - 1 minute h - 1 hour d - 1 day w - 1 week - ''')) - step=input(_('Choice -> ')) + """ + ) + ) + step = input(_("Choice -> ")) ephemeris = scheduling.object_ephemeris(config, object_name, step) print(ephemeris) diff --git a/asteroidpy/scheduling.py b/asteroidpy/scheduling.py index dc400a9..c8dfb34 100644 --- a/asteroidpy/scheduling.py +++ b/asteroidpy/scheduling.py @@ -1,31 +1,95 @@ -import requests import asyncio -import httpx -import gettext -from asteroidpy import configuration import datetime -from bs4 import BeautifulSoup +import gettext + +import httpx +import requests +from astroplan import Observer from astropy import units as u -from astropy.coordinates import (SkyCoord, EarthLocation, AltAz) +from astropy.coordinates import AltAz, EarthLocation, SkyCoord from astropy.table import QTable from astropy.time import Time -from astroplan import Observer from astroquery.mpc import MPC +from bs4 import BeautifulSoup + +from asteroidpy import configuration _ = gettext.gettext -cloudcover_dict = {1: '0%-6%', 2: '6%-19%', 3: '19%-31%', 4: '31%-44%', - 5: '44%-56%', 6: '56%-69%', 7: '69%-81%', 8: '81%-94%', 9: '94%-100%'} -seeing_dict = {1: '<0.5"', 2: '0.5"-0.75"', 3: '0.75"-1"', 4: '1"-1.25"', - 5: '1.25"-1.5"', 6: '1.5"-2"', 7: '2"-2.5"', 8: '>2.5"'} -transparency_dict = {1: '<0.3', 2: '0.3-0.4', 3: '0.4-0.5', - 4: '0.5-0.6', 5: '0.6-0.7', 6: '0.7-0.85', 7: '0.85-1', 8: '>1', } -liftedIndex_dict = {-10: 'Below -7', -6: '-7 - -5', -4: '-5 - -3', - -1: '-3 - 0', 2: '0 - 4', 6: '4 - 8', 10: '8 - 11', 15: 'Over 11'} -rh2m_dict = {-4: '0%-5%', -3: '5%-10%', -2: '10%-15%', -1: '15%-20%', 0: '20%-25%', 1: '25%-30%', 2: '30%-35%', 3: '35%-40%', 4: '40%-45%', 5: '45%-50%', - 6: '50%-55%', 7: '55%-60%', 8: '60%-65%', 9: '65%-70%', 10: '70%-75%', 11: '75%-80%', 12: '80%-85%', 13: '85%-90%', 14: '90%-95%', 15: '95%-99%', 16: '100%'} -wind10m_speed_dict = {1: 'Below 0.3 m/s', 2: '0.3-3.4m/s', 3: '3.4-8.0m/s', 4: '8.0-10.8m/s', - 5: '10.8-17.2m/s', 6: '17.2-24.5m/s', 7: '24.5-32.6m/s', 8: 'Over 32.6m/s'} +cloudcover_dict = { + 1: "0%-6%", + 2: "6%-19%", + 3: "19%-31%", + 4: "31%-44%", + 5: "44%-56%", + 6: "56%-69%", + 7: "69%-81%", + 8: "81%-94%", + 9: "94%-100%", +} +seeing_dict = { + 1: '<0.5"', + 2: '0.5"-0.75"', + 3: '0.75"-1"', + 4: '1"-1.25"', + 5: '1.25"-1.5"', + 6: '1.5"-2"', + 7: '2"-2.5"', + 8: '>2.5"', +} +transparency_dict = { + 1: "<0.3", + 2: "0.3-0.4", + 3: "0.4-0.5", + 4: "0.5-0.6", + 5: "0.6-0.7", + 6: "0.7-0.85", + 7: "0.85-1", + 8: ">1", +} +liftedIndex_dict = { + -10: "Below -7", + -6: "-7 - -5", + -4: "-5 - -3", + -1: "-3 - 0", + 2: "0 - 4", + 6: "4 - 8", + 10: "8 - 11", + 15: "Over 11", +} +rh2m_dict = { + -4: "0%-5%", + -3: "5%-10%", + -2: "10%-15%", + -1: "15%-20%", + 0: "20%-25%", + 1: "25%-30%", + 2: "30%-35%", + 3: "35%-40%", + 4: "40%-45%", + 5: "45%-50%", + 6: "50%-55%", + 7: "55%-60%", + 8: "60%-65%", + 9: "65%-70%", + 10: "70%-75%", + 11: "75%-80%", + 12: "80%-85%", + 13: "85%-90%", + 14: "90%-95%", + 15: "95%-99%", + 16: "100%", +} +wind10m_speed_dict = { + 1: "Below 0.3 m/s", + 2: "0.3-3.4m/s", + 3: "3.4-8.0m/s", + 4: "8.0-10.8m/s", + 5: "10.8-17.2m/s", + 6: "17.2-24.5m/s", + 7: "24.5-32.6m/s", + 8: "Over 32.6m/s", +} async def httpx_get(url, payload, return_type): @@ -43,7 +107,7 @@ async def httpx_get(url, payload, return_type): """ async with httpx.AsyncClient() as client: r = await client.get(url, params=payload) - if (return_type == 'json'): + if return_type == "json": return [r.json(), r.status_code] else: return [r.text, r.status_code] @@ -64,7 +128,7 @@ async def httpx_post(url, payload, return_type): """ async with httpx.AsyncClient() as client: r = await client.post(url, data=payload) - if (return_type == 'json'): + if return_type == "json": return [r.json(), r.status_code] else: return [r.text, r.status_code] @@ -84,10 +148,14 @@ def weather_time(time_init, deltaT): ------- """ - time_start = datetime.datetime(int(time_init[0:4]), int( - time_init[4:6]), int(time_init[6:8]), int(time_init[8:10])) + time_start = datetime.datetime( + int(time_init[0:4]), + int(time_init[4:6]), + int(time_init[6:8]), + int(time_init[8:10]), + ) time = time_start + datetime.timedelta(hours=deltaT) - return time.strftime('%d/%m %H:%M') + return time.strftime("%d/%m %H:%M") def weather(config): @@ -103,28 +171,44 @@ def weather(config): """ configuration.load_config(config) - lat, long = config['Observatory']['latitude'], config['Observatory']['longitude'] - payload = {'lon': long, 'lat': lat, 'product': 'astro', 'output': 'json'} - r = requests.get('http://www.7timer.info/bin/api.pl', params=payload) + lat, long = config["Observatory"]["latitude"], config["Observatory"]["longitude"] + payload = {"lon": long, "lat": lat, "product": "astro", "output": "json"} + r = requests.get("http://www.7timer.info/bin/api.pl", params=payload) weather_forecast = r.json() - table = QTable([[""], [""], [""], [""], [""], [""], [""], [""], [""]], - names=('Time', 'Clouds', 'Seeing', 'Transp', - 'Instab', 'Temp', 'RH', 'Wind', 'Precip'), - meta={'name': 'Weather forecast'}) - for time in weather_forecast['dataseries']: - table.add_row([weather_time(weather_forecast['init'], time['timepoint']), - cloudcover_dict[time['cloudcover']], - seeing_dict[time['seeing']], - transparency_dict[time['transparency']], - liftedIndex_dict[time['lifted_index']], - str(time['temp2m'])+' C', - rh2m_dict[time['rh2m']], - time['wind10m']['direction'] + - ' ' + wind10m_speed_dict[time['wind10m']['speed']], - time['prec_type']]) + table = QTable( + [[""], [""], [""], [""], [""], [""], [""], [""], [""]], + names=( + "Time", + "Clouds", + "Seeing", + "Transp", + "Instab", + "Temp", + "RH", + "Wind", + "Precip", + ), + meta={"name": "Weather forecast"}, + ) + for time in weather_forecast["dataseries"]: + table.add_row( + [ + weather_time(weather_forecast["init"], time["timepoint"]), + cloudcover_dict[time["cloudcover"]], + seeing_dict[time["seeing"]], + transparency_dict[time["transparency"]], + liftedIndex_dict[time["lifted_index"]], + str(time["temp2m"]) + " C", + rh2m_dict[time["rh2m"]], + time["wind10m"]["direction"] + + " " + + wind10m_speed_dict[time["wind10m"]["speed"]], + time["prec_type"], + ] + ) table.remove_row(0) print(table) - print('\n\n\n\n') + print("\n\n\n\n") def skycoord_format(coord, coordid): @@ -142,10 +226,10 @@ def skycoord_format(coord, coordid): """ temp = coord.split() - if (coordid == 'ra'): - return temp[0]+'h'+temp[1]+'m'+temp[2]+'s' - elif (coordid == 'dec'): - return temp[0]+'d'+temp[1]+'m'+temp[2]+'s' + if coordid == "ra": + return temp[0] + "h" + temp[1] + "m" + temp[2] + "s" + elif coordid == "dec": + return temp[0] + "d" + temp[1] + "m" + temp[2] + "s" def is_visible(config, coord, time): @@ -163,23 +247,43 @@ def is_visible(config, coord, time): Returns ------- - + """ - location = EarthLocation.from_geodetic(lat=float(config['Observatory']['latitude'])*u.deg, lon=float( - config['Observatory']['longitude'])*u.deg, height=float(config['Observatory']['altitude'])*u.m) + location = EarthLocation.from_geodetic( + lat=float(config["Observatory"]["latitude"]) * u.deg, + lon=float(config["Observatory"]["longitude"]) * u.deg, + height=float(config["Observatory"]["altitude"]) * u.m, + ) if isinstance(coord, list): - coord = SkyCoord(skycoord_format( - coord[0], "ra") + " " + skycoord_format(coord[1], "dec")) + coord = SkyCoord( + skycoord_format(coord[0], "ra") + " " + skycoord_format(coord[1], "dec") + ) coord = coord.transform_to(AltAz(obstime=time, location=location)) configuration.load_config(config) result = False - if (coord.az > 315*u.deg and coord.az < 45*u.deg and coord.alt > float(config['Observatory']['nord_altitude'])*u.deg): + if ( + coord.az > 315 * u.deg + and coord.az < 45 * u.deg + and coord.alt > float(config["Observatory"]["nord_altitude"]) * u.deg + ): result = True - elif (coord.az > 45*u.deg and coord.az < 135*u.deg and coord.alt > float(config['Observatory']['east_altitude'])*u.deg): + elif ( + coord.az > 45 * u.deg + and coord.az < 135 * u.deg + and coord.alt > float(config["Observatory"]["east_altitude"]) * u.deg + ): result = True - elif (coord.az > 135*u.deg and coord.az < 225*u.deg and coord.alt > float(config['Observatory']['south_altitude'])*u.deg): + elif ( + coord.az > 135 * u.deg + and coord.az < 225 * u.deg + and coord.alt > float(config["Observatory"]["south_altitude"]) * u.deg + ): result = True - elif (coord.az > 225*u.deg and coord.az < 315*u.deg and coord.alt > float(config['Observatory']['west_altitude'])*u.deg): + elif ( + coord.az > 225 * u.deg + and coord.az < 315 * u.deg + and coord.alt > float(config["Observatory"]["west_altitude"]) * u.deg + ): result = True return result @@ -198,19 +302,18 @@ def observing_target_list_scraper(url, payload): ------- """ - r = requests.post( - url, params=payload) - soup = BeautifulSoup(r.content, 'lxml') - tables = soup.find_all('table') + r = requests.post(url, params=payload) + soup = BeautifulSoup(r.content, "lxml") + tables = soup.find_all("table") table = tables[3] - headerstag = table.find_all('th') + headerstag = table.find_all("th") headers = [] for header in headerstag: headers.append(header.string.strip()) - rowstag = table.find_all('tr') + rowstag = table.find_all("tr") datatag = [] for row in rowstag: - datatag.append(row.find_all('td')) + datatag.append(row.find_all("td")) data = [] for d in datatag: temp = [] @@ -228,21 +331,34 @@ def observing_target_list(config, payload): payload : dictionary of strings the payload of parameters config : - + Returns ------- """ - results = QTable([[""], [""], [""], [""], [""], [""]], - names=('Designation', 'Mag', 'Time', 'RA', 'Dec', 'Alt'), - meta={'name': 'Observing Target List'}) + results = QTable( + [[""], [""], [""], [""], [""], [""]], + names=("Designation", "Mag", "Time", "RA", "Dec", "Alt"), + meta={"name": "Observing Target List"}, + ) data = observing_target_list_scraper( - 'https://www.minorplanetcenter.net/whatsup/index', payload) + "https://www.minorplanetcenter.net/whatsup/index", payload + ) for d in data: - if (is_visible(config, [d[5], d[6]], Time(d[4].replace('T', ' ').replace('z', '')))): - results.add_row([d[0], d[1], d[4].replace('z', ''), skycoord_format( - d[5], 'ra'), skycoord_format(d[6], 'dec'), d[7]]) + if is_visible( + config, [d[5], d[6]], Time(d[4].replace("T", " ").replace("z", "")) + ): + results.add_row( + [ + d[0], + d[1], + d[4].replace("z", ""), + skycoord_format(d[5], "ra"), + skycoord_format(d[6], "dec"), + d[7], + ] + ) results.remove_row(0) return results @@ -268,31 +384,53 @@ def neocp_confirmation(config, min_score, max_magnitude, min_altitude): configuration.load_config(config) # r=requests.get('https://www.minorplanetcenter.net/Extended_Files/neocp.json') # data=r.json() - response = asyncio.run(httpx_get( - 'https://www.minorplanetcenter.net/Extended_Files/neocp.json', {}, 'json')) + response = asyncio.run( + httpx_get( + "https://www.minorplanetcenter.net/Extended_Files/neocp.json", {}, "json" + ) + ) data = response[0] - lat = config['Observatory']['latitude'] - long = config['Observatory']['longitude'] + lat = config["Observatory"]["latitude"] + long = config["Observatory"]["longitude"] location = EarthLocation.from_geodetic(lon=float(long), lat=float(lat)) observing_date = Time(datetime.datetime.utcnow()) altaz = AltAz(location=location, obstime=observing_date) - table = QTable([[""], [0], [""], [""], [0.0], [0.0], [0], [0.0], [0.0]], - names=('Temp_Desig', 'Score', 'R.A.', 'Decl', - 'Alt', 'V', 'NObs', 'Arc', 'Not_seen'), - meta={'name': 'NEOcp confirmation'}) + table = QTable( + [[""], [0], [""], [""], [0.0], [0.0], [0], [0.0], [0.0]], + names=( + "Temp_Desig", + "Score", + "R.A.", + "Decl", + "Alt", + "V", + "NObs", + "Arc", + "Not_seen", + ), + meta={"name": "NEOcp confirmation"}, + ) for item in data: - coord = SkyCoord(float(item['R.A.'])*u.deg, float(item['Decl.'])*u.deg) + coord = SkyCoord(float(item["R.A."]) * u.deg, float(item["Decl."]) * u.deg) coord_altaz = coord.transform_to(altaz) - if (int(item['Score'] > min_score and is_visible(config, coord, observing_date) and float(item['V'] < max_magnitude))): - table.add_row([item['Temp_Desig'], - int(item['Score']), - coord.ra.to_string(u.hour), - coord.dec.to_string(u.degree, alwayssign=True), - coord_altaz.alt, - float(item['V']), - int(item['NObs']), - float(item['Arc']), - float(item['Not_Seen_dys'])]) + if int( + item["Score"] > min_score + and is_visible(config, coord, observing_date) + and float(item["V"] < max_magnitude) + ): + table.add_row( + [ + item["Temp_Desig"], + int(item["Score"]), + coord.ra.to_string(u.hour), + coord.dec.to_string(u.degree, alwayssign=True), + coord_altaz.alt, + float(item["V"]), + int(item["NObs"]), + float(item["Arc"]), + float(item["Not_Seen_dys"]), + ] + ) table.remove_row(0) return table @@ -310,17 +448,21 @@ def twilight_times(config): """ configuration.load_config(config) - location = EarthLocation.from_geodetic(float(config['Observatory']['longitude'])*u.deg, float( - config['Observatory']['latitude'])*u.deg, float(config['Observatory']['altitude'])*u.m) - observer = Observer(name=config['Observatory'] - ['obs_name'], location=location) + location = EarthLocation.from_geodetic( + float(config["Observatory"]["longitude"]) * u.deg, + float(config["Observatory"]["latitude"]) * u.deg, + float(config["Observatory"]["altitude"]) * u.m, + ) + observer = Observer(name=config["Observatory"]["obs_name"], location=location) observing_date = Time(datetime.datetime.utcnow()) - result = {'AstroM': observer.twilight_morning_astronomical(observing_date, which='next'), - 'AstroE': observer.twilight_evening_astronomical(observing_date, which='next'), - 'CivilM': observer.twilight_morning_civil(observing_date, which='next'), - 'CivilE': observer.twilight_evening_civil(observing_date, which='next'), - 'NautiM': observer.twilight_morning_nautical(observing_date, which='next'), - 'NautiE': observer.twilight_evening_nautical(observing_date, which='next')} + result = { + "AstroM": observer.twilight_morning_astronomical(observing_date, which="next"), + "AstroE": observer.twilight_evening_astronomical(observing_date, which="next"), + "CivilM": observer.twilight_morning_civil(observing_date, which="next"), + "CivilE": observer.twilight_evening_civil(observing_date, which="next"), + "NautiM": observer.twilight_morning_nautical(observing_date, which="next"), + "NautiE": observer.twilight_evening_nautical(observing_date, which="next"), + } return result @@ -337,17 +479,20 @@ def sun_moon_ephemeris(config): """ configuration.load_config(config) - location = EarthLocation.from_geodetic(float(config['Observatory']['longitude'])*u.deg, float( - config['Observatory']['latitude'])*u.deg, float(config['Observatory']['altitude'])*u.m) - observer = Observer(name=config['Observatory'] - ['obs_name'], location=location) + location = EarthLocation.from_geodetic( + float(config["Observatory"]["longitude"]) * u.deg, + float(config["Observatory"]["latitude"]) * u.deg, + float(config["Observatory"]["altitude"]) * u.m, + ) + observer = Observer(name=config["Observatory"]["obs_name"], location=location) observing_date = Time(datetime.datetime.utcnow()) - result = {'Sunrise': observer.sun_rise_time(observing_date, which='next'), - 'Sunset': observer.sun_set_time(observing_date, which='next'), - 'Moonrise': observer.moon_rise_time(observing_date, which='next'), - 'Moonset': observer.moon_set_time(observing_date, which='next'), - 'MoonIll': observer.moon_illumination(observing_date) - } + result = { + "Sunrise": observer.sun_rise_time(observing_date, which="next"), + "Sunset": observer.sun_set_time(observing_date, which="next"), + "Moonrise": observer.moon_rise_time(observing_date, which="next"), + "Moonset": observer.moon_set_time(observing_date, which="next"), + "MoonIll": observer.moon_illumination(observing_date), + } return result @@ -370,19 +515,25 @@ def object_ephemeris(config, object_name, stepping): """ configuration.load_config(config) - location = EarthLocation.from_geodetic(float(config['Observatory']['longitude'])*u.deg, float( - config['Observatory']['latitude'])*u.deg, float(config['Observatory']['altitude'])*u.m) - if stepping == 'm': - step=1*u.minute - elif stepping == 'h': - step='1h' - elif stepping == 'd': - step='1d' - elif stepping == 'w': - step='7d' + location = EarthLocation.from_geodetic( + float(config["Observatory"]["longitude"]) * u.deg, + float(config["Observatory"]["latitude"]) * u.deg, + float(config["Observatory"]["altitude"]) * u.m, + ) + if stepping == "m": + step = 1 * u.minute + elif stepping == "h": + step = "1h" + elif stepping == "d": + step = "1d" + elif stepping == "w": + step = "7d" else: - print(_('Wrong code')) - eph = MPC.get_ephemeris(str(object_name).upper(), location=location, step=step, number=30) - ephemeris = eph['Date', 'RA', 'Dec', 'Elongation', - 'V', 'Altitude', 'Proper motion', 'Direction'] + print(_("Wrong code")) + eph = MPC.get_ephemeris( + str(object_name).upper(), location=location, step=step, number=30 + ) + ephemeris = eph[ + "Date", "RA", "Dec", "Elongation", "V", "Altitude", "Proper motion", "Direction" + ] return ephemeris diff --git a/setup.py b/setup.py index 0cb7a71..fcb80af 100644 --- a/setup.py +++ b/setup.py @@ -1,27 +1,33 @@ -from setuptools import setup, find_packages +from setuptools import find_packages, setup setup( - name='AsteroidPy', - version='0.1', - description='A tool for asteroid observation scheduling and analysis', - url='https://github.com/ziriuz84/asteroidpy', - author='Sirio Negri', - author_email='ziriuz84@gmail.com', - license='GPL v3', - packages=find_packages('.'), - install_requires=['requests', - 'bs4', 'configparser', 'astropy', 'httpx', 'astroplan', 'lxml', 'astroquery'], + name="AsteroidPy", + version="0.1", + description="A tool for asteroid observation scheduling and analysis", + url="https://github.com/ziriuz84/asteroidpy", + author="Sirio Negri", + author_email="ziriuz84@gmail.com", + license="GPL v3", + packages=find_packages("."), + install_requires=[ + "requests", + "bs4", + "configparser", + "astropy", + "httpx", + "astroplan", + "lxml", + "astroquery", + ], classifiers=[ - 'Development Status :: 1 - Planning', - 'Intended Audience :: Science/Research', - 'License :: OSI Approved :: GPL v3', - 'Operating System :: POSIX :: Linux', - 'Programming Language :: Python :: 3', + "Development Status :: 1 - Planning", + "Intended Audience :: Science/Research", + "License :: OSI Approved :: GPL v3", + "Operating System :: POSIX :: Linux", + "Programming Language :: Python :: 3", ], - py_modules=['configuration', 'scheduling', 'interface'], + py_modules=["configuration", "scheduling", "interface"], entry_points={ - 'console_scripts': [ - 'asteroidpy=asteroidpy:main' - ], + "console_scripts": ["asteroidpy=asteroidpy:main"], }, )