Example #1
0
def subtract_stars(args):
    """ Routine to subtract a set of stars defined by the user. We will model the PSF of some suitable stars in the
        images, then use that """

    # First substitute the names of the image in args.image by the corresponding astroim object, with more information
    args.image = astroim.Astroim(args.image)

    # Do photometry on the stars to be used to model the PSF
    phot_modstars, phot_subtstars = apply_phot(args)
    pst_file = apply_pst(args, phot_modstars)
    psf_file = apply_psf(args, phot_modstars, pst_file)

    hdr = args.image.header  # for short
    seeing, sigma = utils.get_from_header(args.image.im_name, hdr.seeingk, hdr.sigmak)
    utils.if_exists_remove(args.output)
    iraf.allstar(
        args.image.im_name,
        photfile=phot_subtstars,
        psfimage=psf_file,
        subimage=args.output,
        psfrad=6 * seeing,
        fitrad=3 * seeing,
        wcsin="physical",
        fitsky="yes",
        sannulus=4 * seeing,
        wsannulus=3 * seeing,
        verify="no",
    )
Example #2
0
def daofind(filelist, psfimage):
	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.daopars.setParam("fitrad", "5.853")
	iraf.daopars.setParam("psfrad", "18.56")
	

	with open(filelist) as file1:
		for line in file1:
			filename = line.strip()
			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.allstar.setParam("image","%s" % filename	)
			iraf.allstar.setParam("photfile","%s.mag" % filename	)
			iraf.allstar.setParam("psfimage",psfimage	)
			iraf.allstar.setParam("allstarfile","%s.als"%filename	)
			iraf.allstar.setParam("rejfile","%s.arj"%filename	)
			iraf.allstar.setParam("subimage","%s.sub" %filename	)


			iraf.allstar(mode="h")
def run_allstar(imageFile, psfimage):
    iraf.allstar.unlearn()
    iraf.allstar(image=imageFile,\
                 photfile=imageFile+".mags.1",\
                 psfimage=psfimage, \
                 allstarfile=imageFile+".als.1",\
                 rejfile=imageFile+".arj.1",\
                 subimage=imageFile+".sub.1")
def run_allstar(imageFile, psfimage):
    iraf.allstar.unlearn()
    iraf.allstar(image=imageFile,\
                 photfile=imageFile+".mags.1",\
                 psfimage=psfimage, \
                 allstarfile=imageFile+".als.1",\
                 rejfile=imageFile+".arj.1",\
                 subimage=imageFile+".sub.1")
Example #5
0
def simplepsfphot(image,coords,psf,refstar,centre=True,vary=False):
    """PSF photometry, with a given PSF file in psf used for every image"""
    iraf.dele('temp.mag*')
    iraf.dele('temp.als')
    iraf.dele('temp.sub.fits')
    if centre:
        xsh,ysh = recentre(image,refstar) 
        print "Fine Centring: ", xsh,ysh
    else: xsh,ysh = 0,0
    if vary:
        setaperture(image,refstar)
    shift_file_coords(coords,xsh,ysh,'tempcoords2',sort='als')
    iraf.phot(image,'tempcoords2','temp.mag2',inter="no",calgorithm='none',
                  mode='h',verify='no',update='no',verbose='no')
    iraf.allstar(image,'temp.mag2',psf,'temp.als','temp.mag.arj','temp.sub.fits',
                 mode='h',verify='no',update='no',verbose='no')
    out = iraf.pdump('temp.als','id,mag,merr,msky','yes',Stdout=1)
    return out   
Example #6
0
def psfphot(image,coords,pststars,refstar,centre=True,vary=False):
    """PSF photometry. Centering is through phot on refstar.
Assume coords is a .als file for now. Recentering is always done
for the reference star, never for the targets."""
    iraf.dele('temp.mag*')
    iraf.dele('temp.psf.fits')
    iraf.dele('temp.als')
    if centre:
        xsh,ysh = recentre(image,refstar) 
        print "Fine Centring: ", xsh,ysh
    else: xsh,ysh = 0,0
    if vary:
        setaperture(image,refstar)
    shift_file_coords(coords,xsh,ysh,'tempcoords2',sort='als')
    shift_file_coords(pststars,xsh,ysh,'temppst2',sort='pst')
    iraf.phot(image,'tempcoords2','temp.mag2',inter="no",calgorithm='none',
                  mode='h',verify='no',update='no',verbose='no')
    iraf.psf(image,'temp.mag2','temppst2','temp.psf','temp.mag.pst','temp.mag.psg',
             inter='no',mode='h',verify='no',update='no',verbose='no')
    iraf.allstar(image,'temp.mag2','temp.psf','temp.als','temp.mag.arj',"default",
                 mode='h',verify='no',update='no',verbose='no')
    out = iraf.pdump('temp.als','id,mag,merr,msky','yes',Stdout=1)
    return out   
