Example #1
0
def convolve_healpix(input_map, func=None, sigma=None, thetamax=10 ):
    """
    Convolve a HEALPix map with a function, or Gaussian
    input_map : array of float
        a HEALPix array, RING indexing, nside a power of 2
    func : The function of an integer el | None
        returns the amplitude for spherical harmonic el
        example: for a Gaussian with sigma in radians: 
          lambda el : np.exp(-0.5 * (el * (el + 1)) * sigma**2)

    sigma : None | float (deg)
        If not None, use gaussian for func
          
    Returns: the convolved map
    """
    import healpy
    nside = int(np.sqrt(len(input_map)/12))
    assert 12*nside**2 == len(input_map),'Bad length: expect power of 2'
    if func is None: 
        assert sigma is not None, 'If no func, must specify sigma'
        func= lambda el : np.exp(-0.5 * (el * (el + 1)) * np.radians(sigma)**2)
    else: 
        assert func(thetamax)/func(0) <1e-3
    alm = healpy.map2alm(input_map);
    lmax = healpy.Alm.getlmax(len(alm))
    if lmax < 0:
        raise TypeError('Wrong alm size for the given '
                        'mmax (len(alms[%d]) = %d).'%(ialm, len(alm)))
    ell = np.arange(lmax + 1.)
    fact = np.array([func(x) for x in ell])
    
    healpy.almxfl(alm, fact, inplace=True)
    return healpy.alm2map(alm, nside=nside, verbose=False)
def run_MCMC_new(which_par,niter,save_title, renorm_var):
    """
    Functions that runs the MCMC for a given set of parameters

    Keyword Arguments:
    which_par -- a list of indices, corresponding to the order defined above, exemple [0,2] means ombh2,tau if order is [ombh2,omch2,tau,As,ns,H0]
    niter -- number of iterations in MCMC
    renorm_var -- factor multipling the variance, to play around for better acceptance rate.
    """
    cov_new_temp = cov_new[which_par,:][:,which_par] * renorm_var
    string_temp = strings[which_par]
    titles_temp = titles[which_par]
    x_mean_temp = x_mean[which_par]
    priors_central_temp = priors_central[which_par]
    priors_invvar_temp = priors_invvar[which_par]
    print titles_temp
    # generate first guess parameters
    guess_param = PS2P.prop_dist_form_params(x_mean_temp,cov_new_temp)
    print "initial guess = ", guess_param
    # generate first fluctuation map
    dd2 = cb.update_dic(dd,guess_param,string_temp)
    cl = cb.generate_spectrum(dd2)[:,1]
    cl[:2] = 1.e-35
    renorm = CG.renorm_term(cl,bl,nl)
    fluc = hp.almxfl(CG.generate_w1term(cl[:lmax+1],bl[:lmax+1],nl[:lmax+1]) + CG.generate_w0term(cl[:lmax+1]),renorm)
    mf = hp.almxfl(CG.generate_mfterm(dlm,cl[:lmax+1],bl[:lmax+1],nl[:lmax+1]),renorm)
    # the core of the MCMC
    testss = np.array(MH.MCMC_log_Jeff_new(guess_param, JJi.target_new,PS2P.prop_dist_form_params, PS2P.prop_func_form_params,niter,PS2P.Gaussian_priors_func,[[dlm,string_temp,dd,nl[:lmax+1],bl[:lmax+1]],[cl[:lmax+1],fluc,mf]],[x_mean_temp*0,np.matrix(cov_new_temp)],[priors_central_temp,priors_invvar_temp]))
    np.save("chain_%s_%s_%d_%d.npy"%(save_title,str(which_par).replace(',','').replace('[','').replace(']','').replace(' ',''),np.random.randint(0,100000),niter),testss)
    return testss
Example #3
0
    def _icov_diag(self, alm, lens_power=False):    
        '''
        Return (in-place) inverse covariance weighted version if input.
        Assuming that covariance is diagonal in multipole.

        Parameters
        ----------
        alm : (npol, nelem) array
            Healpix-ordered alm array to be inverse weighted. Order: T, E.
        lens_power : bool, optional
            Include lensing power in invserse covariance.

        Returns
        -------
        c_inv_a : (npol, nelem) complex array
            Inverse covariance weighted input array.

        Raises
        ------
        ValueError
            If shape input alm does not match npol or exceeds lmax.
        '''

        if alm.ndim == 1:
            input_1d = True
            alm = np.atleast_2d(alm)
        else:
            input_1d = False

        if alm.shape[0] != self.npol:
            raise ValueError(
                'Shape alm: {} does not match with length of pol: {}.'
                .format(alm.shape, self.npol))
                    
        lmax_alm = hp.Alm.getlmax(alm.shape[-1])
        if lmax_alm > self.lmax:
            raise ValueError('lmax alm exceeds lmax icov ({} > {})'.
                             format(lmax_alm, self.lmax))
               
        if lens_power:
            icov = self.icov_ell_lensed
        else:
            icov = self.icov_ell_nonlensed

        if self.pol == ('T', 'E'):
            # Would be nice get rid of this copy with C or cython.
            tmp = alm.copy()
            hp.almxfl(tmp[0], icov[2,:lmax_alm+1], inplace=True)
            hp.almxfl(tmp[1], icov[2,:lmax_alm+1], inplace=True)
            hp.almxfl(alm[0], icov[0,:lmax_alm+1], inplace=True)            
            hp.almxfl(alm[1], icov[1,:lmax_alm+1], inplace=True)
            alm[1] += tmp[0]
            alm[0] += tmp[1]
        else:
            hp.almxfl(alm[0], icov[0,:lmax_alm+1], inplace=True)            
            
        if input_1d:
            return alm[0]
        else:
            return alm
Example #4
0
def _get_alms(data, beams=None, lmax=None, weights=None, iter=3):
    alms = []
    for f, fdata in enumerate(data):
        if weights is None:
            alms.append(hp.map2alm(fdata, lmax=lmax, iter=iter))
        else:
            alms.append(
                hp.map2alm(hp.ma(fdata) * weights, lmax=lmax, iter=iter))
        logging.info(f"{f+1} of {len(data)} complete")
    alms = np.array(alms)

    if beams is not None:
        logging.info('Correcting alms for the beams')
        for fwhm, alm in zip(beams, alms):
            bl = hp.gauss_beam(np.radians(fwhm / 60.0),
                               lmax,
                               pol=(alm.ndim == 2))
            if alm.ndim == 1:
                alm = [alm]
                bl = [bl]

            for i_alm, i_bl in zip(alm, bl.T):
                hp.almxfl(i_alm, 1.0 / i_bl, inplace=True)

    return alms
Example #5
0
def calc_prep(m, s_cls, n_inv_filt):
    """Missing doc."""
    kmap = np.copy(m)
    n_inv_filt.apply_map(kmap)
    alm = map2alm(kmap, lmax=len(n_inv_filt.b_transf) - 1, iter=0)
    hp.almxfl(alm, n_inv_filt.b_transf * (len(m) / (4. * np.pi)), inplace=True)
    return alm
