Esempio n. 1
0
    def __init__(self, config, r, Alens, radec):

        self.config = config
        self.nus = self.config['frequency']
        self.depth_p = self.config['depth_p']
        #print(self.depth_p)
        #stop
        self.nside = 64
        self.npix = 12 * self.nside**2
        self.nfreqs = len(self.nus)
        self.w = None
        self.lmin = 20
        self.lmax = 2 * self.nside - 1
        #self.lmax=355
        self.dl = 10
        self.r = r
        self.Alens = Alens
        self.cc = 0
        self.fsky = self.config['fsky']
        self.radec = radec
        self.covmap = get_coverage(self.fsky,
                                   self.nside,
                                   center_radec=self.radec)

        maskpix = np.zeros(12 * self.nside**2)
        self.pixok = self.covmap > 0
        maskpix[self.pixok] = 1
        self.Namaster = nam.Namaster(maskpix,
                                     lmin=self.lmin,
                                     lmax=self.lmax,
                                     delta_ell=self.dl)
        self.Namaster.fsky = self.fsky
        self.Namaster.ell_binned, _ = self.Namaster.get_binning(self.nside)
        #self.Namaster.ell_binned=self.Namaster.ell_binned[:-1]
        #print(self.Namaster.ell_binned.shape)

        print('*********************************')
        print('********** Parameters ***********')
        print('*********************************')
        print()
        print('    Frequency [GHz] : {}'.format(self.nus))
        print('    Depth [muK.arcmin] : {}'.format(self.depth_p))
        print('    Nside : {}'.format(self.nside))
        print('    Fsky : {}'.format(self.fsky))
        print('    Patch sky : {}'.format(self.radec))
        print('    lmin : {}'.format(self.lmin))
        print('    lmax : {}'.format(self.lmax))
        print('    dl : {}'.format(self.dl))
        print('    r : {}'.format(self.r))
        print('    Alens : {}'.format(self.Alens))
        print('    ell : {}'.format(self.Namaster.ell_binned))
        print()
        print('*********************************')
        print('*********************************')
        print('*********************************\n')
Esempio n. 2
0
def get_binned_spectra(nside, lmin, lmax, delta_ell, input_spectra):
    ### Making mask - it will be automaticall apodized when instanciating the object with default (tunable) parameters
    import NamasterLib as nam
    mask = np.zeros(12 * nside**2)
    mask[np.arange(10)] = 1
    Namaster = nam.Namaster(mask, lmin=lmin, lmax=lmax, delta_ell=delta_ell)
    ell_binned, b = Namaster.get_binning(nside)
    #print(input_spectra.shape)
    binned_spectra = Namaster.bin_spectra(
        input_spectra, nside)  #Namaster.bin_spectra(input_Dl[0, :], nside)
    return binned_spectra
Esempio n. 3
0
# print(residuals.shape)
#
# # There is only the patch so you need to put them in a full map to plot with healpy
# noisemaps = np.zeros_like(qubicmaps)
# noisemaps[:, :, seenmap, :] = residuals

# ================== Power spectrum =============================
print('\n =============== Starting power spectrum ================')
# Create a Namaster object
lmin = 40
lmax = 2 * d['nside'] - 1
delta_ell = 30

mask = np.zeros(12 * d['nside']**2)
mask[seenmap] = 1
Namaster = nam.Namaster(mask, lmin=lmin, lmax=lmax, delta_ell=delta_ell)
mask_apo = Namaster.get_apodized_mask()

ell_binned, b = Namaster.get_binning(d['nside'])
nbins = len(ell_binned)
print('lmin:', lmin)
print('lmax:', lmax)
print('delta_ell:', delta_ell)
print('nbins:', nbins)
print('ell binned:', ell_binned)

