Пример #1
0
def find_objects(inputImage):
    """
    Find the objects in the field
    use DAOfind 
    """

    output_locations= inputImage  + ".stars" #best to set this if you're scripting
    
    #check if a file already exists and remove it
    if os.access(output_locations,os.F_OK):
        print "Removing previous star location file"
        os.remove(output_locations)
        
    
    #set up some finding parameters, you can make this more explicit
    iraf.daophot.findpars.threshold=3.0 #3sigma detections only
    iraf.daophot.findpars.nsigma=1.5 #width of convolution kernal in sigma
    iraf.daophot.findpars.ratio=1.0 #ratio of gaussian axes
    iraf.daophot.findpars.theta=0.
    iraf.daophot.findpars.sharplo=0.2 #lower bound on feature
    iraf.daophot.findpars.sharphi=1.0 #upper bound on feature
    iraf.daophot.findpars.roundlo=-1.0 #lower bound on roundness
    iraf.daophot.findpars.roundhi=1.0 #upper bound on roundness
    iraf.daophot.findpars.mkdetections="no"
    
    #assume the science extension
    sci="[SCI,1]"
    message(inputImage + sci)
    iraf.daofind(image=inputImage+sci,output=output_locations,interactive="no",verify="no",verbose="no")

    print "Saved output locations to %s"%(output_locations)
    
    return output_locations #return the name of the saved file
Пример #2
0
def run_daofind(image, wht='NA', extension=0, outfile='default',dthreshold=3.0, fwhmpsf=2.5, backsigma=-1.0,rdnoise=-1.0):
	'''RUN DAOFIND ON INPUT IMAGE'''

	# Parse input parameters
	if outfile == 'default': outfile = image+'0.coo.1'

	# Read in fits header
	f = pyfits.open(image)
	fheader = f[0].header

	# Extract relevant info from the header (exposure, filter, input/output pixel scale)
	exptime = fheader['exptime']
	instr = fheader['INSTRUME']
	if instr == 'WFC3':
		filter = fheader['FILTER']
	else: #assuming ACS
		filter = fheader['FILTER1']
		if filter[0] == 'C': filter == fheader['FILTER2']
	opxscl=0.03962
	ipxscl=0.03962
	f.close()

        # Assign number of flt images (IR/calibration images only have 1 chip; NDRIZIM keyword includes both chips from single FLT)
	if (fheader['detector'] == 'IR'): nchips = 1.0						# IR
	elif (fheader['subarray'] == True) and (len(fheader['CCDAMP']) == 1): nchips = 1.0	# UVIS sub-array
	elif (fheader['detector'] == 'UVIS') and (fheader['subarray'] == False): nchips = 2.0	# UVIS full-frame
        else: raise exception('Image type is not defined.')
	num_flts = 1.0


	# Perform read noise correction
	if rdnoise < 0.0:
		amps = fheader['CCDAMP']
		rdnoise = np.zeros(len(amps))
		for namp in xrange(len(amps)): rdnoise[namp] = fheader['READNSE'+amps[namp]]
	rdnoise_corr = np.sqrt(num_flts * (np.average(rdnoise) * opxscl/ipxscl)**2)


	# Perform background noise calculation
	if backsigma < 0.0:
                backstats=iraf.imstatistics(image+'[0]', fields='stddev', lower = -100, upper = 100, nclip=5, \
                                                lsigma=3.0, usigma=3.0, cache='yes', format='no',Stdout=1)
		backsigma=float(backstats[0])


	# remove old daofind files
	file_query = os.access(outfile, os.R_OK)	
	if file_query == True: os.remove(outfile)
	iraf.daofind.unlearn()
	iraf.daofind(image=image+'[0]', interactive='no', verify='no',output=outfile, fwhmpsf=fwhmpsf, sigma=backsigma, \
	readnoise=rdnoise_corr, itime=exptime, threshold=dthreshold, datamin=-10, datamax=100000)


	# Display results of daofind (***WORK IN PROGRESS***)
	#os.system('ds9&')
	#tmp=image.split('_cnts')
	#iraf.display(tmp[0]+'.fits',1, zscale='no', zrange='no', z1=0, z2=100,ztrans='log')
	#iraf.tvmark(1,outfile,mark = 'circle', radii = 8, color = 205)

	return outfile		# return name of coordinate file
Пример #3
0
def daofind(filelist):
	iraf.datapars.setParam("exposure", "EXPTIME")
	iraf.datapars.setParam("airmass", "AIRMASS")
	iraf.datapars.setParam("filter", "INSFILTE")
	iraf.datapars.setParam("ccdread", "RDNOISE")
	iraf.datapars.setParam("gain", "GAIN")

	iraf.centerpars.setParam("calgorithm", "centroid")

	iraf.photpars.setParam("apertures", "17.56")
	
	iraf.fitskypars.setParam("annulus", "20.56")
	iraf.fitskypars.setParam("dannulus", "5")
	
	

	with open(filelist) as file1:
		for line in file1:
			filename = line.strip()
			print("Filename %s"  % filename)
			y,z = np.loadtxt(filename + "-daoedit", usecols=[3,4], unpack=True)
			sigma = np.mean(y) 
			fwhm = np.mean(z)
			iraf.datapars.setParam("fwhmpsf", "%s" % str(fwhm)  )
			iraf.datapars.setParam("sigma", "%s" % str(sigma)  )
			iraf.daofind.setParam("mode", "h")
			iraf.phot.setParam("mode", "h")
			iraf.datapars.setParam("mode", "h")
			iraf.centerpars.setParam("mode", "h")
			iraf.fitskypars.setParam("mode", "h")
			iraf.photpars.setParam("mode", "h")
	
			iraf.daofind(filename, filename + "-daofind", mode='h')
			
			iraf.phot(filename, coords=(filename + "-daofind"), output=(filename+".mag"), mode='h')
Пример #4
0
def identify_objects(fnlist,skysiglist,fwhmlist,suffix=".coo"):
    """Runs the IRAF routine 'daofind' to locate objects in a series of images,
    creating coordinate files.
    
    Inputs:
    fnlist -> List of strings, each the path to a fits image.
    skysiglist -> List of floats, each the sky background sigma for an image.
    fwhmlist -> List of floats, each the FWHM of objects in an image.
    suffix -> Suffix for the coordinate files. '.coo' by default.
    
    Outputs:
    coolist -> List of strings, each the path to the coordinate files created.
    
    """
    
    print "Identifying objects in images..."
    
    coolist = []
    
    #Open IRAF packages
    iraf.noao(_doprint=0)
    iraf.digiphot(_doprint=0)
    iraf.apphot(_doprint=0)
    for i in range(len(fnlist)):
        coolist.append(fnlist[i]+suffix)
        iraf.daofind(image=fnlist[i],
                     output=fnlist[i]+suffix,
                     fwhmpsf=fwhmlist[i],
                     sigma=skysiglist[i],
                     threshold=4.0,
                     datamin='INDEF',
                     datamax='INDEF',
                     verify='N')
    return coolist
Пример #5
0
def run_daofind(image, wht='NA', extension=0, outfile='default',dthreshold=3.0, fwhmpsf=2.5, backsigma=-1.0,rdnoise=-1.0):
	'''RUN DAOFIND ON INPUT IMAGE'''

	# Parse input parameters
	if outfile == 'default': outfile = image+'0.coo.1'

	# Read in fits header
	f = pyfits.open(image)
	fheader = f[0].header

	# Extract relevant info from the header (exposure, filter, input/output pixel scale)
	exptime = fheader['exptime']
	instr = fheader['INSTRUME']
	if instr == 'WFC3':
		filter = fheader['FILTER']
	else: #assuming ACS
		filter = fheader['FILTER1']
		if filter[0] == 'C': filter == fheader['FILTER2']
	opxscl=0.03962
	ipxscl=0.03962
	f.close()

        # Assign number of flt images (IR/calibration images only have 1 chip; NDRIZIM keyword includes both chips from single FLT)
	if (fheader['detector'] == 'IR'): nchips = 1.0						# IR
	elif (fheader['subarray'] == True) and (len(fheader['CCDAMP']) == 1): nchips = 1.0	# UVIS sub-array
	elif (fheader['detector'] == 'UVIS') and (fheader['subarray'] == False): nchips = 2.0	# UVIS full-frame
        else: raise exception('Image type is not defined.')
	num_flts = 1.0


	# Perform read noise correction
	if rdnoise < 0.0:
		amps = fheader['CCDAMP']
		rdnoise = np.zeros(len(amps))
		for namp in xrange(len(amps)): rdnoise[namp] = fheader['READNSE'+amps[namp]]
	rdnoise_corr = np.sqrt(num_flts * (np.average(rdnoise) * opxscl/ipxscl)**2)


	# Perform background noise calculation
	if backsigma < 0.0:
                backstats=iraf.imstatistics(image+'[1]', fields='stddev', lower = -100, upper = 100, nclip=5, \
                                                lsigma=3.0, usigma=3.0, cache='yes', format='no',Stdout=1)
		backsigma=float(backstats[0])


	# remove old daofind files
	file_query = os.access(outfile, os.R_OK)	
	if file_query == True: os.remove(outfile)
	iraf.daofind.unlearn()
	iraf.daofind(image=image+'[1]', interactive='no', verify='no',output=outfile, fwhmpsf=fwhmpsf, sigma=backsigma, \
	readnoise=rdnoise_corr, itime=exptime, threshold=dthreshold, datamin=-10, datamax=100000)


	# Display results of daofind (***WORK IN PROGRESS***)
	#os.system('ds9&')
	#tmp=image.split('_cnts')
	#iraf.display(tmp[0]+'.fits',1, zscale='no', zrange='no', z1=0, z2=100,ztrans='log')
	#iraf.tvmark(1,outfile,mark = 'circle', radii = 8, color = 205)

	return outfile		# return name of coordinate file
Пример #6
0
def aperture_photometry(image,photfilesuffix,threshold=4.,wcs='logical',mode='small', telescope='Pairitel'):
  '''perform aperture photometry on a given image
  
  This procedure perfrom IRAF/DAOPHOT aperture phtometry on (all extensions of) a fits image.
  It sets some global daophot parameters, then perfroms daophot.daofind and daophot.phot
  The output .mag file is filtered for valid magnitudes and a mag.sex file computed, where
  all coordinates are transformed to sexagesimal coordinates.
  
  input: image: filename
  keywords:  threshold=4 :daofind detection threshold in sigma_sky
             wcs='logical' :working wcs system, can be  'logical','physical' or 'tv'
                        in any case an additional sexagesimal output file will be computed
         mode='small' : 'standard' = 'large' or 'psf' = 'small' choses a pre-defined aperture size for 
                        aperture photometry of standards or just as starting point for psf photometry
  '''
  print 'Performing aperture photometry on '+image
  if telescope == 'Pairitel':
      set_Pairitel_params()
  elif telescope == 'FLWO':
      set_FLWO_params()
  else:
      print 'No parameters found for this telescope!'
  
  iraf.mscred(_doprint=0)
  iraf.digiphot(_doprint=0)
  iraf.daophot(_doprint=0)
  iraf.daophot.verify = False
  iraf.daophot.wcsin = wcs
  iraf.daophot.wcsout = wcs
  iraf.daophot.wcspsf = wcs
  iraf.centerpars.cbox=2.*iraf.datapars.fwhmpsf
  iraf.fitskypars.annulus=20 # usually one would use 5.*iraf.datapars.fwhmpsf
  #annulus must be wide enough to have good sky statistics
  iraf.fitskypars.dannulus=10. # this is standard
  if 'standard'.find(mode.lower()) != -1 or 'large'.find(mode.lower()) != -1:
    iraf.photpars.aperture = 4.*iraf.datapars.fwhmpsf
    iraf.centerpars.calgorithm = 'centroid'
  elif 'small'.find(mode.lower()) != -1 or 'psf'.find(mode.lower()) != -1:
    iraf.photpars.aperture = 4. # close in for crowded regions
    iraf.centerpars.calgorithm = 'none'
  else:
    print '''use: aperture_photometry(image,threshold=4.,wcs="logical",mode="small")
    
    The following mode keywords are implemented: standard, large, psf, small'''
    raise NotImplementedError
  #for imagebi in fits_ext(image):
  sky,skydev=get_sky(image)
  iraf.datapars.datamin=sky-5*skydev
  iraf.datapars.sigma=skydev      
  #this could be changed to use Stdin and Stdout so that fewer files are written (saves space and time), but for debug purposes better keep all that
  iraf.daofind(image, output='default', verbose=False, verify=False, threshold=threshold) 
  iraf.daophot.phot(image, coords='default', output=image+photfilesuffix, verbose=False, verify=False, interactive=False, wcsout=wcs)