Example #7
0
def fitsn(img,
          imgpsf,
          coordlist,
          _recenter,
          fwhm0,
          original,
          sn,
          residual,
          _show,
          _interactive,
          z11='',
          z22='',
          midpt='',
          size=7,
          apco0=0,
          dmax=51000,
          dmin=-500):
    import lsc
    lsc.util.delete("apori")
    lsc.util.delete(img + ".sn.mag")
    #################################
    from pyraf import iraf
    import string
    iraf.imcoords(_doprint=0)
    iraf.digiphot(_doprint=0)
    iraf.daophot(_doprint=0)
    from iraf import digiphot
    from iraf import daophot
    from iraf import ptools
    a1 = int(fwhm0)
    a2 = int(2. * fwhm0 + .5)
    a3 = int(3. * fwhm0 + .5)
    a4 = int(4. * fwhm0 + .5)
    ap = str(a1) + "," + str(a2) + "," + str(a3)
    ########################################
    if _recenter: answ = 'yes'
    else: answ = 'no'
    #########################################
    hdr = lsc.util.readhdr(img + '.fits')
    _gain = lsc.util.readkey3(hdr, 'gain')
    _ron = lsc.util.readkey3(hdr, 'ron')
    _exptime = lsc.util.readkey3(hdr, 'exptime')
    _datamin = dmin
    _datamax = dmax
    iraf.noao.digiphot.daophot.photpars.zmag = 0
    iraf.noao.digiphot.daophot.datapars.readnoi = _gain  #1.4   #_ron
    iraf.noao.digiphot.daophot.datapars.epadu = _ron  #  13      #_gain
    iraf.noao.digiphot.daophot.datapars.datamin = _datamin  # -100  #_datamin
    iraf.noao.digiphot.daophot.datapars.datamax = _datamax
    iraf.noao.daophot.fitskypars.annulus = a3
    iraf.noao.daophot.photpars.apertures = ap
    iraf.noao.digiphot.daophot.datapars.exposure = 'exptime'
    iraf.noao.digiphot.daophot.datapars.airmass = 'airmass'
    iraf.noao.digiphot.daophot.datapars.filter = 'filter2'
    iraf.noao.digiphot.daophot.daopars.psfrad = a4
    #  modify fitrad to 3 fwhm to see if works better
    iraf.noao.digiphot.daophot.daopars.fitrad = fwhm0  #* 3
    iraf.noao.digiphot.daophot.daopars.sannulus = int(a4)
    iraf.noao.digiphot.daophot.daopars.recenter = answ
    iraf.noao.digiphot.daophot.daopars.fitsky = 'yes'
    #    iraf.noao.digiphot.daophot.centerpars.cbox = 0
    iraf.noao.digiphot.daophot.centerpars.cbox = 4
    iraf.noao.digiphot.daophot.centerpars.calgori = 'gauss'

    #  fitskypars.salgorithm = "constant"
    #  fitskypars.skyvalue = 0
    print '\n### recentering: ' + str(answ)
    if _show:
        iraf.noao.digiphot.daophot.phot(original,
                                        coordlist,
                                        "apori",
                                        veri='no')
        iraf.noao.digiphot.daophot.phot(sn,
                                        coordlist,
                                        img + ".sn.mag",
                                        veri='no')
    else:
        iraf.noao.digiphot.daophot.phot(original,
                                        coordlist,
                                        "apori",
                                        veri='no',
                                        verb='no')
        iraf.noao.digiphot.daophot.phot(sn,
                                        coordlist,
                                        img + ".sn.mag",
                                        veri='no',
                                        verb='no')

    lsc.util.delete(img + ".sn.als")
    print sn, imgpsf, img
    iraf.allstar(sn,
                 img + ".sn.mag",
                 imgpsf,
                 img + ".sn.als",
                 "",
                 residual,
                 veri='no',
                 verb='no')
    lsc.util.delete("snfit.fits")
    iraf.imarith(sn + '.fits', "-", residual + '.fits', "snfit.fits")
    lsc.util.delete("skyfit.fits")
    iraf.imarith(original + '.fits', "-", "snfit.fits", "skyfit.fits")
    iraf.txsort(img + ".sn.als", "ID")
    tmptbl = iraf.txdump(img + ".sn.als",
                         "mag,merr,xcenter,ycenter",
                         expr='yes',
                         Stdout=1)
    magerr, fitmag, centx, centy = [], [], [], []
    for i in tmptbl:
        try:
            fitmag.append(float(string.split(i)[0]))  #-2.5*log10(_exptime))
        except:
            fitmag.append(string.split(i)[0])
        try:
            magerr.append(float(string.split(i)[1]))
        except:
            magerr.append(string.split(i)[1])
        centx.append(float(string.split(i)[2]))
        centy.append(float(string.split(i)[3]))
    tmptbl = iraf.txdump("apori", "mag", expr='yes', Stdout=1)
    apori1, apori2, apori3 = [], [], []
    for i in tmptbl:
        try:
            apori1.append(float(string.split(i)[0]))  #-2.5*log10(_exptime))
        except:
            apori1.append(string.split(i)[0])
        try:
            apori2.append(float(string.split(i)[1]))  #-2.5*log10(_exptime))
        except:
            apori2.append(string.split(i)[1])
        try:
            apori3.append(float(string.split(i)[2]))  #-2.5*log10(_exptime))
        except:
            apori3.append(string.split(i)[2])

    iraf.txsort(img + ".sn.mag", "YCENTER")
    tmptbl = iraf.txdump(img + ".sn.mag", "mag,magerr", expr='yes', Stdout=1)

    if _show:
        print "********************************************************************"
        print "ID <apmag on original>  <apmag on bgsubt> fitmag truemag err_fit"
        print "     ", a1, "       ", a2, "      ", a3, "        ", a1, "     ", a2, "     ", a3

    apmag1, apmag2, apmag3, truemag = [], [], [], []
    for i in range(len(tmptbl)):
        try:
            apmag1.append(float(string.split(
                tmptbl[i])[0]))  #-2.5*log10(_exptime))
        except:
            apmag1.append(9999)
        try:
            apmag2.append(float(string.split(
                tmptbl[i])[1]))  #-2.5*log10(_exptime))
        except:
            apmag2.append(9999)
        try:
            apmag3.append(float(string.split(
                tmptbl[i])[2]))  #-2.5*log10(_exptime))
        except:
            apmag3.append(9999)
        try:
            truemag.append(fitmag[i] + float(apco0))
        except:
            truemag.append('INDEF')
        if _show:
            print i, apori1[i], apori2[i], apori3[i], apmag1[i], apmag2[
                i], apmag3[i], fitmag[i], truemag[i], magerr[i]
    if _show:
        print "********************************************************************"

    if _show:
        print midpt, z11, z22
        _tmp1, _tmp2, goon = lsc.util.display_image(original + '.fits',
                                                    1,
                                                    z11,
                                                    z22,
                                                    False,
                                                    _xcen=.25,
                                                    _ycen=.25,
                                                    _xsize=.3,
                                                    _ysize=.3)
        z01 = float(z11) - float(midpt)
        z02 = float(z22) - float(midpt)
        s1 = 1
        s2 = -int(fwhm0)
        lsc.util.delete("tmptbl")
        ff = open('tmptbl', 'w')
        ff.write(str(s1) + ' ' + str(s2) + " ORIGINAL")
        ff.close()
        iraf.tvmark(1,
                    "tmptbl",
                    autol='no',
                    mark="none",
                    inter='no',
                    label='yes',
                    txsize=2)
        _tmp1, _tmp2, goon = lsc.util.display_image('snfit.fits',
                                                    1,
                                                    z01,
                                                    z02,
                                                    False,
                                                    _xcen=.25,
                                                    _ycen=.75,
                                                    _xsize=.3,
                                                    _ysize=.3,
                                                    _erase='no')
        lsc.util.delete("tmptbl")
        tmptbl0 = iraf.txdump(img + ".sn.als",
                              "xcen,ycen",
                              expr='yes',
                              Stdout=1)
        ff = open('tmptbl', 'w')
        for i in tmptbl0:
            ff.write(i + '\n')
        ff.close()
        lra = int((2 * float(size) * float(fwhm0)) * 2)
        iraf.tvmark(1,
                    "tmptbl",
                    autol='no',
                    mark="circle",
                    number='yes',
                    nyoffset=lra,
                    radi=a2,
                    txsize=2,
                    inter='no')
        s1 = 1
        s2 = -1 * int(fwhm0)
        lsc.util.delete("tmptbl")
        ff = open('tmptbl', 'w')
        ff.write(str(s1) + ' ' + str(s2) + " FITTED")
        ff.close()
        iraf.tvmark(1,
                    "tmptbl",
                    autol='no',
                    mark="none",
                    inter='no',
                    label='yes',
                    txsize=2)
        _tmp1, _tmp2, goon = lsc.util.display_image('skyfit.fits',
                                                    1,
                                                    z11,
                                                    z22,
                                                    False,
                                                    _xcen=.75,
                                                    _ycen=.25,
                                                    _xsize=.3,
                                                    _ysize=.3,
                                                    _erase='no')
        s1 = 1
        s2 = -1 * int(fwhm0)
        lsc.util.delete("tmptbl")
        ff = open('tmptbl', 'w')
        ff.write(str(s1) + ' ' + str(s2) + " RESIDUAL")
        ff.close()
        iraf.tvmark(1,
                    "tmptbl",
                    autol='no',
                    mark="none",
                    inter='no',
                    label='yes',
                    txsize=2)
    return apori1, apori2, apori3, apmag1, apmag2, apmag3, fitmag, truemag, magerr, centx, centy