# Possible combinations between bands
combi = list(combinations_with_replacement(np.arange(nbands), 2))
ncombi = len(combi)
print('combi:', combi)
print('ncombi:', ncombi)
Esempio n. 4
0
def apply_fgb(inmaps,
              freqs,
              fwhms,
              verbose=True,
              apodize=0,
              plot_apo=False,
              apocut=False,
              apotype='C1',
              coverage_recut=None,
              coverage=None,
              resol_correction=True,
              ref_fwhm=0.5,
              alm_space=False,
              plot_separated=False,
              center=None,
              add_title='',
              plot_residuals=False,
              truth=None,
              alm_maps=False,
              apply_to_unconvolved=False):
    ### FGB Configuration
    instrument = fgb.get_instrument('Qubic')
    instrument.frequency = freqs
    instrument.fwhm = fwhms
    components = [fgb.Dust(150., temp=20.), fgb.CMB()]

    ### Check good pixels
    pixok = inmaps[0, 0, :] != hp.UNSEEN
    nside = hp.npix2nside(len(inmaps[0, 0, :]))

    if apodize != 0:
        mymask = pixok.astype(float)
        nmt = nam.Namaster(mymask,
                           40,
                           400,
                           30,
                           aposize=apodize,
                           apotype=apotype)
        apodized_mask = nmt.get_apodized_mask()
        if plot_apo:
            hp.gnomview(apodized_mask,
                        title='Apodized Mask {} deg.'.format(apodize),
                        reso=15,
                        rot=center)
        maps = inmaps * apodized_mask
        maps[:, :, ~pixok] = hp.UNSEEN
    else:
        maps = inmaps.copy()
        apodized_mask = np.ones(12 * nside**2)

    ### Data to feed FGB:
    if alm_space:
        if verbose:
            print(
                '\nFBG in alm-space with resol_correction={} and ref_resol={}'.
                format(resol_correction, ref_fwhm))
        mydata = get_alm_maps(maps,
                              fwhms,
                              ref_fwhm=ref_fwhm,
                              resol_correction=resol_correction,
                              verbose=verbose)

        if (truth is not None) & ~apply_to_unconvolved:
            if verbose:
                print('\nNow reconvolving truth to ref_fwhm = {}'.format(
                    ref_fwhm))
            mytruth = [
                hp.smoothing(truth[0],
                             fwhm=np.deg2rad(ref_fwhm),
                             pol=True,
                             verbose=False),
                hp.smoothing(truth[1],
                             fwhm=np.deg2rad(ref_fwhm),
                             pol=True,
                             verbose=False)
            ]
        space = ' (alm based)'
    else:
        if verbose:
            print(
                '\nFBG in pixel-space with resol_correction={} and ref_resol={}'
                .format(resol_correction, ref_fwhm))

        if resol_correction:
            if verbose:
                print('\nNow reconvolving input maps to ref_fwhm = {}'.format(
                    ref_fwhm))
            mydata = reconvolve(maps, fwhms, ref_fwhm, verbose=verbose)

            if (truth is not None):
                if verbose:
                    print(
                        '\nNow reconvolving truth (dust and CMB) to ref_fwhm = {}'
                        .format(ref_fwhm))
                mytruth = [
                    hp.smoothing(truth[0],
                                 fwhm=np.deg2rad(ref_fwhm),
                                 pol=True,
                                 verbose=False),
                    hp.smoothing(truth[1],
                                 fwhm=np.deg2rad(ref_fwhm),
                                 pol=True,
                                 verbose=False)
                ]
            space = ' (Pixel based - Reconv.)'
        else:
            mydata = maps
            if (truth is not None):
                mytruth = truth.copy()
            space = ' (Pixel based - No Reconv.)'

        if coverage_recut is not None:
            if verbose:
                print('Applying coverage recut to {}'.format(coverage_recut))
            fidregion = (coverage > (coverage_recut * np.max(coverage)))
            mydata[..., ~fidregion] = hp.UNSEEN
            mapregions = np.zeros(12 * nside**2) + hp.UNSEEN
            mapregions[pixok] = 1
            mapregions[fidregion] = 2
            if verbose:
                hp.gnomview(mapregions,
                            rot=center,
                            reso=15,
                            title='Fiducial region: {}'.format(coverage_recut))
                show()

        if (apodize != 0) & (apocut == True):
            fidregion = apodized_mask == 1
            mydata[..., ~fidregion] = hp.UNSEEN

    ### FGB itself
    if verbose: print('Starting FGBuster in s')
    r = separate(components, instrument, mydata, print_option=verbose)
    if verbose: print('Resulting beta: {}'.format(r.x[0]))

    ### Resulting separated maps
    if alm_space:
        if alm_maps:
            ### Directly use the output from FGB => not very accurate because of alm-transform near the edges of the patch
            almdustrec = r.s[0, :, :]
            print('ALM', np.shape(almdustrec))
            dustrec = hp.alm2map(
                almdustrec[..., ::2] + almdustrec[..., 1::2] * 1j, nside)
            dustrec[:, ~pixok] = hp.UNSEEN
            almcmbrec = r.s[1, :, :]
            cmbrec = hp.alm2map(
                almcmbrec[..., ::2] + almcmbrec[..., 1::2] * 1j, nside)
            cmbrec[:, ~pixok] = hp.UNSEEN
        else:
            ### Instead we use the fitted beta and recalculate the component maps in pixel space
            ### This avoids inaccuracy of the alm transformation near the edges of the patch
            A = fgb.MixingMatrix(*components)
            print('          >>> building s = Wd in pixel space')
            A_ev = A.evaluator(instrument.frequency)
            A_maxL = A_ev(r.x)
            print('A_maxl', np.shape(A_maxL))

            if apply_to_unconvolved:
                # We apply the mixing matrix to maps each at its own resolution...
                # this allows to keep the effecgive resolution as good as possible, but surely the bell is no
                # longer Gaussian. It is the combnation of various resolutions with weird weights.
                themaps = maps.copy()
                # Now we calculate the effective Bell
                Bl_each = []
                for fw in fwhms:
                    Bl_gauss_fwhm = hp.gauss_beam(np.radians(fw),
                                                  lmax=2 * nside + 1)
                    Bl_each.append(Bl_gauss_fwhm)
                    plot(Bl_gauss_fwhm, label='FWHM {:4.2}'.format(fw))
                Bl_each = np.array(Bl_each)
                ### Compute W matrix (from Josquin)
                invN = np.diag(np.ones(len(fwhms)))
                inv_AtNA = np.linalg.inv(A_maxL.T.dot(invN).dot(A_maxL))
                W = inv_AtNA.dot(A_maxL.T).dot(invN)
                Bl_eff_Dust = W.dot(Bl_each)[0]  #1 is for the Dust
                Bl_eff_CMB = W.dot(Bl_each)[1]  #1 is for the CMB component

                # print('W matrix')
                # print(W)
                # print('A_maxL matrix')
                # print(A_maxL)
                # print('Bl_each:',np.shape(Bl_each))

                Bl_eff_Dust_new = np.zeros(2 * nside + 1)
                Bl_eff_CMB_new = np.zeros(2 * nside + 1)
                ones_comp = np.ones(2)  #number of components
                for i in range(2 * nside + 1):
                    blunknown = W.dot(Bl_each[:, i] *
                                      np.dot(A_maxL, ones_comp))
                    Bl_eff_Dust_new[i] = blunknown[0]
                    Bl_eff_CMB_new[i] = blunknown[1]

                plot(Bl_eff_CMB, ':', label='Effective Bl CMB: W.Bl', lw=3)
                plot(Bl_eff_Dust, ':', label='Effective Bl Dust: W.Bl', lw=3)
                plot(Bl_eff_CMB_new,
                     '--',
                     label='Effective Bl CMB NEW: W.B.A.1',
                     lw=3)
                plot(Bl_eff_Dust_new,
                     '--',
                     label='Effective Bl Dust NEW: W.B.A.1',
                     lw=3)
                legend()
                # We need to smooth the truth with this Bell
                if (truth is not None):
                    if verbose:
                        print(
                            '\nNow reconvolving truth (dust and CMB) with effective Bell'
                        )
                    mytruth = [
                        hp.smoothing(truth[0],
                                     beam_window=Bl_eff_Dust_new,
                                     pol=True,
                                     verbose=False),
                        hp.smoothing(truth[1],
                                     beam_window=Bl_eff_CMB_new,
                                     pol=True,
                                     verbose=False)
                    ]
            else:
                # We will apply the mixing matrix to maps at a chosen reeference resolution
                # this might not bee the most optimal although it is simple in the sens that the components maps resolution
                # is what we have chosen and is gaussian.
                themaps = reconvolve(maps, fwhms, ref_fwhm, verbose=verbose)
                components_bell = hp.gauss_beam(np.radians(ref_fwhm),
                                                lmax=2 * nside + 1)
            themaps[themaps == hp.UNSEEN] = 0
            ### Needed to comment the two lines below as prewhiten_factors was None
            #prewhiten_factors = fgb.separation_recipes._get_prewhiten_factors(instrument, themaps.shape, nside)
            #invN = np.zeros(prewhiten_factors.shape+prewhiten_factors.shape[-1:])
            r.s = fgb.algebra.Wd(A_maxL, themaps.T)  #, invN=invN)
            r.s = np.swapaxes(r.s, -1, 0)
            dustrec = r.s[0, :, :]
            dustrec[:, ~pixok] = hp.UNSEEN
            cmbrec = r.s[1, :, :]
            cmbrec[:, ~pixok] = hp.UNSEEN
    else:
        dustrec = r.s[0, :, :]
        cmbrec = r.s[1, :, :]

    if plot_separated:
        display_maps(
            dustrec,
            bigtitle=r'$\beta=${0:7.6f} - Reconstructed Dust'.format(r.x[0]) +
            space,
            rot=center,
            figsize=(16, 7))
        display_maps(
            cmbrec,
            bigtitle=r'$\beta=${0:7.6f} - Reconstructed CMB'.format(r.x[0]) +
            space,
            rot=center,
            figsize=(16, 7))

    if truth:
        resid_dust = dustrec - mytruth[0] * apodized_mask
        resid_dust[:, ~pixok] = hp.UNSEEN
        resid_cmb = cmbrec - mytruth[1] * apodized_mask
        resid_cmb[:, ~pixok] = hp.UNSEEN
        if coverage_recut:
            resid_cmb[:, ~fidregion] = hp.UNSEEN
            resid_dust[:, ~fidregion] = hp.UNSEEN
            pixok = fidregion.copy()
        if (apodize != 0) & (apocut == True):
            resid_cmb[:, ~fidregion] = hp.UNSEEN
            resid_dust[:, ~fidregion] = hp.UNSEEN
            pixok = fidregion.copy()
        sigs_dust = np.std(resid_dust[:, pixok], axis=1)
        sigs_cmb = np.std(resid_cmb[:, pixok], axis=1)
        if plot_residuals:
            #             display_maps(mytruth[0], bigtitle=r'$\beta=${0:7.6f} Input Dust'.format(r.x[0])+space,
            #                          rot=center, figsize=(16, 7), add_rms=True)
            #             display_maps(mytruth[1], bigtitle=r'$\beta=${0:7.6f} - Input CMB'.format(r.x[0])+space,
            #                          rot=center, figsize=(16, 7), add_rms=True)

            display_maps(mytruth[0],
                         bigtitle='Truth Dust Reconvolved',
                         rot=center,
                         figsize=(16, 7),
                         add_rms=True,
                         unseen=~pixok)
            display_maps(mytruth[1],
                         bigtitle='Truth CMB Reconvolved',
                         rot=center,
                         figsize=(16, 7),
                         add_rms=True,
                         unseen=~pixok)

            display_maps(
                resid_dust,
                bigtitle=r'$\beta=${0:7.6f} Residuals Dust'.format(r.x[0]) +
                space,
                rot=center,
                figsize=(16, 7),
                add_rms=True)
            display_maps(
                resid_cmb,
                bigtitle=r'$\beta=${0:7.6f} - Residuals CMB'.format(r.x[0]) +
                space,
                rot=center,
                figsize=(16, 7),
                add_rms=True)

            figure()
            suptitle(r'$\beta=${0:7.6f} - Residuals:'.format(r.x[0]) + space,
                     fontsize=30,
                     y=1.05)
            for i in range(3):
                subplot(1, 3, i + 1)
                hist(resid_dust[i, pixok],
                     range=[-5 * sigs_dust[i], 5 * sigs_dust[i]],
                     bins=100,
                     alpha=0.5,
                     color='b',
                     label='Dust: RMS={:4.2g}'.format(sigs_dust[i]),
                     density=True)
                hist(resid_cmb[i, pixok],
                     range=[-5 * sigs_cmb[i], 5 * sigs_cmb[i]],
                     bins=100,
                     alpha=0.5,
                     color='r',
                     label='CMB: RMS={:4.2g}'.format(sigs_cmb[i]),
                     density=True)
                title('Residuals Stokes {}'.format(stk[i]))
                legend()
            tight_layout()
    if truth:
        return r.x[
            0], dustrec, cmbrec, sigs_dust, sigs_cmb, resid_dust, resid_cmb, mytruth[
                0], mytruth[1]
    else:
        return r.x[0], dustrec, cmbrec
