Beispiel #1
0
 def test_project_nn(self):
     shape,wcs = enmap.fullsky_geometry(res=np.deg2rad(12/60.),proj='car')
     shape2,wcs2 = enmap.fullsky_geometry(res=np.deg2rad(6/60.),proj='car')
     shape3,wcs3 = enmap.fullsky_geometry(res=np.deg2rad(24/60.),proj='car')
     imap = enmap.ones(shape,wcs)
     omap2 = enmap.project(imap,shape2,wcs2,order=0,mode='wrap')
     omap3 = enmap.project(imap,shape3,wcs3,order=0,mode='wrap')
     assert np.all(np.isclose(omap2,1))
     assert np.all(np.isclose(omap3,1))
Beispiel #2
0
    def observe(self,freq_GHz,noise_ukarcmin=3.,beam_fwhm_arcmin=8.):

        import pysm3
        import pysm3.units as u
        #np.random.seed(213114124+int(freq_GHz))

        beam = gauss_beam(np.arange(self.lmax_sim+10),beam_fwhm_arcmin)#hp.gauss_beam(beam_fwhm_arcmin*(np.pi/60./180),lmax=3*self.nside)
        beam[beam==0] = np.inf
        beam = 1/beam

        shape,wcs = enmap.fullsky_geometry(self.pixRes_arcmin)

        Q_noise = np.sqrt(2)*noise_ukarcmin*(np.pi/180/60)*curvedsky.rand_map(shape, wcs, beam**2)
        U_noise = np.sqrt(2)*noise_ukarcmin*(np.pi/180/60)*curvedsky.rand_map(shape, wcs, beam**2)

        sky = pysm3.Sky(nside=self.nside_pysm,preset_strings=["d1","s1"],output_unit="K_CMB")
        # Get the map at the desired frequency:
        I,Q_foreground,U_foreground = sky.get_emission(freq_GHz*u.GHz)*1e6

        I,Q_foreground,U_foreground = reproject.enmap_from_healpix([I,Q_foreground,U_foreground], shape, wcs,
                                  ncomp=3, unit=1, lmax=self.lmax_sim,rot=None)

        Q_map =  self.Q_cmb.copy()
        Q_map += Q_noise
        Q_map += Q_foreground


        U_map =  self.U_cmb.copy()
        U_map += U_noise
        U_map += U_foreground

        return Q_map,U_map
Beispiel #3
0
    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])
Beispiel #4
0
    def observe(self,freq_GHz,noise_ukarcmin=3.,beam_fwhm_arcmin=8.):


        #np.random.seed(213114124+int(freq_GHz))


        beam = gauss_beam(np.arange(self.lmax_sim+10),beam_fwhm_arcmin)#hp.gauss_beam(beam_fwhm_arcmin*(np.pi/60./180),lmax=3*self.nside)
        beam[beam==0] = np.inf
        beam = 1/beam

        shape,wcs = enmap.fullsky_geometry(self.pixRes_arcmin)

        Q_noise = np.sqrt(2)*noise_ukarcmin*(np.pi/180/60)*curvedsky.rand_map(shape, wcs, beam**2)
        U_noise = np.sqrt(2)*noise_ukarcmin*(np.pi/180/60)*curvedsky.rand_map(shape, wcs, beam**2)
        Q_map =  self.Q_cmb.copy()
        Q_map += Q_noise
        Q_map += self.Q_dust*galaticDust_SED(freq_GHz,in_uk=True)
        Q_map += self.Q_sync*synchrotron_SED(freq_GHz,in_uk=True)


        U_map =  self.U_cmb.copy()
        U_map += U_noise
        U_map += self.U_dust*galaticDust_SED(freq_GHz,in_uk=True)
        U_map += self.U_sync*synchrotron_SED(freq_GHz,in_uk=True)

        return Q_map,U_map
