예제 #1
0
파일: sources.py 프로젝트: wdobbels/CAAPR
def find_source_daofind(frame, ellipse, config, track_record, special=False):

    """
    This function ...
    :param data:
    :return:
    """

    # TODO: FIX THIS FUNCTION

    sigma_level = 5.0

    # Calculate the sigma-clipped statistics of the data
    mean, median, std = sigma_clipped_stats(data, sigma=3.0)

    result_table = DAOStarFinder(data - median, fwhm=3.0, threshold=sigma_level*std)

    result_table.rename_column('xcentroid', 'x_peak')
    result_table.rename_column('ycentroid', 'y_peak')

    # If requested, make a plot with the source(s) indicated
    if plot: plotting.plot_peaks(data, result_table['x_peak'], result_table['y_peak'], radius=4.0)

    # Return the list of source positions
    #return result_table, median

    source = []
    return source
예제 #2
0
def find_psf(image,fwhm,show=False):
	'''
	Obtain the position of the centroids in a image matrix
	---
	Input:

	- image:	str		image path including the name
	-
	'''
	#importing useful packages from astropy
	from photutils import datasets
	from astropy.stats import sigma_clipped_stats
	from photutils import DAOStarFinder #daofind

	im,hdr = fits.getdata(image,header=True) #reading the fits image (data + header)
	im = np.array(im,dtype='Float64') #transform the data for a matrix
	tam = np.shape(im) #dimension of the matrix
	mean, median, std = sigma_clipped_stats(im, sigma=fwhm, iters=5)

	# sources = daofind(im - median,fwhm=fwhm, threshold=5.*std)
	result = DAOStarFinder(threshold=median,fwhm=3.5)
	sources = result.find_stars(im)

	if show == True:
		plt.figure()
		plt.imshow(im,origin='lower', cmap=plt.cm.gray,vmin=np.mean(im)-np.std(im),vmax=np.mean(im)+np.std(im))
		plt.colorbar()
		plt.scatter(sources['xcentroid'],sources['ycentroid'],color='red')
		plt.savefig('psf_sources_.png')

	# sources = sources.to_
	return sources
예제 #3
0
    def _detect_sources(self):
        from photutils import DAOStarFinder

        fwhm = 3.
        detection_threshold = 3.
        daofind = DAOStarFinder(threshold=(self._med +
                                           self._std * detection_threshold),
                                fwhm=fwhm)
        sources = daofind.find_stars(self.image)
        pl.plot(sources['xcentroid'], sources['ycentroid'], 'r.')
예제 #4
0
def find_sources(file_, fwhm):
    """
    Uses DAOStarFinder to extract source positions from fits file
    :param file_ (str): name of target .fits file
    :param fwhm (float): The full width half maximum of the gaussian kernel in pixels
    For more config see
    https://photutils.readthedocs.io/en/stable/api/photutils.detection.DAOStarFinder.html
    """
    # Read in fits file as numpy array
    data = read_fits(file_, return_array=True)
    # Calculate background level
    mean, median, std = stats.sigma_clipped_stats(data)
    print(('mean', 'median', 'std'))
    print((mean, median, std))
    # Set up DAO Finder and run on bg subtracted image, printing results
    # sharplo=.2, sharphi=1., roundlo=-.3, roundhi=.3,
    daofind = DAOStarFinder(exclude_border=True, fwhm=fwhm, threshold=std)
    sources = daofind.find_stars(data - median)  # daofind(data-median) #
    print('Sources:')
    print(sources)
    # Save positions of detected sources to csv file
    positions = (sources['xcentroid'], sources['ycentroid'])
    print_positions = zip(*[
        sources[x] for x in [
            'id', 'xcentroid', 'ycentroid', 'sharpness', 'roundness1',
            'roundness2', 'npix', 'sky', 'peak', 'flux', 'mag'
        ]
    ])
    header = 'id,xcentroid,ycentroid,sharpness,roundness1,roundness2,npix,sky,peak,flux,mag'
    np.savetxt(file_[:-5] + '_positions.csv',
               print_positions,
               fmt='%.5e',
               header=header)
    # Show image with detected sources circled in blue
    apertures = CircularAperture(positions, r=4.)
    norm = ImageNormalize(stretch=SqrtStretch())
    plt.imshow(data, cmap='Greys', origin='lower', norm=norm)
    apertures.plot(color='blue', lw=1.5, alpha=0.5)
    plt.draw()
    # Scatter plot sharpness vs magnitude
    plt.figure(2)
    sharp, round_, mags = (sources['sharpness'], sources['roundness1'],
                           sources['mag'])
    plt.scatter(mags, sharp)
    plt.title('Sharpness vs Magnitude')
    plt.xlabel('Mag')
    plt.ylabel('Sharp')
    # Scatter plot roundness vs magnitude
    plt.figure(3)
    plt.scatter(mags, round_)
    plt.title('Roundness vs Magnitude')
    plt.xlabel('Mag')
    plt.ylabel('Roundness1')
    plt.show()