Esempio n. 5
0
    def _RUN_MC(self,
                N,
                fit,
                x0,
                covmap,
                beta=[],
                nside_param=0,
                fixcmb=True,
                noiseless=False):

        maskpix = np.zeros(12 * 256**2)
        pixok = covmap > 0
        maskpix[pixok] = 1
        Namaster = nam.Namaster(maskpix, lmin=21, lmax=355, delta_ell=35)

        comp, _ = self._get_comp_instr(nu0=145, fit=fit, x0=x0)
        instr = self._get_instr_nsamples(N_SAMPLE_BAND=10)
        inputs = self.newfg.copy()
        clBB = np.zeros((N, 9))
        clres = np.zeros((N, 9))
        components = np.zeros((N, 3, 3, np.sum(pixok)))
        if nside_param != 0:
            beta = np.zeros(
                (N, fgbuster.MixingMatrix(*comp).n_param, 12 * 256**2))
        else:
            beta = np.zeros((N, fgbuster.MixingMatrix(*comp).n_param))

        print('********** Separation ************')

        for i in range(N):

            if fixcmb:
                seed = 42
            else:
                seed = np.random.randint(1000000)

            print(seed)
            cmb = self._get_cmb(self.covmap, seed)
            if self.nside != 256:
                newcmb = np.zeros((self.newfg.shape[0], self.newfg.shape[0],
                                   12 * self.nside**2))
                for i in range(self.fg.shape[0]):
                    newcmb[i] = hp.pixelfunc.ud_grade(cmb[i], self.nside)
            else:
                newcmb = cmb.copy()

            data = inputs + newcmb.copy()
            print(data.shape)

            r1, components1 = self._separation(comp, instr, data, self.covmap,
                                               beta, nside_param, fit, x0,
                                               noiseless)
            r2, components2 = self._separation(comp, instr, data, self.covmap,
                                               beta, nside_param, fit, x0,
                                               noiseless)

            beta[i] = r1.copy()

            components1[:, :, ~pixok] = 0
            components2[:, :, ~pixok] = 0

            components[i] = components1[:, :, pixok].copy()

            leff, clBB[i] = self._get_clBB(components1[0], components2[0],
                                           Namaster)

            #res1=cmb[0]-components1[0]
            #res2=cmb[0]-components2[0]
            #res1[:, ~pixok]=0
            #res2[:, ~pixok]=0
            #leff, clres[i]=self._get_clBB(res1, res2, Namaster)
            #print(cmb[0, 1, pixok]-components1[0, 1, pixok])

        return leff, clBB, beta, components
