Ejemplo n.º 1
0
def lris_standard(standards, xcorr=yes):

    '''Extract standard stars and calculate sensitivity functions.'''

    for ofile, nstd in standards:

        shutil.copy(ofile, "%s.fits" % nstd)
        
        # Extract standard
        if get_head("%s.fits" % nstd, "SKYSUB"):
            iraf.apall(nstd, output="", inter=yes, find=yes, recenter=yes, resize=yes,
                       edit=yes, trace=yes, fittrace=yes, extract=yes, extras=yes,
                       review=no, background="none")
        else:
            iraf.apall(nstd, output="", inter=yes, find=yes, recenter=yes, resize=yes,
                       edit=yes, trace=yes, fittrace=yes, extract=yes, extras=yes,
                       review=no, background="fit")

        if xcorr:
            # Cross correlate to tweak wavelength
            iraf.xcsao("%s.ms" % nstd, templates=XCTEMPLATE,
                       correlate="wavelength", logfiles="%s.xcsao" % ofile)

            # If a solution was found, apply shift
            try:
                xcsaof = open("%s.xcsao" % ofile)
                shift = float(xcsaof.readlines()[6].split()[14])
            except:
                shift = 0.0
                iraf.specshift("%s.ms" % nstd, -shift)
        
        # Create telluric
        iraf.splot("%s.ms" % nstd) # Remove telluric and absorption, save as a%s.ms
        iraf.sarith("%s.ms" % nstd, "/", "a%s.ms" % nstd, "telluric.%s.fits" % nstd)
        iraf.imreplace("telluric.%s.fits" % nstd, 1.0, lower=0.0, upper=0.0)
        iraf.splot("telluric.%s.fits" % nstd) # Remove stellar features and resave
        
        # Create smoothed standard
        iraf.gauss("a%s.ms[*,1,1]" % nstd, "s%s.ms" % nstd, 5.0)
        iraf.sarith("%s.ms" % nstd, "/", "s%s.ms" % nstd, "ds%s.ms" % nstd)

        # Apply telluric correction
        iraf.telluric("ds%s.ms" % nstd, "tds%s.ms" % nstd, "telluric.%s.fits" % nstd,
                      xcorr=no, tweakrms=no, interactive=no,
                      sample='4000:4010,6850:6975,7150:7350,7575:7725,8050:8400,8900:9725')

        # Define bandpasses for standard star calculation
        obj=get_head("%s.fits" % nstd, "OBJECT")
        iraf.standard("tds%s.ms" % nstd, "%s.std" % nstd,
                  extinction='home$extinct/maunakeaextinct.dat',
                  caldir='home$standards/', observatory='Keck', interac=yes,
                  star_name=obj, airmass='', exptime='')
    
        # Determine sensitivity function
        iraf.sensfunc('%s.std' % nstd, '%s.sens' % nstd,
                      extinction='home$extinct/maunakeaextinct.dat',
                      newextinction='extinct.dat', observatory='Keck',
                      function='legendre', order=4, interactive=yes)

    return
Ejemplo n.º 2
0
    def mk24noiseimage(self):
	os.chdir(self.imagepath24)

        # remove temp images if they exist
        os.system('rm temp*.fits')

        # multiply image by exptime x gain x coverage map
        scale=FLUXCONV*GAIN*EXPT
        iraf.imarith(operand1=self.sex_image,op='*',operand2=scale,result='temp1.fits')
        iraf.imarith(operand1='temp1.fits',op='*',operand2=self.cov_image,result='temp2.fits')
        
        # smooth image using iraf.images.imfilter.gauss
        iraf.gauss(input='temp2.fits',output='temp3.fits',sigma=2,nsigma=6)

        # take sqrt
        iraf.imfunction(input='temp3.fits',output='temp4.fits',function='sqrt')
        # divide by exptime x gain x coverage map

        iraf.imarith(operand1='temp4.fits',op='/',operand2=scale,result='temp5.fits')
    
        # mutliply image and sigma image by 100
        s=self.prefix+'-scalednoise.fits'
        iraf.imarith(operand1='temp5.fits',op='*',operand2=100,result=s)
        s=self.prefix+'-scaled24.fits'
        iraf.imarith(operand1=self.sex_image,op='*',operand2=100,result=s)
Ejemplo n.º 3
0
def run_gauss(imageFilename, sigma):
	'''
	using the image given, calls iraf's gauss method and returns the
	filename of the result, which is blurred using the sigma given
	
	parameter imageFilename - the original image's filename
	parameter sigma - the number of pixels to blur the image by
	
	returns - the blurred image's filename
	'''
	newImageFilename = imageFilename[:-5] + "_gauss.fits"
	iraf.gauss(imageFilename, newImageFilename, sigma)
	return newImageFilename
Ejemplo n.º 4
0
def skyest(inputimg, segimg, gsigma):
    """
    Rough estimate of local sky background.
    """
    if len(glob.glob('segcutout*.fits')):
        os.system('rm segcutout*.fits')
    iraf.imexpr("a > 0 ? 100 : 0", "segcutout2.fits", a=segimg)
    # grow mask by Gaussian wing
    iraf.gauss(input="segcutout2.fits", output="segcutout3.fits", sigma=gsigma)
    h1 = pyfits.open(inputimg)
    h2 = pyfits.open('segcutout3.fits')
    him1 = h1[0].data  # image data
    him2 = h2[0].data
    skyim = np.compress(him2.ravel() < 10., him1.ravel())
    bkgnd = np.median(skyim)  # take the median of unmasked sky
    #os.system('rm cutout.fits')
    os.system('rm segcutout*.fits')

    return bkgnd
Ejemplo n.º 5
0
def skyest(inputimg, segimg, gsigma):
    #if len(glob.glob("cutout.fits")):
    #    os.system("rm cutout.fits")
    #iraf.imcopy("%s[%d:%d,%d:%d]"%(inputimg,xmin,xmax,ymin,ymax),"cutout.fits")
    #iraf.imcopy(segimg+"[%d:%d,%d:%d]"%(xmin,xmax,ymin,ymax),"segcutout.fits")
    if len(glob.glob('segcutout*.fits')):
        os.system('rm segcutout*.fits')
    iraf.imexpr("a > 0 ? 100 : 0", "segcutout2.fits", a=segimg)
    # grow mask by Gaussian wing
    iraf.gauss(input="segcutout2.fits", output="segcutout3.fits", sigma=gsigma)
    h1 = pyfits.open(inputimg)
    h2 = pyfits.open('segcutout3.fits')
    him1 = h1[0].data  # image data
    him2 = h2[0].data
    skyim = compress(him2.ravel() < 10., him1.ravel())
    bkgnd = median(skyim)  # take the median of unmasked sky
    #os.system('rm cutout.fits')
    os.system('rm segcutout*.fits')
    return bkgnd
