示例#1
0
    def get_power_spectra(self, field1, field2):
        """
        Calculates the power spectrum for a given pair of number maps
        """

        c_l = []

        for zbin1, zbin2 in zip(field1, field2):

            coupled_c_l = nmt.compute_coupled_cell_flat(
                zbin1.field, zbin2.field, self.ell_bins)
            c_l.append(self.wsp.decouple_cell(coupled_c_l)[0])

        return np.array(c_l)
def get_cls_sim(ws, fields):
    """
    :param ws: workspaces for fields in fields.
    :param fields: tuple of tuple of fields to compute the mode-coupling matrix for. Shape is nbis x (f0, f2)
    """
    dof = [1, 2] * len(fields)

    nfs = 3 * len(fields)

    fields = sum(fields, ())  # Flatten the tuple of tuples

    cl_ar = np.empty((nfs, nfs, b.get_n_bands()))

    index1 = 0
    c = 0
    for c1, dof1 in enumerate(dof):
        f1 = fields[c1]
        index2 = index1
        for c2, dof2 in enumerate(dof[c1:], c1):
            f2 = fields[c2]
            cls = ws[c].decouple_cell(nmt.compute_coupled_cell_flat(f1, f2, b)).reshape((dof1, dof2, -1))

            # from matplotlib import pyplot as plt
            # cls_true = (f['cls'] + f['nls'])[index1 : index1 + dof1, index2 : index2 + dof2].reshape(dof1 * dof2, -1)
            # print(cls_true.shape)
            # print(cls.reshape(dof1 * dof2, -1).shape)
            # for cli_true, cli in zip(cls_true, cls.reshape(dof1 * dof2, -1)):
            #     print(cli)
            #     plt.suptitle("{}, {}".format(dof1, dof2))
            #     plt.loglog(l, cli_true, b.get_effective_ells(), cli, 'o')
            #     plt.show()
            #     plt.close()

            cl_ar[index1 : index1 + dof1, index2 : index2 + dof2] = cls

             # from matplotlib import pyplot as plt
             # for cli_true, cli in zip(cls_true,
             #                          cl_ar[index1 : index1 + dof1, index2 : index2 + dof2].reshape(dof1 * dof2, -1)):
             #     plt.suptitle("{}, {}".format(dof1, dof2))
             #     plt.loglog(l, cli_true, b.get_effective_ells(), cli, 'o')
             #     plt.show()
             #     plt.close()

            index2 += dof2
            c += 1
        index1 += dof1

    return cl_ar[np.triu_indices(cl_ar.shape[0])]
示例#3
0
 def get_power_spectra(self, trc, wsp, bpws):
     """
     Compute all possible power spectra between pairs of tracers
     :param trc: list of Tracers.
     :param wsp: NaMaster workspace.
     :param bpws: NaMaster bandpowers.
     """
     cls_all = []
     cls_coupled = []
     for i in range(self.nbins):
         for j in range(i, self.nbins):
             cl_coupled = nmt.compute_coupled_cell_flat(
                 trc[i].field, trc[j].field, bpws)
             cls_all.append(wsp.decouple_cell(cl_coupled)[0])
             cls_coupled.append(cl_coupled[0])
     return np.array(cls_all), np.array(cls_coupled)
示例#4
0
    def mastest(self,wtemp,wpure) :
        prefix="test/benchmarks/bm_f"
        if wtemp :
            prefix+="_yc"
            f0=nmt.NmtFieldFlat(self.lx,self.ly,self.msk,[self.mps[0]],templates=[[self.tmp[0]]])
            f2=nmt.NmtFieldFlat(self.lx,self.ly,self.msk,[self.mps[1],self.mps[2]],
                                templates=[[self.tmp[1],self.tmp[2]]],
                                purify_b=wpure)
        else :
            prefix+="_nc"
            f0=nmt.NmtFieldFlat(self.lx,self.ly,self.msk,[self.mps[0]])
            f2=nmt.NmtFieldFlat(self.lx,self.ly,self.msk,[self.mps[1],self.mps[2]],purify_b=wpure)
        f=[f0,f2]
        
        if wpure :
            prefix+="_yp"
        else :
            prefix+="_np"

        for ip1 in range(2) :
            for ip2 in range(ip1,2) :
                if ip1==ip2==0 :
                    clth=np.array([self.cltt]);
                    nlth=np.array([self.nltt]);
                elif ip1==ip2==1 :
                    clth=np.array([self.clee,0*self.clee,0*self.clbb,self.clbb]);
                    nlth=np.array([self.nlee,0*self.nlee,0*self.nlbb,self.nlbb]);
                else :
                    clth=np.array([self.clte,0*self.clte]);
                    nlth=np.array([self.nlte,0*self.nlte]);
                w=nmt.NmtWorkspaceFlat()
                w.compute_coupling_matrix(f[ip1],f[ip2],self.b)
                clb=w.couple_cell(self.l,nlth)
                if wtemp :
                    dlb=nmt.deprojection_bias_flat(f[ip1],f[ip2],self.b,self.l,clth+nlth)
                    tlb=np.loadtxt(prefix+'_cb%d%d.txt'%(2*ip1,2*ip2),unpack=True)[1:,:]
                    self.assertTrue((np.fabs(dlb-tlb)<=np.fmin(np.fabs(dlb),np.fabs(tlb))*1E-5).all())
                    clb+=dlb
                cl=w.decouple_cell(nmt.compute_coupled_cell_flat(f[ip1],f[ip2],self.b),cl_bias=clb)
                tl=np.loadtxt(prefix+'_c%d%d.txt'%(2*ip1,2*ip2),unpack=True)[1:,:]
                self.assertTrue((np.fabs(cl-tl)<=np.fmin(np.fabs(cl),np.fabs(tl))*1E-5).all())
示例#5
0
    def test_spin1(self):
        prefix = "test/benchmarks/bm_f_sp1"
        f0 = nmt.NmtFieldFlat(self.lx, self.ly, self.msk,
                              [self.mps_s1[0]])
        f1 = nmt.NmtFieldFlat(self.lx, self.ly, self.msk,
                              [self.mps_s1[1], self.mps_s1[2]],
                              spin=1)
        f = [f0, f1]

        for ip1 in range(2):
            for ip2 in range(ip1, 2):
                w = nmt.NmtWorkspaceFlat()
                w.compute_coupling_matrix(f[ip1], f[ip2], self.b)
                cl = w.decouple_cell(nmt.compute_coupled_cell_flat(f[ip1],
                                                                   f[ip2],
                                                                   self.b))[0]
                tl = np.loadtxt(prefix+'_c%d%d.txt' % (ip1, ip2),
                                unpack=True)[1]
                self.assertTrue((np.fabs(cl-tl) <=
                                 np.fmin(np.fabs(cl),
                                         np.fabs(tl))*1E-5).all())