def source_detection(Band, Reduced_Image_Data, Bkg, Bkg_Sigma, Median, Std,
                     image_num):

    Find_Source = DAOStarFinder(fwhm=8, threshold=3. * Std[image_num])
    Sources = Find_Source(
        Reduced_Image_Data[image_num] - Median[image_num]
    )  # Finding the sources within the defined parameters in DAOStarFinder

    Positions = np.transpose((Sources['xcentroid'], Sources['ycentroid']))
    DAO_Flux = np.array(Sources['flux'])
    Apertures = CircularAperture(
        Positions, r=5.)  # Chossing an aperture radius of 5 pixels
    Phot_Table = aperture_photometry(Reduced_Image_Data[image_num], Apertures)

    X_coord = np.array(Phot_Table['xcenter'])
    Y_coord = np.array(Phot_Table['ycenter'])

    Aperture_Sum = Phot_Table['aperture_sum']
    Flux_Err = 15 * 0.5 * Std[image_num]

    Mags = -2.5 * np.log10(Aperture_Sum)  # Convert aperture sums to magnitudes
    Mag_Err = ((-2.5 * Flux_Err) / (np.log10(10) * Aperture_Sum))

    #plt.figure()   # This block of code will plot the identified sources
    #plt.imshow(Reduced_Image_Data[image_num], cmap = 'gray_r', origin = 'lower')
    #Apertures.plot(color = 'blue', lw = 1.5, alpha = 1.5)
    #print(f'Time of Obs : {Header_Data_Dictionary[Band[image_num]][0]}')
    #print(f'Band : {Header_Data_Dictionary[Band[image_num]][2]}')

    return Aperture_Sum, Mags, Mag_Err, X_coord, Y_coord, Phot_Table, DAO_Flux
예제 #6
0
    def getOffsetStars(self, finderim, PS1=True, roundlo=-1.0, roundhi=1.0):

        imdata = fits.getdata(finderim)
        hdr = fits.getheader(finderim)
        ImWCS = wcs.WCS(hdr)

        # use detection/findstars from photutils to get stars
        from photutils import DAOStarFinder
        mean, median, std = sigma_clipped_stats(imdata, sigma=3.0, iters=5)
        self.skystd = std
        daofind = DAOStarFinder(fwhm=3.0,
                                threshold=5. * std,
                                roundlo=roundlo,
                                roundhi=roundhi)
        sources = daofind(imdata - median)

        positions = []
        for x, y in zip(sources['xcentroid'], sources['ycentroid']):
            positions += [(x, y)]

        ap = CircularAperture(positions, r=10)
        skysubim = imdata - median
        #err = calc_total_error(skysubim, std, 1.0)
        phot_table = aperture_photometry(skysubim, ap)  #, error=err)

        # check mags with aperture photometry
        if PS1:
            zpt = 25 + 2.5 * np.log10(hdr['EXPTIME'])
        else:
            zpt = 28.0 + np.log10(hdr['EXPOSURE'] / 60.) * 2.5

        mag = -2.5 * np.log10(phot_table['aperture_sum']) + zpt
        imshape = np.shape(imdata)
        iGood = np.where((mag < self.options.maxOffsetStarMag)
                         & (sources['xcentroid'] > 10)
                         & (sources['xcentroid'] < imshape[1] - 10)
                         & (sources['ycentroid'] > 10)
                         & (sources['ycentroid'] < imshape[0] - 10))[0]

        if not len(iGood):
            print('Error : no good offset stars found')
            return (None, None, None, None, None, None, None)
        iBright = iGood[np.argsort(mag[iGood])]
        xpos,ypos = sources['xcentroid'][iBright][0:self.options.numOffsetStar],\
           sources['ycentroid'][iBright][0:self.options.numOffsetStar]
        mag = mag[iBright][0:self.options.numOffsetStar]

        # get ra, dec offsets
        objcoord = SkyCoord(self.options.ra, self.options.dec, unit=u.deg)
        ralist, declist, raofflist, decofflist, maglist = [], [], [], [], []
        for x, y in zip(xpos, ypos):
            ra, dec = ImWCS.wcs_pix2world([(x, y)], 0)[0]
            ralist += [ra]
            declist += [dec]
            offcoord = SkyCoord(ra, dec, unit=u.deg)
            dra, ddec = offcoord.spherical_offsets_to(objcoord)
            raofflist += [dra.to(u.arcsec)]
            decofflist += [ddec.to(u.arcsec)]

        return (xpos, ypos, ralist, declist, mag, raofflist, decofflist)
