Exemplo n.º 1
0
def test_mask_errors():
    with pytest.raises(RuntimeError):  # Badly shaped input
        nmt.mask_apodization(MT.msk[:13], MT.aposize, apotype="C1")
    with pytest.raises(RuntimeError):  # Negative apodization
        nmt.mask_apodization(MT.msk, -MT.aposize, apotype="C1")
    with pytest.raises(RuntimeError):  # Wrong apodization type
        nmt.mask_apodization(MT.msk, MT.aposize, apotype="C3")
    with pytest.raises(RuntimeError):  # Aposize too small
        nmt.mask_apodization(MT.msk[:12 * 2**2], 1., apotype='C1')
    with pytest.raises(RuntimeError):
        nmt.mask_apodization(MT.msk[:12 * 2**2], 1., apotype='Smooth')
Exemplo n.º 2
0
 def _get_mask(self):
     msk = hp.read_map(self.config['file_mask'], dtype=float)
     msk = rotate_mask(msk, self.rot, binarize=True)
     # Apodize
     msk = nmt.mask_apodization(msk, self.mask_aposize, self.mask_apotype)
     msk = hp.ud_grade(msk, nside_out=self.nside)
     return msk
Exemplo n.º 3
0
def so_mask_hits(nside, aposcale=20, gal_mask=None):
    """ Function to return mask on which power spectra will be calculated. This
    combines the SO hits map (passed as the hits map to each field, not square root)
    with a Galactic mask from Planck (between 20 and 80 % of the sky unmasked) by
    simply multiplying the two masks. The resulting mask then has an additional
    tapering applied to ensure the second derivative is zero at the boundary.

    Parameters
    ----------
    nside: int
        Resolution at which to calculate the mask.
    aposcale: float
        Parameter relevant to the additional tapering applied. This is the length
        scale of the taper, and is defined in the NaMaster documentation. Note that
        we use the 'C2' apodization scheme, which is outlined in Grain et al. 2009.
    gal_mask: int
        Field of the Planck mask fits file to use. This can be 0 - 6. Increasing
        numbers refer to less masking.

    Returns
    -------
    ndarray(float)
        Scalar mask at resolution given by `nside`.
    """
    mask = get_nhits(nside)
    if gal_mask is not None:
        # read planck mask at a given nside, and make binary by applying the
        # numpy.ceil function.
        mask *= np.ceil(
            hp.ud_grade(hp.read_map(_GAL_MASK, field=gal_mask, verbose=False),
                        nside_out=nside))
    # apply an additional C2 apodization to the nhits mask + galactic mask
    return nmt.mask_apodization(mask, aposcale, apotype="C2")
Exemplo n.º 4
0
    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)
