Example #1
0
def set_sname(fn):
    """
    set a new keyword 'SNAME' to fits fn,
    the value is standard name of the source.
    the SNAME value depend on the 'OBJECT' keyword.
    fn : fits name
    type : string
    """
    standname = sname(fn)
    size = len(pyfits.open(fn))
    if size == 1:
        iraf.hedit(images=fn,
                   fields='SNAME',
                   value=standname,
                   add='Yes',
                   addonly='No',
                   delete='No',
                   verify='No',
                   show='Yes',
                   update='Yes')
    else:
        for i in range(len(size)):
            iraf.hedit(images=fn + '[%d]' % i,
                       fields='SNAME',
                       value=standname,
                       add='Yes',
                       addonly='No',
                       delete='No',
                       verify='No',
                       show='Yes',
                       update='Yes')
Example #2
0
def time_calibration(input_file):
    """
    Obtain the calibration for time (hjd) by pyraf and the airmass for each image. Include in the header all information.
    """
    original_path = os.getcwd()
    save_path = input_file['save_path']
    #change to save data reduction directory
    os.chdir(save_path)
    print '\n Reading the list of images ....\n'
    planet = input_file['exoplanet'] #set exoplanet name
    images = sorted(glob.glob('AB'+planet+'*.fits'))
    print images
    #include de RA,DEC and epoch of the exoplanet
    RA,DEC,epoch = input_file['RA'],input_file['DEC'],input_file['epoch']
    #obtain ST JD using iraf task and introduce in the header
    for i in range(len(images)):
        hdr = fits.getheader(images[i])
        if int(split(hdr['UT'],':')[0]) < int(hdr['timezone']):
            new_date = use.yesterday(hdr['date-obs'])
            #print images[i], new_date
        else:
            new_date = hdr['date-obs']
        year,month,day = split(new_date,'-')
        iraf.asttimes(year=year,month=month,day=day,time=hdr['loctime'],obs=input_file['observatory'])
        JD = iraf.asttimes.jd #obtain julian date
        LMST = iraf.asttimes.lmst #obtain the sideral time
        LMST = use.sexagesimal_format(LMST) #convert sideral time in sexagesimal format
        iraf.hedit(images[i],'ST',LMST,add='yes',verify='no',show='no',update='yes') #create the ST keyword in the header
        iraf.ccdhedit(images[i],'LMST',LMST,type='string') #include the mean sideral time in the header
        iraf.ccdhedit(images[i],'JD',JD,type='string') #include de julian date in the header
        #include RA, and DEC of the object in your header
        iraf.ccdhedit(images[i],"RA",RA,type="string") #include right ascention in the header
        iraf.ccdhedit(images[i],"DEC",DEC,type="string")  #include declination in the header
        iraf.ccdhedit(images[i],"epoch",epoch,type="string") #include epoch in the header
        # use.update_progress((i+1.)/len(images))
    print '\n Setting airmass ....\n'
    for i in range(len(images)):
        print '# ',images[i]
        #iraf.hedit(images[i],'airmass',airmass,add='yes')
        #iraf.hedit(images[i],'HJD',HJD,add='yes')
        iraf.setairmass.observatory = input_file['observatory']
        iraf.setairmass(images[i])
        iraf.setjd.time = 'ut'
        iraf.setjd(images[i])
    print '\n.... done.\n'
    #export information
    hjd, jd, airmass, st = [],[],[],[]
    for i in range(len(images)):
        hdr = fits.getheader(images[i])
        hjd.append(hdr['HJD'])
        jd.append(hdr['JD'])
        airmass.append(hdr['airmass'])
        st.append(hdr['st'])
    #saving the data
    data = DataFrame([list(hjd),list(jd),list(st),list(airmass)]).T
    data.columns = ['HJD','JD','ST','Airmass']
    data.to_csv('results_iraf_calibrations.csv')
    #change to workings directory
    os.chdir(original_path)
    return
Example #3
0
def clean_FLXCORR(file, N=16):

    from pyraf import iraf
    from pyfits import getheader

    print("Analizing %s ..." % file)
    header = getheader(file, 1)

    try:
        FLXCORR = header['FLXCORR']
        print("Cleaning up %s" % file)
        for i in range(N):
            n = i + 1
            image = "%s[%s]" % (file, n)
            iraf.hedit(image,
                       'FLXCORR',
                       delete='yes',
                       verify='no',
                       update='yes',
                       show='yes')
            # Remove key from [0] extension
            #print image
    except:
        print("NO FLXCORR key found")

    return
Example #4
0
def MEFarithOLD(MEF, image, out, op, result):

    if os.path.exists(out + '.fits'):
        os.remove(out + '.fits')
    for i in range(1, 88):
        header = pyfits.open(MEF + '.fits')
        extname = header[i].header['EXTNAME']
        if extname == 'DQ' or extname == 'VAR':
            iraf.imarith(operand1=MEF + '[' + str(i) + ']',
                         op='*',
                         operand2='1',
                         result=out)
        if extname == 'SCI':
            iraf.imarith(operand1=MEF + '[' + str(i) + ']',
                         op=op,
                         operand2=image,
                         result=out,
                         divzero=0.0)

    iraf.fxcopy(input=MEF + '[0],' + out, output=result)
    iraf.hedit(result + '[1]',
               field='EXTNAME',
               value='SCI',
               add='yes',
               verify='no')
    iraf.hedit(result + '[1]',
               field='EXTVER',
               value='1',
               add='yes',
               verify='no')
Example #5
0
 def omitPhotcorr(self, file):
     """
     This function will change PHOTCORR keyword value to OMIT in the header
     of given file. The file can contain wildcards i.e. multiple files can
     be given on one command..
     """
     I.hedit(file, fields='PHOTCORR', value='omit', verify='no', show='no')
Example #6
0
def get_jd(fn):
    try:
        val = pyfits.getval(fn, 'JD')
        return val
    except KeyError:
        from pyraf import iraf
        iraf.hedit(images=fn,
                   fields='OBSERVAT',
                   value='ca',
                   add='Yes',
                   addonly='Yes',
                   delete='No',
                   verify='No',
                   show='Yes',
                   update='Yes')
        iraf.setjd(images=fn,
                   observatory='ca',
                   date='date-obs',
                   time='date-obs',
                   exposure='exptime',
                   ra='ra',
                   dec='dec',
                   epoch='EQUINOX',
                   utdate='Yes',
                   uttime='Yes')
        val = pyfits.getval(fn, 'JD')
        return val
Example #7
0
def ExpNormalize(images, outbase="_en"):
			
	# Build the list of output image names
	out = [os.path.splitext(i) for i in images]	# Split off the extension
	out = [i[0] + outbase + '.fits' for i in out]	# Paste the outbase at the end of the filename 
												# and put the extension back on
	# Get a list of exposure times.
	exp_times = [GetHeaderKeyword(i, 'exptime') for i in images]
	exp_times = [str(e) for e in exp_times]	
	
	# run imarith to do the normalization
	iraf.imarith.unlearn()
	iraf.imarith.op = '/'
	iraf.imarith.mode = 'h'

	for i in range(len(images)):
		iraf.imarith.operand1 = images[i]
		iraf.imarith.operand2 = exp_times[i]
		iraf.imarith.result = out[i]
	
		iraf.imarith()

		# update the exptime keyword		
		iraf.hedit.unlearn()
		iraf.hedit.verify='no'
		iraf.hedit.show='yes'
		iraf.hedit.update='yes'
		iraf.hedit.images=out[i]
		iraf.hedit.fields='exptime'
		iraf.hedit.value=1
		iraf.hedit.mode='h'

		iraf.hedit(Stdout=1)

	return out
