Esempio n. 1
0
def signal_average(cov,bin_edges=None,bin_width=40,kind=3,lmin=None,dlspace=True,return_bins=False,**kwargs):
    """
    dcov = cov * ellfact
    bin dcov in annuli
    interpolate back on to ell
    cov = dcov / ellfact
    where ellfact = ell**2 if dlspace else 1
    """
    modlmap = cov.modlmap()
    assert np.all(np.isfinite(cov))

    dcov = cov*modlmap**2. if dlspace else cov.copy()
    if lmin is None:
        minell = maps.minimum_ell(dcov.shape,dcov.wcs)
    else:
        minell = modlmap[modlmap<=lmin].max()

    if bin_edges is None: bin_edges = np.append([2],np.arange(minell,modlmap.max(),bin_width))

    binner = stats.bin2D(modlmap,bin_edges)
    cents,c1d = binner.bin(dcov)

    outcov = enmap.enmap(maps.interp(cents,c1d,kind=kind,fill_value=c1d[-1],**kwargs)(modlmap),dcov.wcs)
    with np.errstate(invalid='ignore'): outcov = outcov / modlmap**2. if dlspace else outcov
    outcov[modlmap<2] = 0
    assert np.all(np.isfinite(outcov))

    if return_bins: return cents,c1d,outcov
    else: return outcov 
Esempio n. 2
0
        dscov = tilec.signal_average(scov, bin_width=40)

        print("Noise avg...")

        if isplanck(aindex1) or isplanck(aindex2):
            do_radial = False
        elif aindex1 == aindex2:
            do_radial = True
        else:
            do_radial = False
        # dncov,_ = tilec.noise_average(ncov,radial_fit=do_radial) if ((aindex1==aindex2) or is90150(aindex1,aindex2)) else (0.,None)
        dncov, _ = tilec.noise_average(ncov, radial_fit=do_radial) if (
            aindex1 == aindex2) else (0., None)  # ignore 90 / 150

        if isplanck(aindex1) and isplanck(aindex2):
            lmin = maps.minimum_ell(shape, wcs)
        else:
            lmin = 300

        sel = np.logical_or(modlmap < lmin, modlmap > lmax)
        ifwhm, jfwhm = get_beams(aindex1, aindex2)
        dncov /= np.nan_to_num(
            maps.gauss_beam(modlmap, ifwhm) * maps.gauss_beam(modlmap, jfwhm))
        dscov /= np.nan_to_num(
            maps.gauss_beam(modlmap, ifwhm) * maps.gauss_beam(modlmap, jfwhm))
        # dncov[sel] = 1e90 #np.inf # inf gives invertible matrix but nonsensical output, 1e90 gives noninvertible, but with eigpow sensible
        # dscov[sel] = 1e90 #np.inf

        # io.plot_img((np.fft.fftshift(ncov)),"tuncov%d%d.png"%(aindex1,aindex2),aspect='auto')
        # io.plot_img(np.log10(np.fft.fftshift(scov+ncov)),"udsncov%d%d.png"%(aindex1,aindex2),aspect='auto',lim=[-5,1])
        # io.plot_img(np.log10(np.fft.fftshift(ncov)),"uncov%d%d.png"%(aindex1,aindex2),aspect='auto',lim=[-5,1])
Esempio n. 3
0
from szar import foregrounds as fgs
import soapack.interfaces as sints
from tilec import ilc,utils as tutils
from scipy.optimize import curve_fit

ells = np.arange(2,8000,1)


region = 'deep56'

mask = enmap.read_map("/scratch/r/rbond/msyriac/data/depot/tilec/test_v1.1.0_rc_deep56/tilec_mask.fits")
w2 = np.mean(mask**2.)
template = mask
shape,wcs = template.shape,template.wcs
modlmap = template.modlmap()
minell = maps.minimum_ell(shape,wcs)
bin_edges = np.arange(80,8000,2*minell)
binner = stats.bin2D(modlmap,bin_edges)

cents = binner.centers
ctheory = ilc.CTheory(cents)

#arrays = "p01,p02,p03,p04,p05,p06,p07,p08".split(',')
arrays = "d56_01,d56_02,d56_03,d56_04,d56_05,d56_06,p01,p02,p03,p04,p05,p06,p07,p08".split(',')
narrays = len(arrays)
for qind1 in range(narrays):
    for qind2 in range(qind1,narrays):
        
        qid1 = arrays[qind1]
        qid2 = arrays[qind2]
