Example #1
0
def rand_map(shape,
             wcs,
             ps_lensinput,
             lmax=None,
             maplmax=None,
             dtype=np.float64,
             seed=None,
             oversample=2.0,
             spin=2,
             output="l",
             geodesic=True,
             verbose=False):
    ctype = np.result_type(dtype, 0j)
    # First draw a random lensing field, and use it to compute the undeflected positions
    if verbose: print "Computing observed coordinates"
    obs_pos = enmap.posmap(shape, wcs)
    if verbose: print "Generating alms"
    alm = curvedsky.rand_alm(ps_lensinput, lmax=lmax, seed=seed, dtype=ctype)
    phi_alm, cmb_alm = alm[0], alm[1:]
    # 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]
    del alm
    if "p" in output:
        if verbose: print "Computing phi map"
        phi_map = curvedsky.alm2map(phi_alm,
                                    enmap.zeros(shape[-2:], wcs, dtype=dtype))
    if verbose: print "Computing grad map"
    grad = curvedsky.alm2map(phi_alm,
                             enmap.zeros((2, ) + shape[-2:], wcs, dtype=dtype),
                             deriv=True)
    if verbose: print "Computing alpha map"
    raw_pos = enmap.samewcs(
        offset_by_grad(obs_pos, grad, pol=True, geodesic=geodesic), obs_pos)
    del obs_pos, phi_alm
    if "a" not in output: del grad
    if "u" in output:
        if verbose: print "Computing unlensed map"
        cmb_raw = curvedsky.alm2map(cmb_alm,
                                    enmap.zeros(shape, wcs, dtype=dtype),
                                    spin=spin)
    if verbose: print "Computing lensed map"
    cmb_obs = curvedsky.alm2map_pos(cmb_alm,
                                    raw_pos[:2],
                                    oversample=oversample,
                                    spin=spin)
    if raw_pos.shape[0] > 2 and np.any(raw_pos[2]):
        if verbose: print "Rotating polarization"
        cmb_obs = enmap.rotate_pol(cmb_obs, raw_pos[2])
    del cmb_alm, raw_pos
    # Output in same order as specified in output argument
    res = []
    for c in output:
        if c == "l": res.append(cmb_obs)
        elif c == "u": res.append(cmb_raw)
        elif c == "p": res.append(phi_map)
        elif c == "a": res.append(grad)
    return tuple(res)
def get_sim(sim_idx, beam_fwhm=beam_fwhm, noise_level=noise_level):
    ret = act_sim.getActpolCmbSim(None,
                                  coords,
                                  sim_idx,
                                  cmb_dir,
                                  doBeam=False,
                                  pixelFac=1)

    np.random.seed(sim_idx)

    # handle mean
    for i in range(len(ret)):
        ret[i].data -= np.mean(ret[i].data)
        ret[i] = enmap.from_flipper(ret[i])

    # beam convolve
    owcs, shape = (ret[0].wcs.copy(), ret[0].shape)
    tqu = np.zeros((3, ) + ret[0].shape)
    tqu[0], tqu[1], tqu[2] = (ret[0], ret[1], ret[2])
    tqu = enmap.enmap(tqu, owcs)
    alm = curvedsky.map2alm(tqu, lmax=lmax)
    del ret

    _, beam = cmblens.theory.get_gauss_beam(np.arange(lmax + 1), beam_fwhm)
    fl = np.sqrt(beam)

    log.info("beam convolution")
    for i in range(alm.shape[0]):
        alm[i] = hp.sphtfunc.almxfl(alm[i], fl)

    tqu = curvedsky.alm2map(alm[:, None], tqu.copy()[:, None])[:, 0]

    if noise_level > 0:
        log.info("adding noise")
        for i in range(len(tqu)):
            noise = enmap.to_flipper(tqu[i]).getTemplate()
            l_n = np.arange(lmax + 1000)
            noise_fact = 1. if i == 0 else np.sqrt(2)
            nl = cmblens.theory.get_white_noise_power(l_n,
                                                      noise_level * noise_fact)
            ps = nl.reshape((1, 1, nl.size))
            noise = curvedsky.rand_map(shape, owcs, ps, lmax=(lmax + 1000))
            #noise.fillWithGaussianRandomField(l_n, nl, bufferFactor=1)
            tqu[i] += noise
            del noise

    # beam deconvolve
    log.info("beam deconvolution")
    alm = curvedsky.map2alm(tqu, lmax=lmax)
    for i in range(alm.shape[0]):
        alm[i] = hp.sphtfunc.almxfl(alm[i], 1. / fl)
    tqu = curvedsky.alm2map(alm[:, None], tqu.copy()[:, None])[:, 0]

    return (tqu[0], tqu[1], tqu[2])  # TQU
def tqu2teb(tmap, qmap, umap):
    tqu = np.zeros((3, ) + tmap.shape)
    tqu[0], tqu[1], tqu[2] = (tmap, qmap, umap)
    tqu = enmap.enmap(tqu, tmap.wcs)
    alm = curvedsky.map2alm(tqu, lmax=lmax)

    teb = curvedsky.alm2map(alm[:, None], tqu.copy()[:, None], spin=0)[:, 0]
    del tqu

    return (teb[0], teb[1], teb[2])