def prep(df_image, hi_res_image):
    'run SExtractor to get bright sources that are easily detected in the high resolution data'
    ##### DEB: Can choose to run sextractor more or less aggressively
    subprocess.call('sex %s' % hi_res_image, shell=True)
    'copy the segmentation map to a mask'
    iraf.imcopy('seg.fits', '_mask.fits')
    'replace the values in the segments in the segmentation map (i.e. stars) all to 1, all the background is still 0'
    iraf.imreplace('_mask.fits', 1, lower=0.5)
    'multiply the mask (with 1s at the stars) by the high res image to get the star flux back - now have the flux model'
    iraf.imarith('_mask.fits', '*', '%s' % hi_res_image, '_fluxmod_cfht')
    'smooth the flux model'
    'increase size of mask, so more is subtracted'
    'the "1.5" in the next line should be a user-defined parameter that is given'
    'to the script; it controls how much of the low surface brightness'
    'emission in the outskirts of galaxies is subtracted. This choice'
    'depends on the science application'
    iraf.gauss('_fluxmod_cfht', '_fluxmod_cfht_smoothed', 2.5)  ### nsigma=4
    '''
    imreplace _fluxmod_cfht_rs -1 lower=0 upper=0
    imreplace _fluxmod_cfht_rs 1 lower=-0.5
    imreplace _fluxmod_cfht_rs 0 upper=-0.5
    imarith _cfht_r * _fluxmod_cfht_rs _fluxmod_cfht_r_new
    '''
    '''
    # this is the key new step! we're registering the CFHT image
    #  to a frame that is 4x finer sampled than the Dragonfly image.
    # this avoids all the pixelation effects we had before. 
    #  (4x seems enough; but we could have it as a free parameter - need
    # to be careful as it occurs elsewhere in the scripts too) 
    blkrep _df_g _df_g4 4 4
    '''

    'register the flux model onto the same pixel scale as the dragonfly image'
    iraf.wregister('_fluxmod_cfht_smoothed',
                   '%s' % df_image,
                   '_fluxmod_dragonfly',
                   interpo='linear',
                   fluxcon='yes')

    return None
Ejemplo n.º 7
0
def prep(df_image,hi_res_image,width_mask=1.5,unmaskgal=False,galvalues = None):
    print "\n************ Running the preparation steps ************\n"
    iraf.imdel('_mask.fits')
    iraf.imdel('_fluxmod_cfht*.fits')
    iraf.imdel('_df_4*.fits')
    
    'run SExtractor to get bright sources that are easily detected in the high resolution data'
    subprocess.call('sex %s'%hi_res_image,shell=True)    #####  Add in option to change sextractor threshold detect_thresh and analysis_thresh 2/3
    'copy the segmentation map to a mask'
    iraf.imcopy('seg.fits','_mask.fits')

    ##### Add step to get rid of diffraction spikes

    if unmaskgal:
        'Run SExtractor to get values for the central galaxy'
        print '\nDoing a second sextractor run to unmask central galaxy. \n'
        analysis_thresh_lg=2;back_size_lg=128;detect_thresh_lg=2;detect_minarea_lg=60
        segname = run_SExtractor(hi_res_image,detect_thresh=detect_thresh_lg,analysis_thresh=analysis_thresh_lg,back_size=back_size_lg,detect_minarea=detect_minarea_lg)
        print '\nSegmentation map is named: '+segname
        
        'Open up the data'
        seg2data = fits.getdata(segname)
        segdata,segheader = fits.getdata('_mask.fits',header=True)
        
        'Detect sources from the segmentation map'
        from photutils import detect_sources
        segrefdata = detect_sources(seg2data, 3, npixels=5)#, filter_kernel=kernel) 
        segrefdata = segrefdata.data
        segrefname = re.sub('.fits','_ds.fits',segname)
        writeFITS(segrefdata,segheader,segrefname)    
        print '\nSource separated segmentation map is named: '+segrefname
        
        'Use detected source seg map to mask galaxies' #galvalues = [3531,5444,5496]
        print 'Unmask the galaxies in the mask from the original segmap. \n'
        segdatanew = unmaskgalaxy(segdata,'_mask.fits',segrefname=segrefname,segref=segrefdata,galvalues=galvalues)        
        writeFITS(segdatanew,segheader,'_mask.fits')
        
    if verbose:
        print_verbose_string('Carrying on')
        
    'replace the values in the segments in the segmentation map (i.e. stars) all to 1, all the background is still 0'
    iraf.imreplace('_mask.fits',1,lower=0.5)
    'multiply the mask (with 1s at the stars) by the high res image to get the star flux back - now have the flux model'
    iraf.imarith('_mask.fits','*','%s'%hi_res_image,'_fluxmod_cfht')
    
    'smooth the flux model'
    'increase size of mask, so more is subtracted'
    'the "1.5" in the next line should be a user-defined parameter that is given'
    'to the script; it controls how much of the low surface brightness'
    'emission in the outskirts of galaxies is subtracted. This choice'
    'depends on the science application'
    iraf.gauss('_fluxmod_cfht','_fluxmod_cfht_smoothed',width_mask,nsigma=4.)

    iraf.imreplace('_fluxmod_cfht_smoothed', -1, lower=0, upper=0)
    iraf.imreplace('_fluxmod_cfht_smoothed', 1, lower=-0.5)
    iraf.imreplace('_fluxmod_cfht_smoothed', 0, upper=-0.5)
    iraf.imarith('%s'%hi_res_image, '*','_fluxmod_cfht_smoothed', '_fluxmod_cfht_new')
    
    ' this is the key new step! we"re registering the CFHT image'
    ' to a frame that is 4x finer sampled than the Dragonfly image.'
    ' this avoids all the pixelation effects we had before.'
    '  (4x seems enough; but we could have it as a free parameter - need'
    ' to be careful as it occurs elsewhere in the scripts too) '
    iraf.blkrep('%s'%df_image,'_df_4',4,4)
    
    'register the flux model onto the same pixel scale as the dragonfly image'
    iraf.wregister('_fluxmod_cfht_new','_df_4','_fluxmod_dragonfly',interpo='linear',fluxcon='yes')

    return None
Ejemplo n.º 8
0
def lris_standard(standards, xcorr=yes):
    '''Extract standard stars and calculate sensitivity functions.'''

    for ofile, nstd in standards:

        shutil.copy(ofile, "%s.fits" % nstd)

        # Extract standard
        if get_head("%s.fits" % nstd, "SKYSUB"):
            iraf.apall(nstd,
                       output="",
                       inter=yes,
                       find=yes,
                       recenter=yes,
                       resize=yes,
                       edit=yes,
                       trace=yes,
                       fittrace=yes,
                       extract=yes,
                       extras=yes,
                       review=no,
                       background="none")
        else:
            iraf.apall(nstd,
                       output="",
                       inter=yes,
                       find=yes,
                       recenter=yes,
                       resize=yes,
                       edit=yes,
                       trace=yes,
                       fittrace=yes,
                       extract=yes,
                       extras=yes,
                       review=no,
                       background="fit")

        if xcorr:
            # Cross correlate to tweak wavelength
            iraf.xcsao("%s.ms" % nstd,
                       templates=XCTEMPLATE,
                       correlate="wavelength",
                       logfiles="%s.xcsao" % ofile)

            # If a solution was found, apply shift
            try:
                xcsaof = open("%s.xcsao" % ofile)
                shift = float(xcsaof.readlines()[6].split()[14])
            except:
                shift = 0.0
                iraf.specshift("%s.ms" % nstd, -shift)

        # Create telluric
        iraf.splot("%s.ms" %
                   nstd)  # Remove telluric and absorption, save as a%s.ms
        iraf.sarith("%s.ms" % nstd, "/", "a%s.ms" % nstd,
                    "telluric.%s.fits" % nstd)
        iraf.imreplace("telluric.%s.fits" % nstd, 1.0, lower=0.0, upper=0.0)
        iraf.splot("telluric.%s.fits" %
                   nstd)  # Remove stellar features and resave

        # Create smoothed standard
        iraf.gauss("a%s.ms[*,1,1]" % nstd, "s%s.ms" % nstd, 5.0)
        iraf.sarith("%s.ms" % nstd, "/", "s%s.ms" % nstd, "ds%s.ms" % nstd)

        # Apply telluric correction
        iraf.telluric(
            "ds%s.ms" % nstd,
            "tds%s.ms" % nstd,
            "telluric.%s.fits" % nstd,
            xcorr=no,
            tweakrms=no,
            interactive=no,
            sample='4000:4010,6850:6975,7150:7350,7575:7725,8050:8400,8900:9725'
        )

        # Define bandpasses for standard star calculation
        obj = get_head("%s.fits" % nstd, "OBJECT")
        iraf.standard("tds%s.ms" % nstd,
                      "%s.std" % nstd,
                      extinction='home$extinct/maunakeaextinct.dat',
                      caldir='home$standards/',
                      observatory='Keck',
                      interac=yes,
                      star_name=obj,
                      airmass='',
                      exptime='')

        # Determine sensitivity function
        iraf.sensfunc('%s.std' % nstd,
                      '%s.sens' % nstd,
                      extinction='home$extinct/maunakeaextinct.dat',
                      newextinction='extinct.dat',
                      observatory='Keck',
                      function='legendre',
                      order=4,
                      interactive=yes)

    return