Exemplo n.º 5
0
def main(cfg_path: Path, log_level: int):
    logging.basicConfig(
        stream=sys.stdout,
        level=log_level,
        datefmt='%Y-%m-%d %H:%M',
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    with open(cfg_path) as f:
        cfg = yaml.load(f, Loader=yaml.FullLoader)

    nside = cfg['nside']
    outpath = cfg['hdf5_path']

    mask_file = 'data/n0512.fits'
    mask_data = old_np.nan_to_num(
        hp.read_map(mask_file, verbose=False, dtype=np.float32))
    mask_apodized = nmt.mask_apodization(mask_data, 5., apotype="C2")
    mask_binary = old_np.where(mask_data > 0.0, 1.0, 0.0)

    with h5py.File(outpath, 'w') as f:
        ns0512 = f.require_group('ns0512')
        data_dset = ns0512.require_dataset('binary',
                                           shape=(hp.nside2npix(nside), ),
                                           dtype=np.float32)
        data_dset[...] = np.nan_to_num(mask_binary)

        apodized = ns0512.require_group('apodized')
        data_dset2 = apodized.require_dataset('basic',
                                              shape=(hp.nside2npix(nside), ),
                                              dtype=np.float32)
        data_dset2[...] = np.nan_to_num(mask_apodized)
 def __init__(self,cat,nside,theta_apo) :
     """ Initializes Mask object from catalog and resolution parameters
     
     Parameters
     ----------
     cat : fc.Catalog
         Catalog containing window information
     nside : int
         HEALPix resolution index
     theta_apo : float
         Apodization scale in degrees
     """
     
     if cat.window.typestr=='decbcut':
         npix=hp.nside2npix(nside)
         ind_aux=np.arange(0,npix)
         theta,phi=hp.pix2ang(nside,ind_aux)
         self.weights=cat.window(phi*180/np.pi,90-theta*180/np.pi)
     elif cat.window.typestr=='base':
         self.weights=np.ones(12*nside**2)
     else:
         self.weights=cat.window.map.copy()
     if debug:
         hp.mollview(self.weights)
         plt.show() 
     #Figure out which pixels are empty
     self.ip_nomask=np.where(self.weights>0)[0] 
     #Generate sky mask and apply apodization
     self.binary=np.zeros_like(self.weights)
     self.binary[self.ip_nomask]=1.
     if theta_apo>0 :
         self.mask_apo=nmt.mask_apodization(self.binary,theta_apo,apotype='C1')
     else :
         self.mask_apo=self.binary.copy()
     #Final weights are a combination of mask + depth fluctuations
     self.total=self.mask_apo*self.weights
     #Can't generate maps with pixels larger than the mask
     if (cat.window.typestr!='decbcut') & (cat.window.typestr!='base'):
         if nside<cat.window.nside:
             #If mask pixelization is higher, upgrade output maps
             self.nside=cat.window.nside
         else :
             #If mask pixelization is lower, upgrade mask
             self.nside=nside
             self.total  =hp.ud_grade(self.total  ,nside_out=nside)
             self.binary =hp.ud_grade(self.binary ,nside_out=nside)
             self.weights=hp.ud_grade(self.weights,nside_out=nside)
             self.ip_nomask=np.where(self.weights>0)[0] 
     else:
         self.nside=nside
         self.total  =hp.ud_grade(self.total  ,nside_out=nside)
         self.binary =hp.ud_grade(self.binary ,nside_out=nside)
         self.weights=hp.ud_grade(self.weights,nside_out=nside)
         self.ip_nomask=np.where(self.weights>0)[0]
     #Pixel area
     self.pixOmega=4*np.pi/hp.nside2npix(self.nside)
     if debug:
         hp.mollview(self.weights)
         plt.show()
Exemplo n.º 7
0
 def mask(self, mask):
     """apply apodization during initialization"""
     if mask is None:
         self._mask = np.ones((1,self._npix),dtype=np.float64)
     else:
         assert isinstance(mask, np.ndarray)
         assert (mask.shape == (1,self._npix))
         self._mask = nmt.mask_apodization(mask[0], self._aposcale, apotype='C2').reshape(1,-1)
def apodize_mask(mask, apod_arcmin=60, apod_type='C2'):
    """
    for pure-B formalism, must be differentiable at boundary : use 'C1' or 'C2' schemes
    """

    apod_deg = apod_arcmin / 60.
    mask_apod = nmt.mask_apodization(mask, apod_deg, apotype=apod_type)

    return mask_apod
Exemplo n.º 9
0
 def mask(self, mask):
     if mask is None:
         self._mask = np.ones(self._npix,dtype=np.float64)
         self._apomask = np.ones(self._npix,dtype=np.float64)
     else:
         assert isinstance(mask, np.ndarray)
         assert (len(mask) == self._npix)
         self._mask = mask.copy()
         self._apomask = nmt.mask_apodization(self._mask, self._aposcale, apotype='C2')
Exemplo n.º 10
0
 def __init__(self, cat, nside, theta_apo):
     """ Initializes Mask object from catalog and resolution parameters
     
     Parameters
     ----------
     cat : fc.Catalog
         Catalog containing window information
     nside : int
         HEALPix resolution index
     theta_apo : float
         Apodization scale in degrees
     """
     if cat.window.typestr == 'decbcut':
         npix = hp.nside2npix(nside)
         ind_aux = np.arange(0, npix)
         theta, phi = hp.pix2ang(nside, ind_aux)
         self.weights = cat.window(phi * 180 / np.pi,
                                   90 - theta * 180 / np.pi)
     else:
         self.weights = cat.window.map.copy()
     if debug:
         hp.mollview(self.weights)
         plt.show()
     #Figure out which pixels are empty
     self.ip_nomask = np.where(self.weights > 0)[0]
     #Generate sky mask and apply apodization
     self.binary = np.zeros_like(self.weights)
     self.binary[self.ip_nomask] = 1.
     if theta_apo > 0:
         self.mask_apo = nmt.mask_apodization(self.binary,
                                              theta_apo,
                                              apotype='C1')
     else:
         self.mask_apo = self.binary.copy()
     #Final weights are a combination of mask + depth fluctuations
     self.total = self.mask_apo * self.weights
     #Can't generate maps with pixels larger than the mask
     if cat.window.typestr != 'decbcut':
         if nside < cat.window.nside:
             #If mask pixelization is higher, upgrade output maps
             self.nside = cat.window.nside
         else:
             #If mask pixelization is lower, upgrade mask
             self.nside = nside
             self.total = hp.ud_grade(self.total, nside_out=nside)
             self.binary = hp.ud_grade(self.binary, nside_out=nside)
             self.weights = hp.ud_grade(self.weights, nside_out=nside)
             self.ip_nomask = np.where(self.weights > 0)[0]
     else:
         self.nside = nside
         self.total = hp.ud_grade(self.total, nside_out=nside)
         self.binary = hp.ud_grade(self.binary, nside_out=nside)
         self.weights = hp.ud_grade(self.weights, nside_out=nside)
         self.ip_nomask = np.where(self.weights > 0)[0]
     if debug:
         hp.mollview(self.weights)
         plt.show()
Exemplo n.º 11
0
 def calculate_apodizations(self, mask_in):
     for value in self.masks['powerspectrum'].values():
         apo_mask = nmt.mask_apodization(mask_in,
                                         **value['nmt_apo']['args'])
         with h5py.File(self.hdf5_path, 'a') as f:
             dset = f.require_dataset(value['record'],
                                      shape=apo_mask.shape,
                                      dtype=apo_mask.dtype)
             dset[...] = apo_mask
Exemplo n.º 12
0
 def get_apodized_mask(self):
     """
     Make an apodized mask. The pure-B formalism requires the mask to be
     differentiable along the edges. The 'C1' and 'C2' apodization types
     supported by mask_apodization achieve this.
     """
     mask_apo = nmt.mask_apodization(self.weight_mask,
                                     aposize=self.aposize,
                                     apotype=self.apotype)
     return mask_apo
Exemplo n.º 13
0
 def mask(self, mask):
     if mask is None:
         self._mask = np.ones(self._npix,dtype=np.float64)
     else:
         assert isinstance(mask, np.ndarray)
         assert (len(mask) == self._npix)
         self._mask = mask.copy()
         self._mask = nmt.mask_apodization(self._mask, self._aposcale, apotype='C2')
         self._qml_mask=degrade_mask(self._qml_nside, self._mask)
         self._fsky=np.mean(self._qml_mask)
         self._qml_npix = sum(self._qml_mask)
Exemplo n.º 14
0
 def mask(self, mask):
     if mask is None:
         self._mask = np.ones(hp.nsdie2pix(self._qml_nside), dtype=np.bool)
     else:
         assert isinstance(mask, np.ndarray)
         self._mask = mask.copy()
         self._mask = nmt.mask_apodization(self._mask,
                                           self._aposcale,
                                           apotype='C2')
         self._qml_mask = degrade_mask(self._qml_nside, self._mask)
         self._fsky = np.mean(self._qml_mask)
         self._qml_npix = sum(self._qml_mask)
Exemplo n.º 15
0
 def test_mask_errors(self):
     with self.assertRaises(RuntimeError):  # Badly shaped input
         nmt.mask_apodization(self.msk[:13], self.aposize, apotype="C1")
     with self.assertRaises(RuntimeError):  # Negative apodization
         nmt.mask_apodization(self.msk, -self.aposize, apotype="C1")
     with self.assertRaises(RuntimeError):  # Wrong apodization type
         nmt.mask_apodization(self.msk, self.aposize, apotype="C3")
Exemplo n.º 16
0
def test_mask_c2():
    msk_apo = nmt.mask_apodization(MT.msk, MT.aposize, apotype="C2")
    # Below transition
    assert (msk_apo[MT.th > MT.th0] < 1E-10).all()
    # Above transition
    assert (np.fabs(msk_apo[MT.th < MT.th0 - np.radians(MT.aposize)] - 1.) <
            1E-10).all()
    # Within transition
    x = np.sqrt((1 - np.cos(MT.th - MT.th0)) * MT.inv_x2thr)
    f = 0.5 * (1 - np.cos(x * np.pi))
    ind_transition = ((MT.th < MT.th0) &
                      (MT.th > MT.th0 - np.radians(MT.aposize)))
    assert (np.fabs(msk_apo[ind_transition] - f[ind_transition]) < 2E-2).all()
Exemplo n.º 17
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]
Exemplo n.º 18
0
 def get_apodized_mask(self):
     """
     Make an apodized mask. The pure-B formalism requires the mask to be
     differentiable along the edges. The 'C1' and 'C2' apodization types
     supported by mask_apodization achieve this.
     """
     resol = np.degrees(hp.nside2resol(hp.npix2nside(len(self.weight_mask))))
     if resol < self.aposize:
         mask_apo = nmt.mask_apodization(self.weight_mask,
                                         aposize=self.aposize,
                                         apotype=self.apotype)
     else:
         mask_apo = self.weight_mask.copy()
     return mask_apo