Example #8
0
def cos_clear2(filenames):
    outname = 'fake_' + filenames[0]
    if os.path.isfile(outname):
        print outname, 'is already exist'
    else:
        inname = filenames[0] + ',' + filenames[1]
        print 'runing cos_clear2, imcombine...'
        print 'make file', outname
        iraf.imcombine(input = inname
                , output = outname, headers = '', bpmasks = ''
                , rejmasks = '', nrejmasks = '', expmasks = ''
                , sigmas = '', imcmb = '$I', logfile = 'STDOUT'
                , combine = 'average', reject = 'minmax', project = False
                , outtype = 'real', outlimits = 'none', offsets = 'none'
                , masktype = 'none', maskvalue = 0, blank = 0.0
                , scale = 'exposure', zero = 'none', weight = 'none'
                , statsec = '', expname = 'EXPTIME', lthreshold = 'INDEF'
                , hthreshold = 'INDEF', nlow = 0, nhigh = 1
                , nkeep = 1, mclip = True, lsigma = 3.0
                , hsigma = 10.0, rdnoise = 'RDNOISE', gain = 'GAIN'
                , snoise = 0.0, sigscale = 0.1, pclip = -0.5, grow = 0.0)
        iraf.hedit(images = outname
                , fields = 'ncombine', value = '0', add = True
                , addonly = False, delete = False, verify = False
                , show = True, update = True)
        iraf.hedit(images = outname
                , fields = 'EXPTIME', value = '0', add = True
                , addonly = False, delete = False, verify = False
                , show = True, update = True)
    print 'display %s 1' % outname
    iraf.display(image = outname, frame = 1)
    filenames.append(outname)
    return cos_clear3(filenames)
Example #9
0
 def omitPhotcorr(self, file):
     """
     This function will change PHOTCORR keyword value to OMIT in the header
     of given file. The file can contain wildcards i.e. multiple files can
     be given on one command..
     """
     I.hedit(file, fields='PHOTCORR', value='omit', verify='no', show='no')
def ExpNormalize(images, outbase="_n"):
			
	# Build the list of output image names
	out = [os.path.splitext(i) for i in images]	# Split off the extension
	out = [i[0] + outbase + '.fits' for i in out]	# Paste the outbase at the end of the filename 
												# and put the extension back on
	# Get a list of exposure times.
	exp_times = [GetHeaderKeyword(i, 'exptime') for i in images]
	exp_times = [str(e) for e in exp_times]	
	
	# run imarith to do the normalization
	iraf.imarith.unlearn()
	iraf.imarith.op = '/'
	iraf.imarith.mode = 'h'

	for i in range(len(images)):
		iraf.imarith.operand1 = images[i]
		iraf.imarith.operand2 = exp_times[i]
		iraf.imarith.result = out[i]
	
		iraf.imarith()

		# update the exptime keyword		
		iraf.hedit.unlearn()
		iraf.hedit.verify='no'
		iraf.hedit.show='yes'
		iraf.hedit.update='yes'
		iraf.hedit.images=out[i]
		iraf.hedit.fields='exptime'
		iraf.hedit.value=1
		iraf.hedit.mode='h'

		iraf.hedit(Stdout=1)

	return out
Example #11
0
def add_DISPAXIS(filelst):
    iraf.hedit(images='@' + filelst + '[0]',
               fields='DISPAXIS',
               value='2',
               addonly='Yes',
               verify='No',
               show='Yes',
               update='Yes')
Example #12
0
def main():
    parser = argparse.ArgumentParser(description='Fixes BITPIX issue with archive data')
    parser.add_argument('filelist',nargs='+',help='Input images to process')

    args = parser.parse_args()

    for image in args.filelist:
        iraf.hedit(images=image,fields='BITPIX',value=32,update=True,show=True,addonly=True)
Example #13
0
def putheader(images, param, value):
    iraf.hedit(images,
               fields=param,
               value=value,
               add='yes',
               addonly='yes',
               verify='no',
               show='yes')
Example #14
0
 def hedit(inim, kword, value):
     iraf.hedit.images = inim
     iraf.hedit.fields = kword
     iraf.hedit.value = value
     iraf.hedit.add = 'yes'
     iraf.hedit.verify = 'no'
     iraf.hedit.update = 'yes'
     iraf.hedit.mode = 'h'
     iraf.hedit()
Example #15
0
    def test_hedit(self):
        if os.path.exists('image.real.fits'):
            os.remove('image.real.fits')

        iraf.imarith('dev$pix', '/', '1', 'image.real', pixtype='r')
        iraf.hedit('image.real', 'title', 'm51 real', verify=False,
                   Stdout="/dev/null")
        with fits.open('image.real.fits') as f:
            assert f[0].header['OBJECT'] == 'm51 real'
Example #16
0
    def omitPHOTCORR(self):
        """
        Sets PHOTCORR keyword to OMIT to prevent crashing.

        :note: find a proper fix for this.
        :note: Change from iraf to pyfits.
        """
        for raw in glob.glob('*_raw.fits'):
            iraf.hedit(images=raw + '[0]', fields='PHOTCORR', value='OMIT',
                       add=self.no, addonly=self.no, delete=self.no,
                       verify=self.no, show=self.yes, update=self.yes)
Example #17
0
def append_VHELIO(image_file,v_value): #Note v_value must be string!
    iraf.hedit(
        images = image_file,\
        fields = "VHELIO",\
        value = v_value,\
        add = 1,\
        addonly = 0,\
        delete = 0,\
        verify = 0,\
        show = 1,\
        update = 1)
Example #18
0
def hedit(images, fields, value):  # edits header of files
    '''
    Edits header of files.
    '''
    iraf.hedit(images=images,
               fields=fields,
               value=value,
               add='yes',
               update='yes',
               ver='no',
               show='no')
Example #19
0
    def test_hedit(self):
        if os.path.exists('image.real.fits'):
            os.remove('image.real.fits')

        iraf.imarith('dev$pix', '/', '1', 'image.real', pixtype='r')
        iraf.hedit('image.real',
                   'title',
                   'm51 real',
                   verify=False,
                   Stdout="/dev/null")
        with fits.open('image.real.fits') as f:
            assert f[0].header['OBJECT'] == 'm51 real'
Example #20
0
def extractComps(assignments, dorefspec=1):
    '''This task takes a dictionary 'assignments' which has keywords equal
      to the objects spectrum and value equal to the comparison spectrum
      which should be used for the object spectrum.  You could use 
      closest_time_pos() to figure this out, for example.  The apertures
      of each comp are then extracted using apall and the object's spectrum
      as a reference.  Finally, the object's headers are updated using
      the REFSPEC1 keyword (unless dorefspec=0).'''
    iraf.noao()
    iraf.imred()
    iraf.echelle()
    # First things first, we save the old paramter list.
    iraf.apall.saveParList(filename='temp.apall.par')

    # iraf.apall.unlearn()
    iraf.apall.format = 'echelle'

    # now, get the associated list of references and comps:
    stuff = assignments

    for ref in stuff.keys():
        print 'extracting %s using %s as reference' % (stuff[ref], ref)
        comp = stuff[ref]
        if iraf.imaccess(re.sub('\.fits', '.ec.fits', comp)):
            print 'Extracted comparison exists, skipping...'
        else:
            iraf.apall(input=comp,
                       references=re.sub('\.ec', '', ref),
                       interactive=0,
                       find=0,
                       recenter=0,
                       resize=0,
                       edit=0,
                       trace=0,
                       fittrace=0,
                       extract=1,
                       extras=0,
                       review=0)

        # Now, since we've used them to extract the spectra, we can assign
        # them using refspec:
        # print "now assigning reference spectrum"
        if dorefspec:
            iraf.hedit(images=ref,
                       fields='REFSPEC1',
                       value=re.sub('\.fits', '.ec', comp),
                       add=1,
                       addonly=1,
                       verify=0,
                       show=1)

    iraf.apall.setParList(ParList='temp.apall.par')