Ejemplo n.º 9
0
def deimos_standard(standard):

    '''Extract standard star and calculate sensitivit function.'''
    
    bstd = "%s_01_B" % standard; rstd = "%s_01_R" % standard

    # Extract standard
    if get_head("%s.fits" % bstd, "SKYSUB"):
        iraf.apall(bstd, output="", inter=yes, find=yes, recenter=yes, resize=yes,
                   edit=yes, trace=yes, fittrace=yes, extract=yes, extras=yes,
                   review=no, background="none")
        iraf.apall(rstd, output="", inter=yes, find=yes, recenter=yes, resize=yes,
                   edit=yes, trace=yes, fittrace=yes, extract=yes, extras=yes,
                   review=no, background="none")
    else:
        iraf.apall(bstd, output="", inter=yes, find=yes, recenter=yes, resize=yes,
                   edit=yes, trace=yes, fittrace=yes, extract=yes, extras=yes,
                   review=no, background="fit")
        iraf.apall(rstd, output="", inter=yes, find=yes, recenter=yes, resize=yes,
                   edit=yes, trace=yes, fittrace=yes, extract=yes, extras=yes,
                   review=no, background="fit")

    # Fit the continuum
    #iraf.continuum("%s.ms" % bstd, output="s%s.ms" % bstd, lines=1, bands=1,
    #               type="fit", sample="*", naverage=1, function="chebyshev",
    #               order=15, low_reject=3.0, high_reject=5.0, niterate=10, grow=1.0,
    #               interac=yes)
    #iraf.continuum("%s.ms" % rstd, output="s%s.ms" % rstd, lines=1, bands=1,
    #               type="fit", sample="*", naverage=1, function="chebyshev",
    #               order=15, low_reject=3.0, high_reject=5.0, niterate=10, grow=1.0,
    #               interac=yes)

    # Create telluric
    iraf.splot("%s.ms" % bstd) # Remove telluric and absorption, save as a%s.ms
    iraf.sarith("%s.ms" % bstd, "/", "a%s.ms" % bstd, "telluric.B.%s.fits" % bstd)
    iraf.imreplace("telluric.B.%s.fits" % bstd, 1.0, lower=0.0, upper=0.0)
    iraf.splot("telluric.B.%s.fits" % bstd) # Remove stellar features and resave

    iraf.splot("%s.ms" % rstd) # Remove telluric and absorption, save as a%s.ms
    iraf.sarith("%s.ms" % rstd, "/", "a%s.ms" % rstd, "telluric.R.%s.fits" % rstd)
    iraf.imreplace("telluric.R.%s.fits" % rstd, 1.0, lower=0.0, upper=0.0)
    iraf.splot("telluric.R.%s.fits" % rstd) # Remove stellar features and resave
    
    # Create smoothed standard
    iraf.gauss("a%s.ms[*,1,1]" % bstd, "s%s.ms" % bstd, 5.0)
    iraf.sarith("%s.ms" % bstd, "/", "s%s.ms" % bstd, "ds%s.ms" % bstd)
    iraf.gauss("a%s.ms[*,1,1]" % rstd, "s%s.ms" % rstd, 5.0)
    iraf.sarith("%s.ms" % rstd, "/", "s%s.ms" % rstd, "ds%s.ms" % rstd)

    # Divide through by smoothed standard
    #iraf.sarith("%s.ms" % bstd, "/", "s%s.ms" % bstd, "ds%s.ms" % bstd)
    #iraf.sarith("%s.ms" % rstd, "/", "s%s.ms" % rstd, "ds%s.ms" % rstd)

    # Create and apply telluric correction
    #iraf.splot("%s.ms" % bstd) # Remove telluric, save as a%s.ms
    #iraf.splot("%s.ms" % rstd) # Remove telluric, save as a%s.ms
    #iraf.sarith("%s.ms" % bstd, "/", "a%s.ms" % bstd, "telluric.B.fits")
    #iraf.sarith("%s.ms" % rstd, "/", "a%s.ms" % rstd, "telluric.R.fits")
    #iraf.imreplace("telluric.B.fits", 1.0, lower=0.0, upper=0.0)
    #iraf.imreplace("telluric.R.fits", 1.0, lower=0.0, upper=0.0)
    iraf.telluric("ds%s.ms" % bstd, "tds%s.ms" % bstd, "telluric.B.%s.fits" % bstd,
                  xcorr=no, tweakrms=no, interactive=no, sample='6850:6950,7575:7700')
    iraf.telluric("ds%s.ms" % rstd, "tds%s.ms" % rstd, "telluric.R.%s.fits" % rstd,
                  xcorr=no, tweakrms=no, interactive=no, sample='6850:6950,7575:7700')

    # Define bandpasses for standard star calculation
    iraf.standard("tds%s.ms" % bstd, "%s.B.std" % standard,
                  extinction='home$extinct/maunakeaextinct.dat',
                  caldir='home$standards/', observatory='Keck', interac=yes,
                  star_name=standard, airmass='', exptime='')
    iraf.standard("tds%s.ms" % rstd, "%s.R.std" % standard,
                  extinction='home$extinct/maunakeaextinct.dat',
                  caldir='home$standards/', observatory='Keck', interac=yes,
                  star_name=standard, airmass='', exptime='')

    # Determine sensitivity function
    iraf.sensfunc('%s.B.std' % standard, '%s.B.sens' % standard,
                  extinction='home$extinct/maunakeaextinct.dat',
                  newextinction='extinct.dat', observatory='Keck',
                  function='legendre', order=4, interactive=yes)
    iraf.sensfunc('%s.R.std' % standard, '%s.R.sens' % standard,
                  extinction='home$extinct/maunakeaextinct.dat',
                  newextinction='extinct.dat', observatory='Keck',
                  function='legendre', order=4, interactive=yes)

    return
Ejemplo n.º 10
0
def convolve_images():    
    for i in range(nfiles):
        convolved_image = 'g'+files[i]
        gauss(input=files[i],output=convolved_image,sigma=sigma_filter[i])
Ejemplo n.º 11
0
def gauss2(fn):
    iraf.images()
    iraf.imfilter()
    for i in (fn):
        iraf.gauss(i, i, '2')