Example #8
0
def performPhotometry(task, logger):
  #iraf.prcacheOff()
  [iraf.unlearn(t) for t in ('phot','pstselect','psf','allstar')]
  iraf.set(imtype="fits,noinherit")   # set image output format
  iraf.set(clobber="yes")
  hdu=pyfits.open(task['images'])[0] 
  hdr = hdu.header
  imdata = hdu.data  
  for key,value in task['fits'].iteritems():
    task[key] = hdr.get(value,1)

  #Sextractor to find stars; add an object for the force detect
  logger.info('Running SExtractor on [%s]' % os.path.basename(task['images']))
  sex = sextractor.SExtractor()
  makeSexConfig(sex,task)
  sex.run(task['images'])
  catalog = sex.catalog()

  #Set up image parameters
  MIN_X = max(1,int(task['numpixx']*task['filtfactor']))
  MIN_Y = max(1,int(task['numpixy']*task['filtfactor']))
  MAX_X = int(task['numpixx']*(1-task['filtfactor']))
  MAX_Y = int(task['numpixy']*(1-task['filtfactor']))
  AREAXY = '[%s:%s,%s:%s]' % (MIN_X, MAX_X, MIN_Y, MAX_Y)
  AREANO = '[%s:%s,%s:%s]' % (MIN_X, MAX_X-2*MIN_X, MIN_Y, MAX_Y-2*MIN_Y)
  try:
    task['pixscale'] = abs(hdr.get('CD1_1'))*3600.
  except TypeError:
    task['pixscale'] = abs(hdr.get('CDELT1'))*3600.
  task['seeing'] = np.median( sorted([i['FWHM_IMAGE'] for i in catalog])[:int(-len(catalog)*0.5)] ) #Take the median of the "bottom" 50% of objects
  
  logger.info('--> %s SExtractor detected bright objects in the field' % (len(catalog),) )
  logger.info('--> %0.2f median FWHM of bright objects in the field, in arcsec' % (task['seeing']*task['pixscale'],))

  task['objects'] = [(i['ALPHA_J2000'],i['DELTA_J2000']) for i in catalog]
  task['objects'].append(task['objwcs'])  
  task['objectlist'] = open(os.path.join(task['output_directory'],'objectlist'),'w')  
  task['objectlist'].write('\n'.join([' %s %s' % (i[0],i[1]) for i in task['objects']]))
  task['objectlist'].close()

  logger.info('Running iraf.imstat')
  irafoutput = iraf.imstat(images=task['images']+AREANO,fields='midpt,min,max,stddev', format=0, Stdout=1)
  task['nimgs'] = hdr.get('NIMGS',1)
  task['gain'] *= task['nimgs']*2/3.
  task['ron'] *= np.sqrt(task['nimgs'])/task['nimgs']*constants.INTERPSM[task['band']]
  task['datamean'], task['datamin'], task['datamax'], task['datastdev']  = map(float, irafoutput[0].split())
  irafoutput = iraf.imstat(images=task['images'],fields='stddev,midpt',nclip=25,format=0,cache='yes',Stdout=1)
  task['skynoise'], task['datamean'] = map(float, irafoutput[0].split() )
  task['skynoise'] *= constants.INTERPSM[task['band']]
  task['airmass'] = hdr.get('AIRMASS',1)
  task['zmag'] -= (float(task['airmass'])-1.0)*constants.extinction_coefficients[task['band']]  
  task['match_proximity'] = 2.5 * task['seeing']
  logger.info('--> %5.2f counts: Sky noise, corrected for drizzle imcombine' % task['skynoise'])
  logger.info('--> %5.2f Median count value, after background subtraction' % task['datamean'])
  logger.info('--> %5.2f Airmass' % task['airmass'])

  #prepare temp files that iraf will use
  for filename in ('photfile','pstfile','psfimg','opstfile','groupfile','allstarfile','rejfile','subimage'): 
    task[filename] = open(os.path.join(task['output_directory'],filename),'w')
    task[filename].close()

  #iraf.phot to get APP magnitudes
  logger.info('Running iraf.apphot.phot')
  #apsizes = [i*task['faperture']*task['seeing'] for i in (0.4,0.5,0.6,0.8,1.0,1.2,1.5,2.0,2.5,3.0)]
  #irafapsizes = ','.join(['%.2f' % i for i in apsizes])
  irafapsizes = '%0.2f' % (task['faperture']*task['seeing'])
  kwargs = dict(image=task['images'],coords=task['objectlist'].name,
    output=task['photfile'].name,
    interac='no',scale=1,
    fwhmpsf=task['seeing'], 
    wcsin='world', wcsout='physical',
    sigma=task['skynoise'],
    datamin=task['datamin'],
    datamax=task['datamax'],
    readnoi=task['ron'],
    epadu=task['gain'],
    itime=task['exposure'],
    xairmass=task['airmass'],
    ifilter=task['band'],
    otime=task['dateobs'],
    aperture= irafapsizes,
    zmag=task['zmag'],
    annulus=task['fannulus']*task['seeing'],
    dannulus=task['fdannulus']*task['seeing'],
    calgorithm='gauss',
    cbox = 1.5*task['seeing'],
    maxshift=2.0*task['seeing'],
    mode="h",Stdout=1,verify=0)
  iraf.phot(**kwargs)

  if task['band'] not in constants.infrared:
    #iraf.pstselect to choose objects for PSF modelling
    logger.info('Running iraf.daophot.pstselect')
    kwargs = dict(image=task['images'],
                     photfile=task['photfile'].name,pstfile=task['pstfile'].name,
                     maxnpsf=task['pstnumber'],
                     wcsin='physical',
                     wcsout='physical',
                     interac="no",verify='no',scale=1,
                     fwhmpsf=task['seeing'],
                     datamin=0,
                     datamax=task['datamax'],
                     psfrad=3.0*task['seeing'],
                     fitrad=1.0*task['seeing'],
                     recente='yes',
                     nclean=task['nclean'],
                     mode="h",Stdout=1)
    iraf.pstselect(**kwargs)

    #iraf.psf to model PSF
    logger.info('Running iraf.daophot.psf')
    kwargs = dict( image=task['images'],
              photfile=task['photfile'].name,
              pstfile=task['pstfile'].name,
              psfimage=task['psfimg'].name,
              opstfile=task['opstfile'].name,
              groupfile=task['groupfile'].name,
              wcsin='physical',wcsout='physical',
              interac="no",verify="no",scale=1,
              fwhmpsf=task['seeing'],
              sigma=task['skynoise'],
              datamin=task['datamin'],
              datamax=task['datamax'],
              readnoi=task['ron'],
              epadu=task['gain'],
              itime=task['exposure'],
              xairmass=task['airmass'],
              ifilter=task['band'],
              otime=task['dateobs'],
              function=task['func'],
              varorder=task['varorder'],
              saturat='no',
              psfrad=3.0*task['seeing'],
              fitrad=1.*task['faperture']*task['seeing'],
              nclean=task['nclean'],
              mergerad=1.5*task['seeing'],
              mode='h',Stdout=1)  

    iraf.psf(**kwargs)
    logger.info('Running iraf.daophot.allstar')
    #iraf.allstars to compute PSF photometry; recenter with recenter='yes', mergerad=<value> to avoid duplicate detection
    kwargs = dict(image=task['images'],
                  photfile=task['photfile'].name,
                  wcsin='physical',
                  wcsout='physical',
                  psfimage=task['psfimg'].name,
                  allstarf=task['allstarfile'].name,
                  rejfile=task['rejfile'].name,
                  subimage=task['subimage'].name,
                  verbose=1,verify='no',scale=1,
                  fwhmpsf=task['seeing'],
                  sigma=task['skynoise'],
                  datamin=task['datamin'],
                  datamax=task['datamax'],
                  readnoi=task['ron'],
                  epadu=task['gain'],
                  itime=task['exposure'],
                  xairmass=task['airmass'],
                  ifilter=task['band'],
                  otime=task['dateobs'],
                  function=task['func'],
                  varorder=task['varorder'],
                  psfrad=3.*task['seeing'],
                  fitrad=1.*task['faperture']*task['seeing'],
                  recenter='yes',
                  mergerad=1.5*task['seeing'],
                  mode='h',Stdout=1)
    iraf.allstar(**kwargs)
  

  #Parse both photometry, convert to RA,DEC,MAG,MAGERR
  logger.info('iraf tasks complete. Parsing results and calibrating')
  photometry = {}
  photometry['APP'] = iraf.txdump(textfiles=task['photfile'].name,
                        fields='XCENTER,YCENTER,MAG,MERR',expr='yes',
                        headers='no',Stdout=1)

  if task['band'] not in constants.infrared:
    photometry['PSF'] = iraf.txdump(textfiles=task['allstarfile'].name,
                          fields='XCENTER,YCENTER,MAG,MERR',expr='yes',
                          headers='no',Stdout=1)


  for phototype in photometry:
    kwargs = dict(input='STDIN',
                  output='STDOUT',
                  insystem='%s physical' % task['images'],
                  outsystem='%s world' % task['images'],
                  ilatuni='physical',
                  ilnguni='physical',
                  olnguni='degrees',
                  olatuni='degrees',
                  ilngfor='%10.7f',
                  ilatfor='%10.7f',
                  olngfor='%10.5f',
                  olatfor='%10.5f',
                  Stdin=photometry[phototype],Stdout=1)
    photometry[phototype] = [i.split() for i in iraf.skyctran(**kwargs) if i and not i.startswith('#') and 'INDEF' not in i]
    photometry[phototype] = [map(float,(i[4],i[5],i[2],i[3])) for i in photometry[phototype] ] #Now we have [(ra,dec,'mag','mageerr'),...]
  results = calibrate((task['objwcs'][0],task['objwcs'][1]),task,photometry,logger)
