Exemple #1
0
def maps_view(**kwargs):
    """Viewer interface for healpix maps
    """
    input_file = kwargs['infile']
    healpix_maps = hp.read_map(input_file, field=kwargs['field'])
    if not os.path.exists(input_file):
        abort("Map %s not found!" % input_file)
    t = os.path.basename(input_file)
    plt.figure(figsize=(10, 7), dpi=80)
    nside_out = kwargs['udgrade']
    logger.info('Returning a map with NSIDE=%i' % nside_out)
    if kwargs['field'] == 0:
        if kwargs['counts'] == True:
            healpix_maps = hp.pixelfunc.ud_grade(healpix_maps,
                                                 nside_out,
                                                 pess=True,
                                                 power=-2)
        else:
            healpix_maps = hp.pixelfunc.ud_grade(healpix_maps,
                                                 nside_out,
                                                 pess=True)
        if kwargs['optimized'] == True:
            logger.info('Optimizing...')
            hp.mollview(healpix_maps, title=t.replace('.fits',''), \
                            coord='G', min=1e-7, max=1e-4, norm='log')
            hp.graticule()
            overlay_tag(color='silver', x=0.45)
            save_current_figure(t.replace('.fits', '.png'))
        else:
            hp.mollview(healpix_maps, title=t.replace('.fits',''), \
                            coord='G')
            hp.graticule()
            overlay_tag(color='silver', x=0.45)
            save_current_figure(t.replace('.fits', '.png'))
    else:
        for i, maps in enumerate(healpix_maps):
            healpix_maps = hp.pixelfunc.ud_grade(healpix_maps, nside_out, \
                                                     pess=True)
            if kwargs['optimized'] == True:
                logger.info('Optimizing...')
                hp.mollview(maps, title=t.replace('.fits','_%i'%i), \
                                coord='G', min=1e-7, max=1e-4, norm='log')
                hp.graticule()
                overlay_tag(color='silver', x=0.45)
                save_current_figure(t.replace('.fits', '.png'))
            else:
                hp.mollview(healpix_maps, title=t.replace('.fits',''), \
                                coord='G')
                hp.graticule()
                overlay_tag(color='silver', x=0.05)
                save_current_figure(t.replace('.fits', '_%i.png' % i))
Exemple #2
0
                np.sqrt(len(cls_tocompare[j][i][_index]))
            _cls_rebin.append(clmean)
            _clerrs_rebin.append(clmeanerr)
        _l_rebin = np.array(_l_rebin)
        l_range_fit = np.where(np.logical_and(_l_rebin>=l_min, _l_rebin<l_max))
        _cls_rebin = np.array(_cls_rebin)
        _clerrs_rebin = np.array(_clerrs_rebin)
        cp =  np.polyfit(_l_rebin[l_range_fit], _cls_rebin[l_range_fit], 0, 
                         w=1/_clerrs_rebin[l_range_fit])
        lab = os.path.basename(f).replace('_13bins_cls.txt', '')
        plt.errorbar(_l_rebin, _cls_rebin, fmt='o', markersize=3, \
                         elinewidth=1, xerr=[xerrL, xerrR], \
                         yerr=_clerrs_rebin, label=lab )
        plt.plot([1, 1000], [cp[0], cp[0]], '-', linewidth=1, label='Fit '+lab)
    plt.plot([l_max, l_max], [-5e-15, 5e-15], '--', color='silver')
    plt.plot([l_min, l_min], [-5e-15, 5e-15], '--', color='silver')
    plt.xlim(1, _l[-1])
    plt.ylim(ymin, ymax)
    plt.xscale('log')
    #plt.yscale('log', nonposy='clip')
    plt.xlabel('$l$')
    plt.ylabel('$C_{sig,l}$')
    plt.title('%.2f - %.2f MeV'%(emin[i], emax[i]))
    plt.legend(loc=4, fontsize=10)
    save_current_figure(OUT_LABEL+'_%i-%i.png'%(emin[i], emax[i]))
    ymin = ymin + abs(ymin/(1.5+0.01*i))
    ymax = ymax - abs(ymax/(1.5+0.01*i))

    

