def test_toeplitz_22(): l_toeplitz = WT.nside l_exact = WT.nside // 2 dl_band = WT.nside // 4 we = nmt.NmtWorkspace() we.compute_coupling_matrix(WT.f2, WT.f2, WT.b) ce = we.get_coupling_matrix().reshape([3*WT.nside, 4, 3*WT.nside, 4]) ce_pp = ce[:, 0, :, 0] ce_mm = ce[:, 0, :, 3] wt = nmt.NmtWorkspace() wt.compute_coupling_matrix(WT.f2, WT.f2, WT.b, l_toeplitz=l_toeplitz, l_exact=l_exact, dl_band=dl_band) ct = wt.get_coupling_matrix().reshape([3*WT.nside, 4, 3*WT.nside, 4]) ct_pp = ct[:, 0, :, 0] ct_mm = ct[:, 0, :, 3] # Check that the approximate matrix is constructed # as expected. compare_toeplitz(ce_pp, ct_pp, l_toeplitz, l_exact, dl_band) compare_toeplitz(ce_mm, ct_mm, l_toeplitz, l_exact, dl_band) # Check that it's not a bad approximation (0.5% for these ells) cle = we.decouple_cell(nmt.compute_coupled_cell(WT.f2, WT.f2)) clt = wt.decouple_cell(nmt.compute_coupled_cell(WT.f2, WT.f2)) assert np.all(np.fabs(clt[0]/cle[0]-1) < 5E-3)
def test_toeplitz_02(self): l_toeplitz = self.nside l_exact = self.nside // 2 dl_band = self.nside // 4 we = nmt.NmtWorkspace() we.compute_coupling_matrix(self.f0, self.f2, self.b) ce = we.get_coupling_matrix().reshape([3*self.nside, 2, 3*self.nside, 2]) ce = ce[:, 0, :, 0] wt = nmt.NmtWorkspace() wt.compute_coupling_matrix(self.f0, self.f2, self.b, l_toeplitz=l_toeplitz, l_exact=l_exact, dl_band=dl_band) ct = wt.get_coupling_matrix().reshape([3*self.nside, 2, 3*self.nside, 2]) ct = ct[:, 0, :, 0] # Check that the approximate matrix is constructed # as expected. self.compare_toeplitz(ce, ct, l_toeplitz, l_exact, dl_band) # Check that it's not a bad approximation (0.5% for these ells) cle = we.decouple_cell(nmt.compute_coupled_cell(self.f0, self.f2)) clt = wt.decouple_cell(nmt.compute_coupled_cell(self.f0, self.f2)) self.assertTrue(np.all(np.fabs(clt[0]/cle[0]-1) < 5E-3))
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)
def get_cls_covar_coupled(self): if self.cls_cov is None: self.signal_map = self.get_signal_map() self.hm1_map, self.hm2_map = self._get_hm_maps() coadd_f = self._get_nmt_field(signal=self.signal_map) hm1_f = self._get_nmt_field(signal=self.hm1_map) hm2_f = self._get_nmt_field(signal=self.hm2_map) cl_cc = nmt.compute_coupled_cell(coadd_f, coadd_f) cl_11 = nmt.compute_coupled_cell(hm1_f, hm1_f) cl_12 = nmt.compute_coupled_cell(hm1_f, hm2_f) cl_22 = nmt.compute_coupled_cell(hm2_f, hm2_f) self.cls_cov = {'cross': cl_cc, 'auto_11': cl_11, 'auto_12': cl_12, 'auto_22': cl_22} return self.cls_cov
def compute_cells_from_splits(self, splits_list): # Generate fields print(" Generating fields") fields = {} for b in range(self.n_bpss): for s in range(self.nsplits): name = self.get_map_label(b, s) print(" " + name) fname = splits_list[s] if not os.path.isfile(fname): # See if it's gzipped fname = fname + '.gz' if not os.path.isfile(fname): raise ValueError("Can't find file ", splits_list[s]) mp_q, mp_u = hp.read_map(fname, field=[2 * b, 2 * b + 1], verbose=False) fields[name] = self.get_field(b, [mp_q, mp_u]) # Iterate over field pairs print(" Computing cross-spectra") cells = {} for b1, b2, s1, s2, l1, l2 in self.get_cell_iterator(): wsp = self.workspaces[self.get_workspace_label(b1, b2)] # Create sub-dictionary if it doesn't exist if cells.get(l1) is None: cells[l1] = {} f1 = fields[l1] f2 = fields[l2] # Compute power spectrum print(" " + l1 + " " + l2) cells[l1][l2] = wsp.decouple_cell(nmt.compute_coupled_cell(f1, f2)) return cells
def test_get_nmt_field(): import pymaster as nmt m = get_mapper() f = m.get_nmt_field() cl = nmt.compute_coupled_cell(f, f)[0] assert np.fabs(cl[0] - 4 * np.pi) < 1E-3 assert np.all(np.fabs(cl[1:]) < 1E-5)
def get_cl(self, typ): if self.cls[typ] is None: fname = self.get_clfile_name(typ, 'cl', 'npz') if not os.path.isfile(fname): if 'g' in typ: self.get_delta_field() if 'k' in typ: self.get_kappa_field() fl = {'g': self.f_d, 'k': self.f_k} t1, t2 = typ wsp = self.get_workspace(typ) cl = wsp.decouple_cell(nmt.compute_coupled_cell( fl[t1], fl[t2])) leff = self.bpw.get_effective_ells() nlc = self.get_nl_coupled(typ) nl = wsp.decouple_cell(nlc) self.cls[typ] = { 'ls': leff, 'cl': cl, 'nl': nl, 'nlc': nlc, 'win': wsp.get_bandpower_windows() } np.savez(fname, **(self.cls[typ])) else: d = np.load(fname) self.cls[typ] = { k: d[k] for k in ['ls', 'cl', 'nl', 'nlc', 'win'] } return self.cls[typ]
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())
def _get_nl_coupled(self): if self.nside < self.nside_nl_threshold: print('calculing nl from weights') cat_data = self.get_catalog(mod='data') cat_random = self.get_catalog(mod='random') w_data = self._get_w(mod='data') w_random = self._get_w(mod='random') alpha = self._get_alpha() pixel_A = 4*np.pi/hp.nside2npix(self.nside) mask = self.get_mask() w2_data = get_map_from_points(cat_data, self.nside, w=w_data**2, rot=self.rot) w2_random = get_map_from_points(cat_random, self.nside, w=w_random**2, rot=self.rot) goodpix = mask > 0 N_ell = (w2_data[goodpix].sum() + alpha**2*w2_random[goodpix].sum()) N_ell *= pixel_A**2/(4*np.pi) nl_coupled = N_ell * np.ones((1, 3*self.nside)) else: print('calculating nl from mean cl values') f = self.get_nmt_field() cl = nmt.compute_coupled_cell(f, f)[0] N_ell = np.mean(cl[self.lmin_nl_from_data:2*self.nside]) nl_coupled = N_ell * np.ones((1, 3*self.nside)) return {'nls': nl_coupled}
def est_cl(w, fld1, fld2, b, me='step', ccl=None): '''Estimate Cl.''' if me == 'full': print('>> Computing full master...') cl = nmt.compute_full_master(fld1, fld2, b, workspace=w) cl_decoupled = cl[0] elif me == 'step': if ccl is None: # compute the coupled full-sky angular power spectra # this is equivalent to Healpy.anafast on masked maps print('>> Computing coupled Cl...') cl_coupled = nmt.compute_coupled_cell(fld1, fld2) else: cl_coupled = [ccl] # decouple into bandpowers by inverting the binned coupling matrix print('>> Decoupling Cl...') cl_decoupled = w.decouple_cell(cl_coupled)[0] else: sys.exit('>> Wrong me.') # get the effective ells print('>> Getting effective ells...') ell = b.get_effective_ells() return ell, cl_decoupled
def get_cl_coupled(self): if self.cl_coupled is None: self.hm1_map, self.hm2_map = self._get_hm_maps() hm1_f = self._get_nmt_field(signal=self.hm1_map) hm2_f = self._get_nmt_field(signal=self.hm2_map) self.cl_coupled = nmt.compute_coupled_cell(hm1_f, hm2_f) return self.cl_coupled
def get_cl_file(self): if self.read_symm: tr1 = self.tr2 tr2 = self.tr1 else: tr1 = self.tr1 tr2 = self.tr2 fname = os.path.join(self.outdir, 'cl_{}_{}.npz'.format(tr1, tr2)) ell = self.b.get_effective_ells() if not os.path.isfile(fname): f1, f2 = self.get_fields() w = self.get_workspace() cl = w.decouple_cell(nmt.compute_coupled_cell(f1.f, f2.f)) nl_cp = self.compute_coupled_noise() if (tr1 == tr2) and (self.data['tracers'][tr1]['type'] == 'cv'): tracer = self.data['tracers'][tr1] ell_nl, nl = np.loadtxt(tracer['nl'], unpack=True, usecols=tracer['nl_cols']) nl = interp1d(ell_nl, nl, bounds_error=False, fill_value=(nl[0], nl[-1]))(ell) nl = np.array([nl]) else: nl = w.decouple_cell(nl_cp) np.savez(fname, ell=ell, cl=cl - nl, nl=nl, nl_cp=nl_cp) cl_file = np.load(fname) cl = cl_file['cl'] if np.any(ell != cl_file['ell']): raise ValueError( 'The file {} does not have the expected bpw. Aborting!'.format( fname)) return cl_file
def compute_pseudo_and_decouple(field1, field2, wsp): """ Function to calculate pseudospectrum using namaster and decouple using a provided mode coupling matrix. """ cls_coupled = nmt.compute_coupled_cell(field1, field2) cls = wsp.decouple_cell(cls_coupled) return cls
def test_lite_errors(): f0 = nmt.NmtField(WT.msk, [WT.mps[0]], n_iter=0) fl = nmt.NmtField(WT.msk, [WT.mps[0]], templates=[[WT.tmp[0]]], n_iter=0, lite=True) with pytest.raises(ValueError): # Needs spin fe = nmt.NmtField(WT.msk, None) fe = nmt.NmtField(WT.msk, None, spin=0) for f in [fl, fe]: with pytest.raises(RuntimeError): # No deprojection bias nmt.deprojection_bias(f0, f, np.zeros([1, 3*WT.nside])) with pytest.raises(RuntimeError): # No deprojection bias nmt.uncorr_noise_deprojection_bias(fl, WT.mps[0]) with pytest.raises(RuntimeError): # No C_l without maps nmt.compute_coupled_cell(f0, fe)
def get_nl(self, fields, use_analytic=False): if fields[self.tracers[0]].name != fields[self.tracers[1]].name: return np.zeros(self.shape) f = fields[self.tracers[0]] w = self.get_workspace(fields) if f.type == 'gc': nl = w.decouple_cell(f.get_nl_coupled()) elif f.type == 'sh': if use_analytic: nl = w.decouple_cell(f.get_nl_coupled()) else: cls = [] for irot in range(f.config_h['nrot']): print(" - %d-th/%d rotation" % (irot, f.config_h['nrot'])) try: f_nmt = f.get_field(irot) cl = w.decouple_cell( nmt.compute_coupled_cell(f_nmt, f_nmt)) cls.append(cl) except: print("File not found. Oh well...") cls = np.array(cls) nl = np.mean(cls, axis=0) return nl
def cross_eb(self, maps, wsp=None, fwhms=[None,None]): """ Cross PS, apply NaMaster estimator to QU (spin-2) maps with(out) masks. Parameters ---------- maps : numpy.ndarray A four-row array of Q, U maps, arranged as {Q1, U1, Q2, U2}, with polarization in CMB convention. wsp : (PS-estimator-defined) workspace A template of mask-induced mode coupling matrix. fwhms : list, tuple FWHM of gaussian beams Returns ------- pseudo-PS results : tuple of numpy.ndarray (ell, EE, BB, wsp(if input wsp is None)) """ assert isinstance(maps, np.ndarray) assert (maps.shape == (4,self._npix)) assert (len(fwhms) == 2) # assemble NaMaster fields if fwhms[0] is None: _f21 = nmt.NmtField(self._mask[0], [maps[0], maps[1]], purify_e=False, purify_b=True) else: _f21 = nmt.NmtField(self._mask[0], [maps[0], maps[1]], purify_e=False, purify_b=True, beam=hp.gauss_beam(fwhms[0], 3*self._nside-1)) if fwhms[1] is None: _f22 = nmt.NmtField(self._mask[0], [maps[2], maps[3]], purify_e=False, purify_b=True) else: _f22 = nmt.NmtField(self._mask[0], [maps[2], maps[3]], purify_e=False, purify_b=True, beam=hp.gauss_beam(fwhms[1], 3*self._nside-1)) # estimate PS if wsp is None: _w = nmt.NmtWorkspace() _w.compute_coupling_matrix(_f21, _f22, self._b) _cl22c = nmt.compute_coupled_cell(_f21, _f22) _cl22 = _w.decouple_cell(_cl22c) return (self._modes, _cl22[0], _cl22[3], _cl22[1], _w) else: _cl22c = nmt.compute_coupled_cell(_f21, _f22) _cl22 = wsp.decouple_cell(_cl22c) return (self._modes, _cl22[0], _cl22[3], _cl22[1])
def cross_t(self, maps, wsp=None, fwhms=[None,None]): """ Cross PS, apply NaMaster estimator to T (scalar) map with(out) masks. Parameters ---------- maps : numpy.ndarray A two-row array array of two T maps. wsp : (PS-estimator-defined) workspace A template of mask-induced mode coupling matrix. fwhms : list, tuple FWHM of gaussian beams Returns ------- pseudo-PS results : tuple of numpy.ndarray (ell, TT, wsp(if input wsp is None)) """ assert isinstance(maps, np.ndarray) assert (maps.shape == (2,self._npix)) assert (len(fwhms) == 2) # assemble NaMaster fields if fwhms[0] is None: _f01 = nmt.NmtField(self._mask[0], [maps[0]]) else: _f01 = nmt.NmtField(self._mask[0], [maps[0]], beam=hp.gauss_beam(fwhms[0], 3*self._nside-1)) if fwhms[1] is None: _f02 = nmt.NmtField(self._mask[0], [maps[1]]) else: _f02 = nmt.NmtField(self._mask[0], [maps[1]], beam=hp.gauss_beam(fwhms[1], 3*self._nside-1)) # estimate PS if wsp is None: _w = nmt.NmtWorkspace() _w.compute_coupling_matrix(_f01, _f02, self._b) _cl00c = nmt.compute_coupled_cell(_f01, _f02) _cl00 = _w.decouple_cell(_cl00c) return (self._modes, _cl00[0], _w) else: _cl00c = nmt.compute_coupled_cell(_f01, _f02) _cl00 = wsp.decouple_cell(_cl00c) return (self._modes, _cl00[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)
def compute_master(f_a, f_b, wsp, clb): #Compute the power spectrum (a la anafast) of the masked fields #Note that we only use n_iter=0 here to speed up the computation, #but the default value of 3 is recommended in general. cl_coupled = nmt.compute_coupled_cell(f_a, f_b) #Decouple power spectrum into bandpowers inverting the coupling matrix cl_decoupled = wsp.decouple_cell(cl_coupled, cl_bias=clb) return cl_decoupled
def des_sh_nls_rot_gal(des_mask_gwl, des_opm_mean, des_data_folder_gwl, output_folder, b, nbins=4, galaxy_treatment='metacal'): des_wl_noise_file = os.path.join( output_folder, "des_sh_{}_rot0-10_noise_ns4096.npz".format(galaxy_treatment)) if os.path.isfile(des_wl_noise_file): N_wl = np.load(des_wl_noise_file)['cls'] return N_wl N_wl = [] for ibin in range(nbins): rotated_cls = [] ws = nmt.NmtWorkspace() fname = os.path.join(output_folder, 'w22_{}{}.dat'.format(1 + ibin, 1 + ibin)) ws.read_from(fname) for irot in range(10): map_file_e1 = os.path.join( des_data_folder_gwl, 'map_{}_bin{}_rot{}_counts_e1_ns4096.fits'.format( galaxy_treatment, ibin, irot)) map_file_e2 = os.path.join( des_data_folder_gwl, 'map_{}_bin{}_rot{}_counts_e2_ns4096.fits'.format( galaxy_treatment, ibin, irot)) map_we1 = hp.read_map(map_file_e1) map_we2 = hp.read_map(map_file_e2) map_e1 = (map_we1 / des_mask_gwl[ibin] - (map_we1.sum() / des_mask_gwl[ibin].sum())) / des_opm_mean[ibin] map_e2 = (map_we2 / des_mask_gwl[ibin] - (map_we2.sum() / des_mask_gwl[ibin].sum())) / des_opm_mean[ibin] map_e1[np.isnan(map_e1)] = 0. map_e2[np.isnan(map_e2)] = 0. sq = map_e1 su = -map_e2 f = nmt.NmtField(des_mask_gwl[ibin], [sq, su]) cls = ws.decouple_cell(nmt.compute_coupled_cell(f, f)).reshape( (2, 2, -1)) rotated_cls.append(cls) N_wl.append(np.mean(rotated_cls, axis=0)) np.savez(des_wl_noise_file, l=b.get_effective_ells(), cls=N_wl) return N_wl
def auto_t(self, maps, wsp=None, fwhms=None): """ Auto PS, apply NaMaster estimator to T (scalar) map with(out) masks. Parameters ---------- maps : numpy.ndarray A single-row array of single T map. wsp : (PS-estimator-defined) workspace A template of mask-induced mode coupling matrix. fwhms : float FWHM of gaussian beams Returns ------- pseudo-PS results : tuple of numpy.ndarray (ell, TT, wsp(if input wsp is None)) """ assert isinstance(maps, np.ndarray) assert (maps.shape == (1,self._npix)) # assemble NaMaster fields if fwhms is None: _f0 = nmt.NmtField(self._mask[0], [maps[0]]) else: _f0 = nmt.NmtField(self._mask[0], [maps[0]], beam=hp.gauss_beam(fwhms, 3*self._nside-1)) # estimate PS if wsp is None: _w = nmt.NmtWorkspace() _w.compute_coupling_matrix(_f0, _f0, self._b) _cl00c = nmt.compute_coupled_cell(_f0, _f0) _cl00 = _w.decouple_cell(_cl00c) return (self._modes, _cl00[0], _w) else: _cl00c = nmt.compute_coupled_cell(_f0, _f0) _cl00 = wsp.decouple_cell(_cl00c) return (self._modes, _cl00[0])
def get_cls_sim(ws, fields): """ :param ws: workspaces for fields in fields. :param fields: tuple of tuple of fields to compute the mode-coupling matrix for. Shape is nbis x (f0, f2) """ dof = [1, 2] * len(fields) nfs = 3 * len(fields) fields = sum(fields, ()) # Flatten the tuple of tuples cl_ar = np.empty((nfs, nfs, b.get_n_bands())) index1 = 0 c = 0 for c1, dof1 in enumerate(dof): f1 = fields[c1] index2 = index1 for c2, dof2 in enumerate(dof[c1:], c1): f2 = fields[c2] cls = ws[c].decouple_cell(nmt.compute_coupled_cell(f1, f2)).reshape( (dof1, dof2, -1)) # from matplotlib import pyplot as plt # cls_true = (f['cls'] + f['nls'])[index1 : index1 + dof1, index2 : index2 + dof2].reshape(dof1 * dof2, -1) # print(cls_true.shape) # print(cls.reshape(dof1 * dof2, -1).shape) # for cli_true, cli in zip(cls_true, cls.reshape(dof1 * dof2, -1)): # print(cli) # plt.suptitle("{}, {}".format(dof1, dof2)) # plt.loglog(l, cli_true, b.get_effective_ells(), cli, 'o') # plt.show() # plt.close() cl_ar[index1:index1 + dof1, index2:index2 + dof2] = cls # from matplotlib import pyplot as plt # for cli_true, cli in zip(cls_true, # cl_ar[index1 : index1 + dof1, index2 : index2 + dof2].reshape(dof1 * dof2, -1)): # plt.suptitle("{}, {}".format(dof1, dof2)) # plt.loglog(l, cli_true, b.get_effective_ells(), cli, 'o') # plt.show() # plt.close() index2 += dof2 c += 1 index1 += dof1 return cl_ar[np.triu_indices(cl_ar.shape[0])]
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]))
def from_fields(Spectrum, field1, field2, bpws, wsp=None, save_windows=True): """ Creator from two fields. Args: field1, field2 (:obj:`Field`): fields to correlate. bpws (:obj:`Bandpowers`): bandpowers to use when computing the power spectrum. wsp (:obj:`NmtWorkspace`): object containing the mode-coupling matrix. If `None`, a new one will be computed. save_windows (bool): whether to compute bandpower window functions. """ leff = bpws.bn.get_effective_ells() # Compute MCM if needed if wsp is None: wsp = nmt.NmtWorkspace() wsp.compute_coupling_matrix(field1.field, field2.field, bpws.bn) # Compute data power spectrum cell = wsp.decouple_cell( nmt.compute_coupled_cell(field1.field, field2.field))[0] # Compute noise power spectrum if needed. # Only for auto-correlations of galaxy overdensity fields. if field1.is_ndens and field2.is_ndens and field1.name == field2.name: nl = wsp.couple_cell([np.ones(3 * field1.nside) / field1.ndens]) nell = wsp.decouple_cell(nl)[0] else: nell = np.zeros(len(leff)) # Compute bandpower windows nbpw = len(cell) lmax = 3 * field1.nside - 1 if save_windows: windows = np.zeros([nbpw, lmax + 1]) for il in range(lmax + 1): t_hat = np.zeros(lmax + 1) t_hat[il] = 1. windows[:, il] = wsp.decouple_cell(wsp.couple_cell([t_hat])) else: windows = None return Spectrum(field1.name, field2.name, leff, nell, cell, windows)
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]))
def test_toeplitz_00(): l_toeplitz = WT.nside l_exact = WT.nside // 2 dl_band = WT.nside // 4 we = nmt.NmtWorkspace() we.compute_coupling_matrix(WT.f0, WT.f0, WT.b) ce = we.get_coupling_matrix() wt = nmt.NmtWorkspace() wt.compute_coupling_matrix(WT.f0, WT.f0, WT.b, l_toeplitz=l_toeplitz, l_exact=l_exact, dl_band=dl_band) ct = wt.get_coupling_matrix() # Check that the approximate matrix is constructed # as expected. compare_toeplitz(ce, ct, l_toeplitz, l_exact, dl_band) # Check that it's not a bad approximation (0.5% for these ells) cle = we.decouple_cell(nmt.compute_coupled_cell(WT.f0, WT.f0)) clt = wt.decouple_cell(nmt.compute_coupled_cell(WT.f0, WT.f0)) assert np.all(np.fabs(clt[0]/cle[0]-1) < 5E-3)
def get_xsys(self, fields): if fields[self.tracers[0]].name != fields[self.tracers[1]].name: return {} xsys = {} f = fields[self.tracers[0]] if 'systematics' in f.config_h: fl1 = f.get_field() w = self.get_workspace(fields) for n, d in f.config_h['systematics'].items(): if d['xcorr']: fl2 = f.get_systematic_field(n) cl = w.decouple_cell(nmt.compute_coupled_cell(fl1, fl2)) xsys[n] = cl return xsys
def test_lite_pure(): f0 = nmt.NmtField(WT.msk, [WT.mps[0]]) f2l = nmt.NmtField(WT.msk, [WT.mps[1], WT.mps[2]], purify_b=True, lite=True) f2e = nmt.NmtField(WT.msk, None, purify_b=True, lite=True, spin=2) nlth = np.array([WT.nlte, 0*WT.nlte]) w = nmt.NmtWorkspace() w.compute_coupling_matrix(f0, f2e, WT.b) clb = nlth cl = w.decouple_cell(nmt.compute_coupled_cell(f0, f2l), cl_bias=clb) tl = np.loadtxt("test/benchmarks/bm_nc_yp_c02.txt", unpack=True)[1:, :] assert (np.fabs(cl-tl) <= np.fmin(np.fabs(cl), np.fabs(tl))*1E-5).all()
def compute_master(self, field_a, field_b, workspace): """ Parameters ---------- field_a: NmtField field_b: NmtField workspace: NmtWorkspace Contains the coupling matrix Returns ------- decoupled Cls. """ cl_coupled = nmt.compute_coupled_cell(field_a, field_b) cl_decoupled = workspace.decouple_cell(cl_coupled) return cl_decoupled
def _get_cl(iz, cat, msk, w, nside, ipgood, wgt=False): """ Returns auto-correlation Cls for the IZ ZBIN """ if wgt: nc = bincount(cat.loc[cat.ZBIN == iz, f'IP{nside}'], weights=cat.loc[cat.ZBIN == iz, 'WEIGHT'], minlength=len(msk)) else: nc = bincount(cat.loc[cat.ZBIN == iz, f'IP{nside}'], minlength=len(msk)) f = _gc_field(nc, msk, ipgood) cl = compute_coupled_cell(f, f) ndens = msk.mean() * 4.0 * pi / nc[ipgood].sum() print(iz, ndens) nl = msk.mean() * ndens nl = [full(w.wsp.lmax + 1, nl)] return w.decouple_cell(cl)[0], w.decouple_cell(nl)[0]
def compute_master(fa,fb,wsp,clb=None,cln=None) : cl_coupled=nmt.compute_coupled_cell(fa,fb) cl_decoupled=wsp.decouple_cell(cl_coupled,cl_bias=clb,cl_noise=cln) return cl_decoupled