예제 #1
0
def get_one_contrast_and_SN(data, positions, fwhm, fwhm_flux):
    '''
    Args:
        path : a string. The path of repository where the files are.
        positions : a list of tuple (x,y). The coordinates of companions.
    Return:
        flux : a np.array, 1 dimension. Store the list of each companion's flux.
        SN : a np.array, 1 dimension. Store the list of each companion's Signal to Noise ratio.
    '''

    # flux
    aperture = CircularAperture(positions, r=2)
    annulus = CircularAnnulus(positions, r_in=4, r_out=6)

    # flux
    flux_companion = aperture_photometry(data, [aperture, annulus])
    flux_companion['aperture_sum_0', 'aperture_sum_1'].info.format = '%.8g'
    flux = (flux_companion['aperture_sum_0'] / aperture.area) / fwhm_flux

    # SN
    ds9 = vip.Ds9Window()
    ds9.display(data)
    SN = vip.metrics.snr(data, source_xy=positions[0], fwhm=fwhm, plot=True)

    return flux[0], SN
def get_contrast_and_SN(res_fake, res_real, positions, fwhm_for_snr, fwhm_flux,
                        r_aperture, r_in_annulus, r_out_annulus):
    '''
    Args:
        res_fake : a 2D np.array. The path of repository where the files are.
        res_real : a 2D np.array. The path of another repository where the files are, for calculating snr.
        positions : a list of tuple (x,y). The coordinates of companions.
        fwhm : a float. fwhm's diameter.
        fwhm_flux : a float. The flux of fwhm.
    Return:
        contrast : a np.array, 1 dimension. Store the list of each companion's flux.
        SN : a np.array, 1 dimension. Store the list of each companion's Signal to Noise ratio.
    '''

    aperture = CircularAperture(positions, r=r_aperture)
    annulus = CircularAnnulus(positions,
                              r_in=r_in_annulus,
                              r_out=r_out_annulus)

    # contrast
    flux_companion = aperture_photometry(res_fake, [aperture, annulus])
    flux_companion['aperture_sum_0', 'aperture_sum_1'].info.format = '%.8g'
    flux = flux_companion['aperture_sum_0']
    contrast = (flux_companion['aperture_sum_0']) / fwhm_flux

    # SN
    SN = vip.metrics.snr(array=res_fake,
                         source_xy=positions,
                         fwhm=fwhm_for_snr,
                         plot=False,
                         array2=res_real,
                         use2alone=True)

    return contrast.data[0], SN, flux.data[0]
예제 #3
0
    def set_aperture_properties(self):
        """
        Calculate the aperture photometry.

        The values are set as dynamic attributes.
        """
        apertures = [
            CircularAperture(self._xypos_finite, radius)
            for radius in self.aperture_params['aperture_radii']
        ]
        aper_phot = aperture_photometry(self.model.data,
                                        apertures,
                                        error=self.model.err)

        for i, aperture in enumerate(apertures):
            flux_col = f'aperture_sum_{i}'
            flux_err_col = f'aperture_sum_err_{i}'

            # subtract the local background measured in the annulus
            aper_phot[flux_col] -= (self.aper_bkg_flux * aperture.area)

            flux = aper_phot[flux_col]
            flux_err = aper_phot[flux_err_col]
            abmag, abmag_err = self.convert_flux_to_abmag(flux, flux_err)
            vegamag = abmag - self.abvega_offset
            vegamag_err = abmag_err

            idx0 = 2 * i
            idx1 = (2 * i) + 1
            setattr(self, self.aperture_flux_colnames[idx0], flux)
            setattr(self, self.aperture_flux_colnames[idx1], flux_err)
            setattr(self, self.aperture_abmag_colnames[idx0], abmag)
            setattr(self, self.aperture_abmag_colnames[idx1], abmag_err)
            setattr(self, self.aperture_vegamag_colnames[idx0], vegamag)
            setattr(self, self.aperture_vegamag_colnames[idx1], vegamag_err)
예제 #4
0
    def get_sky_from_annulus(self, r_in=3, r_out=5, units='arcsec'):
        """ Measure the sky flux with aperture photometry in an annulus.
        :param r_in, r_out: float
            inner, outer radius of the sky annulus
        :param units: 'arcsec' or 'pixels'
           units for the radii. 
        :return: skyval : the measured average sky brightness per pixel.
        """
        self.skyxy = [self.x_0, self.y_0]
        if units.lower()=='arcsec':
            r_in = r_in / self.pixscale
            r_out = r_out / self.pixscale
        elif not units.lower().startswith('pix'):
            raise RuntimeError('Unknown unit %s'%units)

        skyannulus = CircularAnnulus(self.skyxy, r_in=r_in, r_out=r_out)
        phot_table = aperture_photometry(
            self.imdat, skyannulus, error=None, mask=None,
            method=u'exact', subpixels=5, unit=None, wcs=None)
        skyvaltot = phot_table['aperture_sum']

        self.skyannpix = [r_in, r_out]
        self.skyvalperpix = skyvaltot / skyannulus.area()

        # TODO: compute the error properly
        self.skyerr = 0.0
        return
예제 #5
0
def redoAperturePhotometry(catalog, imagedata, aperture, annulus_inner,
                           annulus_outer):
    """ Recalculate the FLUX column off a fits / BANZAI CAT extension based on operature photometry. """
    _logger.info("redoing aperture photometry")
    positions = [(catalog['x'][ii], catalog['y'][ii])
                 for ii in range(len(catalog['x']))]

    apertures = CircularAperture(positions, r=aperture)
    sky_apertures = CircularAnnulus(positions,
                                    r_in=annulus_inner,
                                    r_out=annulus_outer)
    sky_apertures_masks = sky_apertures.to_mask(method='center')
    bkg_median = []
    for mask in sky_apertures_masks:
        annulus_data = mask.multiply(imagedata)
        annulus_data_1d = annulus_data[mask.data > 0]
        _, median_sigclip, _ = sigma_clipped_stats(annulus_data_1d)
        bkg_median.append(median_sigclip)
    bkg_median = np.array(bkg_median)

    phottable = aperture_photometry(imagedata, [apertures, sky_apertures])

    # plt.plot (phottable['aperture_sum_1'] / sky_apertures.area, phottable['aperture_sum_1'] / sky_apertures.area - bkg_median,'.')
    # plt.savefig ('sky.png')

    newflux = phottable['aperture_sum_0'] - bkg_median * apertures.area

    # oldmag = -2.5 * np.log10(catalog['FLUX'])
    # newmag = -2.5 * np.log10 (newflux)
    # _logger.info ( newmag - oldmag)
    # plt.plot (newmag, newmag - oldmag, '.')
    # plt.savefig("Comparison.png")

    catalog['FLUX'] = newflux
def create_dao_like_sourcelists(fitsfile,
                                sl_filename,
                                sources,
                                aper_radius=4.,
                                make_region_file=False):
    """Make DAOphot-like sourcelists

    Parameters
    ----------
    fitsfile : string
        Name of the drizzle-combined filter product to used to generate photometric sourcelists.


    sl_filename : string
        Name of the sourcelist file that will be generated by this subroutine

    sources : astropy table
        Table containing x, y coordinates of identified sources

    aper_radius : float
        Aperture radius (in pixels) used for photometry. Default value = 4.

    make_region_file : Boolean
        Generate ds9-compatible region file(s) along with the sourcelist? Default value = False

    Returns
    -------
    Nothing.
    """
    # Open and background subtract image
    hdulist = fits.open(fitsfile)
    image = hdulist['SCI'].data
    image -= np.nanmedian(image)

    # Aperture Photometry
    positions = (sources['xcentroid'], sources['ycentroid'])
    apertures = CircularAperture(positions, r=aper_radius)
    phot_table = aperture_photometry(image, apertures)

    for col in phot_table.colnames:
        phot_table[col].info.format = '%.8g'  # for consistent table output
    hdulist.close()

    # Write out sourcelist
    tbl_length = len(phot_table)
    phot_table.write(sl_filename, format="ascii.ecsv")
    log.info("Created sourcelist file '{}' with {} sources".format(
        sl_filename, tbl_length))

    # Write out ds9-compatable .reg file
    if make_region_file:
        reg_filename = sl_filename.replace(".ecsv", ".reg")
        out_table = phot_table.copy()
        out_table['xcenter'].data = out_table['xcenter'].data + np.float64(1.0)
        out_table['ycenter'].data = out_table['ycenter'].data + np.float64(1.0)
        out_table.remove_column('id')
        out_table.write(reg_filename, format="ascii")
        log.info("Created region file '{}' with {} sources".format(
            reg_filename, tbl_length))
