예제 #1
0
파일: io.py 프로젝트: mjvakili/orphics
def high_res_plot_img(array,
                      filename=None,
                      down=None,
                      verbose=True,
                      overwrite=True,
                      crange=None,
                      cmap="planck"):
    if not (overwrite):
        if os.path.isfile(filename): return
    try:
        from enlib import enmap, enplot
    except:
        traceback.print_exc()
        cprint(
            "Could not produce plot " + filename +
            ". High resolution plotting requires enlib, which couldn't be imported. Continuing without plotting.",
            color='fail')
        return

    if (down is not None) and (down != 1):
        downmap = enmap.downgrade(enmap.enmap(array)[None], down)
    else:
        downmap = enmap.enmap(array)[None]
    img = enplot.draw_map_field(downmap,
                                enplot.parse_args("-c " + cmap + " -vvvg moo"),
                                crange=crange)
    #img = enplot.draw_map_field(downmap,enplot.parse_args("--grid 1"),crange=crange)
    if filename is None:
        img.show()
    else:
        img.save(filename)
        if verbose:
            print(bcolors.OKGREEN + "Saved high-res plot to",
                  filename + bcolors.ENDC)
예제 #2
0
def highResPlot2d(array,
                  outPath,
                  down=None,
                  verbose=True,
                  overwrite=True,
                  crange=None):
    if not (overwrite):
        if os.path.isfile(outPath): return
    try:
        from enlib import enmap, enplot
    except:
        traceback.print_exc()
        printC(
            "Could not produce plot " + outPath +
            ". High resolution plotting requires enlib, which couldn't be imported. Continuing without plotting.",
            color='fail')
        return

    if (down is not None) and (down != 1):
        downmap = enmap.downgrade(enmap.enmap(array)[None], down)
    else:
        downmap = enmap.enmap(array)[None]
    img = enplot.draw_map_field(downmap,
                                enplot.parse_args("-vvvg moo"),
                                crange=crange)
    img.save(outPath)
    if verbose:
        print(bcolors.OKGREEN + "Saved high-res plot to",
              outPath + bcolors.ENDC)
예제 #3
0
    def get_shear(self, do_m=True, do_c=True):
        rms = self.cat.data['ishape_hsm_regauss_derived_rms_e']
        m = self.cat.data['ishape_hsm_regauss_derived_bias_m']
        e1 = self.cat.data['ishape_hsm_regauss_e1']
        e2 = self.cat.data['ishape_hsm_regauss_e2']
        c1 = self.cat.data['ishape_hsm_regauss_derived_bias_c1']
        c2 = self.cat.data['ishape_hsm_regauss_derived_bias_c2']

        hsc_wts = self.hsc_wts
        wts = self.wts
        hsc_resp = 1. - np.nan_to_num(
            self.get_map(weights=(wts * (rms**2.))) / hsc_wts)
        hsc_m = np.nan_to_num(self.get_map(weights=(wts * (m))) /
                              hsc_wts) if do_m else hsc_wts * 0.

        hsc_e1 = self.get_map(weights=e1 * wts)
        hsc_e2 = self.get_map(weights=e2 * wts)

        hsc_c1 = np.nan_to_num(self.get_map(weights=c1 * wts) /
                               hsc_wts) if do_c else hsc_wts * 0.
        hsc_c2 = np.nan_to_num(self.get_map(weights=c2 * wts) /
                               hsc_wts) if do_c else hsc_wts * 0.

        g1map = np.nan_to_num(hsc_e1 / 2. / hsc_resp / (1. + hsc_m) /
                              hsc_wts) - np.nan_to_num(hsc_c1 / (1. + hsc_m))
        g2map = np.nan_to_num(hsc_e2 / 2. / hsc_resp / (1. + hsc_m) /
                              hsc_wts) - np.nan_to_num(hsc_c2 / (1. + hsc_m))

        if not self.curved:
            g1map = enmap.enmap(g1map, self.wcs)
            g2map = enmap.enmap(g2map, self.wcs)

        return g1map, g2map
예제 #4
0
def lens(ulensed,convergence):
    posmap = ulensed.posmap()
    kmask = maps.mask_kspace(ulensed.shape,ulensed.wcs,lmin=10,lmax=8000)
    phi,_ = lensing.kappa_to_phi(enmap.enmap(maps.filter_map(enmap.enmap(convergence,wcs),kmask),wcs),ulensed.modlmap(),return_fphi=True)
    grad_phi = enmap.grad(phi)
    pos = posmap + grad_phi
    alpha_pix = ulensed.sky2pix(pos, safe=False)
    lensed = enlensing.displace_map(ulensed, alpha_pix, order=5)
    return lensed
