Ejemplo n.º 1
0
def align_combine(fitsdir, myfilter, examine=True):
    from pyraf import iraf 
    
    iraf.noao(_doprint=0)
    iraf.digiphot(_doprint=0)
    iraf.apphot(_doprint=0)
    
    os.chdir(fitsdir)
    listfiles = glob.glob(myfilter)
    listfiles.sort()
    
    if (examine):
        print "Opening ",listfiles[0]," to examine."
        iraf.imexamine(input=listfiles[0], \
                    logfile="coords.dat", \
                    keeplog="yes")
        
        with open("align.list",'w') as f:
            for i in listfiles:
                f.write(i+"\n")
    
    print "Aligning with reference:",listfiles[0]
    iraf.imalign( input   =  "@align.list", referenc= listfiles[0], coords  =  "coords.dat", output  = "*****@*****.**")  
    
    listfiles = glob.glob("a_"+myfilter)
    listfiles.sort()
    with open("comb.list",'w') as f:
        for i in listfiles:
            f.write(i+"\n")
            
    print "Combining"        
    iraf.imcombine(input = "@comb.list",\
                   output = "out.fits",\
                   combine= "median")
Ejemplo n.º 2
0
def align_combine(fitsdir, myfilter, examine=True):
    from pyraf import iraf 
    
    iraf.noao(_doprint=0)
    iraf.digiphot(_doprint=0)
    iraf.apphot(_doprint=0)
    
    os.chdir(fitsdir)
    listfiles = glob.glob(myfilter)
    listfiles.sort()
    
    if (examine):
        print "Opening ",listfiles[0]," to examine."
        iraf.imexamine(input=listfiles[0], \
                    logfile="coords.dat", \
                    keeplog="yes")
        
        with open("align.list",'w') as f:
            for i in listfiles:
                f.write(i+"\n")
    
    print "Aligning with reference:",listfiles[0]
    iraf.imalign( input   =  "@align.list", referenc= listfiles[0], coords  =  "coords.dat", output  = "*****@*****.**")  
    
    listfiles = glob.glob("a_"+myfilter)
    listfiles.sort()
    with open("comb.list",'w') as f:
        for i in listfiles:
            f.write(i+"\n")
            
    print "Combining"        
    iraf.imcombine(input = "@comb.list",\
                   output = "out.fits",\
                   combine= "median")
Ejemplo n.º 3
0
def check():
    lstlst = ['objlst']
    if os.path.isfile('objlst'):
        webbrowser.open('objlst')
        webbrowser.open('../errfilelst')
        iraf.imexamine(input='@objlst', frame=1)
    print '<<<<<check the list>>>>>'
Ejemplo n.º 4
0
def checkfile(filename):
    '''Print statistics and run open imexamine task'''

    iraf.imstatistics.unlearn()
    iraf.imexamine.unlearn()
    print 'Check output file:'
    iraf.imstatistics(filename)
    print ' Running "imexamine" task..'
    iraf.imexamine(filename, 1)
Ejemplo n.º 5
0
def checkfile(filename):
    '''Print statistics and run open imexamine task'''

    iraf.imstatistics.unlearn()
    iraf.imexamine.unlearn()
    print 'Check output file:'
    iraf.imstatistics(filename)
    print ' Running "imexamine" task..'
    iraf.imexamine(filename, 1)
Ejemplo n.º 6
0
def check():
    lstlst = [
        'spec_bias.lst', 'halogen.lst', 'lamp.lst', 'std.lst', 'cor_std.lst'
    ]
    for i in lstlst:
        if os.path.isfile(i):
            webbrowser.open(i)
            iraf.imexamine(input='@%s' % i, frame=1)
            if 'i' == 'cor_std.lst':
                break
Ejemplo n.º 7
0
def check_bias():
    biaspath = os.getcwd() + os.sep + 'bias'
    if os.path.isfile(biaspath + os.sep + 'spec_bias.lst'):
        os.chdir('bias')
        webbrowser.open('spec_bias.lst')
        iraf.imexamine(input='@spec_bias.lst[1]', frame=1)
        dirname = os.path.dirname(os.getcwd())
        os.chdir(dirname)
        iraf.flpr()
    else:
        print('no bias dir in ' + os.getcwd())
Ejemplo n.º 8
0
def check_bias():
    biaspath = os.getcwd() + os.sep + 'bias'
    if os.path.isfile(biaspath + os.sep + 'spec_bias.lst'):
        os.chdir('bias')
        os.system('gedit spec_bias.lst &')
        iraf.imexamine(input = '@spec_bias.lst[1]', frame = 1)
        dirname, filename = os.path.split(os.getcwd())
        os.chdir(dirname)
        iraf.flpr()
    else:
        print('no bias dir in ' + os.getcwd())