Exemple #3
0
FLUX_LABELS = ['UCV (t56) w/o Foreground sub', 'UCV (t56) w/ Foreground sub']
#OUT_LABEL = 'Flux_t56_srcmask2_Rm-Rp'
#OUT_LABEL = 'Flux_types_srcmask2'
#OUT_LABEL = 'Flux_t56_srcmask2-1p5-weighted'
#OUT_LABEL = 'Flux_t56_maskweight_north-south'
#OUT_LABEL = 'Flux_t56_maskweight_east-west'
OUT_LABEL = 'Flux_t56_maskweight'

plt.figure(figsize=(10, 7), dpi=80)
from GRATools.utils.gDrawRef import ref_igrb_band
from GRATools.utils.gDrawRef import ref_igrb_noFGsub
leg, lab = ref_igrb_band()
igrb, lab_igrb = ref_igrb_noFGsub()
flux = []
for f in FLUX_FILES:
    from GRATools.utils.gFTools import get_cl_param
    _emin, _emax, _emean, _f, _ferr, _cn, fsky = get_cl_param(f)
    
    spec = plt.errorbar(_emean, _f*_emean, fmt='o', markersize=3, \
                     elinewidth=1, xerr=(_emax-_emin)/2, yerr=_ferr*_emean)
    label = os.path.basename(f).replace('_parameters.txt', '')
    flux.append(spec)
