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))
def build_filter(shape, wcs, lbounds, dtype=np.float32): # Intermediate because the filter we're applying is for a systematic that # isn't on the curved sky. ly, lx = enmap.laxes(shape, wcs, method="intermediate") ly, lx = [a.astype(dtype) for a in [ly, lx]] lbounds = np.asarray(lbounds).astype(dtype) if lbounds.ndim < 2: lbounds = np.broadcast_to(lbounds, (1, 2)) if lbounds.ndim > 2 or lbounds.shape[-1] != 2: raise ValueError("lbounds must be [:,{ly,lx}]") filter = enmap.ones(shape[-2:], wcs, dtype) # Apply the filters for i, (ycut, xcut) in enumerate(lbounds): filter *= 1 - (np.exp(-0.5 * (ly / ycut)**2)[:, None] * np.exp(-0.5 * (lx / xcut)**2)[None, :]) return filter
def rectangular_apodization(shape, wcs, width, N_cut=0): r"""Generate a tapered mask at the edges of the box. Maps of actual data are unlikely to be periodic, which will induce ringing when one applies a k-space filter. To solve this, we taper the edges of the map to zero prior to filtering. This taper was written to match the output of Steve's power spectrum pipeline, for reproducibility. See :py:func:`nawrapper.maptools.kfilter_map`. Parameters ---------- shape : tuple of ints Shape of the map to be tapered. wcs : astropy wcs object WCS information for the map width : float width of the taper N_cut : int number of pixels to set to zero at the edges of the map Returns ------- apo : enmap A smooth mask that is one in the center and tapers to zero at the edges. """ apo = enmap.ones(shape, wcs=wcs) apo_i = np.arange(width) apo_profile = 1 - ( -np.sin(2.0 * np.pi * (width - apo_i) / (width - N_cut)) / (2.0 * np.pi) + (width - apo_i) / (width - N_cut) ) # set it up for x and y edges apo[:width, :] *= apo_profile[:, np.newaxis] apo[:, :width] *= apo_profile[np.newaxis, :] apo[-width:, :] *= apo_profile[::-1, np.newaxis] apo[:, -width:] *= apo_profile[np.newaxis, ::-1] return apo
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)
# 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 mask = nw.apod_C2(mask, 0.5) # apodize the mask # # plot our cool results # fig, axes = plt.subplots(1, 2, figsize=(8,16)) # axes[0].imshow(imap) # axes[1].imshow(mask)
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) #Calculation for a given L L = 100 seed = (0, 0, 0)
comm=comm, width_deg=4., pix_arcmin=0.5) for solution in solutions: ta.initialize_output(name=solution) down = lambda x, n=2: enmap.downgrade(x, n) if args.dtiles is not None: dtiles = [int(x) for x in args.dtiles.split(',')] else: dtiles = [] if comm.rank == 0: enmap.write_map( os.environ['WORK'] + "/sim_tiling/ivar_ones.fits", enmap.pad(enmap.ones((2, ) + pshape[-2:], pwcs), 900) * 0 + 1) comm.Barrier() for i, extracter, inserter, eshape, ewcs in ta.tiles( from_file=True): # this is an MPI loop # What is the shape and wcs of the tile? is this needed? aids = [] kdiffs = [] ksplits = [] kcoadds = [] masks = [] lmins = [] lmaxs = [] do_radial_fit = [] hybrids = [] friends = {}
def integrate(shape, wcs, feed_dict, expr, xmask=None, ymask=None, cache=True, validate=True, groups=None, physical_units=True): """ Integrate an arbitrary expression after factorizing it. Parameters ---------- shape : tuple The shape of the array for the geometry of the footprint. Typically (...,Ny,Nx) for Ny pixels in the y-direction and Nx in the x-direction. wcs : :obj:`astropy.wcs.wcs.WCS` The wcs object completing the specification of the geometry of the footprint. feed_dict: dict Mapping from names of custom symbols to numpy arrays. expr: :obj:`sympy.core.symbol.Symbol` A sympy expression containing recognized symbols (see docs) xmask: (Ny,Nx) ndarray,optional Fourier space 2D mask for the l1 part of the integral. Defaults to ones. ymask: (Ny,Nx) ndarray, optional Fourier space 2D mask for the l2 part of the integral. Defaults to ones. cache: boolean, optional Whether to store in memory and reuse repeated terms. Defaults to true. validate: boolean,optional Whether to check that the final expression and the original agree. Defaults to True. groups: list,optional Group all terms such that they have common factors of the provided list of expressions to reduce the number of FFTs. physical_units: boolean,optional Whether the input is in pixel units or not. Returns ------- result : (Ny,Nx) ndarray The numerical result of the integration of the expression after factorization. """ # Geometry modlmap = enmap.modlmap(shape, wcs) lymap, lxmap = enmap.lmap(shape, wcs) pixarea = np.prod(enmap.pixshape(shape, wcs)) feed_dict['L'] = modlmap feed_dict['Ly'] = lymap feed_dict['Lx'] = lxmap shape = shape[-2:] ones = enmap.ones(shape, wcs, dtype=np.float32) val = 0. if xmask is None: warnings.warn( "No xmask specified; assuming all ones. This is probably not going to end well." ) xmask = ones if ymask is None: warnings.warn( "No xmask specified; assuming all ones. This is probably not going to end well." ) ymask = ones # Expression syms = expr.free_symbols l1funcs = [] l2funcs = [] for sym in syms: strsym = str(sym) if strsym[-3:] == "_l1": l1funcs.append(sym) elif strsym[-3:] == "_l2": l2funcs.append(sym) integrands,ul1s,ul2s, \ ogroups,ogroup_weights, \ ogroup_symbols = factorize_2d_convolution_integral(expr,l1funcs=l1funcs,l2funcs=l2funcs, validate=validate,groups=groups) def _fft(x): return fft(enmap.enmap(x + 0j, wcs)) def _ifft(x): return ifft(enmap.enmap(x + 0j, wcs)) if cache: cached_u1s = [] cached_u2s = [] for u1 in ul1s: l12d = evaluate(u1, feed_dict) * ones cached_u1s.append(_ifft(l12d * xmask)) for u2 in ul2s: l22d = evaluate(u2, feed_dict) * ones cached_u2s.append(_ifft(l22d * ymask)) # For each term, the index of which group it belongs to def get_l1l2(term): if cache: ifft1 = cached_u1s[term['l1index']] ifft2 = cached_u2s[term['l2index']] else: l12d = evaluate(term['l1'], feed_dict) * ones ifft1 = _ifft(l12d * xmask) l22d = evaluate(term['l2'], feed_dict) * ones ifft2 = _ifft(l22d * ymask) return ifft1, ifft2 if ogroups is None: for i, term in enumerate(integrands): ifft1, ifft2 = get_l1l2(term) ot2d = evaluate(term['other'], feed_dict) * ones ffft = _fft(ifft1 * ifft2) val += ot2d * ffft else: vals = np.zeros((len(ogroup_symbols), ) + shape, dtype=np.float32) + 0j for i, term in enumerate(integrands): ifft1, ifft2 = get_l1l2(term) gindex = ogroups[i] vals[gindex, ...] += ifft1 * ifft2 * ogroup_weights[i] for i, group in enumerate(ogroup_symbols): ot2d = evaluate(ogroup_symbols[i], feed_dict) * ones ffft = _fft(vals[i, ...]) val += ot2d * ffft mul = 1 if physical_units else 1. / pixarea return val * mul
if analytic: Cov = ilc.build_analytic_cov(tsim.modlmap, theory.lCl('TT', tsim.modlmap), ffuncs, tsim.freqs, tsim.kbeams, tsim.ps_noises, lmins=lmins, lmaxs=lmaxs, verbose=True) Cov = Cov[:, :, modlmap < lmax1].reshape( (narrays, narrays, modlmap[modlmap < lmax1].size)) s = stats.Stats(comm) mask = enmap.ones(tsim.shape[-2:], tsim.wcs) Cov = maps.SymMat(narrays, tsim.shape[-2:]) names = ["a%d" % i for i in range(narrays)] def save_fn(tcov, a1, a2): Cov[a1, a2] = tcov.copy() for task in my_tasks: with bench.show("sim gen"): isim, isimnoise = tsim.get_sim(task) with bench.show("ffts"): iksplits = [] ikmaps = []