Example #6
0
    def get_gpmap(self, idx, spin, k=None, xfilt=None):
        """
        \sum_{lm} (Elm +- iBlm) sqrt(l+2 (l-1)) _1 Ylm(n).
                                sqrt(l-2 (l+3)) _3 Ylm(n).
        Output is list with real and imaginary part of the spin 1 or 3 transforms.
        """
        assert spin in [1, 3]
        assert xfilt is None, 'not implemented'
        Glm = self.ivfs.get_sim_emliklm(idx)
        Clm = self.ivfs.get_sim_bmliklm(idx)

        assert Glm.size == Clm.size, (Clm.size, Clm.size)
        lmax = hp.Alm.getlmax(Glm.size)
        if spin == 1:
            fl = np.arange(2, lmax + 3, dtype=float) * (np.arange(-1, lmax))
        elif spin == 3:
            fl = np.arange(-2, lmax - 1, dtype=float) * (np.arange(
                3, lmax + 4))
        else:
            assert 0
        fl[:spin] *= 0.
        fl = np.sqrt(fl)
        hp.almxfl(Glm, fl, inplace=True)
        hp.almxfl(Clm, fl, inplace=True)
        return hp.alm2map_spin([Glm, Clm], self.nside, spin, lmax)
Example #7
0
def test_t():
    lmax = 200
    nside = 256
    cls_unl = np.ones(lmax + 1, dtype=float)
    tunl = hp.synalm(cls_unl, new=True)
    dlm = np.zeros_like(tunl)
    hp.almxfl(dlm,
              np.sqrt(
                  np.arange(lmax + 1) * np.arange(1, lmax + 2, dtype=float)),
              inplace=True)
    T = hp.alm2map(tunl, nside)
    T1 = lensing.alm2lenmap(tunl, [dlm, None],
                            nside,
                            verbose=True,
                            nband=8,
                            facres=-2)
    assert np.max(np.abs(T - T1)) / np.std(T) < 1e-5
    d1Re, d1Im = hp.alm2map_spin([dlm, np.zeros_like(dlm)], nside, 1, lmax)
    T2 = lensing.alm2lenmap(tunl, [d1Re, d1Im],
                            nside,
                            verbose=True,
                            nband=8,
                            facres=-2)
    assert np.max(np.abs(T - T2)) / np.std(T) < 1e-5
    T3 = lensing.alm2lenmap(tunl, [dlm, dlm.copy()],
                            nside,
                            verbose=True,
                            nband=8,
                            facres=-2)
    assert np.all(T2 == T3)
Example #8
0
    def draw_realization(self, synalm_lmax=None, seeds=None):

        if seeds is None:
            seeds = (None, None)

        if synalm_lmax is None:
            synalm_lmax = min(16384, 3 * self.nside - 1)

        np.random.seed(seeds[0])

        alm_small_scale = hp.synalm(
            list(self.small_scale_cl.value) +
            [np.zeros_like(self.small_scale_cl[0])] * 3,
            lmax=synalm_lmax,
            new=True,
        )

        alm_small_scale = [
            hp.almxfl(each, np.ones(min(synalm_lmax, 3 * self.nside - 1)))
            for each in alm_small_scale
        ]
        map_small_scale = hp.alm2map(alm_small_scale, nside=self.nside)

        # need later for beta
        modulate_map_I = hp.alm2map(self.modulate_alm[0].value, self.nside)

        map_small_scale[0] *= modulate_map_I
        map_small_scale[1:] *= hp.alm2map(self.modulate_alm[1].value,
                                          self.nside)

        map_small_scale += hp.alm2map(
            self.template_largescale_alm.value,
            nside=self.nside,
        )

        output_IQU = (utils.log_pol_tens_to_map(map_small_scale) *
                      self.template_largescale_alm.unit)

        np.random.seed(seeds[1])
        output_unit = np.sqrt(1 * self.small_scale_cl_pl_index.unit).unit
        alm_small_scale = hp.synalm(
            self.small_scale_cl_pl_index.value,
            lmax=synalm_lmax,
            new=True,
        )

        alm_small_scale = hp.almxfl(
            alm_small_scale, np.ones(min(3 * self.nside - 1, synalm_lmax + 1)))
        pl_index = hp.alm2map(alm_small_scale, nside=self.nside) * output_unit
        pl_index *= modulate_map_I
        pl_index += (hp.alm2map(
            self.largescale_alm_pl_index.value,
            nside=self.nside,
        ) * output_unit)
        pl_index -= 3.1 * u.dimensionless_unscaled

        # Fixed values for comparison with s4
        # pl_index = -3.1 * u.dimensionless_unscaled

        return (output_IQU[0], output_IQU[1], output_IQU[2], pl_index)
def Step_MC(guess, *arg):
    """
    Keyword Arguments:
    x -- the vector of params

    *args are:
    arg[0] -- a target class object
    arg[1] -- Cl_old, fluc_lm_old
    """
    ##print guess, arg
    dlm,strings,params,nl,bl = arg[0]
    Cl_old, fluc_lm_GS,mf_old = arg[1]
    dd = cb.update_dic(params,guess,strings)
    #generate new spectrum from new params
    lmax = len(Cl_old)
    Cl_new = cb.generate_spectrum(dd)[:lmax,1]
    # avoid dividing by 0
    Cl_new[:2] = 1.e-35
    #print "new = ",Cl_new[50]
    #print "old = ",Cl_old[50]
    # renormalization, i.e. lhs part of eq (24) and (25)
    renorm = CG.renorm_term(Cl_new,bl,nl)
    # generate mean field map using new PS
    mf_lm_new = hp.almxfl(CG.generate_mfterm(dlm,Cl_new,bl,nl),renorm)
    # get deterministic fluctuation map (new rescaling with noise)
    fluc_lm_determ = hp.almxfl(fluc_lm_GS,np.sqrt((1./Cl_old))/np.sqrt((1./Cl_new)))
    # get GS fluctuation map "for next iteration"
    fluc_lm_GS_next = hp.almxfl(CG.generate_w1term(Cl_new,bl,nl)+CG.generate_w0term(Cl_new),renorm)
    # Chi2 part of the likelihood
    return fluc_lm_determ,mf_lm_new, fluc_lm_GS_next, Cl_new
def test_fluctuation_term(guess, *arg):
    """
    Keyword Arguments:
    x -- the vector of params

    *args are:
    arg[0] -- a target class object
    arg[1] -- Cl_old, fluc_lm_old
    """
    ##print guess, arg
    dlm,strings,params,nl,bl = arg[0]
    Cl_old, fluc_lm_old = arg[1]
    dd = cb.update_dic(params,guess,strings)
    #generate new spectrum from new params
    lmax = len(Cl_old)
    Cl_new = cb.generate_spectrum(dd)[:lmax,1]
    # avoid dividing by 0
    Cl_new[:2] = 1.e-35
    #print "new = ",Cl_new[50]
    #print "old = ",Cl_old[50]
    # renormalization, i.e. lhs part of eq (24) and (25)
    renorm = CG.renorm_term(Cl_new,bl,nl)

    # generate fluctuation map using new PS, this is actually the 'step 2', with acceptance 1, won't be used anymore in this function
    fluc_lm_type2 = hp.almxfl(CG.generate_w1term(Cl_new,bl,nl)+CG.generate_w0term(Cl_new),renorm)
    #print "new = ",fluc_lm_type2[50]
    #print "old = ",fluc_lm_old[50]
    # get deterministic fluctuation map (new rescaling with noise)
    fluc_lm_determ = hp.almxfl(fluc_lm_old,np.sqrt((1./Cl_old+bl**2/nl))/np.sqrt((1./Cl_new+bl**2/nl)))
    # "fluctuation part" of the likelihood
    tt3 = -1/2. *np.real(np.vdot((fluc_lm_determ).T,hp.almxfl((fluc_lm_determ),1/nl*bl**2)))
    #print tt3
    # we return Cl_new and fluc_lm_type2 for next iteration.
    return tt3,Cl_new,fluc_lm_type2,fluc_lm_determ