Ejemplo n.º 12
0
def gauss2(setup, filelist):
    iraf.images()
    iraf.imfilter()
    for i in (filelist):
        name = setup + '/' + i
        iraf.gauss(name, name, '2')
Ejemplo n.º 13
0
    def fitone(self, objectid, psffile=None, magzpt=None, exptime=1.0):
        """
        A driver function that fits one object, given its ID.
        Most of the work is done here.
        Provide a PSF file and magnitude zero point for each object!
        """
        if psffile == None: psffile = self.psffile
        if magzpt == None: magzpt = self.magzpt
        idcrit = (self.id_array == objectid)
        ra = self.ra_array[idcrit][0]
        dec = self.dec_array[idcrit][0]
        mag = self.mag_array[idcrit][0]
        Re = self.Re_array[idcrit][0]
        axratio = self.axratio_array[idcrit][0]
        theta = self.theta_array[idcrit][0]
        isoarea = self.isoarea_array[idcrit][0]
        # Now figure out image coordinates
        x = self.x_array[idcrit][0]
        y = self.y_array[idcrit][0]
        print "x, y =", x, y
        OUT1 = open(self.crashes, "ab")
        OUT2 = open(self.fitted, "ab")

        # now create arrays that will be included in this GALFIT run
        id_fit = [objectid]
        mag_fit = [mag]
        Re_fit = [Re]
        x_fit = [x]
        y_fit = [y]
        theta_fit = [theta]
        axratio_fit = [axratio]

        # step 1: determine temporary image size
        # Experimental image size
        majx = abs(N.sqrt(isoarea) * 4. *
                   N.sin(theta / 180. * N.pi))  # convert degree into radian
        majy = abs(N.sqrt(isoarea) * 4. * N.cos(theta / 180. * N.pi))
        minx = axratio * N.sqrt(isoarea) * 4. * abs(
            N.sin((theta + N.pi / 2.) / 180. * N.pi))
        miny = axratio * N.sqrt(isoarea) * 4. * abs(
            N.sin((theta + N.pi / 2.) / 180. * N.pi))
        #Re_max = 20.
        Re_max = 60
        if Re > Re_max:
            Re_max = Re
        xsize = majx
        # determine the offset of this cutout relative to the entire mosaic
        if minx >= majx:
            xsize = minx
        if xsize <= 30.:
            xsize = 30.
        ysize = majy
        if miny >= majy:
            ysize = miny
        if ysize <= 30.:
            ysize = 30.
        xmin = int(x - xsize)
        if xmin <= 0:
            xmin = 1
        xmax = int(x + xsize)
        ymin = int(y - ysize)
        if ymin <= 0:
            ymin = 1
        ymax = int(y + ysize)
        # construct postage stamp name
        outname = self.root + '/obj%d_out.fits' % objectid

        # step 2: determine which objects to be included
        for jj in range(self.nobj_all):  # iterate through other objects
            if self.id_array[jj] != objectid:
                dx = x - self.x_array[jj]
                dy = y - self.y_array[jj]
                dist = N.sqrt(dx**2 + dy**2)
                # Fit all objects that fall within a certain
                #  radius of the central object:
                radck = N.sqrt(self.isoarea_array[jj])
                angle = N.arctan2(dy, dx)
                phi = N.pi / 2. - (self.theta_array[jj] / 180. * N.pi +
                                   N.pi / 2. - angle)
                thetap = N.arctan2(self.axratio_array[jj] * N.tan(phi), 1.)
                isorad = radck * N.sqrt((self.axratio_array[jj] *
                                         N.cos(thetap))**2 + N.sin(thetap)**2)
                # If object is within the fitted image region...
                if (((self.x_array[jj] >= xmin) and
                     (self.x_array[jj] <= xmax) and
                     (self.y_array[jj] >= ymin) and
                     (self.y_array[jj] <= ymax) and
                     # but is greater than 2 Re away, and is not more than 3 mag fainter, or
                     ((dist > 2 * Re and self.mag_array[jj] - 3. <= mag) or
                      # is less than 2 Re away and not more than 5 mag fainter, or
                      (dist < 2. * Re and self.mag_array[jj] - 5. <= mag))) or
                        # is outside image, but is about 3 Re away and 1 mag brighter
                    ((self.x_array[jj] >= (xmin - isorad) and
                      (self.x_array[jj] <= (xmax + isorad) and
                       (self.y_array[jj] >=
                        (ymin - isorad)) and (self.y_array[jj] <=
                                              (ymax + isorad)) and
                       (self.mag_array[jj] + 1.) <= mag)))):
                    id_fit += [self.id_array[jj]]
                    x_fit += [self.x_array[jj]]
                    y_fit += [self.y_array[jj]]
                    mag_fit += [self.mag_array[jj]]
                    Re_fit += [self.Re_array[jj]]
                    axratio_fit += [self.axratio_array[jj]]
                    theta_fit += [self.theta_array[jj]]
                    if self.Re_array[jj] > Re_max:
                        Re_max = self.Re_array[jj]

        # step 3: determine fitting size & copy images
        # Determine image fitting size and convolution box info
        # into the galfit template file
        Refrac = 0.7
        #Refrac = 2.0
        if xmin >= min(x_fit) - Refrac * Re_max:
            xmin = min(x_fit) - Refrac * Re_max
        if xmin < 1:
            xmin = 1
        if ymin >= min(y_fit) - Refrac * Re_max:
            ymin = min(y_fit) - Refrac * Re_max
        if ymin < 1:
            ymin = 1
        if xmax <= max(x_fit) + Refrac * Re_max:
            xmax = max(x_fit) + Refrac * Re_max
        if ymax <= max(y_fit) + Refrac * Re_max:
            ymax = max(y_fit) + Refrac * Re_max
        #cbox = 60
        imgxsize = xmax - xmin + 1
        imgysize = ymax - ymin + 1
        if os.path.exists(outname):
            os.remove(outname)
        # copy drizzled images
        if os.path.exists(self.root + '/obj%d_drz.fits' % objectid):
            os.system('rm %s/obj%d_drz.fits' % (self.root, objectid))
        drzimg = self.sci_image + '[%d:%d,%d:%d]' % (xmin, xmax, ymin, ymax)
        iraf.imcopy(drzimg, self.root + '/obj%d_drz.fits' % objectid)
        h = pyfits.open(self.root + '/obj%d_drz.fits' % objectid, 'update')
        h[0].header.update('xmin', xmin)
        h[0].header.update('xmax', xmax)
        h[0].header.update('ymin', ymin)
        h[0].header.update('ymax', ymax)
        h[0].header.update('exptime', exptime)
        h.flush()
        h.close()
        # copy sigma image
        if os.path.exists(self.root + '/obj%d_rms.fits' % objectid):
            os.system('rm %s/obj%d_rms.fits' % (self.root, objectid))
        iraf.imcopy(
            self.rms_image + '[%d:%d,%d:%d]' % (xmin, xmax, ymin, ymax),
            self.root + '/obj%d_rms.fits' % objectid)
        # copy segmentation images
        if os.path.exists(self.root + '/obj%d_seg.fits' % objectid):
            os.system('rm %s/obj%d_seg.fits' % (self.root, objectid))
        iraf.imcopy(
            self.seg_image + '[%d:%d,%d:%d]' % (xmin, xmax, ymin, ymax),
            self.root + '/obj%d_seg.fits' % objectid)
        # make mask image -- zero-out the included components in the mask image
        if os.path.exists("mask2.fits"):
            iraf.imdelete("mask2.fits")
        if os.path.exists("mask3.fits"):
            iraf.imdelete("mask3.fits")
        maskexpr = ""
        maskname = self.root + "/obj%d_seg.fits" % objectid
        print "id_fit", id_fit
        for j in range(len(id_fit)):
            inid = id_fit[j]
            maskexpr = maskexpr + "(a==%d)" % inid
            if j != len(id_fit) - 1:
                maskexpr = maskexpr + "||"
        print maskexpr
        # Now make the masks
        # In GALFIT, good pixels have mask value 0, while bad pixels have mask values > 0
        iraf.imexpr(maskexpr + " ? 0 : a", "mask2.fits", a=maskname)
        # After this step, the only non-zero pixels will be those belonging to the objects that are NOT
        # included in the list id_fit.
        # Now flatten the mask image and convolve with a Gaussian, in order to grow the masked region a little bit
        # to account for wings of objects.
        iraf.imexpr("a>0 ? 100. : 0.", "mask3.fits", a="mask2.fits")
        iraf.gauss(input="mask3.fits", output="mask3.fits", sigma=5)
        if os.path.exists(self.root + '/mask_obj%d.fits' % objectid):
            os.remove(self.root + '/mask_obj%d.fits' % objectid)
        iraf.imexpr("a<=10. ? 0. : a",
                    self.root + "/mask_obj%d.fits" % objectid,
                    a="mask3.fits")
        os.remove("mask2.fits")
        os.remove("mask3.fits")

        # step 4: write GALFIT input file
        parfile = "obj%d" % objectid
        f = open(parfile, 'w')
        # Write image parameters
        print >> f, "==============================================================================="
        print >> f, "# IMAGE PARAMETERS"
        print >> f, "A) %s/obj%d_drz.fits   # Input Data image (FITS file) " % (
            self.root, objectid)
        print >> f, "B) %s/obj%d_out.fits   # Output data image block " % (
            self.root, objectid)
        print >> f, 'C) %s/obj%d_rms.fits   # Noise image name (made from data if blank or "none") ' % (
            self.root, objectid)
        print >> f, "D) %s         # Input PSF image for convolution (FITS file) " % psffile
        print >> f, "E) 1                   # PSF oversampling factor relative to data "
        print >> f, "F) %s/mask_obj%d.fits     # Bad pixel mask (FITS image or ASCII coord list)" % (
            self.root, objectid)
        print >> f, "G) %s           # Parameter constraint file " % self.constraint_file
        print >> f, "H) %d %d %d %d  # Image region to fit " % (1, imgxsize, 1,
                                                                imgysize)
        print >> f, "I) %d  %d       # Size of the convolution box (x y)" % (
            self.cbox, self.cbox)
        print >> f, "J) %f             # Magnitude photometric zeropoint " % magzpt
        print >> f, "K) %s %s       # Plate scale (dx dy). " % (self.xscale,
                                                                self.yscale)
        print >> f, "O) regular             # Display type (regular, curses, both) "
        print >> f, "P) 0                   # Create ouput only? (1=yes; 0=optimize) "
        print >> f, "S) 0                   # Modify/create objects interactively? "
        print >> f, ""
        print >> f, "# INITIAL FITTING PARAMETERS "
        print >> f, ""
        print >> f, "#   For object type, allowed functions are: sersic, nuker, "
        print >> f, "#                       expdisk, devauc, moffat, gaussian. "
        print >> f, ""
        print >> f, "# Objtype:      Fit?         Parameters "
        print >> f, ""
        # Write individual component
        for j in range(len(id_fit)):
            self.component(f, j + 1, x_fit[j] - xmin + 1, y_fit[j] - ymin + 1,
                           mag_fit[j], Re_fit[j], axratio_fit[j], theta_fit[j])
        # Make sky component
        #bkgnd = skyest('images/obj%d_drz.fits'%objectid,'images/obj%d_seg.fits'%objectid,5.)
        bkgnd = 0.
        self.sky(f, len(id_fit) + 1, bkgnd)
        f.close()

        # step 5: run GALFIT
        t1 = time.time()
        galfitrun = subprocess.Popen(["galfit", parfile], stdout=sys.stdout)
        # runs GALFIT
        # ======================================================= #
        # Try to time GALFIT and kill it after spending more than
        # 10 min on one object
        # ======================================================= #
        timelimit = 10. * 60.  # time limit: 10 minutes
        timeint = 10.  # check every 10 seconds
        maxcheck = int(timelimit / timeint)
        kill = 1
        for j in range(maxcheck):
            time.sleep(timeint)  # sleep for check time interval
            if galfitrun.poll() == None:  # if it's still running:
                pass  # haven't reached time limit; let it run
            else:
                kill = 0  # finished before time limit; don't need to kill
                break  # jump out of process checking
        if kill:  # if reached time limit and still running:
            os.kill(galfitrun.pid, signal.SIGKILL)  # kill GALFIT
            print "Killed GALFIT; GALFIT froze"
        retcode = galfitrun.returncode
        t2 = time.time()
        try:
            print >> OUT1, "returned code is %d" % retcode
        except:
            print >> OUT1, "returned code is ", retcode
        dt = t2 - t1
        if retcode != 7:  # not sure about the behavior when GALFIT crashes...!!!
            print >> OUT1, "%d  %s" % (objectid, parfile)
        else:
            print >> OUT2, "%s-wmask-out.fits %.1f seconds" % (outname, dt)
        OUT1.close()
        OUT2.close()
        print "Finishes GALFIT fitting"