plt.xscale("log")
plt.yscale("log")
plt.xlabel('Energy [MeV]')
plt.ylabel('E$^{2}$ $\cdot$ Flux [MeV cm$^{-2}$ s$^{-1}$ sr$^{-1}$]')
plt.title(' Energy Spectrum')
plt.legend([igrb, leg]+flux, [lab_igrb, lab]+FLUX_LABELS, loc=3)
#overlay_tag()
save_current_figure(OUT_LABEL+'_ESpec.png')
Exemple #4
0
def mkCl(**kwargs):
    """                                      
    """
    get_var_from_file(kwargs['config'])

    logger.info('Calculating PSF with gtpsf...')
    dict_gtpsf = data.DICT_GTPSF
    logger.info('Calculating Wbeam Function...')
    out_wb_label = data.OUT_W_LABEL
    mask_label = data.MASK_LABEL
    out_wb_txt = os.path.join(GRATOOLS_OUT, 'Wbeam_%s.txt' % out_wb_label)
    if not os.path.exists(out_wb_txt):
        from GRATools.utils.ScienceTools_ import gtpsf
        gtpsf(dict_gtpsf)
        from GRATools.utils.gWindowFunc import get_psf
        psf_file = data.PSF_FILE
        psf = get_psf(psf_file)
        _l = np.arange(0, 1000)
        from GRATools.utils.gWindowFunc import build_wbeam
        wb = build_wbeam(psf, _l, out_wb_txt)
    else:
        from GRATools.utils.gWindowFunc import get_wbeam
        wb = get_wbeam(out_wb_txt)
    save_current_figure('Wbeam_%s.png' % out_wb_label, clear=True)

    logger.info('Starting Cl analysis...')
    in_label = data.IN_LABEL
    in_label = in_label + '_' + mask_label
    out_label = data.OUT_LABEL
    binning_label = data.BINNING_LABEL
    mask_file = data.MASK_FILE
    mask = hp.read_map(mask_file)
    cl_param_file = os.path.join(GRATOOLS_OUT, '%s_%s_parameters.txt' \
                                     %(in_label, binning_label))
    from GRATools.utils.gFTools import get_cl_param
    _emin, _emax, _emean, _f, _ferr, _cn, _fsky = get_cl_param(cl_param_file)
    cl_txt = open(os.path.join(GRATOOLS_OUT, '%s_%s_cls.txt' \
                                   %(out_label, binning_label)), 'w')
    for i, (emin, emax) in enumerate(zip(_emin, _emax)):
        logger.info('Considering bin %.2f - %.2f ...' % (emin, emax))
        gamma = data.WEIGHT_SPEC_INDEX
        Im = (1 / (1 - gamma)) * (emax**(1 - gamma) -
                                  emin**(1 - gamma)) / (emax - emin)
        eweightedmean = np.power(1 / Im, 1 / gamma)
        cl_txt.write('ENERGY\t %.2f %.2f %.2f\n' % (emin, emax, eweightedmean))
        l_max = 1000
        _l = np.arange(l_max)
        wb_en = wb.hslice(eweightedmean)(_l)
        flux_map_name = in_label + '_flux_%i-%i.fits' % (emin, emax)
        flux_map = hp.read_map(os.path.join(GRATOOLS_OUT_FLUX, flux_map_name))
        flux_map_masked = hp.ma(flux_map)
        flux_map_masked.mask = np.logical_not(mask)
        fsky = 1.-(len(np.where(flux_map_masked.filled() == hp.UNSEEN)[0])/\
                       float(len(flux_map)))
        if kwargs['show'] == True:
            hp.mollview(flux_map_masked.filled(),
                        title='f$_{sky}$ = %.3f' % fsky,
                        min=1e-7,
                        max=1e-4,
                        norm='log')
            plt.show()
        print 'fsky = ', fsky
        nside = hp.npix2nside(len(flux_map))
        wpix = hp.sphtfunc.pixwin(nside)[:l_max]
        _cl = hp.sphtfunc.anafast(flux_map_masked.filled(), lmax=l_max-1, \
                                      iter=5)
        _cl_fit = hp.sphtfunc.anafast(flux_map_masked.filled(), iter=4)
        cn_fit = np.average(_cl_fit[-500:-100] / fsky) / len(
            _cl_fit[-500:-100])
        print 'cn fit = ', cn_fit
        print 'cn poisson = ', _cn[i]
        cn = _cn[i]
        wl = wb_en * wpix
        _cl = (_cl / fsky - cn) / (wl**2)
        cl_txt.write('Cl\t%s\n'%str(list(_cl)).replace('[',''). \
                         replace(']','').replace(', ', ' '))
        _cl_err = np.sqrt(2. / ((2 * _l + 1) * fsky)) * (_cl + (cn / wl**2))
        cl_txt.write('Cl_ERR\t%s\n\n'%str(list(_cl_err)).replace('[',''). \
                         replace(']','').replace(', ', ' '))
    cl_txt.close()
    logger.info('Created %s'%(os.path.join(GRATOOLS_OUT, '%s_%s_cls.txt' \
                                               %(out_label, binning_label))))
        plt.errorbar(emeans[i] / 1000,
                     cps_tocompare[i] * (emeans[i] / 1000)**4 /
                     ((emaxs[i] - emins[i]) / 1000)**2,
                     fmt='o',
                     markersize=3,
                     elinewidth=1,
                     xerr=[(emeans[i] - emins[i]) / 1000,
                           (emaxs[i] - emeans[i]) / 1000],
                     yerr=cperrs_tocompare[i] * (emeans[i] / 1000)**4 /
                     ((emaxs[i] - emins[i]) / 1000)**2))
plt.xlabel('E [GeV]')
plt.ylabel('E$^{4}$/$\Delta$E$^{2}$ $\cdot$ C$_{P}$')
plt.xscale('log')
#plt.yscale('log', nonposy='clip')
plt.legend([leg_ref] + leg, [lab_ref] + lab, loc=2)
save_current_figure(OUT_LABEL + '.png')