Example #11
0
 def _get_sim_alm(self, idx, idf):
     # FIXME : triangularise this
     ret = hp.almxfl(self.lib_pha.get_sim(idx, idf=0), self.rmat[:, idf, 0])
     for _i in range(1, len(self.fields)):
         ret += hp.almxfl(self.lib_pha.get_sim(idx, idf=_i),
                          self.rmat[:, idf, _i])
     return ret
def diff_fixed_like(fluc_lm_determ,fluc_lm_GS,mf_lm_new,mf_lm_old,Cl_new,Cl_old, *arg):
    """
    Keyword Arguments:
    x -- the vector of params

    *args are:
    arg[0] -- a target class object
    arg[1] -- Cl_old, fluc_lm_old
    """
    ##print guess, arg
    dlm,strings,params,nl,bl = arg[0]
    tt1_new = -1/2.*np.real(np.vdot(CG.complex2real_alm(dlm-hp.almxfl(mf_lm_new,bl).T),CG.complex2real_alm(hp.almxfl((dlm-hp.almxfl(mf_lm_new,bl)),1/nl))))
    tt1_old = -1/2.*np.real(np.vdot(CG.complex2real_alm(dlm-hp.almxfl(mf_lm_old,bl).T),CG.complex2real_alm(hp.almxfl((dlm-hp.almxfl(mf_lm_old,bl)),1/nl))))
    #print "chi**2 = ",tt1_new-tt1_old
    # "mean field part" of the likelihood
    tt2_new = -1/2. *np.real(np.vdot(CG.complex2real_alm(mf_lm_new.T),CG.complex2real_alm(hp.almxfl((mf_lm_new),1./Cl_new))))
    tt2_old = -1/2. *np.real(np.vdot(CG.complex2real_alm(mf_lm_old.T),CG.complex2real_alm(hp.almxfl((mf_lm_old),1./Cl_old))))
    #print "'mf like' = ",tt2_new-tt2_old
    # "fluctuation part" of the likelihood
    tt3_new = -1/2. *np.real(np.vdot(CG.complex2real_alm(fluc_lm_determ.T),CG.complex2real_alm(hp.almxfl((fluc_lm_determ),1/nl*bl**2))))  
    tt3_old = -1/2. *np.real(np.vdot(CG.complex2real_alm(fluc_lm_GS.T),CG.complex2real_alm(hp.almxfl((fluc_lm_GS),1/nl*bl**2))))
    #print "'fluc like' = ",tt3_new-tt3_old
    tt_new = tt1_new + tt2_new + tt3_new
    tt_old = tt1_old + tt2_old + tt3_old
    return tt_new,tt_old
Example #13
0
def analworker(i):
    print "This is analysis worker starting for map", i[1]+1, "/", nmaps
    alms = hp.map2alm(i[0],lmax=ellmax-1)
    hp.almxfl(alms,pixrecip,inplace=True) #Correcting for pixwin
    
    #TESTING
    '''cls = hp.alm2cl(alms)
    map_bandlim = hp.alm2map(alms,nside=256,pixwin=True)
    hp.write_map('/Users/keir/Documents/s2let_ilc_planck/planck2015_2_cmb_map_1_bandlim300.fits',map_bandlim)'''

    wav_maps, scal_maps = ps.analysis_lm2wav_manualtiling(alms,ellmax,ndir,spin,scal_tiles,wav_tiles.T.ravel(),scal_bandlims,wav_bandlims)
    del alms
    np.save(scal_outfits[i[1]],scal_maps)
    del scal_maps
    
    #Splitting up output wavelet maps
    offset = 0
    for j in xrange(jmax+1):
        for n in xrange(ndir):
            bandlim = wav_bandlims[j]
            nelem = bandlim*(2.*bandlim-1.)
            wav_outfits = wav_outfits_root[i[1]] + '_' + wavparam_code + str(j) + '_n' + str(n+1) + '.npy'
            np.save(wav_outfits,wav_maps[offset:offset+nelem])
            offset += nelem
    del wav_maps

    return 0 #wav_maps,scal_maps #,map_bandlim,alms,cls
Example #14
0
    def _cache_eblm(self, idx):
        elm = self.unlcmbs.get_sim_elm(idx)
        blm = None if 'b' not in self.fields else self.unlcmbs.get_sim_blm(idx)
        dlm = self.get_sim_plm(idx)
        assert 'o' not in self.fields, 'not implemented'

        lmaxd = hp.Alm.getlmax(dlm.size)
        hp.almxfl(dlm,
                  np.sqrt(
                      np.arange(lmaxd + 1, dtype=float) *
                      np.arange(1, lmaxd + 2)),
                  inplace=True)
        Qlen, Ulen = self.lens_module.alm2lenmap_spin([elm, blm], [dlm, None],
                                                      self.nside_lens,
                                                      2,
                                                      nband=self.nbands,
                                                      facres=self.facres,
                                                      verbose=self.verbose)
        elm, blm = hp.map2alm_spin([Qlen, Ulen], 2, lmax=self.lmax)
        del Qlen, Ulen
        hp.write_alm(os.path.join(self.lib_dir, 'sim_%04d_elm.fits' % idx),
                     elm)
        del elm
        hp.write_alm(os.path.join(self.lib_dir, 'sim_%04d_blm.fits' % idx),
                     blm)
Example #15
0
    def apply_ivf(self, det, tmap, pmap):
        assert(self.lmax == 1000)

        mask_t = qcinv.util.load_map(self.mask_t)
        mask_p = qcinv.util.load_map(self.mask_p)

        bl  = dmc.get_bl(self.sim_lib.year, det)[0:self.lmax+1]
        pxw = hp.pixwin( self.sim_lib.nside )[0:self.lmax+1]

        # qcinv filtering for temperature
        dcf = self.lib_dir + "/dense_cache_det_" + det + ".pk"
        #                  id         preconditioners                 lmax    nside     im      em            tr                      cache
        chain_descr = [ [  2, ["split(dense("+dcf+"), 64, diag_cl)"],  256,   128,       3,     0.0,  qcinv.cd_solve.tr_cg,  qcinv.cd_solve.cache_mem()],
                        [  1, ["split(stage(2), 256, diag_cl)"],       512,   256,       3,     0.0,  qcinv.cd_solve.tr_cg,  qcinv.cd_solve.cache_mem()],
                        [  0, ["split(stage(1), 512, diag_cl)"],      1000,   512,  np.inf,  1.0e-6,  qcinv.cd_solve.tr_cg,  qcinv.cd_solve.cache_mem()] ]

        ninv = ( hp.read_map( dmc.get_fname_iqumap(self.sim_lib.year, det, self.sim_lib.forered), hdu=1, field=3 ) /
                 dmc.sigma0[(self.sim_lib.year, self.sim_lib.forered, 'T')][det]**2 / 1e6 * mask_t ) 
        n_inv_filt = qcinv.opfilt_tt.alm_filter_ninv( ninv, bl*pxw, marge_monopole=True, marge_dipole=True, marge_maps=[] )
        chain = qcinv.multigrid.multigrid_chain( qcinv.opfilt_tt, chain_descr, self.cl, n_inv_filt )

        tlm = np.zeros( qcinv.util_alm.lmax2nlm(self.lmax), dtype=np.complex )
        chain.solve( tlm, tmap )

        # simple filtering for polarization.
        elm, blm = hp.map2alm_spin( (pmap.real * mask_p, pmap.imag * mask_p), 2, lmax=self.lmax )
        ftl, fel, fbl = self.get_ftebl(det)
        hp.almxfl( elm, fel / bl / pxw, inplace=True )
        hp.almxfl( blm, fbl / bl / pxw, inplace=True )

        return tlm, elm, blm