Example #21
0
def wavelength_calibration(targetdir):

    """
    Does wavelength calibration.

    Writes every fit to database so make sure it's using the correct one.

    This needs to be run in object directory for database

    """

    print 'Target directory is ' + targetdir
    print 'Doing wavelength calibration...'

    if os.getcwd() != targetdir:

        print 'Warning: current working directory must be target directory!'

        return None

    iraf.noao(_doprint=0)
    iraf.onedspec(_doprint=0)

    iraf.unlearn('identify')

    iraf.identify.setParam('images','aimcomb.fits')
    iraf.identify.setParam('coordli','/home/lc585/Dropbox/IoA/WHT_Proposal_2015a/argon+xenon.dat')
    iraf.identify.setParam('niterat',1)
    iraf.identify.setParam('function','spline3')
    iraf.identify.setParam('order',3)
    iraf.identify.setParam('zwidth',200.0) #  Zoom graph width in user units
    iraf.identify.setParam('database','database')

    iraf.identify()

    # Update fits header

    print '\n' '\n' '\n'
    print 'Updating fits header...'

    iraf.hedit.setParam('images','imcomb.ms.fits')
    iraf.hedit.setParam('fields','REFSPEC1')
    iraf.hedit.setParam('value','aimcomb.fits') # should be wavelength calibrated?
    iraf.hedit.setParam('add','yes')
    iraf.hedit.setParam('verify','yes')
    iraf.hedit.setParam('show','yes')

    iraf.hedit()

    return None
Example #22
0
def quartz_divide(science_list,object_match):
    '''Divides science frames by user-selected quartz frames'''
    for obj in science_list:
        if len(object_match[obj]) > 1:
            qtzinpt = ''
            for qtz in object_match[obj]:
                qtzinpt += qtz +','
            iraf.imcombine(input=qtzinpt,output='tempquartz')
            iraf.imarith(operand1=obj,operand2='tempquartz',op='/',result='f'+obj)
            heditstr = 'Flat field images are '+qtzinpt[:-1]
            iraf.imdelete(images='tempquartz',go_ahead='yes',verify='no')
            if len(heditstr) > 65:
                nfields = int(len(heditstr)/65) #Declare int for py3 compatibility
                for ii in range(nfields+1):
                    writestr = heditstr[(ii*65):(ii+1)*65]
                    iraf.hedit(images='f'+obj,fields='flatcor'+str(ii),value=writestr,add='yes',verify='No')
            else:
                iraf.hedit(images='f'+obj,fields='flatcor',value=heditstr,add='yes',verify='No')
        else:
            iraf.imarith(operand1=obj,operand2=object_match[obj][0],op='/',result='f'+obj)
            heditstr = 'Flat field image is '+object_match[obj][0]
            if len(heditstr) > 65:
                nfields = int(len(heditstr)/65) #Declare int for py3 compatibility
                for ii in range(nfields+1):
                    writestr = heditstr[(ii*65):(ii+1)*65]
                    iraf.hedit(images='f'+obj,fields='flatcor'+str(ii),value=writestr,add='yes',verify='No')
            else:
                iraf.hedit(images='f'+obj,fields='flatcor',value=heditstr,add='yes',verify='No')
    return
def vhelio_correct(WORK_DIR):
  print '\n + VHELIO correction\n'
    
  for obj in observations[WORK_DIR]['objects']:
    obj = obj+'.ec'

    utm = iraf.hselect(images=obj, fields='UTMIDDLE', Stdout=1, expr='yes')
    year = utm[0][:4]
    month = utm[0][5:7]
    day = utm[0][8:10]
    h = int(utm[0][11:13])
    m = int(utm[0][14:16])
    s = int(utm[0][17:19])

    ra = iraf.hselect(images=obj, fields='RA', Stdout=1, expr='yes')[0].split(':')
    dec = iraf.hselect(images=obj, fields='DEC', Stdout=1, expr='yes')[0].split(':')
    ra = float(ra[0])+int(ra[1])/60.+float(ra[2])/3600.
    dec = float(dec[0])+int(dec[1])/60.+float(dec[2])/3600.
    
    shutil.copy(obj+'.fits', obj+'.vh.fits')
    iraf.hedit(images=obj+'.vh', fields='UT', value=h+m/60.+s/3600., add='yes', verify='no')
    iraf.hedit(images=obj+'.vh', fields='EPOCH', value=year, add='yes', verify='no')
    iraf.rvcorrect(images=obj+'.vh', imupdat='yes', epoch=year, observa='ekar', year=year, month=month, day=day, ut=h+m/60.+s/3600., ra=ra, dec=dec)
    iraf.dopcor(input=obj+'.vh', redshift='-vhelio', isveloc='yes', dispers='yes')

    obj = obj+'.nosky'
    shutil.copy(obj+'.fits', obj+'.vh.fits')
    iraf.hedit(images=obj+'.vh', fields='UT', value=h+m/60.+s/3600., add='yes', verify='no')
    iraf.hedit(images=obj+'.vh', fields='EPOCH', value=year, add='yes', verify='no')
    iraf.rvcorrect(images=obj+'.vh', imupdat='yes', epoch=year, observa='ekar', year=year, month=month, day=day, ut=h+m/60.+s/3600., ra=ra, dec=dec)
    iraf.dopcor(input=obj+'.vh', redshift='-vhelio', isveloc='yes', dispers='yes')
Example #24
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)
Example #25
0
def main():
    print('FLAG 1================')
    checkfilepath = os.path.split(os.path.abspath(__file__))[0] + os.sep + 'objcheck.lst'
    dct = filedict(checkfilepath)
    fitlst = findmarkfit(os.getcwd())
    for fitname in fitlst:
        print(fitname)
    for fitname in fitlst:
        fit = pyfits.open(fitname)
        oldsname = fit[0].header['sname']
        newsname = dct[str(oldsname)]
        iraf.hedit(images = fitname, fields = 'sname',
                value = newsname, add = 'yes', delete = 'no',
                verify = 'no', show = 'yes', update = 'yes')
Example #26
0
def set_airmass(fn):

    fit = pyfits.open(fn)
    size = len(fit)
    for i, hdu in enumerate(fit):
        if 'AIRMASS' in hdu.header:
            airmassold = hdu.header['AIRMASS']
            print('%s[%d] airmassold = %f' % (fn, i, airmassold), )
            if 'AIROLD' in hdu.header:
                airold = hdu.header['AIROLD']
                print('%s[%d] AIROLD = %f' % (fn, i, airold))
                print(
                    'AIROLD keyword alreay exist, the airmass old will not saved'
                )
            else:
                iraf.hedit(images=fn + '[%d]' % i,
                           fields='AIROLD',
                           value=airmassold,
                           add='Yes',
                           addonly='Yes',
                           delete='No',
                           verify='No',
                           show='Yes',
                           update='Yes')
    fit.close()
    ra, dec = get_ra_dec(fn)
    set_ra_dec(fn, ra, dec)

    iraf.twodspec()
    iraf.longslit(dispaxis=2, nsum=1, observatory='ca', caldir=stdpath)

    for i in range(size):
        iraf.setairmass(images=fn,
                        observatory='ca',
                        intype='beginning',
                        outtype='effective',
                        ra='ra',
                        dec='dec',
                        equinox='epoch',
                        st='lst',
                        ut='date-obs',
                        date='date-obs',
                        exposure='exptime',
                        airmass='airmass',
                        utmiddle='utmiddle',
                        scale=750.0,
                        show='yes',
                        override='yes',
                        update='yes')
Example #27
0
def prepare_files(list_files, resultpath, readoutnoise):
    # copies data to output directory, trim data files and mask files to contain only good exposure parts, normalize masks, normalize images by masks. Yields exposure-normalized, trimmed sky images.
    for datafile in list_files[:]:
	    #prepare directories and copy image to resultpath
	    filename=os.path.basename(datafile)
	    obsid=os.path.basename(os.path.dirname(datafile))
	    imagepath=os.path.join(resultpath,obsid)
	    image=os.path.join(imagepath,filename)
	    if not os.access(imagepath,os.F_OK): os.makedirs(imagepath)
	    print image
	    shutil.copy(datafile,imagepath)
	    os.chdir(imagepath)
	    iraf.cd(imagepath)
	    # add readoutnoise keyword to header:
	    iraf.hedit(images=filename, fields="RDNOISE", value=str(readoutnoise), addonly="yes", verify="no")