Exemplo n.º 19
0
 def test_mask_c2(self):
     msk_apo = nmt.mask_apodization(self.msk, self.aposize, apotype="C2")
     # Below transition
     self.assertTrue((msk_apo[self.th > self.th0] < 1E-10).all())
     # Above transition
     self.assertTrue(
         (np.fabs(msk_apo[self.th < self.th0 - np.radians(self.aposize)] -
                  1.) < 1E-10).all())
     # Within transition
     x = np.sqrt((1 - np.cos(self.th - self.th0)) * self.inv_x2thr)
     f = 0.5 * (1 - np.cos(x * np.pi))
     ind_transition = ((self.th < self.th0) &
                       (self.th > self.th0 - np.radians(self.aposize)))
     self.assertTrue((np.fabs(msk_apo[ind_transition] - f[ind_transition]) <
                      2E-2).all())
Exemplo n.º 20
0
    def __init__(self, mask_in, nside, bin_w, lmax, beam = None):
        
        '''
        Define the **apodized mask**, **beam weights**, **nside**, **bin-scheme**, **ell**
        
        Needs to be revised for the beam correction
        '''
        self.mask = nmt.mask_apodization(mask_in, 6, apotype='C2')
        
        self.nside = nside; self.lmax = lmax
        
#         self.beam = hp.gauss_beam(beam/60/180*np.pi, lmax = 3*self.nside); 
        
        self.b = nmt.NmtBin(self.nside, nlb=bin_w, lmax=self.lmax, is_Dell = True)
        
        self.ell_n = self.b.get_effective_ells(); self.lbin = len(self.ell_n)