示例#6
0
 def test_lite_pure(self):
     f0 = nmt.NmtFieldFlat(self.lx, self.ly, self.msk,
                           [self.mps[0]])
     f2l = nmt.NmtFieldFlat(self.lx, self.ly, self.msk,
                            [self.mps[1], self.mps[2]],
                            purify_b=True, lite=True)
     f2e = nmt.NmtFieldFlat(self.lx, self.ly, self.msk,
                            None, purify_b=True,
                            lite=True, spin=2)
     nlth = np.array([self.nlte, 0*self.nlte])
     w = nmt.NmtWorkspaceFlat()
     w.compute_coupling_matrix(f0, f2e, self.b)
     clb = w.couple_cell(self.ll, nlth)
     cl = w.decouple_cell(nmt.compute_coupled_cell_flat(f0,
                                                        f2l,
                                                        self.b),
                          cl_bias=clb)
     tl = np.loadtxt("test/benchmarks/bm_f_nc_yp_c02.txt",
                     unpack=True)[1:, :]
     self.assertTrue((np.fabs(cl-tl) <=
                      np.fmin(np.fabs(cl),
                              np.fabs(tl))*1E-5).all())
示例#7
0
 def test_lite_cont(self):
     f0 = nmt.NmtFieldFlat(self.lx, self.ly, self.msk,
                           [self.mps[0]],
                           templates=[[self.tmp[0]]])
     tmps = [[self.tmp[1], self.tmp[2]]]
     f2 = nmt.NmtFieldFlat(self.lx, self.ly, self.msk,
                           [self.mps[1], self.mps[2]],
                           templates=tmps)
     f2l = nmt.NmtFieldFlat(self.lx, self.ly, self.msk,
                            [self.mps[1], self.mps[2]],
                            templates=tmps, lite=True)
     f2e = nmt.NmtFieldFlat(self.lx, self.ly, self.msk,
                            None, lite=True, spin=2)
     clth = np.array([self.clte, 0*self.clte])
     nlth = np.array([self.nlte, 0*self.nlte])
     w = nmt.NmtWorkspaceFlat()
     w.compute_coupling_matrix(f0, f2e, self.b)
     clb = w.couple_cell(self.ll, nlth)
     dlb = nmt.deprojection_bias_flat(f0, f2,
                                      self.b, self.ll,
                                      clth+nlth)
     clb += dlb
     cl = w.decouple_cell(nmt.compute_coupled_cell_flat(f0,
                                                        f2l,
                                                        self.b),
                          cl_bias=clb)
     tl = np.loadtxt("test/benchmarks/bm_f_yc_np_c02.txt",
                     unpack=True)[1:, :]
     tlb = np.loadtxt("test/benchmarks/bm_f_yc_np_cb02.txt",
                      unpack=True)[1:, :]
     self.assertTrue((np.fabs(dlb-tlb) <=
                      np.fmin(np.fabs(dlb),
                              np.fabs(tlb))*1E-5).all())
     self.assertTrue((np.fabs(cl-tl) <=
                      np.fmin(np.fabs(cl),
                              np.fabs(tl))*1E-5).all())
