def update_astronomical_tables(self): """ Update astronomical databases """ curr_time = dt.datetime.now() if "grand_spectra_run1a" in self.h5py_file.keys(): last_change = self.h5py_file['grand_spectra_run1a']['last_change'][ 0].decode() if last_change != '': last_change_obj = dt.datetime.strptime(last_change, '%Y-%m-%d') if np.abs((curr_time - last_change_obj).total_seconds()) / ( 60 * 60 * 24) > 7.0: #if last execution was more than a week ago try: from astroplan import download_IERS_A print("\nUpdating astronomical tables\n") download_IERS_A() return None except urllib.error.URLError: print( "Cannot download astronomical data. Check internet connection or manually update datatables. Defaulting to stored data" ) else: try: from astroplan import download_IERS_A print("\nUpdating astronomical tables\n") download_IERS_A() return None except urllib.error.URLError: print( "Cannot download astronomical data. Check internet connection or manually update datatables. Defaulting to stored data" )
def __init__(self, storage=None): if not storage: storage = PanStorage(bucket_name='panoptes-simulated-data') self.storage = storage self.cameras = defaultdict(list) self.star_dict = {} self.unit_dict = {} download_IERS_A()
def iers_data(): # grab the latest earth orientation data for observatory calculations if ap_utils.IERS_A_in_cache(): with warnings.catch_warnings(): warnings.filterwarnings( "error", category=astroplan.OldEarthOrientationDataWarning ) try: ap_utils._get_IERS_A_table() except astroplan.OldEarthOrientationDataWarning: astroplan.download_IERS_A()
def download_all_files(data_folder="{}/astrometry/data".format(os.getenv('PANDIR'))): download_IERS_A() for i in range(4214, 4219): fn = 'index-{}.fits'.format(i) dest = "{}/{}".format(data_folder, fn) if not os.path.exists(dest): url = "http://data.astrometry.net/4200/{}".format(fn) df = data.download_file(url) try: shutil.move(df, dest) except OSError as e: print("Problem saving. (Maybe permissions?): {}".format(e))
def download_all_files(data_folder="{}/astrometry/data".format( os.getenv('PANDIR'))): download_IERS_A() for i in range(4214, 4219): fn = 'index-{}.fits'.format(i) dest = "{}/{}".format(data_folder, fn) if not os.path.exists(dest): url = "http://data.astrometry.net/4200/{}".format(fn) df = data.download_file(url) try: shutil.move(df, dest) except OSError as e: print("Problem saving. (Maybe permissions?): {}".format(e))
def get_iers(url='https://datacenter.iers.org/data/9/finals2000A.all'): # check input(s) if not isinstance(url, str) or url.strip() == '': raise Exception(f'invalid input, url={url}') if not (url.strip().lower().startswith('ftp') or url.strip().lower().startswith('http')): raise Exception(f'invalid address, url={url}') # astropy download try: clear_download_cache() iers.IERS_A_URL = f'{url}' download_IERS_A() except: pass
def download_iers(self): """Downloads the earth rotation catalog needed for accurate coordinate positions. Note: This download gives us a host of problems. This function should be called less than every 14 days otherwise a warning will be given. Currently we are downloading of our own google-based mirror of the data. Returns: TYPE: Description """ try: download_IERS_A(show_progress=self.verbose) return True except Exception as e: logger.warning(f'Failed to download IERS A bulletin: {e!r}') return False
def get_iers_1(url=ASTROPLAN_IERS_URL): # check input(s) if not isinstance(url, str) or url.strip() == '': raise Exception(f'invalid input, url={url}') if not (url.strip().lower().startswith('ftp') or url.strip().lower().startswith('http')): raise Exception(f'invalid address, url={url}') # astroplan download try: print(f'IERS updating from astroplan from {url}') from astroplan import download_IERS_A download_IERS_A() print(f'IERS updated from astroplan from {url}') except: print(f'failed IERS update from astroplan from {url}')
def __init__(self, observatory, observations): self.observatory = observatory self.observations = observations #assign unique ids to observations for observation in self.observations: observation.id = self.last_id self.last_id += 1 #uncomment to download the latest for astroplan logger.debug('Updating Astroplan IERS Bulletin A...') download_IERS_A() #get *nearest* sunset and *next* sunrise times #still not a big fan of this! observatory_location_obsplan = Observer(longitude=self.observatory.longitude*u.deg, latitude=self.observatory.latitude*u.deg, elevation=self.observatory.altitude*u.m, name=self.observatory.code, timezone=self.observatory.timezone) self.sunset_time = observatory_location_obsplan.twilight_evening_nautical(Time.now(), which="nearest") self.sunrise_time = observatory_location_obsplan.twilight_morning_nautical(Time.now(), which="next") logger.debug('The nearest sunset is %s. The next sunrise is %s.'%(self.sunset_time.iso, self.sunrise_time.iso))
def download_all_files(self): """Downloads the files according to the attributes of this object.""" result = True try: download_IERS_A() except Exception as e: if not self.keep_going: raise e print('Failed to download IERS A bulletin: {}'.format(e)) result = False if self.wide_field: for i in range(4110, 4119): if not self.download_one_file('4100/index-{}.fits'.format(i)): result = False if self.narrow_field: for i in range(4210, 4219): if not self.download_one_file('4200/index-{}.fits'.format(i)): result = False return result
def dct_astroplan_loc(): location_name = 'Discovery Channel Telescope' try: dct_loc_dict = pickle.load(open(settings.DCT_ASTROPLAN_LOC_PICKLE, 'rb')) except FileNotFoundError: dct_loc_dict = {'archive_time': dt.utcnow(), 'location': Observer.at_site(location_name)} file = open(settings.DCT_ASTROPLAN_LOC_PICKLE, 'wb') pickle.dump(dct_loc_dict, file) file.close() archive_time = dct_loc_dict['archive_time'] dct_loc_obj = dct_loc_dict['location'] if (dt.utcnow()-archive_time) > td(days=2): from astroplan import download_IERS_A download_IERS_A() dct_loc_dict = {'archive_time': dt.utcnow(), 'location': Observer.at_site(location_name)} file = open(settings.DCT_ASTROPLAN_LOC_PICKLE, 'wb') pickle.dump(dct_loc_dict, file) file.close() return dct_loc_obj
def Isky_parker_radecobs(ra, dec, obs_time): ''' wrapper for Isky_parker, where the input parameters are calculated based on RA, Dec, and obs_time ''' from astroplan import download_IERS_A from astropy.coordinates import EarthLocation, SkyCoord, AltAz, get_sun, get_moon download_IERS_A() # target coordinates coord = SkyCoord(ra=ra * u.deg, dec=dec * u.deg) # observed time (UTC) utc_time = Time(obs_time) kpno = EarthLocation.of_site('kitt peak') kpno_altaz = AltAz(obstime=utc_time, location=kpno) coord_altaz = coord.transform_to(kpno_altaz) airmass = coord_altaz.secz elc_lat = coord.barycentrictrueecliptic.lat.deg gal_lat = coord.galactic.l.deg # galactic latitude ( used for ISL contribution ) gal_lon = coord.galactic.b.deg # galactic longitude ( used for ISL contribution ) tai = utc_time.tai # sun altitude (degrees) sun = get_sun(utc_time) sun_altaz = sun.transform_to(kpno_altaz) sunalt = sun_altaz.alt.deg # sun separation sunsep = sun.separation(coord).deg # used for scattered moonlight moon = get_moon(utc_time) moon_altaz = moon.transform_to(kpno_altaz) moon_alt = moon_altaz.alt.deg moon_sep = moon.separation(coord).deg #coord.separation(self.moon).deg elongation = sun.separation(moon) phase = np.arctan2(sun.distance * np.sin(elongation), moon.distance - sun.distance*np.cos(elongation)) moon_phase = phase.value moon_ill = (1. + np.cos(phase))/2. return Isky_parker(airmass, ecl_lat, gal_lat, gal_lon, tai, sun_alt, sun_sep, moon_phase, moon_ill, moon_alt, moon_sep)
def get_iers_2(url=ASTROPLAN_IERS_URL_ALTERNATE): # check input(s) if not isinstance(url, str) or url.strip() == '': raise Exception(f'invalid input, url={url}') if not (url.strip().lower().startswith('ftp') or url.strip().lower().startswith('http')): raise Exception(f'invalid address, url={url}') # astropy download try: print(f'IERS updating from astropy from {url}') from astroplan import download_IERS_A from astropy.utils import iers from astropy.utils.data import clear_download_cache clear_download_cache() iers.IERS_A_URL = f'{url}' download_IERS_A() print(f'IERS updated from astropy from {url}') except: print(f'failed IERS update from astropy from {url}')
def download_all_files(data_folder=None, wide_field=True, narrow_field=False): download_IERS_A() if data_folder is None: data_folder = "{}/astrometry/data".format(os.getenv('PANDIR')) def download_one_file(fn): dest = "{}/{}".format(data_folder, os.path.basename(fn)) if not os.path.exists(dest): url = "http://data.astrometry.net/{}".format(fn) df = data.download_file(url) try: shutil.move(df, dest) except OSError as e: print("Problem saving. (Maybe permissions?): {}".format(e)) if wide_field: for i in range(4110, 4119): download_one_file('4100/index-{}.fits'.format(i)) if narrow_field: for i in range(4210, 4219): download_one_file('4200/index-{}.fits'.format(i))
def get_iers(_url=ASTROPLAN_IERS_URL, _verbose=True): # get logger _iers_log = None if _verbose: _iers_log = UtilsLogger('IERS-Logger').logger # update ephemeris try: # try astroplan download if _verbose: _iers_log.info("from astroplan import download_IERS_A") from astroplan import download_IERS_A if _verbose: _iers_log.info("download_IERS_A()") download_IERS_A() except Exception: # try alternate download if _verbose: _iers_log.debug("from astroplan import download_IERS_A") from astroplan import download_IERS_A if _verbose: _iers_log.debug("from astropy.utils import iers") from astropy.utils import iers if _verbose: _iers_log.debug( "from astropy.utils.data import clear_download_cache") from astropy.utils.data import clear_download_cache if _verbose: _iers_log.debug("clear_download_cache()") clear_download_cache() if _verbose: _iers_log.debug(f"iers.IERS_A_URL = {_url}") iers.IERS_A_URL = f'{_url}' if _verbose: _iers_log.debug("download_IERS_A()") download_IERS_A()
def _update_IERS_A(): from astroplan import download_IERS_A download_IERS_A()
start = np.max([sunset_tonight, all_up_start]) end = np.min([sunrise_tonight, all_up_end]) is_up = site.target_is_up(time, obj) print("Is your object visible? " + str(is_up)) #print(is_up) t.sleep(3) if is_up == True: import numpy as np import astropy.units as u object_rise = site.target_rise_time(time, obj) + 5 * u.minute object_set = site.target_set_time(time, obj) - 5 * u.minute from astroplan import download_IERS_A download_IERS_A() sunset_tonight = site.sun_set_time(time, which='nearest') if sunset_tonight < time: print("the sun has already set at this location") else: print("sunset at your selected site will be " + sunset_tonight.iso + " UTC") t.sleep(3) from astroplan.plots import plot_airmass import matplotlib.pyplot as plt plot_airmass(obj, site, time) plt.title("Visibility Chart") plt.legend(loc=1, bbox_to_anchor=(1, 1))
def main(): download_IERS_A() print( "This program represents a Mueller matrix system for a dual channel polarimeter using the pyMuellerMat" "library.") find = "" while find != "d": # Prompt find = input( "\nWhat would you like to do?\na) compute the two beams of the Wollaston prism from Stokes " "parameters\nb) find the corresponding on-sky polarization with a set of measurements from " "the two beams of the Wollaston prism and HWP/parallactic angles data\nc) plot the tracks of " "a set of targets over time and parallactic angle from the Keck telescope\n" "d) quit the program\n(a/b/c/d): ").lower() if find == "a": stokes = [] # Get the Stokes parameters input and store into a list while len(stokes) != 4: stokes = input( "\nEnter the Stokes parameters, separated by a space: ") stokes = stokes.split() if len(stokes) != 4: print("Enter all four parameters!") stokes = np.array([[float(stokes[0])], [float(stokes[1])], [float(stokes[2])], [float(stokes[3])]]) woll = wollaston(stokes) print("\nThe two beams from the Wollaston prism are ", woll[0][0][0], " and ", woll[1][0][0]) input( "\n---------------------------------------------------------------------------------------------" ) # Plot the intensities if the user chooses to plot = input( "\nWould you like to see a plot of the intensities? (y/n): " ).lower() if plot == 'y': plot_wollaston(stokes) print( "\n---------------------------------------------------------------------------------------------" ) elif find == "b": # Get the intensities and angle data values = [] cont = "y" while cont == "y": I_1 = float( input( "\nEnter the first I parameter in the pair (positive Wollaston): " )) I_2 = float( input( "Enter the second I parameter in the pair (negative Wollaston): " )) hwp = math.radians(float(input("Enter the HWP angle (deg): "))) sky = math.radians( float(input("Enter the parallactic angle (deg): "))) values.append([I_1, I_2, hwp, sky]) cont = input( "\nDo you have another pair of data to add? (y/n): " ).lower() print("\nThe corresponding on-sky polarization is:\n") print(on_sky(values)) input( "\n---------------------------------------------------------------------------------------------" ) elif find == "c": # Get the targets to track targets = [] cont = "y" while cont == "y": target = input("\nEnter the name of the target to track: ") targets.append(target) cont = input("Add another target? (y/n): ").lower() print("\nTracking", ', '.join(targets), "...\n") track_plot(targets) input( "\n---------------------------------------------------------------------------------------------" ) print("\nProgram ended.\n")
def invoke(): """ Call all other relevant functions. """ cli_parse() download_IERS_A() check_integrity() CALDWELL_OBJECTS = parse_caldwell(Const.ROOT_DIR) MESSIER_OBJECTS = parse_messier(Const.ROOT_DIR) USER_OBJECTS = read_user_prefs() STARS, EPHEMERIS = query_jpl_horizons(USER_OBJECTS) EPHEMERIS_BODIES = list(EPHEMERIS.keys()) # api and returns the the list of stars invoke_skyview(STARS) # Open cache file cache_path = Path(Const.ROOT_DIR, "data", "cache") cache_file = json.loads(open(cache_path, "r").read()) for star in STARS: cache_file = set_simbad_values(star, cache_file) temp_cache = {**cache_file, **EPHEMERIS} # Dump cache file with open(cache_path, "w") as json_out: json.dump(temp_cache, json_out, indent=4, sort_keys=True) cache_file = json.loads(open(cache_path, "r").read()) set_img_txt(STARS) # Iterate through the ephemeris to add information for body in tqdm(EPHEMERIS_BODIES): cache_file = get_ephemeris_info(body, cache_file) # Dump cache file with open(cache_path, "w") as json_out: json.dump(cache_file, json_out, indent=4, sort_keys=True) visible_objs = dict() for star in cache_file: Logger.log("Gathering zen, altitude, and " + f"azimuth for {star}...") try: start_altitude, start_azimuth, end_altitude, end_azimuth = get_visible( star, cache_file[star]["Coordinates"]["ra"], cache_file[star]["Coordinates"]["dec"], ) except KeyError: continue if (start_altitude != "-" and start_azimuth != "-" and end_altitude != "-" and end_azimuth != "-"): Logger.log(f"Successfully gathered data for {star}!\n") visible = {str(star): dict()} if start_altitude != "-": visible[star]["Start Alt."] = round( float(start_altitude.to_string(decimal=True))) else: visible[star]["Start Alt."] = "-" if start_azimuth != "-": visible[star]["Start Az."] = round( float(start_azimuth.to_string(decimal=True))) else: visible[star]["Start Az."] = "-" if end_altitude != "-": visible[star]["End Alt."] = round( float(end_altitude.to_string(decimal=True))) else: visible[star]["End Alt."] = "-" if end_azimuth != "-": visible[star]["End Az."] = round( float(end_azimuth.to_string(decimal=True))) else: visible[star]["End Az."] = "-" visible_objs.update(visible) # Dump cache file with open(cache_path, "w") as json_out: json.dump(cache_file, json_out, indent=4, sort_keys=True) cache_file = json.loads(open(cache_path, "r").read()) # Iterate through the ephemeris to add information for body in tqdm(EPHEMERIS_BODIES): cache_file = get_ephemeris_info(body, cache_file) # Dump cache file with open(cache_path, "w") as json_out: json.dump(cache_file, json_out, indent=4, sort_keys=True) visible_messier = dict() visible = dict() for m_obj in MESSIER_OBJECTS.keys(): if (not isinstance(MESSIER_OBJECTS[str(m_obj)]["Brightness"], str) and MESSIER_OBJECTS[str(m_obj)]["Brightness"] <= Const.MIN_V): Logger.log("Gathering zen, altitude, and " + f"azimuth for {m_obj}...") start_altitude, start_azimuth, end_altitude, end_azimuth = get_visible( m_obj, MESSIER_OBJECTS[m_obj]["Coordinates"]["ra"], MESSIER_OBJECTS[m_obj]["Coordinates"]["dec"], ) if (start_altitude != "-" and start_azimuth != "-" and end_altitude != "-" and end_azimuth != "-"): Logger.log(f"Successfully gathered data for {m_obj}!\n") visible[str(m_obj)] = dict() visible[str( m_obj)]["Type"] = MESSIER_OBJECTS[m_obj]["Type"].title() try: visible[str(m_obj)]["Start Alt. (°)"] = round( float(start_altitude.to_string(decimal=True))) except AttributeError: visible[str(m_obj)]["Start Alt. (°)"] = start_altitude try: visible[str(m_obj)]["Start Az. (°)"] = round( float(start_azimuth.to_string(decimal=True))) except AttributeError: visible[str(m_obj)]["Start Az. (°)"] = start_azimuth try: visible[str(m_obj)]["End Alt. (°)"] = round( float(end_altitude.to_string(decimal=True))) except AttributeError: visible[str(m_obj)]["End Alt. (°)"] = end_altitude try: visible[str(m_obj)]["End Az. (°)"] = round( float(end_azimuth.to_string(decimal=True))) except AttributeError: visible[str(m_obj)]["End Az. (°)"] = end_azimuth visible[str(m_obj)]["Constellation"] = MESSIER_OBJECTS[m_obj][ "Constellation"] visible[str(m_obj)]["Brightness"] = MESSIER_OBJECTS[m_obj][ "Brightness"] visible[str(m_obj)]["Distance (Pm)"] = int( (float("%.2g" % MESSIER_OBJECTS[m_obj]["Distance"]))) visible_messier.update(visible) else: Logger.log(f"{m_obj} is not visible.", 30) else: Logger.log( f"Ignoring {m_obj} since it is below the magnitude threshold of {Const.MIN_V}", 30, ) visible_caldwell = dict() visible = dict() for c_obj in CALDWELL_OBJECTS.keys(): if (not isinstance(CALDWELL_OBJECTS[str(c_obj)]["Brightness"], str) and CALDWELL_OBJECTS[str(c_obj)]["Brightness"] <= Const.MIN_V): Logger.log("Gathering zen, altitude, and " + f"azimuth for {c_obj}...") start_altitude, start_azimuth, end_altitude, end_azimuth = get_visible( c_obj, CALDWELL_OBJECTS[c_obj]["Coordinates"]["ra"], CALDWELL_OBJECTS[c_obj]["Coordinates"]["dec"], ) if (start_altitude != "-" and start_azimuth != "-" and end_altitude != "-" and end_azimuth != "-"): Logger.log(f"Successfully gathered data for {c_obj}!\n") visible[str(c_obj)] = dict() visible[str( c_obj)]["Type"] = CALDWELL_OBJECTS[c_obj]["Type"].title() try: visible[str(c_obj)]["Start Alt. (°)"] = round( float(start_altitude.to_string(decimal=True))) except AttributeError: visible[str(c_obj)]["Start Alt. (°)"] = start_altitude try: visible[str(c_obj)]["Start Az. (°)"] = round( float(start_azimuth.to_string(decimal=True))) except AttributeError: visible[str(c_obj)]["Start Az. (°)"] = start_azimuth try: visible[str(c_obj)]["End Alt. (°)"] = round( float(end_altitude.to_string(decimal=True))) except AttributeError: visible[str(c_obj)]["End Alt. (°)"] = end_altitude try: visible[str(c_obj)]["End Az. (°)"] = round( float(end_azimuth.to_string(decimal=True))) except AttributeError: visible[str(c_obj)]["End Az. (°)"] = end_azimuth visible[str(c_obj)]["Constellation"] = CALDWELL_OBJECTS[c_obj][ "Constellation"] visible[str(c_obj)]["Brightness"] = CALDWELL_OBJECTS[c_obj][ "Brightness"] visible[str(c_obj)]["Distance (Pm)"] = int( float("%.2g" % CALDWELL_OBJECTS[c_obj]["Distance"])) visible_caldwell.update(visible) else: Logger.log(f"{c_obj} is not visible.", 30) else: Logger.log( f"Ignoring {c_obj} since it is below the magnitude threshold of {Const.MIN_V}", 30, ) set_img_txt(visible_messier) set_img_txt(visible_caldwell) s_list = list() v_obj = dict() to_prune = list() for star, data in cache_file.items(): num_of_dashes = 0 v_obj[star] = {} try: v_obj[star]["Type"] = cache_file[star]["Type"].title() except KeyError: v_obj[star]["Type"] = "-" try: v_obj[star]["Start Alt. (°)"] = visible_objs[star]["Start Alt."] except KeyError: num_of_dashes += 1 v_obj[star]["Alt. (°)"] = "-" try: v_obj[star]["Start Az. (°)"] = visible_objs[star]["Start Az."] except KeyError: num_of_dashes += 1 v_obj[star]["Start Az. (°)"] = "-" try: v_obj[star]["End Alt. (°)"] = visible_objs[star]["End Alt."] except KeyError: num_of_dashes += 1 v_obj[star]["End. (°)"] = "-" try: v_obj[star]["End Az. (°)"] = visible_objs[star]["End Az."] except KeyError: num_of_dashes += 1 v_obj[star]["End Az. (°)"] = "-" if num_of_dashes == 4: to_prune.append(star) continue try: v_obj[star]["Constellation"] = cache_file[star]["Constellation"] except KeyError: v_obj[star]["Constellation"] = "-" try: v_obj[star]["Brightness"] = cache_file[star]["Brightness"] except KeyError: v_obj[star]["Brightness"] = "-" try: if "e" in str(cache_file[star]["Distance"]): v_obj[star]["Distance (Pm)"] = "{:.5f}".format( float( str(round( float(cache_file[star]["Distance"]), 6, )).upper())) else: v_obj[star]["Distance (Pm)"] = cache_file[star]["Distance"] except KeyError: v_obj[star]["Distance (Pm)"] = "-" for f in to_prune: v_obj.pop(f, None) moon_data, _ = ephemeris_query("Moon") moon_data = moon_data.pop("Moon") months = { "01": "Jan", "02": "Feb", "03": "Mar", "04": "Apr", "05": "May", "06": "Jun", "07": "Jul", "08": "Aug", "09": "Sep", "10": "Oct", "11": "Nov", "12": "Dec", } v_obj["Moon"] = dict() phase_calculation() try: v_obj["Moon"]["Type"] = f"Satellite (Phase: {Const.MOON_PHASE})" except KeyError: v_obj["Moon"]["Type"] = "-" try: v_obj["Moon"]["Start Alt. (°)"] = round( float(moon_data[ f"{Const.START_YEAR}-{months[str(Const.START_MONTH)]}-{Const.START_DAY} {Const.START_TIME}"] ["alt"])) except KeyError: v_obj["Moon"]["Start Alt. (°)"] = "-" try: v_obj["Moon"]["Start Az. (°)"] = round( float(moon_data[ f"{Const.START_YEAR}-{months[str(Const.START_MONTH)]}-{Const.START_DAY} {Const.START_TIME}"] ["az"])) except KeyError: v_obj["Moon"]["Start Az. (°)"] = "-" try: v_obj["Moon"]["End Alt. (°)"] = round( float(moon_data[ f"{Const.END_YEAR}-{months[str(Const.END_MONTH)]}-{Const.END_DAY} {Const.END_TIME}"] ["alt"])) except KeyError: v_obj["Moon"]["End Alt. (°)"] = "-" try: v_obj["Moon"]["End Az. (°)"] = round( float(moon_data[ f"{Const.END_YEAR}-{months[str(Const.END_MONTH)]}-{Const.END_DAY} {Const.END_TIME}"] ["az"])) except KeyError: v_obj["Moon"]["End Az. (°)"] = "-" try: v_obj["Moon"]["Constellation"] = moon_data["Constellation"] except KeyError: v_obj["Moon"]["Constellation"] = "-" try: v_obj["Moon"]["Brightness"] = round( float(moon_data[ f"{Const.START_YEAR}-{months[str(Const.START_MONTH)]}-{Const.START_DAY} {Const.START_TIME}"] ["Brightness"]), 1, ) except KeyError: v_obj["Moon"]["Brightness"] = "-" try: v_obj["Moon"]["Distance"] = "{:.7f}".format( float( str( round( float(moon_data[ f"{Const.START_YEAR}-{months[str(Const.START_MONTH)]}-{Const.START_DAY} {Const.START_TIME}"] ["Distance"]), 8, )).upper())) except KeyError: v_obj["Moon"]["Distance"] = "-" overlay_text("Moon", v_obj) for key, value in v_obj.items(): s_list.append({str(key).title(): value}) m_list = list() for key, value in visible_messier.items(): m_list.append({key: value}) c_list = list() for key, value in visible_caldwell.items(): c_list.append({key: value}) write_out(s_list, filename="Stars") write_out(m_list, filename="VisibleMessier") write_out(c_list, filename="VisibleCaldwell") cel_objs = s_list + m_list + c_list if len(cel_objs) > 0: write_out(cel_objs, code=1) fixed_objs = list() for c in cel_objs: if str(list(c.keys())[0]).lower() in cache_file: ra, dec = ra_dec_to_deg( cache_file[str(list( c.keys())[0]).lower()]["Coordinates"]["ra"], cache_file[str(list( c.keys())[0]).lower()]["Coordinates"]["dec"], ) celestial_obj_coord = SkyCoord(ra=ra * u.deg, dec=dec * u.deg) fixed_objs.append( FixedTarget(coord=celestial_obj_coord, name=str(list(c.keys())[0]).title())) elif str(list(c.keys())[0]) in MESSIER_OBJECTS: ra, dec = ra_dec_to_deg( MESSIER_OBJECTS[str(list( c.keys())[0])]["Coordinates"]["ra"], MESSIER_OBJECTS[str(list( c.keys())[0])]["Coordinates"]["dec"], ) celestial_obj_coord = SkyCoord(ra=ra * u.deg, dec=dec * u.deg) fixed_objs.append( FixedTarget( coord=celestial_obj_coord, name=str(list(c.keys())[0]), )) elif str(list(c.keys())[0]) in CALDWELL_OBJECTS: ra, dec = ra_dec_to_deg( CALDWELL_OBJECTS[str(list( c.keys())[0])]["Coordinates"]["ra"], CALDWELL_OBJECTS[str(list( c.keys())[0])]["Coordinates"]["dec"], ) celestial_obj_coord = SkyCoord(ra=ra * u.deg, dec=dec * u.deg) fixed_objs.append( FixedTarget( coord=celestial_obj_coord, name=str(list(c.keys())[0]), )) elif str(list(c.keys())[0]).lower() == "moon": moon_data = json.loads( open( Path( Const.SLIDESHOW_DIR, "PySkySlideshow", f"Moon-{Const.START_YEAR}-{Const.START_MONTH}-{Const.START_DAY}-{Const.START_TIME.replace(':', '')}-{Const.END_YEAR}-{Const.END_MONTH}-{Const.END_DAY}-{Const.END_TIME.replace(':', '')}-data.json" ), "r").read()) celestial_obj_coord = SkyCoord( ra=moon_data['Coordinates']['ra'] * u.deg, dec=moon_data['Coordinates']['dec'] * u.deg) fixed_objs.append( FixedTarget( coord=celestial_obj_coord, name=str(list(c.keys())[0]), )) write_out(fixed_objs, code=2) else: Logger.log("No visible objects in the given range.")
def astroplan(self): """Updates astropy""" try: download_IERS_A() except Exception as excpt: self.logger.log(excpt)
# hour = tdelta(seconds=60.*60.*1.) # pyephem_site = ephem.Observer() # pyephem_site.lat = str(loc.lat.to(u.degree).value) # pyephem_site.lon = str(loc.lon.to(u.deg).value) # pyephem_site.elevation = loc.height.to(u.m).value # pyephem_moon = ephem.Moon() oneday = TimeDelta(60.*60.*24., format='sec') date_iso_string = '{:4d}-01-01T00:00:00'.format(args.year) start_date = Time(date_iso_string, format='isot', scale='utc', location=loc) sunset = obs.sun_set_time(start_date, which='next') ical_file = 'DarkMoonCalendar_{:4d}.ics'.format(args.year) if os.path.exists(ical_file): os.remove(ical_file) with open(ical_file, 'w') as FO: FO.write('BEGIN:VCALENDAR\n'.format()) FO.write('PRODID:-//hacksw/handcal//NONSGML v1.0//EN\n'.format()) while sunset < start_date + 365*oneday: search_around = sunset + oneday sunset = analyze_day(search_around, obs, FO, localtz, args, verbose=True) FO.write('END:VCALENDAR\n') if __name__ == '__main__': from astroplan import download_IERS_A download_IERS_A() main()
def wfpt(): parser = argparse.ArgumentParser(prog='wfpt.py', formatter_class=argparse.RawDescriptionHelpFormatter, description=textwrap.dedent(''' Weight function plotting tool ***************************************************************************************************** otfile OT catalog file name. prfile Gemini exechours program status file name. instcal Instrument calendar filename. -o --observatory Observatory site [DEFAULT='gemini_south']. Accepts the following: 1. 'gemini_north' (or 'MK' for Mauna Kea) 2. 'gemini_south' (or 'CP' for Cerro Pachon) -d --date Date 'YYYY-MM-DD' [DEFAULT=current]. -dst --daylightsavings Toggle daylight savings time [DEFAULT=False]. -dt --gridsize Size of time-grid spacing [DEFAULT=0.1hr]. Sky conditions: -i --iq Image quality constraint [DEFAULT=70]. -c --cc Cloud cover constraint [DEFAULT=50]. -w --wv Water vapor constraint [DEFAULT=Any]. Wind conditions: -dir --direction Wind direction [DEFAULT=270deg]. -vel --velocity Wind velocity [DEFAULT=10deg]. -rw --randwind Random wind conditions (use mean and standard deviation of site): Cerro Pachon : dir=(330 +/- 20)deg, vel=(5 +/- 3)m/s Mauna Kea : dir=(330 +/- 20)deg, vel=(5 +/- 3)m/s -u --update Download up-to-date IERS(International Earth Rotation and Reference Systems). ***************************************************************************************************** ''')) parser.add_argument(action='store', dest='otfile') parser.add_argument(action='store', dest='prfile') parser.add_argument(action='store', dest='instfile') parser.add_argument('-o', '--observatory', action='store', default='gemini_south') parser.add_argument('-d', '--date', action='store', default=None) parser.add_argument('-dst', '--daylightsavings', action='store_true', dest='dst', default=False) parser.add_argument('-dt', '--gridsize', action='store', default=0.1) parser.add_argument('-iq', '--iq', default='70') parser.add_argument('-cc', '--cc', default='50') parser.add_argument('-wv', '--wv', default='Any') parser.add_argument('-dir', '--direction', default=330) parser.add_argument('-vel', '--velocity', default=5) parser.add_argument('-rw', '--randwind', action='store_true', default=False) parser.add_argument('-u', '--update', action='store_true', default=False) parse = parser.parse_args() otfile = parse.otfile prfile = parse.prfile instfile = parse.instfile iq, cc, wv = convertcond.inputcond(parse.iq, parse.cc, parse.wv) dst = parse.dst dir = parse.direction vel = parse.velocity randwind = parse.randwind if parse.update: # download most recent International Earth Rotation and Reference Systems data download_IERS_A() verbose = False verbose_progress = True # Time grid spacing size in hours dt = float(parse.gridsize) * u.h if dt <= 0 * u.h: raise ValueError('Time grid spacing must be greater than 0.') # ====== Get Site Info ====== if verbose_progress: print('...observatory site, time_zone, utc_to_local') # Create 'astroplan.Observer' object for observing site. # Get time-zone name (for use by pytz) and utc_to_local time difference. site, timezone_name, utc_to_local = getsite(site_name=parse.observatory, daylightsavings=dst) # ====== Plan start/end dates ====== if verbose_progress: print('...scheduling period dates') # Check format of command line input dates. # Create 'astropy.time.core.Time' objects for start and end of plan period start, end = getdates(startdate=parse.date, enddate=None, utc_to_local=utc_to_local) # ====== Time data table for scheduling period ====== if verbose_progress: print('...time data and grids') # Create 'astropy.table.Table' (one row for each day in plan period) # Stores time grids for UTC, local, lst. # Stores solar midnight, evening/morning nautical twilights timetable = time_table(site=site, utc_to_local=utc_to_local, dt=dt, start=start, end=end) # set start and end times as boundaries of scheduling period start = Time(timetable[0]['utc'][0]) end = Time(timetable[-1]['utc'][-1]) # ====== Sun data table for scheduling period ====== if verbose_progress: print('...Sun data') # Create 'astropy.table.Table' (one row for each day in plan period) # Stores ra, dec at midnight on each night. # Stores azimuth angle, zenith distance angle, and hour angle # throughout scheduling period. sun = sun_table(latitude=site.location.lat, solar_midnight=timetable['solar_midnight'].data, lst=timetable['lst'].data) # ====== Moon data table for scheduling period ====== if verbose_progress: print('...Moon data') # Create 'astropy.table.Table' (one row for each day in plan period) # Stores fraction illuminated, phase angle, ra, and dec at solar midnight # on each night. # Stores ra, dec, azimuth angle, zenith distance angle, hour angle, airmass # throughout scheduling period. moon = moon_table(site=site, solar_midnight=timetable['solar_midnight'].data, utc=timetable['utc'].data, lst=timetable['lst'].data, verbose=False) # ====== Assemble Observation Table ====== if verbose_progress: print('...observations') # Create 'astropy.table.Table' (one observation per row) obs = observation_table(filename=otfile) # ====== Assemble Program Table ====== if verbose_progress: print('...programs') # read columns from exechours_YYYYL.txt file into 'astropy.table.Table' object exechourtable = program_table.read_exechours(filename=prfile) # retrieve additional program information from the observation table (if available) proginfo = program_table.get_proginfo(exechourtable=exechourtable, prog_ref_obs=obs['prog_ref'].data, obs_id=obs['obs_id'].data, pi=obs['pi'].data, partner=obs['partner'].data, band=obs['band'].data, too_status=obs['too_status'].data) # For now, program activation(prog_start) and # deactivation(prog_end) times are are set to the scheduling period # boundaries. # All programs are set to active. # These inputs can be changed once the information is available. progs = program_table.programtable(gemprgid=proginfo['prog_ref'].data, partner=proginfo['partner'].data, pi=proginfo['pi'].data, prog_time=proginfo['prog_time'].data, alloc_time=proginfo['alloc_time'].data, partner_time=proginfo['partner_time'].data, active=np.full(len(proginfo), True), prog_start=np.full(len(proginfo), start), prog_end=np.full(len(proginfo), end), too_status=proginfo['too_status'].data, scirank=proginfo['scirank'].data, observations=proginfo['obs'].data) # Add an additional column in the observation table to hold the # program table (progs) row index of each observation's # corresponding program. obs['i_prog'] = select_obs.i_progs(gemprgid=progs['gemprgid'].data, prog_ref=obs['prog_ref'].data) # ====== Instrument configuration calendar table ====== # Create 'astropy.table.Table' (one row per night in plan period) # Store date, available instruments, GMOS-FPU, GMOS-Disperser, F2-FPU if verbose_progress: print('...instrument calendar') instcal = instrument_table(filename=instfile, dates=timetable['date'].data) # ====== Timing windows and target calendar ====== if verbose_progress: print('...target calendar') targetcal = timing_windows.get_timing_windows(site=site, timetable=timetable, moon=moon, obs=obs, progs=progs, instcal=instcal) # -- Conditions tables -- skycond = condition_table(size=len(timetable['utc'][0]), iq=iq, cc=cc, wv=wv) wind = wind_table(size=len(timetable['utc'][0]), direction=dir, velocity=vel, site_name=site.name) if verbose: print('skycond\n',skycond) print('wind\n',wind) # ====== Get remaining available observations in nightly queue ====== # target_cal[i_day] observations with remaining program time i_queue_cal = np.where(progs['prog_comp'].data[obs['i_prog'].data[targetcal[0]['i'].data]] < 1)[0][:] # target_cal[i_day] observations with remaining observation time i_queue_cal = i_queue_cal[np.where(obs['obs_comp'].data[targetcal[0]['i'].data[i_queue_cal]] < 1)[0][:]] # obs table rows of observations with remaining observation and program time i_queue_obs = targetcal[0]['i'].data[i_queue_cal] # all observations with remaining observation and program time in full queue. # Required for computing the distribution of remaining observation time. i_obs = np.where(progs['prog_comp'].data[obs['i_prog'].data] < 1)[0][:] i_obs = i_obs[np.where(obs['obs_comp'].data[i_obs] < 1)[0][:]] # ====== Compute observation time distribution (wra = right ascension weight) ====== wra_all = weights.radist(ra=obs['ra'].quantity[i_obs], tot_time=obs['tot_time'].quantity[i_obs], obs_time=obs['obs_time'].quantity[i_obs]) # wra of all obs wra = wra_all[np.where([(i in i_obs) for i in i_queue_obs])[0][:]] # wra of obs in tonight's queue # ====== tonight's queue from targetcal table ====== # Create 'astropy.table.Table' for the active observations in tonight's queue targets = Table(targetcal[0][i_queue_cal]) weightplotmode(site=site, timetable=timetable, sun=sun, moon=moon, obs=Table(obs[i_queue_obs]), progs=progs, targets=targets, skycond=skycond, wind=wind, wra=wra) return
ETC_calculator = misc.ask_for_value( msg= 'Do you want to call the ETC calculator to process the results S/N ratio? (WARNING : Only works with stable internet connection!) y/n ' ) print( f"*** Running full transit analysis for transits between {d} and {d_end} ***" ) """ Update most recent IERS data """ get_IERS_data = 'yes' # not working at the moment, problem seams to be on IERS side. timeoutcount = 0 iers.Conf.iers_auto_url.set( 'https://datacenter.iers.org/data/9/finals2000A.all' ) # temporary fix for iers data download_IERS_A(show_progress=True) # success = 0 # while timeoutcount < 5 and success == 0: # timeoutcount += 1 # try: # download_IERS_A(show_progress=True) # print('IERS data successfully downloaded') # success = True # except Exception as e: # print(e, timeoutcount) # if success == 0: # get_IERS_A_or_workaround() # print('IERS data successfully retrieved')
def generate_schedule( telescope_config, global_constraint_configuration, start_datetime, end_datetime, no_weather_constraints=False, requests=None ): # Sometimes a warning arises called OldEarthOrientationDataWarning which means the following line must run to refresh # should find a way to catch this warning and only download when necessary download_IERS_A() cfht = Observer.at_site('cfht') transitioner = create_transitioner(telescope_config['slew_rate'], telescope_config['filters']) # Retrieve global constraints from Constraint Aggregator global_constraints = ca.initialize_constraints( global_constraint_configuration, start_datetime, end_datetime, no_weather_constraints ) # Currently defined in config but may belong on the block-level instead read_out = telescope_config['read_out'] * u.second # TODO: gather this data from each ObservationRequest instead n_exp = 5 blocks = [] # In order to supply block-level constraints, they should be initialized from attributes of the source data # and passed into the ObservingBlock initialization below for request in requests: # For each filter available on the telescope # TODO: define the available set within config for bandpass in ['B', 'G', 'R']: block = ObservingBlock.from_exposures( request.target, request.priority, request.duration, n_exp, read_out, configuration={'filter': bandpass}, constraints=[] ) blocks.append(block) print('Appending block {} with Target {} and filter {}'.format(block, request.target, bandpass)) prior_scheduler = PriorityScheduler( constraints=global_constraints, observer=cfht, transitioner=transitioner ) priority_schedule = Schedule(Time(start_datetime), Time(end_datetime)) prior_scheduler(blocks, priority_schedule) return priority_schedule