Ejemplo n.º 14
0
def blue_standard(image,
                  arcs,
                  flats,
                  object=None,
                  biassec1=BLUEBIAS1,
                  trimsec1=BLUETRIM1,
                  biassec2=BLUEBIAS2,
                  trimsec2=BLUETRIM2,
                  outflat='Flat-Blue.fits',
                  gain=BLUEGAIN,
                  rdnoise=BLUERDNOISE,
                  arc='Arc-Blue.fits',
                  caldir='home$standards/'):
    '''Reduce and calibrate standard star observation with blue CCD'''

    # Bias subtract everything first
    bluebias(image,
             biassec1=biassec1,
             trimsec1=trimsec1,
             biassec2=biassec2,
             trimsec2=trimsec2)
    bluebias(arcs,
             biassec1=biassec1,
             trimsec1=trimsec1,
             biassec2=biassec2,
             trimsec2=trimsec2)
    bluebias(flats,
             biassec1=biassec1,
             trimsec1=trimsec1,
             biassec2=biassec2,
             trimsec2=trimsec2)

    # Create and apply flat-field
    for i in range(len(flats)):
        flats[i] = 'j%s' % flats[i]
    make_flat(flats, outflat, gain=gain, rdnoise=rdnoise)
    iraf.ccdproc('j%s' % image[0],
                 ccdtype='',
                 noproc=no,
                 fixpix=no,
                 overscan=no,
                 trim=no,
                 zerocor=no,
                 darkcor=no,
                 flatcor=yes,
                 illumcor=no,
                 fringecor=no,
                 readcor=no,
                 scancor=no,
                 flat=outflat)
    iraf.ccdproc('j%s' % arcs[0],
                 ccdtype='',
                 noproc=no,
                 fixpix=no,
                 overscan=no,
                 trim=no,
                 zerocor=no,
                 darkcor=no,
                 flatcor=yes,
                 illumcor=no,
                 fringecor=no,
                 readcor=no,
                 scancor=no,
                 flat=outflat)

    # Extract spectrum of standard
    if object == None:
        object = get_head(image, 'OBJECT')
    iraf.apall('j%s' % image[0],
               output=object,
               references='',
               interactive=yes,
               find=yes,
               recenter=yes,
               resize=yes,
               edit=yes,
               trace=yes,
               fittrace=yes,
               extract=yes,
               extras=yes,
               review=no,
               background='fit',
               weights='variance',
               pfit='fit1d',
               readnoise=rdnoise,
               gain=gain)

    # Extract arc and fit wavelength solution
    reference_arc('j%s' % arcs[0], arc, 'j%s' % image[0])

    # Apply wavelength solution to standard
    iraf.refspec(object,
                 references=arc,
                 sort="",
                 group="",
                 override=yes,
                 confirm=no,
                 assign=yes)
    iraf.dispcor(object, '%s.w' % object, confirm=no, listonly=no)

    # Remove absorption features and smooth
    iraf.splot('%s.w' % object, 1, 1)
    iraf.gauss('temp1[*,1,1]', '%s.smooth' % object, 3.0)
    iraf.sarith('%s.w' % object, '/', '%s.smooth' % object, '%s.s' % object)

    # Define bandpasses for standard star calculation
    iraf.standard('%s.s' % object,
                  '%s.std' % object,
                  extinction='onedstds$kpnoextinct.dat',
                  caldir=caldir,
                  observatory='Lick',
                  interact=yes,
                  star_name=object,
                  airmass='',
                  exptime='')

    # Determine sensitivity function
    iraf.sensfunc('%s.std' % object,
                  '%s.sens' % object,
                  extinction='onedstds$kpnoextinct.dat',
                  newextinction='extinct.dat',
                  observatory='Lick',
                  function='legendre',
                  order=3,
                  interactive=yes)

    return
