def _get_projection(self): if self.hdu is None: try: hdu = SkyView.get_images(position=self.coord, coordinates='icrs', survey=self.survey, radius=self.radius * u.arcsec, grid=self.grid)[0][0] wcs = WCS(hdu.header) self.vlim = PercentileInterval(99.).get_limits(hdu.data) except (IndexError, HTTPError): hdu = SkyView.get_images(position=self.coord, coordinates='icrs', survey=self.survey, radius=self.radius * u.arcsec - 1 * u.arcsec, grid=self.grid)[0][0] wcs = WCS(hdu.header) self.vlim = PercentileInterval(99.).get_limits(hdu.data) else: wcs = WCS(self.hdu.header) self.vlim = PercentileInterval(99.).get_limits(self.hdu.data) return wcs
def get_images(self, pos, radius, surveys, savefits=True, dirname='images/'): if not os.path.exists(dirname): os.makedirs(dirname) images = SkyView.get_images(position=pos, coordinates='icrs', survey=surveys, radius=radius*u.arcmin, pixels=1000) if savefits: for i, s in enumerate(surveys): images[i].writeto(dirname+s+'.fits', clobber=True) # overwrite existing file else: images = [] for i, s in enumerate(surveys): filename = dirname+s+'.fits' if not os.path.isfile(filename): img = SkyView.get_images(position=pos, coordinates='icrs', survey=[s], radius=radius*u.arcmin, pixels=1000) images.append(img[0]) if savefits: images[i].writeto(filename, clobber=True) # overwrite existing file else: images.append(fits.open(filename)) return images
def get_source_images(target, survey_list, pixels=512, folder='./', verbose=False): ''' Download postagestamp images of targets from SkyView :param target: An astropy table row containing the name and coordinates of the target :param survey_list: A list of strings containing survey names :param pixels: An integer, the dimensions of the requested (square) image :param folder: A string, the location where downloaded images should be saved :param verbose: A boolean, determine whether or not to print errors ''' paths = SkyView.get_image_list( position='%s, %s' % (target['ra'], target['dec']), survey=survey_list ) # can't use get_image() because it throws errors when files don't exist for survey, path in zip(survey_list, paths): filepath = "%s%s_%s.fits" % (folder, target['full_name'], survey) filepath = filepath.replace(' ', '_') try: urllib.request.urlretrieve(path, filepath) except urllib.error.HTTPError: if verbose: print("%s not in %s" % (target['full_name'], survey)) pass
def get_nvss(ra, dec, size=1000, overwrite=True): # uses skyview # if this is failing with 404 not found # rm ~/.astropy/cache/astroquery/SkyView/* print('importing skyview ... this could hang...') from astroquery.skyview import SkyView coords = coord.SkyCoord(ra, dec, unit=(u.deg, u.deg)) filename = 'NVSS-' + coords.to_string('hmsdms').replace(' ', '') + '.fits' if os.path.isfile(filename): if overwrite: print('removing ' + filename) os.system('rm ' + filename) else: return filename paths = SkyView.get_images(position=coords.to_string('hmsdms'), survey='NVSS', width=size * u.arcsec) hdu = paths[0] hdu[0].header['BMAJ'] = 45.0 / 3600.0 hdu[0].header['BMIN'] = 45.0 / 3600.0 hdu[0].header['BPA'] = 0 hdu[0].header['RESTFREQ'] = 1.4e9 hdu.writeto(filename) return filename
def plot_sky(axes, EPIC): # Get K2 image tpf_file = "/home/stephanie/data/c5_tpf/ktwo{0}-c05_lpd-targ.fits.gz".format( EPIC) tabl, times, pixels, maskmap, maskheader, kpmag = tpf_io.get_data(tpf_file) coadd = np.sum(pixels, axis=0) pos = coords.SkyCoord(maskheader["RA_OBJ"], maskheader["DEC_OBJ"], unit=u.deg) with fits.open(tpf_file) as hdu2: dataheader = hdu2[1].header # keysel = np.empty(13, "S6") # keysel[:] = "binary" w2 = extract_wcs(dataheader) # Get 2MASS K image twomass_images, pix_2mass, hdr_2mass = None, None, None try: twomass_images = SkyView.get_images(position=pos, survey=['DSS2 Red'], pixels=500) # print(twomass_images) if len(twomass_images) > 0: pix_2mass = twomass_images[0][0].data hdr_2mass = twomass_images[0][0].header except astroquery.exceptions.TimeoutError, urllib.HTTPError: pix_2mass, hdr_2mass = None, None
def get_skyview(survey_name, ra, dec, size): from astroquery.skyview import SkyView hdu = SkyView.get_images("{0},{1}".format(ra, dec), radius=size * u.arcsecond, survey=survey_name)[0] image_header = hdu[0].header return (hdu)
def __init__(self, coord, radius, mission, **kwargs): surveycoord.SurveyCoord.__init__(self, coord, radius, **kwargs) # self.survey = None self.mission = mission # Instantiate astroquery object self.skyview = SkyView()
def create_chart(self, path=None): """ Creates the finding chart :param path: Path the save place of the finding chart :type path: str :return: """ paths = SkyView.get_images(position=self.coord, survey=self.config.survey, width=self.config.width, height=self.config.height, pixels=self.config.pixels)[0][0] wcs = WCS(paths.header) shape = paths.shape fig = pl.figure(num=0) fig.clf() sp = fig.add_subplot(111, projection=wcs) self.__image__(paths.data.copy(), sp) # cross around the target if self.config.cross: center = wcs.all_world2pix(self.coord.ra.degree, self.coord.dec.degree, 0) self.__cross__(sp, shape, center) self.__arrows__(sp, shape) self.__scale__(sp, wcs) if path is not None: fig.savefig(path)
def download_data(pos, survey, filters, pxl): """Proxy to astroquery SkyviewService. This functions is mostly for internal use. Parameters ---------- pos: SkyCoord Determines the center of the field to be retrieved. survey: str The data to download the survey. filters: list Specific astronomical filters of the data. pxl: Selects the pixel dimensions of the image to be produced. Returns ------- A list of `~astropy.io.fits.HDUList` objects. """ path = SkyView.get_images( position=pos, survey=survey + str(filters), radius=2 * apu.arcmin, pixels=(pxl, pxl), coordinates=DOWNLOAD_COORDINATE_SYSTEM, show_progress=DOWNLOAD_SHOW_PROGRESS, ) return path
def call_skyview_simple(survey, source_name, fov=1): """Call Skyview to download data from a survey based on input parameters Args: survey (str): name of survey, from https://skyview.gsfc.nasa.gov/current/cgi/survey.pl source (str): name of astronomical source fov (float): FOV in degrees Examples: >>> call_skyview('DSS', 'M31', 2.) >>> call_skyview('NVSS', NGC6670, 0.5) """ coords = coords_from_name(source_name) outname = f'{source_name}_{survey}_{fov}d.fits' images = SkyView.get_images(coords, survey, coordinates='J2000', projection='Car', pixels=500, height=fov * u.deg, width=fov * u.deg) fitsname = f'images/{source_name}_{survey}_{fov}d.fits' try: images[0][0].writeto(fitsname, overwrite=True) except astropy.io.fits.verify.VerifyError: print('Data not available') pass return fitsname
def image(ra, dec, sur): from astropy import coordinates, units as u, wcs from astroquery.skyview import SkyView from astropy.io import fits from astropy.io.fits import getdata import aplpy from matplotlib.pyplot import * import numpy as np from matplotlib import gridspec import matplotlib.pyplot as plt center = coordinates.SkyCoord(str(ra) + ' ' + str(dec), frame='icrs', unit='deg') rad = 60 * u.arcsecond images = SkyView.get_images(position=center, survey=[sur], radius=rad) x = np.zeros(1) y = np.zeros(1) r = np.zeros(1) x[0] = (ra) y[0] = (dec) r[0] = (0.00139) fig = aplpy.FITSFigure(images[0]) fig.show_colorscale(cmap='gist_heat') fig.show_circles(x, y, r, color='g', alpha=1, lw=4) fig.recenter(ra, dec, radius=0.00416) fig.axis_labels.hide() fig.tick_labels.hide() fig.savefig(sur + '.png')
def _get_skyview_cutout(self): """Fetch cutout data via SkyView API.""" sv = SkyView() path = cutout_cache + self.survey + '/{:.3f}arcmin_{:.3f}_{:.3f}.fits' path = path.format(self.radius * 60, self.ra, self.dec) progress = self.kwargs.get('progress', False) if not os.path.exists(path): skyview_key = SURVEYS.loc[self.survey].sv try: hdul = sv.get_images(position=self.position, survey=[skyview_key], radius=self.radius * u.deg, show_progress=progress)[0][0] except IndexError: raise FITSException('Skyview image list returned empty.') except ValueError: raise FITSException( f'{self.survey} is not a valid SkyView survey.') except HTTPError: raise FITSException('No response from Skyview server.') with open(path, 'wb') as f: hdul.writeto(f) with fits.open(path) as hdul: self.header, self.data = hdul[0].header, hdul[0].data self.wcs = WCS(self.header, naxis=2) try: self.mjd = Time(self.header['DATE']).mjd except KeyError: try: self.epoch = self.kwargs.get('epoch') msg = "Could not detect epoch, PM correction disabled." assert self.epoch is not None, msg self.mjd = self.epoch if self.epoch > 3000 else Time( self.epoch, format='decimalyear').mjd except AssertionError as e: if self.kwargs.get('pm'): self.logger.warning(e) self.mjd = None self.data *= 1000
def genSimulation(configpath, star, orders = [-1,0,1], seeing = 1): """"Generates the arguments for plot_all to simulate the spectrogram of star through a slitless spectrogram which properties are contained in the configuration file. Parameters ---------- configpath : string path to the slitless spectrograph configutation file star : string the studied star identifier orders : list of integers the list of orders to represent. seeing : float the wanted seeing for the spectrogram in arcseconds, 1 arcsec by default Returns ------- stars : list a list of star_class objects, containing the stars to take into account with their position on the captor, img : 2d ndarray a background image for the stars, angle : float the angle of dispersion used for the spectrogram, config : configuration the configuration used for the spectrogram, LTh : list a list of angles for Overlap_list, Overlap_list : list the list of the total overlap caused by surrounding stars on the studied star spectrum """ config = configuration(configpath) imsize, pix2ars = config.ccd_imsize, config.pixel2arcsec query = customSimbad.query_object(star) ra0, dec0, mag0 = query["RA_d"][0], query["DEC_d"][0], query["FLUX_V"][0] r = 2*imsize*config.pixel2arcsec/3600 maglim = mag0 + 7.5 job = Gaia.launch_job_async("SELECT ra, dec, DISTANCE(POINT('ICRS', ra, dec),POINT('ICRS', {0}, {1})) AS dist, phot_g_mean_mag AS flux FROM gaiadr2.gaia_source WHERE CONTAINS(POINT('ICRS', ra, dec),CIRCLE('ICRS', {0}, {1}, {2})) = 1 AND phot_g_mean_mag < {3} ORDER BY dist".format(ra0, dec0, r, maglim)) result = job.get_results() ra0, dec0 = result['ra'][0], result['dec'][0] config.wcs.wcs.crval = [ra0,dec0] cra, cdec = config.wcs.wcs_pix2world([[imsize/2, imsize/2]], 0)[0] stars = list_stars(result,config,maglim,seeing, orders) angle, LTh, Overlap_list = best_angle(stars, config) for star in stars : star.rotate_orders(angle, use_radians = True) LTh = LTh*180/np.pi img = SkyView.get_images(position = '{}, {}'.format(cra, cdec), survey = 'DSS', width = imsize*pix2ars*u.arcsec, height = imsize*pix2ars*u.arcsec)[0][0].data return (stars, img, angle, config, LTh, Overlap_list)
def show_guide_camera(npointing,south_camera=True,offset_ra=0,offset_dec=0,plotsingle=True): ''' offset_ra in arcsec offset_dec in arcsec camera = 0 for south camera = 1 for north ''' i = npointing-1 if south_camera: # South camera delta_ra = -25./3600 delta_dec = -2410./3600 width_ra = 3.3/60. width_dec = 2.2/60. outputfile=outfile_prefix+'Pointing%02d-guiding-south.png'%(npointing) mytitle = "Pointing %02d South Camera (3.3'x2.2'): NSAID %i"%((i+1),pointing_id[i]) else: # offsets and dimensions of # North camera delta_ra = 0 delta_dec = 2610./3600 width_ra = 3.3/60. width_dec = 2.2/60. outputfile=outfile_prefix+'Pointing%02d-guiding-north.png'%(npointing) mytitle = "Pointing %02d North Camera (3.3'x2.2'): NSAID %i"%((i+1),pointing_id[i]) center_ra = pointing_ra[i]+offset_ra/3600. + delta_ra center_dec = pointing_dec[i] + offset_dec/3600. + delta_dec delta_image = width_ra if plotsingle: plt.figure(figsize=(6,6)) ax = plt.gca() pos = coords.SkyCoord(center_ra,center_dec,frame='icrs',unit='degree') xout = SkyView.get_images(pos,survey=['DSS'],height=2*delta_image*u.degree,width=2.*delta_image*u.degree) b=xout[0][0] ax.imshow(xout[0][0].data,interpolation='none',aspect='equal',cmap='gray_r',extent=[b.header['CRVAL1']-(b.header['NAXIS1']-b.header['CRPIX1'])*b.header['CDELT1'], b.header['CRVAL1']+(b.header['NAXIS1']-b.header['CRPIX1'])*b.header['CDELT1'], b.header['CRVAL2']+(b.header['NAXIS2']-b.header['CRPIX2'])*b.header['CDELT2'], b.header['CRVAL2']-(b.header['NAXIS2']-b.header['CRPIX2'])*b.header['CDELT2']]) rect= plt.Rectangle((center_ra - 0.5*width_ra,center_dec - 0.5*width_dec), width_ra, width_dec,fill=False, color='k') plt.gca().add_artist(rect) if plotsingle: plt.title(mytitle) else: if south_camera: plt.title("South Camera (3.3'x2.2')") else: plt.title("North Camera (3.3'x2.2')") plt.xlabel('RA (deg)') plt.ylabel('DEC (deg)') plt.gca().invert_yaxis() if plotsingle: plt.savefig(outputfile)
def main(): ap = argparse.ArgumentParser(description='Get contextual imagery') ap.add_argument('--size', type=float, default=1000., help='The size of the images to fetch, in arcseconds.') ap.add_argument('surveys', help='Comma-separated list of surveys to query.') ap.add_argument( 'outdir', help='The directory in which to save the downloaded FITS files.') settings = ap.parse_args() surveys = settings.surveys.split(',') sv = SkyView() for name, ra_deg, dec_deg in TARGETS: for survey in surveys: print(name, survey, '...') hdulists = sv.get_images( position=f'{ra_deg} {dec_deg}', survey=survey, projection='Tan', width=settings.size * u.arcsec, height=settings.size * u.arcsec, #pixels = 300 # which produces JPEG images of 40 KB #pixels = 1000 # which produces JPEG images of 300 KB pixels= 2000 #which produces JPEG images of 300 KB to 1.2 MB depending on the richness of the region ) if len(hdulists) == 0: print(f'warning: no images for {name}', file=sys.stderr) continue if len(hdulists) > 1: print(f'warning: multiple images for {name}', file=sys.stderr) hdulists[0].writeto( os.path.join(settings.outdir, f'{name}_{survey}.fits'))
def get_surveys(self, survey_list, field_side_length): """ Center: skycoord coordinate+ survey_list: list or iterable consisting of strings in the form of SkyView surveynames. Full description of all the surveys availible can be found here: https://skyview.gsfc.nasa.gov/current/cgi/survey.plhttps://skyview.gsfc.nasa.gov/current/cgi/survey.pl Some surveynames are: "2MASS-J" "2MASS-H" "2MASS-K" "WISE 3.4" "WISE 4.6" "WISE 12" "WISE 22" "DSS" "SDSSg" "SDSSi" "SDSSr" "SDSSu" "SDSSz" Returns a list of astropy.fits.HDUList objects. All elements of this list have an attribute "".data" that can be passed to plt.imshow(). """ print("Fetching surveys:") print(survey_list) print("With radius:") print(field_side_length) center = self.ra + self.dec return (SkyView.get_images(position=center, survey=survey_list, radius=(field_side_length)))
def get_skyview(survey_name,ra,dec,size): from astroquery.skyview import SkyView pstg_stamp=SkyView.get_images("{0},{1}".format(ra,dec),radius=size*u.arcsecond,survey=survey_name)[0] image_header=pstg_stamp[0].header # print(image_header) if survey_name == 'NVSS': image_header['BMAJ']=0.0125 image_header['BMIN']=0.0125 image_header['BPA']=0 # pstg_stamp.writeto(path_to_save_dir+viewer_surveys()[i]+'_{0}.fits'.format(size),overwrite=True) return(pstg_stamp)
def get_dss_image(shape, wcs, survey='DSS'): '''Use astroquery SkyView to get a DSS image projected to wcs and shape.''' shape = np.array(shape) platescale = proj_plane_pixel_scales(wcs) ra, dec = wcs.wcs_pix2world(*(shape / 2), 0) sk = SkyCoord(ra, dec, unit=('degree', 'degree'), frame='icrs') im = SkyView.get_images(sk, survey='DSS', coordinates='ICRS', width=shape[0] * platescale[0] * u.degree, height=shape[1] * platescale[1] * u.degree)[0] im = reproject_interp(im[0], output_projection=wcs, shape_out=shape)[0] return im
def get_sdss_sky_image(img_center, fov=9 * u.deg, n_pix=1000): ''' A small helper method which uses astroquery to get an image from the sdss. This requires internet access and fails pretty often due to http timeouts. ''' hdu = SkyView.get_images(position=img_center, pixels=n_pix, survey=['DSS'], width=fov, height=fov)[0][0] img = hdu.data wcs = WCS(hdu.header) return img, wcs
def get_nvss(ra, dec, size=1000): # uses skyview coords = coord.SkyCoord(ra, dec, unit=(u.deg, u.deg)) paths = SkyView.get_images(position=coords.to_string('hmsdms'), survey='NVSS', width=size * u.arcsec) hdu = paths[0] hdu[0].header['BMAJ'] = 45.0 / 3600.0 hdu[0].header['BMIN'] = 45.0 / 3600.0 hdu[0].header['BPA'] = 0 hdu[0].header['RESTFREQ'] = 1.4e9 filename = 'NVSS-' + coords.to_string('hmsdms').replace(' ', '') + '.fits' hdu.writeto(filename) return filename
def download_image(coords, surveys, name='field', radius=None, width=None, height=None): print('Getting fitsfiles') fitsfiles = SkyView.get_images(position=coords, survey=surveys, radius=radius, width=width, height=height) os.system('mkdir catalogs') for fitsfile, survey in zip(fitsfiles, surveys): print('Writing to file: {0} ...'.format(survey), end='') filename = f'./catalogs/{name}_{survey}.fits'.replace(' ', '_') try: fitsfile[0].writeto(filename, overwrite=True) print('...Done') except astropy.io.fits.verify.VerifyError: print('...Failed')
def getSVImg(SC_ObjPos, SkyViewSurvey): """ Input: a SkyCoord Position Vector and a Survey Type that is Compatable with NASA SkyView Output: A Numpy Pixel Array and Header Array """ img_survey, pix_survey, hdr_survey = None, None, None try: img_survey = SkyView.get_images(position=SC_ObjPos, survey=[SkyViewSurvey], coordinates="J2000", pixels=30) if len(img_survey) > 0: pix_survey = img_survey[0][0].data hdr_survey = img_survey[0][0].header except astroquery.exceptions.TimeoutError, urllib.HTTPError: pix_survey, hdr_survey = None, None
def Planck_SkyView(name, ra, dec, width, band, bands_dict, temp_dir): print('Querying for Planck ' + bands_dict[band]['wavelength'] + 'um data for ' + name + ' from NASA SkyView') position_string = str(ra) + ' ' + str(dec) query_success = None pix_size = bands_dict[band]['pix_size'] # Add tiny permutation to width to stop SkyView flailing over repeat queries width *= 1.0 + (0.01 * (np.random.rand() - 0.5)) # Perform query while query_success == None: try: query_filename = os.path.join( temp_dir, name + '_Planck_' + bands_dict[band]['wavelength'] + '.fits') query_url = SkyView.get_image_list( position_string, bands_dict[band]['band_name'], deedger='_skip_', pixels=int((width * 3600.0) / pix_size), radius=astropy.units.Quantity(width, unit='deg')) if len(query_url) != 1: pdb.set_trace() query_success = True except: query_success = False # Retrieve and verify data if query_success: print('Retrieving identified Planck ' + bands_dict[band]['wavelength'] + 'um data for ' + name) Planck_wget(str(query_url[0]), query_filename) try: astropy.io.fits.info(query_filename) except Exception: query_success = False pdb.set_trace() # If no data available, generate null file and report failure if not query_success: os.system('touch ' + os.path.join( temp_dir, '.' + name + '_Planck_' + bands_dict[band]['wavelength'] + '.null')) print('No ' + band + ' data for ' + name)
def get_image_index(): cache = get_cache_dir() ast_data = os.path.dirname(_solve_field) ast_data = os.path.dirname(ast_data) ast_data = os.path.join(ast_data, 'data') os.makedirs(ast_data, exist_ok=True) index = 'index-4107.fits' # index-4202-28.fits' d = 'http://broiler.astrometry.net/~dstn/4100/' + index f = os.path.join(ast_data, index) if not os.path.isfile(f): request.urlretrieve(d, f) # nosec name = os.path.join(cache, 'm20_dss.fits') if not os.path.isfile(name): s = SkyView.get_images('M20', radius=Angle('60arcmin'), pixels=2048, survey='DSS') s[0][0].writeto(name) return name, f
def get_asset_data(self, path: str) -> bytes: """ Return data for a non-collection asset at the given path :param path: asset path; must identify a non-collection asset :return: asset data """ survey, position, width, height = self._get_asset_params(path) try: res = SkyView.get_images( position, **self._get_query_args(survey, width, height)) except Exception as e: raise AssetNotFoundError(path=path, reason=str(e)) if not res: raise AssetNotFoundError(path=path, reason='No images returned by SkyView') buf = BytesIO() res[0].writeto(buf, output_verify='silentfix+ignore') return buf.getvalue()
def Planck_SkyView(name, ra, dec, width, band, bands_dict, out_dir): print('Retrieving ' + band + ' data for ' + name + ' from NASA SkyView') position_string = str(ra) + ' ' + str(dec) query_success = None query_reattempt = False pix_size = bands_dict[band]['pix_size'] # Perform query while query_success == None: try: query_filename = os.path.join( out_dir, name + '_Planck_' + bands_dict[band]['wavelength'] + '.fits') query_url = SkyView.get_image_list( position_string, bands_dict[band]['band_name'], deedger='_skip_', pixels=str(int((width * 3600.0) / pix_size)), radius=astropy.units.Quantity(width, unit='deg')) if len(query_url) != 1: pdb.set_trace() query_success = True except: query_success = False # Retrieve and verify data if query_success: print('Retrieving identified Planck ' + band + ' data for ' + name) Planck_wget(str(query_url[0]), query_filename) try: astropy.io.fits.info(query_filename) except Exception as exception: if exception.message == 'Empty or corrupt FITS file': pdb.set_trace() else: pdb.set_trace() # Report failure if not query_success: print('No Planck ' + band + ' data for ' + name) pdb.set_trace()
def get_url(coords, surveys, radius=None, width=None, height=None): print('Reading urls') urls = [] valid_surveys = [] missing_surveys = [] for survey in surveys: url = SkyView.get_image_list(position=coords, survey=survey, radius=radius, width=width, height=height) if url != []: if requests.get(url[0]).status_code != 404: urls.append(url) valid_surveys.append(survey) print('OK: ', survey) else: missing_surveys.append(survey) print('Failed: ', survey) for u,s in zip(urls, valid_surveys): print(u,s) return urls, valid_surveys, missing_surveys
def retrieve_image_SkyView(ra, dec, size, scale, logger): size_pix = min(512, int(size * 3600. / scale)) scale = size * 3600. / size_pix paths = SkyView.get_images(position='%3.5f %2.5f' % (ra, dec), survey='DSS2 Blue', coordinates='J2000', height=size * aunit.deg, width=size * aunit.deg, pixels=str(size_pix), cache=False) if paths: hdu = paths[0][0].header imarray = paths[0][0].data imarray = imarray[::-1, :] CD = numpy.matrix([[hdu['CDELT1'], 0], [0, hdu['CDELT2']]]) else: # Default to PS1 logger.warning( "Could not contact SDSS or DSS. Falling back to PS1!") return retrieve_image_PS1(ra, dec, size, scale, logger) return imarray, CD, '', 'DSS2'
def DownloadImage(RA, DEC, outputfolder): Pos = RA_convert(RA) + "," + DEC_convert(DEC) print(RA, DEC) print(Pos) img = SkyView.get_images(position=Pos, survey=['DSS2 Blue', 'DSS2 IR', 'DSS2 Red'], pixels='50,50', coordinates='J2000', grid=True, gridlabels=True) #img = SkyView.get_images(position='22:57:00,62:38:00',survey=['DSS2 Blue','DSS2 IR','DSS2 Red'],pixels='100,100',coordinates='J2000',grid=True,gridlabels=True) fig, ax = pl.subplots(ncols=3, figsize=(24, 8)) plot = ax[0].imshow(img[0][0].data, vmax=np.max(img[0][0].data) * .65, vmin=np.max(img[2][0].data) * .45) plot1 = ax[1].imshow(img[1][0].data, vmax=np.max(img[1][0].data) * .75, vmin=np.max(img[1][0].data) * .4) plot2 = ax[2].imshow(img[2][0].data, vmax=np.max(img[2][0].data) * .485, vmin=np.max(img[2][0].data) * .25) pl.savefig(outputfolder + "/SkyImage.png")
def asteroids_plot(self, image_path=None, ra=None, dec=None, odate=None, time_travel=1, radi=6, max_mag=20.0, circle_color='yellow', arrow_color='red'): """ Source plot module. @param image_path: data part of the FITS image @type image_path: numpy array @param ra: RA coordinate of target area. @type ra: str in "HH MM SS" @param dec: DEC coordinate of target area @type dec: str in "+DD MM SS" @param radi: Radius in arcmin. @type radi: float @param odate: Ephemeris date of observation in date @type odate: "2017-08-15T19:50:00.95" format in str @param time_travel: Jump into time after given date (in hour). @type time_travel: float @param max_mag: Limit magnitude to be queried object(s) @type max_mag: float @param circle_color: Color of the asteroids marks @type circle_color: str @param arrow_color: Color of the asteroids direction marks @type arrow_color: str @returns: boolean """ from .catalog import Query # filename = get_pkg_data_filename(image_path) rcParams['figure.figsize'] = [15., 12.] # rcParams.update({'font.size': 10}) if image_path: hdu = fits.open(image_path)[0] elif not image_path and ra and dec and odate: co = coordinates.SkyCoord('{0} {1}'.format(ra, dec), unit=(u.hourangle, u.deg), frame='icrs') print('Target Coordinates:', co.to_string(style='hmsdms', sep=':'), 'in {0} arcmin'.format(radi)) try: server_img = SkyView.get_images(position=co, survey=['DSS'], radius=radi * u.arcmin) hdu = server_img[0][0] except Exception as e: print("SkyView could not get the image from DSS server.") print(e) raise SystemExit wcs = WCS(hdu.header) data = hdu.data.astype(float) bkg = sep.Background(data) # bkg_image = bkg.back() # bkg_rms = bkg.rms() data_sub = data - bkg m, s = np.mean(data_sub), np.std(data_sub) ax = plt.subplot(projection=wcs) plt.imshow(data_sub, interpolation='nearest', cmap='gray', vmin=m - s, vmax=m + s, origin='lower') ax.coords.grid(True, color='white', ls='solid') ax.coords[0].set_axislabel('Galactic Longitude') ax.coords[1].set_axislabel('Galactic Latitude') overlay = ax.get_coords_overlay('icrs') overlay.grid(color='white', ls='dotted') overlay[0].set_axislabel('Right Ascension (ICRS)') overlay[1].set_axislabel('Declination (ICRS)') sb = Query() ac = AstCalc() if image_path: fo = FitsOps(image_path) if not odate: odate = fo.get_header('date-obs') else: odate = odate ra_dec = ac.center_finder(image_path, wcs_ref=True) elif not image_path and ra and dec and odate: odate = odate ra_dec = [co.ra, co.dec] request0 = sb.find_skybot_objects(odate, ra_dec[0].degree, ra_dec[1].degree, radius=radi) if request0[0]: asteroids = request0[1] elif request0[0] is False: print(request0[1]) raise SystemExit request1 = sb.find_skybot_objects(odate, ra_dec[0].degree, ra_dec[1].degree, radius=float(radi), time_travel=time_travel) if request1[0]: asteroids_after = request1[1] elif request1[0] is False: print(request1[1]) raise SystemExit for i in range(len(asteroids)): if float(asteroids['m_v'][i]) <= max_mag: c = coordinates.SkyCoord('{0} {1}'.format( asteroids['ra(h)'][i], asteroids['dec(deg)'][i]), unit=(u.hourangle, u.deg), frame='icrs') c_after = coordinates.SkyCoord('{0} {1}'.format( asteroids_after['ra(h)'][i], asteroids_after['dec(deg)'][i]), unit=(u.hourangle, u.deg), frame='icrs') r = FancyArrowPatch( (c.ra.degree, c.dec.degree), (c_after.ra.degree, c_after.dec.degree), arrowstyle='->', mutation_scale=10, transform=ax.get_transform('icrs')) p = Circle((c.ra.degree, c.dec.degree), 0.005, edgecolor=circle_color, facecolor='none', transform=ax.get_transform('icrs')) ax.text(c.ra.degree, c.dec.degree - 0.007, asteroids['name'][i], size=12, color='black', ha='center', va='center', transform=ax.get_transform('icrs')) r.set_facecolor('none') r.set_edgecolor(arrow_color) ax.add_patch(p) ax.add_patch(r) # plt.gca().invert_xaxis() plt.gca().invert_yaxis() plt.show() print(asteroids) return True
from astropy import units as u from astropy import coordinates import pylab as pl import aplpy # Retrieve OrionKL 2MASS K-band image: # In[92]: orionkl_coords = coordinates.SkyCoord.from_name('Orion KL') # In[93]: orionkl_images = SkyView.get_images(position='Orion KL', survey=['2MASS-K'], pixels=500) orionkl_images # Retrieve ALMA archive information *including* private data and non-science fields: # # In[94]: orionkl = Alma.query_region(coordinate=orionkl_coords, radius=4*u.arcmin, public=False, science=False) # In[95]: orionkl
import numpy as np from astroquery.alma import Alma from astroquery.skyview import SkyView import string from astropy import units as u from astropy.io import fits from astropy import wcs from astropy import log import pylab as pl import aplpy import pyregion # Retrieve M83 2MASS K-band image: m83_images = SkyView.get_images(position='M83', survey=['2MASS-K'], pixels=1500) # Retrieve ALMA archive information *including* private data and non-science # fields: m83 = Alma.query_object('M83', public=False, science=False) # Parse components of the ALMA data. Specifically, find the frequency support # - the frequency range covered - and convert that into a central frequency for # beam radius estimation. def parse_frequency_support(frequency_support_str): supports = frequency_support_str.split("U") freq_ranges = [(float(sup.strip('[] ').split("..")[0]), float(sup.strip('[] ') .split("..")[1] .split(', ')[0]
survey = imgparms['survey'] projection = imgparms['projection'] pixels = imgparms['pixels'] action = imgparms['action'] overwrite = imgparms['overwrite'] if action.lower() == 'download': failure_count = 0 failed_coords = [] for ii,ind in enumerate(select_ind): radec_hmsdms = coords[ind].to_string('hmsdms') outfname = outdir + '{0}_{1[0]:0d}x{1[1]:0d}.fits'.format(radec_hmsdms.replace(' ',''), pixels) if (not os.path.isfile(outfname)) or overwrite: try: paths = SkyView.get_images(radec_hmsdms, survey=survey, pixels=pixels, coordinates=coordinfo['epoch'], projection=projection) hdulist = paths[0][0] hdulist.writeto(outfname, overwrite=True, output_verify='warn') print('Successfully saved {0} [{1:0d}/{2:0d}]'.format(outfname, ii+1, select_ind.size)) except Exception as err: warnings.warn('Problem with retrieving image at {0}.\nEncountered error: {1}.\nProceeding to the next object...\n'.format(radec_hmsdms, err.message), Warning) if isinstance(err, AttributeError): # For some reason, timeouts come under Attribute Error. # There will be retries on these failures, but not others # such as pointing outside the survey area, etc. failure_count += 1 failed_coords += [radec_hmsdms] if failure_count > 0:
from astropy import coordinates, units as u, wcs from astroquery.skyview import SkyView from astroquery.vizier import Vizier import pylab as pl center = coordinates.SkyCoord.from_name('Orion KL') # Grab an image from SkyView of the Orion KL nebula region imglist = SkyView.get_images(position=center, survey='2MASS-J') # the returned value is a list of images, but there is only one img = imglist[0] # 'img' is now a fits.HDUList object; the 0th entry is the image mywcs = wcs.WCS(img[0].header) fig = pl.figure(1) fig.clf() # just in case one was open before # use astropy's wcsaxes tool to create an RA/Dec image ax = fig.add_axes([0.15, 0.1, 0.8, 0.8], projection=mywcs) ax.set_xlabel("RA") ax.set_ylabel("Dec") ax.imshow(img[0].data, cmap='gray_r', interpolation='none', origin='lower', norm=pl.matplotlib.colors.LogNorm()) # retrieve a specific table from Vizier to overplot tablelist = Vizier.query_region(center, radius=5*u.arcmin, catalog='J/ApJ/826/16/table1') # again, the result is a list of tables, so we'll get the first one
source_common_name = input('Common name of source: ') source_coordinates = get_icrs_coordinates(source_common_name) #Module for manual entry of target coordinates. if input_is_coords == 1: source_coords = input('Source coordinates as ra_deg,dec_deg: ') source_ra = float(source_coords.split(',')[0]) source_dec = float(source_coords.split(',')[1]) source_coordinates = SkyCoord(source_ra, source_dec, unit=u.deg) #Execute astroquery for the DSS image with the requested number of pixels. if input_is_coords == 1: dss_image = SkyView.get_images( position=source_coords, survey='DSS', pixels=str(dss_pixel_size) ) #Use this line for the dss query if the input is manual coor#Use this line for thedinates in decimal degrees. if input_is_name == 1: dss_image = SkyView.get_images( position=source_coordinates, survey='DSS', pixels=str(dss_pixel_size) ) #Use this line for the dss query if the input is the source's common name. dss_image_data = dss_image[0][0].data dss_pixmin = np.min(dss_image_data) dss_pixmax = np.max(dss_image_data) wcs_dss = WCS(dss_image[0][0].header) #Create the sector masks by allowing user to click the desired pixels, one sector at a time. cutlist = get_multi_cutout_lst(source_coordinates, sz=(xsize, ysize))
def plot_image(ra=None, dec=None, pos=None, **kwargs): """ Use SkyView to get a cutout image :param ra: float or string or None, right ascension (deg or hh:mm:ss) :param dec: float or string or None, declination (deg or dd:mm:ss) :param pos: string or None, Determines the center of the field to be retrieved. Both coordinates (also equatorial ones) and object names are supported. Object names are converted to coordinates via the SIMBAD or NED name resolver. See the reference for more info on the supported syntax for coordinates. :param kwargs: see below kwargs are as follows - coords Choose among common equatorial, galactic and ecliptic coordinate systems ("J2000", "B1950", "Galactic", "E2000", "ICRS") or pass a custom string. - survey string, surveys used in SkyView.get_images define survey (can find info in SkyView.list_surveys()) e.g.: SDSSg, SDSSi, SDSSr, SDSSu, SDSSz, 2MASS-J, 2MASS-H, 2MASS-K, UKIDSS-Y, UKIDSS-J, UKIDSS-H, UKIDSS-K, WISE 3.4, WISE 4.6, WISE 12, WISE 22 if colour kwarg is True this is a list of three strings and is from red --> blue i.e. ['WISE 12', 'WISE 4.6', 'WISE 3.4'] - radius float, half width of image - pixels int, size of the image produced in pixels (for x and y) - colour bool, whether to plot rgb or not, default=False - cmap string, matplotlib colormap indicator (used if not rgb), default='gist_gray' - stretches tuple, defines the rgb stretches to use on rgb plot [stretch in r, stretch in g, stretch in b] default is ['log', 'log', 'log'] can have: 'linear', 'log', 'sqrt', 'arcsinh', 'power' - gridc string, colour of the grid - gridl string, linestyle of the grid :return: """ # load params from kwargs coords = kwargs.get('coords', 'J2000') s = kwargs.get('survey', '2MASS-J') radius = kwargs.get('radius', 1.0 * u.deg) pixels = kwargs.get('pixels', 1024) colour = kwargs.get('colour', False) cmap = kwargs.get('cmap', 'gist_gray') stretches = kwargs.get('stretches', ('log', 'log', 'log')) gridc = kwargs.get('gridc', '0.75') gridl = kwargs.get('gridl', '--') # get position as ra dec string if ra is not None and dec is not None: pos = '{0} {1}'.format(ra, dec) elif pos is not None: pos = pos else: raise Exception('Error need RA, Dec or Pos to get image') # download images giargs = dict(position=pos, survey=s, radius=radius, pixels=pixels, coordinates=coords) images = SkyView.get_images(**giargs) # plot aplpy FITS figure apx = aplpy.FITSFigure(images[0][0]) # if colour expect 3 surveys and make an rgb plot if colour: files = [] # loops round each image for i, j in enumerate(images): # defines a tmp filename for each iamge fname = '{0}.fits'.format(i) # writes fits to file j[0].writeto(fname, clobber=True) # appends filename to file list files.append(fname) # add rgb image to file list files.append('rgb.png') # create rgb image rgbargs = dict(zip(['stretch_r', 'stretch_g', 'stretch_b'], stretches)) aplpy.make_rgb_image(files[:3], files[3], **rgbargs) # show rgb plot on top apx.show_rgb('rgb.png') for fn in files: os.remove(fn) # if not colour just show the colour scale else: apx.show_colorscale(cmap=cmap) # add grid apx.add_grid() apx.grid.set_color(gridc) apx.grid.set_linestyle(gridl) # return aplpy figure return apx
def plot_finder_image(target, survey='DSS', fov_radius=10*u.arcmin, log=False, ax=None, grid=False, reticle=False, style_kwargs=None, reticle_style_kwargs=None): """ Plot survey image centered on ``target``. Survey images are retrieved from NASA Goddard's SkyView service via `~astroquery.skyview.SkyView`, and plotted using WCSAxes. If a `~matplotlib.axes.Axes` object already exists, plots the finder image on top. Otherwise, creates a new `~matplotlib.axes.Axes` object with the finder image. Parameters ---------- target : `~astroplan.FixedTarget`, `~astropy.coordinates.SkyCoord` Coordinates of celestial object survey : string Name of survey to retrieve image from. For dictionary of available surveys, use `from astroquery.skyview import SkyView; print(SkyView.survey_dict)`. Defaults to `'DSS'`, the Digital Sky Survey. fov_radius : `~astropy.units.Quantity` Radius of field of view of retrieved image. Defaults to 10 arcmin. log : bool, optional Take the natural logarithm of the FITS image if `True`. False by default. ax : `~matplotlib.axes.Axes` or None, optional. The `~matplotlib.axes.Axes` object to be drawn on. If None, uses the current `~matplotlib.axes.Axes`. grid : bool, optional. Grid is drawn if `True`. `False` by default. reticle : bool, optional Draw reticle on the center of the FOV if `True`. Default is `False`. style_kwargs : dict or `None`, optional. A dictionary of keywords passed into `~matplotlib.pyplot.imshow` to set plotting styles. reticle_style_kwargs : dict or `None`, optional A dictionary of keywords passed into `~matplotlib.pyplot.axvline` and `~matplotlib.pyplot.axhline` to set reticle style. Returns ------- ax : `~matplotlib.axes.Axes` Matplotlib axes with survey image centered on ``target`` hdu : `~astropy.io.fits.PrimaryHDU` FITS HDU of the retrieved image """ import matplotlib.pyplot as plt from astroquery.skyview import SkyView coord = target if not hasattr(target, 'coord') else target.coord position = coord.icrs coordinates = 'icrs' target_name = None if isinstance(target, SkyCoord) else target.name hdu = SkyView.get_images(position=position, coordinates=coordinates, survey=survey, radius=fov_radius, grid=grid)[0][0] wcs = WCS(hdu.header) # Set up axes & plot styles if needed. if ax is None: ax = plt.gca(projection=wcs) if style_kwargs is None: style_kwargs = {} style_kwargs = dict(style_kwargs) style_kwargs.setdefault('cmap', 'Greys') style_kwargs.setdefault('origin', 'lower') if log: image_data = np.log(hdu.data) else: image_data = hdu.data ax.imshow(image_data, **style_kwargs) # Draw reticle if reticle: pixel_width = image_data.shape[0] inner, outer = 0.03, 0.08 if reticle_style_kwargs is None: reticle_style_kwargs = {} reticle_style_kwargs.setdefault('linewidth', 2) reticle_style_kwargs.setdefault('color', 'm') ax.axvline(x=0.5*pixel_width, ymin=0.5+inner, ymax=0.5+outer, **reticle_style_kwargs) ax.axvline(x=0.5*pixel_width, ymin=0.5-inner, ymax=0.5-outer, **reticle_style_kwargs) ax.axhline(y=0.5*pixel_width, xmin=0.5+inner, xmax=0.5+outer, **reticle_style_kwargs) ax.axhline(y=0.5*pixel_width, xmin=0.5-inner, xmax=0.5-outer, **reticle_style_kwargs) # Labels, title, grid ax.set(xlabel='RA', ylabel='DEC') if target_name is not None: ax.set_title(target_name) ax.grid(grid) # Redraw the figure for interactive sessions. ax.figure.canvas.draw() return ax, hdu
def finding_charts(target, observer, start, surveys=['SDSSr', 'DSS Red', 'DSS'], text=None, size=15, step=1, lstep=6, number=25, lformat='%H:%M', alpha=0.5, lalpha=1, **kwargs): """Generate finding charts for a moving target. The downloaded images are saved as gzipped FITS with a name based on the ephemeris position. If an image has already been downloaded for an ephemeris position, then it will read the file instead of fetching a new one. The finding charts are saved with the RA, Dec, and time of the center ephemeris point. Parameters ---------- target : string Target designation. observer : string Observer location. date : array-like of string Start date for the finding charts. Processed with `astropy.time.Time`. surveys : array-like, optional List of surveys to display in order of preference. See `astroquery.skyview`. size : int, optional Field of view in arcmin. text : string, optiona Additional text to add to the upper-left corner of the plot. step : float, optional Length of each time step. [hr] lstep : float, optional Length of time steps between labels. [hr] number : int, optional Number of steps. lformat : string, optional Label format, using strftime format codes. alpha : float, optional Transparency for figure annotations. 0 to 1 for transparent to solid. lalpha : float, optional Transparency for labels. **kwargs Additional keyword arguments are passed to `astroquery.mpc.MPC.get_ephemeris`. """ import os import matplotlib.pyplot as plt from astropy.io import fits from astropy.wcs import WCS from astropy.wcs.utils import skycoord_to_pixel from astropy.time import Time import astropy.units as u import astropy.coordinates as coords from astropy.table import vstack from astroquery.skyview import SkyView from astroquery.mpc import MPC import aplpy from .. import util # nominal tick marks t0 = Time(start) current = 0 tab = None while True: t1 = t0 + current * u.hr n = min(number - current, 1440) if n <= 0: break e = MPC.get_ephemeris(target, location=observer, start=t1, step=step * u.hr, number=n, **kwargs) if tab is None: tab = e else: tab = vstack((tab, e)) current += n dates = tab['Date'] eph = coords.SkyCoord(u.Quantity(tab['RA']), u.Quantity(tab['Dec'])) # label tick marks current = 0 tab = None number_lsteps = int(number * step / lstep) while True: t1 = t0 + current * u.hr n = min(number_lsteps - current, 1440) if n <= 0: break e = MPC.get_ephemeris(target, location=observer, start=t1, step=lstep * u.hr, number=n, **kwargs) if tab is None: tab = e else: tab = vstack((tab, e)) current += n dates_labels = tab['Date'] labels = coords.SkyCoord(u.Quantity(tab['RA']), u.Quantity(tab['Dec'])) step = 0 while step < len(eph): print('This step: ', dates[step], eph[step].to_string('hmsdms', sep=':', precision=0)) fn = '{}'.format( eph[step].to_string('hmsdms', sep='', precision=0).replace(' ', '')) if os.path.exists('sky-{}.fits.gz'.format(fn)): print('reading from file') im = fits.open('sky-{}.fits.gz'.format(fn)) else: print('reading from URL') # note, radius seems to be size of image position = eph[step].to_string('decimal', precision=6) opts = dict(position=position, radius=size * u.arcmin, pixels=int(900 / 15 * size)) im = None for survey in surveys: print(survey) try: im = SkyView.get_images(survey=survey, **opts)[0] except: continue break if im is None: raise ValueError("Cannot download sky image.") im.writeto('sky-{}.fits.gz'.format(fn)) wcs = WCS(im[0].header) c = skycoord_to_pixel(eph, wcs, 0) i = (c[0] > 0) * (c[0] < 900) * (c[1] > 0) * (c[1] < 900) c = skycoord_to_pixel(labels, wcs, 0) j = (c[0] > 0) * (c[0] < 900) * (c[1] > 0) * (c[1] < 900) fig = aplpy.FITSFigure(im) fig.set_title(target) vmin = np.min(im[0].data) if vmin < 0: vmid = vmin * 1.5 else: vmid = vmin / 2 fig.show_colorscale(cmap='viridis', stretch='log', vmid=vmid) fig.show_lines([np.vstack((eph[i].ra.degree, eph[i].dec.degree))], color='w', alpha=alpha) fig.show_markers(eph[i].ra.degree, eph[i].dec.degree, c='w', marker='x', alpha=alpha) for k in np.flatnonzero(j): d = dates_labels[k] fig.add_label(labels.ra[k].degree, labels.dec[k].degree, d.datetime.strftime(lformat), color='w', alpha=lalpha, size='small') fig.show_rectangles(eph[step].ra.degree, eph[step].dec.degree, 1 / 60, 1 / 60, edgecolors='w', alpha=alpha) if text is not None: ax = plt.gca() ax.text(0.03, 0.98, text, va='top', transform=ax.transAxes, size=16, color='w') t = target.replace(' ', '').replace('/', '').replace("'", '').lower() d = dates[step] d = d.isot[:16].replace('-', '').replace(':', '').replace('T', '_') fig.save('{}-{}-{}.png'.format(t, d, fn), dpi=300) step = np.flatnonzero(i)[-1] + 1
def plot_finder_image(target, survey='DSS', fov_radius=10 * u.arcmin, log=False, ax=None, grid=False, reticle=False, style_kwargs=None, reticle_style_kwargs=None): """ Plot survey image centered on ``target``. Survey images are retrieved from NASA Goddard's SkyView service via ``astroquery.skyview.SkyView``. If a `~matplotlib.axes.Axes` object already exists, plots the finder image on top. Otherwise, creates a new `~matplotlib.axes.Axes` object with the finder image. Parameters ---------- target : `~astroplan.FixedTarget`, `~astropy.coordinates.SkyCoord` Coordinates of celestial object survey : string Name of survey to retrieve image from. For dictionary of available surveys, use ``from astroquery.skyview import SkyView; SkyView.list_surveys()``. Defaults to ``'DSS'``, the Digital Sky Survey. fov_radius : `~astropy.units.Quantity` Radius of field of view of retrieved image. Defaults to 10 arcmin. log : bool, optional Take the natural logarithm of the FITS image if `True`. False by default. ax : `~matplotlib.axes.Axes` or None, optional. The `~matplotlib.axes.Axes` object to be drawn on. If None, uses the current `~matplotlib.axes.Axes`. grid : bool, optional. Grid is drawn if `True`. `False` by default. reticle : bool, optional Draw reticle on the center of the FOV if `True`. Default is `False`. style_kwargs : dict or `None`, optional. A dictionary of keywords passed into `~matplotlib.pyplot.imshow` to set plotting styles. reticle_style_kwargs : dict or `None`, optional A dictionary of keywords passed into `~matplotlib.pyplot.axvline` and `~matplotlib.pyplot.axhline` to set reticle style. Returns ------- ax : `~matplotlib.axes.Axes` Matplotlib axes with survey image centered on ``target`` hdu : `~astropy.io.fits.PrimaryHDU` FITS HDU of the retrieved image Notes ----- Dependencies: In addition to Matplotlib, this function makes use of astroquery. """ import matplotlib.pyplot as plt from astroquery.skyview import SkyView coord = target if not hasattr(target, 'coord') else target.coord position = coord.icrs coordinates = 'icrs' target_name = None if isinstance(target, SkyCoord) else target.name hdu = SkyView.get_images(position=position, coordinates=coordinates, survey=survey, radius=fov_radius, grid=grid)[0][0] wcs = WCS(hdu.header) # Set up axes & plot styles if needed. if ax is None: ax = plt.gca(projection=wcs) if style_kwargs is None: style_kwargs = {} style_kwargs = dict(style_kwargs) style_kwargs.setdefault('cmap', 'Greys') style_kwargs.setdefault('origin', 'lower') if log: image_data = np.log(hdu.data) else: image_data = hdu.data ax.imshow(image_data, **style_kwargs) # Draw reticle if reticle: pixel_width = image_data.shape[0] inner, outer = 0.03, 0.08 if reticle_style_kwargs is None: reticle_style_kwargs = {} reticle_style_kwargs.setdefault('linewidth', 2) reticle_style_kwargs.setdefault('color', 'm') ax.axvline(x=0.5 * pixel_width, ymin=0.5 + inner, ymax=0.5 + outer, **reticle_style_kwargs) ax.axvline(x=0.5 * pixel_width, ymin=0.5 - inner, ymax=0.5 - outer, **reticle_style_kwargs) ax.axhline(y=0.5 * pixel_width, xmin=0.5 + inner, xmax=0.5 + outer, **reticle_style_kwargs) ax.axhline(y=0.5 * pixel_width, xmin=0.5 - inner, xmax=0.5 - outer, **reticle_style_kwargs) # Labels, title, grid ax.set(xlabel='RA', ylabel='DEC') if target_name is not None: ax.set_title(target_name) ax.grid(grid) # Redraw the figure for interactive sessions. ax.figure.canvas.draw() return ax, hdu
def finding_chart(npointing,delta_image = .25,offset_ra=0.,offset_dec=0.,plotsingle=True,ING=False,MLO=False,KPNO=False): galsize=0.033 i = npointing-1 center_ra = pointing_ra[i]+offset_ra center_dec = pointing_dec[i] + offset_dec print('center ra, dec = ',center_ra,center_dec) if plotsingle: if delta_image > .3: plt.subplots_adjust(right=.9,top=.9,bottom=.1,left=.1) plt.figure(figsize=(10,9)) else: plt.figure(figsize=(6,6)) ax=plt.gca() pos = coords.SkyCoord(center_ra,center_dec,frame='icrs',unit='degree') delta_imagex=2.*delta_image delta_imagey=2.*delta_image if ING: delta_imagex=.8 #image width in deg delta_imagey=.8 # image width in deg xout = SkyView.get_images(pos,survey=['DSS'],height=delta_imagex*u.degree,width=delta_imagey*u.degree) elif MLO: delta_imagex = 13./60. # image width in deg delta_imagey = 13./60 # image width in deg xout = SkyView.get_images(pos,survey=['DSS'],height=2*delta_image*u.degree,width=2.*delta_image*u.degree) b=xout[0][0] ax.imshow(xout[0][0].data,interpolation='none',aspect='equal',cmap='gray_r',extent=[b.header['CRVAL1']-(b.header['NAXIS1']-b.header['CRPIX1'])*b.header['CDELT1'], b.header['CRVAL1']+(b.header['NAXIS1']-b.header['CRPIX1'])*b.header['CDELT1'], b.header['CRVAL2']+(b.header['NAXIS2']-b.header['CRPIX2'])*b.header['CDELT2'], b.header['CRVAL2']-(b.header['NAXIS2']-b.header['CRPIX2'])*b.header['CDELT2']]) if ING: # add footprint of WFC chips plot_INT_footprint(center_ra,center_dec) elif MLO: delta_arcmin = 13. rect= plt.Rectangle((center_ra-0.5*delta_imagex,center_dec-0.5*delta_imagey), delta_arcmin/60., delta_arcmin/60.,fill=False, color='k') plt.gca().add_artist(rect) elif KPNO: rect= plt.Rectangle((center_ra-delta_image,center_dec-delta_image), 0.5, 0.5,fill=False, color='k') plt.gca().add_artist(rect) #add_cameras() # find galaxies on FOV #for MLO plot galaxies outside the field of view to help with tweaking the pointing if MLO: source_pad = 8./60. gals = (nsa.RA > (pos.ra.value-(delta_imagex/2.+source_pad))) & (nsa.RA < (pos.ra.value+delta_imagex/2 + source_pad)) & (nsa.DEC > (pos.dec.value-(delta_imagey/2. + source_pad))) & (nsa.DEC < (pos.dec.value+delta_imagey/2. + source_pad)) else: gals = (nsa.RA > (pos.ra.value-delta_imagex/2.)) & (nsa.RA < (pos.ra.value+delta_imagex/2)) & (nsa.DEC > (pos.dec.value-delta_imagey/2.)) & (nsa.DEC < (pos.dec.value+delta_imagey/2.)) print('pointing ',i+1,' ngal = ',np.sum(gals)) gindex=np.arange(len(nsa.RA))[gals] print('Pointing %02d Galaxies'%(npointing),': ',nsa.NSAID[gals]) print('Pointing %02d Galaxies'%(npointing),': ',nsa.Z[gals]*3.e5) for j in gindex: ran,decn=fix_project(nsa.RA[j],nsa.DEC[j],b) rect= plt.Rectangle((ran-galsize/2.,decn-galsize/2.), galsize, galsize,fill=False, color='c') plt.gca().add_artist(rect) s='%i\n vr=%i'%(nsa.NSAID[j],nsa.Z[j]*3.e5) plt.text(ran,decn+galsize/2.,s,fontsize=10,clip_on=True,horizontalalignment='center',verticalalignment='bottom') plt.text(ran,decn-galsize/2.,co.NEDname[j].decode("utf-8"),fontsize=10,clip_on=True,horizontalalignment='center',verticalalignment='top') if COflag[j]: size=galsize-.005 rect= plt.Rectangle((ran-size/2.,decn-size/2.), size, size,fill=False, color='g') plt.gca().add_artist(rect) if HIflag[j]: size=galsize+.005 rect= plt.Rectangle((ran-size/2.,decn-size/2.), size, size,fill=False, color='b') plt.gca().add_artist(rect) if ha_obs[j]: size=galsize+.005 rect= plt.Rectangle((ran-size/2.,decn-size/2.), size, size,fill=False, color='r') plt.gca().add_artist(rect) #plt.legend(['filament','CO','Halpha']) if moretargets: plt.title('LM-Pointing %02d: %s'%((i+1),pos.to_string('hmsdms'))) else: plt.title('Pointing %02d: %s'%((i+1),pos.to_string('hmsdms'))) plt.xlabel('RA (deg)') plt.ylabel('DEC (deg)') plt.gca().invert_yaxis() if plotsingle: plt.savefig(outfile_prefix+'Pointing%02d.png'%(i+1))
def mkpy3_finder_chart_survey_fits_image_get_v1(\ ra_deg=None, dec_deg=None, radius_arcmin=None, survey=None, cframe=None, verbose=None ): """ Function: mkpy3_finder_chart_survey_fits_image_get_v1() Purpose: Gets sky survey image data around a position on the sky. Parameters ---------- ra_deg : float (optional) right ascencsion [deg] dec_deg : float (optional) declination [deg] radius_arcmin : float (optional) radius (halfwidth and halfheight of image) [arcmin] survey : string (optional) [e.g., '2MASS-J', 'DSS2 Red', etc.] survey string name cframe : str (optional) coordinate frame name [e.g., 'fk5', 'icrs', etc.] verbose : bool (optional) if True, print extra information Returns ------- hdu : Header/Data Unit (HDU) of the survey FITS file hdr : header associated with hdu data : data associated with hdu wcs : World Coordinate System from hdu cframe : coordinate frame of the survey data # Kenneth John Mighell # Kepler/K2 Support Scientist # Kepler/K2 Science Office # NASA Ames Research Center / SETI Institute """ import astropy.units as u from astropy.coordinates import SkyCoord from astroquery.skyview import SkyView from astropy.wcs import WCS # if (ra_deg is None): ra_deg = 291.41829 # Kepler-93b if (dec_deg is None): dec_deg = 38.67236 # Kepler-93b if (radius_arcmin is None): radius_arcmin = 1.99 if (survey is None): survey = '2MASS-J' # alternate: 'DSS2 Red' # ^--- to see all surveys: astroquery.skyview.SkyView.list_surveys() if (cframe is None): cframe = 'fk5' # N.B.: '2MASS-J' uses 'fk5' if (verbose is None): verbose = False # if (verbose): print(ra_deg, '=ra_deg') print(dec_deg, '=dec_deg') print(radius_arcmin, '=radius_arcmin') print("'%s' =survey" % (survey)) print("'%s' =cframe" % (cframe)) print(verbose, '=verbose') print() pass #if # # sc <--- astropy sky coordinates sc = SkyCoord(ra=ra_deg * u.degree, dec=dec_deg * u.degree, frame=cframe) # image list # assume that the list contains a single image imgl = SkyView.get_images(position=sc, survey=survey, radius=radius_arcmin * u.arcmin) # # outputs: hdu = imgl[0] # Header/Data Unit of the FITS image hdr = hdu[0].header # header associated with the HDU data = hdu[0].data # data associated with the HDU wcs = WCS( hdr ) # World Coordinate System from the FITS header of the survey image # return hdu, hdr, data, wcs, cframe
def finding_chart(npointing,delta_image = .25,offset_ra=0.,offset_dec=0.,plotsingle=True,ING_flag=False): i = npointing-1 galsize=0.033 center_ra = pointing_ra[i]+offset_ra center_dec = pointing_dec[i] + offset_dec print('center ra, dec = ',center_ra,center_dec) if plotsingle: if delta_image > .3: plt.subplots_adjust(right=.9,top=.9,bottom=.1,left=.1) plt.figure(figsize=(10,9)) else: plt.figure(figsize=(6,6)) ax=plt.gca() pos = coords.SkyCoord(center_ra,center_dec,frame='icrs',unit='degree') if ING_flag: xout = SkyView.get_images(pos,survey=['DSS'],height=.7*u.degree,width=.6*u.degree) else: xout = SkyView.get_images(pos,survey=['DSS'],height=2*delta_image*u.degree,width=2.*delta_image*u.degree) b=xout[0][0] ax.imshow(xout[0][0].data,interpolation='none',aspect='equal',cmap='gray_r',extent=[b.header['CRVAL1']-(b.header['NAXIS1']-b.header['CRPIX1'])*b.header['CDELT1'], b.header['CRVAL1']+(b.header['NAXIS1']-b.header['CRPIX1'])*b.header['CDELT1'], b.header['CRVAL2']+(b.header['NAXIS2']-b.header['CRPIX2'])*b.header['CDELT2'], b.header['CRVAL2']-(b.header['NAXIS2']-b.header['CRPIX2'])*b.header['CDELT2']]) if ING_flag: # add footprint of WFC chips plot_INT_footprint(center_ra,center_dec) else: rect= plt.Rectangle((center_ra-delta_image,center_dec-delta_image), 0.5, 0.5,fill=False, color='k') plt.gca().add_artist(rect) #add_cameras() # find galaxies on FOV gals = (nsa.RA > (center_ra-delta_image)) & (nsa.RA < (center_ra+delta_image)) & (nsa.DEC > (center_dec-delta_image)) & (nsa.DEC < (center_dec+delta_image)) print('pointing ',i+1,' ngal = ',np.sum(gals)) gindex=np.arange(len(nsa.RA))[gals] print('Pointing %02d Galaxies'%(npointing),': ',nsa.NSAID[gals]) for j in gindex: ran,decn=fix_project(nsa.RA[j],nsa.DEC[j],b) rect= plt.Rectangle((ran-galsize/2.,decn-galsize/2.), galsize, galsize,fill=False, color='c') plt.gca().add_artist(rect) s='%i, vr=%i'%(nsa.NSAID[j],nsa.ZDIST[j]*3.e5) plt.text(ran,decn+galsize/2.,s,fontsize=10,clip_on=True,horizontalalignment='center') plt.text(ran,decn-galsize/2.,co.NEDname[j],fontsize=10,clip_on=True,horizontalalignment='center',verticalalignment='top') if COflag[j]: size=galsize-.005 rect= plt.Rectangle((ran-size/2.,decn-size/2.), size, size,fill=False, color='g') plt.gca().add_artist(rect) if HIflag[j]: size=galsize+.005 rect= plt.Rectangle((ran-size/2.,decn-size/2.), size, size,fill=False, color='b') plt.gca().add_artist(rect) if ha_obs[j]: size=galsize+.005 rect= plt.Rectangle((ran-size/2.,decn-size/2.), size, size,fill=False, color='r') plt.gca().add_artist(rect) #plt.legend(['filament','CO','Halpha']) plt.title('Pointing %02d: %s'%((i+1),pos.to_string('hmsdms'))) plt.xlabel('RA (deg)') plt.ylabel('DEC (deg)') plt.gca().invert_yaxis() if plotsingle: plt.savefig(outfile_prefix+'Pointing%02d.png'%(i+1))