Пример #7
0
def run_daofind(image, extension=0,outfile='default',dthreshold=3.0, fwhmpsf=2.5, backsigma=-1.0,rdnoise=5.2):

	'''THIS PROCEDURE RUNS DAOFIND ON INPUT IMAGE'''

	# Parse input parameters
	if outfile == 'default': outfile = image+'0.coo.1'

	# Read in fits header
	f = pyfits.open(image)
	fheader = f[0].header
	f.close()

	# Extract relevant info from the header
	exptime = fheader['texptime']
	instr = fheader['INSTRUME']
	if instr == 'WFC3':
		filter = fheader['FILTER']
	else: #assuming ACS
		filter = fheader['FILTER1']
		if filter[0] == 'C': filter == fheader['FILTER2']
	ipxscl = fheader['D001ISCL']
	opxscl = fheader['D001SCAL']
	num_flts = float(fheader['NDRIZIM'])/2.0
	#df_max = 10000000.	# upper limit for "good" pixels (sometimes used to ID bad pixels)---Not used here.

	# Perform read noise correction
	rdnoise_corr = np.sqrt(num_flts * (rdnoise * opxscl/ipxscl)**2)
		
	# Perform background noise calculation
	if backsigma < 0.0:
		backrms=iraf.imstatistics(image+'[0]', fields='stddev', nclip=10, lsigma=3.0, usigma=3.0, cache='yes', format='no',Stdout=1)
		backsigma=float(backrms[0])


	'''Run daofind'''
	# remove old daofind files
	file_query = os.access(outfile, os.R_OK)	
	if file_query == True: os.remove(outfile)
	iraf.daofind.unlearn()
	iraf.daofind(image=image+'[0]', interactive='no', verify='no',output=outfile, fwhmpsf=fwhmpsf, sigma=backsigma, \
	readnoise=rdnoise_corr, itime=exptime, threshold=dthreshold)

	# Display results of daofind (***WORK IN PROGRESS***)
	#!ds9 &
	#iraf.display(file+'['+exten+']',1)
	#iraf.tvmark(1,ofile+'0.coo.1',mark = 'circle', radii = 8, color = 205)

	return outfile		# return name of coordinate file
Пример #8
0
def detect_stars(f,params):
    print 'Detecting stars in',f.name
    print 'Current directory is', os.getcwd()
    fp = params.loc_output+os.path.sep
    fn = f.fullname
    iraf.digiphot()
    iraf.daophot()
    print 'FWHM = ',f.fw
    nstars = 0
    thresh = 100
    while (nstars < 2*params.nstamps) and (thresh > 1.5):
        print 'thresh = ',thresh
        for d in ['temp.stars','temp.phot']:
            if os.path.exists(fp+d):
                os.system('/bin/rm '+fp+d)
        iraf.daofind(image=fn,output=fp+'temp.stars',interactive='no',verify='no',
                     threshold=thresh,sigma=30,fwhmpsf=f.fw,
                     datamin=params.pixel_min,datamax=params.pixel_max,
                     epadu=params.gain,readnoise=params.readnoise,
                     noise='poisson')
        iraf.phot(image=fn,output=fp+'temp.phot',coords=fp+'temp.stars',interactive='no',
                  verify='no',
                  sigma=30,fwhmpsf=f.fw,datamin=params.pixel_min,
                  datamax=params.pixel_max,epadu=params.gain,
                  readnoise=params.readnoise,noise='poisson',Stdout='/dev/null')
        nstars = 0
        if os.path.exists(fp+'temp.phot'):
            iraf.psort(infiles=fp+'temp.phot',field='MAG')   
            iraf.prenumber(infile=fp+'temp.phot')
            s = iraf.pdump(infiles=fp+'temp.phot',Stdout=1,fields='ID,XCENTER,YCENTER,MAG',
                           expr='yes')
            stars = np.zeros([len(s),3])
            i = 0
            for line in s:
                mag = line.split()[3]
                if not(mag == 'INDEF'):
                    stars[i,:] = np.array(map(float,line.split()[1:4]))
                    i += 1
            nstars = i
        thresh = thresh*0.5
    if nstars == 0:
        print 'Error: could not detect stars in',fn
        return None
    stars = stars[:i,:].copy()
    sys.old_stdout = sys.stdout
    return stars
Пример #9
0
 def source_find(self):
     '''
     Uses iraf.daofind to find sources.  datapars and findpars parameters
     are hardcoded here.
     '''
     
     cntlist = glob.glob(self.root + '/*counts.fits')
     
     for image, fwhm, sigma in zip(cntlist, self.fwhmlist, self.sigmalist):
         iraf.datapars.fwhmpsf = fwhm
         iraf.datapars.sigma = sigma
         iraf.datapars.gain = 'ccdgain'
         iraf.datapars.datamax = 60000
         iraf.findpars.threshold = self.threshold
         
         iraf.daofind(image=image, output=image[:-12] + '_sources.dat', \
                      verify='no', verbose='no')
Пример #10
0
def run_daofind(input_image,output_coo,verbosity):

    ### Find bksigma
    data = pyfits.getdata(input_image)
    oned = []
    for i in range(len(data)):
        for j in range(len(data)):
            oned.append(data[i,j])

    niter = 5
    sig = 2.0
    for i in range(niter):
        bksigma = std(oned)
        med = median(oned)
        temp = []
        for n in oned:
            if abs(n-med) < sig*bksigma:
                temp.append(n)
        if len(temp) > 1:
            oned = temp

    bksigma = std(oned)

    os.system("rm "+output_coo)
    iraf.unlearn(iraf.daofind)
    set_datapars(bksigma)
    set_findpars()

    iraf.daofind(
        image = input_image,\
        output = output_coo,\
        starmap = "",\
        skymap = "",\
        boundary = "nearest",\
        constant = 0.0,\
        interactive = 0,\
        icommands = "",\
        gcommands = "",\
        wcsout = "logical",\
        cache = 0,\
        verify = 0,\
        update = 0,\
        verbose = verbosity)
Пример #11
0
def findStars(frame,fwhm,sigma,thresh,extra="",overwrite=True,interactive=True):
	if overwrite:
		if os.path.isfile(frame+".fullcoo"):
			os.system("rm "+frame+".fullcoo")
	iraf.noao()
	iraf.digiphot()
	iraf.daophot()
	iraf.datapars.setParam("fwhmpsf",fwhm)
	iraf.datapars.setParam("sigma",sigma)
	iraf.findpars.setParam("thresh",thresh)
	foo = iraf.daofind(image=frame+extra,output=frame+".fullcoo",Stdin=cr,Stdout=1)
Пример #12
0
def daofind():
	print 'FIND'
	"""Identifies and computes approximate centroids for small luminous objects in the field. Read out noise and gain in photons (or electrons) must be defined, and a significance level (in standard deviations) given, above which an object is considered real.  Find computes the actual brightness enhancment of an object in data numbers above the local sky brightness.
	
	Searches the image for local density maxima, which have a fwhm = datapars.fwhmpsf and a peak amplitude greater than findpars.threshold * datapars.sigma

	Image = input image
	Output = output name. Default is .coo

	ratio = 1   : The ratio of the sigma of the Gaussian convolution kernel along the minor axis direction to the sigma along the major axis direction. 
	Ratio defaults to 1.0 in which case the image is convolved with a circular Gaussian. 

	theta = 0 : The position of the major axis of the elliptical Gaussian. Theta is measured counter-clockwise from the x axis. 

	nsigma = 1.5 The semi-major axis of the Gaussian convolution kernel used to computed the density enhancement and mean density images in Gaussian sigma. 
	This semi- major axis is equal to min (2.0, 0.42466 * nsigma * datapars.fwhmpsf / datapars.scale) pixels.
	"""

	iraf.daofind(image=img_fpath, output=daofind_out, fwhmpsf=fwhm, ratio=1, theta=0, verify='no', verbose='no')
	print 'Created', daofind_out
	print
Пример #13
0
def daofind(filelist):
    iraf.datapars.setParam("exposure", "EXPTIME")
    iraf.datapars.setParam("airmass", "AIRMASS")
    iraf.datapars.setParam("filter", "INSFILTE")
    iraf.datapars.setParam("ccdread", "RDNOISE")
    iraf.datapars.setParam("gain", "GAIN")

    iraf.centerpars.setParam("calgorithm", "centroid")

    iraf.photpars.setParam("apertures", "17.56")

    iraf.fitskypars.setParam("annulus", "20.56")
    iraf.fitskypars.setParam("dannulus", "5")

    with open(filelist) as file1:
        for line in file1:
            filename = line.strip()
            print("Filename %s" % filename)
            y, z = np.loadtxt(filename + "-daoedit",
                              usecols=[3, 4],
                              unpack=True)
            sigma = np.mean(y)
            fwhm = np.mean(z)
            iraf.datapars.setParam("fwhmpsf", "%s" % str(fwhm))
            iraf.datapars.setParam("sigma", "%s" % str(sigma))
            iraf.daofind.setParam("mode", "h")
            iraf.phot.setParam("mode", "h")
            iraf.datapars.setParam("mode", "h")
            iraf.centerpars.setParam("mode", "h")
            iraf.fitskypars.setParam("mode", "h")
            iraf.photpars.setParam("mode", "h")

            iraf.daofind(filename, filename + "-daofind", mode='h')

            iraf.phot(filename,
                      coords=(filename + "-daofind"),
                      output=(filename + ".mag"),
                      mode='h')