示例#8
0
    def __call__(self, realiz):
        """
        Convenience method for calculating the signal and noise cls for
        a given mock realization. This is a function that can be pickled and can be thus
        used when running the mock generation in parallel using multiprocessing pool.
        :param realis: number of the realisation to run
        :param noise: boolean flag indicating if noise is added to the mocks
        noise=True: add noise to the mocks
        noise=False: do not add noise to the mocks
        :param probes: list of desired probes to run the mock for
        :param maskmat: matrix with the relevant masks for the probes
        :param clparams: list of dictionaries with the parameters for calculating the
        power spectra for each probe
        :return cls: 3D array of signal and noise cls for the given realisation,
        0. and 1. axis denote the power spectrum, 2. axis gives the cls belonging
        to this configuration
        :return noisecls: 3D array of noise cls for the given realisation,
        0. and 1. axis denote the power spectrum, 2. axis gives the cls belonging
        to this configuration
        :return tempells: array of the ell range of the power spectra
        """

        logger.info('Running realization : {}.'.format(realiz))

        cls = np.zeros((self.params['nautocls'], self.params['nautocls'],
                        self.params['nell']))
        noisecls = np.zeros_like(cls)

        if self.params['signal']:
            signalmaps = self.simmaps.generate_maps()
        if self.params['noise']:
            # We need to add noise maps to the signal maps
            noisemaps = self.noisemaps.generate_maps()

        if self.params['signal'] and self.params['noise']:
            # We need to add the two lists elementwise
            maps = list(map(add, signalmaps, noisemaps))
        elif self.params['signal'] and not self.params['noise']:
            maps = copy.deepcopy(signalmaps)
        elif not self.params['signal'] and self.params['noise']:
            maps = copy.deepcopy(noisemaps)
        else:
            raise RuntimeError(
                'Either signal or noise must be True. Aborting.')

        b = nmt.NmtBinFlat(self.params['l0_bins'], self.params['lf_bins'])
        # The effective sampling rate for these bandpowers can be obtained calling:
        ells_uncoupled = b.get_effective_ells()

        # First compute the cls of map realization for all the probes
        for j in range(self.params['nprobes']):
            for jj in range(j + 1):

                if j == jj:
                    compute_cls = True
                else:
                    if self.params['signal']:
                        compute_cls = True
                    else:
                        compute_cls = False

                if compute_cls:
                    probe1 = self.params['probes'][j]
                    probe2 = self.params['probes'][jj]
                    spin1 = self.params['spins'][j]
                    spin2 = self.params['spins'][jj]

                    logger.info(
                        'Computing the power spectrum between probe1 = {} and probe2 = {}.'
                        .format(probe1, probe2))
                    logger.info('Spins: spin1 = {}, spin2 = {}.'.format(
                        spin1, spin2))
                    if spin1 == 2 and spin2 == 0:
                        # Define flat sky spin-2 field
                        emaps = [maps[j], maps[j + self.params['nspin2']]]
                        f2_1 = nmt.NmtFieldFlat(np.radians(self.fsk.lx),
                                                np.radians(self.fsk.ly),
                                                self.masks[j],
                                                emaps,
                                                purify_b=False)
                        # Define flat sky spin-0 field
                        emaps = [maps[jj]]
                        f0_1 = nmt.NmtFieldFlat(np.radians(self.fsk.lx),
                                                np.radians(self.fsk.ly),
                                                self.masks[jj],
                                                emaps,
                                                purify_b=False)

                        if self.wsps[j][jj] is None:
                            logger.info(
                                'Workspace element for j, jj = {}, {} not set.'
                                .format(j, jj))
                            logger.info('Computing workspace element.')
                            wsp = nmt.NmtWorkspaceFlat()
                            wsp.compute_coupling_matrix(f2_1, f0_1, b)
                            self.wsps[j][jj] = wsp
                            if j != jj:
                                self.wsps[jj][j] = wsp
                        else:
                            logger.info(
                                'Workspace element already set for j, jj = {}, {}.'
                                .format(j, jj))

                        # Compute pseudo-Cls
                        cl_coupled = nmt.compute_coupled_cell_flat(
                            f2_1, f0_1, b)
                        # Uncoupling pseudo-Cls
                        cl_uncoupled = self.wsps[j][jj].decouple_cell(
                            cl_coupled)

                        # For one spin-0 field and one spin-2 field, NaMaster gives: n_cls=2, [C_TE,C_TB]
                        tempclse = cl_uncoupled[0]
                        tempclsb = cl_uncoupled[1]

                        cls[j, jj, :] = tempclse
                        cls[j + self.params['nspin2'], jj, :] = tempclsb

                    elif spin1 == 2 and spin2 == 2:
                        # Define flat sky spin-2 field
                        emaps = [maps[j], maps[j + self.params['nspin2']]]
                        f2_1 = nmt.NmtFieldFlat(np.radians(self.fsk.lx),
                                                np.radians(self.fsk.ly),
                                                self.masks[j],
                                                emaps,
                                                purify_b=False)
                        # Define flat sky spin-0 field
                        emaps = [maps[jj], maps[jj + self.params['nspin2']]]
                        f2_2 = nmt.NmtFieldFlat(np.radians(self.fsk.lx),
                                                np.radians(self.fsk.ly),
                                                self.masks[jj],
                                                emaps,
                                                purify_b=False)

                        if self.wsps[j][jj] is None:
                            logger.info(
                                'Workspace element for j, jj = {}, {} not set.'
                                .format(j, jj))
                            logger.info('Computing workspace element.')
                            wsp = nmt.NmtWorkspaceFlat()
                            wsp.compute_coupling_matrix(f2_1, f2_2, b)
                            self.wsps[j][jj] = wsp
                            if j != jj:
                                self.wsps[jj][j] = wsp
                        else:
                            logger.info(
                                'Workspace element already set for j, jj = {}, {}.'
                                .format(j, jj))

                        # Compute pseudo-Cls
                        cl_coupled = nmt.compute_coupled_cell_flat(
                            f2_1, f2_2, b)
                        # Uncoupling pseudo-Cls
                        cl_uncoupled = self.wsps[j][jj].decouple_cell(
                            cl_coupled)

                        # For two spin-2 fields, NaMaster gives: n_cls=4, [C_E1E2,C_E1B2,C_E2B1,C_B1B2]
                        tempclse = cl_uncoupled[0]
                        tempclseb = cl_uncoupled[1]
                        tempclsb = cl_uncoupled[3]

                        cls[j, jj, :] = tempclse
                        cls[j + self.params['nspin2'], jj, :] = tempclseb
                        cls[j + self.params['nspin2'],
                            jj + self.params['nspin2'], :] = tempclsb

                    else:
                        # Define flat sky spin-0 field
                        emaps = [maps[j]]
                        f0_1 = nmt.NmtFieldFlat(np.radians(self.fsk.lx),
                                                np.radians(self.fsk.ly),
                                                self.masks[j],
                                                emaps,
                                                purify_b=False)
                        # Define flat sky spin-0 field
                        emaps = [maps[jj]]
                        f0_2 = nmt.NmtFieldFlat(np.radians(self.fsk.lx),
                                                np.radians(self.fsk.ly),
                                                self.masks[jj],
                                                emaps,
                                                purify_b=False)

                        if self.wsps[j][jj] is None:
                            logger.info(
                                'Workspace element for j, jj = {}, {} not set.'
                                .format(j, jj))
                            logger.info('Computing workspace element.')
                            wsp = nmt.NmtWorkspaceFlat()
                            wsp.compute_coupling_matrix(f0_1, f0_2, b)
                            self.wsps[j][jj] = wsp
                            if j != jj:
                                self.wsps[jj][j] = wsp
                        else:
                            logger.info(
                                'Workspace element already set for j, jj = {}, {}.'
                                .format(j, jj))

                        # Compute pseudo-Cls
                        cl_coupled = nmt.compute_coupled_cell_flat(
                            f0_1, f0_2, b)
                        # Uncoupling pseudo-Cls
                        cl_uncoupled = self.wsps[j][jj].decouple_cell(
                            cl_coupled)
                        cls[j, jj, :] = cl_uncoupled

        # If noise is True, then we need to compute the noise from simulations
        # We therefore generate different noise maps for each realisation so that
        # we can then compute the noise power spectrum from these noise realisations
        if self.params['signal'] and self.params['noise']:
            # Determine the noise bias on the auto power spectrum for each realisation
            # For the cosmic shear, we now add the shear from the noisefree signal maps to the
            # data i.e. we simulate how we would do it in real life
            noisemaps = self.noisemaps.generate_maps(signalmaps)
            for j, probe in enumerate(self.params['probes']):
                logger.info(
                    'Computing the noise power spectrum for {}.'.format(probe))
                if self.params['spins'][j] == 2:
                    # Define flat sky spin-2 field
                    emaps = [
                        noisemaps[j], noisemaps[j + self.params['nspin2']]
                    ]
                    f2 = nmt.NmtFieldFlat(np.radians(self.fsk.lx),
                                          np.radians(self.fsk.ly),
                                          self.masks[j],
                                          emaps,
                                          purify_b=False)

                    if self.wsps[j][j] is None:
                        logger.info(
                            'Workspace element for j, j = {}, {} not set.'.
                            format(j, j))
                        logger.info('Computing workspace element.')
                        wsp = nmt.NmtWorkspaceFlat()
                        wsp.compute_coupling_matrix(f2, f2, b)
                        self.wsps[j][j] = wsp
                    else:
                        logger.info(
                            'Workspace element already set for j, j = {}, {}.'.
                            format(j, j))

                    # Compute pseudo-Cls
                    cl_coupled = nmt.compute_coupled_cell_flat(f2, f2, b)
                    # Uncoupling pseudo-Cls
                    cl_uncoupled = self.wsps[j][j].decouple_cell(cl_coupled)

                    # For two spin-2 fields, NaMaster gives: n_cls=4, [C_E1E2,C_E1B2,C_E2B1,C_B1B2]
                    tempclse = cl_uncoupled[0]
                    tempclsb = cl_uncoupled[3]

                    noisecls[j, j, :] = tempclse
                    noisecls[j + self.params['nspin2'],
                             j + self.params['nspin2'], :] = tempclsb
                else:
                    # Define flat sky spin-0 field
                    emaps = [noisemaps[j]]
                    f0 = nmt.NmtFieldFlat(np.radians(self.fsk.lx),
                                          np.radians(self.fsk.ly),
                                          self.masks[j],
                                          emaps,
                                          purify_b=False)

                    if self.wsps[j][j] is None:
                        logger.info(
                            'Workspace element for j, j = {}, {} not set.'.
                            format(j, j))
                        logger.info('Computing workspace element.')
                        wsp = nmt.NmtWorkspaceFlat()
                        wsp.compute_coupling_matrix(f0, f0, b)
                        self.wsps[j][j] = wsp
                    else:
                        logger.info(
                            'Workspace element already set for j, j = {}, {}.'.
                            format(j, j))

                    # Compute pseudo-Cls
                    cl_coupled = nmt.compute_coupled_cell_flat(f0, f0, b)
                    # Uncoupling pseudo-Cls
                    cl_uncoupled = self.wsps[j][j].decouple_cell(cl_coupled)
                    noisecls[j, j, :] = cl_uncoupled

        if not self.params['signal'] and self.params['noise']:
            noisecls = copy.deepcopy(cls)
            cls = np.zeros_like(noisecls)

        return cls, noisecls, ells_uncoupled
 def test_workspace_flat_compute_coupled_cell(self):
     # Test compute_coupled_cell_flat
     c = nmt.compute_coupled_cell_flat(self.f0, self.f0, self.b)
     self.assertEqual(c.shape, (1, self.b.bin.n_bands))
     with self.assertRaises(ValueError):  # Different resolutions
         nmt.compute_coupled_cell_flat(self.f0, self.f0_half, self.b)
