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)
def test_wcsunequal(self): shape1,wcs1 = enmap.geometry(pos=(0,0),shape=(100,100),res=1*u.arcmin,proj='car') shape1,wcs2 = enmap.geometry(pos=(0,0),shape=(100,100),res=1*u.arcmin,proj='cea') shape1,wcs3 = enmap.geometry(pos=(10,10),shape=(100,100),res=1*u.arcmin,proj='car') shape1,wcs4 = enmap.geometry(pos=(0,0),shape=(100,100),res=2*u.arcmin,proj='car') assert not(wcsutils.equal(wcs1,wcs2)) assert not(wcsutils.equal(wcs1,wcs3)) assert not(wcsutils.equal(wcs1,wcs4))
def test_plain_wcs(self): # Test area and box for a small Cartesian geometry shape,wcs = enmap.geometry(res=np.deg2rad(1./60.),shape=(600,600),pos=(0,0),proj='plain') box = np.rad2deg(enmap.box(shape,wcs)) area = np.rad2deg(np.rad2deg(enmap.area(shape,wcs))) assert np.all(np.isclose(box,np.array([[-5,-5],[5,5]]))) assert np.isclose(area,100.) # and for an artifical Cartesian geometry with area>4pi shape,wcs = enmap.geometry(res=np.deg2rad(10),shape=(100,100),pos=(0,0),proj='plain') box = np.rad2deg(enmap.box(shape,wcs)) area = np.rad2deg(np.rad2deg(enmap.area(shape,wcs))) assert np.all(np.isclose(box,np.array([[-500,-500],[500,500]]))) assert np.isclose(area,1000000)
def rect_geometry(width_arcmin=None,width_deg=None,px_res_arcmin=0.5,proj="car",pol=False,height_deg=None,height_arcmin=None,xoffset_degree=0.,yoffset_degree=0.,extra=False,**kwargs): """ Get shape and wcs for a rectangular patch of specified size and coordinate center """ if width_deg is not None: width_arcmin = 60.*width_deg if height_deg is not None: height_arcmin = 60.*height_deg hwidth = width_arcmin/2. if height_arcmin is None: vwidth = hwidth else: vwidth = height_arcmin/2. arcmin = utils.arcmin degree = utils.degree pos = [[-vwidth*arcmin+yoffset_degree*degree,-hwidth*arcmin+xoffset_degree*degree],[vwidth*arcmin+yoffset_degree*degree,hwidth*arcmin+xoffset_degree*degree]] shape, wcs = enmap.geometry(pos=pos, res=px_res_arcmin*arcmin, proj=proj,**kwargs) if pol: shape = (3,)+shape if extra: modlmap = enmap.modlmap(shape,wcs) lmax = modlmap.max() ells = np.arange(0,lmax,1.) return shape,wcs,modlmap,ells else: return shape, wcs
def get_wcs_kernel(proj, ra, dec, res): """Construct a WCS. This fixes the projection type (e.g. CAR, TAN), reference point (the special ra, dec), and resolution of a pixelization, without specifying a particular grid of pixels. This interface is subject to change. Args: proj (str): Name of the projection to use, as processed by pixell. E.g. 'car', 'cea', 'tan'. ra: Right Ascension (longitude) of the reference position, in radians. dec: Declination (latitude) of the reference position, in radians. res: Resolution, in radians. Returns a WCS object that captures the requested pixelization. """ assert np.isscalar(res) # This ain't enlib. _, wcs = enmap.geometry(np.array((dec, ra)), shape=(1, 1), proj=proj, res=(res, -res)) return wcs
def alm2stripe(alm, width, resol, proj='car'): """Return the stripe centered at dec=0 of the map corresponding to alm. Return a slice of the map corresponding to alm from declination -width/2 to +width/2, and right ascension -180deg to +180deg. Parameters ---------- alm: array The set of alms to convert to map-space. width: value The width of the map (centered at dec=0) in degrees. resol: value The resolution of the map in arcmin. proj: str, default='car' The projection of the map. Must be compatible with pixell. Returns ------- stmap: array The output map. """ box = np.array([[-width/2,180], [width/2,-180]]) * utils.degree shape, wcs = enmap.geometry(pos=box, res=resol*utils.arcmin, proj=proj) cmap = enmap.zeros(shape, wcs) return curvedsky.alm2map(alm, cmap, method='cyl')
def s18dStamp(ra, dec, data, name, width=0.5, write=True): #Find tile corresponding to RA, Dec path = '/scratch/r/rbond/jorlo/S18d_202006/filteredMaps/' tileName = tileFinder(ra, dec, data) if tileName == None: return None tile = enmap.read_map(path + tileName + '/Arnaud_M2e14_z0p4#' + tileName + '_filteredMap.fits') stamp = reproject.postage_stamp(tile, ra, dec, width * 60, 0.5) if write: #tempdec, tempra = np.deg2rad([dec, ra]) #tempwid = np.deg2rad(width) #box = [[tempdec-tempwid,tempra-tempwid],[tempdec+tempwid,tempra+tempwid]] #stampgeo = tile.submap(box) box = np.array([[ra - width / 2, dec - width / 2], [ra + width / 2, dec + width / 2]]) * utils.degree shape, wcs = enmap.geometry(pos=box, res=0.5 * utils.arcmin, proj='car') print(shape) #print(stampgeo.wcs) #print(stamp.wcs) stamp.wcs = wcs print(stamp.wcs) print(stamp[0].shape) #plt.imshow(stamp[0]) #plt.show() #Return map plot = enplot.plot(stamp, mask=0) enplot.show(plot) enmap.write_map('./for_tony/{}.fits'.format(name), stamp) return stamp
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))
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 get_geometry_regions(ncomp,n,res,hole_radius): tshape,twcs = enmap.geometry(pos=(0,0),shape=(n,n),res=res,proj='car') modrmap = enmap.modrmap(tshape,twcs) # Select the hole (m1) and context(m2) across all components amodrmap = np.repeat(modrmap.reshape((1,n,n)),ncomp,0) m1 = np.where(amodrmap.reshape(-1)<hole_radius)[0] m2 = np.where(amodrmap.reshape(-1)>=hole_radius)[0] return m1,m2
def test_fft(self): # Tests that ifft(ifft(imap))==imap, i.e. default normalizations are consistent shape, wcs = enmap.geometry(pos=(0, 0), shape=(3, 100, 100), res=0.01) imap = enmap.enmap(np.random.random(shape), wcs) assert np.all( np.isclose( imap, enmap.ifft(enmap.fft(imap, normalize='phy'), normalize='phy').real)) assert np.all(np.isclose(imap, enmap.ifft(enmap.fft(imap)).real))
def test_zenithal(self): DELT = 0.05 patch0 = Patch.centered_at(308., -38., 1.+DELT, 1.+DELT) patch1 = Patch.centered_at(309., -39., 1.+DELT, 1.+DELT) ref = patch0.center() # (dec,ra) in degrees. for proj in ['tan', 'zea', 'air']: print('Checking reference tracking of "%s"...' % proj) shape0, wcs0 = enmap.geometry(pos=patch0.pos(), res=DELT*utils.degree, proj=proj, ref=ref*DEG) shape1, wcs1 = enmap.geometry(pos=patch1.pos(), res=DELT*utils.degree, proj=proj, ref=ref*DEG) # Note world2pix wants [(ra,dec)], in degrees... pix0 = wcs0.wcs_world2pix(ref[::-1][None],0) pix1 = wcs1.wcs_world2pix(ref[::-1][None],0) print(shape0,wcs0,pix0) assert(np.all(is_centered(pix0))) assert(np.all(is_centered(pix1)))
def get_wcs_kernel(proj, ra, dec, res): """Get a WCS "kernel" -- this is a WCS holding a single pixel centered on CRVAL. This interface _will_ change. """ assert np.isscalar(res) # This ain't enlib. _, wcs = enmap.geometry(np.array((dec, ra)), shape=(1, 1), proj=proj, res=(res, -res)) return wcs
def get_basics(): t, az, el = get_scan() csl = proj.CelestialSightLine.az_el(t, az, el, weather='vacuum', site='so') fp = proj.FocalPlane.from_xieta(['a', 'b'], [0., .1 * DEG], [0, .1 * DEG]) asm = proj.Assembly.attach(csl, fp) # And a map ... of where? ra, dec = csl.coords()[:, :2].T ra0, dec0 = ra.mean(), dec.mean() shape, wcs = enmap.geometry((dec0, ra0), res=(.01 * DEG, -0.01 * DEG), shape=(300, 300), proj='tan', ref=(dec0, ra0)) return ((t, az, el), asm, (shape, wcs))
def __init__(self, dirpath, npatches=72, height_deg=10.0, px_arcmin=2.0, cache_alms=True): assert npatches % 2 == 0 width_deg = 360.0 / (npatches / 2) self.geoms = [] for i in range(npatches): box = np.deg2rad([[0, i * width_deg], [height_deg, (i + 1) * width_deg]]) shape, wcs = enmap.geometry(pos=box, res=np.deg2rad(px_arcmin / 60.0)) self.geoms.append((shape, wcs)) box = np.deg2rad([[-height_deg, i * width_deg], [0, (i + 1) * width_deg]]) shape, wcs = enmap.geometry(pos=box, res=np.deg2rad(px_arcmin / 60.0)) self.geoms.append((shape, wcs)) self.dirpath = dirpath self._cache = cache_alms self._alm_cache = {} self.npatches = npatches
def test_reference(self): """Test that WCS are properly adjusted, on request, to put a reference pixel at integer pixel number. """ DELT = 0.1 # Note we're adding a half-pixel margin to stay away from rounding cut. patch = Patch.centered_at(-52., -38., 12. + DELT, 12.0 + DELT) # Test a few reference RAs. for ra1 in [0., 0.001, 90.999, 91.101, 120., 179.9, 180.0, 180.1, 270.]: shape, wcs = enmap.geometry(pos=patch.pos(), res=DELT*DEG, proj='cea', ref=(0, ra1*DEG)) ref = np.array([[ra1,0]]) ref_pix = wcs.wcs_world2pix(ref, 0) assert(np.all(is_centered(ref_pix)))
def test_extract(self): # Tests that extraction is sensible shape, wcs = enmap.geometry(pos=(0, 0), shape=(500, 500), res=0.01) imap = enmap.enmap(np.random.random(shape), wcs) smap = imap[200:300, 200:300] sshape, swcs = smap.shape, smap.wcs smap2 = enmap.extract(imap, sshape, swcs) pixbox = enmap.pixbox_of(imap.wcs, sshape, swcs) # Do write and read test filename = "temporary_extract_map.fits" # NOT THREAD SAFE enmap.write_map(filename, imap) smap3 = enmap.read_map(filename, pixbox=pixbox) os.remove(filename) assert np.all(np.isclose(smap, smap2)) assert np.all(np.isclose(smap, smap3)) assert wcsutils.equal(smap.wcs, smap2.wcs) assert wcsutils.equal(smap.wcs, smap3.wcs)
def test_scale(self): # Test (with a plain geometry) that scale_geometry # will result in geometries with the same bounding box # but different area pixel pres = 0.5 ufact = 2 dfact = 0.5 shape,wcs = enmap.geometry(pos=(0,0),shape=(30,30),res=pres*u.arcmin,proj='plain') ushape,uwcs = enmap.scale_geometry(shape,wcs,ufact) dshape,dwcs = enmap.scale_geometry(shape,wcs,dfact) box = enmap.box(shape,wcs) ubox = enmap.box(ushape,uwcs) dbox = enmap.box(dshape,dwcs) parea = enmap.pixsize(shape,wcs) uparea = enmap.pixsize(ushape,uwcs) dparea = enmap.pixsize(dshape,dwcs) assert np.all(np.isclose(box,ubox)) assert np.all(np.isclose(box,dbox)) assert np.isclose(parea/(ufact**2),uparea) assert np.isclose(parea/(dfact**2),dparea)
thetas = np.geomspace(0.1,10,1000) kappa = lensing.nfw_kappa(mass,thetas*utils.arcmin,cc,zL=z,concentration=conc,overdensity=180,critical=False,atClusterZ=False) hthetas,hkappa = np.loadtxt("data/hdv_unfiltered.csv",unpack=True,delimiter=',') pl = io.Plotter(xyscale='loglog', xlabel='$\\theta$ [arcmin]', ylabel='$\\kappa$') pl.add(thetas,kappa) pl.add(hthetas,hkappa,ls='--') pl.done('test_uhdv.png') pl = io.Plotter(xyscale='linlin', xlabel='$\\theta$ [arcmin]', ylabel='$\\kappa$') pl.add(hthetas,hkappa/maps.interp(thetas,kappa)(hthetas),ls='--') pl.hline(y=1) pl.done('test_uhdv_ratio.png') shape,wcs = enmap.geometry(pos=(0,0),shape=(512,512),res=0.2 * utils.arcmin,proj='plain') kmask = maps.mask_kspace(shape,wcs,lmax=8095) bin_edges_arcmin= np.arange(0,15,0.4) cents,k1d = lensing.binned_nfw(mass,z,conc,cc,shape,wcs,bin_edges_arcmin,overdensity=180.,critical=False,at_cluster_z=False,kmask=kmask) hcents,hk1d = np.loadtxt("data/hdv_filtered_kappa.csv",unpack=True,delimiter=',') pl = io.Plotter(xyscale='linlin', xlabel='$\\theta$ [arcmin]', ylabel='$\\kappa$') pl.add(cents*180.*60/np.pi,k1d) pl.add(hcents,hk1d,ls='--') pl.done('test_hdv.png') pl = io.Plotter(xyscale='linlin', xlabel='$\\theta$ [arcmin]', ylabel='$\\kappa$') pl.add(hcents,hk1d/maps.interp(cents*180.*60/np.pi,k1d)(hcents),ls='--') pl.hline(y=1)
def test_thumbnails(self): print("Testing thumbnails...") # Make a geometry far away from the equator dec_min = 70 * u.degree dec_max = 80 * u.degree res = 0.5 * u.arcmin shape, wcs = enmap.band_geometry((dec_min, dec_max), res=res) # Create a set of point source positions separated by # 2 degrees but with 1 column wrapping around the RA # direction width = 120 * u.arcmin Ny = int((dec_max - dec_min) / (width)) Nx = int((2 * np.pi / (width))) pys = np.linspace(0, shape[0], Ny)[1:-1] pxs = np.linspace(0, shape[1], Nx)[:-1] Ny = len(pys) Nx = len(pxs) xx, yy = np.meshgrid(pxs, pys) xx = xx.reshape(-1) yy = yy.reshape(-1) ps = np.vstack((yy, xx)) decs, ras = enmap.pix2sky(shape, wcs, ps) # Simulate these sources with unit peak value and 2.5 arcmin FWHM N = ps.shape[1] srcs = np.zeros((N, 3)) srcs[:, 0] = decs srcs[:, 1] = ras srcs[:, 2] = ras * 0 + 1 sigma = 2.5 * u.fwhm * u.arcmin omap = pointsrcs.sim_srcs(shape, wcs, srcs, beam=sigma) # Reproject thumbnails centered on the sources # with gnomonic/tangent projection proj = "tan" r = 10 * u.arcmin ret = reproject.thumbnails(omap, srcs[:, :2], r=r, res=res, proj=proj, apod=2 * u.arcmin, order=3, oversample=2, pixwin=False) # Create a reference source at the equator to compare this against ishape, iwcs = enmap.geometry(shape=ret.shape, res=res, pos=(0, 0), proj=proj) imodrmap = enmap.modrmap(ishape, iwcs) model = np.exp(-imodrmap**2. / 2. / sigma**2.) # Make sure all thumbnails agree with the reference at the # sub-percent level for i in range(ret.shape[0]): diff = ret[i] - model assert np.all(np.isclose(diff, 0, atol=1e-3))
def test_enplot(self): print("Testing enplot...") shape, wcs = enmap.geometry(pos=(0, 0), shape=(3, 100, 100), res=0.01) a = enmap.ones(shape, wcs) p = enplot.get_plots(a)
"""Example script, copy of the quickstart in the documentation.""" import nawrapper as nw import numpy as np import matplotlib.pyplot as plt from pixell import enmap # map information shape, wcs = enmap.geometry(shape=(1024, 1024), res=np.deg2rad(0.5 / 60.), pos=(0, 0)) # create power spectrum information ells = np.arange(0, 6000, 1) ps = np.zeros(len(ells)) ps[2:] = 1 / ells[2:]**2.5 # don't want monopole/dipole # generate a realization imap = enmap.rand_map(shape, wcs, ps[np.newaxis, np.newaxis]) # plt.imshow(imap) mask = enmap.ones(imap.shape, imap.wcs) N_point_sources = 50 for i in range(N_point_sources): mask[np.random.randint(low=0, high=mask.shape[0]), np.random.randint(low=0, high=mask.shape[1])] = 0 # apodize the pixels to make fake sources point_source_map = 1 - nw.apod_C2(mask, 0.1) imap += point_source_map # add our sources to the map
try: os.makedirs(savedir) except: if overwrite: pass else: raise comm.Barrier() ## Set up the lensing simulation geometry Npix = int(args.stamp_width_arcmin * args.buffer_fact / (args.pix_width_arcmin / args.pix_scale)) dNpix = int(args.stamp_width_arcmin * args.buffer_fact / (args.pix_width_arcmin)) ddNpix = int(args.stamp_width_arcmin / (args.pix_width_arcmin)) shape, wcs = enmap.geometry(pos=(0, 0), shape=(Npix, Npix), res=args.pix_width_arcmin * utils.arcmin / args.pix_scale, proj='plain') # Select the fiducial cluster profile from Hu, DeDeo, Vale 2007 massOverh = 2e14 z = 0.7 c = 3.2 cc = cutils.get_hdv_cc() # Set up lensing def lens_map(imap): return plensing.displace_map(imap, alpha, order=args.lens_order)
def test_hdv_huok_planck(): from orphics import lensing, io, cosmology, maps shape, wcs = enmap.geometry(shape=(512, 512), res=2.0 * putils.arcmin, pos=(0, 0)) modlmap = enmap.modlmap(shape, wcs) theory = cosmology.default_theory() ells = np.arange(0, 3000, 1) ctt = theory.lCl('TT', ells) # ps,_ = powspec.read_camb_scalar("tests/Aug6_highAcc_CDM_scalCls.dat") # ells = range(ps.shape[-1]) ## Build HuOk TT estimator f = s.Ldl1 * s.e('uC_T_T_l1') + s.Ldl2 * s.e('uC_T_T_l2') F = f / 2 / s.e('tC_T_T_l1') / s.e('tC_T_T_l2') expr1 = f * F feed_dict = {} feed_dict['uC_T_T'] = s.interp(ells, ctt)(modlmap) feed_dict['tC_T_T'] = s.interp(ells, ctt)(modlmap) + ( 33. * np.pi / 180. / 60.)**2. / s.gauss_beam(modlmap, 7.0)**2. tellmin = 10 tellmax = 3000 xmask = s.mask_kspace(shape, wcs, lmin=tellmin, lmax=tellmax) integral = s.integrate(shape, wcs, feed_dict, expr1, xmask=xmask, ymask=xmask).real Nl = modlmap**4. / integral / 4. bin_edges = np.arange(10, 3000, 40) binner = s.bin2D(modlmap, bin_edges) cents, nl1d = binner.bin(Nl) ## Build HDV TT estimator F = s.Ldl1 * s.e('uC_T_T_l1') / s.e('tC_T_T_l1') / s.e('tC_T_T_l2') expr1 = f * F integral = s.integrate(shape, wcs, feed_dict, expr1, xmask=xmask, ymask=xmask).real Nl = modlmap**4. / integral / 4. cents, nl1d2 = binner.bin(Nl) cents, nl1d3 = binner.bin( s.N_l_cross(shape, wcs, feed_dict, "hu_ok", "TT", "hu_ok", "TT", xmask=xmask, ymask=xmask)) cents, nl1d4 = binner.bin( s.N_l_cross(shape, wcs, feed_dict, "hdv", "TT", "hdv", "TT", xmask=xmask, ymask=xmask)) cents, nl1d5 = binner.bin( s.N_l(shape, wcs, feed_dict, "hu_ok", "TT", xmask=xmask, ymask=xmask)) cents, nl1d6 = binner.bin( s.N_l(shape, wcs, feed_dict, "hdv", "TT", xmask=xmask, ymask=xmask)) clkk = theory.gCl('kk', ells) pl = io.Plotter(xyscale='linlog') pl.add(cents, nl1d) pl.add(cents, nl1d2) # pl.add(cents,nl1d3) pl.add(cents, nl1d4) pl.add(cents, nl1d5) pl.add(cents, nl1d6) pl.add(ells, clkk) pl.done("plcomp.png")
def do(ymap, cmap, mask, ras, decs, wt): combined = list(zip(ras, decs)) random.shuffle(combined) ras[:], decs[:] = zip(*combined) njobs = len(ras) comm, rank, my_tasks = mpi.distribute(njobs) print("Rank %d starting" % rank) s = stats.Stats(comm) i = 0 for task in my_tasks: ra = ras[task] dec = decs[task] # mcut = reproject.cutout(mask, ra=np.deg2rad(ra), dec=np.deg2rad(dec),npix=int(arcmin/pix)) mcut = reproject.postage_stamp(mask, np.deg2rad(ra), np.deg2rad(dec), arcmin, pix) if mcut is None: continue if np.any(mcut) <= 0: continue # ycut = reproject.cutout(ymap, ra=np.deg2rad(ra), dec=np.deg2rad(dec),npix=int(arcmin/pix)) # ccut = reproject.cutout(cmap, ra=np.deg2rad(ra), dec=np.deg2rad(dec),npix=int(arcmin/pix)) # wcut = reproject.cutout(wt, ra=np.deg2rad(ra), dec=np.deg2rad(dec),npix=int(arcmin/pix)) ycut = reproject.postage_stamp(ymap, np.deg2rad(ra), np.deg2rad(dec), arcmin, pix) ccut = reproject.postage_stamp(cmap, np.deg2rad(ra), np.deg2rad(dec), arcmin, pix) wcut = reproject.postage_stamp(wt, np.deg2rad(ra), np.deg2rad(dec), arcmin, pix) weight = wcut.mean() # if i==0: # modrmap = np.rad2deg(ycut.modrmap())*60. # bin_edges = np.arange(0.,15.,1.0) # binner = stats.bin2D(modrmap,bin_edges) # cents,y1d = binner.bin(ycut) # cents,c1d = binner.bin(ccut) # s.add_to_stats("c1d",c1d*1e6) # s.add_to_stats("y1d",y1d*1e6) s.add_to_stack("cstack", ccut * 1e6 * weight) s.add_to_stack("ystack", ycut * 1e6 * weight) s.add_to_stats("sum", (weight, )) i = i + 1 if i % 10 == 0 and rank == 0: print(i) print("Rank %d done " % rank) s.get_stats() s.get_stacks() if rank == 0: N = s.vectors['sum'].sum() ystack = s.stacks['ystack'] * N cstack = s.stacks['cstack'] * N _, nwcs = enmap.geometry(pos=(0, 0), shape=ystack.shape, res=np.deg2rad(0.5 / 60.)) return rank, enmap.enmap(ystack, nwcs), enmap.enmap(cstack, nwcs), N else: return rank, None, None, None
def test_geom_args(self): """Test that the different combinations of passing and not passing arguments to geometry() work.""" box = np.array([[40, 100], [45, 95]]) * utils.degree res = 1 * utils.degree def close(a, b): return np.all(np.isclose(a, b, atol=1e-6 * utils.degree)) # Plain shape, wcs = enmap.geometry(box, res=res, proj="car") assert (close(shape, [5, 5])) assert (close( enmap.pix2sky(shape, wcs, [0, 0]) / utils.degree, [40.00000000, 100.00000000])) shape, wcs = enmap.geometry(box, res=res, proj="cea") assert (close(shape, [7, 5])) assert (close( enmap.pix2sky(shape, wcs, [0, 0]) / utils.degree, [40.17551345, 100.00000000])) shape, wcs = enmap.geometry(box, res=res, proj="zea") assert (close(shape, [5, 4])) assert (close( enmap.pix2sky(shape, wcs, [0, 0]) / utils.degree, [40.49221947, 98.81479953])) shape, wcs = enmap.geometry(box, res=res, proj="tan") assert (close(shape, [5, 4])) assert (close( enmap.pix2sky(shape, wcs, [0, 0]) / utils.degree, [40.49336943, 98.81407198])) shape, wcs = enmap.geometry(box, res=res, proj="air") assert (close(shape, [2, 10])) assert (close( enmap.pix2sky(shape, wcs, [0, 0]) / utils.degree, [40.42085960, 99.75799905])) shape, wcs = enmap.geometry(box, res=res, proj="plain") assert (close(shape, [5, 5])) assert (close( enmap.pix2sky(shape, wcs, [0, 0]) / utils.degree, [40.50000000, 99.50000000])) # Swap box order shape, wcs = enmap.geometry(box[::-1], res=res, proj="car") assert (close(shape, [5, 5])) assert (close( enmap.pix2sky(shape, wcs, [0, 0]) / utils.degree, [45.00000000, 95.00000000])) shape, wcs = enmap.geometry(box[::-1], res=res, proj="cea") assert (close(shape, [7, 5])) assert (close( enmap.pix2sky(shape, wcs, [0, 0]) / utils.degree, [44.59207383, 95.00000000])) shape, wcs = enmap.geometry(box[::-1], res=res, proj="zea") assert (close(shape, [5, 4])) assert (close( enmap.pix2sky(shape, wcs, [0, 0]) / utils.degree, [44.49175753, 96.09829319])) shape, wcs = enmap.geometry(box[::-1], res=res, proj="tan") assert (close(shape, [5, 4])) assert (close( enmap.pix2sky(shape, wcs, [0, 0]) / utils.degree, [44.49062589, 96.09912004])) shape, wcs = enmap.geometry(box[::-1], res=res, proj="air") assert (close(shape, [2, 10])) assert (close( enmap.pix2sky(shape, wcs, [0, 0]) / utils.degree, [44.88532797, 95.12307674])) shape, wcs = enmap.geometry(box[::-1], res=res, proj="plain") assert (close(shape, [5, 5])) assert (close( enmap.pix2sky(shape, wcs, [0, 0]) / utils.degree, [44.50000000, 95.50000000])) # Specify center and shape instead of box. FIXME: These should be changed to make them right-handed. pos = np.array([50, 120]) * utils.degree shape = (5, 5) oshape, wcs = enmap.geometry(pos, res=res, shape=shape, proj="car") assert (close(oshape, shape)) assert (close( enmap.pix2sky(shape, wcs, [0, 0]) / utils.degree, [48.00000000, 122.00000000])) oshape, wcs = enmap.geometry(pos, res=res, shape=shape, proj="cea") assert (close(oshape, shape)) assert (close( enmap.pix2sky(shape, wcs, [0, 0]) / utils.degree, [48.58804987, 122.00000000])) oshape, wcs = enmap.geometry(pos, res=res, shape=shape, proj="zea") assert (close(oshape, shape)) assert (close( enmap.pix2sky(shape, wcs, [0, 0]) / utils.degree, [47.96024416, 122.98709530])) oshape, wcs = enmap.geometry(pos, res=res, shape=shape, proj="tan") assert (close(oshape, shape)) assert (close( enmap.pix2sky(shape, wcs, [0, 0]) / utils.degree, [47.96213990, 122.98447863])) oshape, wcs = enmap.geometry(pos, res=res, shape=shape, proj="plain") assert (close(oshape, shape)) assert (close( enmap.pix2sky(shape, wcs, [0, 0]) / utils.degree, [48.00000000, 118.00000000])) # Same but with explicit 2d res oshape, wcs = enmap.geometry(pos, res=[res, -res], shape=shape, proj="car") assert (close(oshape, shape)) assert (close( enmap.pix2sky(shape, wcs, [0, 0]) / utils.degree, [48.00000000, 122.00000000])) oshape, wcs = enmap.geometry(pos, res=[res, -res], shape=shape, proj="cea") assert (close(oshape, shape)) assert (close( enmap.pix2sky(shape, wcs, [0, 0]) / utils.degree, [48.58804987, 122.00000000])) oshape, wcs = enmap.geometry(pos, res=[res, -res], shape=shape, proj="zea") assert (close(oshape, shape)) assert (close( enmap.pix2sky(shape, wcs, [0, 0]) / utils.degree, [47.96024416, 122.98709530])) oshape, wcs = enmap.geometry(pos, res=[res, -res], shape=shape, proj="tan") assert (close(oshape, shape)) assert (close( enmap.pix2sky(shape, wcs, [0, 0]) / utils.degree, [47.96213990, 122.98447863])) oshape, wcs = enmap.geometry(pos, res=[res, -res], shape=shape, proj="plain") assert (close(oshape, shape)) assert (close( enmap.pix2sky(shape, wcs, [0, 0]) / utils.degree, [48.00000000, 122.00000000])) # Box and shape oshape, wcs = enmap.geometry(box, shape=shape, proj="car") assert (close(oshape, shape)) assert (close( enmap.pix2sky(shape, wcs, [0, 0]) / utils.degree, [40.00000000, 100.00000000])) oshape, wcs = enmap.geometry(box, shape=shape, proj="cea") assert (close(oshape, shape)) assert (close( enmap.pix2sky(shape, wcs, [0, 0]) / utils.degree, [40.03023148, 100.00000000])) oshape, wcs = enmap.geometry(box, shape=shape, proj="zea") assert (close(oshape, shape)) assert (close( enmap.pix2sky(shape, wcs, [0, 0]) / utils.degree, [40.48400209, 99.43687135])) oshape, wcs = enmap.geometry(box, shape=shape, proj="tan") assert (close(oshape, shape)) assert (close( enmap.pix2sky(shape, wcs, [0, 0]) / utils.degree, [40.48319549, 99.43761826])) oshape, wcs = enmap.geometry(box, shape=shape, proj="air") assert (close(oshape, shape)) assert (close( enmap.pix2sky(shape, wcs, [0, 0]) / utils.degree, [40.04076497, 100.02606306])) oshape, wcs = enmap.geometry(box, shape=shape, proj="plain") assert (close(oshape, shape)) assert (close( enmap.pix2sky(shape, wcs, [0, 0]) / utils.degree, [40.50000000, 99.50000000]))
import argparse parser = argparse.ArgumentParser() parser.add_argument("box", type=str) parser.add_argument("ofile") parser.add_argument("-r", "--res", type=float, default=0.5) parser.add_argument("-p", "--proj", type=str, default="car") args = parser.parse_args() import numpy as np from pixell import utils, enmap box = utils.parse_box(args.box) * utils.degree shape, wcs = enmap.geometry(box, res=args.res * utils.arcmin, proj=args.proj) enmap.write_map(args.ofile, enmap.zeros(shape, wcs, np.uint8))
def do(ymap, cmap, dmap, mask, ras, decs, wt): combined = list(zip(ras, decs)) random.shuffle(combined) ras[:], decs[:] = zip(*combined) Nrand = 400 njobs = len(ras) comm, rank, my_tasks = mpi.distribute(njobs) print("Rank %d starting" % rank) s = stats.Stats(comm) i = 0 for task in my_tasks: ra = ras[task] dec = decs[task] mcut, ycut, ccut, dcut, weight = get_cuts(mask, ymap, cmap, dmap, wt, ra, dec, arcmin, pix) if mcut is None: continue if i == 0: modrmap = np.rad2deg(ycut.modrmap()) * 60. bin_edges = np.arange(0., 15., 1.0) binner = stats.bin2D(modrmap, bin_edges) rras, rdecs = catalogs.random_catalog(ymap.shape, ymap.wcs, Nrand, edge_avoid_deg=4.) nrej = 0 for rra, rdec in zip(rras, rdecs): rmcut, rycut, rccut, rdcut, rweight = get_cuts( mask, ymap, cmap, dmap, wt, rra, rdec, arcmin, pix) if rmcut is None: nrej = nrej + 1 continue cents, ry1d = binner.bin(rycut) cents, rc1d = binner.bin(rccut) cents, rd1d = binner.bin(rdcut) s.add_to_stats("rc1d", rc1d * 1e6) s.add_to_stats("ry1d", ry1d * 1e6) s.add_to_stats("rd1d", rd1d * 1e6) if rank == 0: print(Nrand - nrej, " accepted") cents, y1d = binner.bin(ycut) cents, c1d = binner.bin(ccut) cents, d1d = binner.bin(dcut) s.add_to_stats("c1d", c1d * 1e6) s.add_to_stats("y1d", y1d * 1e6) s.add_to_stats("d1d", d1d * 1e6) s.add_to_stack("cstack", ccut * 1e6 * weight) s.add_to_stack("dstack", dcut * 1e6 * weight) s.add_to_stack("ystack", ycut * 1e6 * weight) s.add_to_stats("sum", (weight, )) i = i + 1 if i % 10 == 0 and rank == 0: print(i) print("Rank %d done " % rank) s.get_stats() s.get_stacks() if rank == 0: N = s.vectors['sum'].sum() ystack = s.stacks['ystack'] * N cstack = s.stacks['cstack'] * N dstack = s.stacks['dstack'] * N y1ds = s.vectors['y1d'] c1ds = s.vectors['c1d'] d1ds = s.vectors['d1d'] ry1d = s.stats['ry1d']['mean'] rc1d = s.stats['rc1d']['mean'] rd1d = s.stats['rd1d']['mean'] _, nwcs = enmap.geometry(pos=(0, 0), shape=ystack.shape, res=np.deg2rad(0.5 / 60.)) return rank, enmap.enmap( ystack, nwcs), enmap.enmap(cstack, nwcs), enmap.enmap( dstack, nwcs), N, cents, y1ds, c1ds, d1ds, ry1d, rc1d, rd1d else: return rank, None, None, None, None, None, None, None, None, None, None, None
changemap=changemap, getfft=u.fft, lmax=lmax_A) #Leg1, Leg2, for estimator B LoadB = u.LoadfftedMaps(mapsObj=mapsObjB, WR=WR, ConvertingObj=C, changemap=changemap, getfft=u.fft, lmax=lmax_B) if i == iMin: #Get shape and wcs shape = LoadA.read_shape() lonCenter, latCenter = 0, 0 shape, wcs = enmap.geometry(shape=shape, res=1. * putils.arcmin, pos=(lonCenter, latCenter)) modlmap = enmap.modlmap(shape, wcs) #Binner Binner = u.Binner(shape, wcs, lmin=10, lmax=4000, deltal=deltal, log=logmode, nBins=nlogBins) feed_dict = u.Loadfeed_dict(pathlib.Path(spectra_path), field_names_A, field_names_B, modlmap)
istack = istack + icut ystack = ystack + ycut sstack = sstack + scut cstack = cstack + ccut i += 1 if i > 5000: break s.get_stats() istack = istack / i * 1e6 ystack = ystack / i * 1e6 sstack = sstack / i cstack = cstack / i # Approximate geometry of stack _, nwcs = enmap.geometry(pos=(0, 0), shape=istack.shape, res=np.deg2rad(0.5 / 60.)) # Plot images if do_images: io.hplot(enmap.enmap(istack, nwcs), "istack", ticks=5, tick_unit='arcmin', grid=True, colorbar=True, color='gray', upgrade=4, min=-5, max=25) io.hplot(enmap.enmap(ystack, nwcs),