Ejemplo n.º 9
0
def getfwhm(images='@imh.lis', coordlist='ref_stars', outfile='getfwhm.log',radius=4.0,buffer=7.0,width=5.0,rplot=15.0,center='no',verbose='no',imagelist=None,mode='al',DOLLARnargs=0,taskObj=None):
	Vars = IrafParList('getfwhm')
	Vars.addParam(makeIrafPar(images, datatype='string', name='images',mode='a',prompt='Input image(s)'))
	Vars.addParam(makeIrafPar(coordlist, datatype='string', name='coordlist',mode='a',prompt='List of object positions'))
	Vars.addParam(makeIrafPar(outfile, datatype='string', name='outfile',mode='a',prompt='Output file'))
	Vars.addParam(makeIrafPar(radius, datatype='real', name='radius', mode='h',prompt='Object radius'))
	Vars.addParam(makeIrafPar(buffer, datatype='real', name='buffer', mode='h',prompt='Background buffer width'))
	Vars.addParam(makeIrafPar(width, datatype='real', name='width', mode='h',prompt='Background width'))
	Vars.addParam(makeIrafPar(rplot, datatype='real', name='rplot', mode='h',prompt='Plotting radius'))
	Vars.addParam(makeIrafPar(center, datatype='bool', name='center', mode='h',prompt='Center object in aperture?'))
	Vars.addParam(makeIrafPar(verbose, datatype='bool', name='verbose',mode='h',prompt='Verbose output?'))
	Vars.addParam(makeIrafPar(imagelist, datatype='struct', name='imagelist',list_flag=1,mode='h'))
	Vars.addParam(makeIrafPar(mode, datatype='string', name='mode', mode='h'))
	Vars.addParam(makeIrafPar(DOLLARnargs, datatype='int', name='$nargs',mode='h'))
	Vars.addParam(makeIrafPar(None, datatype='int', name='len', mode='u'))
	Vars.addParam(makeIrafPar(None, datatype='string', name='image', mode='u'))
	Vars.addParam(makeIrafPar(None, datatype='string', name='imagefile',mode='u'))
	Vars.addParam(makeIrafPar(None, datatype='string', name='imlist', mode='u'))
	Vars.addParam(makeIrafPar(None, datatype='string', name='coords', mode='u'))
	Vars.addParam(makeIrafPar(None, datatype='string', name='outputfile',mode='u'))
	Vars.addParam(makeIrafPar(None, datatype='real', name='rad', mode='u'))
	Vars.addParam(makeIrafPar(None, datatype='real', name='buff', mode='u'))
	Vars.addParam(makeIrafPar(None, datatype='real', name='wid', mode='u'))
	Vars.addParam(makeIrafPar(None, datatype='real', name='rpl', mode='u'))

	Vars.imlist = Vars.images
	Vars.imagefile = iraf.mktemp('tmp$getfwhm')
	iraf.sections(Vars.imlist, option = 'fullname', Stdout=Vars.imagefile)
	Vars.imagelist = Vars.imagefile
	Vars.coords = Vars.coordlist
	Vars.outputfile = Vars.outfile
	Vars.rad = Vars.radius
	Vars.buff = Vars.buffer
	Vars.wid = Vars.width
	Vars.rpl = Vars.rplot
	iraf.rimexam.radius = Vars.rad
	iraf.rimexam.buffer = Vars.buff
	iraf.rimexam.width = Vars.wid
	iraf.rimexam.rplot = Vars.rpl
	if (Vars.center == yes):
		iraf.rimexam.center = yes
	else:
		iraf.rimexam.center = no
	iraf.rimexam.fittype = 'gaussian'
	iraf.rimexam.iterati = 1
	iraf.clPrint('# RIMEXAM Parameter Settings:  Radius=', Vars.rad,', Buffer=',Vars.buff,', Width=',Vars.wid,StdoutAppend=Vars.outputfile)
	while (iraf.fscan(locals(), 'Vars.imagelist', 'Vars.image') != EOF):
		Vars.len = iraf.strlen(Vars.image)
		if (iraf.substr(Vars.image, Vars.len - 3, Vars.len) == '.imh'):
			Vars.image = iraf.substr(Vars.image, 1, Vars.len - 4)
		if (Vars.verbose):
			iraf.clPrint('...processing ', Vars.image)
		iraf.clPrint(Vars.image)
		iraf.imexamine(Vars.image, logfile = Vars.outputfile, keeplog = yes,defkey = 'a',imagecur = Vars.coords,wcs = 'world',use_display = no)
Ejemplo n.º 10
0
def check_other(path):
    if os.path.isdir(path):
        os.chdir(path)
        lstlst = ['halogen.lst', 'lamp.lst', 'cor_lamp.lst','std.lst','cor_std.lst']
        for i in lstlst:
            if os.path.isfile(i):
                os.system('gedit %s &' % i)
                iraf.imexamine(input = '@%s[1]'%i, frame = 1)
        dirname, filename = os.path.split(os.getcwd())
        os.chdir(dirname)
        iraf.flpr()
    else:
        print('no dir ' + path + ' in ' + os.getcwd())
Ejemplo n.º 11
0
def check_other(path):
    if os.path.isdir(path):
        os.chdir(path)
        lstlst = [
            'halogen.lst', 'lamp.lst', 'cor_lamp.lst', 'std.lst', 'cor_std.lst'
        ]
        for i in lstlst:
            if os.path.isfile(i):
                webbrowser.open(i)
                iraf.imexamine(input='@%s[1]' % i, frame=1)
        dirname, filename = os.path.split(os.getcwd())
        os.chdir(dirname)
        iraf.flpr()
    else:
        print('no dir ' + path + ' in ' + os.getcwd())
Ejemplo n.º 12
0
def check_bias():
	print 'check bias...'
	print '***please remove the bad bias from the list***'
	f = open('bias.lst')
	l = f.readlines()
	f.close()
	if len(l) != 0:
		os.popen("gedit bias.lst &")
		iraf.imexamine(input = '@bias.lst//[1]', frame = 1)
	else:
		os.remove('bias.lst')
		label = raw_input('bias.lst has no fits files, do you want to use older bias?')
		if label == 'y' or label == 'Y' or label == 'yes' or label == 'Yes':
			path = raw_input('Please input the path of the file:')
			print 'copying older flat ' + path + '...'
			shutil.copy(path, './')
Ejemplo n.º 13
0
def check_obj():
	print 'check object...'
	print '***please correct the wrong fits in the list***'
	name = os.popen('ls object*.lst').readlines()
	name = [i.split('\n')[0] for i in name]
	for i in name:
		f = open(i)
		l = f.readlines()
		f.close()
		l = [i2.split('\n')[0] for i2 in l if '.fits' in i2]
		output = open('temp.lst', 'w')
		for i2 in l:
			output.write(i2 + '\n')
		output.close()
		os.popen("gedit " + i + " &")
                iraf.imexamine(input = '@temp.lst//[1]', frame = 1)
	os.remove("temp.lst")
Ejemplo n.º 14
0
def shift_align(filenames):
    if len(filenames) == 0:
        return ''
    fno = 1
    for i in filenames:
        iraf.display(image = i, frame = fno)
        fno += 1
    print 'The fits number is', len(filenames)
    if len(filenames) > 1:
        print 'Please check the fits pic and determine whether you need to shift the pic'
        print 'imexamine...'
        iraf.imexamine()
        valget = raw_input('Are you need to shift the fits picture?(y)')
        if valget == 'y' or valget == 'Y':
            nfilenames = [filenames[0]]
            for i2 in filenames:
                print 'implot ' + i2
                iraf.implot(image = i2)
            fno = 1
            iraf.immatch()
            while fno < len(filenames):
                valget = raw_input('Please input ' + filenames[fno] + ' xshift, yshift: ')
                valget = valget.split()
                fxshift = float(valget[0])
                fyshift = float(valget[1])
                ims_key = 1
                if os.path.isfile('shift_' + filenames[fno]):
                    valget = raw_input('shift_' + filenames[fno] + ' is already exist, are you want to delete the old one?(y):')
                    if valget == 'y' or valget == 'Y' or valget == 'yes' or valget == 'Yes':
                        os.remove('shift_' + filenames[fno])
                    else:
                        ims_key = 0
                if ims_key == 1:
                    print 'what happend????????????????'
                    iraf.imshift(input = filenames[fno]
                            , output = 'shift_' + filenames[fno], xshift = fxshift
                            , yshift = fyshift, shifts_file = '', interp_type = 'linear'
                            , boundary_type = 'nearest', constant = 0.0)
                nfilenames.append('shift_' + filenames[fno])
                fno += 1
            for i2 in xrange(len(nfilenames)):
                iraf.display(image = nfilenames[i2], frame = i2 + 1)
            iraf.imexamine()
            return cos_clear(nfilenames)
    return cos_clear(filenames)