plt.figure(figsize=(10, 7), dpi=80)
lab = []
leg = []
for i, f in enumerate(Cl_FILES):
    lab.append(os.path.basename(f).replace('_13bins_cross.txt', ''))
    leg.append(
        plt.errorbar(emeans[i] / 1000,
                     abs(0 - cps_tocompare[i]),
                     fmt='o',
                     markersize=3,
                     elinewidth=1,
                     xerr=[(emeans[i] - emins[i]) / 1000,
                           (emaxs[i] - emeans[i]) / 1000],
                     yerr=cperrs_tocompare[i]))
Exemple #6
0
def mkCross(**kwargs):
    """                                      
    """
    get_var_from_file(kwargs['config'])

    logger.info('Calculating PSF with gtpsf...')
    dict_gtpsf = data.DICT_GTPSF
    logger.info('Calculating Wbeam Function...')
    out_wb_label = data.OUT_W_LABEL
    out_wb_txt = os.path.join(GRATOOLS_OUT, 'Wbeam_%s.txt'%out_wb_label)
    if not os.path.exists(out_wb_txt):
        from GRATools.utils.ScienceTools_ import gtpsf
        gtpsf(dict_gtpsf)
        from GRATools.utils.gWindowFunc import get_psf
        psf_file = data.PSF_FILE
        psf = get_psf(psf_file)
        _l = np.arange(0, 1000)
        from GRATools.utils.gWindowFunc import build_wbeam
        wb = build_wbeam(psf, _l, out_wb_txt)
    else:
        from GRATools.utils.gWindowFunc import get_wbeam
        wb = get_wbeam(out_wb_txt)
    save_current_figure('Wbeam_%s.png'%out_wb_label, clear=True)

    logger.info('Starting Cl analysis...')
    in_label1 = data.IN_LABEL1
    in_label2 = data.IN_LABEL2
    out_label = data.OUT_LABEL
    binning_label = data.BINNING_LABEL
    mask_file = data.MASK_FILE
    mask = hp.read_map(mask_file)
    cl_param_file1 = os.path.join(GRATOOLS_OUT, '%s_%s_parameters.txt' \
                                     %(in_label1, binning_label))
    cl_param_file2 = os.path.join(GRATOOLS_OUT, '%s_%s_parameters.txt' \
                                      %(in_label2, binning_label))
    from GRATools.utils.gFTools import get_cl_param
    _emin, _emax, _emean, _f, _ferr, _cn, _fsky = get_cl_param(cl_param_file1)
    _emin2, _emax2, _emean2, _f2, _ferr2, _cn2, _fsky2 = get_cl_param(cl_param_file2)
    cross_txt = open(os.path.join(GRATOOLS_OUT, '%s_%s_cross.txt' \
                                   %(out_label, binning_label)), 'w')
    for i, (emin, emax) in enumerate(zip(_emin, _emax)):
        logger.info('Considering bin %.2f - %.2f ...'%(emin, emax))
        gamma = data.WEIGHT_SPEC_INDEX
        Im = (1/(1-gamma))*(emax**(1-gamma)-emin**(1-gamma))/(emax-emin)
        eweightedmean = np.power(1/Im, 1/gamma)
        cross_txt.write('ENERGY\t %.2f %.2f %.2f\n'%(emin, emax, eweightedmean))
        l_max= 1000
        _l = np.arange(l_max)
        wb_en = wb.hslice(eweightedmean)(_l)
        flux_map_name1 = in_label1+'_flux_%i-%i.fits'%(emin, emax)
        flux_map_name2 = in_label2+'_flux_%i-%i.fits'%(emin, emax)
        flux_map1 = hp.read_map(os.path.join(GRATOOLS_OUT_FLUX, flux_map_name1))
        flux_map2 = hp.read_map(os.path.join(GRATOOLS_OUT_FLUX, flux_map_name2))
        flux_map_masked1 = hp.ma(flux_map1)
        flux_map_masked1.mask = np.logical_not(mask)
        flux_map_masked2 = hp.ma(flux_map2)
        flux_map_masked2.mask = np.logical_not(mask)
        fsky1 = 1.-(len(np.where(flux_map_masked1.filled() == hp.UNSEEN)[0])/\
                       float(len(flux_map1)))
        fsky2 = 1.-(len(np.where(flux_map_masked2.filled() == hp.UNSEEN)[0])/\
                       float(len(flux_map2)))
        if kwargs['show'] == True:
            hp.mollview(flux_map_masked1.filled(), title='f$_{sky}$ = %.3f'%fsky,
                        min=1e-7, max=1e-4, norm='log')
            plt.show()
        print 'fsky = ', fsky1, fsky2
        fsky = np.sqrt(fsky1*fsky2)
        nside1 = hp.npix2nside(len(flux_map1))
        nside2 = hp.npix2nside(len(flux_map1))
        wpix1 = hp.sphtfunc.pixwin(nside1)[:l_max]
        wpix2 = hp.sphtfunc.pixwin(nside2)[:l_max]
        _cl_cross = hp.sphtfunc.anafast(flux_map_masked1.filled(),
                                        flux_map_masked2.filled(), lmax=l_max-1, \
                                             iter=5)
        wl2 = wb_en*wb_en*wpix1*wpix2
        _cl_cross = (_cl_cross/fsky)/(wl2)
        cross_txt.write('Cl\t%s\n'%str(list(_cl_cross)).replace('[',''). \
                         replace(']','').replace(', ', ' '))
        _cl_cross_err = np.sqrt(2./((2*_l+1)*fsky))*(_cl_cross)
        cross_txt.write('Cl_ERR\t%s\n\n'%str(list(_cl_cross_err)).replace('[',''). \
                         replace(']','').replace(', ', ' '))
    cross_txt.close()
    logger.info('Created %s'%(os.path.join(GRATOOLS_OUT, '%s_%s_cross.txt' \
                                               %(out_label, binning_label))))
