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)) result_tab = photometry(image=image) residual_image = photometry.get_residual_image() #Plot images made# plt.subplot(1, 2, 1) plt.imshow(image, cmap='viridis', aspect=1,
# 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, bkg_estimator = mmm_bkg, psf_model = psf_model, fitter = LevMarLSQFitter(), niters = 1, fitshape = (2 * fwhm - 1, 2 * fwhm - 1)) # On exécute le tout et on extrait des résultats ! result_tabBV = photometry (image = imageSumBV) residual_imageBV = photometry.get_residual_image () #result_tabBV.write ('result_tabBV.2.5s.dat', format = 'ascii') #np.array (residual_imageBV).tofile ('residual_imageBV.2.5s.dat') #residual_imageBV = np.fromfile ('residual_imageBV.2.5s.dat', dtype=np.float32).reshape ((1804, 1804))
def extractFlux(cnam, ccd, rccd, read, gain, ccdwin, rfile, store): """This extracts the flux of all apertures of a given CCD. The steps are (1) creation of PSF model, (2) PSF fitting, (3) flux extraction. The apertures are assumed to be correctly positioned. It returns the results as a dictionary keyed on the aperture label. Each entry returns a list: [x, ex, y, ey, fwhm, efwhm, beta, ebeta, counts, countse, sky, esky, nsky, nrej, flag] flag = bitmask. See hipercam.core to see all the options which are referred to by name in the code e.g. ALL_OK. The various flags can signal that there no sky pixels (NO_SKY), the sky aperture was off the edge of the window (SKY_AT_EDGE), etc. This code:: >> bset = flag & TARGET_SATURATED determines whether the data saturation flag is set for example. Arguments:: cnam : string CCD identifier label ccd : CCD the debiassed, flat-fielded CCD. rccd : CCD corresponding raw CCD, used to work out whether data are saturated in target aperture. read : CCD readnoise divided by the flat-field gain : CCD gain multiplied by the flat field ccdwin : dictionary of strings the Window label corresponding to each Aperture rfile : Rfile reduce file configuration parameters store : dict of dicts see moveApers for what this contains. """ # initialise flag flag = hcam.ALL_OK ccdaper = rfile.aper[cnam] results = {} # get profile params from aperture store mfwhm = store["mfwhm"] mbeta = store["mbeta"] method = "m" if mbeta > 0.0 else "g" if mfwhm <= 0: # die hard, die soon as there's nothing we can do. print((" *** WARNING: CCD {:s}: no measured FWHM to create PSF model" "; no extraction possible").format(cnam)) # set flag to indicate no FWHM flag = hcam.NO_FWHM for apnam, aper in ccdaper.items(): info = store[apnam] results[apnam] = { "x": aper.x, "xe": info["xe"], "y": aper.y, "ye": info["ye"], "fwhm": info["fwhm"], "fwhme": info["fwhme"], "beta": info["beta"], "betae": info["betae"], "counts": 0.0, "countse": -1, "sky": 0.0, "skye": 0.0, "nsky": 0, "nrej": 0, "flag": flag, } return results # all apertures have to be in the same window, or we can't easily make a # postage stamp of the data wnames = set(ccdwin.values()) if len(wnames) != 1: print((" *** WARNING: CCD {:s}: not all apertures" " lie within the same window; no extraction possible" ).format(cnam)) # set flag to indicate no extraction flag = hcam.NO_EXTRACTION # return empty results for apnam, aper in ccdaper.items(): info = store[apnam] results[apnam] = { "x": aper.x, "xe": info["xe"], "y": aper.y, "ye": info["ye"], "fwhm": info["fwhm"], "fwhme": info["fwhme"], "beta": info["beta"], "betae": info["betae"], "counts": 0.0, "countse": -1, "sky": 0.0, "skye": 0.0, "nsky": 0, "nrej": 0, "flag": flag, } return results wnam = wnames.pop() # PSF params are in binned pixels, so find binning bin_fac = ccd[wnam].xbin # create PSF model if method == "m": psf_model = MoffatPSF(beta=mbeta, fwhm=mfwhm / bin_fac) else: psf_model = IntegratedGaussianPRF(sigma=mfwhm * gaussian_fwhm_to_sigma / bin_fac) # force photometry only at aperture positions # this means PSF shape and positions are fixed, we are only fitting flux if rfile["psf_photom"]["positions"] == "fixed": psf_model.x_0.fixed = True psf_model.y_0.fixed = True # create instances for PSF photometry gfac = float(rfile["psf_photom"]["gfac"]) sclip = float(rfile["sky"]["thresh"]) daogroup = DAOGroup(gfac * mfwhm / bin_fac) mmm_bkg = MMMBackground(sigma_clip=SigmaClip(sclip)) fitter = LevMarLSQFitter() fitshape_box_size = int(2 * int(rfile["psf_photom"]["fit_half_width"]) + 1) fitshape = (fitshape_box_size, fitshape_box_size) photometry_task = BasicPSFPhotometry( group_maker=daogroup, bkg_estimator=mmm_bkg, psf_model=psf_model, fitter=fitter, fitshape=fitshape, ) # initialise flag flag = hcam.ALL_OK # extract Windows relevant for these apertures wdata = ccd[wnam] wraw = rccd[wnam] # extract sub-windows that include all of the apertures, plus a little # extra around the edges. x1 = min([ap.x - ap.rsky2 - wdata.xbin for ap in ccdaper.values()]) x2 = max([ap.x + ap.rsky2 + wdata.xbin for ap in ccdaper.values()]) y1 = min([ap.y - ap.rsky2 - wdata.ybin for ap in ccdaper.values()]) y2 = max([ap.y + ap.rsky2 + wdata.ybin for ap in ccdaper.values()]) # extract sub-Windows swdata = wdata.window(x1, x2, y1, y2) swraw = wraw.window(x1, x2, y1, y2) # compute pixel positions of apertures in windows xpos, ypos = zip(*((swdata.x_pixel(ap.x), swdata.y_pixel(ap.y)) for ap in ccdaper.values())) positions = Table(names=["x_0", "y_0"], data=(xpos, ypos)) # do the PSF photometry photom_results = photometry_task(swdata.data, init_guesses=positions) slevel = mmm_bkg(swdata.data) # unpack the results and check apertures for apnam, aper in ccdaper.items(): try: # reset flag flag = hcam.ALL_OK result_row = photom_results[photom_results["id"] == int(apnam)] if len(result_row) == 0: flag |= hcam.NO_DATA raise hcam.HipercamError( "no source in PSF photometry for this aperture") elif len(result_row) > 1: flag |= hcam.NO_EXTRACTION raise hcam.HipercamError( "ambiguous lookup for this aperture in PSF photometry") else: result_row = result_row[0] # compute X, Y arrays over the sub-window relative to the centre # of the aperture and the distance squared from the centre (Rsq) # to save a little effort. x = swdata.x(np.arange(swdata.nx)) - aper.x y = swdata.y(np.arange(swdata.ny)) - aper.y X, Y = np.meshgrid(x, y) Rsq = X**2 + Y**2 # size of a pixel which is used to taper pixels as they approach # the edge of the aperture to reduce pixellation noise size = np.sqrt(wdata.xbin * wdata.ybin) # target selection, accounting for extra apertures and allowing # pixels to contribute if their centres are as far as size/2 beyond # the edge of the circle (but with a tapered weight) dok = Rsq < (aper.rtarg + size / 2.0)**2 if not dok.any(): # check there are some valid pixels flag |= hcam.NO_DATA raise hcam.HipercamError("no valid pixels in aperture") # check for saturation and nonlinearity if cnam in rfile.warn: if swraw.data[dok].max() >= rfile.warn[cnam]["saturation"]: flag |= hcam.TARGET_SATURATED if swraw.data[dok].max() >= rfile.warn[cnam]["nonlinear"]: flag |= hcam.TARGET_NONLINEAR else: warnings.warn( "CCD {:s} has no nonlinearity or saturation levels set") counts = result_row["flux_fit"] countse = result_row["flux_unc"] info = store[apnam] results[apnam] = { "x": aper.x, "xe": info["xe"], "y": aper.y, "ye": info["ye"], "fwhm": info["fwhm"], "fwhme": info["fwhme"], "beta": info["beta"], "betae": info["betae"], "counts": counts, "countse": countse, "sky": slevel, "skye": 0, "nsky": 0, "nrej": 0, "flag": flag, } except hcam.HipercamError as err: info = store[apnam] flag |= hcam.NO_EXTRACTION results[apnam] = { "x": aper.x, "xe": info["xe"], "y": aper.y, "ye": info["ye"], "fwhm": info["fwhm"], "fwhme": info["fwhme"], "beta": info["beta"], "betae": info["betae"], "counts": 0.0, "countse": -1, "sky": 0.0, "skye": 0.0, "nsky": 0, "nrej": 0, "flag": flag, } # finally, we are done return results
#plt.show() fitsStars = fits.open("Images/FitsImages/L_2019-04-08_22-59-51_c.fits") imgStars = fitsStars[0].data.astype(np.float64) #bkg = MMMBackground() #background = bkg(imgStars) #gaussian_prf = PRF() #gaussian_prf.sigma.fixed = False #photTester = DAOP(8,background,5,gaussian_prf,(11,11)) daogroup = DAOGroup(crit_separation=8) mmm_bkg = MMMBackground() iraffind = DAOStarFinder(threshold=2 * mmm_bkg(imgStars), fwhm=4.5) fitter = LevMarLSQFitter() gaussian_prf = IntegratedGaussianPRF(sigma=2.05) gaussian_prf.sigma.fixed = False photTester = IterativelySubtractedPSFPhotometry(finder=iraffind, group_maker=daogroup, bkg_estimator=mmm_bkg, psf_model=gaussian_prf, fitter=fitter, fitshape=(11, 11), niters=2) photResults = photTester(imgStars) print(photResults['x_fit', 'y_fit', 'flux_fit']) finalImg = photTester.get_residual_image() rescale = 200
from astropy.modeling.fitting import LevMarLSQFitter from astropy.stats import gaussian_sigma_to_fwhm 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) #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=(11, 11)) result_tab = photometry(image=image) residual_image = photometry.get_residual_image() plt.subplot(1, 2, 1) plt.imshow(image, cmap='viridis', aspect=1,
def daophot(cnam, ccd, xlo, xhi, ylo, yhi, niters, method, fwhm, beta, gfac, thresh, rejthresh): """ Perform iterative PSF photometry and star finding on region of CCD """ print(xlo, ylo, xhi, yhi) # first check we are within a single window wnam1 = ccd.inside(xlo, ylo, 2) wnam2 = ccd.inside(xhi, yhi, 2) if wnam1 != wnam2: raise hcam.HipercamError( 'PSF photometry cannot currently be run across seperate windows') wnam = wnam1 print(wnam) # background stats from whole windpw # estimate background RMS wind = ccd[wnam] rms_func = MADStdBackgroundRMS(sigma_clip=SigmaClip(sigma=rejthresh)) bkg_rms = rms_func(wind.data) bkg_func = MMMBackground(sigma_clip=SigmaClip(sigma=rejthresh)) bkg = bkg_func(wind.data) print(' Background estimate = {}, BKG RMS = {}'.format(bkg, bkg_rms)) # crop window to ROI wind = ccd[wnam].window(xlo, xhi, ylo, yhi) # correct FWHM for binning fwhm /= wind.xbin if method == 'm': psf_model = MoffatPSF(fwhm, beta) print(' FWHM = {:.1f}, BETA={:.1f}'.format(fwhm, beta)) else: psf_model = IntegratedGaussianPRF(sigma=fwhm * gaussian_fwhm_to_sigma) print(' FWHM = {:.1f}'.format(fwhm)) # region to extract around positions for fits fitshape = int(5 * fwhm) # ensure odd if fitshape % 2 == 0: fitshape += 1 photometry_task = DAOPhotPSFPhotometry(gfac * fwhm, thresh * bkg_rms, fwhm, psf_model, fitshape, niters=niters, sigma=rejthresh) with warnings.catch_warnings(): warnings.simplefilter('ignore') results = photometry_task(wind.data - bkg) # filter out junk fits tiny = 1e-30 bad_errs = (results['flux_unc'] < tiny) | (results['x_0_unc'] < tiny) | ( results['y_0_unc'] < tiny) results = results[~bad_errs] results.write('table_{}.fits'.format(cnam)) print(' found {} stars'.format(len(results))) xlocs, ylocs = results['x_fit'], results['y_fit'] # convert to device coordinates xlocs = wind.x(xlocs) ylocs = wind.y(ylocs) return xlocs, ylocs
def compute_photutils(settings, image_data): # Taken from photuils example http://photutils.readthedocs.io/en/stable/psf.html # See also http://photutils.readthedocs.io/en/stable/api/photutils.psf.DAOPhotPSFPhotometry.html#photutils.psf.DAOPhotPSFPhotometry sigma_psf = settings.sigma_psf crit_separation = settings.crit_separation threshold = settings.threshold box_size = settings.box_size niters = settings.iters bkgrms = MADStdBackgroundRMS(SigmaClip(sigma=3.)) std = bkgrms(image_data) logger.info('Using sigma=%f, threshold=%f, separation=%f, box_size=%d, niters=%d, std=%f' % \ (sigma_psf, threshold, crit_separation, box_size, niters, std)) fitter = LevMarLSQFitter() # See findpars args http://stsdas.stsci.edu/cgi-bin/gethelp.cgi?findpars photargs = { 'crit_separation': crit_separation * sigma_psf * gaussian_sigma_to_fwhm, #'crit_separation': crit_separation, 'threshold': threshold * std, 'fwhm': sigma_psf * gaussian_sigma_to_fwhm, 'sigma_radius': sigma_psf * gaussian_sigma_to_fwhm, #'sigma': 3.0, 'fitter': fitter, 'niters': niters, 'fitshape': (box_size, box_size), 'sharplo': 0.2, 'sharphi': 2.0, 'roundlo': -1.0, 'roundhi': 1.0, 'psf_model': IntegratedGaussianPRF(sigma=sigma_psf), 'aperture_radius': sigma_psf * gaussian_sigma_to_fwhm, } # starfinder takes 'exclude border' # photargs['psf_model'].sigma.fixed = False photometry = DAOPhotPSFPhotometry(**photargs) # Column names: # 'flux_0', 'x_fit', 'x_0', 'y_fit', 'y_0', 'flux_fit', 'id', 'group_id', # 'flux_unc', 'x_0_unc', 'y_0_unc', 'iter_detected' result_tab = photometry(image=image_data) # Only use from final iteration # result_tab = result_tab[result_tab['iter_detected'] == niters] logger.info('Fit info: %s' % fitter.fit_info['message']) # Filter out negative flux #result_tab = result_tab[result_tab['flux_fit'] >= 0] # Formula: https://en.wikipedia.org/wiki/Instrumental_magnitude result_tab['mag'] = -2.5 * np.log10(result_tab['flux_fit']) result_tab['mag_unc'] = np.abs(-2.5 * np.log10(result_tab['flux_fit'] + result_tab['flux_unc']) - \ -2.5 * np.log10(result_tab['flux_fit'] - result_tab['flux_unc'])) / 2.0 # http://www.ucolick.org/~bolte/AY257/s_n.pdf #result_tab['snr'] = 1.0875 / result_tab['mag_unc'] result_tab['snr'] = 1.0 / (np.power(10, (result_tab['mag_unc'] / 2.5)) - 1) residual_image = photometry.get_residual_image() return result_tab, residual_image, std
gauss = 0 if(np.ma.count(image) >= 7): gauss = photutils.fit_2dgaussian(image[40 : 61, 40 : 61], mask = None) fwhm = 0 if gauss != 0: fwhm = abs(gauss.x_stddev) * gaussian_sigma_to_fwhm print(fwhm) daogroup = DAOGroup(5.0*sigma_psf*gaussian_sigma_to_fwhm) mmm_bkg = MMMBackground() fitter = LevMarLSQFitter() psf_model = IntegratedGaussianPRF(sigma=abs(gauss.x_stddev)) fitshape = (int(3. * fwhm), int(3. * fwhm)) if int(3. * fwhm) % 2 == 0: fitshape = (int(3. * fwhm) + 1, int(3. * fwhm) + 1) photometry = IterativelySubtractedPSFPhotometry(finder=iraffind, group_maker=daogroup, bkg_estimator=mmm_bkg, psf_model=psf_model, fitter=LevMarLSQFitter(), niters=1, fitshape=fitshape) result_tab = photometry(image=image) residual_image = photometry.get_residual_image() #print(result_tab)
def get_photometry(self, aperture_radius=3, fwhm=None, sky_radius_inner=None, sky_radius_outer=None, mag_zero_point=0, mode="basic"): if sky_radius_outer is None: sky_radius_outer = np.min(self.image.shape) // 2 if sky_radius_inner is None: sky_radius_inner = sky_radius_outer - 3 x, y = np.array(self.image.shape) // 2 r = aperture_radius ro = sky_radius_outer dw = sky_radius_outer - sky_radius_inner bg = np.copy(self.image[y - ro:y + ro, x - ro:x + ro]) bg[dw:-dw, dw:-dw] = 0 bg_median = np.median(bg[bg != 0]) bg_std = np.std(bg[bg != 0]) noise = bg_std * np.sqrt(np.sum(bg != 0)) im = np.copy(self.image[y - r:y + r, x - r:x + r]) if "circ" in mode.lower(): pass elif "basic" in mode.lower(): flux = np.sum(im - bg_median) self.results = None elif "psf" in mode.lower(): if fwhm is None: warnings.warn("``fwhm`` must be given for PSF photometry") flux = 0 try: x, y = self._find_center(self.image, fwhm) flux = self._basic_psf_flux(self.image, fwhm, x=x, y=y) ##### Really bad form!!! Keep this in mind =) self.x, self.y = x, y except: flux = 0 elif "dao" in mode.lower(): if fwhm is None: warnings.warn("``fwhm`` must be given for PSF photometry") flux = 0 sigma = fwhm / 2.35 prf = IntegratedGaussianPRF(sigma) fitshape = im.shape[0] if im.shape[0] % 2 == 1 else im.shape[0] - 1 daophot = DAOPhotPSFPhotometry(crit_separation=sigma, threshold=np.median(im), fwhm=fwhm, psf_model=prf, fitshape=fitshape) #try: results = daophot(im) width, height = im.shape dist_from_centre = np.sqrt((results["x_fit"] - width / 2)**2 + \ (results["y_fit"] - height / 2)**2) i = np.argmin(dist_from_centre) x, y = results["x_fit"][i], results["y_fit"][i], flux = results["flux_fit"][i] ##### Really bad form!!! Keep this in mind =) self.x, self.y = x, y self.results = results #except: # self.results = None # flux = 0 snr = flux / noise mag = -2.5 * np.log10(flux) + mag_zero_point return mag, snr, flux, noise, bg_std, bg_median
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()
#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 from photutils.psf import DAOPhotPSFPhotometry photometry = DAOPhotPSFPhotometry(crit_separation=3*fwhm, threshold=3.5*std, fwhm=fwhm, psf_model=psf_model, fitshape=(fitshape, fitshape), sharplo=0.0, sharphi=2.0, roundlo=-5.0, roundhi=5.0, fitter=iraffind, niters=100, aperture_radius=1.2*fwhm) raw_input('Done') print 'Results table' result_tab = photometry(image=image)
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)