Ejemplo n.º 15
0
    def _profiler(self,coordfile,coord):
        # deploy task to pyraf
        results = iraf.imexamine(self.filename,image=self.filename,use_display='no',logfile='',defkey='r',imagecur=coordfile,frame=1,mode='h',StdoutG=self.tempradfile.name,Stdout=1)
        try:
            results = results[0].split()
            # prad frad flux bgd mpeak ellip pa mbeta 2dfwhm mfwhm fwhm
        except IndexError:
            # some error
            results = [np.nan]*len(self.R_COLMAP)

        # first, process stdout
        for idx,r in enumerate(results):
            try:
                results[idx] = np.float(r)
            except ValueError:
                results[idx] = np.nan
            
        results = OrderedDict(zip(self.R_COLMAP,results))
        tbl = Table([results])
        tbl = tbl[self.R_COLMAP]
        tbl['flux'].unit = u.ct
        tbl['bgd'].unit = u.ct
        tbl['mpeak'].unit = u.ct
        tbl['pa'].unit = u.deg
        #tbl['2dfwhm'].unit = u.pix
        tbl['mfwhm'].unit = u.pix
        tbl['fwhm'].unit = u.pix

        # add xi,yi
        xi,yi = (np.float(i) for i in coord)
        tbl.add_column(Column([xi],name='xi',format='%.2f'),0)
        tbl.add_column(Column([yi],name='yi',format='%.2f'),1)

        #remove 2dfwhm cuz wut?
        tbl.remove_column('2dfwhm')

        #add arcsec columns
        for fwhmcol in tbl.colnames[-2:]:
            try:
                val = tbl[fwhmcol]*self.pxscale
            except TypeError:
                val = [np.nan]
            tbl.add_column(Column(val,name='%s_s'%fwhmcol,unit=u.arcsec,format='%.3f'),tbl.index_column(fwhmcol)+1)

        # process profile graphics
        gki = iraf.gkidecode(self.tempradfile.name,Stdout=1,verbose=True)
        gki = '\n'.join(gki)
        xr,yr,xf,yf = self.extract_gkidata(gki)

        vals = [tbl[x][0] for x in tbl.colnames] + [xr,yr,xf,yf,tbl]
        p = Profile(*vals)

        return p
Ejemplo n.º 16
0
def label_objects(images, xfield, yfield):
    '''Given a list of images, allow the user to pick an object in the
   display and have the x and y coordinates saved as header keywords
   xfield and yfield.'''
    files = get_files(images)
    print "Please use the 'a' key to select objects"
    for file in files:
        iraf.display(file, 1)
        res = iraf.imexamine(file, Stdout=1)
        #res = iraf.rimcursor(file, Stdout=1)
        x, y = map(float, (string.split(res[2])[0:2]))

        iraf.hedit(images=file, fields=xfield, value=x, add=1, verify=0)
        iraf.hedit(images=file, fields=yfield, value=y, add=1, verify=0)
Ejemplo n.º 17
0
def check_flat():
	print 'check flat...'
	print '***please remove the bad flat from the list***'
	name = os.popen('ls *flat.lst').readlines()
	name1 = [i.split('\n')[0] for i in name if '_no_flat' not in i]
	name2 = [i.split('\n')[0] for i in name if '_no_flat' in i]
	for i in name1:
		os.popen("gedit " + i + " &")
		iraf.imexamine(input = '@' + i + '//[1]', frame = 1)
	for i in name2:
		if i.replace('_no','') not in name1:
			label = raw_input(i + " has no flat fits, do you want use older flat?")
			if label == 'y' or label == 'Y' or label == 'yes' or label == 'Yes':
				path = raw_input('Please input the path of the lstfile:')
				print 'coping older lstflat ' + path + ' as new name ' + i.replace('_no','') + '...'
				shutil.copy(path, './' + i.replace('_no',''))
				path = path[0:path.rfind('/')]
				file1 = open(i.replace('_no',''))
				file1_ctent = file1.readlines()
				file1.close()
				file1_ctent = [j.split('\n')[0] for j in file1_ctent]
				for j in file1_ctent:
					print 'coping ' + j + '...'
					shutil.copy(path + '/' + j, './')
Ejemplo n.º 18
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
Ejemplo n.º 19
0
if not os.path.isdir('flat_files'):
    os.mkdir('flat_files')

allfiles = flatlist
for file in allfiles:
    shutil.copy(file, 'flat_files/')

# combine flat images
print 'Combining flat images ...'
iraf.ccdred.flatcombine.ccdtype = ''
iraf.ccdred.flatcombine.process = 'no'
iraf.ccdred.flatcombine.reject = 'ccdclip'
iraf.ccdred.flatcombine.rdnoise = 'rdnoise'
iraf.ccdred.flatcombine.gain = 'gain'
iraf.ccdred.flatcombine.output = 'Flat'
iraf.ccdred.flatcombine(input=flatin)

for file in flatlist:
    os.remove(file)

print 'openning a ds9 window if not already openned...'
ds9.ds9()

# check output flat image
print 'Check output file:'
iraf.imstatistics('Flat')
print ' Running "imexamine" task..'
iraf.imexamine('Flat', 1)

print '--- DONE ---'
Ejemplo n.º 20
0
def main():
    print '=' * 20 + ' check wcal2d ' + '=' * 20
    iraf.imexamine('wftbo//@cor_halogen.lst', frame=1)
Ejemplo n.º 21
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
Ejemplo n.º 22
0
                        _xpos, _ypos = pix1[0][0], pix1[0][1]
                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)
Ejemplo n.º 23
0
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)
    xycoo = iraf.fields('tmp.coo', '1,2,13', Stdout=1)
    print '>> Identify reference stars'
    idcat = []
    for i in range(len(xycoo)):
        idcat.append(int(raw_input('Star ' + str(i + 1) + '= ? ')))