Beispiel #5
0
    def test_area(self):
        """Test that map area is computed accurately."""
        test_patches = []
        # Small CAR patch
        DELT = 0.01
        patch = Patch.centered_at(-52., -38., 12. + DELT, 12.0 + DELT)
        shape, w = enmap.geometry(pos=patch.pos(),
                                  res=DELT*DEG,
                                  proj='car',
                                  ref=(0, 0))
        exact_area = (np.dot(patch.ra_range*DEG, [-1,1]) *
                      np.dot(np.sin(patch.dec_range*DEG), [1,-1]))

        test_patches.append((shape, w, exact_area))
        # Full sky CAR patch
        shape, w = enmap.fullsky_geometry(res=0.01*DEG, proj='car')
        exact_area = 4*np.pi
        test_patches.append((shape, w, exact_area))
        # Small ZEA patch at pole
        shape, w = enmap.geometry(pos=[90*DEG,0], res=DELT*DEG, proj='zea', shape=[100,100])
        exact_area = 1*DEG**2
        test_patches.append((shape, w, exact_area))

        for shape, w, exact_area in test_patches:
            ratio = enmap.area(shape, w)/exact_area
            print(ratio)
            assert(abs(ratio-1) < 1e-6)
Beispiel #6
0
    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)
Beispiel #7
0
 def test_fullsky_geometry(self):
     # Tests whether number of pixels and area of a full-sky 0.5 arcminute resolution map are correct
     print("Testing full sky geometry...")
     test_res_arcmin = 0.5
     shape,wcs = enmap.fullsky_geometry(res=np.deg2rad(test_res_arcmin/60.),proj='car')
     assert shape[0]==21601 and shape[1]==43200
     assert abs(enmap.area(shape,wcs) - 4*np.pi) < 1e-6
Beispiel #8
0
    def test_pospix(self):
        # Posmap separable and non-separable on CAR
        for res in [6,12,24]:
            shape,wcs = enmap.fullsky_geometry(res=np.deg2rad(res/60.),proj='car')
            posmap1 = enmap.posmap(shape,wcs)
            posmap2 = enmap.posmap(shape,wcs,separable=True)
            assert np.all(np.isclose(posmap1,posmap2))

        # Pixmap plain
        pres = 0.5
        shape,wcs = enmap.geometry(pos=(0,0),shape=(30,30),res=pres*u.degree,proj='plain')
        yp,xp = enmap.pixshapemap(shape,wcs)
        assert np.all(np.isclose(yp,pres*u.degree))
        assert np.all(np.isclose(xp,pres*u.degree))
        yp,xp = enmap.pixshape(shape,wcs)
        parea = enmap.pixsize(shape,wcs)
        assert np.isclose(parea,(pres*u.degree)**2)
        assert np.isclose(yp,pres*u.degree)
        assert np.isclose(xp,pres*u.degree)
        pmap = enmap.pixsizemap(shape,wcs)
        assert np.all(np.isclose(pmap,(pres*u.degree)**2))

        # Pixmap CAR
        pres = 0.1
        dec_cut = 89.5 # pixsizemap is not accurate near the poles currently
        shape,wcs = enmap.band_geometry(dec_cut=dec_cut*u.degree,res=pres*u.degree,proj='car')
        # Current slow and general but inaccurate near the poles implementation
        pmap = enmap.pixsizemap(shape,wcs)
        # Fast CAR-specific pixsizemap implementation
        dra, ddec = wcs.wcs.cdelt*u.degree
        dec = enmap.posmap([shape[-2],1],wcs)[0,:,0]
        area = np.abs(dra*(np.sin(np.minimum(np.pi/2.,dec+ddec/2))-np.sin(np.maximum(-np.pi/2.,dec-ddec/2))))
        Nx = shape[-1]
        pmap2 = enmap.ndmap(area[...,None].repeat(Nx,axis=-1),wcs)
        assert np.all(np.isclose(pmap,pmap2))
Beispiel #9
0
    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))