Esempio n. 6
0
    def explore_like(self,
                     leff,
                     cl,
                     errors,
                     lmin,
                     dl,
                     cc,
                     rv,
                     otherp=None,
                     cov=None,
                     sample_variance=False):

        #     print(lmin, dl, cc)
        #     print(leff)
        #     print(scl_noise[:,2])
        ### Create Namaster Object
        # Unfortunately we need to recalculate fsky for calculating sample variance
        nside = 256
        lmax = 355
        if cov is None:
            Namaster = nam.Namaster(None, lmin=lmin, lmax=lmax, delta_ell=dl)
            Namaster.fsky = 0.03
        else:
            okpix = cov > (np.max(cov) * float(cc))
            maskpix = np.zeros(12 * nside**2)
            maskpix[okpix] = 1
            Namaster = nam.Namaster(maskpix,
                                    lmin=lmin,
                                    lmax=lmax,
                                    delta_ell=dl)
            Namaster.fsky = 0.03

        #     print('Fsky: {}'.format(Namaster.fsky))
        lbinned, b = Namaster.get_binning(nside)

        ### Bibnning CambLib
        #     binned_camblib = qc.bin_camblib(Namaster, '../../scripts/QubicGeneralPaper2020/camblib.pickle',
        #                                     nside, verbose=False)
        global_dir = '/pbs/home/m/mregnier/sps1/QUBIC+/d0/cls'
        binned_camblib = qc.bin_camblib(Namaster,
                                        global_dir + '/camblib.pkl',
                                        nside,
                                        verbose=False)

        ### Redefine the function for getting binned Cls
        def myclth(ell, r):
            clth = qc.get_Dl_fromlib(ell, r, lib=binned_camblib,
                                     unlensed=True)[1]
            return clth

        allfakedata = myclth(leff, 0.)

        #lll, totDL, unlensedCL = qc.get_camb_Dl(lmax=3*256, r=0)
        ### And we need a fast one for BB only as well
        def myBBth(ell, r):
            clBB = qc.get_Dl_fromlib(ell,
                                     r,
                                     lib=binned_camblib,
                                     unlensed=True,
                                     specindex=2)[1]
            return clBB

        ### Fake data
        fakedata = cl.copy()  #myBBth(leff, 0.)

        if sample_variance:
            covariance_model_funct = Namaster.knox_covariance
        else:
            covariance_model_funct = None

        if otherp is None:
            like, cumint, allrlim, maxL = self.ana_likelihood(
                rv,
                leff,
                fakedata,
                errors,
                myBBth, [[0, 1]],
                covariance_model_funct=covariance_model_funct)
        else:
            like, cumint, allrlim, other, maxL = self.ana_likelihood(
                rv,
                leff,
                fakedata,
                errors,
                myBBth, [[0, 1]],
                covariance_model_funct=covariance_model_funct,
                otherp=otherp)

        if otherp is None:
            return like, cumint, allrlim, maxL
        else:
            return like, cumint, allrlim, other, maxL