Exemplo n.º 21
0
 def cross_t(self, maps, mask=None, aposcale=None, binning=None):
     """
     Cross PS,
     apply NaMaster estimator to T (scalar) map with(out) masks,
     requires NaMaster, healpy, numpy packages.
     
     Parameters
     ----------
     
     maps : numpy.ndarray
         A two-row array array of two T maps.
         
     mask : numpy.ndarray
         mask map
         
     Returns
     -------
     
     pseudo-PS results : tuple of numpy.ndarray
         (ell, TT)
     """
     assert isinstance(maps, np.ndarray)
     assert (maps.shape[0] == 2)
     # 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]
     _mapI02 = maps[1]
     # assemble NaMaster fields
     _f01 = nmt.NmtField(_apd_mask, [_mapI01])
     _f02 = nmt.NmtField(_apd_mask, [_mapI02])
     # 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
     return _b.get_effective_ells(), _cl00[0]
Exemplo n.º 22
0
 def auto_eb(self, maps, mask=None, aposcale=None, binning=None):
     """
     Auto PS,
     apply NaMaster estimator to QU (spin-2) maps with(out) masks,
     requires NaMaster, healpy, numpy packages.
     
     Parameters
     ----------
     
     maps : numpy.ndarray
         A two-row array of Q, U maps,
         with polarization in CMB convention.
         
     mask : numpy.ndarray
         mask map
         
     Returns
     -------
     
     pseudo-PS results : tuple of numpy.ndarray
         (ell, EE, BB)
     """
     assert isinstance(maps, np.ndarray)
     assert (maps.shape[0] == 2)
     # 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')
     _mapQ = maps[0]
     _mapU = maps[1]
     # assemble NaMaster fields
     _f2 = nmt.NmtField(_apd_mask, [_mapQ, _mapU])
     # 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
     _cl22 = nmt.compute_full_master(_f2, _f2, _b)  # tensor - tensor
     return _b.get_effective_ells(), _cl22[0], _cl22[3]
