def create_graphs(file_path, event, site_data, fov=30): """Create airmass and finder plots.""" # Plot airmass during the night delta_t = site_data['sun_rise'] - site_data['sun_set'] time_range = site_data['sun_set'] + delta_t * np.linspace(0, 1, 75) plot_airmass(event.coord, site_data['observer'], time_range, altitude_yaxis=True, style_sheet=dark_style_sheet) airmass_file = "{}_AIRMASS.png".format(event.name) plt.savefig(os.path.join(file_path, 'airmass_plots', airmass_file)) plt.clf() # Plot finder chart import warnings with warnings.catch_warnings(): warnings.simplefilter('ignore') plot_finder_image(event.target, fov_radius=fov * u.arcmin, grid=False, reticle=True) airmass_file = "{}_FINDER.png".format(event.name) plt.savefig(os.path.join(file_path, 'finder_charts', airmass_file)) plt.clf()
def target_preview(target: str, **kwargs) -> matplotlib.figure.Figure: """ Generate a static image preview of a target. Parameters ---------- target: str The name of the target. Authors ------- @rprechelt """ # lookup target with astroquery target = astroplan.FixedTarget.from_name(target) # if we have found a target if target: fig, ax = plt.subplots() # plot the finder image with astroplan ax, hdu = plot_finder_image(target, fov_radius=26 * units.arcmin, ax=ax) # disable all the extraneous jazz ax.set_axis_off() ax.set_title('') # and we are done return fig
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 plot_finding_chart(self): """ """ ax, hdu = plot_finder_image( self.target, fov_radius=2 * u.arcmin, survey="DSS2 Blue", grid=True, reticle=False, ) outpath_png = os.path.join(self.name, f"{self.name}_finding_chart.png") plt.savefig(outpath_png, dpi=300) plt.close()
def _make_figure(self, ax=None, right=False, style_kwargs=None): if ax: self.ax = ax else: self.ax = None plt.figure(dpi=100) if self.style_kwargs is None: self.style_kwargs = style_kwargs try: self.ax, self.hdu = plot_finder_image( self.target, survey=self.survey, fov_radius=self.radius * u.arcsec, reticle=self.reticle, ax=self.ax, grid=self.grid, log=self.log, style_kwargs=self.style_kwargs) lon = self.ax.coords[0] lat = self.ax.coords[1] if right: #lat.set_axislabel('DEC',fontsize=10) lat.set_axislabel_position('r') lat.set_axislabel(r'$\delta_{2000}$', fontsize=14) lat.set_ticks_position('r') lat.set_ticklabel_position('r') #lon.set_axislabel('RA',fontsize=10) lon.set_axislabel(r'$\alpha_{2000}$', fontsize=14) lon.set_major_formatter('hh:mm:ss.s') lat.set_major_formatter('dd:mm:ss') if right: lat.ticklabels.set_fontsize(8) lon.ticklabels.set_fontsize(8) #self.ax.yaxis.set_label_position("right") #lat.set_ticklabel_position('r') #self.ax.set_ylabel(r'$\delta_{2000}$',fontsize=14) #except IndexError as e: except: self.ax = None return None
plt.fill_between(delta_midnight, 0 * u.deg, 90 * u.deg, sunaltazs_July12_to_13.alt < -0 * u.deg, color='0.5', zorder=0) plt.fill_between(delta_midnight, 0 * u.deg, 90 * u.deg, sunaltazs_July12_to_13.alt < -18 * u.deg, color='k', zorder=0) plt.colorbar().set_label('Azimuth [deg]') plt.legend(loc='upper left') plt.xlim(-12 * u.hour, 12 * u.hour) plt.xticks((np.arange(13) * 2 - 12) * u.hour) plt.ylim(0 * u.deg, 90 * u.deg) plt.xlabel('Hours from EDT Midnight') plt.ylabel('Altitude [deg]') plt.show() K2_24_c_transit = ExoplanetOrbitDatabase.query_planet('K2-24 c') K2_24_c = SkyCoord.from_name('K2-24 c') from astroplan.plots import plot_finder_image from astroplan import FixedTarget import matplotlib.pyplot as plt messier1 = FixedTarget.from_name("M1") ax, hdu = plot_finder_image(messier1) plt.show()
def observe(request, method="POST"): if request.POST['observing_date'] == "": messages.error(request, 'Please choose a date!') if request.POST['name'] == "": messages.error(request, 'Object name cannot be empty!') if request.POST['ra'] == "": messages.error(request, 'Object RA cannot be empty!') if request.POST['dec'] == "": messages.error(request, 'Object Dec cannot be empty!') if request.POST['observing_date'] == "" or request.POST[ 'name'] == "" or request.POST['ra'] == "" or request.POST[ 'dec'] == "": return redirect('/') observatory = None offset = None for idx, val in enumerate(T['name']): if val == request.POST['observatory']: observatory = Observer(longitude=T['longitude'][idx] * u.deg, latitude=T['latitude'][idx] * u.deg, elevation=T['altitude'][idx] * u.m, name=T['name'][idx]) today = datetime.now() if tf.certain_timezone_at(lat=T['latitude'][idx], lng=T['longitude'][idx]) == None: return redirect('/error') tz_target = timezone( tf.certain_timezone_at(lat=T['latitude'][idx], lng=T['longitude'][idx])) # ATTENTION: tf.certain_timezone_at(...) could be None! handle error case today_target = tz_target.localize(today) today_utc = utc.localize(today) offset = (today_utc - today_target).total_seconds() * u.s # # offset = offsetfunction(observatory) observe_date = Time(request.POST['observing_date'] + ' 00:00:00', format='iso') sunset_here = observatory.sun_set_time(observe_date, which="nearest") + offset sunrise_here = observatory.sun_rise_time(observe_date, which="next") + offset midnight_here = observatory.midnight(observe_date, which="nearest") + offset astro_set = observatory.twilight_evening_astronomical(observe_date, which='nearest') astro_rise = observatory.twilight_morning_astronomical(observe_date, which='next') coords = SkyCoord(request.POST['ra'], request.POST['dec'], frame='icrs') target = FixedTarget(name=request.POST['name'], coord=coords) start_time = astro_set end_time = astro_rise delta_t = end_time - start_time observe_time = start_time + delta_t * np.linspace(0.0, 2.0, 100) plt.ioff() sky = plot_sky(target, observatory, observe_time) sky.figure.savefig('apps/project_app/static/project_app/plot_sky.png') plt.close() plt.ioff() airmass = plot_airmass(target, observatory, observe_time) airmass.figure.savefig( 'apps/project_app/static/project_app/plot_airmass.png') plt.close() plt.ioff() finder_image = plot_finder_image(target) finder_image[0].figure.savefig( 'apps/project_app/static/project_app/plot_finder_image.png') plt.close() request.session['context'] = { "sunset": Time(sunset_here, format="iso").value, "sunrise": Time(sunrise_here, format="iso").value, "date": Time(observe_date, format="iso").value, "midnight": Time(midnight_here, format="iso").value, "site": request.POST['observatory'], "ra": request.POST['ra'], "dec": request.POST['dec'], "name": request.POST['name'] } return redirect('/display')
def plot_gaia_sources_on_survey( self, gaia_sources=None, aper_mask=None, fov_rad=None, depth=0.0, kmax=1.0, survey="DSS2 Red", ax=None, figsize=None, color_aper="C0", ): """Plot (superpose) Gaia sources on archival image Parameters ---------- gaia_sources : pd.DataFrame gaia sources table aper_mask : array aperture mask (uses pipeline mask if None) fov_rad : astropy.unit FOV radius survey : str image survey; see from astroquery.skyview import SkyView; SkyView.list_surveys() ax : axis subplot axis Returns ------- ax : axis subplot axis """ if aper_mask is None: if self.best_aper_mask is None: errmsg = "Use either `Everest` or `K2sff` class\n." # errmsg = "Else, provide `aper_mask`.\n" # errmsg += "Try: `tpf = self.get_tpf(); aper_mask = tpf.pipeline_mask`" raise ValueError(errmsg) else: aper_mask = self.best_aper_mask if self.tpf is None: tpf = self.get_tpf() else: tpf = self.tpf ny, nx = tpf.flux.shape[1:] if fov_rad is None: diag = np.sqrt(nx**2 + ny**2) fov_rad = (diag * Kepler_pix_scale).to(u.arcsec).round(0) if gaia_sources is None: gaia_sources = self.query_gaia_dr2_catalog(radius=fov_rad.value) assert len(gaia_sources) > 1, "gaia_sources contains single entry" if self.gaiaid is None: # _ = self.query_gaia_dr2_catalog(return_nearest_xmatch=True) target_gaiaid = gaia_sources.loc[0, "source_id"] else: target_gaiaid = self.gaiaid # make aperture mask # maskhdr = tpf.hdu[2].header # self.k2sff_header # make aperture mask outline contour = np.zeros((ny, nx)) contour[np.where(aper_mask)] = 1 contour = np.lib.pad(contour, 1, PadWithZeros) highres = zoom(contour, 100, order=0, mode="nearest") # extent = np.array([-1, nx, -1, ny]) # if self.epicid == 212428509: # import pdb # pdb.set_trace() if self.verbose: print( f"Querying {survey} ({fov_rad:.2f} x {fov_rad:.2f}) archival image" ) # -----------create figure---------------# if ax is None: # get img hdu for subplot projection results = SkyView.get_images( position=self.target_coord.icrs.to_string(), coordinates="icrs", survey=survey, radius=fov_rad, grid=False, ) if len(results) > 0: hdu = results[0][0] else: errmsg = ( "SkyView returned empty result. Try a different survey.") raise ValueError(errmsg) # create figure with subplot projection fig = pl.figure(figsize=figsize) ax = fig.add_subplot(111, projection=WCS(hdu.header)) # plot survey img # FIXME: SkyView throws error when self.target_coord.distance=nan coord = SkyCoord(ra=self.target_coord.ra, dec=self.target_coord.dec) fixed_target = FixedTarget(coord, name=self.target_name) nax, hdu = plot_finder_image( fixed_target, ax=ax, fov_radius=fov_rad, survey=survey, reticle=False, ) imgwcs = WCS(hdu.header) mx, my = hdu.data.shape # # make aperture mask outline # contour = np.zeros((my, mx)) # contour[np.where(aper_mask)] = 1 # contour = np.lib.pad(contour, 1, PadWithZeros) # highres = zoom(contour, 100, order=0, mode="nearest") extent = np.array([-1, mx, -1, my]) # plot mask _ = ax.contour( highres, levels=[0.5], extent=extent, origin="lower", colors=color_aper, transform=ax.get_transform(imgwcs), ) idx = gaia_sources["source_id"].astype(int).isin([target_gaiaid]) target_gmag = gaia_sources.loc[idx, "phot_g_mean_mag"].values[0] for _, row in gaia_sources.iterrows(): marker, s = "o", 100 r, d, mag, id = row[["ra", "dec", "phot_g_mean_mag", "source_id"]] pix = imgwcs.all_world2pix(np.c_[r, d], 1)[0] if int(id) != int(target_gaiaid): gamma = 1 + 10**(0.4 * (mag - target_gmag)) if depth > kmax / gamma: # too deep to have originated from secondary star edgecolor = "C1" alpha = 1 # 0.5 else: # possible NEBs edgecolor = "C3" alpha = 1 else: s = 200 edgecolor = "C2" marker = "s" alpha = 1 nax.scatter( pix[0], pix[1], marker=marker, s=s, edgecolor=edgecolor, alpha=alpha, facecolor="none", ) # orient such that north is up; left is east ax.invert_yaxis() if hasattr(ax, "coords"): ax.coords[0].set_major_formatter("dd:mm") ax.coords[1].set_major_formatter("dd:mm") # set img limits pl.setp( nax, xlim=(0, mx), ylim=(0, my), title=self.target_name # title="{0} ({1:.2f}' x {1:.2f}')".format(survey, fov_rad.value), ) return ax
def show_ref_frame(self, tid=0, refid=None, ref_band=None, survey=None, dataloc='/ut2/muscat/reduction/muscat', figsize=(10, 8)): """ show star ids superposed with the reference frame Note: refid refers to fits filename frame number whereas ref_frame starts with 0 for first science frame """ bandnum = {band: i for i, band in enumerate(self.bands)} refband = ref_band if ref_band is not None else self.ref_band bn = bandnum[refband] if refid is None: path = f'{dataloc}/{self.obsdate}/{self.objname}/region/*.reg' region_file_path = glob(path)[0] refid = region_file_path.split('.')[-1][:-4] reffilename = region_file_path.split('/')[-1].split('.')[0] else: refid = str(refid).zfill(4) reffilename = f'MSCT{bn}_{self.obsdate}{refid}' region_file_path = f'{dataloc}/{self.obsdate}/{self.objname}/region/{reffilename}.reg' pos = np.loadtxt(region_file_path, dtype='str') centers = [] for n in range(len(pos) - 1): line = n + 1 i = re.findall(r'\d+', ''.join(pos[line])) x = float(f'{i[0]}.{i[1]}') y = float(f'{i[2]}.{i[3]}') centers.append((x, y)) # fp = f'{dataloc}/{self.obsdate}/{self.objname}/reference/ref-{reffilename}.fits' img = fits.getdata(fp) hdr = fits.getheader(fp) fig, ax = pl.subplots(1, 2, figsize=figsize) #imaging survey if survey is None: survey = 'DSS2 Blue' #left panel zmin, zmax = interval.get_limits(img) ax[0].imshow(img, vmin=zmin, vmax=zmax, origin='bottom', cmap='viridis') ax[0].set_title(hdr['OBJECT']) #circles for n, center in enumerate(centers[:self.nstars]): if n == tid: c = pl.Circle(center, 20, color='r', fill=False, lw=3) else: c = pl.Circle(center, 20, color='w', fill=False, lw=3) x, y = center ax[0].text(x + 5, y + 5, n, color='w', fontsize=15) ax[0].add_artist(c) #right panel plot_finder_image(self.objcoord, fov_radius=fov_rad, survey=survey, reticle=True, ax=ax[1]) ax[1].set_title(survey) return fig
def createPlot(args, saveflag, id): observer = Observer.at_site('lbt') try: args.coordinate[0] = float(args.coordinate[0]) args.coordinate[1] = float(args.coordinate[1]) coordinates = SkyCoord(args.coordinate[0], args.coordinate[1], unit=(u.deg, u.deg), frame='icrs') except: coordinates = SkyCoord(args.coordinate[0], args.coordinate[1], unit=(u.hourangle, u.deg), frame='icrs') observe_time = Time(f'{args.time[0]} {args.time[1]}', scale='utc') target = FixedTarget(name=args.output, coord=coordinates) if args.mode == 'single': obs_time = Time(f'{args.time[0]} {args.time[1]}') lbtcoord = EarthLocation(lat=32.7016 * u.deg, lon=-109.8719 * u.deg, height=3221.0 * u.m) altazcoord = coordinates.transform_to( AltAz(obstime=obs_time, location=lbtcoord)) if args.output is None: args.output = 'Unknown' print(f'\n{args.output}:') print("Altitude = {0.alt:.4}".format(altazcoord)) if args.plot == 'Alt' or args.plot == 'all': if id == 0: plt.figure(figsize=(10, 6)) if args.mode == "list": plt.title(args.filename + '\n' + args.time[0]) else: plt.title(args.output + '\n' + args.time[0]) plot_altitude(target, observer, observe_time, brightness_shading=True) if saveflag == 1: if args.mode == 'list': filename = args.filename + '_' + str(ceil(id / args.number)) else: filename = args.output #plt.tight_layout() plt.axhline(y=30, ls='--', color='k') plt.legend() plt.savefig(f'{filename}_Alt.png') plt.clf() if args.plot == 'Sky' or args.plot == 'all': observe_time2 = observe_time + np.linspace(-6, 6, 13) * u.hour if id == 0: plt.figure(figsize=(8, 6)) if args.mode == "list": plt.title(f'{args.filename}\n{args.time[0]} - {args.time[1]} UT', pad=13) else: plt.title(f'{args.time[0]} - {args.time[1]} UT', pad=13) plot_sky(target, observer, observe_time, style_kwargs={ 'marker': '+', 'c': 'k', 's': 160 }) plot_sky(target, observer, observe_time2) if saveflag == 1: if args.mode == 'list': filename = args.filename + '_' + str(ceil(id / args.number)) else: filename = args.output handles, labels = plt.gca().get_legend_handles_labels() by_label = dict(zip(labels, handles)) plt.legend(by_label.values(), by_label.keys(), loc='center left', bbox_to_anchor=(1.25, 0.5)) plt.tight_layout() plt.savefig(f'{filename}_Sky.png') plt.clf() if args.plot == 'FC' or args.plot == 'all': plt.figure(figsize=(8, 8)) ax, hdu = plot_finder_image(target, survey=args.survey, fov_radius=5 * u.arcmin, grid=True, reticle=True) if saveflag == 1: plt.savefig(f'{args.output}_FC.png') plt.clf() if args.plot == 'par' or args.plot == 'all': if id == 0: plt.figure(figsize=(10, 6)) #plt.locator_params(axis='y', nbins=13) #plt.locator_params(axis='x', nbins=18) plot_parallactic(target, observer, observe_time) if args.mode == "list": plt.title(args.filename + '\n' + args.time[0]) if saveflag == 1: if args.mode == 'list': filename = args.filename + '_' + str(ceil(id / args.number)) else: filename = args.output plt.ylim(deg2rad(-360), deg2rad(360)) plt.yticks(np.arange(deg2rad(-360), deg2rad(360), step=deg2rad(45))) locs, labels = plt.yticks() label = [] for parrad in locs: label.append(round(rad2deg(parrad))) plt.yticks(locs, label) plt.ylabel('Parallactic angle') plt.grid() plt.legend() plt.tight_layout() plt.savefig(f'{filename}_par.png') plt.clf() if args.plot != 'None': del observe_time del observer del coordinates del target del observe_time2
def plot_fov(target_coord,res,fov_rad=60*u.arcsec,ang_dist=15*u.arcsec, survey='DSS',verbose=True,outdir=None,savefig=False): """Plot FOV indicating the query position (magenta reticle) and nearby HARPS target (colored triangle), query radius (green circle) and Gaia DR2 sources (red squares) Parameters ---------- targ_coord : astropy.coordinates.SkyCoord targ_coord res : pandas.DataFrame masked dataframe from `query_target` fov_rad : astropy.unit field of view radius ang_dist : astropy.unit angular distance within which to find nearest HARPS object survey : str survey name of archival image outdir : str download directory location verbose : bool print texts savefig : bool save figure Returns ------- res : pandas.DataFrame masked dataframe """ if verbose: print('\nGenerating FOV ...\n') nearest_obj = res['Target'].values[0] tic = res['ticid'].values[0] if outdir is None: outdir = nearest_obj else: #save with folder name==ticid if len(res['ticid'].dropna())>0: outdir = join(outdir,'tic'+str(tic)) # elif res['toi'] is not None: # outdir = join(outdir,str(res['toi']).split('.')[0]) else: outdir = join(outdir,nearest_obj) if not isdir(outdir): makedirs(outdir) nearest_obj_ra,nearest_obj_dec =res[['RA_deg','DEC_deg']].values[0] nearest_obj_coord = SkyCoord(ra=nearest_obj_ra, dec=nearest_obj_dec, unit=u.deg) #indicate target location with magenta reticle ax,hdu=plot_finder_image(target_coord,fov_radius=fov_rad,reticle=True, survey=survey,reticle_style_kwargs={'label':'target'}) c = SphericalCircle((nearest_obj_ra, nearest_obj_dec)*u.deg, ang_dist, edgecolor='C2', transform=ax.get_transform('icrs'), facecolor='none', label='query radius') ax.set_title('{} ({})'.format(survey,nearest_obj)) ax.add_patch(c) #harps objects within angular distance coords = SkyCoord(ra=res['RA_deg'], dec=res['DEC_deg'], unit=u.deg) sep2d = target_coord.separation(coords) #get indices that satisfy the criterion idxs = sep2d < ang_dist colors = cm.rainbow(np.linspace(0, 1, idxs.sum())) if len(coords[idxs])>1: #plot each star match within search radius for n,(coord,color) in enumerate(zip(coords[idxs],colors)): ax.scatter(coord.ra.deg, coord.dec.deg, transform=ax.get_transform('icrs'), s=300, marker='^', edgecolor=color, facecolor='none',label=res.loc[idxs,'Target'].values[n]) else: ax.scatter(coords.ra.deg, coords.dec.deg, transform=ax.get_transform('icrs'), s=300, marker='^', edgecolor='blue', facecolor='none',label=res['Target'].values[0]) #gaia dr2 sources wcs = WCS(hdu.header) mx, my = hdu.data.shape #query gaia sources within region centered at target_coord gaia_sources = Catalogs.query_region(target_coord, radius=fov_rad, catalog="Gaia", version=2).to_pandas() for r,d in gaia_sources[['ra','dec']].values: pix = wcs.all_world2pix(np.c_[r,d],1)[0] ax.scatter(pix[0], pix[1], marker='s', s=50, edgecolor='C1', facecolor='none', label='gaia source') pl.setp(ax, xlim=(0,mx), ylim=(0,my)) #remove redundant labels due to 4 reticles handles, labels = pl.gca().get_legend_handles_labels() by_label = OrderedDict(zip(labels, handles)) pl.legend(by_label.values(), by_label.keys()) if savefig: fp = join(outdir,'tic{}_{}_fov.png'.format(tic,nearest_obj)) ax.figure.savefig(fp,bbox_inches='tight') print('Saved: {}'.format(fp)) return None
coord=SkyCoord(line['RA'], line['Dec'], frame='icrs')) if line == trunctable[0]: plot_airmass(cur_targ, observatory, daytime, brightness_shading=True, altitude_yaxis=True) else: plot_airmass(cur_targ, observatory, daytime, brightness_shading=False, altitude_yaxis=False) plt.savefig((subdir + '\\amassplot.png'), dpi=900, orientation='landscape', bbox_inches='tight') plt.clf() # In[18]: for line in trunctable: cur_targ = FixedTarget(name=line['OBJ'], coord=SkyCoord(line['RA'], line['Dec'], frame='icrs')) ax, hdu = plot_finder_image(cur_targ) hdu.writeto(subdir + '\\' + line['OBJ'] + '.fits')
from astroplan.plots import plot_finder_image from astroplan import FixedTarget import matplotlib.pyplot as plt from astropy.coordinates import SkyCoord from astropy import units as u from matplotlib.patches import Rectangle c = SkyCoord('16 52 38.52 -19 09 41.7', unit=(u.hourangle, u.deg)) c1 = SkyCoord('16 52 39.48 -19 09 46.5', unit=(u.hourangle, u.deg)) c2 = SkyCoord('16 52 39.99 -19 09 40.3', unit=(u.hourangle, u.deg)) c3 = SkyCoord('16 52 39.49 -19 09 32.458', unit=(u.hourangle, u.deg)) plt.ion() ax, hdu = plot_finder_image(c, fov_radius=1 * u.arcmin) # Pot main ax.scatter(c.ra.deg - 0.0005, c.dec.deg, transform=ax.get_transform('fk5'), s=2000, edgecolor='red', facecolor='none') ax.text(c.ra.deg - 100, c.dec.deg + 120, 'J1652$-$13\n$G$ = 12.4132') ax.scatter(c1.ra.deg - 0.0005, c1.dec.deg, transform=ax.get_transform('fk5'), s=1000, edgecolor='red', facecolor='none') ax.text(c.ra.deg - 180, c.dec.deg + 115, '$G$ = 15.7474')
imcordy = (decW - leftdecW) / degpix - 0.5 graW = guideW[:, 0] gdecW = guideW[:, 1] gimcordx = (graW - leftraW) / degpix - 0.5 gimcordy = (gdecW - leftdecW) / degpix - 0.5 # print(gimcordx) # print(graW-leftraW) # print(gdecW-leftdecW) #print(mainW[4,0]) #print(mainW[4,1]) plt.figure() ax, hdu = plot_finder_image(center, fov_radius=fov * u.deg) point = patches.Circle((imcordx[0], imcordy[0]), radius=3, color='red') point1 = patches.Circle((imcordx[1], imcordy[1]), radius=3, color='blue') point2 = patches.Circle((imcordx[2], imcordy[2]), radius=3, color='black') point3 = patches.Circle((imcordx[3], imcordy[3]), radius=3, color='green') gpoint = patches.Circle((gimcordx[0], gimcordy[0]), radius=3) gpoint1 = patches.Circle((gimcordx[1], gimcordy[1]), radius=3) gpoint2 = patches.Circle((gimcordx[2], gimcordy[2]), radius=3) gpoint3 = patches.Circle((gimcordx[3], gimcordy[3]), radius=3) ax.add_patch(point) ax.add_patch(point1) ax.add_patch(point2) ax.add_patch(point3)
if "__main__": args = cli() fov = args.fov try: targets = np.genfromtxt(args.file,dtype=None) except: targets = np.atleast_2d(np.array([args.file, "0:0:0", "0:0:0"])) for t in targets: objname = t[0].upper() # From coordinates if args.COORD: ra,dec = t[1], t[2] try: radeg = ra.astype('float') decdeg = dec.astype('float') except: radeg,decdeg = sexa2deg([ra,dec]) mycoord = SkyCoord(ra=radeg*u.deg,dec=decdeg*u.deg,frame='fk5') object = FixedTarget(coord=mycoord, name=t[0].upper()) # From object name else: object = FixedTarget.from_name(objname) ax, hdu = plot_finder_image(object,reticle=True,fov_radius=fov*u.arcmin) plt.savefig(objname+'.jpg') plt.close()
def plot_gaia_sources_on_survey( tpf, target_gaiaid, gaia_sources=None, fov_rad=None, depth=0.0, kmax=1.0, sap_mask="pipeline", survey="DSS2 Red", ax=None, color_aper="C0", # pink figsize=None, invert_xaxis=False, invert_yaxis=False, pix_scale=TESS_pix_scale, verbose=True, **mask_kwargs, ): """Plot (superpose) Gaia sources on archival image Parameters ---------- target_coord : astropy.coordinates target coordinate gaia_sources : pd.DataFrame gaia sources table fov_rad : astropy.unit FOV radius survey : str image survey; see from astroquery.skyview import SkyView; SkyView.list_surveys() verbose : bool print texts ax : axis subplot axis color_aper : str aperture outline color (default=C6) kwargs : dict keyword arguments for aper_radius, percentile Returns ------- ax : axis subplot axis TODO: correct for proper motion difference between survey image and gaia DR2 positions """ if verbose: print("Plotting nearby gaia sources on survey image.") assert target_gaiaid is not None ny, nx = tpf.flux.shape[1:] if fov_rad is None: diag = np.sqrt(nx**2 + ny**2) fov_rad = (0.4 * diag * pix_scale).to(u.arcmin).round(0) target_coord = SkyCoord(ra=tpf.ra * u.deg, dec=tpf.dec * u.deg) if gaia_sources is None: print( "Querying Gaia sometimes hangs. Provide `gaia_sources` if you can." ) gaia_sources = Catalogs.query_region(target_coord, radius=fov_rad, catalog="Gaia", version=2).to_pandas() assert len(gaia_sources) > 1, "gaia_sources contains single entry" # make aperture mask mask = parse_aperture_mask(tpf, sap_mask=sap_mask, **mask_kwargs) maskhdr = tpf.hdu[2].header # make aperture mask outline contour = np.zeros((ny, nx)) contour[np.where(mask)] = 1 contour = np.lib.pad(contour, 1, PadWithZeros) highres = zoom(contour, 100, order=0, mode="nearest") extent = np.array([-1, nx, -1, ny]) if verbose: print( f"Querying {survey} ({fov_rad:.2f} x {fov_rad:.2f}) archival image" ) # -----------create figure---------------# if ax is None: # get img hdu for subplot projection try: hdu = SkyView.get_images( position=target_coord.icrs.to_string(), coordinates="icrs", survey=survey, radius=fov_rad, grid=False, )[0][0] except Exception: errmsg = "survey image not available" raise FileNotFoundError(errmsg) fig = pl.figure(figsize=figsize) # define scaling in projection ax = fig.add_subplot(111, projection=WCS(hdu.header)) # plot survey img if str(target_coord.distance) == "nan": target_coord = SkyCoord(ra=target_coord.ra, dec=target_coord.dec) nax, hdu = plot_finder_image(target_coord, ax=ax, fov_radius=fov_rad, survey=survey, reticle=False) imgwcs = WCS(hdu.header) mx, my = hdu.data.shape # plot mask _ = ax.contour( highres, levels=[0.5], extent=extent, origin="lower", linewidths=[3], colors=color_aper, transform=ax.get_transform(WCS(maskhdr)), ) idx = gaia_sources["source_id"].astype(int).isin([target_gaiaid]) target_gmag = gaia_sources.loc[idx, "phot_g_mean_mag"].values[0] for index, row in gaia_sources.iterrows(): marker, s = "o", 100 r, d, mag, id = row[["ra", "dec", "phot_g_mean_mag", "source_id"]] pix = imgwcs.all_world2pix(np.c_[r, d], 1)[0] if int(id) != int(target_gaiaid): gamma = 1 + 10**(0.4 * (mag - target_gmag)) if depth > kmax / gamma: # too deep to have originated from secondary star edgecolor = "C1" alpha = 1 # 0.5 else: # possible NEBs edgecolor = "C3" alpha = 1 else: s = 200 edgecolor = "C2" marker = "s" alpha = 1 nax.scatter( pix[0], pix[1], marker=marker, s=s, edgecolor=edgecolor, alpha=alpha, facecolor="none", ) # orient such that north is up; left is east if invert_yaxis: # ax.invert_yaxis() raise NotImplementedError() if invert_xaxis: # ax.invert_xaxis() raise NotImplementedError() if hasattr(ax, "coords"): ax.coords[0].set_major_formatter("dd:mm") ax.coords[1].set_major_formatter("dd:mm") # set img limits pl.setp( nax, xlim=(0, mx), ylim=(0, my), title="{0} ({1:.2f}' x {1:.2f}')".format(survey, fov_rad.value), ) return ax