def airmass_plots(KPNO=False,ING=False,MLO=False): observer_site = Observer.at_site("Kitt Peak", timezone="US/Mountain") if KPNO: print('plotting airmass curves for Kitt Peak') observing_location = EarthLocation.of_site('Kitt Peak') observer_site = Observer.at_site("Kitt Peak", timezone="US/Mountain") start_time = Time('2017-03-12 01:00:00') # UTC time, so 1:00 UTC = 6 pm AZ mountain time end_time = Time('2017-03-12 14:00:00') elif MLO: print('plotting airmass curves for MLO') observing_location = EarthLocation.of_site(u'Palomar') observer_site = Observer.at_site("Palomar", timezone="US/Pacific") # for run starting 2019-Apr-04 at MLO start_time = Time('2019-04-03 01:00:00') # need to enter UTC time, MLO UTC+6? end_time = Time('2019-04-03 14:00:00') elif ING: print('plotting airmass curves for INT') observing_location = EarthLocation.of_site(u'Roque de los Muchachos') observer_site = Observer.at_site("Roque de los Muchachos", timezone="GMT") # for run starting 2019-Feb-04 at INT start_time = Time('2019-02-04 19:00:00') # INT is on UTC end_time = Time('2019-02-05 07:00:00') #observing_time = Time('2017-05-19 07:00') # 1am UTC=6pm AZ mountain time #observing_time = Time('2018-03-12 07:00') # 1am UTC=6pm AZ mountain time #aa = AltAz(location=observing_location, obstime=observing_time) #for i in range(len(pointing_ra)): delta_t = end_time - start_time observing_time = start_time + delta_t*np.linspace(0, 1, 75) nplots = int(sum(obs_mass_flag)/8.) print(nplots) for j in range(nplots): plt.figure() legend_list = [] for i in range(8): pointing_center = coords.SkyCoord(pointing_ra[8*j+i]*u.deg, pointing_dec[8*j+i]*u.deg, frame='icrs') if i == 3: plot_airmass(pointing_center,observer_site,observing_time,brightness_shading=True) else: plot_airmass(pointing_center,observer_site,observing_time) legend_list.append('Pointing %02d'%(8*j+i+1)) plt.legend(legend_list) #plt.ylim(0.9,2.5) plt.gca().invert_yaxis() plt.subplots_adjust(bottom=.15) #plt.axvline(x=7*u.hour,ls='--',color='k') plt.axhline(y=2,ls='--',color='k') plt.savefig(outfile_prefix+'airmass-%02d.png'%(j+1))
def main(): ticid = '268301217' ra = '07:45:28.97' dec = '-52:22:59.73' t0 = 2458860.60021 * u.day # BJD_TDB period = 0.94667643 * u.day site = Observer.at_site('Cerro Tololo') start_time = Time('2020-10-24 22:00:00') end_time = Time('2020-11-06 07:00:00') # axvspan windows obs_per_night = [(Time('2020-10-{}'.format(str(d).zfill(2)) + ' 06:00:00'), Time('2020-10-{}'.format(str(d).zfill(2)) + ' 10:00:00')) for d in range(24, 32)] for d in range(1, 6): obs_per_night.append( (Time('2020-11-{}'.format(str(d).zfill(2)) + ' 06:00:00'), Time('2020-11-{}'.format(str(d).zfill(2)) + ' 10:00:00'))) plot_quadrature_windows(ra, dec, ticid, t0, period, start_time, end_time, site, obs_per_night=obs_per_night, N_points=500)
def test_docs_example(): # Test the example in astroplan/docs/tutorials/constraints.rst target_table_string = """# name ra_degrees dec_degrees Polaris 37.95456067 89.26410897 Vega 279.234734787 38.783688956 Albireo 292.68033548 27.959680072 Algol 47.042218553 40.955646675 Rigel 78.634467067 -8.201638365 Regulus 152.092962438 11.967208776""" from astroplan import Observer, FixedTarget from astropy.time import Time subaru = Observer.at_site("Subaru") time_range = Time(["2015-08-01 06:00", "2015-08-01 12:00"]) # Read in the table of targets from astropy.io import ascii target_table = ascii.read(target_table_string) # Create astroplan.FixedTarget objects for each one in the table from astropy.coordinates import SkyCoord import astropy.units as u targets = [FixedTarget(coord=SkyCoord(ra=ra*u.deg, dec=dec*u.deg), name=name) for name, ra, dec in target_table] from astroplan import Constraint, is_observable class VegaSeparationConstraint(Constraint): """ Constraint the separation from Vega """ def __init__(self, min=None, max=None): """ min : `~astropy.units.Quantity` or `None` (optional) Minimum acceptable separation between Vega and target. `None` indicates no limit. max : `~astropy.units.Quantity` or `None` (optional) Minimum acceptable separation between Vega and target. `None` indicates no limit. """ self.min = min if min else 0*u.deg self.max = max if max else 180*u.deg def compute_constraint(self, times, observer, targets): vega = SkyCoord(ra=279.23473479*u.deg, dec=38.78368896*u.deg) # Calculate separation between target and vega # Targets are automatically converted to SkyCoord objects # by __call__ before compute_constraint is called. vega_separation = vega.separation(targets) # Return an array that is True where the target is observable and # False where it is not return (self.min < vega_separation) & (vega_separation < self.max) constraints = [VegaSeparationConstraint(min=5*u.deg, max=30*u.deg)] observability = is_observable(constraints, subaru, targets, time_range=time_range) assert all(observability == [False, False, True, False, False, False])
async def test_scheduler(): # init observer and time observer = Observer.at_site('SAAO') now = Time('2019-11-21T17:10:00Z') # have some test functions functions = { 'B': ' exp(-1.22034 * (h + 3.16086))', 'V': ' exp(-1.27565 * (h + 3.48265))', 'R': ' exp(-1.39148 * (h + 3.63401))', } # set constant priorities priorities = ConstSkyflatPriorities({('B', (1, 1)): 1, ('V', (1, 1)): 2, ('R', (1, 1)): 3}) # create scheduler scheduler = Scheduler(functions, priorities, observer) await scheduler(now) # test order assert scheduler[0].filter_name == 'B' assert scheduler[1].filter_name == 'V' assert scheduler[2].filter_name == 'R' # test start/end times assert scheduler[0].start == 1160 assert pytest.approx(scheduler[0].end, 0.01) == 1200.46 assert scheduler[1].start == 1270 assert pytest.approx(scheduler[1].end, 0.01) == 1310.59 assert scheduler[2].start == 1330 assert pytest.approx(scheduler[2].end, 0.01) == 1370.59
def __init__(self): self.scheduler = scheduler.Scheduler() self.observatory = Observer.at_site( "Anglo-Australian Observatory" ) # TODO: enter LAT and LON coordinates self.ra_current = None self.dec_current = None self.number_of_tiles = self.scheduler.number_of_all_tiles( ) # total number of all the tiles in this tiling run self.number_of_tiles_observed = 0 self.unique_targets = set() self.repeats = Dictlist() self.total_number_cumulative_unique = 0 # EXcluding repeated observations self.total_number_cumulative = 0 # INcluding repeated observations self.number_of_tiles_observed = 0 self.number_of_all_tiles = scheduler.number_of_all_tiles() self.dt = TimeDelta(0, format='sec') self.time_with_no_observing = TimeDelta(0, format='sec') # print output self.f = open(params_simulator.params['simulator_statistics_output'], 'wb') self.f.write( '# time; tile_id; Ntargets_in_this_tile; Nunique_targets_in_this_tile; Ntotal_number_cumulative_unique; Ntotal_number_cumulative; priority; weight; mag_max; json_filename \n' ) # Print calibration files (times) self.fc = open( params_simulator.params['simulator_statistics_output_calibration'], 'wb')
def __init__(self, coordinates, observatory='Mt Graham', night=None, timezone='UTC', ax=None, timedelta=None): if not isinstance(coordinates, SkyCoord): self.coord = SkyCoord(coordinates, unit=(u.hourangle, u.deg)) else: self.coord = coordinates try: self.observer = Observer.at_site(observatory, timezone=timezone) except USE: print EarthLocation.get_site_names() raise if not night: self.time = Time.now() else: self.time = Time(night) if timedelta: self.time = timedelta self.ax = ax self._make_figure()
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 test_caches_shapes(): times = Time([2457884.43350526, 2457884.5029497, 2457884.57239415], format='jd') m31 = SkyCoord(10.6847929*u.deg, 41.269065*u.deg) ippeg = SkyCoord(350.785625*u.deg, 18.416472*u.deg) htcas = SkyCoord(17.5566667*u.deg, 60.0752778*u.deg) targets = get_skycoord([m31, ippeg, htcas]) observer = Observer.at_site('lapalma') ac = AltitudeConstraint(min=30*u.deg) assert ac(observer, targets, times, grid_times_targets=True).shape == (3, 3) assert ac(observer, targets, times, grid_times_targets=False).shape == (3,)
def getObservingTimeStartAndEnd(): # midnight = Time(date+' 00:00:00') - utcoffset obs = Observer.at_site( observatoryName) #, timezone='Eastern Standard Time') observationStartTime = obs.twilight_evening_astronomical( midnight) #Time('2019-9-5 19:10:00') - utcoffset observationEndTime = obs.twilight_morning_astronomical( midnight) #Time('2019-9-6 4:55:00') - utcoffset observationStartTime.format = 'iso' observationEndTime.format = 'iso' return [observationStartTime + utcoffset, observationEndTime + utcoffset]
def get_kp_twilights(tt, dd): # example: '2020-01-01 12:00:00' kp = Observer.at_site("Kitt Peak", timezone="MST") ds = str(dd[0]) + '-' + str(dd[1]) + '-' + str(dd[2]) ts = str(tt[0]) + ':' + str(tt[1]) + ':' + str(tt[2]) t = Time(ds + ' ' + ts) eve = kp.twilight_evening_astronomical(t, which='next').datetime mor = kp.twilight_morning_astronomical(t, which='next').datetime return eve, mor
def test_regression_shapes(constraint): times = Time(["2015-08-28 03:30", "2015-09-05 10:30", "2015-09-15 18:35"]) targets = get_skycoord([FixedTarget(SkyCoord(350.7*u.deg, 18.4*u.deg)), FixedTarget(SkyCoord(260.7*u.deg, 22.4*u.deg))]) lapalma = Observer.at_site('lapalma') assert constraint(lapalma, targets[:, np.newaxis], times).shape == (2, 3) assert constraint(lapalma, targets[0], times).shape == (3,) assert np.array(constraint(lapalma, targets[0], times[0])).shape == () assert np.array(constraint(lapalma, targets, times[0])).shape == (2,) with pytest.raises(ValueError): constraint(lapalma, targets, times)
def test_regression_shapes(constraint): times = Time(["2015-08-28 03:30", "2015-09-05 10:30", "2015-09-15 18:35"]) targets = get_skycoord([FixedTarget(SkyCoord(350.7*u.deg, 18.4*u.deg)), FixedTarget(SkyCoord(260.7*u.deg, 22.4*u.deg))]) lapalma = Observer.at_site('lapalma') assert constraint(lapalma, targets[:, np.newaxis], times).shape == (2, 3) assert constraint(lapalma, targets[0], times).shape == (3,) assert constraint(lapalma, targets[0], times[0]).shape == () assert constraint(lapalma, targets, times[0]).shape == (2,) with pytest.raises(ValueError): constraint(lapalma, targets, times)
def get_sunset_mjd(mjd, site='CTIO'): ''' Returns an MJD of sunset prior to input mjd as float - not a Time Object ''' if ASTROPLAN_EXISTS: ctio = Observer.at_site(site) detect_time = Time(mjd, format='mjd') sun_set = ctio.sun_set_time(detect_time, which='previous').mjd NITE = sun_set else: NITE = mjd return NITE
def test_regression_shapes(constraint): times = Time(["2015-08-28 03:30", "2015-09-05 10:30", "2015-09-15 18:35"]) targets = [ FixedTarget(SkyCoord(350.7 * u.deg, 18.4 * u.deg)), FixedTarget(SkyCoord(260.7 * u.deg, 22.4 * u.deg)) ] lapalma = Observer.at_site('lapalma') assert constraint(lapalma, targets, times).shape == (2, 3) assert constraint(lapalma, [targets[0]], times).shape == (1, 3) assert constraint(lapalma, [targets[0]], times[0]).shape == (1, 1) assert constraint(lapalma, targets, times[0]).shape == (2, 1)
def minimal_example(): apo = Observer.at_site('APO', timezone='US/Mountain') target = FixedTarget.from_name("HD 209458") primary_eclipse_time = Time(2452826.628514, format='jd') orbital_period = 3.52474859 * u.day eclipse_duration = 0.1277 * u.day hd209458 = EclipsingSystem(primary_eclipse_time=primary_eclipse_time, orbital_period=orbital_period, duration=eclipse_duration, name='HD 209458 b') n_transits = 100 # This is the roughly number of transits per year obs_time = Time('2017-01-01 12:00') midtransit_times = hd209458.next_primary_eclipse_time( obs_time, n_eclipses=n_transits) import astropy.units as u min_local_time = dt.time(18, 0) # 18:00 local time at APO (7pm) max_local_time = dt.time(8, 0) # 08:00 local time at APO (5am) constraints = [ AtNightConstraint.twilight_civil(), AltitudeConstraint(min=30 * u.deg), LocalTimeConstraint(min=min_local_time, max=max_local_time) ] # just at midtime b = is_event_observable(constraints, apo, target, times=midtransit_times) # completely observable transits observing_time = Time('2016-01-01 00:00') ing_egr = hd209458.next_primary_ingress_egress_time(observing_time, n_eclipses=n_transits) ibe = is_event_observable(constraints, apo, target, times_ingress_egress=ing_egr) oot_duration = 30 * u.minute oot_ing_egr = np.concatenate( (np.array(ing_egr[:, 0] - oot_duration)[:, None], np.array(ing_egr[:, 1] + oot_duration)[:, None]), axis=1) oibeo = is_event_observable(constraints, apo, target, times_ingress_egress=oot_ing_egr)
def test_timetable(): from astropy.time import Time from astroplan import Observer start = Time('2018-07-01 20:00:00') end = Time('2018-07-02 20:00:00') utc_to_local = -4. * u.h site = Observer.at_site('gemini_south') assert isinstance(time_table(site, start, utc_to_local, end=end), Table) print('Test successful!') return
def query_up(self, time=None): if time is None: time = datetime.datetime.now(tz=pytz.timezone("US/Arizona")) bigelow = Observer.at_site("mtbigelow", timezone="US/Arizona") st = bigelow.local_sidereal_time(time).deg lower_ra = self.__getattr__('ra_deg') > (st - 15 * 5) upper_ra = (st + 15 * 5) > self.__getattr__('ra_deg') lower_dec = self.__getattr__('dec_deg') > -30.0 upper_dec = 60.0 > self.__getattr__('dec_deg') qry = self.query().filter(lower_ra).filter(upper_ra).filter( lower_dec).filter(upper_dec) return qry
def __init__(self, time_range, targets, site='cfht', constraints=None, supp_cols=None): # Get infos from the MasterFile if isinstance(targets, list): info = load_from_masterfile(*targets) supp_cols = supp_cols or [ 'pl_orbper', 'st_j', 'st_h', 'ra', 'dec', 'pl_eqt', 'st_teff' ] else: info = targets.copy() if supp_cols is None: supp_cols = list(info.keys()) supp_cols.remove('pl_name') # Default constraint if constraints is None: constraints = [ AtNightConstraint.twilight_nautical(), AirmassConstraint(max=2.5) ] # Define time constraint and append it t1, t2 = Time(time_range) constraints.append(TimeConstraint(t1, t2)) # Convert to List_of_constraints (useful to print and save) constraints_list = List_of_constraints(constraints) # Save infos self.info = info self.constraints = constraints_list self.meta = { 'Time_limits': [t1, t2], 'Target_list': info['pl_name'].tolist(), 'Site': site, **constraints_list.show() } self.supp_cols = supp_cols self.info_cols = ['pl_name'] + supp_cols self.obs = Observer.at_site(site) # self.n_eclipses = n_eclipses # Resolve targets self.targets = [self.resolve_target(i) for i in range(len(targets))]
def getsite(site_name, daylightsavings): """ Initialize '~astroplan.Observer' for Cerro Pachon or Mauna Kea. Parameters ---------- site_name : string Observatory site name. Allowed locations... - 'gemini_north' or 'MK' (Mauna Kea) - 'gemini_south' or 'CP' (Cerro Pachon). daylightsavings : boolean Toggle daylight savings tot_time (does not apply to Gemini North) Returns ------- site : '~astroplan.Observer' Observatory site location object. timezone_name : string Pytz timezone name for observatory site utc_to_local : '~astropy.units' hours Time difference between utc and local tot_time in hours. """ if np.logical_or(site_name == 'gemini_south', site_name == 'CP'): site_name = 'gemini_south' timezone_name = 'Chile/Continental' if daylightsavings: utc_to_local = -3.*u.h else: utc_to_local = -4.*u.h elif np.logical_or(site_name == 'gemini_north', site_name == 'MK'): site_name = 'gemini_north' timezone_name = 'US/Hawaii' utc_to_local = -10.*u.h else: print('Input error: Could not determine observer location and timezone. ' 'Allowed inputs are \'gemini_south\', \'CP\'(Cerro Pachon), \'gemini_north\', and \'MK\'(Mauna Kea).') raise ValueError # Create Observer object for observatory site # Note: can add timezone=timezone_name later # if desired (useful if pytz objects used) site = Observer.at_site(site_name) return site, timezone_name, utc_to_local
def test_regression_airmass_141(): subaru = Observer.at_site("Subaru") time = Time('2001-1-1 12:00') coord = SkyCoord(ra=16 * u.hour, dec=20 * u.deg) assert subaru.altaz(time, coord).alt < 0 * u.deg # ok, it's below the horizon, so it *definitely* should fail an airmass # constraint of being above 2. So both of these should give False: consmax = AirmassConstraint(2) consminmax = AirmassConstraint(2, 1) assert not consminmax(subaru, [coord], [time]).ravel()[0] # prior to 141 the above works, but the below FAILS assert not consmax(subaru, [coord], [time]).ravel()[0]
def test_regression_airmass_141(): subaru = Observer.at_site("Subaru") time = Time("2001-1-1 12:00") coord = SkyCoord(ra=16 * u.hour, dec=20 * u.deg) assert subaru.altaz(time, coord).alt < 0 * u.deg # ok, it's below the horizon, so it *definitely* should fail an airmass # constraint of being above 2. So both of these should give False: consmax = AirmassConstraint(2) consminmax = AirmassConstraint(2, 1) assert not consminmax(subaru, [coord], [time]).ravel()[0] # prior to 141 the above works, but the below FAILS assert not consmax(subaru, [coord], [time]).ravel()[0]
def make_airmass_chart(name="WASP 4"): target = FixedTarget.from_name(name) observer = Observer.at_site('keck') constraints = [ AltitudeConstraint(min=20 * u.deg, max=85 * u.deg), AtNightConstraint.twilight_civil() ] best_months = months_observable(constraints, observer, [target]) # computed observability on "best_months" grid of 0.5 hr print('for {}, got best-months on 0.5 hour grid:'.format(name)) print(best_months) print('where 1 = Jan, 2 = Feb, etc.')
def telescope_can_observe(ra, dec, date, tel): time = Time(date) sc = SkyCoord(ra, dec, unit=u.deg) tel = Observer.at_site(tel) night_start = tel.twilight_evening_astronomical(time, which="previous") night_end = tel.twilight_morning_astronomical(time, which="previous") can_obs = False for jd in np.arange(night_start.mjd, night_end.mjd, 0.02): time = Time(jd, format="mjd") target_up = tel.target_is_up(time, sc) if target_up: can_obs = True break return (can_obs)
def get_rot_rates(observatory='Subaru', multiplier=250): site = EarthLocation.of_site(observatory) unixtimes = time.Time(val=times, format='unix') coords = SkyCoord.from_name('* kap And') apo = Observer.at_site(observatory) altaz = apo.altaz(unixtimes, coords) # TODO each dither potion will have its own altaz rather than the stars. Implement that Earthrate = 2 * np.pi / u.sday.to(u.second) obs_const = Earthrate * np.cos(site.geodetic.lat.rad) rot_rate = obs_const * np.cos(altaz.az.radian) / np.cos(altaz.alt.radian) # rot_rate = [0]*len(times)#obs_const * np.cos(altaz.az.radian) / np.cos(altaz.alt.radian) if multiplier: rot_rate = rot_rate * multiplier return rot_rate
def test_event_observable(): epoch = Time(2452826.628514, format='jd') period = 3.52474859 * u.day duration = 0.1277 * u.day hd209458 = EclipsingSystem(primary_eclipse_time=epoch, orbital_period=period, duration=duration, name='HD 209458 b') observing_time = Time('2017-09-15 10:20') apo = Observer.at_site('APO') target = FixedTarget.from_name("HD 209458") n_transits = 100 # This is the roughly number of transits per year ing_egr = hd209458.next_primary_ingress_egress_time(observing_time, n_eclipses=n_transits) constraints = [AltitudeConstraint(min=0 * u.deg), AtNightConstraint()] observable = is_event_observable(constraints, apo, target, times_ingress_egress=ing_egr) # This answer was validated against the Czech Exoplanet Transit Database # transit prediction service, at: # http://var2.astro.cz/ETD/predict_detail.php?delka=254.1797222222222&submit=submit&sirka=32.780277777777776&STARNAME=HD209458&PLANET=b # There is some disagreement, as the ETD considers some transits which begin # before sunset or after sunrise to be observable. cetd_answer = [[ False, False, False, True, False, True, False, True, False, True, False, True, False, False, False, False, False, False, False, False, False, False, True, False, True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, True, False, True, False, False, False, False, False, False, False, False, False, False, False, False, True, False, True, False, True, False, True, False, True, False, True, False, False ]] assert np.all(observable == np.array(cetd_answer))
def main(): site = Observer.at_site('Las Campanas Observatory') ra = "07:21:28.72" dec = "-45:34:03.85" name = "TIC_59859387.01" start_time = Time('2020-02-05 23:30:00') end_time = Time('2020-02-06 09:30:00') ########################################## range_time = end_time - start_time observe_time = start_time + range_time*np.linspace(0,1,100) if (isinstance(ra, u.quantity.Quantity) and isinstance(dec, u.quantity.Quantity) ): target_coord = SkyCoord(ra=ra, dec=dec) elif (isinstance(ra, str) and isinstance(dec, str) ): target_coord = SkyCoord(ra=ra, dec=dec, unit=(u.hourangle, u.deg)) else: raise NotImplementedError target = FixedTarget(coord=target_coord, name=name) outdir = "../results/{}".format(name) if not os.path.exists(outdir): os.mkdir(outdir) outname = '{}_{}_start{}_airmass.png'.format( name, site.name.replace(' ','_'), repr(start_time.value) ) outpath = os.path.join(outdir,outname) plot_airmass(target, site, observe_time, style_sheet=dark_style_sheet, altitude_yaxis=True) plt.tight_layout() plt.savefig(outpath, dpi=250, bbox_inches='tight') print('made {}'.format(outpath))
def test_eclipses(): subaru = Observer.at_site("Subaru") epoch = Time('2016-01-01') period = 3 * u.day duration = 1 * u.hour eclipsing_system = EclipsingSystem(primary_eclipse_time=epoch, orbital_period=period, duration=duration, name='test system') pec = PrimaryEclipseConstraint(eclipsing_system) times = Time(['2016-01-01 00:00', '2016-01-01 03:00', '2016-01-02 12:00']) assert np.all(np.array([True, False, False]) == pec(subaru, None, times)) sec = SecondaryEclipseConstraint(eclipsing_system) times = Time(['2016-01-01 00:00', '2016-01-01 03:00', '2016-01-02 12:00']) assert np.all(np.array([False, False, True]) == sec(subaru, None, times)) pc = PhaseConstraint(eclipsing_system, min=0.2, max=0.5) times = Time(['2016-01-01 00:00', '2016-01-02 12:00', '2016-01-02 14:00']) assert np.all(np.array([False, True, False]) == pc(subaru, None, times))
def __init__(self): """ Parameters ---------- ra_current, dec_current: float, degrees Current position of telescope. This position is needed to determine slew time to the next target. This data comes directly from Jeeves. For the start of the night it is best to start at meridian (telescope is not parked there). Later on take current telescope position into account. Data needed from Jeeves: ra_current, dec_current weather """ self.tiles = TILES # TODO: do I now have 2 copies of TILES? self.determine_internal_tile_id_and_priorities() self.observed_tiles = manage_list_of_observed_tiles.load_internal_list_of_observed_tile_ids() self.group_tiles_per_magnitude_range() # Need this for magnitude range weight determination self.limiting_magnitude=None self.observatory = Observer.at_site("Anglo-Australian Observatory") # TODO: enter LAT and LON coordinates self.location = EarthLocation(lat=params.params['LAT']*u.deg, lon=params.params['LON']*u.deg, height=params.params['EL']*u.m)
def set_obs_time(self, coords, site, date): """Choose times to begin and end observing the PIC between its rise and set. :param coords: coordinates of the PIC object from SkyCoord :param site: name of the site the unit is at, from astroplan :param date: the date of the observation :return: randomized start and end time of observation """ loc = Observer.at_site(site) # Use astroplan to get rise and set of star, and get reasonable random # obs_time and duration rise = loc.target_rise_time(date, coords, which='next') rise_time = datetime.strptime(rise.isot, "%Y-%m-%dT%H:%M:%S.%f") set = loc.target_set_time(rise_time, coords, which='next') set_time = datetime.strptime(set.isot, "%Y-%m-%dT%H:%M:%S.%f") start_time = self.random_time(rise_time, set_time) seq_duration = self.random_duration(start_time, set_time) end_time = start_time + seq_duration return start_time, end_time
def read_transits(file, site='Keck', frac=1.0): """ read transits from exoplanet archive transit planner CSV file site options from astroplan: e.g. KPNO, Keck """ data = Table.read(file,format='ascii') startimes = data['targetobsstartcalendar'] endtimes = data['targetobsendcalendar'] midtimes = data['midpointcalendar'] duration = data['transitduration'] fracs = data['fractionobservable'] full_transits = np.where(fracs>=frac)[0] target = FixedTarget.from_name(planet.strip('b')) obs = Observer.at_site(site) return startimes[full_transits], endtimes[full_transits], midtimes[full_transits], duration[full_transits], target, obs
def get_observability_fraction(name="WASP 4", site='keck', ra=None, dec=None, start_time=Time('2019-09-13 20:00:00'), end_time=Time('2020-07-31 20:00:00')): if isinstance(name,str) and ra is None and dec is None: target = FixedTarget.from_name(name) elif isinstance(ra,float) and isinstance(dec,float): target_coord = SkyCoord(ra=ra*u.deg, dec=dec*u.deg) target = FixedTarget(coord=target_coord, name=name) else: raise NotImplementedError('failed to make target') observer = Observer.at_site(site) constraints = [AltitudeConstraint(min=20*u.deg, max=85*u.deg), AirmassConstraint(3), AtNightConstraint.twilight_civil()] # over every day between start and end time, check if the observing # constraints are meetable. days = Time( np.arange(start_time.decimalyear, end_time.decimalyear, 1/(365.25)), format='decimalyear' ) frac, ever_observable = [], [] for day in days: table = observability_table(constraints, observer, [target], time_range=day) frac.append(float(table['fraction of time observable'])) ever_observable.append(bool(table['ever observable'])) ever_observable = np.array(ever_observable) frac = np.array(frac) return frac, ever_observable, days
def test_event_observable(): epoch = Time(2452826.628514, format='jd') period = 3.52474859 * u.day duration = 0.1277 * u.day hd209458 = EclipsingSystem(primary_eclipse_time=epoch, orbital_period=period, duration=duration, name='HD 209458 b') observing_time = Time('2017-09-15 10:20') apo = Observer.at_site('APO') target = FixedTarget.from_name("HD 209458") n_transits = 100 # This is the roughly number of transits per year ing_egr = hd209458.next_primary_ingress_egress_time(observing_time, n_eclipses=n_transits) constraints = [AltitudeConstraint(min=0*u.deg), AtNightConstraint()] observable = is_event_observable(constraints, apo, target, times_ingress_egress=ing_egr) # This answer was validated against the Czech Exoplanet Transit Database # transit prediction service, at: # http://var2.astro.cz/ETD/predict_detail.php?delka=254.1797222222222&submit=submit&sirka=32.780277777777776&STARNAME=HD209458&PLANET=b # There is some disagreement, as the ETD considers some transits which begin # before sunset or after sunrise to be observable. cetd_answer = [[False, False, False, True, False, True, False, True, False, True, False, True, False, False, False, False, False, False, False, False, False, False, True, False, True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, True, False, True, False, False, False, False, False, False, False, False, False, False, False, False, True, False, True, False, True, False, True, False, True, False, True, False, False]] assert np.all(observable == np.array(cetd_answer))
def create_real_times(tmin,tmax,ndata=50,air_mass_limit=1.5,tformat='mjd',star='K2-100',observatory='lapalma'): times = [] #Create a observatory instance with astroplan observatory = Observer.at_site(observatory) #Create star object from astroplan, the name has to be a valid simbad name for the target star = FixedTarget.from_name(star) while len(times) < ndata: #Draw random time between tmin and tmax drt = np.random.uniform(tmin,tmax) #Get the time object from astropy.time time = Time(drt,format=tformat) #Compute the air_mass that the target has at time t air_mass = observatory.altaz(time,star).secz #If the target is observable at time drt and the air_mass < air_mass_limit then #We accept the dummy random time if observatory.target_is_up(time,star) and air_mass < air_mass_limit: times.append(drt) #Sort thet times times = sorted(times) #Return a numpy array with all the times return np.array(times)
f.writelines(lines) print('wrote {}'.format(outpath)) if __name__ == "__main__": # will change these a lot (TODO: when in bulk -- write argparse interface) ########################################## #HIRES #site = Observer.at_site('W. M. Keck Observatory') #NEID #site = Observer.at_site('Kitt Peak National Observatory') #HARPS-N #site = Observer.at_site('lapalma') #Las Campanas site = Observer.at_site('Las Campanas Observatory') ra = "19:05:30.24" dec = "-41:26:15.49" name = "TOI_1130.02" t_mid_0 = 2458658.73805 # BJD_TDB period = 4.06719 * u.day duration = 1.783 * u.hour # ra = "19:05:30.24" # dec = "-41:26:15.49" # name = "TOI_1130.01" # t_mid_0 = 2458657.89786 # BJD_TDB # period = 8.3504*u.day # duration = 1.814*u.hour
from PyQt5 import QtGui, QtCore, QtWidgets from telescope import Telescope from allsky import AllSky import gui # parse configuration file config = ConfigObj("config.ini") location = config["LOCATION"] objects = config["OBJECTS"] # set new Observer object from config file obsLocation = EarthLocation(location["LONGITUDE"], location["LATITUDE"], float(location["ELEVATION"])) add_site(location["SITE_NAME"], obsLocation) # add objects to a dictionary of `astroplan.FixedTarget`s fixed_targets = {} for key in objects: coordinates = SkyCoord(objects[key]["RA"], objects[key]["DEC"]) fixed_targets[key] = FixedTarget(name=key, coord=coordinates) skymap = AllSky(objects=fixed_targets) telescope = Telescope(Observer.at_site(location["SITE_NAME"])) gui.run(telescope, skymap) #fig = skymap.draw(telescope.Observer) #fig.savefig("test.png")
def main(): ##------------------------------------------------------------------------- ## Parse Command Line Arguments ##------------------------------------------------------------------------- ## create a parser object for understanding command-line arguments parser = argparse.ArgumentParser( description="Program description.") ## add flags ## add arguments parser.add_argument("-y", "--year", type=int, dest="year", default=-1, help="The calendar year to analyze") parser.add_argument("-s", "--site", type=str, dest="site", default='Keck Observatory', help="Site name to use") parser.add_argument("-z", "--timezone", type=str, dest="timezone", default='US/Hawaii', help='pytz timezone name') parser.add_argument("-d", "--dark_time", type=float, dest="dark_time", default=2, help='Minimum dark time required (hours)') parser.add_argument("-w", "--wait_time", type=float, dest="wait_time", default=2.5, help='Maximum time after dusk to wait for moon set (hours)') args = parser.parse_args() if args.year == -1: args.year = dt.now().year ##------------------------------------------------------------------------- ## ##------------------------------------------------------------------------- loc = EarthLocation.of_site(args.site) obs = Observer.at_site(args.site) utc = pytz.timezone('UTC') localtz = pytz.timezone(args.timezone) # 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')
def test_docs_example(): # Test the example in astroplan/docs/tutorials/constraints.rst target_table_string = """# name ra_degrees dec_degrees Polaris 37.95456067 89.26410897 Vega 279.234734787 38.783688956 Albireo 292.68033548 27.959680072 Algol 47.042218553 40.955646675 Rigel 78.634467067 -8.201638365 Regulus 152.092962438 11.967208776""" from astroplan import Observer, FixedTarget from astropy.time import Time subaru = Observer.at_site("Subaru") time_range = Time(["2015-08-01 06:00", "2015-08-01 12:00"]) # Read in the table of targets from astropy.io import ascii target_table = ascii.read(target_table_string) # Create astroplan.FixedTarget objects for each one in the table from astropy.coordinates import SkyCoord import astropy.units as u targets = [FixedTarget(coord=SkyCoord(ra=ra * u.deg, dec=dec * u.deg), name=name) for name, ra, dec in target_table] from astroplan import Constraint, is_observable from astropy.coordinates import Angle class VegaSeparationConstraint(Constraint): """ Constraint the separation from Vega """ def __init__(self, min=None, max=None): """ min : `~astropy.units.Quantity` or `None` (optional) Minimum acceptable separation between Vega and target. `None` indicates no limit. max : `~astropy.units.Quantity` or `None` (optional) Minimum acceptable separation between Vega and target. `None` indicates no limit. """ self.min = min self.max = max def compute_constraint(self, times, observer, targets): # Vega's coordinate must be non-scalar for the dimensions # to work out properly when combined with other constraints which # test multiple times vega = SkyCoord(ra=[279.23473479] * u.deg, dec=[38.78368896] * u.deg) # Calculate separation between target and vega vega_separation = Angle([vega.separation(target.coord) for target in targets]) # If a maximum is specified but no minimum if self.min is None and self.max is not None: mask = vega_separation < self.max # If a minimum is specified but no maximum elif self.max is None and self.min is not None: mask = self.min < vega_separation # If both a minimum and a maximum are specified elif self.min is not None and self.max is not None: mask = (self.min < vega_separation) & (vega_separation < self.max) # Otherwise, raise an error else: raise ValueError("No max and/or min specified in " "VegaSeparationConstraint.") # Return an array that is True where the target is observable and # False where it is not return mask constraints = [VegaSeparationConstraint(min=5 * u.deg, max=30 * u.deg)] observability = is_observable(constraints, subaru, targets, time_range=time_range) assert all(observability == [False, False, True, False, False, False])