Beispiel #10
0
def get_offset_result(res=1.,dtype=np.float64,seed=1):
    shape,wcs  = enmap.fullsky_geometry(res=np.deg2rad(res))
    shape = (3,) + shape
    obs_pos = enmap.posmap(shape, wcs)
    np.random.seed(seed)
    grad = enmap.enmap(np.random.random(shape),wcs)*1e-3
    raw_pos = enmap.samewcs(lensing.offset_by_grad(obs_pos, grad, pol=shape[-3]>1, geodesic=True), obs_pos)
    return obs_pos,grad,raw_pos
Beispiel #11
0
 def test_tilemap(self):
     shape, wcs = enmap.fullsky_geometry(30 * utils.degree)
     assert shape == (7, 12)
     geo = tilemap.geometry((3, ) + shape, wcs, tile_shape=(2, 2))
     assert len(geo.active) == 0
     assert np.all(geo.lookup < 0)
     assert geo.ntile == 24
     assert geo.nactive == 0
     assert geo.tile_shape == (2, 2)
     assert geo.grid_shape == (4, 6)
     assert tuple(geo.tile_shapes[0]) == (2, 2)
     assert tuple(geo.tile_shapes[5]) == (2, 2)
     assert tuple(geo.tile_shapes[18]) == (1, 2)
     assert tuple(geo.tile_shapes[23]) == (1, 2)
     assert geo.ind2grid(7) == (1, 1)
     assert geo.grid2ind(1, 1) == 7
     geo = geo.copy(active=[1])
     assert geo.nactive == 1
     assert np.sum(geo.lookup >= 0) == 1
     assert geo.active[0] == 1
     assert geo.lookup[1] == 0
     geo2 = geo.copy(active=[0, 1, 2])
     assert geo.nactive == 1
     assert geo2.nactive == 3
     assert geo.compatible(geo) == 2
     assert geo.compatible(geo2) == 1
     geo3 = tilemap.geometry((3, ) + shape, wcs, tile_shape=(2, 3))
     assert geo.compatible(geo3) == 0
     del geo2, geo3
     m1 = tilemap.zeros(geo.copy(active=[1, 2]))
     m2 = tilemap.zeros(geo.copy(active=[2, 3, 4]))
     m3 = tilemap.zeros(geo.copy(active=[2]))
     for a, i in enumerate(m1.geometry.active):
         m1.active_tiles[a] = i
     for a, i in enumerate(m2.geometry.active):
         m2.active_tiles[a] = i * 10
     for a, i in enumerate(m3.geometry.active):
         m3.active_tiles[a] = i * 100
     assert m1[0, 0] == 1
     assert np.all(m1.tiles[1] == m1.active_tiles[0])
     m12 = m1 + m2
     m21 = m2 + m1
     assert (m12.nactive == 4)
     assert (m21.nactive == 4)
     assert (np.all(m12.tiles[1] == 1))
     assert (np.all(m21.tiles[1] == 1))
     assert (np.all(m12.tiles[2] == 22))
     assert (np.all(m21.tiles[2] == 22))
     assert (sorted(m12.geometry.active) == sorted(m21.geometry.active))
     m1 += m3
     assert np.all(m1.tiles[2] == 202)
     with self.assertRaises(ValueError):
         m3 += m1
     m1[:] = 0
     m1c = np.cos(m1)
     assert m1c.geometry.nactive == 2
     assert np.allclose(m1c, 1)
Beispiel #12
0
def get_geom(c):
    try:
        nside = c.nside
        shape, wcs = None, None
        res = None
    except:
        nside = None
        res = c.res
        shape, wcs = enmap.fullsky_geometry(res=np.deg2rad(res / 60.0))
    return nside, shape, wcs, res
