def setUp(self): wcs, msk = read_flat_map("test/benchmarks/msk_flat.fits") (ny, nx) = msk.shape lx = np.radians(np.fabs(nx * wcs.wcs.cdelt[0])) ly = np.radians(np.fabs(ny * wcs.wcs.cdelt[1])) mps = np.array([ read_flat_map("test/benchmarks/mps_flat.fits", i_map=i)[1] for i in range(3) ]) d_ell = 20 lmax = 500. ledges = np.arange(int(lmax / d_ell) + 1) * d_ell + 2 self.b = nmt.NmtBinFlat(ledges[:-1], ledges[1:]) ledges_half = ledges[:len(ledges) // 2] self.b_half = nmt.NmtBinFlat(ledges_half[:-1], ledges_half[1:]) self.f0 = nmt.NmtFieldFlat(lx, ly, msk, [mps[0]]) self.f2 = nmt.NmtFieldFlat(lx, ly, msk, [mps[1], mps[2]]) self.f0_half = nmt.NmtFieldFlat(lx, ly, msk[:ny // 2, :nx // 2], [mps[0, :ny // 2, :nx // 2]]) self.w = nmt.NmtWorkspaceFlat() self.w.read_from("test/benchmarks/bm_f_nc_np_w00.fits") self.w02 = nmt.NmtWorkspaceFlat() self.w02.read_from("test/benchmarks/bm_f_nc_np_w02.fits") self.w22 = nmt.NmtWorkspaceFlat() self.w22.read_from("test/benchmarks/bm_f_nc_np_w22.fits") cls = np.loadtxt("test/benchmarks/cls_lss.txt", unpack=True) l, cltt, clee, clbb, clte, nltt, nlee, nlbb, nlte = cls self.ll = l self.cltt = cltt + nltt self.clee = clee + nlee self.clbb = clbb + nlbb self.clte = clte
def test_workspace_flat_full_master(self) : w=nmt.NmtWorkspaceFlat() w.compute_coupling_matrix(self.f0,self.f0,self.b) w_half=nmt.NmtWorkspaceFlat() w_half.compute_coupling_matrix(self.f0_half,self.f0_half,self.b_half) c=nmt.compute_full_master_flat(self.f0,self.f0,self.b) self.assertEqual(c.shape,(1,self.b.bin.n_bands)) with self.assertRaises(ValueError) : #Incompatible resolutions c=nmt.compute_full_master_flat(self.f0,self.f0_half,self.b) c=nmt.compute_full_master_flat(self.f0,self.f0,self.b_half) #Passing correct input workspace c=nmt.compute_full_master_flat(self.f0,self.f0,self.b,workspace=w) #Computing from correct wsp self.assertEqual(c.shape,(1,self.b.bin.n_bands)) with self.assertRaises(RuntimeError) : #Incompatible bandpowers c=nmt.compute_full_master_flat(self.f0,self.f0,self.b_half,workspace=w) with self.assertRaises(RuntimeError) : #Incompatible workspace c=nmt.compute_full_master_flat(self.f0,self.f0,self.b,workspace=w_half) #Incorrect input spectra with self.assertRaises(ValueError) : c=nmt.compute_full_master_flat(self.f0,self.f0,self.b,cl_noise=self.nb_bad,workspace=w) with self.assertRaises(ValueError) : c=nmt.compute_full_master_flat(self.f0,self.f0,self.b,cl_noise=self.n_good,workspace=w) with self.assertRaises(ValueError) : #Non ell-values c=nmt.compute_full_master_flat(self.f0,self.f0,self.b,cl_noise=self.nb_good, cl_guess=self.n_good,workspace=w) with self.assertRaises(ValueError) : #Wrong cl_guess c=nmt.compute_full_master_flat(self.f0,self.f0,self.b,cl_noise=self.nb_good, cl_guess=self.n_bad,ells_guess=self.l,workspace=w) with self.assertRaises(ValueError) : #Wrong cl_guess c=nmt.compute_full_master_flat(self.f0,self.f0,self.b,cl_noise=self.nb_good, cl_guess=self.nb_good,ells_guess=self.l,workspace=w)
def __init__(self, catfolder): """ Holds all of the information relevant to a given HSC field """ self.name = catfolder.split('_')[-3] self.filepath = catfolder self.cat = fits.open(self.filepath + 'clean_catalog.fits')[1].data self.masked_fraction_fp = self.filepath + 'masked_fraction.fits' self.masked_fraction = fits.open( self.masked_fraction_fp)[0].data.ravel() self.mask_binary = np.ones_like(self.masked_fraction) self.mask_binary[self.masked_fraction < 0.5] = 0. self.weight = self.masked_fraction * self.mask_binary self.goodpix = np.where(self.mask_binary > 0.1)[0] self.fsk, _ = read_flat_map(self.masked_fraction_fp) self.nmaps, self.nmaps_s1, self.nmaps_s2 = self.get_nmaps_split() self.fields = [field(self, thisbin) for thisbin in self.nmaps] self.fields_s1 = [field(self, thisbin) for thisbin in self.nmaps_s1] self.fields_s2 = [field(self, thisbin) for thisbin in self.nmaps_s2] self.ell_bins = nmt.NmtBinFlat(ell_bins[:-1], ell_bins[1:]) self.ell_bins_uncpld = self.ell_bins.get_effective_ells() self.wsp = nmt.NmtWorkspaceFlat() self.wsp.compute_coupling_matrix(self.fields[0].field, self.fields[0].field, self.ell_bins)
def test_workspace_flat_methods(): w = nmt.NmtWorkspaceFlat() w.compute_coupling_matrix(WT.f0, WT.f0, WT.b) # OK init assert WT.msk.shape == (w.wsp.fs.ny, w.wsp.fs.nx) with pytest.raises(RuntimeError): # Incompatible resolutions w.compute_coupling_matrix(WT.f0, WT.f0_half, WT.b) with pytest.raises(RuntimeError): # Wrong fields for TEB w.compute_coupling_matrix(WT.f0, WT.f0, WT.b, is_teb=True) w.compute_coupling_matrix(WT.f0, WT.f0, WT.b) # Test couple_cell c = w.couple_cell(WT.ll, WT.n_good) assert c.shape == (1, WT.b.bin.n_bands) with pytest.raises(ValueError): w.couple_cell(WT.ll, WT.n_bad) with pytest.raises(ValueError): w.couple_cell(WT.ll, WT.n_good[:, :len(WT.ll)//2]) # Test decouple_cell c = w.decouple_cell(WT.nb_good, WT.nb_good, WT.nb_good) assert c.shape == (1, WT.b.bin.n_bands) with pytest.raises(ValueError): w.decouple_cell(WT.nb_bad) with pytest.raises(ValueError): w.decouple_cell(WT.n_good) with pytest.raises(ValueError): w.decouple_cell(WT.nb_good, cl_bias=WT.nb_bad) with pytest.raises(ValueError): w.decouple_cell(WT.nb_good, cl_bias=WT.n_good) with pytest.raises(ValueError): w.decouple_cell(WT.nb_good, cl_noise=WT.nb_bad) with pytest.raises(ValueError): w.decouple_cell(WT.nb_good, cl_noise=WT.n_good)
def test_workspace_flat_methods(self): w = nmt.NmtWorkspaceFlat() w.compute_coupling_matrix(self.f0, self.f0, self.b) # OK init self.assertEqual(self.msk.shape, (w.wsp.fs.ny, w.wsp.fs.nx)) with self.assertRaises(RuntimeError): # Incompatible resolutions w.compute_coupling_matrix(self.f0, self.f0_half, self.b) with self.assertRaises(RuntimeError): # Wrong fields for TEB w.compute_coupling_matrix(self.f0, self.f0, self.b, is_teb=True) w.compute_coupling_matrix(self.f0, self.f0, self.b) # Test couple_cell c = w.couple_cell(self.ll, self.n_good) self.assertEqual(c.shape, (1, self.b.bin.n_bands)) with self.assertRaises(ValueError): w.couple_cell(self.ll, self.n_bad) with self.assertRaises(ValueError): w.couple_cell(self.ll, self.n_good[:, :len(self.ll) // 2]) # Test decouple_cell c = w.decouple_cell(self.nb_good, self.nb_good, self.nb_good) self.assertEqual(c.shape, (1, self.b.bin.n_bands)) with self.assertRaises(ValueError): w.decouple_cell(self.nb_bad) with self.assertRaises(ValueError): w.decouple_cell(self.n_good) with self.assertRaises(ValueError): w.decouple_cell(self.nb_good, cl_bias=self.nb_bad) with self.assertRaises(ValueError): w.decouple_cell(self.nb_good, cl_bias=self.n_good) with self.assertRaises(ValueError): w.decouple_cell(self.nb_good, cl_noise=self.nb_bad) with self.assertRaises(ValueError): w.decouple_cell(self.nb_good, cl_noise=self.n_good)
def get_workspaces(fields): """ :param fields: tuple of tuple of fields to compute the mode-coupling matrix for. Shape is nbis x (f0, f2) """ spins = [0, 2] * len(fields) ws = [] fields = sum(fields, ()) # Flatten the tuple of tuples zbin1 = 1 c1 = 0 for f1, s1 in zip(fields, spins): c2 = c1 zbin2 = int(c2 / 2) + 1 for f2, s2 in zip(fields[c1:], spins[c1:]): print("Computing {}{}_{}{}".format(s1, s2, zbin1, zbin2)) suffix = "_w{}{}_{}{}.dat".format(s1, s2, zbin1, zbin2) w = nmt.NmtWorkspaceFlat() get_coupling_matrix(w, f1, f2, suffix) ws.append(w) if not ((c2 + 1) % 2): zbin2 += 1 c2 += 1 if not ((c1 + 1) % 2): zbin1 += 1 c1 +=1 return ws
def setUp(self): self.w = nmt.NmtWorkspaceFlat() self.w.read_from("test/benchmarks/bm_f_nc_np_w00.dat") l, cltt, clee, clbb, clte, nltt, nlee, nlbb, nlte = np.loadtxt( "test/benchmarks/cls_lss.txt", unpack=True) self.l = l self.cltt = cltt + nltt
def test_field_masked(self): wcs, msk = read_flat_map("test/benchmarks/msk_flat.fits") ny, nx = msk.shape lx = np.radians(np.fabs(nx * wcs.wcs.cdelt[0])) ly = np.radians(np.fabs(ny * wcs.wcs.cdelt[1])) mps = np.array([ read_flat_map("test/benchmarks/mps_flat.fits", i_map=i)[1] for i in range(3) ]) mps_msk = np.array([m * msk for m in mps]) d_ell = 20 lmax = 500. ledges = np.arange(int(lmax / d_ell) + 1) * d_ell + 2 b = nmt.NmtBinFlat(ledges[:-1], ledges[1:]) f0 = nmt.NmtFieldFlat(lx, ly, msk, [mps[0]]) f0_msk = nmt.NmtFieldFlat(lx, ly, msk, [mps_msk[0]], masked_on_input=True) f2 = nmt.NmtFieldFlat(lx, ly, msk, [mps[1], mps[2]]) f2_msk = nmt.NmtFieldFlat(lx, ly, msk, [mps_msk[1], mps_msk[2]], masked_on_input=True) w00 = nmt.NmtWorkspaceFlat() w00.compute_coupling_matrix(f0, f0, b) w02 = nmt.NmtWorkspaceFlat() w02.compute_coupling_matrix(f0, f2, b) w22 = nmt.NmtWorkspaceFlat() w22.compute_coupling_matrix(f2, f2, b) def mkcl(w, f, g): return w.decouple_cell(nmt.compute_coupled_cell_flat(f, g, b)) c00 = mkcl(w00, f0, f0).flatten() c02 = mkcl(w02, f0, f2).flatten() c22 = mkcl(w22, f2, f2).flatten() c00_msk = mkcl(w00, f0_msk, f0_msk).flatten() c02_msk = mkcl(w02, f0_msk, f2_msk).flatten() c22_msk = mkcl(w22, f2_msk, f2_msk).flatten() self.assertTrue(np.all(np.fabs(c00 - c00_msk) / np.mean(c00) < 1E-10)) self.assertTrue(np.all(np.fabs(c02 - c02_msk) / np.mean(c02) < 1E-10)) self.assertTrue(np.all(np.fabs(c22 - c22_msk) / np.mean(c22) < 1E-10))
def test_workspace_flat_full_master(): w = nmt.NmtWorkspaceFlat() w.compute_coupling_matrix(WT.f0, WT.f0, WT.b) w_half = nmt.NmtWorkspaceFlat() w_half.compute_coupling_matrix(WT.f0_half, WT.f0_half, WT.b_half) c = nmt.compute_full_master_flat(WT.f0, WT.f0, WT.b) assert c.shape == (1, WT.b.bin.n_bands) with pytest.raises(ValueError): # Incompatible resolutions nmt.compute_full_master_flat(WT.f0, WT.f0_half, WT.b) c = nmt.compute_full_master_flat(WT.f0, WT.f0, WT.b_half) # Passing correct input workspace # Computing from correct wsp c = nmt.compute_full_master_flat(WT.f0, WT.f0, WT.b, workspace=w) assert c.shape == (1, WT.b.bin.n_bands) with pytest.raises(RuntimeError): # Incompatible bandpowers nmt.compute_full_master_flat(WT.f0, WT.f0, WT.b_half, workspace=w) with pytest.raises(RuntimeError): # Incompatible workspace nmt.compute_full_master_flat(WT.f0, WT.f0, WT.b, workspace=w_half) # Incorrect input spectra with pytest.raises(ValueError): nmt.compute_full_master_flat(WT.f0, WT.f0, WT.b, cl_noise=WT.nb_bad, workspace=w) with pytest.raises(ValueError): nmt.compute_full_master_flat(WT.f0, WT.f0, WT.b, cl_noise=WT.n_good, workspace=w) with pytest.raises(ValueError): # Non ell-values nmt.compute_full_master_flat(WT.f0, WT.f0, WT.b, cl_noise=WT.nb_good, cl_guess=WT.n_good, workspace=w) with pytest.raises(ValueError): # Wrong cl_guess nmt.compute_full_master_flat(WT.f0, WT.f0, WT.b, cl_noise=WT.nb_good, cl_guess=WT.n_bad, ells_guess=WT.ll, workspace=w) with pytest.raises(ValueError): # Wrong cl_guess nmt.compute_full_master_flat(WT.f0, WT.f0, WT.b, cl_noise=WT.nb_good, cl_guess=WT.nb_good, ells_guess=WT.ll, workspace=w)
def test_workspace_flat_io(self): w = nmt.NmtWorkspaceFlat() with self.assertRaises(RuntimeError): # Invalid writing w.write_to("test/wspc.fits") w.read_from("test/benchmarks/bm_f_yc_yp_w02.fits") # OK read self.assertEqual(self.msk.shape, (w.wsp.fs.ny, w.wsp.fs.nx)) with self.assertRaises(RuntimeError): # Can't write on that file w.write_to("tests/wspc.fits") with self.assertRaises(RuntimeError): # File doesn't exist w.read_from("none")
def get_mcm(self, tracers, bpws): """ Get NmtWorkspaceFlat for our mask """ wsp = nmt.NmtWorkspaceFlat() if not os.path.isfile(self.get_output_fname('mcm', ext='dat')): print("Computing MCM") wsp.compute_coupling_matrix(tracers[0].field, tracers[0].field, bpws) wsp.write_to(self.get_output_fname('mcm', ext='dat')) else: print("Reading MCM") wsp.read_from(self.get_output_fname('mcm', ext='dat')) return wsp
def mastest(self,wtemp,wpure) : prefix="test/benchmarks/bm_f" if wtemp : prefix+="_yc" f0=nmt.NmtFieldFlat(self.lx,self.ly,self.msk,[self.mps[0]],templates=[[self.tmp[0]]]) f2=nmt.NmtFieldFlat(self.lx,self.ly,self.msk,[self.mps[1],self.mps[2]], templates=[[self.tmp[1],self.tmp[2]]], purify_b=wpure) else : prefix+="_nc" f0=nmt.NmtFieldFlat(self.lx,self.ly,self.msk,[self.mps[0]]) f2=nmt.NmtFieldFlat(self.lx,self.ly,self.msk,[self.mps[1],self.mps[2]],purify_b=wpure) f=[f0,f2] if wpure : prefix+="_yp" else : prefix+="_np" for ip1 in range(2) : for ip2 in range(ip1,2) : if ip1==ip2==0 : clth=np.array([self.cltt]); nlth=np.array([self.nltt]); elif ip1==ip2==1 : clth=np.array([self.clee,0*self.clee,0*self.clbb,self.clbb]); nlth=np.array([self.nlee,0*self.nlee,0*self.nlbb,self.nlbb]); else : clth=np.array([self.clte,0*self.clte]); nlth=np.array([self.nlte,0*self.nlte]); w=nmt.NmtWorkspaceFlat() w.compute_coupling_matrix(f[ip1],f[ip2],self.b) clb=w.couple_cell(self.l,nlth) if wtemp : dlb=nmt.deprojection_bias_flat(f[ip1],f[ip2],self.b,self.l,clth+nlth) tlb=np.loadtxt(prefix+'_cb%d%d.txt'%(2*ip1,2*ip2),unpack=True)[1:,:] self.assertTrue((np.fabs(dlb-tlb)<=np.fmin(np.fabs(dlb),np.fabs(tlb))*1E-5).all()) clb+=dlb cl=w.decouple_cell(nmt.compute_coupled_cell_flat(f[ip1],f[ip2],self.b),cl_bias=clb) tl=np.loadtxt(prefix+'_c%d%d.txt'%(2*ip1,2*ip2),unpack=True)[1:,:] self.assertTrue((np.fabs(cl-tl)<=np.fmin(np.fabs(cl),np.fabs(tl))*1E-5).all())
def test_spin1(self): prefix = "test/benchmarks/bm_f_sp1" f0 = nmt.NmtFieldFlat(self.lx, self.ly, self.msk, [self.mps_s1[0]]) f1 = nmt.NmtFieldFlat(self.lx, self.ly, self.msk, [self.mps_s1[1], self.mps_s1[2]], spin=1) f = [f0, f1] for ip1 in range(2): for ip2 in range(ip1, 2): w = nmt.NmtWorkspaceFlat() w.compute_coupling_matrix(f[ip1], f[ip2], self.b) cl = w.decouple_cell(nmt.compute_coupled_cell_flat(f[ip1], f[ip2], self.b))[0] tl = np.loadtxt(prefix+'_c%d%d.txt' % (ip1, ip2), unpack=True)[1] self.assertTrue((np.fabs(cl-tl) <= np.fmin(np.fabs(cl), np.fabs(tl))*1E-5).all())
def test_lite_pure(self): f0 = nmt.NmtFieldFlat(self.lx, self.ly, self.msk, [self.mps[0]]) f2l = nmt.NmtFieldFlat(self.lx, self.ly, self.msk, [self.mps[1], self.mps[2]], purify_b=True, lite=True) f2e = nmt.NmtFieldFlat(self.lx, self.ly, self.msk, None, purify_b=True, lite=True, spin=2) nlth = np.array([self.nlte, 0*self.nlte]) w = nmt.NmtWorkspaceFlat() w.compute_coupling_matrix(f0, f2e, self.b) clb = w.couple_cell(self.ll, nlth) cl = w.decouple_cell(nmt.compute_coupled_cell_flat(f0, f2l, self.b), cl_bias=clb) tl = np.loadtxt("test/benchmarks/bm_f_nc_yp_c02.txt", unpack=True)[1:, :] self.assertTrue((np.fabs(cl-tl) <= np.fmin(np.fabs(cl), np.fabs(tl))*1E-5).all())
def generate_covariance_workspace00(run_path, fa1, fa2, flat=False): if flat: w00 = nmt.NmtWorkspaceFlat() cw00 = nmt.NmtCovarianceWorkspaceFlat() else: w00 = nmt.NmtWorkspace() cw00 = nmt.NmtCovarianceWorkspace() w00.read_from(run_path + "_w00.dat") cw00_file = run_path + "_cw00.dat" if not os.path.isfile(cw00_file): if flat: raise ValueError('flat not implemented yet') # cw00.compute_coupling_coefficients(w00, w00) else: cw00.compute_coupling_coefficients(fa1, fa2) cw00.write_to(cw00_file) else: cw00.read_from(cw00_file) return w00, cw00
def test_lite_cont(self): f0 = nmt.NmtFieldFlat(self.lx, self.ly, self.msk, [self.mps[0]], templates=[[self.tmp[0]]]) tmps = [[self.tmp[1], self.tmp[2]]] f2 = nmt.NmtFieldFlat(self.lx, self.ly, self.msk, [self.mps[1], self.mps[2]], templates=tmps) f2l = nmt.NmtFieldFlat(self.lx, self.ly, self.msk, [self.mps[1], self.mps[2]], templates=tmps, lite=True) f2e = nmt.NmtFieldFlat(self.lx, self.ly, self.msk, None, lite=True, spin=2) clth = np.array([self.clte, 0*self.clte]) nlth = np.array([self.nlte, 0*self.nlte]) w = nmt.NmtWorkspaceFlat() w.compute_coupling_matrix(f0, f2e, self.b) clb = w.couple_cell(self.ll, nlth) dlb = nmt.deprojection_bias_flat(f0, f2, self.b, self.ll, clth+nlth) clb += dlb cl = w.decouple_cell(nmt.compute_coupled_cell_flat(f0, f2l, self.b), cl_bias=clb) tl = np.loadtxt("test/benchmarks/bm_f_yc_np_c02.txt", unpack=True)[1:, :] tlb = np.loadtxt("test/benchmarks/bm_f_yc_np_cb02.txt", unpack=True)[1:, :] self.assertTrue((np.fabs(dlb-tlb) <= np.fmin(np.fabs(dlb), np.fabs(tlb))*1E-5).all()) self.assertTrue((np.fabs(cl-tl) <= np.fmin(np.fabs(cl), np.fabs(tl))*1E-5).all())
def test_workspace_covar_flat_errors(self): cw = nmt.NmtCovarianceWorkspaceFlat() with self.assertRaises(ValueError): #Write uninitialized cw.write_to("wsp.dat") cw.compute_coupling_coefficients(self.w, self.w) #All good self.assertEqual(cw.wsp.bin.n_bands, self.w.wsp.bin.n_bands) with self.assertRaises(RuntimeError): #Write uninitialized cw.write_to("tests/wsp.dat") cw.read_from('test/benchmarks/bm_f_nc_np_cw00.dat') #Correct reading self.assertEqual(cw.wsp.bin.n_bands, self.w.wsp.bin.n_bands) #gaussian_covariance with self.assertRaises(ValueError): #Wrong input power spectra nmt.gaussian_covariance_flat(cw, self.l, self.cltt, self.cltt, self.cltt, self.cltt[:15]) with self.assertRaises(RuntimeError): #Incorrect reading cw.read_from('none') w2 = nmt.NmtWorkspaceFlat() w2.read_from("test/benchmarks/bm_f_nc_np_w00.dat") w2.wsp.fs.nx = self.w.wsp.fs.nx // 2 with self.assertRaises(ValueError): #Incompatible resolutions cw.compute_coupling_coefficients(self.w, w2) w2.wsp.fs.nx = self.w.wsp.fs.nx w2.wsp.bin.n_bands = self.w.wsp.bin.n_bands // 2 with self.assertRaises(RuntimeError): #Incompatible resolutions cw.compute_coupling_coefficients(self.w, w2) w2.wsp.bin.n_bands = self.w.wsp.bin.n_bands w2.read_from("test/benchmarks/bm_f_nc_np_w02.dat") with self.assertRaises(ValueError): #Spin-2 cw.compute_coupling_coefficients(self.w, w2)
ff2=nmt.NmtFieldFlat(fmi.lx_rad,fmi.ly_rad,mask.reshape([fmi.ny,fmi.nx]), [sq.reshape([fmi.ny,fmi.nx]),su.reshape([fmi.ny,fmi.nx])], templates=fgp.reshape([1,2,fmi.ny,fmi.nx]),beam=[l,beam], purify_e=False,purify_b=w_pureb) else : ff2=nmt.NmtFieldFlat(fmi.lx_rad,fmi.ly_rad,mask.reshape([fmi.ny,fmi.nx]), [sq.reshape([fmi.ny,fmi.nx]),su.reshape([fmi.ny,fmi.nx])], beam=[l,beam],purify_e=False,purify_b=w_pureb) return ff2 np.random.seed(1000) print("Fielding") f2=get_fields() #Use initial fields to generate coupling matrix w22=nmt.NmtWorkspaceFlat(); if not os.path.isfile(prefix+"_w22.dat") : print("Computing 22") w22.compute_coupling_matrix(f2,f2,b) w22.write_to(prefix+"_w22.dat"); else : w22.read_from(prefix+"_w22.dat") #Generate theory prediction if not os.path.isfile(prefix+'_cl_th.txt') : print("Computing theory prediction") cl22_th=w22.decouple_cell(w22.couple_cell(l,np.array([clee,0*clee,0*clbb,clbb]))) np.savetxt(prefix+"_cl_th.txt", np.transpose([b.get_effective_ells(),cl22_th[0],cl22_th[1],cl22_th[2],cl22_th[3]])) else : cl22_th=np.zeros([4,b.get_n_bands()])
def compute_wsps(self): """ Convenience method for calculating the NaMaster workspaces for all the probes in the simulation. :return wsps: wsps list """ wsps = [[None for i in range(self.params['nprobes'])] for ii in range(self.params['nprobes'])] maps = self.simmaps.generate_maps() b = nmt.NmtBinFlat(self.params['l0_bins'], self.params['lf_bins']) # Compute workspaces for all the probes for j in range(self.params['nprobes']): for jj in range(j + 1): spin1 = self.params['spins'][j] spin2 = self.params['spins'][jj] logger.info('Spins: spin1 = {}, spin2 = {}.'.format( spin1, spin2)) if spin1 == 2 and spin2 == 0: # Define flat sky spin-2 field emaps = [maps[j], maps[j + self.params['nspin2']]] f2_1 = nmt.NmtFieldFlat(self.params['Lx'], self.params['Ly'], self.maskmat[j, jj], emaps, purify_b=False) # Define flat sky spin-0 field emaps = [maps[jj]] f0_1 = nmt.NmtFieldFlat(self.params['Lx'], self.params['Ly'], self.maskmat[j, jj], emaps, purify_b=False) logger.info('Computing workspace element.') wsp = nmt.NmtWorkspaceFlat() wsp.compute_coupling_matrix(f2_1, f0_1, b) wsps[j][jj] = wsp if j != jj: wsps[jj][j] = wsp elif spin1 == 2 and spin2 == 2: # Define flat sky spin-2 field emaps = [maps[j], maps[j + self.params['nspin2']]] f2_1 = nmt.NmtFieldFlat(self.params['Lx'], self.params['Ly'], self.maskmat[j, jj], emaps, purify_b=False) # Define flat sky spin-0 field emaps = [maps[jj], maps[jj + self.params['nspin2']]] f2_2 = nmt.NmtFieldFlat(self.params['Lx'], self.params['Ly'], self.maskmat[j, jj], emaps, purify_b=False) logger.info('Computing workspace element.') wsp = nmt.NmtWorkspaceFlat() wsp.compute_coupling_matrix(f2_1, f2_2, b) wsps[j][jj] = wsp if j != jj: wsps[jj][j] = wsp else: # Define flat sky spin-0 field emaps = [maps[j]] f0_1 = nmt.NmtFieldFlat(self.params['Lx'], self.params['Ly'], self.maskmat[j, jj], emaps, purify_b=False) # Define flat sky spin-0 field emaps = [maps[jj]] f0_2 = nmt.NmtFieldFlat(self.params['Lx'], self.params['Ly'], self.maskmat[j, jj], emaps, purify_b=False) logger.info('Computing workspace element.') wsp = nmt.NmtWorkspaceFlat() wsp.compute_coupling_matrix(f0_1, f0_2, b) wsps[j][jj] = wsp if j != jj: wsps[jj][j] = wsp return wsps
wcs,msk=read_flat_map("msk_flat.fits") (ny,nx)=msk.shape lx=np.fabs(nx*wcs.wcs.cdelt[0])*np.pi/180 ly=np.fabs(ny*wcs.wcs.cdelt[1])*np.pi/180 d_ell=20; lmax=500.; ledges=np.arange(int(lmax/d_ell)+1)*d_ell+2 b=nmt.NmtBinFlat(ledges[:-1],ledges[1:]) leff=b.get_effective_ells(); dt,dq,du=nmt.synfast_flat(int(nx),int(ny),lx,ly, [cltt,cltt,0*cltt,cltt,0*cltt,0*cltt],[0,1]) write_flat_map("mps_sp1_flat.fits", np.array([dt,dq,du]),wcs,["T", "Q", "U"]) prefix = 'bm_f_sp1' f0=nmt.NmtFieldFlat(lx,ly,msk,[dt]) f1=nmt.NmtFieldFlat(lx,ly,msk,[dq,du], spin=1) w00=nmt.NmtWorkspaceFlat(); w00.compute_coupling_matrix(f0,f0,b); w00.write_to(prefix+'_w00.fits') c00=w00.decouple_cell(nmt.compute_coupled_cell_flat(f0,f0,b)) np.savetxt(prefix+'_c00.txt', np.transpose([leff, c00[0]])) w01=nmt.NmtWorkspaceFlat(); w01.compute_coupling_matrix(f0,f1,b); w01.write_to(prefix+'_w01.fits') c01=w01.decouple_cell(nmt.compute_coupled_cell_flat(f0,f1,b)) np.savetxt(prefix+'_c01.txt', np.transpose([leff, c01[0], c01[1]])) w11=nmt.NmtWorkspaceFlat(); w11.compute_coupling_matrix(f1,f1,b); w11.write_to(prefix+'_w11.fits') c11=w11.decouple_cell(nmt.compute_coupled_cell_flat(f1,f1,b)) np.savetxt(prefix+'_c11.txt', np.transpose([leff, c11[0], c11[1], c11[2], c11[3]])) plt.figure()
def compute_power_spectrum(self, map1, mask1, map2=None, mask2=None, l_bpw=None, return_bpw=False, wsp=None, return_wsp=False, temp1=None, temp2=None): """ Computes power spectrum between two maps. map1 : first map to correlate mask1 : mask for the first map map2 : second map to correlate. If None map2==map1. mask2 : mask for the second map. If None mask2==mask1. l_bpw : bandpowers on which to calculate the power spectrum. Should be an [2,N_ell] array, where the first and second columns list the edges of each bandpower. If None, the function will create bandpowers of its own taylored to the properties of your map. return_bpw : if True, the bandpowers will also be returned wsp : NmtWorkspaceFlat object to accelerate the calculation. If None, this will be precomputed. return_wsp : if True, the workspace will also be returned temp1 : if not None, set of contaminants to remove from map1 temp2 : if not None, set of contaminants to remove from map2 """ same_map = False if map2 is None: map2 = map1 same_map = True same_mask = False if mask2 is None: mask2 = mask1 same_mask = False if len(map1) != self.npix: raise ValueError("Input map has the wrong size") if (len(map1) != len(map2)) or (len(map1) != len(mask1)) or ( len(map1) != len(mask2)): raise ValueError("Sizes of all maps and masks don't match") if l_bpw is None: ell_min = max(2 * np.pi / self.lx_rad, 2 * np.pi / self.ly_rad) ell_max = min(self.nx * np.pi / self.lx_rad, self.ny * np.pi / self.ly_rad) d_ell = 2 * ell_min n_ell = int((ell_max - ell_min) / d_ell) - 1 l_bpw = np.zeros([2, n_ell]) l_bpw[0, :] = ell_min + np.arange(n_ell) * d_ell l_bpw[1, :] = l_bpw[0, :] + d_ell return_bpw = True #Generate binning scheme b = nmt.NmtBinFlat(l_bpw[0, :], l_bpw[1, :]) if temp1 is not None: tmp1 = np.array([[t.reshape([self.ny, self.nx])] for t in temp1]) else: tmp1 = None if temp2 is not None: tmp2 = np.array([[t.reshape([self.ny, self.nx])] for t in temp2]) else: tmp2 = None #Generate fields f1 = nmt.NmtFieldFlat(self.lx_rad, self.ly_rad, mask1.reshape([self.ny, self.nx]), [map1.reshape([self.ny, self.nx])], templates=tmp1) if same_map and same_mask: f2 = f1 else: f2 = nmt.NmtFieldFlat(self.lx_rad, self.ly_rad, mask2.reshape([self.ny, self.nx]), [map2.reshape([self.ny, self.nx])], templates=tmp2) #Compute workspace if needed if wsp is None: wsp = nmt.NmtWorkspaceFlat() wsp.compute_coupling_matrix(f1, f2, b) return_wsp = True #Compute power spectrum cl_coupled = nmt.compute_coupled_cell_flat(f1, f2, b) cl_uncoupled = wsp.decouple_cell(cl_coupled)[0] #Return if return_bpw and return_wsp: return cl_uncoupled, l_bpw, wsp else: if return_bpw: return cl_uncoupled, l_bpw elif return_wsp: return cl_uncoupled, wsp else: return cl_uncoupled
np.save('../data/mpt_conv.npy', mpt_conv) np.save('../data/mpt_conv2.npy', mpt_conv2) np.save('../data/mpt_conv3.npy', mpt_conv3) mask = np.ones_like(mpt) f0 = nmt.NmtFieldFlat(Lx, Ly, mask, [mpt]) f0_conv = nmt.NmtFieldFlat(Lx, Ly, mask, [mpt_conv], beam=[l, beam]) f0_conv2 = nmt.NmtFieldFlat(Lx, Ly, mask, [mpt_conv2], beam=[l, beam]) f0_conv3 = nmt.NmtFieldFlat(Lx, Ly, mask, [mpt_conv3], beam=[l, beam]) l0_bins = np.arange(Nx / 8) * 8 * np.pi / Lx lf_bins = (np.arange(Nx / 8) + 1) * 8 * np.pi / Lx b = nmt.NmtBinFlat(l0_bins, lf_bins) ells_uncoupled = b.get_effective_ells() w00 = nmt.NmtWorkspaceFlat() w00.compute_coupling_matrix(f0, f0, b) w00.write_to("../data/w00_flat.fits") w00_conv = nmt.NmtWorkspaceFlat() w00_conv.compute_coupling_matrix(f0_conv, f0_conv, b) w00_conv.write_to("../data/w00_flat_conv.fits") w00_conv2 = nmt.NmtWorkspaceFlat() w00_conv2.compute_coupling_matrix(f0_conv2, f0_conv2, b) w00_conv2.write_to("../data/w00_flat_conv2.fits") w00_conv3 = nmt.NmtWorkspaceFlat() w00_conv3.compute_coupling_matrix(f0_conv3, f0_conv3, b) w00_conv3.write_to("../data/w00_flat_conv3.fits")
Ly, mask, [norm_y_fluc], beam=[ells_uncoupled, beam(ells_uncoupled)]) plt.figure() plt.imshow(f0.get_maps()[0] * mask, interpolation='nearest', origin='lower') plt.colorbar() plt.savefig('../images/map with mask.png', dpi=400) plt.show() print( "\n--------------------------- ANGULAR POWER SPECTRUM ------------------------------------\n" ) w00 = nmt.NmtWorkspaceFlat() w00.compute_coupling_matrix(f0, f0, b) #Coupling matrix used to estimate angular spectrum cl00_coupled = nmt.compute_coupled_cell_flat(f0, f0, b) cl00_uncoupled = w00.decouple_cell(cl00_coupled)[0] print(cl00_uncoupled) amp = abs((ells_uncoupled**2) * cl00_uncoupled / (2 * np.pi))**(1 / 2) print( "\n************************* Covariance matrix *************************************\n" ) cw = nmt.NmtCovarianceWorkspaceFlat() cw.compute_coupling_coefficients(f0, f0, b) covar = nmt.gaussian_covariance_flat(cw, 0, 0, 0, 0, ells_uncoupled,
emaps = [map2] # Define fields f1 = nmt.NmtFieldFlat(config['Lx'], config['Ly'], mask1, emaps, purify_b=False) f2 = nmt.NmtFieldFlat(config['Lx'], config['Ly'], mask2, emaps, purify_b=False) logger.info('Computing workspace element.') wsp = nmt.NmtWorkspaceFlat() wsp.compute_coupling_matrix(f1, f2, b) # Compute pseudo-Cls cl_coupled = nmt.compute_coupled_cell_flat(f1, f2, b) # Uncoupling pseudo-Cls # For one spin-0 field and one spin-2 field, NaMaster gives: n_cls=2, [C_TE,C_TB] # For two spin-2 fields, NaMaster gives: n_cls=4, [C_E1E2,C_E1B2,C_E2B1,C_B1B2] logger.info('Decoupling cls.') cl_uncoupled = wsp.decouple_cell(cl_coupled) cl_out = np.vstack((ells_uncoupled, cl_uncoupled)) else: raise NotImplementedError()
def compute_wsps(self): """ Convenience method for calculating the NaMaster workspaces for all the probes in the simulation. :return wsps: wsps list """ self.wsps = [[None for i in range(self.params['nprobes'])] for ii in range(self.params['nprobes'])] if self.params['signal']: signalmaps = self.simmaps.generate_maps() if self.params['noise']: # We need to add noise maps to the signal maps noisemaps = self.noisemaps.generate_maps() if self.params['signal']: maps = copy.deepcopy(signalmaps) elif self.params['noise']: maps = copy.deepcopy(noisemaps) else: raise RuntimeError( 'Either signal or noise must be True. Aborting.') b = nmt.NmtBinFlat(self.params['l0_bins'], self.params['lf_bins']) # Compute workspaces for all the probes for j in range(self.params['nprobes']): for jj in range(j + 1): if j == jj: compute_cls = True else: if self.params['signal']: compute_cls = True else: compute_cls = False if compute_cls: spin1 = self.params['spins'][j] spin2 = self.params['spins'][jj] logger.info('Spins: spin1 = {}, spin2 = {}.'.format( spin1, spin2)) if spin1 == 2 and spin2 == 0: # Define flat sky spin-2 field emaps = [maps[j], maps[j + self.params['nspin2']]] f2_1 = nmt.NmtFieldFlat(np.radians(self.fsk.lx), np.radians(self.fsk.ly), self.masks[j], emaps, purify_b=False) # Define flat sky spin-0 field emaps = [maps[jj]] f0_1 = nmt.NmtFieldFlat(np.radians(self.fsk.lx), np.radians(self.fsk.ly), self.masks[jj], emaps, purify_b=False) logger.info('Computing workspace element.') wsp = nmt.NmtWorkspaceFlat() wsp.compute_coupling_matrix(f2_1, f0_1, b) self.wsps[j][jj] = wsp if j != jj: self.wsps[jj][j] = wsp elif spin1 == 2 and spin2 == 2: # Define flat sky spin-2 field emaps = [maps[j], maps[j + self.params['nspin2']]] f2_1 = nmt.NmtFieldFlat(np.radians(self.fsk.lx), np.radians(self.fsk.ly), self.masks[j], emaps, purify_b=False) # Define flat sky spin-0 field emaps = [maps[jj], maps[jj + self.params['nspin2']]] f2_2 = nmt.NmtFieldFlat(np.radians(self.fsk.lx), np.radians(self.fsk.ly), self.masks[jj], emaps, purify_b=False) logger.info('Computing workspace element.') wsp = nmt.NmtWorkspaceFlat() wsp.compute_coupling_matrix(f2_1, f2_2, b) self.wsps[j][jj] = wsp if j != jj: self.wsps[jj][j] = wsp else: # Define flat sky spin-0 field emaps = [maps[j]] f0_1 = nmt.NmtFieldFlat(np.radians(self.fsk.lx), np.radians(self.fsk.ly), self.masks[j], emaps, purify_b=False) # Define flat sky spin-0 field emaps = [maps[jj]] f0_2 = nmt.NmtFieldFlat(np.radians(self.fsk.lx), np.radians(self.fsk.ly), self.masks[jj], emaps, purify_b=False) logger.info('Computing workspace element.') wsp = nmt.NmtWorkspaceFlat() wsp.compute_coupling_matrix(f0_1, f0_2, b) self.wsps[j][jj] = wsp if j != jj: self.wsps[jj][j] = wsp return self.wsps
def __call__(self, realiz): """ Convenience method for calculating the signal and noise cls for a given mock realization. This is a function that can be pickled and can be thus used when running the mock generation in parallel using multiprocessing pool. :param realis: number of the realisation to run :param noise: boolean flag indicating if noise is added to the mocks noise=True: add noise to the mocks noise=False: do not add noise to the mocks :param probes: list of desired probes to run the mock for :param maskmat: matrix with the relevant masks for the probes :param clparams: list of dictionaries with the parameters for calculating the power spectra for each probe :return cls: 3D array of signal and noise cls for the given realisation, 0. and 1. axis denote the power spectrum, 2. axis gives the cls belonging to this configuration :return noisecls: 3D array of noise cls for the given realisation, 0. and 1. axis denote the power spectrum, 2. axis gives the cls belonging to this configuration :return tempells: array of the ell range of the power spectra """ logger.info('Running realization : {}.'.format(realiz)) cls = np.zeros((self.params['nautocls'], self.params['nautocls'], self.params['nell'])) noisecls = np.zeros_like(cls) if self.params['signal']: signalmaps = self.simmaps.generate_maps() if self.params['noise']: # We need to add noise maps to the signal maps noisemaps = self.noisemaps.generate_maps() if self.params['signal'] and self.params['noise']: # We need to add the two lists elementwise maps = list(map(add, signalmaps, noisemaps)) elif self.params['signal'] and not self.params['noise']: maps = copy.deepcopy(signalmaps) elif not self.params['signal'] and self.params['noise']: maps = copy.deepcopy(noisemaps) else: raise RuntimeError( 'Either signal or noise must be True. Aborting.') b = nmt.NmtBinFlat(self.params['l0_bins'], self.params['lf_bins']) # The effective sampling rate for these bandpowers can be obtained calling: ells_uncoupled = b.get_effective_ells() # First compute the cls of map realization for all the probes for j in range(self.params['nprobes']): for jj in range(j + 1): if j == jj: compute_cls = True else: if self.params['signal']: compute_cls = True else: compute_cls = False if compute_cls: probe1 = self.params['probes'][j] probe2 = self.params['probes'][jj] spin1 = self.params['spins'][j] spin2 = self.params['spins'][jj] logger.info( 'Computing the power spectrum between probe1 = {} and probe2 = {}.' .format(probe1, probe2)) logger.info('Spins: spin1 = {}, spin2 = {}.'.format( spin1, spin2)) if spin1 == 2 and spin2 == 0: # Define flat sky spin-2 field emaps = [maps[j], maps[j + self.params['nspin2']]] f2_1 = nmt.NmtFieldFlat(np.radians(self.fsk.lx), np.radians(self.fsk.ly), self.masks[j], emaps, purify_b=False) # Define flat sky spin-0 field emaps = [maps[jj]] f0_1 = nmt.NmtFieldFlat(np.radians(self.fsk.lx), np.radians(self.fsk.ly), self.masks[jj], emaps, purify_b=False) if self.wsps[j][jj] is None: logger.info( 'Workspace element for j, jj = {}, {} not set.' .format(j, jj)) logger.info('Computing workspace element.') wsp = nmt.NmtWorkspaceFlat() wsp.compute_coupling_matrix(f2_1, f0_1, b) self.wsps[j][jj] = wsp if j != jj: self.wsps[jj][j] = wsp else: logger.info( 'Workspace element already set for j, jj = {}, {}.' .format(j, jj)) # Compute pseudo-Cls cl_coupled = nmt.compute_coupled_cell_flat( f2_1, f0_1, b) # Uncoupling pseudo-Cls cl_uncoupled = self.wsps[j][jj].decouple_cell( cl_coupled) # For one spin-0 field and one spin-2 field, NaMaster gives: n_cls=2, [C_TE,C_TB] tempclse = cl_uncoupled[0] tempclsb = cl_uncoupled[1] cls[j, jj, :] = tempclse cls[j + self.params['nspin2'], jj, :] = tempclsb elif spin1 == 2 and spin2 == 2: # Define flat sky spin-2 field emaps = [maps[j], maps[j + self.params['nspin2']]] f2_1 = nmt.NmtFieldFlat(np.radians(self.fsk.lx), np.radians(self.fsk.ly), self.masks[j], emaps, purify_b=False) # Define flat sky spin-0 field emaps = [maps[jj], maps[jj + self.params['nspin2']]] f2_2 = nmt.NmtFieldFlat(np.radians(self.fsk.lx), np.radians(self.fsk.ly), self.masks[jj], emaps, purify_b=False) if self.wsps[j][jj] is None: logger.info( 'Workspace element for j, jj = {}, {} not set.' .format(j, jj)) logger.info('Computing workspace element.') wsp = nmt.NmtWorkspaceFlat() wsp.compute_coupling_matrix(f2_1, f2_2, b) self.wsps[j][jj] = wsp if j != jj: self.wsps[jj][j] = wsp else: logger.info( 'Workspace element already set for j, jj = {}, {}.' .format(j, jj)) # Compute pseudo-Cls cl_coupled = nmt.compute_coupled_cell_flat( f2_1, f2_2, b) # Uncoupling pseudo-Cls cl_uncoupled = self.wsps[j][jj].decouple_cell( cl_coupled) # For two spin-2 fields, NaMaster gives: n_cls=4, [C_E1E2,C_E1B2,C_E2B1,C_B1B2] tempclse = cl_uncoupled[0] tempclseb = cl_uncoupled[1] tempclsb = cl_uncoupled[3] cls[j, jj, :] = tempclse cls[j + self.params['nspin2'], jj, :] = tempclseb cls[j + self.params['nspin2'], jj + self.params['nspin2'], :] = tempclsb else: # Define flat sky spin-0 field emaps = [maps[j]] f0_1 = nmt.NmtFieldFlat(np.radians(self.fsk.lx), np.radians(self.fsk.ly), self.masks[j], emaps, purify_b=False) # Define flat sky spin-0 field emaps = [maps[jj]] f0_2 = nmt.NmtFieldFlat(np.radians(self.fsk.lx), np.radians(self.fsk.ly), self.masks[jj], emaps, purify_b=False) if self.wsps[j][jj] is None: logger.info( 'Workspace element for j, jj = {}, {} not set.' .format(j, jj)) logger.info('Computing workspace element.') wsp = nmt.NmtWorkspaceFlat() wsp.compute_coupling_matrix(f0_1, f0_2, b) self.wsps[j][jj] = wsp if j != jj: self.wsps[jj][j] = wsp else: logger.info( 'Workspace element already set for j, jj = {}, {}.' .format(j, jj)) # Compute pseudo-Cls cl_coupled = nmt.compute_coupled_cell_flat( f0_1, f0_2, b) # Uncoupling pseudo-Cls cl_uncoupled = self.wsps[j][jj].decouple_cell( cl_coupled) cls[j, jj, :] = cl_uncoupled # If noise is True, then we need to compute the noise from simulations # We therefore generate different noise maps for each realisation so that # we can then compute the noise power spectrum from these noise realisations if self.params['signal'] and self.params['noise']: # Determine the noise bias on the auto power spectrum for each realisation # For the cosmic shear, we now add the shear from the noisefree signal maps to the # data i.e. we simulate how we would do it in real life noisemaps = self.noisemaps.generate_maps(signalmaps) for j, probe in enumerate(self.params['probes']): logger.info( 'Computing the noise power spectrum for {}.'.format(probe)) if self.params['spins'][j] == 2: # Define flat sky spin-2 field emaps = [ noisemaps[j], noisemaps[j + self.params['nspin2']] ] f2 = nmt.NmtFieldFlat(np.radians(self.fsk.lx), np.radians(self.fsk.ly), self.masks[j], emaps, purify_b=False) if self.wsps[j][j] is None: logger.info( 'Workspace element for j, j = {}, {} not set.'. format(j, j)) logger.info('Computing workspace element.') wsp = nmt.NmtWorkspaceFlat() wsp.compute_coupling_matrix(f2, f2, b) self.wsps[j][j] = wsp else: logger.info( 'Workspace element already set for j, j = {}, {}.'. format(j, j)) # Compute pseudo-Cls cl_coupled = nmt.compute_coupled_cell_flat(f2, f2, b) # Uncoupling pseudo-Cls cl_uncoupled = self.wsps[j][j].decouple_cell(cl_coupled) # For two spin-2 fields, NaMaster gives: n_cls=4, [C_E1E2,C_E1B2,C_E2B1,C_B1B2] tempclse = cl_uncoupled[0] tempclsb = cl_uncoupled[3] noisecls[j, j, :] = tempclse noisecls[j + self.params['nspin2'], j + self.params['nspin2'], :] = tempclsb else: # Define flat sky spin-0 field emaps = [noisemaps[j]] f0 = nmt.NmtFieldFlat(np.radians(self.fsk.lx), np.radians(self.fsk.ly), self.masks[j], emaps, purify_b=False) if self.wsps[j][j] is None: logger.info( 'Workspace element for j, j = {}, {} not set.'. format(j, j)) logger.info('Computing workspace element.') wsp = nmt.NmtWorkspaceFlat() wsp.compute_coupling_matrix(f0, f0, b) self.wsps[j][j] = wsp else: logger.info( 'Workspace element already set for j, j = {}, {}.'. format(j, j)) # Compute pseudo-Cls cl_coupled = nmt.compute_coupled_cell_flat(f0, f0, b) # Uncoupling pseudo-Cls cl_uncoupled = self.wsps[j][j].decouple_cell(cl_coupled) noisecls[j, j, :] = cl_uncoupled if not self.params['signal'] and self.params['noise']: noisecls = copy.deepcopy(cls) cls = np.zeros_like(noisecls) return cls, noisecls, ells_uncoupled
def guess_spectra_cpld(self, params, saccfile_coadd, noise_saccfile_coadd=None): ell_theor = np.arange(self.config['ellmax']) theor = GSKYPrediction(saccfile_coadd, ells=ell_theor) cl_theor = theor.get_prediction(params) masks, fsk = self.get_masks() dl_min = int( min(2 * np.pi / np.radians(fsk.lx), 2 * np.pi / np.radians(fsk.ly))) ells_hi = np.arange(2, 15800, dl_min * 1.5).astype(int) bpws_hi = nmt.NmtBinFlat(ells_hi[:-1], ells_hi[1:]) leff_hi = bpws_hi.get_effective_ells() cl_cpld = [] trc_combs = saccfile_coadd.get_tracer_combinations() for i, (tr_i, tr_j) in enumerate(trc_combs): logger.info('Computing wsp for trc_comb = {}.'.format( (tr_i, tr_j))) tr_i_ind = self.config['tracers'].index(tr_i) tr_j_ind = self.config['tracers'].index(tr_j) mask_i = masks[tr_i_ind] mask_j = masks[tr_j_ind] cl_theor_curr = [cl_theor[i]] if 'wl' in tr_i: field_i = nmt.NmtFieldFlat( np.radians(fsk.lx), np.radians(fsk.ly), mask_i.reshape([fsk.ny, fsk.nx]), [ mask_i.reshape([fsk.ny, fsk.nx]), mask_i.reshape([fsk.ny, fsk.nx]) ], templates=None) cl_theor_curr.append(np.zeros_like(cl_theor[i])) else: field_i = nmt.NmtFieldFlat(np.radians(fsk.lx), np.radians(fsk.ly), mask_i.reshape([fsk.ny, fsk.nx]), [mask_i.reshape([fsk.ny, fsk.nx])], templates=None) if 'wl' in tr_j: field_j = nmt.NmtFieldFlat( np.radians(fsk.lx), np.radians(fsk.ly), mask_j.reshape([fsk.ny, fsk.nx]), [ mask_j.reshape([fsk.ny, fsk.nx]), mask_j.reshape([fsk.ny, fsk.nx]) ], templates=None) cl_theor_curr.append(np.zeros_like(cl_theor[i])) else: field_j = nmt.NmtFieldFlat(np.radians(fsk.lx), np.radians(fsk.ly), mask_j.reshape([fsk.ny, fsk.nx]), [mask_j.reshape([fsk.ny, fsk.nx])], templates=None) wsp_hi_curr = nmt.NmtWorkspaceFlat() wsp_hi_curr.compute_coupling_matrix(field_i, field_j, bpws_hi) msk_prod = mask_i * mask_j cl_cpld_curr = self.get_cl_cpld(cl_theor_curr, ell_theor, leff_hi, wsp_hi_curr, msk_prod) if noise_saccfile_coadd is not None: logger.info('Adding noise.') if tr_i == tr_j: if 'wl' in tr_i: datatype = 'cl_ee' else: datatype = 'cl_00' l_curr, nl_curr = noise_saccfile_coadd.get_ell_cl( datatype, tr_i, tr_j, return_cov=False) nl_curr_int = scipy.interpolate.interp1d( l_curr, nl_curr, bounds_error=False, fill_value=(nl_curr[0], nl_curr[-1])) nl_curr_hi = nl_curr_int(ell_theor) cl_cpld_curr += nl_curr_hi cl_cpld.append(cl_cpld_curr) # Add tracers to sacc saccfile_guess_spec = sacc.Sacc() for trc_name, trc in saccfile_coadd.tracers.items(): saccfile_guess_spec.add_tracer_object(trc) for i, (tr_i, tr_j) in enumerate(trc_combs): if 'wl' not in tr_i and 'wl' not in tr_j: saccfile_guess_spec.add_ell_cl('cl_00', tr_i, tr_j, ell_theor, cl_cpld[i]) elif ('wl' in tr_i and 'wl' not in tr_j) or ('wl' not in tr_i and 'wl' in tr_j): saccfile_guess_spec.add_ell_cl('cl_0e', tr_i, tr_j, ell_theor, cl_cpld[i]) saccfile_guess_spec.add_ell_cl('cl_0b', tr_i, tr_j, ell_theor, np.zeros_like(cl_cpld[i])) else: saccfile_guess_spec.add_ell_cl('cl_ee', tr_i, tr_j, ell_theor, cl_cpld[i]) saccfile_guess_spec.add_ell_cl('cl_eb', tr_i, tr_j, ell_theor, np.zeros_like(cl_cpld[i])) saccfile_guess_spec.add_ell_cl('cl_bb', tr_i, tr_j, ell_theor, np.zeros_like(cl_cpld[i])) return saccfile_coadd, noise_saccfile_coadd, saccfile_guess_spec
def mastest(wtemp, wpure, do_teb=False): prefix = "test/benchmarks/bm_f" if wtemp: prefix += "_yc" f0 = nmt.NmtFieldFlat(WT.lx, WT.ly, WT.msk, [WT.mps[0]], templates=[[WT.tmp[0]]]) f2 = nmt.NmtFieldFlat(WT.lx, WT.ly, WT.msk, [WT.mps[1], WT.mps[2]], templates=[[WT.tmp[1], WT.tmp[2]]], purify_b=wpure) else: prefix += "_nc" f0 = nmt.NmtFieldFlat(WT.lx, WT.ly, WT.msk, [WT.mps[0]]) f2 = nmt.NmtFieldFlat(WT.lx, WT.ly, WT.msk, [WT.mps[1], WT.mps[2]], purify_b=wpure) f = [f0, f2] if wpure: prefix += "_yp" else: prefix += "_np" for ip1 in range(2): for ip2 in range(ip1, 2): if ip1 == ip2 == 0: clth = np.array([WT.cltt]) nlth = np.array([WT.nltt]) elif ip1 == ip2 == 1: clth = np.array([WT.clee, 0*WT.clee, 0*WT.clbb, WT.clbb]) nlth = np.array([WT.nlee, 0*WT.nlee, 0*WT.nlbb, WT.nlbb]) else: clth = np.array([WT.clte, 0*WT.clte]) nlth = np.array([WT.nlte, 0*WT.nlte]) w = nmt.NmtWorkspaceFlat() w.compute_coupling_matrix(f[ip1], f[ip2], WT.b) clb = w.couple_cell(WT.ll, nlth) if wtemp: dlb = nmt.deprojection_bias_flat(f[ip1], f[ip2], WT.b, WT.ll, clth+nlth) tlb = np.loadtxt(prefix+'_cb%d%d.txt' % (2*ip1, 2*ip2), unpack=True)[1:, :] assert (np.fabs(dlb-tlb) <= np.fmin(np.fabs(dlb), np.fabs(tlb))*1E-5).all() clb += dlb cl = w.decouple_cell(nmt.compute_coupled_cell_flat(f[ip1], f[ip2], WT.b), cl_bias=clb) tl = np.loadtxt(prefix+'_c%d%d.txt' % (2*ip1, 2*ip2), unpack=True)[1:, :] assert (np.fabs(cl-tl) <= np.fmin(np.fabs(cl), np.fabs(tl))*1E-5).all() # TEB if do_teb: clth = np.array([WT.cltt, WT.clte, 0*WT.clte, WT.clee, 0*WT.clee, 0*WT.clbb, WT.clbb]) nlth = np.array([WT.nltt, WT.nlte, 0*WT.nlte, WT.nlee, 0*WT.nlee, 0*WT.nlbb, WT.nlbb]) w = nmt.NmtWorkspaceFlat() w.compute_coupling_matrix(f[0], f[1], WT.b, is_teb=True) c00 = nmt.compute_coupled_cell_flat(f[0], f[0], WT.b) c02 = nmt.compute_coupled_cell_flat(f[0], f[1], WT.b) c22 = nmt.compute_coupled_cell_flat(f[1], f[1], WT.b) cl = np.array([c00[0], c02[0], c02[1], c22[0], c22[1], c22[2], c22[3]]) t00 = np.loadtxt(prefix+'_c00.txt', unpack=True)[1:, :] t02 = np.loadtxt(prefix+'_c02.txt', unpack=True)[1:, :] t22 = np.loadtxt(prefix+'_c22.txt', unpack=True)[1:, :] tl = np.array([t00[0], t02[0], t02[1], t22[0], t22[1], t22[2], t22[3]]) cl = w.decouple_cell(cl, cl_bias=w.couple_cell(WT.ll, nlth)) assert (np.fabs(cl-tl) <= np.fmin(np.fabs(cl), np.fabs(tl))*1E-5).all()
else: ff0 = nmt.NmtFieldFlat(fmi.lx_rad, fmi.ly_rad, mask.reshape([fmi.ny, fmi.nx]), [st.reshape([fmi.ny, fmi.nx])]) ff2 = nmt.NmtFieldFlat( fmi.lx_rad, fmi.ly_rad, mask.reshape([fmi.ny, fmi.nx]), [sq.reshape([fmi.ny, fmi.nx]), su.reshape([fmi.ny, fmi.nx])]) return ff0, ff2 np.random.seed(1000) f0, f2 = get_fields() #Use initial fields to generate coupling matrix w00 = nmt.NmtWorkspaceFlat() if not os.path.isfile(prefix + "_w00.dat"): print("Computing 00") w00.compute_coupling_matrix(f0, f0, b) w00.write_to(prefix + "_w00.dat") else: w00.read_from(prefix + "_w00.dat") w02 = nmt.NmtWorkspaceFlat() if not os.path.isfile(prefix + "_w02.dat"): print("Computing 02") w02.compute_coupling_matrix(f0, f2, b) w02.write_to(prefix + "_w02.dat") else: w02.read_from(prefix + "_w02.dat") w22 = nmt.NmtWorkspaceFlat() if not os.path.isfile(prefix + "_w22.dat"):
def xcorr_flatsky(modedecomp=False, simkey="512_alfven3_0002_a_z", Imapkey="", deglen=10, apotype="C2", aposcale=0.5, Epure=True, Bpure=True): TQU = SimsTQU(fn=simkey, modedecomp=modedecomp, ikey=Imapkey) # Define flat-sky field # - Lx and Ly: the size of the patch in the x and y dimensions (in radians) Lx = deglen * np.pi / 180. # arbitrarily set this to a deglen x deglen deg box Ly = deglen * np.pi / 180. # - Nx and Ny: the number of pixels in the x and y dimensions Nx = 512 Ny = 512 # Define mask mask = np.ones_like(TQU.T).flatten() xarr = np.ones(Ny)[:, None] * np.arange(Nx)[None, :] * Lx / Nx yarr = np.ones(Nx)[None, :] * np.arange(Ny)[:, None] * Ly / Ny #Let's also trim the edges mask[np.where(xarr.flatten() < Lx / 16.)] = 0 mask[np.where(xarr.flatten() > 15 * Lx / 16.)] = 0 mask[np.where(yarr.flatten() < Ly / 16.)] = 0 mask[np.where(yarr.flatten() > 15 * Ly / 16.)] = 0 mask = mask.reshape([Ny, Nx]) mask = nmt.mask_apodization_flat(mask, Lx, Ly, aposize=aposcale, apotype=apotype) # Fields: # Once you have maps it's time to create pymaster fields. # Note that, as in the full-sky case, you can also pass # contaminant templates and flags for E and B purification # (see the documentation for more details) f0 = nmt.NmtFieldFlat(Lx, Ly, mask, [TQU.T]) f2 = nmt.NmtFieldFlat(Lx, Ly, mask, [TQU.Q, TQU.U], purify_b=Bpure, purify_e=Epure) # Bins: # For flat-sky fields, bandpowers are simply defined as intervals in ell, and # pymaster doesn't currently support any weighting scheme within each interval. l0_bins = np.arange(Nx / 8) * 8 * np.pi / Lx lf_bins = (np.arange(Nx / 8) + 1) * 8 * np.pi / Lx b = nmt.NmtBinFlat(l0_bins, lf_bins) # The effective sampling rate for these bandpowers can be obtained calling: ells_uncoupled = b.get_effective_ells() # Workspaces: # As in the full-sky case, the computation of the coupling matrix and of # the pseudo-CL estimator is mediated by a WorkspaceFlat case, initialized # by calling its compute_coupling_matrix method: w00 = nmt.NmtWorkspaceFlat() w00.compute_coupling_matrix(f0, f0, b) w02 = nmt.NmtWorkspaceFlat() w02.compute_coupling_matrix(f0, f2, b) w22 = nmt.NmtWorkspaceFlat() w22.compute_coupling_matrix(f2, f2, b) # Computing power spectra: # As in the full-sky case, you compute the pseudo-CL estimator by # computing the coupled power spectra and then decoupling them by # inverting the mode-coupling matrix. This is done in two steps below, # but pymaster provides convenience routines to do this # through a single function call cl00_coupled = nmt.compute_coupled_cell_flat(f0, f0, b) cl00_uncoupled = w00.decouple_cell(cl00_coupled) cl02_coupled = nmt.compute_coupled_cell_flat(f0, f2, b) cl02_uncoupled = w02.decouple_cell(cl02_coupled) cl22_coupled = nmt.compute_coupled_cell_flat(f2, f2, b) cl22_uncoupled = w22.decouple_cell(cl22_coupled) TT = cl00_uncoupled[0] TE = cl02_uncoupled[0] TB = cl02_uncoupled[1] EE = cl22_uncoupled[0] EB = cl22_uncoupled[1] BE = cl22_uncoupled[2] BB = cl22_uncoupled[3] if modedecomp: outroot = "/data/seclark/BlakesleySims/simdata/ModeDecomp/xcorrdata/" else: outroot = "/data/seclark/BlakesleySims/xcorrdata/" outfn = simkey + "_deglen{}_{}apod{}_EBpure{}{}.h5".format( deglen, apotype, aposcale, Epure, Bpure) with h5py.File(outroot + outfn, 'w') as f: TTdset = f.create_dataset(name='TT', data=TT) TEdset = f.create_dataset(name='TE', data=TE) TBdset = f.create_dataset(name='TB', data=TB) EEdset = f.create_dataset(name='EE', data=EE) EBdset = f.create_dataset(name='EB', data=EB) BEdset = f.create_dataset(name='BE', data=BE) BBdset = f.create_dataset(name='BB', data=BB) TTdset.attrs['deglen'] = deglen TTdset.attrs['Epure'] = Epure TTdset.attrs['Bpure'] = Bpure TTdset.attrs['ell_binned'] = ells_uncoupled