How to use the photutils.aperture_photometry function in photutils

To help you get started, we’ve selected a few photutils examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github vortex-exoplanet / VIP / vip_hci / metrics / contrcurve.py View on Github external
init_rad = fwhm

    if debug:
        _, ax = plt.subplots(figsize=(6, 6))
        ax.imshow(array, origin='lower', interpolation='nearest',
                  alpha=0.5, cmap='gray')

    for i in range(n_annuli):
        y = centery + init_rad + separation * i
        rad = dist(centery, centerx, y, centerx)
        yy, xx = find_coords(rad, fwhm, init_angle, fin_angle)
        yy += centery
        xx += centerx

        apertures = photutils.CircularAperture((xx, yy), fwhm/2)
        fluxes = photutils.aperture_photometry(array, apertures)
        fluxes = np.array(fluxes['aperture_sum'])

        noise_ann = np.std(fluxes)
        noise.append(noise_ann)
        vector_radd.append(rad)

        if debug:
            for j in range(xx.shape[0]):
                # Circle takes coordinates as (X,Y)
                aper = plt.Circle((xx[j], yy[j]), radius=fwhm/2, color='r',
                                  fill=False, alpha=0.8)
                ax.add_patch(aper)
                cent = plt.Circle((xx[j], yy[j]), radius=0.8, color='r',
                                  fill=True, alpha=0.5)
                ax.add_patch(cent)
github dstndstn / tractor / projects / desi / runbrick.py View on Github external
if apertures is not None:
            import photutils

            # Aperture photometry, using the unweighted "coimg" and "coiv" arrays.
            with np.errstate(divide='ignore'):
                imsigma = 1.0/np.sqrt(coiv)
                imsigma[coiv == 0] = 0

            apimg = []
            apimgerr = []
            if mods:
                apres = []
                
            for rad in apertures:
                aper = photutils.CircularAperture(apxy, rad)
                p = photutils.aperture_photometry(coimg, aper, error=imsigma)
                apimg.append(p.field('aperture_sum'))
                apimgerr.append(p.field('aperture_sum_err'))
                if mods:
                    p = photutils.aperture_photometry(coresid, aper)
                    apres.append(p.field('aperture_sum'))
            ap = np.vstack(apimg).T
            ap[np.logical_not(np.isfinite(ap))] = 0.
            C.AP.set('apflux_img_%s' % band, ap)
            ap = 1./(np.vstack(apimgerr).T)**2
            ap[np.logical_not(np.isfinite(ap))] = 0.
            C.AP.set('apflux_img_ivar_%s' % band, ap)
            if mods:
                ap = np.vstack(apres).T
                ap[np.logical_not(np.isfinite(ap))] = 0.
                C.AP.set('apflux_resid_%s' % band, ap)
                del apres
