示例#1
0
def ecpsf(img, ofwhm, threshold, psfstars, distance, interactive, ds9, psffun='gauss', fixaperture=False, _catalog='', _datamax=None, show=False):
    try:
        import lsc, string

        hdr = lsc.util.readhdr(img + '.fits')
        instrument = lsc.util.readkey3(hdr, 'instrume')
        print 'INSTRUMENT:', instrument

        if 'PIXSCALE' in hdr:
            scale = lsc.util.readkey3(hdr, 'PIXSCALE')
        elif 'CCDSCALE' in hdr:
            if 'CCDXBIN' in hdr:
                scale = lsc.util.readkey3(hdr, 'CCDSCALE') * lsc.util.readkey3(hdr, 'CCDXBIN')
            elif 'CCDSUM' in hdr:
                scale = lsc.util.readkey3(hdr, 'CCDSCALE') * int(string.split(lsc.util.readkey3(hdr, 'CCDSUM'))[0])

        if _datamax is None and 'kb' in instrument:
            _datamax = 45000
        elif _datamax is None:
            _datamax = 65000
        _wcserr = lsc.util.readkey3(hdr, 'wcserr')
        print _wcserr
        if float(_wcserr) == 0:
            if 'L1FWHM' in hdr:
                seeing = float(lsc.util.readkey3(hdr, 'L1FWHM'))
            elif 'L1SEEING' in hdr:
                seeing = float(lsc.util.readkey3(hdr, 'L1SEEING')) * scale
            else:
                seeing = 3
        else:
            seeing = 3
            if 'PSF_FWHM' in hdr:
                seeing = float(lsc.util.readkey3(hdr, 'PSF_FWHM'))
            else:
                sys.exit('astrometry not good')
        #except:  sys.exit('astrometry not good')

        fwhm = seeing / scale
        print 'FWHM[header]  ', fwhm, '   in pixel'
        if ofwhm: fwhm = float(ofwhm)
        print '    FWHM[input]  ', fwhm, ' in pixel'

        xdim, ydim = iraf.hselect(img+'[0]', 'i_naxis1,i_naxis2', 'yes', Stdout=1)[0].split()
        print img, fwhm, threshold, scale,xdim

        #################################################################################
        ###################        write file to compute psf     _psf.coo    ############
        #################################################################################
        if interactive:
            iraf.display(img, 1, fill=True)
            iraf.delete('tmp.lo?', verify=False)
            print '_' * 80
            print '>>> Mark reference stars with "a". Then "q"'
            print '-' * 80
            iraf.imexamine(img, 1, wcs='logical', logfile='tmp.log', keeplog=True)
            xyrefer = iraf.fields('tmp.log', '1,2,6,15', Stdout=1)
            xns, yns, _fws = [], [], []
            #############      write    file for PSF                           #########################
            ff = open('_psf.coo', 'w')
            for i in range(len(xyrefer)):
                xns.append(float(xyrefer[i].split()[0]))
                yns.append(float(xyrefer[i].split()[1]))
                _fws.append(float(xyrefer[i].split()[3]))
                ff.write('%10.3f %10.3f %7.2f \n' % (xns[i], yns[i], float(_fws[i])))
            ff.close()
            fwhm = np.median(_fws)
        elif _catalog:
            print '\n#### use catalog to measure the psf'
            ddd=iraf.wcsctran(input=_catalog,output='STDOUT',Stdout=1,image=img + '[0]',inwcs='world',outwcs='logical',
                              units='degrees degrees',columns='1 2',formats='%10.1f %10.1f',verbose='no')
            ddd=[i for i in ddd if i[0]!='#']
            ddd=['  '.join(i.split()[0:3]) for i in ddd]
            line=''
            for i in ddd:
                a,b,c = string.split(i)
                if float(a) < float(xdim) and  float(b) < float(ydim) and float(b) > 0:
                    line = line + '%10s %10s %10s \n' % (a, b, c)
            if line:
                ff = open('_psf.coo', 'w')
                ff.write(line)
                ff.close()
            else:
                sys.exit('error: no catalog objects are in the field')
        else:
            ############              run  sextractor                #####################################
            xs, ys, ran, decn, magbest, classstar, fluxrad, bkg = runsex(img, fwhm, threshold, scale)
            tot = np.compress(abs(np.array(fluxrad) * 1.6 - fwhm) / fwhm < .5, fluxrad)
            if len(tot) < 5:
                print 'warning: fwhm from sexractor different from fwhm computed during pre-reduction'
                print 'try using option --fwhm xxx'

            ff = open('tmp.cursor', 'w')
            image_hdu = fits.open(img + '.fits')
            for i in range(len(xs)):
                _xs = np.delete(xs, i)
                _ys = np.delete(ys, i)
                dist2 = np.sqrt((_xs - xs[i]) ** 2 + (_ys - ys[i]) ** 2)
                ###########           cut  star, not near other object    ##########################
                if abs(fluxrad[i] * 1.6 - fwhm) / fwhm < .5 and min(dist2) > distance * fwhm:
                    x1, x2 = int(xs[i] - fwhm * 3), int(xs[i] + fwhm * 3)
                    y1, y2 = int(ys[i] - fwhm * 3), int(ys[i] + fwhm * 3)
                    if x1 < 1: x1 = 1
                    if y1 < 1: y1 = 1
                    if x2 > int(xdim):
                        x2 = int(xdim)
                    if y2 > int(ydim):
                        y2 = int(ydim)
                    fmax = np.max(image_hdu[0].data[y1-1:y2, x1-1:x2])
                ##########       cut saturated object               ########################
                    if float(fmax) < _datamax:  # not saturated
                        ff.write('%10.3f %10.3f 1 m \n' % (xs[i], ys[i]))
            ff.close()
            image_hdu.close()

            iraf.delete('tmp.lo?,tmp.sta?,tmp.gk?', verify=False)
            iraf.psfmeasure(img+'[0]', imagecur='tmp.cursor', logfile='tmp.log', radius=int(fwhm), iter=3,
                            display=False, StdoutG='tmp.gki')

            ff = open('tmp.log')
            righe = ff.readlines()
            xn = [float(righe[3].split()[1])]
            yn = [float(righe[3].split()[2])]
            _fw = [float(righe[3].split()[4])]
            for r in righe[4:-2]:
                if len(r) > 0:
                    xn.append(float(r.split()[0]))
                    yn.append(float(r.split()[1]))
                    _fw.append(float(r.split()[3]))
            print 'FWHM: ', righe[-1].split()[-1]
            print 80 * "#"
            ######
            ##############            eliminate double object identification         ###########################
            xns, yns, _fws = [xn[0]], [yn[0]], [_fw[0]]
            for i in range(1, len(xn)):
                if abs(xn[i] - xn[i - 1]) > .2 and abs(yn[i] - yn[i - 1]) > .2:
                    xns.append(xn[i])
                    yns.append(yn[i])
                    _fws.append(_fw[i])
            #########      write clean   file for PSF                           #########################
            fw = []
            ff = open('_psf.coo', 'w')
            for i in range(len(xns)):
                if abs(_fws[i] - fwhm) / fwhm < .3:
                    ff.write('%10.3f %10.3f %7.2f \n' % (xns[i], yns[i], float(_fws[i])))
                    fw.append(_fws[i])
            ff.close()  ## End automatic selection
        ######################################################################################
        ###################        write file of object to store in  fits table  #############
        ######################################################################################
        if interactive:
            xs, ys, ran, decn, magbest, classstar, fluxrad, bkg = runsex(img, fwhm, threshold, scale)
            ff = open('_psf2.coo', 'w')
            for i in range(len(xs)):
                ff.write('%10s %10s %10s \n' % (xs[i], ys[i], fluxrad[i]))
            ff.close()
        elif _catalog:
            ddd=iraf.wcsctran(input=_catalog,output='STDOUT',Stdout=1,image=img + '[0]',inwcs='world',outwcs='logical',
                              units='degrees degrees',columns='1 2',formats='%10.1f %10.1f',verbose='no')
            ddd=[i for i in ddd if i[0]!='#']
            ddd=['  '.join(i.split()[0:3]) for i in ddd]
            ff = open('_psf2.coo', 'w')
            for i in ddd:
                a,b,c = string.split(i)
                ff.write('%10s %10s %10s \n' % (a, b, c))
            ff.close()
        else:
            os.system('cp _psf.coo _psf2.coo')
#            dflux = fluxrad - np.median(fluxrad)
#            fstar = np.compress(dflux < np.std(fluxrad), fluxrad)
#################################################################################################################

        print 80 * "#"
        photmag, pst, fitmag = psffit(img, fwhm, psfstars, hdr, interactive, _datamax, psffun, fixaperture)

        photmag2, fitmag2 = psffit2(img, fwhm, psfstars, hdr, _datamax, psffun, fixaperture)

        radec = iraf.wcsctran(input='STDIN', output='STDOUT', Stdin=photmag,
                              Stdout=1, image=img + '[0]', inwcs='logical', outwcs='world', columns="1 2",
                              format='%13.3H %12.2h', min_sig=9, mode='h')[3:]

        radec2 = iraf.wcsctran(input='STDIN', output='STDOUT', Stdin=photmag2,
                               Stdout=1, image=img + '[0]', inwcs='logical', outwcs='world', columns="1 2",
                               format='%13.3H %12.2h', min_sig=9, mode='h')[3:]

        if ds9 == 0 and (interactive or show):
            iraf.set(stdimage='imt1024')
            iraf.display(img, 1, fill=True, Stdout=1)
            iraf.tvmark(1, coords='STDIN', mark='circle', radii=15, label=True, Stdin=photmag, nxoffset=5, nyoffset=5, txsize=2)
            iraf.tvmark(1, coords='STDIN', mark='circle', radii=35, label=False, Stdin=pst, color=208)
#            iraf.tvmark(1, coords='STDIN', mark='cross', length=35, label=False, Stdin=fitmag2, color=204)

        idpsf = []
        for i in range(len(pst)):
            idpsf.append(pst[i].split()[2])
        dmag = []
        for i in range(len(radec)):
            ra, dec, idph, magp2, magp3, magp4, merrp2, merrp3, merrp4 = radec[i].split()
            dmag.append(9.99)
            for j in range(len(fitmag)):
                raf, decf, idf, magf, magerrf = fitmag[j].split()
                if idph == idf and idph in idpsf and \
                                magp3 != 'INDEF' and magf != 'INDEF':
                    dmag[i] = float(magp3) - float(magf)
                    break

        _dmag = np.compress(np.array(dmag) < 9.99, np.array(dmag))

        print '>>> Aperture correction (phot)   %6.3f +/- %5.3f %3d ' % \
              (np.mean(_dmag), np.std(_dmag), len(_dmag))
        if len(_dmag) > 3:
            _dmag = np.compress(np.abs(_dmag - np.median(_dmag)) < 2 * np.std(_dmag), _dmag)
            print '>>>         2 sigma rejection)   %6.3f +/- %5.3f %3d  [default]' \
                  % (np.mean(_dmag), np.std(_dmag), len(_dmag))
            print '>>>     fwhm   %s  ' % (str(fwhm))
        for i in range(len(dmag)):
            if dmag[i] == 9.99:
                dmag[i] = ''
            else:
                dmag[i] = '%6.3f' % (dmag[i])

        exptime = lsc.util.readkey3(hdr, 'exptime')
        object = lsc.util.readkey3(hdr, 'object').replace(' ', '')
        filtro = lsc.util.readkey3(hdr, 'filter')

        #######################################
        rap, decp, magp2, magp3, magp4, smagf, merrp3, smagerrf = [], [], [], [], [], [], [], []
        rap0, decp0 = [], []
        for i in range(len(radec2)):
            aa = radec2[i].split()
            rap.append(aa[0])
            decp.append(aa[1])
            rap0.append(lsc.lscabsphotdef.deg2HMS(ra=aa[0]))
            decp0.append(lsc.lscabsphotdef.deg2HMS(dec=aa[1]))
            idp = aa[2]
            magp2.append(aa[3])
            magp3.append(aa[4])
            magp4.append(aa[5])
            merrp3.append(aa[7])
            _smagf, _smagerrf = 9999, 9999
            for j in range(len(fitmag2)):
                raf, decf, idf, magf, magerrf = fitmag2[j].split()
                if idf == idp:
                    _smagf = magf
                    _smagerrf = magerrf
                    break
            smagf.append(_smagf)
            smagerrf.append(_smagerrf)
        tbhdu = fits.BinTableHDU.from_columns(fits.ColDefs([fits.Column(name='ra', format='20A', array=np.array(rap)),
                                               fits.Column(name='dec', format='20A', array=np.array(decp)),
                                               fits.Column(name='ra0', format='E', array=np.array(rap0)),
                                               fits.Column(name='dec0', format='E', array=np.array(decp0)),
                                               fits.Column(name='magp2', format='E',
                                                           array=np.array(np.where((np.array(magp2) != 'INDEF'),
                                                                                   np.array(magp2), 9999), float)),
                                               fits.Column(name='magp3', format='E',
                                                               array=np.array(np.where((np.array(magp3) != 'INDEF'),
                                                                                       np.array(magp3), 9999), float)),
                                               fits.Column(name='merrp3', format='E',
                                                               array=np.array(np.where((np.array(merrp3) != 'INDEF'),
                                                                                       np.array(merrp3), 9999), float)),
                                               fits.Column(name='magp4', format='E',
                                                               array=np.array(np.where((np.array(magp4) != 'INDEF'),
                                                                                       np.array(magp4), 9999), float)),
                                               fits.Column(name='smagf', format='E',
                                                               array=np.array(np.where((np.array(smagf) != 'INDEF'),
                                                                                       np.array(smagf), 9999), float)),
                                               fits.Column(name='smagerrf', format='E',
                                                               array=np.array(np.where((np.array(smagerrf) != 'INDEF'),
                                                                                       np.array(smagerrf), 9999),
                                                                              float)),
        ]))

        hdu = fits.PrimaryHDU(header=hdr)
        thdulist = fits.HDUList([hdu, tbhdu])
        lsc.util.delete(img + '.sn2.fits')
        thdulist.writeto(img + '.sn2.fits')
        lsc.util.updateheader(img + '.sn2.fits', 0, {'APCO': [np.mean(_dmag), 'Aperture correction']})
        lsc.util.updateheader(img + '.sn2.fits', 0, {'APCOERR': [np.std(_dmag), 'Aperture correction error']})
        lsc.util.updateheader(img + '.sn2.fits', 0, {'XDIM': [lsc.util.readkey3(hdr, 'naxis1'), 'x number of pixels']})
        lsc.util.updateheader(img + '.sn2.fits', 0, {'YDIM': [lsc.util.readkey3(hdr, 'naxis2'), 'y number of pixels']})
        lsc.util.updateheader(img + '.sn2.fits', 0,
                              {'PSF_FWHM': [fwhm * scale, 'FWHM (arcsec) - computed with daophot']})
        os.chmod(img + '.sn2.fits', 0664)
        os.chmod(img + '.psf.fits', 0664)
        result = 1

    except:
        result = 0
        fwhm = 0.0
        traceback.print_exc()
    return result, fwhm * scale
