def run_ell(file_in, file_tab, file_dat, mag, **ellipse_par): # prochaine etape : mettre en argument sous une certaine forme les parametres associes epar des taches 1) strict minimum sous forme de dico fixe 2) tout pouvoir changer sous forme de dictionnaire et tester les cles ... # import iraf packages iraf.stsdas() iraf.analysis() iraf.isophote() p = Popen("ds9", shell = True) time.sleep(5) iraf.display(file_in, 1) set_iraf_param(ellipse_par) # iraf.lpar(iraf.geompar) iraf.ellipse(file_in, file_tab, mag0 = str(mag), verbose = "no") # iraf.lpar(iraf.isoimap) iraf.isoimap(file_in, file_tab) iraf.tproject(file_tab, "temp.fits", "SMA,INTENS,INT_ERR,ELLIP,ELLIP_ERR, PA, PA_ERR, X0, Y0, TFLUX_C, TMAG_E,NPIX_E") iraf.tprint("temp.fits", pwidth = 200, Stdout = file_dat) iraf.imdel("temp.fits") p.kill()
def run_elli_full(cutimage, output, xcntr, ycntr, eg, pa, sma, sky): #,radd,background): """The function responsible for fit ellipse""" EllGal = c.outdir + 'GalEllFit.fits' fEl = pyfits.open(os.path.join(c.datadir, cutimage)) GaLaXy = fEl[0].data fEl.close() GaLaXy = GaLaXy - sky hdu = pyfits.PrimaryHDU(GaLaXy.astype(n.float32)) hdu.writeto(EllGal) try: iraf.stsdas(_doprint=0) iraf.tables(_doprint=0) iraf.stsdas.analysis(_doprint=0) iraf.stsdas.analysis.isophote(_doprint=0) except: iraf.stsdas() iraf.tables() iraf.stsdas.analysis() iraf.stsdas.analysis.isophote() image_exist = 1 iraf.unlearn('geompar') iraf.geompar.x0 = xcntr iraf.geompar.y0 = ycntr iraf.geompar.ellip0 = eg iraf.geompar.pa0 = pa iraf.geompar.sma0 = 6.0 iraf.geompar.minsma = 0.1 iraf.geompar.maxsma = sma * 5.0 iraf.geompar.step = 0.1 iraf.geompar.recente = "no" iraf.geompar.xylearn = "no" iraf.unlearn('controlpar') iraf.controlpar.conver = 0.05 iraf.controlpar.minit = 10 iraf.controlpar.maxit = 50 iraf.controlpar.hcenter = "no" iraf.controlpar.hellip = "no" iraf.controlpar.hpa = "no" iraf.controlpar.wander = "INDEF" iraf.controlpar.maxgerr = 0.5 iraf.controlpar.olthres = 1 iraf.controlpar.soft = "no" iraf.samplepar.integrm = "bi-linear" iraf.samplepar.usclip = 3 iraf.samplepar.lsclip = 3 iraf.samplepar.nclip = 0 iraf.samplepar.fflag = 0.5 iraf.unlearn('ellipse') iraf.ellipse("".join(EllGal), output="test", interac="no",Stdout="ellip", \ Stderr="err") iraf.tprint("test.tab", prparam="no", prdata="yes", pwidth=80, plength=0, \ showrow="no", orig_row="no", showhdr="no", showunits="no", \ columns="SMA, INTENS, INT_ERR, ELLIP, ELLIP_ERR, PA, PA_ERR, \ MAG, MAG_LERR, MAG_UERR, TMAG_E, TMAG_C, A3, \ A3_ERR, B3, B3_ERR, A4, A4_ERR, B4_ERR" , rows="-", \ option="plain", align="yes", sp_col="", lgroup=0, Stdout=output) for myfile in ['ellip', 'err', 'test.tab', EllGal]: if os.access(c.outdir + myfile, os.F_OK): os.remove(c.outdir + myfile)
def run_elli(input, xcntr, ycntr, eg, pa, sma):#,radd,background): iraf.stsdas(_doprint=0) iraf.tables(_doprint=0) iraf.stsdas.analysis(_doprint=0) iraf.stsdas.analysis.isophote(_doprint=0) image_exist = 1 if(str(input)[:3] == 'ima'): output = 'elli_' + input[6:-4] + 'txt' if(str(input)[:3] == 'out'): output = 'out_elli_' + str(input)[4:-7] + 'txt' #unlearn geompar controlpar samplepar magpar ellipse iraf.geompar(x0=xcntr, y0=ycntr, ellip0=eg, pa0=pa, sma0=10, minsma=0.1, \ maxsma=sma*5.0, step=0.1,recente="yes") iraf.controlpar(conver=0.05, minit=10, maxit=50, hcenter="no", hellip="no",\ hpa="no", wander="", maxgerr=0.5, olthres=1,soft="no") iraf.samplepar(integrm="bi-linear", usclip=3,lsclip=3, nclip=0, fflag=0.5) iraf.magpar(mag0=0, refer=1, zerolev=0) iraf.ellipse("".join(input), output="test", interac="no",Stdout="ellip", \ Stderr="err") iraf.tprint("test.tab", prparam="no", prdata="yes", pwidth=80, plength=0, \ showrow="no", orig_row="no", showhdr="no", showunits="no", \ columns="SMA, INTENS, INT_ERR, MAG, MAG_LERR, MAG_UERR",\ rows="-", \ option="plain", align="yes", sp_col="", lgroup=0, Stdout=output) for myfile in ['ellip','err','test.tab']: if os.access(myfile,os.F_OK): os.remove(myfile)
def run_elli_full(input, output, xcntr, ycntr, eg, pa, sma, sky):#,radd,background): """The function responsible for fit ellipse""" EllGal = 'GalEllFit.fits' fEl = pyfits.open(input) GaLaXy = fEl[0].data fEl.close() GaLaXy = GaLaXy - sky hdu = pyfits.PrimaryHDU(GaLaXy.astype(n.float32)) hdu.writeto(EllGal) try: iraf.stsdas(_doprint=0) iraf.tables(_doprint=0) iraf.stsdas.analysis(_doprint=0) iraf.stsdas.analysis.isophote(_doprint=0) except: iraf.stsdas() iraf.tables() iraf.stsdas.analysis() iraf.stsdas.analysis.isophote() image_exist = 1 iraf.unlearn('geompar') iraf.geompar.x0=xcntr iraf.geompar.y0=ycntr iraf.geompar.ellip0=eg iraf.geompar.pa0=pa iraf.geompar.sma0=6.0 iraf.geompar.minsma=0.1 iraf.geompar.maxsma=sma*5.0 iraf.geompar.step=0.1 iraf.geompar.recente="no" iraf.geompar.xylearn="no" iraf.unlearn('controlpar') iraf.controlpar.conver=0.05 iraf.controlpar.minit=10 iraf.controlpar.maxit=50 iraf.controlpar.hcenter="no" iraf.controlpar.hellip="no" iraf.controlpar.hpa="no" iraf.controlpar.wander="INDEF" iraf.controlpar.maxgerr=0.5 iraf.controlpar.olthres=1 iraf.controlpar.soft="no" iraf.samplepar.integrm="bi-linear" iraf.samplepar.usclip=3 iraf.samplepar.lsclip=3 iraf.samplepar.nclip=0 iraf.samplepar.fflag=0.5 iraf.unlearn('ellipse') iraf.ellipse("".join(EllGal), output="test", interac="no",Stdout="ellip", \ Stderr="err") iraf.tprint("test.tab", prparam="no", prdata="yes", pwidth=80, plength=0, \ showrow="no", orig_row="no", showhdr="no", showunits="no", \ columns="SMA, INTENS, INT_ERR, ELLIP, ELLIP_ERR, PA, PA_ERR, \ MAG, MAG_LERR, MAG_UERR, TMAG_E, TMAG_C, A3, \ A3_ERR, B3, B3_ERR, A4, A4_ERR, B4_ERR", rows="-", \ option="plain", align="yes", sp_col="", lgroup=0, Stdout=output) for myfile in ['ellip','err','test.tab', EllGal]: if os.access(myfile,os.F_OK): os.remove(myfile)
def run_elli(input, output, xcntr, ycntr, eg, pa, sma):#,radd,background): """The function resposible for fit ellipse""" iraf.stsdas(_doprint=0) iraf.tables(_doprint=0) iraf.stsdas.analysis(_doprint=0) iraf.stsdas.analysis.isophote(_doprint=0) image_exist = 1 # if(str(input)[:3] == 'ima'): # output = 'elli_' + input[6:-4] + 'txt' # if(str(input)[:3] == 'out'): # output = 'out_elli_' + str(input)[4:-7] + 'txt' # else: # output = 'elli_' + input[:-5] + '.txt' #unlearn geompar controlpar samplepar magpar ellipse iraf.unlearn('geompar') iraf.geompar.x0=xcntr iraf.geompar.y0=ycntr iraf.geompar.ellip0=eg iraf.geompar.pa0=pa iraf.geompar.sma0=10 iraf.geompar.minsma=0.1 iraf.geompar.maxsma=sma*5.0 iraf.geompar.step=0.1 iraf.geompar.recente="no" iraf.geompar.xylearn="no" iraf.unlearn('controlpar') iraf.controlpar.conver=0.05 iraf.controlpar.minit=10 iraf.controlpar.maxit=50 iraf.controlpar.hcenter="no" iraf.controlpar.hellip="no" iraf.controlpar.hpa="no" iraf.controlpar.wander="INDEF" iraf.controlpar.maxgerr=0.5 iraf.controlpar.olthres=1 iraf.controlpar.soft="no" iraf.samplepar.integrm="bi-linear" iraf.samplepar.usclip=3 iraf.samplepar.lsclip=3 iraf.samplepar.nclip=0 iraf.samplepar.fflag=0.5 iraf.magpar.mag0=c.mag_zero iraf.magpar.refer=1 iraf.magpar.zerolev=0 iraf.ellipse("".join(input), output="test", interac="no",Stdout="ellip", \ Stderr="err") iraf.tprint("test.tab", prparam="no", prdata="yes", pwidth=80, plength=0, \ showrow="no", orig_row="no", showhdr="no", showunits="no", \ columns="SMA, INTENS, INT_ERR, MAG, MAG_LERR, MAG_UERR, \ TFLUX_E", rows="-", \ option="plain", align="yes", sp_col="", lgroup=0, Stdout=output) for myfile in ['ellip','err','test.tab']: if os.access(myfile,os.F_OK): os.remove(myfile)
def run(args): """Generate the residual image using Ellipse run.""" """Call the STSDAS.ANALYSIS.ISOPHOTE package""" if args.isophote is None: if args.verbose: print '\n' + SEP print "## Call STSDAS.ANALYSIS.ISOPHOTE() " print SEP iraf.stsdas() iraf.analysis() iraf.isophote() iraf.ttools()
def _iraf_pset_init(): """Initialize common IRAF tasks for pset tests """ if not HAS_IRAF: return # imports & package loading iraf.stsdas(_doprint=0) iraf.imgtools(_doprint=0) iraf.mstools(_doprint=0) # reset PSET egstp's values _unlearn_egstp(iraf.egstp)
def _iraf_dqbits_init(_data): """Initialize common IRAF tasks for dqbits tests """ if not HAS_IRAF: return # imports & package loading iraf.stsdas(_doprint=0) iraf.imgtools(_doprint=0) iraf.artdata(_doprint=0) iraf.mstools(_doprint=0) # create two data files as input (dont care if appropriate to mscombine) iraf.imcopy('dev$pix', _data['dqbits']['input1']) iraf.imcopy('dev$pix', _data['dqbits']['input2'])
def __init__(self, shortparlists, parlists, FitsDir, logfile, verbose=1, clean_up=1, skyKey='ALIGNSKY', hdrGain=0, crlower=None, imNsci=1): self.modName = string.split(string.split(str(self))[0], '.')[0][1:] self.shortparlists = shortparlists self.parlists = parlists self.Fits = FitsDir self.verbose = verbose self.crmasks = {} # cosmic ray masks names self.removeList = [] self.clean_up = clean_up self.skyKey = skyKey self.hdrGain = hdrGain self.crlower = crlower if imNsci < 1: raise ValueError, 'Error: pyblot got imNsci = ' + imNsci self.imNsci = imNsci self.logfile = logfile print self.modName, 'version', __version__ self.logfile.write('Instantiating ' + self.modName + ' version ' + __version__) # make sure these packages are loaded iraf.stsdas() iraf.toolbox() iraf.imgtool() iraf.fourier() iraf.fitting() iraf.ttools() iraf.analysis() iraf.dither() # flush the cash! twice! iraf.flpr() iraf.flpr() iraf.reset(imtype='fits') # seems to make deriv task a bit happier iraf.set(tmp='./')
def define_lacosmic(path_to_lacos_im=''): """Moves to ``STSDAS`` package and defines ``LACOS_IM`` as an ``iraf`` task. Parameters ----------- path_to_lacos_im : string Your path to ``lacos_im.cl``. If left blank, assume Current Working Directory. #By default, reads from lacos_setup Notes ----- The IRAF way is task lacos_im = /path/lacos_im.cl """ iraf.stsdas() iraf.task(lacos_im=path_to_lacos_im + 'lacos_im.cl')
# Try iqpkg try: import iqpkg import iqutils except: print "No iqpkg, iqutils. Can't run lmi_stats." # Necessary packages iraf.images() iraf.immatch() # iraf.imfilter() iraf.noao() iraf.imred() iraf.ccdred() iraf.stsdas() iraf.hst_calib() iraf.nicmos() iraf.imutil() yes = iraf.yes no = iraf.no INDEF = iraf.INDEF globclob = yes globver = yes LMIFILTS = ["U", "B", "V", "R", "I", "SDSS-G", "SDSS-R", "SDSS-I", "SDSS-Z", "SDSS-U"] LMIPIXSCALE = 0.240 ASTROMCMD = "/Users/scenko/python/astrometry/vlt_autoastrometry.py" FDICT = {"SDSS-U": "UMAG", "SDSS-G": "GMAG", "SDSS-R": "RMAG", "SDSS-I": "IMAG", "SDSS-Z": "ZMAG"} SEEDICT = {"SDSS-U": "co", "SDSS-G": "go", "SDSS-R": "ro", "SDSS-I": "bo", "SDSS-Z": "ko"}
def imshiftcomb(inlist, outimg, fitgeom='shift', inpref='', objmask='none', combine='average', reject='none', fscale=False, fbase=100, fhead='F1', second=False, first_pref='sdfr', second_pref='sdf2r', indep=False, sigmap='none', expmap='none', whtmap='none', gain=5.6, ffpref=''): # check output image if os.access(outimg, os.R_OK): print >> sys.stderr, 'operation would overwrite existing image (%s)' % outimg return 1 # check input image list inimg_arr = check_input(inlist, inpref) if isinstance(inimg_arr, int): return 1 # check input image list if sigmap != 'none': ffimg_arr = check_input2(inlist, ffpref) if isinstance(ffimg_arr, int): return 1 # check optional output image if sigmap != 'none': if os.access(sigmap, os.R_OK): print >> sys.stderr, 'operation would overwrite existing image (%s)' % sigmap return 1 if expmap != 'none': if os.access(expmap, os.R_OK): print >> sys.stderr, 'operation would overwrite existing image (%s)' % expmap return 1 if whtmap != 'none': if os.access(whtmap, os.R_OK): print >> sys.stderr, 'operation would overwrite existing image (%s)' % whtmap return 1 # get array size im = pyfits.open(inimg_arr[0]) nx = im[0].header['NAXIS1'] ny = im[0].header['NAXIS2'] im.close() # check geomap data dx = [] dy = [] gmp_arr = [] gmp2_arr = [] dbs_arr = [] for i in range(len(inimg_arr)): fname, ext = os.path.splitext(inimg_arr[i]) gmp = fname + '.gmp' gmp2 = fname + '.gmp2' dbs = fname + '.dbs' gmp_arr.append(gmp) gmp2_arr.append(gmp2) dbs_arr.append(dbs) if not os.access(gmp, os.R_OK): print >> sys.stderr, 'geomap file (%s) does not exist' % (gmp) return 1 if os.access(dbs, os.R_OK): print >> sys.stderr, 'database file (%s) is already exist' % (dbs) return 1 if os.access(gmp2, os.R_OK): print >> sys.stderr, 'modified geomap file (%s) is already exist' % ( gmp2) return 1 fgmp = open(gmp) nl = 1 dx_ave = 0.0 dy_ave = 0.0 for line in fgmp: if not line.startswith('#'): param = line[:-1].split() if len(param) != 4: print >> sys.stderr, 'Invalid format in line %d of %s: %s' % ( nl, gmp, line[:-1]) fgmp.close() return 1 else: if isfloat(param[0]) == False or isfloat( param[1]) == False or isfloat( param[2]) == False or isfloat( param[3]) == False: print >> sys.stderr, 'failed to decode line %d of %s: %s' % ( nl, gmp, line[:-1]) fgmp.close() return 1 else: dx_ave += float(param[0]) - float(param[2]) dy_ave += float(param[1]) - float(param[3]) nl += 1 #print inimg_arr[i],nl dx.append(dx_ave / (nl - 1)) dy.append(dy_ave / (nl - 1)) if len(inimg_arr) != len(dx): print >> sys.stderr, 'number of input images does not match with that of offsets' return 1 #print 'debug' #print dx, max(dx), min(dx) #print dy, max(dy), min(dy) # check object mask if objmask.lower() == 'none': objmask = '' else: objmask_arr = check_inpref(objmask, inimg_arr) if isinstance(objmask_arr, int): return 1 # independent run flag if indep: second = True # prepare for temporary file tmp = tempfile.NamedTemporaryFile(suffix='', prefix='', dir='/tmp') tmp_prefix = tmp.name tmp.close() # calculate image median for zero shift iraf.unlearn('imstat') iraf.unlearn('mimstat') bgmed = [] for i in range(len(inimg_arr)): if objmask == '': ret = iraf.imstat(inimg_arr[i], format='no', fields='midpt', nclip=50, lsigma=3., usigma=3., Stdout=1) else: if not second: ret = iraf.mimstat(inimg_arr[i], imasks=objmask_arr[i] + '[pl]', format='no', fields='midpt', nclip=50, lsigma=3., usigma=3., Stdout=1) else: ret = iraf.mimstat(inimg_arr[i], imasks=objmask_arr[i], format='no', fields='midpt', nclip=50, lsigma=3., usigma=3., Stdout=1) if len(ret) == 1: bgmed.append(-1.0 * float(ret[0])) else: fout.close() remove_temp_all(tmp_prefix) print >> sys.stderr, 'failed to calculate median of the background in %s' % inimg_arr[ i] return 1 # get large array size and combined image size ret = get_large_region(nx, ny, dx, dy) if len(ret) != 6: print >> sys.stderr, 'failed to get large array size' return 1 x_size = ret[0] y_size = ret[1] xcmin = ret[2] xcmax = ret[3] ycmin = ret[4] ycmax = ret[5] # calculate image region in the large format xmin = int((x_size - nx) / 2) + 1 xmax = nx + int((x_size - nx) / 2) ymin = int((y_size - ny) / 2) + 1 ymax = ny + int((y_size - ny) / 2) #print 'debug' #print x_size, y_size, xcmin, xcmax, ycmin, ycmax #print xmin, xmax, ymin, ymax # copy image to larger format and shift image # iraf.unlearn('geomap') iraf.unlearn('geotran') obj_list = tmp_prefix + '_obj.lst' if os.access(obj_list, os.R_OK): os.remove(obj_list) fobj = open(obj_list, 'w') # for exposure time weight expweight = tmp_prefix + '_exp.lst' if os.access(expweight, os.R_OK): os.remove(expweight) fexp = open(expweight, 'w') # for zero offset zeroshift = tmp_prefix + '_zeroshift.dat' if os.access(zeroshift, os.R_OK): os.remove(zeroshift) fzero = open(zeroshift, 'w') # save the original fit geometry fitgeom_org = fitgeom # preparing for the sigma list and mask if sigmap == 'none': tmp_rejmask = '' else: tmp_rejmask = tmp_prefix + 'rejmask.fits' if os.access(tmp_rejmask, os.R_OK): os.remove(tmp_rejmask) inverse_var_list = tmp_prefix + '_var.lst' if os.access(inverse_var_list, os.R_OK): os.remove(inverse_var_list) finverse_var = open(inverse_var_list, 'w') for i in range(len(inimg_arr)): # restore the original fit geometry fitgeom = fitgeom_org # geometry transformation fgmp = open(gmp_arr[i]) fgmp2 = open(gmp2_arr[i], 'w') nobj = 0 for line in fgmp: if not line.startswith('#'): param = line[:-1].split() xref = float(param[0]) + xmin - 1 yref = float(param[1]) + ymin - 1 xin = float(param[2]) + xmin - 1 yin = float(param[3]) + ymin - 1 fgmp2.write('%.3f %.3f %.3f %.3f\n' % (xref, yref, xin, yin)) nobj += 1 fgmp.close() fgmp2.close() # check number of objects if i == 0 and nobj == 1 and fitgeom == 'rotate': print 'Warning: Number of reference objects is not enought to measure the rotation' print 'Warning: Only shift applied for all images' fitgeom = 'shift' fitgeom_org = 'shift' if nobj == 1 and fitgeom == 'rotate': print 'Warning: Number of objects in %s is not enought to measure the rotation' % ( inimg_arr[i]) print 'Warning: Only shift applied for %s' % (inimg_arr[i]) fitgeom = 'shift' # mapping geometry iraf.geomap(gmp2_arr[i], dbs_arr[i], 1, x_size, 1, y_size, fitgeom=fitgeom, interac='no') # mask frame msk = np.ones((y_size, x_size)) msk[ymin - 1:ymax, xmin - 1:xmax] = 0 hdu = pyfits.PrimaryHDU(msk) msk_img = pyfits.HDUList([hdu]) msk_fits = tmp_prefix + 'mask' + os.path.basename(inimg_arr[i]) msktr_fits = tmp_prefix + 'masktr' + os.path.basename(inimg_arr[i]) if os.access(msk_fits, os.R_OK): os.remove(msk_fits) if os.access(msktr_fits, os.R_OK): os.remove(msktr_fits) msk_img.writeto(msk_fits) msk_img.close() # transform mask geometry iraf.geotran(msk_fits, msktr_fits, dbs_arr[i], gmp2_arr[i], geometr='linear', boundar='constant', constant=1) os.remove(msk_fits) convert_maskfits_int(msktr_fits, msktr_fits) # load original frame img = pyfits.open(inimg_arr[i]) if sigmap != 'none': ffimg = pyfits.open(ffimg_arr[i]) # for exposure time weight try: t = float(img[0].header['EXP1TIME']) coadd = float(img[0].header['COADDS']) expt = t * coadd except KeyError: print >> sys.stderr, 'can not read exposure time from the header of %s' % inimg_arr[ i] img.close() return 1 # for flux scaling and weight if fscale: try: flux = float(img[0].header[fhead]) except KeyError: print >> sys.stderr, 'can not read flux keyword (%s) from the header of %s' % ( fhead, inimg_arr[i]) img.close() return 1 flux_scale = fbase / flux weight = expt * (1.0 / flux_scale)**2 else: flux_scale = 1.0 weight = expt fzero.write('%f\n' % (bgmed[i] * flux_scale)) fexp.write('%f\n' % weight) # object frame obj = np.zeros((y_size, x_size)) obj[ymin - 1:ymax, xmin - 1:xmax] = img[0].data * flux_scale hdu = pyfits.PrimaryHDU(obj) obj_img = pyfits.HDUList([hdu]) obj_img[0].header = img[0].header obj_img[0].header['bpm'] = msktr_fits obj_img[0].header['expmap'] = expt obj_fits = tmp_prefix + 'obj' + os.path.basename(inimg_arr[i]) objtr_fits = tmp_prefix + 'objtr' + os.path.basename(inimg_arr[i]) if os.access(obj_fits, os.R_OK): os.remove(obj_fits) obj_img.writeto(obj_fits) obj_img.close() iraf.geotran(obj_fits, objtr_fits, dbs_arr[i], gmp2_arr[i], geometr='linear', boundar='constant', constant=0) fobj.write('%s\n' % objtr_fits) img.close() if sigmap != 'none': inverse_var = np.zeros((y_size, x_size)) inverse_var[ymin - 1:ymax, xmin - 1:xmax] = (np.sqrt(ffimg[0].data / (gain * expt)) * flux_scale)**-2 hdu_var = pyfits.PrimaryHDU(inverse_var) inverse_var_img = pyfits.HDUList([hdu_var]) inverse_var_img[0].header = img[0].header inverse_var_img[0].header['bpm2'] = '%s[*,*,%d]' % (tmp_rejmask, i + 1) inverse_var_fits = tmp_prefix + 'var' + os.path.basename( inimg_arr[i]) inverse_vartr_fits = tmp_prefix + 'vartr' + os.path.basename( inimg_arr[i]) if os.access(inverse_var_fits, os.R_OK): os.remove(inverse_var_fits) if os.access(inverse_vartr_fits, os.R_OK): os.remove(inverse_vartr_fits) inverse_var_img.writeto(inverse_var_fits) inverse_var_img.close() iraf.geotran(inverse_var_fits, inverse_vartr_fits, dbs_arr[i], gmp2_arr[i], geometr='linear', boundar='constant', constant=0) finverse_var.write('%s\n' % inverse_vartr_fits) ffimg.close() # close file handlers fobj.close() fexp.close() fzero.close() if sigmap != 'none': finverse_var.close() # combine image comb_img = tmp_prefix + '_comb.fits' if os.access(comb_img, os.R_OK): os.remove(comb_img) if expmap == 'none': tmp_expmap = '' else: tmp_expmap = tmp_prefix + 'expmap.fits' if os.access(tmp_expmap, os.R_OK): os.remove(tmp_expmap) iraf.unlearn('imcombine') try: iraf.imcombine('@' + obj_list, comb_img, sigma='', rejmask=tmp_rejmask, expmasks=tmp_expmap, combine=combine, reject=reject, masktype='!BPM', maskvalue=0.0, zero='@' + zeroshift, weight='@' + expweight, expname='EXPMAP') except: if os.access(comb_img, os.R_OK): os.remove(comb_img) if expmap != 'none': if os.access(tmp_expmap, os.R_OK): os.remove(tmp_expmap) iraf.imcombine('@' + obj_list, comb_img, sigma='', rejmask='', expmasks=tmp_expmap, combine=combine, reject=reject, masktype='!BPM', maskvalue=0.0, zero='@' + zeroshift, weight='@' + expweight, expname='EXPMAP') if sigmap != 'none': tmp_inverse_var_sum = tmp_prefix + 'inverse_var.fits' if os.access(tmp_inverse_var_sum, os.R_OK): os.remove(tmp_inverse_var_sum) iraf.imcombine('@' + inverse_var_list, tmp_inverse_var_sum, combine='sum', reject='none', masktype='!BPM', maskvalue=0.0) iraf.stsdas() tmp_sigma = tmp_prefix + 'sigma.fits' if os.access(tmp_sigma, os.R_OK): os.remove(tmp_sigma) iraf.imcalc(tmp_inverse_var_sum, tmp_sigma, 'sqrt(1.0/im1)', pixtype='double') # cut image iraf.unlearn('imcopy') cut_img = '%s[%d:%d,%d:%d]' % (comb_img, xcmin, xcmax, ycmin, ycmax) iraf.imcopy(cut_img, outimg) if expmap != 'none': cut_exp = '%s[%d:%d,%d:%d]' % (tmp_expmap, xcmin, xcmax, ycmin, ycmax) iraf.imcopy(cut_exp, expmap) if sigmap != 'none': cut_sigma = '%s[%d:%d,%d:%d]' % (tmp_sigma, xcmin, xcmax, ycmin, ycmax) iraf.imcopy(cut_sigma, sigmap) if whtmap != 'none': cut_wht = '%s[%d:%d,%d:%d]' % (tmp_inverse_var_sum, xcmin, xcmax, ycmin, ycmax) iraf.imcopy(cut_wht, whtmap) # delete temporary object files remove_temp_all(tmp_prefix + 'obj') os.remove(obj_list) os.remove(comb_img) # record relative offset between input images and combined image and rotation for i in range(len(inimg_arr)): im = pyfits.open(inimg_arr[i], mode='update') if second: if indep: # calculate offset dxc = xcmin - xmin - dx[i] dyc = ycmin - ymin - dy[i] # retrieve rotation rot = 0.0 fdbs = open(dbs_arr[i]) for line in fdbs: param = line[:-1].split() if param[0] == 'xrotation': rot = float(param[1]) if rot > 180.0: rot = rot - 360.0 im[0].header['dx'] = dx[i] im[0].header['dy'] = dy[i] im[0].header['dxc'] = dxc im[0].header['dyc'] = dyc im[0].header['rotation'] = rot else: # check number of objects in the geomap file nobj = 0 fgmp = open(gmp_arr[0]) for line in fgmp: nobj += 1 im1 = pyfits.open(inimg_arr[i].replace(second_pref, first_pref), mode='update') for j in range(nobj): key = 'XC%d' % (j + 1) im[0].header[key] = float(im1[0].header[key]) key = 'YC%d' % (j + 1) im[0].header[key] = float(im1[0].header[key]) key = 'PEAK%d' % (j + 1) im[0].header[key] = float(im1[0].header[key]) key = 'FWHM%d' % (j + 1) im[0].header[key] = float(im1[0].header[key]) key = 'DX' im[0].header[key] = float(im1[0].header[key]) key = 'DY' im[0].header[key] = float(im1[0].header[key]) key = 'DXC' im[0].header[key] = float(im1[0].header[key]) key = 'DYC' im[0].header[key] = float(im1[0].header[key]) key = 'ROTATION' im[0].header[key] = float(im1[0].header[key]) im1.close() else: # calculate offset dxc = xcmin - xmin - dx[i] dyc = ycmin - ymin - dy[i] # retrieve rotation rot = 0.0 fdbs = open(dbs_arr[i]) for line in fdbs: param = line[:-1].split() if param[0] == 'xrotation': rot = float(param[1]) if rot > 180.0: rot = rot - 360.0 im[0].header['dx'] = dx[i] im[0].header['dy'] = dy[i] im[0].header['dxc'] = dxc im[0].header['dyc'] = dyc im[0].header['rotation'] = rot im.close() # remove all temporary files remove_temp_all(tmp_prefix) return 0
def sigmap(inlist, sigmap, expmap='none', whtmap='none', inpref='', ffpref='', objmask='none', reject='sigclip', fscale=False, fbase=100, fhead='F1', gain=5.6): # check output image if os.access(sigmap, os.R_OK): print >> sys.stderr, 'operation would overwrite existing image (%s)' % sigmap return 1 if os.access(expmap, os.R_OK): print >> sys.stderr, 'operation would overwrite existing image (%s)' % expmap return 1 if os.access(whtmap, os.R_OK): print >> sys.stderr, 'operation would overwrite existing image (%s)' % whtmap return 1 # check input image list inimg_arr = check_input(inlist, inpref) if isinstance(inimg_arr, int): return 1 # check input image list ffimg_arr = check_input2(inlist, ffpref) if isinstance(ffimg_arr, int): return 1 # get array size im = pyfits.open(inimg_arr[0]) nx = im[0].header['NAXIS1'] ny = im[0].header['NAXIS2'] im.close() # check geomap data dx = [] dy = [] gmp_arr = [] gmp2_arr = [] dbs_arr = [] for i in range(len(inimg_arr)): fname, ext = os.path.splitext(inimg_arr[i]) gmp = fname + '.gmp' gmp2 = fname + '.gmp2' dbs = fname + '.dbs' gmp_arr.append(gmp) gmp2_arr.append(gmp2) dbs_arr.append(dbs) if not os.access(gmp, os.R_OK): print >> sys.stderr, 'geomap file (%s) does not exist' % (gmp) return 1 if not os.access(dbs, os.R_OK): print >> sys.stderr, 'database file (%s) does not exist' % (dbs) return 1 if not os.access(gmp2, os.R_OK): print >> sys.stderr, 'modified geomap file (%s) does not exist' % ( gmp2) return 1 fgmp = open(gmp) nl = 1 dx_ave = 0.0 dy_ave = 0.0 for line in fgmp: if not line.startswith('#'): param = line[:-1].split() if len(param) != 4: print >> sys.stderr, 'Invalid format in line %d of %s: %s' % ( nl, gmp, line[:-1]) fgmp.close() return 1 else: if isfloat(param[0]) == False or isfloat( param[1]) == False or isfloat( param[2]) == False or isfloat( param[3]) == False: print >> sys.stderr, 'failed to decode line %d of %s: %s' % ( nl, gmp, line[:-1]) fgmp.close() return 1 else: dx_ave += float(param[0]) - float(param[2]) dy_ave += float(param[1]) - float(param[3]) nl += 1 #print inimg_arr[i],nl dx.append(dx_ave / (nl - 1)) dy.append(dy_ave / (nl - 1)) if len(inimg_arr) != len(dx): print >> sys.stderr, 'number of input images does not match with that of offsets' return 1 # check object mask if objmask.lower() == 'none': objmask = '' else: objmask_arr = check_inpref(objmask, inimg_arr) if isinstance(objmask_arr, int): return 1 # prepare for temporary file tmp = tempfile.NamedTemporaryFile(suffix='', prefix='', dir='/tmp') tmp_prefix = tmp.name tmp.close() # get large array size and combined image size ret = get_large_region(nx, ny, dx, dy) if len(ret) != 6: print >> sys.stderr, 'failed to get large array size' return 1 x_size = ret[0] y_size = ret[1] xcmin = ret[2] xcmax = ret[3] ycmin = ret[4] ycmax = ret[5] # calculate image region in the large format xmin = int((x_size - nx) / 2) + 1 xmax = nx + int((x_size - nx) / 2) ymin = int((y_size - ny) / 2) + 1 ymax = ny + int((y_size - ny) / 2) # copy image to larger format and shift image # iraf.unlearn('geomap') iraf.unlearn('geotran') # for exposure time weight and flux scaling expt_arr = [] flux_scale_arr = [] for i in range(len(inimg_arr)): # load original frame img = pyfits.open(inimg_arr[i]) # for exposure time weight try: t = float(img[0].header['EXP1TIME']) coadd = float(img[0].header['COADDS']) expt_arr.append(t * coadd) except KeyError: print >> sys.stderr, 'can not read exposure time from the header of %s' % inimg_arr[ i] img.close() return 1 # for flux scaling and weight if fscale: try: flux = float(img[0].header[fhead]) except KeyError: print >> sys.stderr, 'can not read flux keyword (%s) from the header of %s' % ( fhead, inimg_arr[i]) img.close() return 1 flux_scale_arr.append(fbase / flux) else: flux_scale_arr.append(1.0) img.close() # preparing weighted variance map for each image inverse_var_list = tmp_prefix + '_obj.lst' if os.access(inverse_var_list, os.R_OK): os.remove(inverse_var_list) finverse_var = open(inverse_var_list, 'w') for i in range(len(inimg_arr)): # mask frame msk = np.ones((y_size, x_size)) msk[ymin - 1:ymax, xmin - 1:xmax] = 0 hdu = pyfits.PrimaryHDU(msk) msk_img = pyfits.HDUList([hdu]) msk_fits = tmp_prefix + 'mask' + os.path.basename(inimg_arr[i]) msktr_fits = tmp_prefix + 'masktr' + os.path.basename(inimg_arr[i]) if os.access(msk_fits, os.R_OK): os.remove(msk_fits) if os.access(msktr_fits, os.R_OK): os.remove(msktr_fits) msk_img.writeto(msk_fits) msk_img.close() # transform mask geometry iraf.geotran(msk_fits, msktr_fits, dbs_arr[i], gmp2_arr[i], geometr='linear', boundar='constant', constant=1) os.remove(msk_fits) convert_maskfits_int(msktr_fits, msktr_fits) # load original frame ffimg = pyfits.open(ffimg_arr[i]) img = pyfits.open(inimg_arr[i]) # object frame inverse_var = np.zeros((y_size, x_size)) #print np.median(ffimg[0].data), ffimg_arr[i], gain, expt_arr[i], flux_scale_arr[i] #print np.median(np.sqrt(ffimg[0].data / (gain * expt_arr[i]))), flux_scale_arr[i] inverse_var[ymin - 1:ymax, xmin - 1:xmax] = (np.sqrt(ffimg[0].data / (gain * expt_arr[i])) * flux_scale_arr[i])**-2 hdu = pyfits.PrimaryHDU(inverse_var) inverse_var_img = pyfits.HDUList([hdu]) inverse_var_img[0].header = img[0].header inverse_var_img[0].header['bpm'] = msktr_fits inverse_var_img[0].header.update('EXPTIME', expt_arr[i]) #inverse_var_img[0].header.update('MASKSCAL', expt_arr[i]) #inverse_var_img[0].header.update('MASKZERO', expt_arr[i]) #print 'EXPT = %f' % (expt_arr[i]) inverse_var_fits = tmp_prefix + 'var' + os.path.basename(inimg_arr[i]) inverse_vartr_fits = tmp_prefix + 'vartr' + os.path.basename( inimg_arr[i]) if os.access(inverse_var_fits, os.R_OK): os.remove(inverse_var_fits) if os.access(inverse_vartr_fits, os.R_OK): os.remove(inverse_vartr_fits) inverse_var_img.writeto(inverse_var_fits) inverse_var_img.close() iraf.geotran(inverse_var_fits, inverse_vartr_fits, dbs_arr[i], gmp2_arr[i], geometr='linear', boundar='constant', constant=0) finverse_var.write('%s\n' % inverse_vartr_fits) ffimg.close() # close file handlers finverse_var.close() # sum weighted variance images tmp_inverse_var_sum = tmp_prefix + 'inverse_var.fits' if os.access(tmp_inverse_var_sum, os.R_OK): os.remove(tmp_inverse_var_sum) tmp_sigma = tmp_prefix + 'sigma.fits' if os.access(tmp_sigma, os.R_OK): os.remove(tmp_sigma) tmp_exp = tmp_prefix + 'exp.fits' if os.access(tmp_exp, os.R_OK): os.remove(tmp_exp) if expmap != 'none': #iraf.hselect('@'+inverse_var_list,"$I,EXPTIME,MASKSCAL,MASKZERO","yes") iraf.imcombine('@' + inverse_var_list, tmp_inverse_var_sum, expmasks=tmp_exp, combine='sum', reject=reject, masktype='!BPM', maskvalue=0.0, expname='EXPTIME') else: iraf.imcombine('@' + inverse_var_list, tmp_inverse_var_sum, combine='sum', reject=reject, masktype='!BPM', maskvalue=0.0) # calculate sigma iraf.stsdas() iraf.imcalc(tmp_inverse_var_sum, tmp_sigma, 'sqrt(1.0/im1)', pixtype='double') # cut image iraf.unlearn('imcopy') cut_sig = '%s[%d:%d,%d:%d]' % (tmp_sigma, xcmin, xcmax, ycmin, ycmax) iraf.imcopy(cut_sig, sigmap) if expmap != 'none': cut_exp = '%s[%d:%d,%d:%d]' % (tmp_exp, xcmin, xcmax, ycmin, ycmax) iraf.imcopy(cut_exp, expmap) # calc weight map if whtmap != 'none': cut_wht = '%s[%d:%d,%d:%d]' % (tmp_inverse_var_sum, xcmin, xcmax, ycmin, ycmax) iraf.imcopy(cut_wht, whtmap) # delete temporary object files os.remove(inverse_var_list) # remove all temporary files remove_temp_all(tmp_prefix) return 0
def decon(r, f, idx, r1, r2, fiber_size, pixel_pitch): # x1 = np.where(r >= r1)[0][0] # x2 = np.where(r >= r2)[0][0] 'in pixel units' radius = (fiber_size/pixel_pitch)/(2)#*(r2-r1)/(x2-x1)) # idx = np.where(r >= peak)[0][0] idx += chi(r,f,radius, idx) size = f.shape[0] _ = np.seterr(invalid='ignore') theta = np.arccos(np.abs(r - r[idx])/radius) pn = radius*np.nan_to_num(np.sin(theta)) zpn = pn[np.where(pn != 0)[0]] # zpn = pn # zpn = np.zeros(f.size) # zpn[0:f.size] = pn[np.where(pn != 0)[0][0]] ff = np.copy(f)/np.sum(f[np.where(f > 0)[0]]) pnf = np.copy(zpn)/np.sum(zpn) if debug: fig1 = plt.figure(fignum) plt.clf() sp3 = fig1.add_subplot(223) sp3.plot(r*pixel_pitch,ff,label='Ring profile') sp3.plot(r*pixel_pitch,pn/pn.sum(),label='Ideal beam profile') sp3.legend() sp3.set_title("Area normalized data and ideal beam profile") sp3.set_xlabel("Radius (um)") sp3.set_ylabel("Normalized Counts") 'so we can parallelize' temp_str = 'temp_'+str(datetime.now().microsecond) idl_name = temp_str+'_idl.fits' pyfits.PrimaryHDU(ff).writeto(temp_str+'_ff.fits') pyfits.PrimaryHDU(pnf).writeto(temp_str+'_pn.fits') stsdas() stsdas.analysis() stsdas.analysis.restore() stsdas.analysis.restore.lucy\ (temp_str+'_ff.fits',temp_str+'_pn.fits',temp_str+'_frd.fits',1,0) command = "\"MWRFITS, MRDFITS('"+temp_str+"_frd.fits'),'"+idl_name+"'\"" os.system('idl -quiet -e '+command) frd = pyfits.open(idl_name)[0].data global frd_sav frd_save = frd (peak, r1, r2) = find_peak(r,frd) os.system('rm ./'+temp_str+'*.fits') return ((r2 - r1),frd)
# # ######################################################################################### ''' import os from pyraf import iraf from astropy.io import fits from shutil import copy2 import rsstools as rt import numpy as np iraf.noao(_doprint=0) iraf.twodspec(_doprint=0) iraf.longslit(_doprint=0) iraf.apextract(dispaxis='1') iraf.stsdas(_doprint=0) iraf.analysis(_doprint=0) iraf.fitting(_doprint=0) class arc(object): def __init__(self, name): self.name = name self.noext = os.path.splitext(self.name)[0] self.idname = rt.makesetups(self.name,"arc") self.idfits = self.idname+'.fits' self.linelist = self.idname.split('_')[0].lower()+'.dat' self.header = self.read_header() def read_header(self): return fits.getheader(self.name) def __str__(self):
#!/usr/bin/env python import numpy as np import pyfits from pyraf import iraf iraf.stsdas() import subtract_scattered_background as ssb import rmscheck import os, sys import pylab as plt from stats import gauss """ A pipeline that prepares the IRAC mosaics for use by TFIT. Assume the starting images to be the following: - a drizzled IRAC mosaic image with pixel scale 0.6 arcsec/pixel, with the same astrometry as the high-resolution HST mosaics, and has the unit of MJy/sr - an IRAC uncertainty image (*_unc.fits), in units of MJy/sr - usually the cutout of the IRAC mosaic should cover a larger area than the HST mosaics, so that TFIT doesn't break down when there are high-resolution templates near (or even beyond) the image border of the IRAC mosaic """ exptimes={'ch1':96.8, 'ch2':96.8, 'ch3':96.8, 'ch4':46.8} # exposure time per AOR (used to convert cov map to exp map) fluxconv = {'ch1':0.1253, 'ch2':0.1469} subreg_default = {'bullet':(141,260,365,450)} # the FLUXCONV factor in units of MJy/sr per DN/sec, for the warm mission only # taken from the webpage # http://irsa.ipac.caltech.edu/data/SPITZER/docs/irac/warmfeatures/ def irac_pipeline(drz_img, unc_img, channel, rmsmode='unc', pixscale=0.6, gain=3.7,
def ellipse(image, outname, verbose=False, **kwargs): """run ellipse task image : input image name outname : output filename Keywords: *geompar* x0, y0 -- required ellip0 : initial ellipticity (default=0.2) pa0 : initial PA in degrees ccw from +y (default=20) sma0 : initial semi-major axis (default=10) minsma : minimum sma (default=1) maxsma : maximum sma (default='INDEF') step : sma step size (default=0.1) linear : linear sampling of sma? (default='no') *controlpar* conver : """ # verify input if 'x0' not in kwargs.keys() or 'y0' not in kwargs.keys(): raise KeyError('x0 or y0 is not found') # load packages iraf.stsdas(_doprint=0, motd=False) iraf.analysis(_doprint=0) iraf.isophote(_doprint=0) # reset all parameters iraf.unlearn('ellipse', 'geompar', 'controlpar', 'samplepar') iraf.ellipse.interactive = False iraf.ellipse.xylearn = False # if True, it prompts input upon faling to find center # geompar iraf.ellipse.x0 = kwargs.pop('x0') iraf.ellipse.y0 = kwargs.pop('y0') iraf.ellipse.ellip0 = kwargs.pop('ellip0', 0.2) iraf.ellipse.pa0 = kwargs.pop('pa0', 20.0) iraf.ellipse.sma0 = kwargs.pop('sma0', 10.0) iraf.ellipse.minsma = kwargs.pop('minsma', 1.) iraf.ellipse.maxsma = kwargs.pop('maxsma', 'INDEF') iraf.ellipse.step = kwargs.pop('step', 0.1) iraf.ellipse.linear = kwargs.pop('linear', 0) iraf.ellipse.verbose = verbose # controlpar iraf.ellipse.conver = kwargs.pop('conver', 0.05) iraf.ellipse.minit = kwargs.pop('minit', 10) iraf.ellipse.maxit = kwargs.pop('maxit', 50) iraf.ellipse.hcenter = kwargs.pop('hcenter', 'no') # samplepar iraf.ellipse.tsample = kwargs.pop('tsample', 'none') iraf.ellipse.harmonics = kwargs.pop('harmonics', 'none') if verbose: iraf.lparam('ellipse') iraf.lparam('geompar') iraf.lparam('controlpar') iraf.lparam('samplepar') # run ellipse tempname = shorten_iauname(image) + str(uuid.uuid4()) + '.tab' try: iraf.ellipse(image, tempname) # print ascii table iraf.tprint(tempname, pwidth='INDEF', Stdout=outname) os.remove(tempname) except: print 'ellipse failed'
from pyraf import iraf from astropy.io import fits import numpy as np import os import glob os.putenv('iraf', '/iraf/iraf') iraf.stsdas(_doprint=1) objectName = os.getcwd()[-5:].lower() print objectName # iraf.stsdas.analysis.gasp.xyeq() os.putenv('iraf', '/iraf.216/iraf') iraf.stsdas(_doprint=1) os.putenv('iraf', '/iraf/iraf') iraf.stsdas(_doprint=1)
def pyraf_bmodel(binary, parent, output=None, highar=False, verbose=False, interp='spline', backgr=0.0): """Wrapper of the `Pyraf` `bmodel` function to build 2-D model. For details about the `bmodel` task, please see: http://stsdas.stsci.edu/cgi-bin/gethelp.cgi?bmodel Parameters ---------- binary: str Location of the output binary file from `ellipse` task. parent: str Location of the input image that `ellipse` run is based on. output: str, optional Name of the output FITS image highar: boolen, optional Whether to include the higher-order Fourier component. Default: False. verbose: boolen, optional Verbose mode. Default: False. interp: str, optional The interpolation mode used by the `trebin` task. Allowed values are: nearest | linear | poly3 | spline. Default: spline. Returns ------- model: ndarray 2-D model image of the `ellipse` results. """ # Initiate the isophote module in IRAF/STSDAS try: from pyraf import iraf iraf.stsdas() iraf.analysis() iraf.isophote() except ImportError: raise Exception("# Unfortunately, you need to install pyraf first.") # Make sure the files are available if not os.path.isfile(binary): raise FileNotFoundError( "# Can not find the binary output file: {}".format(binary)) if not os.path.isfile(parent): raise FileNotFoundError( "# Can not find the input image: {}".format(parent)) # Name of the output FITS file if output is None: output = os.path.splitext(binary)[0] + '_model.fits' # Remove the output file if it exists if os.path.isfile(output): os.remove(output) # Check the interpolation method if interp not in PYRAF_INTERP: raise Exception("# Wrong interpolation method! Choices are {}".format( PYRAF_INTERP)) # Higher-order harmonic modes highar_str = "yes" if highar else "no" verbose_str = "yes" if verbose else "no" try: iraf.bmodel(binary, output, parent=parent, interp=interp, highar=highar_str, backgr=backgr, verbose=verbose_str) except Exception: warnings.warn("# Something is wrong with the Bmodel task!") return None if not os.path.isfile(output): raise FileNotFoundError( "# Cannot find the output file: {}".format(output)) else: model = fits.open(output)[0].data return model
from pyraf import iraf from astropy.io import fits import numpy as np import os import glob os.putenv('iraf','/iraf/iraf') iraf.stsdas(_doprint=1) objectName = os.getcwd()[-5:].lower() print objectName # iraf.stsdas.analysis.gasp.xyeq() os.putenv('iraf','/iraf.216/iraf') iraf.stsdas(_doprint=1) os.putenv('iraf','/iraf/iraf') iraf.stsdas(_doprint=1)