예제 #7
0
파일: curvit.py 프로젝트: prajwel/curvit
def detect_sources_daofind(fx, fy, photons, threshold):
    mask_radius = 1700
    kernel = Gaussian2DKernel(x_stddev=4 * gaussian_fwhm_to_sigma)

    aperture = CircularAperture((2400, 2400), r=mask_radius)
    mask = aperture.to_mask(method='center')
    mask = mask.to_image(shape=((4800, 4800)))

    weights = photons / framecount_per_sec
    bins = np.arange(0, 4801)
    ndarray, yedges, xedges = np.histogram2d(fy,
                                             fx,
                                             bins=(bins, bins),
                                             weights=weights)
    data = ndarray * mask

    mean, _, std = sigma_clipped_stats(data, sigma=5., maxiters=1)
    # to avoid std becoming zero.
    if std == 0:
        mean = np.mean(data)
        std = np.std(data)

    data = convolve(data, kernel)
    daofind = DAOStarFinder(fwhm=3.0,
                            threshold=threshold * std,
                            exclude_border=True)
    sources = daofind(data - mean)
    sources.sort('mag')

    uA = np.array([sources['xcentroid'].data, sources['ycentroid'].data]).T
    uA = np.round(uA, 2)
    return uA
예제 #8
0
def clusterfindsubfunc(image_array,
                       image_sigma,
                       fwhm,
                       threshold,
                       apertureplotrad=7):
    '''
	Function: Find cluster and output results (wrapper around DAOfild)
	'''

    daofind = DAOStarFinder(fwhm=fwhm, threshold=threshold * image_sigma)
    sources = daofind(image_array)

    # Output source detection table
    for col in sources.colnames:
        sources[col].info.format = '%.8g'
    sources_cut_xcentroid = sources['xcentroid']
    sources_cut_ycentroid = sources['ycentroid']
    positions = convert2xNtoarray(
        (sources_cut_xcentroid, sources_cut_ycentroid))
    positions_out = positions
    apertures = CircularAperture(positions_out, r=fwhm)
    apertures_plot = CircularAperture(positions_out, r=fwhm + apertureplotrad)

    print('Found {} using FWHM = {} and Threshold = {}'.format(
        len(sources_cut_xcentroid), fwhm, threshold))

    return sources, positions, apertures_plot
예제 #9
0
파일: snr.py 프로젝트: scibuff/astro-phd
def findStars(image):
    # In order to use the MAD as a consistent estimator for the estimation
    # of the standard deviation σ, one takes σ = k * MAD where k is a constant
    # scale factor, which depends on the distribution. For normally distributed
    # data k is taken to be k = 1.48[26]
    bkg_sigma = 1.48 * mad(image)
    t = 5 * bkg_sigma
    daofind = DAOStarFinder(fwhm=3.0, threshold=t)
    stars = daofind(image)

    #stars['signal'] = stars['flux'] * t
    #
    data = image
    mask = make_source_mask(data, snr=2, npixels=5, dilate_size=11)
    mean, median, std = sigma_clipped_stats(data, sigma=3.0, mask=mask)
    madstd = mad_std(data)

    snrs = []
    for peak in stars['peak']:
        snrs.append(peak / madstd / 7.4)
    stars['snr'] = snrs
    print((mean, median, std, bkg_sigma, t, madstd))
    #
    #print stars
    return stars