Ejemplo n.º 24
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'
Ejemplo n.º 25
0
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
Ejemplo n.º 26
0
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
Ejemplo n.º 27
0
                        _mag0 = raw_input(
                            'which mag do you want to subtract  ' + str(_mag) +
                            ' ? ')
                        if _mag0:
                            _mag = float(_mag0)
                print 'magnitude to be subtracted:', _mag

                #######################  Chose Ra   and    Dec  ##############
                if chosepos:
                    print 'choose xpos, ypos interactively'
                    lsc.util.delete('tmp.log')
                    zz1, zz2, goon = lsc.util.display_image(
                        img, 1, '', '', True)
                    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]
                elif not _ra or not _dec:
                    print 'use ra and dec from input database !!! '
                    _ra, _dec, _SN0, _type = lsc.util.checksndb(
                        img0, 'targets')

                if _ra and _dec:
                    print 'convert RA, dec to xpos, ypos using header'
                    hdr0 = lsc.util.readhdr(img0)
                    wcs = WCS(hdr0)
                    pix1 = wcs.wcs_world2pix([(_ra, _dec)], 1)
Ejemplo n.º 28
0
        op1 = cordatals[i].split('_')[3]
        op2 = cordatals[i + 1].split('_')[3]
        print "\tnormal step:"
    print '  subtracting', rname + '_' + op1 + '_cor.fit' + '-' + rname + '_' + op2 + '_cor.fit', 'to create:', rname + '_' + op1 + '-' + op2 + '_df.fit'
    iraf.imarith(operand1=rname + '_' + op1 + '_cor.fit',
                 op="-",
                 operand2=rname + '_' + op2 + '_cor.fit',
                 result=rname + '_' + op1 + '-' + op2 + '_df.fit')
    imimlst.write(rname + '_' + op1 + '-' + op2 + '_df.fit' + '\n')
imimlst.close()

# setting display parameters and imexamine (<<< select star to align)
print "> displaying images to select the star used for alignment"
iraf.set(stdimage="imt1024")
iraf.imexamine("@imexamine_image.irafl",
               frame=1,
               logfile="imexamine.irafl",
               keeplog="yes")

# preparation and manipulation of lists and align/shift processes
shimlst1 = open('images_to_shift.irafl', 'w')
shimlst22 = open('shifted_images.irafl', 'w')
imlog = open("imexamine.irafl", "r")  # selecting the x,y values only
lines = imlog.readlines()
imlog.close()

x = []
y = []
for lin in lines:
    lin.split(' ')
    if lin.split()[0] != "#":
        print lin.split()[0], lin.split()[1]
Ejemplo n.º 29
0
def Main(obj, obstime_kw=None, iraf_display_mode='display'):
    """
    Given a list of images in a specified folder, will display
    them using iraf.display (if iraf_display_mode=='display') or iraf.imexamine
    (if iraf_display_mode=='imexamine') in blocks of 10. For first pass inspection,
    the point is to see whether there are any significant pointing
    drifts between frames that will cause the source tracking
    algorithm to fail. For second pass inspection, the point is
    to make a quick comparison between the absolute photometry
    output from the pipeline and manual imexam photometry values.
    """
    images = np.loadtxt(obj.image_list, dtype='str')
    if obstime_kw!=None:
        obstimes = np.zeros(len(images))
        for i in range(len(obstimes)):
            h = pyfits.getheader(images[i])
            obstimes[i] = h[obstime_kw]
        ixs = np.argsort(obstimes)
        images = images[ixs]
    blockids = np.zeros(len(images))
    nperblock = 10
    nimages = len(images)
    nblocks = int(np.ceil(float(nimages)/nperblock))
    record_outcome = np.ones(nblocks)
    block_counter = 0
    for i in range(nblocks):
        n = min([nperblock, nimages-i*nperblock])
        print '\nBlock %i of %i' % (i+1,nblocks)
        for j in range(n):
            ix = i*nperblock+j
            blockids[ix] = i
            try:
                print 'Loading %s...' % images[ix]
                if iraf_display_mode=='display':
                    iraf.display(images[ix],j+1)
                elif iraf_display_mode=='imexamine':
                    iraf.imexamine(images[ix],j+1)
                else:
                    pdb.set_trace()
            except:
                pass
        print '\nEnter 1 for OK, 0 if not:\n'
        outcome = ''
        while outcome=='':
            outcome = raw_input('')
        record_outcome[i] = outcome
    ixs = np.arange(nblocks)[record_outcome==0]
    ncloser = len(ixs)
    print '\nYou identified %i blocks to look at again closely.' % ncloser
    print 'Enter y to go through them again now, or n to exit:'
    outcome = ''
    while outcome=='':
        outcome = raw_input('')
    if outcome=='y':
        for i in range(ncloser):
            closer_images = images[blockids==ixs[i]]
            print '\n Block %i:' % (ixs[i]+1)
            for j in range(len(closer_images)):
                print closer_images[j]
                iraf.display(closer_images[j],j+1)
            print '   (enter c to continue)'
            outcome = ''
            while outcome=='':
                outcome = raw_input('')
    else:
        print '\nFor future reference, the identified blocks were:'
        for i in range(ncloser):
            print '\n  Block %i, containing:' % ixs[i]
            closer_images = images[blockids==ixs[i]]
            for j in range(len(closer_images)):
                print '   - %s' % closer_images[j]
    return None
Ejemplo n.º 30
0
print '\ncreating a zero_files/ dir to store original data'
if not os.path.isdir('zero_files'):
    os.mkdir('zero_files')

allfiles = zerolist
for file in allfiles:
    shutil.copy(file, 'zero_files/')

# combine bias images
print 'Combining zero level images...'
iraf.ccdred.zerocombine.ccdtype = ''
iraf.ccdred.zerocombine.reject = 'ccdclip'
iraf.ccdred.zerocombine.rdnoise = 'rdnoise'
iraf.ccdred.zerocombine.gain = 'gain'
iraf.ccdred.zerocombine(input=zeroin)

for zero in zerolist:
    os.remove(zero)

print 'openning a ds9 window if not already openned...'
ds9.ds9()

# check output image
print 'Check output file:'
iraf.imstatistics('Zero')

print ' Running "imexamine" task..'
iraf.imexamine('Zero', 1)