示例#10
0
def compute_master(f_a, f_b, wsp):
    cl_coupled = nmt.compute_coupled_cell_flat(f_a, f_b, b)
    cl_decoupled = wsp.decouple_cell(cl_coupled)

    return cl_decoupled
示例#11
0
def test_workspace_flat_compute_coupled_cell():
    # Test compute_coupled_cell_flat
    c = nmt.compute_coupled_cell_flat(WT.f0, WT.f0, WT.b)
    assert c.shape == (1, WT.b.bin.n_bands)
    with pytest.raises(ValueError):  # Different resolutions
        nmt.compute_coupled_cell_flat(WT.f0, WT.f0_half, WT.b)
示例#12
0
    if w_cont :
        clb22+=nmt.deprojection_bias_flat(f2,f2,b,l,[clee*beam**2+nlee,0*clee,0*clbb,clbb*beam**2+nlbb])
    np.save(prefix+"_clb22",clb22)
else :
    clb22=np.load(prefix+"_clb22.npy")

#Compute mean and variance over nsims simulations
cl22_all=[]
for i in np.arange(nsims) :
    #if i%100==0 :
    print("%d-th sim"%(i+o.isim_ini))

    if not os.path.isfile(prefix+"_cl_%04d.txt"%(o.isim_ini+i)) :
        np.random.seed(1000+o.isim_ini+i)
        f2=get_fields()
        cl22=w22.decouple_cell(nmt.compute_coupled_cell_flat(f2,f2,b),cl_bias=clb22)
        np.savetxt(prefix+"_cl_%04d.txt"%(o.isim_ini+i),
                   np.transpose([b.get_effective_ells(),cl22[0],cl22[1],cl22[2],cl22[3]]))
    cld=np.loadtxt(prefix+"_cl_%04d.txt"%(o.isim_ini+i),unpack=True)
    cl22_all.append([cld[1],cld[2],cld[3],cld[4]])
cl22_all=np.array(cl22_all)

#Plot results
if o.plot_stuff :
    import scipy.stats as st
    
    def tickfs(ax,x=True,y=True) :
        if x :
            for tick in ax.xaxis.get_major_ticks():
                tick.label.set_fontsize(12)
        if y :
示例#13
0
    def compute_power_spectrum(self,
                               map1,
                               mask1,
                               map2=None,
                               mask2=None,
                               l_bpw=None,
                               return_bpw=False,
                               wsp=None,
                               return_wsp=False,
                               temp1=None,
                               temp2=None):
        """
        Computes power spectrum between two maps.
        map1 : first map to correlate
        mask1 : mask for the first map
        map2 : second map to correlate. If None map2==map1.
        mask2 : mask for the second map. If None mask2==mask1.
        l_bpw : bandpowers on which to calculate the power spectrum. Should be an [2,N_ell] array, where
                the first and second columns list the edges of each bandpower. If None, the function will
                create bandpowers of its own taylored to the properties of your map.
        return_bpw : if True, the bandpowers will also be returned
        wsp : NmtWorkspaceFlat object to accelerate the calculation. If None, this will be precomputed.
        return_wsp : if True, the workspace will also be returned 
        temp1 : if not None, set of contaminants to remove from map1
        temp2 : if not None, set of contaminants to remove from map2
        """
        same_map = False
        if map2 is None:
            map2 = map1
            same_map = True

        same_mask = False
        if mask2 is None:
            mask2 = mask1
            same_mask = False

        if len(map1) != self.npix:
            raise ValueError("Input map has the wrong size")
        if (len(map1) != len(map2)) or (len(map1) != len(mask1)) or (
                len(map1) != len(mask2)):
            raise ValueError("Sizes of all maps and masks don't match")

        if l_bpw is None:
            ell_min = max(2 * np.pi / self.lx_rad, 2 * np.pi / self.ly_rad)
            ell_max = min(self.nx * np.pi / self.lx_rad,
                          self.ny * np.pi / self.ly_rad)
            d_ell = 2 * ell_min
            n_ell = int((ell_max - ell_min) / d_ell) - 1
            l_bpw = np.zeros([2, n_ell])
            l_bpw[0, :] = ell_min + np.arange(n_ell) * d_ell
            l_bpw[1, :] = l_bpw[0, :] + d_ell
            return_bpw = True

        #Generate binning scheme
        b = nmt.NmtBinFlat(l_bpw[0, :], l_bpw[1, :])

        if temp1 is not None:
            tmp1 = np.array([[t.reshape([self.ny, self.nx])] for t in temp1])
        else:
            tmp1 = None
        if temp2 is not None:
            tmp2 = np.array([[t.reshape([self.ny, self.nx])] for t in temp2])
        else:
            tmp2 = None

        #Generate fields
        f1 = nmt.NmtFieldFlat(self.lx_rad,
                              self.ly_rad,
                              mask1.reshape([self.ny, self.nx]),
                              [map1.reshape([self.ny, self.nx])],
                              templates=tmp1)
        if same_map and same_mask:
            f2 = f1
        else:
            f2 = nmt.NmtFieldFlat(self.lx_rad,
                                  self.ly_rad,
                                  mask2.reshape([self.ny, self.nx]),
                                  [map2.reshape([self.ny, self.nx])],
                                  templates=tmp2)

        #Compute workspace if needed
        if wsp is None:
            wsp = nmt.NmtWorkspaceFlat()
            wsp.compute_coupling_matrix(f1, f2, b)
            return_wsp = True

        #Compute power spectrum
        cl_coupled = nmt.compute_coupled_cell_flat(f1, f2, b)
        cl_uncoupled = wsp.decouple_cell(cl_coupled)[0]

        #Return
        if return_bpw and return_wsp:
            return cl_uncoupled, l_bpw, wsp
        else:
            if return_bpw:
                return cl_uncoupled, l_bpw
            elif return_wsp:
                return cl_uncoupled, wsp
            else:
                return cl_uncoupled
        if wexists:
            w00.read_from(out_dir + field + "_w00_flat.dat")
            w02.read_from(out_dir + field + "_w02_flat.dat")
            w22.read_from(out_dir + field + "_w22_flat.dat")
            print("Loaded saved workspaces.")
        else:
            w00.compute_coupling_matrix(f0, f0, b)
            w02.compute_coupling_matrix(f0, f2, b)
            w22.compute_coupling_matrix(f2, f2, b)

            w00.write_to(out_dir + field + "_w00_flat.dat")
            w02.write_to(out_dir + field + "_w02_flat.dat")
            w22.write_to(out_dir + field + "_w22_flat.dat")

    #Computing power spectra:
    cl00_coupled = nmt.compute_coupled_cell_flat(f0, f0, b)
    cl00_uncoupled = w00.decouple_cell(cl00_coupled)
    cl02_coupled = nmt.compute_coupled_cell_flat(f0, f2, b)
    cl02_uncoupled = w02.decouple_cell(cl02_coupled)
    cl22_coupled = nmt.compute_coupled_cell_flat(f2, f2, b)
    cl22_uncoupled = w22.decouple_cell(cl22_coupled)

    # Collect statistics
    s.add_to_stats("ukk", cl00_uncoupled[0])
    s.add_to_stats("ckk", cl00_coupled[0] / w2)
    s.add_to_stats(
        "uke", -cl02_uncoupled[0])  # ENLIB CONVENTION GIVES WRONG SIGN OF TE
    s.add_to_stats("cke", -cl02_coupled[0] / w2)
    s.add_to_stats("uee", cl22_uncoupled[0])
    s.add_to_stats("cee", cl22_coupled[0] / w2)