def checkRN(filename):
    imageHeader = fits.open(filename)[0]
    hasDateObsKey = True
    dateString = ""

    try:
        dateString = imageHeader.header['DATE-OBS']
    except KeyError:
        hasDateObsKey = False

    year = dateString[:4]

    if (hasDateObsKey and year == '2011'):
        iraf.hedit(filename, 'RDNOISE', 26, add='yes', verify='no')
        print(" ")
Example #29
0
def checkRN(filename):
  imageHeader = fits.open(filename)[0]
  hasDateObsKey = True
  dateString = ""
  
  try:
    dateString = imageHeader.header['DATE-OBS']
  except KeyError:
    hasDateObsKey = False
      

  year = dateString[:4]
  
  if (hasDateObsKey and year=='2011'):
    iraf.hedit(filename,'RDNOISE',26,add='yes',verify='no')
    print(" ")
Example #30
0
def wcs_transfer(file1,file2,extensions="1,2,3,4"):

    if type(extensions) is str:
        extensions = [int(x) for x in extensions.split(',')]

    template = "%s[%i]" 

    for ext in extensions:
        for kw in WCS_keywords:
            #print file1,file2,ext,kw,
            iraf.images.imutil.imgets(template % (file1,ext),kw)
            var = iraf.images.imutil.imgets.value
            #print var
            if var != '0':
                iraf.hedit(template % (file2,ext), fields=kw, value=var,
                        add=True, verify=False, update=True, show=True)
Example #31
0
def applywavesolution(inputre, calspec):
    ''' apply calibration solution to science spectra '''

    inputlist = glob.glob(inputre)
    inputstring = ', '.join(inputlist)
    outputstring = ', '.join([inp[:-5]+'_spec.fits' for inp in inputlist])

    iraf.hedit.unlearn()
    iraf.dispcor.unlearn()

    iraf.hedit.fields = 'REFSPEC1'
    iraf.hedit.value = calspec
    iraf.hedit.add = True
    iraf.hedit(images=inputstring)

    iraf.dispcor(input=inputstring, output=outputstring)
Example #32
0
File: SCRIPT.py Project: dafh/stuff
def edit_header (input1,input2):
    abrir1 = open(input1,'r')
    abrir2 = open(input2,'r')
    for line in abrir1:
        linea = abrir2.readline().split('\n')[0]
        line = line.split('\n')[0]
        iraf.hedit.images = line
        iraf.hedit.fields = 'REFSPEC1'
        iraf.hedit.add  = 'yes'
        iraf.hedit.value = linea
        iraf.hedit.show = 'yes'
        iraf.hedit.ver = 'no'
        iraf.hedit(mode='h')

    abrir1.close()
    abrir2.close()
Example #33
0
def applywavesolution(inputre, calspec):
    ''' apply calibration solution to science spectra '''

    inputlist = glob.glob(inputre)
    inputstring = ', '.join(inputlist)
    outputstring = ', '.join([inp[:-5] + '_spec.fits' for inp in inputlist])

    iraf.hedit.unlearn()
    iraf.dispcor.unlearn()

    iraf.hedit.fields = 'REFSPEC1'
    iraf.hedit.value = calspec
    iraf.hedit.add = True
    iraf.hedit(images=inputstring)

    iraf.dispcor(input=inputstring, output=outputstring)
Example #34
0
def headerRead(filename, field):
    res = iraf.hedit(filename, field, ".", Stdout=1)
    if res != []:
        res = res[0]
        return res.split("=")[1].replace(" ", "")
    else:
        return ""
Example #35
0
def cor_keyword(fn):
    """
    Correct bad keyword of setairmass command needed.
    then set airmass.
    fn : fits name
    type : string
    """
    ra, dec = func.get_ra_dec(fn)
    func.set_ra_dec(fn, ra, dec)  # set ra dec
    iraf.hedit(images=fn, fields='EPOCH', value='2000.000', add='Yes',
               addonly='No', delete='No', verify='No', show='Yes',
               update='Yes')  # set epoch
    dateobs = pyfits.getval(fn, 'DATE-OBS')
    sidtime = get_sidereal_time2(dateobs)
    iraf.hedit(images=fn, fields='LST', value=sidtime, add='Yes', addonly='No',
               delete='No', verify='No', show='Yes', update='Yes')
    func.set_airmass(fn)
Example #36
0
    def omitPHOTCORR(self):
        """
        Sets PHOTCORR keyword to OMIT to prevent crashing.

        :note: find a proper fix for this.
        :note: Change from iraf to pyfits.
        """
        for raw in glob.glob('*_raw.fits'):
            iraf.hedit(images=raw + '[0]',
                       fields='PHOTCORR',
                       value='OMIT',
                       add=self.no,
                       addonly=self.no,
                       delete=self.no,
                       verify=self.no,
                       show=self.yes,
                       update=self.yes)
Example #37
0
def del_wrong_keyword(fn):
    """
    delete the keyword CCDSEC, DATASEC, BIASSEC in fits fn, the value of the
    keyword is wrong in caha's data, iraf command ccdproc can not process
    the data.
    """
    keywordlst = ['CCDSEC', 'DATASEC', 'BIASSEC']
    for keyword in keywordlst:
        iraf.hedit(images=fn,
                   fields=keyword,
                   value='',
                   add='No',
                   addonly='No',
                   delete='Yes',
                   verify='No',
                   show='Yes',
                   update='Yes')
Example #38
0
def hedit(imlist_name, wavfile):
    """
    Put the result of wavelenght calibration on standard, science images.
    hedit fcdbstd.ms.fits REFSPEC1 "fcdbwav.ms.fits" add+ ver- show+
    """
    import glob
    import os, sys
    from pyraf import iraf
    imlist = glob.glob(imlist_name)
    imlist.sort()
    for i in range(len(imlist)):
        inim = imlist[i]
        iraf.hedit(images=inim,
                   fields='REFSPEC1',
                   value=wavfile,
                   add='yes',
                   verify='no',
                   show='yes')
Example #39
0
def continuumReduce(imageName,imageHaName):

  avgScaleFactor = contsubfactor

  print("The scale factor is "+str(avgScaleFactor))
  
  #configure hedit
  iraf.hedit.add='yes'
  iraf.hedit.verify='no'
  
  iraf.imarith(imageName+'.fits',"*",avgScaleFactor,imageName+"_scaled.fits")
  iraf.imarith(imageHaName+'.fits',"-",imageName+"_scaled.fits",imageHaName+"cs.fits")
  iraf.hedit(imageHaName+'cs.fits','Rscale',avgScaleFactor) 
  
  #clear up superfluous images
  for f in (imageName+'_scaled.fits'):
    silentDelete(f)

  print('The continuum subtracted image is '+ imageHaName+'cs.fits')
Example #40
0
def AvThAr(ThAr1,ThAr2,operator,ThArAv1,ThArAv):
	
	# check that the ARCSs are really the right ones before combining
	if pf.open(ThAr1+".fits")[0].header['OBJECT'] != pf.open(ThAr2+".fits")[0].header['OBJECT']:
		return 1
	
	# Do imarith while keeping FITS extensions
	# first make a sum of the two images -> ThArAv1
	# then divide ThArAv1 / 2 to get the average
	iraf.mscred.mscarith(ThAr1,operator,ThAr2,ThArAv1,verbose='yes')
	iraf.mscred.mscarith(ThArAv1,"/",2,ThArAv,verbose='yes')
	
	iraf.hedit(images=ThAr1+"A.fits[0]",fields='THARCOMB',value='xxx',add='yes',verify='no',show='yes')
	iraf.hedit(images=ThAr1+"A.fits[0]",fields='THARCOMB',value='Combined ThAr from (%s+%s)/2' % (ThAr1,ThAr2),add='yes',verify='no',show='yes')
	
	os.system('mv %s.fits uncombinedarcs/' % ThAr1)
	os.system('mv %s.fits uncombinedarcs/' % ThAr2)
	os.system('rm -rf %s.fits' % ThArAv1)
	
	return 0
