Example #1
0
    def readspectext(self, InputFile, OutputFile, Fits_Folder, conf_dict = None, Suffix = ''):
        
        if OutputFile == None:
            OutputFile = self.outputNameGenerator(InputFile, Suffix)    

        self.deleteIrafFiles(Fits_Folder + OutputFile)
        
        conf_dict = self.rspectextAttributes(InputFile, OutputFile, Fits_Folder)

        #Display the equivalent command in IRAF
        Command = self.printIrafCommand('rspectext', conf_dict)
        print '--Using command'
        print Command

        iraf.rspectext(**conf_dict)
        
        return
Example #2
0
def extract(image,trace,sigma,bk):

    if sigma < 1.:
        sigma = 1.

    #sigma = sigma*2
    #print sigma,"sigma"

    original_file = pyfits.open(image)
    original_header = iraf.imheader(images=image,longheader=1,Stdout=1)

    image = pyfits.getdata(image)
    image = transpose(image)

    line = []
    peak = []

    step = 200

    i = 0
    while i < len(image):
        crop = image[i]

        bk_i = []
        signal_i = []

        ### uncomment this to see where the extraction is taking place

        # plt.plot(crop)
        # plt.axvline(x=trace[i])
        # plt.show()

        x = arange(0,len(crop)+0.1-1,0.1)
        y = interpolate.interp1d(arange(0,len(crop)),crop)
        y = y(x)
        weights = []

        for j in range(len(x)):
            for n in bk:
                if x[j] > n[0] and x[j] < n[1]:
                    bk_i.append(y[j])
            
            if x[j] > trace[i] - sigma and x[j] < trace[i] + sigma:
                signal_i.append(y[j])

                weights.append(gaussian([1,trace[i],sigma,0],x[j]))

        if len(bk_i) > 0:
            bk_i = median(bk_i)
        else:
            bk_i = 0

        if len(signal_i) > 0:
            pass
        else:
            signal_i = [0]
            weights = [1]

        signal_i = array(signal_i)
        weights = array(weights)

        line.append(i+1)
        peak.append(sum(signal_i)-bk_i*len(signal_i))
        #peak.append(sum(signal_i*weights)-sum(bk_i*weights))

        i = i + 1    

    ### Uncomment to plot spectrum
    # plt.clf()
    # plt.plot(line,peak)
    # plt.show()

    data = transpose(array([line,peak]))
    f = open("spectrum.flux","w")
    functions.write_table(data,f)
    f.close()

    os.system("rm spectrum.fits")
    iraf.rspectext(
        input = "spectrum.flux",\
        output = "spectrum.fits",\
        title = "",\
        flux = 0,\
        dtype = "interp")
    
    update_fitsheader(original_header,original_file,"spectrum.fits")
    original_file.close()
Example #3
0
else:
# leave things in vacuum wavelengths
   AIR = wl
   newf = f
   bfmod = model[:-4]+'.bf.apogee.txt'

# Various outfiles, some of which will be deleted at the end
textcont = model[:-4]+'_short.txt'
fitscont = model[:-4]+'_short.fits'
fitsnocont = model[:-4]+'_nocont.fits'
convtext = model[:-4]+'.cnv'
convout = model[:-4]+'.cnv.out'

# Continuum fit the spectrum so we can use IRAF's continuum function to remove it
np.savetxt(textcont, np.array([AIR,newf]).transpose())
iraf.rspectext(input=textcont, output=fitscont, flux='No', dtype='interp')
print('iraf rspectext complete')
iraf.continuum(input=fitscont, output=fitsnocont, lines='*',
               type='ratio', replace=no, wavescale=yes, logscale=no,
               listonly=no, interactive=no, sample='*',
               naverage=-25, function='spline3', order=5, niterate=10,
               low_reject=1.5, high_reject=5.0, markrej=no, grow=0,
               override=yes)
print('iraf continuum complete')
print('friendly untouched by convspec FITS saved {0}'.format(fitsnocont))

# Create a text file correctly formatted for convspec
wave, data = read_fits(fitsnocont)
np.savetxt(convtext, np.array([wave, np.zeros(len(wave)), data]).transpose())

# Run convspec, the fortran code
#!/usr/bin/env python

from astropy.io import fits
from pyraf import iraf
import os
import sys

#filename = 'spec-0266-51602-0051.fits'
filename = sys.argv[1]

#import fits
ob = fits.open(filename)
#Get data and save wavelenft in x, and flux on y
dataob = ob[1].data
x = 10**(dataob['loglam'])
y = dataob['model']

#save to a .txt file
namenewfits = '{name}.txt'.format(name=filename.split('.')[0])
with open(namenewfits, 'w') as file:
    for i in zip(x, y):
        file.write('{}\t{}\n'.format(i[0], i[1]))