示例#15
0
def xcorr_flatsky(modedecomp=False,
                  simkey="512_alfven3_0002_a_z",
                  Imapkey="",
                  deglen=10,
                  apotype="C2",
                  aposcale=0.5,
                  Epure=True,
                  Bpure=True):

    TQU = SimsTQU(fn=simkey, modedecomp=modedecomp, ikey=Imapkey)

    # Define flat-sky field
    #  - Lx and Ly: the size of the patch in the x and y dimensions (in radians)
    Lx = deglen * np.pi / 180.  # arbitrarily set this to a deglen x deglen deg box
    Ly = deglen * np.pi / 180.
    #  - Nx and Ny: the number of pixels in the x and y dimensions
    Nx = 512
    Ny = 512

    # Define mask
    mask = np.ones_like(TQU.T).flatten()
    xarr = np.ones(Ny)[:, None] * np.arange(Nx)[None, :] * Lx / Nx
    yarr = np.ones(Nx)[None, :] * np.arange(Ny)[:, None] * Ly / Ny
    #Let's also trim the edges
    mask[np.where(xarr.flatten() < Lx / 16.)] = 0
    mask[np.where(xarr.flatten() > 15 * Lx / 16.)] = 0
    mask[np.where(yarr.flatten() < Ly / 16.)] = 0
    mask[np.where(yarr.flatten() > 15 * Ly / 16.)] = 0
    mask = mask.reshape([Ny, Nx])
    mask = nmt.mask_apodization_flat(mask,
                                     Lx,
                                     Ly,
                                     aposize=aposcale,
                                     apotype=apotype)

    # Fields:
    # Once you have maps it's time to create pymaster fields.
    # Note that, as in the full-sky case, you can also pass
    # contaminant templates and flags for E and B purification
    # (see the documentation for more details)
    f0 = nmt.NmtFieldFlat(Lx, Ly, mask, [TQU.T])
    f2 = nmt.NmtFieldFlat(Lx,
                          Ly,
                          mask, [TQU.Q, TQU.U],
                          purify_b=Bpure,
                          purify_e=Epure)

    # Bins:
    # For flat-sky fields, bandpowers are simply defined as intervals in ell, and
    # pymaster doesn't currently support any weighting scheme within each interval.
    l0_bins = np.arange(Nx / 8) * 8 * np.pi / Lx
    lf_bins = (np.arange(Nx / 8) + 1) * 8 * np.pi / Lx
    b = nmt.NmtBinFlat(l0_bins, lf_bins)
    # The effective sampling rate for these bandpowers can be obtained calling:
    ells_uncoupled = b.get_effective_ells()

    # Workspaces:
    # As in the full-sky case, the computation of the coupling matrix and of
    # the pseudo-CL estimator is mediated by a WorkspaceFlat case, initialized
    # by calling its compute_coupling_matrix method:
    w00 = nmt.NmtWorkspaceFlat()
    w00.compute_coupling_matrix(f0, f0, b)
    w02 = nmt.NmtWorkspaceFlat()
    w02.compute_coupling_matrix(f0, f2, b)
    w22 = nmt.NmtWorkspaceFlat()
    w22.compute_coupling_matrix(f2, f2, b)

    # Computing power spectra:
    # As in the full-sky case, you compute the pseudo-CL estimator by
    # computing the coupled power spectra and then decoupling them by
    # inverting the mode-coupling matrix. This is done in two steps below,
    # but pymaster provides convenience routines to do this
    # through a single function call
    cl00_coupled = nmt.compute_coupled_cell_flat(f0, f0, b)
    cl00_uncoupled = w00.decouple_cell(cl00_coupled)
    cl02_coupled = nmt.compute_coupled_cell_flat(f0, f2, b)
    cl02_uncoupled = w02.decouple_cell(cl02_coupled)
    cl22_coupled = nmt.compute_coupled_cell_flat(f2, f2, b)
    cl22_uncoupled = w22.decouple_cell(cl22_coupled)

    TT = cl00_uncoupled[0]
    TE = cl02_uncoupled[0]
    TB = cl02_uncoupled[1]
    EE = cl22_uncoupled[0]
    EB = cl22_uncoupled[1]
    BE = cl22_uncoupled[2]
    BB = cl22_uncoupled[3]

    if modedecomp:
        outroot = "/data/seclark/BlakesleySims/simdata/ModeDecomp/xcorrdata/"
    else:
        outroot = "/data/seclark/BlakesleySims/xcorrdata/"
    outfn = simkey + "_deglen{}_{}apod{}_EBpure{}{}.h5".format(
        deglen, apotype, aposcale, Epure, Bpure)

    with h5py.File(outroot + outfn, 'w') as f:

        TTdset = f.create_dataset(name='TT', data=TT)
        TEdset = f.create_dataset(name='TE', data=TE)
        TBdset = f.create_dataset(name='TB', data=TB)
        EEdset = f.create_dataset(name='EE', data=EE)
        EBdset = f.create_dataset(name='EB', data=EB)
        BEdset = f.create_dataset(name='BE', data=BE)
        BBdset = f.create_dataset(name='BB', data=BB)
        TTdset.attrs['deglen'] = deglen
        TTdset.attrs['Epure'] = Epure
        TTdset.attrs['Bpure'] = Bpure
        TTdset.attrs['ell_binned'] = ells_uncoupled
示例#16
0
(ny,nx)=msk.shape
lx=np.fabs(nx*wcs.wcs.cdelt[0])*np.pi/180
ly=np.fabs(ny*wcs.wcs.cdelt[1])*np.pi/180
d_ell=20; lmax=500.; ledges=np.arange(int(lmax/d_ell)+1)*d_ell+2
b=nmt.NmtBinFlat(ledges[:-1],ledges[1:])
leff=b.get_effective_ells();
dt,dq,du=nmt.synfast_flat(int(nx),int(ny),lx,ly,
                          [cltt,cltt,0*cltt,cltt,0*cltt,0*cltt],[0,1])
write_flat_map("mps_sp1_flat.fits", np.array([dt,dq,du]),wcs,["T", "Q", "U"])
prefix = 'bm_f_sp1'
f0=nmt.NmtFieldFlat(lx,ly,msk,[dt])
f1=nmt.NmtFieldFlat(lx,ly,msk,[dq,du], spin=1)

w00=nmt.NmtWorkspaceFlat(); w00.compute_coupling_matrix(f0,f0,b);
w00.write_to(prefix+'_w00.fits')
c00=w00.decouple_cell(nmt.compute_coupled_cell_flat(f0,f0,b))
np.savetxt(prefix+'_c00.txt', np.transpose([leff, c00[0]]))

w01=nmt.NmtWorkspaceFlat(); w01.compute_coupling_matrix(f0,f1,b);
w01.write_to(prefix+'_w01.fits')
c01=w01.decouple_cell(nmt.compute_coupled_cell_flat(f0,f1,b))
np.savetxt(prefix+'_c01.txt', np.transpose([leff, c01[0], c01[1]]))

w11=nmt.NmtWorkspaceFlat(); w11.compute_coupling_matrix(f1,f1,b);
w11.write_to(prefix+'_w11.fits')
c11=w11.decouple_cell(nmt.compute_coupled_cell_flat(f1,f1,b))
np.savetxt(prefix+'_c11.txt', np.transpose([leff, c11[0], c11[1], c11[2], c11[3]]))

