Beispiel #1
0
def findzeropoint(xarr, specarr, slines, sfluxes, ws, swarr=None, sfarr=None, function='poly', order=3, dc=10, nstep=20, res=2.0, dres=0.1):
   """Uses cross-correlation to find the best fitting zeropoint""" 

   #if an initial solution, then cut the template lines to just be the length of the spectrum
   if ws==None: return ws


   lmax=specarr.max()
   wmin=ws.value(xarr.min())
   wmax=ws.value(xarr.max())
   mask=(slines>wmin)*(slines<wmax)
   sl=slines[mask]
   sf=sfluxes[mask]
   #if no lines after matching, then just exit
   if not sl.any(): return None

   if swarr==None and sfarr==None:
       swarr, sfarr=st.makeartificial(sl, sf, lmax, res, dres)

   #cross-correlate the spectral lines and the observed fluxes in order to refine the solution
   nws=WavelengthSolution.WavelengthSolution(ws.x_arr, ws.w_arr, order=order, function=function)
   nws.setcoef(ws.coef)

   #create the range of coefficents
   dcoef=ws.coef*0.0
   #dcoef[-2]=0.001
   dcoef[-1]=dc
   dlist=st.mod_coef(ws.coef, dcoef, 0, nstep)

   #loop through them and deteremine the best cofficient
   cc_arr=np.zeros(len(dlist), dtype=float)
   zp_arr=np.zeros(len(dlist), dtype=float)
   dp_arr=np.zeros(len(dlist), dtype=float)
   for i in range(len(dlist)):
       #set the coeficient
       nws.setcoef(dlist[i])

       #set the wavelegnth coverage 
       warr=nws.value(xarr)

       #resample the artificial spectrum at the same wavelengths as the 
       asfarr=st.interpolate(warr, swarr, sfarr, left=0.0, right=0.0)

       #calculate the correlation value
       zp_arr[i]=dlist[i][-1]
       dp_arr[i]=dlist[i][-2]
       cc_arr[i]=st.ncor(specarr, asfarr)
   
   #print cc_arr,  zp_arr
   nws.setcoef(dlist[cc_arr.argmax()])
   coef=np.polyfit(zp_arr, cc_arr, 2)
   nws.coef[-1]=-0.5*coef[1]/coef[0]
   #coef=np.polyfit(dp_arr, cc_arr, 2)
   #nws.coef[-2]=-0.5*coef[1]/coef[0]
   
   nws.setcoef(nws.coef)
   warr=nws.value(xarr)
   ws=WavelengthSolution.WavelengthSolution(xarr, warr, order=order, function=function)
   ws.fit()
   return ws
Beispiel #2
0
 def plotArt(self):
     """Plot the artificial spectrum"""
     self.isArt=True
     warr=self.ws.value(self.xarr)
     asfarr=st.interpolate(warr, self.swarr, self.sfarr, left=0.0, right=0.0)
     asfarr=asfarr*self.farr.max()/asfarr.max()
     self.fpcurve,=self.axes.plot(self.xarr,asfarr,linewidth=0.5,linestyle='-',
                              marker='None',color='r')
Beispiel #3
0
def zeroshift(data, xarr, nws, blank=0, inttype='interp'):
    """Calculate zeropoint shift and apply to the data
    """
    if nws is not None:
        w_arr = nws.value(xarr)
        data = st.interpolate(xarr,
                              w_arr,
                              data,
                              inttype,
                              left=blank,
                              right=blank)
    return data
Beispiel #4
0
def zeroshift(data, xarr, nws, blank=0, inttype='interp'):
    """Calculate zeropoint shift and apply to the data
    """
    if nws is not None:
        w_arr = nws.value(xarr)
        data = st.interpolate(
            xarr,
            w_arr,
            data,
            inttype,
            left=blank,
            right=blank)
    return data