def CreateAnafastPartialSky(cl, nside, lmin, lmax, delta_ell, f_sky = 1., plot_results = False, noise_rms = 0):
    import qubic.NamasterLib as nam

    npix = 12 * nside**2

    # Determine SEEN pixels from f_sky using query_disc
    vec = hp.pixelfunc.ang2vec(np.pi/2, np.pi*3/4)
    radius = f_sky*np.pi

    ipix_disc = hp.query_disc(nside=nside, vec=vec, radius=radius, nest=False)
    while len(ipix_disc) < f_sky*npix:
        radius += 0.01*np.pi
        ipix_disc = hp.query_disc(nside=nside, vec=vec, radius=radius, nest=False)
    #print("npix_partial_sky: ", len(ipix_disc))

    m = np.arange(npix)
    m = np.delete(m, ipix_disc, axis=None)

    # Define the seen pixels
    seenpix = ipix_disc

    ### Making mask - it will be automaticall apodized when instanciating the object with default (tunable) parameters
    mask = np.zeros(npix)
    mask[seenpix] = 1
    Namaster = nam.Namaster(mask, lmin=lmin, lmax=lmax, delta_ell=delta_ell)

    if plot_results:
        if not os.path.isdir(path_):
            os.mkdir(path_)
        plt.figure()
        hp.mollview(mask)
        figname = 'fig_map_partial_mask.png'
        dest = os.path.join(path_, figname)
        plt.savefig(dest)  # write image to file
        plt.clf()
        plt.figure()
        mask_apo = Namaster.mask_apo
        hp.mollview(mask_apo)
        figname = 'fig_map_partial_mask_apo.png'
        dest = os.path.join(path_, figname)
        plt.savefig(dest)  # write image to file
        plt.clf()

    ell_binned, b = Namaster.get_binning(nside)
    # Get binned input spectra
    cl_theo_binned = np.zeros(shape=(4, ell_binned.shape[0]))
    for i in range(4):
        cl_theo_binned[i, :] = Namaster.bin_spectra(cl.T[i, :], nside)
    print(cl_theo_binned.shape)

    # Create map
    map_ = hp.synfast(cl.T, nside, pixwin=False, verbose=False, new = True)
    noise = np.random.randn(npix)*noise_rms
    map_ = map_ + noise

    # constructing partial map
    map_partial = map_.copy()

    # Set UNSEEN pixels to zero for NaMaster
    map_partial[:, m] = 0

    # Get spectra
    leff, dells, w = Namaster.get_spectra(map_partial, 
                                        purify_e=True, 
                                        purify_b=False, 
                                        beam_correction=None, 
                                        pixwin_correction=None, 
                                        verbose=False)
    dells = dells.T

    if plot_results: 

        clnames = ['TT', 'EE', 'BB', 'TE']
        ll = np.arange(cl.shape[0])
        #rc('figure', figsize=(12, 8))
        plt.figure(figsize=(12, 8))
        for i in range(dells.shape[0]):
            plt.subplot(2, 2, i+1)
            plt.plot(ll, ll * (ll + 1) * cl[:, i] / (2*np.pi),label="Input spectra")
            plt.plot(leff, leff * (leff + 1) * cl_theo_binned[i, :] / (2*np.pi), "o", label="Binned input spectra")
            plt.plot(leff, dells[i], label="NaMaster")
            plt.xlabel('$\\ell$')
            plt.ylabel('$D_\\ell$')
            plt.title(clnames[i])
            plt.legend()
        plt.tight_layout()
        figname = 'fig_theor_namaster_all_Dl.png'
        dest = os.path.join(path_, figname)
        plt.savefig(dest)  # write image to file
        plt.clf()

    # Anafast spectrum of this map
    # Set UNSEEN pixels to hp.UNSEEN for Anafast
    map_partial[:, m] = hp.UNSEEN
    cl_ana, alm_ana = hp.anafast(map_partial, alm=True, lmax=lmax)

    # Get binned anafast spectra
    cl_ana_binned = np.zeros(shape=(4, ell_binned.shape[0]))
    for i in range(4):
        cl_ana_binned[i, :] = Namaster.bin_spectra(cl_ana[i, :], nside)

    if plot_results:

        mapnames = ['T', 'Q', 'U']
        for i in range(3):
            plt.figure()
            hp.mollview(map_partial[i])
            figname = 'fig_map_partial_{}.png'.format(mapnames[i])
            dest = os.path.join(path_, figname)
            plt.savefig(dest)  # write image to file
            plt.clf()

        for i in range(4):
            # Plot theoretical and anafast spectra
            plt.figure()
            plt.plot(ll, ll * (ll + 1) * cl_ana[i][:lmax+1], label="Anafast")
            plt.plot(leff, leff * (leff + 1) * cl_ana_binned[i], "o", label="Anafast binned")
            plt.plot(ll, ll * (ll + 1) * cl.T[i], 'r', label="Input spectra")
            plt.xlim(0, max(ll))
            plt.title(clnames[i])
            plt.ylabel(r"$\ell (\ell + 1) C_{\ell}^{"+clnames[i]+r"}$")
            plt.legend()
            figname = 'fig_theor_anaf_{}.png'.format(clnames[i])
            dest = os.path.join(path_, figname)
            plt.savefig(dest)  # write image to file
            plt.clf()
	    
    return dells, alm_ana, cl_theo_binned, cl_ana_binned
