Пример #1
0
def read_ptg(filename):
    print ""
    print "[READ PTG]: BEGIN reading "+filename
    ptg = h.mrdfits(filename,hdu=1)
    ptg_package = {'ra':ptg[2], 'dec':ptg[1], 'pa':ptg[0], 'hwp':ptg[3]}
    print "[READ PTG]: END reading "
    return ptg_package
Пример #2
0
def read_ptg(filename):
    print ""
    print "[READ PTG]: BEGIN reading " + filename
    ptg = h.mrdfits(filename, hdu=1)
    ptg_package = {'ra': ptg[2], 'dec': ptg[1], 'pa': ptg[0], 'hwp': ptg[3]}
    print "[READ PTG]: END reading "
    return ptg_package
Пример #3
0
 def __init__(self, freq, nripple=1, **keywords):
     nripple_max = 2
     if nripple not in np.arange(1, nripple_max + 1):
         raise ValueError('Input nripple is not a positive integer '
                          'less or equal {}'.format(nripples_max))
     self.nripple = nripple
     fl = hp.mrdfits(PATH +
                     'sb_peak_ripple{}_150HGz.fits'.format(nripple))[0]
     #        fl /= fl.max()
     fl = np.sqrt(fl)
     if freq == 150e9:
         self.fl = fl
     else:
         ell = np.arange(len(fl)) + 1
         spl = splrep(ell * freq / 150e9, fl)
         self.fl = splev(ell, spl)
Пример #4
0
    def read_mark_beam_map(self):
        beam_kernel = np.array(hp.mrdfits(self.config.input_beam_file))
        mark_orig_dim = np.sqrt(beam_kernel.shape[1])                             #pixels
        beam_kernel = beam_kernel.reshape((4, mark_orig_dim, mark_orig_dim))
        mark_fwhm_major = 7.68                   #arc-mins
        mark_fwhm_minor = 7.68                   #arc-mins
        mark_resolution = 0.39523370660946627            #arc-mins

        new_dim = int(mark_orig_dim * mark_resolution / self.config.scan_resolution)
        if new_dim%2 == 0:
            new_dim += 1
        #print "old resolution :", mark_resolution
        #print "new_resolution :", self.config.scan_resolution
        old_extent = mark_orig_dim * mark_resolution
        new_extent = new_dim * self.config.scan_resolution
        #print "old extent :", mark_resolution * 181
        #print "new_extent :", new_extent
        self.config.fwhm_major = mark_fwhm_major * new_extent / old_extent
        self.config.fwhm_minor = mark_fwhm_minor * new_extent / old_extent
        #print "old fwhm :", mark_fwhm_major
        #print "new fwhm :", self.config.fwhm_major

        self.beam_kernel = np.empty((4, new_dim, new_dim))
        for i in range(4):
            self.beam_kernel[i] = zoom(beam_kernel[i], float(new_dim)/float(mark_orig_dim))
            self.beam_kernel[i] = interpolation.rotate(self.beam_kernel[i], angle=self.config.beam_angle, reshape=False)

        #print "beam_cutoff required :", self.config.beam_cutoff
        beam_extension_required = self.config.fwhm_major * self.config.beam_cutoff          #arc-min
        #print "extention required :", beam_extension_required
        num_pix = int(new_dim * beam_extension_required / new_extent)
        if num_pix%2 == 0:
            num_pix -= 1
        #print "num pix :", num_pix
        #print "extension achieved :", num_pix * self.config.scan_resolution

        self.config.beam_cutoff = num_pix * self.config.scan_resolution / self.config.fwhm_major
        #print "cutoff achieved :", self.config.beam_cutoff

        start = new_dim/2 - num_pix/2
        stop = new_dim/2 + num_pix/2 + 1
        self.beam_kernel = self.beam_kernel[..., start:stop, start:stop]
        #print "kernel shape :", self.beam_kernel.shape
        self.del_beta = self.config.scan_resolution * np.arange(-num_pix/2 + 1, num_pix/2 + 1)
Пример #5
0
    def __init__(self, freq,
                 nripple=1,
                 **keywords):
        nripple_max = 2
        if nripple not in np.arange(1, nripple_max + 1):
            raise ValueError(
                'Input nripple is not a positive integer '
                'less or equal {}'.format(nripples_max))
        self.nripple = nripple
        fl = hp.mrdfits(PATH + 'sb_peak_ripple{}_150HGz.fits'.
                               format(nripple))[0]
#        fl /= fl.max()
        fl = np.sqrt(fl)
        if freq == 150e9:
            self.fl = fl
        else:
            ell = np.arange(len(fl)) + 1
            spl = splrep(ell * freq / 150e9, fl)
            self.fl = splev(ell, spl)