plt.figure()
plt.plot(leff, c01[0]/c00[0]-1, 'r--')
plt.plot(leff, c11[0]/c00[0]-1, 'b:')
示例#17
0
    print("Computing mode-coupling matrix")
    wsp.compute_coupling_matrix(tracers[0].field, tracers[0].field, bpws)
    if o.fname_mcm != 'NONE':
        wsp.write_to(o.fname_mcm)
else:
    print("Reading mode-coupling matrix from file")
    wsp.read_from(o.fname_mcm)

#Compute all cross-correlations
print("Computing all cross-power specra")
cls_all = []
ordering = np.zeros([nbins, nbins], dtype=int)
i_x = 0
for i in range(nbins):
    for j in range(i, nbins):
        cl_coupled = nmt.compute_coupled_cell_flat(tracers[i].field,
                                                   tracers[j].field, bpws)
        cls_all.append(wsp.decouple_cell(cl_coupled)[0])
        ordering[i, j] = i_x
        if j != i:
            ordering[j, i] = i_x
        i_x += 1

#Set up deprojection bias proposal power spectrum
if o.cont_deproj_bias:
    cls_all = np.array(cls_all)
    n_cross = len(cls_all)
    print("Computing deprojection bias")
    if o.cont_deproj_bias_opt == 'data':
        lmax = int(
            np.sqrt((fsk.nx * np.pi / np.radians(fsk.lx))**2 +
                    (fsk.ny * np.pi / np.radians(fsk.ly))**2)) + 1
    cl02_th=np.zeros([2,b.get_n_bands()])
    cl22_th=np.zeros([4,b.get_n_bands()])
    dum,cl00_th[0],cl02_th[0],cl02_th[1],cl22_th[0],cl22_th[1],cl22_th[2],cl22_th[3]=np.loadtxt(o.prefix_out+"_cl_th.txt",unpack=True)


#Compute mean and variance over nsims simulations
cl00_all=[]
cl02_all=[]
cl22_all=[]
for i in np.arange(nsims) :
    #if i%100==0 :
    print("%d-th sim"%(i+o.isim_ini))

    if not os.path.isfile(o.prefix_out+"_cl_%04d.npz"%(o.isim_ini+i)) :
        f0,f2=get_fields(fmi,mask_hsc)
        cl00=w00.decouple_cell(nmt.compute_coupled_cell_flat(f0,f0,b))#,cl_bias=clb00)
        cl02=w02.decouple_cell(nmt.compute_coupled_cell_flat(f0,f2,b))#,cl_bias=clb02)
        cl22=w22.decouple_cell(nmt.compute_coupled_cell_flat(f2,f2,b))#,cl_bias=clb22)
        np.savez(o.prefix_out+"_cl_%04d"%(o.isim_ini+i),
                 l=b.get_effective_ells(),cltt=cl00[0],clte=cl02[0],cltb=cl02[1],
                 clee=cl22[0],cleb=cl22[1],clbe=cl22[2],clbb=cl22[3])
    cld=np.load(o.prefix_out+"_cl_%04d.npz"%(o.isim_ini+i))
    cl00_all.append([cld['cltt']])
    cl02_all.append([cld['clte'],cld['cltb']])
    cl22_all.append([cld['clee'],cld['cleb'],cld['clbe'],cld['clbb']])
cl00_all=np.array(cl00_all)
cl02_all=np.array(cl02_all)
cl22_all=np.array(cl22_all)

#Save output
np.savez(o.prefix_out+'_clsims_%04d-%04d'%(o.isim_ini,o.isim_end),
示例#19
0
                              config['Ly'],
                              mask1,
                              emaps,
                              purify_b=False)
        f2 = nmt.NmtFieldFlat(config['Lx'],
                              config['Ly'],
                              mask2,
                              emaps,
                              purify_b=False)

        logger.info('Computing workspace element.')
        wsp = nmt.NmtWorkspaceFlat()
        wsp.compute_coupling_matrix(f1, f2, b)

        # Compute pseudo-Cls
        cl_coupled = nmt.compute_coupled_cell_flat(f1, f2, b)
        # Uncoupling pseudo-Cls
        # For one spin-0 field and one spin-2 field, NaMaster gives: n_cls=2, [C_TE,C_TB]
        # For two spin-2 fields, NaMaster gives: n_cls=4, [C_E1E2,C_E1B2,C_E2B1,C_B1B2]
        logger.info('Decoupling cls.')
        cl_uncoupled = wsp.decouple_cell(cl_coupled)

        cl_out = np.vstack((ells_uncoupled, cl_uncoupled))

    else:
        raise NotImplementedError()

    path2outputdir, _ = os.path.split(config['path2cls'])
    if not os.path.isdir(path2outputdir):
        try:
            os.makedirs(path2outputdir)
示例#20
0
    def get_noise_simulated(self, tracers, wsp, bpws, nsims):
        """
        Get a simulated estimate of the noise bias.
        :param tracers: list of Tracers.
        :param wsp: NaMaster workspace.
        :param bpws: NaMaster bandpowers.
        :param nsims: number of simulations to use (if using them).
        """
        def randomize_deltag_map(tracer, seed):
            """
            Creates a randomised version of the input map map by assigning the
            galaxies in the surevy to random pixels in the map. Basically it rotates each
            galaxy by a random angle but not rotating it out of the survey footprint.
            :param map: masked galaxy overdensity map which needs to randomised
            :param Ngal: number of galaxies used to create the map
            :return randomised_map: a randomised version of the masked input map
            """

            mask = tracer.weight.reshape([tracer.fsk.ny, tracer.fsk.nx])
            Ngal = int(tracer.Ngal)

            np.random.seed(seed=seed)
            maskpixy, maskpixx = np.where(mask != 0.)
            galpix_mask = np.random.choice(np.arange(maskpixx.shape[0]),
                                           size=Ngal,
                                           p=mask[mask != 0.] /
                                           np.sum(mask[mask != 0.]))
            galpixx = maskpixx[galpix_mask]
            galpixy = maskpixy[galpix_mask]

            maskshape = mask.shape
            ny, nx = maskshape
            ipix = galpixx + nx * galpixy

            randomized_nmap = np.bincount(ipix, minlength=nx * ny)

            randomized_deltamap = np.zeros_like(randomized_nmap, dtype='float')
            ndens = np.sum(randomized_nmap * tracer.mask_binary) / np.sum(
                tracer.weight)
            randomized_deltamap[
                tracer.goodpix] = randomized_nmap[tracer.goodpix] / (
                    ndens * tracer.masked_fraction[tracer.goodpix]) - 1
            randomized_deltamap = randomized_deltamap.reshape(maskshape)

            return randomized_deltamap

        nls_all = np.zeros([self.ncross, self.nell])
        i_x = 0
        for i in range(self.nbins):
            for j in range(i, self.nbins):
                if i == j:  #Add shot noise in the auto-correlation
                    tracer = tracers[i]
                    mask = tracer.weight.reshape(
                        [tracer.fsk.ny, tracer.fsk.nx])
                    ncl_uncoupled = np.zeros((nsims, self.nell))
                    for ii in range(nsims):
                        randomized_map = randomize_deltag_map(
                            tracer, ii + nsims * i)
                        f0 = nmt.NmtFieldFlat(np.radians(self.fsk.lx),
                                              np.radians(self.fsk.ly), mask,
                                              [randomized_map])
                        ncl_uncoupled[ii, :] = wsp.decouple_cell(
                            nmt.compute_coupled_cell_flat(f0, f0, bpws))
                    nls_all[i_x] = np.mean(ncl_uncoupled, axis=0)
                i_x += 1

        return nls_all