Example #41
0
def cor_airmass(lstfile):
    f = open(lstfile)
    l = f.readlines()
    f.close()
    l = [tmp.split('\n')[0] for tmp in l]
    fitlst = ['awftbo' + tmp for tmp in l]
    for fitname in fitlst:
        if os.path.isfile(fitname):
            fit = pyfits.open(fitname)
            objname = fit[0].header['object'].replace('_', ' ').split()[0]
            print(fitname + ' ' + objname)
            objname_new = find_normal_objname(objname)
            if len(objname_new) == 0:
                objname_new = raw_input('please input object name:')
            radec = findradec(objname_new)
            if len(radec) == 0:
                radec = raw_input('please input ra dec of objname:')
                radec = radec.split()
            fitextnum = len(fit)
            fit.close()
            for lay in range(fitextnum):
                airold = iraf.hselect(images = fitname + '[%i]' % lay, fields = 'airmass', expr = 'yes', Stdout = 1)
                airold = float(airold[0])
                print(fitname + ' ' + objname + ' ' + str(lay) + ' airmass old: ' + str(airold))
                fitnamelay = fitname + '[%i]' % lay
                iraf.hedit(images = fitnamelay, fields = 'airold', 
                    value = airold, add = 'yes', addonly = 'yes', delete = 'no', 
                    verify = 'no', show = 'yes', update = 'yes')
                iraf.hedit(images = fitnamelay, fields = 'sname', 
                    value = objname_new, add = 'yes', addonly = 'yes', delete = 'no', 
                    verify = 'no', show = 'yes', update = 'yes')
                iraf.hedit(images = fitnamelay, fields = 'RA', 
                    value = radec[0], add = 'yes', addonly = 'yes', delete = 'no', 
                    verify = 'no', show = 'yes', update = 'yes')
                iraf.hedit(images = fitnamelay, fields = 'DEC', 
                    value = radec[1], add = 'yes', addonly = 'yes', delete = 'no', 
                    verify = 'no', show = 'yes', update = 'yes')
                iraf.twodspec()
                stdpath = os.path.split(os.path.realpath(__file__))[0] + os.sep + 'standarddir' + os.sep
                iraf.longslit(dispaxis = 2, nsum = 1, observatory = 'Lijiang', 
                    extinction = 'onedstds$LJextinct.dat', caldir = stdpath)
                iraf.setairmass(images = fitnamelay,
                    observatory = 'Lijiang', intype = 'beginning', 
                    outtype = 'effective', ra = 'ra', dec = 'dec', 
                    equinox = 'epoch', st = 'lst', ut = 'date-obs', 
                    date = 'date-obs', exposure = 'exptime', airmass = 'airmass', 
                    utmiddle = 'utmiddle', scale = 750.0, show = 'yes', 
                    override = 'yes', update = 'yes')
                print('name airmass_new airmass_old')
                iraf.hselect(fitnamelay, fields = '$I,airmass,airold', 
                             expr = 'yes')
Example #42
0
def continuumReduce(imageName, imageHaName):

    avgScaleFactor = contsubfactor

    print("The scale factor is " + str(avgScaleFactor))

    #configure hedit
    iraf.hedit.add = 'yes'
    iraf.hedit.verify = 'no'

    iraf.imarith(imageName + '.fits', "*", avgScaleFactor,
                 imageName + "_scaled.fits")
    iraf.imarith(imageHaName + '.fits', "-", imageName + "_scaled.fits",
                 imageHaName + "cs.fits")
    iraf.hedit(imageHaName + 'cs.fits', 'Rscale', avgScaleFactor)

    #clear up superfluous images
    for f in (imageName + '_scaled.fits'):
        silentDelete(f)

    print('The continuum subtracted image is ' + imageHaName + 'cs.fits')
def manual_offset(config, sci, total_sci_ext):

	#any other files not specifically mentioned were within 1 angstrom of 5577 so I didn't give them any changes
	if frame in ('N20011220S155.fits', 'N20011220S158.fits', 'N20011220S159.fits'):
		big_offset = -1.5

	elif frame in ('N20020114S113.fits', 'N20020114S116.fits','N20020114S117.fits'):
		big_offset = -11

	elif frame in ('N20020108S097.fits', 'N20020108S098.fits', 'N20020108S100.fits', 'N20020108S101.fits'):
		big_offset = -7.5

	else:
		big_offset = 0.0


	for i in range(2,total_sci_ext+1):
  		slit_header = pyfits.getheader(sky, i)
   		crval1 = slit_header['CRVAL1']
    		iraf.hedit('%s[%d]' % (sky,i), 'CRVAL1', crval1 + big_offset, update='yes', verify='no')
      		iraf.hedit('%s[%d]' % (sci,i), 'CRVAL1', crval1 + big_offset, update='yes', verify='no')
Example #44
0
def set_ra_dec(fn, ra, dec):
    """
    set the fits fn keyword 'RA' and 'DEC'
    fn : fits name
    type : string
    ra : format like '12:34:56.78'
    type : string
    dec : format like '+23:45:67.89'
    type : string
    """
    size = len(pyfits.open(fn))
    if size == 1:
        iraf.hedit(images=fn,
                   fields='RA',
                   value=ra,
                   add='Yes',
                   addonly='No',
                   delete='No',
                   verify='No',
                   show='Yes',
                   update='Yes')
        iraf.hedit(images=fn,
                   fields='DEC',
                   value=dec,
                   add='Yes',
                   addonly='No',
                   delete='No',
                   verify='No',
                   show='Yes',
                   update='Yes')
    else:
        for i in range(len(size)):
            iraf.hedit(images=fn + '[%d]' % i,
                       fields='RA',
                       value=ra,
                       add='Yes',
                       addonly='No',
                       delete='No',
                       verify='No',
                       show='Yes',
                       update='Yes')
            iraf.hedit(images=fn + '[%d]' % i,
                       fields='DEC',
                       value=dec,
                       add='Yes',
                       addonly='No',
                       delete='No',
                       verify='No',
                       show='Yes',
                       update='Yes')
Example #45
0
def tweak_filter(file, Namps=4):
    import pyfits

    header = pyfits.getheader(file)
    filter1 = header['FILTER1']
    filter2 = header['FILTER2']

    if filter1.split()[1] != 'Open':
        filter = filter1.split()[1]
    else:
        filter = filter2.split()[1]

        #try:
        #    filter = filter1.split()[1]
        #except:
        #    filter = filter1.split()[0]

    f = pyfits.open(file, "readonly")
    for i in range(Namps):
        n = i + 1
        header = f[n].header
        image = "%s[%s]" % (file, n)
        filter1 = header['FILTER1']
        if filter != filter1:
            iraf.hedit(image,
                       'FILTER1',
                       filter,
                       add='no',
                       update='yes',
                       verify='no')
            iraf.hedit(image,
                       'FILTER',
                       filter,
                       add='yes',
                       update='yes',
                       verify='no')
        else:
            print("Skipping filter %s %s" % (filter, image))
    f.close()
    return