Exemplo n.º 23
0
    def __init__(self, mask_in, nside, bin_w, lmax, beam = None, wsp = True):
        
        '''
        class for Band-Power-Estimation;
        
        Define the **apodized mask**, **beam weights**, **nside**, **bin-scheme**, **ell**
        
        Needs to be revised for the beam correction. Different frequency have different sigma,
        which may lead to different wsp...
        '''
        self.mask = nmt.mask_apodization(mask_in, 6, apotype='C2')
        
        self.nside = nside; self.lmax = lmax
        
#         self.beam = hp.gauss_beam(beam/60/180*np.pi, lmax = 3*self.nside); 
        
        self.b = nmt.NmtBin(self.nside, nlb=bin_w, lmax=self.lmax, is_Dell = True)
        
        self.ell_n = self.b.get_effective_ells(); self.lbin = len(self.ell_n)
        
        
        # - 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))
            m0 = nmt.NmtField(self.mask,[qu[0]],purify_e=False, purify_b=True)
            m2 = nmt.NmtField(self.mask, qu, purify_e=False, purify_b=True)#, beam=bl)

            # 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
            
            _w02 = nmt.NmtWorkspace()
            _w02.compute_coupling_matrix(m0, m2, self.b)  ## spin-0 with spin-2
            
            _w22 = nmt.NmtWorkspace()
            _w22.compute_coupling_matrix(m2, m2, self.b)  ## spin-2 with spin-2
            
            self.w00 = _w00
            self.w02 = _w02
            self.w22 = _w22
Exemplo n.º 24
0
def estimate_bandpowers(hmap,
                        maskval=hp.UNSEEN,
                        nest=True,
                        nside=2048,
                        apodize=True,
                        aposcale=0.1,
                        nbins=32,
                        work=None,
                        cache_maps=False,
                        key=None):
    bins = nmt.NmtBin.from_nside_linear(nside, nbins)
    # First, check whether map is NEST or RING. If NEST, re-order.
    if nest:
        print(
            "Converting power spectrum from NEST to RING for pseudo-C_\ell estimation."
        )
        hmap = hp.pixelfunc.reorder(hmap, inp='NEST', out='RING')

    mask = np.ones_like(hmap)
    mask[hmap == maskval] = 0
    # Apodize mask??
    if apodize:
        mask = nmt.mask_apodization(mask, aposcale)

    # Convert to a fluctuation field.
    hmap[mask > 0] = hmap[mask > 0] / np.average(hmap[mask > 0],
                                                 weights=mask[mask > 0]) - 1.
    if cache_maps:
        fitsio.write(f'map-{key}.fits', hmap_ngal, clobber=True)
        fitsio.write(f'map-{key}.fits', mask, clobber=False)

    field = nmt.NmtField(mask, hmap[np.newaxis, :])
    if work == None:
        w = nmt.NmtWorkspace()
        w.compute_coupling_matrix(field, field, bins)
    else:
        w = work

    cl = nmt.compute_full_master(field, field, bins, workspace=w)
    l_eff = bins.get_effective_ells()
    return l_eff, cl, w
