Ejemplo n.º 1
0
def psf_star_fitting_2runs(imagebi, psfstarfile,photfilesuffix,satmag, psfcleaningradius=10.):
    print '!!!!!!!!!!!!'+str(psfcleaningradius)
    print "Fitting the PSF model for file: " + imagebi
    iraf.daophot.verify = False
    #needs to be set here because it is different for each amplifier
    sky,skydev=get_sky(imagebi)
    iraf.datapars.datamin=sky-5*skydev
    iraf.datapars.sigma=skydev
    #use a smaller radius for nstar and substar to substract the "core only" of close neighbours
    original_psfrad=iraf.daopars.psfrad
    iraf.daopars.psfrad = psfcleaningradius
    print '!!!!!!!!!!!!'+str(psfcleaningradius)
    print '!!!!!!!!!!!!'+str(iraf.daopars.psfrad)
    # get inital list of psf stars (either selected by hand or let iraf select) and make a first-round psf model:
    psf_star_fitting_initial(imagebi, psfstarfile,photfilesuffix,satmag)
    # find neighbors of psf stars which are in the fitting radius.
    iraf.nstar(imagebi,get_last_iraf(imagebi+'.psg'),'default','default','default', verbose = False)
    # subtract the first-round psf model of those neighboring stars from the psf stars (so that wings of psf stars are star-free).
    iraf.substar(imagebi,get_last_iraf(imagebi+'.nst'), get_last_iraf(imagebi+'.pst'), get_last_iraf(imagebi+'.psf',suffix='fits'), 'default', verbose=True, Stdout=1)
    #then reset psfrad to original value
    iraf.daopars.psfrad = original_psfrad
    # now get the second-round psf model by fitting the neighbor-subtracted psf stars.
    iraf.daophot.psf(get_last_iraf(imagebi+'.sub',suffix='fits'), imagebi+photfilesuffix,get_last_iraf(imagebi+'.pst'), get_next_iraf(imagebi+'.psf',suffix='fits'), get_next_iraf(imagebi+'.pst'), get_next_iraf(imagebi+'.psg'), interactive=False,verify=False,nclean=10)
Ejemplo n.º 2
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
Ejemplo n.º 3
0
    pst1.write(fn[:-5] + '.pst.0',
               format='ascii.commented_header',
               delimiter='\t',
               comment='#N ID    XCENTER   YCENTER \
	    MAG         MSKY\n#U ##    pixels    pixels    magnitudes  counts\n#F %-9d  %-10.3f   %-10.3f   %-12.3f     %-15.7g\n#'
               )

    original = sys.stdout
    try:
        sys.stdout = open(fn[:-5] + '.psf1.out', 'w')
        iraf.psf(fn[:-5],photfile=fn[:-5]+'.mag.1',pstfile=fn[:-5]+'.pst.0',psfimage=fn[:-5]+'.psf.1',opstfile=fn[:-5]+'.pst.1', \
         groupfile=fn[:-5]+'.psg.1',verify='no',interactive='no',plotfile=fn[:-5]+'.psf1.plots')
        iraf.allstar(fn[:-5],photfile=fn[:-5]+'.psg.1',psfimage=fn[:-5]+'.psf.1',allstarfile=fn[:-5]+'.als.1',rejfile=fn[:-5]+ \
            '.arj.1',subimage=fn[:-5]+'.sub.1',verify='no',verbos='no')
        iraf.substar(fn[:-5],photfile=fn[:-5]+'.als.1',exfile=fn[:-5]+'.pst.1',psfimage=fn[:-5]+'.psf.1',subimage=fn[:-5]+ \
            '.sub.11',verify='no',verbose='no')

        sys.stdout = open(fn[:-5] + '.psf2.out', 'w')
        iraf.psf(fn[:-5]+'.sub.11',photfile=fn[:-5]+'.mag.1',pstfile=fn[:-5]+'.pst.1',psfimage=fn[:-5]+'.psf.2', \
            opstfile=fn[:-5]+'.pst.2', groupfile=fn[:-5]+'.psg.2',verify='no',interactive='no')
        iraf.allstar(fn[:-5],photfile=fn[:-5]+'.psg.2',psfimage=fn[:-5]+'.psf.2',allstarfile=fn[:-5]+'.als.2',rejfile=fn[:-5]+ \
            '.arj.2',subimage=fn[:-5]+'.sub.2',verify='no',verbos='no')
        iraf.substar(fn[:-5],photfile=fn[:-5]+'.als.2',exfile=fn[:-5]+'.pst.2',psfimage=fn[:-5]+'.psf.2',subimage=fn[:-5]+ \
            '.sub.22',verify='no',verbose='no')

        sys.stdout = open(fn[:-5] + '.psf3.out', 'w')
        iraf.psf(fn[:-5]+'.sub.22',photfile=fn[:-5]+'.mag.1',pstfile=fn[:-5]+'.pst.2',psfimage=fn[:-5]+'.psf.3',opstfile \
            =fn[:-5]+'.pst.3', groupfile=fn[:-5]+'.psg.3',verify='no',interactive='no')
    except iraf.IrafError, e:
        sys.stdout = original
        print fn