Example #4
0
		if args.rot and ncomp==3:
			L.debug("Rotating polarization vectors")
			res[1:3] = enmap.rotate_pol(res[1:3], psi)
	else:
		# We will project directly onto target map if possible
		if args.rot:
			L.debug("Rotating alms")
			s1,s2 = args.rot.split(",")
			if s1 != s2:
				# Note: rotate_alm does not actually modify alm
				# if it is single precision
				alm = alm.astype(np.complex128,copy=False)
				if s1 == "gal" and (s2 == "equ" or s2 == "cel"):
					healpy.rotate_alm(alm, euler[0], euler[1], euler[2])
				elif s2 == "gal" and (s1 == "equ" or s1 == "cel"):
					healpy.rotate_alm(alm,-euler[2],-euler[1],-euler[0])
				else:
					raise NotImplementedError
				alm = alm.astype(ctype,copy=False)
		L.debug("Projecting")
		res = enmap.zeros((len(alm),)+shape[-2:], wcs, dtype)
		res = curvedsky.alm2map(alm, res)
	if len(args.templates) > 1:
		oname = args.odir + "/" + os.path.basename(tfile)
	else:
		oname = args.ofile
	if args.oslice:
		res = eval("res"+args.oslice)
	L.info("Writing " + oname)
	enmap.write_map(oname, res)
Example #5
0
def rand_map_curved(shape,
                    wcs,
                    ps,
                    lmax=None,
                    lens=True,
                    aberrate=True,
                    beta=None,
                    dir=None,
                    seed=None,
                    dtype=None,
                    verbose=False,
                    recenter=False):
    """Simulate a random curved-sky map. The input spectrum should be
	[{phi,T,E,B},{phi,T,E,b},nl] of lens is True, and just [{T,E,B},{T,E,B},nl]
	otherwise."""
    if dtype is None: dtype = np.float64
    if dir is None: dir = aberration.dir_equ
    if beta is None: beta = aberration.beta
    ctype = np.result_type(dtype, 0j)

    if verbose: print "Generating alms"
    alm = curvedsky.rand_alm(ps, lmax=lmax, seed=seed, dtype=ctype)
    # Before any corrections are applied, the pixel positions map
    # directly to the raw cmb positions, and there is no induced polarization
    # rotation or amplitude modulation.
    if verbose: print "Computing observed coordinates"
    pos = enmap.posmap(shape, wcs)
    ang = enmap.zeros(shape[-2:], wcs)
    amp = enmap.zeros(shape[-2:], wcs) + 1
    # Lensing remaps positions
    if lens:
        phi_alm, alm = alm[0], alm[1:]
        if verbose: print "Computing lensing gradient"
        grad = curvedsky.alm2map(phi_alm,
                                 enmap.zeros((2, ) + shape[-2:],
                                             wcs,
                                             dtype=dtype),
                                 deriv=True)
        del phi_alm
        if verbose: print "Applying lensing gradient"
        pos = enmap.samewcs(
            lensing.offset_by_grad(pos, grad, pol=True, geodesic=True), pos)
        ang += pos[2]
    # Aberration remaps positions and modulates amplitudes
    if aberrate:
        if verbose: print "Computing aberration"
        pos = enmap.samewcs(
            aberration.remap(pos[1::-1], dir=dir, beta=beta,
                             recenter=recenter), pos)
        ang += pos[2]
        amp *= pos[3]
        pos = pos[1::-1]
    # Simulate the sky at the observed locations
    if verbose: print "Simulating sky signal"
    map = curvedsky.alm2map_pos(alm, pos)
    del alm, pos
    # Apply polarization rotation
    if verbose: print "Applying polarization rotation"
    map = enmap.rotate_pol(map, ang)
    # and modulation
    if verbose: print "Applying mouldation"
    map *= amp
    return map
Example #6
0
mg = enmap.MapGen(shape,wcs,p2d.reshape(1,1,modlmap.shape[0],modlmap.shape[1]))
imap = mg.get_map()

io.quickPlot2d(imap,io.dout_dir+"cmb.png")
# imap2 = mg.get_map()
# io.quickPlot2d(imap2,io.dout_dir+"cmb2.png")
dtype = np.complex128
rtype = np.zeros([0],dtype=dtype).real.dtype

print("alms...")
alm = curvedsky.map2alm(imap,lmax=4000)
powfac = 0.5
ps_data = enmap.multi_pow(alm*alm.conj()[None,None],powfac).astype(rtype)
print(alm)
print((alm.shape))

pspec = np.ones((8000))
pspec[:200] = 0.
pspec[4000:] = 0.
rand_alm,ainfo = curvedsky.rand_alm(ps=pspec,lmax=4000,return_ainfo=True)
#rand_map = curvedsky.rand_map(shape,wcs,pspec)
#rand_alm = curvedsky.map2alm(rand_map,lmax=4000)
ps_alm = enmap.multi_pow(rand_alm*rand_alm.conj()[None,None],powfac).astype(rtype)

new_sim_alm = rand_alm *np.nan_to_num(ps_data/ps_alm)

new_sim = curvedsky.alm2map(new_sim_alm,imap)#,ainfo=ainfo)
#new_sim = curvedsky.alm2map(alm,imap)#,ainfo=ainfo)
io.quickPlot2d(imap,io.dout_dir+"cmbsim.png")