def clean_folder_write_header(WORK_DIR):
  print '\n + Cleaning folder, truncating edges, fixing bad pixels\n'

  for obj in observations[WORK_DIR]['objects']:
    try: os.remove(obj+'.fits')
    except: pass
    try: os.remove(obj+'.ec.fits')
    except: pass
    iraf.imcopy(input=observations[WORK_DIR]['ORIG_DIR']+obj, output=obj) 

  for cal in observations[WORK_DIR]['calibs']:
    try: os.remove(cal+'.fits')
    except: pass  
    iraf.imcopy(input=observations[WORK_DIR]['ORIG_DIR']+cal, output=cal)

  with open('badpix.txt', 'w+') as file:
    file.write('704 704 1262  2048\n703 705 1262  1277')  

  iraf.hedit(images=','.join(observations[WORK_DIR]['objects']+observations[WORK_DIR]['calibs']), fields='CCDSEC', value='[51:2098,1:2048]', add='yes', verify='no')
  iraf.hedit(images=','.join(observations[WORK_DIR]['objects']+observations[WORK_DIR]['calibs']), fields='DATASEC', value='[51:2098,1:2048]', add='yes', verify='no') 

  # FIX badpix
  iraf.ccdproc(images=','.join(observations[WORK_DIR]['objects']+observations[WORK_DIR]['calibs']), ccdtype='', fixpix='yes', oversca='no', trim='yes', zerocor='no', darkcor='no', flatcor='no', fixfile='badpix.txt')
def header_correction(config, fits, sky, sky_nofits, fits_number, offset_value):

	#getting the MDF information; neccessary for length of second for-loop
	mdf_sky = pyfits.getdata(sky, 'MDF')
	mdf_sci = pyfits.getdata(sci, 'MDF')

	
	#get CRVAL1 from header and add the offset for all extensions in the sky and science frames
	#The range will start where the MEF sci extensions start, 3, and ends 1 before bc the way python loops work
	for i in range(3,len(mdf_sci)-1): #fix this to the offset value - don't hardcode it
		
		#this is loading the mdf for the specific file and then extracting the specific CRVAL1 for each slit
		sky_header = pyfits.getheader(sky, i)
		sci_header = pyfits.getheader(sci, i)
		crval1_sky= sky_header['CRVAL1']
		crval1_sci = sci_header['CRVAL1']
		print '%s %s slit %d' % (config, fits, i)
		print 'Sky CRVAL1: ', crval1_sky
		print 'Science CRVAL1: ', crval1_sci

		#the new CRVAL1 value will be equal to the offset_value (dlambda) plus the original CRVAL1
		iraf.hedit('%s[%d]' % (sky,i), 'CRVAL1', (crval1_sky+offset_value), update='yes', ver='no')
		iraf.hedit('%s[%d]' % (sci,i), 'CRVAL1', (crval1_sci+offset_value), update='yes', ver='no')	
def run_scldark(input):
    iraf.image(_doprint=0)
    iraf.image.imutil(_doprint=0)
    scl=float(input[1])/float(input[2])
#    print input[1],scl
    iraf.imarith(input[0],"*",scl,input[3],divzero="0.0",hparams="",pixtype="",calctype="",verbose="no",noact="no")
    iraf.hedit(input[3],"EXPTIME",input[1], add="yes", addonly="yes", delete="no", verify="no", show="no", update="yes")
    iraf.hedit(input[3],"DARKTIME",input[1], add="yes", addonly="yes", delete="no", verify="no", show="no", update="yes")
    iraf.hedit(input[3],"EXPOSURE","", add="no", addonly="no", delete="yes", verify="no", show="no", update="yes")
iraf.apextract(_doprint=0)
iraf.unlearn(iraf.apall)

# The name of the science file.

filename = 'vega_9.3narrow.fit'
extracted_filename = 'vega_9.3narrow.ms.fits'
calibrated_filename = 'vega_9.3narrow.calib.fits'

# Delete previous results.

os.system("rm "+extracted_filename+" "+calibrated_filename)

# Make sure that the dispersion axis is in the header.

iraf.hedit(images=[filename], fields=["DISPAXIS"], value=["1"], add="Yes")

# Run the spectral extraction program.

iraf.apextract.setParam("dispaxis", "1")

iraf.apall(input=filename, find="No", recenter="No", resize="No")

# Now identify the spectral lines in the arc lamps. Need to replace l1 l2 
# with the range of rows that have the spectral lines.

iraf.identify(filename, section="line 265 285")

# Tell the extracted spectrum what the wavelength solutions are.

