Exemplo n.º 1
0
def CrowdedFieldSingle(AvgFlux,XPos,YPos, StdCutOff=3.0):
    '''returns the best aperture from the crowded field'''
    MedianFlux = np.median(AvgFlux)
    Std = np.std(np.nonzero(AvgFlux*(AvgFlux<MedianFlux)))
    Mask = AvgFlux>(MedianFlux+ StdCutOff*Std)
    MaskValue = MedianFlux + StdCutOff*Std

    MaskedImage = AvgFlux*Mask

    sigma_psf = 2.0
    #daofind = DAOStarFinder(fwhm=4., threshold=1.5*std)
    iraffind = IRAFStarFinder(threshold=MaskValue, fwhm=4.0, minsep_fwhm=0.01, sharplo=-20.0, sharphi=20.0,roundhi=20.0, roundlo=-20.0)
                             #fwhm=sigma_psf*gaussian_sigma_to_fwhm)

    sources = iraffind(MaskedImage)
    StarUpdLocation = np.zeros((len(AvgFlux),len(AvgFlux[0])))
    for i in range(len(sources)):
        StarUpdLocation[int(round(sources['ycentroid'][i],0)), int(round(sources['xcentroid'][i],0))] = i+1
    Apertures = watershed(-MaskedImage, StarUpdLocation, mask=Mask)

    Distance= 6.0
    for i in range(1,np.max(Apertures)):
        TempAper = Apertures==i
        TempImage = TempAper*MaskedImage
        YCen, XCen = measurements.center_of_mass(TempImage)
        TempDistance = ((XPos-XCen)**2+(YPos-YCen)**2)**0.5

        if TempDistance<Distance:
            Distance=TempDistance
            StdAper = TempAper

    if Distance>5.5:
        print "Failed to find a good aperture"
        StdAper = Apertures==np.max(Apertures)
    return StdAper
Exemplo n.º 2
0
def CrowdedFieldMultiple(AvgFlux, XPos, YPos, StdCutOff=3.0):
    '''returns the best aperture from the crowded field'''
    '''returns the best aperture from the crowded field'''
    MedianFlux = np.median(AvgFlux)
    Std = np.std(np.nonzero(AvgFlux * (AvgFlux < MedianFlux)))
    Mask = AvgFlux > (MedianFlux + StdCutOff * Std)
    MaskValue = MedianFlux + StdCutOff * Std

    MaskedImage = AvgFlux * Mask

    sigma_psf = 2.0
    #daofind = DAOStarFinder(fwhm=4., threshold=1.5*std)
    iraffind = IRAFStarFinder(threshold=MaskValue,
                              fwhm=4.0,
                              minsep_fwhm=0.01,
                              sharplo=-20.0,
                              sharphi=20.0,
                              roundhi=20.0,
                              roundlo=-20.0)
    #fwhm=sigma_psf*gaussian_sigma_to_fwhm)

    sources = iraffind(MaskedImage)
    StarUpdLocation = np.zeros((len(AvgFlux), len(AvgFlux[0])))
    for i in range(len(sources)):
        StarUpdLocation[int(round(sources['ycentroid'][i], 0)),
                        int(round(sources['xcentroid'][i], 0))] = i + 1

    Distance = np.exp(-1.05 * (distance_transform_edt(Mask))**2)
    Apertures = watershed(-MaskedImage, StarUpdLocation, mask=Mask)
    return Apertures
Exemplo n.º 3
0
def PSF_photometry(data, coord_table, sigma_psf=10, scale=0.67, step=0.5):
    FLUX = []
    bkgrms = MADStdBackgroundRMS()
    std = bkgrms(data)
    iraffind = IRAFStarFinder(threshold=3.5 * std,
                              fwhm=sigma_psf * gaussian_sigma_to_fwhm,
                              minsep_fwhm=0.01,
                              roundhi=5.0,
                              roundlo=-5.0,
                              sharplo=0.0,
                              sharphi=2.0)
    daogroup = DAOGroup(2.0 * sigma_psf * gaussian_sigma_to_fwhm)
    mmm_bkg = MMMBackground()
    fitter = LevMarLSQFitter()
    psf_model = IntegratedGaussianPRF(sigma=sigma_psf)
    # psf_model.x_0.fixed = True
    # psf_model.y_0.fixed = True

    pos = Table(names=['x_0', 'y_0'],
                data=[coord_table['X'],
                      coord_table['Y']])[coord_table['good_star']]

    photometry = IterativelySubtractedPSFPhotometry(finder=iraffind,
                                                    group_maker=daogroup,
                                                    bkg_estimator=mmm_bkg,
                                                    psf_model=psf_model,
                                                    fitter=LevMarLSQFitter(),
                                                    niters=1,
                                                    fitshape=(41, 41))
    result_tab = photometry(image=data, init_guesses=pos)
    return result_tab['flux_fit']