Ejemplo n.º 15
0
def red_standard(image, arcs, flats, object=None, biassec=REDBIAS, 
                 trimsec=REDTRIM, outflat='Flat-Red.fits', gain=REDGAIN,
                 rdnoise=REDRDNOISE, arc='Arc-Red.fits', 
                 caldir='home$standards/'):

    '''Reduce and calibrate standard star observation with red CCD'''

    
    # Bias subtract everything first
    redbias(image, biassec=biassec, trimsec=trimsec)
    redbias(arcs, biassec=biassec, trimsec=trimsec)
    redbias(flats, biassec=biassec, trimsec=trimsec)

    # Create and apply flat-field
    make_flat(flats, outflat, gain=gain, rdnoise=rdnoise)
    iraf.ccdproc(image[0], ccdtype='', noproc=no, fixpix=no, overscan=no, 
                 trim=no, zerocor=no, darkcor=no, flatcor=yes, illumcor=no,
                 fringecor=no, readcor=no, scancor=no, flat=outflat)
    arcimages=','.join(arcs)
    iraf.ccdproc(arcs, ccdtype='', noproc=no, fixpix=no, overscan=no, 
                 trim=no, zerocor=no, darkcor=no, flatcor=yes, illumcor=no,
                 fringecor=no, readcor=no, scancor=no, flat=outflat)

    # Extract spectrum of standard
    if object==None:
        object=get_head(image, 'OBJECT')
    iraf.apall(image[0], output=object, references='', interactive=yes, 
               find=yes, recenter=yes, resize=yes, edit=yes, trace=yes, 
               fittrace=yes, extract=yes, extras=yes, review=no, 
               background='fit', weights='variance', pfit='fit1d', 
               readnoise=rdnoise, gain=gain)

    # Extract arc and fit wavelength solution
    iraf.imarith(arcs[0], '+', arcs[1], 'Arc-Sum.fits')
    reference_arc('Arc-Sum.fits', arc, image[0])

    # Apply wavelength solution to standard
    iraf.refspec(object, references=arc, sort="", group="", override=yes,
                 confirm=no, assign=yes)
    iraf.dispcor(object, '%s.w' % object, confirm=no, listonly=no)

    # Remove absorption features and smooth
    iraf.splot('%s.w' % object, 1, 1)
    iraf.gauss('temp1[*,1,1]', '%s.smooth' % object, 3.0)
    iraf.sarith('%s.w' % object, '/', '%s.smooth' % object, '%s.s' % object)

    # Create and apply telluric correction
    iraf.sarith('%s.w' % object, '/', 'temp1', 'telluric')
    iraf.splot('telluric', 1, 1)
    iraf.telluric('%s.s' % object, '%s.t' % object, 'telluric', xcorr=no,
                  tweakrms=no, interactive=no, sample='6850:6950,7575:7700')

    # Define bandpasses for standard star calculation
    iraf.standard('%s.t' % object, '%s.std' % object, 
                  extinction='onedstds$kpnoextinct.dat', caldir=caldir,
                  observatory='Lick', interact=yes, star_name=object, 
                  airmass='', exptime='')

    # Determine sensitivity function
    iraf.sensfunc('%s.std' % object, '%s.sens' % object, 
                  extinction='onedstds$kpnoextinct.dat', 
                  newextinction='extinct.dat', observatory='Lick',
                  function='legendre', order=3, interactive=yes)

    return
def convolve_images():
    for i in range(nfiles):
        convolved_image = 'g' + files[i]
        gauss(input=files[i], output=convolved_image, sigma=sigma_filter[i])