示例#2
0
                                  units='degrees degrees',
                                  outwcs='logical',
                                  columns='1 2',
                                  formats='%10.1f %10.1f')
                    if _show:
                        iraf.tvmark(1,
                                    'tmp.pix',
                                    mark="circle",
                                    number='yes',
                                    radii=10,
                                    nxoffse=5,
                                    nyoffse=5,
                                    color=214,
                                    txsize=2)
                    xx0, yy0 = string.split(
                        iraf.fields('tmp.pix', '1,2', Stdout=1)[2])
                    print xx0, yy0
                    os.system('rm -rf tmp.*')
                else:
                    xx0, yy0 = '', ''
            else:
                xx0 = ''

            if xx0 == '' and not _interactive: skip = 1

            if skip == 0:
                if _interactive: xx0 = ''
                _z1, _z2 = '', ''
                z11, z22 = 0, 0
                if xx0 == '':
                    #print '\n###  coordinate not found, reduction should be interactive'
示例#3
0
                else:
                    _xpos, _ypos = '', ''
                if _xpos and _ypos:
                    print 'use xpos and ypos from fits table'
                    print _xpos, _ypos
                else:
                    print 'no xpos and ypos define, do that interactively'
                    jj = 0
                    while not _xpos or not _ypos:
                        print "  MARK SN REGION WITH - x -, EXIT  - q -"
                        try:
                            agnkey.util.delete('tmp.log')
                            zz1, zz2, goon = agnkey.util.display_image(img, 1, '', '', True)
                            #                              iraf.display(img,1,fill=True,Stdout=1)
                            iraf.imexamine(img, 1, wcs='logical', logfile='tmp.log', keeplog=True)
                            xytargets = iraf.fields('tmp.log', '1,2', Stdout=1)
                            _xpos, _ypos = string.split(xytargets[0])[0], string.split(xytargets[0])[1]
                        except:
                            _xpos, _ypos = '', ''
                        jj = jj + 1
                        if jj > 10:
                            goon = False
                            break

            if goon:
                print _xpos, _ypos, _mag
                print img0, psfimg, _xpos, _ypos, _mag
                imgout = re.sub('.fits', '.temp.fits', string.split(img0, '/')[-1])
                agnkey.util.delete('_tmp.fits,_tmp2.fits,_tmp2.fits.art,' + imgout)

                if _clean:
示例#4
0
def ecpsf(img, ofwhm, threshold, interactive, ds9, fixaperture=False,_catalog=''):
    try:
        import agnkey
        import string

        hdr = agnkey.util.readhdr(img + '.fits')
        instrument = agnkey.util.readkey3(hdr, 'instrume')
        print 'INSTRUMENT:', instrument

        if 'PIXSCALE' in hdr:
            pixelscale = agnkey.util.readkey3(hdr, 'PIXSCALE')
        elif 'CCDSCALE' in hdr:
            if 'CCDXBIN' in hdr:
                pixelscale = agnkey.util.readkey3(hdr, 'CCDSCALE') * agnkey.util.readkey3(hdr, 'CCDXBIN')
            elif 'CCDSUM' in hdr:
                pixelscale = agnkey.util.readkey3(hdr, 'CCDSCALE') * int(
                    string.split(agnkey.util.readkey3(hdr, 'CCDSUM'))[0])

        if instrument in ['kb05', 'kb70', 'kb71', 'kb73', 'kb74', 'kb75', 'kb76', 'kb77', 'kb78', 'kb79']:
            scale = pixelscale
            _datamax = 45000
        elif instrument in ['fl02', 'fl03', 'fl04']:
            scale = pixelscale
            _datamax = 120000
        elif instrument in ['fs01', 'em03']:
            scale = pixelscale
            _datamax = 65000
        elif instrument in ['fs02', 'fs03']:
            scale = pixelscale
            _datamax = 65000
        elif instrument in ['em01']:
            scale = pixelscale
            _datamax = 65000
        try:
            _wcserr = agnkey.util.readkey3(hdr, 'wcserr')
            if float(_wcserr) == 0:
                if instrument in ['kb05', 'kb70', 'kb71', 'kb73', 'kb74', 'kb75', 'kb76', 'kb77', 'kb78', 'kb79']:
                    seeing = float(agnkey.util.readkey3(hdr, 'L1FWHM')) * .75
                elif instrument in ['fl02', 'fl03', 'fl04']:
                    seeing = float(agnkey.util.readkey3(hdr, 'L1FWHM')) * .75
                elif instrument in ['fs01', 'fs02', 'fs03', 'em03', 'em01']:
                    if 'L1FWHM' in hdr:
                        seeing = float(agnkey.util.readkey3(hdr, 'L1FWHM')) * .75
                    elif 'L1SEEING' in hdr:
                        seeing = float(agnkey.util.readkey3(hdr, 'L1SEEING')) * scale
                    else:
                        seeing = 3
                else:
                    seeing = 3
            else:
                seeing = float(agnkey.util.readkey3(hdr, 'PSF_FWHM'))
                sys.exit('astrometry not good')
        except:
            sys.exit('astrometry not good')

        fwhm = seeing / scale
        print 'FWHM[header]  ', fwhm, '   in pixel'
        if ofwhm:
            fwhm = float(ofwhm)
        print '    FWHM[input]  ', fwhm, ' in pixel'

        if interactive:
            iraf.display(img, 1, fill=True)
            iraf.delete('tmp.lo?', verify=False)
            print '_' * 80
            print '>>> Mark reference stars with "a". Then "q"'
            print '-' * 80
            iraf.imexamine(img, 1, wcs='logical', logfile='tmp.log', keeplog=True)
            xyrefer = iraf.fields('tmp.log', '1,2,6,15', Stdout=1)
            xns, yns, _fws = [], [], []
            ff = open('_ap.coo', 'w')
            for i in range(len(xyrefer)):
                xns.append(float(xyrefer[i].split()[0]))
                yns.append(float(xyrefer[i].split()[1]))
                _fws.append(float(xyrefer[i].split()[3]))
                ff.write('%10.3f %10.3f %7.2f \n' % (xns[i], yns[i], float(_fws[i])))
            ff.close()

        elif _catalog:
#            cat1=agnkey.agnastrodef.readtxt(_catalog)
#            cat1['ra'],cat1['dec']
            ddd=iraf.wcsctran(input=_catalog,output='STDOUT',Stdout=1,image=img,inwcs='world',outwcs='logical',
                              units='degrees degrees',columns='1 2',formats='%10.1f %10.1f',verbose='no')
            ddd=[i for i in ddd if i[0]!='#']
            ddd=['  '.join(i.split()[0:3]) for i in ddd]
            ff = open('_ap.coo', 'w')
            for i in ddd:
                a,b,c = string.split(i)
                #print a,b,c
                ff.write('%10s %10s %10s \n' % (a, b, c))
            ff.close()
            print 'use catalog'
        else:
            xs, ys, ran, decn, magbest, classstar, fluxrad, bkg = runsex(img, fwhm, threshold, scale)
            ff = open('_ap.coo', 'w')
            for i in range(len(xs)):
                    ff.write('%10.3f %10.3f %7.2f \n' % (xs[i], ys[i], float(fluxrad[i])))
            ff.close()  ## End automatic selection

        print 80 * "#"
        photmag = apfit(img, fwhm, hdr, interactive, _datamax, fixaperture)

        radec = iraf.wcsctran(input='STDIN', output='STDOUT', Stdin=photmag, \
                              Stdout=1, image=img, inwcs='logical', outwcs='world', columns="1 2", \
                              format='%13.3H %12.2h', min_sig=9, mode='h')[3:]

        exptime = agnkey.util.readkey3(hdr, 'exptime')
        object = agnkey.util.readkey3(hdr, 'object').replace(' ', '')
        filtro = agnkey.util.readkey3(hdr, 'filter')

        #######################################
        rap, decp, magp2, magp3, magp4, smagf = [], [], [], [], [], []
        merrp2, merrp3, merrp4, smagerrf = [], [], [], []
        rap0, decp0 = [], []
        for i in range(len(radec)):
            aa = radec[i].split()
            rap.append(aa[0])
            decp.append(aa[1])
            rap0.append(agnkey.agnabsphotdef.deg2HMS(ra=aa[0]))
            decp0.append(agnkey.agnabsphotdef.deg2HMS(dec=aa[1]))
            idp = aa[2]
            magp2.append(aa[3])
            magp3.append(aa[4])
            magp4.append(aa[5])
            merrp2.append(aa[6])
            merrp3.append(aa[7])
            merrp4.append(aa[8])

        tbhdu = pyfits.new_table(pyfits.ColDefs([
            pyfits.Column(name='ra', format='20A', array=np.array(rap)),
            pyfits.Column(name='dec', format='20A', array=np.array(decp)),
            pyfits.Column(name='ra0', format='E', array=np.array(rap0)),
            pyfits.Column(name='dec0', format='E', array=np.array(decp0)),
            pyfits.Column(name='magp2', format='E', array=np.array(np.where((np.array(magp2) != 'INDEF'),
                                                                            np.array(magp2), 9999), float)),
            pyfits.Column(name='magp3', format='E', array=np.array(np.where((np.array(magp3) != 'INDEF'),
                                                                            np.array(magp3), 9999), float)),
            pyfits.Column(name='magp4', format='E', array=np.array(np.where((np.array(magp4) != 'INDEF'),
                                                                            np.array(magp4), 9999), float)),
            pyfits.Column(name='merrp2', format='E', array=np.array(np.where((np.array(merrp2) != 'INDEF'),
                                                                             np.array(merrp2), 9999), float)),
            pyfits.Column(name='merrp3', format='E', array=np.array(np.where((np.array(merrp3) != 'INDEF'),
                                                                             np.array(merrp3), 9999), float)),
            pyfits.Column(name='merrp4', format='E', array=np.array(np.where((np.array(merrp4) != 'INDEF'),
                                                                             np.array(merrp4), 9999), float)),
            pyfits.Column(name='smagf', format='E', array=np.array(np.where((np.array(magp2) != 'INDEF'),
                                                                            np.array(magp2), 9999), float)),
            pyfits.Column(name='smagerrf', format='E', array=np.array(np.where((np.array(merrp2) != 'INDEF'),
                                                                               np.array(merrp2), 9999), float)),

        ]))
        hdu = pyfits.PrimaryHDU(header=hdr)
        thdulist = pyfits.HDUList([hdu, tbhdu])
        agnkey.util.delete(img + '.sn2.fits')
        thdulist.writeto(img + '.sn2.fits')
        agnkey.util.updateheader(img + '.sn2.fits', 0,
                                 {'XDIM': [agnkey.util.readkey3(hdr, 'naxis1'), 'x number of pixels']})
        agnkey.util.updateheader(img + '.sn2.fits', 0,
                                 {'YDIM': [agnkey.util.readkey3(hdr, 'naxis2'), 'y number of pixels']})
        agnkey.util.updateheader(img + '.sn2.fits', 0,
                                 {'PSF_FWHM': [fwhm * scale, 'FWHM (arcsec) - computed with daophot']})
        os.chmod(img + '.sn2.fits', 0664)
        os.chmod(img + '.psf.fits', 0664)
        result = 1

    except:
        result = 0
        fwhm = 0.0
        traceback.print_exc()
    return result, fwhm * scale