#  if 'PSF' not in results:
    
  return results
Example #9
0
def psfphot(image,
            coofile,
            ot,
            wtimage="",
            varorder=1,
            clobber=globclob,
            verbose=globver,
            pixtol=3.0,
            maxnpsf=25):
    """ 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()
    iraf.digiphot()
    iraf.daophot()

    # Detect stars
    iqobjs("%s.sub.fits" % image[:-5],
           1.5,
           12000.0,
           wtimage=wtimage,
           skyval="0.0")

    root = image[:-5]
    [gain, rnoise, fwhm] = get_head(image, ["GAIN", "READN", "SEEPIX"])
    fwhm = float(fwhm)
    rnoise = float(rnoise)

    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.50 * saturate
    iraf.datapars.readnoise = rnoise
    iraf.datapars.epadu = gain
    iraf.daopars.psfrad = psfmult * fwhm
    iraf.daopars.fitrad = fwhm
    iraf.daopars.function = "gauss,moffat15,moffat25,lorentz,penny1"
    iraf.daopars.varorder = varorder

    # Reference stars file
    stars = Starlist(coofile)
    stars.wcs2pix(image)
    outf = open("%s.coo.1" % image[:-5], "w")
    for star in stars:
        outf.write("%10.3f%10.3f\n" % (star.xval, star.yval))
    outf.close()

    #Aperture photometry
    iraf.daophot.phot(root,
                      'default',
                      'default',
                      apertures=fwhm,
                      verify=no,
                      interac=no,
                      verbose=verbose)

    iraf.datapars.datamax = 0.50 * saturate
    iraf.pstselect(root,
                   'default',
                   'default',
                   maxnpsf,
                   interactive=no,
                   verify=no,
                   verbose=verbose)

    iraf.psf(root,
             'default',
             'default',
             'default',
             'default',
             'default',
             interactive=no,
             showplots=no,
             verify=no,
             verbose=verbose)

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

    # Prep for subtracted image
    iraf.iterstat("%s.sub.fits" % root)

    iraf.datapars.sigma = iraf.iterstat.sigma
    iraf.datapars.datamin = iraf.iterstat.median - 10 * iraf.iterstat.sigma
    iraf.datapars.datamax = saturate

    # Look for source at OT location
    substars = Starlist("%s.sub.fits.stars" % image[:-5])
    otstars = Starlist(ot)
    otstars.wcs2pix("%s.sub.fits" % image[:-5])
    smatch, omatch = substars.match(otstars, tol=pixtol, useflags=no)

    # Generate coo file
    otcoo = open("%s.sub.coo.1" % image[:-5], "w")

    if len(smatch) == 0:
        otcoo.write("%10.3f%10.3f\n" % (otstars[0].xval, otstars[0].yval))
    else:
        otcoo.write("%10.3f%10.3f\n" % (smatch[0].xval, smatch[0].yval))

    otcoo.close()

    iraf.daophot.phot("%s.sub.fits" % root,
                      "%s.sub.coo.1" % image[:-5],
                      'default',
                      'default',
                      apertures=fwhm,
                      calgorithm="none",
                      interac=no,
                      verify=no,
                      verbose=verbose)

    if len(smatch) == 0:
        print "No match in subtracted image: %s.sub.fits" % root
    else:
        iraf.allstar("%s.sub.fits" % root,
                     'default',
                     "%s.psf.1.fits" % root,
                     'default',
                     'default',
                     'default',
                     verify=no,
                     verbose=no)

        return
Example #10
0
def fitsn(img,imgpsf,coordlist,_recenter,fwhm0,original,sn,residual,_show,_interactive,dmax,dmin,z11='',z22='',midpt='',size=7,apco0=0):
    import lsc
    lsc.util.delete("apori")
    lsc.util.delete(img+".sn.mag")
#################################
    from pyraf import iraf
    import string
    iraf.imcoords(_doprint=0)
    iraf.digiphot(_doprint=0)
    iraf.daophot(_doprint=0)
    from iraf import digiphot
    from iraf import daophot
    from iraf import ptools
    a1 = int(fwhm0)
    a2 = int(2.*fwhm0+.5)
    a3 = int(3.*fwhm0+.5)
    a4 = int(4.*fwhm0+.5)
    ap = str(a1)+","+str(a2)+","+str(a3)
########################################
    if _recenter:        answ='yes'
    else:                answ='no'
#########################################
    hdr=lsc.util.readhdr(img+'.fits')
    _gain=lsc.util.readkey3(hdr,'gain')
    _ron=lsc.util.readkey3(hdr,'ron')
    _exptime=lsc.util.readkey3(hdr,'exptime')
    iraf.noao.digiphot.daophot.photpars.zmag = 0
    iraf.noao.digiphot.daophot.datapars.readnoi = _gain
    iraf.noao.digiphot.daophot.datapars.epadu = _ron
    iraf.noao.digiphot.daophot.datapars.datamin = dmin
    iraf.noao.digiphot.daophot.datapars.datamax = dmax
    iraf.noao.daophot.fitskypars.annulus=a3
    iraf.noao.daophot.photpars.apertures = ap
    iraf.noao.digiphot.daophot.datapars.exposure = 'exptime'
    iraf.noao.digiphot.daophot.datapars.airmass = 'airmass'
    iraf.noao.digiphot.daophot.datapars.filter = 'filter2'
    iraf.noao.digiphot.daophot.daopars.psfrad = a4
    #  modify fitrad to 3 fwhm to see if works better     
    iraf.noao.digiphot.daophot.daopars.fitrad = fwhm0 #* 3
    iraf.noao.digiphot.daophot.daopars.sannulus = int(a4)
    iraf.noao.digiphot.daophot.daopars.recenter = answ
    iraf.noao.digiphot.daophot.daopars.fitsky = 'yes'
#    iraf.noao.digiphot.daophot.centerpars.cbox = 0
    iraf.noao.digiphot.daophot.centerpars.cbox = 4
    iraf.noao.digiphot.daophot.centerpars.calgori = 'gauss'

    #  fitskypars.salgorithm = "constant"
    #  fitskypars.skyvalue = 0
    print '\n### recentering: '+str(answ)
    if _show:
        iraf.noao.digiphot.daophot.phot(original,coordlist,"apori",veri='no')   
        iraf.noao.digiphot.daophot.phot(sn,coordlist,img+".sn.mag",veri='no')   
    else:
        iraf.noao.digiphot.daophot.phot(original,coordlist,"apori",veri='no',verb='no')   
        iraf.noao.digiphot.daophot.phot(sn,coordlist,img+".sn.mag",veri='no',verb='no')   

    lsc.util.delete(img+".sn.als")
    print sn,imgpsf,img
    iraf.allstar(sn,img+".sn.mag",imgpsf,img+".sn.als","",residual,veri='no',verb='no')
    lsc.util.delete("snfit.fits")
    iraf.imarith(sn+'.fits',"-",residual+'.fits',"snfit.fits")
    lsc.util.delete("skyfit.fits")
    iraf.imarith(original+'.fits',"-","snfit.fits","skyfit.fits")
    iraf.txsort(img+".sn.als","ID")
    tmptbl = iraf.txdump(img+".sn.als","mag,merr,xcenter,ycenter",expr='yes', Stdout=1)
    magerr,fitmag,centx,centy=[],[],[],[]
    for i in tmptbl:
        try:
            fitmag.append(float(string.split(i)[0]))#-2.5*log10(_exptime))
        except:
            fitmag.append(string.split(i)[0])
        try:
            magerr.append(float(string.split(i)[1]))
        except:
            magerr.append(string.split(i)[1])
        centx.append(float(string.split(i)[2]))
        centy.append(float(string.split(i)[3]))
    tmptbl=iraf.txdump("apori","mag",expr='yes', Stdout=1)
    apori1,apori2,apori3=[],[],[]
    for i in tmptbl:
        try:
            apori1.append(float(string.split(i)[0]))#-2.5*log10(_exptime))
        except:
            apori1.append(string.split(i)[0])
        try:            
            apori2.append(float(string.split(i)[1]))#-2.5*log10(_exptime))
        except:
            apori2.append(string.split(i)[1])
        try:
            apori3.append(float(string.split(i)[2]))#-2.5*log10(_exptime))
        except:
            apori3.append(string.split(i)[2])
            
    iraf.txsort(img+".sn.mag","YCENTER")
    tmptbl=iraf.txdump(img+".sn.mag","mag,magerr",expr='yes', Stdout=1) 

    if _show:
        print "********************************************************************"
        print "ID <apmag on original>  <apmag on bgsubt> fitmag truemag err_fit"         
        print "     ",a1,"       ",a2,"      ",a3,"        ",a1,"     ",a2,"     ",a3 


    apmag1,apmag2,apmag3,truemag=[],[],[],[]
    for i in range(len(tmptbl)):
        try:
            apmag1.append(float(string.split(tmptbl[i])[0]))#-2.5*log10(_exptime))
        except:
            apmag1.append(9999)
        try:
            apmag2.append(float(string.split(tmptbl[i])[1]))#-2.5*log10(_exptime))
        except:
            apmag2.append(9999)
        try:
            apmag3.append(float(string.split(tmptbl[i])[2]))#-2.5*log10(_exptime))
        except:
            apmag3.append(9999)
        try:
            truemag.append(fitmag[i]+float(apco0))
        except:
            truemag.append('INDEF')
        if _show:
            print i,apori1[i],apori2[i],apori3[i],apmag1[i],apmag2[i],apmag3[i],fitmag[i],truemag[i],magerr[i]
    if _show:
        print "********************************************************************"

    if _show:
        print midpt,z11,z22
        _tmp1,_tmp2,goon=lsc.util.display_image(original+'.fits',1, z11, z22, False, _xcen=.25, _ycen=.25, _xsize=.3, _ysize=.3)
        z01 = float(z11)-float(midpt)
        z02 = float(z22)-float(midpt) 
        s1 = 1
        s2 = -int(fwhm0)
        lsc.util.delete("tmptbl")
        ff=open('tmptbl','w')
        ff.write(str(s1)+' '+str(s2)+" ORIGINAL")
        ff.close()    
        iraf.tvmark(1,"tmptbl",autol='no',mark="none",inter='no',label='yes',txsize=2)
        _tmp1,_tmp2,goon=lsc.util.display_image('snfit.fits',1, z01, z02, False, _xcen=.25, _ycen=.75, _xsize=.3, _ysize=.3, _erase='no')
        lsc.util.delete("tmptbl")
        tmptbl0=iraf.txdump(img+".sn.als","xcen,ycen",expr='yes',Stdout=1)
        ff=open('tmptbl','w')
        for i in tmptbl0:
            ff.write(i+'\n')
        ff.close()    
        lra = int((2*float(size)*float(fwhm0))*2)
        iraf.tvmark(1,"tmptbl",autol='no',mark="circle", number='yes',nyoffset=lra,radi=a2,txsize=2,inter='no')
        s1 = 1
        s2 = -1*int(fwhm0)
        lsc.util.delete("tmptbl")
        ff=open('tmptbl','w')
        ff.write(str(s1)+' '+str(s2)+" FITTED")
        ff.close()    
        iraf.tvmark(1,"tmptbl",autol='no',mark="none",inter='no',label='yes',txsize=2)
        _tmp1,_tmp2,goon=lsc.util.display_image('skyfit.fits',1, z11, z22, False, _xcen=.75, _ycen=.25, _xsize=.3, _ysize=.3, _erase='no')
        s1 = 1
        s2 = -1*int(fwhm0)
        lsc.util.delete("tmptbl")
        ff=open('tmptbl','w')
        ff.write(str(s1)+' '+str(s2)+" RESIDUAL")
        ff.close()    
        iraf.tvmark(1,"tmptbl",autol='no',mark="none",inter='no',label='yes',txsize=2)
    return apori1,apori2,apori3,apmag1,apmag2,apmag3,fitmag,truemag,magerr,centx,centy
Example #11
0
        print "...merging phot lists"
        print "========================================="
        iraf.pfmerge(inphotfi=str(flnm + '.sub.' + str(i - 1) + '.als' + ',' +
                                  runnm + '.mag'),
                     outphotf=runnm + '.tot.mag')
        iraf.prenumber(runnm + '.tot.mag')

    print "========================================="
    print "...running allstar for", runnm + '.fits'
    print "========================================="
    iraf.daopars.setParam('recenter', 'yes')
    tas = time.time()
    iraf.allstar(image=initimg,
                 photfile=runnm + '.tot.mag',
                 psfimage=flnm + '.psf.fits',
                 allstarf=runnm + '.als',
                 rejfile=runnm + '.arj',
                 subimage=flnm + '.sub.' + str(i + 1) + '.fits',
                 cache='no',
                 verify='no')  # ALLSTAR on original sub.0
    tae = time.time()
    times[runnm + '_allstar'] = tae - tas

    # removing the merged phot file (not needed for analysis)
    os.remove(runnm + '.tot.mag')

    print "\n>>> END OF DAOLOOP #" + str(i)

# Creating the total list of positions for all stars (after running allstar) for input in other routines (e.g. Ha photometry)
transform(str(runnm) + ".als", str(flnm) + ".final.list.coo")

# Printing parameters to check
Example #12
0
    pstfile.write("#U ##    pixels    pixels    magnitudes  counts                                \\\n")
    pstfile.write("#F %-9d  %-10.3f   %-10.3f   %-12.3f     %-15.7g                                 \n")
    pstfile.write("#\n")
    np.savetxt(pstfile,g.take([-1,0,1,2,3],axis=1),fmt=['%-9d','%-10.3f','%-10.3f','%-12.3f','%-15.7g'])
    pstfile.close()

    iraf.daopars.setParam('matchra',fwhm)
    iraf.daopars.setParam('psfrad',4*fwhm+1)
    iraf.daopars.setParam('fitrad',fwhm)
    iraf.daopars.setParam('sannulu',2*fwhm)
    iraf.daopars.setParam('wsannul',4*fwhm)
    iraf.psf.setParam('image',FitsFileName)
    iraf.psf(mode='h')
    iraf.seepsf(psfimage=FitsFileName+'.psf.1.fits',image=base+'psfim'+ext+'.fits',magnitu='18.0')
    iraf.allstar.setParam('image',FitsFileName)
    iraf.allstar(mode='h',verbose='no')

    if os.path.exists(base+'allstartmp') == True: os.remove(base+'allstartmp')
    iraf.txdump(textfile=FitsFileName+'.als.1',fields='xcenter,ycenter,mag,merr,id',expr='mag\
    != INDEF && merr != INDEF', Stdout=base+'allstartmp')
    outmags = np.loadtxt(base+'allstartmp')
    if os.path.exists(base+'allstartmp') == True: os.remove(base+'allstartmp')

    if int(ext) <= 4:
        shifty = 0.0
        shiftx = (float(ext) - 1.)*sx
    else:
        shifty = sy
        shiftx = (float(ext) - 5.)*sx

    outmags[:,0] = outmags[:,0] + shiftx
Example #13
0
def errore(size, truemag, fwhm0, leng0):
    from pyraf import iraf
    import string, os, sys

    dartf = 100
    while dartf >= size - 1:
        artfac0 = raw_input(
            '>>> Dispersion of artificial star positions (in units of FWHM) [1] '
        )
        if not artfac0: artfac0 = 1
        try:
            artfac0 = float(artfac0)
            if float(artfac0) >= size - 1:
                print '!!! WARNING: ' + str(
                    artfac0) + ' too large (max ' + str(size) + '- 1)'
                print 'try again....'
            else:
                dartf = artfac0
        except:
            print '#### WARNING: ' + str(artfac0) + ' should be a number !!!!'
            print 'try again....'
    iraf.delete("tmpar?", ve='no')
    i = 0
    tmpart = []
    while i <= 8:
        iraf.delete(
            "reserr.fit?,artbg.fit?,artstar.fit?,artres.fit?,artfit.fit?,artskyfit.fit?",
            ve='no')
        artrad = fwhm0 / 2.
        #artseed = artseed+1234
        artx = int(i / 3.) - 1
        if i <= 2: arty = artx + i
        if 3 <= i <= 5: arty = artx - 1 + i - 3
        if i >= 6: arty = artx - 2 + i - 6

        ff = open(img + ".sn.coo", 'r')
        ss = ff.readline()
        ff.close()
        xbb = float(string.split(ss)[0])
        ybb = float(string.split(ss)[1])

        xbb = xbb + artx * fwhm0 * artfac0
        ybb = ybb + arty * fwhm0 * artfac0
        print xbb, ybb

        iraf.delete("artlist.coo", ve='no')
        ff = open("artlist.coo", 'w')
        ff.write(str(xbb) + '  ' + str(ybb) + '  ' + str(truemag[0]) + "  1")
        ff.close()

        xb1 = int(float(xbb) - fwhm0 * float(leng0) / 2)
        xb2 = int(float(xbb) + fwhm0 * float(leng0) / 2)
        yb1 = int(float(ybb) - fwhm0 * float(leng0) / 2)
        yb2 = int(float(ybb) + fwhm0 * float(leng0) / 2)
        sec = "1 " + str(xb1) + " 1 " + str(nay) + '\n'
        sec = sec + str(xb2) + ' ' + str(nax) + " 1 " + str(nay) + '\n'
        sec = sec + str(xb1) + ' ' + str(xb2) + " 1 " + str(yb1) + '\n'
        sec = sec + str(xb1) + ' ' + str(xb2) + ' ' + str(yb2) + ' ' + str(
            nay) + '\n'
        ff = open('sec', 'w')
        ff.write(sec)
        ff.close()

        iraf.delete("reserr.art", ve='no')
        iraf.delete("artlist.mag", ve='no')
        iraf.delete("artlist.als", ve='no')
        iraf.addstar("skyfit",
                     "artlist.coo",
                     imgpsf,
                     "reserr",
                     nstar=1,
                     veri='no',
                     simple='yes')
        iraf.imsurfit("reserr",
                      "artbg",
                      xorder=xbgord0,
                      yorder=ybgord0,
                      regions="section",
                      section="sec")
        iraf.imarith("reserr", "-", "artbg", "artstar")
        iraf.phot("artstar", "artlist.coo", "artlist.mag", veri='no')
        iraf.allstar("artstar",
                     "artlist.mag",
                     imgpsf,
                     "artlist.als",
                     "",
                     "artres",
                     veri='no',
                     verb='no')
        iraf.imarith("artstar", "-", "artres", "artfit")
        iraf.imarith("reserr", "-", "artfit", "artskyfit")
        if i == 0: era = 'yes'
        else: era = 'no'
        artx = .5 + .25 * artx
        arty = .5 + .25 * arty
        iraf.display("artskyfit",
                     1,
                     fill='yes',
                     erase=era,
                     xcen=artx,
                     ycen=arty,
                     xsize=.25,
                     ysize=.25)
        try:
            tmpart.append(
                float(
                    iraf.txdump("artlist.als", "mag", expr='yes',
                                Stdout=1)[0]))
        except:
            pass
        i = i + 1

    for i in tmpart:
        print i

    print " ########## "
    try:
        media = mean(array(tmpart))
        arterr = std(array(tmpart))
        arterr2 = std(
            compress((average(tmpart) - std(tmpart) < array(tmpart)) &
                     (array(tmpart) < average(tmpart) + std(tmpart)),
                     array(tmpart)))
    except:
        media = 0
        arterr = 0
        arterr2 = 0
    print '### average = %6.6s \t arterr= %6.6s ' % (str(media), str(arterr))
    print '###  %6.6s \t (error at 1 sigma rejection) ' % (str(arterr2))
    iraf.delete(
        "reserr.fit?,artbg.fit?,artstar.fit?,artres.fit?,artfit.fit?,artskyfit.fit?",
        ve='no')
    iraf.delete("reserr.art", ve='no')
    iraf.delete("artlist.*", ve='no')
    return arterr2, arterr
Example #14
0
            (mag1['ID'][ind[0]], mag1['XINIT'][ind[0]], mag1['YINIT'][ind[0]],
             mag1['MAG'][ind[0]], mag1['MSKY'][ind[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:
Example #15
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)
Example #16
0
def psfphot(image,
            clobber=globclob,
            verbose=globver,
            pixtol=3.0,
            maxnpsf=5,
            interact=yes):
    """ 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()

    # Detect stars
    iqpkg.iqobjs(image, 3.0, 50000.0, wtimage="", skyval="!MEDSKY")

    root = image[:-5]
    [gain, rnoise, fwhm] = get_head(image, ["GAIN", "READNOI", "SEEPIX"])
    fwhm = float(fwhm)
    rnoise = float(rnoise)

    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 = 70000.0
    iraf.datapars.readnoise = rnoise
    iraf.datapars.epadu = gain
    iraf.daopars.psfrad = psfmult * fwhm
    iraf.daopars.fitrad = fwhm
    iraf.daopars.function = "gauss,moffat15,moffat25,lorentz,penny1"

    # coo file
    stars = Starlist("%s.stars" % image)
    outf = open("%s.coo.1" % image[:-5], "w")
    for star in stars:
        outf.write("%10.3f%10.3f\n" % (star.xval, star.yval))
    outf.close()

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

    iraf.datapars.datamax = 30000.0
    iraf.pstselect(root,
                   'default',
                   'default',
                   maxnpsf,
                   interactive=yes,
                   verify=no,
                   verbose=verbose)

    iraf.psf(root,
             'default',
             'default',
             'default',
             'default',
             'default',
             interactive=interact,
             verify=no,
             verbose=verbose)

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

    iraf.iterstat("%s.sub.fits" % root)

    iraf.datapars.sigma = iraf.iterstat.sigma
    iraf.datapars.datamin = iraf.iterstat.median - 10 * iraf.iterstat.sigma

    iraf.datapars.datamax = 70000.0
    iraf.daophot.phot("%s.sub.fits" % root,
                      "SN.coo",
                      'default',
                      'default',
                      aperture=fwhm,
                      verify=no,
                      verbose=verbose)

    iraf.datapars.datamax = 30000.0
    iraf.daopars.fitrad = fwhm * 2.0
    iraf.allstar("%s.sub.fits" % root,
                 'default',
                 "%s.psf.1.fits" % root,
                 'default',
                 'default',
                 'default',
                 verify=no,
                 verbose=no)