Esempio n. 8
0
def explore_like(leff,
                 mcl_noise,
                 errors,
                 lmin,
                 dl,
                 cc,
                 rv,
                 otherp=None,
                 cov=None,
                 plotlike=False,
                 plotcls=False,
                 verbose=False,
                 sample_variance=True,
                 mytitle='',
                 color=None,
                 mylabel='',
                 my_ylim=None):

    #     print(lmin, dl, cc)
    #     print(leff)
    #     print(scl_noise[:,2])
    ### Create Namaster Object
    # Unfortunately we need to recalculate fsky for calculating sample variance
    nside = 256
    lmax = 2 * nside - 1
    if cov is None:
        Namaster = nam.Namaster(None, lmin=lmin, lmax=lmax, delta_ell=dl)
        Namaster.fsky = 0.018
    else:
        okpix = cov > (np.max(cov) * float(cc))
        maskpix = np.zeros(12 * nside**2)
        maskpix[okpix] = 1
        Namaster = nam.Namaster(maskpix, lmin=lmin, lmax=lmax, delta_ell=dl)

#     print('Fsky: {}'.format(Namaster.fsky))
    lbinned, b = Namaster.get_binning(nside)

    ### Bibnning CambLib
    #     binned_camblib = qc.bin_camblib(Namaster, '../../scripts/QubicGeneralPaper2020/camblib.pickle',
    #                                     nside, verbose=False)
    binned_camblib = qc.bin_camblib(Namaster,
                                    global_dir + '/doc/CAMB/camblib.pkl',
                                    nside,
                                    verbose=False)

    ### Redefine the function for getting binned Cls
    def myclth(ell, r):
        clth = qc.get_Dl_fromlib(ell, r, lib=binned_camblib, unlensed=False)[0]
        return clth

    allfakedata = myclth(leff, 0.)

    ### And we need a fast one for BB only as well
    def myBBth(ell, r):
        clBB = qc.get_Dl_fromlib(ell,
                                 r,
                                 lib=binned_camblib,
                                 unlensed=False,
                                 specindex=2)[0]
        return clBB

    ### Fake data
    fakedata = myBBth(leff, 0.)

    if sample_variance:
        covariance_model_funct = Namaster.knox_covariance
    else:
        covariance_model_funct = None
    if otherp is None:
        like, cumint, allrlim = ana_likelihood(
            rv,
            leff,
            fakedata,
            errors,
            myBBth, [[0, 1]],
            covariance_model_funct=covariance_model_funct)
    else:
        like, cumint, allrlim, other = ana_likelihood(
            rv,
            leff,
            fakedata,
            errors,
            myBBth, [[0, 1]],
            covariance_model_funct=covariance_model_funct,
            otherp=otherp)

    if plotcls:
        if plotlike:
            subplot(1, 2, 1)
            if np.ndim(BBcov) == 2:
                errorstoplot = np.sqrt(np.diag(errors))
            else:
                errorstoplot = errors
        #plot(inputl, inputcl[:,2], 'k', label='r=0')
        plot(leff, errorstoplot, label=mylabel + ' Errors', color=color)
        xlim(0, lmax)
        if my_ylim is None:
            ylim(1e-4, 1e0)
        else:
            ylim(my_ylim[0], my_ylim[1])
        yscale('log')
        xlabel('$\\ell$')
        ylabel('$D_\\ell$')
        legend(loc='upper left')
    if plotlike:
        if plotcls:
            subplot(1, 2, 2)
        p = plot(rv,
                 like / np.max(like),
                 label=mylabel + ' $\sigma(r)={0:6.4f}$'.format(allrlim),
                 color=color)
        plot(allrlim + np.zeros(2), [0, 1.2], ':', color=p[0].get_color())
        xlabel('r')
        ylabel('posterior')
        legend(fontsize=8, loc='upper right')
        xlim(0, 0.1)
        ylim(0, 1.2)
        title(mytitle)

    if otherp is None:
        return like, cumint, allrlim
    else:
        return like, cumint, allrlim, other