iraf.hedit(images=[extracted_filename], fields=["REFSPEC1"], \
Example #50
0
    spec = file_path + "spec_"+file_name
    normspec = file_path + "normspec_"+file_name
    print normspec


    os.system("cp "+spec+" "+output_folder+""+str(i)+".fits")    
    os.system("cp "+spec+" "+output_folder+"reduced/spec_A_"+str(i)+".fits")
    os.system("cp "+normspec+" "+output_folder+"reduced/normspec_A_"+str(i)+".fits")

    
    if i ==0:
        iraf.hedit(
            images = output_folder+"0.fits",\
            fields = "NOTES",\
            value = "RV Standard",\
            add = 1,\
            addonly = 0,\
            delete = 0,\
            verify = 0,\
            show = 1,\
            update =1)

        iraf.hedit(
            images = output_folder+"0.fits",\
            fields = "VHELIO",\
            value = "0.0",\
            add = 1,\
            addonly = 0,\
            delete = 0,\
            verify = 0,\
            show = 1,\
            update =1)
Example #51
0
def update_fitsheader(input_header,original_data,image):
    bad_header_names = "SIMPLE,BITPIX,NAXIS,NAXIS1,NAXIS2,BSCALE,BZERO"

    # print input_header
    # sys.exit()
    
    ### correct header
    #input_header = string.split(input_header,"\n")
    corrected_header = []
    for i in range(len(input_header)):
        #print input_header[i]
        if not input_header[i] == "":
            if not input_header[i][0] == " ":
                header_name = re.split(" |=",input_header[i])[0]
                try:
                    header_value = original_data[0].header[header_name]
                    if type(header_value) == str:
                        if len(header_value) > 0:
                            if header_value[0] == "+":
                                header_value = header_value[1:]

                    # else:
                    #     header_value = str(header_value)

                    if not (header_name in bad_header_names):
                        try:            
                            #print header_name,header_value,type(header_value)
                            iraf.hedit(
                                images = image,\
                                fields = header_name,\
                                add = 0,\
                                addonly = 0,\
                                delete = 1,\
                                verify = 0,\
                                show = 0,\
                                update = 0)

                            iraf.hedit(
                                images = image,\
                                fields = header_name,\
                                value = "dummy",\
                                add = 1,\
                                addonly = 0,\
                                delete = 0,\
                                verify = 0,\
                                show = 0,\
                                update = 1)

                            iraf.hedit(
                                images = image,\
                                fields = header_name,\
                                value = header_value,\
                                add = 1,\
                                addonly = 0,\
                                delete = 0,\
                                verify = 0,\
                                show = 0,\
                                update = 1)
                        except iraf.IrafError:
                            print "Hedit insert error",header_name,header_value,type(header_value)

                except KeyError:
                    pass
            name=raw_input('Enter the name for combined image without .fits extension : ')
            iraf.imcombine(input=inpVAR, output=name+'.fits',combine="average")

        elif (choice == "s" ) :  # Summing and finally dividing by total EXPTIME 
            imgINP=map(int, raw_input('Enter the Sl.No#s of all Images to average by weighted sum of EXPTIME [ Eg: 1,2,3 ] : ').split(','))
            i=len(imgINP)
            if i < 2 : break    # minimum 2 images to combine are not there..
            for j in imgINP :
                if j >= len(images) :  #Sanity check
                    print('Wrong serial number '+str(j)+' given.. exiting the combine task..')
                    break
                hdulist=pyfits.open(images[j])
                Exptime=hdulist[0].header.get('EXPTIME')
                Observatory=hdulist[0].header.get('OBSERVAT')
                hdulist.close()
                if Observatory == 'IGO' : iraf.hedit(images[j],'IntSec',Exptime/1000.0,add=1, ver=0)
                else : iraf.hedit(images[j],'IntSec',Exptime,add=1, ver=0)

            inpVAR=','.join([images[j] for j in imgINP])
            name=raw_input('Enter the name for combined image without .fits extension : ')
            iraf.imcombine(input=inpVAR, output=name+'.fits',combine="sum",scale="exp",zero="mode",weight="exp",expname="IntSec")

        elif ( choice == "a" ) :    # Moving forward to do alignment
            inp=input('Enter the Sl.No# of Reference Image :')
            Refimage=images[inp]
            iraf.display(Refimage,1) 
            print ('Press _a_ over some good stars to align, u can press s also, but DONT press r \n')
            imx=iraf.imexam(Stdout=1)
            Xref=eval(imx[2].split()[0])    #Using the first star as ref star for cose shift calculation
            Yref=eval(imx[2].split()[1])
            foo=open(Refimage+'.coo','w')
Example #53
0
#!/usr/bin/env python
#
# Associate wavelenght solution to science spectra
#
import glob
from pyraf import iraf

calspec = str(raw_input("Enter calibrated spectra: "))

inputre = str(raw_input("Enter regular expression for science spectra: "))
inputlist = glob.glob(inputre)

iraf.hedit.unlearn()
iraf.dispcor.unlearn()
iraf.hedit.fields = 'REFSPEC1'
iraf.hedit.value = calspec
iraf.hedit.add = True
for img in inputlist:
    iraf.hedit(images=img)
    iraf.dispcor(input=img, output=img[:-5]+'_spec')

print '--- DONE ---'
Example #54
0
			try:
				iraf.scopy(sn + '[*,1,1]',"sn_galdered.fits", w1='INDEF', w2='INDEF',format='multispec')
			except:
				print ' WARNING: a problem is appeared to copy the spectrum, problems with the spectrum fits format'
		print '\033[34m*** correcting the spectrum for redshift ***\033[0m'
		try:
			iraf.dopcor('sn_galdered.fits','sn_galdered_dez.fits', redshift=redshift, isveloc='no', flux='no')
			iraf.dopcor('sn_galdered.fits','sn_galdered_dez_err1.fits', redshift=redserrspace1, isveloc='no', flux='no',factor=3)
			iraf.dopcor('sn_galdered.fits','sn_galdered_dez_err2.fits', redshift=redserrspace2, isveloc='no', flux='no',factor=3)
		except:
			print ' WARNING: Problem to redshift the spectrum'
		# host reddening correction
		print '\033[31m*** correcting spectrum for host reddening ***\033[0m'
		ebv = ebvg+ebvh
		print '\033[31m NOW total E(B-V) = ',ebv
		iraf.hedit("sn_galdered_dez.fits", 'DEREDDEN', add='no', addonly='no', delete='yes', verify ='no')
		iraf.hedit("sn_galdered_dez_err1.fits", 'DEREDDEN', add='no', addonly='no', delete='yes', verify ='no', show='no')
		iraf.hedit("sn_galdered_dez_err2.fits", 'DEREDDEN', add='no', addonly='no', delete='yes', verify ='no', show='no')
		iraf.dered('sn_galdered_dez.fits',"sn_dez_dered.fits", value=ebvh, R=3.1, type='E(B-V)',overrid='yes')
		iraf.dered('sn_galdered_dez_err1.fits',"sn_dez_dered_err1.fits", value=ebvh, R=3.1, type='E(B-V)',overrid='yes')
		iraf.dered('sn_galdered_dez_err2.fits',"sn_dez_dered_err2.fits", value=ebvh, R=3.1, type='E(B-V)',overrid='yes')
		print '\033[0m' 
	

	#################################################################
	#### Preparation for wavelength check
	#################################################################
	
	spectrum=iraf.wspec("sn.fits","sn_xbbody.txt", header='no')
	lcf = open('sn_xbbody.txt','r')     
	riga = lcf.readlines()            
RA,DEC,epoch = input_data['RA'],input_data['DEC'],input_data['epoch']

#obtain ST JD using iraf task and introduce in the header
for i in range(len(images)):
    hdr = fits.getheader(images[i])
    if int(split(hdr['UT'],':')[0]) < int(hdr['timezone']):
        new_date = use.yesterday(hdr['date-obs'])
        #print images[i], new_date
    else:
        new_date = hdr['date-obs']
    year,month,day = split(new_date,'-')
    iraf.asttimes(year=year,month=month,day=day,time=hdr['loctime'],obs=input_data['observatory'])
    JD = iraf.asttimes.jd #obtain julian date
    LMST = iraf.asttimes.lmst #obtain the sideral time
    LMST = use.sexagesimal_format(LMST) #convert sideral time in sexagesimal format
    iraf.hedit(images[i],'ST',LMST,add='yes',verify='no',show='no',update='yes') #create the ST keyword in the header
    iraf.ccdhedit(images[i],'LMST',LMST,type='string') #include the mean sideral time in the header
    iraf.ccdhedit(images[i],'JD',JD,type='string') #include de julian date in the header
    #include RA, and DEC of the object in your header
    iraf.ccdhedit(images[i],"RA",RA,type="string") #include right ascention in the header
    iraf.ccdhedit(images[i],"DEC",DEC,type="string")  #include declination in the header
    iraf.ccdhedit(images[i],"epoch",epoch,type="string") #include epoch in the header
    # use.update_progress((i+1.)/len(images))

print '\n Setting airmass ....\n'
for i in range(len(images)):
    print '# ',images[i]
    #iraf.hedit(images[i],'airmass',airmass,add='yes')
    #iraf.hedit(images[i],'HJD',HJD,add='yes')
    iraf.setairmass.observatory = input_data['observatory']
    iraf.setairmass(images[i])
Example #56
0
    title = "",\
    divzero = 0.,\
    hparams = "",\
    pixtype = "",\
    calctype = "",\
    verbose = 1,\
    noact = 0,\
    mode = "ql")    

os.system("rm " + "master_smooth.fits")
os.system("mv " + "temp_master_smooth.fits master_smooth.fits")

### Apply continuum 
os.system("rm continuum_fit.fits")

iraf.hedit(images="master_smooth",fields = "SFIT",value="",add=0,delete=1,verify=0, show=1, update=1)