예제 #10
0
    def find_stars_dao(self,
                       fwhm=5,
                       maxn=100,
                       target_sky=None,
                       target_pix=None):
        data = self.reduced
        imean, imedian, istd = sigma_clipped_stats(data, sigma=3.0, iters=5)
        sfinder = DAOStarFinder(5 * istd, fwhm, exclude_border=True)
        stars = sfinder(data)
        sids = argsort(array(stars['flux']))[::-1]
        cpix = array([stars['xcentroid'], stars['ycentroid']]).T
        cpix = cpix[sids, :][:maxn, :]
        self.nstars = cpix.shape[0]

        if self._wcs and target_sky is not None:
            target_pix = array(target_sky.to_pixel(self._wcs))
            cpix = concatenate([atleast_2d(target_pix), cpix])
        elif target_pix is not None:
            cpix = concatenate([atleast_2d(target_pix), cpix])

        self._initialize_tables(self.nstars, self.napt)
        if self._wcs:
            csky = pd.DataFrame(self._wcs.all_pix2world(cpix, 0),
                                columns='RA Dec'.split())
            self.set_reference_stars(cpix, csky=csky)
        else:
            self.set_reference_stars(cpix)
예제 #11
0
파일: sources.py 프로젝트: battyone/PIAA
def _lookup_via_photutils(fits_file, wcs=None, *args, **kwargs):
    from photutils import DAOStarFinder
    data = fits.getdata(fits_file) - 2048  # Camera bias
    mean, median, std = sigma_clipped_stats(data)

    fwhm = kwargs.get('fwhm', 3.0)
    threshold = kwargs.get('threshold', 3.0)

    daofind = DAOStarFinder(fwhm=fwhm, threshold=threshold * std)
    sources = daofind(data - median).to_pandas()

    sources.rename(columns={
        'xcentroid': 'x',
        'ycentroid': 'y',
    },
                   inplace=True)

    if wcs is None:
        header = fits_utils.getheader(fits_file)
        wcs = WCS(header)

    coords = wcs.all_pix2world(sources['x'], sources['y'], 1)

    sources['ra'] = coords[0]
    sources['dec'] = coords[1]

    return sources
예제 #12
0
def getDAOStarFinderStats(img_file,
                          target_dir,
                          kernel_in_pix,
                          sig_clipping_for_stats=3.0,
                          star_find_n_sig_threshold=4.0,
                          fit_radius_scaling=5.0,
                          bg_radii_scalings=[7.0, 8.0]):

    data, header = can.readInDataFromFitsFile(img_file, target_dir)
    mean, median, std = astrostats.sigma_clipped_stats(
        data, sigma=sig_clipping_for_stats)
    print('Finding stars in image: ' + target_dir + img_file)
    daofind = DAOStarFinder(fwhm=kernel_in_pix,
                            threshold=star_find_n_sig_threshold * std)
    sources = daofind(data - median)
    results = {
        'xcentroid': sources['xcentroid'].data,
        'ycentroid': sources['ycentroid'].data,
        'sharpness': sources['sharpness'].data,
        'roundness1': sources['roundness1'].data,
        'roundness2': sources['roundness2'].data,
        'npix': sources['npix'].data,
        'sky': sources['sky'].data,
        'peak': sources['peak'].data,
        'flux': sources['flux'].data,
        'mag': sources['mag'].data
    }

    return results
예제 #13
0
def detect_sources(ccd, fwhm=8, thresh=10):
    """
    Detect sources in an image using the DAOStarFinder from photutils.

    Parameters
    ----------

    ccd : `astropy.nddata.CCDData`
        The CCD image in which to detect sources.

    fwhm : float, optional
        Full-width half-max of the sources, in pixels.

    thresh : float, optional
        Threshold above which a source must be to count as a source. This
        argument is multiplied by the sigma-clipped standard deviation of
        the data.
    """
    men, med, std = faster_sigma_clip_stats(ccd.data, sigma=5)
    # This sets up the source detection. The FWHM turns out to be key...making
    # it too small results in a single star being detected as two separate
    # sources.
    #
    # Stars must be brighter than the threshold to count as sources. Making
    # the number higher gives you fewer detected sources, lower gives you more.
    # There is no "magic" number.
    dao = DAOStarFinder(threshold=thresh * std, fwhm=fwhm, exclude_border=True)
    stars = dao(ccd - med)
    return stars