Example #17
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)
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
Example #19
0
def fitsn(_recenter, img, imgpsf, fwhm0, apco0, z22, z11, midpt, size, nor,
          _values, DM):
    from pyraf import iraf
    import string, os, sys
    from numpy import log10

    a1 = int(fwhm0 + .5)
    a2 = int(2. * fwhm0 + .5)
    a3 = int(3. * fwhm0 + .5)
    a4 = int(4. * fwhm0 + .5)
    a5 = int(5. * fwhm0 + .5)
    ap = str(a1) + "," + str(a2) + "," + str(a3)

    iraf.digiphot(_doprint=0)
    iraf.daophot(_doprint=0)

    from iraf import digiphot
    from iraf import daophot
    from iraf import ptools

    zmag = 0
    iraf.noao.digiphot.daophot.photpars.zmag = zmag

    iraf.delete("apori", verify='no')
    iraf.delete(img + ".sn.mag", verify='no')
    iraf.noao.digiphot.daophot.phot("original",
                                    img + ".sn.coo",
                                    "apori",
                                    veri='no')
    iraf.noao.digiphot.daophot.phot("sn",
                                    img + ".sn.coo",
                                    img + ".sn.mag",
                                    veri='no')
    iraf.noao.digiphot.daophot.daopars.psfrad = a4
    iraf.noao.digiphot.daophot.daopars.fitrad = fwhm0
    iraf.noao.digiphot.daophot.daopars.fitsky = 'no'
    iraf.noao.digiphot.daophot.daopars.sannulus = int(a4)

    if _recenter:
        answ = raw_input(">>> recentering for targets [yes/no] ? [yes] ")
        if not answ: answ = 'yes'
    else:
        answ = 'yes'
    iraf.noao.digiphot.daophot.daopars.recenter = answ
    iraf.noao.digiphot.daophot.daopars.fitsky = 'yes'
    iraf.delete(img + ".sn.als", verify='no')
    iraf.allstar("sn",
                 img + ".sn.mag",
                 imgpsf,
                 img + ".sn.als",
                 "",
                 "residual",
                 veri='no',
                 verb='no')
    iraf.delete("snfit.fits", verify='no')
    iraf.imarith("sn", "-", "residual", "snfit")
    iraf.delete("skyfit.fits", verify='no')
    iraf.imarith("original", "-", "snfit", "skyfit")
    iraf.txsort(img + ".sn.als", "ID")
    tmptbl = iraf.txdump(img + ".sn.als",
                         "mag,merr,xcenter,ycenter",
                         expr='yes',
                         Stdout=1)
    magerr, fitmag, centx, centy = [], [], [], []
    for i in tmptbl:
        try:
            fitmag.append(float(string.split(i)[0]))  #+2.5*log10(nor))
        except:
            fitmag.append('INDEF')
        try:
            magerr.append(float(string.split(i)[1]))
        except:
            magerr.append('INDEF')

        centx.append(float(string.split(i)[2]))
        centy.append(float(string.split(i)[3]))
    tmptbl = iraf.txdump("apori", "mag", expr='yes', Stdout=1)
    apori1, apori2, apori3 = [], [], []
    for i in tmptbl:
        try:
            apori1.append(
                float(string.split(i)[0]) - float(_values) -
                float(DM))  #+2.5*log10(nor)
        except:
            apori1.append('INDEF')
        try:
            apori2.append(
                float(string.split(i)[1]) - float(_values) -
                float(DM))  #+2.5*log10(nor)
        except:
            apori2.append('INDEF')
        try:
            apori3.append(
                float(string.split(i)[2]) - float(_values) -
                float(DM))  #+2.5*log10(nor)
        except:
            apori3.append('INDEF')

    iraf.txsort(img + ".sn.mag", "YCENTER")
    tmptbl = iraf.txdump(img + ".sn.mag", "mag,magerr", expr='yes', Stdout=1)

    print "********************************************************************"
    print "ID <apmag on original>  <apmag on bgsubt> fitmag truemag err_fit"
    print "     ", a1, "       ", a2, "      ", a3, "        ", a1, "     ", a2, "     ", a3

    apmag1, apmag2, apmag3, truemag = [], [], [], []
    for i in range(len(tmptbl)):
        try:
            apmag1.append(
                float(string.split(tmptbl[i])[0]) - float(_values) -
                float(DM))  #+2.5*log10(nor)
        except:
            apmag1.append('INDEF')
        try:
            apmag2.append(
                float(string.split(tmptbl[i])[1]) - float(_values) -
                float(DM))  #+2.5*log10(nor)
        except:
            apmag2.append('INDEF')
        try:
            apmag3.append(
                float(string.split(tmptbl[i])[2]) - float(_values) -
                float(DM))  #+2.5*log10(no)
        except:
            apmag3.append('INDEF')
        try:
            truemag.append(
                float(fitmag[i]) + float(apco0) + 2.5 * log10(nor) -
                float(_values) - float(DM))
        except:
            truemag.append('INDEF')
        print i, apori1[i], apori2[i], apori3[i], apmag1[i], apmag2[i], apmag3[
            i], fitmag[i], truemag[i], magerr[i]

    print "********************************************************************"

    iraf.display("original",
                 1,
                 fill='yes',
                 xcen=.25,
                 ycen=.25,
                 xsize=.3,
                 ysize=.3,
                 zscal='no',
                 zrang='no',
                 z2=z22,
                 z1=z11)

    z01 = z11 - midpt
    z02 = z22 - midpt
    s1 = 1
    s2 = -int(fwhm0)
    iraf.delete("tmptbl", ve='no')
    ff = open('tmptbl', 'w')
    ff.write(str(s1) + ' ' + str(s2) + " ORIGINAL")
    ff.close()
    iraf.tvmark(1,
                "tmptbl",
                autol='no',
                mark="none",
                inter='no',
                label='yes',
                txsize=2)

    iraf.display("snfit",
                 1,
                 erase='no',
                 fill='yes',
                 xcen=.25,
                 ycen=.75,
                 xsize=.3,
                 ysize=.3,
                 zscal='no',
                 zrang='no',
                 z2=z02,
                 z1=z01)
    iraf.delete("tmptbl", ve='no')
    tmptbl0 = iraf.txdump(img + ".sn.als", "xcen,ycen", expr='yes', Stdout=1)
    ff = open('tmptbl', 'w')
    for i in tmptbl0:
        ff.write(i + '\n')
    ff.close()
    lra = int((2 * float(size) * float(fwhm0)) * 2)
    iraf.tvmark(1,
                "tmptbl",
                autol='no',
                mark="circle",
                number='yes',
                nyoffset=lra,
                radi=a2,
                txsize=2,
                inter='no')
    s1 = 1
    s2 = -1 * int(fwhm0)
    iraf.delete("tmptbl", ve='no')
    ff = open('tmptbl', 'w')
    ff.write(str(s1) + ' ' + str(s2) + " FITTED")
    ff.close()
    iraf.tvmark(1,
                "tmptbl",
                autol='no',
                mark="none",
                inter='no',
                label='yes',
                txsize=2)

    iraf.display("skyfit",
                 1,
                 erase='no',
                 fill='yes',
                 xcen=.75,
                 ycen=.25,
                 xsize=.3,
                 ysize=.3,
                 zscal='no',
                 zrang='no',
                 z2=z22,
                 z1=z11)
    s1 = 1
    s2 = -1 * int(fwhm0)
    iraf.delete("tmptbl", ve='no')
    ff = open('tmptbl', 'w')
    ff.write(str(s1) + ' ' + str(s2) + " RESIDUAL")
    ff.close()
    iraf.tvmark(1,
                "tmptbl",
                autol='no',
                mark="none",
                inter='no',
                label='yes',
                txsize=2)
    print '###'
    print '### magnitude scaled to target exposure time using: ' + str(
        2.5 * log10(nor))
    print '### fit magnitude corrected with aperture correction: ' + str(
        float(apco0))
    print '### magnitude scaled to target using DM: ' + str(DM)
    print '###'
    return apori1, apori2, apori3, apmag1, apmag2, apmag3, fitmag, truemag, magerr, centx, centy