Example #16
0
def vmaps2vmap_P(pix_vmaps, weights_e, weights_b, nside):
    """From individual Q and U freq pixel variance maps and weights create expected pixel variance map

        Args:
            pix_vmaps: list of pixel variance maps
            weights_e: weights for E-mode freq. weighting (as applied onto the noise maps)
            weights_b: weights for B-mode freq. weighting (as applied onto the noise maps)
            nside: desired output map resolution

       Note:
           the pix_vmaps in pol in this routine are expected to be ~ 1/2 (s2_Q + s2_U)

           See Planck 2018 gravitational lensing paper Eqs 16-17


    """
    assert len(pix_vmaps) == len(weights_e), (len(pix_vmaps), len(weights_e))
    assert len(pix_vmaps) == len(weights_b), (len(pix_vmaps), len(weights_b))

    nf, lmaxp1_e = weights_e.shape
    nf, lmaxp1_b = weights_b.shape

    lmax_out = min(2 * max(lmaxp1_e, lmaxp1_b) - 2, 3 * nside - 1)
    ret_lm = np.zeros(hp.Alm.getsize(lmax_out), dtype=complex)
    for i, (pix_vmap, wle, wlb) in enumerate_progress(
            list(zip(pix_vmaps, weights_e, weights_b))):
        m = read_map(pix_vmap)
        vpix = hp.nside2pixarea(hp.npix2nside(m.size), degrees=False)
        this_s2lm = hp.map2alm(m, iter=0, lmax=lmax_out)
        wl2 = 0.25 * vpix * _w2wsq(wle + wlb, 2, 2, lmax_out)
        wl2 += 0.25 * vpix * _w2wsq(wle - wlb, 2, -2, lmax_out)
        hp.almxfl(this_s2lm, wl2, inplace=True)
        ret_lm += this_s2lm
    return hp.alm2map(ret_lm, nside, verbose=False)
Example #17
0
def convolve_healpix(input_map,  func, thetamax, quiet=True, lmax_limit=None ):
    """
    Convolve a HEALPix map with a function

    input_map : array of float
        a HEALPix array, RING indexing, nside a power of 2
    func : function of theta to convolve with
    thetamax : float
        estimate of largest theta for function

    Returns: the convolved map
    """
    nside = int(np.sqrt(len(input_map)/12))
    assert 12*nside**2 == len(input_map),'Bad length'

    alm = healpy.map2alm(input_map);
    lmax = healpy.Alm.getlmax(len(alm))
    if lmax < 0:
        raise TypeError('Wrong alm size for the given '
                        'mmax (len(alms[%d]) = %d).'%(ialm, len(alm)))
    if lmax_limit is not None and lmax>lmax_limit:
        lmax=lmax_limit
    ell = np.arange(lmax + 1.)
    if not quiet:
        print 'Creating spherical harmonic content, lmax={}'.format(lmax)
    fact = convolution.SphericalHarmonicContent(func,lmax, thetamax, quiet=quiet)(ell)

    healpy.almxfl(alm, fact, inplace=True)
    return healpy.alm2map(alm, nside=nside, verbose=False)
Example #18
0
def almworker(i):
    print "This is (map2alm & alm2map) worker starting for another map"
    alms_worker = hp.map2alm(i[0], lmax=ellmax - 1)
    hp.almxfl(alms_worker, i[1],
              inplace=True)  #Correcting for pixwin & smoothing
    map_worker = hp.alm2map(alms_worker, nside_out, pixwin=True)
    del alms_worker
    return map_worker
Example #19
0
    def calc(self, alm):
        tmat = self.slinv

        relm = hp.almxfl(alm.elm, tmat[:, 0, 0], inplace=False) + hp.almxfl(
            alm.blm, tmat[:, 0, 1], inplace=False)
        rblm = hp.almxfl(alm.elm, tmat[:, 1, 0], inplace=False) + hp.almxfl(
            alm.blm, tmat[:, 1, 1], inplace=False)
        return eblm([relm, rblm])
def A_matrix_func(data):
    """
    cf eq 25 of eriksen 2004
    """
    Chalf = np.sqrt(data.cl_th[: data.lmax + 1]) * data.beam[: data.lmax + 1]
    map2 = hp.alm2map(hp.almxfl(real2complex_alm(data.alm), Chalf), data.nside) * data.invvar
    alm2 = hp.almxfl(hp.map2alm(map2, data.lmax, use_weights=False) * hp.nside2npix(data.nside) / 4.0 / np.pi, Chalf)
    return data.alm + complex2real_alm(alm2)
Example #21
0
 def get_sim_qumap(self,idx):
     elm = self.sims_cmb_len.get_sim_elm(idx)
     hp.almxfl(elm,self.cl_ptransf,inplace=True)
     blm = self.sims_cmb_len.get_sim_blm(idx)
     hp.almxfl(blm, self.cl_ptransf, inplace=True)
     Q,U = hp.alm2map_spin([elm,blm], self.nside, 2,hp.Alm.getlmax(elm.size))
     del elm,blm
     return [Q + self.get_sim_qnoise(idx),U + self.get_sim_unoise(idx)]
Example #22
0
def get_deriv(mp) :
    ns=hp.npix2nside(len(mp))
    l=np.arange(3*ns)
    alpha1i=np.sqrt(l*(l+1.))
    alpha2i=np.sqrt((l-1.)*l*(l+1.)*(l+2.))
    mpd1=hp.alm2map(hp.almxfl(hp.map2alm(mp),alpha1i),nside=ns,verbose=False)
    mpd2=hp.alm2map(hp.almxfl(hp.map2alm(mp),alpha2i),nside=ns,verbose=False)
    return mpd1,mpd2
Example #23
0
 def apply_alm(self, alm):
     """Missing doc. """
     npix = len(self.n_inv)
     hp.almxfl(alm, self.b_transf, inplace=True)
     kmap = alm2map(alm, hp.npix2nside(npix), verbose=False)
     self.apply_map(kmap)
     alm[:] = map2alm(kmap, lmax=hp.Alm.getlmax(alm.size), iter=0)
     hp.almxfl(alm, self.b_transf * (npix / (4. * np.pi)), inplace=True)
Example #24
0
 def get_irestmap(self, idx, xfilt=None):
     reslm = self.ivfs.get_sim_tlm(idx)
     if xfilt is not None:
         assert isinstance(xfilt, dict) and 't' in xfilt.keys()
         hp.almxfl(reslm, xfilt['t'], inplace=True)
     return hp.alm2map(reslm,
                       self.nside,
                       lmax=hp.Alm.getlmax(reslm.size),
                       verbose=False)
