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 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_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_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 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 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 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 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 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 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 __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 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 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 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 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 __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 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 __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 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 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 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 targetsFromCSV(path, minUpdated=None, **read_csv_kwargs): """ Obtain a target list from a csv file. Reads a csv file with the TESS alerts as downloaded from the TEV homepage, extracts coordinates and names, and transforms the entries to astroplan target objects. Parameters ---------- path : str path to the csv file minUpdated : str, optional earliest time in column "Updated" to be considered Format: YYYY-MM-DD read_csv_kwargs : keyword arguments, optional keyword arguments to pass to pandas' read_csv function Returns ------- alerts : pandas DataFrame table containing alerts targets : list list containing astroplan targets """ alerts = pd.read_csv(path, **read_csv_kwargs) alerts.rename(columns={'Full TOI ID': 'TOI'}, inplace=True) targets = [] if minUpdated is not None: if not 'Updated' in alerts.columns: # newer alert files contain "Alerted" instead of "Updated" alerts.rename(columns={'Alerted': 'Updated'}, inplace=True) alerts.Updated = pd.to_datetime(alerts.Updated) alerts.Updated = alerts.Updated.dt.tz_localize(None) # strip timezone minUpdated = np.datetime64(minUpdated) alerts = alerts[alerts.Updated > minUpdated] for toi in alerts.iterrows(): target = toi[1] coords = SkyCoord(target['TIC Right Ascension'], target['TIC Declination'], unit=(u.deg, u.deg)) targets.append(FixedTarget(coord=coords, name=target['TOI'])) return alerts, targets
def load_NEO(filename): filenameSplit = filename.split("_") 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, format='csv') targets['priority'] = 1e15 targets['ra_rate'].dtype = np.float64 targets['dec_rate'].dtype = np.float64 targets = targets.filled() coords, target = [], [] ras, decs = [], [] for row in targets: 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["coords"] = coords targets["target"] = target targets["ra"] = ras targets["dec"] = decs mjd_now = Time.now().mjd mjds = [] for row in targets: if not row["comment"]: continue tt = datetime(*strptime(row["comment"], '%Y-%b-%d %H:%M:%S.%f')[:6]) mjds.append(Time(tt, format='datetime').mjd) mjds = np.array(mjds) idx = np.argmin(np.abs(mjd_now - mjds)) targets = targets[idx] return targets
def __init__(self, observation_id, coordinates, agency_id, priority, remaining_observing_chances, duration, exposure_count, constraint_meta): if not isinstance(coordinates, SkyCoord): raise RuntimeError( "Constructor Error :: Coordinates have not been mapped to Astropy SkyCoord Class" ) self.observation_id = observation_id self.coordinates = coordinates self.agency_id = agency_id self.priority = priority self.remaining_observing_chances = remaining_observing_chances self.duration = duration self.exposure_count = exposure_count self.constraint_meta = constraint_meta self.target = FixedTarget(coord=coordinates, name=str(observation_id))