Esempio n. 1
0
def put_zeropt(file, zeropt, photo='yes'):
    import pyfits

    # Open thr child info, update mode
    f = pyfits.open(file, mode="update")  # open a FITS file
    hdr = f[0].header  # the primary HDU header

    print("# Updating %s with ZP=%s as in SExtractor, photo:%s" %
          (file, zeropt, photo),
          file=sys.stderr)

    after = "DATE"

    c = {}
    if photo == 'yes':
        c['ZEROPT'] = pyfits.Card("ZEROPT", zeropt,
                                  "Computed ZEROPOINT AB mags/sec")
        c['PHOTOM'] = pyfits.Card("PHOTOM", 1,
                                  "Photometric quality 1=photo/0=not")
    else:
        c['ZEROPT'] = pyfits.Card("ZEROPT", zeropt,
                                  "Non-photo ZEROPOINT AB mags/sec")
        c['PHOTOM'] = pyfits.Card("PHOTOM", 0,
                                  "Photometric quality 1=photo/0=not")

    for key in list(c.keys()):
        c[key].verify()
        hdr.update(key, c[key].value, c[key].comment, after=after)

    # Close the file
    #f.verify('silentfix')
    f.verify('fix')
    #f.verify('ignore')
    f.close()
    return
Esempio n. 2
0
def copy_header(header):
    header_dict = dict(header)
    dtype = get_dtype(header)
    cards = list()
    for k in header_dict:
        try:
            cards.append(pyfits.Card(key=k, value=header_dict[k]))
        except (ValueError):
            try:
                cards.append(pyfits.Card(key=k, value=float(header_dict[k])))
            except (ValueError):
                pass
    return pyfits.Header(cards=cards)
Esempio n. 3
0
def fixHeader(fpath, list):
    """Adjust the keyword value pairs of a header of an image.
    This function does this 'in place', by just overwriting the
    old file with the new one. list is a list of tuples which are
    (keyword,value) pairs.
    """
    curdir = os.getcwd()
    path, file = os.path.split(fpath)
    if path:
        os.chdir(path)

    oldfits = pyfits.open(file, "update")
    if len(oldfits) > 1:
        raise IOError, "file is not a simple fits file."

    for keyword, value in list:
        oldfits[0].header.update(keyword, value)

    oldfits[0].header.update('COMMENT',
                             'fUtil function call to adjust keyword values.')
    index = oldfits[0].header.ascard.index_of('COMMENT')

    for keyword, value in list:
        index += 1
        card = pyfits.Card('COMMENT', value=keyword + ' ' + str(value))
        oldfits[0].header.ascard.insert(index, card)
    oldfits.close()
    os.chdir(curdir)
    return
def gal_header(center, major_axes, galactic=True):

    values = [
            ["NAXIS",  2,          ],

            ["NAXIS1", IMAGE_SIZE,       ],
            ["NAXIS2", IMAGE_SIZE,       ],

            ["CTYPE1", 'GLON-ZEA' if galactic else 'RA---ZEA' ],
            ["CTYPE2", 'GLAT-ZEA' if galactic else 'DEC--ZEA' ],

            ["CRPIX1", IMAGE_SIZE/2. + 0.5,       ],
            ["CRPIX2", IMAGE_SIZE/2. + 0.5,       ],

            ["CRVAL1", center.l() if galactic else center.ra(),        ],
            ["CRVAL2", center.b() if galactic else center.dec(),       ],

            ["CDELT1", -3.*major_axes/IMAGE_SIZE,       ],
            ["CDELT2", 3.*major_axes/IMAGE_SIZE,        ],
    ]

    if galactic is False:
        values += [
            ['RADECSYS','FK5'],
            ['EQUINOX',2000],
        ]


    cards = [pyfits.Card(*i) for i in values]

    header=pyfits.Header(cards=cards)

    return header