Exemplo n.º 4
0
def first_run(image, fwhm, nsigma, debug=0, mask=None):
    mean, median, std_dev = sigma_clipped_stats(image, mask=mask, sigma=nsigma)

    #    daofind = DAOStarFinder(fwhm=fwhm, threshold=5.*std_dev)
    #    sources = daofind(image - median)
    threshold = nsigma * std_dev
    print("first_run: mean, median, std_dev, threshold ", mean, median,
          std_dev, threshold)
    iraf_find = IRAFStarFinder(threshold, fwhm)
    sources = iraf_find(image - median)

    if (debug == 1):
        print("mean, median, std_dev ", mean, median, std_dev)
        print("detection threshold ", threshold)
        for col in sources.colnames:
            sources[col].info.format = "%.8g"
        print(sources)

        np.fwhm = sources['fwhm']
        np.area = np.log10(sources['npix'])
        np.flux = sources['flux']
        np.mag = sources['mag']
        np.roundness = sources['roundness']
        np.sharpness = sources['sharpness']

        fig, ax = plt.subplots()
        plt.plot(np.area, np.mag, 'bo', markersize=1)
        ax.set_xlabel('Log(area)')
        ax.set_ylabel('mag')
        plt.show()
        plt.plot(np.roundness, np.sharpness, 'bo', markersize=1)
        ax.set_xlabel('roundness')
        ax.set_ylabel('sharpness')
        plt.show()
    return sources
Exemplo n.º 5
0
def starfinder(image_name):
    infos = image_info(image_name)
    mean_bkg = infos.bkg
    std_bkg = infos.std
    u_sigma = infos.u_sigma
    sigma = u_sigma.n
    print 3.0 * std_bkg + mean_bkg
    iraffind = IRAFStarFinder(threshold = 3.0*std_bkg + mean_bkg, \
                            # fwhm = sigma*gaussian_sigma_to_fwhm, \
                            fwhm = 5.0,
                            roundhi = 1.0,
                            roundlo = -1.0,
                            sharphi = 2.0,
                            sharplo = 0.5)
    iraf_table = iraffind.find_stars(infos.data)
    return iraf_table, infos
Exemplo n.º 6
0
def irafdetect(image,nsigma=1.5,fwhm=3.0):
    """ Detection with IRAFFinder."""
    threshold = np.median(image.error)*nsigma        
    iraffind = IRAFStarFinder(fwhm=fwhm, threshold=threshold, sky=0.0)
    objects = iraffind(image.data-image.sky, mask=image.mask)
    # homogenize the columns
    objects['xcentroid'].name = 'x'
    objects['ycentroid'].name = 'y'        
    return objects