Beispiel #13
0
def get_lens_result(res=1.,lmax=400,dtype=np.float64,seed=1):
    shape,wcs  = enmap.fullsky_geometry(res=np.deg2rad(res))
    shape = (3,) + shape
    # ells = np.arange(lmax)
    ps_cmb,ps_lens = powspec.read_camb_scalar(DATA_PREFIX+"test_scalCls.dat")
    ps_lensinput = np.zeros((4,4,ps_cmb.shape[-1]))
    ps_lensinput[0,0] = ps_lens
    ps_lensinput[1:,1:] = ps_cmb
    lensed = lensing.rand_map(shape, wcs, ps_lensinput, lmax=lmax, maplmax=None, dtype=dtype, seed=seed, phi_seed=None, oversample=2.0, spin=[0,2], output="lu", geodesic=True, verbose=False, delta_theta=None)
    return lensed
Beispiel #14
0
 def test_sim_slice(self):
     ps = powspec.read_spectrum(DATA_PREFIX+"test_scalCls.dat")[:1,:1]
     test_res_arcmin = 10.0
     lmax = 2000
     fact = 2.
     shape,wcs = enmap.fullsky_geometry(res=np.deg2rad(test_res_arcmin/60.),proj='car')
     omap = curvedsky.rand_map(shape, wcs, ps,lmax=lmax)
     ofunc = lambda ishape,iwcs: fact*enmap.extract(omap,ishape,iwcs)
     nmap = reproject.populate(shape,wcs,ofunc,maxpixy = 400,maxpixx = 400)
     assert np.all(np.isclose(nmap/omap,2.))
Beispiel #15
0
def test_sim_slice():
    path = os.path.dirname(enmap.__file__) + "/../tests/"
    ps = powspec.read_spectrum(path + "data/test_scalCls.dat")[:1, :1]
    test_res_arcmin = 10.0
    lmax = 2000
    fact = 2.
    shape, wcs = enmap.fullsky_geometry(res=np.deg2rad(test_res_arcmin / 60.),
                                        proj='car')
    omap = curvedsky.rand_map(shape, wcs, ps, lmax=lmax)
    ofunc = lambda ishape, iwcs: fact * enmap.extract(omap, ishape, iwcs)
    nmap = reproject.populate(shape, wcs, ofunc, maxpixy=400, maxpixx=400)
    assert np.all(np.isclose(nmap / omap, 2.))
Beispiel #16
0
def get_geometries(yml_section):
    geos = {}
    for g in yml_section:
        if g['type'] == 'fullsky':
            geos[g['name']] = enmap.fullsky_geometry(res=np.deg2rad(
                g['res_arcmin'] / 60.),
                                                     proj=g['proj'])
        elif g['type'] == 'pickle':
            geos[g['name']] = pickle.load(
                open(DATA_PREFIX + "%s" % g['filename'], 'rb'))
        else:
            raise NotImplementedError
    return geos
Beispiel #17
0
    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])
Beispiel #18
0
def get_geometries(yml_section):
    geos = {}
    for g in yml_section:
        if g['type'] == 'fullsky':
            geos[g['name']] = enmap.fullsky_geometry(res=np.deg2rad(
                g['res_arcmin'] / 60.),
                                                     proj=g['proj'])
        elif g['type'] == 'pickle':
            path = os.path.dirname(enmap.__file__) + "/../tests/"
            geos[g['name']] = pickle.load(
                open(path + "data/%s" % g['filename'], 'rb'))
        else:
            raise NotImplementedError
    return geos
Beispiel #19
0
def test_noise_simulator_car(tube):

    from pixell import enmap

    seed = 1234
    shape, wcs = enmap.fullsky_geometry(res=res)
    simulator = mapsims.SONoiseSimulator(shape=shape, wcs=wcs)

    output_map = simulator.simulate(tube, seed=seed)
    expected_map = enmap.read_map(
        data.get_pkg_data_filename(
            f"data/noise_{tube}_uKCMB_classical_res30_seed1234_car.fits.gz"
        )
    )
    assert_quantity_allclose(output_map, expected_map, rtol=1e-5)