print '--- DONE ---'
Ejemplo n.º 31
0
def radprof_iraf(image,
                 coords,
                 radius,
                 step=0.1,
                 output='STDOUT',
                 plotfile=None,
                 verbose=False,
                 test=False,
                 pxscale=None):
    iraf.apphot.centerpars.setParam('maxshift', radius)  # search radius
    if test:
        results = iraf.imexamine(image,
                                 image=image,
                                 use_display='no',
                                 logfile='',
                                 defkey='r',
                                 imagecur=coords,
                                 frame=1,
                                 mode='h',
                                 StdoutG=plotfile,
                                 Stdout=1)
        results = [np.float(x) for x in results[0].split()]
        # prad frad flux bgd mpeak ellip pa mbeta 2dfwhm mfwhm fwhm
        results = OrderedDict(zip(R_COLMAP, results))
        tbl = Table([results])
        tbl = tbl[R_COLMAP]
        tbl['flux'].unit = u.ct
        tbl['bgd'].unit = u.ct
        tbl['mpeak'].unit = u.ct
        tbl['pa'].unit = u.deg
        #tbl['2dfwhm'].unit = u.pix
        tbl['mfwhm'].unit = u.pix
        tbl['fwhm'].unit = u.pix

        #remove 2dfwhm cuz wut?
        tbl.remove_column('2dfwhm')

        if pxscale:
            #add arcsec columns
            for fwhmcol in tbl.colnames[-2:]:
                tbl.add_column(
                    Column(tbl[fwhmcol] * pxscale,
                           name='%s_s' % fwhmcol,
                           unit=u.arcsec,
                           format='%.3f'),
                    tbl.index_column(fwhmcol) + 1)

        gki = iraf.gkidecode(plotfile, Stdout=1, verbose=True)
        gki = '\n'.join(gki)
        xr, yr, xf, yf = extract_gkidata(gki)
        #plt.scatter(xr,yr)
        #plt.plot(xf,yf)
        #plt.show()

        return tbl, xr, yr, xf, yf

    results = iraf.apphot.radprof(image,
                                  radius=radius,
                                  step=step,
                                  coords=coords,
                                  output=output,
                                  verbose=verbose,
                                  verify=False,
                                  interactive=False,
                                  Stdout=1)

    #remove datalines
    data = []
    pradline = None
    for idx, line in enumerate(results):
        if '*\\' in line:
            line = line.split()[0:3]
            line = [np.float(x) for x in line]
            data.append((idx, line))
        #remove pradius line descriptors
        elif 'PRADIUS' in line:
            pradline = idx
    idx, data = zip(*data)
    #print data
    #remove from min idx onward
    ridx = np.min(idx)
    del results[ridx:]
    del results[pradline:pradline + 4]
    # remove '\' from last line
    results[-1] = results[-1][0:-1]
    results = '\n'.join(results[1:])

    rtbl = Table.read(results, format='ascii.daophot')
    #print rtbl['PFWHM']/2.0
    ptbl = Table(rows=data, names=('radius', 'intensity', 'tintensity'))
    ptbl['intensity'] *= rtbl['INORM']
    #tbl.pprint()
    #plt.plot(tbl['radius'],tbl['intensity']*ptbl['INORM'])
    return ptbl
Ejemplo n.º 32
0
                                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.imexamine(img, 1, logfile='tmp.coo', keeplog='yes')
                iraf.tvmark(1,
                            'tmp.coo',
                            mark="circle",
                            number='yes',
                            label='no',
                            radii=5,
                            nxoffse=5,
                            nyoffse=5,
                            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) + '= ? '))