示例#21
0
                            beam(ells_uncoupled)])

plt.figure()
plt.imshow(f0.get_maps()[0] * mask, interpolation='nearest', origin='lower')
plt.colorbar()
plt.savefig('../images/map with mask.png', dpi=400)
plt.show()

print(
    "\n--------------------------- ANGULAR POWER SPECTRUM ------------------------------------\n"
)

w00 = nmt.NmtWorkspaceFlat()
w00.compute_coupling_matrix(f0, f0, b)
#Coupling matrix used to estimate angular spectrum
cl00_coupled = nmt.compute_coupled_cell_flat(f0, f0, b)
cl00_uncoupled = w00.decouple_cell(cl00_coupled)[0]
print(cl00_uncoupled)

amp = abs((ells_uncoupled**2) * cl00_uncoupled / (2 * np.pi))**(1 / 2)

print(
    "\n*************************  Covariance matrix  *************************************\n"
)

cw = nmt.NmtCovarianceWorkspaceFlat()
cw.compute_coupling_coefficients(f0, f0, b)
covar = nmt.gaussian_covariance_flat(cw, 0, 0, 0, 0, ells_uncoupled,
                                     [cl00_uncoupled], [cl00_uncoupled],
                                     [cl00_uncoupled], [cl00_uncoupled], w00)
示例#22
0
  if o.fname_mcm!='NONE' :
    np.savez(o.fname_mcm+".windows",windows=windows)
else :
  print("Reading window functions")
  windows=np.load(o.fname_mcm+".windows.npz")['windows']
    

#Compute all cross-correlations
print("Computing all cross-power specra")
cls_all=[]
windows_sacc=[]
ordering=np.zeros([nbins,nbins],dtype=int)
i_x=0
for i in range(nbins) :
  for j in range(i,nbins) :
    cl_coupled=nmt.compute_coupled_cell_flat(tracers[i].field,tracers[j].field,bpws)
    cls_all.append(wsp.decouple_cell(cl_coupled)[0])
    for b in range(nbands) :
      windows_sacc.append(sacc.Window(l_arr,windows[b]))
    ordering[i,j]=i_x
    if j!=i :
      ordering[j,i]=i_x
    i_x+=1
cls_all=np.array(cls_all)
n_cross=len(cls_all)
n_ell=len(ell_eff)

#Get guess power spectra
if o.guess_cell=='data' :
  #Interpolate measured power spectra
  lth=np.arange(2,lmax+1)+0.
示例#23
0
w00_conv2 = nmt.NmtWorkspaceFlat()
w00_conv2.compute_coupling_matrix(f0_conv2, f0_conv2, b)
w00_conv2.write_to("../data/w00_flat_conv2.fits")

w00_conv3 = nmt.NmtWorkspaceFlat()
w00_conv3.compute_coupling_matrix(f0_conv3, f0_conv3, b)
w00_conv3.write_to("../data/w00_flat_conv3.fits")

# Computing power spectra:
# As in the full-sky case, you compute the pseudo-CL estimator by
# computing the coupled power spectra and then decoupling them by
# inverting the mode-coupling matrix. This is done in two steps below,
# but pymaster provides convenience routines to do this
# through a single function call
cl00_coupled = nmt.compute_coupled_cell_flat(f0, f0, b)
cl00_uncoupled = w00.decouple_cell(cl00_coupled)

cl00_coupled_conv = nmt.compute_coupled_cell_flat(f0_conv, f0_conv, b)
cl00_uncoupled_conv = w00_conv.decouple_cell(cl00_coupled_conv)

cl00_coupled_conv2 = nmt.compute_coupled_cell_flat(f0_conv2, f0_conv2, b)
cl00_uncoupled_conv2 = w00_conv2.decouple_cell(cl00_coupled_conv2)

cl00_coupled_conv3 = nmt.compute_coupled_cell_flat(f0_conv3, f0_conv3, b)
cl00_uncoupled_conv3 = w00_conv3.decouple_cell(cl00_coupled_conv3)

# Let's look at the results!
plt.figure()
plt.plot(l, cl_tt, 'r-', label='Input TT')
plt.plot(ells_uncoupled, cl00_uncoupled[0], 'r.', label='Uncoupled, no beam')
示例#24
0
    def get_covar_gaussim(self, lth, clth, bpws, wsp, temps, cl_dpj_all):
        """
        Estimate the power spectrum covariance from Gaussian simulations
        :param lth: list of multipoles.
        :param clth: list of guess power spectra sampled at the multipoles stored in `lth`.
        :param bpws: NaMaster bandpowers.
        :param wsp: NaMaster workspace.
        :param temps: list of contaminatn templates.
        :params cl_dpj_all: list of deprojection biases for each bin pair combination.
        """
        #Create a dummy file for the covariance MCM
        f = open(self.get_output_fname('cov_mcm', ext='dat'), "w")
        f.close()

        #Setup
        nsims = 10 * self.ncross * self.nell
        print("Computing covariance from %d Gaussian simulations" % nsims)
        msk_binary = self.msk_bi.reshape([self.fsk.ny, self.fsk.nx])
        weights = (self.msk_bi * self.mskfrac).reshape(
            [self.fsk.ny, self.fsk.nx])
        if temps is not None:
            conts = [[t.reshape([self.fsk.ny, self.fsk.nx])] for t in temps]
            cl_dpj = [[c] for c in cl_dpj_all]
        else:
            conts = None
            cl_dpj = [None for i in range(self.ncross)]

        #Iterate
        cells_sims = []
        for isim in range(nsims):
            if isim % 100 == 0:
                print(" %d-th sim" % isim)
            #Generate random maps
            mps = nmt.synfast_flat(self.fsk.nx,
                                   self.fsk.ny,
                                   np.radians(self.fsk.lx),
                                   np.radians(self.fsk.ly),
                                   clth,
                                   np.zeros(self.nbins),
                                   seed=1000 + isim)
            #Nmt fields
            flds = [
                nmt.NmtFieldFlat(np.radians(self.fsk.lx),
                                 np.radians(self.fsk.ly),
                                 weights, [m],
                                 templates=conts) for m in mps
            ]
            #Compute power spectra (possibly with deprojection)
            i_x = 0
            cells_this = []
            for i in range(self.nbins):
                for j in range(i, self.nbins):
                    cl = nmt.compute_coupled_cell_flat(flds[i], flds[j], bpws)
                    cells_this.append(
                        wsp.decouple_cell(cl, cl_bias=cl_dpj[i_x])[0])
                    i_x += 1
            cells_sims.append(np.array(cells_this).flatten())
        cells_sims = np.array(cells_sims)
        #Save simulations for further
        np.savez(self.get_output_fname('gaucov_sims'), cl_sims=cells_sims)

        #Compute covariance
        covar = np.cov(cells_sims.T)
        return covar