FLUX_LABELS = ['UCV (t56) w/o Foreground sub', 'UCV (t56) w/ Foreground sub']
#OUT_LABEL = 'Flux_t56_srcmask2_Rm-Rp'
#OUT_LABEL = 'Flux_types_srcmask2'
#OUT_LABEL = 'Flux_t56_srcmask2-1p5-weighted'
#OUT_LABEL = 'Flux_t56_maskweight_north-south'
#OUT_LABEL = 'Flux_t56_maskweight_east-west'
OUT_LABEL = 'Flux_t56_maskweight'

plt.figure(figsize=(10, 7), dpi=80)
from GRATools.utils.gDrawRef import ref_igrb_band
from GRATools.utils.gDrawRef import ref_igrb_noFGsub
leg, lab = ref_igrb_band()
igrb, lab_igrb = ref_igrb_noFGsub()
flux = []
for f in FLUX_FILES:
    from GRATools.utils.gFTools import get_cl_param
    _emin, _emax, _emean, _f, _ferr, _cn, fsky = get_cl_param(f)

    spec = plt.errorbar(_emean, _f*_emean, fmt='o', markersize=3, \
                     elinewidth=1, xerr=(_emax-_emin)/2, yerr=_ferr*_emean)
    label = os.path.basename(f).replace('_parameters.txt', '')
    flux.append(spec)
plt.xscale("log")
plt.yscale("log")
plt.xlabel('Energy [MeV]')
plt.ylabel('E$^{2}$ $\cdot$ Flux [MeV cm$^{-2}$ s$^{-1}$ sr$^{-1}$]')
plt.title(' Energy Spectrum')
plt.legend([igrb, leg] + flux, [lab_igrb, lab] + FLUX_LABELS, loc=3)
#overlay_tag()
save_current_figure(OUT_LABEL + '_ESpec.png')
#               'UCV-PSF1+2+3 srcmask2']
OUT_LABEL = 'Cp_t56_srcmask2-1p5-weight' 
#OUT_LABEL = 'Cp_t56_maskweight_all-north-south'
#OUT_LABEL = 'Cp_t56_maskweight_all-east-west'
#OUT_LABEL = 'Cp_t56_all-north-south'
#OUT_LABEL = 'Cp_t56_all-east-west'
#OUT_LABEL = 'Cp_types_srmask2'