示例#5
0
def ecpsf(img, ofwhm, threshold, psfstars, distance, interactive, psffun='gauss', fixaperture=False, _catalog='', _datamax=None, show=False):
    try:
        import lsc, string

        hdr = lsc.util.readhdr(img + '.fits')
        instrument = lsc.util.readkey3(hdr, 'instrume')
        print 'INSTRUMENT:', instrument

        if 'PIXSCALE' in hdr:
            scale = lsc.util.readkey3(hdr, 'PIXSCALE')
        elif 'CCDSCALE' in hdr:
            if 'CCDXBIN' in hdr:
                scale = lsc.util.readkey3(hdr, 'CCDSCALE') * lsc.util.readkey3(hdr, 'CCDXBIN')
            elif 'CCDSUM' in hdr:
                scale = lsc.util.readkey3(hdr, 'CCDSCALE') * int(string.split(lsc.util.readkey3(hdr, 'CCDSUM'))[0])

        if _datamax is None:
            _datamax = lsc.util.readkey3(hdr, 'datamax')
        _wcserr = lsc.util.readkey3(hdr, 'wcserr')
        print _wcserr
        if float(_wcserr) == 0:
            if 'L1FWHM' in hdr:
                seeing = float(lsc.util.readkey3(hdr, 'L1FWHM'))
            elif 'L1SEEING' in hdr:
                seeing = float(lsc.util.readkey3(hdr, 'L1SEEING')) * scale
            else:
                seeing = 3
        else:
            seeing = 3
            if 'PSF_FWHM' in hdr:
                seeing = float(lsc.util.readkey3(hdr, 'PSF_FWHM'))
            else:
                sys.exit('astrometry not good')
        #except:  sys.exit('astrometry not good')

        fwhm = seeing / scale
        print 'FWHM[header]  ', fwhm, '   in pixel'
        if ofwhm: fwhm = float(ofwhm)
        print '    FWHM[input]  ', fwhm, ' in pixel'

        xdim, ydim = iraf.hselect(img+'[0]', 'i_naxis1,i_naxis2', 'yes', Stdout=1)[0].split()
        print img, fwhm, threshold, scale,xdim

        #################################################################################
        ###################        write file to compute psf     _psf.coo    ############
        #################################################################################
        if _catalog:
            print '\n#### use catalog to measure the psf'
            ddd=iraf.wcsctran(input=_catalog,output='STDOUT',Stdout=1,image=img + '[0]',inwcs='world',outwcs='logical',
                              units='degrees degrees',columns='1 2',formats='%10.1f %10.1f',verbose='no')
            ddd=[i for i in ddd if i[0]!='#']
            ddd=['  '.join(i.split()[0:3]) for i in ddd]
            line=''
            for i in ddd:
                a,b,c = string.split(i)
                if float(a) < float(xdim) and  float(b) < float(ydim) and float(b) > 0:
                    line = line + '%10s %10s %10s \n' % (a, b, c)
            if line:
                ff = open('_psf.coo', 'w')
                ff.write(line)
                ff.close()
            else:
                sys.exit('error: no catalog objects are in the field')
        elif interactive:
            iraf.display(img + '[0]', 1, fill=True)
            iraf.delete('tmp.lo?', verify=False)
            print '_' * 80
            print '>>> Mark reference stars with "a". Then "q"'
            print '-' * 80
            iraf.imexamine(img, 1, wcs='logical', logfile='tmp.log', keeplog=True)
            xyrefer = iraf.fields('tmp.log', '1,2,6,15', Stdout=1)
            xns, yns, _fws = [], [], []
            #############      write    file for PSF                           #########################
            ff = open('_psf.coo', 'w')
            for i in range(len(xyrefer)):
                xns.append(float(xyrefer[i].split()[0]))
                yns.append(float(xyrefer[i].split()[1]))
                _fws.append(float(xyrefer[i].split()[3]))
                ff.write('%10.3f %10.3f %7.2f \n' % (xns[i], yns[i], float(_fws[i])))
            ff.close()
            fwhm = np.median(_fws)
        else:
            ############              run  sextractor                #####################################
            xs, ys, ran, decn, magbest, classstar, fluxrad, bkg = runsex(img, fwhm, threshold, scale)
            tot = np.compress(abs(np.array(fluxrad) * 1.6 - fwhm) / fwhm < .5, fluxrad)
            if len(tot) < 5:
                print 'warning: fwhm from sexractor different from fwhm computed during pre-reduction'
                print 'try using option --fwhm xxx'

            ff = open('tmp.cursor', 'w')
            image_hdu = fits.open(img + '.fits')
            for i in range(len(xs)):
                _xs = np.delete(xs, i)
                _ys = np.delete(ys, i)
                dist2 = np.sqrt((_xs - xs[i]) ** 2 + (_ys - ys[i]) ** 2)
                ###########           cut  star, not near other object    ##########################
                if abs(fluxrad[i] * 1.6 - fwhm) / fwhm < .5 and min(dist2) > distance * fwhm:
                    x1, x2 = int(xs[i] - fwhm * 3), int(xs[i] + fwhm * 3)
                    y1, y2 = int(ys[i] - fwhm * 3), int(ys[i] + fwhm * 3)
                    if x1 < 1: x1 = 1
                    if y1 < 1: y1 = 1
                    if x2 > int(xdim):
                        x2 = int(xdim)
                    if y2 > int(ydim):
                        y2 = int(ydim)
                    fmax = np.max(image_hdu[0].data[y1-1:y2, x1-1:x2])
                ##########       cut saturated object               ########################
                    if float(fmax) < _datamax:  # not saturated
                        ff.write('%10.3f %10.3f 1 m \n' % (xs[i], ys[i]))
            ff.close()
            image_hdu.close()

            iraf.delete('tmp.lo?,tmp.sta?,tmp.gk?', verify=False)
            iraf.psfmeasure(img+'[0]', imagecur='tmp.cursor', logfile='tmp.log', radius=int(fwhm), iter=3,
                            display=False, StdoutG='tmp.gki')

            ff = open('tmp.log')
            righe = ff.readlines()
            xn = [float(righe[3].split()[1])]
            yn = [float(righe[3].split()[2])]
            _fw = [float(righe[3].split()[4])]
            for r in righe[4:-2]:
                if len(r) > 0:
                    xn.append(float(r.split()[0]))
                    yn.append(float(r.split()[1]))
                    _fw.append(float(r.split()[3]))
            print 'FWHM: ', righe[-1].split()[-1]
            print 80 * "#"
            ######
            ##############            eliminate double object identification         ###########################
            xns, yns, _fws = [xn[0]], [yn[0]], [_fw[0]]
            for i in range(1, len(xn)):
                if abs(xn[i] - xn[i - 1]) > .2 and abs(yn[i] - yn[i - 1]) > .2:
                    xns.append(xn[i])
                    yns.append(yn[i])
                    _fws.append(_fw[i])
            #########      write clean   file for PSF                           #########################
            fw = []
            ff = open('_psf.coo', 'w')
            for i in range(len(xns)):
                if abs(_fws[i] - fwhm) / fwhm < .3:
                    ff.write('%10.3f %10.3f %7.2f \n' % (xns[i], yns[i], float(_fws[i])))
                    fw.append(_fws[i])
            ff.close()  ## End automatic selection
        ######################################################################################
        ###################        write file of object to store in  fits table  #############
        ######################################################################################
        if _catalog:
            ddd=iraf.wcsctran(input=_catalog,output='STDOUT',Stdout=1,image=img + '[0]',inwcs='world',outwcs='logical',
                              units='degrees degrees',columns='1 2',formats='%10.1f %10.1f',verbose='no')
            ddd=[i for i in ddd if i[0]!='#']
            ddd=['  '.join(i.split()[0:3]) for i in ddd]
            ff = open('_psf2.coo', 'w')
            for i in ddd:
                a,b,c = string.split(i)
                ff.write('%10s %10s %10s \n' % (a, b, c))
            ff.close()
        elif interactive:
            xs, ys, ran, decn, magbest, classstar, fluxrad, bkg = runsex(img, fwhm, threshold, scale)
            ff = open('_psf2.coo', 'w')
            for i in range(len(xs)):
                ff.write('%10s %10s %10s \n' % (xs[i], ys[i], fluxrad[i]))
            ff.close()
        else:
            os.system('cp _psf.coo _psf2.coo')
#            dflux = fluxrad - np.median(fluxrad)
#            fstar = np.compress(dflux < np.std(fluxrad), fluxrad)
#################################################################################################################

        print 80 * "#"
        photmag, pst, fitmag = psffit(img, fwhm, psfstars, hdr, interactive, _datamax, psffun, fixaperture)

        photmag2, fitmag2 = psffit2(img, fwhm, psfstars, hdr, _datamax, psffun, fixaperture)

        radec = iraf.wcsctran(input='STDIN', output='STDOUT', Stdin=photmag,
                              Stdout=1, image=img + '[0]', inwcs='logical', outwcs='world', columns="1 2",
                              format='%13.3H %12.2h', min_sig=9, mode='h')[3:]

        radec2 = iraf.wcsctran(input='STDIN', output='STDOUT', Stdin=photmag2,
                               Stdout=1, image=img + '[0]', inwcs='logical', outwcs='world', columns="1 2",
                               format='%13.3H %12.2h', min_sig=9, mode='h')[3:]

        if interactive or show:
            iraf.set(stdimage='imt1024')
            iraf.display(img + '[0]', 1, fill=True, Stdout=1)
            iraf.tvmark(1, coords='STDIN', mark='circle', radii=15, label=True, Stdin=photmag, nxoffset=5, nyoffset=5, txsize=2)
            iraf.tvmark(1, coords='STDIN', mark='circle', radii=35, label=False, Stdin=pst, color=208)
#            iraf.tvmark(1, coords='STDIN', mark='cross', length=35, label=False, Stdin=fitmag2, color=204)

        idpsf = []
        for i in range(len(pst)):
            idpsf.append(pst[i].split()[2])
        dmag = []
        for i in range(len(radec)):
            ra, dec, idph, magp2, magp3, magp4, merrp2, merrp3, merrp4 = radec[i].split()
            dmag.append(9.99)
            for j in range(len(fitmag)):
                raf, decf, idf, magf, magerrf = fitmag[j].split()
                if idph == idf and idph in idpsf and \
                                magp3 != 'INDEF' and magf != 'INDEF':
                    dmag[i] = float(magp3) - float(magf)
                    break

        _dmag = np.compress(np.array(dmag) < 9.99, np.array(dmag))

        print '>>> Aperture correction (phot)   %6.3f +/- %5.3f %3d ' % \
              (np.mean(_dmag), np.std(_dmag), len(_dmag))
        if len(_dmag) > 3:
            _dmag = np.compress(np.abs(_dmag - np.median(_dmag)) < 2 * np.std(_dmag), _dmag)
            print '>>>         2 sigma rejection)   %6.3f +/- %5.3f %3d  [default]' \
                  % (np.mean(_dmag), np.std(_dmag), len(_dmag))
            print '>>>     fwhm   %s  ' % (str(fwhm))
        for i in range(len(dmag)):
            if dmag[i] == 9.99:
                dmag[i] = ''
            else:
                dmag[i] = '%6.3f' % (dmag[i])

        exptime = lsc.util.readkey3(hdr, 'exptime')
        object = lsc.util.readkey3(hdr, 'object').replace(' ', '')
        filtro = lsc.util.readkey3(hdr, 'filter')

        #######################################
        rap, decp, magp2, magp3, magp4, smagf, merrp3, smagerrf = [], [], [], [], [], [], [], []
        rap0, decp0 = [], []
        for i in range(len(radec2)):
            aa = radec2[i].split()
            rap.append(aa[0])
            decp.append(aa[1])
            rap0.append(lsc.lscabsphotdef.deg2HMS(ra=aa[0]))
            decp0.append(lsc.lscabsphotdef.deg2HMS(dec=aa[1]))
            idp = aa[2]
            magp2.append(aa[3])
            magp3.append(aa[4])
            magp4.append(aa[5])
            merrp3.append(aa[7])
            _smagf, _smagerrf = 9999, 9999
            for j in range(len(fitmag2)):
                raf, decf, idf, magf, magerrf = fitmag2[j].split()
                if idf == idp:
                    _smagf = magf
                    _smagerrf = magerrf
                    break
            smagf.append(_smagf)
            smagerrf.append(_smagerrf)
        tbhdu = fits.BinTableHDU.from_columns(fits.ColDefs([fits.Column(name='ra', format='20A', array=np.array(rap)),
                                               fits.Column(name='dec', format='20A', array=np.array(decp)),
                                               fits.Column(name='ra0', format='E', array=np.array(rap0)),
                                               fits.Column(name='dec0', format='E', array=np.array(decp0)),
                                               fits.Column(name='magp2', format='E',
                                                           array=np.array(np.where((np.array(magp2) != 'INDEF'),
                                                                                   np.array(magp2), 9999), float)),
                                               fits.Column(name='magp3', format='E',
                                                               array=np.array(np.where((np.array(magp3) != 'INDEF'),
                                                                                       np.array(magp3), 9999), float)),
                                               fits.Column(name='merrp3', format='E',
                                                               array=np.array(np.where((np.array(merrp3) != 'INDEF'),
                                                                                       np.array(merrp3), 9999), float)),
                                               fits.Column(name='magp4', format='E',
                                                               array=np.array(np.where((np.array(magp4) != 'INDEF'),
                                                                                       np.array(magp4), 9999), float)),
                                               fits.Column(name='smagf', format='E',
                                                               array=np.array(np.where((np.array(smagf) != 'INDEF'),
                                                                                       np.array(smagf), 9999), float)),
                                               fits.Column(name='smagerrf', format='E',
                                                               array=np.array(np.where((np.array(smagerrf) != 'INDEF'),
                                                                                       np.array(smagerrf), 9999),
                                                                              float)),
        ]))

        hdu = fits.PrimaryHDU(header=hdr)
        thdulist = fits.HDUList([hdu, tbhdu])
        lsc.util.delete(img + '.sn2.fits')
        thdulist.writeto(img + '.sn2.fits')
        lsc.util.updateheader(img + '.sn2.fits', 0, {'APCO': [np.mean(_dmag), 'Aperture correction']})
        lsc.util.updateheader(img + '.sn2.fits', 0, {'APCOERR': [np.std(_dmag), 'Aperture correction error']})
        lsc.util.updateheader(img + '.sn2.fits', 0, {'XDIM': [lsc.util.readkey3(hdr, 'naxis1'), 'x number of pixels']})
        lsc.util.updateheader(img + '.sn2.fits', 0, {'YDIM': [lsc.util.readkey3(hdr, 'naxis2'), 'y number of pixels']})
        lsc.util.updateheader(img + '.sn2.fits', 0,
                              {'PSF_FWHM': [fwhm * scale, 'FWHM (arcsec) - computed with daophot']})
        os.chmod(img + '.sn2.fits', 0664)
        os.chmod(img + '.psf.fits', 0664)
        result = 1

    except:
        result = 0
        fwhm = 0.0
        traceback.print_exc()
    return result, fwhm * scale