Пример #14
0
				iraf.datapars.sigma = sig

				iraf.centerpars.cbox = max(5, 2*fwhm)
				iraf.fitskypars.skyvalu = bg
				iraf.fitskypars.annulus = 4*fwhm
				iraf.fitskypars.dannulus = 3*fwhm
				#iraf.photpars.aperture = max(3, fwhm)
				iraf.photpars.aperture = max(3, 91)		# from 24" diameter from Smith+06
				iraf.photpars.zmag = zmag
				iraf.daopars.fitrad = fwhm              # Fitting radius in scale units. Only pixels within the fitting radius of the center of a star will contribute to
													# the fits computed by the PEAK, NSTAR and ALLSTAR tasks.

				##### Get Coordiates and Magnitudes Stars #################
				# Run DAOFIND to get coordinates and PHOT to get magnitudes
				###########################################################
				iraf.daofind(fn+'['+str(i)+']', '../'+dates[k]+'_phot/'+fn[:-5]+'.coo.'+str(i),verify='no',verbose='no')			# generate coo.1 file
				iraf.phot(fn+'['+str(i)+']', '../'+dates[k]+'_phot/'+fn[:-5]+'.coo.'+str(i),'../'+dates[k]+'_phot/'+fn[:-5]+'.mag.'+str(i),verify='no',verbose='no')	# generate mag.1 file

				##### MAKE PSF STAR LIST FILE 'pst.1' #######
				# read coordinates and magnitudes of the stars selected based
				# on the catalog generated by Source Extractor and make
				# 'pst.1' file to use for running PSF task
				#######################################################
				# coo1 = ascii.read(fn[:-5]+'.coo.'+str(i))
				# mag1 = ascii.read(fn[:-5]+'.mag.'+str(i))
				# coo1.sort('ID')
				# mag1.sort('ID')
				# pst1 = Table(names=('ID','XCENTER','YCENTER','MAG','MSKY'),dtype=('i4','f8','f8','f8','f8'))
				# for j in range(min(len(mag1),len(coo1))):
				# 	ind = np.where((abs(mag1['XCENTER'][j]-coo1['XCENTER']) < tol_star_match) & \
				# 		(abs(mag1['Ycenter'][j]-coo1['YCENTER']) < tol_star_match))[0]
def maskStars(imageName):
    #read in the fits data and header
    imageHeader = fits.open(imageName + ".fits")[0]

    #Read in the skysigma, skyv, and seeing (fwhm) from the header and set up other relevant values
    sigma = imageHeader.header['SKYSIGMA']
    threshold = 3.0 * sigma

    skyv = imageHeader.header['SKY']

    fwhm = imageHeader.header['SEEING']
    aper = 3.0 * fwhm
    annul = 5 * fwhm

    #Read in the galcut file
    galcut = open("galcut.file")
    galcutString = file.read(galcut)
    galcut.close()

    #Parse the galcut file into its variables
    galList = galcutString.split(' ')
    xCenter = float(galList[0])
    yCenter = float(galList[1])
    a = float(galList[2])  #Semimajor Axis
    eccent = float(galList[3])  #Eccentricity
    posAngle = float(galList[4])  #Position angle

    posAngleRad = (posAngle + 90) * 3.14159 / 180
    b = a * eccent  #Semiminor Axis
    na = -1 * a
    nb = -1 * b

    #Create a version of the r image with the sky added back in for the daofind procedure
    iraf.imdelete("withsky")
    iraf.imarith(imageName, '+', skyv, "withsky")

    # Load daophot package
    iraf.digiphot()
    iraf.daophot()

    print("A. Find stars using daofind")

    #DAOFIND  searches  the  IRAF  images image for local density maxima,
    #    with a  full-width  half-maxima  of  datapars.fwhmpsf,  and  a  peak
    #    amplitude  greater  than  findpars.threshold  * datapars.sigma above
    #    the local background, and writes a list of detected objects  in  the
    #    file  output.
    # Here we set the fwhm and sigma equal to those listed in the header.
    # We set the datamin to -3*sigma = -1*threshold defined above
    # The findpars.threshold is set to 4.5*sigma by default. You may have
    # to alter this value for images where too few/many stars are found.

    #Configure 'datapars', 'findpars', and 'daofind'
    iraf.datapars.fwhmpsf = fwhm
    iraf.datapars.sigma = sigma
    iraf.datapars.datamax = 'indef'
    iraf.datapars.datamin = (-1) * threshold
    iraf.datapars.ccdread = 'RDNOISE'
    iraf.datapars.gain = "GAIN"
    iraf.datapars.exposure = "EXPTIME"
    iraf.datapars.airmass = "AIRMASS"
    iraf.datapars.filter = "FILTER"
    iraf.datapars.obstime = "TIME-OBS"

    iraf.findpars.threshold = 4.5
    iraf.findpars.roundhi = 3
    iraf.findpars.roundlo = -3

    iraf.daofind.verify = 'no'
    iraf.daofind.verbose = 'no'

    #create the variable for the coordinate file
    allStars = imageName + '.coo'

    #Remove a previous coordinate file if one exists
    silentDelete(imageName + '.coo')

    #Find the stars in the aligned R image
    iraf.daofind("withsky", allStars)
    print(
        "The file containing the data of the stars in the aligned R-image is ",
        allStars)
    print(" ")

    if os.path.getsize(allStars) > 2239:

        print("B. Separate stars inside and outside galaxy")

        #Delete existing files
        for f in ("temp.file", "maskfile", "maskfile.sat"):
            silentDelete(f)

        #Extract the coordinates from the allStars file, redirecting stdout to do so
        sys.stdout = open("temp.file", "w")
        iraf.pdump(allStars, "xcenter,ycenter", 'yes')
        sys.stdout = sys.__stdout__

        #Read the file to get the xy coordinate pairs in a list
        coords = open("temp.file")
        coordList = list(coords)
        countout = 0

        #Create strings of xy pairs to write to files
        outGalString = ""
        for pair in coordList:
            #for each entry in the list, parse it into xy value integer pairs
            values = pair.split("  ")
            x = float(values[0])
            y = float(values[1])

            #Determine if the star lies within the galaxy-centered ellipse
            inGalaxy = False
            deltaX = x - xCenter
            deltaY = y - yCenter
            cdx = abs(deltaX)
            cdy = abs(deltaY)
            if (cdx < a and cdy < a):
                xt = (deltaX * math.cos(posAngleRad)) + (deltaY *
                                                         math.sin(posAngleRad))
                yt = (deltaY * math.cos(posAngleRad)) - (deltaX *
                                                         math.sin(posAngleRad))
                if (xt <= a and xt >= na and yt <= b and yt >= nb):
                    inGalaxy = True

            if (not inGalaxy):
                outGalString += str(x) + " " + str(y) + "\n"
                countout = countout + 1

    #Write the coordinate list to a file
        mask = open("maskfile", "w")
        mask.write(outGalString)
        mask.close()
        print('')
        print("  ", countout, " stars found outside galaxy")
        print('')
        if countout != 0:

            print("C. Do photometry to find saturated stars")

            for f in ("maskfile.mag", "maskfile.satmag", "maskfile.sat"):
                silentDelete(f)

    #Configure 'centerpars', 'fitskypars','photpars'
            iraf.datapars.datamax = 150000
            iraf.datapars.datamin = 'indef'
            iraf.centerpars.calgorithm = "none"

            iraf.fitskypars.salgorithm = "mode"
            iraf.fitskypars.annulus = annul
            iraf.fitskypars.dannulus = 10

            iraf.photpars.apertures = fwhm
            iraf.phot.verify = 'no'
            iraf.phot.verbose = 'no'

            #Call 'phot' to get the data of the stars
            iraf.phot(imageName, "maskfile", "maskfile.mag")

            boexpr = "PIER==305"
            iraf.pselect("maskfile.mag", "maskfile.satmag", boexpr)

            sys.stdout = open("maskfile.sat", "w")
            iraf.pdump("maskfile.satmag", "xcenter,ycenter", "yes")
            sys.stdout = sys.__stdout__

            print("D. Make mask of stars outside galaxy")

            #Delete the rmask if one exists
            silentDelete("rmask.fits")

            #Configure 'imedit'
            iraf.imedit.cursor = "maskfile"
            iraf.imedit.display = 'no'
            iraf.imedit.autodisplay = 'no'
            iraf.imedit.aperture = "circular"
            iraf.imedit.value = -1000
            iraf.imedit.default = "e"

            #Replace the pixel values near the star coordinates with value -1000 using imedit
            iraf.imedit(imageName, "redit", radius=aper)

            iraf.imcopy.verbose = 'no'
            #Do the same for the saturated stars, but with larger apertures
            satMaskSize = os.path.getsize("maskfile.sat")
            if satMaskSize < 1:
                print("   No saturated stars found")
            if (satMaskSize != 0):
                iraf.imedit.cursor = "maskfile.sat"
                iraf.imedit.radius = 2 * aper
                iraf.imedit("redit", "rmask")
            else:
                iraf.imcopy("redit", "rmask")

    #Replace good pixels with value 0 in 'rmask'
            iraf.imreplace.lower = -999
            iraf.imreplace.upper = 'indef'
            iraf.imreplace("rmask", 0)

            #Replace bad pixels with value 1 in 'rmask'
            iraf.imreplace.lower = 'indef'
            iraf.imreplace.upper = -1000
            iraf.imreplace("rmask", 1)

            #Remove the mask file if one already exists
            silentDelete(imageName + "mask.fits")
            iraf.imcopy("rmask", imageName + "mask")

            print(" ")
            print("The mask image is ", imageName + "mask")
            print("The masked image is ", imageName + "Masked")
            print(" ")

        else:
            print("No stars found outside galaxy, no mask created.")

    if os.path.getsize(allStars) < 2314:
        print("No stars found, no mask created.")

    #Delete intermediate images
    for f in ("rmask.fits", "redit.fits", "maskimage.fits", "maskfile.mag",
              "maskfile.satmag", "temp.file", "withsky.fits", "mask.fits"):
        silentDelete(f)
Пример #16
0
iraf.findpars.setParam('threshold','80')
iraf.centerpars.saveParList(filename='~/iraf/uparm/datcentes.par')
iraf.datapars.saveParList(filename='~/iraf/uparm/datdataps.par')

#Set up daofind to go without prompting for input
iraf.daofind.setParam('image','@all_fits_files.txt')	#Set filename
iraf.daofind.setParam('output','../coo_'+exam_date+'/')
iraf.daofind.setParam('verify','no')			#Don't verify
iraf.daofind.saveParList(filename='daofind.par')	#Save values


