Ejemplo n.º 1
0
def getPrimaryKeyword(filename, keyword):

    iraf.keypar(filename, keyword)
    value = iraf.keypar.value
    if value == '':
        value = None

    return value
Ejemplo n.º 2
0
def findNumExt(filename):
    # Open the file given by 'rootname' and return the
    # number of extensions written out for the observation.
    # It will be up to the Exposure classes to determine how
    # many IMSETS they have to work with.
    #
    # Only look in the primary extension or first group.
    iraf.keypar(filename, 'NEXTEND', silent='yes')

    # This may need to be changed to support simple image without
    # extensions (such as simple FITS images).
    if iraf.keypar.value == 0 or iraf.keypar.value == '':
        raise ValueError, "There are NO extensions to be read in this image!"

    return iraf.keypar.value
Ejemplo n.º 3
0
def getChipId(rootname):

    chip = 1
    _found = yes

    try:
        iraf.keypar(rootname, "CCDCHIP", silent='yes')
        chip = int(iraf.keypar.value)
    except ValueError:
        chip = 1
        _found = no

    if _found == no:
        try:
            iraf.keypar(rootname, "DETECTOR", silent='yes')
            chip = int(iraf.keypar.value)
        except ValueError:
            chip = 1

    return chip
Ejemplo n.º 4
0
    def __init__(self, image=None, inimage=None):

        if image == None:
            self.scale = 1.0
            self.coeffs = None
            self.lam = 555.0
            self.xsh = 0.0
            self.ysh = 0.0
            self.rot = 0.0
            self.shft_un = "input"
            self.shft_fr = "input"
            self.align = "center"
            self.xgeoim = ""
            self.ygeoim = ""
            self.d2xscale = 0.0
            self.d2yscale = 0.0
            self.d2xsh = 0.0
            self.d2ysh = 0.0
            self.d2rot = 0.0
            self.d2shft_fr = "output"
        else:

            # Read geometric parameters from a header using an image name as
            # the key

            found = FALSE

            # First search for the entry for this image
            i = 1
            while i < MaxImages:
                datkey = 'D%3iDATA' % i
                datkey = datkey.replace(' ', '0')

                iraf.keypar(image, datkey, silent='yes')

                # If we can't read this no point considering
                if iraf.keypar.value == '':
                    break

                # If we have a match set flag and leave
                if iraf.keypar.value == inimage:
                    found = TRUE
                    break

                i += 1

            if not found:
                raise Exception(
                    "Failed to get keyword information from header.")

            # Now we know that the selected image is present we can
            # get all the other parameters - we don't check whether this
            # succeeds, if it doesn't let it crash
            stem = datkey[:4]

            iraf.keypar(image, stem + "SCAL", silent='yes')
            self.scale = float(iraf.keypar.value)

            iraf.keypar(image, stem + "COEF", silent='yes')
            self.coeffs = iraf.keypar.value
            # Check for existence
            if fileutil.findFile(self.coeffs) == FALSE:
                try:
                    print(
                        '\n-Coeffs file not found.  Trying to reproduce them using PyDrizzle...'
                    )
                    # Try to generate the coeffs file automatically
                    indx = inimage.find('[')
                    p = pydrizzle.PyDrizzle(inimage[:indx],
                                            bits_single=None,
                                            bits_final=None,
                                            updatewcs=FALSE)
                    del p
                except:
                    print("! Cannot access coefficients file. (", self.coeffs,
                          ")")
                    raise Exception("File missing or inaccessible.")

            iraf.keypar(image, stem + "LAM", silent='yes')
            if iraf.keypar.value != '':
                self.lam = float(iraf.keypar.value)
            else:
                self.lam = 555.0

            iraf.keypar(image, stem + "XSH", silent='yes')
            self.xsh = float(iraf.keypar.value)

            iraf.keypar(image, stem + "YSH", silent='yes')
            self.ysh = float(iraf.keypar.value)

            iraf.keypar(image, stem + "ROT", silent='yes')
            self.rot = float(iraf.keypar.value)

            iraf.keypar(image, stem + "SFTU", silent='yes')
            self.shft_un = iraf.keypar.value

            iraf.keypar(image, stem + "SFTF", silent='yes')
            self.shft_fr = iraf.keypar.value

            iraf.keypar(image, stem + "XGIM", silent='yes')
            self.xgeoim = iraf.keypar.value
            indx = self.xgeoim.find('[')
            # Check for existence
            if fileutil.findFile(
                    self.xgeoim[:indx]) == FALSE and self.xgeoim != '':
                print("! Warning, cannot access X distortion correction image")
                print(" continuing without it. (", self.xgeoim, ")")
                self.xgeoim = ''

            iraf.keypar(image, stem + "YGIM", silent='yes')
            self.ygeoim = iraf.keypar.value
            indx = self.ygeoim.find('[')
            # Check for existence
            if fileutil.findFile(
                    self.ygeoim[:indx]) == FALSE and self.ygeoim != '':
                print("! Warning, cannot access Y distortion correction image")
                print(" continuing without it. (", self.ygeoim, ")")
                self.ygeoim = ''

            # The case of the "align" parameter is more tricky, we
            # have to deduce it from INXC keyword
            iraf.keypar(image, stem + "INXC", silent='yes')
            inxc = float(iraf.keypar.value)

            # Need the X and Y dimensions as well - both input and
            # output
            iraf.keypar(inimage, 'i_naxis1', silent='yes')
            xdim = int(iraf.keypar.value)
            iraf.keypar(inimage, 'i_naxis2', silent='yes')
            ydim = int(iraf.keypar.value)

            self.nxin = xdim
            self.nyin = ydim

            iraf.keypar(image, 'i_naxis1', silent='yes')
            xdim = int(iraf.keypar.value)
            iraf.keypar(image, 'i_naxis2', silent='yes')
            ydim = int(iraf.keypar.value)

            self.nxout = xdim
            self.nyout = ydim

            if abs(inxc - float(xdim / 2) - 0.5) < 1e-4:
                self.align = 'corner'
            else:
                self.align = 'center'

            # Check for the presence of secondary parameters
            iraf.keypar(image, stem + "SECP", silent='yes')
            if iraf.keypar.value == "yes":
                raise Exception(
                    "Sorry, this version does NOT support secondary parameters."
                )
            else:
                self.secp = FALSE