Esempio n. 4
0
def calculate_yy(bin_edges,arrays,region,version,cov_versions,beam_version,
                 effective_freq,overwrite,maxval,unsanitized_beam=False,do_weights=False,
                 pa1_shift = None,
                 pa2_shift = None,
                 pa3_150_shift = None,
                 pa3_090_shift = None,
                 no_act_color_correction=False, ccor_exp = -1,
                 sim_splits=None,unblind=False,all_analytic=False,beta_samples=None):


    """
    
    We calculate the yy power spectrum as follows.
    We restrict the Fourier modes in our analysis to those within bin_edges.
    This way we don't carry irrelevant pixels and thus speed up the ability to MC.
    We accept two covariance versions in cov_versions, which correspond to 
    [act_covariance_from_split_0,act_covariance_from_split_1,other_covs].
    Thus the ACT auto covariances are pre-calculated

    """
    arrays = arrays.split(',')
    narrays = len(arrays)
    if sim_splits is not None: assert not(unblind)
    def warn(): print("WARNING: no bandpass file found. Assuming array ",dm.c['id']," has no response to CMB, tSZ and CIB.")
    aspecs = tutils.ASpecs().get_specs
    bandpasses = not(effective_freq)
    savedir = tutils.get_save_path(version,region)
    assert len(cov_versions)==3
    covdirs = [tutils.get_save_path(cov_versions[i],region) for i in range(3)]
    for covdir in covdirs: assert os.path.exists(covdir)
    if not(overwrite):
        assert not(os.path.exists(savedir)), \
       "This version already exists on disk. Please use a different version identifier."
    try: os.makedirs(savedir)
    except:
        if overwrite: pass
        else: raise


    mask = enmap.read_map(covdir+"tilec_mask.fits")


    from scipy.ndimage.filters import gaussian_filter as smooth
    pm = enmap.read_map("/scratch/r/rbond/msyriac/data/planck/data/pr2/COM_Mask_Lensing_2048_R2.00_car_deep56_interp_order0.fits")
    wcs = pm.wcs
    mask = enmap.enmap(smooth(pm,sigma=10),wcs) * mask


    shape,wcs = mask.shape,mask.wcs
    Ny,Nx = shape
    modlmap = enmap.modlmap(shape,wcs)
    omodlmap = modlmap.copy()
    ells = np.arange(0,modlmap.max())
    minell = maps.minimum_ell(shape,wcs)
    sel = np.where(np.logical_and(modlmap>=bin_edges[0]-minell,modlmap<=bin_edges[-1]+minell))
    modlmap = modlmap[sel]

    bps = []
    lbeams = []
    kbeams = []
    shifts = []
    cfreqs = []
    lmins = []
    lmaxs = []
    names = []
    for i,qid in enumerate(arrays):
        dm = sints.models[sints.arrays(qid,'data_model')](region=mask,calibrated=True)
        if dm.name=='act_mr3':
            season,array1,array2 = sints.arrays(qid,'season'),sints.arrays(qid,'array'),sints.arrays(qid,'freq')
            array = '_'.join([array1,array2])
        elif dm.name=='planck_hybrid':
            season,patch,array = None,None,sints.arrays(qid,'freq')
        else:
            raise ValueError
        lmin,lmax,hybrid,radial,friend,cfreq,fgroup,wrfit = aspecs(qid)
        lmins.append(lmin)
        lmaxs.append(lmax)
        names.append(qid)
        cfreqs.append(cfreq)
        if bandpasses:
            try: 
                fname = dm.get_bandpass_file_name(array) 
                bps.append("data/"+fname)
                if (pa1_shift is not None) and 'PA1' in fname:
                    shifts.append(pa1_shift)
                elif (pa2_shift is not None) and 'PA2' in fname:
                    shifts.append(pa2_shift)
                elif (pa3_150_shift is not None) and ('PA3' in fname) and ('150' in fname):
                    shifts.append(pa3_150_shift)
                elif (pa3_090_shift is not None) and ('PA3' in fname) and ('090' in fname):
                    shifts.append(pa3_90_shift)
                else:
                    shifts.append(0)

            except:
                warn()
                bps.append(None)
        else:
            try: bps.append(cfreq)
            except:
                warn()
                bps.append(None)

        kbeam = tutils.get_kbeam(qid,modlmap,sanitize=not(unsanitized_beam),version=beam_version,planck_pixwin=True)
        if dm.name=='act_mr3':
            lbeam = tutils.get_kbeam(qid,ells,sanitize=not(unsanitized_beam),version=beam_version,planck_pixwin=False) # note no pixwin but doesnt matter since no ccorr for planck
        elif dm.name=='planck_hybrid':
            lbeam = None
        else:
            raise ValueError
        lbeams.append(lbeam)
        kbeams.append(kbeam.copy())
    # Make responses
    responses = {}

    def _get_response(comp,param_override=None):
        if bandpasses:
            if no_act_color_correction:
                r = tfg.get_mix_bandpassed(bps, comp, bandpass_shifts=shifts,
                                           param_dict_override=param_override)
            else:
                r = tfg.get_mix_bandpassed(bps, comp, bandpass_shifts=shifts,
                                           ccor_cen_nus=cfreqs, ccor_beams=lbeams, 
                                           ccor_exps = [ccor_exp] * narrays,
                                           param_dict_override=param_override)
        else:
            r = tfg.get_mix(bps, comp,param_dict_override=param_override)
        return r

    for comp in ['tSZ','CMB','CIB']:
        responses[comp] = _get_response(comp,None)


    
    from tilec.utils import is_planck
    ilcgens = []
    okcoadds = []
    for splitnum in range(2):
        covdir = covdirs[splitnum]
        kcoadds = []
        for i,qid in enumerate(arrays):
            lmin = lmins[i]
            lmax = lmaxs[i]

            if is_planck(qid):
                dm = sints.models[sints.arrays(qid,'data_model')](region=mask,calibrated=True)

                _,kcoadd,_ = kspace.process(dm,region,qid,mask,
                                            skip_splits=True,
                                            splits_fname=sim_splits[i] if sim_splits is not None else None,
                                            inpaint=False,fn_beam = None,
                                            plot_inpaint_path = None,
                                            split_set=splitnum)
            else:
                kcoadd_name = covdir + "kcoadd_%s.npy" % qid
                kcoadd = enmap.enmap(np.load(kcoadd_name),wcs)

            kmask = maps.mask_kspace(shape,wcs,lmin=lmin,lmax=lmax)
            dtype = kcoadd.dtype
            kcoadds.append((kcoadd.copy()*kmask)[sel])

        kcoadds = enmap.enmap(np.stack(kcoadds),wcs)
        okcoadds.append(kcoadds.copy())


        # Read Covmat
        ctheory = ilc.CTheory(modlmap)
        nells = kcoadds[0].size
        cov = np.zeros((narrays,narrays,nells))
        for aindex1 in range(narrays):
            for aindex2 in range(aindex1,narrays):
                qid1 = names[aindex1]
                qid2 = names[aindex2]
                if is_planck(names[aindex1]) or is_planck(names[aindex2]) or all_analytic:
                    lmin,lmax,hybrid,radial,friend,f1,fgroup,wrfit = aspecs(qid1)
                    lmin,lmax,hybrid,radial,friend,f2,fgroup,wrfit = aspecs(qid2)
                    # If both are Planck and same array, get white noise from last bin
                    icov = ctheory.get_theory_cls(f1,f2,a_cmb=1,a_gal=0.8)*kbeams[aindex1]*kbeams[aindex2]
                    if aindex1==aindex2:
                        pcov = enmap.enmap(np.load(covdirs[2]+"tilec_hybrid_covariance_%s_%s.npy" % (names[aindex1],names[aindex2])),wcs)
                        pbin_edges = np.append(np.arange(500,3000,200) ,[3000,4000,5000,5800])
                        pbinner = stats.bin2D(omodlmap,pbin_edges)
                        w = pbinner.bin(pcov)[1][-1]
                        icov = icov + w
                else:
                    icov = np.load(covdir+"tilec_hybrid_covariance_%s_%s.npy" % (names[aindex1],names[aindex2]))[sel]
                if aindex1==aindex2: 
                    icov[modlmap<lmins[aindex1]] = maxval
                    icov[modlmap>lmaxs[aindex1]] = maxval
                cov[aindex1,aindex2] = icov
                cov[aindex2,aindex1] = icov

        assert np.all(np.isfinite(cov))

        ilcgen = ilc.HILC(modlmap,np.stack(kbeams),cov=cov,responses=responses,invert=True)
        ilcgens.append(ilcgen)
      

    solutions = ['tSZ','tSZ-CMB','tSZ-CIB']
    ypowers = {}
    w2 = np.mean(mask**2.)
    binner = stats.bin2D(modlmap,bin_edges)
    np.random.seed(100)
    blinding = np.random.uniform(0.8,1.2) if not(unblind) else 1


    def _get_ypow(sname,dname,dresponse=None,dcmb=False):

        if dresponse is not None:
            assert dname is not None
            for splitnum in range(2):
                ilcgens[splitnum].add_response(dname,dresponse)

        ykmaps = []
        for splitnum in range(2):
            if dcmb:
                assert dname is not None
                ykmap = ilcgens[splitnum].multi_constrained_map(okcoadds[splitnum],sname,[dname,"CMB"])
            else:
                if dname is None:
                    ykmap = ilcgens[splitnum].standard_map(okcoadds[splitnum],sname)
                else:
                    ykmap = ilcgens[splitnum].constrained_map(okcoadds[splitnum],sname,dname)
            ykmaps.append(ykmap.copy())

        ypower = (ykmaps[0]*ykmaps[1].conj()).real / w2
        return binner.bin(ypower)[1] * blinding


    # The usual solutions
    for solution in solutions:

        sols = solution.split('-')
        if len(sols)==2:
            sname = sols[0]
            dname = sols[1]
        elif len(sols)==1:
            sname = sols[0]
            dname = None
        else:
            raise ValueError

        ypowers[solution] = _get_ypow(sname,dname,dresponse=None)


    # The CIB SED samples
    if beta_samples is not None:
        y_bsamples = []
        y_bsamples_cmb = []
        for beta in beta_samples:
            pdict = tfg.default_dict.copy()
            pdict['beta_CIB'] = beta
            response = _get_response("CIB",param_override=pdict)
            y_bsamples.append(  _get_ypow("tSZ","iCIB",dresponse=response,dcmb=False) )
            y_bsamples_cmb.append(  _get_ypow("tSZ","iCIB",dresponse=response,dcmb=True) )
    else:
        y_bsamples = None
        y_bsamples_cmb = None


    return binner.centers,ypowers,y_bsamples,y_bsamples_cmb