Пример #6
0
def make_minimasks(refmap, nside, radius, nside_pixcen, dir_out):

    sfrac = radius2skyfrac(radius)
    print 'Making mini masks for',sfrac,'sky fraction'

    # Read available pixels
    m = _hp.mrdfits(refmap)
    mappix = m[0]

    # Get theta, phi coordinates
    pix = _np.array(range(_hp.nside2npix(nside)))
    theta, phi = _hp.pix2ang(nside, pix)

    # Make minimasks
    mask = _np.zeros(_hp.nside2npix(nside))
    mask[mappix] = 1.0
    mask_pixcen = _hp.ud_grade(mask, nside_pixcen)
    pixcen = _np.where(mask_pixcen > 0)[0]
    n = 0
    for i,p0 in enumerate(pixcen):
        if i%100 == 0:
            print i,'/',len(pixcen)
        theta0, phi0 = _hp.pix2ang(nside_pixcen, p0)
        d = gcdist(theta, phi, theta0, phi0)
        p = _np.where(d < radius)[0]
        if len(_np.where(mask[p] == 0)[0]) > 0:
            continue
        # p = _np.where( (d < radius) & (mask > 0) )[0]
        # x = float(len(p))/float(_hp.nside2npix(nside))
        # # Check if entire circle is contained in daniel's map
        # if x < sfrac:
        #     continue
        # Make minimask
        m = _np.zeros(_hp.nside2npix(nside))
        m[p] = _np.cos(_np.pi*d[p]/(2*radius))
        out = dir_out+'/mask_n'+str(nside_pixcen)+'_'+str(p0)+'.fits'
        _hp.write_map(out,m)
        print 'Wrote',out
        n = n + 1
    print 'Found',n,'good pixel centers'
    return
Пример #7
0
#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*

LMAX = 1500
NSIDE = 1024
FWHM_arcmin = 8.0
FWHM = np.deg2rad(FWHM_arcmin/60.0)
SIGMA = FWHM/2.35482
ell = np.arange(LMAX + 1)
norm = 2*np.pi
beam_attenuation = np.exp(-ell*(ell + 1)*SIGMA**2)

#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*
#Loading input spectra and masks
#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*

cl = hp.mrdfits(output_folder + "cls/" + tag + "/cellpure_sky_map_mask1_0_0.fits")
ps = hp.mrdfits(output_folder + "cls/" + tag + "/pseudopure_sky_map_mask1_0_0.fits")
input_spectra = np.load(input_spectra_folder + spectra_name)[...,:LMAX + 1]
binary_mask = hp.read_map(binary_mask_folder + "mask_ebex.fits")
apodised_mask = hp.read_map(output_folder + "mask/" + tag + "/apodized_mask_I_" + tag + ".fits")


#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*
#Calculate the normalisation due to partial sky and other factors
#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*

sky_frac = float(np.sum(binary_mask))/hp.nside2npix(NSIDE)
norm_apodised = float(np.sum(apodised_mask**2))/hp.nside2npix(NSIDE)

#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*
#Plotting sub routine
# In[10]:

# First calculate the covariance matrix by the definition, i.e. 
# 
# C_ij = < \delta T_i \delta T_j > = 1/4pi \sum^{N_pix} p = 
# ( T_i(p) - mean(T_i) ) * ( T_j(p) - mean(T_j) )
#
#
# Larson, Weiland, Hinshaw, Bennett, 
# http://arxiv.org/pdf/1409.7718.pdf
#


# In[11]:

tempmap = hp.mrdfits("camb_nside4.fits") #type() = list


# In[12]:

tempdata = tempmap[0] #len()=192, type()=numpy.ndarray


# In[13]:

# First calculate the mean
#
# numpy.mean
#
# numpy.mean(a, axis=None, dtype=None, out=None, keepdims=False)
# Compute the arithmetic mean along the specified axis.
Пример #9
0
mapa[0][:] = mapa[0][:] * 1e6

hp.write_map('new_map.fits',mapa, coord='G', column_names=list(['30GHz','44GHz','70GHz']), column_units=list(['microK','K','K']))

mapa2 = hp.read_map('new_map.fits', field={0,1,2}, h=True)


#%%
"""
STEP 6: Reading/Writing generic data of/into an fits file

"""

#####################################
data = hp.mrdfits('COM_PCCS_030_R2.04.fits')

# OU AINDA:
    
from astropy.io import fits
hdulist = fits.open('COM_PCCS_030_R2.04.fits')
hdulist.info()
data = hp.mrdfits(hdulist, hdu=1)