Ejemplo n.º 5
0
    def __init__(self, rootname, shape=None):
        # Initialize wcs dictionaries:
        #   wcsdef - default values for new images
        #   wcstrans - translation table from header keyword to attribute
        self.wcsdef = {
            'crpix1': 0.0,
            'crpix2': 0.0,
            'crval1': 0.0,
            'crval2': 0.0,
            'cd11': 1.0,
            'cd12': 1.0,
            'cd21': 1.0,
            'cd22': 1.0,
            'orient': 1.0,
            'naxis1': 0,
            'naxis2': 0,
            'pscale': 1.0
        }
        self.wcstrans = {
            'CRPIX1': 'crpix1',
            'CRPIX2': 'crpix2',
            'CRVAL1': 'crval1',
            'CRVAL2': 'crval2',
            'CD1_1': 'cd11',
            'CD1_2': 'cd12',
            'CD2_1': 'cd21',
            'CD2_2': 'cd22',
            'ORIENTAT': 'orient',
            'NAXIS1': 'naxis1',
            'NAXIS2': 'naxis2',
            'pixel scale': 'pscale'
        }
        # Now, read in the CRPIX1/2, CRVAL1/2, CD1/2_1/2 keywords.
        # Simplistic, but easy to understand what you are asking for.

        _exists = yes
        if rootname != None:
            self.rootname = rootname
        else:
            self.rootname = 'New'
        # Look for extension specification in rootname
        _indx = string.find(self.rootname, '[')
        # If none are found, use entire rootname
        if _indx < 0:
            _indx = len(self.rootname)

        #pdb.set_trace()
        # Determine whether we are working with a new image or not.
        _filename = self.rootname[:_indx]
        _dirindx = string.rfind(_filename, os.sep)
        _logindx = string.rfind(_filename, '$')
        # Check to see if there is a path pre-pended to filename
        if _dirindx < 0 and _logindx < 0:
            # No path...
            _dir = None
            _rootname = _filename

        else:
            # Path specified is pulled out, rootname found seperately.
            if _dirindx < 0: _dirindx = len(_filename)
            _dir = _filename[:_dirindx]
            _logindx = string.rfind(_dir, '$')
            if _logindx > 0:
                # We have an IRAF logical given in path that needs expanding
                _dir = iraf.osfn(_dir)

            _rootname = _filename[_dirindx + 1:]
            _filename = _dir + os.sep + _rootname

        _exists = fileutil.checkFileExists(_rootname, directory=_dir)

        if string.find(_filename, '.fits') > 0:
            _fits = yes
        else:
            _fits = no

        if _exists == yes and _fits == yes:
            _fimg = pyfits.open(_filename)
            # Extract extnum
            if _indx > 0:
                _indx2 = string.find(self.rootname[_indx + 1:], ']')
                if self.rootname[_indx + 1:_indx + _indx2 + 1] in list(
                        string.digits):
                    # We were given an extension number directly
                    extnum = int(self.rootname[_indx + 1:_indx + _indx2 + 1])
                else:
                    # Look for extension with given name
                    _indxc = string.find(self.rootname[_indx + 1:], ',')
                    if _indxc < 0:
                        # No EXTVER number given, so use first occurance of
                        # extension with specified EXTNAME
                        extnum = self.rootname[_indx + 1:_indx + _indx2 + 1]
                    else:
                        # extract EXTNAME,EXTVER number and return extension number
                        _extname = self.rootname[_indx + 1:_indx + _indxc + 1]
                        _extn = int(self.rootname[_indx + _indxc + 2:_indx +
                                                  _indx2 + 1])

                        extnum = fileutil.findExtname(_fimg,
                                                      _extname,
                                                      extver=_extn)

            # Initialize WCS object with keyword values...
            try:
                for key in self.wcstrans.keys():
                    _dkey = self.wcstrans[key]
                    if _dkey != 'pscale':
                        self.__dict__[_dkey] = _fimg[extnum].header[key]

                self.new = no

            except:
                raise IOError, 'Image %s does not contain valid WCS keywords!' % self.rootname
            _fimg.close()
            del _fimg
        elif _exists == yes and _fits == no:
            # Initialize WCS object with keyword values...
            try:
                iraf.keypar(self.rootname, 'i_naxis1', silent='yes')
                self.naxis1 = int(iraf.keypar.value)
                iraf.keypar(self.rootname, 'i_naxis2', silent='yes')
                self.naxis2 = int(iraf.keypar.value)

                for key in self.wcstrans.keys():
                    _dkey = self.wcstrans[key]
                    if _dkey != 'pscale' and _dkey != 'naxis1' and _dkey != 'naxis2':
                        iraf.keypar(self.rootname, key, silent='yes')
                        self.__dict__[_dkey] = float(iraf.keypar.value)

                self.new = no

            except:
                raise IOError, 'Image %s does not contain valid WCS keywords!' % self.rootname

        else:
            # or set default values...
            self.new = yes
            for key in self.wcsdef.keys():
                self.__dict__[key] = self.wcsdef[key]
            if shape != None:
                # ... and update with user values.
                self.naxis1 = int(shape[0])
                self.naxis2 = int(shape[1])
                self.pscale = float(shape[2])

        # Set up a true CD array which can be used numerically
        #self.cd = array([[self.cd11,self.cd12],[self.cd21,self.cd22]])

        if shape == None:
            self.pscale = N.sqrt(
                N.power(self.cd11, 2) + N.power(self.cd21, 2)) * 3600.
        # Establish an attribute for the linearized orient
        # defined as the orientation of the CD after applying the default
        # distortion correction.
        self._orient_lin = 0.