Esempio n. 5
0
# What am I doing?
my_tasks = each_tasks[rank]

# Read config
iniFile = "../halofg/input/recon.ini"
Config = SafeConfigParser()
Config.optionxform = str
Config.read(iniFile)

pol = False
shape_sim, wcs_sim, shape_dat, wcs_dat = aio.enmaps_from_config(
    Config, sim_section, analysis_section, pol=pol)
analysis_resolution = np.min(
    enmap.extent(shape_dat, wcs_dat) / shape_dat[-2:]) * 60. * 180. / np.pi
min_ell = fmaps.minimum_ell(shape_dat, wcs_dat)
lb = aio.ellbounds_from_config(Config, "reconstruction_small", min_ell)
tellmin = lb['tellminY']
tellmax = lb['tellmaxY']
pellmin = lb['pellminY']
pellmax = lb['pellmaxY']
kellmin = lb['kellmin']
kellmax = lb['kellmax']
parray_dat = aio.patch_array_from_config(Config,
                                         expf_name,
                                         shape_dat,
                                         wcs_dat,
                                         dimensionless=True)
parray_sim = aio.patch_array_from_config(Config,
                                         expf_name,
                                         shape_sim,
Esempio n. 6
0
def noise_block_average(n2d,nsplits,delta_ell,lmin=300,lmax=8000,wnoise_annulus=500,bin_annulus=20,
                        lknee_guess=3000,alpha_guess=-4,nparams=None,
                        verbose=False,radial_fit=True,fill_lmax=None,fill_lmax_width=100,log=True,
                        isotropic_low_ell=True,allow_low_wnoise=False):
    """Find the empirical mean noise binned in blocks of dfact[0] x dfact[1] . Preserves noise anisotropy.
    Most arguments are for the radial fitting part.
    A radial fit is divided out before downsampling (by default by FFT) and then multplied back with the radial fit.
    Watch for ringing in the final output.
    n2d noise power


    n2d -- the [...,Ny,Nx] 2d power to smooth
    nsplits -- the number of splits from which the 2d noise power was estimated. This needs to be known
    if log is True, in which case the power is log-transformed before smoothing, which changes the statistics
    of the samples and hence needs a pre-determined correction based on the distribution of the original sample.
    log -- whether to log transform before smoothing. Should only be used if the power is positive (so should not
    be used e.g. if this is for the cross-noise of two components)
    delta_ell -- the block width in ell units for the smoothing. The smoothing effectively gets done in blocks
    of delta_ell x delta_ell.
    
    radial_fit -- if True, divides out a fit to the 1d power
    lmin -- lmin for the radial fit
    lmax -- lmax for the radial fit (adjust based on resolution of map)
    wnoise_annulus -- width of annulus in ell within which to estimate high ell white noise (adjust based on resolution)
    bin_annulus -- width of 1d bins (IMPORTANT: adjust based on map size)
    lknee_guess -- guess lknee for fit
    alpha_guess -- guess alpha for fit
    nparams -- optionally pass in a radial fit's parameters
    verbose -- print more
    fill_lmax -- fill power outside this lmax with the mean of the annulus between fill_lmax and fill_lmax_width
    fill_lmax_width -- see above
    isotropic_low_ell -- fill below lmin with an isotropic fit to the 1d power
    allow_low_wnoise -- allow white noise level to be negative (for debugging)
    """
    assert np.all(np.isfinite(n2d))
    if log: assert np.all(n2d>0), "You can't log smooth a PS with negative or zero power. Use log=False for these."
    shape,wcs = n2d.shape,n2d.wcs
    modlmap = n2d.modlmap()
    minell = maps.minimum_ell(shape,wcs)
    Ny,Nx = shape[-2:]
    if radial_fit:
        with bench.show("radial fit"):
            if nparams is None:
                if verbose: print("Radial fitting...")
                nparams = fit_noise_1d(n2d,lmin=lmin,lmax=lmax,wnoise_annulus=wnoise_annulus,
                                       bin_annulus=bin_annulus,lknee_guess=lknee_guess,alpha_guess=alpha_guess,
                                       allow_low_wnoise=allow_low_wnoise)
            wfit,lfit,afit = nparams
            nfitted = rednoise(modlmap,wfit,lfit,afit)
    else:
        nparams = None
        nfitted = n2d*0 + 1
    nfitted = np.maximum(nfitted,np.max(n2d)*1e-14)
    nflat = enmap.enmap(n2d/nfitted,wcs) # flattened 2d noise power
    fval = nflat[np.logical_and(modlmap>2,modlmap<2*minell)].mean()
    nflat[modlmap<2] = fval
    if fill_lmax is not None:
        fill_avg = nflat[np.logical_and(modlmap>(fill_lmax-fill_lmax_width),modlmap<=fill_lmax)].mean()
        nflat[modlmap>fill_lmax] = fill_avg
    if verbose: print("Resampling...")
    assert np.all(np.isfinite(nflat))
    with bench.show("smooth ps grid"):
        ndown = smooth_ps_grid(nflat, res=delta_ell, alpha=4, log=log, ndof=2*(nsplits-1))
    # pshow(nflat)
    # pshow(ndown)
    outcov = ndown*nfitted
    outcov[modlmap<minell] = 0
    if fill_lmax is not None: outcov[modlmap>fill_lmax] = 0
    assert np.all(np.isfinite(outcov))

    if isotropic_low_ell:
        with bench.show("isotropic low ell"):
            if radial_fit:
                ifunc = lambda ells,ell0,A,shell: (A*np.exp(-ell0/ells) + shell)
            sel = np.logical_and(modlmap<=lmin,modlmap>=2)

            ibin_edges = np.arange(minell,(lmin*2)+2*minell,2*minell)
            ibinner = stats.bin2D(modlmap,ibin_edges)
            cents,inls = ibinner.bin(nflat)
            ys = inls
            xs = cents
            if radial_fit:
                res,_ = curve_fit(ifunc,xs,ys,p0=[20,1,0],bounds=([2,0.,-np.inf],[lmin*2,np.inf,np.inf]))
                outcov[sel] = ifunc(modlmap[sel],res[0],res[1],res[2])*nfitted[sel]
            else:
                deg = 5
                res = np.polyfit(np.log(xs),np.log(ys*xs**2.),deg=deg)
                assert res.size==(deg+1)
                fitfunc = lambda x: sum([res[deg-p]*(x**p) for p in range(0,deg+1)[::-1]])
                outcov[sel] = (np.exp(fitfunc(np.log(modlmap[sel])))/modlmap[sel]**2.)*nfitted[sel]
            outcov[modlmap<2] = 0

        # fbin_edges = np.arange(minell,lmax,bin_annulus)
        # fbinner = stats.bin2D(modlmap,fbin_edges)
        # cents, n1d = fbinner.bin(nflat)
        # pl = io.Plotter(xyscale='loglog',xlabel='l',ylabel='D',scalefn=lambda x: x**2./2./np.pi)
        # ells = np.arange(minell,2*lmin,1)
        # if radial_fit:
        #     pl.add(ells,ifunc(ells,res[0],res[1],res[2]))
        # else:
        #     pl.add(xs,ys,ls="--")
        #     pl.add(ells,np.exp(fitfunc(np.log(ells)))/ells**2.)
        # pl.add(cents,n1d)
        # pl.vline(x=100)
        # pl.vline(x=200)
        # pl.vline(x=300)
        # pl.vline(x=500)
        # t = "000"
        # pl._ax.set_xlim(10,3000)
        # pl.done(os.environ['WORK']+"/iso_fitnoise2_%s.png" % t)



    # fbin_edges = np.arange(minell,lmax,bin_annulus)
    # fbinner = stats.bin2D(modlmap,fbin_edges)
    # cents, n1d = fbinner.bin(n2d)
    # cents,dn1d = fbinner.bin(outcov)
    # # cents,dn1d2 = fbinner.bin(nfitted)
    # pl = io.Plotter(xyscale='linlog',xlabel='l',ylabel='D',scalefn=lambda x: x**2./2./np.pi)
    # pl.add(cents,n1d)
    # pl.add(cents,dn1d,ls="--")
    # pl.vline(x=100)
    # pl.vline(x=200)
    # pl.vline(x=300)
    # pl.vline(x=500)
    # # pl.add(cents,dn1d2,ls="-.")
    # t = "000"
    # pl._ax.set_ylim(1e1,1e5)
    # pl.done(os.environ['WORK']+"/fitnoise2_%s.png" % t)
    # sys.exit()


    return outcov,nfitted,nparams
Esempio n. 7
0
def noise_average(n2d,dfact=(16,16),lmin=300,lmax=8000,wnoise_annulus=500,bin_annulus=20,
                  lknee_guess=3000,alpha_guess=-4,nparams=None,modlmap=None,
                  verbose=False,method="fft",radial_fit=True,
                  oshape=None,upsample=True,fill_lmax=None,fill_lmax_width=100):
    """Find the empirical mean noise binned in blocks of dfact[0] x dfact[1] . Preserves noise anisotropy.
    Most arguments are for the radial fitting part.
    A radial fit is divided out before downsampling (by default by FFT) and then multplied back with the radial fit.
    Watch for ringing in the final output.
    n2d noise power
    """
    assert np.all(np.isfinite(n2d))
    shape,wcs = n2d.shape,n2d.wcs
    minell = maps.minimum_ell(shape,wcs)
    if modlmap is None: modlmap = enmap.modlmap(shape,wcs)
    Ny,Nx = shape[-2:]
    if radial_fit:
        if nparams is None:
            if verbose: print("Radial fitting...")
            nparams = fit_noise_1d(n2d,lmin=lmin,lmax=lmax,wnoise_annulus=wnoise_annulus,
                                bin_annulus=bin_annulus,lknee_guess=lknee_guess,alpha_guess=alpha_guess)
        wfit,lfit,afit = nparams
        nfitted = rednoise(modlmap,wfit,lfit,afit)
    else:
        nparams = None
        nfitted = 1.
    nflat = enmap.enmap(np.nan_to_num(n2d/nfitted),wcs) # flattened 2d noise power
    if fill_lmax is not None:
        fill_avg = nflat[np.logical_and(modlmap>(fill_lmax-fill_lmax_width),modlmap<=fill_lmax)].mean()
        nflat[modlmap>fill_lmax] = fill_avg
    if oshape is None: oshape = (Ny//dfact[0],Nx//dfact[1])
    if verbose: print("Resampling...")
    nint = enmap.resample(enmap.enmap(nflat,wcs), oshape, method=method)
    if not(upsample):
        if radial_fit:
            nshape,nwcs = nint.shape,nint.wcs
            modlmap = enmap.modlmap(nshape,nwcs)
            nfitted = rednoise(modlmap,wfit,lfit,afit)
        ndown = nint
    else:
        ndown = enmap.enmap(enmap.resample(nint,shape,method=method),wcs)
    outcov = ndown*nfitted
    outcov[modlmap<minell] = 0 #np.inf
    if fill_lmax is not None: outcov[modlmap>fill_lmax] = 0
    # res,_ = curve_fit(ntemplatefunc,cents,dn1d,p0=[lknee_guess,alpha_guess],bounds=([lknee_min,alpha_min],[lknee_max,alpha_max]))



    # bad_ells = modlmap[np.isnan(outcov)]
    # for ell in bad_ells:
    #     print(ell)
    # print(maps.minimum_ell(shape,wcs))
    # from orphics import io
    # # io.hplot(enmap.enmap(np.fft.fftshift(np.log(n2d)),wcs),"fitnoise_npower.png")
    # # io.hplot(enmap.enmap(np.fft.fftshift(np.log(outcov)),wcs),"fitnoise_ndown.png")
    # io.plot_img(enmap.enmap(np.fft.fftshift(np.log(n2d)),wcs),"fitnoise_npower_lowres.png",aspect='auto')#,lim=[-20,-16])
    # io.plot_img(enmap.enmap(np.fft.fftshift(np.log(ndown)),wcs),"fitnoise_ndown_lowres.png",aspect='auto')#,lim=[-20,-16])
    # io.plot_img(enmap.enmap(np.fft.fftshift(np.log(outcov)),wcs),"fitnoise_outcov_lowres.png",aspect='auto')#,lim=[-20,-16])

    # import time
    # t = time.time()
    # fbin_edges = np.arange(lmin,lmax,bin_annulus)
    # fbinner = stats.bin2D(modlmap,fbin_edges)
    # cents, n1d = fbinner.bin(n2d)
    # cents,dn1d = fbinner.bin(outcov)
    # pl = io.Plotter(xyscale='linlog',xlabel='l',ylabel='D',scalefn=lambda x: x**2./2./np.pi)
    # pl.add(cents,n1d)
    # pl.add(cents,dn1d,ls="--")
    # pl.done(os.environ['WORK']+"/fitnoise2_%s.png" % t)
    # sys.exit()

    assert not(np.any(np.isnan(outcov)))
    return outcov,nfitted,nparams
    pcross2d = f2power(ik1.reshape((Ny, Nx)), ik2.reshape((Ny, Nx)))
    cents, p1d = binner.bin(pcross2d)
    s.add_to_stats(tag, p1d.copy())


def ncompute(ik, nk, tag):
    pauto2d = f2power(ik.reshape((Ny, Nx)), ik.reshape(
        (Ny, Nx))) - f2power(nk.reshape((Ny, Nx)), nk.reshape((Ny, Nx)))
    cents, p1d = binner.bin(pauto2d)
    s.add_to_stats(tag, p1d.copy())


shape, wcs = maps.rect_geometry(width_deg=width,
                                height_deg=height,
                                px_res_arcmin=px)
minell = maps.minimum_ell(shape, wcs)
lmax1 = lmax - minell

ells = np.arange(0, lmax, 1)
theory = cosmology.default_theory()

nu0 = 150.
if dust: cibkcorr = fg.kappa_cib_corrcoeff(ells)
ycorr = fg.y_kappa_corrcoeff(ells)

cltt = theory.lCl('tt', ells)
clkk = theory.gCl('kk', ells)
clss = fg.power_tsz(ells, nu0)
# pl = io.Plotter(xscale='log',yscale='log',scalefn=lambda x:x**2.)
# pl.add(ells,clss)
# pl._ax.set_xlim(2,1000)