plt.figure(figsize=(10, 7), dpi=80)
emin, emax, emean, cps_ref, cperrs_ref = cp_parse(FLUX_REF)
plt.plot((emin[0], emax[-1]), (0, 0), '--', color='gray')
plt.plot((0.1, 1000), (0.1, 0.1), '-', color='silver', linewidth=1.0)
plt.plot((0.1, 1000), (-0.1, -0.1), '-', color='silver', linewidth=1.0)
spec, spec_label = [], []
plt.title('Flux Residuals - Ref.: %s'%FLUX_REF_LABEL)
for f in FLUX_FILES:
    emin, emax, emean, cps, cperrs = cp_parse(f)
    _res = (cps_ref - cps)/cps_ref
    _res_err = np.sqrt(((cps/cps_ref**2)*cperrs_ref)**2+(cperrs/cps_ref)**2)
    cp_plot = plt.errorbar(emean, _res, fmt='o', markersize=3,
                           elinewidth=1, 
                           xerr=[(emean-emin), (emax-emean)], 
                           yerr=_res_err)
    spec.append(cp_plot)
plt.xscale("log")
plt.ylim(-1, 1)
plt.xlabel('Energy [GeV]')
plt.ylabel('(C$_{P,ref}$ - C$_{P}$) / C$_{P,ref}$')
plt.legend(spec, FLUX_LABELS, loc=3)
save_current_figure(OUT_LABEL+'_residuals.png')
Exemple #9
0
def mkCl(**kwargs):
    """                                      
    """
    get_var_from_file(kwargs['config'])
    logger.info('Calculating PSF with gtpsf...')
    dict_gtpsf = data.DICT_GTPSF
    logger.info('Calculating Wbeam Function...')
    out_wb_label = data.OUT_W_LABEL

    out_wb_txt = os.path.join(GRATOOLS_OUT, 'Wbeam_%s.txt' % out_wb_label)
    if not os.path.exists(out_wb_txt):
        from GRATools.utils.ScienceTools_ import gtpsf
        gtpsf(dict_gtpsf)
        from GRATools.utils.gWindowFunc import get_psf
        psf_file = data.PSF_FILE
        psf = get_psf(psf_file)
        _l = np.arange(0, 1000)
        from GRATools.utils.gWindowFunc import build_wbeam
        wb = build_wbeam(psf, _l, out_wb_txt)
    else:
        from GRATools.utils.gWindowFunc import get_wbeam
        wb = get_wbeam(out_wb_txt)
    save_current_figure('Wbeam_%s.png' % out_wb_label, clear=True)

    logger.info('Starting Cl analysis...')
    in_label = data.IN_LABEL
    mask_label = data.MASK_LABEL
    in_label = in_label + '_' + mask_label
    out_label = data.OUT_LABEL
    binning_label = data.BINNING_LABEL
    mask_file = data.MASK_FILE
    cl_param_file = os.path.join(GRATOOLS_OUT, '%s_%s_parameters.txt' \
                                     %(in_label, binning_label))
    from GRATools.utils.gFTools import get_cl_param
    _emin, _emax, _emean, _f, _ferr, _cn, _fsky = get_cl_param(cl_param_file)
    cl_txt = open(os.path.join(GRATOOLS_OUT, '%s_%s_polspicecls.txt' \
                                   %(out_label, binning_label)), 'w')
    for i, (emin, emax) in enumerate(zip(_emin, _emax)):
        logger.info('Considering bin %.2f - %.2f ...' % (emin, emax))
        mask_f = mask_file
        if type(mask_file) == list:
            mask_f = mask_file[i]
        gamma = data.WEIGHT_SPEC_INDEX
        Im = (1 / (1 - gamma)) * (emax**(1 - gamma) -
                                  emin**(1 - gamma)) / (emax - emin)
        eweightedmean = np.power(1 / Im, 1 / gamma)
        cl_txt.write('ENERGY\t %.2f %.2f %.2f\n' % (emin, emax, eweightedmean))
        l_max = 1000
        _l = np.arange(l_max)
        wb_en = wb.hslice(eweightedmean)(_l)
        flux_map_name = in_label + '_flux_%i-%i.fits' % (emin, emax)
        flux_map_f = os.path.join(GRATOOLS_OUT_FLUX, flux_map_name)
        flux_map = hp.read_map(flux_map_f)
        fsky = _fsky[i]
        if kwargs['show'] == True:
            hp.mollview(flux_map_masked.filled(),
                        title='f$_{sky}$ = %.3f' % fsky,
                        min=1e-7,
                        max=1e-4,
                        norm='log')
            plt.show()
        logger.info('fsky = ' % fsky)
        nside = hp.npix2nside(len(flux_map))
        wpix = hp.sphtfunc.pixwin(nside)[:l_max]
        out_name = '%s_%i-%i' % (out_label, emin, emax)
        out_folder = os.path.join(GRATOOLS_OUT, 'output_pol')
        if not os.path.exists(out_folder):
            os.makedirs(out_folder)
        pol_dict = data.POLCEPICE_DICT
        for key in pol_dict:
            if key == 'clfile':
                pol_dict[key] = os.path.join(out_folder,
                                             '%s_cl.txt' % out_name)
            if key == 'cl_outmap_file':
                pol_dict[key] = os.path.join(out_folder,
                                             '%s_clraw.txt' % out_name)
            if key == 'covfileout':
                pol_dict[key] = os.path.join(out_folder,
                                             '%s_cov.fits' % out_name)
            if key == 'mapfile':
                pol_dict[key] = flux_map_f
            if key == 'maskfile':
                pol_dict[key] = mask_f
        config_file_name = 'pol_%s' % (out_name)
        _l, _cl, _cl_err = pol_cl_calculation(pol_dict, config_file_name)
        logger.info('cn poisson = %e' % _cn[i])
        cn = _cn[i]
        wl = wb_en * wpix
        _cl = (_cl[:l_max] - cn) / (wl**2)
        _cl_err = _cl_err[:l_max] / (wl**2)
        cl_txt.write('Cl\t%s\n'%str(list(_cl)).replace('[',''). \
                         replace(']','').replace(', ', ' '))
        #_cl_err = np.sqrt(2./((2*_l+1)*fsky))*(_cl+(cn/wl**2))
        cl_txt.write('Cl_ERR\t%s\n\n'%str(list(_cl_err)).replace('[',''). \
                         replace(']','').replace(', ', ' '))
    cl_txt.close()
    logger.info(
        'Created %s' %
        (os.path.join(GRATOOLS_OUT, '%s_%s_polspicecls.txt' %
                      (out_label, binning_label))))