Ejemplo n.º 33
0
@author: jlee
"""

import numpy as np
import os
from time import sleep

from pyraf import iraf
iraf.images()
iraf.tv()

import init_cfg as ic

com_ds9 = 'ds9 -scalemode zscale -scale lock yes -frame lock image '

# ----- Enter an image list (manually!) ----- #
# imglist = ' '
# for i in np.arange(len(ic.nfits)):
#     imglist += ic.nfits[i]+' '

imgs = ['B.fits', 'mB.fits', 'V.fits']
imglist = ' '
for i in np.arange(len(imgs)):
    imglist += imgs[i] + ' '

# ------------------------------------------- #

os.system(com_ds9 + imglist + '&')
sleep(float(len(ic.nfits)))
iraf.imexamine()
Ejemplo n.º 34
0
    fin = open('alginput.list', 'w+')
    fout = open('algoutput.list', 'w+')
    for afile in files:
        print >> fin, afile
        print >> fout, 'alg' + afile
    fin.close()
    fout.close()

    print green("\nUse imexam to mark stars in your reference image.")
    print green(
        "Use keystroke 'a' to measure a point source, and keystroke 'q' to quit."
    )
    print green("The reference image is: %s\n" % reference)

    #Imexam
    output = iraf.imexamine(Stdout=1)

    #make coordinate file
    f = open('images.coord', 'w+')
    for i in range(1, len(output)):
        splt = output[i].split()
        if len(splt) == 4:
            print >> f, splt[0] + '   ' + splt[1]
    f.close()

    print green(
        "\nUse imexam to mark a star in all images that are to be aligned, starting with your"
    )
    print green("reference image. Mark the same star in all images.")
    print green(
        "Use keystroke 'a' to measure a point source, and keystroke 'q' to quit."
Ejemplo n.º 35
0
def ntrim_flat(filename):
    flatname = get_flatlst_name(filename)
    f = open(filename)
    l = f.readlines()
    f.close()
    l = [i.split()[0] for i in l]
    objfitsnames = []
    for i in l:
        if '.fits' in i:
            objfitsnames.append(i)
    f = open(flatname)
    l = f.readlines()
    f.close()
    l = [i.split()[0] for i in l]
    flatfitsnames = []
    for i in l:
        if '.fits' in i:
            flatfitsnames.append(i)
    fitsnames = objfitsnames + flatfitsnames
    tempfile = 'temp.lst'
    f = open(tempfile,'w')
    for i in fitsnames:
        f.write(i + '\n')
    f.close()
    temppath = sys.argv[0]
    tempindex = temppath.rfind(os.sep)
    temppath = temppath[:tempindex]
    trimfile = temppath + os.sep + 'trim.lst'
    print 'get trimlst'
    f = open(trimfile)
    l = f.readlines()
    f.close()
    trimseclist = []
    for i in l:
        trimseclist.append(i.split())
    trimsec = ''
    for i in trimseclist:
        if i[0] == filename:
            trimsec = i[1]
            break
    if trimsec == '':
        print 'trim.lst not have the object'
        print 'Please check the fits image and determine the size to trim...'
        os.popen('gedit ' + tempfile +' &')
        iraf.imexamine(input = 'bo//@' + tempfile, frame = 1)
        xy = raw_input("Please input x1, x2, y1, y2 to trim: ")
        xy = xy.split()
        trimsec = '[' + xy[0] + ':' + xy[1] + ',' + xy[2] + ':' + xy[3] +']'
        f = open(trimfile,'a')
        f.write(filename + ' ' + trimsec + '\n')
        f.close()
    print '=' * 20, 'correct trim', '=' * 20
    correct_trim(tempfile, trimsec)
    print '=' * 20, 'cimbine flat', '=' * 20
    dtempname = combine_flat(flatname)
    f = open(tempfile, 'w')
    for i in objfitsnames:
        f.write(i + '\n')
    f.close()
    print '=' * 20, 'correct flat', '=' * 20
    correct_flat(tempfile, dtempname[-1])
    print 'delete useless file...'
    print 'delete ' + tempfile
    os.remove(tempfile)
    for i in dtempname:
        print 'delete ' + i
        os.remove(i)
    for i in flatfitsnames:
        print 'delete ' + 'tbo' + i
        os.remove('tbo' + i)
    print 'correct standard file name...'
    objname = filename.split('_')[1]
    f = open(filename)
    l = f.readlines()
    f.close()
    l = [i.split()[0] for i in l]
    sindex = l.index('standard') + 1
    while sindex < len(l):
        if '.fits' in l[sindex]:
            nname = l[sindex].replace('.fits', objname + '.fits')
            print 'ftbo' + l[sindex], 'rename', 'ftbo' + nname
            os.rename('ftbo' + l[sindex], 'ftbo' + nname)
            print 'delete tbo' + l[sindex]
            os.remove('tbo' + l[sindex])
            l[sindex] = nname
            sindex += 1
        else:
            break
    f = open(filename, 'w')
    for i in l:
        f.write(i + '\n')
    f.close()
Ejemplo n.º 36
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
Ejemplo n.º 37
0
def continuum_imexamine(setup, frame, sample_ext, cursor_file):
	iraf.imexamine(input='%s[%d]' % (frame,sample_ext), logfile='%s_ext%s_continuum_fit' % (setup, sample_ext), keeplog='yes', imagecur='%s_%s_cursor_file.dat' % (setup, frame))
Ejemplo n.º 38
0
print '\ncreating a zero_files/ dir to store original data'
if not os.path.isdir('zero_files'):
    os.mkdir('zero_files')

allfiles = zerolist
for file in allfiles:
    shutil.copy(file, 'zero_files/')

# combine bias images
print 'Combining zero level images...'
iraf.ccdred.zerocombine.ccdtype = ''
iraf.ccdred.zerocombine.reject = 'ccdclip'
iraf.ccdred.zerocombine.rdnoise = 'rdnoise'
iraf.ccdred.zerocombine.gain = 'gain'
iraf.ccdred.zerocombine(input=zeroin)

for zero in zerolist:
    os.remove(zero)

print 'openning a ds9 window if not already openned...'
ds9.ds9()

# check output image
print 'Check output file:'
iraf.imstatistics('Zero')

print ' Running "imexamine" task..'
iraf.imexamine('Zero', 1)

print '--- DONE ---'
Ejemplo n.º 39
0
iraf.ccdred.combine.unlearn()
iraf.ccdred.zerocombine.unlearn()
iraf.ccdred.flatcombine.unlearn()
iraf.specred.response.unlearn()

# regular expression of files (e.g bias_00*.fits, flat-2000jan01_?.*)
theflat = str(raw_input('Enter flat image: '))

iraf.specred.extinction = ''
iraf.specred.caldir = ''
iraf.specred.observatory = 'lna'

print 'Create a response for flat...'
iraf.specred.response.interactive = True
iraf.specred.response.high_reject = 3.0
iraf.specred.response.low_reject = 3.0
iraf.specred.response(calibration=theflat,
                      normalization=theflat,
                      response='nFlat')

# check output flat image
print 'openning a ds9 window if not already openned...'
ds9.ds9()

print 'Check output file:'
iraf.imstatistics('nFlat')
print ' Running "imexamine" task..'
iraf.imexamine('nFlat', 1)

print '--- DONE ---'
Ejemplo n.º 40
0
def skynoise(image,path=None):
    '''
     Calcula el ruido del cielo de una imagen. 
     Toma una moda de la imagen total con \verb|imstat|. Luego genera una lista
     de n puntos aleatorios entre los límites de la imagen, con
     $n=\frac{anchoCCD^2}{10}$, y corre \verb|imexa| sobre cada punto, sacando
     la estadística. Descarta los puntos que superen en cuentas 3 veces la moda
     y toma la media de la desviación estandar del cielo de los puntos
     restantes. Este valor es el que devuelve como aproximación del skynoise.
    INPUT
    image : una imagen
    (path): camino a imagen
     '''
    
    if path is not None:
        originalpath=aux.chdir(path,save=True)
        
    stat= iraf.imstat(image,fields='mode',Stdout=1) #get the mode of the image
    moda=float(stat[1]) # reads the mode as a float variable

    binn=aux.hselect(image,'CCDSUM') # gets binning of the image
    binn=binn[0]  # access element 0 of the array
    binn=binn[1]  # access first character
    binn=int(binn)  # converts string to integer

    #------------------------------------------------------------------
    ccdsec=aux.hselect(image,'CCDSEC') # para agarrar imagenes con trim
    if ccdsec[0]=='':
        limits=aux.hselect(image,'CCDSIZE') # gets ccd pixel size
    else:
        limits=aux.hselect(image,'BIASSEC')
    limit=limits[0]  # gets element 0 of the array
    limit=limit.strip() # removes white space
    dd=[]  # stores position of double dot
    c=[]   # stores position of comma
    i=0 
    for x in limit:  # for every character
        if x==':': # if character is :
            dd.append(i) #stores index
        elif x==',': # if character is ,
            c.append(i) #stores index
        i=i+1
    #-----------------------------------------------------------------
#   
#    x1=int(limit[1:dd[0]])  # saves first limit
#    y1=int(limit[c[0]+1:dd[1]]) #saves las limit

    x2=int(limit[dd[0]+1:c[0]]) 
    y2=int(limit[dd[1]+1:-1])  
    
    l1=x2/binn # limit one 

    l2=y2/binn # limit two  
    # set random numbers aux file   
    aux.rm('ruidoceleste.coo') #delete if already exists
    output='ruidoceleste.coo'
  
    
    coords=[]
    nrandom=int((l1**2)/100.) #quadratic growth
    
    f=open(output,'a+') # creates outfile
    for i in range(nrandom): # creates l1/10 random coordinates
        x=random.randint(1,l1) # random x coord, from x1 to l1
        y=random.randint(1,l2) # random y coord, from y1 to l2
        coords.append([x,y])
        print >> f,x,y  # writes coords in file 
    f.close()

    iraf.unlearn(iraf.imexamine) #unlearns imexamine first
# tuve que mandar estos comandos para que no me cambie el z1yz2 cada vez
# que calculaba todo. Cosa de como tenia mi seteado mi iraf ( o no?)            
    iraf.imexamine.autoredraw='no' #noredraw of the image 
#    iraf.display.zscale='no'
    iraf.imexamine.allframes='no'
    iraf.imexamine.use_display='no'  
    iraf.imexamine.imagecur=output # sets imexa infile
    iraf.imexamine.defkey='m'  # sets key to use in imexa
    imst=iraf.imexamine(image,frame=1,Stdout=1)  # calls imexa
    

    stdev=[]
    maxi=[]

    for lin in imst[1:]:
        stdev.append(float(lin.split()[4]))
        maxi.append(float(lin.split()[6]))

    # criterio de seleccion <3*moda no es estrella
    validos=[]
    for j in range(nrandom):
            if maxi[j] < 3*moda:
                validos.append(stdev[j])

                
    sigmasky=mode(validos) # toma la moda
    sigmasky=sigmasky[0][0]
    
#     tomo la media de la disperción
#    sigmasky=np.mean(validos)
#    print validos             
    aux.rm(output) # mata el archivo auxiliar    
    
    if path is not None:
        aux.chdir(originalpath)
    return(sigmasky) 
Ejemplo n.º 41
0
def getfwhm(images='@imh.lis',
            coordlist='ref_stars',
            outfile='getfwhm.log',
            radius=4.0,
            buffer=7.0,
            width=5.0,
            rplot=15.0,
            center='no',
            verbose='no',
            imagelist=None,
            mode='al',
            DOLLARnargs=0,
            taskObj=None):
    Vars = IrafParList('getfwhm')
    Vars.addParam(
        makeIrafPar(images,
                    datatype='string',
                    name='images',
                    mode='a',
                    prompt='Input image(s)'))
    Vars.addParam(
        makeIrafPar(coordlist,
                    datatype='string',
                    name='coordlist',
                    mode='a',
                    prompt='List of object positions'))
    Vars.addParam(
        makeIrafPar(outfile,
                    datatype='string',
                    name='outfile',
                    mode='a',
                    prompt='Output file'))
    Vars.addParam(
        makeIrafPar(radius,
                    datatype='real',
                    name='radius',
                    mode='h',
                    prompt='Object radius'))
    Vars.addParam(
        makeIrafPar(buffer,
                    datatype='real',
                    name='buffer',
                    mode='h',
                    prompt='Background buffer width'))
    Vars.addParam(
        makeIrafPar(width,
                    datatype='real',
                    name='width',
                    mode='h',
                    prompt='Background width'))
    Vars.addParam(
        makeIrafPar(rplot,
                    datatype='real',
                    name='rplot',
                    mode='h',
                    prompt='Plotting radius'))
    Vars.addParam(
        makeIrafPar(center,
                    datatype='bool',
                    name='center',
                    mode='h',
                    prompt='Center object in aperture?'))
    Vars.addParam(
        makeIrafPar(verbose,
                    datatype='bool',
                    name='verbose',
                    mode='h',
                    prompt='Verbose output?'))
    Vars.addParam(
        makeIrafPar(imagelist,
                    datatype='struct',
                    name='imagelist',
                    list_flag=1,
                    mode='h'))
    Vars.addParam(makeIrafPar(mode, datatype='string', name='mode', mode='h'))
    Vars.addParam(
        makeIrafPar(DOLLARnargs, datatype='int', name='$nargs', mode='h'))
    Vars.addParam(makeIrafPar(None, datatype='int', name='len', mode='u'))
    Vars.addParam(makeIrafPar(None, datatype='string', name='image', mode='u'))
    Vars.addParam(
        makeIrafPar(None, datatype='string', name='imagefile', mode='u'))
    Vars.addParam(makeIrafPar(None, datatype='string', name='imlist',
                              mode='u'))
    Vars.addParam(makeIrafPar(None, datatype='string', name='coords',
                              mode='u'))
    Vars.addParam(
        makeIrafPar(None, datatype='string', name='outputfile', mode='u'))
    Vars.addParam(makeIrafPar(None, datatype='real', name='rad', mode='u'))
    Vars.addParam(makeIrafPar(None, datatype='real', name='buff', mode='u'))
    Vars.addParam(makeIrafPar(None, datatype='real', name='wid', mode='u'))
    Vars.addParam(makeIrafPar(None, datatype='real', name='rpl', mode='u'))

    Vars.imlist = Vars.images
    Vars.imagefile = iraf.mktemp('tmp$getfwhm')
    iraf.sections(Vars.imlist, option='fullname', Stdout=Vars.imagefile)
    Vars.imagelist = Vars.imagefile
    Vars.coords = Vars.coordlist
    Vars.outputfile = Vars.outfile
    Vars.rad = Vars.radius
    Vars.buff = Vars.buffer
    Vars.wid = Vars.width
    Vars.rpl = Vars.rplot
    iraf.rimexam.radius = Vars.rad
    iraf.rimexam.buffer = Vars.buff
    iraf.rimexam.width = Vars.wid
    iraf.rimexam.rplot = Vars.rpl
    if (Vars.center == yes):
        iraf.rimexam.center = yes
    else:
        iraf.rimexam.center = no
    iraf.rimexam.fittype = 'gaussian'
    iraf.rimexam.iterati = 1
    iraf.clPrint('# RIMEXAM Parameter Settings:  Radius=',
                 Vars.rad,
                 ', Buffer=',
                 Vars.buff,
                 ', Width=',
                 Vars.wid,
                 StdoutAppend=Vars.outputfile)
    while (iraf.fscan(locals(), 'Vars.imagelist', 'Vars.image') != EOF):
        Vars.len = iraf.strlen(Vars.image)
        if (iraf.substr(Vars.image, Vars.len - 3, Vars.len) == '.imh'):
            Vars.image = iraf.substr(Vars.image, 1, Vars.len - 4)
        if (Vars.verbose):
            iraf.clPrint('...processing ', Vars.image)
        iraf.clPrint(Vars.image)
        iraf.imexamine(Vars.image,
                       logfile=Vars.outputfile,
                       keeplog=yes,
                       defkey='a',
                       imagecur=Vars.coords,
                       wcs='world',
                       use_display=no)
Ejemplo n.º 42
0
	def calc_upperlimit( self, skysigfits ):
		skysigpath	= os.path.join(self.dir,skysigfits)
		hd		= pyfits.open(skysigpath)[0].header

		#set region range
		one_side 		= round(0.5*self.aperture*np.sqrt(np.pi),0)
		iraf.imexam.ncstat 	= one_side
		iraf.imexam.nlstat 	= one_side
		area_unit          	= one_side*one_side

		#logical coord range
		log_xmin	= 1
		log_xmax	= float(hd["NAXIS1"])
		log_ymin	= 1
		log_ymax 	= float(hd["NAXIS2"])
		
		bias	= 65 #np.sqrt((maxfwhm=20*1.75)**2*np.pi)
		
		xmin	= log_xmin + bias
		xmax 	= log_xmax - bias
		ymin	= log_ymin + bias
		ymax	= log_ymax - bias
	
		length_x	= xmax - xmin
		length_y	= ymax - ymin
		print length_x,length_y
		
		sample_num = 1000 
		x = np.random.rand(sample_num)*length_x + bias
		y = np.random.rand(sample_num)*length_y + bias
		print len(x),len(y)
		
		coords = SkyCoord(x,y,0,representation="cartesian")
		print coords

		idx,d2d,d3d 	= coords.match_to_catalog_3d(coords,nthneighbor=2)
		required_d	= one_side*np.sqrt(2)
		print required_d
		select		= np.where(required_d < d3d)
		print d3d
		print select
		survived        = coords[select]
		points  	= np.c_[x,y][select][:len(survived)]
		
		ap_reg	= os.path.join(self.dir,"aperture.reg") #random apertures
		ap_tmp	= os.path.join(self.dir,"aperture.tmp") #imexam m  aperture template
		with open(ap_reg,"w") as f, open(ap_tmp,"w") as g:
			frame   = 1
			command = "m"
			for i,xy in enumerate(points):
				if i ==0:
					f.write("global color=green dashlist=8 3 width=1 font=\"helvetica 10 normal roman\" select=1 highlite=1 dash=0 fixed=0 edit=1 move=1 delete=1 include=1 source=1\nimage\n")
				x = round(xy[0],3)
				y = round(xy[1],3)
				tmp = "%s %s %s %s\n" % (x,y,frame,command)
				g.write(tmp)
				reg   = "circle(%s,%s,10)\n" % (x,y)
				f.write(reg)
	
		output		= os.path.join(self.dir,"aperture0.log")
		iraf.imexamine(input=skysigpath,imagecur=ap_tmp,use_display="no",keeplog="yes",logfile=output,Stdout=True,frame=1)
		log		= os.path.join(self.dir,"aperture.log")
		if os.path.exists(log):os.remove(log)
		else:pass

		os.system("sed -e \"1d\" %s > %s" % (output,log))
		os.remove(output)
		
		data	= ascii.read(log)
		print data.keys()
		select	= np.where(-200000. < data["MIN"])
		print select
		S	= (0.5*self.aperture)**2*np.pi

		mean_ls			= np.array(data["MEAN"][select]*S)

		clipper3	= ~sigma_clip(mean_ls,sigma=3).mask
		mean_clip	= mean_ls[clipper3]

		self.random_ap_num	= len(mean_clip)
		print mean_clip
		self.sigma	= np.std(mean_clip)
		print self.sigma
		self.upperlimit	= -2.5*np.log10(5*self.sigma) + self.Zmag
Ejemplo n.º 43
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
Ejemplo n.º 44
0
                    xx0, yy0 = string.split(iraf.fields('tmp.pix', '1,2', Stdout=1)[2])
                    print 'box coordinate ',xx0, yy0
                    os.system('rm -rf tmp.*')
                else:
                    xx0, yy0 = '', ''

                if xx0 == '' and not _interactive:
                    sys.exit('coordinate of the object not found, reduction not possible')

                if _interactive:
                    repeat = 'y'
                    while repeat == 'y':
                        print "_____________________________________________"
                        print "  MARK SN REGION WITH - x -, EXIT  - q -"
                        try:
                            iraf.imexamine(img + '.fits', 1, wcs='logical', logfile='tmp.log', keeplog=True)
                            xytargets = iraf.fields('tmp.log', '1,2', Stdout=1)
                            xx0 = xytargets[0].split()[0]
                            yy0 = xytargets[0].split()[1]
                            lsc.util.delete("tmplabel")
                            ff = open('tmplabel', 'w')
                            ff.write(str(xx0) + ' ' + str(yy0) + ' -1' + ' \n')
                            ff.close()
                            iraf.tvmark(1, 'tmplabel', autol='no', mark="cross", inter='no', label='no', txsize=4)
                            repeat = raw_input('### repeat selection ? [y/n] ? [n] ')
                            if not repeat:
                                repeat = 'n'
                            elif repeat == 'yes':
                                repeat = 'y'
                            elif repeat == 'YES':
                                repeat = 'y'
Ejemplo n.º 45
0
 if _interactive: xx0 = ''
 _z1, _z2 = '', ''
 z11, z22 = 0, 0
 if xx0 == '':
     #print '\n###  coordinate not found, reduction should be interactive'
     _interactive = True
     _show = True
     ######################    POINT TO SN #######################################
     repeat = 'y'
     while repeat == 'y':
         print "_____________________________________________"
         print "  MARK SN REGION WITH - x -, EXIT  - q -"
         try:
             iraf.imexamine(img + '.fits',
                            1,
                            wcs='logical',
                            logfile='tmp.log',
                            keeplog=True)
             xytargets = iraf.fields('tmp.log', '1,2', Stdout=1)
             x = xytargets[0].split()[0]
             y = xytargets[0].split()[1]
             agnkey.util.delete("tmplabel")
             ff = open('tmplabel', 'w')
             ff.write(str(x) + ' ' + str(y) + ' -1' + ' \n')
             ff.close()
             iraf.tvmark(1,
                         'tmplabel',
                         autol='no',
                         mark="cross",
                         inter='no',
                         label='no',
Ejemplo n.º 46
0
iraf.imred()
iraf.ccdred()
iraf.specred()
ds9()

iraf.zerocombine.unlearn()
iraf.zerocombine(input=bias,
                 reject='avsigclip',
                 ccdtype='',
                 rdnoise='rdnoise',
                 gain='gain')

iraf.imstat('bias*')
iraf.imstat('Zero')

iraf.imexamine('Zero')

iraf.flatcombine.unlearn()
iraf.flatcombine(input=flatcup,
                 output='Flat',
                 ccdtype='',
                 process=False,
                 subsets=False,
                 rdnoise='rdnoise',
                 gain='gain')

iraf.flatcombine(input=flati,
                 output='iFlat',
                 ccdtype='',
                 process=False,
                 subsets=False,