hdulist.writeto('new_table.fits')

#####################################

len(data)

hp.mwrfits('new_table.fits', data)
Пример #10
0
def main():
    usage = "usage: %(prog)s [options]"
    description = "Make output summary plots of all-sky fitting"

    parser = argparse.ArgumentParser(usage, description=description)
    parser.add_argument('-i',
                        "--input",
                        type=str,
                        default="mcube_baseline",
                        help="Input file prefix")
    parser.add_argument('-c',
                        "--ccube",
                        type=str,
                        default="ccube.fits",
                        help="Input file prefix")
    args = parser.parse_args(sys.argv[1:])

    fontsize = 9
    matplotlib.rcParams.update({'font.size': fontsize})

    #pdf_pages = PdfPages("%s.pdf"%(args.input))

    ccube = hp.mrdfits(args.ccube, hdu=1)[1:]
    ebins = hp.mrdfits(args.ccube, hdu=2)
    eranges = np.vstack([ebins[1], ebins[2]]).T / 1e6  # keV to GeV
    ecents = np.sqrt(ebins[1] * ebins[2])
    ewidths = ebins[2] - ebins[1]

    nebins = len(eranges)
    counts_spectrum = np.zeros((nebins))

    idx = 0
    sys.stdout.write("Making plots: ")

    region_spectra = {}

    for i in range(NCOMP):
        mcube_file = "%s_%02i.fits" % (args.input, i)
        mcube = hp.mrdfits(mcube_file, hdu=1)[1:]

        for j in range(len(mcube)):
            sys.stdout.write('.')
            sys.stdout.flush()

            counts_cast = hp.ud_grade(ccube[idx], NSIDE, power=-2)
            model_cast = hp.ud_grade(mcube[j], NSIDE, power=-2)

            fig, axs = plt.subplots(nrows=1, ncols=3, figsize=(14, 4))
            figure_model(model_cast, eranges[idx])
            figure_frac_resid(counts_cast, model_cast, eranges[idx])

            figure_signif(counts_cast, model_cast, eranges[idx])
            #pdf_pages.savefig(fig,bbox_inches='tight')

            fig.savefig('fig_%s_maps_%02i_%02i.png' % (args.input, i, j),
                        bbox_inches='tight')

            for regName, regPixels in zip(REGIONS['regionNames'],
                                          REGIONS['regionPixels']):
                if not region_spectra.has_key(regName):
                    region_spectra[regName] = dict(counts=np.zeros((nebins)),
                                                   model=np.zeros((nebins)))
                region_counts_spectra = region_spectra[regName]['counts']
                region_model_spectra = region_spectra[regName]['model']

                if regPixels is None:
                    region_counts_spectra[idx] = counts_cast.sum()
                    region_model_spectra[idx] = model_cast.sum()
                else:
                    region_counts_spectra[idx] = counts_cast[regPixels].sum()
                    region_model_spectra[idx] = model_cast[regPixels].sum()

            idx += 1

    fig_region_spectra = figure_region_spectra(REGIONS['regionNames'],
                                               region_spectra, ecents, ewidths)
    fig_region_resid = figure_region_resid(REGIONS['regionNames'],
                                           region_spectra, ecents, ewidths)

    fig_region_spectra.savefig('fig_%s_region_spectra.png' % (args.input),
                               bbox_inches='tight')
    fig_region_resid.savefig('fig_%s_region_resid.png' % (args.input),
                             bbox_inches='tight')
#
# Larson, Weiland, Hinshaw, Bennett, 
# http://arxiv.org/pdf/1409.7718.pdf
#


# In[51]:

temp1 = "camb_nside2.fits" #CAMB simulated maps associated with scalar C_l values above
temp2 = "camb_nside4.fits"
temp3 = "camb_nside8.fits"


# In[52]:

tempmap1 = hp.mrdfits("camb_nside2.fits") #type() = list
tempmap2 = hp.mrdfits("camb_nside4.fits")
tempmap3 = hp.mrdfits("camb_nside8.fits")


# In[53]:

tempdata1 = tempmap1[0] #len()=48, type()=numpy.ndarray
tempdata2 = tempmap2[0] #len()=192
tempdata3 = tempmap3[0] #len()=768


# In[54]:

# First calculate the mean
#
Пример #12
0
def read_FPDB_fits(filename):
    fpdb = h.mrdfits(filename, hdu=1)
    return fpdb