Exemple #10
0
    cperrs_tocompare.append(np.array(cperrs))
    logger.info('Created %s' %f.replace('_cls.txt', '_cps.txt'))
    txt.close()

print cps_tocompare[0]*(emeans[0]/1000)**4/((emaxs[0]-emins[0])/1000)**2
print emeans[0]/1000
from GRATools.utils.gDrawRef import ref_cp_band
plt.figure(figsize=(10, 7), dpi=80)
lab = []
leg = []
leg_ref, lab_ref = ref_cp_band()
for i, f in enumerate(Cl_FILES):
    #print cps_tocompare[i]
    lab.append(os.path.basename(f).replace('_13bins_cls.txt', ''))
    leg.append(plt.errorbar(emeans[i]/1000, 
             cps_tocompare[i]*(emeans[i]/1000)**4/((emaxs[i]-emins[i])/1000)**2,
             fmt='o', markersize=3, elinewidth=1,
             xerr=[(emeans[i]-emins[i])/1000, (emaxs[i]-emeans[i])/1000],
             yerr=cperrs_tocompare[i]*(emeans[i]/1000)**4/((emaxs[i]-emins[i])/1000)**2))
plt.xlabel('E [GeV]')
plt.ylabel('E$^{4}$/$\Delta$E$^{2}$ $\cdot$ C$_{P}$')
plt.xscale('log')
plt.yscale('log', nonposy='clip')
plt.legend([leg_ref]+leg, [lab_ref]+lab, loc=3)