示例#6
0
xpa('zoom to fit')
xpa('catalog ua2')
xpa('catalog server cds')
xpa('catalog size 10 10 arcmin')
xpa('catalog save "' + userPath + '/tmp.cat"')
xpa('catalog filter "' + mag + '<' + str(magsel) + '"')
xpa('catalog symbol shape text')

if environ == 'mac':
    xpa('catalog save sb "' + userPath + '/tmp.catsel"')
elif environ == 'linux':
    xpa('catalog save sb "' + userPath + '/tmp.catsel"')

xpa('raise')

iraf.fields('tmp.catsel', '1,2', Stdout='tmp.tv')

answ = 'no'

while answ != 'yes':
    print '>> Identify (minimum 2, preferably 3) reference stars (mark with "a") in your image'
    iraf.imexamine(img, 1, logfile='tmp.coo', keeplog='yes')
    iraf.tvmark(1,
                'tmp.coo',
                mark="circle",
                number='yes',
                radii=10,
                nxoffse=10,
                nyoffse=10,
                color=214,
                txsize=2)
示例#7
0
ff.write(ra + ' ' + dec + ' ' + '10 10')
ff.close()
iraf.agetim('tmp.reg', 'tmpdss', imsurve='dss1@cadc', wcsedit='yes')
iraf.display('tmpdss', 2)

answ = raw_input('>> Change cuts (y/n) ? [n]')
if len(answ) > 0:
    while string.lower(answ) == 'y':
        z1, z2 = string.split(raw_input('z1 z2 ? '))
        iraf.display('tmpdss', 2, z1=z1, z2=z2, zscale='no', zrange='no')
        answ = raw_input('>> Change cuts (y/n) ? [n]')
        if len(answ) == 0: answ = 'n'

iraf.agetcat('tmpdss', 'tmp.cat', catalog='usno2@cadc')
iraf.afiltcat('tmp.cat', 'tmp.catsel', fexpr="mag1<=" + str(magsel))
iraf.fields('tmp.catsel', '2,3', Stdout='tmp.tv')
iraf.wcsctran('tmp.tv',
              'tmp.pix',
              'tmpdss',
              inwcs='world',
              units='degrees degrees',
              outwcs='logical',
              columns='1 2',
              formats='%10.1f %10.1f')