#Create fits file from text file interpolation.
iraffitsname = 'iraf' + filename.split('.')[0]
if os.path.exists(iraffitsname + '.fits'):
    os.remove(iraffitsname + '.fits')

iraf.noao.onedspec()
iraf.dataio()
iraf.rspectext(namenewfits, iraffitsname, dtype='interp')
Example #5
0
    def find_shift(input1,input2,i1,i2,shift_range):
        if abs(i2 - i1) < 300:
            i1 = i1 - 150
            i2 = i2 + 150

        if i1 < 0:
            i1 = 0
            i2 = 300
        if i2 > len(input1):
            i2 = len(input1)
            i1 = len(input1) - 300
            
        ### Use xcorr
        currdir = os.getcwd()
        os.chdir(file_path_reduced)
        os.system("rm "+file_path_reduced+"shift_spec*")
        input1_cropped = input1[i1:i2]/median(input1[i1:i2])
        input2_cropped = input2[i1:i2]/median(input1[i1:i2])
        wave_axis = arange(1,len(input1_cropped)+1)
        
        shift_spec1 = open(file_path_reduced+"shift_spec1.txt","w")
        functions.write_table(transpose([wave_axis,input1_cropped]),shift_spec1)
        shift_spec1.close()

        shift_spec2 = open(file_path_reduced+"shift_spec2.txt","w")
        functions.write_table(transpose([wave_axis,input2_cropped]),shift_spec2)
        shift_spec2.close()
        
        iraf.rspectext(
            input = file_path_reduced+"shift_spec1.txt",\
            output = file_path_reduced+"shift_spec1.fits",\
            title = "shift_spec1",\
            flux = 0,\
            dtype = "interp",\
            crval1 = "",\
            cdelt1 = "",\
            fd1 = "",\
            fd2 = "")

        iraf.rspectext(
            input = file_path_reduced+"shift_spec2.txt",\
            output = file_path_reduced+"shift_spec2.fits",\
            title = "shift_spec2",\
            flux = 0,\
            dtype = "interp",\
            crval1 = "",\
            cdelt1 = "",\
            fd1 = "",\
            fd2 = "")

        time.sleep(0.5) 
            
        ### Find shift
        os.system("rm apshift*")

        ### Makesure keywpars is set at default
        iraf.unlearn(iraf.keywpars)

        cuton = len(input1_cropped)/25.
        cutoff = len(input1_cropped)/2.5

        iraf.filtpars.setParam("f_type","welch",check=1,exact=1)
        iraf.filtpars.setParam("cuton",cuton,check=1,exact=1)
        iraf.filtpars.setParam("cutoff",cutoff,check=1,exact=1)

        run_fxcor(file_path_reduced+"shift_spec1.fits",file_path_reduced+"shift_spec2.fits","*","apshift",0,10,"gaussian","INDEF",0)
        vel_shift = functions.read_ascii("apshift.txt")
        vel_shift = functions.read_table(vel_shift)
        vel_shift = vel_shift[0][6]
        if vel_shift == "INDEF":
            vel_shift = 0.0
        if abs(vel_shift) > shift_range:
            vel_shift = 0.0

        print "best pixel shift of ",vel_shift

        os.system("rm apshift*")
        os.system("rm "+file_path_reduced+"shift_spec*")
        os.chdir(currdir)
        
        #if i1 < shift_range:
        #    i1 = shift_range
        #if i2 > len(input1)-shift_range:
        #    i2 = len(input1)-shift_range

        # shift_rms = []
        # shift_list = []
        # for shift in range(-1*shift_range,shift_range+1):
        #     input1_cropped = input1[i1+shift:i2+shift]
        #     input2_cropped = input2[i1:i2]

        #     diff = input1_cropped/median(input1_cropped) * input2_cropped/median(input2_cropped)
        #     rms = sum(diff)
        #     #rms = sqrt(sum(diff**2) /float(len(diff)))
        #     shift_rms.append(rms)
        #     shift_list.append(shift)
            
        # for i in range(len(shift_rms)):
        #     if shift_rms[i] == max(shift_rms):
        #         break
        
        # print "Applying a shift of ",shift_list[i]
        # plt.clf()
        # plt.plot(input1[i1+shift_list[i]:i2+shift_list[i]]/median(input1[i1+shift_list[i]:i2+shift_list[i]]),"b-")
        # plt.plot(input1[i1:i2]/median(input1[i1:i2]),"r-")
        # plt.plot(input2[i1:i2]/median(input2[i1:i2]),"g-")
        # plt.show()

        # return shift_list[i]
        return int(round(vel_shift,0))