Esempio n. 5
0
def fits2fits(infile, outfile, verbose=False, fix_idr=False):
    """
    Returns: error string, or None on success.
    """
    if fix_idr:
        from astrometry.util.fix_sdss_idr import fix_sdss_idr

    # Read input file.
    fitsin = pyfits.open(infile)
    # Print out info about input file.
    if verbose:
        fitsin.info()

    for i, hdu in enumerate(fitsin):
        if fix_idr:
            hdu = fitsin[i] = fix_sdss_idr(hdu)
        # verify() fails when a keywords contains invalid characters,
        # so go through the primary header and fix them by converting invalid
        # characters to '_'
        hdr = hdu.header
        logging.info('Header has %i cards' % len(hdr))
        # allowed characters (FITS standard section 5.1.2.1)
        pat = re.compile(r'[^A-Z0-9_\-]')

        newcards = []
        for c in hdr.ascard:
            k = c.keyword
            # new keyword:
            knew = pat.sub('_', k)
            if k != knew:
                logging.debug('Replacing illegal keyword %s by %s' % (k, knew))
                # it seems pyfits is not clever enough to notice this...
                if len(knew) > 8:
                    knew = 'HIERARCH ' + knew
            newcards.append(pyfits.Card(keyword=knew, value=c.value,
                                        comment=c.comment))
        hdu.header = pyfits.Header(newcards)
            
        # Fix input header
        hdu.verify('fix')

        # UGH!  Work around stupid pyfits handling of scaled data...
        # (it fails to round-trip scaled data correctly!)
        bzero = hdr.get('BZERO', None)
        bscale = hdr.get('BSCALE', None)
        if (bzero is not None and bscale is not None
            and (bzero != 0. or bscale != 1.)):
            logging.debug('Scaling to bzero=%g, bscale=%g' % (bzero, bscale))
            hdu.scale('int16', '', bscale, bzero)

    # Describe output file we're about to write...
    if verbose:
        print 'Outputting:'
        fitsin.info()

    try:
        pyfits_writeto(fitsin, outfile, output_verify='warn')
    except pyfits.VerifyError, ve:
        return ('Verification of output file failed: your FITS file is probably too broken to automatically fix.' +
                '  Error message is:' + str(ve))
Esempio n. 6
0
def add_nonstructural_headers(fromhdr, tohdr):
    for card in fromhdr.ascardlist():
        if ((card.key in [
                'SIMPLE',
                'XTENSION',
                'BITPIX',
                'END',
                'PCOUNT',
                'GCOUNT',
                'TFIELDS',
        ]) or card.key.startswith('NAXIS') or card.key.startswith('TTYPE')
                or card.key.startswith('TFORM')):
            #card.key.startswith('TUNIT') or
            #card.key.startswith('TDISP')):
            #print 'skipping card', card.key
            continue
        #if tohdr.has_key(card.key):
        #   #print 'skipping existing card', card.key
        #   continue
        #print 'adding card', card.key
        #tohdr.update(card.key, card.value, card.comment, before='END')
        #tohdr.ascardlist().append(
        cl = tohdr.ascardlist()
        if 'END' in cl.keys():
            i = cl.index_of('END')
        else:
            i = len(cl)
        cl.insert(i, pyfits.Card(card.key, card.value, card.comment))
Esempio n. 7
0
def card_from_string(str):
    """
    card_from_string(str):
        Return a pyfits 'Card' based on the input 'str', which should
            be an 80-character 'line' from a FITS header.
    """
    card = pyfits.Card()
    return card.fromstring(str)
Esempio n. 8
0
def add_airmass(filename, airmass):

    import pyfits
    c = pyfits.Card("AIRMASS", airmass, "Computed Stacked Mean Airmass")
    f = pyfits.open(filename, mode="update")
    #f[0].header.ascardlist().append(c)
    f[0].header.update(c.key, c.value, c.comment)
    f.close()
Esempio n. 9
0
def create_header(coord, radius, proj='ZEA', npix=30):
    """ Create a header a new image """
    gal = coord.name == 'galactic'
    values = [
        [
            "NAXIS",
            2,
        ],
        [
            "NAXIS1",
            npix,
        ],
        [
            "NAXIS2",
            npix,
        ],
        ["CTYPE1", 'GLON-%s' % proj if gal else 'RA---%s' % proj],
        ["CTYPE2", 'GLAT-%s' % proj if gal else 'DEC--%s' % proj],
        [
            "CRPIX1",
            npix / 2. + 0.5,
        ],
        [
            "CRPIX2",
            npix / 2. + 0.5,
        ],
        [
            "CRVAL1",
            coord.l.deg if gal else coord.ra.deg,
        ],
        [
            "CRVAL2",
            coord.b.deg if gal else coord.dec.deg,
        ],
        [
            "CDELT1",
            -3. * radius / npix,
        ],
        [
            "CDELT2",
            3. * radius / npix,
        ],
    ]

    if not gal:
        values += [
            ['RADECSYS', 'FK5'],
            ['EQUINOX', 2000],
        ]

    cards = [pyfits.Card(*i) for i in values]
    header = pyfits.Header(cards=cards)

    return header
Esempio n. 10
0
def put_scaled_head(file):

    import pyfits

    # Open the file, update mode
    f = pyfits.open(file, mode="update")  # open a FITS file
    hdr = f[0].header  # the primary HDU header

    #print >>sys.stderr,"# Updating %s with EXPTIME=%s after SWarp" % (file,exptime)
    c = pyfits.Card("FSCALED", True,
                    "Has the flux been scaled in individual frames")
    c.verify()
    hdr.update('FSCALED', c.value, c.comment)  #,after=after)

    # Close the file
    f.verify('fix')
    f.close()
    return