예제 #14
0
def find_sources(scidata, margin=10, nmax=None):
    """Detect stars in the science image."""

    # Initialize the DAOStarFinder.
    mean, median, stddev = sigma_clipped_stats(scidata, sigma=3.0, maxiters=5)
    daofind = DAOStarFinder(fwhm=2.0,
                            threshold=5. * stddev,
                            exclude_border=True)

    # Mask a border around the edge of the image.
    mask = np.zeros_like(scidata, dtype='bool')
    mask[:margin] = True
    mask[-margin:] = True
    mask[:, :margin] = True
    mask[:, -margin:] = True

    # Find sources in the image.
    sources = daofind(scidata - median, mask=mask)

    # Sort the sources from brightest to faintest.
    invsort = np.argsort(sources['flux'])[::-1]
    sources = sources[invsort]

    # If nmax is given pick only the nmax brightest sources.
    if nmax is not None:
        nmax = np.minimum(len(sources), nmax)
        sources = sources[:nmax]

    return sources
예제 #15
0
def dao(i):
    """Entrée:
        i: numéro de l'image que l'on veut étudier
    Sortie:
        la liste des objets présents sur l'image i avec leurs données sous forme d'une liste de liste (indice de l'objet,
         coord x, coord y, sharpness, roundness 1, roundness 2, npix, sky, peak, flux, mag)
    """

    # Ouvre l'image format .fits suivante
    hdul = fits.open(
        '/home/maxime/Documents/Workspace Python/Project_S3/photos/tn%d0.fts' %
        i)  # Modifier le chemin d'accès pour ouvrir les images
    hdu = hdul[0].data

    # On utilise des paramètres adaptés afin de détecter tous les objets sur l'image
    mean, median, std = sigma_clipped_stats(hdu, sigma=3.0)
    # Nous avons fait les 3 premières étoiles avec fwhm=10
    # La dernière a été faite avec fwhm=5
    daofind = DAOStarFinder(fwhm=5.0, threshold=5 * std)
    sources = daofind(hdu - median)

    # Construit une table avec les données relatives aux objets détéctés
    for col in sources.colnames:
        sources[col].info.format = '%.8g'
    return sources
예제 #16
0
def takePicture():

    img = cv2.imread('output/20201024013736_ZWO_ASI294MC_Pro.tiff')
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    mean, median, std = sigma_clipped_stats(gray, sigma=3.0)
    print(f'mean:{mean} median:{median} std:{std}')
    daofind = DAOStarFinder(fwhm=5.0, threshold=5. * std)
    print(gray.shape, median.shape)
    sources = daofind(gray - median)
    for col in sources.colnames:
        sources[col].info.format = '%.8g'  # for consistent table output
    print(sources)

    import numpy as np
    import matplotlib.pyplot as plt
    from astropy.visualization import SqrtStretch
    from astropy.visualization.mpl_normalize import ImageNormalize
    from photutils import CircularAperture
    positions = np.transpose((sources['xcentroid'], sources['ycentroid']))
    apertures = CircularAperture(positions, r=4.)
    norm = ImageNormalize(stretch=SqrtStretch())
    plt.imshow(gray,
               cmap='Greys',
               origin='lower',
               norm=norm,
               interpolation='nearest')
    apertures.plot(color='blue', lw=1.5, alpha=0.5)
    plt.savefig('kk.png')
    cv2.namedWindow('Falcon')
    cv2.imshow('Falcon', gray)
    cv2.waitKey(0)

    return
예제 #17
0
    def find_guide_star(self):
        """ Find a guide star

        Uses DAOStar find the `photutils` package to find all point sources in
        the image after sigma clipping. The 10th best match is selected and the
        X and Y pixel coordinates are returned.

        Returns:
            tuple(int, int): X and Y pixel coordinates of matched star
        """
        self.logger.debug("Finding point sources in image")
        data = fits.getdata(self.image_path)
        mean, median, std = sigma_clipped_stats(data)
        daofind = DAOStarFinder(fwhm=3.0, threshold=5. * std)
        sources = daofind(data - median)
        sources.sort('flux')
        sources.reverse()

        selected = sources[9]  # 10th best match
        x = selected['xcentroid']
        y = selected['ycentroid']

        self.logger.debug("Found star at pixel coordinates ({}, {})".format(
            x, y))
        return x, y