Beispiel #5
0
def rectify(hdu, soldict, caltype='line', function='poly', order=3, inttype='interp',
            w1=None, w2=None, dw=None, nw=None, blank=0, pixscale=0.0, time_interp=False,
            conserve=False, nearest=False, clobber=True, log=None, verbose=True):
    """Read in an image and a set of wavlength solutions.  Calculate the best
       wavelength solution for a given dataset and then apply that data set to the
       image

     return
    """

    # set the basic values
    set_w1 = (w1 is None)
    set_w2 = (w2 is None)
    set_dw = (dw is None)
    set_nw = (nw is None)

    # set up the time of the observation
    dateobs = saltkey.get('DATE-OBS', hdu[0])
    utctime = saltkey.get('TIME-OBS', hdu[0])
    exptime = saltkey.get('EXPTIME', hdu[0])
    instrume = saltkey.get('INSTRUME', hdu[0]).strip()
    grating = saltkey.get('GRATING', hdu[0]).strip()
    if caltype == 'line':
        grang = saltkey.get('GRTILT', hdu[0])
        arang = saltkey.get('CAMANG', hdu[0])
    else:
        grang = saltkey.get('GR-ANGLE', hdu[0])
        arang = saltkey.get('AR-ANGLE', hdu[0])
    filtername = saltkey.get('FILTER', hdu[0]).strip()
    slitname = saltkey.get('MASKID', hdu[0])
    slit = st.getslitsize(slitname)
    xbin, ybin = saltkey.ccdbin(hdu[0])

    timeobs = enterdatetime('%s %s' % (dateobs, utctime))

    # check to see if there is more than one solution
    if caltype == 'line':
        if len(soldict) == 1:
            sol = soldict.keys()[0]
            slitid = None
            if not matchobservations(
                    soldict[sol], instrume, grating, grang, arang, filtername, slitid):
                msg = 'Observations do not match setup for transformation but using the solution anyway'
                if log:
                    log.warning(msg)

    for i in range(1, len(hdu)):
        if hdu[i].name == 'SCI':
            if log:
                log.message('Correcting extension %i' % i)
            istart = int(0.5 * len(hdu[i].data))
            # open up the data
            # set up the xarr and initial wavlength solution
            xarr = np.arange(len(hdu[i].data[istart]), dtype='int64')

            # get the slitid
            try:
                slitid = saltkey.get('SLITNAME', hdu[i])
            except:
                slitid = None
            # set up a wavelength solution
            try:
                w_arr = findsol(xarr, soldict, istart, caltype, nearest, timeobs, exptime, instrume, grating, grang, arang, filtername,
                                slit, xbin, ybin, slitid, function, order)
            except SALTSpecError as e:
                if slitid:
                    msg = 'SLITID %s: %s' % (slitid, e)
                    if log:
                        log.warning(msg)
                    continue
                else:
                    raise SALTSpecError(e)

            if w_arr is None:
                w_arr = findsol(xarr, soldict, istart, 'rss', nearest, timeobs, exptime, instrume, grating, grang, arang, filtername,
                                slit, xbin, ybin, slitid, function, order)

            # set up the output x-axis

            if set_w1:
                w1 = w_arr.min()
            if set_w2:
                w2 = w_arr.max()
            if set_nw:
                nw = len(xarr)
            if set_dw:
                dw = float(w2 - w1) / nw
            nw_arr = createoutputxaxis(w1, w2, nw)

            # setup the VARIANCE and BPM frames
            if saltkey.found('VAREXT', hdu[i]):
                varext = saltkey.get('VAREXT', hdu[i])
            else:
                varext = None

            # setup the BPM frames
            if saltkey.found('BPMEXT', hdu[i]):
                bpmext = saltkey.get('BPMEXT', hdu[i])
            else:
                bpmext = None

            # for each line in the data, determine the wavelength solution
            # for a given line in the image
            for j in range(len(hdu[i].data)):
                # find the wavelength solution for the data
                w_arr = findsol(xarr, soldict, j, caltype, nearest, timeobs, exptime, instrume, grating, grang, arang, filtername,
                                slit, xbin, ybin, slitid, function, order)

                # apply that wavelength solution to the data
                if w_arr is not None:
                    try:
                        hdu[i].data[
                            j,
                            :] = st.interpolate(
                            nw_arr,
                            w_arr,
                            hdu[i].data[
                                j,
                                :],
                            inttype,
                            left=blank,
                            right=blank)
                    except Exception as e:
                        hdu[i].data[j, :] = hdu[i].data[j, :] * 0.0 + blank
                        msg = 'In row %i, solution cannot be found due to %s' % (
                            i, e)

                    # correct the variance frame
                    if varext:
                        try:
                            hdu[varext].data[
                                j,
                                :] = st.interpolate(
                                nw_arr,
                                w_arr,
                                hdu[varext].data[
                                    j,
                                    :],
                                inttype,
                                left=blank,
                                right=blank)
                        except Exception as e:
                            msg = 'In row %i, solution cannot be found due to %s' % (
                                i, e)

                    # correct the BPM frame
                    if bpmext:
                        try:
                            hdu[bpmext].data[
                                j,
                                :] = st.interpolate(
                                nw_arr,
                                w_arr,
                                hdu[bpmext].data[
                                    j,
                                    :],
                                inttype,
                                left=blank,
                                right=blank)
                        except Exception as e:
                            msg = 'In row %i, solution cannot be found due to %s' % (
                                i, e)
                else:
                    hdu[i].data[j, :] = hdu[i].data[j, :] * 0.0 + blank

            if conserve:
                hdu[i].data = hdu[i].data / dw
                if varext:
                    hdu[varext].data = hdu[varext].data / dw

            # Add WCS information
            saltkey.new('CTYPE1', 'LAMBDA', 'Coordinate Type', hdu[i])
            saltkey.new('CTYPE2', 'PIXEL', 'Coordinate Type', hdu[i])
            saltkey.new(
                'CD1_1',
                dw,
                'WCS: Wavelength Dispersion in angstrom/pixel',
                hdu[i])
            saltkey.new('CD2_1', 0.0, 'WCS: ', hdu[i])
            saltkey.new('CD1_2', 0.0, 'WCS: ', hdu[i])
            saltkey.new('CD2_2', ybin * pixscale, 'WCS: ', hdu[i])
            saltkey.new('CRPIX1', 0.0, 'WCS: X Reference pixel', hdu[i])
            saltkey.new('CRPIX2', 0.0, 'WCS: Y Reference pixel', hdu[i])
            saltkey.new('CRVAL1', w1, 'WCS: X Reference pixel', hdu[i])
            saltkey.new('CRVAL2', 0.0, 'WCS: Y Reference pixel', hdu[i])
            saltkey.new('CDELT1', 1.0, 'WCS: X pixel size', hdu[i])
            saltkey.new('CDELT2', 1.0, 'WCS: Y pixel size', hdu[i])
            saltkey.new('DC-FLAG', 0, 'Dispesion Corrected image', hdu[i])

    return hdu