Beispiel #20
0
    def test_full_sky(self):
        """Test that fullsky_geometry returns sensible objects.

        Or at least the objects that we considered sensible when we
        wrote this test.

        """
        shape, w = enmap.fullsky_geometry(res=0.01*DEG, proj='car')
        ny, nx = shape
        for delta, expect_nans in [(0., False), (.001, True)]:
            for ix in [-0.5-delta,nx-0.5+delta]:
                for iy in [0-delta, ny-1+delta]:
                    c = w.wcs_pix2world([(ix,iy)], 0)
                    #print(ix,iy,c)
                    assert np.any(np.isnan(c)) == expect_nans
Beispiel #21
0
def get_mv_kappa(polcomb, xalm, yalm):
    shape, wcs = enmap.fullsky_geometry(res=np.deg2rad(0.5 * 8192 / nside /
                                                       60.))
    res = qe.qe_all(shape,
                    wcs,
                    lambda x, y: theory.lCl(x, y),
                    mlmax,
                    yalm[0],
                    yalm[1],
                    yalm[2],
                    estimators=[polcomb],
                    xfTalm=xalm[0],
                    xfEalm=xalm[1],
                    xfBalm=xalm[2])
    return res[polcomb]
Beispiel #22
0
def webget(tilepath,
           box,
           tsize=675,
           res=0.5 * utils.arcmin,
           dtype=np.float64,
           verbose=False):
    # Build the geometry representing the tiles web map. This is a normal
    # fullsky geometry, except that the origin is in the top-left corner
    # instead of the bottom-left, so we flip the y axis.
    geo = enmap.Geometry(*enmap.fullsky_geometry(res=res))[::-1]
    ntile = np.array(geo.shape) // tsize
    pbox = enmap.subinds(*geo, box, cap=False, noflip=True)
    # Set up output geometry with the same ordering as the input one. We will
    # flip it to the final ordering at the end
    ogeo = geo[pbox[0, 0]:pbox[1, 0], pbox[0, 1]:pbox[1, 1]]
    omap = enmap.zeros(*ogeo, dtype=dtype)
    # Loop through tiles
    t1 = pbox[0] // tsize
    t2 = (pbox[1] + tsize - 1) // tsize
    urls = []
    for ty in range(t1[0], t2[0]):
        ty = ty % ntile[0]
        for tx in range(t1[1], t2[1]):
            tx = tx % ntile[1]
            url = tilepath.format(y=ty, x=tx)
            urls.append(url)
    datas = download_all(urls, verbose=verbose)
    di = 0
    for ty in range(t1[0], t2[0]):
        ty = ty % ntile[0]
        y1, y2 = ty * tsize, (ty + 1) * tsize
        for tx in range(t1[1], t2[1]):
            tx = tx % ntile[1]
            x1, x2 = tx * tsize, (tx + 1) * tsize
            tgeo = geo[y1:y2, x1:x2]
            data = datas[di]
            di += 1
            imgdata = np.array(Image.open(io.BytesIO(data)))
            mapdata, mask = unpack(imgdata)
            map = enmap.enmap(mapdata, tgeo.wcs)
            omap.insert(map)
    # Flip omap to normal ordering
    omap = omap[::-1]
    return omap
Beispiel #23
0
    modlmap = imap.modlmap()
    ells = np.arange(0, 8000, 1)
    fcurve = np.exp(-(ells - 4000)**2. / 2. / 200**2.)
    return maps.filter_map(imap, maps.interp(ells, fcurve)(modlmap))


#mask = sints.get_act_mr3_crosslinked_mask("deep56")
#dm = sints.ACTmr3(region=mask,pickupsub=False)
# dm = sints.ACTmr3(pickupsub=False)
# imap = enmap.pad(dm.get_coadd("s14","deep56","pa1_f150",srcfree=True,ncomp=None)[0],300)
# shape,wcs = imap.shape,imap.wcs

# shape,wcs = maps.rect_geometry(width_deg=20.,px_res_arcmin=0.5)
# imap = enmap.rand_map(shape,wcs,np.ones((1,1,shape[0],shape[1])))

