def PDF(cutout): """ Create a pdf file with the plot of your objects in different filters Parameters ---------- cutout: list array of images N filt x N sources """ # create the pdf pdfOut = PdfPages(dirpath + 'stampPDF.pdf') # it's a sum to derive the good number of stamp p = 0 # Placement of the Id sizeId = cutout[0][0].shape # while p < np.size(cutout[0]) - 1: print(p) if np.size(cutout[0]) - p > 10: fig, axs = plt.subplots(10, len(cutout), figsize=(8.3, 11.7)) else: fig, axs = plt.subplots(np.size(cutout[0]) - p, len(cutout), figsize=(8.3, 11.7)) # Loop over the 10 sources to be include in one PDF page for k in range(10): # id of object axs[k, 0].text(-sizeId[0], sizeId[0] / 2, tbl['id'][p]) # Loop over the filters for j in range(len(cutout)): # Display the image mappa = axs[k, j].imshow(cutout[j][p].data, cmap='afmhot', origin='lower', interpolation='nearest') axs[k, j].set_title(filters[j], fontsize=5, pad=2.5) axs[k, j].get_xaxis().set_visible(False) axs[k, j].get_yaxis().set_visible(False) # Plot circular aperture at the coordinate of your object apertures = SkyCircularAperture(tbl['skycoord'][p], r=1.5 * u.arcsec) aperturesPix = apertures.to_pixel(cutout[j][p].wcs) aperturesPix.plot(color='cyan', ax=axs[k, j], lw=1, alpha=0.5) # DS9 zscale zrange = zscale.zscale(cutout[j][p].data) mappa.set_clim(zrange) # it's a sum to derive the good number of stamp if p < np.size(cutout[0]) - 1: p = p + 1 else: break # save the page plt.savefig(pdfOut, format='pdf') pdfOut.close() return
#idx_fitsheader=np.array([2673]) print(idx_fitsheader) print(fits_ori) print(fits_ori[idx_fitsheader]) n_idx = len(idx_fitsheader) Rmag0 = np.array([0.] * n_idx) #sys.exit(0) r_circle = 15. r_circle_as = r_circle * u.arcsec r_inner = 20. r_outer = 25. r_inner_as = r_inner * u.arcsec r_outer_as = r_outer * u.arcsec aperture = SkyCircularAperture(positions, r_circle_as) #print(aperture) r_as = aperture.r print('r_as =', r_as) k = 0 for i in idx_fitsheader: print('-----------------------') print('idx', i, ') ID =', ID[i], ', #', k) fits_root = fits_ori[i].split('.', -1)[0].split('_calib', -1)[0] fits_calib = fits_root + '_calib.fits' print(fits_calib) #print(fits_root) #print(fits_calib) #print(fits_ori) # sys.exit(0)
from regions import read_ds9 fitsimage = imageDir + 'mass_map.fits' hdr = fits.open(fitsimage)[0].header wcs = fits_import(fitsimage)[0] mass = fits_import(fitsimage)[1] # file=regionDir+'stellar_total.reg' # whole_star=read_ds9(file)[0] # wholestar_pix=whole_star.to_pixel(wcs) # whole_masked=Apmask_convert(wholestar_pix, mass) # SM=np.ma.sum(whole_masked)*(480*0.3)**2 radius = 17.53 # SDSS petrosian radius for NGC 5257 in arcsec. center = position aperture_whole = SkyCircularAperture(center, radius * u.arcsec) aperture_whole_pix = aperture_whole.to_pixel(wcs=wcs) aperture_whole_masked = Apmask_convert(aperture_whole_pix, mass) SM = np.ma.sum(aperture_whole_masked) * (480 * 0.3)**2 fig = plt.figure() plt.imshow(mass, origin='lower') aperture_whole_pix.plot(color='red') #### check total stellar mass flux_36 = 19448.31 * 1e6 / (4.25e10) * 0.3**2 flux_45 = 13959 * 1e6 / (4.25e10) * 0.3**2 Mstar_total = mass_calc(flux_36, flux_45)
def FitCircularAperture( hdu=None, coords=None, radius=1.5 * u.arcsec, annulus=[5, 7] * u.arcsec, plot=False, plottitle=None, ): """ Fit a circular aperture with either an HDU object or and """ im = hdu[0].data error = hdu[1].data w = wcs.WCS(hdu[0].header) # create mask (set True for where you want to mask) im_mask = im == 0 # define circular aperture and annulus aperture for background subtraction aper = SkyCircularAperture(coords, r=radius) aper_annulus = SkyCircularAnnulus(coords, annulus[0], annulus[1]) mask = aper_annulus.to_pixel(w).to_mask(method="center").data annulus_data = aper_annulus.to_pixel(w).to_mask(method="center").multiply(im) annulus_data_1d = annulus_data[mask > 0] annulus_mask = aper_annulus.to_pixel(w).to_mask(method="center").multiply(im_mask) annulus_mask_1d = annulus_mask[mask > 0] # determine fractional fiber coverage apcor_im = aper.to_pixel(w).to_mask(method="center").multiply( im_mask ) / aper.to_pixel(w).to_mask(method="center").multiply(np.ones_like(im)) apcor = np.sum(apcor_im == 0) / np.sum(np.isfinite(apcor_im)) # get median and standard deviation in background mean_sigclip, median_sigclip, stddev_sigclip = sigma_clipped_stats( annulus_data_1d, mask=annulus_mask_1d ) bkg_median = median_sigclip * aper.to_pixel(w).area * apcor bkg_stddev = stddev_sigclip * aper.to_pixel(w).area * apcor phottable = aperture_photometry( hdu[0].data, [aper, aper_annulus], error=hdu[1].data, mask=im_mask, wcs=wcs.WCS(hdu[0].header), ) if np.abs(bkg_median) > 2 * bkg_stddev: flux = (phottable["aperture_sum_0"][0] - bkg_median) * u.Unit( "10^-17 erg cm-2 s-1" ) else: flux = (phottable["aperture_sum_0"][0]) * u.Unit("10^-17 erg cm-2 s-1") flux_err = phottable["aperture_sum_err_0"][0] * u.Unit("10^-17 erg cm-2 s-1") if plot: plt.subplot(111, projection=w) plt.imshow(im, vmin= -1 * stddev_sigclip, vmax=4 * stddev_sigclip) aper.to_pixel(w).plot(color="white") # for SkyCircularAperture aper_annulus.to_pixel(w).plot(color="red", linestyle="dashed") plt.xlabel("RA") plt.ylabel("Dec") plt.colorbar() if plottitle is not None: plt.title(plottitle) return flux, flux_err, bkg_stddev * u.Unit("10^-17 erg cm-2 s-1"), apcor
def calc_radial_profile(fitsfile, center, rstart, rend, rstep, verbose=False, detmaskfile=None, plot=True): """ Utility function to calculate the radial profile from an image `fitsfile` at a `center` """ # if (not os.path.isfile(fitsfile)): print(f"ERROR. FITS file {fitsfile} not found. Cannot continue.") return None # qhdu = fits.open(fitsfile) wcs = WCS(qhdu[0].header) # # if detmaskfile is provided then will use it for detector mask # doMask = False if (detmaskfile != None): if (not os.path.isfile(detmaskfile)): print(f"Warning. Detector mask file {detmaskfile} not found. Will not use detector mask!") doMask = False else: det = fits.open(detmaskfile) detmask = det['MASK'] # need the WCS wcs_det = WCS(detmask.header) doMask = True # if (not isinstance(center, SkyCoord)): print(f"ERROR: the input radial profile centre is not SkyCoord object. Cannot continue.") return None # j = 0 rx = rstart counts = [] counts_err = [] rmid = [] # emtpy = False while rx < rend: r0 = rstart + rstep * j rx = rstart + rstep * (j + 1) # the mid point, can be better the mid area point rmid.append((r0.value + rx.value) / 2.0) if (j == 0): xap = SkyCircularAperture(center, rx) photo = aperture_photometry(qhdu[0].data, xap, wcs=wcs) if (doMask): masked = aperture_photometry(detmask.data, xap, wcs=wcs_det) else: xap = SkyCircularAnnulus(center, r0, rx) photo = aperture_photometry(qhdu[0].data, xap, wcs=wcs) if (doMask): masked = aperture_photometry(detmask.data, xap, wcs=wcs_det) # ap_area = xap.to_pixel(wcs).area good_area = ap_area if (doMask): good_area = masked['aperture_sum'][0] # compare the two annuli areas: with and without bad pixels if (verbose): print( f"Annulus: {r0:.2f},{rx:.2f},geometric area: {ap_area:.1f} pixels,non-masked area {good_area:.1f} pixels, ratio: {ap_area / good_area:.2f}") # taking into account the masked pixels if (good_area == 0.0): counts.append(float('nan')) counts_err.append(float('nan')) else: counts.append(photo['aperture_sum'][0] / good_area) counts_err.append(np.sqrt(photo['aperture_sum'][0]) / good_area) j += 1 # # convert the results in numpy arrays # rmid = np.array(rmid) counts = np.array(counts) counts_err = np.array(counts_err) # # convert per pixel to per arcsec^2 pix_area = utils.proj_plane_pixel_area(wcs) * 3600.0 * 3600.0 # in arcsec^2 counts = counts / pix_area counts_err = counts_err / pix_area # if (plot): fig, ax = plt.subplots(figsize=(10, 8)) ax.errorbar(rmid, counts, xerr=rstep.value / 2.0, yerr=counts_err) ax.set_xscale('linear') ax.set_yscale('log') ax.set_xlabel('Radial distance (arcsec)') ax.set_ylabel(r'Counts/arcsec$^2$') ax.grid() ax.set_title(f"Radial profile"); qhdu.close() if (doMask): det.close() return rmid, counts, counts_err
def main(file, right_ascension, declination, redshift, Rout_Mpc): science = fits.open(file) # open the science image header = science[0].header # define the header, in order to get the WCS image = science[0].data # create the image that will be used science.close() world_cs = WCS(header) RA = Angle(right_ascension, u.deg) # the RA, Dec for this cluster Dec = Angle(declination, u.deg) Rout = Rout_Mpc * u.Mpc # the Rout_Mpc for this cluster D_A = cosmo.angular_diameter_distance(redshift) R_max = Angle(Rout / D_A * u.rad) # maximum radius in radians position = SkyCoord(ra=RA, dec=Dec, distance=D_A) aperture = SkyCircularAperture(position, r=R_max) phot_table = aperture_photometry(image, aperture, wcs=world_cs) total_counts_per_second = phot_table['aperture_sum'][0] exposure_time = header['EXPOSURE'] # exposure time in seconds minimum_necessary_counts = 20000 if (total_counts_per_second * exposure_time) < minimum_necessary_counts: with open('insufficient.txt', 'w') as file: file.write("Actual counts: " + str(total_counts_per_second * exposure_time)) return "skip" else: roi_sky = ('# Region file format: DS9 version 4.1\n' + 'global width=1\n' + 'fk5\n') roi_sky += ("circle(" + RA.to_string(unit=u.hour, sep=':') + "," + Dec.to_string(unit=u.degree, sep=':') + "," + str(R_max.to(u.arcsec).value) + '")\n') box_sky = ('# Region file format: DS9 version 4.1\n' + 'global width=1\n' + 'fk5\n') box_sky += ("box(" + RA.to_string(unit=u.hour, sep=':') + "," + Dec.to_string(unit=u.degree, sep=':') + "," + str(4 * R_max.to(u.arcsec).value) + '"' + "," + str(4 * R_max.to(u.arcsec).value) + '",360)\n') with open('roi_sky.reg', 'w') as file: file.write(roi_sky) # create the roi_sky.reg file for further use with open('box_sky.reg', 'w') as file: file.write(box_sky) # save square region with l=w=2*R_max # http://cxc.harvard.edu/ciao/ahelp/dmmakereg.html subprocess.run("punlearn dmmakereg", shell=True) subprocess.run("dmmakereg 'region(roi_sky.reg)' roi_phys.reg " + "kernel=ascii wcsfile=merged_2/broad_flux.img", shell=True) # take the roi_sky.reg file and create a # CIAO physical roi_phys.reg file subprocess.run("dmmakereg 'region(box_sky.reg)' box_phys.reg " + "kernel=ascii wcsfile=merged_2/broad_flux.img", shell=True) # take the box_sky.reg file and create a # CIAO physical box_phys.reg file return "sufficient"
SFR_cut_wcs, SFR_cut=cut_2d(SFR, position, size, wcs) SFR_cutbin=reproj_binning(SFR_cut, SFR_cut_wcs, bin_number)[1] # ax=plt.subplot(projection=Qtot_cut_wcs) ax=plt.subplot('111', projection=Qtotbin_wcs) ax.tick_params(direction='in') ax.text(9, 31, galaxy+' Q$_{tot}$', fontsize=17) # ax.set_xticks([]) # ax.set_yticks([]) im=ax.imshow(Qtot_cutbin,origin='lower', vmax=3.0, norm=colors.PowerNorm(gamma=0.5)) # rings[11].plot() # rings[13].plot() plt.xlabel('J2000 Right Ascension') plt.ylabel('J2000 Declination') cbar=plt.colorbar(im) cbar.set_label('$Q_{tot}$',fontsize=24) cbar.ax.tick_params(labelsize=20) ax.contour(SFR_cutbin,levels=levels,colors=['red']) plt.savefig(picDir+galaxy_label+'_Toomre_map.png') ############################################################ # check fig=plt.figure() circle=SkyCircularAperture(positions=position, r=3*u.arcsec) circle_pix=circle.to_pixel(Qtot_cut_wcs) plt.imshow(Qtot_cut, origin='lower') circle_pix.plot()
def show_cutout_with_slit(hdr, data=None, slit_ra=None, slit_dec=None, slit_shape='rectangular', slit_width=0.2, slit_length=3.3, slit_angle=90, slit_radius=0.2, slit_rout=0.5, cmap='Greys_r', plotname='', **kwargs): """Show a cutout image with the slit(s) superimposed. Parameters ---------- hdr : dict Cutout image header. data : ndarray or `None`, optional Cutout image data. If not given, data is not shown. slit_ra, slit_dec : float or array or `None`, optional Slit RA and DEC in degrees. Default is to use object position from image header. If an array is given, each pair of RA and DEC becomes a slit. slit_shape : {'annulus', 'circular', 'rectangular'}, optional Shape of the slit (circular or rectangular). Default is rectangular. slit_width, slit_length : float, optional Rectangular slit width and length in arcseconds. Defaults are some fudge values. slit_angle : float, optional Rectangular slit angle in degrees for the display. Default is vertical. slit_radius : float, optional Radius of a circular or annulus slit in arcseconds. For annulus, this is the inner radius. Default is some fudge value. slit_rout : float, optional Outer radius of an annulus slit in arcseconds. Default is some fudge value. cmap : str or obj, optional Matplotlib color map for image display. Default is grayscale. plotname : str, optional Filename to save plot as. If not given, it is not saved. kwargs : dict, optional Keyword argument(s) for the aperture overlay. If ``ax`` is given, it will also be used for image display. See Also -------- make_cutouts """ # Optional dependencies... import matplotlib.pyplot as plt from photutils import (SkyCircularAnnulus, SkyCircularAperture, SkyRectangularAperture) from scipy.ndimage.interpolation import rotate if slit_ra is None: slit_ra = hdr['OBJ_RA'] if slit_dec is None: slit_dec = hdr['OBJ_DEC'] position = SkyCoord(slit_ra, slit_dec, unit='deg') if slit_shape == 'circular': slit_radius = u.Quantity(slit_radius, u.arcsec) aper = SkyCircularAperture(position, slit_radius) elif slit_shape == 'annulus': slit_rin = u.Quantity(slit_radius, u.arcsec) slit_rout = u.Quantity(slit_rout, u.arcsec) aper = SkyCircularAnnulus(position, slit_rin, slit_rout) else: # rectangular slit_width = u.Quantity(slit_width, u.arcsec) slit_length = u.Quantity(slit_length, u.arcsec) theta = u.Quantity(90, u.degree) aper = SkyRectangularAperture(position, slit_width, slit_length, theta=theta) # Rotate data and keep slit upright if data is not None: data = rotate(data, slit_angle - theta.value, reshape=False) wcs = WCS(hdr) aper_pix = aper.to_pixel(wcs) ax = kwargs.get('ax', plt) if data is not None: ax.imshow(data, cmap=cmap, origin='lower') aper_pix.plot(**kwargs) if plotname: ax.savefig(plotname)
############################################################ # main program Dir='/1/home/heh15/workingspace/Arp240/NGC5258/12CO10/' imageDir=Dir+'casa5.4/' regionDir=Dir+'region/' fitsimage=imageDir+'NGC5258_12CO10_combine_contsub_pbcor_mom0.fits' wcs=fits_import(fitsimage)[0] data_masked=fits_import(fitsimage)[1] data=data_masked.data # regionfile=regionDir+'southarm.reg' # southarm=read_ds9(regionfile)[0] r=0.5/0.485*u.arcsec southarm=SkyCircularAperture(positions=position,r=r) southarm_pix=southarm.to_pixel(wcs) southarm_masked=Apmask_convert(southarm_pix,data) intensity_southarm=np.ma.mean(southarm_masked)*incl regionfile=regionDir+'whole.reg' whole_pix=read_ds9(regionfile)[0] # whole_pix=whole.to_pixel(wcs) fig=plt.figure() ax=plt.subplot('111',projection=wcs) plt.imshow(data,origin='lower') southarm_pix.plot() def Apmask_convert(aperture,data_cut):
def plot_reduced(self, ax=None, figsize=(6, 6), plot_apertures=True, minp=10, maxp=100, flt=lambda a: a, transform=lambda im: (im.reduced, im._wcs), **kwargs): if 'subfield_radius' in kwargs.keys() and kwargs['subfield_radius']: from astropy.nddata import Cutout2D sc = kwargs.get('target', self._target_center) assert isinstance(sc, SkyCoord) assert self._wcs is not None r = kwargs['subfield_radius'] * u.arcmin co = Cutout2D(self.reduced, sc, (r, r), mode='partial', fill_value=median(self.reduced), wcs=self._wcs) data, wcs = co.data, co.wcs else: data, wcs = transform(self) height, width = data.shape fig, ax = super().plot(flt(data), ax=ax, figsize=figsize, title='Reduced image', minp=minp, maxp=maxp, wcs=wcs) setp(ax, xlim=(0, width), ylim=(0, height)) if plot_apertures: self.plot_apertures(ax, wcs=wcs) # Plot the circle of inclusion if self._separation_cut is not None: from photutils import SkyCircularAperture sa = SkyCircularAperture(self._target_center, self._separation_cut).to_pixel(wcs) ax.plot(*self._target_center.to_pixel(wcs), marker='x', c='k', ms=15) sa.plot(ax=ax, color='0.4', ls=':', lw=2) if sa.positions[0][0] + sa.r - 20 < width: ax.text(sa.positions[0][0] + sa.r + 10, sa.positions[0][1], "r = {:3.1f}'".format(self._separation_cut.value), size='larger') # Plot the margins if self._margins_cut: ax.axvline(self.margin, c='k', ls='--', alpha=0.5) ax.axvline(self.width - self.margin, c='k', ls='--', alpha=0.5) ax.axhline(self.margin, c='k', ls='--', alpha=0.5) ax.axhline(self.height - self.margin, c='k', ls='--', alpha=0.5) # Plot the image scale if self._wcs: xlims = ax.get_xlim() py = 0.96 * ax.get_ylim()[1] x0, x1 = 0.3 * xlims[1], 0.7 * xlims[1] scale = SkyCoord.from_pixel(x0, py, wcs).separation( SkyCoord.from_pixel(x1, py, wcs)) ax.annotate('', xy=(x0, py), xytext=(x1, py), arrowprops=dict(arrowstyle='|-|', lw=1.5, color='k')) ax.text(width / 2, py - 7.5, "{:3.1f}'".format(scale.arcmin), va='top', ha='center', size='larger') return fig, ax
def make_aperture(self, ra, dec, unit=u.deg, aperture_radius=1.): position = SkyCoord(ra, dec, unit=unit, frame='icrs') ap = SkyCircularAperture(position, r=aperture_radius * u.arcsec) return ap
def ap_phot(self, my_image_files, Rad, test_src_coord, wavelength): """ ap_phot applies aperture photometry to calculate the flux of the source. It creates a circle aperture around the source referencing the radius of the snr as the radius of the circular aperture. It also creates 4 more apertures away from the source which are then averaged and subtracted from the target flux to remove background Input ========================== my_image_files (.fits): .fits file from coordinates Rad (float): radius in units of arcsec test_src_coord (float): coordinates of target in decimal degrees wavelength (float): waveband in units of um Output ========================== FluxIR (float): calculated flux in units of erg/s/cm^2 """ fluxes = [] fluxesav = [] im_name = [] for i in my_image_files: # load the file data, header, and wcs with fits.open(i) as hdulist: my_hdu = hdulist[0] my_hdu.data = np.nan_to_num(my_hdu.data) r = Rad * u.arcsec position = SkyCoord(test_src_coord[0] * u.degree, test_src_coord[1] * u.degree, frame='icrs') apertures = SkyCircularAperture(position, r=Rad * u.arcsec) phot_table = aperture_photometry(my_hdu, apertures) fluxes.append(phot_table['aperture_sum']) x = Angle(Rad, u.arcsec) y = 2.25 * x.degree z = y * 2.5 t1_pos = SkyCoord((test_src_coord[0] + z) * u.degree, (test_src_coord[1]) * u.degree, frame='icrs') t2_pos = SkyCoord((test_src_coord[0] - z) * u.degree, (test_src_coord[1]) * u.degree, frame='icrs') t3_pos = SkyCoord((test_src_coord[0]) * u.degree, (test_src_coord[1] + y) * u.degree, frame='icrs') t4_pos = SkyCoord((test_src_coord[0]) * u.degree, (test_src_coord[1] - y) * u.degree, frame='icrs') ap1 = SkyCircularAperture(t1_pos, r=Rad * u.arcsec) ap2 = SkyCircularAperture(t2_pos, r=Rad * u.arcsec) ap3 = SkyCircularAperture(t3_pos, r=Rad * u.arcsec) ap4 = SkyCircularAperture(t4_pos, r=Rad * u.arcsec) phot_table1 = aperture_photometry(my_hdu, ap1) fluxesav.append(phot_table1['aperture_sum']) phot_table2 = aperture_photometry(my_hdu, ap2) fluxesav.append(phot_table2['aperture_sum']) phot_table3 = aperture_photometry(my_hdu, ap3) fluxesav.append(phot_table3['aperture_sum']) phot_table4 = aperture_photometry(my_hdu, ap4) fluxesav.append(phot_table4['aperture_sum']) average = np.mean(fluxesav) flux = fluxes - average unit = flux * 23.5045 ap_ar = np.pi * Rad**2 jan = unit / ap_ar erg = jan * 10**-17 band_list = [3.6, 4.5, 5.8, 8.0, 24, 70, 160] if wavelength == 3.6: band = 9.671e13 - 7.687e13 if wavelength == 4.5: band = 7.687e13 - 5.996e13 if wavelength == 5.8: band = 6.118e13 - 4.835e13 if wavelength == 8.0: band = 4.835e13 - 3.224e13 if wavelength == 24: band = 1.499e13 - 1.070e13 if wavelength == 70: band = 5.996e12 - 3.331e12 if wavelength == 160: band = 2.306e12 - 1.578e12 fluxIR = erg * band FluxIR = fluxIR[0] return FluxIR
def plot_image(self, data, wcs, coords=None): """ convience function to plot data on a wcs projection Input: data - the data array wcs - the WCS object coords - the coordinates of the object for plotting (1x2 array, optional) """ # set up the plot fig, axs = plt.subplots(1, 1, figsize=(8, 8), subplot_kw={'projection': wcs}) # set up limits of the colour scale for plotting vmin = 5e-2 # plot axs.imshow(data, cmap='jet', interpolation='nearest', origin='lower', norm=LogNorm(vmin=vmin)) #axs.scatter(coords[0], coords[1], transform=axs.get_transform('fk5'), s=20000, lw=2, # edgecolor='white', facecolor='none') # define the apertures to plot (these are the same as in other functions) # SNR position = SkyCoord(self.ra_deg * u.degree, self.dec_deg * u.degree, frame='icrs') snr_aperture = SkyCircularAperture(position, r=self.radius * u.arcsec) snr_pix_aperture = snr_aperture.to_pixel(wcs) snr_pix_aperture.plot(color='white', lw=3, alpha=1.0) # BKG x = Angle(self.radius, u.arcsec) y = 2.25 * x.degree z = y * 2.5 t1_pos = SkyCoord((self.ra_deg + z) * u.degree, (self.dec_deg) * u.degree, frame='icrs') t2_pos = SkyCoord((self.ra_deg - z) * u.degree, (self.dec_deg) * u.degree, frame='icrs') t3_pos = SkyCoord((self.ra_deg) * u.degree, (self.dec_deg + y) * u.degree, frame='icrs') t4_pos = SkyCoord((self.ra_deg) * u.degree, (self.dec_deg - y) * u.degree, frame='icrs') ap1 = SkyCircularAperture(t1_pos, r=self.radius * u.arcsec) ap1_pix = ap1.to_pixel(wcs) ap1_pix.plot(color='white', lw=4, ls='--', alpha=1.0) ap2 = SkyCircularAperture(t2_pos, r=self.radius * u.arcsec) ap2_pix = ap2.to_pixel(wcs) ap2_pix.plot(color='white', lw=4, ls='--', alpha=1.0) ap3 = SkyCircularAperture(t3_pos, r=self.radius * u.arcsec) ap3_pix = ap3.to_pixel(wcs) ap3_pix.plot(color='white', lw=4, ls='--', alpha=1.0) ap4 = SkyCircularAperture(t4_pos, r=self.radius * u.arcsec) ap4_pix = ap4.to_pixel(wcs) ap4_pix.plot(color='white', lw=4, ls='--', alpha=1.0) # MIRI Imager FOVs x = Angle(self.radius, u.arcsec) y = x.degree z = y * 2.5 t1_pos = SkyCoord((self.ra_deg + z) * u.degree, (self.dec_deg) * u.degree, frame='icrs') t2_pos = SkyCoord((self.ra_deg - z) * u.degree, (self.dec_deg) * u.degree, frame='icrs') t3_pos = SkyCoord((self.ra_deg) * u.degree, (self.dec_deg + y) * u.degree, frame='icrs') t4_pos = SkyCoord((self.ra_deg) * u.degree, (self.dec_deg - y) * u.degree, frame='icrs') ap1 = SkyRectangularAperture(t1_pos, 74 * u.arcsec, 113 * u.arcsec, 90 * u.degree) ap1_pix = ap1.to_pixel(wcs) ap1_pix.plot(color='white', lw=5, ls=':', alpha=1.0) ap2 = SkyRectangularAperture(t2_pos, 74 * u.arcsec, 113 * u.arcsec, 90 * u.degree) ap2_pix = ap2.to_pixel(wcs) ap2_pix.plot(color='white', lw=5, ls=':', alpha=1.0) ap3 = SkyRectangularAperture(t3_pos, 74 * u.arcsec, 113 * u.arcsec, 0 * u.degree) ap3_pix = ap3.to_pixel(wcs) ap3_pix.plot(color='white', lw=5, ls=':', alpha=1.0) ap4 = SkyRectangularAperture(t4_pos, 74 * u.arcsec, 113 * u.arcsec, 0 * u.degree) ap4_pix = ap4.to_pixel(wcs) ap4_pix.plot(color='white', lw=5, ls=':', alpha=1.0) axs.set_facecolor('black') axs.coords.grid(True, color='white', ls='dotted') axs.coords[0].set_axislabel('Right Ascension (J2000)') axs.coords[1].set_axislabel('Declination (J2000)') # display the plot plt.tight_layout() # save as a pdf plot_name = os.path.join( str(self.name), str(self.name) + '_' + str(self.wavelength) + '.pdf') try: os.remove(plot_name) except: pass fig.savefig(plot_name, dpi=200)
pf = fits.open(wht_file) # inverse variance weight images wht = pf[ext].data noise = 1. / np.sqrt(wht) wcs = WCS(head) wcs.sip = None ra = mcat_row['RA'] dec = mcat_row['DEC'] area = mcat_row['area'] coords = SkyCoord(ra, dec, unit="deg") radius = round(np.sqrt(area / np.pi), 4) * u.pix # pixels sky_aper = SkyCircularAperture(coords, r=radius) ap_sum = aperture_photometry( image, sky_aper, error=noise, wcs=wcs) # flux + flux error in counts or electrons flux = ap_sum["aperture_sum"] flux_err = ap_sum["aperture_sum_err"] mag, magerr = hst_phot(photflam, photplam, flux, dn_err=flux_err) # AB magnitude # store values in a dict --> eventually write to a table... mdict[obj][filt + '_mag'] = float(mag) mdict[obj][filt + '_magerr'] = float(magerr) mdict[obj][filt + '_pivot'] = float(photplam) mdict[obj][filt + '_bandwidth'] = float(photbw) / 2. mdict[obj]["keys"]["mag"].append(filt + '_mag')
# ------------------------------------------------------------------------------------------------------------------- # list_galex = group_similar_files('', common_text=DIR_GAL + 'GalEX/BS_*.fits') list_ps1 = group_similar_files('', common_text=DIR_GAL + 'Pan-Starrs/BS_*.fits') list_spitz = group_similar_files('', common_text=DIR_GAL + 'Spitzer/BS_*.fits') list_2mass = group_similar_files('', common_text=DIR_GAL + '2MASS/BS_*.fits') list_files = list_galex + list_ps1 + list_spitz + list_2mass # ------------------------------------------------------------------------------------------------------------------- # # ------------------------------------------------------------------------------------------------------------------- # # Apertures For Different Datasets In Pixel Coordinates # ------------------------------------------------------------------------------------------------------------------- # aperture_final = SkyCircularAperture(SkyCoord('7:27:33.040', '+85:45:28.078', unit=(u.hourangle, u.deg), frame='fk5'), r=79.914 * u.arcsec) aperture_ps1 = CircularAperture((511.99622, 635.88791), r=319.65599) aperture_galex = CircularAperture((1230.4901, 2327.5328), r=53.276) aperture_spitz = CircularAperture((1096.5952, 544.47686), r=133.18973) aperture_2mass = CircularAperture((106.53127, 74.079436), r=79.913998) # ------------------------------------------------------------------------------------------------------------------- # # ------------------------------------------------------------------------------------------------------------------- # # Calculate SFR Of The Host Galaxy Using GalEX FUV Magnitude (In AB System) # ------------------------------------------------------------------------------------------------------------------- # display_text("Calculating Star Formation Rate in {0}".format(name_glx)) for file_name in list_galex:
def show_cutout_with_slit(hdr, data=None, slit_ra=None, slit_dec=None, slit_shape='rectangular', slit_width=0.2, slit_length=3.3, slit_angle=90, slit_radius=0.2, slit_rout=0.5, cmap='Greys_r', plotname='', **kwargs): """Show a cutout image with the slit(s) superimposed. Parameters ---------- hdr : dict Cutout image header. data : ndarray or `None`, optional Cutout image data. If not given, data is not shown. slit_ra, slit_dec : float or array or `None`, optional Slit RA and DEC in degrees. Default is to use object position from image header. If an array is given, each pair of RA and DEC becomes a slit. slit_shape : {'annulus', 'circular', 'rectangular'}, optional Shape of the slit (circular or rectangular). Default is rectangular. slit_width, slit_length : float, optional Rectangular slit width and length in arcseconds. Defaults are some fudge values. slit_angle : float, optional Rectangular slit angle in degrees for the display. Default is vertical. slit_radius : float, optional Radius of a circular or annulus slit in arcseconds. For annulus, this is the inner radius. Default is some fudge value. slit_rout : float, optional Outer radius of an annulus slit in arcseconds. Default is some fudge value. cmap : str or obj, optional Matplotlib color map for image display. Default is grayscale. plotname : str, optional Filename to save plot as. If not given, it is not saved. kwargs : dict, optional Keyword argument(s) for the aperture overlay. If ``ax`` is given, it will also be used for image display. See Also -------- make_cutouts """ # Optional dependencies... import matplotlib.pyplot as plt from photutils import (SkyCircularAnnulus, SkyCircularAperture, SkyRectangularAperture) if slit_ra is None: slit_ra = hdr['OBJ_RA'] if slit_dec is None: slit_dec = hdr['OBJ_DEC'] position = SkyCoord(slit_ra, slit_dec, unit='deg') if slit_shape == 'circular': slit_radius = u.Quantity(slit_radius, u.arcsec) aper = SkyCircularAperture(position, slit_radius) elif slit_shape == 'annulus': slit_rin = u.Quantity(slit_radius, u.arcsec) slit_rout = u.Quantity(slit_rout, u.arcsec) aper = SkyCircularAnnulus(position, slit_rin, slit_rout) else: # rectangular slit_width = u.Quantity(slit_width, u.arcsec) slit_length = u.Quantity(slit_length, u.arcsec) slit_angle = u.Quantity(slit_angle, u.degree) aper = SkyRectangularAperture(position, slit_width, slit_length, theta=slit_angle) wcs = WCS(hdr) aper_pix = aper.to_pixel(wcs) ax = kwargs.get('ax', plt) if data is not None: ax.imshow(data, cmap=cmap, origin='lower') aper_pix.plot(**kwargs) if plotname: ax.savefig(plotname)
def generate_regions(hdu, approx_location, centering_width=80, ap_rad=6.5, in_rad=7.0, out_rad=14.0): """ Generates source and background regions for aperture photometry. Given an image and the approximate RA/Dec of the source, finds the centroid within centering_width pixels and generates regions with the given parameters Parameters ---------- hdu : `~astropy.io.fits.hdu.image.PrimaryHDU` HDU object containing the FITS image from which regions are generated. Should be just the primary hdu (e.g., hdu[0]). approx_location : `~astropy.coordinates.SkyCoord` `astropy.coordinates.SkyCoord` with the RA and Dec of the object you want to generate a region for. centering_width : int, optional Size of box around source region to find the centroid of in pixels. ap_rad : float, optional Radius of source region in arcseconds. in_rad : float, optional Inner radius of background annulus in arcseconds out_rad : float, optional Outer radius of background annulus in arcseconds Returns ------- src : `~photutils.SkyCircularAperture` Aperture object for source bkg : `~photutils.SkyCircularAnnulus` Aperture object for background """ #Make data and wcs objects data = hdu.data wcs = WCS(hdu) #Make the right shape array of coordinates world_loc = np.array( [[approx_location.ra.value, approx_location.dec.value]]) #Convert to pixel coordinates from the FITS image, 0 indexed b.c. we're working with #a numpy array approx_pix = wcs.wcs_world2pix(world_loc, 0)[0] #Convert to pixel locations of the window. min_x = int(approx_pix[0] - centering_width / 2.0) min_y = int(approx_pix[1] - centering_width / 2.0) max_x = int(approx_pix[0] + centering_width / 2.0) max_y = int(approx_pix[1] + centering_width / 2.0) #Make a little cutout around the object #Numpy arrays are weird, so x->y, y->x stamp = data[min_y:max_y, min_x:max_x] #Calculate the centroid of the stamp x_stamp_centroid, y_stamp_centroid = centroid_com(stamp) #Add back in the boundaries of the box to get centroid in data coords x_centroid = x_stamp_centroid + min_x y_centroid = y_stamp_centroid + min_y #Convert back to RA/Dec. Remember, these are 0-indexed pixels. centroid = wcs.wcs_pix2world(np.array([[x_centroid, y_centroid]]), 0) #Convert centroid to SkyCoords object location = SkyCoord(ra=centroid[0, 0] * u.degree, dec=centroid[0, 1] * u.degree) #Generate regions based on coordinates and given radii. src = SkyCircularAperture(location, r=ap_rad * u.arcsecond) bkg = SkyCircularAnnulus(location, r_in=in_rad * u.arcsecond, r_out=out_rad * u.arcsecond) return src, bkg
u.arcsec**2) # from the imhead in casa beamarea = 6 * u.arcsec * 6 * u.arcsec * 1.1331 # flux measured from original image flux_33GHz = 6.8e-4 error = 1.4e-5 flux_unpb = 6.4e-4 # compare to the smoothed image filename = imageDir + 'NGC5257_33GHz_pbcor_smooth_6arcsec.fits' wcs_33GHz = fits_import(filename)[0] data_33GHz = fits_import(filename)[1] ra = -2.7057736283005824 dec = 0.014605178692092591 position = SkyCoord(dec=dec * u.rad, ra=ra * u.rad, frame='icrs') south_sky = SkyCircularAperture(positions=position, r=3 * ratio * u.arcsec) south_pix = south_sky.to_pixel(wcs_33GHz) flux = aperture_photometry(data_33GHz, apertures=south_pix)['aperture_sum'][0] flux = float(flux / (beamarea / pixsize)) freq = 33 SFR_33GHz = sfr_radio(flux_33GHz, freq, d) error = np.full(np.shape(data_33GHz), rms_33) flux_error = aperture_photometry( data_33GHz, apertures=south_pix, error=error)['aperture_sum_err'][0] / (np.sqrt(1.1331 * 6 * 6 / 0.12**2)) # error=np.sqrt(np.ma.count(arm_masked)/(1.1331*6*6/0.12**2))*rms_33 df['region']['33GHz'] = 'south' df['flux']['33GHz'] = flux_33GHz
month = date[4:6] day = date[6:8] yearmonth = date[0:6] # sys.exit(0) dir_file = yearmonth + '/slt' + date + '_calib_sci/' # dir_reg=yearmonth+'/slt'+date+'_reg/' hdu = fits.open(dir_file + fits_calib)[0] imhead = hdu.header imdata = hdu.data wcs = WCS(imhead) # print(wcs) r_circle = fwhm[i] * xfwhm print('fwhm =', fwhm[i], ', r =', r_circle, 'pix') r_circle_as = r_circle * u.arcsec aperture = SkyCircularAperture(positions, r_circle_as) # radec_pix=wcs.all_world2pix(ra_deg,dec_deg,1) ra_pix, dec_pix = wcs.all_world2pix(ra_deg, dec_deg, 1) ra_pix = ra_pix.tolist() dec_pix = dec_pix.tolist() # print(ra_pix,dec_pix) print() # j1=0 # for j2 in idx_refstar: # ra_deg[j1]=df_refstar['RefStarRA_deg'][j2] # dec_deg[j1]=df_refstar['RefStarDEC_deg'][j2] # print(ra_deg[j1],dec_deg[j1]) # radec_deg[j1]=[ra_deg[j1],dec_deg[j1]] # print(i,j1,radec_deg[j1])
# fitsimage=imageDir+'12CO10/NGC5258_12CO10_uvrange_pbcor_cube_masked.fits' fitsimage = ratioDir + 'NGC5258_12CO10_combine_contsub_uvrange_smooth_masked_pbcor_mom0.fits' wcs = fits_import(fitsimage)[0] data10_masked = fits_import(fitsimage)[1] # import the channel used map. # fitsimage='NGC5258_12CO10_combine_uvrange_smooth_regrid21_nchan.fits' # chans=fits_import(fitsimage)[1] chans = 50 chans_10 = chans # define the aperture position = SkyCoord(dec=0.8309 * u.degree, ra=204.9906 * u.degree, frame='icrs') center_sky = SkyCircularAperture(position, r=3 * u.arcsec) center_pix = center_sky.to_pixel(wcs=wcs) apertures['center'] = center_pix ring_sky = SkyCircularAnnulus(position, r_in=3 * u.arcsec, r_out=7 * u.arcsec) ring_pix = ring_sky.to_pixel(wcs=wcs) apertures['ring'] = ring_pix position = SkyCoord(dec=0.8340 * u.degree, ra=204.9935 * u.degree, frame='icrs') northarm_sky = SkyEllipticalAperture(position, a=13 * u.arcsec, b=4 * u.arcsec, theta=185 * u.degree) northarm_pix = northarm_sky.to_pixel(wcs=wcs)
def get_counts(dirtarget, ra, dec, fil, aper_rad, ann_in_rad, ann_out_rad, name, date, set_rad=False, centroid_plot=False): """Generates background-substracted aperture sums for a source in an image. Defines source region as a 20x20 square centered at the input R.A. and dec. Source region is checked to ensure it is below the CCD saturation level, and lies entirely in the image. Centroiding is then performed to locate the central pixel of the source. An aperture and annulus are placed around this pixel and the background-subtracted aperture sum is calculated. All returns have size (#source(s) x #image(s)). Parameters ---------- dirtarget : str Directory containing all bias, flat, and raw science images. ra : list List of string(s) of right ascension(s) of object(s) to be processed. dec : list List of string(s) of declination(s) of object(s) to be processed. fil : str Name of filter used for images which are currently being processed. aper_rad : float User-specified aperture radius in arcseconds. ann_in_rad : float User-specified annulus inner radius in arcseconds. ann_out_rad : float User-specified annulus outer radius in arcseconds. name : str Object type that get_counts is being ran on (e.g. target, comp, check). date : str Date of observation. set_rad : Boolean Determine whether user would like to use default aperture/annulus radii or specify their own. centroid_plot : Boolean Whether or not to plot centroid shifts for object. Returns ------- aper_sum : numpy.ndarray Array of floats corresponding to aperture sums of each source. err : numpy.ndarray Array of floats corresponding to uncertainty of each aperture sum. date_obs : numpy.ndarray Array of floats corresponding to Julian Date of each image. altitudes : numpy.ndarray Array of floats corresponding to the altitude of each image. saturated : list List of list(s) containing the file path of any image whose source meets or exceeds the expected saturation level. exptimes : numpy.ndarray Array of floats corresponding to exposure time of each image. init_coords : numpy.ndarray Array of strings corresponding to the pixel coordinates (x,y) of the R.A. and dec. of the image's source, according to its WCS solution. cent_coords : numpy.ndarray Array of strings corresponding to the central pixel coordinates (x,y) of the centroided aperture. If the centroid routine failed, the string 'init' is returned for that image. image_num : numpy.ndarray Array of integers containing the number of each image in dirtarget. sat_qual : numpy.ndarray Data quality mask that contains 0s for images that do not have a saturated source and 1s for source that do. cent_qual : numpy.ndarray Data quality mask that contains 0s for images with successful aperture centroiding and 1s for images with failed centoiding or poor WCS solutions. """ dirtarget_wcs = os.path.join(dirtarget, 'ISR_Images', fil, 'WCS') files = sorted(glob.glob(os.path.join(dirtarget_wcs, '*.fits'))) size_files = len(files) size_sources = len(ra) # Initialize output arrays. # Dimensions: #sources x #(images in dirtarget) aper_sum = np.empty([size_sources, size_files], dtype=float) aper_sum[:][:] = np.nan err = np.empty([size_sources, size_files], dtype=float) err[:][:] = np.nan date_obs = np.empty([size_sources, size_files], dtype=float) date_obs[:][:] = np.nan altitudes = np.empty([size_sources, size_files], dtype=float) altitudes[:][:] = np.nan saturated = [] exptimes = np.empty([size_sources, size_files], dtype=float) exptimes[:][:] = np.nan init_coords = np.empty([size_sources, size_files], dtype=object) init_coords[:][:] = 'init' cent_coords = np.empty([size_sources, size_files], dtype=object) cent_coords[:][:] = 'init' image_num = np.empty([size_sources, size_files], dtype=object) image_num[:][:] = 'init' pix_radius = np.empty(size_sources, dtype=float) pix_radius[:] = np.nan image_arr = np.empty([size_sources, size_files], dtype=float) image_arr[:][:] = np.nan sat_qual = np.empty([size_sources, size_files], dtype=int) sat_qual[:][:] = 0 cent_qual = np.empty([size_sources, size_files], dtype=int) cent_qual[:][:] = 0 for i, (ra_i, dec_i) in enumerate(zip(ra, dec)): print('\nProcessing {} star ({})...'.format(name, fil)) im = None p1 = None p2 = None circ = None fig = None ax = None pix_radius = None saturated_i = [] # Initialize nine evenly-spaced indices to plot a centroiding summary. cent_ind = np.linspace(0, size_files - 1, 9).astype(int) if centroid_plot: fig, ax = plt.subplots(nrows=3, ncols=3, figsize=(10, 8)) ax = ax.flatten() for k in range(0, 9): ax[k].set_title('Image {}'.format(cent_ind[k]), size=10) for l in (ax[k].get_xticklabels() + ax[k].get_yticklabels()): l.set_fontsize(8) # fig_anim, ax_anim = plt.subplots(nrows=1, ncols=1, figsize=(10,8)) # im_anim = plt.imshow() # def animate(i): for j, item in enumerate(files): o_file = os.path.join(dirtarget_wcs, item) hdulist = fits.open(o_file) header = hdulist[0].header data = hdulist[0].data im_str = str(o_file) im_n = im_str[-10:-7] try: int(im_n) except ValueError: im_n = j image_num[i][j] = im_n # Read output information from header of image being processed. exptimes[i][j] = float(header['EXPTIME']) date_j = header['DATE-OBS'] t = Time(date_j) time = t.jd date_obs[i][j] = float(time) altitudes[i][j] = float(header['OBJCTALT']) # Check if WCS solution was successful. if header['WCSMATCH'] < 10: print('\nLess than 10 stars matched in WCS calculation.') cent_qual[i][j] = 1 continue # Find pixel location of R.A. and dec. according to WCS solution w = WCS(header) coords = SkyCoord(ra_i, dec_i, unit=(u.hourangle, u.deg)) px_dec, py_dec = w.wcs_world2pix(coords.ra.deg, coords.dec.deg, 1) px, py = int(px_dec), int(py_dec) init_coords_pix = (px, py) init_coords[i][j] = ','.join(map(str, init_coords_pix)) # Define source region as a 20x20 square centered at (px,py) star = data[(py - 19):(py + 21), (px - 19):(px + 21)] # Check that region lies entirely within image. if ((py - 19) < 0) or ((py + 21) > 2084): print('\n{} star not entirely in the image for'.format(name) + ' image number {}'.format(im_n)) cent_qual[i][j] = 1 continue if ((px - 19) < 0) or ((px + 21) > 3072): print('\n{} star not entirely in the image for'.format(name) + ' image number {}'.format(im_n)) cent_qual[i][j] = 1 continue star_flat = star.reshape(1, len(star) * len(star[0])) # Check that source does not exceed the expected saturation level. max_pix = int(np.amax(star_flat)) if max_pix >= header['SATLEVEL']: print('\n{} star met or exceeded saturation '.format(name) + 'level for image number {}.'.format(im_n)) print('\nSaturation value: {}'.format(header['SATLEVEL'])) print('\nMax aperture value: {}'.format(max_pix)) saturated_i.append(item) sat_qual[i][j] = 1 continue # Peform aperture centroiding for the source. # If centroiding failed, then move onto the next image. FWHM = 4 try: mean, median, std = sigma_clipped_stats(star, sigma=3.0) daofind = DAOStarFinder(fwhm=FWHM, threshold=5. * std) sources = daofind(star - median) px_cent = np.average(sources['xcentroid']) py_cent = np.average(sources['ycentroid']) except TypeError: print('\nCentroiding failed for image {}.'.format(im_n)) cent_qual[i][j] = 1 continue # Return centroided pixel coordinates. x_cent = int(px - 19 + px_cent) y_cent = int(py - 19 + py_cent) cent_coords_pix = (x_cent, y_cent) cent_coords[i][j] = ','.join(map(str, cent_coords_pix)) cent_equa = SkyCoord.from_pixel(x_cent, y_cent, w) # Define aperture and annulus radii. radius = None r_in = None r_out = None if set_rad: radius = float(aper_rad) * u.arcsec r_in = float(ann_in_rad) * u.arcsec r_out = float(ann_out_rad) * u.arcsec else: radius = 4 * u.arcsec r_in = 25 * u.arcsec r_out = 27 * u.arcsec # Create SkyCircularAperture and SkyCircularAnnulus objects # centered at the position of the star whose counts are being # summed. aperture = SkyCircularAperture(cent_equa, radius) annulus = SkyCircularAnnulus(cent_equa, r_in=r_in, r_out=r_out) apers = (aperture, annulus) secpix1 = abs(hdulist[0].header['SECPIX1']) # Determine the area of the aperture and annulus using the # arcseconds per pixel in the horizontal dimension header keyword. aper_area = np.pi * (radius / secpix1)**2 area_out = np.pi * (r_out / secpix1)**2 area_in = np.pi * (r_in / secpix1)**2 annulus_area = area_out - area_in pix_radius = radius.value / secpix1 # Call aperture_photometry function in order to sum all of the # counts in both the aperture and annulus for item. phot_table = aperture_photometry(hdulist, apers) # Remove the background level from the aperture sum. bkg_mean = phot_table['aperture_sum_1'] / annulus_area bkg_sum = bkg_mean * aper_area final_sum = phot_table['aperture_sum_0'] - bkg_sum phot_table['residual_aperture_sum'] = final_sum # Determine the error in the aperture sum and background level. # source_err = np.sqrt(phot_table['residual_aperture_sum']) source = phot_table['residual_aperture_sum'] aper_sum[i][j] = phot_table['residual_aperture_sum'][0] err[i][j] = np.sqrt(source + bkg_sum) j_plot = np.where(cent_ind == j)[0] if centroid_plot: if j in cent_ind: j_plot = j_plot[0] p1 = ax[j_plot].scatter([px + 1], [py + 1], c="thistle", label="Original", edgecolors='mistyrose') p2 = ax[j_plot].scatter([x_cent + 1], [y_cent + 1], c="rebeccapurple", label="Corrected", edgecolors='mistyrose') im = ax[j_plot].imshow(star, extent=(px - 19, px + 21, py - 19, py + 21), cmap='magma', origin='lower') ax[j_plot].set_title('Image {}'.format(im_n), size=10) circ = Circle((x_cent + 1, y_cent + 1), radius.value / secpix1, fill=False, label='Aperture', ls='-', color='mistyrose') ax[j_plot].add_patch(circ) for label in (ax[j_plot].get_xticklabels() + ax[j_plot].get_yticklabels()): label.set_fontsize(8) hdulist.close() del data saturated.append(saturated_i) if centroid_plot: fig.subplots_adjust(right=0.8) cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7]) cb = fig.colorbar(im, cax=cbar_ax) plt.setp(cb.ax.get_yticklabels(), fontsize=8) plt.figlegend([p1, p2, circ], ['Original', 'Corrected', 'Aperture'], fontsize=14) fig.suptitle('Aperture Centroiding on {}, {}'.format(ra_i, dec_i), fontsize=16) fig.text(0.5, 0.04, 'x [pixel]', ha='center') fig.text(0.04, 0.5, 'y [pixel]', va='center', rotation='vertical') if name == 'comp': out_file = os.path.join('centroid_{}{}_{}_{}.pdf'.format( name, i + 1, date, fil)) else: out_file = os.path.join('centroid_{}_{}_{}.pdf'.format( name, date, fil)) plt.savefig( os.path.join(dirtarget, 'ISR_Images', fil, 'WCS', 'output', out_file)) return aper_sum, err, date_obs, altitudes, saturated, exptimes, \ init_coords, cent_coords, image_num, sat_qual, cent_qual
def sb_at_frb(host, cut_dat: np.ndarray, cut_err: np.ndarray, wcs: WCS, fwhm=3., physical=False, min_uncert=2): """ Measure the surface brightness at an FRB location in a host galaxy Args: host (Host object): host galaxy object from frb repo cut_dat (np.ndarray): data (data from astorpy 2D Cutout object) cut_err (np.ndarray): inverse variance of data (from astropy 2D Cutout object) wcs (WCS): WCS for the cutout fwhm (float, optional): FWHM of the PSF of the image in either pixels or kpc. Defaults to 3 [pix]. physical (bool, optional): If True, FWHM is in kpc. Defaults to False. min_uncert (int, optional): Minimum localization unceratainty for the FRB, in pixels. Defaults to 2. Returns: tuple: sb_average, sb_average_err [counts/sqarcsec] """ # Generate the x,y grid of coordiantes x = np.arange(np.shape(cut_dat)[0]) y = np.arange(np.shape(cut_dat)[1]) xx, yy = np.meshgrid(x, y) coords = wcs_utils.pixel_to_skycoord(xx, yy, wcs) xfrb, yfrb = wcs_utils.skycoord_to_pixel(host.frb.coord, wcs) plate_scale = coords[0, 0].separation(coords[0, 1]).to('arcsec').value # Calculate total a, b uncertainty (FRB frame) uncerta, uncertb = host.calc_tot_uncert() # Put in pixel space uncerta /= plate_scale uncertb /= plate_scale # Set a minimum threshold uncerta = max(uncerta, min_uncert) uncertb = max(uncertb, min_uncert) # check if in ellipse -- pixel space! theta = host.frb.eellipse['theta'] in_ellipse = ( (xx - xfrb.item()) * np.cos(theta) + (yy - yfrb.item()) * np.sin(theta))**2 / (uncerta**2) + ( (xx - xfrb.item()) * np.sin(theta) - (yy - yfrb.item()) * np.cos(theta))**2 / (uncertb**2) <= 1 idx = np.where(in_ellipse) xval = xx[idx] yval = yy[idx] # x, y gal on the tilted grid (same for frb coords) xp = yval * np.cos(theta) - xval * np.sin(theta) yp = xval * np.cos(theta) + yval * np.sin(theta) xpfrb = yfrb.item() * np.cos(theta) - xfrb.item() * np.sin(theta) ypfrb = xfrb.item() * np.cos(theta) + yfrb.item() * np.sin(theta) # convert fwhm from pixels to arcsec or kpc to arcsec if physical: fwhm_as = fwhm * units.kpc * defs.frb_cosmo.arcsec_per_kpc_proper( host.z) else: fwhm_as = fwhm * plate_scale * units.arcsec # Aperture photometry at every pixel in the ellipse photom = [] photom_var = [] for i in np.arange(np.shape(idx)[1]): aper = SkyCircularAperture(coords[idx[0][i], idx[1][i]], fwhm_as) apermap = aper.to_pixel(wcs) # aperture photometry for psf-size within the galaxy photo_frb = aperture_photometry(cut_dat, apermap) photo_err = aperture_photometry(1 / cut_err, apermap) photom.append(photo_frb['aperture_sum'][0]) photom_var.append(photo_err['aperture_sum'][0]) # ff prob distribution p_ff = np.exp(-(xp - xpfrb)**2 / (2 * uncerta**2)) * np.exp(-(yp - ypfrb)**2 / (2 * uncertb**2)) f_weight = (photom / (np.pi * fwhm_as.value**2)) * p_ff # weighted photometry fvar_weight = (photom_var / (np.pi * fwhm_as.value**2)) * p_ff # weighted sigma weight_avg = np.sum(f_weight) / np.sum(p_ff) # per unit area (arcsec^2) # Errors weight_var_avg = np.sum(fvar_weight) / np.sum(p_ff) weight_err_avg = np.sqrt(weight_var_avg) return weight_avg, weight_err_avg
clusters = pd.merge(info, derived, left_index=True, right_index=True) clusters_young = clusters.loc[(clusters['Age'] < 7.0) & (clusters['Mass'] > 6.0)] coordinates = clusters_young[['RA', 'Dec']] positions = list() apertures = list() for i in coordinates.index: position = SkyCoord(ra=coordinates['RA'][i] * u.degree, dec=coordinates['Dec'][i] * u.degree, frame='fk5') position_icrs = position.transform_to('icrs') positions.append(position_icrs) aperture = SkyCircularAperture(positions=position_icrs, r=0.3 * u.arcsec) apertures.append(aperture) ### Draw figures. fig = plt.figure() ax = plt.subplot(projection=wcs_cut) im = plt.imshow(data_cut * 1000, origin='lower', cmap='viridis_r', vmax=0.4, vmin=0.0) # coordinates. plt.xlabel('J2000 Right Ascension') plt.ylabel('J2000 Declination')
wavelength = ['24um', '70um', '33GHz', '24nd70'] value = ['region', 'flux', 'uncertainty', 'SFR'] df = pd.DataFrame(index=wavelength, columns=value) df_center = pd.DataFrame(index=wavelength, columns=value) ### south arm peak ## herschel flux fitsimage = imageDir + 'herschel_70um.fits' header = fits.open(fitsimage)[1].header wcs_her = WCS(header).celestial data_70um = fits.open(fitsimage)[1].data southarm_sky = SkyCircularAperture(positions=position, r=3 * ratio * u.arcsec) southarm_pix = southarm_sky.to_pixel(wcs_her) fig = plt.figure() ax = plt.subplot('111', projection=wcs_her) ax.imshow(data_70um, origin='lower', vmax=0.05) southarm_pix.plot() flux = aperture_photometry(data_70um, apertures=southarm_pix)['aperture_sum'][0] SFR_70um = sfr_70um(flux) df['region']['70um'] = 'south' df['flux']['70um'] = flux df['SFR']['70um'] = SFR_70um
usecols=[2], skiprows=1) #Use circular area to calulcate radius #Create circular aperatures in skycoordinates coords, radius, sky_apers = [], [], [] iden_int, rad = [], [] obj, pixobs = [], [] for l in range(0, len(area)): rad.append(round(np.sqrt(area[l] / np.pi), 4)) iden_int.append(int(iden[l])) coords.append(SkyCoord(ra[l], dec[l], unit="deg")) radius.append(rad[l] * u.pix) # pixels sky_apers.append(SkyCircularAperture(coords[l], r=radius[l])) #Makes sure that the correct number of apertures were created print(len(sky_apers)) filter_list = [ 'f225w', 'f275w', 'f336w', 'f390w', 'f435w', 'f475w', 'f606w', 'f625w', 'f775w', 'f814w', 'f850lp', 'f105w', 'f110w', 'f125w', 'f140w', 'f160w' ] filter_list_a611 = [ 'f225w', 'f275w', 'f336w', 'f390w', 'f435w', 'f475w', 'f606w', 'f775w', 'f814w', 'f850lp', 'f105w', 'f110w', 'f125w', 'f140w', 'f160w' ] macs1423_filter_list = [ 'f225w', 'f275w', 'f336w', 'f390w', 'f435w', 'f475w', 'f606w', 'f775w', 'f850lp', 'f105w', 'f110w', 'f125w', 'f140w', 'f160w'
data = fits.open(fitsimage)[item].data data = np.squeeze(data) data_masked = np.ma.masked_invalid(data) return wcs, data_masked ############################################################ # main program ### Draw different regions. position = SkyCoord(dec=0.8309 * u.degree, ra=204.9906 * u.degree, frame='icrs') apertures['center']['sky'] = SkyCircularAperture(position, r=3 * u.arcsec) apertures['ring around center']['sky'] = SkyCircularAnnulus(position, r_in=3 * u.arcsec, r_out=7 * u.arcsec) position = SkyCoord(dec=0.8349 * u.degree, ra=204.9930 * u.degree, frame='icrs') apertures['northarm']['sky'] = SkyEllipticalAperture(position, a=15 * u.arcsec, b=7 * u.arcsec, theta=340 * u.degree) position = SkyCoord(dec=0.8275 * u.degree, ra=204.9884 * u.degree, frame='icrs') apertures['southarm']['sky'] = SkyEllipticalAperture(position, a=10 * u.arcsec,
def app_phot(self, imagefile, ras, decs, fwhm, plot=False, save=False): ''' Computes the aperture photometry on the image, for the coordinates given. Parameters ---------- imagefile : str The name of the fits file with the image. ras : array Array of floats with the RA positions for which aperture photometry is needed. decs : array Array of floats with the DEC positions for which aperture photometry is needed. fwhm : float Average FWHM of the field used to compute the aperture. plot : boolean Shall the apertures be plotted in the plot directory? save : boolean Save the aperture measurement to a file. Returns ------- phot : QTable A table of the photometry with the following columns: 'id': The source ID. 'xcenter', 'ycenter': The x and y pixel coordinates of the input aperture center(s). 'celestial_center': 'aperture_sum': The sum of the values within the aperture. 'aperture_sum_err': The corresponding uncertainty in the 'aperture_sum' values. Returned only if the input error is not None. ''' data = fits.open(imagefile)[self.ext].data filt = fitsutils.get_par(imagefile, 'FILTER', self.ext) mjd = Time(fitsutils.get_par(imagefile, "DATE-OBS", ext=self.ext)).mjd zp = fitsutils.get_par(imagefile, 'ZP', self.ext) color = fitsutils.get_par(imagefile, 'COLOR', self.ext) kcoef = fitsutils.get_par(imagefile, 'KCOEF', self.ext) zperr = fitsutils.get_par(imagefile, 'ZPERR', self.ext) if zp is None: zp = 0 if zperr is None: zperr = 0 wcs = astropy.wcs.WCS(fits.open(imagefile)[self.ext].header) positions = SkyCoord(ras*u.deg, decs*u.deg, frame='icrs') # Set aperture radius to three times the fwhm radius aperture_rad = np.median(fwhm)*2* u.arcsec aperture = SkyCircularAperture(positions, r=aperture_rad) annulus_apertures = SkyCircularAnnulus(positions, r_in=aperture_rad*2, r_out=aperture_rad*4) #Convert to pixels pix_aperture = aperture.to_pixel(wcs) pix_annulus = annulus_apertures.to_pixel(wcs) pix_annulus_masks = pix_annulus.to_mask(method='center') #Plot apertures from astropy.visualization import simple_norm try: if np.ndim(ras) == 0: c = wcs.wcs_world2pix(np.array([[ras, decs]]), 0) else: c = wcs.wcs_world2pix(np.array([ras, decs]).T, 0) except ValueError: self.logger.error('The vectors of RAs, DECs could not be converted into pixels using the WCS!') self.logger.error(str(np.array([ras, decs]).T)) if plot: x = c[:,0] y = c[:,1] plt.figure(figsize=(10,10)) norm = simple_norm(data, 'sqrt', percent=99) plt.imshow(data, norm=norm) pix_aperture.plot(color='white', lw=2) pix_annulus.plot(color='red', lw=2) plt.xlim(x[0]-200, x[0]+200) plt.ylim(y[0]-200, y[0]+200) plt.title('Apertures for filter %s'%filt) plt.savefig(os.path.join(self._plotpath, "apertures_cutout_%s.png"%os.path.basename(imagefile))) plt.clf() #Divide each pixel in 5 subpixels to make apertures apers = [pix_aperture, pix_annulus] phot_table = aperture_photometry(data, apers, method='subpixel', subpixels=5) for col in phot_table.colnames: phot_table[col].info.format = '%.8g' # for consistent table output bkg_median = [] std_counts = [] for mask in pix_annulus_masks: annulus_data = mask.multiply(data) annulus_data_1d = annulus_data[mask.data > 0] _, median_sigclip, stdv_clip = sigma_clipped_stats(annulus_data_1d) bkg_median.append(median_sigclip) std_counts.append(stdv_clip) bkg_median = np.array(bkg_median) std_counts = np.array(std_counts) phot = aperture_photometry(data, pix_aperture) phot['annulus_median'] = bkg_median phot['annulus_std'] = std_counts phot['aper_bkg'] = bkg_median * pix_aperture.area() phot['aper_sum_bkgsub'] = phot['aperture_sum'] - phot['aper_bkg'] # Flux = Gain * Counts / Exptime. exptime = fitsutils.get_par(imagefile, 'EXPTIME', self.ext) gain = fitsutils.get_par(imagefile, self.gain_keyword, self.ext) flux = gain * phot['aper_sum_bkgsub'] / exptime inst_mag = -2.5*np.log10(flux) phot['flux'] = flux phot['inst_mag'] = inst_mag #Noise is the poisson noise of the source plus the background noise for the extracted area err = np.sqrt (flux + pix_aperture.area() * std_counts**2) #Transform pixels to magnitudes flux2 = gain * (phot['aper_sum_bkgsub']+err) / exptime inst_mag2 = -2.5*np.log10(flux2) errmag = np.abs(inst_mag2 - inst_mag) phot['err_counts'] = err phot['err_mag'] = errmag for col in phot.colnames: phot[col].info.format = '%.8g' # for consistent table output if save: appfile = os.path.join(self._photpath, fitsutils.get_par(imagefile, "OBJECT", self.ext)+".app.phot.txt") self.logger.info('Creating aperture photometry out file as %s'%appfile) #Save the photometry into a file if (not os.path.isfile(appfile)): with open(appfile, 'w') as f: f.write("mjd filter instr_mag zp zperr color kcoef mag magerr\n") with open(appfile, 'a') as f: self.logger.info('Adding aperture photometry to file %s'%appfile) f.write("%.3f %s %.4f %.4f %.4f %s %.4f %.4f %.4f\n"%(mjd, filt, phot['inst_mag'].data[0], \ zp, zperr, color, kcoef, phot['inst_mag'].data[0]+ zp, phot['err_mag'].data[0])) return phot
def flux(nddata, tbl, zeroPoint, gain, radius): """ Derive the flux and the magnitude within circular aperture Parameters ---------- nddata: numpy array Numpy array where is saved the data and the sky coordinates wcs. tbl: table Table where the first column is the id, the second the ra coordinate, the third is dec coordinate and the four the skycoordinate. zeroPoint: float Zero point of your image gain: float The gain of your image radius: float The radius of your circle in arcsec to derive the flux Return ------ Table with id, skycoord, flux, flux error, magnitude, magnitude error """ # By convention, sextractor if gain == 0.: gain = 1000000000000000000000000000. result = tbl['id', 'skycoord'] result['flux'] = float(np.size(tbl)) result['flux_err'] = float(np.size(tbl)) for i in range(np.size(tbl)): # Recover the position for each object position = tbl['skycoord'][i] if hdr['NAXIS1'] >= 50 and hdr['NAXIS2'] >= 50: # size of the background map sizeBkg = 50 # cut the mosaic in stamp to the wcs coordinate of your objects cutout = Cutout2D(nddata.data, position, (sizeBkg, sizeBkg), wcs=nddata.wcs) # Recover new data and wcs of the stamp data = cutout.data wcs = cutout.wcs else: # size of the background map sizeBkg = min(hdr['NAXIS1'], hdr['NAXIS2']) # Keep data and wcs of the initial image data = nddata.data wcs = nddata.wcs ######################### ####### Background ###### ######################### # Mask sources mask = make_source_mask(data, snr=1, npixels=3, dilate_size=3) # Derive the background and the rms image bkg = Background2D( data, int(sizeBkg / 10), filter_size=1, sigma_clip=None, bkg_estimator=SExtractorBackground(SigmaClip(sigma=2.5)), bkgrms_estimator=StdBackgroundRMS(SigmaClip(sigma=2.5)), exclude_percentile=60, mask=mask) ########################### ###### Aperture Flux ###### ########################### nddataStamp = NDData(data=data - bkg.background, wcs=wcs) # Calculate the total error error = calc_total_error(cutout.data, bkg.background_rms, gain) # Define a cicularAperture in the wcs position of your objects apertures = SkyCircularAperture(position, r=radius * u.arcsec) # Derive the flux and error flux phot_table = aperture_photometry(nddataStamp, apertures, error=error) phot_table['aperture_sum'].info.format = '%.8g' phot_table['aperture_sum_err'].info.format = '%.8g' # Recover data result['flux'][i] = phot_table['aperture_sum'][0] result['flux_err'][i] = phot_table['aperture_sum_err'][0] ########################### ######## Magnitude ######## ########################### # convert flux into magnitude result['mag'] = -2.5 * np.log10(result['flux']) + zeroPoint # convert flux error into magnitude error result['mag_err'] = 1.0857 * (result['flux_err'] / result['flux']) return result
plt.show() #sys.exit(0) #position= SkyCoord([ICRS(ra=ra_deg*u.deg,dec=dec_deg*u.deg)]) position = SkyCoord(ra_deg, dec_deg, unit=(u.hourangle, u.deg), frame='icrs') print(position) print(position.ra) print(position.dec) #sys.exit(0) r4 = fwhm * 4. * u.arcsec r5 = fwhm * 5. * u.arcsec r6 = fwhm * 6. * u.arcsec r7 = fwhm * 7. * u.arcsec #aperture=SkyCircularAperture(position, r=4. * u.arcsec) aperture = SkyCircularAperture(position, r4) print(aperture) r_as = aperture.r print(r_as) #sys.exit(0) aperture_pix = aperture.to_pixel(wcs) print(aperture_pix) r_pix = aperture_pix.r print(r_pix) #sys.exit(0) #phot_table = aperture_photometry(imdata, aperture,wcs=wcs) phot_table = aperture_photometry(imdata, aperture_pix) print(phot_table)
radec_deg[j1] = [ra_deg[j1], dec_deg[j1]] # print(j1,j2,radec_deg[j1]) ra_hhmmss[j1] = df_refstar['RefStarRA_hhmmss'][j2] dec_ddmmss[j1] = df_refstar['RefStarDEC_ddmmss'][j2] # print(i,j1,radec_deg[j1],ra_hhmmss[j1],dec_ddmmss[j1]) rmag[j1] = df_refstar['Rmag'][j2] rmag_err[j1] = df_refstar['Rmag_err'][j2] r_circle[j1] = df_refstar['R_circle_as'][j2] r_inner[j1] = df_refstar['R_inner_as'][j2] r_outer[j1] = df_refstar['R_outer_as'][j2] # position= SkyCoord(ra_deg[j1],dec_deg[j1],unit=(u.hourangle,u.deg),frame='icrs') position = SkyCoord(ra_deg[j1], dec_deg[j1], unit=(u.deg), frame='icrs') # print(position) r_circle_as = r_circle[j1] * u.arcsec # print(r_circle_as) aperture[j1] = SkyCircularAperture(position, r=r_circle_as) # print(aperture[j1]) r_inner_as = r_inner[j1] * u.arcsec r_outer_as = r_outer[j1] * u.arcsec aper_annu[j1] = SkyCircularAnnulus(position, r_inner_as, r_outer_as) # print(aper_annu[j1]) # print(aper_annu[j1].r_in) # print(aper_annu[j1].r_out) # refstarID[j1]=df_refstar['RefStarID'][j2] # refstarRA_deg[j1]=df_refstar['RefStarRA_deg'][j2] # refstarDEC_deg[j1]=df_refstar['RefStarDEC_deg'][j2] # print(refstarID[j1]) # print(refstarRA_deg[j1] # print(refstarDEC_deg[j1])
# data_FUV_tmp=data_FUV_tmp*10**17/(1.5**2)*4.25*10**10 # # regrid the image and add the spitzer and FUV map together # SFR=8.1*10**(-2)*data_FUV_tmp+3.2*10**-3*data_24um # SFR_ob=3.2*10**-3*data_24um # SFR_uob=8.1*10**(-2)*data_FUV_tmp # ratio=intensity_70um/data_24um ## add the aperture ra = 204 * u.degree + 58 * u.arcmin + 15 * u.arcsec dec = 50 * u.arcmin + 13 * u.arcsec south = SkyCoord(ra=ra, dec=dec, frame='icrs') Coordinates['70']['south'] = south south_her = SkyCircularAperture(positions=Coordinates['70']['south'], r=3 * 1.24 * u.arcsec).to_pixel(herschel_wcs_cut) ra = 204 * u.degree + 58 * u.arcmin + 13 * u.arcsec dec = 50 * u.arcmin + 13 * u.arcsec south = SkyCoord(ra=ra, dec=dec, frame='icrs') Coordinates['24']['south'] = south south_spi = SkyCircularAperture(positions=Coordinates['24']['south'], r=3 * 1.24 * u.arcsec).to_pixel(herschel_wcs_cut) ra = 204 * u.degree + 58 * u.arcmin + 15 * u.arcsec dec = 50 * u.arcmin + 25 * u.arcsec Coordinates['70']['center'] = SkyCoord(ra=ra, dec=dec, frame='icrs') center_her = SkyCircularAperture(positions=Coordinates['70']['center'], r=3 * 1.24 *