save_current_figure(OUT_LABEL+'.png')
#plt.show()

    

Exemple #11
0
def pol_cov_parse(pol_cov_out_file, wl_array=None, rebin=False, show=False):
    """Created to parse and return the fits output file of PolSpice, which 
       contains the covariance matrix of the angular power spectra (APS).

       pol_cov_out_file :
          .fits file containing the covariance matrix created by PolSpice
       wl_array : numpy array (or spline)
          array (or the spline) of the  Wbeam function as a funcion of l 
          integrated in a energy bin.
       rebin : bool
          if True a multipole rebinni of the APS is done. 
          ATT: the multipole bins are hardcoded; if you want to change it 
          you must modify 'rebinning' variable defined at the beginnig of 
          GRATools/utils/gPolSpice.py 
       show : bool
          if True a png image of the covariance matrix is saved in 
          GRATools/output/figures 
    """
    hdu = pf.open(pol_cov_out_file)
    _cov = hdu[0].data[0]
    hdu.close()
    _l = np.arange(len(_cov))
    if wl_array is not None:
        wl = wl_array
        _l = np.arange(len( wl_array))
        _cov = np.array([_cov[i][:len(wl)] for i in range(0,len(wl))])
        _cov = _cov/(wl**2)
        for l in _l:
            _cov[l] = _cov[l]/(wl[l]**2)    
    if rebin:
        _covr = []
        _lr = []
        for imin, imax in zip(rebinning[:-1], rebinning[1:]):
            _imean = np.sqrt(imin*imax)
            _covrj = []
            _lmean = np.sqrt(imin*imax)
            _lr.append(_lmean)
            for jmin, jmax in zip(rebinning[:-1], rebinning[1:]):
                _covrj.append(np.mean(_cov[imin:imax, jmin:jmax]))
            _covr.append(np.array(_covrj))
        _cov = np.array(_covr)
        _l = np.array(_lr)
    else:
        pass 
    pic.dump(_cov, 
             open(pol_cov_out_file.replace('.fits', '.pkl'),'wb'))
    if show==True:
         _cov2ploti = []
         for i in range(0, len(_l)):
             sigii = _cov[i][i]
             _cov2plotj = []
             for j in range(0, len(_l)):
                 sigjj = _cov[j][j]
                 sigij = _cov[j][i]
                 if sigij < 0:
                     sigij = 1e-100
                 _cov2plotj.append(np.sqrt(sigij/np.sqrt(sigii*sigjj)))
             _cov2ploti.append(_cov2plotj)
         _cov2ploti = np.array(_cov2ploti)
         fig = plt.figure(facecolor='white')
         ax = fig.add_subplot(111)
         cax = ax.matshow(np.log10(np.abs(_cov)), origin='lower', 
                          aspect='auto', cmap='Spectral')
         en_tick = list(np.logspace(0, np.log10(1500), 6).astype(int))
         ax.set_yticklabels(['']+en_tick)
         ax.set_xticklabels(['']+en_tick)
         plt.title('Covariance matrix')
         plt.xlabel('$l_{i}$')
         plt.ylabel('$l_{j}$')
         cb = plt.colorbar(cax, format='$%i$')
         plt.grid()
         save_current_figure(os.path.basename(pol_cov_out_file).replace('.fits',
                                                                       ''))
    return _cov