예제 #5
0
 def update_mask(self, mask_threshold):
     mask = np.zeros(self.shape)
     mask[self.mean_wt > mask_threshold] = 1
     self.mask = mask
     if not self.curved:
         self.mask = enmap.enmap(self.mask, self.wcs)
     self._counts()
예제 #6
0
    def __init__(self,
                 ras_deg,
                 decs_deg,
                 shape=None,
                 wcs=None,
                 nside=None,
                 verbose=True):

        self.verbose = verbose
        if nside is not None:
            if verbose: print("Calculating pixels...")
            self.pixs = hp.ang2pix(nside, ras_deg, decs_deg, lonlat=True)
            if verbose: print("Done with pixels...")
            self.nside = nside
            self.shape = hp.nside2npix(nside)
            self.curved = True
        else:
            coords = np.vstack((decs_deg, ras_deg)) * np.pi / 180.
            self.shape = shape
            self.wcs = wcs
            if verbose: print("Calculating pixels...")
            self.pixs = enmap.sky2pix(shape, wcs, coords,
                                      corner=True)  # should corner=True?!
            if verbose: print("Done with pixels...")
            self.curved = False
        self.counts = self.get_map()
        if not self.curved:
            self.counts = enmap.enmap(self.counts, self.wcs)
예제 #7
0
def get_patch(coords, sim_idx, map_type, cmb_type, pixel_fac = 2):
    shape,wcs = enmap.fullsky_geometry(res=1.0*np.pi/180./60.)

    def _process_coords(coords):
        coords = np.array(coords)
        if coords[1,1] > 180. : coords[1,1] -= 360.
        if coords[0,1] > 180. : coords[0,1] -= 360.

        coords *= np.pi/180.
        return coords

    zpsim_idx = '%05d' %sim_idx
    coords = _process_coords(coords)

    file_name = sim_file_temp.format(zpsim_idx, map_type, cmb_type, zpsim_idx)
    emap = enmap.read_fits(file_name, box=coords, wcs_override=wcs)

    nshape = tuple(np.array([i for i in emap.shape])*2)
    data   = simTools.resample_fft_withbeam(emap, nshape, doBeam=False, beamData=None)
    oshape, owcs = enmap.scale_geometry(emap.shape, emap.wcs, pixel_fac)

    assert(oshape == nshape)
    pmap   = enmap.enmap(data, owcs)

    return emap.to_flipper()
예제 #8
0
def getKappaSZ(bSims,snap,massIndex,px,thetaMapshape):
    b = bSims
    PIX = 2048
    maps, z, kappaSimDat, szMapuKDat, projectedM500, trueM500, trueR500, pxInRad, pxInRad = b.getMaps(snap,massIndex,freqGHz=150.)
    pxIn = pxInRad * 180.*60./np.pi
    hwidth = PIX*pxIn/2.
    print "At redshift ", z , " stamp is ", hwidth ," arcminutes wide."
    
    # input pixelization
    shapeSim, wcsSim = enmap.geometry(pos=[[-hwidth*arcmin,-hwidth*arcmin],[hwidth*arcmin,hwidth*arcmin]], res=pxIn*arcmin, proj="car")
    kappaSim = enmap.enmap(kappaSimDat,wcsSim)
    szMapuK = enmap.enmap(szMapuKDat,wcsSim)
    
    # downgrade to native
    shapeOut, wcsOut = enmap.geometry(pos=[[-hwidth*arcmin,-hwidth*arcmin],[hwidth*arcmin,hwidth*arcmin]], res=px*arcmin, proj="car")
    kappaMap = enmap.project(kappaSim,shapeOut,wcsOut)
    szMap = enmap.project(szMapuK,shapeOut,wcsOut)

    print thetaMapshape
    print szMap.shape

    if szMap.shape[0]>thetaMapshape[0]:
        kappaMap = enmap.project(kappaSim,thetaMapshape,wcsOut)
        szMap = enmap.project(szMapuK,thetaMapshape,wcsOut)
    else:
        diffPad = ((np.array(thetaMapshape) - np.array(szMap.shape))/2.+0.5).astype(int)
    
        apodWidth = 25
        kappaMap = enmap.pad(enmap.apod(kappaMap,apodWidth),diffPad)[:-1,:-1]
        szMap = enmap.pad(enmap.apod(szMap,apodWidth),diffPad)[:-1,:-1]
        # print szMap.shape
        assert szMap.shape==thetaMap.shape

    # print z, projectedM500
    # pl = Plotter()
    # pl.plot2d(kappaMap)
    # pl.done("output/kappasim.png")
    # pl = Plotter()
    # pl.plot2d(szMap)
    # pl.done("output/szsim.png")
    # sys.exit()

    # print "kappaint ", kappaMap[thetaMap*60.*180./np.pi<10.].mean()
    return kappaMap,szMap
