def setUp(self):
        from astropy.io import fits
        from astropy.wcs import WCS

        # Read mask
        hdul = fits.open("test/benchmarks/msk_car.fits")
        self.msk = hdul[0].data
        # Set up coordinates
        self.wcs = WCS(hdul[0].header)
        self.nx, self.ny = self.wcs.pixel_shape
        hdul.close()
        # Read maps
        hdul = fits.open("test/benchmarks/mps_car.fits")
        self.mps = hdul[0].data
        hdul.close()

        self.wt = nmt.NmtWCSTranslator(self.wcs, (self.ny, self.nx))
        self.lmax = self.wt.get_lmax()
        self.nlb = 50
        self.npix = self.wt.npix
        self.b = nmt.NmtBin.from_lmax_linear(self.lmax, self.nlb)
        (self.l, self.cltt, self.clte, self.clee, self.clbb, self.cltb,
         self.cleb) = np.loadtxt("test/benchmarks/pspy_cls.txt", unpack=True)
        self.f0 = nmt.NmtField(self.msk, [self.mps[0]], wcs=self.wcs, n_iter=0)
        self.f0_half = nmt.NmtField(
            self.msk[:self.ny // 2, :self.nx // 2],
            [self.mps[0][:self.ny // 2, :self.nx // 2]],
            wcs=self.wcs,
            n_iter=0)
        self.b_half = nmt.NmtBin.from_lmax_linear(self.lmax // 2, self.nlb)
        self.b_doub = nmt.NmtBin.from_lmax_linear(self.lmax * 2, self.nlb)
        self.n_good = np.zeros([1, (self.lmax + 1)])
        self.n_bad = np.zeros([2, (self.lmax + 1)])
        self.n_half = np.zeros([1, (self.lmax // 2 + 1)])
Exemple #2
0
def get_fields():
    #Signal
    st, sq, su = hp.synfast([cltt, clee, clbb, clte],
                            o.nside_out,
                            new=True,
                            verbose=False,
                            pol=True)
    #Inhomogeneous white noise
    nt = np.sqrt(depth_nvar_t) * np.random.randn(hp.nside2npix(o.nside_out))
    nq = np.sqrt(depth_nvar_p) * np.random.randn(hp.nside2npix(o.nside_out))
    nu = np.sqrt(depth_nvar_p) * np.random.randn(hp.nside2npix(o.nside_out))
    st += nt
    sq += nq
    su += nu
    #Contaminants
    if w_cont:
        st += np.sum(fgt, axis=0)[0, :]
        sq += np.sum(fgp, axis=0)[0, :]
        su += np.sum(fgp, axis=0)[1, :]
        ff0 = nmt.NmtField(mask, [st], templates=fgt)
        ff2 = nmt.NmtField(mask, [sq, su], templates=fgp)
    else:
        ff0 = nmt.NmtField(mask, [st])
        ff2 = nmt.NmtField(mask, [sq, su])
    return ff0, ff2
Exemple #3
0
    def setUp(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.nside=64
        self.nlb=16
        self.lmax=3*self.nside-1
        self.npix=int(hp.nside2npix(self.nside))
        self.msk=hp.read_map("test/benchmarks/msk.fits",verbose=False)
        self.mps=np.array(hp.read_map("test/benchmarks/mps.fits",verbose=False,field=[0,1,2]))
        self.tmp=np.array(hp.read_map("test/benchmarks/tmp.fits",verbose=False,field=[0,1,2]))
        self.b=nmt.NmtBin(self.nside,nlb=self.nlb)
        self.f0=nmt.NmtField(self.msk,[self.mps[0]]) #Original nside
        self.f0_half=nmt.NmtField(self.msk[:self.npix//4],[self.mps[0,:self.npix//4]]) #Half nside
        self.b_half=nmt.NmtBin(self.nside//2,nlb=self.nlb) #Small-nside bandpowers
        self.b_doub=nmt.NmtBin(2*self.nside,nlb=self.nlb) #Large-nside bandposers
        self.n_good=np.zeros([1,3*self.nside])
        self.n_bad=np.zeros([2,3*self.nside])
        self.n_half=np.zeros([1,3*(self.nside//2)])
        
        l,cltt,clee,clbb,clte,nltt,nlee,nlbb,nlte=np.loadtxt("test/benchmarks/cls_lss.txt",unpack=True)
        self.l=l[:3*self.nside]
        self.cltt=cltt[:3*self.nside]
        self.clee=clee[:3*self.nside]
        self.clbb=clbb[:3*self.nside]
        self.clte=clte[:3*self.nside]
        self.nltt=nltt[:3*self.nside]
        self.nlee=nlee[:3*self.nside]
        self.nlbb=nlbb[:3*self.nside]
        self.nlte=nlte[:3*self.nside]
Exemple #4
0
    def Auto_TEB(self, maps):
        '''
        Calculate the auto-power spectra; 6 kinds of PS for each l-bin;
        
        Output
        ------------------------
        cls_all, with order TT TE TB EE EB BB.
        '''
        
        cls_all = np.ones((6, self.lbin))
        
        t = nmt.NmtField(self.mask, [maps[0]], purify_e=False, purify_b=True) ### no need to purify?? 2020.07.03
        qu = nmt.NmtField(self.mask, maps[1:3], purify_e=False, purify_b=True)
        
        cls_all[0] = self.compute_master(t, t, self.w00); #TT
        
        cls_all[1:3] = self.compute_master(t, qu, self.w02); #TE, TB

        cls_EB = self.compute_master(qu,qu,self.w22);
        
        cls_all[3] = cls_EB[0]; #EE
        cls_all[4] = cls_EB[1]; #EB
        cls_all[5] = cls_EB[3]; #BB
        
        return cls_all
Exemple #5
0
 def calculate_mode_coupling(self):
     # iterate through masks defined in the power spectrum list
     for var in self.masks['powerspectrum'].values():
         # read apodized mask from hdf5 file
         with h5py.File(self.hdf5_path, 'r') as f:
             mask = f[var['record']][...]
         # create the binning object
         binning = nmt.NmtBin.from_edges(**var['nmt_bin']['args'])
         # define some random fields on which to calculate the
         # mode coupling matrix
         beam = var['nmt_field']['args'].pop('beam', None)
         if beam is not None:
             beam = _gaussian_beam(beam / 60. * np.pi / 180.,
                                   np.arange(3 * self.nside))
         q1, u1, q2, u2 = np.random.randn(4, len(mask))
         f1 = nmt.NmtField(mask, [q1, u1],
                           **var['nmt_field']['args'],
                           beam=beam)
         f2 = nmt.NmtField(mask, [q2, u2],
                           **var['nmt_field']['args'],
                           beam=beam)
         # get namaster workspace object and compute coupling matrix
         wsp = nmt.NmtWorkspace()
         wsp.compute_coupling_matrix(f1, f2, binning)
         path = Path(var['nmt_wsp']['path'])
         if path.exists():
             path.unlink()
         # save to file
         wsp.write_to(str(path))
Exemple #6
0
 def test_lite_cont(self):
     f0 = nmt.NmtField(self.msk, [self.mps[0]], templates=[[self.tmp[0]]])
     f2 = nmt.NmtField(self.msk, [self.mps[1], self.mps[2]],
                       templates=[[self.tmp[1], self.tmp[2]]])
     f2l = nmt.NmtField(self.msk, [self.mps[1], self.mps[2]],
                        templates=[[self.tmp[1], self.tmp[2]]])
     f2e = nmt.NmtField(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.NmtWorkspace()
     w.compute_coupling_matrix(f0, f2e, self.b)
     clb = nlth
     dlb = nmt.deprojection_bias(f0, f2, clth+nlth)
     clb += dlb
     cl = w.decouple_cell(nmt.compute_coupled_cell(f0, f2l),
                          cl_bias=clb)
     tl = np.loadtxt("test/benchmarks/bm_yc_np_c02.txt",
                     unpack=True)[1:, :]
     tlb = np.loadtxt("test/benchmarks/bm_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())
Exemple #7
0
def test_field_alloc():
    # No templates
    f0 = nmt.NmtField(FT.msk, [FT.mps[0]], beam=FT.beam)
    f2 = nmt.NmtField(FT.msk, [FT.mps[1], FT.mps[2]], beam=FT.beam)
    f2p = nmt.NmtField(FT.msk, [FT.mps[1], FT.mps[2]],
                       beam=FT.beam,
                       purify_e=True,
                       purify_b=True,
                       n_iter_mask_purify=10)
    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 (1E-5 * np.mean(np.fabs(f2p.get_maps()[0])) > np.mean(
        np.fabs(f2p.get_maps()[0] - FT.mps[1] * FT.msk)))
    assert (1E-5 * np.mean(np.fabs(f2p.get_maps()[1])) > np.mean(
        np.fabs(f2p.get_maps()[1] - FT.mps[2] * FT.msk)))
    assert (len(f0.get_templates()) == 0)
    assert (len(f2.get_templates()) == 0)
    assert (len(f2p.get_templates()) == 0)

    # With templates
    f0 = nmt.NmtField(FT.msk, [FT.mps[0]],
                      templates=np.array([[t[0]] for t in FT.tmp]),
                      beam=FT.beam)
    f2 = nmt.NmtField(FT.msk, [FT.mps[1], FT.mps[2]],
                      templates=np.array([[t[1], t[2]] for t in FT.tmp]),
                      beam=FT.beam)
    # 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)
    def __init__(self, mask_in, nside, bin_w, lmin, lmax, beams, wsp = True):
        
        '''
        class for Band-Power-Estimation;
        
        Define the **apodized mask**, **beam weights**, **nside**, **bin-scheme**, **ell**
        
        ------------------------
        beams : a numpy array which include fwhms for every frequency. Deconvolve to ** lmax=2*nside **
        
      
        '''
        self.mask = nmt.mask_apodization(mask_in, 6, apotype='C2')
        
        self.nside = nside; self.lmax = lmax; self.Nf = len(beams); self.beams = beams;
        
#         self.beam = hp.gauss_beam(beams/60/180*np.pi, lmax = 3*self.nside); 
        
#         self.b = nmt.NmtBin(self.nside, nlb=bin_w, lmax=self.lmax, is_Dell = True)
        self.b = self.bands(bin_w = bin_w, lmin = lmin, lmax = lmax);
        
        self.ell_n = self.b.get_effective_ells(); self.lbin = len(self.ell_n)
#         self.w00 = [];
#         self.w02 = [];
        self.w22 = [];
                
        # - To construct a empty template with a mask to calculate the **coupling matrix**
        
        if wsp is True:
            
            qu = np.ones((2, 12*self.nside**2))

            for i in range(self.Nf):
                
                beam_i = hp.gauss_beam(beams[i]/60/180*np.pi, lmax = 3*self.nside - 1);
                
#                 m0 = nmt.NmtField(self.mask,[qu[0]],purify_e=False, purify_b=True, beam = beam_i);
                
#                 # construct a workspace that calculate the coupling matrix first.
#                 _w00 = nmt.NmtWorkspace()
#                 _w00.compute_coupling_matrix(m0, m0, self.b)  ## spin-0 with spin-0
                
#                 self.w00.append(_w00);
                
                for j in range(self.Nf):
                    
                    beam_j = hp.gauss_beam(beams[j]/60/180*np.pi, lmax = 3*self.nside - 1);
                    
                    m20 = nmt.NmtField(self.mask, qu, purify_e=False, purify_b=True, beam = beam_i);
                    m21 = nmt.NmtField(self.mask, qu, purify_e=False, purify_b=True, beam = beam_j);
            
#                     _w02 = nmt.NmtWorkspace()
#                     _w02.compute_coupling_matrix(m0, m21, self.b)  ## spin-0 with spin-2

                    _w22 = nmt.NmtWorkspace()
                    _w22.compute_coupling_matrix(m20, m21, self.b)  ## spin-2 with spin-2

            
#                     self.w02.append(_w02); 
                    self.w22.append(_w22)
Exemple #9
0
    def test_field_masked(self):
        nside = 64
        b = nmt.NmtBin.from_nside_linear(nside, 16)
        msk = hp.read_map("test/benchmarks/msk.fits", verbose=False)
        mps = np.array(
            hp.read_map("test/benchmarks/mps.fits",
                        verbose=False,
                        field=[0, 1, 2]))
        mps_msk = np.array([m * msk for m in mps])
        f0 = nmt.NmtField(msk, [mps[0]])
        f0_msk = nmt.NmtField(msk, [mps_msk[0]], masked_on_input=True)
        f2 = nmt.NmtField(msk, [mps[1], mps[2]])
        f2_msk = nmt.NmtField(msk, [mps_msk[1], mps_msk[2]],
                              masked_on_input=True)
        w00 = nmt.NmtWorkspace()
        w00.compute_coupling_matrix(f0, f0, b)
        w02 = nmt.NmtWorkspace()
        w02.compute_coupling_matrix(f0, f2, b)
        w22 = nmt.NmtWorkspace()
        w22.compute_coupling_matrix(f2, f2, b)

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

        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))
Exemple #10
0
    def setUp(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.nside = 64
        self.nlb = 16
        self.npix = hp.nside2npix(self.nside)
        msk = hp.read_map("test/benchmarks/msk.fits", verbose=False)
        mps = np.array(
            hp.read_map("test/benchmarks/mps.fits",
                        verbose=False,
                        field=[0, 1, 2]))
        self.b = nmt.NmtBin.from_nside_linear(self.nside, self.nlb)
        self.f0 = nmt.NmtField(msk, [mps[0]])
        self.f2 = nmt.NmtField(msk, [mps[1], mps[2]])
        self.f0_half = nmt.NmtField(msk[:self.npix // 4],
                                    [mps[0, :self.npix // 4]])  # Half nside
        self.w = nmt.NmtWorkspace()
        self.w.read_from("test/benchmarks/bm_nc_np_w00.fits")
        self.w02 = nmt.NmtWorkspace()
        self.w02.read_from("test/benchmarks/bm_nc_np_w02.fits")
        self.w22 = nmt.NmtWorkspace()
        self.w22.read_from("test/benchmarks/bm_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[:3 * self.nside]
        self.cltt = cltt[:3 * self.nside] + nltt[:3 * self.nside]
        self.clee = clee[:3 * self.nside] + nlee[:3 * self.nside]
        self.clbb = clbb[:3 * self.nside] + nlbb[:3 * self.nside]
        self.clte = clte[:3 * self.nside]
Exemple #11
0
def get_fields():
    #Signal
    st, sq, su = hp.synfast([
        cltt * beam**2 + nltt, clee * beam**2 + nlee, clbb * beam**2 + nlbb,
        clte * beam**2 + nlte
    ],
                            o.nside_out,
                            new=True,
                            verbose=False,
                            pol=True)
    if w_cont:
        sq += np.sum(fgp, axis=0)[0, :]
        su += np.sum(fgp, axis=0)[1, :]
        if o.no_deproject:
            ff2 = nmt.NmtField(mask, [sq, su],
                               beam=beam,
                               purify_e=False,
                               purify_b=w_pureb,
                               n_iter_mask_purify=10)
        else:
            ff2 = nmt.NmtField(mask, [sq, su],
                               templates=fgp,
                               beam=beam,
                               purify_e=False,
                               purify_b=w_pureb,
                               n_iter_mask_purify=10)
    else:
        ff2 = nmt.NmtField(mask, [sq, su],
                           beam=beam,
                           purify_e=False,
                           purify_b=w_pureb,
                           n_iter_mask_purify=10)
    return ff2
    def mastest(self):
        f0 = nmt.NmtField(self.msk, [self.mps[0]], wcs=self.wcs, n_iter=0)
        f2 = nmt.NmtField(self.msk, [self.mps[1], self.mps[2]],
                          wcs=self.wcs,
                          n_iter=0)
        f = [f0, f2]

        for ip1 in range(2):
            for ip2 in range(ip1, 2):
                if ip1 == ip2 == 0:
                    cl_bm = np.array([self.cltt])
                elif ip1 == ip2 == 1:
                    cl_bm = np.array(
                        [self.clee, self.cleb, self.cleb, self.clbb])
                else:
                    cl_bm = np.array([self.clte, self.cltb])
                w = nmt.NmtWorkspace()
                w.compute_coupling_matrix(f[ip1], f[ip2], self.b)
                cl = w.decouple_cell(nmt.compute_coupled_cell(f[ip1], f[ip2]))
                self.assertTrue(np.amax(np.fabs(cl - cl_bm)) <= 1E-10)

        # TEB
        w = nmt.NmtWorkspace()
        w.compute_coupling_matrix(f[0], f[1], self.b, is_teb=True)
        c00 = nmt.compute_coupled_cell(f[0], f[0])
        c02 = nmt.compute_coupled_cell(f[0], f[1])
        c22 = nmt.compute_coupled_cell(f[1], f[1])
        cl = w.decouple_cell(
            np.array([c00[0], c02[0], c02[1], c22[0], c22[1], c22[2], c22[3]]))
        cl_bm = np.array([
            self.cltt, self.clte, self.cltb, self.clee, self.cleb, self.cleb,
            self.clbb
        ])
        self.assertTrue(np.amax(np.fabs(cl - cl_bm)) <= 1E-10)
Exemple #13
0
    def get_fields(self, map, mask_apo=None, purify_e=False, purify_b=True, beam_correction=None):
        """

        Parameters
        ----------
        map: array
            IQU maps, shape (3, #pixels)
        mask_apo: array, optionnal (if not given the one used at the object's instanciation is used)
            Apodized mask.
        purify_e: bool, optional
            False by default.
        purify_b: bool, optional
            True by default.
            Note that generally it's not a good idea to purify both,
            since you'll lose sensitivity on E
        beam_correction: bool, optional
            None by default.
            If True, a correction by the Qubic beam at 150GHz is applied.
            You can also give the beam FWHM you want to correct for.
        Returns
        -------
        f0, f2: spin-0 and spin-2 Namaster fields.

        """

        # The maps may contain hp.UNSEEN - They must be replaced with zeros
        undefpix = map == hp.UNSEEN
        map[undefpix] = 0
        mp_t, mp_q, mp_u = map
        nside = hp.npix2nside(len(mp_t))

        if mask_apo is None:
            mask_apo = self.mask_apo

        if beam_correction is not None:
            if beam_correction is True:
                # Default value for QUBIC at 150 GHz
                beam = hp.gauss_beam(np.deg2rad(0.39268176),
                                     lmax=3 * nside - 1)
            else:
                beam = hp.gauss_beam(np.deg2rad(beam_correction),
                                     lmax=3 * nside - 1)
        else:
            beam = None

        f0 = nmt.NmtField(mask_apo,
                          [mp_t],
                          beam=beam)

        f2 = nmt.NmtField(mask_apo,
                          [mp_q, mp_u],
                          purify_e=purify_e,
                          purify_b=purify_b,
                          beam=beam)

        self.f0 = f0
        self.f2 = f2

        return f0, f2
Exemple #14
0
 def anafast(self, mps1, spin1, mps2=None, spin2=None):
     msk = np.ones(hp.nside2npix(self.nside))
     f1 = nmt.NmtField(msk, mps1, spin=spin1, n_iter=0)
     if mps2 is None:
         f2 = f1
     else:
         f2 = nmt.NmtField(msk, mps2, spin=spin2, n_iter=0)
     return nmt.compute_coupled_cell(f1, f2)
Exemple #15
0
def get_fields() :
    mp_t,mp_q,mp_u=hp.synfast([cltt,clee,clbb,clte],nside=nside,new=True,verbose=False)
    #This creates a spin-2 field without purifying either E or B
    f2_np=nmt.NmtField(msk_apo,[mp_q,mp_u])
    #This creates a spin-2 field with both pure E and B.
    f2_yp=nmt.NmtField(msk_apo,[mp_q,mp_u],purify_e=True,purify_b=True)
    #Note that generally it's not a good idea to purify both, since you'll lose sensitivity on E
    return f2_np,f2_yp
Exemple #16
0
 def autoWSP_EnB(self, maps, beams=None):
     # assemble NaMaster fields
     if beams is None:
         f2 = nmt.NmtField(self._apomask, [maps[1], maps[2]], purify_e=True, purify_b=True)
     else:
         f2 = nmt.NmtField(self._apomask, [maps[1], maps[2]], purify_e=True, purify_b=True, beam=hp.gauss_beam(beams, 3*self._nside-1))
     # prepare workspace
     w = nmt.NmtWorkspace()
     w.compute_coupling_matrix(f2, f2, self._b)
     return w
Exemple #17
0
 def autoWSP_TT(self, maps, beams=None):
     # assemble NaMaster fields
     if beams is None:
         f0 = nmt.NmtField(self._apomask, [maps[0]])
     else:
         f0 = nmt.NmtField(self._apomask, [maps[0]], beam=hp.gauss_beam(beams, 3*self._nside-1))
     # prepare workspace
     w = nmt.NmtWorkspace()
     w.compute_coupling_matrix(f0, f0, self._b)
     return w
Exemple #18
0
def get_fields():
    mppt, mppq, mppu = nmt.synfast_spherical(nside, [cltt, clee, clbb, clte],
                                             pol=True)
    if w_cont:  #Not ready yet
        mppq += alpha_cont_2 * fgq
        mppu += alpha_cont_2 * fgu
        ff2 = nmt.NmtField(mask, [mppq, mppu], [[fgq, fgu]])
    else:
        ff2 = nmt.NmtField(mask, [mppq, mppu],
                           purify_e=ispure_e,
                           purify_b=ispure_b,
                           n_iter_mask_purify=10)
    return mppq, mppu, ff2
Exemple #19
0
def get_fields():
    mppt, mppq, mppu = nmt.synfast_spherical(nside, [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.NmtField(mask, [mppt], templates=[[fgt]])
        ff2 = nmt.NmtField(mask, [mppq, mppu], [[fgq, fgu]])
    else:
        ff0 = nmt.NmtField(mask, [mppt])
        ff2 = nmt.NmtField(mask, [mppq, mppu])
    return mppt, mppq, mppu, ff0, ff2
Exemple #20
0
def get_fields() :
    """
    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=hp.synfast([cltt+nltt,clee+nlee,clbb+nlbb,clte+nlte],o.nside,new=True,verbose=False,pol=True)
    ff0=nmt.NmtField(mask_gc,[st],n_iter=o.n_iter)
    ff2=nmt.NmtField(mask_wl,[sq, su],n_iter=o.n_iter)
    return ff0, ff2
Exemple #21
0
 def cross_teb(self, maps, mask=None, aposcale=None, binning=None):
     """
     Cross PS,
     apply NaMaster estimator to TQU maps with(out) masks,
     requires NaMaster, healpy, numpy packages.
     
     Parameters
     ----------
     
     maps : numpy.ndarray
         A six-row array of T, Q, U maps, arranged as {T,Q,U,T,Q,U},
         with polarization in CMB convention.
         
     mask : numpy.ndarray
         mask map
         
     Returns
     -------
     
     pseudo-PS results : tuple of numpy.ndarray
         (ell, TT, EE, BB)
     """
     assert isinstance(maps, np.ndarray)
     assert (maps.shape[0] == 6)
     # fix resolution and apodization
     _nside = hp.get_nside(maps[0])
     # apodization
     if aposcale is None:
         aposcale = 1.0
     _apd_mask = nmt.mask_apodization(mask, aposcale, apotype='Smooth')
     _mapI01 = maps[0]
     _mapQ01 = maps[1]
     _mapU01 = maps[2]
     _mapI02 = maps[3]
     _mapQ02 = maps[4]
     _mapU02 = maps[5]
     # assemble NaMaster fields
     _f01 = nmt.NmtField(_apd_mask, [_mapI01])
     _f21 = nmt.NmtField(_apd_mask, [_mapQ01, _mapU01])
     _f02 = nmt.NmtField(_apd_mask, [_mapI02])
     _f22 = nmt.NmtField(_apd_mask, [_mapQ02, _mapU02])
     # initialize binning scheme with ? ells per bandpower
     if binning is None:
         binning = 16
     else:
         assert isinstance(binning, int)
     _b = nmt.NmtBin(_nside, nlb=binning)
     # MASTER estimator
     _cl00 = nmt.compute_full_master(_f01, _f02, _b)  # scalar - scalar
     _cl22 = nmt.compute_full_master(_f21, _f22, _b)  # tensor - tensor
     return _b.get_effective_ells(), _cl00[0], _cl22[0], _cl22[3]
Exemple #22
0
 def crosWSP_EnB(self, maps, beams=[None,None]):
     # assemble NaMaster fields
     if beams[0] is None:
         f21 = nmt.NmtField(self._apomask, [maps[1], maps[2]], purify_e=True, purify_b=True)
     else:
         f21 = nmt.NmtField(self._apomask, [maps[1], maps[2]], purify_e=True, purify_b=True, beam=hp.gauss_beam(beams[0], 3*self._nside-1))
     if beams[1] is None:
         f22 = nmt.NmtField(self._apomask, [maps[4], maps[5]], purify_e=True, purify_b=True)
     else:
         f22 = nmt.NmtField(self._apomask, [maps[4], maps[5]], purify_e=True, purify_b=True, beam=hp.gauss_beam(beams[1], 3*self._nside-1))
     # prepare workspace
     w = nmt.NmtWorkspace()
     w.compute_coupling_matrix(f21, f22, self._b)
     return w
Exemple #23
0
 def crosWSP_TT(self, maps, beams=[None,None]):
     # assemble NaMaster fields
     if beams[0] is None:
         f01 = nmt.NmtField(self._apomask, [maps[0]])
     else:
         f01 = nmt.NmtField(self._apomask, [maps[0]], beam=hp.gauss_beam(beams[0], 3*self._nside-1))
     if beams[1] is None:
         f02 = nmt.NmtField(self._apomask, [maps[3]])
     else:
         f02 = nmt.NmtField(self._apomask, [maps[3]], beam=hp.gauss_beam(beams[1], 3*self._nside-1))
     # prepare workspace
     w = nmt.NmtWorkspace()
     w.compute_coupling_matrix(f01, f02, self._b)
     return w
Exemple #24
0
def test_field_lite():
    # Lite field
    fl = nmt.NmtField(FT.msk, [FT.mps[0]], beam=FT.beam, lite=True)
    # Empty field
    with pytest.raises(ValueError):  # No maps and no spin
        fe = nmt.NmtField(FT.msk, None, beam=FT.beam)
    fe = nmt.NmtField(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()
Exemple #25
0
 def autoBP_EnB(self, maps, wsp=None, beams=None):
     # assemble NaMaster fields
     if beams is None:
         f2 = nmt.NmtField(self._apomask, [maps[1], maps[2]], purify_e=True, purify_b=True)
     else:
         f2 = nmt.NmtField(self._apomask, [maps[1], maps[2]], purify_e=True, purify_b=True, beam=hp.gauss_beam(beams, 3*self._nside-1))
     # estimate PS
     if wsp is None:
         cl22 = nmt.compute_full_master(f2, f2, self._b)
         return (self._modes, self.rebinning(cl22[0]), self.rebinning(cl22[3]))
     else:
         cl22c = nmt.compute_coupled_cell(f2, f2)
         cl22 = wsp.decouple_cell(cl22c)
         return (self._modes, self.rebinning(cl22[0]), self.rebinning(cl22[3]))
Exemple #26
0
    def test_field_alloc(self):
        # No templates
        f0 = nmt.NmtField(self.msk, [self.mps[0]],
                          beam=self.beam,
                          wcs=self.wcs)
        f2 = nmt.NmtField(self.msk, [self.mps[1], self.mps[2]],
                          beam=self.beam,
                          wcs=self.wcs)
        f2p = nmt.NmtField(self.msk, [self.mps[1], self.mps[2]],
                           beam=self.beam,
                           wcs=self.wcs,
                           purify_e=True,
                           purify_b=True,
                           n_iter_mask_purify=10)
        self.assertTrue(
            normdiff(f0.get_maps()[0], (self.mps[0] *
                                        self.msk).flatten()) < 1E-10)
        self.assertTrue(
            normdiff(f2.get_maps()[0], (self.mps[1] *
                                        self.msk).flatten()) < 1E-10)
        self.assertTrue(
            normdiff(f2.get_maps()[1], (self.mps[2] *
                                        self.msk).flatten()) < 1E-10)
        self.assertTrue(1E-5 * np.mean(np.fabs(f2p.get_maps()[0])) > np.mean(
            np.fabs(f2p.get_maps()[0] - (self.mps[1] * self.msk).flatten())))
        self.assertTrue(1E-5 * np.mean(np.fabs(f2p.get_maps()[1])) > np.mean(
            np.fabs(f2p.get_maps()[1] - (self.mps[2] * self.msk).flatten())))
        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.NmtField(self.msk, [self.mps[0]],
                          templates=np.array([[t[0]] for t in self.tmp]),
                          beam=self.beam,
                          wcs=self.wcs)
        f2 = nmt.NmtField(self.msk, [self.mps[1], self.mps[2]],
                          templates=np.array([[t[1], t[2]] for t in self.tmp]),
                          beam=self.beam,
                          wcs=self.wcs)
        # Map should be zero, since template =  map
        self.assertTrue(
            normdiff(f0.get_maps()[0], 0 * self.msk.flatten()) < 1E-10)
        self.assertTrue(
            normdiff(f2.get_maps()[0], 0 * self.msk.flatten()) < 1E-10)
        self.assertTrue(
            normdiff(f2.get_maps()[1], 0 * self.msk.flatten()) < 1E-10)
        self.assertEqual(len(f0.get_templates()), 5)
        self.assertEqual(len(f2.get_templates()), 5)
Exemple #27
0
    def Cross_EB(self, maps):

        '''
        Calculate the E- and B-mode power spectrum utilize Namaster purify_B method.

        Given parameters:
        ----------------
        maps : input maps with IQU component. Only Q and U are needed in this EB estimation. maps[i][1:]
        ell_n : the effective number of l_bins
        mask : apodized mask 
        beam : the gaussian beam weights for each multipole

        '''

        
        # - To construct a empty template with a mask to calculate the **coupling matrix**

        # > the template should have a shape (2, 12*nside^2)

        map0 = np.ones((2, 12*self.nside**2))
        m0 = nmt.NmtField(self.mask, map0, purify_e=False, purify_b=True)#, beam=bl)

        # construct a workspace that calculate the coupling matrix first.
        _w = nmt.NmtWorkspace()
        _w.compute_coupling_matrix(m0, m0, self.b)
    
        n_f = len(maps); 
        cl = np.ones((2, n_f*n_f, self.lbin)); Cl = np.zeros((2, self.lbin, n_f, n_f))
        k = 0
        for i in range(n_f):
            for j in range(n_f):

                if i >= j :

                    m_i = nmt.NmtField(self.mask, maps[i][1:], purify_e=False, purify_b=True)#beam=bl); #Q and U maps at i-th fre
                    m_j = nmt.NmtField(self.mask, maps[j][1:], purify_e=False, purify_b=True)#beam=bl); #Q and U maps at j-th fre

                    cross_ps = self.compute_master(m_i, m_j, _w) ## EE, EB, BE, BB
                else:
                    cross_ps = np.zeros((4, self.lbin)) 

                cl[0][k] = cross_ps[0]; cl[1][k] = cross_ps[3]  ## assign the E and B_mode power spectrum 
                k += 1

        for l in range(self.lbin):
            Cl[0, l, : , :] = cl[0, :,l].reshape(n_f, n_f); Cl[1, l, : , :] = cl[1, :,l].reshape(n_f, n_f)
            Cl[0, l] += Cl[0, l].T - np.diag(Cl[0, l].diagonal()) ; Cl[1, l] += Cl[1, l].T - np.diag(Cl[1, l].diagonal()) 
            
        return Cl
Exemple #28
0
 def auto_teb(self, maps, fwhms=None):
     assert isinstance(maps, np.ndarray)
     assert (maps.shape == (3,self._npix))
     # assemble NaMaster fields
     if fwhms is None:
         _f0 = nmt.NmtField(self._mask[0], [maps[0]])
         _f2 = nmt.NmtField(self._mask[0], [maps[1], maps[2]], purify_e=False, purify_b=True)
     else:
         _f0 = nmt.NmtField(self._mask[0], [maps[0]], beam=hp.gauss_beam(fwhms, 3*self._nside-1))
         _f2 = nmt.NmtField(self._mask[0], [maps[1], maps[2]], purify_e=False, purify_b=True, beam=hp.gauss_beam(fwhms, 3*self._nside-1))
     # estimate PS
     _cl00 = nmt.compute_full_master(_f0, _f0, self._b)
     _cl02 = nmt.compute_full_master(_f0, _f2, self._b)
     _cl22 = nmt.compute_full_master(_f2, _f2, self._b)
     return (self._modes, _cl00[0], _cl02[0], _cl02[1], _cl22[0], _cl22[1], _cl22[3])
Exemple #29
0
 def autoBP_TT(self, maps, wsp=None, beams=None):
     dat = maps[0]
     # assemble NaMaster fields
     if beams is None:
         f0 = nmt.NmtField(self._apomask, [dat])
     else:
         f0 = nmt.NmtField(self._apomask, [dat], beam=hp.gauss_beam(beams, 3*self._nside-1))
     # estimate PS
     if wsp is None:
         cl00 = nmt.compute_full_master(f0, f0, self._b)
         return (self._modes, self.rebinning(cl00[0]))
     else:
         cl00c = nmt.compute_coupled_cell(f0, f0)
         cl00 = wsp.decouple_cell(cl00c)
         return (self._modes, self.rebinning(cl00[0]))
Exemple #30
0
def field_make(cshcat,
               cshmask,
               purify_e=False,
               purify_b=False,
               save_maps=False,
               maps_prefix=''):
    """Generates NaMASTER cosmic-shear field
    """
    npix = cshmask.shape[0]
    nside = hp.npix2nside(npix)

    wg1map = np.bincount(cshcat[f'ip{nside}'],
                         minlength=npix,
                         weights=cshcat['w'] * cshcat['g1'])
    wg2map = np.bincount(cshcat[f'ip{nside}'],
                         minlength=npix,
                         weights=cshcat['w'] * cshcat['g2'])
    if save_maps:
        hp.write_map(f'{maps_prefix}_we1map.fits', wg1map, overwrite=True)
        hp.write_map(f'{maps_prefix}_we2map.fits', wg2map, overwrite=True)
        hp.write_map(f'{maps_prefix}_maskmap.fits', wg2map, overwrite=True)

    Rbias_mean = ((cshcat['R'] * cshcat['w']).sum() / cshcat['w'].sum())

    ip_good = (cshmask > 0.0)
    q = np.zeros_like(wg1map)
    q[ip_good] = wg1map[ip_good] / (cshmask[ip_good] * Rbias_mean)
    u = np.zeros_like(wg2map)
    u[ip_good] = wg2map[ip_good] / (cshmask[ip_good] * Rbias_mean)

    return nmt.NmtField(cshmask, [-q, u])