Exemplo n.º 25
0
def get_cmb_lensing_map(nside=None):
    folder_path = os.path.join(DATA_PATH, 'Planck2018/COM_Lensing_2048_R2.00')
    map_path = os.path.join(folder_path, 'dat_klm.fits')
    mask_path = os.path.join(folder_path, 'mask.fits')

    # Read
    klm = hp.read_alm(map_path)
    map = hp.alm2map(klm, nside)
    mask = hp.read_map(mask_path)

    # Rotate
    rotator = Rotator(coord=['G', 'C'])
    map = rotator.rotate_map_pixel(map)
    mask = rotator.rotate_map_pixel(mask)

    # Adjust
    mask = nmt.mask_apodization(mask, 0.2, apotype='C1')
    mask = hp.ud_grade(mask, nside_out=nside)
    mask[mask < 0.1] = 0  # Visualization purpose

    map = get_masked_map(map, mask)
    mask = get_masked_map(mask, mask)
    return map, mask
Exemplo n.º 26
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
Exemplo n.º 27
0
    mpd1=hp.alm2map(hp.almxfl(hp.map2alm(mp),alpha1i),nside=ns,verbose=False)
    mpd2=hp.alm2map(hp.almxfl(hp.map2alm(mp),alpha2i),nside=ns,verbose=False)
    return mpd1,mpd2
                            
ZER0=1E-3
APOSCALE=10.
nside=1024
nh=hp.ud_grade(hp.read_map("norm_nHits_SA_35FOV.fits"),nside_out=nside)
nhg=hp.smoothing(nh,fwhm=np.pi/180,verbose=False)
nhg[nhg<0]=0
nh/=np.amax(nh)
nhg/=np.amax(nhg)
mpb=np.zeros_like(nh); mpb[nh>ZER0]=1
mpbg=np.zeros_like(nhg); mpbg[nhg>ZER0]=1
print("Apodize 1")
msk=nmt.mask_apodization(mpb,APOSCALE,apotype='C1')
print("Apodize 2")
mskg=nmt.mask_apodization(mpbg,APOSCALE,apotype='C1')
print("Deriv")
mskd1,mskd2=get_deriv(nh*msk)
mskd1g,mskd2g=get_deriv(nhg*mskg)
hp.write_map("mask_apo%.1lf.fits"%APOSCALE,mskg*nhg)

hp.write_map("masks_SAT.fits",(mskg*nhg)[None,:]*np.ones(6)[:,None],overwrite=True)

hp.mollview(msk)
hp.mollview(mskd1)
hp.mollview(mskd2)
hp.mollview(mskg)
hp.mollview(mskd1g)
hp.mollview(mskd2g)
# Define the **apodized mask**, **beam weights**, **nside**, **bin-scheme**, **ell**

beam_low = 27.9435
nside = 512
lmax = 1000

b = nmt.NmtBin(nside, nlb=10, lmax=lmax)
ell_n = b.get_effective_ells()
eln2 = utils.l2(ell_n)

bl = hp.gauss_beam(beam_low / 60 / 180 * np.pi, lmax=3 * nside)

ali_ma_512 = hp.read_map("/smc/jianyao/Ali_maps/ali_mask_wo_edge_512.fits",
                         verbose=False)
mask = nmt.mask_apodization(ali_ma_512, 6, apotype='C2')