예제 #18
0
def find_psf_centers(imagePass,fwhmPass,thresholdPass):
    # uses the grid of guesses to find the real centroids
    
    daofind = DAOStarFinder(fwhm=fwhmPass, threshold=thresholdPass, exclude_border=True)
    sources = daofind(imagePass)

    return sources['xcentroid'], sources['ycentroid']
예제 #19
0
 def photometry(self,filepath, b, d):
     hdulist = fits.open(filepath, ignore_missing_end=True)
     hdu = hdulist[0]
     hdu.data.shape
     image = hdu.data.astype(float)
     image -= np.median(image)
     bkg_sigma = mad_std(image)
     daofind = DAOStarFinder(fwhm=b, threshold=d * bkg_sigma)
     sources = daofind(image)  # Save Stellar Sources from DOA Star Algorithm
     for col in sources.colnames:
         sources[col].info.format = '%.8g'  # for consistent table output
     print(sources)
     # Perform Aperture Photometry
     positions = (sources['xcentroid'], sources['ycentroid'])
     apertures = CircularAperture(positions, r=17.)
     phot_table = aperture_photometry(image, apertures)
     for col in phot_table.colnames:
         phot_table[col].info.format = '%.8g'  # for consistent table output
     filedest1 = input("Where to Save the result:")
     filedest2 = input("Where to Save the result 2:")
     print(phot_table)
     np.savetxt(filedest1, (sources), delimiter=',')  # Save Result in CSV
     np.savetxt(filedest2, (phot_table), delimiter=',')  # Save Result in CSV
     plt.imshow(image, cmap='gray_r', origin='lower')
     apertures.plot(color='blue', lw=1.5, alpha=0.5)
     plt.show()
def do_psf(image_num, Letter):

    epsf = build_epsf(image_num)

    daofind = DAOStarFinder(fwhm=8, threshold=3. * Std[image_num])

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

    photometry = IterativelySubtractedPSFPhotometry(finder=daofind,
                                                    group_maker=daogroup,
                                                    bkg_estimator=None,
                                                    psf_model=epsf,
                                                    fitter=LevMarLSQFitter(),
                                                    aperture_radius=5,
                                                    niters=1,
                                                    fitshape=(11, 11))

    result_tab = photometry(image=Reduced_Image_Data[image_num])
    #residual_image = photometry.get_residual_image()

    X_0 = result_tab['x_fit']
    Y_0 = result_tab['y_fit']
    Flux = result_tab['flux_fit']
    Flux_Err = np.sqrt(np.array(Flux))
    PSF_Mags_1 = -2.5 * np.log10(
        np.array(Flux))  # Convert aperture sums to magnitudes
    PSF_Mags_Err_1 = ((-2.5 * Flux_Err) / (np.log10(10) * Flux))

    return PSF_Mags_1, PSF_Mags_Err_1, Flux, Flux_Err, X_0, Y_0
 def find_stars(self, max_dim_per=0.005, times_std=5, n_brightest=20):
     max_dim = max(self.img.shape)
     daofind = DAOStarFinder(fwhm=max_dim * max_dim_per,
                             threshold=times_std * self.std,
                             brightest=n_brightest)
     sources = daofind(self.processed_img)
     self.sources = sources.to_pandas()
예제 #22
0
def build_star_finder(reduction_metadata, image_path, log):
    """Function to construct a DAOStarFinder object to detect point sources
    in an image"""

    log.info('Building star finder for ' + os.path.basename(image_path))

    image_idx = reduction_metadata.images_stats[1]['IM_NAME'].tolist().index(
        os.path.basename(image_path))

    fwhm = reduction_metadata.images_stats[1]['FWHM_X'][image_idx]
    sky_bkgd = reduction_metadata.images_stats[1]['SKY'][image_idx]

    sky_bkgd_sig = np.sqrt(sky_bkgd)

    log.info('FWHM = ' + str(fwhm))
    log.info('Sky background = ' + str(sky_bkgd))

    det_threshold = 3.0 * sky_bkgd_sig

    log.info('Sky background sigma = ' + str(sky_bkgd_sig))

    daofind = DAOStarFinder(fwhm=fwhm, threshold=det_threshold)

    log.info('Completed star finder object')

    return daofind