for i in range(num_files-1):
	
	#DAOFIND------------------------------------------------------------
	iraf.daofind.setParam('image',raw_filenames[i])
	daostring=iraf.daofind(mode='h',Stdout=1)	#Run DAOFIND hidden
	lendaostring=len(daostring)			#Get Number of Spots
	print lendaostring

	filename=daostring[1].split()[1]		#Get Filename


	for spot in range(3,lendaostring-3):
		cursor.execute("INSERT INTO DAOFIND_"+exam_date+'_'+
			       Month+'_'+Day+
			       " VALUES('"+
			       filename+"','"+      
			       daostring[spot].split()[0]+"','"+
                               daostring[spot].split()[1]+"','"+
                               daostring[spot].split()[2]+"','"+
                               daostring[spot].split()[3]+"','"+
Пример #17
0
    iraf.datapars.fwhmpsf = fwhm
    iraf.datapars.sigma = sig

    iraf.centerpars.cbox = max(5, 2 * fwhm)
    iraf.fitskypars.skyvalu = bg
    iraf.fitskypars.annulus = 4 * fwhm
    iraf.fitskypars.dannulus = 3 * fwhm
    iraf.photpars.aperture = max(3, fwhm)
    iraf.photpars.zmag = zmag
    iraf.daopars.fitrad = fwhm  # Fitting radius in scale units. Only pixels within the fitting radius of the center of a star will contribute to
    # the fits computed by the PEAK, NSTAR and ALLSTAR tasks.

    ##### Get Coordiates and Magnitudes Stars #################
    # Run DAOFIND to get coordinates and PHOT to get magnitudes
    ###########################################################
    iraf.daofind(fn, fn[:-5] + '.coo.1', verify='no',
                 verbose='no')  # generate coo.1 file
    iraf.phot(fn,
              fn[:-5] + '.coo.1',
              fn[:-5] + '.mag.1',
              skyfile='bkg_' + fn,
              verify='no',
              verbose='no')  # generate mag.1 file

    ##### MAKE PSF STAR LIST FILE 'pst.1' #######
    # read coordinates and magnitudes of the stars selected based
    # on the catalog generated by Source Extractor and make
    # 'pst.1' file to use for running PSF task
    #######################################################
    coo1 = ascii.read(fn[:-5] + '.coo.1')
    mag1 = ascii.read(fn[:-5] + '.mag.1')
    coo1.sort('ID')
Пример #18
0
#unless keyword _save=1 was specifiedi

#Two simple ways to get entire parameter list updated in uparm copy
#	1-Run epar and click on "SAVE"
#	2-in script mode saveParList() method for the task

#Four methods for getting and setting params
#	1-getParam()		2-setParam()
#	3-
#
print iraf.daofind.getParam('image',prompt=0)
iraf.daofind.setParam('image','hr5132a_001_raw.fits')
print iraf.daofind.getParam('image')
iraf.daofind.saveParList(filename='daofind.par')
iraf.daofind.getParam('verify',prompt=1)
iraf.daofind(ParList="daofind.par")
#iraf.daofind(mode="h")









#from: http://stsdas.stsci.edu/pyraf/doc.old/pyraf_guide/node2.html
"""
2 Writing Python Scripts that Use IRAF/PyRAF Tasks

Here is a very simple example to show the essential components of a Python script that calls an IRAF task, in this case imstatistics. The file imstat_example.py contains the following:
Пример #19
0
'''
ABOUT: How Python can be used to execute IRAF/PyRAF tasks
DEPENDS: Python 2.7.3
AUTHOR: S N Bright for STScI, 2013
HISTORY: 2013: Test program
USE: python pyraf_example.py
'''

#Load the packages we need
import pyraf, os, glob
from pyraf import iraf
from iraf import noao, digiphot, daophot

#Generate a list of all the fits files
file_list = glob.glob('*_ima.fits')
print file_list

#Loops though all the .fits files
for file in file_list:
    #Test for old files, and remove them if they exist
    file_query = os.access(file + '1.coo.1', os.R_OK)
    if file_query == True:
        os.remove(file + '1.coo.1')
    #Run daofind on one image
    iraf.daofind(
        image = file + '[1]',
        interactive = 'no',
        verify = 'no')

Пример #20
0
def run_daofind(image, outfile='default', dthreshold=3.0, fwhmpsf=2.5, backsigma=None,rdnoise=None):
    '''RUN DAOFIND ON INPUT IMAGE'''

    # -- parse output filename
    if outfile == 'default': outfile = image+'.coo'


    # -- extract header info 
    prihdr = pyfits.getheader(image)
    exptime = prihdr['exptime']
    instrum = prihdr['INSTRUME']
    detector = prihdr['DETECTOR']
    SUBARRAY = prihdr['SUBARRAY']
    ccdamp = prihdr['CCDAMP']


    # -- record filter name, native pixel scale, and no. of chips
    if instrum == 'WFC3':
        if detector == 'UVIS':
            pscale_nat = 0.03962
            if ((SUBARRAY == True) & (len(ccdamp) == 1)): nchips = 1.0
            elif SUBARRAY == False: nchips = 2.0
            else: raise Exception('Image type is not defined.')
        elif detector == 'IR':
            pscale_nat = 0.12825
            nchips = 1.0
        else: raise Exception('Detector '+detector+' not covered in our case list.')
    elif instrum == 'ACS':
        if detector == 'WFC':
            pscale_nat = 0.049
            if ((SUBARRAY == True) & (len(ccdamp) == 1)): nchips = 1.0
            elif SUBARRAY == False: nchips = 2.0
            else: raise Exception('Image type is not defined.')
        else: raise Exception('Detector '+detector+' not covered in our case list.')
    else: raise Exception('Instrument '+instrum+' not covered in our case list.')


    # -- record pixel scale of current image, image type, and number of flts
    sciext = []
    pscale_img = prihdr.get('D001SCAL',default='NA')
    if pscale_img == 'NA':
        imtype = 'flt'            # we dont distinguish between flt/crclean, i.e., assume pscales are equal
        pscale_img = pscale_nat
        num_flts = 1.0
        # -- record location of science extension
        hdulist = pyfits.open(image)
        for ext in xrange(len(hdulist)):
            if hdulist[ext].name == 'SCI': sciext.append(ext)
        hdulist.close()
        if len(sciext) != 1: raise Exception('We do not handle images with '+str(len(sciext))+' SCI extensions.')
    else:
        imtype ='drz'
        num_flts = prihdr['NDRIZIM']/nchips
        sciext.append(0)


    # -- estimate read noise
    if rdnoise == None:
	rdnoise = np.zeros(len(ccdamp))
	for namp in xrange(len(ccdamp)): rdnoise[namp] = prihdr['READNSE'+ccdamp[namp]]
    rdnoise_corr = np.sqrt(num_flts * (np.average(rdnoise) * pixscale_img/pixscale_nat)**2)


    # -- perform rough background noise calculation
    if backsigma == None:
        backstats=iraf.imstatistics(image+'['+str(sciext[0])+']', fields='stddev', lower = -100, upper = 100, nclip=5, \
                                    lsigma=3.0, usigma=3.0, cache='yes', format='no',Stdout=1)
        backsigma=float(backstats[0])


    # -- remove old daofind files/run daofind
    file_query = os.access(outfile, os.R_OK)	
    if file_query == True: os.remove(outfile)
    iraf.daofind.unlearn()
    iraf.daofind(image=image+'['+str(sciext[0])+']', interactive='no', verify='no',output=outfile, fwhmpsf=fwhmpsf, \
                 sigma=backsigma, readnoise=rdnoise_corr, itime=exptime, threshold=dthreshold, datamin=-10, datamax=100000)


    return outfile
Пример #21
0
def alignImages(imageName,imageName_Ha):
  #Read the fwhm and seeing from the image file
  imageHeader = fits.open(imageName+".fits")[0]
  fwhm = imageHeader.header['SEEING']
  annul = 5.0 * fwhm
  aper=3.0 * fwhm
  sigma = imageHeader.header['SKYSIGMA']
  iraf.daophot(_doprint=0)
  #Do 'daofind' on the image to locate the stars
  print("1. Find stars using 'daofind'")
  
  #Configure 'datapars', 'findpars', and 'daofind'
  
  iraf.datapars.fwhmpsf=fwhm
  iraf.datapars.sigma=sigma
  iraf.datapars.datamin=-10
  iraf.datapars.ccdread="RDNOISE"
  iraf.datapars.gain="GAIN"
  iraf.datapars.exposure="EXPTIME"
  iraf.datapars.airmass="AIRMASS"
  iraf.datapars.filter="FILTER"
  iraf.datapars.obstime="TIME-OBS"

  iraf.findpars.threshold=20*sigma
  iraf.findpars.sharplo=0.2
  iraf.findpars.sharphi=1.0
  iraf.findpars.roundlo=-1.0
  iraf.findpars.roundhi=1.0
  iraf.daofind.verify='no'
  iraf.daofind.verbose='no'

  #Delete exisiting coordinate,output files of 'phot',file containg data of 'good' stars, old images
  for f in("coord","mag","psel","R_final.fits","Ha_final.fits"):
    silentDelete(f)

  iraf.daofind(imageName,'coord')

  print("File containing the coordinates of the stars is coord")


  print(" ")
  #Configure 'centerpars', 'fitskypars','photpars'
  iraf.datapars.datamax=150000
  iraf.centerpars.calgorithm="centroid"
  iraf.centerpars.cbox=16
  iraf.centerpars.maxshift=3

  iraf.fitskypars.salgorithm="mode"
  iraf.fitskypars.annulus=annul
  iraf.fitskypars.dannulus=10

  iraf.photpars.apertures=aper

  iraf.phot.verify='no'
  iraf.phot.verbose='no'

  print("2. Obtain data of stars using 'phot'")
  #Call 'phot' to get the data of the stars 
  iraf.phot (imageName,'coord','mag')

  #sort in order of increasing magnitude of stars
  iraf.psort('mag',"mag")
  boundsig=sigma+2
  boexpr="CIER==0 && PIER==0 && STDEV <="+str(boundsig)  
  print("File containing the data of the stars in order of decreasing brightness is mag")

  print (" ")

  print("3. Select stars with low error, no bad pixels")
  #Select stars that have no centering error, skyerror <sig+2 and no bad pixels
  iraf.pselect ("mag" ,"psel" ,boexpr)

  print("File containing stars with low sky error,low centering error is psel")
  print(" ")

  #Renumber the ID number of the stars in order of increasing magnitude
  iraf.prenumber ("psel")


  #Delete existing files
  for f in ("pdump.file","stars25",'alR.fits','rIn.fits','haIn.fits'):
    silentDelete(f)

  print("4. Select the 25 brightest stars")
  iraf.pselect ("psel","stars25", "ID <=25")

  print("File containing the brightest 25 'good' stars is stars25")
  print(" ")

  #Pick out only the required data of stars from the .25 file
  sys.stdout=open("pdump.file","w")
  iraf.pdump ("stars25","xcenter,ycenter,flux","yes")
  sys.stdout = sys.__stdout__
  
  print("The coordinates and flux are stored in pdump.file")
  
  #Align images
  iraf.imcopy(imageName,'rIn')
  iraf.imcopy(imageName_Ha,'haIn')
  print("Aligning images")
  #iraf.imalign.verbose='no'
  iraf.imalign("rIn,haIn", "rIn","pdump.file","R_final,Ha_final")
Пример #22
0
def unisf(image,
          fwhm,
          sigma,
          thold,
          zmin='INDEF',
          zmax='INDEF',
          path=None,
          outfile=None):
    '''
     Dada una lista de imágenes, identifica las estrellas de campo y
     genera un archivo de coordenadas.

      INPUT
      image     : Archivo .in con los nombres de las imágenes, o la imagen 
                  simple.
      fwmh      : Ancho a mitad de intensidad máxima de las estrellas.
      sigma     : Desviación estándar del cielo.
      thold     : Amplitud mínima por encima del valor de fondo.
      (zmin)    : Valor mínimo de cuentas a considerar.
      (zmax)    : Valor máximo de cuentas a considerar.
      (path)    : String que indica el camino a la imagen.
      (outfile) : Nombre del archivo de salida. Por defecto usa el nombre de
                  la imagen y agrega un .coo .
                  
                   ---------------------------------------      

      Given a images list, identifies field stars and generates a coordinates
      file.
    
      INPUT
      image     : .in file with the name of each image, or a single image. 
      fwmh      : Full width half maximum of intensity of stars.
      sigma     : Standard deviation of the sky.
      thold     : Minimum amplitude above background level.
      (zmin)    : Minimum counts value to consider.
      (zmax)    : Maximum counts value to consider.
      (path)    : String that indicates the path do the images.
      (outfile) : Name of the output file, including .coo. By default, uses 
                  image name and adds .coo extension.
    '''
    if path is not None:
        originalpath = aux.chdir(path, save=True)

    iraf.noao()  #loads noao
    iraf.digiphot()  #loads digiphot
    iraf.apphot()  #loads apphot

    iraf.unlearn(iraf.daofind)
    iraf.unlearn(iraf.datapars)
    iraf.unlearn(iraf.findpars)  #unlearns every task required

    iraf.datapars.fwhmpsf = fwhm
    iraf.datapars.sigma = sigma
    iraf.datapars.datamin = zmin
    iraf.datapars.datamax = zmax  #sets meaningful parameters

    iraf.findpars.thresho = thold  #sets meaningful threshold

    iraf.daofind.verify = "no"  #avoid checking parameters given

    aux.default(outfile, image + '.coo', borrar=True)

    iraf.daofind.output = outfile
    iraf.daofind.image = image
    iraf.daofind()
    #execute iraf task 'daofind'
    if path is not None:
        aux.chdir(originalpath)
Пример #23
0
        iraf.daofind.setParam('fwhmpsf', FWHM)       
        iraf.daofind.setParam('output', outfile)
        iraf.daofind.setParam('sigma', float(hdr["SKY_STD"]))
        iraf.daofind.setParam('gain', gaink)
        iraf.daofind.setParam('readnoise', float(hdr[read_noisek]))
        iraf.daofind.setParam('roundlo', -0.3)  # Minimal roundness  (0 is round)
        iraf.daofind.setParam('roundhi', 0.3 )
        iraf.daofind.setParam('airmass', "airmass")
        iraf.daofind.setParam('filter', filterk)
        iraf.daofind.setParam('exposure', exptimek)
        iraf.daofind.setParam('obstime', "date-obs")
        iraf.daofind.setParam('verify', "no")
        iraf.daofind.setParam('datamin', 500)
        iraf.daofind.setParam('datamax', 50000)
        iraf.daofind.saveParList(filename='daofind.par')
        iraf.daofind(ParList='daofind.par')

print "Reading catalogs, calculating shifts"
# List of objects to be aligned. There might be several cigs, several clusters
# and several standard fields.
types_need_aligning = ["cig", "standards","clusters"]
objects_need_aligning = ()
for current_type in types_need_aligning:
    whr = np.where(list_images["type"] == current_type)
    objects_need_aligning = objects_need_aligning +\
                                      tuple(set(list_images["objname"][whr]))
# For each object, read x, y, mag from the sextractor catalog, 
# select the top 15 brightest stars and find the translation between images
for current_object in objects_need_aligning:    
    print "Current object", current_object
    # Open files to store data that imalign will need later on
Пример #24
0
def get_photometry(filelist, fwhmpsf, thresh, mkiraf=True):
    """
    Performs sextracting by daofind and photometry by daophot 
    filename is WITHOUT suffix .fits
    fwhmpsf is rough estimation of typical frame FWHM
    THRESH is signal-to-noise ratio, typically 4 or so
    Outputs are two files *.coo.1 and *.mag.1 with x-y coordinates
    """

    # Create login.cl at execution of the script if flag set to true
    if mkiraf:
        proc = subprocess.Popen(['mkiraf'],
                                stdin=subprocess.PIPE,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.STDOUT)
        outs, errs = proc.communicate('y\nxterm')

    # Now we make the Pyraf imports
    from pyraf import iraf
    from pyraf.iraf import daophot

    # Parameter to get rid of the faint stars with high magnitude error
    magnitude_error_threshold = 0.5

    iraf.noao
    iraf.digiphot
    iraf.daophot

    iraf.unlearn('phot')
    iraf.unlearn('datapars')
    iraf.unlearn('photpars')
    iraf.unlearn('daopars')

    iraf.datapars.epadu = 1
    iraf.datapars.readnoi = 6
    iraf.datapars.datamin = "INDEF"
    iraf.datapars.datamax = "50000"

    # fwhm tarot 1.5   oaj 3.5
    iraf.datapars.fwhm = fwhmpsf

    for filename in filelist:

        IMstatres = iraf.imstat(filename, Stdout=1)
        IMmean = IMstatres[1].split()[2]
        iraf.datapars.sigma = math.sqrt(
            float(IMmean) * float(iraf.datapars.epadu) +
            float(iraf.datapars.readnoi)**2) / float(iraf.datapars.epadu)

        print("--- performing daophot sextracting ---")
        iraf.daofind(filename,
                     output="default",
                     verify="no",
                     verbose="no",
                     threshold=thresh)
        iraf.datapars.datamax = "INDEF"
        print("--- performing daophot photometry ---")
        iraf.daophot.phot(image=filename,
                          coords="default",
                          output="default",
                          interactive="no",
                          sigma="INDEF",
                          airmass="AIRMASS",
                          exposure="EXPOSURE",
                          filter="FILTER",
                          obstime="JD",
                          calgorithm="gauss",
                          verify="no",
                          verbose="no")
Пример #25
0
def alignImages(imageName, imageName_Ha):
    #Read the fwhm and seeing from the image file
    imageHeader = fits.open(imageName + ".fits")[0]
    fwhm = imageHeader.header['SEEING']
    annul = 5.0 * fwhm
    aper = 3.0 * fwhm
    sigma = imageHeader.header['SKYSIGMA']
    iraf.daophot(_doprint=0)
    #Do 'daofind' on the image to locate the stars
    print("1. Find stars using 'daofind'")

    #Configure 'datapars', 'findpars', and 'daofind'

    iraf.datapars.fwhmpsf = fwhm
    iraf.datapars.sigma = sigma
    iraf.datapars.datamin = -10
    iraf.datapars.ccdread = "RDNOISE"
    iraf.datapars.gain = "GAIN"
    iraf.datapars.exposure = "EXPTIME"
    iraf.datapars.airmass = "AIRMASS"
    iraf.datapars.filter = "FILTER"
    iraf.datapars.obstime = "TIME-OBS"

    iraf.findpars.threshold = 20 * sigma
    iraf.findpars.sharplo = 0.2
    iraf.findpars.sharphi = 1.0
    iraf.findpars.roundlo = -1.0
    iraf.findpars.roundhi = 1.0
    iraf.daofind.verify = 'no'
    iraf.daofind.verbose = 'no'

    #Delete exisiting coordinate,output files of 'phot',file containg data of 'good' stars, old images
    for f in ("coord", "mag", "psel", "R_final.fits", "Ha_final.fits"):
        silentDelete(f)

    iraf.daofind(imageName, 'coord')

    print("File containing the coordinates of the stars is coord")

    print(" ")
    #Configure 'centerpars', 'fitskypars','photpars'
    iraf.datapars.datamax = 150000
    iraf.centerpars.calgorithm = "centroid"
    iraf.centerpars.cbox = 16
    iraf.centerpars.maxshift = 3

    iraf.fitskypars.salgorithm = "mode"
    iraf.fitskypars.annulus = annul
    iraf.fitskypars.dannulus = 10

    iraf.photpars.apertures = aper

    iraf.phot.verify = 'no'
    iraf.phot.verbose = 'no'

    print("2. Obtain data of stars using 'phot'")
    #Call 'phot' to get the data of the stars
    iraf.phot(imageName, 'coord', 'mag')

    #sort in order of increasing magnitude of stars
    iraf.psort('mag', "mag")
    boundsig = sigma + 2
    boexpr = "CIER==0 && PIER==0 && STDEV <=" + str(boundsig)
    print(
        "File containing the data of the stars in order of decreasing brightness is mag"
    )

    print(" ")

    print("3. Select stars with low error, no bad pixels")
    #Select stars that have no centering error, skyerror <sig+2 and no bad pixels
    iraf.pselect("mag", "psel", boexpr)

    print(
        "File containing stars with low sky error,low centering error is psel")
    print(" ")

    #Renumber the ID number of the stars in order of increasing magnitude
    iraf.prenumber("psel")

    #Delete existing files
    for f in ("pdump.file", "stars25", 'alR.fits', 'rIn.fits', 'haIn.fits'):
        silentDelete(f)

    print("4. Select the 25 brightest stars")
    iraf.pselect("psel", "stars25", "ID <=25")

    print("File containing the brightest 25 'good' stars is stars25")
    print(" ")

    #Pick out only the required data of stars from the .25 file
    sys.stdout = open("pdump.file", "w")
    iraf.pdump("stars25", "xcenter,ycenter,flux", "yes")
    sys.stdout = sys.__stdout__

    print("The coordinates and flux are stored in pdump.file")

    #Align images
    iraf.imcopy(imageName, 'rIn')
    iraf.imcopy(imageName_Ha, 'haIn')
    print("Aligning images")
    #iraf.imalign.verbose='no'
    iraf.imalign("rIn,haIn", "rIn", "pdump.file", "R_final,Ha_final")
Пример #26
0
bg_g = np.mean(bgsig_g)
bg_i = np.mean(bgsig_i)
bgm_g = np.mean(bgmean_g)
bgm_i = np.mean(bgmean_i)
print 'Image mean BG sigma value :: g = {0:5.3f} : i = {1:5.3f}'.format(bg_g,bg_i)
print 'Image mean BG median value :: g = {0:5.3f} : i = {1:5.3f}'.format(bgm_g,bgm_i)

# daofind steps
# find all the sources in the image (threshold value will be data dependent, 4.0 is good for UCHVCs)
# g image
if not os.path.isfile(fits_g+'.coo.1') :
    iraf.datapars.setParam('fwhmpsf',fwhm_g,check=1)
    iraf.datapars.setParam('sigma',bg_g,check=1)
    
    iraf.findpars.setParam('threshold',4.0)
    iraf.daofind(image=fits_g, verbose="no")
    
    # i image
if not os.path.isfile(fits_i+'.coo.1') :
    iraf.datapars.setParam('fwhmpsf',fwhm_i,check=1)
    iraf.datapars.setParam('sigma',bg_i,check=1)
    
    iraf.findpars.setParam('threshold',4.0)
    iraf.daofind(image=fits_i, verbose="no")


# now phot the stars found in daofind
if not os.path.isfile(fits_g+'.mag.1') :
    print 'phot-ing g band daofind stars. This is going to take a while...'
    iraf.unlearn(iraf.apphot.phot,iraf.datapars,iraf.photpars,iraf.centerpars,iraf.fitskypars)
    iraf.apphot.phot.setParam('interactive',"no")
Пример #27
0
images = f.readlines()
f.close()
indx = images[0][::-1].index('/') # find where the image name starts 
image0 = images[0][-indx:-1]

# Loading parameter file and the FWHM
iraf.unlearn('daophot')
iraf.setimpars('int','yes','no') 
FWHM = raw_input('What is the stellar FWHM in pixels?\n')
skysigma = raw_input('What is the sky sigma in the first image?\n')
iraf.datapars.scale = 1/float(FWHM)
iraf.datapars.sigma = float(skysigma)

# Finding calibration stars
os.system('rm *.coo.*')
iraf.daofind('../SCIENCE/' + image0,'default',verify='no',verbose='no')
os.system('rm *.mag.*')
iraf.phot('../SCIENCE/' + image0,'default','default',verify='no',verbose='no')
try:
	os.remove('calibcoords')
except: True
iraf.txdump(image0 + '.mag.1','xcenter,ycenter',\
"cerror='NoError' && perror='NoError' && serror='NoError' && merr<0.005 && mag>0",Stdout = 'calibcoords')

coordarray = []
f = open('calibcoords')
calibcoords = f.readlines()
f.close()
for i in calibcoords:
	coordarray.append(i)
Пример #28
0
def run_daofind(image,
                outfile='default',
                dthreshold=3.0,
                fwhmpsf=2.5,
                backsigma=None,
                rdnoise=None):
    '''RUN DAOFIND ON INPUT IMAGE'''

    # -- parse output filename
    if outfile == 'default': outfile = image + '.coo'

    # -- extract header info
    prihdr = pyfits.getheader(image)
    exptime = prihdr['exptime']
    instrum = prihdr['INSTRUME']
    detector = prihdr['DETECTOR']
    SUBARRAY = prihdr['SUBARRAY']
    ccdamp = prihdr['CCDAMP']

    # -- record filter name, native pixel scale, and no. of chips
    if instrum == 'WFC3':
        if detector == 'UVIS':
            pscale_nat = 0.03962
            if ((SUBARRAY == True) & (len(ccdamp) == 1)): nchips = 1.0
            elif SUBARRAY == False: nchips = 2.0
            else: raise Exception('Image type is not defined.')
        elif detector == 'IR':
            pscale_nat = 0.12825
            nchips = 1.0
        else:
            raise Exception('Detector ' + detector +
                            ' not covered in our case list.')
    elif instrum == 'ACS':
        if detector == 'WFC':
            pscale_nat = 0.049
            if ((SUBARRAY == True) & (len(ccdamp) == 1)): nchips = 1.0
            elif SUBARRAY == False: nchips = 2.0
            else: raise Exception('Image type is not defined.')
        else:
            raise Exception('Detector ' + detector +
                            ' not covered in our case list.')
    else:
        raise Exception('Instrument ' + instrum +
                        ' not covered in our case list.')

    # -- record pixel scale of current image, image type, and number of flts
    sciext = []
    pscale_img = prihdr.get('D001SCAL', default='NA')
    if pscale_img == 'NA':
        imtype = 'flt'  # we dont distinguish between flt/crclean, i.e., assume pscales are equal
        pscale_img = pscale_nat
        num_flts = 1.0
        # -- record location of science extension
        hdulist = pyfits.open(image)
        for ext in xrange(len(hdulist)):
            if hdulist[ext].name == 'SCI': sciext.append(ext)
        hdulist.close()
        if len(sciext) != 1:
            raise Exception('We do not handle images with ' +
                            str(len(sciext)) + ' SCI extensions.')
    else:
        imtype = 'drz'
        num_flts = prihdr['NDRIZIM'] / nchips
        sciext.append(0)

    # -- estimate read noise
    if rdnoise == None:
        rdnoise = np.zeros(len(ccdamp))
        for namp in xrange(len(ccdamp)):
            rdnoise[namp] = prihdr['READNSE' + ccdamp[namp]]
    rdnoise_corr = np.sqrt(
        num_flts * (np.average(rdnoise) * pixscale_img / pixscale_nat)**2)

    # -- perform rough background noise calculation
    if backsigma == None:
        backstats=iraf.imstatistics(image+'['+str(sciext[0])+']', fields='stddev', lower = -100, upper = 100, nclip=5, \
                                    lsigma=3.0, usigma=3.0, cache='yes', format='no',Stdout=1)
        backsigma = float(backstats[0])

    # -- remove old daofind files/run daofind
    file_query = os.access(outfile, os.R_OK)
    if file_query == True: os.remove(outfile)
    iraf.daofind.unlearn()
    iraf.daofind(image=image+'['+str(sciext[0])+']', interactive='no', verify='no',output=outfile, fwhmpsf=fwhmpsf, \
                 sigma=backsigma, readnoise=rdnoise_corr, itime=exptime, threshold=dthreshold, datamin=-10, datamax=100000)

    return outfile
Пример #29
0
'''
ABOUT:
This script will be used to demonstrate how IRAF/PyRAF tasks can
be executed in Python.

'''

#load needed packages
import pyraf, os, glob
from pyraf import iraf
from iraf import noao, digiphot, daophot

#generate list of all fits files in current directory
file_list = glob.glob('*_ima.fits')
print file_list

#loops through all FITS files
for file in file_list:
    #look for old files, and remove if they exist
    file_query = os.access(file + '1.coo.1', os.R_OK)
    if file_query == True:
        os.remove(file + '1.coo.1')

    #execute daofind on one image
    iraf.daofind.unlearn()
    iraf.daofind(
        image = file + '[1]',
        output = 'star_catalogue',
        interactive = 'no',
        verify = 'no')
Пример #30
0
	def findStars(self):

		# To look for the stars that exist in the image specified.
		# It will:
		#	Utilise the IRAF package daofind
		#	be used for this image subtraction package
		#	Gives ouput of co-ords, "#imagename_daofind.coo"
		output = self._Name.replace(".fits", "_daofind.coo")
		try:
			self.cleanOutputFiles(output)
		except:
			print "Error cleaning output files"
			print sys.exc_info()[0]

		# Load as in IRAF and neglect output:
		# NOAO
		# DIGIPHOT
		# APPHOT
		# DAOFIND
		iraf.noao(_doprint=0)
		iraf.digiphot(_doprint=0)
		iraf.apphot(_doprint=0)

		# Set the parameter list
		# image: input image
		# output: output co-ordinates
		# verify: don't know
		# threshold: sigma above which stars are determined (fixed in this script)
		# datapar: point to a file with the user input
		#
		#	ccdread: CCD readout noise (image header keyword)
		#	gain: CCD gain (image header keyword)
		#	readnoi: CCD readout noise in e
		#	epadu: gain in e- per count
		#
		# findpar: point to a file with the user input
		#
		#	threshold: in units of sigma
		#
		# centerpars:
		#
		# Save the parameter list

		# Pull information from the header of the FITS image
		#self.loadHeader()
		#datapars = iraf.datapars.getParList()
		#findpars = iraf.findpars.getParList()
		#ceneterpars = iraf.centerpars.getParList()
		#for par in datapars:
		#print par
		## Print to user
		#print "Information on images:"
		#print "Gain: %s" % self.getHeader('RON')
		#print "RON: %s" % self.getHeader('RON')
	
		# datapar:
		iraf.datapars.setParam('ccdread', 'RON')
		iraf.datapars.setParam('gain', 'GAIN')
		iraf.datapars.setParam('exposur','EXPTIME')
		iraf.datapars.setParam('airmass','AIRMASS')
		iraf.datapars.setParam('filter','SUBSET')
		iraf.datapars.setParam('obstime','HIERARCH ESO OBS START')
		iraf.datapars.setParam('datamin', '-100')
		iraf.datapars.setParam('datamax', '60000')
#		iraf.datapars.saveParList(filename="%s/uparm/datapars.par" % os.getcwd())

		# findpar:
		#threshold = 4.0
		#iraf.findpars.setParam('threshold', str(threshold))
		#iraf.findpars.saveParList(filename="uparm/findpars.par")

		#print glob.glob(output)
			

		# daofind:
		iraf.daofind(image=self._Name,
				output=output,
				verify=0,
				verbose=1,
				sigma=self._skySTDEV,
				nsigma=1,
				scale=1,
				fwhmpsf=self._MEDFWHM,
				sharplo='0.0',
				sharphi='1.0',
				roundlo='-0.9',
				roundhi='0.9',
				thresho='6.0',
				wcsout="logical",
				Stdout=1,
				mode='h'
			)


		# 1. Open the .coo file
		# 2. Pasre the input

		# 1. take input file
		filename = "%s" % (self._Name.replace(".fits", "_daofind.coo"))
		coords = open(filename)
		coord = coords.readlines()
		coords.close()

		# 2. parse out the lines beginning with "#"
		filename = "%s" % (self._Name.replace(".fits", "_daofind.reg"))
		coordregfile = open(filename, "w")
		coobject = []
		for co in coord:
			if co[0] != "#":

		# 2b. parse each element
			
				newCoordObject = imObject()
				coitem = [i for i in co.replace("\n","").split(" ") if i!= ""]
				newCoordObject._id = self.giveObjectID()
				newCoordObject._pixelx = float(coitem[0])
				newCoordObject._pixely = float(coitem[1])
				newCoordObject._mag = float(coitem[2])
				#newCoordObject.printInfo()

				coordregfile.write("image; circle(%f,%f,4) # color = red\n" % (newCoordObject._pixelx, newCoordObject._pixely))

				coobject.append(newCoordObject)

		coordregfile.close()
		self._ObjectList = coobject
Пример #31
0
for i in range(N_loops):
    #for i in range(2):
    initimg = flnm + '.sub.0.fits'
    runnm = flnm + '.sub.' + str(i)
    print "\n>>> Working on", runnm + '.fits', "<<<\n"

    print "========================================="
    print "...running daofind for", runnm + ".fits"
    print "========================================="
    tds = time.time()
    if os.path.exists(runnm + '.coo'):
        print "   File found! skipping this step"
        pass
    else:
        iraf.daofind(image=runnm + '.fits', output=runnm + '.coo', verify='no')
    tde = time.time()
    times[runnm + '_daofind'] = tde - tds

    print "========================================="
    print "...running phot for", runnm + ".coo"
    print "========================================="
    tps = time.time()
    if os.path.exists(runnm + '.mag'):
        print "   File found! skipping this step"
        pass
    else:
        iraf.phot(image=runnm + '.fits',
                  coords=runnm + '.coo',
                  output=runnm + '.mag',
                  verify='no')  # on subtracted image
Пример #32
0
def compute_psf_image(params,g,psf_deg=1,psf_rad=8,
                      star_file='phot.mags',psf_image='psf.fits',edge_dist=5):
    iraf.digiphot()
    iraf.daophot()
    fp = params.loc_output+os.path.sep

    f_im = g.image*g.mask
    f = fp+'temp.ref.fits'
    write_image(f_im,f)

    g.fw = np.max([1.5,g.fw])
    g.fw = np.min([0.5*params.psf_max_radius,g.fw])

    logfile = fp+'psf.log'

    fd = fits.getdata(f)
    xmax = fd.shape[0] - edge_dist
    ymax = fd.shape[1] - edge_dist
    

    for d in ['temp.stars','temp.phot','temp.phot1','temp.phot2','temp.pst',
              'temp.opst','temp.opst2',
              'temp.psf.fits','temp.psf1.fits','temp.psf2.fits','temp.psg',
              'temp.psg2','temp.psg3','temp.psg5','temp.rej','temp.rej2',
              'temp.sub.fits','temp.sub1.fits',
              'temp.sub2.fits','temp.opst1','temp.opst3','temp.rej3',
              'temp.nst','temp.stars1','ref.mags',psf_image,'temp.als',
              'temp.als2']:
            if os.path.exists(fp+d):
                os.remove(fp+d)


    # locate stars
    iraf.daofind(image=f,output=fp+'temp.stars',interactive='no',verify='no',
                 threshold=3,sigma=params.star_detect_sigma,fwhmpsf=g.fw,
                 datamin=1,datamax=params.pixel_max,
                 epadu=params.gain,readnoise=params.readnoise,
                 noise='poisson')

    if params.star_file:
        als_recenter = 'no'
        all_template_stars = np.genfromtxt(params.star_file)
        all_new_stars = np.genfromtxt(fp+'temp.stars')
        
        if all_new_stars.shape[0] > params.star_file_number_match:
            new_stars = all_new_stars[all_new_stars[:,2].argsort()][:params.star_file_number_match]
        else:
            new_stars = all_new_stars

        if all_template_stars.shape[0] > params.star_file_number_match:
            template_stars = all_template_stars[all_template_stars[:,3].argsort()][:params.star_file_number_match]
        else:
            template_stars = all_template_stars

        tx, ty = compute_xy_shift(new_stars,template_stars[:,1:3],0.5,
                                  degree=params.star_file_transform_degree)

        if params.star_file_has_magnitudes:
            star_positions = all_template_stars[:,1:4]
            xx = (star_positions[:,0]-np.mean(new_stars[:,0]))/np.mean(new_stars[:,0])
            yy = (star_positions[:,1]-np.mean(new_stars[:,1]))/np.mean(new_stars[:,1])
            for m in range(params.star_file_transform_degree+1):
                for n in range(params.star_file_transform_degree+1-m):
                    star_positions[:,0] += tx[m,n]* xx**m * yy**n
                    star_positions[:,1] += ty[m,n]* xx**m * yy**n
            np.savetxt(fp+'temp.stars.1',star_positions,fmt='%10.3f %10.3f %10.3f')
        else:
            star_positions = all_template_stars[:,1:3]
            xx = (star_positions[:,0]-np.mean(new_stars[:,0]))/np.mean(new_stars[:,0])
            yy = (star_positions[:,1]-np.mean(new_stars[:,1]))/np.mean(new_stars[:,1])
            for m in range(params.star_file_transform_degree+1):
                for n in range(params.star_file_transform_degree+1-m):
                    star_positions[:,0] += tx[m,n]* xx**m * yy**n
                    star_positions[:,1] += ty[m,n]* xx**m * yy**n
            np.savetxt(fp+'temp.stars.1',star_positions,fmt='%10.3f %10.3f')
        all_template_stars[:,1] = star_positions[:,0]
        all_template_stars[:,2] = star_positions[:,1]
            
    else:
        
        als_recenter = 'yes'
        star_positions = np.genfromtxt(fp+'temp.stars')
        np.savetxt(fp+'temp.stars.1',star_positions[:,:2],fmt='%10.3f %10.3f')

    iraf.phot(image=f,output=fp+'temp.phot',coords=fp+'temp.stars.1',interactive='no',
              verify='no',
              sigma=params.star_detect_sigma,fwhmpsf=g.fw,apertures=g.fw,
              datamin=1,
              datamax=2*params.pixel_max,epadu=params.gain,annulus=3*g.fw,
              dannulus=3.0,
              readnoise=params.readnoise,noise='poisson')

    print 'fw = ',g.fw
    #fw = np.max([4.0,fw])
    #print 'fw = ',fw


    # select PSF stars
    iraf.pstselect(image=f,photfile=fp+'temp.phot',pstfile=fp+'temp.pst',maxnpsf=40,
                   interactive='no',verify='no',datamin=1,fitrad=2.0,
                   datamax=params.pixel_max,epadu=params.gain,psfrad=np.max([3.0,g.fw]),
                   readnoise=params.readnoise,noise='poisson')

    if params.star_file and params.star_file_has_magnitudes:

        # We don't need to do the photometry - only make the PSF

        # Initial PSF estimate to generate PSF groups
        #psfrad=3*np.max([g.fw,1.8])
        iraf.psf(image=f,photfile=fp+'temp.phot',pstfile=fp+'temp.pst',psfimage=fp+'temp.psf',
                 function=params.psf_profile_type,opstfile=fp+'temp.opst',
                 groupfile=fp+'temp.psg',
                 interactive='no',
                 verify='no',varorder=0 ,psfrad=2*np.max([g.fw,1.8]),
                 datamin=-10000,datamax=0.95*params.pixel_max,
                 scale=1.0)

        # construct a file of the psf neighbour stars
        slist = []
        psf_stars = np.loadtxt(fp+'temp.opst',usecols=(0,1,2))

        for star in range(psf_stars.shape[0]):

            xp = psf_stars[star,1]
            yp = psf_stars[star,2]
            xmin = np.max([np.int(xp-10*g.fw),0])
            xmax = np.min([np.int(xp+10*g.fw),f_im.shape[0]])
            ymin = np.max([np.int(yp-10*g.fw),0])
            ymax = np.min([np.int(yp+10*g.fw),f_im.shape[1]])

            p = star_positions[np.logical_and(np.logical_and(star_positions[:,0]>xmin,
                                                             star_positions[:,0]<xmax),
                                              np.logical_and(star_positions[:,1]>ymin,
                                                             star_positions[:,1]<ymax))]
            slist.append(p)

        group_stars = np.concatenate(slist)
        np.savetxt(fp+'temp.nst',group_stars,fmt='%10.3f %10.3f %10.3f')
        
        
        # subtract PSF star neighbours
        iraf.substar(image=f,photfile=fp+'temp.nst',psfimage=fp+'temp.psf',
                     exfile=fp+'temp.opst',fitrad=2.0,
                     subimage=fp+'temp.sub1',verify='no',datamin=1,
                     datamax=params.pixel_max,epadu=params.gain,
                     readnoise=params.readnoise,noise='poisson')
        
        # final PSF
        iraf.psf(image=fp+'temp.sub1',photfile=fp+'temp.phot',pstfile=fp+'temp.opst',
                 psfimage=psf_image,psfrad=2*g.fw,
                 function=params.psf_profile_type,opstfile=fp+'temp.opst2',
                 groupfile=fp+'temp.psg2',
                 interactive='no',
                 verify='no',varorder=0,
                 datamin=1,datamax=0.95*params.pixel_max,
                 scale=1.0)

        np.savetxt(fp+'ref.mags',all_template_stars,fmt='%7d %10.3f %10.3f %10.3f')
        stars = all_template_stars

    else:




        # initial PSF estimate
        iraf.psf(image=f,photfile=fp+'temp.phot',pstfile=fp+'temp.pst',psfimage=fp+'temp.psf',
                 function=params.psf_profile_type,opstfile=fp+'temp.opst',
                 groupfile=fp+'temp.psg1',
                 interactive='no',
                 verify='no',varorder=0 ,psfrad=2*g.fw,
                 datamin=1,datamax=0.95*params.pixel_max,
                 scale=1.0)


        # separation distance of near neighbours
        separation = np.max([rewrite_psg(fp+'temp.psg1',fp+'temp.psg2'),3])
        print 'separation = ',separation

        # subtract all stars using truncated PSF
        iraf.allstar(image=f,photfile=fp+'temp.phot',psfimage=fp+'temp.psf',
                     allstarfile=fp+'temp.als',rejfile='',
                     subimage=fp+'temp.sub',verify='no',psfrad=2*g.fw,fitrad=2.0,
                     recenter='yes',groupsky='yes',fitsky='yes',sannulus=7,wsannulus=10,
                     datamin=1,datamax=params.pixel_max,
                     epadu=params.gain,readnoise=params.readnoise,
                     noise='poisson')

        if params.star_file:

            os.system('cp '+fp+'temp.phot '+fp+'temp.phot2') 

        else:
        
            # locate new stars
            iraf.daofind(image=fp+'temp.sub',output=fp+'temp.stars1',interactive='no',verify='no',
                         threshold=3,sigma=params.star_detect_sigma,fwhmpsf=2*g.fw,
                         datamin=1,datamax=params.pixel_max,
                         epadu=params.gain,readnoise=params.readnoise,
                         noise='poisson')


            # magnitudes for new stars
            iraf.phot(image=fp+'temp.sub',output=fp+'temp.phot1',coords=fp+'temp.stars1',
                      interactive='no',
                      verify='no',sigma=params.star_detect_sigma,
                      fwhmpsf=g.fw,datamin=1,
                      datamax=params.pixel_max,epadu=params.gain,
                      readnoise=params.readnoise,noise='poisson')

            # join star lists together
            iraf.pconcat(infiles=fp+'temp.phot,'+fp+'temp.phot1',outfile=fp+'temp.phot2')

        # new PSF estimate to generate PSF groups
        iraf.psf(image=f,photfile=fp+'temp.phot2',pstfile=fp+'temp.pst',psfimage=fp+'temp.psf2',
                 function=params.psf_profile_type,opstfile=fp+'temp.opst2',
                 groupfile=fp+'temp.psg3',
                 interactive='no',
                 verify='no',varorder=0 ,psfrad=2*g.fw,
                 datamin=-10000,datamax=0.95*params.pixel_max,
                 scale=1.0)

        # magnitudes for PSF group stars
        iraf.nstar(image=f,groupfile=fp+'temp.psg3',psfimage=fp+'temp.psf2',
                   nstarfile=fp+'temp.nst',
                   rejfile='',verify='no',psfrad=2*g.fw,fitrad=2.0,
                   recenter='no',
                   groupsky='yes',fitsky='yes',sannulus=7,wsannulus=10,
                   datamin=1,datamax=params.pixel_max,
                   epadu=params.gain,readnoise=params.readnoise,noise='poisson')

        # subtract PSF star neighbours
        iraf.substar(image=f,photfile=fp+'temp.nst',psfimage=fp+'temp.psf2',
                     exfile=fp+'temp.opst2',fitrad=2.0,
                     subimage=fp+'temp.sub1',verify='no',datamin=1,
                     datamax=params.pixel_max,epadu=params.gain,
                     readnoise=params.readnoise,noise='poisson')
        
        # final PSF
        iraf.psf(image=fp+'temp.sub1',photfile=fp+'temp.phot2',
                 pstfile=fp+'temp.opst2',
                 psfimage=psf_image,psfrad=2*g.fw,
                 function=params.psf_profile_type,opstfile=fp+'temp.opst3',
                 groupfile=fp+'temp.psg5',
                 interactive='no',
                 verify='no',varorder=0,
                 datamin=1,datamax=0.95*params.pixel_max,
                 scale=1.0)

        # final photometry

        
        iraf.allstar(image=g.fullname,photfile=fp+'temp.phot2',psfimage=psf_image,
                     allstarfile=fp+'temp.als2',rejfile='',
                     subimage=fp+'temp.sub2',verify='no',psfrad=2*g.fw,
                     recenter=als_recenter,groupsky='yes',fitsky='yes',sannulus=7,
                     wsannulus=10,fitrad=2.0,
                     datamin=params.pixel_min,datamax=params.pixel_max,
                     epadu=params.gain,readnoise=params.readnoise,
                     noise='poisson')

        psfmag = 10.0
        for line in open(fp+'temp.als2','r'):
            sline = line.split()
            if sline[1] == 'PSFMAG':
                psfmag = float(sline[3])
                break

        if params.star_file:
            
            iraf.psort(infiles=fp+'temp.als2',field='ID')
            os.system('cp '+fp+'temp.als2 '+fp+'temp.als3') 

        else:
        
            selection = 'XCE >= '+str(edge_dist)+' && XCE <= '+str(xmax)+' && YCE >= '+str(edge_dist)+' && YCE <= '+str(ymax)+' && MAG != INDEF'
            iraf.pselect(infiles=fp+'temp.als2',outfiles=fp+'temp.als3',expr=selection)
            iraf.psort(infiles=fp+'temp.als3',field='MAG')   
            iraf.prenumber(infile=fp+'temp.als3')
            
        s = iraf.pdump(infiles=fp+'temp.als3',Stdout=1,
                       fields='ID,XCENTER,YCENTER,MAG,MERR,MSKY,SHARPNESS,CHI',expr='yes')
        sf = [k.replace('INDEF','22.00') for k in s]
        stars = np.zeros([len(sf),5])
        for i, line in enumerate(sf):
            stars[i,:] = np.array(map(float,sf[i].split()[1:6]))

        s = iraf.pdump(infiles=fp+'temp.als3',Stdout=1,
                       fields='ID,XCENTER,YCENTER,MAG,MERR,SHARPNESS,CHI,MSKY',expr='yes')
        sf = [k.replace('INDEF','22.00') for k in s]
        with open(fp+'ref.mags','w') as fid:
            for s in sf:
                fid.write(s+'\n')

    return stars
Пример #33
0
def maskStars(imageName):
  #read in the fits data and header
  imageHeader = fits.open(imageName+".fits")[0]
  
  #Read in the skysigma, skyv, and seeing (fwhm) from the header and set up other relevant values
  sigma = imageHeader.header['SKYSIGMA']
  threshold = 3.0 * sigma
  
  skyv = imageHeader.header['SKY']
  
  fwhm = imageHeader.header['SEEING']
  aper = 3.0 * fwhm
  annul = 5 * fwhm
  
  #Read in the galcut file
  galcut = open("galcut.file")
  galcutString = file.read(galcut)
  galcut.close()
  
  #Parse the galcut file into its variables
  galList = galcutString.split(' ')
  xCenter = float(galList[0])
  yCenter = float(galList[1])
  a = float(galList[2]) #Semimajor Axis
  eccent = float(galList[3]) #Eccentricity
  posAngle = float(galList[4]) #Position angle
  
  posAngleRad = (posAngle+90)*3.14159/180 
  b = a * eccent #Semiminor Axis
  na = -1*a
  nb = -1*b
  
  #Create a version of the r image with the sky added back in for the daofind procedure
  iraf.imdelete("withsky")
  iraf.imarith(imageName,'+',skyv,"withsky")

  # Load daophot package
  iraf.digiphot()
  iraf.daophot()  

  print("A. Find stars using daofind")

#DAOFIND  searches  the  IRAF  images image for local density maxima,
#    with a  full-width  half-maxima  of  datapars.fwhmpsf,  and  a  peak
#    amplitude  greater  than  findpars.threshold  * datapars.sigma above
#    the local background, and writes a list of detected objects  in  the
#    file  output.  
# Here we set the fwhm and sigma equal to those listed in the header.
# We set the datamin to -3*sigma = -1*threshold defined above
# The findpars.threshold is set to 4.5*sigma by default. You may have
# to alter this value for images where too few/many stars are found.


  #Configure 'datapars', 'findpars', and 'daofind'
  iraf.datapars.fwhmpsf=fwhm
  iraf.datapars.sigma=sigma
  iraf.datapars.datamax='indef'
  iraf.datapars.datamin=(-1)*threshold
  iraf.datapars.ccdread='RDNOISE'
  iraf.datapars.gain="GAIN"
  iraf.datapars.exposure="EXPTIME"
  iraf.datapars.airmass="AIRMASS"
  iraf.datapars.filter="FILTER"
  iraf.datapars.obstime="TIME-OBS"

  iraf.findpars.threshold=4.5
  iraf.findpars.roundhi=3
  iraf.findpars.roundlo=-3

  iraf.daofind.verify='no'
  iraf.daofind.verbose='no'
  
  #create the variable for the coordinate file
  allStars = imageName+'.coo'
  
  #Remove a previous coordinate file if one exists
  silentDelete(imageName+'.coo')

  #Find the stars in the aligned R image
  iraf.daofind("withsky",allStars)
  print("The file containing the data of the stars in the aligned R-image is ",allStars)
  print(" ") 

  if os.path.getsize(allStars) > 2239 :

   print("B. Separate stars inside and outside galaxy")
  
   #Delete existing files
   for f in ("temp.file","maskfile","maskfile.sat"):
     silentDelete(f)
  
   #Extract the coordinates from the allStars file, redirecting stdout to do so
   sys.stdout=open("temp.file","w")
   iraf.pdump(allStars,"xcenter,ycenter",'yes')
   sys.stdout = sys.__stdout__
  


  #Read the file to get the xy coordinate pairs in a list
   coords = open("temp.file")
   coordList = list(coords)
   countout=0
  
  #Create strings of xy pairs to write to files
   outGalString = ""
   for pair in coordList:
     #for each entry in the list, parse it into xy value integer pairs
     values = pair.split("  ")
     x = float(values[0])
     y = float(values[1])
    
    #Determine if the star lies within the galaxy-centered ellipse
     inGalaxy = False
     deltaX = x - xCenter
     deltaY = y - yCenter
     cdx = abs(deltaX)
     cdy = abs(deltaY)
     if (cdx < a and cdy < a):
       xt=(deltaX*math.cos(posAngleRad))+(deltaY*math.sin(posAngleRad))
       yt=(deltaY*math.cos(posAngleRad))-(deltaX*math.sin(posAngleRad))
       if(xt <= a and xt >= na and yt <= b and yt >= nb):
         inGalaxy = True
      
     if (not inGalaxy):
       outGalString += str(x) + " " + str(y) + "\n"
       countout=countout+1
 
  #Write the coordinate list to a file
   mask = open("maskfile","w")
   mask.write(outGalString)
   mask.close()
   print('')
   print("  ",countout," stars found outside galaxy")
   print('')
   if countout!=0 :

    print("C. Do photometry to find saturated stars")
  
    for f in ("maskfile.mag","maskfile.satmag","maskfile.sat"):
     silentDelete(f)
  
  #Configure 'centerpars', 'fitskypars','photpars'
    iraf.datapars.datamax=150000
    iraf.datapars.datamin='indef'
    iraf.centerpars.calgorithm="none"

    iraf.fitskypars.salgorithm="mode"
    iraf.fitskypars.annulus=annul
    iraf.fitskypars.dannulus=10

    iraf.photpars.apertures=fwhm
    iraf.phot.verify='no'
    iraf.phot.verbose='no'
  
  #Call 'phot' to get the data of the stars 
    iraf.phot (imageName,"maskfile","maskfile.mag")

    boexpr="PIER==305"
    iraf.pselect("maskfile.mag","maskfile.satmag",boexpr)

    sys.stdout=open("maskfile.sat","w")
    iraf.pdump("maskfile.satmag","xcenter,ycenter","yes")
    sys.stdout = sys.__stdout__
  
    print("D. Make mask of stars outside galaxy")
  
  #Delete the rmask if one exists
    silentDelete("rmask.fits")
  
  #Configure 'imedit'
    iraf.imedit.cursor="maskfile"
    iraf.imedit.display='no'
    iraf.imedit.autodisplay='no'
    iraf.imedit.aperture="circular"
    iraf.imedit.value=-1000
    iraf.imedit.default="e"
  
  #Replace the pixel values near the star coordinates with value -1000 using imedit
    iraf.imedit(imageName,"redit",radius=aper)
 
    iraf.imcopy.verbose='no'
  #Do the same for the saturated stars, but with larger apertures
    satMaskSize = os.path.getsize("maskfile.sat")
    if satMaskSize < 1 : 
     print("   No saturated stars found")
    if (satMaskSize!=0):
     iraf.imedit.cursor="maskfile.sat"
     iraf.imedit.radius=2*aper
     iraf.imedit("redit","rmask")
    else:
     iraf.imcopy("redit","rmask")
  
  #Replace good pixels with value 0 in 'rmask'
    iraf.imreplace.lower=-999
    iraf.imreplace.upper='indef'
    iraf.imreplace("rmask",0)

  #Replace bad pixels with value 1 in 'rmask'
    iraf.imreplace.lower='indef'
    iraf.imreplace.upper=-1000
    iraf.imreplace("rmask",1)
  
   
  #Remove the mask file if one already exists
    silentDelete(imageName+"mask.fits")
    iraf.imcopy("rmask",imageName+"mask")

    print(" ")
    print("The mask image is ",imageName+"mask")
    print("The masked image is ",imageName+"Masked")
    print(" ")
 
   else :
    print("No stars found outside galaxy, no mask created.")

  if os.path.getsize(allStars) < 2314 :
   print("No stars found, no mask created.")



  #Delete intermediate images 
  for f in ("rmask.fits","redit.fits","maskimage.fits","maskfile.mag","maskfile.satmag","temp.file","withsky.fits","mask.fits"):
    silentDelete(f)
Пример #34
0
import pyraf, os, glob
from pyraf import iraf
from iraf import noao, digiphot, daophot

if __name__ == '__main__':

    #generate list of all fits files in current directory
    file_list = glob.glob('*_cts.fits')
    print file_list

    #loops through all FITS files
    for file in file_list:
        #look for old files, and remove if they exist
        file_query = os.access('starlist_' + file.replace('.fits', \
        ''), os.R_OK)
        if file_query == True:
            os.remove('starlist_' + file.replace('.fits', ''))
    
        #execute daofind on one image
        print 'DAOFind on image ', file
        outfile = 'starlist_' + file.replace('.fits', '')
        iraf.daofind.unlearn()
        iraf.daofind(
            image = file,
            output = outfile,
            fwhmpsf = 3,
            readnoise = 7.6424,
            itime = 7024.,
            threshold = 4.0,
            interactive = 'no',
            verify = 'no') 
Пример #35
0
        pars = {}
        print 'Calculating sky and sigma values ...'
        sigma, sky = findsky(FitsFileName,10)
        print 'Skyvalue: ',sky
        print 'Stdv_sky: ',sigma
        iraf.datapars.setParam('sigma',sigma)
        iraf.fitskypars.setParam('skyvalu',sky)
        pars['gain'] = gain
        pars['rdnoise'] = rdnoise
        pars['sigma'] = sigma
        pars['sky'] = sky

        iraf.datapars.setParam('fwhmpsf',4.0)
        iraf.daofind.setParam('image',FitsFileName)
        iraf.daofind.setParam('output',base+'im'+ext+'.guess.coo')
        iraf.daofind(mode='h',Stdout=1)

        iraf.txdump(textfile=base+'im'+ext+'.guess.coo',fields='xcenter,ycenter,sharpness',expr='sharpness!=INDEF',
        Stdout=base+'daofindtmp')
        daofind = np.loadtxt(base+'daofindtmp')
        if os.path.exists(base+'im'+ext+'.guess.coo') == True: os.remove(base+'im'+ext+'.guess.coo')
        i = (daofind[:,2] < np.median(daofind[:,2]) + 0.12) & (daofind[:,2] > np.median(daofind[:,2]) - 0.12)
        np.savetxt(base+'im'+ext+'.guess.coo',daofind[i,0:2],fmt=['%-10.3f','%-10.3f'])
        iraf.fitpsf.setParam('image',FitsFileName)
        iraf.fitpsf.setParam('coords',base+'im'+ext+'.guess.coo')

        val = linspace(2.,6.,11.)
        best = 0.0
        res = 99999.99
        for i in val:
            iraf.datapars.setParam('fwhmpsf',i)