Esempio n. 11
0
def put_exptime(file, exptime):

    import pyfits

    # Open the file, update mode
    f = pyfits.open(file, mode="update")  # open a FITS file
    hdr = f[0].header  # the primary HDU header

    print("# Updating %s with EXPTIME=%s after SWarp" % (file, exptime),
          file=sys.stderr)
    c = pyfits.Card("EXPTIME", exptime, "After SWarp equivalent exptime (sec)")
    c.verify()
    hdr.update('EXPTIME', c.value, c.comment)  #,after=after)

    # Close the file
    f.verify('fix')
    f.close()
    return
Esempio n. 12
0
def parseCards(aString):
    """returns a list of pyfits Cards parsed from aString.

	This will raise a ValueError if aString's length is not divisible by 80.  
	It may also raise pyfits errors for malformed cards.

	Empty (i.e., all-whitespace) cards are ignored.  If an END card is
	encountered processing is aborted.
	"""
    cards = []
    if len(aString) % CARD_SIZE:
        raise ValueError("parseCards argument has impossible length %s" %
                         (len(aString)))
    for offset in range(0, len(aString), CARD_SIZE):
        rawCard = aString[offset:offset + CARD_SIZE]
        if rawCard == END_CARD:
            break
        if not rawCard.strip():
            continue
        cards.append(pyfits.Card().fromstring(rawCard))
    return cards
Esempio n. 13
0
def copy_header(hdr):

    try:
        del hdr['TELESCOPE']
    except KeyError:
        a = 1
    
    try:
        del hdr['INSTRUMENT']
    except KeyError:
        a = 1
    
    try:
        del hdr['REST FREQUENCY']
    except KeyError:
        a = 1
    
    try:
        del hdr['TRANSITION']
    except KeyError:
        a = 1

    hdr_cardlist = hdr.ascard
    ncards = len(hdr_cardlist)
    
    new_hdr_cardlist = pyfits.CardList()

    for i in range(0, ncards):

        new_hdr_cardlist.append(pyfits.Card( 
                                    copy.deepcopy(hdr_cardlist[i].key), 
                                    copy.deepcopy(hdr_cardlist[i].value), 
                                    copy.deepcopy(hdr_cardlist[i].comment) 
                                            )
                                )
    
    new_hdr = pyfits.Header(new_hdr_cardlist)

    return new_hdr
Esempio n. 14
0
    def create_primary_hdu(self, config=None):
        """
        Create the primary hdu. Checks to see if one exists before proceeding.
        Args:
            config (dict): The configuration from a configuration file, containing the header information
        Returns:
            pyfits.PrimaryHDU populated with header data from config
        """
        if not config: config = self.config
        t0 = time.time()
        for hdu in self.hdus:
            if isinstance(hdu, pyfits.PrimaryHDU):
                self.logger.debug("There is already a primary HDU!")
                return

        hdu = pyfits.PrimaryHDU()
        existing_keys = hdu.header.keys()
        for header_line in config['header_primary']:
            card = pyfits.Card().fromstring(header_line)
            card.verify()
            if card.keyword in existing_keys:
                continue
                # del hdu.header[card.keyword]
            hdu.header.append(card)

        date_str = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S")
        hdu.header['DATE'] = date_str
        # self.logger.debug(counter)
        # keys = hdu.header.keys()
        # keys.sort()
        # self.logger.debug(len(keys))
        # self.logger.debug(keys)

        self.hdus.append(hdu)
        self.logger.debug(
            "Took {:.4f} seconds to generated primary HDU".format(time.time() -
                                                                  t0))
        return hdu
Esempio n. 15
0
def write(Maps, file_name, feedback=2):
    """Write a map to fits file.

    Map should be a map_data.MapData object.
    """

    # If only a single Map was passed, make it iterable.
    if not hasattr(Maps, '__iter__'):
        Maps = (Maps, )
    # First create a primary with the history and such:
    prihdu = pyfits.PrimaryHDU()
    # Add history to the primary.
    fname_abbr = ku.abbreviate_file_path(file_name)
    # Add final history entry and store in the primary header.
    history = base_data.merge_histories(*Maps)
    history.add('Written to file.', 'File name: ' + fname_abbr)
    bf.write_history_header(prihdu.header, history)
    list_of_hdus = [prihdu]

    for ii, Map in enumerate(Maps):
        # Creat an image HDU.
        map = sp.array(ma.filled(Map.data, float('nan')))
        imhdu = pyfits.ImageHDU(sp.swapaxes(map, 0, 2), name='MAP%d' % ii)

        # Add extra data to the HDU
        for key in Map.field.iterkeys():
            if Map.field_axes[key] != ():
                raise ce.DataError('Only 0D data can be written to a Fits Map '
                                   'Header.')
            card = pyfits.Card(key, Map.field[key].item())
            imhdu.header.ascardlist().append(card)
        list_of_hdus.append(imhdu)

    # Creat the HDU list and write to file.
    hdulist = pyfits.HDUList(list_of_hdus)
    hdulist.writeto(file_name, clobber=True)
    if feedback > 0:
        print 'Wrote data to file: ' + fname_abbr