예제 #23
0
def make_master_cat(path, root):
    """
    Create catalog of sources from deepsky

    Args:
        path: str - path to deepsky

    Returns:
        a catalog of sources with their timestamp
    """
    kwargs_stat = {'sigma': 3.0, 'maxiters': 5}

    with fits.open(path) as hdu:
        data = hdu[0].data
        mean, median, std = sigma_clipped_stats(data, **kwargs_stat)
        kwargs_dao = {'fwhm': 10.0, 'threshold': 5 * std}
        print('mean: ' + str(mean))
        print('median: ' + str(median))
        print('std: ' + str(std))
        # Next Subtract background and use DAOStarFinder
        print('kwargs_dao: ' + str(kwargs_dao))
        daofind = DAOStarFinder(**kwargs_dao)
        sources = daofind(data - median)

    filename, _ = splitext(basename(path))
    catfile = root + '/deepsky/' + filename + '.cat'
    ascii.write(sources, catfile, overwrite=True)

    # add RA and DEC to cat file
    args_makecatalog = Table()
    args_makecatalog['aligned_path'] = [path]
    args_makecatalog['cat_path'] = [catfile]
    make_catalog(args_makecatalog)

    return catfile
예제 #24
0
def source_detection(imdata):
    mean, median, std = sigma_clipped_stats(imdata, sigma=3.0, iters=5)
    daofind = DAOStarFinder(fwhm=3.0, threshold=5. * std)
    sources = daofind(imdata - median)
    sources.sort('flux')
    sources.reverse()
    return sources
예제 #25
0
    def centroid(self, x, y, data, radius):
        dist = 1024
        x0, y0, arr = self.cut_region(x, y, radius, data)
        mean, median, std = sigma_clipped_stats(arr, sigma=sigma)
        daofind = DAOStarFinder(threshold=5.*std, fwhm=fwhm_daofind)
        sources = daofind.find_stars(arr - median)
        cx, cy = x, y
        for i in sources:
            dist_temp = math.sqrt(abs(i[1]+x0-x)**2 + abs(i[2]+y0-y)**2)
            if dist_temp < dist:
                dist = dist_temp
                cx = i[1] + x0
                cy = i[2] + y0

        print('center: ', cx + 1, cy + 1)
        return (cx, cy)
예제 #26
0
def get_n_source(data,
                 subtract_median=False,
                 return_data=False,
                 fwhm=3.0,
                 nstd=5.0):
    nx = data.shape[0]
    if subtract_median == True:
        median_size = 40
        data_median = np.asfarray(
            median_filter(data, size=(median_size, median_size)))
        data -= data_median
    mean, median, std = sigma_clipped_stats(data, sigma=3.0)
    daofind = DAOStarFinder(fwhm=fwhm, threshold=nstd * std)
    try:
        warnings.filterwarnings('ignore', category=UserWarning, append=True)
        sources = daofind(data - median)
        ix = (sources["xcentroid"] > 10) & (sources["xcentroid"] < nx - 10) & (
            sources["ycentroid"] > 10) & (sources["ycentroid"] < nx - 10)
        sources = sources[ix]
        n = len(sources)
    except Exception:
        n = 0
    if return_data == False:
        return n
    else:
        return n, data
예제 #27
0
def find_stars(image,
               imgfile,
               fwhm=3.0,
               nsigma=3,
               sigma=None,
               verbose=True,
               overwrite=False):
    from astropy.table import Table

    starsfile = os.path.join(reduxdir,
                             'stars-{}'.format(os.path.basename(imgfile)))
    if not os.path.isfile(starsfile) or overwrite:
        from photutils import DAOStarFinder
        if sigma is None:
            sigma = np.std(image)

        daofind = DAOStarFinder(fwhm=fwhm, threshold=nsigma * sigma)
        srcs = daofind(image)
        # reverse-sort by flux
        srcs.sort('flux')
        srcs.reverse()
        if verbose:
            print('Found {} sources'.format(len(srcs)))

        print('Writing {} stars to {}'.format(len(srcs), starsfile))
        srcs.write(starsfile, overwrite=True)
    else:
        srcs = Table.read(starsfile)
        print('Read {} stars from {}'.format(len(srcs), starsfile))
    return srcs