def tqu2teb(tmap, qmap, umap):
    tqu = np.zeros((3, ) + tmap.shape)
    tqu[0], tqu[1], tqu[2] = (tmap, qmap, umap)
    tqu = enmap.enmap(tqu, tmap.wcs)
    alm = curvedsky.map2alm(tqu, lmax=lmax)

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

    return (teb[0], teb[1], teb[2])
예제 #10
0
def get_sim(sim_idx, beam_fwhm=beam_fwhm, noise_level=noise_level):
    ret = act_sim.getActpolCmbSim(None,
                                  coords,
                                  sim_idx,
                                  cmb_dir,
                                  doBeam=False,
                                  pixelFac=1)

    np.random.seed(sim_idx)

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

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

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

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

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

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

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

    return (tqu[0], tqu[1], tqu[2])  # TQU
예제 #11
0
 def A(self, x):
     m = enmap.enmap(x.reshape(self.shape), self.wcs, copy=False)
     res = m * 0
     for dataset in self.datasets:
         for split in dataset.splits:
             if split.data.empty or not split.active: continue
             w = split.data.H * m
             w = map_ifft(map_fft(w) * dataset.iN)
             w *= split.data.H
             res += w
     # Apply resolution mask
     res *= self.highres_mask
     return res.reshape(-1)
예제 #12
0
파일: sims.py 프로젝트: mntw/szar
    def get_map(self,component,mass_index,snap,shape=None,wcs=None):
        if shape is None: 
            assert wcs is None
            shape,wcs = self.get_geometry(snap)
            assert np.all(shape==(self.PIX,self.PIX))
        
        filen = self.files[component](mass_index,snap)
        with open(filen, 'rb') as fd:
            temp = np.fromfile(file=fd, dtype=np.float32)

        dat = np.reshape(temp,shape) * self.h # THIS NEEDS DEBUGGING
        imap = enmap.enmap(dat,wcs)
        return imap
예제 #13
0
def read_maps(fmt, n, ntot=4):
    try:
        maps = en.read_map(fmt)
        if maps.ndim == ntot - 1: maps = en.enmap([maps] * n, maps.wcs)
        if maps.ndim != ntot:
            raise ValueError("Map %s must have %d dimensions" % (fmt, ntot))
        return maps
    except (IOError, OSError):
        maps = [en.read_map(fmt % i) for i in range(n)]
        maps = en.ndmap(maps, maps[0].wcs)
        if maps.ndim != ntot:
            maps = maps.reshape(maps.shape[:-2] + (1, ) * (maps.ndim - ntot) +
                                maps.shape[-2:])
        return maps
예제 #14
0
    def update_mask(self,rand_sigma_arcmin=2.,rand_threshold=1e-3):
        if rand_sigma_arcmin>1.e-3:
            if self.verbose: print( "Smoothing...")
            if self.curved:
                smap = hp.smoothing(self.rand_map,sigma=rand_sigma_arcmin*np.pi/180./60.)
            else:
                smap = enmap.smooth_gauss(self.rand_map,rand_sigma_arcmin*np.pi/180./60.)
            if self.verbose: print( "Done smoothing...")
        else:
            if self.verbose: smap = self.rand_map

        self.mask = np.zeros(self.shape)
        self.mask[smap>rand_threshold] = 1
        if not self.curved:
            self.mask = enmap.enmap(self.mask,self.wcs)
        self._counts()