Esempio n. 16
0
def add_nonstructural_headers(fromhdr, tohdr):
    for card in fromhdr.cards:
        if ((card.keyword in [
                'SIMPLE',
                'XTENSION',
                'BITPIX',
                'END',
                'PCOUNT',
                'GCOUNT',
                'TFIELDS',
        ]) or card.keyword.startswith('NAXIS')
                or card.keyword.startswith('TTYPE')
                or card.keyword.startswith('TFORM')):
            #card.key.startswith('TUNIT') or
            #card.key.startswith('TDISP')):
            #print('skipping card', card.key)
            continue
        cl = tohdr
        if 'END' in cl.keys():
            i = cl.index_of('END')
        else:
            i = len(cl)
        cl.insert(i, pyfits.Card(card.keyword, card.value, card.comment))
Esempio n. 17
0
def sortHeaders(header,
                commentFilter=None,
                historyFilter=None,
                cardSequence=None):
    """returns a pyfits header with "real" cards first, then history, then
	comment cards.

	Blanks in the input are discarded, and one blank each is added in
	between the sections of real cards, history and comments.

	Header can be an iterable yielding Cards or a pyfits header.

	Duplicate history or comment entries will be swallowed.

	cardSequence, if present, is a sequence of (item, mandatory) pairs.
	There item can be a card name, in which case the corresponding
	card will be inserted at this point in the sequence.  If mandatory is
	True, a missing card is an error.  Keywords already in
	fitstools.STANDARD_CARD_SEQUENCE are ignored.

	Item can also a pyfits.Card instance; it will be put into the header
	as-is.

	As a shortcut, a sequence item may be something else then a tuple;
	it will then be combined with a False to make one.

	These days, if you think you need this, have a look at 
	fitstricks.makeHeaderFromTemplate first.
	"""
    commentCs, historyCs, realCs = [], [], []
    if hasattr(header, "ascardlist"):
        iterable = header.ascardlist()
    else:
        iterable = header
    for card in iterable:
        if card.key == "COMMENT":
            commentCs.append(card)
        elif card.key == "HISTORY":
            historyCs.append(card)
        else:
            realCs.append(card)

    newCards = []
    for card in realCs:
        newCards.append(card)

    historySeen = set()
    if historyCs:
        newCards.append(pyfits.Card(key=""))
    for card in historyCs:
        if historyFilter is None or historyFilter(card.value):
            if card.value not in historySeen:
                newCards.append(card)
                historySeen.add(card.value)

    commentsSeen = set()
    if commentCs:
        newCards.append(pyfits.Card(key=""))
    for card in commentCs:
        if commentFilter is None or commentFilter(card.value):
            if card.value not in commentsSeen:
                commentsSeen.add(card.value)
                newCards.append(card)

    return _enforceHeaderConstraints(newCards, cardSequence)
Esempio n. 18
0
    def create_data_hdu(self, dataset_size, config=None):
        """
        Generate a data HDU. This method can be called more that once, and it will just append
        HDUs to the hdus attribute.
        Args:
            dataset_size (int): The size of the dataset to create.
        Keyword Args:
            config (dict): The configuration
        Returns:
            pyfits.BinTableHDU configuration specified by config argument
        """
        if not config: config = self.config
        t0 = time.time()
        cols = []

        re_pattern = "(\d+)([A-Z])"  # match all numbers and uppercase letters
        counter = 0
        for name in config['columns']:

            column_entry = config['columns'][name]

            format = column_entry.get('format', None)
            format_match = re.search(re_pattern, format)
            dtype = self.fits_dtype[format_match.group(2)]
            unit = column_entry.get('unit', None)
            # self.logger.debug("dtype and unit for {}: {} {}".format(name, dtype, unit))
            dim = column_entry.get('dim', None)

            if dim:
                dim_np = dim.strip(")").strip("(")
                dim_np = dim_np.split(",")
                dim_np = [int(d) for d in dim_np]
                # self.logger.debug("dim for {}: {}".format(name, dim_np))
        #     print("name: {}, format: {}, unit: {}, dim: {}".format(name, format, unit, dim))
            if BACKEND == 'pyfits' and pyfits.__version__ >= 3.4 and dim:
                final_shape = [dataset_size] + dim_np[::-1]
            elif BACKEND == 'astropy' and dim:
                final_shape = [dataset_size] + dim_np[::-1]
            else:
                final_shape = dataset_size
            array = np.zeros(final_shape)  #, dtype=dtype)
            # print("{}, Final shape: {}, dtype: {}, array: {}".format(name, final_shape, dtype, array))
            cols.append(
                pyfits.Column(name=name,
                              format=format,
                              unit=unit,
                              dim=dim,
                              array=array))
            counter += 1

        table_data_hdu = pyfits.BinTableHDU.from_columns(pyfits.ColDefs(cols))
        existing_keys = table_data_hdu.header.keys()
        for data_line in config['header_data']:

            card = pyfits.Card().fromstring(data_line)
            card.verify()
            if card.keyword in existing_keys:
                continue
                # del table_data_hdu.header[card.keyword]
            table_data_hdu.header.append(card)

        self.hdus.append(table_data_hdu)
        self.logger.debug(
            "Took {:.4f} seconds to generated data HDU".format(time.time() -
                                                               t0))
        return table_data_hdu