Ejemplo n.º 17
0
def deimos_standard(standard):
    '''Extract standard star and calculate sensitivit function.'''

    bstd = "%s_01_B" % standard
    rstd = "%s_01_R" % standard

    # Extract standard
    if get_head("%s.fits" % bstd, "SKYSUB"):
        iraf.apall(bstd,
                   output="",
                   inter=yes,
                   find=yes,
                   recenter=yes,
                   resize=yes,
                   edit=yes,
                   trace=yes,
                   fittrace=yes,
                   extract=yes,
                   extras=yes,
                   review=no,
                   background="none")
        iraf.apall(rstd,
                   output="",
                   inter=yes,
                   find=yes,
                   recenter=yes,
                   resize=yes,
                   edit=yes,
                   trace=yes,
                   fittrace=yes,
                   extract=yes,
                   extras=yes,
                   review=no,
                   background="none")
    else:
        iraf.apall(bstd,
                   output="",
                   inter=yes,
                   find=yes,
                   recenter=yes,
                   resize=yes,
                   edit=yes,
                   trace=yes,
                   fittrace=yes,
                   extract=yes,
                   extras=yes,
                   review=no,
                   background="fit")
        iraf.apall(rstd,
                   output="",
                   inter=yes,
                   find=yes,
                   recenter=yes,
                   resize=yes,
                   edit=yes,
                   trace=yes,
                   fittrace=yes,
                   extract=yes,
                   extras=yes,
                   review=no,
                   background="fit")

    # Fit the continuum
    #iraf.continuum("%s.ms" % bstd, output="s%s.ms" % bstd, lines=1, bands=1,
    #               type="fit", sample="*", naverage=1, function="chebyshev",
    #               order=15, low_reject=3.0, high_reject=5.0, niterate=10, grow=1.0,
    #               interac=yes)
    #iraf.continuum("%s.ms" % rstd, output="s%s.ms" % rstd, lines=1, bands=1,
    #               type="fit", sample="*", naverage=1, function="chebyshev",
    #               order=15, low_reject=3.0, high_reject=5.0, niterate=10, grow=1.0,
    #               interac=yes)

    # Create telluric
    iraf.splot("%s.ms" %
               bstd)  # Remove telluric and absorption, save as a%s.ms
    iraf.sarith("%s.ms" % bstd, "/", "a%s.ms" % bstd,
                "telluric.B.%s.fits" % bstd)
    iraf.imreplace("telluric.B.%s.fits" % bstd, 1.0, lower=0.0, upper=0.0)
    iraf.splot("telluric.B.%s.fits" %
               bstd)  # Remove stellar features and resave

    iraf.splot("%s.ms" %
               rstd)  # Remove telluric and absorption, save as a%s.ms
    iraf.sarith("%s.ms" % rstd, "/", "a%s.ms" % rstd,
                "telluric.R.%s.fits" % rstd)
    iraf.imreplace("telluric.R.%s.fits" % rstd, 1.0, lower=0.0, upper=0.0)
    iraf.splot("telluric.R.%s.fits" %
               rstd)  # Remove stellar features and resave

    # Create smoothed standard
    iraf.gauss("a%s.ms[*,1,1]" % bstd, "s%s.ms" % bstd, 5.0)
    iraf.sarith("%s.ms" % bstd, "/", "s%s.ms" % bstd, "ds%s.ms" % bstd)
    iraf.gauss("a%s.ms[*,1,1]" % rstd, "s%s.ms" % rstd, 5.0)
    iraf.sarith("%s.ms" % rstd, "/", "s%s.ms" % rstd, "ds%s.ms" % rstd)

    # Divide through by smoothed standard
    #iraf.sarith("%s.ms" % bstd, "/", "s%s.ms" % bstd, "ds%s.ms" % bstd)
    #iraf.sarith("%s.ms" % rstd, "/", "s%s.ms" % rstd, "ds%s.ms" % rstd)

    # Create and apply telluric correction
    #iraf.splot("%s.ms" % bstd) # Remove telluric, save as a%s.ms
    #iraf.splot("%s.ms" % rstd) # Remove telluric, save as a%s.ms
    #iraf.sarith("%s.ms" % bstd, "/", "a%s.ms" % bstd, "telluric.B.fits")
    #iraf.sarith("%s.ms" % rstd, "/", "a%s.ms" % rstd, "telluric.R.fits")
    #iraf.imreplace("telluric.B.fits", 1.0, lower=0.0, upper=0.0)
    #iraf.imreplace("telluric.R.fits", 1.0, lower=0.0, upper=0.0)
    iraf.telluric("ds%s.ms" % bstd,
                  "tds%s.ms" % bstd,
                  "telluric.B.%s.fits" % bstd,
                  xcorr=no,
                  tweakrms=no,
                  interactive=no,
                  sample='6850:6950,7575:7700')
    iraf.telluric("ds%s.ms" % rstd,
                  "tds%s.ms" % rstd,
                  "telluric.R.%s.fits" % rstd,
                  xcorr=no,
                  tweakrms=no,
                  interactive=no,
                  sample='6850:6950,7575:7700')

    # Define bandpasses for standard star calculation
    iraf.standard("tds%s.ms" % bstd,
                  "%s.B.std" % standard,
                  extinction='home$extinct/maunakeaextinct.dat',
                  caldir='home$standards/',
                  observatory='Keck',
                  interac=yes,
                  star_name=standard,
                  airmass='',
                  exptime='')
    iraf.standard("tds%s.ms" % rstd,
                  "%s.R.std" % standard,
                  extinction='home$extinct/maunakeaextinct.dat',
                  caldir='home$standards/',
                  observatory='Keck',
                  interac=yes,
                  star_name=standard,
                  airmass='',
                  exptime='')

    # Determine sensitivity function
    iraf.sensfunc('%s.B.std' % standard,
                  '%s.B.sens' % standard,
                  extinction='home$extinct/maunakeaextinct.dat',
                  newextinction='extinct.dat',
                  observatory='Keck',
                  function='legendre',
                  order=4,
                  interactive=yes)
    iraf.sensfunc('%s.R.std' % standard,
                  '%s.R.sens' % standard,
                  extinction='home$extinct/maunakeaextinct.dat',
                  newextinction='extinct.dat',
                  observatory='Keck',
                  function='legendre',
                  order=4,
                  interactive=yes)

    return
Ejemplo n.º 18
0
def blue_standard(image, arcs, flats, object=None, biassec1=BLUEBIAS1,
                  trimsec1=BLUETRIM1, biassec2=BLUEBIAS2, 
                  trimsec2=BLUETRIM2, outflat='Flat-Blue.fits', gain=BLUEGAIN,
                  rdnoise=BLUERDNOISE, arc='Arc-Blue.fits', 
                  caldir='home$standards/'):

    '''Reduce and calibrate standard star observation with blue CCD'''
  
    # Bias subtract everything first
    bluebias(image, biassec1=biassec1, trimsec1=trimsec1, biassec2=biassec2,
             trimsec2=trimsec2)
    bluebias(arcs, biassec1=biassec1, trimsec1=trimsec1, biassec2=biassec2,
             trimsec2=trimsec2)
    bluebias(flats, biassec1=biassec1, trimsec1=trimsec1, biassec2=biassec2,
             trimsec2=trimsec2)

    # Create and apply flat-field
    for i in range(len(flats)):
        flats[i]='j%s' % flats[i]
    make_flat(flats, outflat, gain=gain, rdnoise=rdnoise)
    iraf.ccdproc('j%s' % image[0], ccdtype='', noproc=no, fixpix=no, 
                 overscan=no, trim=no, zerocor=no, darkcor=no, flatcor=yes, 
                 illumcor=no, fringecor=no, readcor=no, scancor=no, 
                 flat=outflat)
    iraf.ccdproc('j%s' % arcs[0], ccdtype='', noproc=no, fixpix=no, 
                 overscan=no, trim=no, zerocor=no, darkcor=no, flatcor=yes, 
                 illumcor=no, fringecor=no, readcor=no, scancor=no, 
                 flat=outflat)

    # Extract spectrum of standard
    if object==None:
        object=get_head(image, 'OBJECT')
    iraf.apall('j%s' % image[0], output=object, references='', interactive=yes, 
               find=yes, recenter=yes, resize=yes, edit=yes, trace=yes, 
               fittrace=yes, extract=yes, extras=yes, review=no, 
               background='fit', weights='variance', pfit='fit1d', 
               readnoise=rdnoise, gain=gain)

    # Extract arc and fit wavelength solution
    reference_arc('j%s' % arcs[0], arc, 'j%s' % image[0])

    # Apply wavelength solution to standard
    iraf.refspec(object, references=arc, sort="", group="", override=yes,
                 confirm=no, assign=yes)
    iraf.dispcor(object, '%s.w' % object, confirm=no, listonly=no)

    # Remove absorption features and smooth
    iraf.splot('%s.w' % object, 1, 1)
    iraf.gauss('temp1[*,1,1]', '%s.smooth' % object, 3.0)
    iraf.sarith('%s.w' % object, '/', '%s.smooth' % object, '%s.s' % object)

    # Define bandpasses for standard star calculation
    iraf.standard('%s.s' % object, '%s.std' % object, 
                  extinction='onedstds$kpnoextinct.dat', caldir=caldir,
                  observatory='Lick', interact=yes, star_name=object, 
                  airmass='', exptime='')

    # Determine sensitivity function
    iraf.sensfunc('%s.std' % object, '%s.sens' % object, 
                  extinction='onedstds$kpnoextinct.dat', 
                  newextinction='extinct.dat', observatory='Lick',
                  function='legendre', order=3, interactive=yes)

    return