예제 #15
0
    def __init__(self,ras_deg,decs_deg,shape=None,wcs=None,nside=None,verbose=True,hp_coords="equatorial"):

        self.verbose = verbose
        if nside is not None:

            eq_coords = ['fk5','j2000','equatorial']
            gal_coords = ['galactic']

            if verbose: print( "Calculating pixels...")
            if hp_coords in gal_coords:
                if verbose: print( "Transforming coords...")
                from astropy.coordinates import SkyCoord
                import astropy.units as u
                gc = SkyCoord(ra=ras_deg*u.degree, dec=decs_deg*u.degree, frame='fk5')
                gc = gc.transform_to('galactic')
                phOut = gc.l.deg * np.pi/180.
                thOut = gc.b.deg * np.pi/180.
                thOut = np.pi/2. - thOut #polar angle is 0 at north pole

                self.pixs = hp.ang2pix( nside, thOut, phOut )
            elif hp_coords in eq_coords:
                ras_out = ras_deg
                decs_out = decs_deg
                lonlat = True
                self.pixs = hp.ang2pix(nside,ras_out,decs_out,lonlat=lonlat)
                
            else:
                raise ValueError
                
            if verbose: print( "Done with pixels...")
            self.nside = nside
            self.shape = hp.nside2npix(nside)
            self.curved = True
        else:
            coords = np.vstack((decs_deg,ras_deg))*np.pi/180.
            self.shape = shape
            self.wcs = wcs
            if verbose: print( "Calculating pixels...")
            self.pixs = enmap.sky2pix(shape,wcs,coords,corner=True) # should corner=True?!
            if verbose: print( "Done with pixels...")
            self.curved = False
        self.counts = self.get_map()
        if not self.curved:
            self.counts = enmap.enmap(self.counts,self.wcs)

        self.mask = np.ones(shape)
        self._counts()
예제 #16
0
 def __call__(fself, x):
     params = param_zipper.unzip(x)
     chisqs, amps, adiv = self.calc_chisqs_amps_cached(
         params.poss, params.taus)
     #print amps[433], adiv[433]
     chisq = np.sum(chisqs)
     if verbosity > 0 and fself.i % 10 == 0:
         if verbosity == 1:
             print("%6d %12.4f" % (fself.i, chisq / self.ndata))
         else:
             print("%6d %12.4f" % (fself.i, chisq / self.ndata) +
                   " %6.3f" * len(x) % tuple(x))
         sys.stdout.flush()
         if False and fself.i % 10000 == 0:
             model = self.model(params.poss, amps, params.taus)
             map = enmap.enmap(
                 [self.rdata.tod, model, self.rdata.tod - model])
             enmap.write_map(args.odir + "/foo%06d.fits" % fself.i,
                             map)
     fself.i += 1
     return chisq
예제 #17
0
	tweight = None
	for sub in range(nsub):
		pre = args.idir + "/" + tag % sub
		opre = args.odir + "/" + tag % sub
		# Weight map
		if div:
			weight = vread(pre + "div.fits")
			if weight.ndim == 4: weight = weight[0,0]
		elif noise:
			weight = vread(pre + "noise.fits")
			weight[weight>0] = weight[weight>0]**-2
		else:
			weight = vread(pre + "weights_I.fits")
		# CMB map
		map = [vread(pre + args.wpoly + "%d_%s.fits" % (step, comp)) for comp in ["I","Q","U"]]
		map = enmap.enmap(map, map[0].wcs)
		# Input used, if available
		if iused and not args.wpoly:
			for i, comp in enumerate(["I","Q","U"]):
				base = vread(pre + "input_used_%s.fits" % comp)
				map[i,weight>0] += base[weight>0]
		nosrc = map.copy()
		# Point source template, if available
		if beam:
			srcs = vread(pre + "beam_test.fits")
			map[0][weight>0] += srcs[weight>0]
			if args.single % 2 > 0:
				vwrite(opre + "nosrc_%04d.fits" % step, nosrc)
		if args.single % 2 > 0:
			vwrite(opre + "map_%04d.fits"   % step, map)
			vwrite(opre + "div.fits", weight)
                                  coords,
                                  sim_idx,
                                  cmb_dir,
                                  doBeam=False,
                                  pixelFac=2)

    for i in range(len(ret)):
        ret[i] = enmap.from_flipper(ret[i])
        ret[i] -= np.mean(ret[i])
    return (ret[0], ret[1], ret[2])  # TQU


temp_map, _, _ = get_sim(0)
shape, wcs = temp_map.shape, temp_map.wcs
taper, _ = maps.get_taper(shape)
taper = enmap.enmap(taper, wcs=wcs)

# initialize cusps
overwrite = False
mcm_identifier = "%lsd_le%d_nb%d_lm%d_%s_%s" % (0, lmax, nbin, lmax,
                                                coords_str, postfix)