Ejemplo n.º 6
0
def getIDCFile(filename, keyword=None, dir=None):
    # Open the primary header of the file and read the name of
    # the IDCTAB.
    # Parameters:
    #   filename -  filename of primary extension to read IDCTAB info
    #
    #   keyword(optional) - header keyword with name of IDCTAB
    #            --OR-- 'HEADER' if need to build IDCTAB name from scratch
    #           (default value: 'IDCTAB')
    #   dir(optional) - directory with default drizzle coeffs tables
    #                   (default value: 'drizzle$coeffs'
    #
    # This function needs to be generalized to support
    # keyword='HEADER', as would be the case for WFPC2 data.
    #

    if string.lower(keyword) == 'idctab':
        # keyword specifies header keyword with IDCTAB name
        try:
            iraf.keypar(filename, keyword, silent='yes')
            idcfile = iraf.keypar.value
        except:
            print 'Warning: No IDCTAB specified in header!'
            idcfile = None
    else:
        # Need to build IDCTAB filename from scratch
        if dir == None:
            default_dir = 'drizzle$coeffs/'
        else:
            default_dir = dir

        instrument = getPrimaryKeyword(filename, 'INSTRUME')
        detector = getPrimaryKeyword(filename, 'DETECTOR')

        if instrument == 'WFPC2':
            if detector == '1':
                detname = 'pc'
            else:
                detname = 'wf'
            idcfile = default_dir + detname + detector + '-' + string.lower(
                keyword)

        elif instrument == 'STIS':
            idcfile = default_dir + 'stis-' + string.lower(detector)

        elif instrument == 'NICMOS':
            camera = getPrimaryKeyword(filename, 'CAMERA')
            if camera != None:
                idcfile = default_dir + 'nic-' + repr(camera)
            else:
                idcfile = None
        else:
            idcfile = None

    # Account for possible absence of IDCTAB name in header
    if idcfile == 'N/A':
        idcfile = None

    # Now we need to recursively expand any IRAF symbols to full paths...
    indx = 1
    while indx > 0:
        indx = string.find(idcfile, '$')
        if indx > 0:
            fullpath = iraf.envget(idcfile[:indx])
            idcfile = fullpath + idcfile[indx + 1:]

    return idcfile