Esempio n. 19
0
def resampleToTanProjection(imageData,
                            imageWCS,
                            outputPixDimensions=[600, 600]):
    """Resamples an image and WCS to a tangent plane projection. Purely for plotting purposes
    (e.g., ensuring RA, dec. coordinate axes perpendicular).
    
    @type imageData: numpy array
    @param imageData: image data array
    @type imageWCS: astWCS.WCS
    @param imageWCS: astWCS.WCS object
    @type outputPixDimensions: list
    @param outputPixDimensions: [width, height] of output image in pixels
    @rtype: dictionary
    @return: image data (numpy array), updated astWCS WCS object for image, in format {'data', 'wcs'}.
    
    """

    RADeg, decDeg = imageWCS.getCentreWCSCoords()
    xPixelScale = imageWCS.getXPixelSizeDeg()
    yPixelScale = imageWCS.getYPixelSizeDeg()
    xSizeDeg, ySizeDeg = imageWCS.getFullSizeSkyDeg()
    xSizePix = int(round(outputPixDimensions[0]))
    ySizePix = int(round(outputPixDimensions[1]))
    xRefPix = xSizePix / 2.0
    yRefPix = ySizePix / 2.0
    xOutPixScale = xSizeDeg / xSizePix
    yOutPixScale = ySizeDeg / ySizePix
    cardList = pyfits.CardList()
    cardList.append(pyfits.Card('NAXIS', 2))
    cardList.append(pyfits.Card('NAXIS1', xSizePix))
    cardList.append(pyfits.Card('NAXIS2', ySizePix))
    cardList.append(pyfits.Card('CTYPE1', 'RA---TAN'))
    cardList.append(pyfits.Card('CTYPE2', 'DEC--TAN'))
    cardList.append(pyfits.Card('CRVAL1', RADeg))
    cardList.append(pyfits.Card('CRVAL2', decDeg))
    cardList.append(pyfits.Card('CRPIX1', xRefPix + 1))
    cardList.append(pyfits.Card('CRPIX2', yRefPix + 1))
    cardList.append(pyfits.Card('CDELT1', -xOutPixScale))
    cardList.append(pyfits.Card(
        'CDELT2', xOutPixScale))  # Makes more sense to use same pix scale
    cardList.append(pyfits.Card('CUNIT1', 'DEG'))
    cardList.append(pyfits.Card('CUNIT2', 'DEG'))
    newHead = pyfits.Header(cards=cardList)
    newWCS = astWCS.WCS(newHead, mode='pyfits')
    newImage = numpy.zeros([ySizePix, xSizePix])

    tanImage = resampleToWCS(newImage,
                             newWCS,
                             imageData,
                             imageWCS,
                             highAccuracy=True,
                             onlyOverlapping=False)

    return tanImage