iraf.tvmark(2,
            'tmp.pix',
            mark="circle",
            number='yes',
            radii=5,
            nxoffse=5,
            nyoffse=5,
示例#8
0
文件: agnpsf.py 项目: svalenti/agnkey
def ecpsf(img, ofwhm, threshold, psfstars, distance, interactive, ds9, psffun='gauss', fixaperture=False,_catalog='',_datamax=''):
    try:
        import agnkey
        hdr = agnkey.util.readhdr(img + '.fits')
        instrument = agnkey.util.readkey3(hdr, 'instrume')
        print 'INSTRUMENT:', instrument

        if 'PIXSCALE' in hdr:
            pixelscale = agnkey.util.readkey3(hdr, 'PIXSCALE')
        elif 'CCDSCALE' in hdr:
            if 'CCDXBIN' in hdr:
                pixelscale = agnkey.util.readkey3(hdr, 'CCDSCALE') * agnkey.util.readkey3(hdr, 'CCDXBIN')
            elif 'CCDSUM' in hdr:
                pixelscale = agnkey.util.readkey3(hdr, 'CCDSCALE') * int(
                    string.split(agnkey.util.readkey3(hdr, 'CCDSUM'))[0])

        if 'kb' in instrument:  
            scale = pixelscale
            if not _datamax:
                _datamax = 45000
        elif 'fl' in instrument:
            scale = pixelscale
            if not _datamax:
                _datamax = 60000
        elif 'fs' in instrument:
            scale = pixelscale
            if not _datamax:
                _datamax = 65000
        try:
        #if 1==1:
            if 'WCSERR' in hdr:
                _wcserr = hdr['WCSERR']
            elif 'WCS_ERR' in hdr:
                _wcserr = hdr['WCS_ERR']
            print _wcserr
            if float(_wcserr) == 0:
                if 'kb' in instrument:  
                    seeing = float(agnkey.util.readkey3(hdr, 'L1FWHM')) * .75
                elif 'fl' in instrument:     
                    seeing = float(agnkey.util.readkey3(hdr, 'L1FWHM')) * .75
                elif 'fs' in instrument: 
                    if 'L1FWHM' in hdr:
                        seeing = float(agnkey.util.readkey3(hdr, 'L1FWHM')) * .75
                    elif 'L1SEEING' in hdr:
                        seeing = float(agnkey.util.readkey3(hdr, 'L1SEEING')) * scale
                    else:
                        seeing = 3
                else:
                    seeing = 3
            else:
                seeing = float(agnkey.util.readkey3(hdr, 'PSF_FWHM'))
                sys.exit('astrometry not good')
        except ValueError:
#        except:
            sys.exit('astrometry not good')

        fwhm = seeing / scale
        print 'FWHM[header]  ', fwhm, '   in pixel'
        if ofwhm: fwhm = float(ofwhm)
        print '    FWHM[input]  ', fwhm, ' in pixel'

        xdim, ydim = iraf.hselect(img+'.fits[0]', 'i_naxis1,i_naxis2', 'yes', Stdout=1)[0].split()
        print img, fwhm, threshold, scale

        #################################################################################
        ###################        write file to compute psf     _psf.coo    ############
        #################################################################################
        if interactive:
            iraf.set(stdimage='imt1024')
            iraf.display(img+'.fits[0]', 1, fill=True)
            iraf.delete('tmp.lo?', verify=False)
            print '_' * 80
            print '>>> Mark reference stars with "a". Then "q"'
            print '-' * 80
            iraf.imexamine(img+'[0]', 1, wcs='logical', logfile='tmp.log', keeplog=True)
            xyrefer = iraf.fields('tmp.log', '1,2,6,15', Stdout=1)
            xns, yns, _fws = [], [], []

            #############      write    file for PSF                           #########################
            ff = open('_psf.coo', 'w')
            for i in range(len(xyrefer)):
                xns.append(float(xyrefer[i].split()[0]))
                yns.append(float(xyrefer[i].split()[1]))
                _fws.append(float(xyrefer[i].split()[3]))
                ff.write('%10.3f %10.3f %7.2f \n' % (xns[i], yns[i], float(_fws[i])))
            ff.close()
            fwhm = np.median(_fws)
        else:
            ############              run  sextractor                #####################################
            xs, ys, ran, decn, magbest, classstar, fluxrad, bkg = runsex(img, fwhm, threshold, scale)
            
            _ra1,_dec1,xx11,yy11,_mag,_dist = agnkey.agnastrodef.starsfields(img+'.fits',20,19)
            if len(_ra1):
                dist,pos0,pos1 = agnkey.agnastrodef.crossmatchxy(xs,ys,xx11,yy11,10)
                if len(pos0):
                    xs = xs[pos0]
                    ys = ys[pos0]
                    ran = ran[pos0]
                    decn = decn[pos0]
                    magbest = magbest[pos0]
                    classstar = classstar[pos0]
                    fluxrad = fluxrad[pos0]
                    bkg = bkg[pos0]


            ff = open('tmp.cursor', 'w')
            for i in range(len(xs)):
                x1, x2 = int(xs[i] - fwhm * 3), int(xs[i] + fwhm * 3)
                y1, y2 = int(ys[i] - fwhm * 3), int(ys[i] + fwhm * 3)
                sect = '[' + str(x1) + ':' + str(x2) + ',' + str(y1) + ':' + str(y2) + ']'
                try:
                    fmax = iraf.imstat(img+'.fits[0]' + sect, fields='max', Stdout=1)[1]
                    ##########       cut saturated object               ########################
                    if float(fmax) < _datamax:  # not saturated
                        ff.write('%10.3f %10.3f 1 m \n' % (xs[i], ys[i]))
                except:
                    print sect
                #    print 'problem here'
                #    pass
            ff.close()

            iraf.delete('tmp.lo?,tmp.sta?,tmp.gk?', verify=False)
            iraf.psfmeasure(img+'[0]', imagecur='tmp.cursor', logfile='tmp.log', radius=int(fwhm), iter=3,
                            display=False, StdoutG='tmp.gki')

            ff = open('tmp.log')
            righe = ff.readlines()
            xn = [float(righe[3].split()[1])]
            yn = [float(righe[3].split()[2])]
            _fw = [float(righe[3].split()[4])]
            for r in righe[4:-2]:
                if len(r) > 0:
                    xn.append(float(r.split()[0]))
                    yn.append(float(r.split()[1]))
                    _fw.append(float(r.split()[3]))
            print 'FWHM: ', righe[-1].split()[-1]
            print 80 * "#"
            ######
            ##############            eliminate double object identification         ###########################
            xns, yns, _fws = [xn[0]], [yn[0]], [_fw[0]]
            for i in range(1, len(xn)):
                if abs(xn[i] - xn[i - 1]) > .2 and abs(yn[i] - yn[i - 1]) > .2:
                    xns.append(xn[i])
                    yns.append(yn[i])
                    _fws.append(_fw[i])
            #########      write clean   file for PSF                           #########################
            fw = []
            ff = open('_psf.coo', 'w')
            for i in range(len(xns)):
                    ff.write('%10.3f %10.3f %7.2f \n' % (xns[i], yns[i], float(_fws[i])))
                    fw.append(_fws[i])
            ff.close()  ## End automatic selection
        ######################################################################################
        ###################        write file of object to store in  fits table  #############
        ######################################################################################
        if interactive:
            xs, ys, ran, decn, magbest, classstar, fluxrad, bkg = runsex(img, fwhm, threshold, scale)
            ff = open('_psf2.coo', 'w')
            for i in range(len(xs)):
                ff.write('%10s %10s %10s \n' % (xs[i], ys[i], fluxrad[i]))
            ff.close()
        elif _catalog:
            print '\n#### use catalog '
            ddd=iraf.wcsctran(input=_catalog,output='STDOUT',Stdout=1,image=img,inwcs='world',outwcs='logical',
                              units='degrees degrees',columns='1 2',formats='%10.1f %10.1f',verbose='no')
            ddd=[i for i in ddd if i[0]!='#']
            ddd=['  '.join(i.split()[0:3]) for i in ddd]
            ff = open('_psf2.coo', 'w')
            for i in ddd:
                a,b,c = string.split(i)
                ff.write('%10s %10s %10s \n' % (a, b, c))
            ff.close()
            print 'use catalog'
        else:
            os.system('cp _psf.coo _psf2.coo')
#                print '\n###   use sextractor'
#                xs, ys, ran, decn, magbest, classstar, fluxrad, bkg = runsex(img, fwhm, threshold, scale)
#                ff = open('_psf2.coo', 'w')
#                for i in range(len(xs)):
#                    ff.write('%10s %10s %10s \n' % (xs[i], ys[i], fluxrad[i]))
#                ff.close()
        ###################################################################################

        print 80 * "#"
        photmag, pst, fitmag = psffit(img, fwhm, psfstars, hdr, interactive, _datamax, psffun, fixaperture)

        photmag2, fitmag2 = psffit2(img, fwhm, psfstars, hdr, _datamax, psffun, fixaperture)

        radec = iraf.wcsctran(input='STDIN', output='STDOUT', Stdin=photmag, \
                              Stdout=1, image=img+'.fits[0]', inwcs='logical', outwcs='world', columns="1 2", \
                              format='%13.3H %12.2h', min_sig=9, mode='h')[3:]

        radec2 = iraf.wcsctran(input='STDIN', output='STDOUT', Stdin=photmag2, \
                               Stdout=1, image=img+'.fits[0]', inwcs='logical', outwcs='world', columns="1 2", \
                               format='%13.3H %12.2h', min_sig=9, mode='h')[3:]

        if ds9 == 0 and interactive:
            iraf.set(stdimage='imt1024')
            iraf.display(img, 1, fill=True, Stdout=1)
            iraf.tvmark(1, coords='STDIN', mark='circle', radii=15, label=False, Stdin=photmag)
            iraf.tvmark(1, coords='STDIN', mark='rectangle', length=35, label=False, Stdin=pst)
            iraf.tvmark(1, coords='STDIN', mark='cross', length=35, label=False, Stdin=fitmag2, color=204)

        idpsf = []
        for i in range(len(pst)):
            idpsf.append(pst[i].split()[2])
        dmag = []
        for i in range(len(radec)):
            ra, dec, idph, magp2, magp3, magp4, merrp2, merrp3, merrp4 = radec[i].split()
            dmag.append(9.99)
            for j in range(len(fitmag)):
                raf, decf, idf, magf, magerrf = fitmag[j].split()
                if idph == idf and idph in idpsf and \
                                magp3 != 'INDEF' and magf != 'INDEF':
                    dmag[i] = float(magp3) - float(magf)
                    break

        _dmag = np.compress(np.array(dmag) < 9.99, np.array(dmag))

        print '>>> Aperture correction (phot)   %6.3f +/- %5.3f %3d ' % \
              (np.mean(_dmag), np.std(_dmag), len(_dmag))
        if len(_dmag) > 3:
            _dmag = np.compress(abs(_dmag - np.median(_dmag)) < 2 * np.std(_dmag), _dmag)
            print '>>>         2 sigma rejection)   %6.3f +/- %5.3f %3d  [default]' \
                  % (np.mean(_dmag), np.std(_dmag), len(_dmag))
            print '>>>     fwhm   %s  ' % (str(fwhm))
        for i in range(len(dmag)):
            if dmag[i] == 9.99:
                dmag[i] = ''
            else:
                dmag[i] = '%6.3f' % (dmag[i])

        exptime = agnkey.util.readkey3(hdr, 'exptime')
        object = agnkey.util.readkey3(hdr, 'object').replace(' ', '')
        filtro = agnkey.util.readkey3(hdr, 'filter')

        #######################################
        rap, decp, magp2, magp3, magp4, smagf = [], [], [], [], [], []
        merrp2, merrp3, merrp4, smagerrf = [], [], [], []
        rap0, decp0 = [], []
        for i in range(len(radec2)):
            aa = radec2[i].split()
            rap.append(aa[0])
            decp.append(aa[1])
            rap0.append(agnkey.agnabsphotdef.deg2HMS(ra=aa[0]))
            decp0.append(agnkey.agnabsphotdef.deg2HMS(dec=aa[1]))
            idp = aa[2]
            magp2.append(aa[3])
            magp3.append(aa[4])
            magp4.append(aa[5])
            merrp2.append(aa[6])
            merrp3.append(aa[7])
            merrp4.append(aa[8])
            _smagf, _smagerrf = 9999, 9999
            for j in range(len(fitmag2)):
                raf, decf, idf, magf, magerrf = fitmag2[j].split()
                if idf == idp:
                    _smagf = magf
                    _smagerrf = magerrf
                    break
            smagf.append(_smagf)
            smagerrf.append(_smagerrf)

        new_cols = pyfits.ColDefs([
            pyfits.Column(name='ra', format='20A', array=np.array(rap)),
            pyfits.Column(name='dec', format='20A', array=np.array(decp)),
            pyfits.Column(name='ra0', format='E', array=np.array(rap0)),
            pyfits.Column(name='dec0', format='E', array=np.array(decp0)),
            pyfits.Column(name='magp2', format='E', array=np.array(np.where((np.array(magp2) != 'INDEF'),
                                                                            np.array(magp2), 9999), float)),
            pyfits.Column(name='magp3', format='E', array=np.array(np.where((np.array(magp3) != 'INDEF'),
                                                                            np.array(magp3), 9999), float)),
            pyfits.Column(name='magp4', format='E', array=np.array(np.where((np.array(magp4) != 'INDEF'),
                                                                            np.array(magp4), 9999), float)),
            pyfits.Column(name='merrp2', format='E', array=np.array(np.where((np.array(merrp2) != 'INDEF'),
                                                                             np.array(merrp2), 9999), float)),
            pyfits.Column(name='merrp3', format='E', array=np.array(np.where((np.array(merrp3) != 'INDEF'),
                                                                             np.array(merrp3), 9999), float)),
            pyfits.Column(name='merrp4', format='E', array=np.array(np.where((np.array(merrp4) != 'INDEF'),
                                                                             np.array(merrp4), 9999), float)),
            pyfits.Column(name='smagf', format='E', array=np.array(np.where((np.array(smagf) != 'INDEF'),
                                                                            np.array(smagf), 9999), float)),
            pyfits.Column(name='smagerrf', format='E', array=np.array(np.where((np.array(smagerrf) != 'INDEF'),
                                                                               np.array(smagerrf), 9999), float)),
        ])
        
        tbhdu = pyfits.BinTableHDU.from_columns(new_cols)
        
        hdu = pyfits.PrimaryHDU(header=hdr)
        thdulist = pyfits.HDUList([hdu, tbhdu])
        agnkey.util.delete(img + '.sn2.fits')
        thdulist.writeto(img + '.sn2.fits')
        agnkey.util.updateheader(img + '.sn2.fits', 0, {'APCO': [np.mean(_dmag), 'Aperture correction']})
        agnkey.util.updateheader(img + '.sn2.fits', 0, {'APCOERR': [np.std(_dmag), 'Aperture correction error']})
        agnkey.util.updateheader(img + '.sn2.fits', 0,
                                 {'XDIM': [agnkey.util.readkey3(hdr, 'naxis1'), 'x number of pixels']})
        agnkey.util.updateheader(img + '.sn2.fits', 0,
                                 {'YDIM': [agnkey.util.readkey3(hdr, 'naxis2'), 'y number of pixels']})
        agnkey.util.updateheader(img + '.sn2.fits', 0,
                                 {'PSF_FWHM': [fwhm * scale, 'FWHM (arcsec) - computed with daophot']})
        os.chmod(img + '.sn2.fits', 0664)
        os.chmod(img + '.psf.fits', 0664)
        result = 1
    except IOError as e:
        print e
        result = 0
        fwhm = 0.0
        traceback.print_exc()
    return result, fwhm * scale
示例#9
0

                if _ra and _dec:
                    os.system('rm -rf tmp.*')
                    lll=[]
                    for jj in range(0,len(_ra)):
                        lll.append(str(_ra[jj]) + '    ' + str(_dec[jj]))
                        #lll = [str(_ra) + '    ' + str(_dec)]
                    iraf.wcsctran('STDIN', 'tmp.pix', img + '[0]', Stdin=lll, inwcs='world', units='degrees degrees',
                                  outwcs='logical', columns='1 2', formats='%10.1f %10.1f')
                    if _show:
                        iraf.tvmark(1, 'tmp.pix', mark="circle", number='yes', radii=10, nxoffse=5, nyoffse=5,
                                           color=214, txsize=2)
                    xxsn, yysn = [], []

                    for kk in iraf.fields('tmp.pix', '1,2', Stdout=1):
                        if kk:
                            xxsn.append(string.split(kk)[0])
                            yysn.append(string.split(kk)[1])

                    xxsn = array(xxsn,float)
                    yysn = array(yysn,float)

                    print 'SN coordinate ',xxsn, yysn

                if _ra0 and _dec0:
                    os.system('rm -rf tmp.*')
                    lll = [str(_ra0) + '    ' + str(_dec0)]
                    iraf.wcsctran('STDIN', 'tmp.pix', img, Stdin=lll, inwcs='world', units='degrees degrees',
                                  outwcs='logical', columns='1 2', formats='%10.1f %10.1f')
                    if _show:
示例#10
0
def sn_coordinate(imgl, _interactive):
    from math import sqrt
    from snoopy2 import src
    import snoopy2
    from pyraf import iraf
    import string
    import os
    imgl = src.replace_directory(imgl)
    if imgl[-5:] != '.fits':
        imgllong = imgl + '.fits'
    else:
        imgllong = imgl
    listastandard = snoopy2.__path__[
        0] + '/standard/fluxstandard/supernovaelist.txt'
    f = open(listastandard, 'r')
    liststd = f.readlines()
    f.close()
    star, ra, dec = [], [], []
    for i in liststd:
        vector = string.split(i)
        star.append(vector[0])
        #print vector
        ra.append(
            float(vector[1]) + ((float(vector[2]) +
                                 (float(vector[3]) / 60.)) / 60.))
        if float(vector[4]) > 0:
            dec.append(
                float(vector[4]) + ((float(vector[5]) +
                                     (float(vector[6]) / 60.)) / 60.))
        else:
            aa = -1 * ((abs(float(vector[4]))) +
                       ((float(vector[5]) + (float(vector[6]) / 60.)) / 60.))
            dec.append(aa)
        print ra[-1], dec[-1], star[-1]
    _telescope = src.telescope(imgllong)
    _system = src.check_system(_telescope, imgllong, Stdout=True)
    _header = src.read_parameter(_telescope, _system)
    if _telescope == 'other':
        print 'other'
        _xdimen = src.xdimen(imgllong, _telescope)
        _ydimen = src.ydimen(imgllong, _telescope)
        xcenter = int(float(_xdimen) / 2)
        ycenter = int(float(_ydimen) / 2)
        f = open('_tmp.tv', 'w')
        f.write(str(xcenter) + '  ' + str(ycenter) + '\n')
        f.close()
        iraf.delete('tmp.coo')
        iraf.wcsctran('_tmp.tv',
                      'tmp.coo',
                      imgl,
                      inwcs='logical',
                      units='degrees degrees',
                      outwcs='world',
                      columns='1 2',
                      formats='%10.8f %10.8f')
        sss = iraf.fields('tmp.coo', '1,2', Stdout=1)
        _RA, _DEC = string.split(sss[2])
        _RA = float(_RA) / 15.
        _DEC = float(_DEC)
    else:
        _RA = src.RA(imgllong, _header, _telescope)
        _DEC = src.DEC(imgllong, _header, _telescope)
    print _RA, _DEC
    ra0 = ''
    if _RA and _DEC:
        for st in range(len(star)):
            distance = sqrt((float(_RA) - float(ra[st]))**2 +
                            (float(_DEC) - float(dec[st]))**2)
            print st, distance
            if distance <= 0.5:
                print str(star[st]), str(_RA), str(_DEC), str(distance)
                refstar = string.split(star[st])[0]
                ra0, dec0 = ra[st], dec[st]
                if _interactive:
                    print ''
                    print '############################################'
                    question = raw_input(
                        'Is this the right object ? [y/n] [y]')
                    print '############################################'
                    print ''
                    if not question: question = 'y'
                    if question in ['Yes', 'Y', 'y', 'YES', 'yes']:
                        break
                    else:
                        ra0, dec0 = '', ''
                else:
                    print '############################################'
                    print ' object found ' + str(refstar)
                    print '############################################'
                    break
    if ra0:
        os.system('rm -rf tmp.*')
        ff = open('tmp.tv', 'w')
        ff.write(str(ra0 * 15.) + ' ' + str(dec0))
        ff.close()
        iraf.wcsctran('tmp.tv',
                      'tmp.pix',
                      imgl,
                      inwcs='world',
                      units='degrees degrees',
                      outwcs='logical',
                      columns='1 2',
                      formats='%10.1f %10.1f')
        iraf.tvmark(1,
                    'tmp.pix',
                    mark="circle",
                    number='yes',
                    radii=10,
                    nxoffse=5,
                    nyoffse=5,
                    color=214,
                    txsize=2)
        xx, yy = string.split(iraf.fields('tmp.pix', '1,2', Stdout=1)[2])
        print xx, yy
        os.system('rm -rf tmp.*')
    else:
        xx, yy = '', ''
        print '### WARNING: no object in the list'
    return xx, yy
示例#11
0
    print '####################################### '
    print "#### Error with the header !!!!"
    print '### telescope not in the list '
    print '### if you want to continue anyway,'
    print '### run "svother.py" to correct header '
    print '######################################## '

##########################################################################

src.delete(coordinatelist + ".tv")
src.delete(coordinatelist + "_templ.coo")
src.delete("_templ.*")
try:
    dir_system = subdirectory[_system]
    iraf.fields('home$coordinate_std/' + dir_system + coordinatelist + '.list',
                '2,3,1',
                Stdout=coordinatelist + '.tv')
    iraf.fields('home$coordinate_std/' + dir_system + coordinatelist + '.list',
                '1',
                Stdout='_templ.coo')
    iraf.wcsctran(coordinatelist + '.tv',
                  '_templ.coo2',
                  'home$coordinate_std/' + dir_system + coordinatelist +
                  '_templ.fits',
                  inwcs='world',
                  units='degrees degrees',
                  outwcs='logical',
                  columns='1 2',
                  formats='%10.1f %10.1f')
    a = iraf.fields('_templ.coo', '1', Stdout=1)
    b = iraf.fields('_templ.coo2', '1,2', Stdout=1)[2:]
示例#12
0
def ecpsf(img,
          ofwhm,
          threshold,
          interactive,
          ds9,
          fixaperture=False,
          _catalog=''):
    try:
        import agnkey
        import string

        hdr = agnkey.util.readhdr(img + '.fits')
        instrument = agnkey.util.readkey3(hdr, 'instrume')
        print 'INSTRUMENT:', instrument

        if 'PIXSCALE' in hdr:
            pixelscale = agnkey.util.readkey3(hdr, 'PIXSCALE')
        elif 'CCDSCALE' in hdr:
            if 'CCDXBIN' in hdr:
                pixelscale = agnkey.util.readkey3(
                    hdr, 'CCDSCALE') * agnkey.util.readkey3(hdr, 'CCDXBIN')
            elif 'CCDSUM' in hdr:
                pixelscale = agnkey.util.readkey3(hdr, 'CCDSCALE') * int(
                    string.split(agnkey.util.readkey3(hdr, 'CCDSUM'))[0])

        if instrument in [
                'kb05', 'kb70', 'kb71', 'kb73', 'kb74', 'kb75', 'kb76', 'kb77',
                'kb78', 'kb79'
        ]:
            scale = pixelscale
            _datamax = 45000
        elif instrument in ['fl02', 'fl03', 'fl04']:
            scale = pixelscale
            _datamax = 120000
        elif instrument in ['fs01', 'em03']:
            scale = pixelscale
            _datamax = 65000
        elif instrument in ['fs02', 'fs03']:
            scale = pixelscale
            _datamax = 65000
        elif instrument in ['em01']:
            scale = pixelscale
            _datamax = 65000
        try:
            _wcserr = agnkey.util.readkey3(hdr, 'wcserr')
            if float(_wcserr) == 0:
                if instrument in [
                        'kb05', 'kb70', 'kb71', 'kb73', 'kb74', 'kb75', 'kb76',
                        'kb77', 'kb78', 'kb79'
                ]:
                    seeing = float(agnkey.util.readkey3(hdr, 'L1FWHM')) * .75
                elif instrument in ['fl02', 'fl03', 'fl04']:
                    seeing = float(agnkey.util.readkey3(hdr, 'L1FWHM')) * .75
                elif instrument in ['fs01', 'fs02', 'fs03', 'em03', 'em01']:
                    if 'L1FWHM' in hdr:
                        seeing = float(agnkey.util.readkey3(hdr,
                                                            'L1FWHM')) * .75
                    elif 'L1SEEING' in hdr:
                        seeing = float(agnkey.util.readkey3(
                            hdr, 'L1SEEING')) * scale
                    else:
                        seeing = 3
                else:
                    seeing = 3
            else:
                seeing = float(agnkey.util.readkey3(hdr, 'PSF_FWHM'))
                sys.exit('astrometry not good')
        except:
            sys.exit('astrometry not good')

        fwhm = seeing / scale
        print 'FWHM[header]  ', fwhm, '   in pixel'
        if ofwhm:
            fwhm = float(ofwhm)
        print '    FWHM[input]  ', fwhm, ' in pixel'

        if interactive:
            iraf.display(img, 1, fill=True)
            iraf.delete('tmp.lo?', verify=False)
            print '_' * 80
            print '>>> Mark reference stars with "a". Then "q"'
            print '-' * 80
            iraf.imexamine(img,
                           1,
                           wcs='logical',
                           logfile='tmp.log',
                           keeplog=True)
            xyrefer = iraf.fields('tmp.log', '1,2,6,15', Stdout=1)
            xns, yns, _fws = [], [], []
            ff = open('_ap.coo', 'w')
            for i in range(len(xyrefer)):
                xns.append(float(xyrefer[i].split()[0]))
                yns.append(float(xyrefer[i].split()[1]))
                _fws.append(float(xyrefer[i].split()[3]))
                ff.write('%10.3f %10.3f %7.2f \n' %
                         (xns[i], yns[i], float(_fws[i])))
            ff.close()

        elif _catalog:
            #            cat1=agnkey.agnastrodef.readtxt(_catalog)
            #            cat1['ra'],cat1['dec']
            ddd = iraf.wcsctran(input=_catalog,
                                output='STDOUT',
                                Stdout=1,
                                image=img,
                                inwcs='world',
                                outwcs='logical',
                                units='degrees degrees',
                                columns='1 2',
                                formats='%10.1f %10.1f',
                                verbose='no')
            ddd = [i for i in ddd if i[0] != '#']
            ddd = ['  '.join(i.split()[0:3]) for i in ddd]
            ff = open('_ap.coo', 'w')
            for i in ddd:
                a, b, c = string.split(i)
                #print a,b,c
                ff.write('%10s %10s %10s \n' % (a, b, c))
            ff.close()
            print 'use catalog'
        else:
            xs, ys, ran, decn, magbest, classstar, fluxrad, bkg = runsex(
                img, fwhm, threshold, scale)
            ff = open('_ap.coo', 'w')
            for i in range(len(xs)):
                ff.write('%10.3f %10.3f %7.2f \n' %
                         (xs[i], ys[i], float(fluxrad[i])))
            ff.close()  ## End automatic selection

        print 80 * "#"
        photmag = apfit(img, fwhm, hdr, interactive, _datamax, fixaperture)

        radec = iraf.wcsctran(input='STDIN', output='STDOUT', Stdin=photmag, \
                              Stdout=1, image=img, inwcs='logical', outwcs='world', columns="1 2", \
                              format='%13.3H %12.2h', min_sig=9, mode='h')[3:]

        exptime = agnkey.util.readkey3(hdr, 'exptime')
        object = agnkey.util.readkey3(hdr, 'object').replace(' ', '')
        filtro = agnkey.util.readkey3(hdr, 'filter')

        #######################################
        rap, decp, magp2, magp3, magp4, smagf = [], [], [], [], [], []
        merrp2, merrp3, merrp4, smagerrf = [], [], [], []
        rap0, decp0 = [], []
        for i in range(len(radec)):
            aa = radec[i].split()
            rap.append(aa[0])
            decp.append(aa[1])
            rap0.append(agnkey.agnabsphotdef.deg2HMS(ra=aa[0]))
            decp0.append(agnkey.agnabsphotdef.deg2HMS(dec=aa[1]))
            idp = aa[2]
            magp2.append(aa[3])
            magp3.append(aa[4])
            magp4.append(aa[5])
            merrp2.append(aa[6])
            merrp3.append(aa[7])
            merrp4.append(aa[8])

        tbhdu = pyfits.new_table(
            pyfits.ColDefs([
                pyfits.Column(name='ra', format='20A', array=np.array(rap)),
                pyfits.Column(name='dec', format='20A', array=np.array(decp)),
                pyfits.Column(name='ra0', format='E', array=np.array(rap0)),
                pyfits.Column(name='dec0', format='E', array=np.array(decp0)),
                pyfits.Column(name='magp2',
                              format='E',
                              array=np.array(
                                  np.where((np.array(magp2) != 'INDEF'),
                                           np.array(magp2), 9999), float)),
                pyfits.Column(name='magp3',
                              format='E',
                              array=np.array(
                                  np.where((np.array(magp3) != 'INDEF'),
                                           np.array(magp3), 9999), float)),
                pyfits.Column(name='magp4',
                              format='E',
                              array=np.array(
                                  np.where((np.array(magp4) != 'INDEF'),
                                           np.array(magp4), 9999), float)),
                pyfits.Column(name='merrp2',
                              format='E',
                              array=np.array(
                                  np.where((np.array(merrp2) != 'INDEF'),
                                           np.array(merrp2), 9999), float)),
                pyfits.Column(name='merrp3',
                              format='E',
                              array=np.array(
                                  np.where((np.array(merrp3) != 'INDEF'),
                                           np.array(merrp3), 9999), float)),
                pyfits.Column(name='merrp4',
                              format='E',
                              array=np.array(
                                  np.where((np.array(merrp4) != 'INDEF'),
                                           np.array(merrp4), 9999), float)),
                pyfits.Column(name='smagf',
                              format='E',
                              array=np.array(
                                  np.where((np.array(magp2) != 'INDEF'),
                                           np.array(magp2), 9999), float)),
                pyfits.Column(name='smagerrf',
                              format='E',
                              array=np.array(
                                  np.where((np.array(merrp2) != 'INDEF'),
                                           np.array(merrp2), 9999), float)),
            ]))
        hdu = pyfits.PrimaryHDU(header=hdr)
        thdulist = pyfits.HDUList([hdu, tbhdu])
        agnkey.util.delete(img + '.sn2.fits')
        thdulist.writeto(img + '.sn2.fits')
        agnkey.util.updateheader(img + '.sn2.fits', 0, {
            'XDIM':
            [agnkey.util.readkey3(hdr, 'naxis1'), 'x number of pixels']
        })
        agnkey.util.updateheader(img + '.sn2.fits', 0, {
            'YDIM':
            [agnkey.util.readkey3(hdr, 'naxis2'), 'y number of pixels']
        })
        agnkey.util.updateheader(img + '.sn2.fits', 0, {
            'PSF_FWHM':
            [fwhm * scale, 'FWHM (arcsec) - computed with daophot']
        })
        os.chmod(img + '.sn2.fits', 0664)
        os.chmod(img + '.psf.fits', 0664)
        result = 1

    except:
        result = 0
        fwhm = 0.0
        traceback.print_exc()
    return result, fwhm * scale
示例#13
0
def fwhm_computation(img, tmpfiltercoo, stars, system, interactive):
    from snoopy2 import src
    import snoopy2
    import string, os
    from numpy import compress
    from numpy import array
    from numpy import average
    from numpy import mean
    from numpy import median
    from numpy import std
    from pyraf import iraf
    from numpy import log10
    _telescope = src.telescope(img)
    _header = src.read_parameter(_telescope, system)
    _xdimen = src.xdimen(img, _telescope)
    _ydimen = src.ydimen(img, _telescope)
    _filter = src.filter(img, _header, _telescope)
    try:
        filter = src.filtername(_telescope, _filter, system)
    except:
        filter = _filter
    _exptime = src.exptime(img, _header, _telescope)

    iraf.delete("tmp.imex_output", verify='no')
    stars_pos = []
    alllines = []

    ff = open(tmpfiltercoo, 'r')
    for j in range(0, 3):
        exl = ff.readline()
    for j in range(len(stars)):
        alllines.append(ff.readline())
        xx = string.split(alllines[-1])[0:2]
        os.system('echo ' + xx[0] + ' ' + xx[1] + '> tmp.two')
        pp = iraf.imexam(input=img,
                         frame=1,
                         logfile='',
                         keeplog='no',
                         imagecur='tmp.two',
                         defkey='m',
                         wcs='logical',
                         use_disp='no',
                         Stdout=1)
        if not 1. <= float(xx[0]) <= float(_xdimen) or not 1. <= float(
                xx[1]) <= float(_ydimen):
            stars_pos.append(0)
        elif string.split(pp[1])[-1] == string.split(pp[1])[-2]:
            stars_pos.append(0)
        else:
            stars_pos.append(1)
    ff.close()
    ff = open('tmp.' + img + 'good.coo', 'w')
    for i in range(len(stars_pos)):
        if stars_pos[i]:
            ff.write(alllines[i])
    ff.close()
    for i in range(len(alllines)):
        if stars_pos[i]:
            ff = open('tmp.one', 'w')
            xx = string.split(alllines[i])[0:2]
            ff.write(xx[0] + ' ' + xx[1] + '  a')
            ff.close()
            try:
                iraf.imexam(input=img,
                            frame=1,
                            logfile='tmp.imex_output',
                            keeplog='yes',
                            imagecur='tmp.one',
                            wcs='logical',
                            use_disp='no')
            except:
                if not os.path.isfile('tmp.imex_output'):
                    os.system("echo '# [1] " + str(img) + " - " +
                              str(coordinatelist) + "' > tmp.imex_output")
                    os.system(
                        "echo '#   COL    LINE   COORDINATES      R    MAG    FLUX     SKY    PEAK    E   PA BETA ENCLOSED   MOFFAT DIRECT' >> tmp.imex_output"
                    )
                    os.system(
                        "echo '999.  999. 999. 999.  INDEF INDEF INDEF INDEF INDEF INDEF INDEF INDEF INDEF INDEF INDEF' >> tmp.imex_output"
                    )
                else:
                    os.system(
                        "echo '999.  999. 999. 999.  INDEF INDEF INDEF INDEF INDEF INDEF INDEF INDEF INDEF INDEF INDEF' >> tmp.imex_output"
                    )

    _fwhm0 = iraf.fields('tmp.imex_output', '15', Stdout=1)
    _mag = iraf.fields('tmp.imex_output', '6', Stdout=1)
    _fwhm, _magime = [], []
    j = 0
    for i in range(len(stars)):
        if stars_pos[i]:
            try:
                _magime.append(float(_mag[j]) + 2.5 * log10(_exptime))
            except:
                _magime.append(float(9999))
            try:
                _fwhm.append(float(_fwhm0[j]))
            except:
                _fwhm.append(float(9999))
            j = j + 1
        else:
            _magime.append(float(9999))
            _fwhm.append(float(9999))

    fwhm_ave = compress((array(_fwhm) < 999), _fwhm)

    fwhm_ave1 = compress(
        (average(fwhm_ave) - 2 * std(fwhm_ave) < array(fwhm_ave)) &
        (array(fwhm_ave) < average(fwhm_ave) + std(fwhm_ave) * 2),
        array(fwhm_ave))
    _fwhm_ave = mean(
        compress((average(fwhm_ave1) - 2 * std(fwhm_ave1) < array(fwhm_ave1)) &
                 (array(fwhm_ave1) < average(fwhm_ave1) + std(fwhm_ave1) * 2),
                 array(fwhm_ave1)))

    fwhm_ave22 = compress(
        (average(fwhm_ave) - 2 * std(fwhm_ave) < array(fwhm_ave)) &
        (array(fwhm_ave) < average(fwhm_ave) + std(fwhm_ave) * 2),
        array(fwhm_ave))
    _fwhm_ave2 = median(
        compress(
            (average(fwhm_ave22) - 2 * std(fwhm_ave22) < array(fwhm_ave22)) &
            (array(fwhm_ave22) < average(fwhm_ave22) + std(fwhm_ave22) * 2),
            array(fwhm_ave22)))

    checkfwhm = 'yes'
    while checkfwhm == 'yes':
        print '################ FWHM(median) = ' + str(_fwhm_ave2) + '  '
        print '################ FWHM(mean) = ' + str(_fwhm_ave) + '  '
        if interactive:
            fwhm_ave = raw_input('################ FWHM = [' +
                                 str(_fwhm_ave2) + '] ? ')
        else:
            fwhm_ave = str(_fwhm_ave2)
        try:
            if not fwhm_ave: fwhm_ave = _fwhm_ave2
            else: fwhm_ave = float(fwhm_ave)
            checkfwhm = 'no'
        except:
            print 'WARNING: FWHM not good !!!!'
            checkfwhm = 'yes'

    #fwhm[filter]=fwhm_ave
    iraf.hedit(img, 'qubafwhm', fwhm_ave, add='yes', update='yes', verify='no')
    return fwhm_ave, _magime, stars_pos, _fwhm
示例#14
0
def register_module(img, _system, coordinatelist, interactive, logincl,
                    _filter):
    from snoopy2 import src
    import snoopy2
    import string, os

    #    logincl=src.open_program()
    from pyraf import iraf
    iraf.astcat(_doprint=0)
    iraf.imcoords(_doprint=0)
    iraf.set(stdimage='imt1024')
    iraf.tv.rimexam.backgrou = 'yes'

    subdirectory = ['optical/', 'infrared/', 'sloan/']
    iraf.delete(coordinatelist + ".tv", verify='no')
    iraf.delete(coordinatelist + "_templ.coo", verify='no')
    iraf.delete("_templ.*", verify='no')
    try:
        dir_system = subdirectory[_system]
        iraf.fields('home$coordinate_std/' + dir_system + coordinatelist +
                    '.list',
                    '2,3,1',
                    Stdout=coordinatelist + '.tv')
        iraf.fields('home$coordinate_std/' + dir_system + coordinatelist +
                    '.list',
                    '1',
                    Stdout='_templ.coo')
        iraf.wcsctran(coordinatelist + '.tv',
                      '_templ.coo2',
                      'home$coordinate_std/' + dir_system + coordinatelist +
                      '_templ.fits',
                      inwcs='world',
                      units='degrees degrees',
                      outwcs='logical',
                      columns='1 2',
                      formats='%10.1f %10.1f')
        a = iraf.fields('_templ.coo', '1', Stdout=1)
        b = iraf.fields('_templ.coo2', '1,2', Stdout=1)[2:]
        ff = open(coordinatelist + '_templ.coo', 'w')
        for i in range(len(a)):
            ff.write(b[i] + '\t' + a[i] + ' \n')
        ff.close()
        if _system == 0 or _system == 2:
            standard = iraf.fields('home$coordinate_std/' + dir_system +
                                   coordinatelist + '.list',
                                   '1,4,5,6,7,8',
                                   Stdout=1)
        else:
            standard = iraf.fields('home$coordinate_std/' + dir_system +
                                   coordinatelist + '.list',
                                   '1,4,5,6',
                                   Stdout=1)
    except Exception as e:
        print e
        print "WARNING: no coordinate  " + coordinatelist + " file found in " + snoopy2.__path__[
            0] + '/coordinate_std/' + dir_system + '  !!! '
        src.close_program(logincl)
    stars = []
    for i in standard:
        nome = string.split(i)
        stars.append(nome[0])

#    _filter='XXX'
    src.delete("tmp." + img + ".coo")
    iraf.wcsctran(coordinatelist + '.tv',
                  'tmp.' + img + '.coo',
                  img,
                  inwcs='world',
                  units='degrees degrees',
                  outwcs='logical',
                  columns='1 2',
                  formats='%10.1f %10.1f')

    if interactive:
        print '######### Select FRAME TILE on your DS9 !!!!!'
        _z1, _z2, goon = src.display_image(
            snoopy2.__path__[0] + '/coordinate_std/' + dir_system +
            coordinatelist + '_templ.fits', 2, '', '', False)
        if not goon: src.close_program(logincl)

        iraf.tvmark(2,
                    coordinatelist + '_templ.coo',
                    mark="circle",
                    number='no',
                    label='yes',
                    radii=20,
                    nxoffse=15,
                    nyoffse=15,
                    color=214,
                    txsize=4)

        _z1, _z2, goon = src.display_image(img, 1, '', '', False)
        if not goon: src.close_program(logincl)

        iraf.tvmark(1,
                    'tmp.' + img + '.coo',
                    mark="circle",
                    number='no',
                    label='yes',
                    radii=20,
                    nxoffse=15,
                    nyoffse=15,
                    color=205,
                    txsize=2)
        answ = raw_input(
            'is the astrometry of the field good ? \n [y/n] ? [y] ')
        if not answ: answ = 'y'

        if answ == 'n':
            try:
                src.delete('tmp.' + img + '.coo')
                src.delete('tmp.ccdb')
                iraf.ccmap('_first.ccmap',
                           'tmp.ccdb',
                           images=img,
                           fitgeome='rscale',
                           lngunit='degrees',
                           update='yes',
                           interact=False)
                iraf.wcsctran('_first_image.tv',
                              'tmp.' + img + '.coo',
                              img,
                              inwcs='world',
                              units='degrees degrees',
                              outwcs='logical',
                              columns='1 2',
                              formats='%10.1f %10.1f')
                iraf.tvmark(1,
                            'tmp.' + img + '.coo',
                            mark="circle",
                            number='no',
                            label='yes',
                            radii=20,
                            nxoffse=15,
                            nyoffse=15,
                            color=206,
                            txsize=4)
                answ = raw_input(
                    'AND NOW, is the astrometry of the field good [y/n] ? [y] '
                )
                if not answ: answ = 'y'
            except:
                pass

        while answ == 'n':

            _z1, _z2, goon = src.display_image(img, 1, '', '', False)
            if not goon: src.close_program(logincl)

            print '>> Identify (minimum 2, preferably 3) reference stars (mark with "a")'
            iraf.delete('tmp.coo', verify='no')
            iraf.imexamine(img, 1, logfile='tmp.coo', keeplog='yes')
            iraf.tvmark(1,
                        'tmp.coo',
                        mark="circle",
                        number='yes',
                        label='no',
                        radii=15,
                        nxoffse=15,
                        nyoffse=15,
                        color=214,
                        txsize=4)
            xycoo = iraf.fields('tmp.coo', '1,2,13', Stdout=1)
            print '>> Identify reference stars'
            idcat = []
            for i in range(len(xycoo)):
                idcat.append(raw_input('Star ' + str(i + 1) + '= ? '))

            ff = open(coordinatelist + '.tv', 'r')
            rr = ff.readlines()
            ff.close()
            gg = open('tmp.ccmap', 'w')
            fw = []
            for i in range(len(idcat)):
                idpos = stars.index(idcat[i])
                _rr = string.split(rr[idpos])
                _x, _y, _fw = string.split(xycoo[i])
                gg.write(_x + ' ' + _y + ' ' + _rr[0] + ' ' + _rr[1] + ' \n')
                fw.append(float(_fw))
            gg.close()
            iraf.delete('_first_image.tv', verify='no')
            iraf.delete('_first.ccmap', verify='no')
            os.system('cp ' + coordinatelist + '.tv _first_image.tv')
            os.system('cp tmp.ccmap  _first.ccmap')
            iraf.ccmap('tmp.ccmap',
                       'tmp.ccdb',
                       images=img,
                       fitgeome='rscale',
                       lngunit='degrees',
                       update='yes',
                       interact=False)
            _z1, _z2, goon = src.display_image(img, 1, '', '', False)
            if not goon: src.close_program(logincl)

            iraf.delete('tmp.' + img + '.coo', verify='no')
            iraf.wcsctran(coordinatelist + '.tv',
                          'tmp.' + img + '.coo',
                          img,
                          inwcs='world',
                          units='degrees degrees',
                          outwcs='logical',
                          columns='1 2',
                          formats='%10.1f %10.1f')
            iraf.tvmark(1,
                        'tmp.' + img + '.coo',
                        mark="circle",
                        number='yes',
                        label='no',
                        radii=20,
                        nxoffse=15,
                        nyoffse=15,
                        color=205,
                        txsize=4)
            iraf.delete("tmp.ccmap", verify='no')
            iraf.delete("tmp.coo", verify='no')
            iraf.delete("tmp.ccdb", verify='no')
            answ = raw_input(
                'is the astrometry of the field good  [y/n] ? [y]')
            if not answ: answ = 'y'

    iraf.delete("tmp.star", verify='no')
    iraf.ccfind('home$coordinate_std/' + dir_system + coordinatelist + '.list',
                'tmp.star',
                img,
                lngcolu=2,
                latcolu=3,
                lngunit='degrees',
                usewcs='yes')
    iraf.ccmap('tmp.star',
               'tmp.ccdb',
               images=img,
               fitgeome='rscale',
               xcolum=9,
               ycolum=10,
               lngcolum=2,
               latcolumn=3,
               lngunit='degrees',
               update='yes',
               interact=False)
    iraf.delete('tmp.' + img + '.coo', verify='no')
    iraf.wcsctran(coordinatelist + '.tv',
                  'tmp.' + img + '.coo',
                  img,
                  inwcs='world',
                  units='degrees degrees',
                  outwcs='logical',
                  columns='1 2',
                  formats='%10.1f %10.1f')
    iraf.delete("tmp.ccdb", verify='no')
    iraf.delete("tmp.star", verify='no')
    iraf.delete("tmp.coo", verify='no')
    return stars, 'tmp.' + img + '.coo'
示例#15
0
文件: agnpsf.py 项目: svalenti/agnkey
def ecpsf(img, ofwhm, threshold, psfstars, distance, interactive, ds9, psffun='gauss', fixaperture=False,_catalog='',_datamax=''):
    try:
        import agnkey
        hdr = agnkey.util.readhdr(img + '.fits')
        instrument = agnkey.util.readkey3(hdr, 'instrume')
        print ('INSTRUMENT:', instrument)
        if 'PIXSCALE' in hdr:
            pixelscale = agnkey.util.readkey3(hdr, 'PIXSCALE')
        elif 'CCDSCALE' in hdr:
            if 'CCDXBIN' in hdr:
                pixelscale = agnkey.util.readkey3(hdr, 'CCDSCALE') * agnkey.util.readkey3(hdr, 'CCDXBIN')
            elif 'CCDSUM' in hdr:
                pixelscale = agnkey.util.readkey3(hdr, 'CCDSCALE') * int(
                    string.split(agnkey.util.readkey3(hdr, 'CCDSUM'))[0])

        if 'kb' in instrument:  
            scale = pixelscale
            if not _datamax:
                _datamax = 45000
        elif 'fl' in instrument:
            scale = pixelscale
            if not _datamax:
                _datamax = 60000
        elif 'fa' in instrument:
            scale = pixelscale
            if not _datamax:
                _datamax = 60000
        elif 'fs' in instrument:
            scale = pixelscale
            if not _datamax:
                _datamax = 65000
        try:
        #if 1==1:
            if 'WCSERR' in hdr:
                _wcserr = hdr['WCSERR']
            elif 'WCS_ERR' in hdr:
                _wcserr = hdr['WCS_ERR']
            print _wcserr
            if float(_wcserr) == 0:
                if 'kb' in instrument:  
                    seeing = float(agnkey.util.readkey3(hdr, 'L1FWHM')) * .75
                elif 'fl' in instrument:     
                    seeing = float(agnkey.util.readkey3(hdr, 'L1FWHM')) * .75
                elif 'fa' in instrument:     
                    seeing = float(agnkey.util.readkey3(hdr, 'L1FWHM')) * .75
                elif 'fs' in instrument: 
                    if 'L1FWHM' in hdr:
                        seeing = float(agnkey.util.readkey3(hdr, 'L1FWHM')) * .75
                    elif 'L1SEEING' in hdr:
                        seeing = float(agnkey.util.readkey3(hdr, 'L1SEEING')) * scale
                    else:
                        seeing = 3
                else:
                    seeing = 3
            else:
                seeing = float(agnkey.util.readkey3(hdr, 'PSF_FWHM'))
                sys.exit('astrometry not good')
        except ValueError:
#        except:
            sys.exit('astrometry not good')

        fwhm = seeing / scale
        print 'FWHM[header]  ', fwhm, '   in pixel'
        if ofwhm: fwhm = float(ofwhm)
        print '    FWHM[input]  ', fwhm, ' in pixel'
        xdim, ydim = iraf.hselect(img+'.fits[0]', 'i_naxis1,i_naxis2', 'yes', Stdout=1)[0].split()
        print img, fwhm, threshold, scale

        #################################################################################
        ###################        write file to compute psf     _psf.coo    ############
        #################################################################################
        if interactive:
            iraf.set(stdimage='imt1024')
            iraf.display(img+'.fits[0]', 1, fill=True)
            iraf.delete('tmp.lo?', verify=False)
            print '_' * 80
            print '>>> Mark reference stars with "a". Then "q"'
            print '-' * 80
            iraf.imexamine(img+'[0]', 1, wcs='logical', logfile='tmp.log', keeplog=True)
            xyrefer = iraf.fields('tmp.log', '1,2,6,15', Stdout=1)
            xns, yns, _fws = [], [], []

            #############      write    file for PSF                           #########################
            ff = open('_psf.coo', 'w')
            for i in range(len(xyrefer)):
                xns.append(float(xyrefer[i].split()[0]))
                yns.append(float(xyrefer[i].split()[1]))
                _fws.append(float(xyrefer[i].split()[3]))
                ff.write('%10.3f %10.3f %7.2f \n' % (xns[i], yns[i], float(_fws[i])))
            ff.close()
            fwhm = np.median(_fws)
        else:
            ############              run  sextractor                #####################################
            xs, ys, ran, decn, magbest, classstar, fluxrad, bkg = runsex(img, fwhm, threshold, scale)
            
            _ra1,_dec1,xx11,yy11,_mag,_dist = agnkey.agnastrodef.starsfields(img+'.fits',20,19)
            if len(_ra1):
                dist,pos0,pos1 = agnkey.agnastrodef.crossmatchxy(xs,ys,xx11,yy11,10)
                if len(pos0):
                    xs = xs[pos0]
                    ys = ys[pos0]
                    ran = ran[pos0]
                    decn = decn[pos0]
                    magbest = magbest[pos0]
                    classstar = classstar[pos0]
                    fluxrad = fluxrad[pos0]
                    bkg = bkg[pos0]


            ff = open('tmp.cursor', 'w')
            for i in range(len(xs)):
                x1, x2 = int(xs[i] - fwhm * 3), int(xs[i] + fwhm * 3)
                y1, y2 = int(ys[i] - fwhm * 3), int(ys[i] + fwhm * 3)
                sect = '[' + str(x1) + ':' + str(x2) + ',' + str(y1) + ':' + str(y2) + ']'
                try:
                    fmax = iraf.imstat(img+'.fits[0]' + sect, fields='max', Stdout=1)[1]
                    ##########       cut saturated object               ########################
                    if float(fmax) < _datamax:  # not saturated
                        ff.write('%10.3f %10.3f 1 m \n' % (xs[i], ys[i]))
                except:
                    print sect
                #    print 'problem here'
                #    pass
            ff.close()

            iraf.delete('tmp.lo?,tmp.sta?,tmp.gk?', verify=False)
            iraf.psfmeasure(img+'[0]', imagecur='tmp.cursor', logfile='tmp.log', radius=int(fwhm), iter=3,
                            display=False, StdoutG='tmp.gki')

            ff = open('tmp.log')
            righe = ff.readlines()
            xn = [float(righe[3].split()[1])]
            yn = [float(righe[3].split()[2])]
            _fw = [float(righe[3].split()[4])]
            for r in righe[4:-2]:
                if len(r) > 0:
                    xn.append(float(r.split()[0]))
                    yn.append(float(r.split()[1]))
                    _fw.append(float(r.split()[3]))
            print 'FWHM: ', righe[-1].split()[-1]
            print 80 * "#"
            ######
            ##############            eliminate double object identification         ###########################
            xns, yns, _fws = [xn[0]], [yn[0]], [_fw[0]]
            for i in range(1, len(xn)):
                if abs(xn[i] - xn[i - 1]) > .2 and abs(yn[i] - yn[i - 1]) > .2:
                    xns.append(xn[i])
                    yns.append(yn[i])
                    _fws.append(_fw[i])
            #########      write clean   file for PSF                           #########################
            fw = []
            ff = open('_psf.coo', 'w')
            for i in range(len(xns)):
                    ff.write('%10.3f %10.3f %7.2f \n' % (xns[i], yns[i], float(_fws[i])))
                    fw.append(_fws[i])
            ff.close()  ## End automatic selection
        ######################################################################################
        ###################        write file of object to store in  fits table  #############
        ######################################################################################
        if interactive:
            xs, ys, ran, decn, magbest, classstar, fluxrad, bkg = runsex(img, fwhm, threshold, scale)
            ff = open('_psf2.coo', 'w')
            for i in range(len(xs)):
                ff.write('%10s %10s %10s \n' % (xs[i], ys[i], fluxrad[i]))
            ff.close()
        elif _catalog:
            print '\n#### use catalog '
            ddd=iraf.wcsctran(input=_catalog,output='STDOUT',Stdout=1,image=img,inwcs='world',outwcs='logical',
                              units='degrees degrees',columns='1 2',formats='%10.1f %10.1f',verbose='no')
            ddd=[i for i in ddd if i[0]!='#']
            ddd=['  '.join(i.split()[0:3]) for i in ddd]
            ff = open('_psf2.coo', 'w')
            for i in ddd:
                a,b,c = string.split(i)
                ff.write('%10s %10s %10s \n' % (a, b, c))
            ff.close()
            print 'use catalog'
        else:
            os.system('cp _psf.coo _psf2.coo')
#                print '\n###   use sextractor'
#                xs, ys, ran, decn, magbest, classstar, fluxrad, bkg = runsex(img, fwhm, threshold, scale)
#                ff = open('_psf2.coo', 'w')
#                for i in range(len(xs)):
#                    ff.write('%10s %10s %10s \n' % (xs[i], ys[i], fluxrad[i]))
#                ff.close()
        ###################################################################################
        print 80 * "#"
        photmag, pst, fitmag = psffit(img, fwhm, psfstars, hdr, interactive, _datamax, psffun, fixaperture)

        photmag2, fitmag2 = psffit2(img, fwhm, psfstars, hdr, _datamax, psffun, fixaperture)

        radec = iraf.wcsctran(input='STDIN', output='STDOUT', Stdin=photmag, \
                              Stdout=1, image=img+'.fits[0]', inwcs='logical', outwcs='world', columns="1 2", \
                              format='%13.3H %12.2h', min_sig=9, mode='h')[3:]

        radec2 = iraf.wcsctran(input='STDIN', output='STDOUT', Stdin=photmag2, \
                               Stdout=1, image=img+'.fits[0]', inwcs='logical', outwcs='world', columns="1 2", \
                               format='%13.3H %12.2h', min_sig=9, mode='h')[3:]

        if ds9 == 0 and interactive:
            iraf.set(stdimage='imt1024')
            iraf.display(img, 1, fill=True, Stdout=1)
            iraf.tvmark(1, coords='STDIN', mark='circle', radii=15, label=False, Stdin=photmag)
            iraf.tvmark(1, coords='STDIN', mark='rectangle', length=35, label=False, Stdin=pst)
            iraf.tvmark(1, coords='STDIN', mark='cross', length=35, label=False, Stdin=fitmag2, color=204)

        idpsf = []
        for i in range(len(pst)):
            idpsf.append(pst[i].split()[2])
        dmag = []
        for i in range(len(radec)):
            ra, dec, idph, magp2, magp3, magp4, merrp2, merrp3, merrp4 = radec[i].split()
            dmag.append(9.99)
            for j in range(len(fitmag)):
                raf, decf, idf, magf, magerrf = fitmag[j].split()
                if idph == idf and idph in idpsf and \
                                magp3 != 'INDEF' and magf != 'INDEF':
                    dmag[i] = float(magp3) - float(magf)
                    break

        _dmag = np.compress(np.array(dmag) < 9.99, np.array(dmag))

        print '>>> Aperture correction (phot)   %6.3f +/- %5.3f %3d ' % \
              (np.mean(_dmag), np.std(_dmag), len(_dmag))
        if len(_dmag) > 3:
            _dmag = np.compress(abs(_dmag - np.median(_dmag)) < 2 * np.std(_dmag), _dmag)
            print '>>>         2 sigma rejection)   %6.3f +/- %5.3f %3d  [default]' \
                  % (np.mean(_dmag), np.std(_dmag), len(_dmag))
            print '>>>     fwhm   %s  ' % (str(fwhm))
        for i in range(len(dmag)):
            if dmag[i] == 9.99:
                dmag[i] = ''
            else:
                dmag[i] = '%6.3f' % (dmag[i])

        exptime = agnkey.util.readkey3(hdr, 'exptime')
        object = agnkey.util.readkey3(hdr, 'object').replace(' ', '')
        filtro = agnkey.util.readkey3(hdr, 'filter')

        #######################################
        rap, decp, magp2, magp3, magp4, smagf = [], [], [], [], [], []
        merrp2, merrp3, merrp4, smagerrf = [], [], [], []
        rap0, decp0 = [], []
        for i in range(len(radec2)):
            aa = radec2[i].split()
            rap.append(aa[0])
            decp.append(aa[1])
            rap0.append(agnkey.agnabsphotdef.deg2HMS(ra=aa[0]))
            decp0.append(agnkey.agnabsphotdef.deg2HMS(dec=aa[1]))
            idp = aa[2]
            magp2.append(aa[3])
            magp3.append(aa[4])
            magp4.append(aa[5])
            merrp2.append(aa[6])
            merrp3.append(aa[7])
            merrp4.append(aa[8])
            _smagf, _smagerrf = 9999, 9999
            for j in range(len(fitmag2)):
                raf, decf, idf, magf, magerrf = fitmag2[j].split()
                if idf == idp:
                    _smagf = magf
                    _smagerrf = magerrf
                    break
            smagf.append(_smagf)
            smagerrf.append(_smagerrf)

        new_cols = pyfits.ColDefs([
            pyfits.Column(name='ra', format='20A', array=np.array(rap)),
            pyfits.Column(name='dec', format='20A', array=np.array(decp)),
            pyfits.Column(name='ra0', format='E', array=np.array(rap0)),
            pyfits.Column(name='dec0', format='E', array=np.array(decp0)),
            pyfits.Column(name='magp2', format='E', array=np.array(np.where((np.array(magp2) != 'INDEF'),
                                                                            np.array(magp2), 9999), float)),
            pyfits.Column(name='magp3', format='E', array=np.array(np.where((np.array(magp3) != 'INDEF'),
                                                                            np.array(magp3), 9999), float)),
            pyfits.Column(name='magp4', format='E', array=np.array(np.where((np.array(magp4) != 'INDEF'),
                                                                            np.array(magp4), 9999), float)),
            pyfits.Column(name='merrp2', format='E', array=np.array(np.where((np.array(merrp2) != 'INDEF'),
                                                                             np.array(merrp2), 9999), float)),
            pyfits.Column(name='merrp3', format='E', array=np.array(np.where((np.array(merrp3) != 'INDEF'),
                                                                             np.array(merrp3), 9999), float)),
            pyfits.Column(name='merrp4', format='E', array=np.array(np.where((np.array(merrp4) != 'INDEF'),
                                                                             np.array(merrp4), 9999), float)),
            pyfits.Column(name='smagf', format='E', array=np.array(np.where((np.array(smagf) != 'INDEF'),
                                                                            np.array(smagf), 9999), float)),
            pyfits.Column(name='smagerrf', format='E', array=np.array(np.where((np.array(smagerrf) != 'INDEF'),
                                                                               np.array(smagerrf), 9999), float)),
        ])
        
        tbhdu = pyfits.BinTableHDU.from_columns(new_cols)
        
        hdu = pyfits.PrimaryHDU(header=hdr)
        thdulist = pyfits.HDUList([hdu, tbhdu])
        agnkey.util.delete(img + '.sn2.fits')
        thdulist.writeto(img + '.sn2.fits')
        agnkey.util.updateheader(img + '.sn2.fits', 0, {'APCO': [np.mean(_dmag), 'Aperture correction']})
        agnkey.util.updateheader(img + '.sn2.fits', 0, {'APCOERR': [np.std(_dmag), 'Aperture correction error']})
        agnkey.util.updateheader(img + '.sn2.fits', 0,
                                 {'XDIM': [agnkey.util.readkey3(hdr, 'naxis1'), 'x number of pixels']})
        agnkey.util.updateheader(img + '.sn2.fits', 0,
                                 {'YDIM': [agnkey.util.readkey3(hdr, 'naxis2'), 'y number of pixels']})
        agnkey.util.updateheader(img + '.sn2.fits', 0,
                                 {'PSF_FWHM': [fwhm * scale, 'FWHM (arcsec) - computed with daophot']})
        os.chmod(img + '.sn2.fits', 0664)
        os.chmod(img + '.psf.fits', 0664)
        result = 1
    except IOError as e:
        print e
        result = 0
        fwhm = 0.0
        traceback.print_exc()
    return result, fwhm * scale