cusps_fc = cusps.power.CUSPS(mcm_identifier, taper, taper, bin_edges, lmax,
                             None, overwrite)
binner = cusps_fc.binner

# bin the theory
theo_bin = {}
lbin_th, theo_bin['dltt'] = cusps_fc.bin_theory_scalarxscalar(
    l_th, theo['dltt'])
lbin_th, theo_bin['dlte'] = cusps_fc.bin_theory_scalarxscalar(
    l_th, theo['dlte'])
예제 #19
0
		# Overwrite with copies of first half-stroke
		n = ndelay/4
		x = np.linspace(0, 1, n+1, endpoint=False)
		apod = (1+(x/0.99)**2000)**-1
		moo = (d[:,:,:,:n+1]-d[:,:,:,n,None])*apod + d[:,:,:,n,None]
		print apod
		d[:,:,:,2*n:3*n] = moo[:,:,:,0*n:1*n]
		d[:,:,:,1*n:2*n] = moo[:,:,:,n:0:-1]
		d[:,:,:,3*n:4*n] = moo[:,:,:,n:0:-1]
	# Go from stroke to spectrum. This takes us to W/sr/m^2/Hz
	d   = fft.rfft(d).real[...,::2]*2/ndelay/dfreq
	#dump(pre+"_4", d)
	# Unapply the frequency filter
	freqs = np.arange(d.shape[-1])*dfreq
	d  /= filter(freqs)
	#dump(pre+"_5", d)
	# Reorder from [stokes,det,theta,phi,freq] to [det,freq,stokes,theta,phi]
	d   = d[:,:,:,None,:]
	d   = utils.moveaxes(d, (1,4,0,2,3), (0,1,2,3,4))
	# Apply the detector responses.
	for di, det in enumerate(dets):
		d[di] = change_response(det.response, [1,1,0], d[di])
		d[di] = change_horn(det.horn, 0, d[di])
	# If we are in double barrel mode, then we're seeing
	# the sky double up. Compensate for this.
	if args.barrel_mode == "double":
		d /= 2
	# Output as a ring file
	m   = enmap.enmap(d, wcs, copy=False)
	enmap.write_map(pre + ".fits", m)
예제 #20
0
 def M(self, x):
     m = enmap.enmap(x.reshape(self.shape), self.wcs, copy=False)
     res = m * self.tot_idiv
     return res.reshape(-1)
예제 #21
0
posmap = enmap.posmap(gshape, gwcs)
pos = posmap + grad_phi
alpha_pix = enmap.sky2pix(gshape, gwcs, pos, safe=False)
kbeam = maps.gauss_beam(args.beam, gmodlmap)

mstats = stats.Stats()

for i in range(args.Nclusters):

    if (i + 1) % 100 == 0: print(i + 1)
    unlensed = mg.get_map()
    noise_map = ng.get_map()
    lensed = maps.filter_map(
        enlensing.displace_map(unlensed.copy(), alpha_pix, order=lens_order),
        kbeam)
    fdownsampled = enmap.enmap(resample.resample_fft(lensed, bshape), bwcs)
    stamp = fdownsampled + noise_map

    #cutout = lensed  + noise_map
    cutout = stamp[int(bshape[0] / 2. - shape[0] / 2.):int(bshape[0] / 2. +
                                                           shape[0] / 2.),
                   int(bshape[0] / 2. - shape[0] / 2.):int(bshape[0] / 2. +
                                                           shape[0] / 2.)]

    # print(cinvs[k].shape,cutout.shape)

    totlnlikes = []
    for k, kamp in enumerate(kamps):
        lnlike = maps.get_lnlike(cinvs[k], cutout) + logdets[k]
        totlnlike = lnlike  #+ lnprior[k]
        totlnlikes.append(totlnlike)
예제 #22
0
                    beam2d=okbeam,
                    kmask=tmask,
                    kmask_K=kmask,
                    pol=False,
                    grad_cut=2000,
                    unlensed_equals_lensed=False)

