def get_radec_ephemeris(eph_json_single, start_time, end_time, interval, observing_facility, observing_site): observing_facility_class = facility.get_service_class(observing_facility) sites = observing_facility_class().get_observing_sites() observer = None for site_name in sites: obs_site = sites[site_name] if obs_site['sitecode'] == observing_site: observer = coordinates.EarthLocation( lat=obs_site.get('latitude') * units.deg, lon=obs_site.get('longitude') * units.deg, height=obs_site.get('elevation') * units.m) if observer is None: # this condition occurs if the facility being requested isn't in the site list provided. return (None, None, None, None, -1) ra = [] dec = [] mjd = [] for i in range(len(eph_json_single)): ra.append(float(eph_json_single[i]['R'])) dec.append(float(eph_json_single[i]['D'])) mjd.append(float(eph_json_single[i]['t'])) ra = np.array(ra) dec = np.array(dec) mjd = np.array(mjd) fra = interp.interp1d(mjd, ra) fdec = interp.interp1d(mjd, dec) start = Time(start_time) end = Time(end_time) time_range = time_grid_from_range(time_range=[start, end], time_resolution=interval * units.hour) tr_mjd = time_range.mjd airmasses = [] sun_alts = [] for i in range(len(tr_mjd)): c = SkyCoord(fra(time_range[i].mjd), fdec(time_range[i].mjd), frame="icrs", unit="deg") t = Time(tr_mjd[i], format='mjd') sun = coordinates.get_sun(t) altaz = c.transform_to(AltAz(obstime=t, location=observer)) sun_altaz = sun.transform_to(AltAz(obstime=t, location=observer)) airmass = altaz.secz airmasses.append(airmass) sun_alts.append(sun_altaz.alt.value) airmasses = np.array(airmasses) sun_alts = np.array(sun_alts) if np.min(tr_mjd) >= np.min(mjd) and np.max(tr_mjd) <= np.max(mjd): return (tr_mjd, fra(tr_mjd), fdec(tr_mjd), airmasses, sun_alts) else: return (None, None, None, None, -2)
def get_astroplan_sun_and_time(start_time, end_time, interval): """ Uses astroplan's time_grid_from_range to generate an astropy Time object covering the time range. Uses astropy's get_sun to generate sun positions over that time range. If time range is small and interval is coarse, approximates the sun at a fixed position from the middle of the time range to speed up calculations. Since the sun moves ~4 minutes a day, this approximation happens when the number of days covered by the time range * 4 is less than the interval (in minutes) / 2. :param start_time: start of the window for which to calculate the airmass :type start_time: datetime :param end_time: end of the window for which to calculate the airmass :type end_time: datetime :param interval: time interval, in minutes, at which to calculate airmass within the given window :type interval: int :returns: ra/dec positions of the sun over the time range, time range between start_time and end_time at interval :rtype: astropy SkyCoord, astropy Time """ start = Time(start_time) end = Time(end_time) time_range = time_grid_from_range(time_range=[start, end], time_resolution=interval * units.minute) number_of_days = end.mjd - start.mjd if number_of_days * 4 < float(interval) / 2: # Hack to speed up calculation by factor of ~3 sun_coords = get_sun(time_range[int(len(time_range) / 2)]) sun = FixedTarget(name='sun', coord=SkyCoord(sun_coords.ra, sun_coords.dec, unit='deg')) else: sun = get_sun(time_range) return sun, time_range
def get_forecast_window(start=None, size=30 * units.day, cadence=2 * units.min): """ Get an array of times in JD to forecast transits. Defaults to an array covering the next 30 days at 2-min cadence. Parameters ---------- start : `~astropy.time.Time`, optional Start of the forecast window. `None` defaults to now. size : float or `~astropy.units.Quantity`, optional Size of the forecast window. Defaults to days if unit not specified. cadence : float or `~astropy.units.Quantity`, optional Cadence of the times in the forecast window. Defaults to 2-min if unit not specfied. Returns ------- tforecast : `~astropy.time.Time` Array of times. """ if start is None: start = Time.now() if type(size) is units.Quantity: size = size.to(units.day) else: size = size * units.day if type(cadence) is units.Quantity: cadence = cadence.to(units.day) else: cadence = cadence * units.day tforecast = ap.time_grid_from_range([start, start + size], cadence) return tforecast
def get_24hr_airmass(target, interval, airmass_limit): plot_data = [] start = Time(datetime.datetime.utcnow()) end = Time(start.datetime + datetime.timedelta(days=1)) time_range = time_grid_from_range( time_range = [start, end], time_resolution = interval*u.minute) time_plot = time_range.datetime fixed_target = FixedTarget(name = target.name, coord = SkyCoord( target.ra, target.dec, unit = 'deg' ) ) #Hack to speed calculation up by factor of ~3 sun_coords = get_sun(time_range[int(len(time_range)/2)]) fixed_sun = FixedTarget(name = 'sun', coord = SkyCoord( sun_coords.ra, sun_coords.dec, unit = 'deg' ) ) #Colors to match SNEx1 colors = { 'Siding Spring': '#3366cc', 'Sutherland': '#dc3912', 'Teide': '#8c6239', 'Cerro Tololo': '#ff9900', 'McDonald': '#109618', 'Haleakala': '#990099' } for observing_facility in facility.get_service_classes(): observing_facility_class = facility.get_service_class(observing_facility) sites = observing_facility_class().get_observing_sites() for site, site_details in sites.items(): observer = Observer( longitude = site_details.get('longitude')*u.deg, latitude = site_details.get('latitude')*u.deg, elevation = site_details.get('elevation')*u.m ) sun_alt = observer.altaz(time_range, fixed_sun).alt obj_airmass = observer.altaz(time_range, fixed_target).secz bad_indices = np.argwhere( (obj_airmass >= airmass_limit) | (obj_airmass <= 1) | (sun_alt > -18*u.deg) #between astro twilights ) obj_airmass = [np.nan if i in bad_indices else float(x) for i, x in enumerate(obj_airmass)] label = '({facility}) {site}'.format( facility = observing_facility, site = site ) plot_data.append( go.Scatter(x=time_plot, y=obj_airmass, mode='lines', name=label, marker=dict(color=colors.get(site))) ) return plot_data
def get_24hr_airmass(target, interval, airmass_limit): plot_data = [] start = Time(datetime.datetime.utcnow()) end = Time(start.datetime + datetime.timedelta(days=1)) time_range = time_grid_from_range(time_range=[start, end], time_resolution=interval * u.minute) time_plot = time_range.datetime fixed_target = FixedTarget(name=target.name, coord=SkyCoord(target.ra, target.dec, unit='deg')) #Hack to speed calculation up by factor of ~3 sun_coords = get_sun(time_range[int(len(time_range) / 2)]) fixed_sun = FixedTarget(name='sun', coord=SkyCoord(sun_coords.ra, sun_coords.dec, unit='deg')) for observing_facility in facility.get_service_classes(): if observing_facility != 'LCO': continue observing_facility_class = facility.get_service_class( observing_facility) sites = observing_facility_class().get_observing_sites() for site, site_details in sites.items(): observer = Observer(longitude=site_details.get('longitude') * u.deg, latitude=site_details.get('latitude') * u.deg, elevation=site_details.get('elevation') * u.m) sun_alt = observer.altaz(time_range, fixed_sun).alt obj_airmass = observer.altaz(time_range, fixed_target).secz bad_indices = np.argwhere( (obj_airmass >= airmass_limit) | (obj_airmass <= 1) | (sun_alt > -18 * u.deg) #between astro twilights ) obj_airmass = [ np.nan if i in bad_indices else float(x) for i, x in enumerate(obj_airmass) ] label = '({facility}) {site}'.format(facility=observing_facility, site=site) plot_data.append( go.Scatter( x=time_plot, y=obj_airmass, mode='lines', name=label, )) return plot_data
def make_obs_table(obs_info, source_list, save=True, min_uptime=10): tab = Table.read(source_list, format="ascii.csv") targets = [ FixedTarget(coord=SkyCoord(ra=ra, dec=dec, unit=(u.hourangle, u.deg)), name=source) for source, ra, dec, _ in tab ] # Some arecibo specific settings arecibo_site = E.from_geocentric(x=2390490.0, y=-5564764.0, z=1994727.0, unit=u.meter) arecibo = Observer(location=arecibo_site, name="AO") constraints = [ AltitudeConstraint((90 - 19.7) * u.deg, (90 - 1.06) * u.deg) ] min_alt = (90 - 19.7) * u.deg max_alt = (90 - 1.06) * u.deg utc_offset = 4 * u.hour ast_to_utc_offset = TimezoneInfo(utc_offset=utc_offset) months = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ] tstarts = [] tends = [] for index, row in obs_info.iterrows(): obs_month = row['Month'] for i, month in enumerate(months): if month == obs_month: break i = i + 1 if row['End_time(AST)'] == '24:00': row['End_time(AST)'] = '23:59' tstarts.append( f"{row['Year']}-{i:02d}-{row['Start_date']} {row['Start_time(AST)']}" ) tends.append( f"{row['Year']}-{i:02d}-{row['End_date']} {row['End_time(AST)']}") ots = [] for st, et in zip(tstarts, tends): #setting up for altitude constraints tstart_obs = Time(st) + utc_offset tobs_len = (Time(et) - Time(st)).sec / (60 * 60) #hours delta_t = np.linspace(0, tobs_len, 100) * u.hour frame_obs = AltAz(obstime=tstart_obs + delta_t, location=arecibo_site) #setting up for astroplan observability table st_utc = str(Time(st).to_datetime(timezone=ast_to_utc_offset))[:-6] et_utc = str(Time(et).to_datetime(timezone=ast_to_utc_offset))[:-6] time_range = Time([st_utc, et_utc], scale='utc') print(f'Making observability table for {st}') ot = observability_table(constraints, arecibo, targets, times=time_grid_from_range( time_range, 5 * u.min)).to_pandas() ot['ever obs'] = ot['ever observable'] ot = ot.drop([ 'fraction of time observable', 'ever observable', 'always observable' ], axis=1) ot_obs = ot[ot['ever obs']] ra = [] dec = [] set_time = [] up_time = [] rise_time = [] tstart_observable = [] tend_observable = [] print(f'Processing observability table for {st}') for i, row in ot_obs.iterrows(): ra.append(targets[i].ra.deg) dec.append(targets[i].dec.deg) # manual altitude constraints target = SkyCoord(ra=targets[i].ra, dec=targets[i].dec) frame_obs_altaz = target.transform_to(frame_obs) times_observable = tstart_obs + delta_t[ (frame_obs_altaz.alt > min_alt) & (frame_obs_altaz.alt < max_alt)] tstart_observable.append(times_observable.min() - utc_offset) if Time(times_observable.max()) < Time(et_utc): tend_observable.append(times_observable.max() - utc_offset) up_time.append((Time(times_observable.max()) - Time(times_observable.min())).sec / 60) else: tend_observable.append(Time(et_utc) - utc_offset) up_time.append( (Time(et_utc) - Time(times_observable.min())).sec / 60) ot_obs['RA'] = ra ot_obs['DEC'] = dec ot_obs['uptime (min)'] = up_time ot_obs['tstart_obs (AST)'] = tstart_observable ot_obs['tend_obs (AST)'] = tend_observable ot_obs = ot_obs[ot_obs['uptime (min)'] > min_uptime] ot_obs = ot_obs.drop(['ever obs'], axis=1) ots.append(ot_obs) if save: fname = str(Time(st_utc) - utc_offset) f = open(fname.replace(' ', '_') + '.tab', 'w') f.write( f'Observations from {str(Time(st_utc) - utc_offset)} to {str(Time(et_utc) - utc_offset)}\n' ) f.write(f'Length of observations: {tobs_len:.2f}hr \n') f.write( tabulate(ot_obs, headers='keys', tablefmt='psql', showindex="never")) f.close()
obs_database = { name: dict(times=[], fluxes=[], model=[], transit=False) for name in table['spc'] } for i in range(n_years * 365): # Simulate weather losses if np.random.rand() > fraction_cloudy: time = start_time + i * u.day night_start = saintex.twilight_evening_nautical(time, which='previous') night_end = saintex.twilight_morning_nautical(time, which='next') night_duration = night_end - night_start times = time_grid_from_range((night_start, night_end), time_resolution=1.6 * u.min) obs_table = observability_table(constraints, saintex, targets, times=times) # Prevent memory from getting out of hand by clearing out cache: saintex._altaz_cache = {} mask_targets_visible_2hrs = obs_table[ 'fraction of time observable'] * night_duration > 6 * u.hr object_inds_to_observe = np.random.choice( np.argwhere(mask_targets_visible_2hrs)[:, 0], size=n_objects_per_night) target_inds_observed.update(object_inds_to_observe)
# # #observability_table = observability_table(constraints, observer, targets[2:], # time_range=time_range, # time_grid_resolution=1*u.hour) #print(observability_table) ## calculate observability of most-observable target #observability = is_observable(constraints, observer, targets[-1], # time_range=time_range, # time_grid_resolution=1*u.hr) # Create grid of times from ``start_time`` to ``end_time`` # with resolution ``time_resolution`` time_resolution = 7 * u.day time_grid = time_grid_from_range(time_range, time_resolution=time_resolution) observability_grid = np.zeros((24, len(time_grid)), dtype='bool') for targetlon in (-5, 5, 15, 25, 35, 45, 55): target = coordinates.SkyCoord(targetlon * u.deg, 0 * u.deg, frame='galactic') pb = ProgressBar(observability_grid.shape[1]) for ii, day in (enumerate(time_grid)): day_time_grid = time_grid_from_range(Time( [day, day + TimeDelta(1 * u.day)]), time_resolution=1 * u.hour) assert np.all(np.isfinite(day_time_grid.value))
longitude = -104.2455 latitude = 34.4714 elevation = 0 * u.m location = EarthLocation.from_geodetic(longitude, latitude, elevation) observer = Observer(name='Fort Sumner', location=location, pressure=0.615 * u.bar, relative_humidity=0.11, temperature=0 * u.deg_C, timezone=timezone('US/Mountain'), description="Launch") time_range = Time(["2016-09-16 03:00","2016-09-16 13:00"],scale='utc') time_grid = time_grid_from_range(time_range) clean_table = pickle.load(open('data/clean_table.data','r')) # add ratios clean_table['R19'] = clean_table['R50_19']/clean_table['R50_cal_19'] clean_table['R31'] = clean_table['R50_31']/clean_table['R50_cal_31'] clean_table['R37'] = clean_table['R50_37']/clean_table['R50_cal_37'] clean_table.sort(['F37','R37']) clean_table.reverse() clean_table = clean_table[clean_table['F37']>20] print clean_table['SOFIA_name','RA','DEC'] #targets = [FixedTarget(coord=SkyCoord(ra=334.82557*u.deg,dec=63.313065*u.deg),name='S140.5')]
prihdr['cmd'] = ('X', 'command sent to filter-wheel box') prihdr['channel'] = ('X', 'camera type (e.g. B=blue,R=red)') prihdr['F_T'] = ('X', 'filter type (e.g. N=narrow band, g=SDSS g)') prihdr['F_I'] = (0, 'index of filter') prihdr['F_B'] = (0, 'wavelength (A)') prihdr['exp'] = (0, 'Exposure time (seconds)') prihdr['ra'] = (179.755936891, 'RA of obj (deg)') prihdr['dec'] = (-0.524622205172, 'DEC of obj (deg)') prihdr['ra_hms'] = (c.ra.to_string(unit=u.hourangle, sep=':'), 'RA of obj (hourangle)') prihdr['dec_dms'] = (c.dec.to_string(unit=u.deg, sep=':'), 'DEC of obj (deg)') ################################################################ time_range = Time(["2017-09-03 20:00:00", "2017-09-04 08:00"]) #time1=Time("2016-03-04 12:04") time_grid = time_grid_from_range(time_range, time_resolution=12 * u.min) #tt=datetime.datetime(2016, 11, 07, 10, 49, 53, 239,tzinfo=pytz.timezone('Asia/Urumqi')) data = scipy.ndimage.rotate(hdu[0].data, -6, reshape=False) fig = plt.figure() plt.imshow(data, origin='lower', vmin=-0.2, vmax=0.2, cmap=plt.cm.viridis) exp = 1800 #import numpy as np path = 'data4/' #for i in xrange(1): for i in [1, 2, 3, 4, 6]: # II=np.random.randint(11) ff = [0, 1, 2, 0, 1, 1, 6, 7] II = ff[i]