Пример #13
0
def my_mwrfits(filename,
               data,
               colnames=None,
               keys=None,
               bintable=False,
               ftype=None,
               extnames=None,
               origin=None,
               dets=None):
    """Write columns to a fits file in a table extension.

    Parameters
    ----------
    filename : str
      The fits file name
    data : list of 1D arrays
      A list of 1D arrays to write in the table
    colnames : list of str
      The column names
    keys : dict-like
      A dictionary with keywords to write in the header
    """

    hline = '----------------------------------------------------------------'
    if ftype == 'B':
        # name = 'WINDOW FUNCTION'
        comments = [
            'Beam Window Function B(l)',
            'Compatible with Healpix (synfast, smoothing, ...) and PolSpice',
            'To be squared before applying to power spectrum',
            '  C_map(l) = C_sky(l) * B(l)^2 '
        ]
    if ftype == 'B_TEB':
        # name = 'WINDOW FUNCTIONS'
        comments = [
            'Beam Window Functions B(l), for T, E and B',
            'Compatible with Healpix (synfast, smoothing, ...) and PolSpice',
            'To be squared before applying to power spectrum',
            '  C_TT_map(l) = C_TT_sky(l) * B_T(l)^2 ',
            '  C_EE_map(l) = C_EE_sky(l) * B_E(l)^2 ',
            '  C_BB_map(l) = C_BB_sky(l) * B_B(l)^2 '
        ]
    if ftype == 'W':
        # name = 'WINDOW FUNCTIONS'
        comments = [
            'Beam Window Functions W(l) = B(l)^2',
            'Applies directly to power spectrum              ',
            '  C_map(l) = C_sky(l) * W(l) ', 'Includes cross-talk terms   '
        ]

    # ---- primary header -----
    hdu = pyfits.PrimaryHDU(None)
    #hdu.name = name
    hhu = hdu.header.set
    #hhb = hdu.header.add_blank
    hhc = hdu.header.add_comment
    #hhh = hdu.header.add_history
    fdate = datetime.datetime.now().strftime('%Y-%m-%d')
    hhu('DATE', fdate, comment=' Creation date (CCYY-MM-DD) of FITS header')
    if extnames is not None:
        nx = len(extnames)
        hhu('NUMEXT', nx, 'Number of extensions')
        for xt in range(nx):
            hhu('XTNAME%d' % (xt + 1), extnames[xt],
                'Name of extension #%d' % (xt + 1))

    hhc(hline)
    for mycom in comments:
        hhc(mycom)
    if origin is not None:
        for myor in origin:
            hhc(myor)
        hhc(hline)
    if dets is not None:
        for id, det in enumerate(dets):
            hhu('DET%d' % (id + 1), det, 'Detector (set)')

    hdulist = pyfits.HDUList([hdu])

    # ---- other HDUs : tables ----
    getformat = hp.fitsfunc.getformat

    for xt in range(len(data)):
        cols = []
        for line in range(len(data[xt])):
            namei = colnames[xt][line]
            array = data[xt][line]
            if bintable:
                nt = len(array)  # total length
                repeat = nt  # length / cell
                fmt = str(repeat) + getformat(array)
                array = np.reshape(array, (nt // repeat, repeat))
            else:
                fmt = getformat(array)
            cols.append(pyfits.Column(name=namei, format=fmt, array=array))
            if bintable:
                tbhdu = pyfits.BinTableHDU.from_columns(cols)
            else:
                tbhdu = pyfits.TableHDU.from_columns(cols)

        if extnames is not None:
            tbhdu.name = extnames[xt]

        ncols = len(cols)
        tbhdu.header['MAX-LPOL'] = (len(data[xt][0]) - 1,
                                    'Maximum L multipole')
        tbhdu.header['POLAR'] = ((ncols > 1))
        tbhdu.header['BCROSS'] = ((ncols > 4))
        tbhdu.header['ASYMCL'] = ((ncols > 6))

        tbhdu.header.add_comment(hline)
        for mycom in comments:
            tbhdu.header.add_comment(mycom)
        for myor in origin:
            tbhdu.header.add_comment(myor)
        tbhdu.header.add_comment(hline)

        if type(keys) is dict:
            for k, v in list(keys.items()):
                tbhdu.header[k] = (v)

        hdulist.append(tbhdu)

    # write the file
    hdulist.writeto(filename, overwrite=True)

    # checking out the file
    #
    try:
        # pyfits.info(filename)
        p1 = pyfits.getdata(filename)
        junk = hp.mrdfits(filename)
        print(prefix,
              '%s checking out %s%s' % (GREEN_COLOR, filename, NO_COLOR),
              flush=True)
    except:
        raise RuntimeError('Failed to load {}'.format(filename))