Example #25
0
 def get_sim_pmap(self, idx):
     elm = hp.almxfl(cmb_len_ffp10.get_sim_elm(idx), self.transf)
     blm = hp.almxfl(cmb_len_ffp10.get_sim_blm(idx), self.transf)
     Q, U = hp.alm2map_spin((elm, blm), self.nside, 2, hp.Alm.getlmax(elm.size))
     del elm, blm
     nlevp_pix = self.nlevp / np.sqrt(hp.nside2pixarea(self.nside, degrees=True)) / 60.
     Q += self.pix_libphas.get_sim(idx, idf=1) * nlevp_pix
     U += self.pix_libphas.get_sim(idx, idf=2) * nlevp_pix
     return Q, U
Example #26
0
 def get_irespmap(self, idx, xfilt=None):
     reselm = self.ivfs.get_sim_elm(idx)
     resblm = self.ivfs.get_sim_blm(idx)
     assert hp.Alm.getlmax(reselm.size) == hp.Alm.getlmax(resblm.size)
     if xfilt is not None:
         assert isinstance(xfilt, dict) and 'e' in xfilt.keys() and 'b' in xfilt.keys()
         hp.almxfl(reselm, xfilt['e'], inplace=True)
         hp.almxfl(resblm, xfilt['b'], inplace=True)
     fac = 0.5
     return hp.alm2map_spin([reselm * fac, resblm * fac], self.nside, 2, hp.Alm.getlmax(reselm.size))
Example #27
0
def calc_prep(map, s_cls, n_inv_filt):
    tmap = np.copy(map)
    n_inv_filt.apply_map(tmap)
    lmax = len(n_inv_filt.b_transf) - 1
    npix = len(map)
    alm = hp.map2alm(tmap, lmax=lmax, iter=3)
    alm *= npix / (4. * np.pi)

    hp.almxfl(alm, n_inv_filt.b_transf, inplace=True)
    return alm
Example #28
0
 def _apply_ivf_p(self, pmap, soltn=None):
     assert len(pmap[0]) == hp.nside2npix(self.nside) and len(
         pmap[0]) == len(pmap[1])
     elm, blm = hp.map2alm_spin([m for m in pmap], 2, lmax=self.lmax_fl)
     elm = hp.almxfl(
         elm,
         self.get_fel() * utils.cli(self.transf[:len(self.fel)]))
     blm = hp.almxfl(
         blm,
         self.get_fbl() * utils.cli(self.transf[:len(self.fbl)]))
     return elm, blm
Example #29
0
 def test_forward_backward_spin(self):
     """ compare map2alm_spin outputs to alm2map_spin inputs. tolerances are very loose. """
     for spin in [1,2,3]:
         tcl = np.ones(self.lmax+1); tcl[0:spin] = 0.
         almg = hp.almxfl(self.almg, tcl, inplace=False)
         almc = hp.almxfl(self.almc, tcl, inplace=False)
         
         rmap, imap = hp.alm2map_spin( [almg, almc], self.nside, spin, self.lmax )
         tglm, tclm = hp.map2alm_spin( [rmap, imap], spin, self.lmax )
         np.testing.assert_allclose( almg, tglm, rtol=1.e-2, atol=1.e-2)
         np.testing.assert_allclose( almc, tclm, rtol=1.e-2, atol=1.e-2)
Example #30
0
def simulate_tebp_correlated(cl_tebp_arr,nside,lmax) :
	alms=healpy.synalm(cl_tebp_arr,lmax=lmax,new=True)
	aphi=alms[-1]
	acmb=alms[0:-1]
#Set to zero above map resolution to avoid aliasing
	beam_cut=np.ones(3*nside)
	for ac in acmb :
		healpy.almxfl(ac,beam_cut,inplace=True)
	cmb=np.array(healpy.alm2map(acmb,nside,pol=True))

	return cmb,aphi
Example #31
0
def calc_prep(maps, s_cls, n_inv_filt):
    qmap, umap = np.copy(maps[0]), np.copy(maps[1])
    assert len(qmap) == len(umap)
    lmax = len(n_inv_filt.b_transf) - 1
    npix = len(qmap)

    n_inv_filt.apply_map([qmap, umap])
    elm, blm = map2alm_spin([qmap, umap], 2, lmax=lmax)
    hp.almxfl(elm, n_inv_filt.b_transf * npix / (4. * np.pi), inplace=True)
    hp.almxfl(blm, n_inv_filt.b_transf * npix / (4. * np.pi), inplace=True)
    return eblm([elm, blm])
Example #32
0
    def apply_ivf(self, det, tmap, pmap):
        mask_t = qcinv.util.load_map(self.mask_t)

        bl     = self.bl
        pxw    = hp.pixwin(self.nside)[0:self.lmax+1]

        tlm = hp.map2alm( tmap * mask_t, lmax=self.lmax, iter=0, regression=False )

        hp.almxfl( tlm, self.ftl / bl / pxw, inplace=True )
    
        return tlm
Example #33
0
 def test_forward_backward_spin(self):
     """ compare map2alm_spin outputs to alm2map_spin inputs. tolerances are very loose. """
     for spin in [1,2,3]:
         tcl = np.ones(self.lmax+1); tcl[0:spin] = 0.
         almg = hp.almxfl(self.almg, tcl, inplace=False)
         almc = hp.almxfl(self.almc, tcl, inplace=False)
         
         rmap, imap = hp.alm2map_spin( [almg, almc], self.nside, spin, self.lmax )
         tglm, tclm = hp.map2alm_spin( [rmap, imap], spin, self.lmax )
         np.testing.assert_allclose( almg, tglm, rtol=1.e-2, atol=1.e-2)
         np.testing.assert_allclose( almc, tclm, rtol=1.e-2, atol=1.e-2)
Example #34
0
def calc_prep(map, s_cls, n_inv_filt):
    tmap = np.copy(map)
    n_inv_filt.apply_map(tmap)

    lmax  = len(n_inv_filt.b_transf) - 1
    npix  = len(map)

    alm  = hp.map2alm(tmap, lmax=lmax, iter=0, regression=False)
    alm *= npix / (4.*np.pi)

    hp.almxfl( alm, n_inv_filt.b_transf, inplace=True )
    return alm
Example #35
0
def simulate_tebp_correlated(cl_tebp_arr,nside,lmax,seed):
        np.random.seed(seed)
        alms=hp.synalm(cl_tebp_arr,lmax=lmax,new=True)
        aphi=alms[-1]
        acmb=alms[0:-1]
#Set to zero above map resolution to avoid aliasing                                        
        beam_cut=np.ones(3*nside)
        for ac in acmb :
                hp.almxfl(ac,beam_cut,inplace=True)
        cmb=np.array(hp.alm2map(acmb,nside,pol=True,verbose=False))

        return cmb,aphi
Example #36
0
    def apply_alm(self, alm):
        # applies Y^T N^{-1} Y
        npix = len(self.n_inv)

        hp.almxfl(alm, self.b_transf, inplace=True)
        tmap = hp.alm2map(alm, hp.npix2nside(npix))

        self.apply_map(tmap)

        alm[:] = hp.map2alm(tmap, lmax=util_alm.nlm2lmax(len(alm)), iter=0)
        alm[:] *= (npix / (4. * np.pi))

        hp.almxfl(alm, self.b_transf, inplace=True)
Example #37
0
    def simulate(self, det, idx):
        assert( det in (dmc.wmap_das + dmc.wmap_bands) )
        
        tlm = self.sim_tlm_cmb.get_sim_tlm(idx)
        
        hp.almxfl(tlm, self.get_beam(det), inplace=True)
            
        tmap = hp.alm2map(tlm, self.nside)

        tmap_nse = self.simulate_nse(det)
        tmap += tmap_nse; del tmap_nse
        
        return tmap