Beispiel #6
0
def rectify(hdu, soldict, caltype='line', function='poly', order=3, inttype='interp', 
            w1=None, w2=None, dw=None, nw=None,
            blank=0, pixscale=0.0, time_interp=False, clobber=True, log=None, verbose=True):
   """Read in an image and a set of wavlength solutions.  Calculate the best
      wavelength solution for a given dataset and then apply that data set to the 
      image 

    return
   """
 
   #set the 
   set_w1=(w1 is  None)
   set_w2=(w2 is  None)
   set_dw=(dw is  None)
   set_nw=(nw is  None)

   #set up the time of the observation
   dateobs=saltkey.get('DATE-OBS', hdu[0])
   utctime=saltkey.get('TIME-OBS', hdu[0])
   exptime=saltkey.get('EXPTIME', hdu[0])
   instrume=saltkey.get('INSTRUME', hdu[0]).strip()
   grating=saltkey.get('GRATING', hdu[0]).strip()
   if caltype=='line':
      grang=saltkey.get('GRTILT', hdu[0])
      arang=saltkey.get('CAMANG', hdu[0])
   else:
      grang=saltkey.get('GR-ANGLE', hdu[0])
      arang=saltkey.get('AR-ANGLE', hdu[0])
   filtername=saltkey.get('FILTER', hdu[0]).strip()
   slitname=saltkey.get('MASKID', hdu[0])
   slit=st.getslitsize(slitname)
   xbin, ybin = saltkey.ccdbin( hdu[0])

   timeobs=enterdatetime('%s %s' % (dateobs, utctime))

   #check to see if there is more than one solution
   if caltype=='line':
    if len(soldict)==1:
      sol=soldict.keys()[0]
      slitid=None
      if not matchobservations(soldict[sol], instrume, grating, grang, arang, filtername, slitid):
         msg='Observations do not match setup for transformation but using the solution anyway'
         if log: log.warning(msg)

   for i in range(1,len(hdu)):
     if hdu[i].name=='SCI':
       if log: log.message('Correcting extension %i' % i)
       istart=int(0.5*len(hdu[i].data))
       #open up the data
       #set up the xarr and initial wavlength solution
       xarr=np.arange(len(hdu[i].data[istart]), dtype='int64')

       #get the slitid
       try:
          slitid=saltkey.get('SLITNAME', hdu[i])
       except:
          slitid=None
       #set up a wavelength solution
       try:
           w_arr=findsol(xarr, soldict, istart, caltype, timeobs, exptime, instrume, grating, grang, arang, filtername, 
              slit, xbin, ybin, slitid, function, order )
       except SALTSpecError, e:
           if slitid: 
              msg='SLITID %s: %s' % (slitid, e)
              if log: log.warning(msg)
              continue
           else:
              raise SALTSpecError(e)
 
       if w_arr is None: 
          w_arr=findsol(xarr, soldict, istart, 'rss', timeobs, exptime, instrume, grating, grang, arang, filtername, 
              slit, xbin, ybin, slitid, function, order )
  
       #set up the output x-axis

       if set_w1: w1=w_arr.min()
       if set_w2: w2=w_arr.max()
       if set_nw: nw=len(xarr)
       if set_dw: dw=float(w2-w1)/nw
       nw_arr=createoutputxaxis(w1, w2, nw)

       #setup the VARIANCE and BPM frames       
       if saltkey.found('VAREXT', hdu[i]):
           varext=saltkey.get('VAREXT', hdu[i])
       else:
           varext=None

       #setup the BPM frames       
       if saltkey.found('BPMEXT', hdu[i]):
           bpmext=saltkey.get('BPMEXT', hdu[i])
       else:
           bpmext=None

       #for each line in the data, determine the wavelength solution
       #for a given line in the image
       for j in range(len(hdu[i].data)):
           #find the wavelength solution for the data
           w_arr=findsol(xarr, soldict, j, caltype, timeobs, exptime, instrume, grating, grang, arang, filtername, 
              slit, xbin, ybin, slitid, function, order )

           #apply that wavelength solution to the data
           if w_arr is not None:
               try:
                  hdu[i].data[j,:]=st.interpolate(nw_arr, w_arr, hdu[i].data[j,:], inttype, left=blank, right=blank)
               except Exception, e:
                  hdu[i].data[j,:]=hdu[i].data[j,:]*0.0+blank
                  msg='In row %i, solution cannot be found due to %s' % (i, e)  

               #correct the variance frame
               if varext:
                   try:
                       hdu[varext].data[j,:]=st.interpolate(nw_arr, w_arr, hdu[varext].data[j,:], inttype, left=blank, right=blank)
                   except Exception, e:
                       msg='In row %i, solution cannot be found due to %s' % (i, e)  

               #correct the BPM frame
               if bpmext:
                   try:
                       hdu[bpmext].data[j,:]=st.interpolate(nw_arr, w_arr, hdu[bpmext].data[j,:], inttype, left=blank, right=blank)
                   except Exception, e:
                       msg='In row %i, solution cannot be found due to %s' % (i, e)