Exemplo n.º 7
0
def astropy_psf_photometry(img,
                           sigma_psf,
                           aperture=3,
                           x0=None,
                           y0=None,
                           filter=True,
                           sigma_filter=1):
    """
    performs PSF photometry on an image. If x0 and y0 are None will attempt to locate the target by searching for the
    brightest PSF in the field

    :param img: 2D array, image on which to perform PSF photometry
    :param sigma_psf: float, standard deviation of the PSF
    :param aperture: int, size of the paerture (pixels)
    :param x0: x position of the target (pixels)
    :param y0: y position of the target (pixels)
    :param filter: If True will apply a gaussian filter to the image with standard deviation sigma_filter before
     performing PSF photometry
    :param sigma_filter: standard deviation of gaussian filter to apply to the image
    :return: x0 column of photometry table, y0 column of photometry table, flux column of photometry table
    """
    if filter:
        image = ndimage.gaussian_filter(img, sigma=sigma_filter, order=0)
    else:
        image = img
    bkgrms = MADStdBackgroundRMS()
    std = bkgrms(image[image != 0])
    iraffind = IRAFStarFinder(threshold=2 * std,
                              fwhm=sigma_psf * gaussian_sigma_to_fwhm,
                              minsep_fwhm=0.01,
                              roundhi=5.0,
                              roundlo=-5.0,
                              sharplo=0.0,
                              sharphi=2.0)
    daogroup = DAOGroup(2.0 * sigma_psf * gaussian_sigma_to_fwhm)
    mmm_bkg = MMMBackground()
    fitter = LevMarLSQFitter()
    psf_model = IntegratedGaussianPRF(sigma=sigma_psf)
    if x0 and y0:
        pos = Table(names=['x_0', 'y_0'], data=[x0, y0])
        photometry = BasicPSFPhotometry(group_maker=daogroup,
                                        bkg_estimator=mmm_bkg,
                                        psf_model=psf_model,
                                        fitter=LevMarLSQFitter(),
                                        fitshape=(11, 11))
        res = photometry(image=image, init_guesses=pos)
        return res['x_fit'], res['y_fit'], res['flux_0']
    photometry = BasicPSFPhotometry(finder=iraffind,
                                    group_maker=daogroup,
                                    bkg_estimator=mmm_bkg,
                                    psf_model=psf_model,
                                    fitter=fitter,
                                    fitshape=(11, 11),
                                    aperture_radius=aperture)
    res = photometry(image=image)
    return res['x_0'], res['y_0'], res['flux_0']
Exemplo n.º 8
0
def get_star_catalog(img_file, fwhm_init=5.0, threshold=3.5):

    img_hdu = fits.open(img_file)

    std = bkgrms(img_hdu[0].data)
    iraffind = IRAFStarFinder(threshold=threshold*std,
        fwhm=fwhm_init, minsep_fwhm=0.5,
        roundhi=2.0, roundlo=-2.0,sharplo=0.0, sharphi=2.0)

    # Get initial set of stars in image with iraffind
    print('Finding stars...')
    stars = iraffind(img_hdu[0].data)

    return(stars)
Exemplo n.º 9
0
def do_photometry_basic(image: np.ndarray,
                        σ_psf: float) -> Tuple[Table, np.ndarray]:
    """
    Find stars in an image with IRAFStarFinder

    :param image: The image data you want to find stars in
    :param σ_psf: expected deviation of PSF
    :return: tuple result table, residual image
    """
    bkgrms = MADStdBackgroundRMS()

    std = bkgrms(image)

    iraffind = IRAFStarFinder(threshold=3 * std,
                              sigma_radius=σ_psf,
                              fwhm=σ_psf * gaussian_sigma_to_fwhm,
                              minsep_fwhm=2,
                              roundhi=5.0,
                              roundlo=-5.0,
                              sharplo=0.0,
                              sharphi=2.0)
    daogroup = DAOGroup(0.1 * σ_psf * gaussian_sigma_to_fwhm)

    mmm_bkg = MMMBackground()

    # my_psf = AiryDisk2D(x_0=0., y_0=0.,radius=airy_minimum)
    # psf_model = prepare_psf_model(my_psf, xname='x_0', yname='y_0', fluxname='amplitude',renormalize_psf=False)
    psf_model = IntegratedGaussianPRF(sigma=σ_psf)
    # psf_model = AiryDisk2D(radius = airy_minimum)#prepare_psf_model(AiryDisk2D,xname ="x_0",yname="y_0")
    # psf_model = Moffat2D([amplitude, x_0, y_0, gamma, alpha])

    # photometry = IterativelySubtractedPSFPhotometry(finder=iraffind, group_maker=daogroup,
    #                                                bkg_estimator=mmm_bkg, psf_model=psf_model,
    #                                                fitter=LevMarLSQFitter(),
    #                                                niters=2, fitshape=(11,11))
    photometry = BasicPSFPhotometry(finder=iraffind,
                                    group_maker=daogroup,
                                    bkg_estimator=mmm_bkg,
                                    psf_model=psf_model,
                                    fitter=LevMarLSQFitter(),
                                    aperture_radius=11.0,
                                    fitshape=(11, 11))

    result_table = photometry.do_photometry(image)
    return result_table, photometry.get_residual_image()