Example #38
0
    def apply_ivf(self, det, tmap):
        mask_t = qcinv.util.load_map(self.mask_t)

        tlm = hp.map2alm( tmap * mask_t, lmax=self.lmax, iter=0, regression=False )

        bl  = dmc.get_bl(self.sim_lib.year, det)[0:self.lmax+1]
        pxw = hp.pixwin( self.sim_lib.nside )[0:self.lmax+1]

        ftl = self.get_ftl(det)

        hp.almxfl( tlm, ftl / bl / pxw, inplace=True )

        return tlm
Example #39
0
def smoothworker(
        i):  #(Rflat[i],smoothing_lmax,spin,gausssmooth,scale_lmax,n,i,j)
    print "Smoothing another independent covariance element"
    alms = ps.map2alm_mw(
        i[0], i[1],
        i[2])  #No pixwin correct. with MW sampling - calc alms to smooth
    #del i[0] #Everything gets moved down one index
    hp.almxfl(alms, i[3], inplace=True)  #Multiply by gaussian beam
    '''if i[5] != -1: #If n != -1 (i.e. the maps are directional)
        print "Picking out directional component of covariance map"
        #Testing convolving gaussian-smoothed covariance maps with directional wavelet
        jmin_min = 1
        #Need to truncate alm's to scale_lmax (Is this necessary?)
        alms_fname = 'alms_dirwav_' + str(i[7]) + '_' + str(i[5]) + '_' + str(i[6]) + '.fits'
        hp.write_alm(alms_fname,alms,lmax=i[4]-1,mmax=i[4]-1)
        del alms
        alms_truncate = hp.read_alm(alms_fname)
        print "Analysing covariance map" #Could increase wavparam!?
        wav,scal = ps.analysis_lm2wav(alms_truncate,wavparam,i[4],jmin_min,ndir,spin,upsample)
        del alms_truncate
        #Delete wrong directions by zero-ing them
        print "Deleting wrong directions"
        jmax_min = ps.pys2let_j_max(wavparam,i[4],jmin_min)
        for j in xrange(jmin_min,jmax_min+1):
            for n in xrange(0,ndir):
                if n != i[5]:
                    offset,new_scale_lmax,nelem,nelem_wav = ps.wav_ind(j,n,wavparam,i[4],ndir,jmin_min,upsample)
                    wav[offset:offset+nelem] = 0.
        print "Synthesising directional covariance map"
        alms = ps.synthesis_wav2lm(wav,scal,wavparam,i[4],jmin_min,ndir,spin,upsample)
        del wav,scal
        #Expand alm's with zero-padding
        print "Zero-padding the alm's"
        nzeros = i[1] - i[4] #No. zeros to pad
        new_alms_temp = np.concatenate((alms[:i[4]],np.zeros(nzeros)))
        for em in xrange(1,i[4]):
            startindex = em*i[4] - .5*em*(em-1)
            new_alms_temp = np.concatenate((new_alms_temp,alms[startindex:(startindex+i[4]-em)],np.zeros(nzeros)))
        del alms
        print "Temporary length of alm's =", len(new_alms_temp)
        nfinalzeros = hp.Alm.getsize(i[1]-1) - len(new_alms_temp)
        alms = np.concatenate((new_alms_temp,np.zeros(nfinalzeros)))
        del new_alms_temp
        print "Final length of alm's =", len(alms)'''

    #hp.almxfl(alms,i[3],inplace=True) #Multiply by gaussian beam
    print "Synthesising smoothed covariance map"
    Rsmoothflat = ps.alm2map_mw(
        alms, i[1], i[2])  #Smooth covariance in MW - calc final map to scale
    del alms
    return Rsmoothflat
Example #40
0
    def calc(self, alm):
        tmat = self.slinv

        rtlm = hp.almxfl(alm.tlm, tmat[:, 0, 0]) + hp.almxfl(
            alm.elm, tmat[:, 0, 1]) + hp.almxfl(alm.blm, tmat[:, 0, 2])
        relm = hp.almxfl(alm.tlm, tmat[:, 1, 0]) + hp.almxfl(
            alm.elm, tmat[:, 1, 1]) + hp.almxfl(alm.blm, tmat[:, 1, 2])
        rblm = hp.almxfl(alm.tlm, tmat[:, 2, 0]) + hp.almxfl(
            alm.elm, tmat[:, 2, 1]) + hp.almxfl(alm.blm, tmat[:, 2, 2])
        return teblm([rtlm, relm, rblm])
def target_distrib(guess, *arg):
    """
    Keyword Arguments:
    x -- the vector of params

    *args are:
    arg[0] -- a target class object
    arg[1] -- Cl_old, fluc_lm_old
    """
    #print guess, arg
    dlm,strings,params,nl,bl = arg[0]
    Cl_old, fluc_lm_old = arg[1]
    dd = cb.update_dic(params,guess,strings)
    Cl_new = cb.generate_spectrum(dd)[:,1]
    Cl_new[:2] = 1.e-35
    #print "new = ",Cl_new[50]
    #print "old = ",Cl_old[50]
    renorm = CG.renorm_term(Cl_new,bl,nl)
    mf_lm_new = hp.almxfl(CG.generate_mfterm(dlm,Cl_new,bl,nl),renorm)
    fluc_lm_type2 = hp.almxfl(CG.generate_w1term(Cl_new,bl,nl)+CG.generate_w0term(Cl_new),renorm)
    #print "new = ",fluc_lm_type2[50]
    #print "old = ",fluc_lm_old[50]
    fluc_lm_determ = hp.almxfl(fluc_lm_old,np.sqrt(Cl_new/Cl_old))
    tt1 = -1/2.*np.real(np.vdot((dlm-hp.almxfl(mf_lm_new,bl)).T,hp.almxfl((dlm-hp.almxfl(mf_lm_new,bl)),1/nl)))
    #print tt1
    tt2 = -1/2. *np.real(np.vdot((mf_lm_new).T,hp.almxfl((mf_lm_new),1./Cl_new)))
    #print tt2
    tt3 = -1/2. *np.real(np.vdot((fluc_lm_determ).T,hp.almxfl((fluc_lm_determ),1/nl*bl**2)))
    #print tt3
    #tt4 = - 1./2 *(np.arange(1,np.size(Cl_new)+1)*np.log(Cl_new)).sum()
    ##print tt4
    return [tt1,tt2,tt3],Cl_new,fluc_lm_type2
Example #42
0
    def apply_alm(self, alm):
        # applies Y^T N^{-1} Y
        npix = len(self.n_inv)
        
        hp.almxfl(alm, self.b_transf, inplace=True)

        tmap = hp.alm2map(alm, hp.npix2nside(npix))

        self.apply_map(tmap)

        alm[:]  = hp.map2alm(tmap, lmax=util_alm.nlm2lmax(len(alm)), iter=0, regression=False)
        alm[:] *= (npix / (4.*np.pi))
        
        hp.almxfl(alm, self.b_transf, inplace=True)
Example #43
0
    def get_sim_tmap(self, idx):
        """Returns temperature healpy map for a simulation

            Args:
                idx: simulation index

            Returns:
                healpy map

        """
        tmap = self.sims_cmb_len.get_sim_tlm(idx)
        hp.almxfl(tmap, self.cl_transf, inplace=True)
        tmap = hp.alm2map(tmap, self.nside)
        return tmap + self.get_sim_tnoise(idx)