Ejemplo n.º 4
0
def psfphot(inlist,
            ra,
            dec,
            reffilt,
            interact,
            fwhm,
            readnoise,
            gain,
            threshold,
            refimage=None,
            starfile=None,
            maxnpsf=5,
            clobber=globclob,
            verbose=globver,
            skykey='SKYBKG',
            filtkey='FILTER',
            pixtol=3.0):
    """ perform PSF-based photometry on a single target star (SN?) at RA, Dec and  
        also on a set of comparison stars, using daophot.  simultaneously 
        perform aperture photometry on all the comparison stars (after 
        subtracting off contributions from neighbors) to enable absolute 
        photometry by comparison to aperture photometry of standard stars 
        observed in other fields """

    # Defaults / constants
    psfmult = 5.0  #standard factor (multiplied by fwhm to get psfradius)
    psfmultsmall = 3.0  #similar to psfmult, adjusted for nstar and substar

    # Necessary package
    iraf.imutil()

    # Parse inputs
    infiles = iraffiles(inlist)

    # Which file is reffilt?  call it refimage
    if refimage == None:
        for image in infiles:
            if check_head(image, filtkey):
                try:
                    imgfilt = get_head(image, filtkey)
                    if imgfilt == reffilt:
                        refimage = image
                        break
                except:
                    pass

    if not refimage:
        print "BAD USER!  No image corresponds to the filter: %s" % reffilt
        return
    else:
        refroot = 's' + refimage.split('.')[0]

    #first make sure to add back in background of sky
    iraf.iqsubsky(inlist, sub=no, skykey=skykey)

    #put reference image first on list
    infiles.remove(refimage)
    infiles.insert(0, refimage)

    #setup for keywords
    if gain == "!GAIN":
        try:
            gainval = float(get_head(image, gain))
        except:
            print "Bad header keyword for gain."
    else:
        gainval = float(gain)

    if readnoise == "!READNOISE":
        try:
            readval = float(get_head(image, readnoise))
        except:
            print "Bad header keyword for readnoise."
    else:
        readval = float(readnoise)

    # Process each file in turn
    for image in infiles:

        # Check that the image is there
        check_exist(image, "r")

        # Grab image root name
        root = image.split('.')[0]

        # Map image to reference image
        if not (image == refimage):
            [nx, ny] = get_head(image, ['NAXIS1', 'NAXIS2'])
            stars = Starlist(get_head(image, 'STARFILE'))
            refstars = Starlist(get_head(refimage, 'STARFILE'))
            refstars.pix2wcs(refimage)
            refstars.wcs2pix(image)
            match, refmatch = stars.match(refstars, useflags=yes, tol=10.0)
            nstars = len(match)
            if not (nstars > 2):
                print 'Could not find star matches between reference and %s' % image
                infiles.remove(image)
                continue
            refmatch.pix2wcs(image)
            refmatch.wcs2pix(refimage)
            matchfile = open('%s.match' % root, 'w')
            for i in range(len(match)):
                matchfile.write('%10.3f%10.3f%10.3f%10.3f\n' %
                                (refmatch[i].xval, refmatch[i].yval,
                                 match[i].xval, match[i].yval))
            matchfile.close()
            check_exist('%s.geodb' % root, 'w', clobber=clobber)
            iraf.geomap('%s.match' % root,
                        '%s.geodb' % root,
                        1.0,
                        nx,
                        1.0,
                        ny,
                        verbose=no,
                        interactive=no)
            check_exist('s%s.fits' % root, 'w', clobber=clobber)
            iraf.geotran(image,
                         's%s' % root,
                         '%s.geodb' % root,
                         '%s.match' % root,
                         geometry="geometric",
                         boundary="constant",
                         verbose=no)
        else:
            iraf.imcopy(image, 's%s' % root)
        root = 's%s' % root

        #get sky level and calculate sigma
        #if check_head(image, skykey):
        #    try:
        #        sky=float(get_head(image, skykey))
        #    except:
        #        print "No sky levels in header."

        #sigma= (((sky * gainval) + readval**2)**.5) / gainval
        iraf.iterstat(image)

        # Saturation level
        if not check_head(image, "SATURATE"):
            saturate = 60000.0
        else:
            saturate = get_head(image, "SATURATE")

        # Update datapars and daopars
        iraf.datapars.fwhmpsf = fwhm
        iraf.datapars.sigma = iraf.iterstat.sigma
        iraf.datapars.datamin = iraf.iterstat.median - 10 * iraf.iterstat.sigma
        iraf.datapars.datamax = 0.90 * saturate
        iraf.datapars.readnoise = readval
        iraf.datapars.epadu = gainval
        iraf.datapars.filter = filtkey
        iraf.daopars.psfrad = psfmult * fwhm
        iraf.daopars.fitrad = fwhm
        iraf.daopars.function = "gauss,moffat15,moffat25,lorentz,penny1"

        #find stars in image unless a starlist is given
        if image == refimage and starfile == None:
            iraf.daophot.daofind(root,
                                 'refimage.coo.1',
                                 threshold=threshold,
                                 verify=no,
                                 verbose=verbose)
        elif image == refimage:
            shutil.copy(starfile, 'refimage.coo.1')

        #initial photometry
        iraf.daophot.phot(root,
                          'refimage.coo.1',
                          'default',
                          aperture=fwhm,
                          verify=no,
                          verbose=verbose)

        #select stars for psf the first time
        refstarsfile = "refimage.pst.1"
        if image == refimage:
            iraf.pstselect(root,
                           'default',
                           refstarsfile,
                           maxnpsf,
                           interactive=yes,
                           verify=no,
                           verbose=verbose)

        #fit the psf
        iraf.psf(root,
                 'default',
                 refstarsfile,
                 'default',
                 'default',
                 'default',
                 interactive=interact,
                 verify=no,
                 verbose=verbose)

        #identify neighboring/interfering stars to selected stars
        groupingfile = root + ".psg.1"
        iraf.nstar(root,
                   groupingfile,
                   'default',
                   'default',
                   'default',
                   psfrad=psfmultsmall * fwhm,
                   verify=no,
                   verbose=verbose)

        #subtract out neighboring stars from image
        iraf.substar(root,
                     'default',
                     refstarsfile,
                     'default',
                     'default',
                     psfrad=psfmultsmall * fwhm,
                     verify=no,
                     verbose=verbose)

        #repeat psf to get better psf model
        #IRAF's interactive version usually crashes
        subtractedimage = root + ".sub.1"
        iraf.psf(subtractedimage,
                 root + ".nst.1",
                 refstarsfile,
                 '%s.psf.2' % root,
                 '%s.pst.2' % root,
                 '%s.psg.2' % root,
                 interactive=interact,
                 verify=no,
                 verbose=verbose)

        #Need to make sure SN was detected by daofind
        stars = Starlist('%s.mag.1' % root)
        SN = Star(name='SN', radeg=ra, dcdeg=dec, fwhm=2.0, fwhmw=2.0)
        SNlis = Starlist(stars=[SN])
        SNlis.wcs2pix(image)
        if (len(stars.match(SNlis)[0]) == 0):
            #No match - need to add to daofind file
            print "No match!"
            coofile = open('refimage.coo.1', 'a+')
            coofile.write('%10.3f%10.3f%9.3f%8.3f%13.3f%12.3f%8i\n' %
                          (SNlis[0].xval, SNlis[0].yval, 99.999, 0.500, 0.000,
                           0.000, 999))
            coofile.close()

        #repeat aperture photometry to get good comparisons to standard fields
        iraf.daophot.phot(root,
                          'refimage.coo.1',
                          'default',
                          aperture=psfmult * fwhm,
                          verify=no,
                          verbose=verbose)

        # allstar run
        iraf.allstar(root,
                     'default',
                     'default',
                     'default',
                     'default',
                     'default',
                     verify=no,
                     verbose=verbose)