iraf.continuum(
    input = "master_smooth.fits",\
    output = "continuum_fit.fits",\
    lines = "*",\
    bands = "*",\
    type = "fit",\
    replace = 0,\
    wavescale = 1,\
    logscale = 0,\
    override = 1,\
    listonly = 0,\
    logfiles = "logfile",\
    interactive = 1,\
    function  = "spline3",\
Example #57
0
def extractSpectra():
    """
    Extract 1D spectra using IRAF interactively

    Interpolate across the two arcs either side to
    get the most accurate wavelength solution

    TODO: Finish docstring
          Add method of using super arc for inital
          identify
    """
    # load IRAF from the location of the login.cl file
    here = os.getcwd()
    os.chdir(loginCl_location)
    from pyraf import iraf
    os.chdir(here)
    time.sleep(2)

    # make a list of the science images to be analysed
    templist = g.glob('i_s*')
    # import IRAF packages for spectroscopy
    iraf.imred(_doprint=0)
    iraf.kpnoslit(_doprint=0)
    # apall parameters
    iraf.apall.setParam('format', 'multispec')
    iraf.apall.setParam('interac', 'yes')
    iraf.apall.setParam('find', 'yes')
    iraf.apall.setParam('recen', 'yes')
    iraf.apall.setParam('resize', 'yes')
    iraf.apall.setParam('trace', 'yes')
    iraf.apall.setParam('fittrac', 'yes')
    iraf.apall.setParam('extract', 'yes')
    iraf.apall.setParam('extras', 'yes')
    iraf.apall.setParam('review', 'yes')
    iraf.apall.setParam('line', 'INDEF')
    iraf.apall.setParam('nsum', '12')
    iraf.apall.setParam('lower', '-6')
    iraf.apall.setParam('upper', '6')
    iraf.apall.setParam('b_funct', 'chebyshev')
    iraf.apall.setParam('b_order', '1')
    iraf.apall.setParam('b_sampl', '-25:-15,15:25')
    iraf.apall.setParam('b_naver', '-100')
    iraf.apall.setParam('b_niter', '0')
    iraf.apall.setParam('b_low_r', '3')
    iraf.apall.setParam('b_high', '3')
    iraf.apall.setParam('b_grow', '0')
    iraf.apall.setParam('width', '10')
    iraf.apall.setParam('radius', '10')
    iraf.apall.setParam('threshold', '0')
    iraf.apall.setParam('nfind', '1')
    iraf.apall.setParam('t_nsum', '10')
    iraf.apall.setParam('t_step', '10')
    iraf.apall.setParam('t_nlost', '3')
    iraf.apall.setParam('t_niter', '7')
    iraf.apall.setParam('t_funct', 'spline3')
    iraf.apall.setParam('t_order', '3')
    iraf.apall.setParam('backgro', 'fit')
    iraf.apall.setParam('skybox', '1')
    iraf.apall.setParam('weights', 'variance')
    iraf.apall.setParam('pfit', 'fit1d')
    iraf.apall.setParam('clean', 'yes')
    iraf.apall.setParam('saturat', SATURATION)
    iraf.apall.setParam('readnoi', RDNOISE)
    iraf.apall.setParam('gain', GAIN)
    iraf.apall.setParam('lsigma', '4.0')
    iraf.apall.setParam('usigma', '4.0')
    iraf.apall.setParam('nsubaps', '1')
    iraf.apall.saveParList(filename="apall.pars")

    # make reference arc for reidentify
    if '.' in args.refarc:
        args.refarc = args.refarc.split('.')[0]
    refarc = "a_s_{}_t.fits".format(args.refarc)
    refarc_out = "a_s_{}_t.ms.fits".format(args.refarc)

    # loop over all the the spectra
    for i in range(0, len(templist)):
        hdulist = fits.open(templist[i])
        prihdr = hdulist[0].header
        target_id = prihdr['CAT-NAME']
        spectrum_id = int(templist[i].split('_')[2].split('r')[1])
        if args.ds9:
            os.system('xpaset fuckingds9 fits < {}'.format(templist[i]))
        # extract the object spectrum
        print("[{}/{}] Extracting spectrum of {} from image {}".format(i+1, len(templist), target_id, templist[i]))
        print("[{}/{}] Check aperture and background. Change if required".format(i+1, len(templist)))
        print("[{}/{}] AP: m = mark aperture, d = delete aperture".format(i+1, len(templist)))
        print("[{}/{}] SKY: s = mark sky, t = delete sky, f = refit".format(i+1, len(templist)))
        print("[{}/{}] q = continue".format(i+1, len(templist)))
        iraf.apall(input=templist[i])
        print("Spectrum extracted!")
        # find the arcs either side of the object
        arclist = []
        arc1 = "a_s_r{0:d}_t.fits".format(spectrum_id-1)
        arc2 = "a_s_r{0:d}_t.fits".format(spectrum_id+1)
        arc1_out = "a_s_r{0:d}_t.ms.fits".format(spectrum_id-1)
        arc2_out = "a_s_r{0:d}_t.ms.fits".format(spectrum_id+1)
        # predict the arc names
        print("\nPredicting arcs names...")
        print("Arc1: {}".format(arc1))
        print("Arc2: {}".format(arc2))
        # setup a reference filename for the arc conditions in database
        reffile = templist[i].split('.fits')[0]
        # extract the arcs
        print("\nExtracting arcs under the same conditions...")
        if os.path.exists(arc1):
            iraf.apall(input=arc1,
                       reference=reffile,
                       recente="no",
                       trace="no",
                       backgro="no",
                       interac="no")
            print("Arc1 {} extracted".format(arc1))
            arclist.append(arc1_out)
        else:
            print("\n\nArc1 {} FILE NOT FOUND\n\n".format(arc1))
        if os.path.exists(arc2):
            iraf.apall(input=arc2,
                       reference=reffile,
                       recente="no",
                       trace="no",
                       backgro="no",
                       interac="no")
            print("Arc2 {} extracted".format(arc2))
            arclist.append(arc2_out)
        else:
            print("\n\nArc2 {} FILE NOT FOUND\n\n".format(arc2))
        # get a list of the extracted arcs and objects
        spectrum_out = "i_s_r{0:d}_t.ms.fits".format(spectrum_id)
        if i == 0:
            # extract the master reference arc
            print("\nExtracting master arc {} under the same conditions...".format(refarc))
            iraf.apall(input=refarc,
                       reference=reffile,
                       recente="no",
                       trace="no",
                       backgro="no",
                       interac="no")
            print("Reference arc {} extracted".format(refarc))
            # identify the lines in it
            print("\nIdentify arc lines:")
            print("Enter the following in the splot window")
            print("\t:thres 500")
            print("\t:order 1, max = 3")
            print("\tfwidth 2")
            print("Select 3-5 arc lines from line atlas")
            print("Press 'm' to mark, then enter wavelength")
            print("Then press 'l' to automatically ID the other lines")
            print("Press 'f' to fit the dispersion correction")
            print("Use 'd' to remove bad points, 'f' to refit")
            print("'q' from fit, then 'q' from identify to continue\n")
            iraf.identify(images=refarc_out, coordlist=lineList_location)
        # use the refarc to ID all the subsequent arcs
        for arc in arclist:
            print("\nReidentifying arclines from {}".format(arc))
            iraf.reidentify(reference=refarc_out, images=arc)
        # add the refspec keywords to the image header for dispcor
        # refspec_factor tells IRAF how to interpolate the arcs
        refspec_factor = round((1./len(arclist)), 1)
        for i in range(0, len(arclist)):
            refspec = "{} {}".format(arclist[i].split(".fits")[0], refspec_factor)
            print("REFSPEC{}: {}".format(i+1, refspec))
            iraf.hedit(images=spectrum_out,
                       fields="REFSPEC{}".format(i+1),
                       value=refspec,
                       add="yes",
                       verify="no",
                       show="yes")
        print("Headers updated!\n")
        # apply the dispersion correction
        print("Applying the dispersion correction")
        iraf.dispcor(input=spectrum_out,
                     output=spectrum_out,
                     lineari="yes",
                     databas="database",
                     table="")
        print("Correction applied!")
        # normalize the spectrum using continuum
        normspec_out = "{}n.ms.fits".format(spectrum_out.split('.ms')[0])
        iraf.continuum(input=spectrum_out,
                       output=normspec_out,
                       logfile="logfile",
                       interac="yes",
                       functio="spline3",
                       order="5",
                       niterat="10",
                       markrej="yes")
        print("\n\n")
Example #58
0
             #are the specified format
         for element in psflist:
             ra1 = float(str(element)[4:6])
             ra2 = float(str(element)[6:8])
             ra3 = float(str(element)[8:10]) + float(str(element)[10]) / 10.0
             dec1 = float(str(element)[11:-10])
             dec2 = float(str(element)[-10:-8])
             dec3 = float(str(element)[-8:-6]) + \
                    float(str(element)[-6]) / 10.0
             ra = (ra1 + (ra2 + ra3 / 60.0) / 60.0) * 15.0
             if dec1 < 0.0:
                 dec = (dec1 - (dec2 + dec3 / 60.0) / 60.0)
             else:
                 dec = (dec1 + (dec2 + dec3 / 60.0) / 60.0)
             #print element
             iraf.hedit(element, 'RA_TARG', ra, add= 'yes', verify= 'no', \
                        show='no', update='yes')
             iraf.hedit(element, 'DEC_TARG', dec, add= 'yes', verify= 'no', \
                        show='no', update='yes')
     except:
         pass
 def pa(x):
     """ The function which will bring position angle 
      measured by sextrator in the range -90 and 90"""		
     if(float(x)>=0 and float(x)<=180.0): 
         pos_ang = float(x) - 90.0 #position angle
     if(float(x)<0 and float(x)>=-180.0):
         pos_ang = 90.0 - abs(float(x))  #position angle
     if(float(x)>180 and float(x)<=360.0):
         pos_ang = float(x) - 360.0 + 90.0 #position angle
     if(float(x)>=-360 and float(x)<-180.0):
         pos_ang = float(x) + 360.0 - 90.0 #position angle