Esempio n. 20
0
def fixDrzHeader(fpath, module, date, file_type="SCI", addCards=None):
    """Adjust the header of a drizzled image produced by pydrizzle/drizzle.  Mostly,
    this means removing a lot of keywords which have no meaning in the context of
    an image which is created from a number of different images from potentially any
    number of sources.  This list of keywords can be found in Bugzilla bug #1333.
    The addCards option allows the caller to add new ascards to the header.
    addCards is a list of tuples like
    [("newkeyword1","value1"),
     ("newkeyword2","value2"),
     ]
    """
    keepem = [
        "SIMPLE",
        "BITPIX",
        "NAXIS",
        "NAXIS1",
        "NAXIS2",
        #"NAXIS3",
        "TELESCOP",
        "INSTRUME",
        "DETECTOR",
        "FILTER",
        "FILTER1",
        "FILTER2",
        "LRFWAVE",
        "BUNIT",
        "CRPIX1",
        "CRPIX2",
        "CRVAL1",
        "CRVAL2",
        "CTYPE1",
        "CTYPE2",
        "CD1_1",
        "CD1_2",
        "CD2_1",
        "CD2_2",
        "LTV1",
        "LTV2",
        "LTM1_1",
        "LTM2_2",
        "IDCTAB",
        "PHOTMODE",
        "PHOTFLAM",
        "PHOTZPT",
        "PHOTPLAM",
        "PHOTBW",
        "ORIGIN",
        "DATE",
        "FILENAME",
        "EXPTIME",
        "ALIGNSKY",
        "NCOMBINE",
        "NDRIZIM",
        "PA_V3",
    ]
    curdir = os.getcwd()
    path, file = os.path.split(fpath)
    if path:
        os.chdir(path)

    oldfits = pyfits.open(file)
    if len(oldfits) > 1:
        raise IOError, "file is not a simple fits file."

    newfits = pyfits.HDUList()
    newfits.append(pyfits.PrimaryHDU())

    # Tried using the pyfits "update" mode on the open call but this is
    # logically problematic when you start deleting ascards which do not
    # have a keyword (blank cards, section header cards, etc). And we noticed
    # that pyfits winds up doing exactly what we do below when the size of the
    # header changes dramatically, i.e. writes a temp file and does a copy.
    # Pyfits automatically attaches an EXTEND ascard onto the header of the
    # appended Primary HDU with the value T.  This seems like a bug since pyfits
    # has no idea whether the file to be made is an mef file or not.
    # this card is deleted and not required for a simple fits file.

    try:
        del newfits[0].header.ascard["EXTEND"]
    except:
        pass

    # the first regex pattern will match all drizzle keywords. according to the spec in
    # Bugzilla bug # 1333, the drizzle specific keywords should only be kept in the SCI -type data
    # (i.e. the _drz.fits image).  The second pattern will match all context specific keywords
    # (CONnnnn) and should only be kept in the context image (i.e. _drz_context.fits) we need
    # to keep the two patterns seperate and use passed file_type to figure out which to keep for the
    # passed image file.
    # set the matching pattern based on file_type.

    if file_type == "SCI":
        eng_pars = [
            "CCDAMP", "CCDGAIN", "CCDOFSTA", "CCDOFSTB", "CCDOFSTC",
            "CCDOFSTD", "ATODGNA", "ATODGNB", "ATODGNC", "ATODGND", "READNSEA",
            "READNSEB", "READNSEC", "READNSED"
        ]
        for i in eng_pars:
            keepem.append(i)
        pattern = '^D[D0-9][0-9]{2}[a-zA-Z0-9]{2}.?.?'
    elif file_type == "CTX":
        pattern = '^CON[0-9][0-9][0-9][0-9]'
    else:
        pattern = None

    for ascard in oldfits[0].header.ascard:
        if pattern:
            result = re.match(pattern, ascard.key)
        else:
            result = None
        if not ascard.key:
            continue
        elif ascard.key in keepem:
            newfits[0].header.update(ascard.key, ascard.value, ascard.comment)
            continue
        elif result:
            newfits[0].header.update(ascard.key, ascard.value, ascard.comment)
            continue

    newfits[0].header.update("FILENAME", file)
    newfits[0].header.update("FILETYPE", file_type, after="FILENAME")
    newfits[0].header.update("ORIGIN", module)
    newfits[0].header.update("DATE", date)

    if addCards:
        for card in addCards:
            if newfits[0].header.has_key(card[0]):
                keyind = newfits[0].header.ascard.index_of(card[0])
                # prevkey = newfits[0].header.ascard[keyind-1].key
                try:
                    comment = newfits[0].header.ascard[keyind].comment
                except:
                    comment = ''
                del newfits[0].header[card[0]]

                # The format, gentlemen, please!
                try:
                    format = card[2]
                except:
                    if isinstance(card[1], types.FloatType):
                        format = '%20.12G / %s'
                    else:
                        format = None

                #newfits[0].header.update(card[0],card[1],after=prevkey)
                newCard = pyfits.Card(card[0], card[1], comment, format=format)

                newCard = pyfits.Card(card[0], card[1], comment)
                newfits[0].header.ascard.insert(keyind, newCard)
                del keyind, comment, newCard
            else:
                newfits[0].header.update(card[0], card[1])

    newfits[0].data = oldfits[0].data
    newfits.writeto("temp.fits")
    newfits.close()
    oldfits.close()
    del newfits, oldfits
    os.remove(file)
    os.rename('temp.fits', file)
    os.chdir(curdir)
    return
