def resolve_target(self, itar): info = self.info[itar] # First simply try to resolve with the name and return try: target = FixedTarget.from_name(info['pl_name']) return target except NameResolveError as e: print(e) pass # If failed, try to change the name try: try_name = ' '.join(info['pl_name'].split(' ')[:-2]) print("Trying with {}".format(try_name)) target = FixedTarget.from_name(try_name) # Finally, try with ra and dec except NameResolveError as e: print(e) print('Searching with RA and dec') ra = info['ra'].quantity dec = info['dec'].quantity coord = SkyCoord(ra=ra, dec=dec) target = FixedTarget(coord=coord, name=info['pl_name']) return target
def __init__(self, targets, tzinfo='Australia/Sydney', portal_htmls=[]): ### target and calibrators if not isinstance(targets, Sequence): targets = [targets] self.targets = targets self.calibrator = [FixedTarget(name='1934-638', coord=SkyCoord('19h39m25.026s -63d42m45.63s')), FixedTarget(name='0823-500', coord=SkyCoord('08h25m26.869s -50d10m38.49s'))] ### observer ATCA_loc = (149.5501388*u.deg,-30.3128846*u.deg,237*u.m) location = EarthLocation.from_geodetic(*ATCA_loc) self.observer = Observer(name='ATCA', location=location, timezone=timezone('Australia/Sydney')) time_now = datetime.now(timezone(tzinfo)) self.utcoffset = time_now.utcoffset() self.tzinfo = tzinfo if len(portal_htmls) == 0: self.portal_tz = None self.portal_sched = None else: atca_scheds = ATCA_sched(portal_htmls) self.portal_tz = atca_scheds.timezone self.portal_sched = atca_scheds.schedules ### portal utcoffset portal_now = datetime.now(timezone(self.portal_tz)) self.portal_utcoffset = portal_now.utcoffset()
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 __init__(self, name, star_Teff, star_jmag, Coordinates=None): """ Initialize Eclipse instance from Nasa query_planet object """ self.name = name self.star_Teff = star_Teff self.star_jmag = star_jmag self.target_observable = [] try: self.Coordinates = FixedTarget.from_name(self.name) except Exception: self.Coordinates = FixedTarget(Coordinates, name=self.name)
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_months_observable(): obs = Observer(latitude=0 * u.deg, longitude=0 * u.deg, elevation=0 * u.m) coords = [ SkyCoord(ra=0 * u.hourangle, dec=0 * u.deg), SkyCoord(ra=6 * u.hourangle, dec=0 * u.deg), SkyCoord(ra=12 * u.hourangle, dec=0 * u.deg), SkyCoord(ra=18 * u.hourangle, dec=0 * u.deg) ] targets = [FixedTarget(coord=coord) for coord in coords] constraints = [ AltitudeConstraint(min=80 * u.deg), AtNightConstraint.twilight_astronomical() ] time_range = Time(['2014-01-01', '2014-12-31']) months = months_observable(constraints, obs, targets, time_range) should_be = [ set({7, 8, 9, 10, 11, 12}), set({1, 2, 3, 10, 11, 12}), set({1, 2, 3, 4, 5, 6}), set({4, 5, 6, 7, 8, 9}) ] assert months == should_be
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])
def test_station_functions(): """Tests the Station functions. """ sefds = {'18': 100, '6': 40, '0.1': 200} a_station = stations.Station('name', 'Nm', 'VLBI', coord.EarthLocation(3839348.973*u.m, 430403.51*u.m, 5057990.099*u.m), sefds, 20) assert isinstance(a_station.name, str) assert isinstance(a_station.fullname, str) assert a_station.fullname == a_station.name assert a_station.network == 'VLBI' assert a_station.all_networks == a_station.network assert isinstance(a_station.country, str) assert isinstance(a_station.diameter, str) assert isinstance(a_station.real_time, bool) assert isinstance(a_station.location, coord.EarthLocation) assert a_station.location == coord.EarthLocation(3839348.973*u.m, 430403.51*u.m, 5057990.099*u.m) assert list(a_station.bands) == ['18', '6', '0.1'] assert isinstance(a_station.sefds, dict) assert a_station.sefds == sefds assert a_station.has_band('18') assert not a_station.has_band('45') assert a_station.sefd('18') == 100 with pytest.raises(KeyError): a_station.sefd('45') times1 = Time('2020-03-21 1:00') + np.arange(0, 4*60, 10)*u.min times2 = Time('2020-03-21 3:00') + np.arange(0, 4*60, 10)*u.min src1 = FixedTarget(coord=coord.SkyCoord('0h0m0s 30d0m0s'), name='testSrc') # a_station.elevation(times1, src1) # Should have elevation ranging -5 to 16.8 deg. # a_station.elevation(times1, src1) # Should have elevation ranging 3.7 to 34 deg. assert len(a_station.is_visible(times1, src1)[0]) == 0 assert len(a_station.is_visible(times2, src1)[0]) == 10 assert len(a_station.elevation(times2, src1)) == len(times1) assert np.equal(a_station.elevation(times2, src1).value, a_station.altaz(times2, src1).alt.value)[0]
def __init__(self, coord, name=None, survey=None, radius=600, grid=False, ax=None, log=False, reticle=True, style_kwargs=None): self.coord = coord self.name = name self.survey = survey self.radius = radius self.target = FixedTarget(coord, name=name) self.grid = grid self.log = log self.reticle = reticle self.style_kwargs = style_kwargs self.hdu = None self.setstretch = None # set ax to false to suppress if ax != False: self._make_figure(ax=ax)
def culmination_time_utc_astroplan(source_name, date, print_or_not): """ Calculates culmination time in UTC with astroplan library """ # Coordinates of UTR-2 radio telescope longitude = '36d56m27.560s' latitude = '+49d38m10.310s' elevation = 156 * u.m observatory = 'UTR-2, Ukraine' utr2_location = EarthLocation.from_geodetic(longitude, latitude, elevation) if print_or_not == 1: print('\n Observatory:', observatory, '\n') print(' Coordinates: \n * Longitude: ', str(utr2_location.lon).replace("d", "\u00b0 ").replace("m", "\' ").replace("s", "\'\' "), ' \n * Latitude: ' + str(utr2_location.lat).replace("d", "\u00b0 ").replace("m", "\' ").replace("s", "\'\' ") + '\n') print(' Source:', source_name, '\n') observer = Observer(location=utr2_location, name='Volokhiv Yar', timezone='UTC') alt, az = catalogue_sources(source_name) coordinates = SkyCoord(alt, az, frame='icrs') target = FixedTarget(coord=coordinates, name="target") date_of_obs = Time(date, scale='utc') culmination = observer.target_meridian_transit_time(date_of_obs, target, which='next') culm_time = culmination.to_datetime().time() culm_time = date + ' ' + str(culm_time)[0:8] if print_or_not == 1: print(' Culmination time:', culm_time, ' UTC \n') return culm_time
def run_months(observers, nameList, args): targets = [FixedTarget(coord=lookuptarget(name),name=name) for name in nameList] targetLabelList, ylabelsize = makeTargetLabels(nameList,args) constraints = [ AltitudeConstraint(min=args.minAlt*u.deg), AtNightConstraint.twilight_astronomical(), ] outfn = args.outFileNameBase+"_monthly.pdf" with PdfPages(outfn) as pdf: for observer in observers: observability_months_table = months_observable(constraints,observer,targets,time_grid_resolution=1*u.hour) observability_months_grid = numpy.zeros((len(targets),12)) for i, observable in enumerate(observability_months_table): for jMonth in range(1,13): observability_months_grid[i,jMonth-1] = jMonth in observable observable_targets = targets observable_target_labels = targetLabelList ever_observability_months_grid = observability_months_grid if args.onlyEverObservable: target_is_observable = numpy.zeros(len(targets)) for iMonth in range(observability_months_grid.shape[1]): target_is_observable += observability_months_grid[:,iMonth] target_is_observable = target_is_observable > 0. # change to boolean numpy array observable_targets = [x for x, o in zip(targets,target_is_observable) if o] observable_target_labels = [x for x, o in zip(targetLabelList,target_is_observable) if o] ever_observability_months_grid = observability_months_grid[target_is_observable,:] fig, ax = mpl.subplots( figsize=(8.5,11), gridspec_kw={ "top":0.92, "bottom":0.03, "left":0.13, "right":0.98, }, tight_layout=False,constrained_layout=False ) extent = [-0.5, -0.5+12, -0.5, len(observable_targets)-0.5] ax.imshow(ever_observability_months_grid, extent=extent, origin="lower", aspect="auto", cmap=mpl.get_cmap("Greens")) ax.xaxis.tick_top() ax.invert_yaxis() ax.set_yticks(range(0,len(observable_targets))) ax.set_yticklabels(observable_target_labels, fontsize=ylabelsize) ax.set_xticks(range(12)) ax.set_xticklabels(["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]) ax.set_xticks(numpy.arange(extent[0], extent[1]), minor=True) ax.set_yticks(numpy.arange(extent[2], extent[3]), minor=True) ax.grid(which="minor",color="black",ls="-", linewidth=1) ax.tick_params(axis='y', which='minor', left=False, right=False) ax.tick_params(axis='x', which='minor', bottom=False, top=False) fig.suptitle(f"Monthly Observability at {observer.name}") fig.text(1.0,0.0,"Constraints: Astronomical Twilight, Altitude $\geq {:.0f}^\circ$".format(args.minAlt),ha="right",va="bottom") pdf.savefig(fig) print(f"Writing out file: {outfn}")
def airmass_altitude_plot_given_target(name_observatory, day, target, path_target_list=None): """ Parameters ---------- name_observatory : str name of the observatory day : date date in format 'yyyy-mm-dd' target : str name of target path_target_list : path path of the target list Returns ------- """ if path_target_list is None: path_target_list = path_spock + '/target_lists/speculoos_target_list_v6.txt' observatory = charge_observatories(name_observatory)[0] delta_midnight = Time(np.linspace(observatory.twilight_evening_nautical(day, which='next').jd - 0.07, \ observatory.twilight_morning_nautical(day + 1, which='nearest').jd + 0.07, 100), format='jd') sun_set = observatory.twilight_evening_nautical(day, which='next').iso sun_rise = observatory.twilight_morning_nautical(day + 1, which='nearest').iso target_list = pd.read_csv(path_target_list, delimiter=' ') idx_target_list = list(target_list['Sp_ID']).index(target) fig, axs = plt.subplots(1, figsize=(9, 7)) colors_start_new_target = ['black', 'darkgray', 'lightgray'] dec = target_list['DEC'][idx_target_list] ra = target_list['RA'][idx_target_list] plot_styles = {'linestyle': '-', 'color': 'k'} if name_observatory == 'SSO': plot_styles = {'linestyle': '-', 'color': 'skyblue'} if name_observatory == 'SNO': plot_styles = {'linestyle': '-', 'color': 'teal'} if name_observatory == 'Saint-Ex': plot_styles = {'linestyle': '-', 'color': 'gold'} plot_airmass(FixedTarget(coord=SkyCoord(ra=ra, dec=dec, unit=(u.deg, u.deg)), \ name=target), observatory, delta_midnight, brightness_shading=True, altitude_yaxis=True, style_kwargs=plot_styles) #axs.vlines(sun_set, 3, 1, linestyle='--', color='orange', alpha=0.9, linewidth=2) #axs.vlines(sun_rise, 3, 1, linestyle='--', color='orange', alpha=0.9, linewidth=2) plt.ylabel('Altitude (degrees)') plt.grid(color='gainsboro', linestyle='-', linewidth=1, alpha=0.3) plt.title('Visibility plot for ' + target + ' on the ' + str(day.tt.datetime.strftime("%Y-%m-%d")) + ' at ' + name_observatory, y=-0.01) #plt.title('Visibility plot for target ' + target + ' on the ' + str(day.tt.datetime.strftime("%Y-%m-%d"))) plt.show()
def __init__(self,RA,DEC): ' Give coordinates of object, use astroplan to get alt and az at current time' whipple = astroplan.Observer.at_site('whipple') t = Time( time.strftime("%Y-%m-%d %H:%M:%S.000", time.gmtime()), format = 'iso') coords = SkyCoord(RA, DEC, frame='icrs',unit="deg") temptarg = FixedTarget(name='', coord=coords) self.alt = whipple.altaz(t, temptarg).alt self.az = whipple.altaz(t, temptarg).az
def target_information(TID, ra, dec): target_coord = SkyCoord(ra=ra * u.deg, dec=dec * u.deg, frame='icrs', equinox='J2000') # 'icrs' and 'J2000' are coordinate system specifications, keep it target = FixedTarget(coord=target_coord, name=TID) return target
def compute_is_up(name, time): ''' Computes what V<11 objects in a catalog are up right now. args: name (str): one in: ['messier', 'ngc'] time (str): in 24hr format, e.g. "2017-04-17 21:00:00" returns: catalog with is_up calculated, sorted by v_mag. ''' import datetime from astropy.time import Time from astroplan import FixedTarget from astropy.coordinates import SkyCoord from astroplan import Observer, FixedTarget, AltitudeConstraint, \ AtNightConstraint, is_observable, is_always_observable, \ months_observable assert name in ['messier', 'ngc'] if name == 'messier': data_path = '../data/catalogs/messier.csv' elif name == 'ngc': data_path = '../data/catalogs/ngc.csv' df = pd.read_csv(data_path) # The search & target creation is slow for >~thousands of FixedTargets. NGC # catalog is 13226 objects. Take those with v_mag<11, since from Peyton we # likely won't go fainter. df = df.sort_values('v_mag') df = df[df['v_mag']<11] peyton = Observer(longitude=74.65139*u.deg, latitude=40.34661*u.deg, elevation=62*u.m, name='Peyton', timezone='US/Eastern') if name == 'ngc': ras = np.array(df['ra'])*u.hourangle decs = np.array(df['dec'])*u.degree names = np.array(df['ngc_id']) elif name == 'messier': ras = np.array(df['ra'])*u.hourangle decs = np.array(df['dec'])*u.degree names = np.array(df['messier_id']) targets = [FixedTarget(SkyCoord(ra=r, dec=d), name=n) for r, d, n in tuple(zip(ras, decs, names))] constraints = [AltitudeConstraint(10*u.deg, 82*u.deg), AtNightConstraint(max_solar_altitude=-3.*u.deg)] t_obs = Time(time) is_up = is_observable(constraints, peyton, targets, times=t_obs) df['is_up'] = is_up return df
def test_compare_block_lists(): # create lists of blocks blocks = [] for i in range(10): blocks.append( ObservingBlock( FixedTarget(SkyCoord(0. * u.deg, 0. * u.deg, frame='icrs'), name=str(i)), 10 * u.minute, 10)) # create two lists from these with some overlap blocks1 = blocks[:7] blocks2 = blocks[5:] # compare unique1, unique2 = Scheduler._compare_block_lists(blocks1, blocks2) # get names names1 = [int(b.target.name) for b in unique1] names2 = [int(b.target.name) for b in unique2] # names1 should contain 0, 1, 2, 3, 4 assert set(names1) == {0, 1, 2, 3, 4} # names2 should contain 7, 8, 9 assert set(names2) == {7, 8, 9} # create two lists from these with no overlap blocks1 = blocks[:5] blocks2 = blocks[5:] # compare unique1, unique2 = Scheduler._compare_block_lists(blocks1, blocks2) # get names names1 = [int(b.target.name) for b in unique1] names2 = [int(b.target.name) for b in unique2] # names1 should contain 0, 1, 2, 3, 4 assert set(names1) == {0, 1, 2, 3, 4} # names2 should contain 5, 6, 7, 8, 9 assert set(names2) == {5, 6, 7, 8, 9} # create two identical lists blocks1 = blocks blocks2 = blocks # compare unique1, unique2 = Scheduler._compare_block_lists(blocks1, blocks2) # get names names1 = [int(b.target.name) for b in unique1] names2 = [int(b.target.name) for b in unique2] # both lists should be empty assert len(names1) == 0 assert len(names2) == 0
def make_plot(ra, dec, name): '''Creates finding chart plot from input coordinates IN DEGREES and name''' # Generate coordinates coords = SkyCoord(ra=ra * u.deg, dec=dec * u.deg) target = FixedTarget(coord=coords, name=name) # Create figure fig = plt.figure(figsize=(18, 18)) plt.rcParams.update({'font.size': 15}) # Download cutout ax, hdu = plot_finder_image(target, survey='DSS', fov_radius=2 * u.arcmin, reticle='True') # Circle around the star circle = plt.Circle((150, 150), 8.0, color='b', fill=False) # North and East arrows arrow = plt.arrow(270, 30, -50, 0, color='r', length_includes_head='True', width=2, head_width=3) arrow2 = plt.arrow(270, 30, 0, 50, color='r', length_includes_head='True', width=2, head_width=3) # Scale arrow3 = plt.arrow(30, 30, 100, 0, color='k', length_includes_head='False', width=2, head_width=0) ax.add_artist(arrow) ax.add_artist(arrow2) plt.text(30, 270, 'DSS', fontsize=25) plt.text(220, 32, "E", fontsize=25) plt.text(272, 80, "N", fontsize=25) plt.text(80, 34, "40''", fontsize=25) # Save figure fig.savefig('%s.png' % (name)) plt.close(fig)
def show_graph(self): global plt for i in range(len(arr)): star1 = FixedTarget(coord=self.transformed[i].transform_to('fk5'), name="Star" + str(i)) plot_sky(star1, self.observer, reftime) plt.plot(self.transformed[i].alt, self.transformed[i].az, 'bo') plt.legend(loc='center left', bbox_to_anchor=(1.25, 0.5)) plt.show()
def airmass_altitude_plot_saved(name_observatory, telescope, day): """ Parameters ---------- name_observatory : str name of the observatory (ex : 'SSO') telescope : str name of the telescope (exx : 'Io') day : date date of day in fmt "yyyy-mm-dd" Returns ------- plot visibility plot on telescope at a given day """ night_block = pd.read_csv(os.path.join(path_spock + '/DATABASE/', telescope, 'Archive_night_blocks','night_blocks_' + telescope + '_' + day.tt.datetime.strftime("%Y-%m-%d") + '.txt'),\ sep=' ', skipinitialspace=True) observatory = charge_observatories(name_observatory)[0] day = Time(night_block['start time (UTC)'][0]) - 5 * u.hour delta_midnight = Time(np.linspace(observatory.twilight_evening_nautical(day,which='next').jd - 0.07,\ observatory.twilight_morning_nautical(day+1,which='nearest').jd + 0.07, 100),format='jd') sun_set = observatory.twilight_evening_nautical(day, which='next').iso sun_rise = observatory.twilight_morning_nautical(day + 1, which='nearest').iso fig, axs = plt.subplots(1) colors_start_new_target = ['black', 'darkgray', 'lightgray'] for i in range(len(night_block)): dec = str(int(float(night_block['dec (d)'][i]))) + ' ' + str( int(abs(float(night_block['dec (m)'][i])))) + ' ' + str( int(abs(float(night_block['dec (s)'][i])))) ra = str(int(float(night_block['ra (h)'][i]))) + ' ' + str( int(abs(float(night_block['ra (m)'][i])))) + ' ' + str( int(abs(float(night_block['ra (s)'][i])))) plot_airmass(FixedTarget(coord=SkyCoord(ra=ra,dec=dec,unit=(u.hourangle, u.deg)),\ name=night_block['target'][i]), observatory, delta_midnight, altitude_yaxis=True) plt.ylabel('Altitude (degrees)') t = Time(night_block['start time (UTC)'][i]) axs.vlines(t.iso, 3, 1, linestyle='--', color=colors_start_new_target[i], alpha=0.7, label='start ' + str(night_block['target'][i])) axs.vlines(sun_set, 3, 1, linestyle=':', color='yellow', alpha=0.9) axs.vlines(sun_rise, 3, 1, linestyle=':', color='yellow', alpha=0.9) #plt.legend(loc=2) plt.grid(color='gainsboro', linestyle='-', linewidth=1, alpha=0.3) plt.title('Visibility plot for the night of the ' + str(day.tt.datetime.strftime("%Y-%m-%d")) + ' on ' + str(telescope))
def __init__(self, ra, dec, unit,): self.coord = SkyCoord(ra, dec, unit=unit) # self.time = Time(utc_time) self.time_now = Time(str(dt.utcnow())) self.dct = dct_astroplan_loc() self.target = FixedTarget(name='Target', coord=self.coord) self.target_is_up = self.dct.target_is_up(self.time_now, self.target) self.target_rise_time = self.dct.target_rise_time(self.time_now, self.target, which=u'next') self.target_set_time = self.dct.target_set_time(self.time_now, self.target, which=u'next') self.target_rise_time_local = self.target_rise_time.datetime.replace(tzinfo=timezone.utc).astimezone(tz=None)
def load_backup(filename): filenameSplit = filename.split("_") priority = float(filenameSplit[-1].replace(".dat","")) targets = astropy.io.ascii.read(filename) ncolumns = len(targets.columns) if ncolumns == 16: names = ["requestID", "programID", "objectID", "ra_hex", "dec_hex", "epoch", "ra_rate", "dec_rate", "mag", "exposure_time", "filter", "mode", "pi", "comment","redo","delta_redo"] elif ncolumns == 15: names = ["requestID", "programID", "objectID", "ra_hex", "dec_hex", "epoch", "ra_rate", "dec_rate", "mag", "exposure_time", "filter", "mode", "pi", "comment","redo"] elif ncolumns == 14: names = ["requestID", "programID", "objectID", "ra_hex", "dec_hex", "epoch", "ra_rate", "dec_rate", "mag", "exposure_time", "filter", "mode", "pi", "comment"] targets = astropy.io.ascii.read(filename,names=names) sigs, periods = [], [] coords, target = [], [] ras, decs = [], [] for row in targets: comment = row["comment"] commentSplit = comment.split("_") sig, period = float(commentSplit[0]), float(commentSplit[1]) sigs.append(sig) periods.append(period) ra_hex, dec_hex = row["ra_hex"], row["dec_hex"] ra = Angle(ra_hex, unit=u.hour).deg dec = Angle(dec_hex, unit=u.deg).deg coord = SkyCoord(ra=ra*u.deg, dec=dec*u.deg) tar = FixedTarget(coord=coord, name=row["objectID"]) coords.append(coord) target.append(tar) ras.append(ra) decs.append(dec) targets["sig"] = sigs targets["periods"] = periods targets["coords"] = coords targets["target"] = target targets["ra"] = ras targets["dec"] = decs targets["programID"] = 1 targets["priority"] = np.array(sigs) + priority targets["redo"] = 1 targets.sort("sig") targets.reverse() targets = astropy.table.unique(targets, keys=["objectID"]) targets['ra_rate'].dtype= np.float64 targets['dec_rate'].dtype= np.float64 return targets
def objek(nama, ra, dec): op = SkyCoord(ra, dec, frame='icrs', unit='deg') op_name = FixedTarget(coord=op, name=nama) # betelgeus = SkyCoord.from_name('betelgeuse') # altaz_frame = lokasi.altaz(time) # ubah lokasi pengamat ke altaz frame # betelgeus_altaz = betelgeus.transform_to(altaz_frame) # ubah target ke altaz altaz = lokasi.altaz(win_time, op) terbit = lokasi.target_rise_time(win_time, op) transit = lokasi.target_meridian_transit_time(win_time, op) terbenam = lokasi.target_set_time(win_time, op) return op_name, altaz, terbit, transit, terbenam
def get_star_info(obj): star = FixedTarget.from_name(obj) is_up = location.target_is_up(time, star) if not is_up: return None, None, None, is_up rise_time = location.target_rise_time(time, star) set_time = location.target_set_time(time, star) altitude_at_rise = location.altaz(rise_time, star).alt return rise_time, set_time, altitude_at_rise, is_up
def __init__(self, payload): super().__init__(payload) # Get XML param dicts # NB: you can't store these on the Event because they're unpickleable. top_params = vp.get_toplevel_params(self.voevent) # group_params = vp.get_grouped_params(self.voevent) # Default params self.notice = EVENT_DICTIONARY[self.packet_type]['notice_type'] self.type = EVENT_DICTIONARY[self.packet_type]['event_type'] self.source = EVENT_DICTIONARY[self.packet_type]['source'] # Get the run and event ID (e.g. 13311922683750) self.id = top_params['AMON_ID']['value'] # Create our own event name (e.g. ICECUBE_13311922683750) self.name = '{}_{}'.format(self.source, self.id) # Get info from the VOEvent # signalness: the probability this is an astrophysical signal relative to backgrounds self.signalness = float(top_params['signalness']['value']) self.far = float(top_params['FAR']['value']) # Position coordinates self.position = vp.get_event_position(self.voevent) self.coord = SkyCoord(ra=self.position.ra, dec=self.position.dec, unit=self.position.units) self.target = FixedTarget(self.coord) # Position error self.coord_error = Angle(self.position.err, unit=self.position.units) # Systematic error for cascade event is given, so = 0 if self.notice == 'ICECUBE_CASCADE': self.systematic_error = Angle(0, unit='deg') else: self.systematic_error = Angle(.2, unit='deg') self.total_error = Angle(np.sqrt(self.coord_error**2 + self.systematic_error**2), unit='deg') # Enclosed skymap url for CASCADE_EVENT, but others # Get skymap URL if 'skymap_fits' in top_params: self.skymap_url = top_params['skymap_fits']['value'] else: self.skymap_url = None # Don't download the skymap here, it may well be very large. # Only do it when it's absolutely necessary # These params will only be set once the skymap is downloaded self.contour_areas = {0.5: None, 0.9: None}
def lecture_cible(self, evt): """ Lecture des coordonnées de la cible dans le fichier d'abord, puis via internet :param evt: évènement WX :return: """ nom_cible = evt.GetString() coord = None try: # on cherche dans le fichier local cible = [ element for element in self.cibles if element['Nom'].lower() == nom_cible.lower() ][0] coord = SkyCoord(cible['Alpha'], cible['Delta']) except IndexError: # la cible n'a pas été trouvée dans le fichier # on essaie via internet try: cible = FixedTarget.from_name(nom_cible) coord = cible.coord alpha_delta = coord.to_string('hmsdms').split() self.cibles.append( dict([('Nom', nom_cible), ('Alpha', alpha_delta[0]), ('Delta', alpha_delta[1])])) self.ecriture_fichier_csv(self.fichier_csv_cibles) self.colore_champs_etoile(couleur_normale) except astropy.coordinates.name_resolve.NameResolveError: # la cible n'a nom plus pas été trouvée sur Simbad self.colore_champs_etoile(couleur_erreur) self.boite_erreur( 'Impossible de trouver {0}'.format(nom_cible)) finally: if coord: self.edit_heure_alpha.SetValue(str(int(coord.ra.hms[0]))) self.edit_minute_alpha.SetValue( str(int(coord.ra.hms[1] + coord.ra.signed_dms[2] / 60.0))) self.edit_degre_delta.SetValue( str(int(coord.dec.signed_dms[1]))) self.edit_minute_delta.SetValue( str( int(coord.dec.signed_dms[2] + coord.dec.signed_dms[2] / 60.0))) self.br_signe_delta.SetSelection( int((1 - int(coord.dec.signed_dms[0]) / 2))) self.signe_delta = int( coord.dec.signed_dms[0] ) # Pas d'évènement généré quand on change la sélection d'une radiobox self.edit_cible.SetValue(nom_cible) self.nom_cible = nom_cible self.bouton_calcul.Enable() else: self.bouton_calcul.Disable()
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 affichage_masse_air(self, etoile_cible, selection_etoiles, date_obs, observatoire): # Etoiles # Bogue dans plot_airmass : le 1er FixedTarget ne génère pas de légende. Donc on duplique le 1er enregistrement dans la liste etoiles = [ FixedTarget(etoile_cible['equat'], name=etoile_cible['nom']), [FixedTarget(etoile_cible['equat'], name=etoile_cible['nom'])] ] for etoile in selection_etoiles: if len(etoiles) > 6: break if (etoile['Sp'] in type_pickles) or etoile['Miles']: etoiles.append( FixedTarget(etoile['equat'], name=etoile['Name'])) # Intervalle de temps temps_obs = Time(date_obs) debut = temps_obs - TimeDelta(10800.0, format='sec') fin = temps_obs + TimeDelta(10800.0, format='sec') delta_t = fin - debut intervalle_temps = debut + delta_t * np.linspace(0, 1, 75) # Observatoire obs = Observer(location=observatoire, timezone="UTC") # Graphique # Nettoyage d'un éventuel graphique pré-existant if self.graphique_masse_air: self.graphique_masse_air.clear() plt.pause(.1) # Affichage self.graphique_masse_air = plot_airmass(etoiles, obs, intervalle_temps, altitude_yaxis=True, brightness_shading=True, max_region=2.0) self.graphique_masse_air.legend(shadow=True, loc='best') plt.tight_layout() plt.show(block=False) plt.pause(.1)
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 load_rgd_objects(filename): names = [ "requestID", "programID", "objectID", "ra_hex", "dec_hex", "ra_rate", "dec_rate", "exposure_time", "filter", "mode", "pi", "comment" ] targets = astropy.io.ascii.read(filename, format='no_header', delimiter=',', names=names) sigs, periods = [], [] coords, target = [], [] ras, decs = [], [] for row in targets: sigs.append(0) periods.append(0) ra_hex, dec_hex = row["ra_hex"], row["dec_hex"] ra = Angle(ra_hex, unit=u.hour).deg dec = Angle(dec_hex, unit=u.deg).deg coord = SkyCoord(ra=ra * u.deg, dec=dec * u.deg) tar = FixedTarget(coord=coord, name=row["objectID"]) coords.append(coord) target.append(tar) ras.append(ra) decs.append(dec) targets["sig"] = sigs targets["periods"] = periods targets["coords"] = coords targets["target"] = target targets["ra"] = ras targets["dec"] = decs targets["programID"] = 1 targets["epoch"] = 2000 targets["priority"] = np.array(sigs) targets.sort("sig") targets.reverse() targets = astropy.table.unique(targets, keys=["objectID"]) targets['ra_rate'].dtype = np.float64 targets['dec_rate'].dtype = np.float64 #targets['requestID'].dtype = np.float64 return targets
def sortie_graphique(self, etoile_cible, date_obs, observatoire): matplotlib.rcParams['backend'] = 'Qt5Agg' # Etoiles etoile = FixedTarget(etoile_cible['equat'], name=etoile_cible['nom']) # Intervalle de temps temps_obs = Time(date_obs) debut = temps_obs - TimeDelta(10800.0, format='sec') fin = temps_obs + TimeDelta(10800.0, format='sec') delta_t = fin - debut intervalle_temps_1 = debut + delta_t * np.linspace(0, 1, 75) intervalle_temps_2 = debut + delta_t * np.linspace(0, 1, 11) # Observatoire obs = Observer(location=observatoire, timezone="UTC") # Masse d'air if self.graph1 is None: self.fig1, self.graph1 = plt.subplots() else: self.graph1.clear() plot_airmass(etoile, obs, intervalle_temps_1, ax=self.graph1, altitude_yaxis=True, max_region=2.0) self.graph1.legend(shadow=True, loc='best') plt.tight_layout() # Carte # Il faut obligatoirement que le graphique soit en mode polaire avant l'appel à plot_sky if self.graph2 is None: self.fig2, self.graph2 = plt.subplots( subplot_kw=dict([('projection', 'polar')])) else: self.graph2.clear() style = {'marker': '.'} plot_sky(etoile, obs, intervalle_temps_2, ax=self.graph2, style_kwargs=style) self.graph2.legend(shadow=True, loc='best') plt.tight_layout() plt.show(block=False) plt.pause(.1)
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))
A target object defines a single observation target, with coordinates and an optional name. ''' from astroplan import FixedTarget # Define a target. from astropy.coordinates import SkyCoord t1 = FixedTarget(name='Polaris', coord=SkyCoord('02h31m49.09s', '+89d15m50.8s', frame='icrs')) # Leaves scope for NonSiderealTarget, etc. # Convenience methods for looking up/constructing targets by name via # astroquery: t1 = FixedTarget.from_name('Polaris') # ================================ # Condition objects, observability # ================================ """ Q: Can I observe this target on the night of May 1, 2015 between 18:30 and 05:30 HST, above airmass 1.2, on a telescope that can observe between 15 degrees and 89 degrees altitude? """ # first we define the conditions from astroplan import TimeRange, AltitudeRange, AirmassRange, is_observable # `is_observable` is a temporary function which will eventually be a method of # something to support caching