for i, task in enumerate(my_tasks):
    if (i + 1) % 10 == 0 and rank == 0: print(i + 1)

    # Sim
    unlensed = mg.get_map()
    noise_map = ng.get_map()
    lensed = maps.filter_map(
        enlensing.displace_map(unlensed, alpha_pix, order=lens_order), kbeam)
    fdownsampled = enmap.enmap(resample.resample_fft(lensed, oshape), owcs)
    stamp = fdownsampled + noise_map

    # Bayesian
    cutout = stamp[int(oshape[0] / 2. - bshape[0] / 2.):int(oshape[0] / 2. +
                                                            bshape[0] / 2.),
                   int(oshape[0] / 2. - bshape[0] / 2.):int(oshape[0] / 2. +
                                                            bshape[0] / 2.)]

    totlnlikes = []
    for k, kamp in enumerate(bkamps):
        lnlike = maps.get_lnlike(cinvs[k], cutout) + logdets[k]
        totlnlike = lnlike  #+ lnprior[k]
        totlnlikes.append(totlnlike)
    nlnlikes = -0.5 * np.array(totlnlikes)
    mstats.add_to_stats("totlikes", nlnlikes)
예제 #23
0
파일: makemask.py 프로젝트: msyriac/tenki
import numpy as np, argparse
from enlib import enmap
from scipy import ndimage
parser = argparse.ArgumentParser()
parser.add_argument("pos")
parser.add_argument("template")
parser.add_argument("ofile")
parser.add_argument("-r", "--radius", type=float, default=3)
parser.add_argument("-c", "--columns", type=str, default="3,5,2")
parser.add_argument("-t", "--threshold", type=float, default=0)
args = parser.parse_args()

cols = [int(w) for w in args.columns.split(",")]
srcinfo = np.loadtxt(args.pos)[:, cols]
pos = srcinfo[np.abs(srcinfo[:, 2]) >= args.threshold][:, :2] * np.pi / 180
map = enmap.read_map(args.template)
pix = map.sky2pix(pos.T).T.astype(int)

pixrad = (map.area() / map.npix)**0.5
mrad = args.radius * np.pi / 180 / 60 / pixrad

mask = enmap.zeros(map.shape[-2:], map.wcs) + 1
mask[pix[:, 0], pix[:, 1]] = 0
mask = enmap.enmap(1.0 * (ndimage.distance_transform_edt(mask) > mrad),
                   map.wcs)
enmap.write_map(args.ofile, mask)
예제 #24
0
파일: makemask.py 프로젝트: amaurea/tenki
import numpy as np, argparse
from enlib import enmap
from scipy import ndimage
parser = argparse.ArgumentParser()
parser.add_argument("pos")
parser.add_argument("template")
parser.add_argument("ofile")
parser.add_argument("-r", "--radius", type=float, default=3)
parser.add_argument("-c", "--columns", type=str, default="3,5,2")
parser.add_argument("-t", "--threshold", type=float, default=0)
args = parser.parse_args()

cols = [int(w) for w in args.columns.split(",")]
srcinfo = np.loadtxt(args.pos)[:,cols]
pos = srcinfo[np.abs(srcinfo[:,2])>=args.threshold][:,:2] * np.pi/180
map = enmap.read_map(args.template)
pix = map.sky2pix(pos.T).T.astype(int)

pixrad = (map.area()/map.npix)**0.5
mrad = args.radius*np.pi/180/60/pixrad

mask = enmap.zeros(map.shape[-2:], map.wcs)+1
mask[pix[:,0],pix[:,1]] = 0
mask = enmap.enmap(1.0*(ndimage.distance_transform_edt(mask) > mrad), map.wcs)
enmap.write_map(args.ofile, mask)
예제 #25
0
 opre = args.odir + "/" + tag % sub
 # Weight map
 if div:
     weight = vread(pre + "div.fits")
     if weight.ndim == 4: weight = weight[0, 0]
 elif noise:
     weight = vread(pre + "noise.fits")
     weight[weight > 0] = weight[weight > 0]**-2
 else:
     weight = vread(pre + "weights_I.fits")
 # CMB map
 map = [
     vread(pre + args.wpoly + "%d_%s.fits" % (step, comp))
     for comp in ["I", "Q", "U"]
 ]
 map = enmap.enmap(map, map[0].wcs)
 # Input used, if available
 if iused and not args.wpoly:
     for i, comp in enumerate(["I", "Q", "U"]):
         base = vread(pre + "input_used_%s.fits" % comp)
         map[i, weight > 0] += base[weight > 0]
 nosrc = map.copy()
 # Point source template, if available
 if beam:
     srcs = vread(pre + "beam_test.fits")
     map[0][weight > 0] += srcs[weight > 0]
     if args.single % 2 > 0:
         vwrite(opre + "nosrc_%04d.fits" % step, nosrc)
 if args.single % 2 > 0:
     vwrite(opre + "map_%04d.fits" % step, map)
     vwrite(opre + "div.fits", weight)