Ejemplo n.º 5
0
def psfphot(inlist, ra, dec, reffilt, interact, fwhm, readnoise, gain, 
            threshold,refimage=None,starfile=None,maxnpsf=5, 
            clobber=globclob,verbose=globver,skykey='SKYBKG',
            filtkey='FILTER',pixtol=3.0):


    """ perform PSF-based photometry on a single target star (SN?) at RA, Dec and  
        also on a set of comparison stars, using daophot.  simultaneously 
        perform aperture photometry on all the comparison stars (after 
        subtracting off contributions from neighbors) to enable absolute 
        photometry by comparison to aperture photometry of standard stars 
        observed in other fields """

    # Defaults / constants
    psfmult=5.0         #standard factor (multiplied by fwhm to get psfradius)
    psfmultsmall=3.0    #similar to psfmult, adjusted for nstar and substar

    # Necessary package
    iraf.imutil()

    # Parse inputs
    infiles=iraffiles(inlist)

    # Which file is reffilt?  call it refimage
    if refimage==None:
        for image in infiles:
            if check_head(image, filtkey):
                try:
                    imgfilt = get_head(image, filtkey)
                    if imgfilt == reffilt:
                        refimage = image
                        break
                except:
                    pass
            
    if not refimage:
        print "BAD USER!  No image corresponds to the filter: %s" % reffilt
        return
    else:
        refroot='s'+refimage.split('.')[0]

    #first make sure to add back in background of sky
    iraf.iqsubsky(inlist, sub=no, skykey=skykey)

    #put reference image first on list
    infiles.remove(refimage)
    infiles.insert(0,refimage)

    #setup for keywords
    if gain == "!GAIN":
        try: gainval = float(get_head(image, gain))
        except:
            print "Bad header keyword for gain."
    else:
        gainval = float(gain)

    if readnoise == "!READNOISE":
        try: readval = float(get_head(image, readnoise))
        except:
            print "Bad header keyword for readnoise."
    else:
        readval = float(readnoise)

    # Process each file in turn
    for image in infiles:

        # Check that the image is there
        check_exist(image,"r")

        # Grab image root name
        root=image.split('.')[0]

        # Map image to reference image
        if not (image==refimage):
            [nx,ny]=get_head(image,['NAXIS1','NAXIS2'])
            stars=Starlist(get_head(image,'STARFILE'))
            refstars=Starlist(get_head(refimage,'STARFILE'))
            refstars.pix2wcs(refimage)
            refstars.wcs2pix(image)
            match,refmatch=stars.match(refstars,useflags=yes,tol=10.0)
            nstars=len(match)
            if not (nstars>2):
                print 'Could not find star matches between reference and %s' % image
                infiles.remove(image)
                continue
            refmatch.pix2wcs(image)
            refmatch.wcs2pix(refimage)
            matchfile=open('%s.match' % root, 'w')
            for i in range(len(match)):
                matchfile.write('%10.3f%10.3f%10.3f%10.3f\n' % 
                               (refmatch[i].xval,refmatch[i].yval,
                                match[i].xval,match[i].yval))
            matchfile.close()
            check_exist('%s.geodb' % root, 'w', clobber=clobber)
            iraf.geomap('%s.match' % root,'%s.geodb' % root,1.0,nx,1.0,ny,
                        verbose=no,interactive=no)
            check_exist('s%s.fits' % root, 'w', clobber=clobber)
            iraf.geotran(image,'s%s' % root,'%s.geodb' % root,
                         '%s.match' % root,geometry="geometric",
                         boundary="constant",verbose=no)
        else:
            iraf.imcopy(image,'s%s' % root)
        root='s%s' % root
 
        #get sky level and calculate sigma
        #if check_head(image, skykey):
        #    try:
        #        sky=float(get_head(image, skykey))
        #    except:
        #        print "No sky levels in header."

        #sigma= (((sky * gainval) + readval**2)**.5) / gainval        
        iraf.iterstat(image)
        
        # Saturation level
        if not check_head(image, "SATURATE"):
        	saturate = 60000.0
        else:
        	saturate = get_head(image, "SATURATE")
        	        
        # Update datapars and daopars
        iraf.datapars.fwhmpsf=fwhm
        iraf.datapars.sigma=iraf.iterstat.sigma
        iraf.datapars.datamin=iraf.iterstat.median-10*iraf.iterstat.sigma
        iraf.datapars.datamax=0.90*saturate
        iraf.datapars.readnoise=readval
        iraf.datapars.epadu=gainval
        iraf.datapars.filter=filtkey
        iraf.daopars.psfrad=psfmult*fwhm
        iraf.daopars.fitrad=fwhm
        iraf.daopars.function="gauss,moffat15,moffat25,lorentz,penny1"

        #find stars in image unless a starlist is given
        if image==refimage and starfile==None:
            iraf.daophot.daofind(root,'refimage.coo.1',threshold=threshold,verify=no,
                         verbose=verbose)
        elif image==refimage:
            shutil.copy(starfile,'refimage.coo.1')

        #initial photometry
        iraf.daophot.phot(root,'refimage.coo.1','default',aperture=fwhm,verify=no,
                  verbose=verbose)

        #select stars for psf the first time
        refstarsfile = "refimage.pst.1"
        if image == refimage:
            iraf.pstselect(root,'default',refstarsfile,maxnpsf,
                           interactive=yes,verify=no,verbose=verbose)

        #fit the psf
        iraf.psf(root,'default',refstarsfile,'default','default','default',
                 interactive=interact,verify=no,verbose=verbose)

        #identify neighboring/interfering stars to selected stars
        groupingfile = root+".psg.1"
        iraf.nstar(root,groupingfile,'default','default','default',
                   psfrad= psfmultsmall * fwhm,verify=no,verbose=verbose)

        #subtract out neighboring stars from image
        iraf.substar(root,'default',refstarsfile,'default','default',
                     psfrad=psfmultsmall*fwhm,verify=no,verbose=verbose)

        #repeat psf to get better psf model
        #IRAF's interactive version usually crashes
        subtractedimage = root+".sub.1"
        iraf.psf(subtractedimage,root+".nst.1",refstarsfile,'%s.psf.2' % root,
                 '%s.pst.2' % root,'%s.psg.2' % root,interactive=interact,
                 verify=no,verbose=verbose)

        #Need to make sure SN was detected by daofind
        stars=Starlist('%s.mag.1' % root)
        SN=Star(name='SN',radeg=ra,dcdeg=dec,fwhm=2.0,fwhmw=2.0)
        SNlis=Starlist(stars=[SN])
        SNlis.wcs2pix(image)
        if (len(stars.match(SNlis)[0])==0):
            #No match - need to add to daofind file
            print "No match!"
            coofile=open('refimage.coo.1', 'a+')
            coofile.write('%10.3f%10.3f%9.3f%8.3f%13.3f%12.3f%8i\n' % (SNlis[0].xval, SNlis[0].yval,99.999,0.500,0.000,0.000,999))
            coofile.close()    

        #repeat aperture photometry to get good comparisons to standard fields
        iraf.daophot.phot(root,'refimage.coo.1','default',aperture=psfmult*fwhm,
                  verify=no,verbose=verbose)

        # allstar run
        iraf.allstar(root,'default','default','default','default','default',
                     verify=no,verbose=verbose)