예제 #7
0
def calculateFluxes(data,wcs):
	pixelCenter = wcs.world_to_pixel_values(center[0],center[1])
	pixelCenter = (float(pixelCenter[0]),float(pixelCenter[1]))

	apertures = getCircularApetures(pixelCenter,pixelRadius)
	error = np.sqrt(data)   # have to remove the nans 
	nanLocs = np.isnan(error)
	error[nanLocs]=0

	fluxes = []
	fluxErrors = []
	for aperture in apertures:
		print(aperture_photometry(data,aperture,error=error))
		fluxErrors.append(list(aperture_photometry(data,aperture,error=error)['aperture_sum_err'])[0])
		fluxes.append(list(aperture_photometry(data,aperture,error=error)['aperture_sum'])[0])

	return np.array(fluxes), np.array(fluxErrors),pixelCenter
예제 #8
0
def compute_eff_radii(image, plot=False):
    max_pix_rad = np.min(image.shape) // 2
    radius = np.arange(3, max_pix_rad, 3)
    fake_image = np.zeros_like(image)
    fake_image[max_pix_rad // 2:(3 * max_pix_rad) // 2,
               max_pix_rad // 2:(3 * max_pix_rad) //
               2] = image[max_pix_rad // 2:(3 * max_pix_rad) // 2,
                          max_pix_rad // 2:(3 * max_pix_rad) // 2]
    com_x, com_y = centroid_2dg(fake_image)
    aperture_sum = []
    for rad_i in radius:
        aperture = CircularAperture((com_x, com_y), r=rad_i)
        phot_table = aperture_photometry(image, aperture)
        aperture_sum.append(phot_table['aperture_sum'].value)
    aperture_sum = np.array(aperture_sum).squeeze()
    norm_aperture_sum = aperture_sum / aperture_sum[-1]
    half_mass_rad = np.interp(0.5, norm_aperture_sum, radius)
    half_mass_aperture = CircularAperture((com_x, com_y), r=half_mass_rad)
    two_half_mass_aperture = CircularAperture((com_x, com_y),
                                              r=2 * half_mass_rad)
    half_mass_table = aperture_photometry(image, half_mass_aperture)
    two_half_mass_table = aperture_photometry(image, two_half_mass_aperture)
    if plot:
        fig = plt.figure()
        plt.imshow(np.log10(image))
        plt.colorbar(label='log(image)')
        plt.plot(com_x, com_y, '+', markersize=8, color='c')
        half_mass_aperture.plot(color='r', lw=2, label=r'Half mass rad')
        two_half_mass_aperture.plot(color='orange',
                                    lw=2,
                                    label=r'Two half mass rad')
        plt.annotate(
            'Tot mass={:.2}\nHalf mass={:.2}\nTwoHalf mass={:.2}'.format(
                float(aperture_sum[-1]),
                float(half_mass_table['aperture_sum'].value),
                float(two_half_mass_table['aperture_sum'].value)),
            xy=(.1, 1),
            xycoords='axes fraction',
            va='bottom')
        plt.legend()
        plt.close()
        return half_mass_aperture, two_half_mass_aperture, fig
    else:
        return half_mass_aperture, two_half_mass_aperture
예제 #9
0
def get_contrast_and_SN(path, positions, fwhm, fwhm_flux, path_real):
    '''
    Args:
        path : a string. The path of repository where the files are.
        positions : a list of tuple (x,y). The coordinates of companions.
        fwhm : a float. fwhm's diameter.
        fwhm_flux : a float. The flux of fwhm.
        path_real : a string. The path of another repository where the files are, for calculating snr.
    Return:
        contrast : a np.array, 1 dimension. Store the list of each companion's flux.
        SN : a np.array, 1 dimension. Store the list of each companion's Signal to Noise ratio.
    '''
    files = os.listdir(path)
    files.sort()
    
    files_real = os.listdir(path_real)
    files_real.sort()
    l = len(files)
    

    flux = np.zeros(l)
    # contrast
    contrast = np.zeros(l)
    aperture = CircularAperture(positions, r=2)
    annulus = CircularAnnulus(positions, r_in=4, r_out=6)
 
    # SN
    SN = np.zeros(l)

    for i in range(l):
        file = path+'/'+files[i]
        print("file",i,"=", file)
        data = vip.fits.open_fits(file)
        
        # contrast
        flux_companion = aperture_photometry(data, [aperture, annulus])
        flux_companion['aperture_sum_0','aperture_sum_1'].info.format = '%.8g'
        #bkg_mean = flux_companion['aperture_sum_1']/annulus.area
        #bkg_sum_in_companion = bkg_mean * aperture.area
        flux[i] = flux_companion['aperture_sum_0'] 
        contrast[i] = (flux_companion['aperture_sum_0']/aperture.area)/fwhm_flux

        # SN
        lets_plot = False
        if i==2:
            lets_plot = True
            #ds9.display(data)
        file_real = path_real+'/'+files_real[i]
        print("array2 at ",i," =", file_real)
        data2 = vip.fits.open_fits(file_real)
        SN[i] = vip.metrics.snr(array=data, source_xy=positions, fwhm=fwhm, plot=lets_plot, array2 = data2, use2alone=True)
        
    return contrast, SN
예제 #10
0
def aper_phot(image, mask, xc, yc, radii, rsky, debug):

    positions = [(xc, yc)]

    # Define apertures
    apertures = [CircularAperture(positions, r=r) for r in radii]
    if (debug == 1):
        #        print("line ", lineno()," apertures  : ", apertures)
        print("line ", lineno(), " aper_phot: positions: ", positions)
        print("line ", lineno(), " aper_phot: sky aperture ", rsky)
#        for rr in range(0,len(radii)):
#            print("line ", lineno(), " apertures[rr].r, apertures[rr].area :", apertures[rr].r, apertures[rr].area )

# Background, masking bad pixels
    annulus_aperture = CircularAnnulus(positions, r_in=rsky[0], r_out=rsky[1])
    annulus_masks = annulus_aperture.to_mask(method='center')
    bkg_median = []
    for anm in annulus_masks:
        annulus_data = anm.multiply(image)
        annulus_data_1d = annulus_data[anm.data > 0]
        if (debug == 1):
            print("line ", lineno(), " aper_phot: annulus_data_1d.shape ",
                  annulus_data_1d.shape)

        # Remove NaNs, Infs
        annulus_data_1d = annulus_data_1d[np.isfinite(annulus_data_1d)]
        _, median_sigclip, _ = sigma_clipped_stats(annulus_data_1d)
        bkg_median.append(median_sigclip)
        if (debug == 1):
            print("line ", lineno(), " aper_phot: annulus_data_1d.shape ",
                  annulus_data_1d.shape)
            print("line ", lineno(), " aper_phot: median sigclip",
                  median_sigclip)
    if (debug == 1):
        print("line ", lineno(), " aper_phot: bkg_median ", bkg_median)

    phot_table = aperture_photometry(image, apertures, mask=mask)
    #
    junk = []
    area_list = []
    n = -1
    for index in phot_table.colnames:
        if ('aperture_sum' in index):
            n = n + 1
            array = phot_table[index].data[0]
            flux = array.tolist()
            bkg = apertures[n].area * bkg_median[0]
            junk.append(flux - bkg)
            area_list.append(apertures[n].area)
    apflux = np.array(junk)
    area = np.array(area_list)
    #    (diff, encircled)  = differential(apflux,area,True,False)
    return apflux, area
    def calculateFluxes(self, center, pixelRadius):
        pixelCenter = self.wcs.world_to_pixel_values(center[0], center[1])
        pixelCenter = (float(pixelCenter[0]), float(pixelCenter[1]))
        apertures = self.getCircularApetures(pixelCenter, pixelRadius)
        error = np.sqrt(np.abs(self.data))

        fluxes = []
        fluxErrors = []
        for aperture in apertures:
            fluxErrors.append(
                list(
                    aperture_photometry(self.data, aperture,
                                        error=error)['aperture_sum_err'])[0])
            fluxes.append(
                list(
                    aperture_photometry(self.data, aperture,
                                        error=error)['aperture_sum'])[0])

        self.fluxes = np.array(fluxes)
        self.fluxErrors = np.array(fluxErrors)
        self.pixelCenter = pixelCenter
def get_contrast_and_SN_only_real(res_real, positions, fwhm_for_snr, psf,
                                  r_aperture, r_in_annulus, r_out_annulus):
    '''
    Args:
        res_real : a 2D np.array. The path of another repository where the files are, for calculating snr.
        positions : a list of tuple (x,y). The coordinates of companions.
        psf : a 2D np.array. The image of flux.
        fwhm_flux : a float. The flux of fwhm.
        r_aperture, r_in_annulus, r_out_annulus : see args.
    Return:
        contrast : a np.array, 1 dimension. Store the list of each companion's flux.
        SN : a np.array, 1 dimension. Store the list of each companion's Signal to Noise ratio.
    '''

    aperture = CircularAperture(positions, r=r_aperture)
    annulus = CircularAnnulus(positions,
                              r_in=r_in_annulus,
                              r_out=r_out_annulus)

    # contrast
    flux_companion = aperture_photometry(res_real, [aperture, annulus])
    flux_companion['aperture_sum_0', 'aperture_sum_1'].info.format = '%.8g'
    flux = flux_companion['aperture_sum_0']

    x, y = psf.shape
    aperture_psf = CircularAperture((x // 2, y // 2), r=r_aperture)
    flux_psf = aperture_photometry(psf, aperture_psf)
    flux_psf['aperture_sum'].info.format = '%.8g'

    contrast = (flux_companion['aperture_sum_0']) / flux_psf['aperture_sum']

    # SN
    SN = vip.metrics.snr(array=res_real,
                         source_xy=positions,
                         fwhm=fwhm_for_snr,
                         plot=False)

    return contrast.data[0], SN, flux.data[0]
예제 #13
0
 def getApFlux(self, n, **kwargs: {'plot': False}):
     aper = []
     self.getFits()
     #try:
     for i in range(len(n)):
         a = float(self.r['nsa_elpetro_th50_r']) * n[i]
         b = a * float(self.r['nsa_elpetro_ba'])
         phi = float(self.r['nsa_elpetro_phi']) * u.deg
         #print(a,b,phi,self.ra,self.dec)
         pos = SkyCoord(ra=self.ra, dec=self.dec, unit='deg')
         aper.append(
             ap.SkyEllipticalAperture(pos,
                                      a * u.arcsec,
                                      b * u.arcsec,
                                      theta=phi))
         #return aper
     try:
         f = fits.open(self.fP)
         flux = ap.aperture_photometry(f[0], aper)
     except:
         er = 'Something went wrong in getAPFlux() for the file "' + self.fN + '" for scale radius=' + str(
             n)
         log.error(er)
         print(er)
         bad = [0.0, 0.0, 0.0, 0.0]
         return bad
         #return flux[0]['aperture_sum_0']
     if kwargs.get('plot'):
         self.viewImage()
         fw = WCS(f[0].header)
         aper[0].to_pixel(fw).plot(color='blue')
         aper[1].to_pixel(fw).plot(color='red')
         aper[2].to_pixel(fw).plot(color='green')
         aper[3].to_pixel(fw).plot(color='yellow')
     if self.band == 3:
         arr = np.array([
             flux[0]['aperture_sum_0'], flux[0]['aperture_sum_1'],
             flux[0]['aperture_sum_2'], flux[0]['aperture_sum_3']
         ])
         b3 = arr * 1.8326e-06
         f.close()
         return b3
     if self.band == 4:
         arr = np.array([
             flux[0]['aperture_sum_0'], flux[0]['aperture_sum_1'],
             flux[0]['aperture_sum_2'], flux[0]['aperture_sum_3']
         ])
         b4 = arr * 5.2269E-05
         f.close()
         return b4
예제 #14
0
def get_SN(path, positions, fwhm):
    '''
    Args:
        path : a string. The path of repository where the files are.
        positions : a list of tuple (x,y). The coordinates of companions.
    Return:
        flux : a np.array, 1 dimension. Store the list of each companion's flux.
        SN : a np.array, 1 dimension. Store the list of each companion's Signal to Noise ratio.
    '''
    files = os.listdir(path)
    files.sort()
    l = len(files)

    # flux
    flux = np.zeros(l)
    aperture = CircularAperture(positions, r=2)
    annulus = CircularAnnulus(positions, r_in=4, r_out=6)

    # SN
    SN = np.zeros(l)

    for i in range(l):
        file = path + '/' + files[i]
        print("file", i, "=", file)
        data = vip.fits.open_fits(file)

        # flux
        flux_companion = aperture_photometry(data, [aperture, annulus])
        flux_companion['aperture_sum_0', 'aperture_sum_1'].info.format = '%.8g'
        #bkg_mean = flux_companion['aperture_sum_1']/annulus.area
        #bkg_sum_in_companion = bkg_mean * aperture.area
        #flux[i] = flux_companion['aperture_sum_0'] - bkg_sum_in_companion
        flux[i] = (flux_companion['aperture_sum_0'] / aperture.area)

        # SN
        lets_plot = False
        if i == 2:
            lets_plot = True
            #ds9.display(data)
        SN[i] = vip.metrics.snr(data,
                                source_xy=positions[0],
                                fwhm=fwhm,
                                plot=lets_plot)

    return flux, SN
예제 #15
0
def aper_phot_old(image, xc, yc, radii, plot_results,profile_png, mask=None,verbose=False):

    positions = [(xc, yc)]

    apertures = [CircularAperture(positions, r=r) for r in radii ]
    phot_table = aperture_photometry(image, apertures,mask=mask)
#
    junk = []
#    print(phot_table)
#    print(type(phot_table))
    for index  in phot_table.colnames:
        if('aperture_sum' in index):
            array = phot_table[index].data[0]
            temp  = array.tolist()
            junk.append(temp)
    values = np.array(junk)
    diff   = np.zeros(len(values))
    diff[0] = values[0]
    for ii in range(1,len(values)):
        diff[ii]= values[ii]-values[ii-1]
        if(verbose == True or verbose == 1):
            print(values[ii], diff[ii])

    if(verbose == True or verbose == 1):
        print("positions: " ,positions)
        print("Radii  :", radii)
        print("values :",values)

    if(plot_results == True) :
        fig = plt.figure(figsize=(10,8))
        plt.subplot(2, 1, 1)
        plt.plot(radii, values,'bo',markersize=4)
        plt.xlabel("radius (pixels)")
        plt.ylabel("totalintensity")

        plt.subplot(2, 1, 2)
        diff = diff/diff[0]
        plt.plot(radii, diff,'bo',markersize=4)
        plt.yscale("log")
        plt.xlabel("radius (pixels)")
        plt.ylabel("Normalised intensity")
        plt.savefig(profile_png,bbox_inches='tight')
        plt.show()
        return
예제 #16
0
    def doapphot(self, apradlist, units='arcsec'):
        """ Measure the flux in one or more apertures.
        :param apradlist: float or array-like
           aperture radius or list of radii.  
        :param units: 'arcsec' or 'pixels'; 
           the units for the aperture radii in apradlist.
        """
        if not np.iterable(apradlist):
            apradlist = [apradlist]
        if units == 'arcsec':
            apradlist = [ap / self.pixscale for ap in apradlist]
        if self.skyvalperpix is None:
            self.get_sky_from_annulus()

        xy = [self.x_0, self.y_0]
        apertures = [CircularAperture(xy, r) for r in apradlist]
        phot_table = aperture_photometry(
            self.imdat, apertures, error=None, mask=None,
            method=u'exact', subpixels=5, unit=None, wcs=None)

        # Modify the output photometry table
        if 'aperture_sum' in phot_table.colnames:
            # if we had only a single aperture, then the aperture sum column
            # has no index number at the end. So we add it.
            phot_table.rename_column('aperture_sum', 'aperture_sum_0')
        for i in range(len(apertures)):
            # add a column for each aperture specifying the radius in arcsec
            colname = 'radius_arcsec_{:d}'.format(i)
            apradarcsec = apradlist[i] * self.pixscale
            apcol = Column(name=colname, data=[apradarcsec,])
            phot_table.add_column(apcol)

        self._photutils_output_dict['aperturephot'] = \
            MeasuredPhotometry('aperturephot', 'aperture')
        self._photutils_output_dict['aperturephot'].photresultstable = \
            phot_table
        self._photutils_output_dict['aperturephot'].get_flux_and_mag(
            self.zpt, self.camera, self.filter)
예제 #17
0
def get_photometry(path):
    '''
    Args:
        path : a string. The path of repository where the files are.
    Rrturn:
        res : a np.array, 1 dimension. Store the list of each companion's flux.
        SN : a np.array, 1 dimension. Store the list of each companion's Signal to Noise ratio.
    '''

    files = os.listdir(path)
    files.sort()
    res = np.zeros((len(files)))
    SN = np.zeros(len(files))
    for i in range(len(res)):
        file = path+'/'+files[i]
        print("file =",file)
        data = fits.getdata(file)
        flux_companion = aperture_photometry(data, [aperture, annulus])
        flux_companion['aperture_sum_0','aperture_sum_1'].info.format = '%.8g'
        bkg_mean = flux_companion['aperture_sum_1']/annulus.area
        bkg_sum_in_companion = bkg_mean * aperture.area 
        annulus_stdev = get_stdev(data)
        res[i] = flux_companion['aperture_sum_0'] - bkg_sum_in_companion
        SN[i] = res[i] / (annulus_stdev * aperture.area)
        if i==1 and SHOW_POSITION:
            norm = simple_norm(data, 'sqrt', percent=99)
            plt.imshow(data, norm=norm, interpolation='nearest')
            ap_patches = aperture.plot(color='white', lw=2, label='Photometry aperture')
            ann_patches = annulus.plot(color='red', lw=2, label='Background annulus')
            handles = (ap_patches[0],ann_patches[0])
            plt.legend(loc=(0.17, 0.05), facecolor='#458989', labelcolor='white', handles=handles, prop={'weight':'bold', 'size':11})
            plt.xlim(100,170)
            plt.ylim(200,256)
            #plt.savefig('./circle_ADI/ADI_32px_'+str(i))
            plt.show()

    return res, SN 
예제 #18
0
def photutils_apphot(datestr):
    """
    Run aperture photometry using photutils.
    Extract LCs for Tmag < 16 stars within 6 arcminutes of TOI 837.
    And also do the "custom apertures" along a line between TOI 837 and Star A.
    """

    imgpaths, outdir = ____init_dir(datestr)

    # J2015.5 gaia TOI 837
    ra, dec = 157.03728055645, -64.50521068147
    c_obj = SkyCoord(ra, dec, unit=(u.deg), frame='icrs')

    # J2015.5 gaia, Star A = TIC 847769574 (T=14.6). $2.3$'' west
    # == Gaia 5251470948222139904
    A_ra, A_dec = 157.03581886712300, -64.50508245570860
    c_StarA = SkyCoord(A_ra, A_dec, unit=(u.deg), frame='icrs')

    # will do photometry along the line separating these two stars.
    posn_angle = c_obj.position_angle(c_StarA)
    sep = c_obj.separation(c_StarA)

    # number of pixels to shift. sign was checked empirically.
    npxshift = -np.arange(0, 6.5, 0.5)
    px_scale = 0.734 * u.arcsec  # per pixel
    line_ap_locs = []
    for n in npxshift:
        line_ap_locs.append(
            c_StarA.directional_offset_by(posn_angle, n * px_scale))

    # sanity check: 3 pixel shift should be roughly location of TOI 837
    assert np.round(ra, 3) == np.round(line_ap_locs[6].ra.value, 3)

    nbhr_stars, sra, sdec, ticids = get_nbhr_stars()
    positions = SkyCoord(sra, sdec, unit=(u.deg), frame='icrs')

    #
    # apertures of radii 1-7 pixels, for all stars in image
    #
    n_pxs = range(1, 8)

    aplist = []
    for n in n_pxs:
        aplist.append(pa.SkyCircularAperture(positions, r=n * px_scale))

    #
    # finally, do the photometry.
    #
    for imgpath in imgpaths:

        outpath = os.path.join(
            outdir,
            os.path.basename(imgpath).replace('.fit', '_phottable.fits'))

        if os.path.exists(outpath):
            print('found {}, skip.'.format(outpath))
            continue

        hdul = fits.open(imgpath)
        img = hdul[0].data
        img_wcs = wcs.WCS(hdul[0].header)
        hdul.close()

        phot_table = pa.aperture_photometry(img, aplist, wcs=img_wcs)

        #
        # apertures of radii 1-7 pixels, along the line between Star A and TOI
        # 837.
        #
        custom_aplist = []
        custom_phottables = []

        line_ap_locs = SkyCoord(line_ap_locs)
        for n in range(1, 8):
            custom_aplist.append(
                pa.SkyCircularAperture(line_ap_locs, r=n * px_scale))

        custom_phot_table = pa.aperture_photometry(img,
                                                   custom_aplist,
                                                   wcs=img_wcs)

        #
        # save both
        #
        outpath = os.path.join(
            outdir,
            os.path.basename(imgpath).replace('.fit', '_phottable.fits'))
        phot_table.write(outpath, format='fits')
        print('made {}'.format(outpath))

        outpath = os.path.join(
            outdir,
            os.path.basename(imgpath).replace('.fit', '_customtable.fits'))
        custom_phot_table.write(outpath, format='fits')
        print('made {}'.format(outpath))
plt.imshow(img2, cmap='gray', origin='lower')
apertures[22].plot(color='white')
apertures[20].plot(color='white')

K = 24
name = "Br_Imbrium_pt2_"
lcurves = [np.zeros((2, 2)) for i in range(4)]
for I in range(len(lists)):
    for J in range(len(lists[I])):
        fil = lists[I][J]
        img = fit.open(fil)[0].data
        hdr = fit.open(fil)[0].header
        dt = hdr['DATE-OBS']
        tsep = datetime.datetime.strptime(dt, '%Y-%m-%dT%H:%M:%S')
        time = np.int(tsep.strftime('%s'))
        phot = apphot.aperture_photometry(img, apertures[K])
        sums = float(phot['aperture_sum']) / hdr['EXPTIME']
        lcurves[I] = np.vstack((lcurves[I], np.array([time, sums])))
    lcurves[I] = np.delete(lcurves[I], 0, axis=0)
    lcurves[I] = np.delete(lcurves[I], 0, axis=0)
    plt.plot(lcurves[I][:, 0], lcurves[I][:, 1])
    plt.yscale('log')
    plt.savefig(save_in + "plots/" + name + types[I])
    plt.close()
    np.savetxt(save_in + name + types[I], lcurves[I])

plt.savefig(save_in + "B_Imbrium_bl")

#plt.plot(lcurves[0][:,0],lcurves[0][:,1]);plt.yscale('log')
np.savetxt(save_in + "B_Imbrium_bl", lcurves[0])
np.savetxt(save_in + "B_Imbrium_IR", lcurves[1])
예제 #20
0
파일: extract.py 프로젝트: keheintz/PyReduc
    coeff = chebfit(x_sky[~clip_mask], sky_val[~clip_mask], deg=ORDER_APSKY)

    data_skysub.append(cut_i - chebval(np.arange(cut_i.shape[0]), coeff))

data_skysub = np.array(data_skysub).T
hdr = objhdu[0].header
hdr.add_history(f"Sky subtracted using sky offset = {ap_sky_offset}, " +
                f"{SIGMA_APSKY}-sigma {ITERS_APSKY}-iter clipping " +
                f"to fit order {ORDER_APSKY} Chebyshev")
_ = fits.PrimaryHDU(data=data_skysub, header=hdr)
_.data = _.data.astype('float32')
_.writeto(DATAPATH / (OBJIMAGE.stem + ".skysub.fits"), overwrite=True)

pos = np.array([x_ap, y_ap]).T
aps = RectangularAperture(positions=pos, w=1, h=apheight, theta=0)
phot = aperture_photometry(data_skysub, aps, method='subpixel', subpixels=30)
ap_summed = phot['aperture_sum'] / EXPTIME

fig, axs = plt.subplots(2,
                        1,
                        figsize=(10, 6),
                        sharex=False,
                        sharey=False,
                        gridspec_kw=None)
axs[0].imshow(objimage, vmin=3000, vmax=6000, origin='lower')
axs[1].imshow(data_skysub, vmin=0, vmax=200, origin='lower')
axs[0].set(title="Before sky subtraction")
axs[1].set(title="Sky subtracted")

for ax in [axs[0], axs[1]]:
    ax.plot(x_ap, y_ap + apsum_sigma_upper * ap_sigma, 'r-', lw=1)
if nb_wl > 1:
    fwhm_bis = get_fwhm_from_psf(psf[1])
    psfn_bis = vip.metrics.normalize_psf(psf[1], fwhm_bis, size=17)
    print("psfn =", psfn_bis.shape, "psfn.ndim =", psfn_bis.ndim)

# pxscale of IRDIS
pxscale = get_pxscale()

# get flux level
psf_nx, psf_ny = psf[wl_final].shape
position = (psf_nx // 2, psf_ny // 2)

aperture = CircularAperture(position, r=(diameter / 2))
annulus = CircularAnnulus(position, r_in=diameter, r_out=diameter * (3 / 2))
flux_psf = aperture_photometry(psf[wl_final], [aperture, annulus])
flux_psf['aperture_sum_0', 'aperture_sum_1'].info.format = '%.8g'
flux_level = flux_psf['aperture_sum_0'][0] * contrast

print(">> flux of psf in the same aperture is:", flux_psf['aperture_sum_0'][0],
      "contrast is:", contrast)
print(">> flux_level =", flux_level)

################################
# Step-3 do the fake injection #
################################

# use vip to inject a fake companion
science_cube_fake_comp = np.zeros((2, nb_science_frames, nx, ny))
science_cube_fake_comp[wl_final] = vip.metrics.cube_inject_companions(
    science_cube[wl_final],
예제 #22
0
    plt.figure(1)
    plt.clf()

    # label the sources
    mylabels = sources['id']
    for idx, txt in enumerate(mylabels):
        plt.annotate(txt, (positions[idx, 0], positions[idx, 1]))

    plt.imshow(np.log(imdata), cmap='Greys')
    apertures.plot(color='red', lw=1.5, alpha=0.5)
    annulus.plot(color='green', lw=1.5, alpha=0.5)
    plt.show()

# sum signal in source apertures
aper_ann = [apertures, annulus]
phot_table = aperture_photometry(imdata, aper_ann)

# Find the background per pixel from the annulus
print('\nMean background per pixel:')
phot_table['mean_bkg'] = phot_table['aperture_sum_1'] / annulus.area
phot_table['id', 'mean_bkg'].pprint()

# Compute the background signal contribution to the aperture
bkg_signal = phot_table['mean_bkg'] * apertures.area
source_counts = phot_table['aperture_sum_0'] - bkg_signal

# Compute the flux and instrumental magnitude and add info to phot_table
count_rate = source_counts / imheader['EXPTIME']  # count_rate in ADU/sec
mag = get_magnitude(count_rate)

phot_table['count_rate'] = count_rate
예제 #23
0
def extract_ifu(input_model, source_type, extract_params):
    """This function does the extraction.

    Parameters
    ----------
    input_model : IFUCubeModel
        The input model.

    source_type : string
        "POINT" or "EXTENDED"

    extract_params : dict
        The extraction parameters for aperture photometry.

    Returns
    -------
    ra, dec : float
        ra and dec are the right ascension and declination respectively
        at the nominal center of the image.

    wavelength : ndarray, 1-D
        The wavelength in micrometers at each plane of the IFU cube.

    temp_flux : ndarray, 1-D
        The sum of the data values in the extraction aperture minus the
        sum of the data values in the background region (scaled by the
        ratio of areas), for each plane.
        The data values are in units of surface brightness, so this value
        isn't really the flux, it's an intermediate value.  Dividing by
        `npixels` (to compute the average) will give the value for the
        `surf_bright` (surface brightness) column, and multiplying by
        the solid angle of a pixel will give the flux for a point source.

    background : ndarray, 1-D
        For point source data, the background array is the count rate that was subtracted
        from the total source data values to get `temp_flux`. This background is determined
        for annulus region. For extended source data, the background array is the sigma clipped
        extracted region.

    npixels : ndarray, 1-D, float64
        For each slice, this is the number of pixels that were added
        together to get `temp_flux`.

    dq : ndarray, 1-D, uint32
        The data quality array.

    npixels_bkg : ndarray, 1-D, float64
        For each slice, for point source data  this is the number of pixels that were added
        together to get `temp_flux` for an annulus region or for extended source
        data it is the number of pixels used to determine the background

    radius_match : ndarray,1-D, float64
        The size of the extract radius in pixels used at each wavelength of the IFU cube

    x_center, y_center : float
        The x and y center of the extraction region
    """

    data = input_model.data
    weightmap = input_model.weightmap

    shape = data.shape
    if len(shape) != 3:
        log.error("Expected a 3-D IFU cube; dimension is %d.", len(shape))
        raise RuntimeError("The IFU cube should be 3-D.")

    # We need to allocate temp_flux, background, npixels, and dq arrays
    # no matter what.  We may need to divide by npixels, so the default
    # is 1 rather than 0.
    temp_flux = np.zeros(shape[0], dtype=np.float64)
    background = np.zeros(shape[0], dtype=np.float64)
    npixels = np.ones(shape[0], dtype=np.float64)
    npixels_bkg = np.ones(shape[0], dtype=np.float64)

    dq = np.zeros(shape[0], dtype=np.uint32)

    # For an extended target, the entire aperture will be extracted, so
    # it makes no sense to shift the extraction location.
    if source_type != "EXTENDED":
        ra_targ = input_model.meta.target.ra
        dec_targ = input_model.meta.target.dec
        locn = locn_from_wcs(input_model, ra_targ, dec_targ)

        if locn is None or np.isnan(locn[0]):
            log.warning("Couldn't determine pixel location from WCS, so "
                        "source offset correction will not be applied.")

            x_center = float(shape[-1]) / 2.
            y_center = float(shape[-2]) / 2.

        else:
            (x_center, y_center) = locn
            log.info(
                "Using x_center = %g, y_center = %g, based on "
                "TARG_RA and TARG_DEC.", x_center, y_center)

    method = extract_params['method']
    subpixels = extract_params['subpixels']
    subtract_background = extract_params['subtract_background']

    radius = None
    inner_bkg = None
    outer_bkg = None
    width = None
    height = None
    theta = None
    # pull wavelength plane out of input data.
    # using extract 1d wavelength, interpolate the radius, inner_bkg, outer_bkg to match input wavelength

    # find the wavelength array of the IFU cube
    x0 = float(shape[2]) / 2.
    y0 = float(shape[1]) / 2.
    (ra, dec, wavelength) = get_coordinates(input_model, x0, y0)

    # interpolate the extraction parameters to the wavelength of the IFU cube
    radius_match = None
    if source_type == 'POINT':
        wave_extract = extract_params['wavelength'].flatten()
        inner_bkg = extract_params['inner_bkg'].flatten()
        outer_bkg = extract_params['outer_bkg'].flatten()
        radius = extract_params['radius'].flatten()

        frad = interp1d(wave_extract,
                        radius,
                        bounds_error=False,
                        fill_value="extrapolate")
        radius_match = frad(wavelength)
        # radius_match is in arc seconds - need to convert to pixels
        # the spatial scale is the same for all wavelengths do we only need to call compute_scale once.

        if locn is None:
            locn_use = (input_model.meta.wcsinfo.crval1,
                        input_model.meta.wcsinfo.crval2, wavelength[0])
        else:
            locn_use = (ra_targ, dec_targ, wavelength[0])

        scale_degrees = compute_scale(
            input_model.meta.wcs,
            locn_use,
            disp_axis=input_model.meta.wcsinfo.dispersion_direction)

        scale_arcsec = scale_degrees * 3600.00
        radius_match /= scale_arcsec

        finner = interp1d(wave_extract,
                          inner_bkg,
                          bounds_error=False,
                          fill_value="extrapolate")
        inner_bkg_match = finner(wavelength) / scale_arcsec

        fouter = interp1d(wave_extract,
                          outer_bkg,
                          bounds_error=False,
                          fill_value="extrapolate")
        outer_bkg_match = fouter(wavelength) / scale_arcsec

    elif source_type == 'EXTENDED':
        # Ignore any input parameters, and extract the whole image.
        width = float(shape[-1])
        height = float(shape[-2])
        x_center = width / 2. - 0.5
        y_center = height / 2. - 0.5
        theta = 0.
        subtract_background = False
        bkg_sigma_clip = extract_params['bkg_sigma_clip']

    log.debug("IFU 1-D extraction parameters:")
    log.debug("  x_center = %s", str(x_center))
    log.debug("  y_center = %s", str(y_center))
    if source_type == 'POINT':
        log.debug("  method = %s", method)
        if method == "subpixel":
            log.debug("  subpixels = %s", str(subpixels))
    else:
        log.debug("  width = %s", str(width))
        log.debug("  height = %s", str(height))
        log.debug("  theta = %s degrees", str(theta))
        log.debug("  subtract_background = %s", str(subtract_background))
        log.debug("  sigma clip value for background = %s",
                  str(bkg_sigma_clip))
        log.debug("  method = %s", method)
        if method == "subpixel":
            log.debug("  subpixels = %s", str(subpixels))

    position = (x_center, y_center)

    # get aperture for extended it will not change with wavelength
    if source_type == 'EXTENDED':
        aperture = RectangularAperture(position, width, height, theta)
        annulus = None

    for k in range(shape[0]):  # looping over wavelength
        inner_bkg = None
        outer_bkg = None

        if source_type == 'POINT':
            radius = radius_match[
                k]  # this radius has been converted to pixels
            aperture = CircularAperture(position, r=radius)
            inner_bkg = inner_bkg_match[k]
            outer_bkg = outer_bkg_match[k]
            if inner_bkg <= 0. or outer_bkg <= 0. or inner_bkg >= outer_bkg:
                log.debug("Turning background subtraction off, due to "
                          "the values of inner_bkg and outer_bkg.")
                subtract_background = False

        if subtract_background and inner_bkg is not None and outer_bkg is not None:
            annulus = CircularAnnulus(position,
                                      r_in=inner_bkg,
                                      r_out=outer_bkg)
        else:
            annulus = None

        subtract_background_plane = subtract_background
        # Compute the area of the aperture and possibly also of the annulus.
        # for each wavelength bin (taking into account empty spaxels)
        normalization = 1.
        temp_weightmap = weightmap[k, :, :]
        temp_weightmap[temp_weightmap > 1] = 1
        aperture_area = 0
        annulus_area = 0

        # aperture_photometry - using weight map
        phot_table = aperture_photometry(temp_weightmap,
                                         aperture,
                                         method=method,
                                         subpixels=subpixels)

        aperture_area = float(phot_table['aperture_sum'][0])
        log.debug("aperture.area = %g; aperture_area = %g", aperture.area,
                  aperture_area)

        if (aperture_area == 0 and aperture.area > 0):
            aperture_area = aperture.area

        if subtract_background and annulus is not None:
            # Compute the area of the annulus.
            phot_table = aperture_photometry(temp_weightmap,
                                             annulus,
                                             method=method,
                                             subpixels=subpixels)
            annulus_area = float(phot_table['aperture_sum'][0])
            log.debug("annulus.area = %g; annulus_area = %g", annulus.area,
                      annulus_area)

            if (annulus_area == 0 and annulus.area > 0):
                annulus_area = annulus.area

            if annulus_area > 0.:
                normalization = aperture_area / annulus_area
            else:
                log.warning("Background annulus has no area, so background "
                            f"subtraction will be turned off. {k}")
                subtract_background_plane = False

        npixels[k] = aperture_area
        npixels_bkg[k] = 0.0
        if annulus is not None:
            npixels_bkg[k] = annulus_area
        # aperture_photometry - using data

        phot_table = aperture_photometry(data[k, :, :],
                                         aperture,
                                         method=method,
                                         subpixels=subpixels)
        temp_flux[k] = float(phot_table['aperture_sum'][0])

        # Point source type of data with defined annulus size
        if subtract_background_plane:
            bkg_table = aperture_photometry(data[k, :, :],
                                            annulus,
                                            method=method,
                                            subpixels=subpixels)
            background[k] = float(bkg_table['aperture_sum'][0])
            temp_flux[k] = temp_flux[k] - background[k] * normalization

        # Extended source data - background determined from sigma clipping
        if source_type == 'EXTENDED':
            bkg_data = data[k, :, :]
            # pull out the data with coverage in IFU cube. We do not want to use
            # the edge data that is zero to define the statistics on clipping
            bkg_stat_data = bkg_data[temp_weightmap == 1]

            bkg_mean, _, bkg_stddev = stats.sigma_clipped_stats(
                bkg_stat_data, sigma=bkg_sigma_clip, maxiters=5)
            low = bkg_mean - bkg_sigma_clip * bkg_stddev
            high = bkg_mean + bkg_sigma_clip * bkg_stddev

            # set up the mask to flag data that should not be used in aperture photometry
            maskclip = np.logical_or(bkg_data < low, bkg_data > high)

            bkg_table = aperture_photometry(bkg_data,
                                            aperture,
                                            mask=maskclip,
                                            method=method,
                                            subpixels=subpixels)
            background[k] = float(bkg_table['aperture_sum'][0])
            phot_table = aperture_photometry(temp_weightmap,
                                             aperture,
                                             mask=maskclip,
                                             method=method,
                                             subpixels=subpixels)
            npixels_bkg[k] = float(phot_table['aperture_sum'][0])

        del temp_weightmap
        # done looping over wavelength bins
    # Check for NaNs in the wavelength array, flag them in the dq array,
    # and truncate the arrays if NaNs are found at endpoints (unless the
    # entire array is NaN).
    (wavelength, temp_flux, background, npixels, dq, npixels_bkg) = \
        nans_in_wavelength(wavelength, temp_flux, background, npixels, dq, npixels_bkg)

    return (ra, dec, wavelength, temp_flux, background, npixels, dq,
            npixels_bkg, radius_match, x_center, y_center)
예제 #24
0
def ConCur(star_data,
           radius_size=1,
           center=None,
           background_method='astropy',
           find_hots=False,
           find_center=False):

    data = star_data.copy()

    background_mean, background_std = background_calc(data, background_method)

    x, y = np.indices((data.shape))

    if not center:
        center = np.array([(x.max() - x.min()) / 2.0,
                           (y.max() - y.min()) / 2.0])

    if find_hots == True:
        hots = hot_pixels(data, center, background_mean, background_std)

    if find_center == True:
        center_vals = find_best_center(data, radius_size, center)
        center = np.array([center_vals[0], center_vals[1]])

    radii = np.sqrt((x - center[0])**2 + (y - center[1])**2)
    radii = radii.astype(np.int)

    ones = np.array([[1] * len(data)] * len(data[0]))

    number_of_a = radii.max() / radius_size

    center_ap = CircularAperture([center[0], center[1]], radius_size)

    all_apers, all_apers_areas, all_masks = [center_ap], [center_ap.area], [
        center_ap.to_mask(method='exact')
    ]

    all_data, all_weights = [all_masks[0].multiply(data)
                             ], [all_masks[0].multiply(ones)]

    all_stds = [twoD_weighted_std(all_data[0], all_weights[0])]

    for j in range(int(number_of_a)):
        aper = CircularAnnulus([center[0], center[1]],
                               r_in=(j * radius_size + radius_size),
                               r_out=(j * radius_size + 2 * radius_size))
        all_apers.append(aper)
        all_apers_areas.append(aper.area)
        mask = aper.to_mask(method='exact')
        all_masks.append(mask)
        mask_data = mask.multiply(data)
        mask_weight = mask.multiply(ones)
        all_data.append(mask_data)
        all_weights.append(mask_weight)
        all_stds.append(twoD_weighted_std(mask_data, mask_weight))
    phot_table = aperture_photometry(data, all_apers)

    center_val = np.sum(all_data[0]) / all_apers_areas[0] + 5 * all_stds[0]

    delta_mags = []
    for i in range(len(phot_table[0]) - 3):
        try:
            delta_mags.append(-2.5 * math.log((np.sum(all_data[i])/all_apers_areas[i] + \
                                               5*all_stds[i])/center_val,10))
        except ValueError:
            print('annulus',i, 'relative flux equal to', (np.sum(all_data[i])/all_apers_areas[i] + \
                                               5*all_stds[i])/center_val, '...it is not included')
            delta_mags.append(np.NaN)

    arc_lengths = []
    for i in range(len(delta_mags)):
        arc_lengths.append(
            (i * 0.033 + 0.033) *
            radius_size)  #make sure center radius size is correct
    arc_lengths = np.array(arc_lengths)
    lim_arc_lengths = arc_lengths[arc_lengths < 10]
    delta_mags = delta_mags[:len(lim_arc_lengths)]
    delta_mags = np.array(delta_mags)
    if delta_mags[1] < 0:
        print('Warning: first annulus has negative relative flux of value,',
              '%.5f' % delta_mags[1],
              'consider changing center or radius size')

    return (lim_arc_lengths, delta_mags, all_stds)
예제 #25
0
pixelCenter = (155.888, 139.095)
arcsecsInAPixel = hdu.header['CDELT2'] * 3600

#arsecondRadius = 0.1
pixelRadius = 8

data = hdu.data
wcsCube = WCS(hdu.header, naxis=3)
restFrequency = hdu.header['RESTFRQ']

apertures = getCircularApetures(pixelCenter, pixelRadius)

fluxes = []
for aperture in apertures:
    fluxes.append([
        list(aperture_photometry(data[0][val], aperture)['aperture_sum'])[0]
        for val in range(len(data[0]))
    ])

x = np.arange(len(data[0]))
_, _, freqs = wcsCube.pixel_to_world_values(x, x, x)
vels = 300000 * ((-freqs + restFrequency) / restFrequency)

for i in range(7):
    f = open(f'nice_circle{i+1}.txt', 'w')
    for j in range(len(x)):
        f.write(f'{vels[j]} {fluxes[i][j]} \n')
    f.close()

#####################################################################################
infiles = []
예제 #26
0
파일: RDI.py 프로젝트: Na1an/Stage_in_IPAG
            read_file(str(sys.argv[2]), "ROTATION"))
        data_bkg_mean = radial_data_mean(data[0])
        c = plt.imshow(data_bkg_mean, interpolation='nearest', origin='lower')
        plt.colorbar(c)
        plt.title('backgraound flux of target science')
        plt.show()

        #hdu = fits.PrimaryHDU(res_cADI)
        #hdu.writeto("./GJ_667C_origin_rotated.fits")
        positions = [(126.05284, 249.11)]
        #positions = [(143.06025, 166.01939)]
        aperture = CircularAperture(positions, r=2)
        annulus = CircularAnnulus(positions, r_in=4, r_out=6)

        #data[0][1:,1:] = data[0][1:,1:] - data_bkg_mean
        flux_companion = aperture_photometry(data[0], [aperture, annulus])
        bkg_mean = flux_companion['aperture_sum_1'] / annulus.area
        bkg_sum_in_companion = bkg_mean * aperture.area

        print(flux_companion)
        print("bkg_mean =", bkg_mean[0], "\naperture.area =", aperture.area,
              "\nannulus.area =", annulus.area)
        print("bkg_sum_in_companion =", bkg_sum_in_companion[0])
        flux_companion_origin = flux_companion[
            'aperture_sum_0'] - bkg_sum_in_companion
        print("flux companion origin =", flux_companion_origin[0])

        norm = simple_norm(data, 'sqrt', percent=99)
        plt.imshow(data[0], norm=norm, interpolation='nearest')
        ap_patches = aperture.plot(color='white',
                                   lw=2,
예제 #27
0
def apt_phot(images, source_reg, background_reg=None, apt_corr=1):

    #if the image is unique we convert it to a list to keep the next loop
    #unchanged

    if type(images) == str:
        images = [images]

    for image_file in images:
        if os.path.isfile(image_file):

            hst_hdul = fits.open(image_file)
            date = hst_hdul[0].header["DATE-OBS"]
            if "FILTER" in hst_hdul[0].header:
                hst_filter = hst_hdul[0].header["FILTER"]
            elif "FILTER1" in hst_hdul[0].header:
                hst_filter = hst_hdul[0].header["FILTER1"]
            else:
                hst_filter = hst_hdul[0].header["FILTNAM1"]
            instrument = hst_hdul[0].header["INSTRUME"]

            if "BUNIT" in hst_hdul[0].header:
                if hst_hdul[0].header["BUNIT"] == '':
                    print('no unit-assuming ELECTRONS/S')
                    units = 'ELECTRONS/S'
                else:
                    units = hst_hdul[0].header["BUNIT"]
            elif "BUNIT" in hst_hdul[1].header:
                if hst_hdul[1].header["BUNIT"] == '':
                    print('no unit-assuming ELECTRONS/S')
                    units = 'ELECTRONS/S'
                else:
                    units = hst_hdul[1].header["BUNIT"]

            exp_time = float(hst_hdul[0].header["EXPTIME"])
            detector = hst_hdul[0].header[
                "DETECTOR"] if "DETECTOR" in hst_hdul[0].header else ""
            if "PHOTPLAM" in hst_hdul[0].header:
                pivot_wavelength = float(hst_hdul[0].header["PHOTPLAM"])
            elif "PHOTPLAM" in hst_hdul[1].header:
                pivot_wavelength = float(hst_hdul[1].header["PHOTPLAM"])
            if "PHOTBW" in hst_hdul[0].header:
                filter_bandwidth = float(hst_hdul[0].header["PHOTBW"])
            elif "PHOTBW" in hst_hdul[1].header:
                filter_bandwidth = float(hst_hdul[1].header["PHOTBW"])
            # if UV filter then https://www.stsci.edu/files/live/sites/www/files/home/hst/instrumentation/wfc3/documentation/instrument-science-reports-isrs/_documents/2017/WFC3-2017-14.pdf
            # use phftlam1 keyword for UV filters
            uv_filters = [
                "F200LP", "F300X", "F218W", "F225W", "F275W", "FQ232N",
                "FQ243N", "F280N"
            ]
            if detector == "UVIS" and filter in uv_filters:
                photflam = float(hst_hdul[0].header["PHTFLAM1"])
            elif "PHOTFLAM" in hst_hdul[0].header:
                photflam = float(hst_hdul[0].header["PHOTFLAM"])
            elif "PHOTFLAM" in hst_hdul[1].header:
                photflam = float(hst_hdul[1].header["PHOTFLAM"])
            print("PHOTFLAM keyword value: %.2E" % photflam)

            if "PHOTZPT" in hst_hdul[0].header:
                zero_point = float(hst_hdul[0].header["PHOTZPT"])
            elif "PHOTZPT" in hst_hdul[1].header:
                zero_point = float(hst_hdul[1].header["PHOTZPT"])

            if len(hst_hdul) == 1:
                image_data = hst_hdul[0].data
                wcs = WCS(hst_hdul[0].header)
            else:
                image_data = hst_hdul[1].data
                wcs = WCS(hst_hdul[1].header)

            source_aperture = region_to_aperture(source_reg, wcs)
            print(source_aperture)
            bkg_aperture = region_to_aperture(background_reg, wcs)

            phot_source = aperture_photometry(image_data, source_aperture)

            if background_reg is not None:
                phot_bkg = aperture_photometry(image_data, bkg_aperture)
                # background correction
                phot_source["corrected_aperture"] = phot_source[
                    "aperture_sum"] - phot_bkg[
                        "aperture_sum"] / bkg_aperture.area * source_aperture.area
                phot_source["corrected_aperture_err"] = sqrt(
                    phot_source["aperture_sum"] +
                    (sqrt(phot_bkg["aperture_sum"]) / bkg_aperture.area *
                     source_aperture.area)**2)
                phot_source_conf = phot_source[
                    "corrected_aperture"] + phot_source[
                        "corrected_aperture_err"]
                phot_source_conf_neg = phot_source[
                    "corrected_aperture"] - phot_source[
                        "corrected_aperture_err"]
            else:
                phot_source["corrected_aperture"] = phot_source["aperture_sum"]
                phot_source["corrected_aperture_err"] = 0
                phot_source_conf = phot_source[
                    "corrected_aperture"] + phot_source[
                        "corrected_aperture_err"]
                phot_source_conf_neg = phot_source[
                    "corrected_aperture"] - phot_source[
                        "corrected_aperture_err"]
            # divide by the exposure time if needed
            if "/S" in units:
                print(
                    "Units: %s. Exposure time correction will not be applied" %
                    units)
                phot_source["flux"] = phot_source[
                    "corrected_aperture"] / apt_corr * photflam
                phot_source[
                    "flux_err"] = phot_source_conf / apt_corr * photflam - phot_source[
                        "flux"]

                if phot_source["corrected_aperture"] > 0:
                    phot_source["mag"] = -2.5 * log10(
                        phot_source["corrected_aperture"] /
                        apt_corr) - zero_point
                    phot_source["mag_err_neg"] = -2.5 * log10(
                        phot_source_conf /
                        apt_corr) - zero_point - phot_source["mag"]
                else:
                    phot_source["mag"] = 'Nan.'
                    phot_source["mag_err_neg"] = 'Nan.'

                if phot_source_conf_neg > 0:
                    phot_source["mag_err_pos"] = -2.5 * log10(
                        phot_source_conf_neg /
                        apt_corr) - zero_point - phot_source["mag"]
                else:
                    phot_source["mag_err_pos"] = 'Nan.'

            else:
                print("Units: %s. Applying exposure time correction" % units)
                phot_source["flux"] = phot_source[
                    "corrected_aperture"] / apt_corr * photflam / exp_time
                phot_source[
                    "flux_err"] = phot_source_conf / apt_corr * photflam / exp_time - phot_source[
                        "flux"]

                if phot_source["corrected_aperture"] > 0:
                    phot_source["mag"] = -2.5 * log10(
                        phot_source["corrected_aperture"] / apt_corr /
                        exp_time) - zero_point
                    phot_source["mag_err_neg"] = -2.5 * log10(
                        phot_source_conf / apt_corr /
                        exp_time) - zero_point - phot_source["mag"]
                else:
                    phot_source["mag"] = 'Nan.'
                    phot_source["mag_err_neg"] = 'Nan.'

                if phot_source_conf_neg > 0:
                    phot_source["mag_err_pos"] = -2.5 * log10(
                        phot_source_conf_neg / apt_corr /
                        exp_time) - zero_point - phot_source["mag"]
                else:
                    phot_source["mag_err_pos"] = 'Nan.'

            phot_source['flux'].info.format = '%.3E'
            phot_source['flux_err'].info.format = '%.3E'

            if phot_source["mag"] != 'Nan.':
                phot_source["mag"].info.format = "%.3f"

            if phot_source["mag_err_neg"] != 'Nan.':
                phot_source["mag_err_neg"].info.format = "%.3f"

            if phot_source["mag_err_pos"] != 'Nan.':
                phot_source["mag_err_pos"].info.format = "%.3f"

            os.system('mkdir -p photometry')
            os.chdir('photometry')
            phot_source.write("aperture_photometry.csv", overwrite=True)
            output = np.array(
                pd.read_csv("aperture_photometry.csv", delimiter=','))[0]
            os.chdir('..')
            return (output)
예제 #28
0
        if detector == "UVIS" and filter in uv_filters:
            photflam = float(hst_hdul[0].header["PHTFLAM1"])
        elif "PHOTFLAM" in hst_hdul[0].header:
            photflam = float(hst_hdul[0].header["PHOTFLAM"])
        elif "PHOTFLAM" in hst_hdul[1].header:
            photflam = float(hst_hdul[1].header["PHOTFLAM"])
        photflam = photflam * u.erg / u.AA / u.s / u.cm**2
        print("PHOTFLAM keyword value: %.2E %s" % (photflam.value, photflam.unit))
        zero_point = float(hst_hdul[1].header["PHOTZPT"])


        image_data = hst_hdul[1].data
        hst_wcs = wcs.WCS(hst_hdul[1].header)
        source_aperture = hst_ut.region_to_aperture(source_reg, hst_wcs)
        mask = image_data < 0
        phot_source = aperture_photometry(image_data, source_aperture, error=np.sqrt(image_data * exp_time) / exp_time, wcs=hst_wcs, mask=mask)
        source_area  = source_aperture.area
        aperture_keyword = "corrected_aperture_sum(%s)" % units

        if args.exclude is not None:
            for exclude_reg in Regions.read(args.exclude, format="ds9"):
                exclude_aperture = hst_ut.region_to_aperture(exclude_reg, hst_wcs)
                phot_exclude = aperture_photometry(image_data, exclude_aperture, wcs=hst_wcs, error=np.sqrt(image_data * exp_time) / exp_time, mask=mask)
                source_area  -= exclude_aperture.area
                phot_source["aperture_sum_err"] = np.sqrt(phot_exclude["aperture_sum_err"] ** 2 + phot_source["aperture_sum_err"] ** 2)
                phot_source["aperture_sum"] -= phot_exclude["aperture_sum"]

        # if a background region was given
        if len(regions) > 1:
            bkg_reg = regions[1]
            bkg_aperture = hst_ut.region_to_aperture(bkg_reg, hst_wcs)
예제 #29
0
# RC3: R_25 ~ 234 arcsec
Rc=234
nn = Rc/a
nna = nn*a
nnb = nn*b 
phi = angles_in_ellipse(40, nna, nnb)
#print(np.round(np.rad2deg(phi), 2))

e = (1.0 - nnb ** 2.0 / nna ** 2.0) ** 0.5
arcs = sp.special.ellipeinc(phi, e)
#print(np.round(np.diff(arcs), 4))
x = cat.xcentroid + nnb * np.sin(phi)
y = cat.ycentroid + nna * np.cos(phi)
box = RectangularAperture(zip(x,y), 32, 32)
boolmask = box_cutout.data > 0
phot = aperture_photometry(data, box, mask=boolmask)
bkg_mean = np.mean(phot['aperture_sum'] / box.area) # 14.985152614520166
bkg_rms = np.std(phot['aperture_sum'] / box.area) # 4.568966255984001
plt.figure(figsize=(8, 8))
norm = simple_norm(data*~boolmask, 'sqrt', percent=99.)
im=plt.imshow(data*~boolmask, cmap='viridis',interpolation='nearest',norm=norm)
plt.colorbar(im)
aperture.plot(color='#d62728')
box.plot(color='#d62728')
print(bkg_mean,bkg_rms,bkg_mean - 1*bkg_rms,bkg_mean + 1*bkg_rms,bkg_mean - 3*bkg_rms,bkg_mean + 3*bkg_rms)
#data = data - (bkg_mean+3*bkg_rms)#(bkg_mean - 1*bkg_rms) 
### np.median(data[box_cutout.data==0]) # == 15.167292
### np.std(data[box_cutout.data==0]) #== 10.078673
# ----------------------------------------------------------------------------
#datamask = deepcopy(data)
#datamask[mask>0]=0
예제 #30
0
def iraf_style_photometry(phot_apertures,
                          bg_apertures,
                          data,
                          photflam,
                          photplam,
                          error_array=None,
                          bg_method='mode',
                          epadu=1.0):
    """
    Computes photometry with PhotUtils apertures, with IRAF formulae

    Parameters
    ----------
    phot_apertures : photutils PixelAperture object (or subclass)
        The PhotUtils apertures object to compute the photometry. i.e. the object returned via CirularAperture.

    bg_apertures : photutils PixelAperture object (or subclass)
        The phoutils aperture object to measure the background in. i.e. the object returned via CircularAnnulus.

    data : array
        The data for the image to be measured.

    photflam : float
        inverse sensitivity, in ergs/cm2/angstrom/electron

    photplam : float
        Pivot wavelength, in angstroms

    error_array : array
        (Optional) The array of pixelwise error of the data.  If none, the Poisson noise term in the error computation
        will just be the square root of the flux/epadu. If not none, the aperture_sum_err column output by
        aperture_photometry (divided by epadu) will be used as the Poisson noise term.

    bg_method: string
        {'mean', 'median', 'mode'}, optional. The statistic used to calculate the background. All measurements are
        sigma clipped. Default value is 'mode'. NOTE: From DAOPHOT, mode = 3 * median - 2 * mean.

    epadu : float
        (optional) Gain in electrons per adu (only use if image units aren't e-). Default value is 1.0

    Returns
    -------
        An astropy Table with columns as follows:
        X-Center Y-Center RA DEC ID MagAp1 MagErrAp1 MagAp2 MagErrAp2 MSkyAp2 StdevAp2 FluxAp2 CI Flags
    """
    if bg_method not in ['mean', 'median', 'mode']:
        raise ValueError('Invalid background method, choose either \
                          mean, median, or mode')
    phot = aperture_photometry(data, phot_apertures, error=error_array)
    bg_phot = aperture_stats_tbl(data, bg_apertures, sigma_clip=True)
    names = ['X-Center', 'Y-Center', 'ID']
    x, y = phot_apertures[0].positions.T
    final_stacked = np.stack([x, y, phot["id"].data], axis=1)
    # n_aper = 0
    name_list = 'Flux', 'FluxErr', 'Mag', 'MagErr'
    for aper_string in ['Ap1', 'Ap2']:
        for col_name in name_list:
            names.append("{}{}".format(col_name, aper_string))

    # for item in list(phot.keys()):
    #     if item.startswith("aperture_sum_") and not item.startswith("aperture_sum_err_"):
    #         aper_size_arcsec = phot_apertures[n_aper].r * platescale
    #         for name in name_list:
    #             names.append("{}_{:.2f}".format(name, aper_size_arcsec))
    #         n_aper += 1
    for aperCtr in range(0, 2):
        ap_area = phot_apertures[aperCtr].area
        bg_method_name = 'aperture_{}'.format(bg_method)

        flux = phot['aperture_sum_{}'.format(
            aperCtr)] - bg_phot[bg_method_name] * ap_area

        # Need to use variance of the sources
        # for Poisson noise term in error computation.
        #
        # This means error needs to be squared.
        # If no error_array error = flux ** .5

        if error_array is not None:
            flux_error = compute_phot_error(
                phot['aperture_sum_err_{}'.format(aperCtr)]**2.0, bg_phot,
                bg_method, ap_area, epadu)
        else:
            flux_error = compute_phot_error(flux, bg_phot, bg_method, ap_area,
                                            epadu)

        mag = convert_flux_to_abmag(flux, photflam, photplam)

        # NOTE: Magnitude error calculation comes from computing d(ABMAG)/d(flux).
        # See https://iraf.net/forum/viewtopic.php?showtopic=83932 for details.
        mag_err = 1.0857 * flux_error / flux

        # Build the final data table
        stacked = np.stack([flux, flux_error, mag, mag_err], axis=1)
        final_stacked = np.concatenate([final_stacked, stacked], axis=1)

    # Build final output table
    final_tbl = Table(data=final_stacked,
                      names=names,
                      dtype=[
                          np.float64, np.float64, np.int64, np.float64,
                          np.float64, np.float64, np.float64, np.float64,
                          np.float64, np.float64, np.float64
                      ])

    # add sky and std dev columns from background calculation subroutine
    final_tbl.add_column(bg_phot[bg_method_name])
    final_tbl.rename_column(bg_method_name, 'MSkyAp2')
    final_tbl.add_column(bg_phot['aperture_std'])
    final_tbl.rename_column('aperture_std', 'StdevAp2')

    return final_tbl