github vortex-exoplanet / VIP / vip_hci / metrics / contrcurve.py View on Github external
'subpixel': A pixel is divided into subpixels and the center of each
                subpixel is tested (as above).
    'exact': (default) The exact overlap between the aperture and each pixel is
             calculated.

    """
    n_obj = len(yc)
    flux = np.zeros((n_obj))
    for i, (y, x) in enumerate(zip(yc, xc)):
        if mean:
            ind = circle(y, x,  (ap_factor*fwhm)/2)
            values = array[ind]
            obj_flux = np.mean(values)
        else:
            aper = photutils.CircularAperture((x, y), (ap_factor*fwhm)/2)
            obj_flux = photutils.aperture_photometry(array, aper,
                                                     method='exact')
            obj_flux = np.array(obj_flux['aperture_sum'])
        flux[i] = obj_flux

        if verbose:
            print('Coordinates of object {} : ({},{})'.format(i, y, x))
            print('Object Flux = {:.2f}'.format(flux[i]))

    return flux
github dstndstn / tractor / projects / desi / runbrick.py View on Github external
with np.errstate(divide='ignore'):
                imsigma = 1.0/np.sqrt(coiv)
                imsigma[coiv == 0] = 0

            apimg = []
            apimgerr = []
            if mods:
                apres = []
                
            for rad in apertures:
                aper = photutils.CircularAperture(apxy, rad)
                p = photutils.aperture_photometry(coimg, aper, error=imsigma)
                apimg.append(p.field('aperture_sum'))
                apimgerr.append(p.field('aperture_sum_err'))
                if mods:
                    p = photutils.aperture_photometry(coresid, aper)
                    apres.append(p.field('aperture_sum'))
            ap = np.vstack(apimg).T
            ap[np.logical_not(np.isfinite(ap))] = 0.
            C.AP.set('apflux_img_%s' % band, ap)
            ap = 1./(np.vstack(apimgerr).T)**2
            ap[np.logical_not(np.isfinite(ap))] = 0.
            C.AP.set('apflux_img_ivar_%s' % band, ap)
            if mods:
                ap = np.vstack(apres).T
                ap[np.logical_not(np.isfinite(ap))] = 0.
                C.AP.set('apflux_resid_%s' % band, ap)
                del apres
            del apimg,apimgerr,ap

        if callback is not None:
            callback(band, *callback_args, **kwargs)
github vortex-exoplanet / VIP / vip_hci / metrics / snr.py View on Github external
xx[i+1] = cosangle*xx[i] - sinangle*yy[i] 
            yy[i+1] = cosangle*yy[i] + sinangle*xx[i]

    xx += centerx
    yy += centery
    rad = fwhm/2.
    if exclude_negative_lobes:
        xx = np.concatenate(([xx[0]], xx[2:-1]))
        yy = np.concatenate(([yy[0]], yy[2:-1]))

    apertures = photutils.CircularAperture((xx, yy), r=rad)  # Coordinates (X,Y)
    fluxes = photutils.aperture_photometry(array, apertures, method='exact')
    fluxes = np.array(fluxes['aperture_sum'])

    if array2 is not None:
        fluxes2 = photutils.aperture_photometry(array2, apertures,
                                                method='exact')
        fluxes2 = np.array(fluxes2['aperture_sum'])
        if use2alone:
            fluxes = np.concatenate(([fluxes[0]], fluxes2[:]))
        else:
            fluxes = np.concatenate((fluxes, fluxes2))

    f_source = fluxes[0].copy()
    fluxes = fluxes[1:]
    n2 = fluxes.shape[0]
    snr = (f_source - fluxes.mean())/(fluxes.std()*np.sqrt(1+(1/n2)))

    if verbose:
        msg1 = 'S/N for the given pixel = {:.3f}'
        msg2 = 'Integrated flux in FWHM test aperture = {:.3f}'
        msg3 = 'Mean of background apertures integrated fluxes = {:.3f}'
github vortex-exoplanet / VIP / vip_hci / metrics / fakecomp.py View on Github external
# first we find the centroid and put it in the center of the array
            centry, centrx = fit_2d(psf, full_output=False, debug=False)
            shiftx, shifty = centrx - cx, centry - cy
            psf = frame_shift(psf, -shifty, -shiftx, imlib=imlib,
                              interpolation=interpolation)

            for _ in range(2):
                centry, centrx = fit_2d(psf, full_output=False, debug=False)
                cy, cx = frame_center(psf, verbose=False)
                shiftx, shifty = centrx - cx, centry - cy
                psf = frame_shift(psf, -shifty, -shiftx, imlib=imlib,
                                  interpolation=interpolation)

        # we check whether the flux is normalized and fix it if needed
        fwhm_aper = photutils.CircularAperture((frame_center(psf)), fwhm/2)
        fwhm_aper_phot = photutils.aperture_photometry(psf, fwhm_aper,
                                                       method='exact')
        fwhm_flux = np.array(fwhm_aper_phot['aperture_sum'])

        if fwhm_flux > 1.1 or fwhm_flux < 0.9:
            psf_norm_array = psf / np.array(fwhm_aper_phot['aperture_sum'])
        else:
            psf_norm_array = psf

        if threshold is not None:
            psf_norm_array[np.where(psf_norm_array < threshold)] = 0

        if mask_core is not None:
            psf_norm_array = get_circle(psf_norm_array, radius=mask_core)

        if verbose:
            print("Flux in 1xFWHM aperture: {:.3f}".format(fwhm_flux[0]))
github ryanoelkers / DIA / routines / Python / refphot.py View on Github external
mg1 = 25.-2.5*numpy.log10(phot_table[ii][jj+3])
				mg0 = 25.-2.5*numpy.log10(phot_table[ii][jj+2])
				offset[jj,ii] = mg1-mg0
prv = 1.
opt_rad = 10.
for ii in range(0, len(rads)):
	chk = numpy.median(offset[ii,:])	
	if (numpy.abs(chk-prv) <= 0.001) and (rads[ii] < opt_rad):	
		opt_rad = rads[ii]
		print 'The optimal aperture size is '+str(opt_rad)+'.'
	if (numpy.abs(chk-prv) > 0.001):
		prv = chk

#do the aperture photometry
apertures = CircularAperture(positions, r = opt_rad)
phot_table = aperture_photometry(mast, apertures, method = 'exact')

#get the background of the image
cimg, clow, chigh = scipy.stats.sigmaclip(mast, low=2.5, high = 2.5) #do a 2.5 sigma clipping
bkg_mean = numpy.median(cimg) #determine the sky value
sig = numpy.std(cimg) #determine the sigma(sky)

#convert to magnitudes
flx = phot_table['aperture_sum']-(bkg_mean*(numpy.pi*opt_rad**2))
flx_er = numpy.sqrt(phot_table['aperture_sum'])
x_pix = x
y_pix = y

#create the magnitudes from the flux
mag = 25.0-2.5*numpy.log10(flx)
err = (2.5/numpy.log(10.))*(flx_er/flx)
github afeinstein20 / eleanor / ELLIE / ellie.py View on Github external
def cust_lc(center, x=None, y=None):
            nonlocal tpf
            """ Creates the light curve for both cases (if pointing model is on or off) """
            lc = []
            for i in range(len(tpf)):
                if pointing==True:
                    ap = create_ap((x[i], y[i]))
                else:
                    ap = create_ap(center)
                lc.append(aperture_photometry(tpf[i], ap)['aperture_sum'].data[0])
            lc = np.array(lc)/np.nanmedian(lc)
            return lc
github afeinstein20 / eleanor / eleanor / ellie.py View on Github external
x_point, y_point = center
            dx, dy = motion

            r_list = np.arange(1.5, 3.5, 0.5)
            matrix = np.zeros( (len(r_list), 2, len(tpf)) )
            system = np.zeros( (len(r_list), 2, len(tpf)) )
            sigma  = np.zeros( (len(r_list), 2) )

            for i in range(len(r_list)):
                for j in range(len(tpf)):
                    pos = (x_point[j], y_point[j])
                    circ, rect = aperture(r_list[i], pos)

                    # Completes aperture sums for each tpf.flux and each aperture shape
                    matrix[i][0][j] = aperture_photometry(tpf[j], circ)['aperture_sum'].data[0]
                    matrix[i][1][j] = aperture_photometry(tpf[j], rect)['aperture_sum'].data[0]
                matrix[i][0] = matrix[i][0] / np.nanmedian(matrix[i][0])
                matrix[i][1] = matrix[i][1] / np.nanmedian(matrix[i][1])

            print("*************")
            print("Please hold while we do some systematics corrections.")
            print("*************")
            # Creates a complete, systematics corrected light curve for each aperture
            for i in range(len(r_list)):
                lc_circ = self.system_corr(matrix[i][0], dx, dy, jitter=True, roll=True)
                system[i][0] = lc_circ
                sigma[i][0] = np.std(lc_circ)
                lc_rect = self.system_corr(matrix[i][1], dx, dy, jitter=True, roll=True)
                system[i][1] = lc_rect
                sigma[i][1] = np.std(lc_rect)