示例#1
0
    def test_field_lite(self):
        # Lite field
        fl = nmt.NmtFieldFlat(self.lx,
                              self.ly,
                              self.msk, [self.mps[0]],
                              beam=self.beam,
                              lite=True)
        # Empty field
        with self.assertRaises(ValueError):  # No maps and no spin
            fe = nmt.NmtFieldFlat(self.lx,
                                  self.ly,
                                  self.msk,
                                  None,
                                  beam=self.beam)
        fe = nmt.NmtFieldFlat(self.lx,
                              self.ly,
                              self.msk,
                              None,
                              beam=self.beam,
                              spin=1)

        # Error checks
        for f in [fl, fe]:
            with self.assertRaises(ValueError):  # Query maps
                f.get_maps()
            with self.assertRaises(ValueError):  # Query templates
                f.get_templates()
示例#2
0
    def setUp(self):
        wcs, msk = read_flat_map("test/benchmarks/msk_flat.fits")
        (ny, nx) = msk.shape
        lx = np.radians(np.fabs(nx * wcs.wcs.cdelt[0]))
        ly = np.radians(np.fabs(ny * wcs.wcs.cdelt[1]))
        mps = np.array([
            read_flat_map("test/benchmarks/mps_flat.fits", i_map=i)[1]
            for i in range(3)
        ])

        d_ell = 20
        lmax = 500.
        ledges = np.arange(int(lmax / d_ell) + 1) * d_ell + 2
        self.b = nmt.NmtBinFlat(ledges[:-1], ledges[1:])
        ledges_half = ledges[:len(ledges) // 2]
        self.b_half = nmt.NmtBinFlat(ledges_half[:-1], ledges_half[1:])
        self.f0 = nmt.NmtFieldFlat(lx, ly, msk, [mps[0]])
        self.f2 = nmt.NmtFieldFlat(lx, ly, msk, [mps[1], mps[2]])
        self.f0_half = nmt.NmtFieldFlat(lx, ly, msk[:ny // 2, :nx // 2],
                                        [mps[0, :ny // 2, :nx // 2]])
        self.w = nmt.NmtWorkspaceFlat()
        self.w.read_from("test/benchmarks/bm_f_nc_np_w00.fits")
        self.w02 = nmt.NmtWorkspaceFlat()
        self.w02.read_from("test/benchmarks/bm_f_nc_np_w02.fits")
        self.w22 = nmt.NmtWorkspaceFlat()
        self.w22.read_from("test/benchmarks/bm_f_nc_np_w22.fits")

        cls = np.loadtxt("test/benchmarks/cls_lss.txt", unpack=True)
        l, cltt, clee, clbb, clte, nltt, nlee, nlbb, nlte = cls
        self.ll = l
        self.cltt = cltt + nltt
        self.clee = clee + nlee
        self.clbb = clbb + nlbb
        self.clte = clte
示例#3
0
 def test_field_flat_errors(self):
     with self.assertRaises(ValueError):  # Incorrect map sizes
         nmt.NmtFieldFlat(self.lx, -self.ly, self.msk, [self.mps[0]])
     with self.assertRaises(ValueError):
         nmt.NmtFieldFlat(-self.lx, self.ly, self.msk, [self.mps[0]])
     with self.assertRaises(ValueError):  # Mismatching map dimensions
         nmt.NmtFieldFlat(self.lx, self.ly, self.msk,
                          [self.mps[0, :self.ny // 2]])
     with self.assertRaises(ValueError):  # Mismatching template dimensions
         nmt.NmtFieldFlat(self.lx,
                          self.ly,
                          self.msk, [self.mps[0]],
                          templates=np.array([[t[0, :self.ny // 2]]
                                              for t in self.tmp]))
     with self.assertRaises(ValueError):  # Passing 3 templates!
         nmt.NmtFieldFlat(self.lx, self.ly, self.msk, self.mps)
     with self.assertRaises(ValueError):  # Passing 3 templates!
         nmt.NmtFieldFlat(self.lx,
                          self.ly,
                          self.msk, [self.mps[0]],
                          templates=self.tmp)
     with self.assertRaises(ValueError):  # Passing crap templates
         nmt.NmtFieldFlat(self.lx,
                          self.ly,
                          self.msk, [self.mps[0]],
                          templates=1)
     with self.assertRaises(ValueError):  # Passing crap beam
         nmt.NmtFieldFlat(self.lx, self.ly, self.msk, [self.mps[0]], beam=1)
示例#4
0
    def __init__(self):
        # This is to avoid showing an ugly warning
        # that has nothing to do with pymaster
        if (sys.version_info > (3,  1)):
            warnings.simplefilter("ignore",  ResourceWarning)

        self.wcs, self.msk = read_flat_map("test/benchmarks/msk_flat.fits")
        (self.ny, self.nx) = self.msk.shape
        self.lx = np.radians(np.fabs(self.nx*self.wcs.wcs.cdelt[0]))
        self.ly = np.radians(np.fabs(self.ny*self.wcs.wcs.cdelt[1]))
        self.mps = np.array([read_flat_map("test/benchmarks/mps_flat.fits",
                                           i_map=i)[1] for i in range(3)])
        self.mps_s1 = np.array([read_flat_map("test/benchmarks/"
                                              "mps_sp1_flat.fits",
                                              i_map=i)[1] for i in range(3)])
        self.tmp = np.array([read_flat_map("test/benchmarks/tmp_flat.fits",
                                           i_map=i)[1] for i in range(3)])
        self.d_ell = 20
        self.lmax = 500.
        ledges = np.arange(int(self.lmax/self.d_ell)+1)*self.d_ell+2
        self.b = nmt.NmtBinFlat(ledges[:-1], ledges[1:])
        self.leff = self.b.get_effective_ells()
        self.f0 = nmt.NmtFieldFlat(self.lx, self.ly, self.msk,
                                   [self.mps[0]])
        self.f0_half = nmt.NmtFieldFlat(self.lx, self.ly,
                                        self.msk[:self.ny//2,
                                                 :self.nx//2],
                                        [self.mps[0,
                                                  :self.ny//2,
                                                  :self.nx//2]])
        ledges_half = ledges[:len(ledges)//2]
        self.b_half = nmt.NmtBinFlat(ledges_half[:-1],
                                     ledges_half[1:])

        dd = np.loadtxt("test/benchmarks/cls_lss.txt",
                        unpack=True)
        l, cltt, clee, clbb, clte, nltt, nlee, nlbb, nlte = dd
        self.ll = l[:]
        self.cltt = cltt[:]
        self.clee = clee[:]
        self.clbb = clbb[:]
        self.clte = clte[:]
        self.nltt = nltt[:]
        self.nlee = nlee[:]
        self.nlbb = nlbb[:]
        self.nlte = nlte[:]
        self.n_good = np.zeros([1, len(l)])
        self.n_bad = np.zeros([2, len(l)])
        self.nb_good = np.zeros([1, self.b.bin.n_bands])
        self.nb_bad = np.zeros([2, self.b.bin.n_bands])
示例#5
0
    def test_field_flat_alloc(self):
        # No templates
        f0 = nmt.NmtFieldFlat(self.lx,
                              self.ly,
                              self.msk, [self.mps[0]],
                              beam=self.beam)
        f2 = nmt.NmtFieldFlat(self.lx,
                              self.ly,
                              self.msk, [self.mps[1], self.mps[2]],
                              beam=self.beam)
        f2p = nmt.NmtFieldFlat(self.lx,
                               self.ly,
                               self.msk, [self.mps[1], self.mps[2]],
                               beam=self.beam,
                               purify_e=True,
                               purify_b=True)
        self.assertTrue(
            normdiff(f0.get_maps()[0], self.mps[0] * self.msk) < 1E-10)
        self.assertTrue(
            normdiff(f2.get_maps()[0], self.mps[1] * self.msk) < 1E-10)
        self.assertTrue(
            normdiff(f2.get_maps()[1], self.mps[2] * self.msk) < 1E-10)
        self.assertTrue(
            normdiff(f2p.get_maps()[0], self.mps[1] * self.msk) < 1E-10)
        self.assertTrue(
            normdiff(f2p.get_maps()[1], self.mps[2] * self.msk) < 1E-10)
        self.assertEqual(len(f0.get_templates()), 0)
        self.assertEqual(len(f2.get_templates()), 0)
        self.assertEqual(len(f2p.get_templates()), 0)

        # With templates
        f0 = nmt.NmtFieldFlat(self.lx,
                              self.ly,
                              self.msk, [self.mps[0]],
                              beam=self.beam,
                              templates=np.array([[t[0]] for t in self.tmp]))
        f2 = nmt.NmtFieldFlat(self.lx,
                              self.ly,
                              self.msk, [self.mps[1], self.mps[2]],
                              beam=self.beam,
                              templates=np.array([[t[1], t[2]]
                                                  for t in self.tmp]))
        # Map should be zero, since template =  map
        self.assertTrue(normdiff(f0.get_maps()[0], 0 * self.msk) < 1E-10)
        self.assertTrue(normdiff(f2.get_maps()[0], 0 * self.msk) < 1E-10)
        self.assertTrue(normdiff(f2.get_maps()[1], 0 * self.msk) < 1E-10)
        self.assertEqual(len(f0.get_templates()), 5)
        self.assertEqual(len(f2.get_templates()), 5)
def get_fields(fsk_ar, mask_ar, w_cont=False) :
    """
    Generate a simulated field.
    It returns two NmtField objects for a spin-0 and a spin-2 field.

    :param fsk: a fm.FlatMapInfo object.
    :param mask: a sky mask.
    :param w_cont: deproject any contaminants? (not implemented yet)
    """
    nbins = 2
    spins = [0,2] * nbins

    fsk = fsk_ar[0]  # They share fsk.nx, ny, etc.

    # maps == [st1, sq1, su1, st2, sq2, su2, ...] (oredered as in spins)
    maps = nmt.synfast_flat(int(fsk.nx),int(fsk.ny),fsk.lx_rad,fsk.ly_rad,
                              cls_ar + nls_ar, spins)
    st1, sq1, su1, st2, sq2, su2 = maps

    if w_cont :
        raise ValueError('Contaminants not implemented yet')
        # if np.any(templates_all):
        #     tst, tsq, tsu = templates_all.sum(axis=0)
        #     st+=tst; sq+=tsq; su+=tsu;
        # if o.no_deproject :
        #     ff0=nmt.NmtFieldFlat(fsk.lx_rad,fsk.ly_rad,mask.reshape([fsk.ny,fsk.nx]),
        #                          [st])
        #     ff2=nmt.NmtFieldFlat(fsk.lx_rad,fsk.ly_rad,mask.reshape([fsk.ny,fsk.nx]),
        #                          [sq, su])
        # else :
        #     ff0=nmt.NmtFieldFlat(fsk.lx_rad,fsk.ly_rad,mask.reshape([fsk.ny,fsk.nx]),
        #                          [st],
        #                          templates=templates_all[:,0,None,:])
        #     ff2=nmt.NmtFieldFlat(fsk.lx_rad,fsk.ly_rad,mask.reshape([fsk.ny,fsk.nx]),
        #                          [sq,su],
        #                          templates=templates_all[:,1:, :])
    else :
        ff0_1=nmt.NmtFieldFlat(fsk.lx_rad, fsk.ly_rad, mask_ar[0].reshape([fsk.ny, fsk.nx]),
                             [st1])
        ff0_2=nmt.NmtFieldFlat(fsk.lx_rad, fsk.ly_rad, mask_ar[1].reshape([fsk.ny, fsk.nx]),
                             [st2])
        ff2_1=nmt.NmtFieldFlat(fsk.lx_rad, fsk.ly_rad, mask_ar[0].reshape([fsk.ny, fsk.nx]),
                             [sq1, su1])
        ff2_2=nmt.NmtFieldFlat(fsk.lx_rad, fsk.ly_rad, mask_ar[1].reshape([fsk.ny, fsk.nx]),
                             [sq2, su2])
    return (ff0_1,ff2_1), (ff0_2, ff2_2)
示例#7
0
def get_fields() :
    st,sq,su=nmt.synfast_flat(int(fmi.nx),int(fmi.ny),fmi.lx_rad,fmi.ly_rad,
                              np.array([cltt*beam**2+nltt,clte*beam**2+nlte,0*cltt,
                                        clee*beam**2+nlee,0*clee,
                                        clbb*beam**2+nlbb]),[0,2])
    st=st.flatten(); sq=sq.flatten(); su=su.flatten()
    if w_cont :
        sq+=np.sum(fgp,axis=0)[0,:]; su+=np.sum(fgp,axis=0)[1,:];
        ff2=nmt.NmtFieldFlat(fmi.lx_rad,fmi.ly_rad,mask.reshape([fmi.ny,fmi.nx]),
                             [sq.reshape([fmi.ny,fmi.nx]),su.reshape([fmi.ny,fmi.nx])],
                             templates=fgp.reshape([1,2,fmi.ny,fmi.nx]),beam=[l,beam],
                             purify_e=False,purify_b=w_pureb)
    else :
        ff2=nmt.NmtFieldFlat(fmi.lx_rad,fmi.ly_rad,mask.reshape([fmi.ny,fmi.nx]),
                             [sq.reshape([fmi.ny,fmi.nx]),su.reshape([fmi.ny,fmi.nx])],
                             beam=[l,beam],purify_e=False,purify_b=w_pureb)
    return ff2
示例#8
0
def get_fields():
    mppt, mppq, mppu = nmt.synfast_flat(int(mi.nx),
                                        int(mi.ny),
                                        mi.lx * DTOR,
                                        mi.ly * DTOR, [cltt, clee, clbb, clte],
                                        pol=True)
    if w_cont:
        mppt += alpha_cont_0 * fgt
        mppq += alpha_cont_2 * fgq
        mppu += alpha_cont_2 * fgu
        ff0 = nmt.NmtFieldFlat(mi.lx * DTOR, mi.ly * DTOR, mask, [mppt],
                               [[fgt]])
        ff2 = nmt.NmtFieldFlat(mi.lx * DTOR, mi.ly * DTOR, mask, [mppq, mppu],
                               [[fgq, fgu]])
    else:
        ff0 = nmt.NmtFieldFlat(mi.lx * DTOR, mi.ly * DTOR, mask, [mppt])
        ff2 = nmt.NmtFieldFlat(mi.lx * DTOR, mi.ly * DTOR, mask, [mppq, mppu])
    return mppt, mppq, mppu, ff0, ff2
示例#9
0
def test_field_lite():
    # Lite field
    fl = nmt.NmtFieldFlat(FT.lx, FT.ly, FT.msk,
                          [FT.mps[0]], beam=FT.beam,
                          lite=True)
    # Empty field
    with pytest.raises(ValueError):  # No maps and no spin
        fe = nmt.NmtFieldFlat(FT.lx, FT.ly, FT.msk,
                              None, beam=FT.beam)
    fe = nmt.NmtFieldFlat(FT.lx, FT.ly, FT.msk,
                          None, beam=FT.beam, spin=1)

    # Error checks
    for f in [fl, fe]:
        with pytest.raises(ValueError):  # Query maps
            f.get_maps()
        with pytest.raises(ValueError):  # Query templates
            f.get_templates()
示例#10
0
    def test_field_masked(self):
        wcs, msk = read_flat_map("test/benchmarks/msk_flat.fits")
        ny, nx = msk.shape
        lx = np.radians(np.fabs(nx * wcs.wcs.cdelt[0]))
        ly = np.radians(np.fabs(ny * wcs.wcs.cdelt[1]))
        mps = np.array([
            read_flat_map("test/benchmarks/mps_flat.fits", i_map=i)[1]
            for i in range(3)
        ])
        mps_msk = np.array([m * msk for m in mps])
        d_ell = 20
        lmax = 500.
        ledges = np.arange(int(lmax / d_ell) + 1) * d_ell + 2
        b = nmt.NmtBinFlat(ledges[:-1], ledges[1:])

        f0 = nmt.NmtFieldFlat(lx, ly, msk, [mps[0]])
        f0_msk = nmt.NmtFieldFlat(lx,
                                  ly,
                                  msk, [mps_msk[0]],
                                  masked_on_input=True)
        f2 = nmt.NmtFieldFlat(lx, ly, msk, [mps[1], mps[2]])
        f2_msk = nmt.NmtFieldFlat(lx,
                                  ly,
                                  msk, [mps_msk[1], mps_msk[2]],
                                  masked_on_input=True)
        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)

        def mkcl(w, f, g):
            return w.decouple_cell(nmt.compute_coupled_cell_flat(f, g, b))

        c00 = mkcl(w00, f0, f0).flatten()
        c02 = mkcl(w02, f0, f2).flatten()
        c22 = mkcl(w22, f2, f2).flatten()
        c00_msk = mkcl(w00, f0_msk, f0_msk).flatten()
        c02_msk = mkcl(w02, f0_msk, f2_msk).flatten()
        c22_msk = mkcl(w22, f2_msk, f2_msk).flatten()
        self.assertTrue(np.all(np.fabs(c00 - c00_msk) / np.mean(c00) < 1E-10))
        self.assertTrue(np.all(np.fabs(c02 - c02_msk) / np.mean(c02) < 1E-10))
        self.assertTrue(np.all(np.fabs(c22 - c22_msk) / np.mean(c22) < 1E-10))
示例#11
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())
示例#12
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())
def get_fields(fsk,mask,w_cont=False) :
    """
    Generate a simulated field.
    It returns two NmtField objects for a spin-0 and a spin-2 field.

    :param fsk: a fm.FlatMapInfo object.
    :param mask: a sky mask.
    :param w_cont: deproject any contaminants? (not implemented yet)
    """
    st,sq,su=nmt.synfast_flat(int(fsk.nx),int(fsk.ny),fsk.lx_rad,fsk.ly_rad,
                              [cltt+nltt,clte+nlte,0*cltt,clee+nlee,0*clee,clbb+nlbb],[0,2])
    if w_cont :
        if np.any(templates_all):
            tst, tsq, tsu = templates_all.sum(axis=0)
            st+=tst; sq+=tsq; su+=tsu;
        if o.no_deproject :
            ff0=nmt.NmtFieldFlat(fsk.lx_rad,fsk.ly_rad,mask.reshape([fsk.ny,fsk.nx]),
                                 [st])
            ff2=nmt.NmtFieldFlat(fsk.lx_rad,fsk.ly_rad,mask.reshape([fsk.ny,fsk.nx]),
                                 [sq, su])
        else :
            ff0=nmt.NmtFieldFlat(fsk.lx_rad,fsk.ly_rad,mask.reshape([fsk.ny,fsk.nx]),
                                 [st],
                                 templates=templates_all[:,0,None,:])
            ff2=nmt.NmtFieldFlat(fsk.lx_rad,fsk.ly_rad,mask.reshape([fsk.ny,fsk.nx]),
                                 [sq,su],
                                 templates=templates_all[:,1:, :])
    else :
        ff0=nmt.NmtFieldFlat(fsk.lx_rad,fsk.ly_rad,mask.reshape([fsk.ny,fsk.nx]),
                             [st])
        ff2=nmt.NmtFieldFlat(fsk.lx_rad,fsk.ly_rad,mask.reshape([fsk.ny,fsk.nx]),
                             [sq,su])
    return ff0,ff2
示例#14
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())
示例#15
0
def test_field_flat_alloc():
    # No templates
    f0 = nmt.NmtFieldFlat(FT.lx, FT.ly, FT.msk,
                          [FT.mps[0]], beam=FT.beam)
    f2 = nmt.NmtFieldFlat(FT.lx, FT.ly, FT.msk,
                          [FT.mps[1], FT.mps[2]], beam=FT.beam)
    f2p = nmt.NmtFieldFlat(FT.lx, FT.ly, FT.msk,
                           [FT.mps[1], FT.mps[2]], beam=FT.beam,
                           purify_e=True, purify_b=True)
    assert (normdiff(f0.get_maps()[0],
                     FT.mps[0]*FT.msk) < 1E-10)
    assert (normdiff(f2.get_maps()[0],
                     FT.mps[1]*FT.msk) < 1E-10)
    assert (normdiff(f2.get_maps()[1],
                     FT.mps[2]*FT.msk) < 1E-10)
    assert (normdiff(f2p.get_maps()[0],
                     FT.mps[1]*FT.msk) < 1E-10)
    assert (normdiff(f2p.get_maps()[1],
                     FT.mps[2]*FT.msk) < 1E-10)
    assert (len(f0.get_templates()) == 0)
    assert (len(f2.get_templates()) == 0)
    assert (len(f2p.get_templates()) == 0)

    # With templates
    f0 = nmt.NmtFieldFlat(FT.lx, FT.ly, FT.msk,
                          [FT.mps[0]], beam=FT.beam,
                          templates=np.array([[t[0]]
                                              for t in FT.tmp]))
    f2 = nmt.NmtFieldFlat(FT.lx, FT.ly, FT.msk,
                          [FT.mps[1], FT.mps[2]], beam=FT.beam,
                          templates=np.array([[t[1], t[2]]
                                              for t in FT.tmp]))
    # Map should be zero, since template =  map
    assert (normdiff(f0.get_maps()[0], 0*FT.msk) < 1E-10)
    assert (normdiff(f2.get_maps()[0], 0*FT.msk) < 1E-10)
    assert (normdiff(f2.get_maps()[1], 0*FT.msk) < 1E-10)
    assert (len(f0.get_templates()) == 5)
    assert (len(f2.get_templates()) == 5)
示例#16
0
    def __init__(self,
                 hdu_list,
                 i_bin,
                 fsk,
                 mask_binary,
                 masked_fraction,
                 contaminants=None):

        #Read numbers map
        self.fsk, nmap = fm.read_flat_map(None, hdu=hdu_list[2 * i_bin])

        #Read N(z)
        self.nz_data = hdu_list[2 * i_bin + 1].data.copy()

        #Make sure other maps are compatible
        fm.compare_infos(self.fsk, fsk)
        if not self.fsk.is_map_compatible(mask_binary):
            raise ValueError("Mask size is incompatible")
        if not self.fsk.is_map_compatible(masked_fraction):
            raise ValueError("Mask size is incompatible")
        if contaminants is not None:
            for ic, c in enumerate(contaminants):
                if not self.fsk.is_map_compatible(c):
                    raise ValueError(
                        "%d-th contaminant template is incompatible" % ic)

        #Translate into delta map
        self.weight = masked_fraction * mask_binary
        goodpix = np.where(mask_binary > 0.1)[0]
        ndens = np.sum(nmap * mask_binary) / np.sum(self.weight)
        self.ndens_perad = ndens / (np.radians(self.fsk.dx) *
                                    np.radians(self.fsk.dy))
        self.delta = np.zeros_like(self.weight)
        self.delta[goodpix] = nmap[goodpix] / (ndens *
                                               masked_fraction[goodpix]) - 1

        #Reshape contaminants
        conts = None
        if contaminants is not None:
            conts = [[c.reshape([self.fsk.ny, self.fsk.nx])]
                     for c in contaminants]

        #Form NaMaster field
        self.field = nmt.NmtFieldFlat(
            np.radians(self.fsk.lx),
            np.radians(self.fsk.ly),
            self.weight.reshape([self.fsk.ny, self.fsk.nx]),
            [self.delta.reshape([self.fsk.ny, self.fsk.nx])],
            templates=conts)
示例#17
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())
示例#18
0
    def __init__(self, catalog, nmap_zbin):
        """
        Holds all of the relevant information for a given redshift bin number map
        """

        Ngal = np.sum(nmap_zbin * catalog.mask_binary)
        self.ndens = Ngal / np.sum(catalog.weight)
        self.ndens_perad = self.ndens / (np.radians(catalog.fsk.dx) *
                                         np.radians(catalog.fsk.dy))
        self.delta = np.zeros_like(catalog.weight)
        self.delta[catalog.goodpix] = nmap_zbin[catalog.goodpix] / (
            self.ndens * catalog.masked_fraction[catalog.goodpix]) - 1

        self.field = nmt.NmtFieldFlat(
            np.radians(catalog.fsk.lx), np.radians(catalog.fsk.ly),
            catalog.weight.reshape([catalog.fsk.ny, catalog.fsk.nx]),
            [self.delta.reshape([catalog.fsk.ny, catalog.fsk.nx])])
示例#19
0
def get_fields():
    st, sq, su = nmt.synfast_flat(
        int(fmi.nx),
        int(fmi.ny),
        fmi.lx_rad,
        fmi.ly_rad, [cltt + nltt, clee + nlee, clbb + nlbb, clte + nlte],
        pol=True)
    st = st.flatten()
    sq = sq.flatten()
    su = su.flatten()
    if w_cont:
        st += np.sum(fgt, axis=0)[0, :]
        sq += np.sum(fgp, axis=0)[0, :]
        su += np.sum(fgp, axis=0)[1, :]
        if o.no_deproject:
            ff0 = nmt.NmtFieldFlat(fmi.lx_rad, fmi.ly_rad,
                                   mask.reshape([fmi.ny, fmi.nx]),
                                   [st.reshape([fmi.ny, fmi.nx])])
            ff2 = nmt.NmtFieldFlat(
                fmi.lx_rad, fmi.ly_rad, mask.reshape([fmi.ny, fmi.nx]),
                [sq.reshape([fmi.ny, fmi.nx]),
                 su.reshape([fmi.ny, fmi.nx])])
        else:
            ff0 = nmt.NmtFieldFlat(
                fmi.lx_rad,
                fmi.ly_rad,
                mask.reshape([fmi.ny, fmi.nx]), [st.reshape([fmi.ny, fmi.nx])],
                templates=fgt.reshape([2, 1, fmi.ny, fmi.nx]))
            ff2 = nmt.NmtFieldFlat(
                fmi.lx_rad,
                fmi.ly_rad,
                mask.reshape([fmi.ny, fmi.nx]),
                [sq.reshape([fmi.ny, fmi.nx]),
                 su.reshape([fmi.ny, fmi.nx])],
                templates=fgp.reshape([2, 2, fmi.ny, fmi.nx]))
    else:
        ff0 = nmt.NmtFieldFlat(fmi.lx_rad, fmi.ly_rad,
                               mask.reshape([fmi.ny, fmi.nx]),
                               [st.reshape([fmi.ny, fmi.nx])])
        ff2 = nmt.NmtFieldFlat(
            fmi.lx_rad, fmi.ly_rad, mask.reshape([fmi.ny, fmi.nx]),
            [sq.reshape([fmi.ny, fmi.nx]),
             su.reshape([fmi.ny, fmi.nx])])
    return ff0, ff2
示例#20
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
示例#21
0
    l,ctt,cte,ctb,cee,ceb,cbe,cbb=np.loadtxt(fname,unpack=True);
    return l,ctt,cte,ctb,cee,ceb,cbe,cbb
l_th,clTT_th,clTE_th,clTB_th,clEE_th,clEB_th,clBE_th,clBB_th=read_cls(prefix_clean+"_cl_th.txt")
ndof=len(l_th)

print("Plotting contamination figure")
l,cltt,clee,clbb,clte,nltt,nlee,nlbb,nlte=np.loadtxt("data/cls_lss.txt",unpack=True)    
cltt[0]=0; clee[0]=0; clbb[0]=0; clte[0]=0;
nltt[0]=0; nlee[0]=0; nlbb[0]=0; nlte[0]=0;
fmi,mask_hsc=fm.read_flat_map("data/mask_lss_flat.fits")
dum,fgt=fm.read_flat_map("data/cont_lss_dust_flat.fits") #Dust
st,sq,su=nmt.synfast_flat(int(fmi.nx),int(fmi.ny),fmi.lx_rad,fmi.ly_rad,
                          [cltt+nltt,clte+nlte,0*cltt,clee+nlee,0*clee,clbb+nlbb],[0,2])
mask_hsc[:]=1
ff0=nmt.NmtFieldFlat(fmi.lx_rad,fmi.ly_rad,mask_hsc.reshape([fmi.ny,fmi.nx]),
                     [st+fgt.reshape([fmi.ny,fmi.nx])],
                     templates=fgt.reshape([1,1,fmi.ny,fmi.nx]))
plt.figure(figsize=(12,4.75))
fs_or=matplotlib.rcParams['font.size']
ax=plt.subplot(221,projection=fmi.wcs);
fmi.view_map(st.flatten(),ax=ax,addColorbar=False,title='Signal',
             colorMin=np.amin(st),colorMax=np.amax(st))
ax=plt.subplot(222,projection=fmi.wcs);
fmi.view_map(4*fgt,ax=ax,addColorbar=False,title='Contaminant',
             colorMin=np.amin(st),colorMax=np.amax(st))
ax=plt.subplot(223,projection=fmi.wcs);
fmi.view_map(st.flatten()+4*fgt,ax=ax,addColorbar=False,title='Contaminated map',
             colorMin=np.amin(st),colorMax=np.amax(st))
ax=plt.subplot(224,projection=fmi.wcs);
fmi.view_map(ff0.get_maps().flatten(),ax=ax,addColorbar=False,title='Cleaned map',
             colorMin=np.amin(st),colorMax=np.amax(st))
示例#22
0
np.random.seed(rseed)
mpt_conv3, = nmt.synfast_flat(Nx,
                              Ny,
                              Lx,
                              Ly,
                              np.expand_dims(cl_tt_conv3, 0), [0],
                              seed=rseed)

# Write out for reuse later
np.save('../data/mpt.npy', mpt)
np.save('../data/mpt_conv.npy', mpt_conv)
np.save('../data/mpt_conv2.npy', mpt_conv2)
np.save('../data/mpt_conv3.npy', mpt_conv3)

mask = np.ones_like(mpt)
f0 = nmt.NmtFieldFlat(Lx, Ly, mask, [mpt])
f0_conv = nmt.NmtFieldFlat(Lx, Ly, mask, [mpt_conv], beam=[l, beam])
f0_conv2 = nmt.NmtFieldFlat(Lx, Ly, mask, [mpt_conv2], beam=[l, beam])
f0_conv3 = nmt.NmtFieldFlat(Lx, Ly, mask, [mpt_conv3], beam=[l, beam])

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)
ells_uncoupled = b.get_effective_ells()

w00 = nmt.NmtWorkspaceFlat()
w00.compute_coupling_matrix(f0, f0, b)
w00.write_to("../data/w00_flat.fits")

w00_conv = nmt.NmtWorkspaceFlat()
w00_conv.compute_coupling_matrix(f0_conv, f0_conv, b)
        # io.plot_img(imaps[0],io.dout_dir+field+"_I_lowres.png")
        # io.plot_img(imaps[1],io.dout_dir+field+"_Q_lowres.png")
        # io.plot_img(imaps[2],io.dout_dir+field+"_U_lowres.png")

        # Quick power sanity check
        p2d, _, _ = fc.power2d(imaps[0], imaps[0])
        # io.plot_img(np.fft.fftshift(np.log10(p2d)),io.dout_dir+"p2d.png")
        p1d = binit(p2d) / w2
        pl = io.Plotter(yscale='log')
        pl.add(ellrange, clkk, lw=2, color="k")
        pl.add(cents, p1d, marker="o")
        pl.done(io.dout_dir + "cls.png")

    # ENMAP TO NAMASTER FIELDS
    mpt, mpq, mpu = imaps[0], imaps[1], imaps[2]
    f0 = nmt.NmtFieldFlat(Lx, Ly, mask, [mpt])
    f2 = nmt.NmtFieldFlat(Lx,
                          Ly,
                          mask, [mpq, mpu],
                          purify_e=purify_e,
                          purify_b=purify_b)
    # ells_coupled=f0.get_ell_sampling()

    #Bins:
    l0_bins = bin_edges[:-1]
    lf_bins = bin_edges[1:]
    b = nmt.NmtBinFlat(l0_bins, lf_bins)
    ells_uncoupled = b.get_effective_ells()

    if i == 0:
        print("Workspaces; calculating coupling matrices")
示例#24
0
        elif spin1 == 2 and spin2 == 2:
            # Define flat sky spin-2 map
            emaps = [map1[0], map1[1]]
            # Define flat sky spin-0 map
            emaps = [map2[0], map2[1]]

        else:
            # Define flat sky spin-0 map
            emaps = [map1]
            # Define flat sky spin-0 map
            emaps = [map2]

        # Define fields
        f1 = nmt.NmtFieldFlat(config['Lx'],
                              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
示例#25
0
    def compute_wsps(self):
        """
        Convenience method for calculating the NaMaster workspaces for all the probes in the simulation.
        :return wsps: wsps list
        """

        self.wsps = [[None for i in range(self.params['nprobes'])]
                     for ii in range(self.params['nprobes'])]

        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']:
            maps = copy.deepcopy(signalmaps)
        elif 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'])

        # Compute workspaces 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:
                    spin1 = self.params['spins'][j]
                    spin2 = self.params['spins'][jj]

                    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)

                        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

                    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)

                        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:
                        # 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)

                        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

        return self.wsps
示例#26
0
def get_sample_field():
    mpt = nmt.synfast_flat(Nx, Ny, Lx, Ly, np.array([clarr]), [0])[0]
    return nmt.NmtFieldFlat(Lx, Ly, mask, [mpt])
示例#27
0
    [cltt + nltt, clte + nlte, 0 * cltt, clee + nlee, 0 * clee, clbb + nlbb],
    [0, 2])
write_flat_map("mps_flat.fits", np.array([dt, dq, du]), wcs, ["T", "Q", "U"])
d_ell = 20
lmax = 500.
ledges = np.arange(int(lmax / d_ell) + 1) * d_ell + 2
_, st = read_flat_map("tmp_flat.fits", 0)
_, sq = read_flat_map("tmp_flat.fits", 1)
_, su = read_flat_map("tmp_flat.fits", 2)

b = nmt.NmtBinFlat(ledges[:-1], ledges[1:])
leff = b.get_effective_ells()

#No contaminants
prefix = 'bm_f_nc_np'
f0 = nmt.NmtFieldFlat(lx, ly, msk, [dt])
f2 = nmt.NmtFieldFlat(lx, ly, msk, [dq, du])
w00 = nmt.NmtWorkspaceFlat()
w00.compute_coupling_matrix(f0, f0, b)
cw00 = nmt.NmtCovarianceWorkspaceFlat()
cw00.compute_coupling_coefficients(w00, w00)
cw00.write_to(prefix + '_cw00.dat')
cov = nmt.gaussian_covariance_flat(cw00, l, cltt + nltt, cltt + nltt,
                                   cltt + nltt, cltt + nltt)
np.savetxt(prefix + "_cov.txt", cov)
clb00 = w00.couple_cell(l, np.array([nltt]))
c00 = w00.decouple_cell(nmt.compute_coupled_cell_flat(f0, f0, b),
                        cl_bias=clb00)
w00.write_to(prefix + '_w00.dat')
np.savetxt(prefix + '_c00.txt', np.transpose([leff, c00[0]]))
w02 = nmt.NmtWorkspaceFlat()
示例#28
0
   returns:
    -> array-like; value of beam at those ells
"""


def beam(l):
    Planck_res = 10. / 60
    Planck_sig = Planck_res / 2.3548
    return np.exp(-0.5 * l * (l + 1) * (Planck_sig * np.pi / 180)**2)


"----------------------------- PLOTTING FIELD WITH MASK -------------------------"

f0 = nmt.NmtFieldFlat(Lx,
                      Ly,
                      mask, [norm_y_fluc],
                      beam=[ells_uncoupled,
                            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)
示例#29
0
    def load_maps(self):
        import pymaster as nmt
        import healpy
        # Parameters that we need at this point
        apod_size = self.config['apodization_size']
        apod_type = self.config['apodization_type']

        # Load the various input maps and their metadata
        map_file = self.open_input('diagnostic_maps', wrapper=True)
        pix_info = map_file.read_map_info('mask')
        area = map_file.file['maps'].attrs["area"]

        nbin_source = map_file.file['maps'].attrs['nbin_source']
        nbin_lens = map_file.file['maps'].attrs['nbin_lens']

        # Choose pixelization and read mask and systematics maps
        pixel_scheme = choose_pixelization(**pix_info)

        # Load the mask. It should automatically be the same shape as the
        # others, based on how it was originally generated.
        # We remove any pixels that are at or below our threshold (default=0)
        mask = map_file.read_map('mask')
        mask_threshold = self.config['mask_threshold']
        mask[mask <= mask_threshold] = 0
        mask[np.isnan(mask)] = 0
        mask_sum = mask.sum()
        f_sky = area / 41253.
        if self.rank == 0:
            print(f"Unmasked area = {area}, fsky = {f_sky}")

        # Load all the maps in.
        # TODO: make it possible to just do a subset of these
        ngal_maps = [map_file.read_map(f'ngal_{b}') for b in range(nbin_lens)]
        g1_maps = [map_file.read_map(f'g1_{b}') for b in range(nbin_source)]
        g2_maps = [map_file.read_map(f'g2_{b}') for b in range(nbin_source)]

        # Mask any pixels which have the healpix bad value
        for m in g1_maps + g2_maps + ngal_maps:
            mask[m == healpy.UNSEEN] = 0

        if self.config['flip_g2']:
            for g2 in g2_maps:
                w = np.where(g2 != healpy.UNSEEN)
                g2[w] *= -1

        # TODO: load systematics maps here, once we are making them.
        syst_nc = None
        syst_wl = None

        map_file.close()

        # Cut out any pixels below the threshold,
        # zeroing out any pixels there
        cut = mask < mask_threshold
        mask[cut] = 0

        # We also apply this cut to the count maps,
        # since otherwise the pixels below threshold would contaminate
        # the mean calculation below.
        for ng in ngal_maps:
            ng[cut] = 0

        # Convert the number count maps to overdensity maps.
        # First compute the overall mean object count per bin.
        # Maybe we should do this in the mapping code itself?
        n_means = [ng.sum() / mask_sum for ng in ngal_maps]
        # and then use that to convert to overdensity
        d_maps = [(ng / mu) - 1 for (ng, mu) in zip(ngal_maps, n_means)]

        d_fields = []
        wl_fields = []

        if pixel_scheme.name == 'gnomonic':
            lx = np.radians(pixel_scheme.size_x)
            ly = np.radians(pixel_scheme.size_y)

            # Apodize the mask
            if apod_size > 0:
                if self.rank == 0:
                    print(
                        f"Apodizing mask with size {apod_size} deg and method {apod_type}"
                    )
                mask = nmt.mask_apodization_flat(mask,
                                                 lx,
                                                 ly,
                                                 apod_size,
                                                 apotype=apod_type)
            elif self.rank == 0:
                print("Not apodizing mask.")

            for i, d in enumerate(d_maps):
                # Density for gnomonic maps
                if self.rank == 0:
                    print(f"Generating gnomonic density field {i}")
                field = nmt.NmtFieldFlat(lx, ly, mask, [d], templates=syst_nc)
                d_fields.append(field)

            for i, (g1, g2) in enumerate(zip(g1_maps, g2_maps)):
                # Density for gnomonic maps
                if self.rank == 0:
                    print(f"Generating gnomonic lensing field {i}")
                field = nmt.NmtFieldFlat(lx,
                                         ly,
                                         mask, [g1, g2],
                                         templates=syst_wl)
                wl_fields.append(field)

        elif pixel_scheme.name == 'healpix':
            # Apodize the mask
            if apod_size > 0:
                if self.rank == 0:
                    print(
                        f"Apodizing mask with size {apod_size} deg and method {apod_type}"
                    )
                mask = nmt.mask_apodization(mask, apod_size, apotype=apod_type)
            elif self.rank == 0:
                print("Not apodizing mask.")

            for i, d in enumerate(d_maps):
                # Density for gnomonic maps
                print(f"Generating healpix density field {i}")
                field = nmt.NmtField(mask, [d], templates=syst_nc)
                d_fields.append(field)

            for i, (g1, g2) in enumerate(zip(g1_maps, g2_maps)):
                # Density for gnomonic maps
                print(f"Generating healpix lensing field {i}")
                field = nmt.NmtField(mask, [g1, g2], templates=syst_wl)
                wl_fields.append(field)

        else:
            raise ValueError(
                f"Pixelization scheme {pixel_scheme.name} not supported by NaMaster"
            )

        return pixel_scheme, d_fields, wl_fields, nbin_source, nbin_lens, f_sky
示例#30
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