Exemplo n.º 10
0
def find_objects(image, fwhm, nsigma, debug, mask=None):
    mean, median, std_dev = sigma_clipped_stats(image, mask=mask, sigma=nsigma)
    threshold = nsigma * std_dev
    if (debug == 1):
        print("mean, median, std_dev ", mean, median, std_dev)
        print("nsigma, detection threshold ", nsigma, threshold)

    iraf_find = IRAFStarFinder(threshold,
                               fwhm,
                               minsep_fwhm=25.0,
                               sharplo=0.5,
                               sharphi=2.0,
                               roundlo=0.0,
                               roundhi=0.05,
                               peakmax=1000,
                               exclude_border=True,
                               brightest=100)
    sources = iraf_find(image - median, mask=mask)
    return sources
Exemplo n.º 11
0
def init_setup():

    fitimage = fits.open('Serpens3/idxq28010_drz.fits')
    imdata = fitimage[1].data
    head = fitimage[0].header

    bkgrms = MADStdBackgroundRMS()
    std = bkgrms(imdata)
    mean = np.mean(imdata)
    sigma_psf = 2.0
    iraffind = IRAFStarFinder(threshold=3.5 * std,
                              fwhm=sigma_psf * gaussian_sigma_to_fwhm,
                              minsep_fwhm=0.01,
                              roundhi=5.0,
                              roundlo=-5.0,
                              sharplo=0.0,
                              sharphi=2.0)

    daogroup = DAOGroup(2.0 * sigma_psf * gaussian_sigma_to_fwhm)
    mmm_bkg = MMMBackground()

    return imdata, bkgrms, std, sigma_psf, iraffind, daogroup, mmm_bkg, mean
Exemplo n.º 12
0
# Largeur à mi-hauteur totale d'une étoile
fwhm = 12

# On commence par faire de la photométrie de base sur le fichier somme BV.
# Les données calculées pour le fichier somme serviront de point de départ à l'algorithme
# pour les images en filtre B et V.

################################## SUM BV ################################

# On commence par déterminer la déviation standard du fond de ciel.
bkgrms = MADStdBackgroundRMS ()
std = bkgrms (imageSumBV)

# On donne les paramètres du finder pour déterminer les étoiles de base dans l'image
iraffind = IRAFStarFinder (threshold = 10 * std,
                          fwhm = fwhm,
                          minsep_fwhm = 0.01, roundhi = 1.0, roundlo = -1.0,
                          sharplo = 0.1, sharphi = 0.8)



# On donne un critère de groupage des étoiles
daogroup = DAOGroup (2.0 * fwhm)

# On détermine le fond de ciel et la procédure de fitting
mmm_bkg = MMMBackground ()
fitter = LevMarLSQFitter ()
psf_model = IntegratedGaussianPRF (sigma = fwhm / 2.35)

