def test_b_sign(self): """ We generate a random IQU map with geometry such that cdelt[0]<0 We transform this to TEB with map2harm and map2alm followed by scalar harm2map and alm2map and use these as reference T,E,B maps. We flip the original map along the RA direction. We transform this to TEB with map2harm and map2alm followed by scalar harm2map and alm2map and use these as comparison T,E,B maps. We compare these maps. """ ells,cltt,clee,clbb,clte = np.loadtxt(DATA_PREFIX+"cosmo2017_10K_acc3_lensedCls.dat",unpack=True) ps_cmb = np.zeros((3,3,ells.size)) ps_cmb[0,0] = cltt ps_cmb[1,1] = clee ps_cmb[2,2] = clbb ps_cmb[1,0] = clte ps_cmb[0,1] = clte np.random.seed(100) # Curved-sky is fine lmax = 1000 alm = curvedsky.rand_alm_healpy(ps_cmb,lmax=lmax) shape,iwcs = enmap.fullsky_geometry(res=np.deg2rad(10./60.)) wcs = enmap.empty(shape,iwcs)[...,::-1].wcs shape = (3,) + shape imap = curvedsky.alm2map(alm,enmap.empty(shape,wcs)) oalm = curvedsky.map2alm(imap.copy(),lmax=lmax) rmap = curvedsky.alm2map(oalm,enmap.empty(shape,wcs),spin=0) imap2 = imap.copy()[...,::-1] oalm = curvedsky.map2alm(imap2.copy(),lmax=lmax) rmap2 = curvedsky.alm2map(oalm,enmap.empty(shape,wcs),spin=0) assert np.all(np.isclose(rmap[0],rmap2[0])) assert np.all(np.isclose(rmap[1],rmap2[1])) assert np.all(np.isclose(rmap[2],rmap2[2])) # Flat-sky px = 2.0 N = 300 shape,iwcs = enmap.geometry(pos=(0,0),res=np.deg2rad(px/60.),shape=(300,300)) shape = (3,) + shape a = enmap.zeros(shape,iwcs) a = a[...,::-1] wcs = a.wcs seed = 100 imap = enmap.rand_map(shape,wcs,ps_cmb,seed=seed) kmap = enmap.map2harm(imap.copy()) rmap = enmap.harm2map(kmap,spin=0) # reference map imap = imap[...,::-1] kmap = enmap.map2harm(imap.copy()) rmap2 = enmap.harm2map(kmap,spin=0)[...,::-1] # comparison map assert np.all(np.isclose(rmap[0],rmap2[0])) assert np.all(np.isclose(rmap[1],rmap2[1],atol=1e0)) assert np.all(np.isclose(rmap[2],rmap2[2],atol=1e0))
def __init__(self,camb_file='./CMB_fiducial_totalCls.dat',seed=1,pixRes_arcmin=4,lmax_sim=500): cls_camb = np.loadtxt(camb_file,unpack=True) cl_tt = cls_camb[1]/(cls_camb[0]*(cls_camb[0]+1)/2/np.pi) cl_tt = np.append([0,0],cl_tt) cl_ee = cls_camb[2]/(cls_camb[0]*(cls_camb[0]+1)/2/np.pi) cl_ee = np.append([0,0],cl_ee) cl_bb = cls_camb[3]/(cls_camb[0]*(cls_camb[0]+1)/2/np.pi)*0.05 cl_bb = np.append([0,0],cl_bb) cl_te = cls_camb[4]/(cls_camb[0]*(cls_camb[0]+1)/2/np.pi) cl_te = np.append([0,0],cl_te) ells = np.append([0,1],cls_camb[0]) self.pixRes_arcmin=pixRes_arcmin/180./60*np.pi self.lmax_sim = lmax_sim shape,wcs = enmap.fullsky_geometry(self.pixRes_arcmin,dims=(2,)) np.random.seed(seed) self.shape = shape self.wcs = wcs self.alm_cmb_E = curvedsky.rand_alm(cl_ee,lmax=lmax_sim)#hp.synalm(cl_ee,lmax=3*nside-1,new=True) self.alm_cmb_B = curvedsky.rand_alm(cl_bb,lmax=lmax_sim)#hp.synalm(cl_bb,lmax=3*nside-1,new=True) tmp_empty = enmap.empty(shape,wcs) self.Q_cmb,self.U_cmb = curvedsky.alm2map(np.array([self.alm_cmb_E,self.alm_cmb_B]),tmp_empty,spin=[2]) ps = np.zeros([2,2,lmax_sim]) ps[0,0] = synchrotron_Cl('E','E')[:lmax_sim] ps[1,1] = galaticDust_Cl('E','E')[:lmax_sim] ps[1,0] = syncxdust_Cls('E','E')[:lmax_sim] self.alm_sync_E,self.alm_dust_E = curvedsky.rand_alm(ps,lmax=lmax_sim) ps = np.zeros([2,2,lmax_sim]) ps[0,0] = synchrotron_Cl('B','B')[:lmax_sim] ps[1,1] = galaticDust_Cl('B','B')[:lmax_sim] ps[1,0] = syncxdust_Cls('B','B')[:lmax_sim] self.alm_sync_B,self.alm_dust_B = curvedsky.rand_alm(ps,lmax=lmax_sim) tmp_empty = enmap.empty(shape,wcs) self.Q_dust,self.U_dust = curvedsky.alm2map(np.array([self.alm_dust_E,self.alm_dust_B]),tmp_empty,spin=[2]) tmp_empty = enmap.empty(shape,wcs) self.Q_sync,self.U_sync = curvedsky.alm2map(np.array([self.alm_sync_E,self.alm_sync_B]),tmp_empty,spin=[2])
def __init__(self,camb_file='./CMB_fiducial_totalCls.dat',seed=1,pixRes_arcmin=2.,lmax_sim=500,nside_pysm=512): cls_camb = np.loadtxt(camb_file,unpack=True) cl_tt = cls_camb[1]/(cls_camb[0]*(cls_camb[0]+1)/2/np.pi) cl_tt = np.append([0,0],cl_tt) cl_ee = cls_camb[2]/(cls_camb[0]*(cls_camb[0]+1)/2/np.pi) cl_ee = np.append([0,0],cl_ee) cl_bb = cls_camb[3]/(cls_camb[0]*(cls_camb[0]+1)/2/np.pi) cl_bb = np.append([0,0],cl_bb) cl_te = cls_camb[4]/(cls_camb[0]*(cls_camb[0]+1)/2/np.pi) cl_te = np.append([0,0],cl_te) ells = np.append([0,1],cls_camb[0]) self.pixRes_arcmin=pixRes_arcmin/180./60*np.pi self.lmax_sim = lmax_sim shape,wcs = enmap.fullsky_geometry(self.pixRes_arcmin,dims=(2,)) self.shape = shape self.wcs = wcs np.random.seed(seed) self.nside_pysm =nside_pysm self.alm_cmb_E = curvedsky.rand_alm(cl_ee,lmax=lmax_sim)#hp.synalm(cl_ee,lmax=3*nside-1,new=True) self.alm_cmb_B = curvedsky.rand_alm(cl_bb,lmax=lmax_sim)#hp.synalm(cl_bb,lmax=3*nside-1,new=True) tmp_empty = enmap.empty(shape,wcs) self.Q_cmb,self.U_cmb = curvedsky.alm2map(np.array([self.alm_cmb_E,self.alm_cmb_B]),tmp_empty,spin=[2])
def get_lensed_cmb(self, seed=None, kappa=None, save_output=True, verbose=True, overwrite=False, dtype=np.float64): try: assert(seed is not None) assert(not overwrite) if verbose: print(f"trying to load saved lensed cmb. sim idx: {seed}") lmaps = enmap.empty((3,)+self.shape, self.wcs, dtype=dtype) for i, polidx in enumerate(['T','Q','U']): fname = self.get_output_file_name("lensed_cmb", seed, polidx=polidx) lmaps[i] = enmap.read_map(fname) except: ualm = self._generate_unlensed_cmb_alm(seed=seed) if kappa is None: kappa = self._get_kappa(seed, dtype=np.float64) lmax = 10000 l = np.arange(lmax+1) l_fact = 1/((l*(l+1))/2) l_fact[0] = 0 kalm = curvedsky.map2alm(kappa, lmax=lmax) kalm = curvedsky.map2alm(kappa, lmax=lmax); del kappa kalm = hp.almxfl(kalm, l_fact) tshape, twcs = enmap.fullsky_geometry(res=1*utils.arcmin) print("start lensing") lmaps = lensing.lens_map_curved((3,)+tshape, twcs, kalm, ualm)[0] lalms = curvedsky.map2alm(lmaps, lmax=lmax, spin=0) lmaps = curvedsky.alm2map(lalms, enmap.zeros((3,)+self.shape, self.wcs), spin=0) print("finish lensing") if save_output: for i, polidx in enumerate(['T','Q','U']): fname = self.get_output_file_name("lensed_cmb", seed, polidx=polidx) os.makedirs(os.path.dirname(fname), exist_ok=True) enmap.write_map(fname, lmaps[i].astype(np.float32)) return lmaps.astype(dtype)
def rand_map(shape, wcs, ps_lensinput, doRotation=False, ps_rot=None, lmax=None, maplmax=None, dtype=np.float64, seed=None, phi_seed=None, oversample=2.0, spin=[0,2], output="l", geodesic=True, verbose=False, delta_theta=None): from pixell import curvedsky, sharp ctype = np.result_type(dtype,0j) # Restrict to target number of components oshape = shape[-3:] if len(oshape) == 2: shape = (1,)+tuple(shape) ncomp = shape[-3] ps_lensinput = ps_lensinput[:1+ncomp,:1+ncomp] # First draw a random lensing field, and use it to compute the undeflected positions if verbose: print("Generating alms") if phi_seed is None: alm, ainfo = curvedsky.rand_alm(ps_lensinput, lmax=lmax, seed=seed, dtype=ctype, return_ainfo=True) else: # We want separate seeds for cmb and phi. This means we have to do things a bit more manually wps, ainfo = curvedsky.prepare_ps(ps_lensinput, lmax=lmax) alm = np.empty([1+ncomp,ainfo.nelem],ctype) curvedsky.rand_alm_white(ainfo, alm=alm[:1], seed=phi_seed) curvedsky.rand_alm_white(ainfo, alm=alm[1:], seed=seed) ps12 = enmap.multi_pow(wps, 0.5) ainfo.lmul(alm, (ps12/2**0.5).astype(dtype), alm) alm[:,:ainfo.lmax].imag = 0 alm[:,:ainfo.lmax].real *= 2**0.5 del wps, ps12 phi_alm, cmb_alm = alm[0], alm[1:] if doRotation: # generate a gaussian random field of rotational field alpha_shape = (1, shape[-2], shape[-1]) alpha_map = curvedsky.rand_map(alpha_shape, wcs, ps_rot, lmax=lmax) # convert alm to enmap object cmb_map = enmap.empty((3,shape[-2],shape[-1]), wcs) curvedsky.alm2map(cmb_alm, cmb_map) # rotate tqu map by a rotational field # Q_map = cmb_map[1] # U_map = cmb_map[2] cmb_map_rot = enmap.rotate_pol(cmb_map, alpha_map) # convert tqu map back to the alm cmb_alm = curvedsky.map2alm(cmb_map_rot, lmax=lmax) del alpha_map, cmb_map, cmb_map_rot del alm # Truncate alm if we want a smoother map. In taylens, it was necessary to truncate # to a lower lmax for the map than for phi, to avoid aliasing. The appropriate lmax # for the cmb was the one that fits the resolution. FIXME: Can't slice alm this way. #if maplmax: cmb_alm = cmb_alm[:,:maplmax] return lens_map_curved(shape=shape, wcs=wcs, phi_alm=phi_alm, cmb_alm=cmb_alm, phi_ainfo=ainfo, maplmax=maplmax, dtype=dtype, oversample=oversample, spin=spin, output=output, geodesic=geodesic, verbose=verbose, delta_theta=delta_theta)
def get_map(self,seed=None): """Get correlated galaxy and kappa map """ from pixell import curvedsky alms = curvedsky.rand_alm_healpy(self.ps, lmax=int(self.lmax)+1, seed=seed) ncomp = 1 if len(self.shape)==2 else self.shape[0] omap = enmap.empty((ncomp,)+self.shape[-2:], self.wcs, dtype=np.float64) omap = curvedsky.alm2map(alms, omap, spin=0) return alms,omap
def get_template(self, patch, shape, wcs): template = None if patch not in self.templates: self.templates[patch] = enmap.empty((3, ) + shape[-2:], wcs) template = self.templates[patch].copy() self.manage_cache(self.templates, self.max_cached) else: template = self.templates[patch].copy() return template
def alm2map(self,alm,spin,ncomp,mlmax): if self.hpix: if spin!=0: res = hp.alm2map_spin(alm,nside=self.nside,spin=spin,lmax=mlmax) return res else: # complex64 not supported here return hp.alm2map(alm.astype(np.complex128),nside=self.nside,pol=False)[None] else: omap = enmap.empty((ncomp,)+self.shape,self.wcs,dtype=self.dtype) return cs.alm2map(alm,omap,spin=spin)
def compute_output_map(self, alm): if self.nside is None: assert (self.shape is not None) and (self.wcs is not None) n_comp = 3 if self.has_polarization else 1 output_map = enmap.empty((n_comp,) + self.shape[-2:], self.wcs) curvedsky.alm2map(alm, self.output_map, spin=[0, 2], verbose=True) elif self.nside is not None: output_map = hp.alm2map(alm, self.nside) else: raise ValueError("You must specify either nside or both of shape and wcs") return output_map
def get_foreground(self, seed=None, freq=148, verbose=True, input_kappa=None, post_processes=[], save_output=True, flux_cut=7, polfix=True, dtype=np.float64, fgmaps_148=None, overwrite=False): assert(freq in self.freqs) try: assert(seed is not None) assert(not overwrite) if verbose: print(f"trying to load saved foregrounds. sim idx: {seed}, freq: {freq}GHz") fgmaps = enmap.empty((5,)+self.shape, self.wcs, dtype=dtype) for i, compt_idx in reversed(list(enumerate(self.fg_compts))): fname = self.get_output_file_name(compt_idx, seed, freq=freq) fgmaps[i] = enmap.read_map(fname) except: if verbose: print(f"generating foregrounds. sim idx: {seed}, freq: {freq}GHz") fgmaps = None if fgmaps_148 is not None: fgmaps = fgmaps_148.copy() if freq == 148 and fgmaps is None: fgmaps = self._generate_foreground_148GHz(seed=seed, verbose=verbose, input_kappa=input_kappa, post_processes=post_processes, flux_cut=flux_cut, polfix=polfix) else: if fgmaps_148 is None: fgmaps = self.get_foreground(seed=seed, freq=148, verbose=verbose, input_kappa=input_kappa, post_processes=post_processes, save_output=save_output, flux_cut=flux_cut, polfix=polfix, dtype=np.float32) fgmaps[2] *= fnu(freq)/fnu(148) for i in [3,4]: compt_idx = self.fg_compts[i] spec_index = self._get_spectral_index(seed=seed, compt_idx=self.fg_compts[i], freq=freq) fgmaps[i] *= thermo2jysr(148)*(freq/148)**spec_index*jysr2thermo(freq); del spec_index if save_output: for i, compt_idx in enumerate(self.fg_compts): fname = self.get_output_file_name(compt_idx, seed, freq=freq) if os.path.exists(fname) and not overwrite: continue os.makedirs(os.path.dirname(fname), exist_ok=True) enmap.write_map(fname, fgmaps[i].astype(np.float32)) return fgmaps.astype(dtype)
def alm2map_spin(self,alm,spin_alm,spin_transform,ncomp,mlmax): """ Returns X(n) = sum_lm alm_s1 s2_Y_lm(n) where s1=spin_alm and s2=spin_transform are different spins. alm should be (alm_+|s|, alm_-|s|) """ # Transform (alm_+|s|, alm_-|s|) to (alm_+, alm_-) ap_am = irot2d(alm,spin=spin_alm) if self.hpix: res = hp.alm2map_spin(ap_am,nside=self.nside,spin=abs(spin_transform),lmax=mlmax) else: omap = enmap.empty((ncomp,)+self.shape[-2:],self.wcs,dtype=self.dtype) res = cs.alm2map(ap_am,omap,spin=abs(spin_transform)) # Rotate maps M+ and M- to M_+|s| and M_-|s| # M_+|s| is the first component # M_-|s| is the second component return rot2d(res)
def compute_output_map(self, alm): lmax = hp.Alm.getlmax(alm.shape[-1]) # we assume mmax = lmax if self.nside is None: assert (self.shape is not None) and (self.wcs is not None) n_comp = 3 if self.has_polarization else 1 output_map = enmap.empty((n_comp, ) + self.shape[-2:], self.wcs) curvedsky.alm2map(alm, output_map, spin=[0, 2], verbose=True) elif self.nside is not None: if lmax > 3 * self.nside - 1: clip = np.ones(3 * self.nside) if alm.ndim == 1: alm_clipped = hp.almxfl(alm, clip) else: alm_clipped = [hp.almxfl(each, clip) for each in alm] else: alm_clipped = alm output_map = hp.alm2map(alm_clipped, self.nside) else: raise ValueError( "You must specify either nside or both of shape and wcs") return (output_map << self.input_units).to( u.uK_CMB, equivalencies=self.equivalencies)
def load_alms_base(self, set_idx, sim_idx, cache=True, fg_override=None, ret_alm=False, fgflux="15mjy", alm_file_postfix=''): # note: beam is set to false print("loading alm base") #cmb_file = os.path.join(self.signal_path, 'fullsky%s_alm_set%02d_%05d%s.fits' %(self.cmb_type, set_idx, 0, alm_file_postfix)) alm_signal = self.load_cmb_alm(set_idx, sim_idx, alm_file_postfix) # check if rotation is needed if self.apply_rotation: if not np.any(self.alpha_map): print( "[Warning] want to apply rotation but alpha map is not provided..." ) else: alpha_map = self.alpha_map print("applying rotation field") # get wcs from rot_map: doesn't matter which wcs is used because eventually # it is converted back to alm wcs = alpha_map.wcs shape = (3, ) + alpha_map.shape[-2:] # generate cmb map from alm_signal cmb_map = enmap.empty(shape, wcs) curvedsky.alm2map(alm_signal, cmb_map) # apply the rotation field cmb_map = enmap.rotate_pol(cmb_map, 2 * alpha_map) # convert back to alm lmax = hp.Alm.getlmax(alm_signal.shape[-1]) alm_signal = curvedsky.map2alm(cmb_map, lmax=lmax) del cmb_map alm_signal = np.tile(alm_signal, (len(self.freqs), 1, 1)) if fg_override is not None: print("[Warning] override the default foreground flag....") add_foregrounds = fg_override if fg_override is not None else self.add_foregrounds if add_foregrounds: print("adding fgs to the base") alm_fg90_150 = self.load_alm_fg(set_idx, sim_idx, fgflux=fgflux) lmax_sg = hp.Alm.getlmax(alm_signal.shape[-1]) alm_out = np.zeros((len(self.freqs), 3, len(alm_fg90_150[-1])), dtype=np.complex128) lmax_fg = hp.Alm.getlmax(alm_fg90_150.shape[-1]) for idx, freq in enumerate(self.freqs): freq_idx = 1 if freq == 'f150' else 0 alm_out[idx, 0, :] = alm_fg90_150[freq_idx, :].copy() for m in range(lmax_sg + 1): lmin = m lmax = lmax_sg idx_ssidx = hp.Alm.getidx(lmax_sg, lmin, m) idx_seidx = hp.Alm.getidx(lmax_sg, lmax, m) idx_fsidx = hp.Alm.getidx(lmax_fg, lmin, m) idx_feidx = hp.Alm.getidx(lmax_fg, lmax, m) alm_out[..., idx_fsidx:idx_feidx + 1] = alm_out[..., idx_fsidx:idx_feidx + 1] + alm_signal[..., idx_ssidx:idx_seidx + 1] alm_signal = alm_out.copy() del alm_out, alm_fg90_150 if cache: self.alms_base[self.get_base_alm_idx(set_idx, sim_idx)] = alm_signal.copy() if ret_alm: return alm_signal del alm_signal
cov = maps.symmat_from_data(cov) tcmb = 2.726e6 yresponses = tfg.get_mix(freqs, "tSZ") cresponses = tfg.get_mix(freqs, "CMB") dresponses = tfg.get_mix(freqs, "CIB") responses = {'tsz': yresponses, 'cmb': cresponses, 'dust': dresponses} ilcgen = ilc.chunked_ilc(modlmap, np.stack(kbeams), cov, chunk_size, responses=responses, invert=True) snoise = enmap.empty((Ny * Nx), wcs) cnoise = enmap.empty((Ny * Nx), wcs) smap = enmap.empty((Ny * Nx), wcs, dtype=np.complex128) cmap = enmap.empty((Ny * Nx), wcs, dtype=np.complex128) ysmap = enmap.empty((Ny * Nx), wcs, dtype=np.complex128) ycmap = enmap.empty((Ny * Nx), wcs, dtype=np.complex128) ycmap_d = enmap.empty((Ny * Nx), wcs, dtype=np.complex128) ycmap_dc = enmap.empty((Ny * Nx), wcs, dtype=np.complex128) kcoadds = kcoadds.reshape((len(c.arrays), Ny * Nx)) for chunknum, (hilc, selchunk) in enumerate(ilcgen): print("ILC on chunk ", chunknum + 1, " / ", int(modlmap.size / chunk_size) + 1, " ...") snoise[selchunk] = hilc.standard_noise("cmb") cnoise[selchunk] = hilc.constrained_noise("cmb", "tsz") smap[selchunk] = hilc.standard_map(kcoadds[..., selchunk], "cmb") cmap[selchunk] = hilc.constrained_map(kcoadds[..., selchunk], "cmb", "tsz")
fshape, fwcs = enmap.fullsky_geometry(res=px * utils.arcmin, proj='car') imap = f'{my_sim_path}/kap_lt4.5.fits' kmap = reproject.enmap_from_healpix(imap, fshape, fwcs, ncomp=1, unit=1, lmax=6000, rot=None) print(kmap.shape) filename = f'{my_sim_path}/lensed_alm.fits' alm = np.complex128(hp.read_alm(filename, hdu=(1, 2, 3))) #print(alm.shape) (3, 34043626) ncomp = 1 omap = enmap.empty((ncomp, ) + fshape[-2:], fwcs, dtype=np.float64) lmap = curvedsky.alm2map(alm, omap, spin=[0, 2], oversample=2.0, method="auto") print(lmap.shape) tap_per = 12.0 pad_per = 3.0 fwhm = 1.4 nlevel = 20 xlmin = 200 xlmax = 2000 ylmin = 200 ylmax = 6000 ylcut = 2 klmin = 200
def hdowngrade(imap, shape, wcs, lmax): return (cs.alm2map(cs.map2alm(imap, lmax=lmax), enmap.empty(shape, wcs, dtype=imap.dtype)))
pl.add(ls,nls,ls="--",label='theory noise per mode') pl._ax.set_xlim(20,4000) pl.done(config['data_path']+"xcls_%s.png" % polcomb) # Filtered input fikalm = hp.almxfl(ikalm,wfilt) fimap = hp.alm2map(fikalm,nside=256) # Resampled mask dmask = hp.ud_grade(mask,nside_out=256) dmask[dmask<0] = 0 # Mollview plots io.mollview(frmap*dmask,config['data_path']+"wrmap1.png",xsize=1600,lim=8e-6) io.mollview(fimap*dmask,config['data_path']+"wimap1.png",xsize=1600,lim=8e-6) # CAR plots shape,wcs = enmap.band_geometry(np.deg2rad((-70,30)),res=np.deg2rad(0.5*8192/512/60.)) omask = reproject.enmap_from_healpix(dmask, shape, wcs,rot=None) omap = cs.alm2map(fkalm, enmap.empty(shape,wcs)) io.hplot(omap*omask,config['data_path']+"cwrmap1",grid=True,ticks=20,color='gray') omap = cs.alm2map(fikalm, enmap.empty(shape,wcs)) io.hplot(omap*omask,config['data_path']+"cwimap1",grid=True,ticks=20,color='gray')
ikmaps = np.stack(ikmaps) # ikmaps[:,modlmap>lmax1] = 0 inkmaps = np.stack(inkmaps) # inkmaps[:,modlmap>lmax1] = 0 ilcgen = ilc.chunked_ilc(modlmap, np.stack(tsim.kbeams), covfunc, chunk_size, responses={ 'tsz': yresponses, 'cmb': cresponses }, invert=invert) yksilc = enmap.empty((Ny, Nx), wcs, dtype=np.complex128).reshape(-1) ynksilc = enmap.empty((Ny, Nx), wcs, dtype=np.complex128).reshape(-1) ykcilc = enmap.empty((Ny, Nx), wcs, dtype=np.complex128).reshape(-1) ynkcilc = enmap.empty((Ny, Nx), wcs, dtype=np.complex128).reshape(-1) cksilc = enmap.empty((Ny, Nx), wcs, dtype=np.complex128).reshape(-1) cnksilc = enmap.empty((Ny, Nx), wcs, dtype=np.complex128).reshape(-1) ckcilc = enmap.empty((Ny, Nx), wcs, dtype=np.complex128).reshape(-1) cnkcilc = enmap.empty((Ny, Nx), wcs, dtype=np.complex128).reshape(-1) kmaps = ikmaps.reshape((narrays, Ny * Nx)) nkmaps = inkmaps.reshape((narrays, Ny * Nx)) for chunknum, (hilc, selchunk) in enumerate(ilcgen): print("ILC on chunk ", chunknum + 1, " / ", int(modlmap.size / chunk_size) + 1, " ...") yksilc[selchunk] = hilc.standard_map(kmaps[..., selchunk], "tsz")
def getActpolCmbFgSim(beamfileDict, shape, wcs, iterationNum, cmbDir, freqs, psa, cmbSet = 0, \ doBeam = True, applyWindow = True, verbose = True, cmbMaptype = 'LensedCMB', foregroundSeed = 0, simType = 'cmb', foregroundPowerFile = None, applyModulation = True): nTQUs = len('TQU') firstTime = True output = enmap.empty(( len(freqs), nTQUs, ) + shape[-2:], wcs) if simType == 'cmb': filename = cmbDir + "/fullsky%s_alm_set%02d_%05d.fits" % ( cmbMaptype, cmbSet, iterationNum) if verbose: print('getActpolCmbFgSim(): loading CMB a_lms from %s' % filename) import healpy almTebFullskyOnecopy = np.complex128( healpy.fitsfunc.read_alm(filename, hdu=(1, 2, 3))) #Now tile the same for all the frequencies requested (i.e. CMB is same at all frequencies). #The beam convolution happens below. almTebFullsky = np.tile(almTebFullskyOnecopy, (len(freqs), 1, 1)) if verbose: print('getActpolCmbFgSim(): done') elif simType == 'foregrounds': outputFreqs = ['f090', 'f150'] foregroundPowers \ = powspec.read_spectrum(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../data/', foregroundPowerFile), ncol = 3, expand = 'row') if verbose: print('getActpolCmbFgSim(): getting foreground a_lms') almTFullsky90and150 = curvedsky.rand_alm(foregroundPowers, seed=foregroundSeed) almTebFullsky = np.zeros(( len(freqs), nTQUs, ) + (len(almTFullsky90and150[-1]), ), dtype=np.complex128) for fi, freq in enumerate(freqs): if freq in outputFreqs: almTebFullsky[fi, 'TQU'.index('T'), :] \ = almTFullsky90and150[outputFreqs.index(freq), :] #Convolve with beam on full sky for fi, freq in enumerate(freqs): if doBeam: beamFile = beamfileDict[psa + '_' + freq] if verbose: print('getActpolCmbFgSim(): applying beam from %s' % beamFile) beamData = (np.loadtxt(beamFile))[:, 1] else: if verbose: print('getActpolCmbFgSim(): not convolving with beam') beamData = np.repeat(1., almTebFullsky.shape[-1]) import healpy #couldn't quickly figure out how to vectorize this so loop from 0 to 2. for tqui in range(nTQUs): almTebFullsky[fi, tqui] = healpy.sphtfunc.almxfl( almTebFullsky[fi, tqui].copy(), beamData) #These lines stolen from curvedsky.rand_map #doing all freqs at once gives error: #sharp.pyx in sharp.execute_dp (cython/sharp.c:12118)() #ValueError: ndarray is not C-contiguous #so loop over all freqs once for now. curvedsky.alm2map(almTebFullsky, output, spin=[0, 2], verbose=True) # outputThisfreq = enmap.empty(( nTQUs,)+shape[-2:], wcs) # curvedsky.alm2map(almTebFullsky[fi,:,:], outputThisfreq, spin = [0,2], verbose = True) # output[fi,...] = outputThisfreq # curvedsky.alm2map(almTebFullsky[fi,:,:], output[fi,:,:,:], spin = [0,2], verbose = True) if applyModulation: from pixell import aberration for fi, freq in enumerate(freqs): print('applying modulation for frequency %s' % freq) output, A = aberration.boost_map(output, aberration.dir_equ, aberration.beta, return_modulation=True, aberrate=False, freq=freqStrToValGhz[freq] * 1e9) if applyWindow: from pixell import fft #The axes along which to FFT axes = [-2, -1] if verbose: print('getActpolCmbFgSim(): applying pixel window function') nfreq = len(freqs) for idx in range(nfreq): fd = fft.fft(output[idx], axes=axes) wy, wx = enmap.calc_window(fd.shape) twoDWindow = wy[:, None]**1 * wx[None, :]**1 #Careful, this is quietly multiplying an array with shape [N_freq, N_TQU, N_y, N_x] with one of shape [N_y, N_x] fd *= twoDWindow output[idx] = (fft.ifft(fd, axes=axes, normalize=True)).real del fd if verbose: print('getActpolCmbFgSim(): done') return enmap.ndmap(output, wcs)