Example #44
0
def simulate_tebp_correlated(cl_tebp_arr, nside, lmax, seed):
    """This generates correlated T,E,B and Phi maps

        """
    np.random.seed(seed)
    alms = hp.synalm(cl_tebp_arr, lmax=lmax, new=True)
    aphi = alms[-1]
    acmb = alms[0:-1]
    # Set to zero above map resolution to avoid aliasing
    beam_cut = np.ones(3 * nside)
    for ac in acmb:
        hp.almxfl(ac, beam_cut, inplace=True)
    cmb = np.array(hp.alm2map(acmb, nside, pol=True, verbose=False))
    return cmb, aphi
Example #45
0
def deconvolve_alm(alms,
                   lmax=None,
                   fwhm_in=0.0,
                   fwhm_out=0.0,
                   f_sky=1.0,
                   pol=False,
                   wiener=True,
                   sky_prior=None):

    fwhm = np.sqrt(fwhm_in**2 - fwhm_out**2)
    if fwhm == 0.0:
        return alms
    factor = (2.0 * np.sqrt(2.0 * np.log(2.0)))
    sigma = fwhm / factor

    retalm = []

    if lmax is None:
        lmax = hp.Alm.getlmax(len(alms[0] if pol else alms), None)

    if wiener:
        wiener_filter = wiener_filter_for_alm(alms[0] if pol else alms,
                                              lmax,
                                              f_sky=f_sky,
                                              sky_prior=sky_prior,
                                              fwhm=fwhm_in)
        wiener_smooth = fl.filter_butter(wiener_filter, lmax, 100)
        #wiener_smooth[:1500] = 1.0

    if pol:
        for ialm, alm in enumerate(alms):
            ell = np.arange(lmax + 1)
            if ialm >= 1:
                s = 2
            else:
                s = 0
            fact = np.exp(0.5 * (ell * (ell + 1) - s**2) * sigma**2)
            if wiener:
                fact /= wiener_smooth
            res = hp.almxfl(alm, fact, inplace=False)
            retalm.append(res)
    else:
        lmax = hp.Alm.getlmax(len(alms), None)
        ell = np.arange(lmax + 1)
        fact = np.exp(0.5 * (ell * (ell + 1)) * sigma**2)
        if wiener:
            fact /= wiener_smooth
        retalm = hp.almxfl(alms, fact, inplace=False)

    return retalm
Example #46
0
    def generate_gaus_map(self, readGmap=-1):
        if (readGmap<0):
            self.gausalm0=hp.synalm(self.inputCls)
        else:
            self.gausalm0=hp.read_alm(self.mapsdir+"gmap_"+str(readGmap)+".fits")

        self.gausalm1=np.copy(self.gausalm0); self.gausalm1[0]=0.0
        if (self.nodipole):
            ndxfl=np.ones(len(self.inputCls))
            ndxfl[1]=0.0
            hp.almxfl(self.gausalm1, ndxfl, inplace=True)
            hp.almxfl(self.gausalm0, ndxfl, inplace=True)

        self.gausmap0=hp.alm2map(self.gausalm0, nside=self.NSIDE) # includes the monopole bit
        self.gausmap1=hp.alm2map(self.gausalm1, nside=self.NSIDE) # does not include the monopole
def solve_CG(params_i,dd):
    dd = cb.update_dic(dd,params_i,strings)
    cl = cb.generate_spectrum(dd)[:,1]
    # define the first guess, the b from eq 25 since the code was design with this at first (might not be best idea ever)
    b_mf = CG.generate_mfterm(dlm_filt,cl[:lmax+1],bl[:lmax+1],nl[:lmax+1])
    b_w1 = CG.generate_w1term(cl[:lmax+1],bl[:lmax+1],nl[:lmax+1])
    b_w0 = CG.generate_w0term(cl[:lmax+1])
    b = b_mf + b_w1 + b_w0
    ###### left hand side factor
    renorm= np.sqrt(cl[:lmax+1])/(1+cl[:lmax+1]*bl[:lmax+1]**2/(nl[:lmax+1]))
    out = hp.almxfl(b,renorm)
    out_mf = hp.almxfl(b_mf,renorm)
    out_w1 = hp.almxfl(b_w1,renorm)
    out_w0 = hp.almxfl(b_w0,renorm)
    return out,out_mf,out_w0,out_w1
Example #48
0
def calc_prep(maps, s_cls, n_inv_filt):
    qmap, umap = np.copy(maps[0]), np.copy(maps[1])
    assert(len(qmap) == len(umap))
    npix  = len(qmap)
    
    n_inv_filt.apply_map([qmap, umap])

    lmax  = len(n_inv_filt.b_transf) - 1

    tlm, elm, blm = hp.map2alm( [qmap, qmap, umap], lmax=lmax, iter=0, regression=False, use_weights=False, pol=True )
    del tlm
    elm *= npix / (4.*np.pi); blm *= npix / (4.*np.pi)

    hp.almxfl( elm, n_inv_filt.b_transf, inplace=True )
    hp.almxfl( blm, n_inv_filt.b_transf, inplace=True )
    return eblm([elm, blm])
Example #49
0
def fisher_single(par,v) :
    # v -> seen pixels
    nb=len(par.bins)-1
    npix=hp.nside2npix(par.nside)
    npix_seen=len(par.ip_seen)
    lmax=3*par.nside-1
    larr=np.arange(lmax+1)
    fisher=np.zeros([nb,nb])
    pixsize=4*np.pi/hp.nside2npix(par.nside)
    
    v_map=np.zeros(npix); v_map[par.ip_seen]=v
    vcm1=invert_covar(par,v_map)
    v_lm=hp.map2alm(v_map,iter=0)
    vcm1_lm=hp.map2alm(vcm1,iter=0)
    for iba in np.arange(nb) :
#        print " Row %d"%iba
        transfer=np.zeros(lmax+1); transfer[par.bins[iba]:par.bins[iba+1]]=1.
        v_map2=hp.alm2map(hp.almxfl(v_lm,transfer),par.nside,verbose=False)/pixsize #Q_a * v
        v_map2cm1=invert_covar(par,v_map2) #C^-1 * Q_a * v
        va_lm=hp.map2alm(v_map2cm1,iter=0)
        cl_vcm1_va=(2*larr+1)*hp.alm2cl(vcm1_lm,alms2=va_lm)
        for ibb in np.arange(nb-iba)+iba :
            fisher[iba,ibb]=np.sum(cl_vcm1_va[par.bins[ibb]:par.bins[ibb+1]])/pixsize**2
            if iba!=ibb :
                fisher[ibb,iba]=fisher[iba,ibb]

    return fisher
def generate_mfterm(dlm, Cl, bl, nl):
    """
    
    """
    lmax = np.size(Cl) - 1
    out = hp.almxfl(dlm, np.sqrt(Cl[: lmax + 1]) * bl[: lmax + 1] / nl[: lmax + 1])
    return out