oshape, owcs = enmap.fullsky_geometry(res=np.deg2rad(0.5 / 60.))
Ny = oshape[-2:][0]
deg = 5
npix = deg / (0.5 / 60.)
shape, wcs = enmap.slice_geometry(
    oshape, owcs, np.s_[int(Ny // 2 - npix):int(Ny // 2 + npix), :])
imap = enmap.rand_map(shape, wcs, np.ones((1, 1, shape[0], shape[1])))

ta = tiling.TiledAnalysis(shape, wcs, comm)
ta.initialize_output("out")

for ext, ins in ta.tiles():
    emap = ext(imap)
    emap = filter_map(emap)
    ta.update_output("out", emap, ins)
Beispiel #24
0
def test_fullsky_geometry():
    # Tests whether number of pixels and area of a full-sky 0.5 arcminute resolution map are correct
    test_res_arcmin = 0.5
    shape,wcs = enmap.fullsky_geometry(res=np.deg2rad(test_res_arcmin/60.),proj='car')
    assert shape[0]==21601 and shape[1]==43200
    assert 50000 < (enmap.area(shape,wcs)*(180./np.pi)**2.) < 51000
Beispiel #25
0
import plot_ps
from astropy.io import fits

importlib.reload(plot_ps)

lmin = 2
lmax = 1000
ls = np.arange(0, lmax)
nside = 400


def t(ls):
    return ls * (ls + 1)


shape, wcs = enmap.fullsky_geometry(res=20 * utils.arcmin, proj='car')
# generate unlensed map using input unlensd ps
unlensed_ps = load_data.unlensed(lmin, lmax, 'TT').spectra()
unlensed_map = curvedsky.rand_map(shape, wcs, unlensed_ps)
unlensed_alm = curvedsky.map2alm(unlensed_map, lmax=lmax)

# generate deflection potential using input
input_cldd = load_data.input_cldd(lmin, lmax).spectra()

if 1:
    phi_lm = fitsfunc.read_alm('./fullskyPhi_alm_00000.fits')
    phi_lm = phi_lm.astype(np.cdouble)
    cl_phi = sphtfunc.alm2cl(a)[0:lmax]
    cl_dd = cl_phi * t(ls)

if 1:
Beispiel #26
0
"""

# Lensing reconstruction ell range
lmin = 100
lmax = 3000

polcomb = 'TT'

# Number of sims
nsims = 1

# CAR resolution is decided based on lmax
res = np.deg2rad(2.0 * (3000 / lmax) / 60.)

# Make the full sky geometry
shape, wcs = enmap.fullsky_geometry(res=res)

# We use a mask of ones for this test
mask = enmap.ones(shape, wcs)

# Initialize the lens simulation interface
solint = solenspipe.SOLensInterface(mask=mask,
                                    data_mode=None,
                                    scanning_strategy="isotropic",
                                    fsky=0.4)
# Choose the frequency channel
channel = mapsims.SOChannel("LA", 145)

#empty map showing the shape and geometry of the system
omap = enmap.zeros((2, ) + shape[-2:], wcs)
Beispiel #27
0
def hdowngrade(imap, shape, wcs, lmax):
    return (cs.alm2map(cs.map2alm(imap, lmax=lmax),
                       enmap.empty(shape, wcs, dtype=imap.dtype)))


i = splitnum
fname = f"/home/r/rbond/sigurdkn/project/actpol/planck/npipe/car_equ/planck_npipe_{freq}_split{i+1}_map.fits"

hlmax = 12000
nside = 2048
llmax = 3 * nside

print("Loading map...")
oimap = enmap.read_map(fname, sel=np.s_[0, ...])
oshape, owcs = enmap.fullsky_geometry(res=2.0 * u.arcmin)
print("Downgrading map...")
imap = hdowngrade(oimap, oshape, owcs, lmax=hlmax)

# %%

ells = np.arange(9000)
theory = cosmology.default_theory()
cltt = theory.lCl('TT', ells)

smap = fit_beam(imap,
                np.asarray((decs, ras)).T,
                fwhm=4.83,
                ps=cltt,
                noise=818.2,
                r=15 * u.arcmin)
Beispiel #28
0
"""
Loads a catalog
Maps it
Smooths it
Thresholds it
Projects it onto ACT
This gives a mask of 1s and 0s from which a random catalog can be made
"""


paths = cutils.paths
#cat_type = "wise_panstarrs"
#cat_type = "madcows_photz"
cat_type = args.sys[1]
meanfield = False

# cat_type = "sdss_redmapper"
# meanfield = True

shape,wcs = enmap.fullsky_geometry(res=1 * utils.degree)
ras,decs,_ = cutils.catalog_interface(cat_type,is_meanfield=meanfield)
cmapper = catalogs.CatMapper(ras,decs,shape=shape,wcs=wcs)
cmap = maps.binary_mask(enmap.smooth_gauss(cmapper.counts,2 * utils.degree),1e-3)
io.hplot(cmap,'counts')


shape,wcs = enmap.read_map_geometry(paths.coadd_data + f"act_planck_s08_s18_cmb_f150_daynight_srcfree_map.fits")
omap = enmap.project(cmap,shape,wcs,order=0)
io.plot_img(omap,'pcounts')
enmap.write_map(f'{paths.scratch}{cat_type}_mask.fits',omap)
Beispiel #29
0
from __future__ import print_function
from orphics import maps, io, cosmology, stats
from pixell import enmap
import numpy as np
import os, sys
from actsims import signal

shape, wcs = enmap.fullsky_geometry(res=np.deg2rad(4. / 60.))
cmb_type = 'LensedUnabberatedCMB'

model = 'planck_hybrid'
dobeam = True
apply_window = False
max_cached = 0

s1 = signal.SignalGen(cmb_type=cmb_type,
                      dobeam=dobeam,
                      add_foregrounds=True,
                      apply_window=apply_window,
                      max_cached=max_cached,
                      model=model)

# Note freq_idx = 1 for 150 GHz
imap_143 = s1.get_signal_sim('planck',
                             'planck',
                             'planck',
                             '143',
                             sim_num=0,
                             save_alm=True,
                             save_map=False,
                             set_idx=0,
Beispiel #30
0
Nl = maps.interp(ls, nlkks['TT'])(ells)
lpls, lpal = np.loadtxt("data/nls_2000.txt", unpack=True)
pl = io.Plotter(yscale='log', xscale='log')
pl.add(ells, theory.gCl('kk', ells), lw=3, color='k')
pl.add(ells, Nl, ls="--")
pl.add(lpls, lpal * (lpls * (lpls + 1.))**2. / 4., ls="-.")
#pl._ax.set_ylim(1e-10,1e-6)
pl.done(io.dout_dir + "fullsky_qe_result_al.png")

dh_nls = np.nan_to_num(lpal * (lpls * (lpls + 1.))**2. / 4.)
dh_als = np.nan_to_num(dh_nls * 2. / lpls / (lpls + 1))
Al = dh_als

#### MAKE FULL-SKY LENSED SIMS

shape, wcs = enmap.fullsky_geometry(res=np.deg2rad(res / 60.), proj="car")
if not (use_saved):
    # Make a full-sky enlib geometry in CAR
    pfile = camb_root + "_lenspotentialCls.dat"
    ps = powspec.read_camb_full_lens(pfile).astype(dtype)
    cache_loc = "/gpfs01/astro/workarea/msyriac/data/depot/falafel/"
    try:
        assert cache
        Xmap = enmap.read_map("%slensed_map_seed_%d.fits" % (cache_loc, seed))
        ikappa = enmap.read_map("%skappa_map_seed_%d.fits" % (cache_loc, seed))
        print("Loaded cached maps...")
    except:
        print("Making random lensed map...")
        with bench.show("lensing"):
            Xmap, ikappa, = enlensing.rand_map(shape[-2:],
                                               wcs,