def compute_master(f_a, f_b, wsp):
    cl_coupled = nmt.compute_coupled_cell(f_a, f_b)
    cl_decoupled = wsp.decouple_cell(cl_coupled)
    return cl_decoupled


# - 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 * nside**2))
m0 = nmt.NmtField(mask, map0, purify_e=False, purify_b=True, beam=bl)
Exemplo n.º 29
0

# compute apodization mask
lmin = 20
lmax = 3 * nside - 1
delta_ell = 20
racenter = 0.0
deccenter = -57.0
maxang = 20.

center = equ2gal(racenter, deccenter)
veccenter = hp.ang2vec(pi / 2 - np.radians(center[1]), np.radians(center[0]))
vecpix = hp.pix2vec(nside, np.arange(12 * nside ** 2))
cosang = np.dot(veccenter, vecpix)
maskok = np.degrees(np.arccos(cosang)) < maxang
msk_apo = nmt.mask_apodization(maskok, 1, apotype='C1')

# Select a binning scheme
b = nmt.NmtBin(nside, nlb=20, is_Dell=True)
leff = b.get_effective_ells()
# gaussian beam
beam = hp.gauss_beam(np.radians(0.39), lmax)

# initial maps and workspaces
mp_t, mp_q, mp_u = hp.synfast(spectra,
                              nside=nside,
                              fwhm=np.radians(0.39),
                              pixwin=True,
                              new=True,
                              verbose=False)
Exemplo n.º 30
0
#We'll run this many simulations
nsim=10
#HEALPix map resolution
nside=256

#Let us first create a square mask:
msk=np.zeros(hp.nside2npix(nside))
th,ph=hp.pix2ang(nside,np.arange(hp.nside2npix(nside)))
ph[np.where(ph>np.pi)[0]]-=2*np.pi
msk[np.where((th<2.63) & (th>1.86) & (ph>-np.pi/4) & (ph<np.pi/4))[0]]=1.

#Now we apodize the mask. The pure-B formalism requires the mask to be differentiable
#along the edges. The 'C1' and 'C2' apodization types supported by mask_apodization
#achieve this.
msk_apo=nmt.mask_apodization(msk,10.0,apotype='C1')

#Select a binning scheme
b=nmt.NmtBin(nside,nlb=16)
leff=b.get_effective_ells()

#Read power spectrum and provide function to generate simulated skies
l,cltt,clee,clbb,clte=np.loadtxt('cls.txt',unpack=True);
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
Exemplo n.º 31
0
N_side = 2048
Npix = 12 * N_side**2
Coords = 'G'  #coordinate system
mask_dir = '/data/jch/RHT_QU/'
mask_name = 'allsky_GALFA_mask_nonzero_nchannels_edge200_hp_proj_plusbgt70_maskGal'
# apodization scale
apod_Arcmin = 60.
apod_Deg = apod_Arcmin / 60.
# mask file name
mask_file = mask_dir + mask_name + FITS_end
# read in mask and apodize
# to use the pure-B formalism, need the mask to be differentiable at the boundary; the "C1" and "C2" schemes in nmt satisfy this criterion
mask = hp.read_map(mask_file, verbose=False)
apod_Type = 'C2'
#print "apodizing mask"
mask_apod = nmt.mask_apodization(mask, apod_Deg, apotype=apod_Type)
#print "done apodizing"
#####

#####
# simulation directory, maps, and theory power spectra
sim_dir = '/data/jch/Planckdata/DustSims/'
sim_name = 'DustSim_BICEPamp_alpha-2.42_TQU_'  #'+str(i)+'.fits'
Nsim = 10  #actually have 100
sim_theory = 'DustEEBB_BICEPamp_alpha-2.42'
EEDust = (np.loadtxt(sim_dir + sim_theory +
                     TXT_end))[:, 0]  #ClEE -- extends to ell=4000
BBDust = (np.loadtxt(sim_dir + sim_theory +
                     TXT_end))[:, 1]  #ClBB -- extends to ell=4000
ellmax = 1001
ell = np.arange(int(ellmax) + 1)