def functional_form_params_n(x,*arg):
    """
    Keyword Arguments:
    x -- the vector of params

    *args are:
    dlm -- input map
    x_str -- the dictionary strings corresponding to x
    params -- a camber dictionnary
    noise -- a noise power spectrum
    beam -- a beam power spectrum
    """
    dlm = arg[0]
    strings = arg[1]
    params = arg[2].copy()
    noise = arg[3]
    beam = arg[4]    
    Cl_old = arg[5]
    lmax = len(Cl_old)-1
    #params["output_root"] = '../Codes/CG_git/MH_MCMC/camb_ini/test%d'%np.random.randint(100)
    for i in range(np.size(x)):
        ##print strings[i]
        if strings[i]=='scalar_amp(1)':
            ##print params[strings[i]]
            params[strings[i]]=np.exp(x[i])*1e-10
            ##print params[strings[i]]
        else:
            params[strings[i]]=x[i]
    Cl = cb.generate_spectrum(params)
    #lmax = Cl.shape[0]-1
    tt = -1./2 * np.real(np.vdot(CG.complex2real_alm(dlm.T),CG.complex2real_alm(hp.almxfl(dlm,1/(beam[:lmax+1]**2*Cl[:lmax+1,1]+noise[:lmax+1])))))    
    #determinant is the product of the diagonal element: in log:
    tt2 =  - 1./2 *((2*np.arange(2,lmax+1)+1)*np.log(noise[2:lmax+1]+Cl[2:lmax+1,1]*beam[2:lmax+1]**2)).sum()
    return tt+tt2,Cl[:,1]
Example #52
0
 def direct(self, input, output):
     if input.ndim == 1:
         input = input[:, None]
         output = output[:, None]
     for i, o in zip(input.T, output.T):
         ialm = hp.map2alm(i)
         alm_smoothed = hp.almxfl(ialm, self.fl)
         o[...] = hp.alm2map(alm_smoothed, hp.npix2nside(len(i)))# * \
def return_map(map_class):
    """
    We solve for C^{-1/2}x, here is to recover x
    """
    Shalf = np.sqrt(map_class.cl_th[: map_class.lmax + 1])
    alm_out = hp.almxfl(real2complex_alm(map_class.alm), Shalf)
    cl_out = hp.alm2cl(alm_out)
    map_out = hp.alm2map(alm_out, map_class.nside)
    return cl_out, map_out
Example #54
0
def rs_w1_matrix_func(data, w1):
    """
    cf eq 25 of eriksen 2004
    """
    Chalf = np.sqrt(data.cl_th[: data.lmax]) * data.beam[: data.lmax]
    map2 = w1 * np.sqrt(data.invvar)
    # map2 = hp.alm2map(real2complex_alm(data.alm),data.nside)*np.sqrt(data.invvar)
    alm2 = hp.almxfl(hp.map2alm(map2, data.lmax, use_weights=False) * hp.nside2npix(data.nside) / 4.0 / np.pi, Chalf)
    return complex2real_alm(alm2)
def plot_tests():
    spec_mf_b = hp.alm2cl(hp.almxfl(mf_lm_new,bl))
    spec_mf = hp.alm2cl((mf_lm_new))
    spec = hp.alm2cl(dlm)
    diff = hp.alm2cl(dlm - (hp.almxfl(mf_lm_new,bl)))
    fluc_l = hp.alm2cl(fluc)
    nnn = hp.alm2cl(dlm-hp.almxfl(mf_lm_new,bl))
    plt.figure()
    plt.plot(spec_mf,label='mean field ($\hat{s}$)')
    plt.plot(spec_mf_b,label='beamed mean field ($A\hat{s}$)')
    plt.plot(spec,label='data (d)')
    plt.plot(spec - spec_mf_b,label='($d_\ell - (A\hat{s})_\ell$)')
    plt.plot(diff,label='($d - (A\hat{s})$)$_\ell$')
    plt.plot(fluc_l,"-.",label='($\hat{f}$)$_\ell$')
    plt.plot(nl,"-.",label="noise")
    plt.plot(cl,"-.",label="trial spectrum")
    plt.yscale("log")
    plt.legend(loc = 'best')
Example #56
0
    def calc(self, talm):
        if ( np.all(talm == 0) ): # do nothing if zero
            return talm

        alm = np.copy(talm)
        self.n_inv_filt.apply_alm(alm)
        alm += hp.almxfl(talm, self.cltt_inv)

        return alm
Example #57
0
    def test_der1(self):
        """ compare output of alm2map_der1 with the equivalent spin-1 transform using alm2map_spin """
        
        m, dt_der1, dp_der1 = hp.alm2map_der1( self.almg, self.nside )

        alm_spin            = hp.almxfl( self.almg, np.array( [np.sqrt(l*(l+1.)) for l in xrange(0,self.lmax+1)] ), inplace=False )
        dt_spin, dp_spin    = hp.alm2map_spin( [alm_spin, alm_spin*0.], self.nside, 1, self.lmax )

        np.testing.assert_array_almost_equal( dt_der1, dt_spin, decimal=8)
        np.testing.assert_array_almost_equal( dp_der1, dp_spin, decimal=8)
def test_loglike(dlm,Cl,noise,beam):
    """
    returns the log likelihood for a given Cl, beam, noise, and data.
    """
    lmax = Cl.shape[0]
    tt_exp = -1./2 * np.real(np.vdot(dlm.T,hp.almxfl(dlm,1/(beam[:lmax]**2*Cl[:,1]+noise[:lmax]))))
    #plt.plot(Cl[:,1])
    tt_det = - 1./2 *(np.arange(1,lmax+1)*np.log((noise[:lmax]+Cl[:,1]*beam[:lmax]**2))).sum() 
    tt_f = tt_exp  + tt_det
    return tt_exp,tt_det,tt_f#,Cl[:,1]
def CG_algo_precond_diag(Matrix, Precond_diag, b, data_start, i_max, eps):
    """
    Matrix is the function to apply the matrix on a vector 
    data_start is a data_class class, with real alms 
    """
    i = 0
    x = data_start.alm.copy()
    cl_th = data_start.cl_th
    beam = data_start.beam
    sigma = data_start.sigma
    lmax = data_start.lmax
    nside = data_start.nside
    invvar = data_start.invvar
    out = data_class([0, cl_th, beam, sigma, invvar, lmax, nside])
    r = b - Matrix(data_start)
    d = data_class([0, cl_th, beam, sigma, invvar, lmax, nside])
    d.alm = r.copy()
    d.alm = complex2real_alm(hp.almxfl(real2complex_alm(r), Precond_diag))
    delt_n = np.dot(r.T, d.alm)
    delt_0 = delt_n.copy()
    iter_out_map = []
    iter_out_cl = []
    while i < i_max and delt_n > (eps ** 2 * delt_0):
        q = Matrix(d)
        alph = np.float(delt_n) / np.dot(d.alm.T, q)
        x = x + alph * d.alm
        if i % 10 == 0:
            dat_temp = data_class([0, cl_th, beam, sigma, invvar, lmax, nside])
            dat_temp.alm = x
            r = b - Matrix(dat_temp)
        else:
            r = r - alph * q
        s = complex2real_alm(hp.almxfl(real2complex_alm(r), Precond_diag))
        # s = hp.almxfl(r,Precond_diag)
        delt_old = delt_n.copy()
        delt_n = np.dot(r.T, s)
        bet = delt_n / delt_old
        d.alm = s + bet * d.alm
        i += 1
        out.alm = x
        iter_out_map.append(return_map(out)[1])
        iter_out_cl.append(return_map(out)[0])
    return iter_out_map, iter_out_cl
Example #60
0
    def calc(self, talm):
        if ( np.all(talm == 0) ): # do nothing if zero
            return talm

        ret = hp.almxfl(talm, self.cltt_inv)
        for n_inv_filt in self.n_inv_filts:
            alm = np.copy(talm)
            n_inv_filt.apply_alm(alm)
            ret += alm

        return ret