예제 #26
0
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)

rkappa = lens_func(rmodrmap)
phi, _ = lensing.kappa_to_phi(rkappa, rmodlmap, return_fphi=True)
grad_phi = enmap.grad(phi)
pos = enmap.posmap(rshape, rwcs) + grad_phi
ralpha_pix = enmap.sky2pix(rshape, rwcs, pos, safe=False)

hunlensed = enmap.enmap(resample.resample_fft(unlensed.copy(), rshape), rwcs)
enmap.write_map("unlensed_0.001arc.fits", hunlensed)
예제 #27
0
 def get_delta(self):
     delta = (self.counts / self.nmean - 1.)
     if not self.curved:
         delta = enmap.enmap(delta, self.wcs)
     return delta
예제 #28
0
        #fitter = SingleFitter(ref, maps[mi], divs[mi,:1,:1])
        fitter = SingleFitter(ref_small, map_small, div_small)
        p = fitter.fit(verbose=True)
        params.append(p)
    params = np.array(params)
    rhss = divs[:, None] * maps
    mrhss = apply_params(rhss, params, nooff=True)
    mdivs = apply_params(divs, params, nooff=True)
    mrhs = np.sum(mrhss, 0)
    mdiv = np.sum(mdivs, 0)
    ref = solve(mdiv, mrhs)
    # Compute median too. This is more robust to glitches, but not optimally weighted.
    smaps = apply_params(maps, params)
    mask = np.logical_or(np.repeat(mdivs[:, None] == 0, smaps.shape[1], 1),
                         smaps == 0)
    medmap = enmap.enmap(np.ma.median(np.ma.array(smaps, mask=mask), 0),
                         ref.wcs)

    ref = remove_offset(ref)
    medmap = remove_offset(medmap)

    with open(args.odir + "/fit_%03d.txt" % ri, "w") as f:
        for id, p in zip(ids, params):
            f.write(("%7.4f %7.4f %7.4f" + " %12.4f" *
                     (params.shape[-1] - 3) + " %s\n") % (tuple(p) + (id, )))
    enmap.write_map(args.odir + "/tot_map_%03d.fits" % ri, ref)
    enmap.write_map(args.odir + "/tot_div_%03d.fits" % ri, mdiv)
    enmap.write_map(args.odir + "/tot_med_%03d.fits" % ri, medmap)

    # Output the individual best fits too
    if args.individual:
        for i, id in enumerate(ids):
예제 #29
0
파일: planet_fit.py 프로젝트: amaurea/tenki
		div_small = eval("divs[mi]"+args.slice)
		#fitter = SingleFitter(ref, maps[mi], divs[mi,:1,:1])
		fitter = SingleFitter(ref_small, map_small, div_small)
		p = fitter.fit(verbose=True)
		params.append(p)
	params = np.array(params)
	rhss  = divs[:,None]*maps
	mrhss = apply_params(rhss, params, nooff=True)
	mdivs = apply_params(divs, params, nooff=True)
	mrhs = np.sum(mrhss,0)
	mdiv = np.sum(mdivs,0)
	ref  = solve(mdiv, mrhs)
	# Compute median too. This is more robust to glitches, but not optimally weighted.
	smaps = apply_params(maps, params)
	mask  = np.logical_or(np.repeat(mdivs[:,None]==0,smaps.shape[1],1), smaps==0)
	medmap= enmap.enmap(np.ma.median(np.ma.array(smaps,mask=mask),0),ref.wcs)

	ref     = remove_offset(ref)
	medmap  = remove_offset(medmap)

	with open(args.odir + "/fit_%03d.txt"%ri, "w") as f:
		for id, p in zip(ids,params):
			f.write(("%7.4f %7.4f %7.4f" + " %12.4f"*(params.shape[-1]-3) + " %s\n") %
					(tuple(p)+(id,)))
	enmap.write_map(args.odir + "/tot_map_%03d.fits" % ri, ref)
	enmap.write_map(args.odir + "/tot_div_%03d.fits" % ri, mdiv)
	enmap.write_map(args.odir + "/tot_med_%03d.fits" % ri, medmap)

	# Output the individual best fits too
	if args.individual:
		for i, id in enumerate(ids):