def __init__(self, shape, wcs, pattern, offset, site, pad=2.0*utils.degree, order=0, subsample=2.0): """Build an unskew operator that uses spline interpolation along an azimuth sweep to straighten out the scanning motion for one scanning pattern. Relatively slow, and leads to some smoothing due to the interpolation, but does not assume that dec changes with a constant speed during a sweep.""" # Find the unskew transformation for this pattern. # We basically want dec->az and ra->ra0, with az spacing # similar to el spacing. ndec, nra = shape[-2:] info = calc_az_sweep(pattern, offset, site, pad=pad, subsample=subsample) sweep_ra, sweep_dec = info.sweep_cel #(sweep_ra, sweep_dec), naz, daz = calc_az_sweep(pattern, offset, site, pad=pad, subsample=subsample) # We want to be able to go from (y,x) to (ra,dec), with # dec = dec[y] # ra = ra[y]-ra[0]+x # Precompute the pixel mapping. This will have the full witdh in ra, # but will be smaller in dec due to the limited az range. raw_dec, raw_ra = enmap.posmap(shape, wcs) skew_pos = np.zeros((2, info.naz, nra)) skew_pos[0] = sweep_dec[:,None] skew_pos[1] = (sweep_ra-sweep_ra[0])[:,None] + raw_ra[None,ndec/2,:] skew_pix = enmap.sky2pix(shape, wcs, skew_pos).astype(dtype) # Build geometry for the unskewed system ushape, uwcs = enmap.geometry(pos=[0,0], shape=[info.naz, nra], res=[np.abs(info.daz), enmap.pixshape(shape,wcs)[1]], proj="car") # Save self.order = order self.shape = shape self.wcs = wcs self.pattern = pattern self.site = site self.skew_pix = skew_pix # External interface self.ushape = ushape self.uwcs = uwcs
def __init__(self, shape, wcs): pos = enmap.posmap(shape, wcs) self.y = pos[0, :, :] self.x = pos[1, :, :] self.modrmap = enmap.modrmap(shape, wcs) self.shape = shape self.wcs = wcs
def sim_sidelobe(shape, wcs, info): # Horizontal band for illustration pos = enmap.posmap(shape, wcs) x = pos[0] x0 = x.reshape(-1)[np.random.randint(x.size)] r = (x-x0)/info.width return np.exp(-0.5*r**2)*np.cos(2*np.pi*r/info.wave+np.random.uniform(0,2*np.pi,3)[:,None,None])*info.amps[:,None,None]
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 __init__(self, shape_source, wcs_source, patch_width, patch_height, width_multiplier=1., height_multiplier=1.5, pix_target_override_arcmin=None, proj="car", verbose=False, downsample=True, downsample_pix_arcmin=None): self.source_pix = np.min( enmap.extent(shape_source, wcs_source) / shape_source[-2:]) * 60. * 180. / np.pi if pix_target_override_arcmin is None: input_dec = enmap.posmap(shape_source, wcs_source)[0] max_dec = np.max(np.abs(input_dec)) del input_dec recommended_pix = self.source_pix * np.cos(max_dec) if verbose: print("INFO: Maximum declination in southern patch : ", max_dec * 180. / np.pi, " deg.") print("INFO: Recommended pixel size for northern patch : ", recommended_pix, " arcmin") else: recommended_pix = pix_target_override_arcmin shape_target, wcs_target = enmap.rect_geometry( width_arcmin=width_multiplier * patch_width * 60., height_arcmin=height_multiplier * patch_height * 60., px_res_arcmin=recommended_pix, yoffset_degree=0., proj=proj) self.target_pix = recommended_pix self.wcs_target = wcs_target if verbose: print("INFO: Source pixel : ", self.source_pix, " arcmin") if downsample: dpix = downsample_pix_arcmin if downsample_pix_arcmin is not None else self.source_pix self.shape_final, self.wcs_final = enmap.rect_geometry( width_arcmin=width_multiplier * patch_width * 60., height_arcmin=height_multiplier * patch_height * 60., px_res_arcmin=dpix, yoffset_degree=0., proj=proj) else: self.shape_final = shape_target self.wcs_final = wcs_target self.downsample = downsample MapRotator.__init__(self, shape_source, wcs_source, shape_target, wcs_target)
def get_rotated_pixels(shape_source, wcs_source, shape_target, wcs_target, inverse=False): """ Given a source geometry (shape_source,wcs_source) return the pixel positions in the target geometry (shape_target,wcs_target) if the source geometry were rotated such that its center lies on the center of the target geometry. WARNING: Only currently tested for a rotation along declination from one CAR geometry to another CAR geometry. """ from enlib import coordinates # what are the center coordinates of each geometris center_source = enmap.pix2sky(shape_source, wcs_source, (shape_source[0] / 2., shape_source[1] / 2.)) center_target = enmap.pix2sky(shape_target, wcs_target, (shape_target[0] / 2., shape_target[1] / 2.)) decs, ras = center_source dect, rat = center_target # what are the angle coordinates of each pixel in the target geometry pos_target = enmap.posmap(shape_target, wcs_target) lra = pos_target[1, :, :].ravel() ldec = pos_target[0, :, :].ravel() del pos_target # recenter the angle coordinates of the target from the target center to the source center if inverse: newcoord = coordinates.decenter((lra, ldec), (rat, dect, ras, decs)) else: newcoord = coordinates.recenter((lra, ldec), (rat, dect, ras, decs)) del lra del ldec # reshape these new coordinates into enmap-friendly form new_pos = np.empty((2, shape_target[0], shape_target[1])) new_pos[0, :, :] = newcoord[1, :].reshape(shape_target) new_pos[1, :, :] = newcoord[0, :].reshape(shape_target) del newcoord # translate these new coordinates to pixel positions in the target geometry based on the source's wcs pix_new = enmap.sky2pix(shape_source, wcs_source, new_pos) return pix_new
def __init__(self, shape, wcs, dimensionless=False, TCMB=2.7255e6, cc=None, theory=None, lmax=None, skip_real=False, orphics_is_dimensionless=True): self.shape = shape self.wcs = wcs if not (skip_real): self.modrmap = enmap.modrmap(shape, wcs) self.lxmap, self.lymap, self.modlmap, self.angmap, self.lx, self.ly = get_ft_attributes_enmap( shape, wcs) self.pix_ells = np.arange(0., self.modlmap.max(), 1.) self.posmap = enmap.posmap(self.shape, self.wcs) self.dimensionless = dimensionless self.TCMB = TCMB if (theory is not None) or (cc is not None): self.add_theory(cc, theory, lmax, orphics_is_dimensionless)
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, delta_theta=None): 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) # First draw a random lensing field, and use it to compute the undeflected positions if verbose: print("Generating alms") alm, ainfo = curvedsky.rand_alm(ps_lensinput, lmax=lmax, seed=seed, dtype=ctype, return_ainfo=True) phi_alm, cmb_alm = alm[0], alm[1:1 + shape[-3]] # 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 delta_theta is None: bsize = shape[-2] else: bsize = utils.nint(abs(delta_theta / utils.degree / wcs.wcs.cdelt[1])) # Adjust bsize so we don't get any tiny blocks at the end nblock = shape[-2] // bsize bsize = int(shape[-2] / (nblock + 0.5)) # Allocate output maps if "p" in output: phi_map = enmap.empty(shape[-2:], wcs, dtype=dtype) if "k" in output: kappa_map = enmap.empty(shape[-2:], wcs, dtype=dtype) l = np.arange(ainfo.lmax + 1.0) kappa_alm = ainfo.lmul(phi_alm, l * (l + 1) / 2) for i1 in range(0, shape[-2], bsize): curvedsky.alm2map(kappa_alm, kappa_map[..., i1:i1 + bize, :]) del kappa_alm if "a" in output: grad_map = enmap.empty((2, ) + shape[-2:], wcs, dtype=dtype) if "u" in output: cmb_raw = enmap.empty(shape, wcs, dtype=dtype) if "l" in output: cmb_obs = enmap.empty(shape, wcs, dtype=dtype) # Then loop over dec bands for i1 in range(0, shape[-2], bsize): i2 = min(i1 + bsize, shape[-2]) lshape, lwcs = enmap.slice_geometry(shape, wcs, (slice(i1, i2), slice(None))) if "p" in output: if verbose: print("Computing phi map") curvedsky.alm2map(phi_alm, phi_map[..., i1:i2, :]) if verbose: print("Computing grad map") if "a" in output: grad = grad_map[..., i1:i2, :] else: grad = enmap.zeros((2, ) + lshape[-2:], lwcs, dtype=dtype) curvedsky.alm2map(phi_alm, grad, deriv=True) if "l" not in output: continue if verbose: print("Computing observed coordinates") obs_pos = enmap.posmap(lshape, lwcs) if verbose: print("Computing alpha map") raw_pos = enmap.samewcs( offset_by_grad(obs_pos, grad, pol=shape[-3] > 1, geodesic=geodesic), obs_pos) del obs_pos, grad if "u" in output: if verbose: print("Computing unlensed map") curvedsky.alm2map(cmb_alm, cmb_raw[..., i1:i2, :], spin=spin) if verbose: print("Computing lensed map") cmb_obs[..., i1:i2, :] = 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[..., i1:i2, :] = enmap.rotate_pol(cmb_obs[..., i1:i2, :], raw_pos[2]) del raw_pos del cmb_alm, phi_alm # Output in same order as specified in output argument res = [] for c in output: if c == "l": res.append(cmb_obs.reshape(oshape)) elif c == "u": res.append(cmb_raw.reshape(oshape)) elif c == "p": res.append(phi_map) elif c == "k": res.append(kappa_map) elif c == "a": res.append(grad_map) return tuple(res)
# amp_min = 0.76 # amp_max = 0.84 kamps = np.linspace(amp_min, amp_max, 10) print(kamps) Ccovs = [] Cinvs = [] logdets = [] kappa = lensing.nfw_kappa(1e15, modrmap, cc) phi, _ = lensing.kappa_to_phi(kappa, modlmap, return_fphi=True) grad_phi = enmap.grad(phi) lens_order = 5 posmap = enmap.posmap(shape, wcs) for k, kamp in enumerate(kamps): pos = posmap + kamp * grad_phi alpha_pix = enmap.sky2pix(shape, wcs, pos, safe=False) Scov = lensing.lens_cov(Ucov, alpha_pix, lens_order=lens_order, kbeam=kbeam) # io.plot_img(np.nan_to_num((Scov-Ucov)*100./Ucov)) Tcov = Scov + Ncov + 5000 s, logdet = np.linalg.slogdet(Tcov) print(s, logdet) assert s > 0
rshape, rwcs = maps.rect_geometry(width_arcmin=5., px_res_arcmin=0.001) fshape, fwcs = maps.rect_geometry(width_arcmin=20., px_res_arcmin=0.1) cshape, cwcs = maps.rect_geometry(width_arcmin=20., px_res_arcmin=0.5) rmodrmap = enmap.modrmap(rshape, rwcs) fmodrmap = enmap.modrmap(fshape, fwcs) cmodrmap = enmap.modrmap(cshape, cwcs) rmodlmap = enmap.modlmap(rshape, rwcs) fmodlmap = enmap.modlmap(fshape, fwcs) cmodlmap = enmap.modlmap(cshape, cwcs) print(fshape, cshape) mass = 2.e14 fkappa = lens_func(fmodrmap) phi, _ = lensing.kappa_to_phi(fkappa, fmodlmap, return_fphi=True) grad_phi = enmap.grad(phi) pos = enmap.posmap(fshape, fwcs) + grad_phi alpha_pix = enmap.sky2pix(fshape, fwcs, pos, safe=False) lmax = cmodlmap.max() ells = np.arange(0, lmax, 1) cls = theory.uCl('TT', ells) ps = cls.reshape((1, 1, ells.size)) mg = maps.MapGen(cshape, cwcs, ps) unlensed = mg.get_map() hunlensed = enmap.enmap(resample.resample_fft(unlensed.copy(), fshape), fwcs) hlensed = enlensing.displace_map(hunlensed, alpha_pix, order=lens_order, mode=mode) lensed = enmap.enmap(resample.resample_fft(hlensed, cshape), cwcs)
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
if len(group_data) == 0: print("No usable tods in group %s. Skipping" % ",".join([ids[i] for i in group])) continue # Set up the full likelihood progress_thumbs = args.minimaps and verbose >= 3 chisq_wrappers = [data.lik.chisq_wrapper(thumb_path=args.odir + "/" + data.oid + "_thumb%03d.fits", thumb_interval=progress_thumbs) for data in group_data] def likfun(off): return sum([chisq_wrapper(off) for chisq_wrapper in chisq_wrappers]) # Representaive individual lik for stuff that's common to them. This is a bit hacky. # A single joint lik class would have been cleaner. L = group_data[0].lik if not args.nogrid: # Do a grid search first to avoid false minima grid_shape, grid_wcs = build_grid_geometry(grid_bounds, grid_res) grid_pos = enmap.posmap(grid_shape, grid_wcs) grid_lik = eval_offs(L, likfun, grid_pos) enmap.write_map(args.odir + "/grid_%s.fits" % oid, grid_lik) x0 = enmap.argmin(grid_lik) else: x0 = np.zeros(2) # Then do the actual likelihood search off = L.unzip(optimize.fmin_powell(likfun,L.zip(x0))) # and estimate the position error using a few extra samples # Estimate position errors using a few extra samples doff = np.sum([data.lik.estimate_error(off)**-2 for data in group_data],0)**-0.5 # Now that we have the best fit position we can get the amplitudes for # each individual tod in the group tot_dchisq = 0
# zL = 1.0 sourceZ = 1100. overdensity = 180. critical = False atClusterZ = False # === TEMPLATE MAP === px = 0.2 arc = 100 hwidth = arc/2. hwidthTen = 5. deg = utils.degree arcmin = utils.arcmin shape, wcs = enmap.geometry(pos=[[-hwidth*arcmin,-hwidth*arcmin],[hwidth*arcmin,hwidth*arcmin]], res=px*arcmin, proj="car") shapeTen, wcsTen = enmap.geometry(pos=[[-hwidthTen*arcmin,-hwidthTen*arcmin],[hwidthTen*arcmin,hwidthTen*arcmin]], res=px*arcmin, proj="car") thetaMap = enmap.posmap(shape, wcs) thetaMap = np.sum(thetaMap**2,0)**0.5 # === KAPPA MAP === # kappaMap,r500 = NFWkappa(cc,massOverh,concentration,zL,thetaMap*180.*60./np.pi,sourceZ,overdensity=overdensity,critical=critical,atClusterZ=atClusterZ) snap = snapNum b = BattagliaSims(constDict) # === CMB POWER SPECTRUM === ps = powspec.read_spectrum("data/cl_lensinput.dat") # === QUADRATIC ESTIMATOR INITIALIZATION ===
overdensity = 500. critical = True atClusterZ = True # === TEMPLATE MAP === px = 0.1 arc = 50 hwidth = arc/2. pxDown = 0.2 deg = utils.degree arcmin = utils.arcmin shape, wcs = enmap.geometry(pos=[[-hwidth*arcmin,-hwidth*arcmin],[hwidth*arcmin,hwidth*arcmin]], res=px*arcmin, proj="car") shapeDown, wcsDown = enmap.geometry(pos=[[-hwidth*arcmin,-hwidth*arcmin],[hwidth*arcmin,hwidth*arcmin]], res=pxDown*arcmin, proj="car") thetaMap = enmap.posmap(shape, wcs) thetaMap = np.sum(thetaMap**2,0)**0.5 thetaMapDown = enmap.posmap(shapeDown, wcsDown) thetaMapDown = np.sum(thetaMapDown**2,0)**0.5 comL = cc.results.comoving_radial_distance(zL)*cc.h comS = cc.results.comoving_radial_distance(sourceZ)*cc.h winAtLens = (comS-comL)/comS kappaMap,r500 = NFWkappa(cc,massOverh,concentration,zL,thetaMap*180.*60./np.pi,winAtLens,overdensity=overdensity,critical=critical,atClusterZ=atClusterZ) # === CMB POWER SPECTRUM === ps = powspec.read_spectrum("data/cl_lensinput.dat")
# This program computes a simple estimation of the amount of distortion the # flat-sky approximation involves import numpy as np, argparse from enlib import enmap parser = argparse.ArgumentParser() parser.add_argument("omap") parser.add_argument("-D", "--diameter", type=float, default=30) parser.add_argument("-n", "--npix", type=int, default=800) parser.add_argument("--proj", type=str, default="cea") args = parser.parse_args() r = args.diameter*np.pi/180/2 shape, wcs = enmap.geometry(pos=[[-r,-r],[r,r]], shape=(args.npix, args.npix), proj=args.proj) def linpos(n,b): return b[0] + (np.arange(n)+0.5)*(b[1]-b[0])/n alpha = enmap.zeros((2,)+shape, wcs) pos = enmap.posmap(shape, wcs) # I'm not sure how to compute this in general, so here's a specialization # for cylindrical projections if args.proj == "cea" or args.proj =="car": dec = pos[0,:,0] ra = pos[1,0,:] lindec= linpos(shape[0],enmap.box(shape,wcs)[:,0]) scale = 1/np.cos(dec)-1 alpha[0] = (lindec-dec)[:,None] alpha[1] = ra[None,:]*scale[:,None] enmap.write_map(args.omap, alpha*180*60/np.pi)
theory_file_root = "../alhazen/data/Aug6_highAcc_CDM" theory = cosmology.loadTheorySpectraFromCAMB(theory_file_root, unlensedEqualsLensed=False, useTotal=False, TCMB=2.7255e6, lpad=9000, get_dimensionless=False) lmax = 2000 ells = np.arange(0, lmax, 1) cls = theory.lCl('TT', ells) ps = cls.reshape((1, 1, ells.size)) fullsky = enmap.read_map("/home/msyriac/data/act/downgraded_template.fits") #fullsky = enmap.read_map("/home/msyriac/data/act/multitracer_2arc.fits")[0] fshape, fwcs = fullsky.shape, fullsky.wcs posmap = enmap.posmap(fshape, fwcs) DECMIN = posmap[0].min() * 180. / np.pi DECMAX = posmap[0].max() * 180. / np.pi fullsky[posmap[0] < DECMIN * np.pi / 180.] = 0. fullsky[posmap[0] > DECMAX * np.pi / 180.] = 0. print(posmap.shape) # io.plot_img(np.flipud(fullsky),"full.png",high_res=True) print(fshape) height_dec = 15. num_decs = int((DECMAX - DECMIN) / height_dec) print(num_decs) dec_bounds = np.linspace(DECMIN, DECMAX, num_decs + 1) print(dec_bounds)
# Simulate lmax = int(bmodlmap.max()+1) ells = np.arange(0,lmax,1) ps = theory.uCl('TT',ells).reshape((1,1,lmax)) ps_noise = np.array([(noise_uK_rad)**2.]*ells.size).reshape((1,1,ells.size)) mg = maps.MapGen(bshape,bwcs,ps) ng = maps.MapGen(bshape,bwcs,ps_noise) kamp_true = args.Amp kappa = lensing.nfw_kappa(kamp_true*1e15,bmodrmap,cc,overdensity=200.,critical=True,atClusterZ=True) phi,_ = lensing.kappa_to_phi(kappa,bmodlmap,return_fphi=True) grad_phi = enmap.grad(phi) posmap = enmap.posmap(bshape,bwcs) pos = posmap + grad_phi alpha_pix = enmap.sky2pix(bshape,bwcs,pos, safe=False) lens_order = 5 ### FG PROFS famps = np.linspace(fmin,fmax,fnum) fg = kappa * 50. fg_true = maps.filter_map(fg.copy()*ftrue,kbeam) # Load covs bkamps = np.loadtxt(GridName+"/amps.txt",unpack=True) #[:1] # !!!
# Unlensed signal power2d = theory.uCl('TT', bmodlmap) bfcov = maps.diagonal_cov(power2d) sny, snx = shape ny, nx = bshape Ucov = maps.pixcov(bshape, bwcs, bfcov) Ucov = Ucov.reshape(np.prod(bshape), np.prod(bshape)) # Noise model kbeam = maps.gauss_beam(args.beam, bmodlmap) # Lens template lens_order = 5 posmap = enmap.posmap(bshape, bwcs) # Lens grid amin = 0.18 amax = 0.22 num_amps = 10 kamps = np.linspace(amin, amax, num_amps) cinvs = [] logdets = [] for k, kamp in enumerate(kamps): kappa_template = lensing.nfw_kappa(kamp * 1e15, bmodrmap, cc, overdensity=200.,
from enlib import enmap parser = argparse.ArgumentParser() parser.add_argument("omap") parser.add_argument("-D", "--diameter", type=float, default=30) parser.add_argument("-n", "--npix", type=int, default=800) parser.add_argument("--proj", type=str, default="cea") args = parser.parse_args() r = args.diameter * np.pi / 180 / 2 shape, wcs = enmap.geometry(pos=[[-r, -r], [r, r]], shape=(args.npix, args.npix), proj=args.proj) def linpos(n, b): return b[0] + (np.arange(n) + 0.5) * (b[1] - b[0]) / n alpha = enmap.zeros((2, ) + shape, wcs) pos = enmap.posmap(shape, wcs) # I'm not sure how to compute this in general, so here's a specialization # for cylindrical projections if args.proj == "cea" or args.proj == "car": dec = pos[0, :, 0] ra = pos[1, 0, :] lindec = linpos(shape[0], enmap.box(shape, wcs)[:, 0]) scale = 1 / np.cos(dec) - 1 alpha[0] = (lindec - dec)[:, None] alpha[1] = ra[None, :] * scale[:, None] enmap.write_map(args.omap, alpha * 180 * 60 / np.pi)
# Set up our likelihood L = Likelihood(data, srcpos[:,sids], amps[sids]) # Find out which sources are reliable, so we don't waste time on bad ones if prune_unreliable_srcs: _, aicov = L.fit_amp() good = amps[sids]**2*aicov[:,0] > args.minsn**2 sids = [sid for sid,g in zip(sids,good) if g] nsrc = len(sids) print("Restricted to %d srcs: %s" % (nsrc,", ".join(["%d (%.1f)" % (i,a) for i,a in zip(sids,amps[sids])]))) if nsrc == 0: continue L = Likelihood(data, srcpos[:,sids], amps[sids], perdet=perdet, thumbs=True, N=L.N, method=args.method) # And minimize chisq progress_thumbs = args.minimaps and verbose >= 3 likfun = L.chisq_wrapper(thumb_path=args.odir + "/" + oid + "_thumb%03d.fits", thumb_interval=progress_thumbs) grid_shape, grid_wcs = build_grid_geometry(grid_bounds, grid_res) grid_pos = enmap.posmap(grid_shape, grid_wcs) + L.off0[:,None,None] grid_lik = eval_offs(L, likfun, grid_pos) enmap.write_map(args.odir + "/grid_%s.fits" % oid, grid_lik) x0 = enmap.argmin(grid_lik) + L.off0 x0 = L.zip(x0) off = L.unzip(optimize.fmin_powell(likfun,x0)) # Evaluate the ampitude at the ML point oamps, oaicov = L.fit_amp(off) #chisq, oamps, oaicov = likfun(off, full=True) if args.minimaps: thumbs = L.make_thumbs(off, oamps) enmap.write_map(args.odir + "/" + oid + "_thumb.fits", thumbs) # Estimate position errors using a few extra samples doff = L.estimate_error(off) # Estimate our total S/N. We know that our amplitudes should be positive, so