示例#25
0
 def mkcl(w, f, g):
     return w.decouple_cell(nmt.compute_coupled_cell_flat(f, g, b))
示例#26
0
            f2, f2, b, l,
            [clee * beam**2 + nlee, 0 * clee, 0 * clbb, clbb * beam**2 + nlbb])
    np.save(prefix + "_clb22", clb22)
else:
    clb22 = np.load(prefix + "_clb22.npy")

#Compute mean and variance over nsims simulations
cl22_all = []
for i in np.arange(nsims):
    #if i%100==0 :
    print("%d-th sim" % (i + o.isim_ini))

    if not os.path.isfile(prefix + "_cl_%04d.txt" % (o.isim_ini + i)):
        np.random.seed(1000 + o.isim_ini + i)
        f2 = get_fields()
        cl22 = w22.decouple_cell(nmt.compute_coupled_cell_flat(f2, f2, b),
                                 cl_bias=clb22)
        np.savetxt(
            prefix + "_cl_%04d.txt" % (o.isim_ini + i),
            np.transpose(
                [b.get_effective_ells(), cl22[0], cl22[1], cl22[2], cl22[3]]))
    cld = np.loadtxt(prefix + "_cl_%04d.txt" % (o.isim_ini + i), unpack=True)
    cl22_all.append([cld[1], cld[2], cld[3], cld[4]])
cl22_all = np.array(cl22_all)

#Plot results
if o.plot_stuff:
    import scipy.stats as st

    def tickfs(ax, x=True, y=True):
        if x:
示例#27
0
                                            [clee, 0 * clee, 0 * clbb, clbb])
    np.save(prefix + "_clb22", clb22)
else:
    clb22 = np.load(prefix + "_clb22.npy")

#Compute mean and variance over nsims simulations
cl00_all = []
cl02_all = []
cl22_all = []
for i in np.arange(nsims):
    #if i%100==0 :
    print("%d-th sim" % (i + o.isim_ini))

    if not os.path.isfile(prefix + "_cl_%04d.txt" % (o.isim_ini + i)):
        f0, f2 = get_fields()
        cl00 = w00.decouple_cell(nmt.compute_coupled_cell_flat(f0, f0, b),
                                 cl_bias=clb00)
        cl02 = w02.decouple_cell(nmt.compute_coupled_cell_flat(f0, f2, b),
                                 cl_bias=clb02)
        cl22 = w22.decouple_cell(nmt.compute_coupled_cell_flat(f2, f2, b),
                                 cl_bias=clb22)
        np.savetxt(
            prefix + "_cl_%04d.txt" % (o.isim_ini + i),
            np.transpose([
                b.get_effective_ells(), cl00[0], cl02[0], cl02[1], cl22[0],
                cl22[1], cl22[2], cl22[3]
            ]))
    cld = np.loadtxt(prefix + "_cl_%04d.txt" % (o.isim_ini + i), unpack=True)
    cl00_all.append([cld[1]])
    cl02_all.append([cld[2], cld[3]])
    cl22_all.append([cld[4], cld[5], cld[6], cld[7]])
示例#28
0
def mastest(wtemp, wpure, do_teb=False):
    prefix = "test/benchmarks/bm_f"
    if wtemp:
        prefix += "_yc"
        f0 = nmt.NmtFieldFlat(WT.lx, WT.ly, WT.msk,
                              [WT.mps[0]],
                              templates=[[WT.tmp[0]]])
        f2 = nmt.NmtFieldFlat(WT.lx, WT.ly, WT.msk,
                              [WT.mps[1], WT.mps[2]],
                              templates=[[WT.tmp[1],
                                          WT.tmp[2]]],
                              purify_b=wpure)
    else:
        prefix += "_nc"
        f0 = nmt.NmtFieldFlat(WT.lx, WT.ly, WT.msk,
                              [WT.mps[0]])
        f2 = nmt.NmtFieldFlat(WT.lx, WT.ly, WT.msk,
                              [WT.mps[1], WT.mps[2]],
                              purify_b=wpure)
    f = [f0, f2]

    if wpure:
        prefix += "_yp"
    else:
        prefix += "_np"

    for ip1 in range(2):
        for ip2 in range(ip1, 2):
            if ip1 == ip2 == 0:
                clth = np.array([WT.cltt])
                nlth = np.array([WT.nltt])
            elif ip1 == ip2 == 1:
                clth = np.array([WT.clee, 0*WT.clee,
                                 0*WT.clbb, WT.clbb])
                nlth = np.array([WT.nlee, 0*WT.nlee,
                                 0*WT.nlbb, WT.nlbb])
            else:
                clth = np.array([WT.clte, 0*WT.clte])
                nlth = np.array([WT.nlte, 0*WT.nlte])
            w = nmt.NmtWorkspaceFlat()
            w.compute_coupling_matrix(f[ip1], f[ip2], WT.b)
            clb = w.couple_cell(WT.ll, nlth)
            if wtemp:
                dlb = nmt.deprojection_bias_flat(f[ip1], f[ip2],
                                                 WT.b, WT.ll,
                                                 clth+nlth)
                tlb = np.loadtxt(prefix+'_cb%d%d.txt' % (2*ip1, 2*ip2),
                                 unpack=True)[1:, :]
                assert (np.fabs(dlb-tlb) <=
                        np.fmin(np.fabs(dlb),
                                np.fabs(tlb))*1E-5).all()
                clb += dlb
            cl = w.decouple_cell(nmt.compute_coupled_cell_flat(f[ip1],
                                                               f[ip2],
                                                               WT.b),
                                 cl_bias=clb)
            tl = np.loadtxt(prefix+'_c%d%d.txt' % (2*ip1, 2*ip2),
                            unpack=True)[1:, :]
            assert (np.fabs(cl-tl) <=
                    np.fmin(np.fabs(cl),
                            np.fabs(tl))*1E-5).all()

    # TEB
    if do_teb:
        clth = np.array([WT.cltt, WT.clte, 0*WT.clte, WT.clee,
                         0*WT.clee, 0*WT.clbb, WT.clbb])
        nlth = np.array([WT.nltt, WT.nlte, 0*WT.nlte, WT.nlee,
                         0*WT.nlee, 0*WT.nlbb, WT.nlbb])
        w = nmt.NmtWorkspaceFlat()
        w.compute_coupling_matrix(f[0], f[1], WT.b, is_teb=True)
        c00 = nmt.compute_coupled_cell_flat(f[0], f[0], WT.b)
        c02 = nmt.compute_coupled_cell_flat(f[0], f[1], WT.b)
        c22 = nmt.compute_coupled_cell_flat(f[1], f[1], WT.b)
        cl = np.array([c00[0], c02[0], c02[1], c22[0],
                       c22[1], c22[2], c22[3]])
        t00 = np.loadtxt(prefix+'_c00.txt', unpack=True)[1:, :]
        t02 = np.loadtxt(prefix+'_c02.txt', unpack=True)[1:, :]
        t22 = np.loadtxt(prefix+'_c22.txt', unpack=True)[1:, :]
        tl = np.array([t00[0], t02[0], t02[1], t22[0],
                       t22[1], t22[2], t22[3]])
        cl = w.decouple_cell(cl, cl_bias=w.couple_cell(WT.ll, nlth))
        assert (np.fabs(cl-tl) <=
                np.fmin(np.fabs(cl),
                        np.fabs(tl))*1E-5).all()