Ejemplo n.º 1
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 = numpy.int(raSizeDeg / pixScaleXarcmin * 60. + 0.5)
    naxis2 = numpy.int(decSizeDeg / pixScaleYarcmin * 60. + 0.5)
    refPix1 = naxis1 / 2.
    refPix2 = naxis2 / 2.
    pv2_1 = 1.0
    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('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 = numpy.zeros([naxis2, naxis1])
    ltMap = liteMap.liteMapFromDataAndWCS(data, wcs)

    return ltMap
Ejemplo n.º 2
0
 def _get_ids(self):
     """Find source name information and return as a list."""
     name_key = ''
     # deprecated, removed at 3.2
     #cards = self.hdu.header.ascardlist()
     cards = pf.CardList(self.hdu.header.cards)
     #First check for UCD in header
     for card in cards:
         if card.keyword[:5]=='TBUCD' and card.value in ['ID_MAIN','meta.id;meta.main']:
             name_key = cards['TTYPE'+card.key[5:8]].value
             break
         #Sometimes UCDs are declared in comments
         #May be fragile - depends on specific format for comments as in gamma-egr catalog
         value_comment = card.image.split('/') ##ascardimage().split('/')
         if len(value_comment)>1:
             comment = value_comment[1]
             ucd_string = comment[comment.find('UCD'):].split()
             if ucd_string:
                 try:
                     if ucd_string[0].split('=')[1].strip('.')=='ID_MAIN':
                         name_key = cards[''.join(['TTYPE',card.key[5:8]])].value
                         break
                 except IndexError:
                     pass
         if card.keyword[:5]=='TTYPE' and card.value.upper() in ['NAME','ID','PSR_NAME','SOURCE_NAME']:
             name_key = card.value
             break
     try:
         return self.hdu.data.field(name_key)
     except KeyError:
         return
Ejemplo n.º 3
0
def demo_header():
    cards = pyfits.CardList()
    for l in open("sample_fits01.header"):
        card = pyfits_card_fromstring(l.strip())
        cards.append(card)
    h = pyfits.Header(cards)
    return h
Ejemplo n.º 4
0
def test_header():
    cards = pyfits.CardList()
    for l in open("test.header"):
        card = pyfits_card_fromstring(l.strip())
        cards.append(card)
    h = pyfits.Header(cards)
    return h
Ejemplo n.º 5
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.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
Ejemplo n.º 6
0
    def _get_positions(self):
        """Find columns containing position info and return a list of SkyDirs"""

        cards = pf.CardList(self.hdu.header.cards) #ascardlist()
        #ucds = cards.filterList('TBUCD*')
        #ttypes = cards.filterList('TTYPE*')
        ucds = cards.filter_list('TBUCD*')
        ttypes = cards.filter_list('TTYPE*')
        lon_key = lat_key = ''
        if not lon_key:
            if 'POS_EQ_RA_MAIN' in ucds.values():
                ucd = ucds.keys()[ucds.values().index('POS_EQ_RA_MAIN')]
                lon_key = ttypes[''.join(['TTYPE',ucd[5:8]])].value
                #Assumes that if POS_EQ_RA_MAIN exists, POS_EQ_DEC_MAIN does too.
                ucd = ucds.keys()[ucds.values().index('POS_EQ_DEC_MAIN')]
                lat_key = ttypes[''.join(['TTYPE',ucd[5:8]])].value
            elif 'RAdeg' in ttypes.values():
                lon_key = ttypes[ttypes.keys()[ttypes.values().index('RAdeg')]].value
                lat_key = ttypes[ttypes.keys()[ttypes.values().index('DEdeg')]].value
            elif '_RAJ2000' in ttypes.values():
                lon_key = ttypes[ttypes.keys()[ttypes.values().index('_RAJ2000')]].value
                lat_key = ttypes[ttypes.keys()[ttypes.values().index('_DEJ2000')]].value
            elif 'RAJ2000' in ttypes.values():
                lon_key = ttypes[ttypes.keys()[ttypes.values().index('RAJ2000')]].value
                lat_key = ttypes[ttypes.keys()[ttypes.values().index('DEJ2000')]].value
            elif 'RAJD' in ttypes.values(): # only for bigbfile?
                lon_key = ttypes[ttypes.keys()[ttypes.values().index('RAJD')]].value
                lat_key = ttypes[ttypes.keys()[ttypes.values().index('DECJD')]].value
            elif 'RA' in ttypes.values():
                lon_key = ttypes[ttypes.keys()[ttypes.values().index('RA')]].value
                try:
                    lat_key = ttypes[ttypes.keys()[ttypes.values().index('DE')]].value
                except ValueError:
                    lat_key = ttypes[ttypes.keys()[ttypes.values().index('DEC')]].value
        if not lon_key:
            self.coords = skymaps.SkyDir.GALACTIC
            if 'POS_GAL_LON' in ucds.values():
                lon_key = ucds.keys()[ucds.values().index('POS_GAL_LON')]
                lat_key = ucds.keys()[ucds.values().index('POS_GAL_LAT')]
            elif '_GLON' in ttypes.values():
                lon_key = ttypes[ttypes.keys()[ttypes.values().index('_GLON')]].value
                lat_key = ttypes[ttypes.keys()[ttypes.values().index('_GLAT')]].value
            elif 'GLON' in ttypes.values():
                lon_key = ttypes[ttypes.keys()[ttypes.values().index('GLON')]].value
                lat_key = ttypes[ttypes.keys()[ttypes.values().index('GLAT')]].value
        if lon_key:
            return (self.hdu.data.field(lon_key).astype('float'),
                    self.hdu.data.field(lat_key).astype('float'))
        else:
            raise SrcidError('did not find position info in catalog' )
Ejemplo n.º 7
0
 def _get_hdu(self,fits_cat):
     """Find and return HDU with catalog information."""
     #First check for HDUS with CAT-NAME or EXTNAME in header.
     for hdu in fits_cat:
         cards = pf.CardList(hdu.header.cards) ## replaced this function: ascardlist()
         try:
             self.cat_name = cards['CAT-NAME'].value
             return hdu
         except KeyError:
             try:
                 self.cat_name = cards['EXTNAME'].value
                 return hdu
             except KeyError:
                 self.cat_name = self.class_module.catid
                 pass
     #No CAT-NAME or EXTNAME found, just return second HDU
     if len(fits_cat)>=2:
         return fits_cat[1]
     #Only one HDU, no name info, return None
     return
Ejemplo n.º 8
0
def set_pha_data(filename, data, col_names, header=None,
                 ascii=False, clobber=False, packup=False):

    if not packup and os.path.isfile(filename) and not clobber:
        raise IOErr("filefound", filename)

    hdrlist = pyfits.CardList()

    for key in header.keys():
        if header[key] is None:
            continue
        hdrlist.append(pyfits.Card( str(key.upper()), header[key] ))

    collist = []
    cols = []
    coldefs = []
    for name in col_names:
        if data[name] is None:
            continue
        col = pyfits.Column(name=name.upper(),
                            format=data[name].dtype.name.upper(),
                            array=data[name])
        cols.append(data[name])
        coldefs.append(name.upper())
        collist.append(col)

    if ascii:
        set_arrays(filename, cols, coldefs, ascii=ascii, clobber=clobber)
        return

    pha = pyfits.new_table(pyfits.ColDefs(collist),
                           header=pyfits.Header(hdrlist))
    pha.name = 'SPECTRUM'
    if packup:
        return pha
    pha.writeto(filename, clobber=True)
Ejemplo n.º 9
0
def init_SDFITS(DSS, tablesize, time_column=False):
    """
  Initialize an SDFITS file and extension.

  Call this first to initiate an SDFITS file.  It creates the primary HDU
  suitable for a binary table extension.  It then creates a binary table with
  columns that one always needs. The data array has at least four axes for
  compatibility with ASAP.

  Notes
  =====

  The default length of axis 4 (STOKES) is 1 for compatibility with a
  "one spectrum per row" convention.  If this is not to be followed then
  subsequently called methods (probably Observatory.FITS_init_backends)
  must change MAXIS4.

  TDIMxx is calculated from MAXIS1 through MAXISn at the end.

  @param DSS : instance of the Telescope class::
    A front end with no telescope makes no sense.

  @param tablesize : int::
    Number of rows in the table

  @param time_column : boolean::
    If True, there will be a fourth data axis for time.
    Otherwise, the data axes are frequency, RA and decl.

  @return: tuple::
    The primary HDU instance, the table CardList (header)
    instance with initial header data, and the initial column set.
  """
    # create the primary HDU and extension headers
    prihdu = pyfits.PrimaryHDU()
    hdr = pyfits.CardList()
    cols = make_basic_columns(tablesize, time_column)

    # add telescope location data to the table header
    logger.debug("DSS: %s", DSS)
    if type(DSS) == list:
        # This may seem odd but in the most general case there could be two or
        # more antennas, like in an interferometer.  In that case, however,
        # "single dish" FITS format doesn't apply.  We'll just assume a list of
        # length 1.
        dss = DSS[0]
    else:
        dss = DSS
    if dss != 0:
        hdr.append(pyfits.Card('telescop', dss.name))
        hdr.append(pyfits.Card('sitelong', dss['longitude']))
        hdr.append(pyfits.Card('sitelat', dss['latitude']))
        hdr.append(pyfits.Card('siteelev', dss['elevation']))
        hdr.append(pyfits.Card('obsgeo-x', dss['geo-x']))
        hdr.append(pyfits.Card('obsgeo-y', dss['geo-y']))
        hdr.append(pyfits.Card('obsgeo-z', dss['geo-z']))
        hdr.append(pyfits.Card('TIMESYS', 'UTC'))

    # there will always be four axes in the data array
    hdr.append(pyfits.Card('MAXIS', 4))
    # we will always have the first data axis with frequency in the
    # from of the observatory, or time-delay for correlation functions
    # (cannot set MAXIS1 until we know the size of the spectrum)
    # hdr.append(pyfits.Card('MAXIS1',?))
    hdr.append(pyfits.Card('CTYPE1', 'FREQ-OBS'))

    # the second and third axes will be right ascension and declination
    hdr.append(pyfits.Card('MAXIS2', 1))
    hdr.append(pyfits.Card('CTYPE2', 'RA---GLS'))

    hdr.append(pyfits.Card('MAXIS3', 1))
    hdr.append(pyfits.Card('CTYPE3', 'DEC--GLS'))

    # the fourth axis is polarization.  As a default
    hdr.append(pyfits.Card('MAXIS4', 1))
    hdr.append(pyfits.Card('CTYPE4', 'STOKES'))

    if time_column:
        # the optional fifth data axis will be time
        # (cannot set MAXIS5 until we know the number of spectra)
        # hdr.append(pyfits.Card('MAXIS4',?))
        hdr.append(pyfits.Card('CTYPE5', 'TIME'))

    return prihdu, hdr, cols
Ejemplo n.º 10
0
def set_image_data(filename, data, header, ascii=False, clobber=False,
                   packup=False):

    if not packup and os.path.isfile(filename) and not clobber:
        raise IOErr("filefound", filename)

    if ascii:
        set_arrays(filename, [data['pixels'].ravel()],
                   ascii=ascii, clobber=clobber)
        return

    hdrlist = pyfits.CardList()

    # Write Image Header Keys
    for key in header.keys():
        if header[key] is None:
            continue
        _set_wcs_key(hdrlist, key, header[key])

    # Write Image WCS Header Keys
    if data['eqpos'] is not None:
        cdeltw = data['eqpos'].cdelt
        crpixw = data['eqpos'].crpix
        crvalw = data['eqpos'].crval
        equin  = data['eqpos'].equinox

    if data['sky'] is not None:
        cdeltp = data['sky'].cdelt
        crpixp = data['sky'].crpix
        crvalp = data['sky'].crval

        _set_wcs_key(hdrlist, 'MTYPE1', 'sky     ')
        _set_wcs_key(hdrlist, 'MFORM1', 'x,y     ')
        _set_wcs_key(hdrlist, 'CTYPE1P', 'x      ')
        _set_wcs_key(hdrlist, 'CTYPE2P', 'y      ')
        _set_wcs_key(hdrlist, 'WCSNAMEP','PHYSICAL')
        _set_wcs_key(hdrlist, 'CDELT1P', cdeltp[0])
        _set_wcs_key(hdrlist, 'CDELT2P', cdeltp[1])
        _set_wcs_key(hdrlist, 'CRPIX1P', crpixp[0])
        _set_wcs_key(hdrlist, 'CRPIX2P', crpixp[1])
        _set_wcs_key(hdrlist, 'CRVAL1P', crvalp[0])
        _set_wcs_key(hdrlist, 'CRVAL2P', crvalp[1])

        if data['eqpos'] is not None:
            # Simply the inverse of read transformations in get_image_data
            cdeltw = cdeltw * cdeltp
            crpixw = ((crpixw - crvalp) / cdeltp + crpixp )

    if data['eqpos'] is not None:
        _set_wcs_key(hdrlist, 'MTYPE2', 'EQPOS   ')
        _set_wcs_key(hdrlist, 'MFORM2', 'RA,DEC  ')
        _set_wcs_key(hdrlist, 'CTYPE1', 'RA---TAN')
        _set_wcs_key(hdrlist, 'CTYPE2', 'DEC--TAN')
        _set_wcs_key(hdrlist, 'CDELT1', cdeltw[0])
        _set_wcs_key(hdrlist, 'CDELT2', cdeltw[1])
        _set_wcs_key(hdrlist, 'CRPIX1', crpixw[0])
        _set_wcs_key(hdrlist, 'CRPIX2', crpixw[1])
        _set_wcs_key(hdrlist, 'CRVAL1', crvalw[0])
        _set_wcs_key(hdrlist, 'CRVAL2', crvalw[1])
        _set_wcs_key(hdrlist, 'CUNIT1', 'deg     ')
        _set_wcs_key(hdrlist, 'CUNIT2', 'deg     ')
        _set_wcs_key(hdrlist, 'EQUINOX', equin)

    #
    img = pyfits.PrimaryHDU(data['pixels'], header=pyfits.Header(hdrlist))
    if packup:
        return img
    img.writeto(filename, clobber=True)