# On met tout ça dans une boîte noire qui fait des itérations soustractives
photometry = IterativelySubtractedPSFPhotometry (finder = iraffind,
                                                group_maker = daogroup,
Exemplo n.º 13
0
def foo():
    config = Config()
    config.epsfbuilder_iters = 2
    config.clip_sigma = 2.
    config.threshold_factor = 1.
    config.separation_factor = 2.

    image, input_table = read_or_generate_image('scopesim_cluster', config)
    mean, median, std = sigma_clipped_stats(image, sigma=config.clip_sigma)
    threshold = median + config.threshold_factor * std

    finder = IRAFStarFinder(threshold=threshold,
                            fwhm=config.fwhm_guess,
                            minsep_fwhm=1)
    prelim_stars = make_stars_guess(image, finder)

    prelim_epsf = make_epsf_combine(prelim_stars)
    fwhm_guess = estimate_fwhm(prelim_epsf)

    finder = IRAFStarFinder(threshold=threshold,
                            fwhm=fwhm_guess,
                            minsep_fwhm=1)

    # peaks_tbl = IRAFStarFinder(threshold, fwhm_guess, minsep_fwhm=1)(image)
    # peaks_tbl = finder(image)
    # peaks_tbl.rename_columns(['xcentroid', 'ycentroid'], ['x_fit', 'y_fit'])

    # plot_image_with_source_and_measured(image, input_table, peaks_tbl)

    stars = make_stars_guess(image, cutout_size=51, star_finder=finder)
    epsf = make_epsf_fit(stars,
                         iters=config.epsfbuilder_iters,
                         smoothing_kernel=make_gauss_kernel())

    epsf_mod = photutils.psf.prepare_psf_model(epsf, renormalize_psf=False)

    grouper = DAOGroup(config.separation_factor * fwhm_guess)

    shape = (epsf_mod.psfmodel.shape / epsf_mod.psfmodel.oversampling).astype(
        np.int64)

    epsf_mod.fwhm = astropy.modeling.Parameter(
        'fwhm', 'this is not the way to add this I think')
    epsf_mod.fwhm.value = fwhm_guess

    finder = IRAFStarFinder(threshold=0.1 * threshold,
                            fwhm=fwhm_guess,
                            minsep_fwhm=0.1)

    init_guesses = finder(image)
    init_guesses.rename_columns(('xcentroid', 'ycentroid'), ('x_0', 'y_0'))
    photometry = BasicPSFPhotometry(
        finder=finder,
        group_maker=grouper,
        bkg_estimator=MADStdBackgroundRMS(),
        psf_model=epsf_mod,
        fitter=LevMarLSQFitter(),
        fitshape=shape,
    )

    res = photometry(image, init_guesses=init_guesses)
    init_guesses.rename_columns(('x_0', 'y_0'), ('x', 'y'))
    plot_xy_deviation(init_guesses, res)
Exemplo n.º 14
0
        def SubmitEvent(self):

            #Not a fan of globals but this is the easiest way to grab the file location
            global fileLocation
            #sigma_psf = 2.88
            #Grab the Sigma from the Entry box in the GUI
            SigmaPSF = SigmaPSFentry.get()
            #Turn the string into a float
            sigma_psf = float(SigmaPSF)
            #Grab the number of iterations from Entry box in GUI
            N_iters1 = nitersEntry.get()
            #Turn the string into a float
            N_iters = float(N_iters1)
            #Test cases to make sure that information was flowing from the GUI to the program
            #print(SigmaPSF)
            #print(N_iters)

            #Open the file as a fits (allows us to handle it) then turn that into readable data.
            with fits.open(fileLocation) as hdul:
                image = hdul[0].data

            #automatically gathered information needed to run the Star Finder
            bkgrms = MADStdBackgroundRMS()
            std = bkgrms(image)

            #Find the stars
            iraffind = IRAFStarFinder(threshold=3.5 * std,
                                      fwhm=sigma_psf * gaussian_sigma_to_fwhm,
                                      minsep_fwhm=0.01,
                                      roundhi=5.0,
                                      roundlo=-5.0,
                                      sharplo=0.0,
                                      sharphi=2.0)
            #Group the stars
            daogroup = DAOGroup(2.0 * sigma_psf * gaussian_sigma_to_fwhm)

            #More automatically gathered info needed for IS-PSFPhotometry to take places
            mmm_bkg = MMMBackground()
            fitter = LevMarLSQFitter()
            #Grabbed from the user input
            psf_model = IntegratedGaussianPRF(sigma=sigma_psf)
            #Run IS-PSFPhotometry
            photometry = IterativelySubtractedPSFPhotometry(
                finder=iraffind,
                group_maker=daogroup,
                bkg_estimator=mmm_bkg,
                psf_model=psf_model,
                fitter=LevMarLSQFitter(),
                niters=N_iters,
                fitshape=(11, 11))
            #Do photometry on the image
            result_tab = photometry(image=image)
            #grab the resiudal image
            residual_image = photometry.get_residual_image()

            #Get the results of the photometry and print the aspects we want.
            phot_results = photometry(image)
            with open("output.txt", "w") as text_file:
                print(phot_results['x_fit', 'y_fit', 'flux_fit'],
                      file=text_file)
            print(phot_results['x_fit', 'y_fit', 'flux_fit'])
            print("Sum of pixels: {}".format(sum(sum(residual_image))))
            #Plot images made#
            #Start by creating plots.
            plt.subplot(1, 5, 1)
            #Show the first plot (which is just the raw image)
            plt.imshow(image,
                       cmap='viridis',
                       aspect=1,
                       interpolation='nearest',
                       origin='lower')
            plt.title('Raw')
            plt.colorbar(orientation='horizontal', fraction=0.046, pad=0.04)
            #Create the second plot
            plt.subplot(1, 5, 2)
            #Show the residual_image
            plt.imshow(residual_image,
                       cmap='viridis',
                       aspect=1,
                       interpolation='nearest',
                       origin='lower')
            plt.title('PSF')
            plt.colorbar(orientation='horizontal', fraction=0.046, pad=0.04)
            #Draw in the sum of pixels.
            plt.text(0,
                     65,
                     "Sum of pixels: {}".format(sum(sum(residual_image))),
                     fontsize=7)
            #Create the third plot which is the subtracted images combined.
            sb = image - residual_image
            plt.subplot(1, 5, 3)
            plt.imshow(sb,
                       cmap='viridis',
                       aspect=1,
                       interpolation='nearest',
                       origin='lower')
            plt.title('PSF-S')
            plt.colorbar(orientation='horizontal', fraction=0.046, pad=0.04)

            with open("AP_RI.txt", "w") as f:
                for _ in range(len(residual_image)):
                    f.write(str(residual_image[_]))
            with open("AP_BS.txt", "w") as f:
                for _ in range(len(sb)):
                    f.write(str(sb[_]))

            print("Starting creation of CSV")
            subprocess.run(['py', 'create_CSV.py'], shell=False)

            print("Starting creation of Stats")
            subprocess.run(['py', 'create_info.py'], shell=False)

            print("Starting Threshold")
            subprocess.run(['py', 'threshold.py'], shell=False)

            with open("APC_Res.csv", "r") as f:
                APC_Res = f.read()
            APC_Res = APC_Res.split(",")
            APC_Res = [float(i) for i in APC_Res]

            #Every (SquareRoot of the Pixels) datapoints create a new array. Into a 2D Array.
            #I'm going to use the Correct_Res list as the main list and store the temp list every Sqrt(pix) in it,
            #then reset that list and continue until the pixel count is met.
            #Have an internal counter. Reset that every Sqrt(Pix)
            temp_list = np.array([])
            SqrPixels = math.sqrt(len(APC_Res))
            internal_counter = 0
            #print(SqrPixels)
            #print(len(APC_Res))
            Corrected_Res = np.array([[]])

            for _ in range(len(APC_Res)):
                if internal_counter <= SqrPixels - 2:
                    try:
                        temp_list = np.append(temp_list, APC_Res[_ - 1])
                        #print(_)
                        if _ + 1 == (int(SqrPixels) * int(SqrPixels)):
                            Corrected_Res = np.append(Corrected_Res, temp_list)
                    except:
                        print("Not right 2.0")
                    internal_counter = internal_counter + 1
                else:
                    internal_counter = 0
                    #print(temp_list)
                    Corrected_Res = np.append(Corrected_Res, temp_list)
                    temp_list = []
                    temp_list = np.append(temp_list, APC_Res[_ - 1])
                    #print("Resetting Counter & List {}".format(_))
                    if _ + 1 == (int(SqrPixels) * int(SqrPixels)):
                        Corrected_Res = np.append(Corrected_Res, temp_list)
                        #print(_+1)
                    #print("Iteration {}".format(_))
            #print(residual_image)
            #print("\n")
            #print(Corrected_Res)
            Corrected_Res = np.reshape(Corrected_Res,
                                       (int(SqrPixels), int(SqrPixels)))

            Correct_BS = image - Corrected_Res
            plt.subplot(1, 5, 4)
            plt.imshow(Corrected_Res,
                       cmap='viridis',
                       aspect=1,
                       interpolation='nearest',
                       origin='lower')
            plt.title('CPSF')
            plt.colorbar(orientation='horizontal', fraction=0.046, pad=0.04)

            plt.subplot(1, 5, 5)
            plt.imshow(Correct_BS,
                       cmap='viridis',
                       aspect=1,
                       interpolation='nearest',
                       origin='lower')
            plt.title('CPSF-S')
            plt.colorbar(orientation='horizontal', fraction=0.046, pad=0.04)

            #Number of bins
            n_bins = 20
            #Not super sure why this works the way that it does if I’m being truthful, took tinkering to work, and lots of documentation examples.
            fig, axs = plt.subplots(1, 2)

            # We can set the number of bins with the `bins` kwarg
            axs[0].hist(residual_image, bins=n_bins)
            plt.title('Residual Image Hist')
            axs[1].hist(sb, bins=n_bins)
            plt.title('Background Subtracted Hist')
            #plt.colorbar(orientation='horizontal', fraction=0.046, pad=0.04)
            #All Pixels from residual image

            fig = plt.figure()
            ax = fig.add_subplot(111, projection='3d')
            delta = (6 * (1 / len(sb)))

            nx = ny = np.arange(-3.0, 3.0, delta)
            X, Y = np.meshgrid(nx, ny)
            #print(X)
            #print(Y)
            x, y, z = X * len(sb), Y * len(sb), sb
            ax.plot_surface(x, y, z, rstride=1, cstride=1, cmap='viridis')

            figi = plt.figure()
            axi = figi.add_subplot(111, projection='3d')
            deltai = (6 * (1 / len(sb)))

            nxi = nyi = np.arange(-3.0, 3.0, deltai)
            Xi, Yi = np.meshgrid(nxi, nyi)
            #print(X)
            #print(Y)
            xi, yi, zi = Xi * len(Correct_BS), Yi * len(Correct_BS), Correct_BS
            axi.plot_surface(xi, yi, zi, rstride=1, cstride=1, cmap='viridis')

            plt.show()
		#plt.colorbar(orientation='horizontal', fraction=0.046, pad=0.04) 
		#plt.show()
		
		
		
		

		#calculate background
		bkgrms = MADStdBackgroundRMS()
		std = bkgrms(image)
		print 'Background level :', std
		
		
		#find stars
		print 'Finding stars'
		iraffind = IRAFStarFinder(threshold=3.5*std, fwhm=fwhm, minsep_fwhm=0.01, roundhi=5.0, roundlo=-5.0, sharplo=0.0, sharphi=2.0)
		
			
		daogroup = DAOGroup(2.0*fwhm)
		
		mmm_bkg = MMMBackground()
		fitter = LevMarLSQFitter()
		psf_model = IntegratedGaussianPRF(sigma=(fwhm/gaussian_sigma_to_fwhm))
		
		#fitshape must be odd
		fitshape = 2*int(fwhm)+1
	
		print 'Performing photometry'
		#photometry = IterativelySubtractedPSFPhotometry(finder=iraffind, group_maker=daogroup, bkg_estimator=mmm_bkg, psf_model=psf_model,fitter=LevMarLSQFitter(), niters=None, fitshape=(fitshape, fitshape), aperture_radius=fwhm)
		#niters = None means continue until all stars subtracted - might recur infinitely
		
Exemplo n.º 16
0
    def Flux(self,x,y):
        x = int(x)
        y = int(y)
        r = 25
        data = self.hdulist[self.fz].data[x-r:x+r,y-r:y+r]
        data = (lacosmic.lacosmic(data,2,10,10, effective_gain = self.gain, readnoise = self.readnoise))[0]
        bkgrms = MADStdBackgroundRMS()
        std = bkgrms(data)
        iraffind = IRAFStarFinder(threshold=self.limit*std,
                                   fwhm=self.sigma_psf*gaussian_sigma_to_fwhm,
                                   minsep_fwhm=0.01, roundhi=5.0, roundlo=-5.0,
                                   sharplo=0.0, sharphi=2.0)
        daogroup = DAOGroup(2.0*self.sigma_psf*gaussian_sigma_to_fwhm)
        mmm_bkg = MMMBackground()
        psf_model = IntegratedGaussianPRF(sigma=self.sigma_psf)
        from photutils.psf import IterativelySubtractedPSFPhotometry
        photometry = IterativelySubtractedPSFPhotometry(finder=iraffind,
                                                         group_maker=daogroup,
                                                         bkg_estimator=mmm_bkg,
                                                         psf_model=psf_model,
                                                         fitter=LevMarLSQFitter(),
                                                         niters=1, fitshape=(21,21))
        

        
        result_tab = photometry(image=data)   
        
        """
        if plot == 1:
            residual_image = photometry.get_residual_image()
            print(result_tab['x_fit','y_fit'])
            plt.figure(self.filename+' data')
            plt.imshow(data, cmap='viridis',
                       aspect=1, interpolation='nearest', origin='lower')
            plt.show()
            plt.figure(self.filename+' residual')
            plt.imshow(residual_image, cmap='viridis',
                       aspect=1, interpolation='nearest', origin='lower')
            plt.show()
            plt.figure(self.filename+' PSF')
            plt.imshow(data-residual_image, cmap='viridis',
                       aspect=1, interpolation='nearest', origin='lower')
            plt.show()
        """
        
        if len(result_tab) > 5:
            return(0,0) 
        if len(result_tab) ==0:
            print('None')
            return(0,0) 
        result_tab['Minus'] = np.zeros(len(result_tab))
        for i in range(len(result_tab)):
            if 18.5 < result_tab['x_fit'][i] < 28.5 and 18.5 < result_tab['y_fit'][i] < 28.5:
            #if 15 < result_tab['x_fit'][i] < 25 and 15 < result_tab['y_fit'][i] < 25:
                result_tab['Minus'][i] = 1
            else:
                result_tab['Minus'][i] = 0
        mask = result_tab['Minus'] == 1.0
        result_tab = result_tab[mask]
        if len(result_tab) != 1:
            return(0,0)   
        flux_counts = float(result_tab['flux_fit'][0])
        flux_unc = float(result_tab['flux_unc'][0])
        flux_unc = flux_unc/flux_counts
        return(flux_counts,flux_unc)
Exemplo n.º 17
0
##THIS IS THE SIGMA, CHANGE THIS FOR RESULTS
sigma_psf = 3.1

##THIS IS THE FILE, CHANGE THIS FOR RESULTS
with fits.open(
        r'/Users/phystastical/Desktop/BB2/script/twomass-j.fits') as hdul:
    image = hdul[0].data

bkgrms = MADStdBackgroundRMS()
std = bkgrms(image)

iraffind = IRAFStarFinder(threshold=3.5 * std,
                          fwhm=sigma_psf * gaussian_sigma_to_fwhm,
                          minsep_fwhm=0.01,
                          roundhi=5.0,
                          roundlo=-5.0,
                          sharplo=0.0,
                          sharphi=2.0)
daogroup = DAOGroup(2.0 * sigma_psf * gaussian_sigma_to_fwhm)

mmm_bkg = MMMBackground()
fitter = LevMarLSQFitter()
psf_model = IntegratedGaussianPRF(sigma=sigma_psf)
photometry = IterativelySubtractedPSFPhotometry(finder=iraffind,
                                                group_maker=daogroup,
                                                bkg_estimator=mmm_bkg,
                                                psf_model=psf_model,
                                                fitter=LevMarLSQFitter(),
                                                niters=1,
                                                fitshape=(11, 11))
Exemplo n.º 18
0
from astropy.nddata import NDData
from photutils import EPSFBuilder, prepare_psf_model, Background2D
from astropy.stats import SigmaClip
from photutils.background import MADStdBackgroundRMS, MMMBackground
import pickle
import os

image = fits.getdata('./cutout_BS90_V.fits').astype(np.float64)

epsf_file = 'epsf.pkl'

if not os.path.exists(epsf_file):
    mean, median, std = sigma_clipped_stats(image)
    threshold = median + 10 * std

    finder = IRAFStarFinder(threshold=threshold, fwhm=4, minsep_fwhm=5, peakmax=image.max() / 0.8)

    star_table = finder(image)
    star_table.rename_columns(('xcentroid', 'ycentroid'),('x','y'))

    sigma_clip = SigmaClip(sigma=5.0)
    bkg_estimator = MMMBackground()
    bkg = Background2D(image, 5, filter_size=(3, 3),
                       sigma_clip=sigma_clip, bkg_estimator=bkg_estimator)

    nddata = NDData(image-bkg.background)
    stars = extract_stars(nddata, star_table, size=51)

    epsf, fitted_stars = EPSFBuilder(oversampling=4, maxiters=3, progress_bar=True, smoothing_kernel='quadratic')(stars)
    epsf_model = prepare_psf_model(epsf, renormalize_psf=False)