def wspectext(): if not os.path.exists(Path + '/test3/'): os.mkdir(Path + '/test3/') fs = glob(Path + '/test/' + '/sci*.fits') for i, f in enumerate(fs): iraf.cd(Path + '/test3/') iraf.wspectext(f, ('sci' + str(i) + '.dat'))
def export_observation_to_txt(fits_path, txt_path): print(' Exporting file') for order in np.arange(1, 32, 1): try: iraf.wspectext(input=fits_path + '[*,' + str(order) + ',1]', output=txt_path + '_{:.0f}.txt'.format(order), header='no') except Exception as e: print(e) pass
def export_spectrum_to_txt(WORK_DIR, suffix='_vh_norm', export_cal=False): if export_cal: objects = observations[WORK_DIR]['calibs'] else: objects = observations[WORK_DIR]['objects'] for obj in objects: print ' Exporting file:', obj+suffix for order in np.arange(1, 31, 1): try: iraf.wspectext(input=obj+suffix+'.fits[*,'+str(order)+',1]', output=obj+suffix+'_order{:02.0f}.txt'.format(order), header='no') except: pass
def fits2ascii(input_files): if '.list' in input_files: input_files = [line.rstrip('\n') for line in open(input_files)] elif len(input_files.split()) > 1: pass elif '.fits' in input_files: input_files = [input_files] for input_file in input_files: try: output_file = input_file.split('.fits')[0] + '.dat' iraf.wspectext(input_file + '[*,1]', output_file, header=False) print(input_file, ' > ', output_file) except: print(input_file, ' failed...')
justplot = True if justplot == False: print 'Extracting spectrum' np.savetxt('.' + input_location + 'allspec', [spectrum + '[4]'], fmt="%s") ## begin IRAFing ### Extract the 1D spectrum iraf.scopy(spectrum + '[4]', '.' + input_location + 'allspeccal2') iraf.wspectext('.' + input_location + 'allspeccal2', '.' + input_location + '' + SN + '_' + date + '.txt', header='no') print 'Removing allspeccal2.fits' os.remove('.' + input_location + 'allspeccal2.fits') else: print 'Skipping spectrum extraction' ### Correct the spectrum corrections = glob.glob('./CorrectionFiles/*.txt') clist = [float(os.path.basename(c)[:-4]) for c in corrections] correction_index = np.argmin(abs(np.array(clist) - airmass)) corloc = './CorrectionFiles/' + str(clist[correction_index]) + '.txt' print 'Correcting flux for airmass', airmass, 'using', str( clist[correction_index]) + '.txt'
os.system("rm fluxcal_" + file_name) os.system("mv temp.fits fluxcal_" + file_name) ### Move spectrum to reduced/ #os.system("rm " + file_path_reduced + "spec_" + file_name) os.system("cp -f " + "fluxcal_" + file_name + " " + file_path_reduced) ######################## ### Create .dat file ### ######################## ### This file will later be read in for spectral matching os.chdir(file_path_reduced) os.system("rm fluxcal_" + file_name + ".dat") iraf.wspectext("fluxcal_" + file_name+"[*,1,1]", "fluxcal_" + file_name + ".dat") ### rewrite it in the form #wavelength flux spectrum = functions.read_ascii("fluxcal_" + file_name + ".dat") spectrum = functions.read_table(spectrum) temp = [] for i in spectrum: if len(i) == 2: if functions.is_number(i[0]): temp.append(i) spectrum = temp spectrum = spectrum[1:len(spectrum)-2] output_spectrum = open("fluxcal_" + file_name + ".dat","w") functions.write_table(spectrum,output_spectrum) output_spectrum.close()
def wechelletxt(self, infile, outdir): for i in range(1, self.norders + 1): #Do this for all 51 orders inp = infile + "[*,{:d}]".format(i) out = outdir + "/{:0>2d}.txt".format(i) iraf.wspectext(input=inp, output=out)
nhigh=1, nkeep=2) iraf.scombine(input=combstr, out='combinedspec.ms', combine='average', reject='minmax', scale='none', sample='5000:7500', nlow=0, nhigh=1, nkeep=1) l.write('calib=yes') iraf.splot(images='combinedspec_rmlow.ms.fits') for objname in objects_pars: if 'sn' in objname: SNName = objects_pars[objname][0] break iraf.wspectext(input='combinedspec.ms.fits[*,1]', output=SNName + '.ascii', header='NO') iraf.wspectext(input='combinedspec_rmlow.ms.fits[*,1]', output=SNName + '_rmlow.ascii', header='NO') l.write('finalname=' + SNName + '.ascii') l.close()
def gen_ar(): #cargo resultado de f2c temps, pasos, intensidad = f2c(res_tem="S", step_tem=100) x = pasos y = temps z = intensidad print(x[z.index(max(z))], y[z.index(max(z))]) os.chdir("../") # obtengo parametros para para fxcor obfx = "aB" + str(x[z.index(max(z))]) temp = str(int(y[z.index(max(z))])) if len(temp) == 4: temp = "0" + temp iraf.imdel("ss") iraf.imdel("tem") iraf.sarit("T" + temp, "-", 1, "ss") iraf.sarit("ss", "*", "amortigua", "tem") fig = plt.figure(figsize=(12, 9.0)) fig.subplots_adjust(hspace=0.4, bottom=0.06, top=0.94, left=0.12, right=0.94) #ejecuto y ploteo fxcor ax2 = plt.subplot2grid((4, 1), (0, 0)) # grafico la func, de correlacion program_dir = os.getcwd() + "/" ccf_command = program_dir + "fxcor_cursor_command.txt" #comando para extraeer los datos del grafico interact = 1 iraf.imdel("new_ccf.txt") iraf.fxcor(object=obfx, templates="tem", cursor=ccf_command, ccftype="text", interactive=interact) #fxcor de irad data = asciitable.read("new_ccf.txt") #archivo de salida del fxcor ax2.set_xlim(-2000, 2000) plt.axhline(linewidth=2, color='r') plt.plot(data["col1"], data["col2"], "-", color="black") plt.axvspan(-100, 100, facecolor='grey', alpha=0.5) #plt.axhspan(0.9, 1.00, facecolor='grey', alpha=0.5) ax2.yaxis.set_major_locator(plt.MaxNLocator(5)) ax2.set_xlabel(r'Velocity', fontsize=18) ax2.set_ylabel(r'Correlation', fontsize=18) #datos para scale iraf.imdel("scale") iraf.imdel("tplsca") obscale = "B" + str(x[z.index(max(z))]) temp = "T" + temp w1 = 5900 w2 = 6490 wi = 300 iraf.imdel("scale.txt") iraf.imdel("tplsca.txt") iraf.scale(spec=obscale, tpl=temp, w1=w1, w2=w2, width=wi) iraf.wspectext("scale.fits", "scale.txt", header="no") iraf.wspectext("tplsca.fits", "tplsca.txt", header="no") iraf.wspectext(obscale, "obscale.txt", header="no") #ploteo resultados de f2c ax1 = plt.subplot2grid((4, 1), (1, 0), rowspan=3) # define grid. xi = np.linspace(min(x), max(x), 1000) yi = np.linspace(min(y), max(y), 1000) # grid the data. zi = griddata((x, y), z, (xi[None, :], yi[:, None]), method='linear') # contour the gridded data, plotting dots at the randomly spaced data points. CS = plt.contour(xi, yi, zi, 15, linewidths=0.5, colors='k') CS = plt.contourf(xi, yi, zi, 15, cmap=plt.cm.jet) cb = plt.colorbar(orientation='horizontal', pad=0.1, aspect=30) # draw colorbar cb.set_label('Intensity', fontsize=18) # plot data points. plt.scatter(x, y, marker='o', c='b', s=5) plt.scatter(x[z.index(max(z))], y[z.index(max(z))], marker='o', color="w", s=20) plt.xlabel('Mass ratio') plt.ylabel('Secondary Temperature (K)') ax1.set_xlabel(r'Mass ratio', fontsize=18) ax1.set_ylabel(r'Secondary Temperature (K)', fontsize=18) ax1.set_xlim(min(pasos), max(pasos)) ax1.set_ylim(min(temps), max(temps)) ax1.yaxis.set_major_locator(plt.MaxNLocator(6)) ax1.xaxis.set_major_locator(plt.MaxNLocator(8)) ax2.text(0.03, 0.96, "T=%s K" % y[z.index(max(z))], ha='left', va='top', transform=ax2.transAxes, fontsize=20) ax2.text(0.04, 0.5, "q=%s" % x[z.index(max(z))], ha='left', va='top', transform=ax2.transAxes, fontsize=20) #plot scale fig = plt.figure(figsize=(12, 9.0)) fig.subplots_adjust(hspace=0.4, bottom=0.06, top=0.94, left=0.12, right=0.94) ax2 = plt.subplot2grid((4, 1), (0, 0)) data = asciitable.read("tplsca.txt") #archivo de salida del scale #ax2.set_xlim(min(data["col1"]),max(data["col1"])) plt.plot(data["col1"], data["col2"], "-", color="red") data = asciitable.read("obscale.txt") plt.plot(data["col1"], data["col2"], "-", color="black") ax2.yaxis.set_major_locator(plt.MaxNLocator(5)) ax2.set_xlabel(r'Wavelength ($\AA$)', fontsize=18) ax2.set_ylabel(r'Intensity', fontsize=18) data = asciitable.read("scale.txt") #archivo de salida del scale ax2.set_xlim(min(data["col1"]), max(data["col1"]) - 1) plt.plot(data["col1"], data["col2"] * 100, "-", color="black") ax2.yaxis.set_major_locator(plt.MaxNLocator(5)) ax2.set_xlabel(r'Wavelength ($\AA$)', fontsize=18) ax2.set_ylabel(r'$I_2/I_T$ (%)', fontsize=18) #plt.savefig('mass_temp.pdf',format="pdf", bbox_inches='tight',dpi = 300) plt.show()
iraf.deredden( input = "fluxcal_" + file_name,\ output = redden_name,\ value = redden,\ R = 3.1,\ type = "E(B-V)",\ apertures = "*",\ override = 1,\ uncorrect = 0,\ mode = "al") ### Create .dat file out of fits file redden_name os.system("rm " + redden_name + ".dat") iraf.wspectext(redden_name + "[*,1,1]", redden_name + ".dat") spectrum = functions.read_ascii(redden_name + ".dat") spectrum = functions.read_table(spectrum) temp = [] for i in spectrum: if len(i) == 2: if functions.is_number(i[0]): temp.append(i) spectrum = temp spectrum = spectrum[1:len(spectrum)-2] output_spectrum = open(redden_name + ".dat","w") functions.write_table(spectrum,output_spectrum) output_spectrum.close()
def get_RV(WORK_DIR, multi_ref=False, multi_sample=False): # list RV ref files if multi_ref: rv_ref_list = glob.glob('../../*_Echelle_RVS.fits') rv_ref_list = [rf.split('/')[-1].split('.')[0] for rf in rv_ref_list] else: rv_ref_list = ['solar'] # rv_ref_list = ['solar_spectra_conv'] # print ' RV ref files list:', rv_ref_list for obj in observations[WORK_DIR]['objects']: for rv_ref in rv_ref_list: ts = time.time() rvs = [] e_rvs = [] # determine barycentric RV with open('RVS_'+obj+'_'+rv_ref+'.txt', 'w+') as file: for order in np.arange(2, 31, 1): try: iraf.wspectext(input=obj+'_vh_norm.fits[*,'+str(order)+',1]', output='template.txt', header='no') template = np.loadtxt('template.txt') wav = template[:, 0] mid1 = int(len(wav)/4.0) mid2 = int(len(wav)/12.0) wav1 = wav[mid1*1] wav2 = wav[mid1*3] #print 'WAV:', wav, mid1, wav1,wav2 # create multiple wav1, wav2 ranges if requested if multi_sample: wav_ranges = [[wav[mid2*2], wav[mid2*7]], [wav[mid2*4], wav[mid2*8]], [wav[mid2*5], wav[mid2*10]]] else: wav_ranges = [[wav1, wav2]] for wav_r in wav_ranges: iraf.unlearn('fxcor') try: os.remove('test.txt') os.remove('test.log') os.remove('test.gki') except: pass try: os.remove('template.txt') except: pass iraf.fxcor(obj+'.ec.vh', '../../'+rv_ref, apertures=order, pixcorr='no', continuum='both', osample='a %s %s' % (wav_r[0], wav_r[1]), rsample='a %s %s' % (wav_r[0], wav_r[1]), interactive='no', output='test', function = 'gaussian', apodize = 0.0, rebin = "smallest") fields = np.loadtxt('test.txt', comments='#', dtype='str') # print wav_r # print fields vrel, verr = fields[-3], fields[-1] # vrel, verr = fields[-3], 0. if vrel == 'INDEF' or np.float(verr) > 10. or np.abs(np.float(vrel)) > 350.: vrel = np.nan verr = np.nan print order, vrel, verr file.write("%s %s %s\n" % (order, vrel, verr)) rvs.append(float(vrel)) e_rvs.append(float(verr)) except: print_exception() # export all values in a list # file.write('\n') # file.write("'rv_echelle':[" + ','.join([str(v) for v in rvs]) + "]\n") # file.write("'e_rv_echelle':[" + ','.join([str(v) for v in e_rvs]) + "]\n") print '%s: RV median: %s, RV mean: %s, RV sigma: %s' % (obj, np.nanmedian(rvs), np.nanmean(rvs), np.nanstd(rvs)) print 'RV fit time: '+str((time.time()-ts)/60.)+' min' print ''
def iterate(): os.system("rm temp_norm.dat") iraf.wspectext( input = "temp_norm.fits",\ output = "temp_norm.dat",\ header = 0) data_spec = transpose(loadtxt("temp_norm.dat")) wave = arange(min(data_spec[0]),max(data_spec[0]),1) data_flux = interpolate.splrep(data_spec[0],data_spec[1]) data_flux = interpolate.splev(wave,data_flux) telluric_spec = transpose(loadtxt("telluric.dat")) telluric_flux = interpolate.splrep(telluric_spec[0],telluric_spec[1]) telluric_flux = interpolate.splev(wave,telluric_flux) ### Loop through telluric scaling telluric_scaling = [] rms_list = [] maxscale = 1.08 for scale in arange(0.0,maxscale,0.01): scatter_list = [] for region in telluric_region_list: temp_flux = [] temp_tel = [] for i in range(len(wave)): if wave[i] > region[0] and wave[i] < region[1]: temp_flux.append(data_flux[i]) temp_tel.append(telluric_flux[i]) if wave[i] > region[1]: break temp_flux = array(temp_flux) temp_tel = array(temp_tel) scatter = temp_flux / (temp_tel * scale + (1-scale)) # plt.plot(scatter) # plt.show() scatter_list.append(std(scatter)) telluric_scaling.append(scale) rms_list.append(average(scatter_list)) telluric_scaling,rms_list = array(telluric_scaling),array(rms_list) best_scale = find_min(telluric_scaling,rms_list) if best_scale > maxscale: best_scale = maxscale if best_scale < 0: best_scale = 0 print "scaling telluric by",best_scale # plt.plot(telluric_scaling,rms_list) # plt.show() os.system("cp telluric.fits telluric_temp.fits") iraf.sarith( input1 = "telluric_temp.fits",\ op = "*",\ input2 = best_scale,\ output = "telluric_temp.fits",\ w1 = "INDEF",\ w2 = "INDEF",\ apertures = "",\ bands = "",\ beams = "",\ apmodulus = 0,\ reverse = 0,\ ignoreaps = 1,\ format = "multispec",\ renumber = 0,\ offset = 0,\ clobber = 1,\ merge = 0,\ rebin = 0,\ verbose = 0) iraf.sarith( input1 = "telluric_temp.fits",\ op = "+",\ input2 = 1-best_scale,\ output = "telluric_temp.fits",\ w1 = "INDEF",\ w2 = "INDEF",\ apertures = "",\ bands = "",\ beams = "",\ apmodulus = 0,\ reverse = 0,\ ignoreaps = 1,\ format = "multispec",\ renumber = 0,\ offset = 0,\ clobber = 1,\ merge = 0,\ rebin = 0,\ verbose = 0) iraf.sarith( input1 = "temp_spec.fits",\ op = "/",\ input2 = "telluric_temp.fits",\ output = "temp_spec",\ w1 = "INDEF",\ w2 = "INDEF",\ apertures = "",\ bands = "",\ beams = "",\ apmodulus = 0,\ reverse = 0,\ ignoreaps = 1,\ format = "multispec",\ renumber = 0,\ offset = 0,\ clobber = 1,\ merge = 0,\ rebin = 0,\ verbose = 0) iraf.sarith( input1 = "temp_norm.fits",\ op = "/",\ input2 = "telluric_temp.fits",\ output = "temp_norm",\ w1 = "INDEF",\ w2 = "INDEF",\ apertures = "",\ bands = "",\ beams = "",\ apmodulus = 0,\ reverse = 0,\ ignoreaps = 1,\ format = "multispec",\ renumber = 0,\ offset = 0,\ clobber = 1,\ merge = 0,\ rebin = 0,\ verbose = 0) return best_scale
sens=sensfile, extinct='no', ignoreaps='yes' ) ## If extinct='yes', try extinction ='onedstds$ctioextinct.dat' print('\n' + 'Extracting the 1D spectra from the calibrated multispec file...') iraf.scopy('allspeccal[0]', 'allspeccal2', format='onedspec', w1=4000, w2=8000, rebin='no') print('\n' + '1D spectrum output...') iraf.wspectext('allspeccal2.0001', obj + '_' + date + '.txt', header='no') print('\n' + 'Tidying up...') a = glob.glob('./*') for f in a: if 'allspec' in f: os.remove(f) if apply_flux_correction != 'n': s = np.loadtxt('./ManualExtractionFluxCorrections.txt', unpack=True, usecols=(0, 1)) file_to_use = obj + '_' + date + '.txt' print('\n' + 'Using ' + file_to_use + ' as reference...')
low_reject = 1.5,\ high_reject = 4.0,\ niterate = 10,\ markrej = 1,\ graphics = "stdgraph",\ cursor = "",\ ask = "no",\ mode = "ql") ####################### ### Convert to .dat ### ####################### os.system("rm norm_" + file_name + ".dat") iraf.wspectext("norm_" + file_name +"[*,1,1]", "norm_" + file_name + ".dat") spectrum = functions.read_ascii("norm_" + file_name + ".dat") spectrum = functions.read_table(spectrum) temp = [] for i in spectrum: if len(i) == 2: if functions.is_number(i[0]): temp.append(i) spectrum = temp spectrum = spectrum[1:len(spectrum)-2] output_spectrum = open("norm_" + file_name + ".dat","w") functions.write_table(spectrum,output_spectrum) output_spectrum.close()
def salt_scombine(objlist): obj = np.loadtxt(objlist, dtype="str", unpack=True, ndmin=1) objlist1d = objlist + '1d' objj = os.path.splitext(obj[0])[0] if os.path.isfile(objj + 'wsf.fits'): os.system('sed s/.fits/wsf1d.fits/ ' + objlist + ' > ' + objlist1d) objnofits = string.split(obj[0], sep='.')[0] + 'wsf' os.system('sed s/.fits/wsf1d_var.fits/ ' + objlist + ' > templist') else: os.system('sed s/.fits/ws1d.fits/ ' + objlist + ' > ' + objlist1d) objnofits = string.split(obj[0], sep='.')[0] + 'ws' os.system('sed s/.fits/ws1d_var.fits/ ' + objlist + ' > templist') low_ap = float( rt.getsh("grep -i 'low\t' database/ap" + objnofits + " | awk '{print $3}'")) high_ap = float( rt.getsh("grep -i 'high\t' database/ap" + objnofits + " | awk '{print $3}'")) apradius = abs(low_ap) + abs(high_ap) readnoise = 2.45 * np.sqrt(apradius) print "ggg = %s" % readnoise iraf.scombine.combine = 'average' iraf.scombine.rdnoise = readnoise iraf.scombine.reject = 'ccdclip' iraf.scombine.scale = 'median' outnam = ''.join(rt.header(obj[0], 'OBJECT').split()).lower() outname = outnam + '_' + objlist if os.path.isfile(outname + '.fits'): os.system('rm ' + outname + '.fits') inname = str('@' + objlist1d) iraf.scombine(input=inname, output=outname, first='yes') tempfile = 'temp.fits' if os.path.isfile(tempfile): os.system('rm ' + tempfile) iraf.imsum('@templist', tempfile) nspec = len(obj) outname_var = outname + '_var' if os.path.isfile(outname_var + '.fits'): os.system('rm ' + outname_var + '.fits') nspec = nspec * nspec iraf.imarith(tempfile, '/', nspec, outname_var) os.system('rm *temp.fits') os.system('rm templist') iraf.dispcor(outname_var, output='', table=outname) outnametxt = outname + '.txt' outname_vartxt = outname_var + '.txt' iraf.wspectext(outname, outnametxt, header='no') iraf.wspectext(outname_var, outname_vartxt, header='no') rssdate = rt.header(obj[0], 'DATE-OBS') rssdate = string.replace(rssdate, '-', '') pastefinal = outname + '_final_' + rssdate + '.txt' os.system('paste ' + outnametxt + ' ' + outname_vartxt + ' > ' + pastefinal)
for ec in objects: source_fits1 = source_dir + ec + '.ec.fits' source_fits2 = source_dir + ec + '.ec.vh.fits' date_f = obs_key.split('_')[-1] if not os.path.isfile(source_fits1): print(ec + ' - no data (' + date_f + ')') continue if not os.path.isfile(source_fits2): print(ec + ' - no vh (' + date_f + ')') continue os.system('rm temp.txt') iraf.wspectext(input=source_fits2 + '[*,15,1]', output='temp.txt', header='no') s = np.loadtxt('temp.txt') wvl = s[:, 0] if wvl[1] - wvl[0] == 1: print(ec + ' - no wvl (' + date_f + ')') raise SystemExit obs_metadata = Table.read(data_dir + 'star_data_all.csv') obs_metadata = obs_metadata[obs_metadata['odkdaj'] == 'nova'] _go_to_dir('Binaries_spectra') copyfile(data_dir + 'star_data_all.csv', 'star_data_all.csv') for star in [
finalcomb.append(file) print('.') print('.') print('Combining frames...') print('.') print('.') file1 = open('listascombine', 'w') file1.writelines(["%s\n" % item for item in finalcomb]) file1.close() # iraf.scombine('@listascombine', 'temp_quick.fits') iraf.scopy('temp_quick.fits', target + '_quick.fits', w1='3800', w2='9000') iraf.wspectext(target + '_quick.fits', target + '_spec.txt', header='no') iraf.wspectext(target + '_quick.fits', target + '_spec.csv', header='no') #mv final file in a dedicated folder shutil.copy(target + '_quick.fits', './output/.') shutil.copy(target + '_spec.txt', './output/.') shutil.copy(target + '_spec.csv', './output/.') # #remove temp FILES os.remove('lapalmaextinct.dat') os.remove(target + '_spec.txt') os.remove(target + '_spec.csv') for file in os.listdir(os.getcwd()): if file.endswith('fits'): os.remove(file) elif file.startswith('lista'):
extinction='mk_extinct.txt', observatory='Keck', ignoreaps=yes, sensitivity='sensstar2.fits') inputname = ptfsn1f + ',' + ptfsn2f #Produce combined spectrum iraf.scombine(input=inputname, out='finalspectrum.ms', reject='avsigclip', scale='median', sample='5500:6500') l.write('calib=yes') iraf.splot(images='finalspectrum.ms.fits') iraf.wspectext(input='finalspectrum.ms.fits[*,1]', output=ptfsn1_name + '.ascii', header='NO') iraf.wspectext(input='ptfsn1.f.fits[*,1]', output=ptfsn1_name + '_r400.ascii', header='NO') iraf.wspectext(input='ptfsn2.f.fits[*,1]', output=ptfsn1_name + '_b600.ascii', header='NO') l.write('finalname=' + ptfsn1_name + '.ascii') l.close()
def remove_molecule(molecule,spec_name,outspec_name): telluric_region = eval("TELLURIC_REGION_"+molecule) telluric_region_list = string.split(telluric_region,",") for n in range(len(telluric_region_list)): region = telluric_region_list[n][1:] region = string.split(region,"-") temp = [] for i in region: temp.append(float(i)) telluric_region_list[n] = temp ### Copy telluric line spectra to working directory telluric_fits = grating + "_"+molecule+".fits" os.system("cp -f "+program_dir+"telluric_fits/" + telluric_fits + " telluric.fits") os.system("rm temp_norm*") os.system("rm temp_spec*") os.system("cp -f "+spec_name+" temp_spec.fits") iraf.continuum( input = spec_name,\ output = "temp_norm.fits",\ lines = "*",\ bands = "*",\ type = "ratio",\ replace = 0,\ wavescale = 1,\ logscale = 0,\ override = 1,\ listonly = 0,\ logfiles = "logfile",\ interactive = 0,\ sample = "*",\ naverage = 1,\ function = "spline3",\ order = 20,\ low_reject = 2.0,\ high_reject = 5.0,\ niterate = 5,\ grow = 2.0,\ ask = "yes") ################## ### Find shift ### ################## shift = run_fxcor("telluric.fits","temp_norm.fits",telluric_region) os.system("rm telluric.dat") iraf.dopcor( input = "telluric.fits",\ output = "telluric.fits",\ redshift = shift,\ isvelocity = 1,\ add = 1,\ dispersion = 1,\ flux = 0,\ verbose = 0) iraf.wspectext( input = "telluric.fits",\ output = "telluric.dat",\ header = 0) ###################################### ### Iterative telluric subtraction ### ###################################### def iterate(): os.system("rm temp_norm.dat") iraf.wspectext( input = "temp_norm.fits",\ output = "temp_norm.dat",\ header = 0) data_spec = transpose(loadtxt("temp_norm.dat")) wave = arange(min(data_spec[0]),max(data_spec[0]),1) data_flux = interpolate.splrep(data_spec[0],data_spec[1]) data_flux = interpolate.splev(wave,data_flux) telluric_spec = transpose(loadtxt("telluric.dat")) telluric_flux = interpolate.splrep(telluric_spec[0],telluric_spec[1]) telluric_flux = interpolate.splev(wave,telluric_flux) ### Loop through telluric scaling telluric_scaling = [] rms_list = [] maxscale = 1.08 for scale in arange(0.0,maxscale,0.01): scatter_list = [] for region in telluric_region_list: temp_flux = [] temp_tel = [] for i in range(len(wave)): if wave[i] > region[0] and wave[i] < region[1]: temp_flux.append(data_flux[i]) temp_tel.append(telluric_flux[i]) if wave[i] > region[1]: break temp_flux = array(temp_flux) temp_tel = array(temp_tel) scatter = temp_flux / (temp_tel * scale + (1-scale)) # plt.plot(scatter) # plt.show() scatter_list.append(std(scatter)) telluric_scaling.append(scale) rms_list.append(average(scatter_list)) telluric_scaling,rms_list = array(telluric_scaling),array(rms_list) best_scale = find_min(telluric_scaling,rms_list) if best_scale > maxscale: best_scale = maxscale if best_scale < 0: best_scale = 0 print "scaling telluric by",best_scale # plt.plot(telluric_scaling,rms_list) # plt.show() os.system("cp telluric.fits telluric_temp.fits") iraf.sarith( input1 = "telluric_temp.fits",\ op = "*",\ input2 = best_scale,\ output = "telluric_temp.fits",\ w1 = "INDEF",\ w2 = "INDEF",\ apertures = "",\ bands = "",\ beams = "",\ apmodulus = 0,\ reverse = 0,\ ignoreaps = 1,\ format = "multispec",\ renumber = 0,\ offset = 0,\ clobber = 1,\ merge = 0,\ rebin = 0,\ verbose = 0) iraf.sarith( input1 = "telluric_temp.fits",\ op = "+",\ input2 = 1-best_scale,\ output = "telluric_temp.fits",\ w1 = "INDEF",\ w2 = "INDEF",\ apertures = "",\ bands = "",\ beams = "",\ apmodulus = 0,\ reverse = 0,\ ignoreaps = 1,\ format = "multispec",\ renumber = 0,\ offset = 0,\ clobber = 1,\ merge = 0,\ rebin = 0,\ verbose = 0) iraf.sarith( input1 = "temp_spec.fits",\ op = "/",\ input2 = "telluric_temp.fits",\ output = "temp_spec",\ w1 = "INDEF",\ w2 = "INDEF",\ apertures = "",\ bands = "",\ beams = "",\ apmodulus = 0,\ reverse = 0,\ ignoreaps = 1,\ format = "multispec",\ renumber = 0,\ offset = 0,\ clobber = 1,\ merge = 0,\ rebin = 0,\ verbose = 0) iraf.sarith( input1 = "temp_norm.fits",\ op = "/",\ input2 = "telluric_temp.fits",\ output = "temp_norm",\ w1 = "INDEF",\ w2 = "INDEF",\ apertures = "",\ bands = "",\ beams = "",\ apmodulus = 0,\ reverse = 0,\ ignoreaps = 1,\ format = "multispec",\ renumber = 0,\ offset = 0,\ clobber = 1,\ merge = 0,\ rebin = 0,\ verbose = 0) return best_scale best_scaling = 1.0 while best_scaling > 0.05: best_scaling = iterate() os.system("cp temp_spec.fits "+outspec_name)