Esempio n. 21
0
def makeEmptyCEATemplateAdvanced(ra0, dec0, \
                                 ra1, dec1,\
                                 pixScaleXarcmin = 0.5, \
                                 pixScaleYarcmin= 0.5):

    """
    ALL RA DEC IN DEGREES
    """
    assert ra0<ra1
    assert dec0<dec1
    refDec = (dec0+dec1)/2.
    cosRefDec =  np.cos(refDec/180.*np.pi)
    raSizeDeg  = (ra1 - ra0)*cosRefDec
    decSizeDeg = (dec1-dec0)
    
    cdelt1 = -pixScaleXarcmin/(60.*cosRefDec)
    cdelt2 = pixScaleYarcmin/(60.*cosRefDec)
    naxis1 = np.int(raSizeDeg/pixScaleXarcmin*60.+0.5)
    naxis2 = np.int(decSizeDeg/pixScaleYarcmin*60.+0.5)
    refPix1 = np.int(-ra1/cdelt1+0.5)
    refPix2 = np.int(np.sin(-dec0*np.pi/180.)\
                        *180./np.pi/cdelt2/cosRefDec**2+0.5)
    pv2_1 = cosRefDec**2
    cardList = pyfits.Header() #CardList()
    #cardList = pyfits.CardList()
    cardList.append(pyfits.Card('NAXIS', 2))
    cardList.append(pyfits.Card('NAXIS1', naxis1))
    cardList.append(pyfits.Card('NAXIS2', naxis2))
    cardList.append(pyfits.Card('EXTEND', True))
    cardList.append(pyfits.Card('CTYPE1', 'RA---CEA'))
    cardList.append(pyfits.Card('CTYPE2', 'DEC--CEA'))
    cardList.append(pyfits.Card('CRVAL1', 0))
    cardList.append(pyfits.Card('CRVAL2', 0))
    cardList.append(pyfits.Card('CRPIX1', refPix1+1))
    cardList.append(pyfits.Card('CRPIX2', refPix2+1))
    cardList.append(pyfits.Card('CDELT1', cdelt1))
    cardList.append(pyfits.Card('CDELT2', cdelt2))
    cardList.append(pyfits.Card('CUNIT1', 'DEG'))
    cardList.append(pyfits.Card('CUNIT2', 'DEG'))
    cardList.append(pyfits.Card('PV2_1', pv2_1))
    cardList.append(pyfits.Card('EQUINOX',2000))
    cardList.append(pyfits.Card('PC1_1',1))
    cardList.append(pyfits.Card('PC1_2',0))
    cardList.append(pyfits.Card('PC2_1',0))
    cardList.append(pyfits.Card('PC2_2',1))
    
    hh = pyfits.Header(cards=cardList)
    wcs = astLib.astWCS.WCS(hh, mode='pyfits')
    data = np.zeros([naxis2,naxis1])
    ltMap = liteMapFromDataAndWCS(data,wcs)
    
    return ltMap
Esempio n. 22
0
def makeEmptyCEATemplate(raSizeDeg, decSizeDeg,meanRa = 180., meanDec = 0.,\
                      pixScaleXarcmin = 0.5, pixScaleYarcmin=0.5):
    assert meanDec == 0.,'mean dec other than zero not implemented yet'

    
    cdelt1 = -pixScaleXarcmin/60.
    cdelt2 = pixScaleYarcmin/60.
    naxis1 = np.int(raSizeDeg/pixScaleXarcmin*60.+0.5)
    naxis2 = np.int(decSizeDeg/pixScaleYarcmin*60.+0.5)
    refPix1 = naxis1/2.
    refPix2 = naxis2/2.
    pv2_1 = 1.0
    cardList = pyfits.Header() #CardList()
    cardList.append(pyfits.Card('NAXIS', 2))
    cardList.append(pyfits.Card('NAXIS1', naxis1))
    cardList.append(pyfits.Card('NAXIS2', naxis2))
    cardList.append(pyfits.Card('CTYPE1', 'RA---CEA'))
    cardList.append(pyfits.Card('CTYPE2', 'DEC--CEA'))
    cardList.append(pyfits.Card('CRVAL1', meanRa))
    cardList.append(pyfits.Card('CRVAL2', meanDec))
    cardList.append(pyfits.Card('CRPIX1', refPix1+1))
    cardList.append(pyfits.Card('CRPIX2', refPix2+1))
    cardList.append(pyfits.Card('CDELT1', cdelt1))
    cardList.append(pyfits.Card('CDELT2', cdelt2))
    cardList.append(pyfits.Card('CUNIT1', 'DEG'))
    cardList.append(pyfits.Card('CUNIT2', 'DEG'))
    hh = pyfits.Header(cards=cardList)
    wcs = astLib.astWCS.WCS(hh, mode='pyfits')
    data = np.zeros([naxis2,naxis1])
    ltMap = liteMapFromDataAndWCS(data,wcs)
    
    return ltMap