예제 #28
0
def get_wcs(pattern):
    for filename in pattern:

        which_hdu = choose_hdu(filename)
        header = fits.getheader(filename, which_hdu)
        print(header)
        w = WCS(header)
        print(w)

        data = fits.getdata(filename, ext=0)
        threshold = detect_threshold(data, nsigma=2.)
        sigma = 3.0 * gaussian_fwhm_to_sigma  # FWHM = 3.
        kernel = Gaussian2DKernel(sigma, x_size=3, y_size=3)
        kernel.normalize()
        mean, median, std = sigma_clipped_stats(data, sigma=3)
        daofind = DAOStarFinder(fwhm=3.0, threshold=5. * std)
        sources = daofind(data - median)
        for col in sources.colnames:
            sources[col].info.format = '%.8g'  # for consistent table output

        x_unscaled = np.array(sources['xcentroid'])
        y_unscaled = np.array(sources['ycentroid'])
        x_min = min(x_unscaled)
        y_min = min(y_unscaled)
        x_max = max(x_unscaled)
        y_max = max(y_unscaled)
        x1 = ((x_unscaled - x_min) / x_max) * 90
        y1 = ((y_unscaled - y_min) / y_max) * 90
        fig, ax = plt.subplots()
        ax.plot(x1, y1, 'ok', ms=5)

        plt.show()
        c1 = SkyCoord(ra=x1 * u.degree, dec=y1 * u.degree)
        print(c1)
        coo = SkyCoord.from_name('GJ3470')
예제 #29
0
def Centroids_DAO(Flux, Median, TPF=None, Plot=False):
    """
    Calculate the centroid shifts of time series images.
    """
    m = Median.copy()
    f = Flux  #TPF.flux.copy()
    mean, med, std = sigma_clipped_stats(m, sigma=3.0)
    daofind = DAOStarFinder(fwhm=3.0, threshold=5. * std)
    s = daofind(m - med)
    mx = s['xcentroid']
    my = s['ycentroid']
    shifts = np.zeros((len(TPF.flux), 2, len(mx))) * np.nan
    for i in range(len(f)):
        if np.nansum(f[i]) > 0:
            mean, med, std = sigma_clipped_stats(f[i], sigma=3.0)
            s = daofind(f[i] - med)
            x = s['xcentroid']
            y = s['ycentroid']
            dist = np.zeros((len(mx), len(x)))
            dist = dist + np.sqrt((x[np.newaxis, :] - mx[:, np.newaxis])**2 +
                                  (y[np.newaxis, :] - my[:, np.newaxis])**2)

            ind = np.argmin(dist, axis=1)
            indo = np.nanmin(dist) < 1
            ind = ind[indo]
            shifts[i, 0, indo] = x[ind] - mx[indo]
            shifts[i, 1, indo] = y[ind] - my[indo]

    meds = np.nanmedian(shifts, axis=2)
    smooth = Smooth_motion(meds, TPF)
    nans = np.nansum(f, axis=(1, 2)) == 0
    smooth[nans] = np.nan
    if Plot:
        Plot_centroids(TPF, meds, smooth)
    return smooth
예제 #30
0
def DAOStarFinder_wrapper(args_dao, kwargs):
    path = args_dao[0]
    median = args_dao[1]
    with fits.open(path) as fitsfile:
        data = fitsfile[0].data
        daofind = DAOStarFinder(**kwargs)
        return daofind(data - median)
예제 #31
0
def centralizar(img, banda, cx, cy):
    '''
    Encontra uma fonte dentro de uma abertura com o raio definido pelo usuário
    '''

    xmax, ymax = img.shape
    dmin = np.sqrt(xmax*xmax+ymax*ymax)

    r = session['r']
    aperture = CircularAperture((cx,cy), r)
    mask = aperture.to_mask()
    print(mask)
    _, median, std = session['stats'][banda]
    find = DAOStarFinder(fwhm=3, threshold=3*std)
    cr = find((img-median)*mask.to_image(img.shape))
    if cr:
        print(cr)
        # Pega o índice mais próxima do ponto clicado
        for i in range(len(cr)):
            x = cr[i]['xcentroid']
            y = cr[i]['ycentroid']
            d = np.sqrt((x-cx)**2+(y-cy)**2)
            if d<dmin:
                dmin = d
                cx = cr[i]['xcentroid']
                cy = cr[i]['ycentroid']

    return cx,cy