Ejemplo n.º 19
0
def subract(df_image,shifts=99.99,width_cfhtsm=0.,upperlim=0.04,medphotosc=True,numsources=100,sigmaclip=False,cutout=False):
    print "\n************ Running the subtraction steps ************\n"

    #iraf.imdel('_psf*.fits')
    #iraf.imdel('_model*.fits')
    #iraf.imdel('_df_sub')
    iraf.imdel('_res*.fits')
    iraf.imdel('cc_images')
    iraf.imdel('_model_sh')
    iraf.imdel('_model_sc')
    iraf.imdel('_model_mask')
    iraf.imdel('_model_maskb')
    
    'shift the images so they have the same physical coordinates'
    if shifts[0]==99.99:
        print('\n**** Calculating shifts... ****\n')
        iraf.stsdas.analysis.dither.crossdriz('_df_sub.fits','_model.fits','cc_images',dinp='no',dref='no')
        iraf.stsdas.analysis.dither.shiftfind('cc_images.fits','shift_values')
        x_shift=0
        y_shift=0
        with open('shift_values','r') as datafile:
            line = datafile.read().split()
            x_shift = float(line[2])
            y_shift = float(line[4])
        print('Shifting model image by x and y: '+str(x_shift)+','+str(y_shift))
         
        iraf.imshift('_model','_model_sh',0-x_shift,0-y_shift)
    else:
        print('Shifting model image by x and y: '+str(shifts[0])+','+str(shifts[1]))
        iraf.imshift('_model','_model_sh',shifts[0],shifts[1])

    'scale the model so that roughly the same as the _df_sub image'
#    if usemodelpsf:
#        iraf.imarith('_model_sh','/',16.,'_model_sc')
#    else:
    'the photometric step, matching the images to each other. '
    'in principle this comes from the headers - both datasets are calibrated,'
    'so this multiplication should be something like 10^((ZP_DF - ZP_CFHT)/-2.5)'
    '(perhaps with a correction for the difference in pixel size - depending'
    'on what wregister does - so another factor (PIX_SIZE_DF)^2/(PIX_SIZE_CFHT)^2'
    
    avgphotosc,medianphotosc = getphotosc('_model_sh.fits','_df_sub.fits',numsources=numsources,sigmaclip=sigmaclip,cutout=cutout)
    if medphotosc:
        photosc = medianphotosc
        print 'Using median calculated photosc: %s'%photosc
    else:
        photosc = avgphotosc
        print 'Using average calculated photosc: %s'%photosc
    iraf.imarith('_model_sh','*',photosc,'_model_sc')

    iraf.imdel('_df_ga.fits')
    
    'correction for the smoothing that was applied to the CFHT'
    if width_cfhtsm != 0:
        iraf.gauss('_df_sub','_df_ga',width_cfhtsm) # iraf.gauss('%s'%df_image,'_df_ga',width_cfhtsm)
    else:
        print 'WARNING: No smoothing applied to the dragonfly image before subtracting the model.'
        iraf.imcopy('_df_sub.fits','_df_ga.fits')

    'subtract the model from the dragonfly cutout'
    iraf.imarith('_df_ga','-','_model_sc','_res')

    'duplicate the residual so that we can redo the masking step later'
    iraf.imcopy('_res.fits','_res_org.fits')

    'mask the image to get block out stuff that didnt subtract nicely'
    mask('_res',upperlim=upperlim)

    return None
Ejemplo n.º 20
0
def red_standard(image,
                 arcs,
                 flats,
                 object=None,
                 biassec=REDBIAS,
                 trimsec=REDTRIM,
                 outflat='Flat-Red.fits',
                 gain=REDGAIN,
                 rdnoise=REDRDNOISE,
                 arc='Arc-Red.fits',
                 caldir='home$standards/'):
    '''Reduce and calibrate standard star observation with red CCD'''

    # Bias subtract everything first
    redbias(image, biassec=biassec, trimsec=trimsec)
    redbias(arcs, biassec=biassec, trimsec=trimsec)
    redbias(flats, biassec=biassec, trimsec=trimsec)

    # Create and apply flat-field
    make_flat(flats, outflat, gain=gain, rdnoise=rdnoise)
    iraf.ccdproc(image[0],
                 ccdtype='',
                 noproc=no,
                 fixpix=no,
                 overscan=no,
                 trim=no,
                 zerocor=no,
                 darkcor=no,
                 flatcor=yes,
                 illumcor=no,
                 fringecor=no,
                 readcor=no,
                 scancor=no,
                 flat=outflat)
    arcimages = ','.join(arcs)
    iraf.ccdproc(arcs,
                 ccdtype='',
                 noproc=no,
                 fixpix=no,
                 overscan=no,
                 trim=no,
                 zerocor=no,
                 darkcor=no,
                 flatcor=yes,
                 illumcor=no,
                 fringecor=no,
                 readcor=no,
                 scancor=no,
                 flat=outflat)

    # Extract spectrum of standard
    if object == None:
        object = get_head(image, 'OBJECT')
    iraf.apall(image[0],
               output=object,
               references='',
               interactive=yes,
               find=yes,
               recenter=yes,
               resize=yes,
               edit=yes,
               trace=yes,
               fittrace=yes,
               extract=yes,
               extras=yes,
               review=no,
               background='fit',
               weights='variance',
               pfit='fit1d',
               readnoise=rdnoise,
               gain=gain)

    # Extract arc and fit wavelength solution
    iraf.imarith(arcs[0], '+', arcs[1], 'Arc-Sum.fits')
    reference_arc('Arc-Sum.fits', arc, image[0])

    # Apply wavelength solution to standard
    iraf.refspec(object,
                 references=arc,
                 sort="",
                 group="",
                 override=yes,
                 confirm=no,
                 assign=yes)
    iraf.dispcor(object, '%s.w' % object, confirm=no, listonly=no)

    # Remove absorption features and smooth
    iraf.splot('%s.w' % object, 1, 1)
    iraf.gauss('temp1[*,1,1]', '%s.smooth' % object, 3.0)
    iraf.sarith('%s.w' % object, '/', '%s.smooth' % object, '%s.s' % object)

    # Create and apply telluric correction
    iraf.sarith('%s.w' % object, '/', 'temp1', 'telluric')
    iraf.splot('telluric', 1, 1)
    iraf.telluric('%s.s' % object,
                  '%s.t' % object,
                  'telluric',
                  xcorr=no,
                  tweakrms=no,
                  interactive=no,
                  sample='6850:6950,7575:7700')

    # Define bandpasses for standard star calculation
    iraf.standard('%s.t' % object,
                  '%s.std' % object,
                  extinction='onedstds$kpnoextinct.dat',
                  caldir=caldir,
                  observatory='Lick',
                  interact=yes,
                  star_name=object,
                  airmass='',
                  exptime='')

    # Determine sensitivity function
    iraf.sensfunc('%s.std' % object,
                  '%s.sens' % object,
                  extinction='onedstds$kpnoextinct.dat',
                  newextinction='extinct.dat',
                  observatory='Lick',
                  function='legendre',
                  order=3,
                  interactive=yes)

    return