Esempio n. 23
0
def mkfitshdr(cards=None, usedefaults=True):
	"""
	Make a FITS file header of all arguments supplied in the dict **cards**.

	If **usedefaults** is set, also add default header items:
	- Program filename and pasth (from sys.argv[0])
	- Current working dir
	- Program filesize, mtime and ctime
	- Git revision of executable (if available)
	- epoch (time())
	- utctime / localtime
	- hostid

	@params [in] cards Dict containing key=value pairs for the header
	@params [in] usedefaults Also store default parameters in header
	@return pyfits header object
	"""

	clist = pyfits.CardList()

	if (usedefaults):
		clist.append(pyfits.Card(key='progname', 
								value=os.path.basename(sys.argv[0]),
								comment='Program filename') )
		clist.append(pyfits.Card(key='progpath', 
								value=os.path.dirname(sys.argv[0]),
								comment='Program path') )
		grev = git_rev(sys.argv[0])
		if (grev):
			clist.append(pyfits.Card(key='gitrev', 
								value=grev,
								comment='Program git revision') )
		clist.append(pyfits.Card(key='progsize', 
								value=os.path.getsize(sys.argv[0]),
								comment='Program filesize (bytes)') )
		clist.append(pyfits.Card(key='mtime', 
								value=os.path.getmtime(sys.argv[0]),
								comment='Program last last modification time') )
		clist.append(pyfits.Card(key='ctime', 
								value=os.path.getctime(sys.argv[0]),
								comment='Program metadata change time' ) )
		clist.append(pyfits.Card(key='curdir', 
								value=os.path.realpath(os.path.curdir),
								comment='Current working dir') )
		clist.append(pyfits.Card(key='epoch', value=time(),
								comment='Current seconds since epoch from time.time()') )
		# No comments for the last two fields because they are too large
		clist.append(pyfits.Card(key='utctime', value=asctime(gmtime(time()))) )
		clist.append(pyfits.Card(key='loctime', value=asctime(localtime(time()))) )
		clist.append(pyfits.Card(key='hostid', value=os.uname()[1],
								comment='Hostname from os.uname()') )

	if (cards):
		for key, val in cards.iteritems():
			clist.append(pyfits.Card(key, val) )

	return pyfits.Header(cards=clist)
Esempio n. 24
0
def dict2header(header):
    cards = [pyfits.Card(k, header[k]) for k in header]
    return pyfits.Header(cards=cards)
Esempio n. 25
0
import os, re,string, pdb
import time
import pyfits
import numpy
from numpy import char as chararray


# List of supported default file types
# It will look for these file types by default
# when trying to recognize input rootnames.
EXTLIST =  ['_crj.fits','_flt.fits','_flc.fits','_sfl.fits']

__version__ = '1.0 (15-Jun-2012)'

_prihdr = pyfits.Header([pyfits.Card('SIMPLE', pyfits.TRUE,'Fits standard'),
                pyfits.Card('BITPIX  ',                    16 ,' Bits per pixel'),
                pyfits.Card('NAXIS   ',                     0 ,' Number of axes'),
                pyfits.Card('ORIGIN  ',  'NOAO-IRAF FITS Image Kernel July 1999' ,'FITS file originator'),
                pyfits.Card('IRAF-TLM',  '18:26:13 (27/03/2000)' ,' Time of last modification'),
                pyfits.Card('EXTEND  ',pyfits.TRUE ,' File may contain standard extensions'),
                pyfits.Card('NEXTEND ',                     1 ,' Number of standard extensions'),
                pyfits.Card('DATE    ',  '2001-02-14T20:07:57',' date this file was written (yyyy-mm-dd)'),
                pyfits.Card('FILENAME',  'hr_box_asn.fits'            ,' name of file'),
                pyfits.Card('FILETYPE',  'ASN_TABLE'          ,' type of data found in data file'),
                pyfits.Card('TELESCOP',  'HST'                ,' telescope used to acquire data'),
                pyfits.Card('INSTRUME',  'ACS   '             ,' identifier for instrument used to acquire data'),
                pyfits.Card('EQUINOX ',                2000.0 ,' equinox of celestial coord. system'),
                pyfits.Card('ROOTNAME',  'hr_box  '              ,' rootname of the observation set'),
                pyfits.Card('PRIMESI ',  'ACS   '             ,' instrument designated as prime'),
                pyfits.Card('TARGNAME',  'SIM-DITHER'                     ,'proposer\'s target name'),