コード例 #1
0
def main(nsim=1, fnl=0.0):

    nl = 1024
    nside_fnl = 512

    # Load map, mll
    print ""
    print "Loading alm_g, alm_ng and creating map..."

    fn_almg = ('data/fnl_sims/alm_l_%04d_v3.fits' % (nsim,))
    #fn_almg = ('data/fnl_sims/alm_l_%i.fits' % (nsim,))
    almg = hp.read_alm(fn_almg)
    #almg = almg[:hp.Alm.getsize(nl)]
    fn_almng = ('data/fnl_sims/alm_nl_%04d_v3.fits' % (nsim,))
    #fn_almng = ('data/fnl_sims/alm_nl_%i.fits' % (nsim,))
    almng = hp.read_alm(fn_almng)
    #almng = almng[:hp.Alm.getsize(nl)]
    alm = almg * (2.7e6) + fnl * almng * (2.7e6) # convert to units of uK to be consistent with other maps

    map_sim_fnl = hp.alm2map(alm, nside=nside_fnl)
    
    #print "Normalizing map..."
    #map_sim_fnl *= (1e6 * 2.7) # convert to units of uK to be consistent with other maps

    fn_map = 'data/fnl_sims/map_fnl_%i_sim_%i.fits' % (int(fnl), nsim)
    print "Writing map: %s" % fn_map
    hp.write_map(fn_map, map_sim_fnl)
コード例 #2
0
ファイル: tools_qrec.py プロジェクト: toshiyan/planck-ilens
def aps(rlz, qobj, xobj, wfac, flens, fcib, **kwargs_ov):

    Lmax = qobj.olmax
    cl = np.zeros((len(rlz), 7, Lmax + 1))

    for q in qobj.qlist:

        for i, r in enumerate(
                tqdm.tqdm(rlz,
                          ncols=100,
                          desc='aps (' + qobj.qtype + ',' + q + ')')):

            if misctools.check_path(xobj.fcli[q][r], **kwargs_ov): continue

            # load qlm
            alm = quad_func.load_rec_alm(qobj, q, r, mean_sub=True)[0]
            #alm = pickle.load(open(qobj.f[q].alm[r],"rb"))[0]
            #mf  = pickle.load(open(qobj.f[q].mfalm[r],"rb"))[0]
            #alm -= mf

            # auto spectrum
            cl[i, 0, :] = csu.alm2cl(Lmax, alm) / qobj.wn[4]

            if r > 0:
                # load input klm
                klm = hp.read_alm(flens['IN'][r])
                klm = csu.lm_healpy2healpix(klm, 4096)[:Lmax + 1, :Lmax + 1]
                # cross with input klm
                cl[i, 1, :] = csu.alm2cl(Lmax, alm, klm) / qobj.wn[2]

            # load reconstructed klm
            klm = hp.read_alm(flens['MV'][r])
            klm = csu.lm_healpy2healpix(klm, 4096)[:Lmax + 1, :Lmax + 1]
            # cross with lens
            cl[i, 2, :] = csu.alm2cl(Lmax, alm, klm) / wfac['ik']
            # lens auto
            cl[i, 3, :] = csu.alm2cl(Lmax, klm) / wfac['kk']

            # load cib alm
            Ilm = pickle.load(open(fcib[r], "rb"))
            # cross with cib
            cl[i, 4, :] = csu.alm2cl(Lmax, alm, Ilm) / wfac['iI']
            # cib
            cl[i, 5, :] = csu.alm2cl(Lmax, Ilm) / wfac['II']

            # lens x cib
            cl[i, 6, :] = csu.alm2cl(Lmax, Ilm, klm) / wfac['kI']

            np.savetxt(xobj.fcli[q][r],
                       np.concatenate((qobj.l[None, :], cl[i, :, :])).T)

        # save to files
        if rlz[-1] >= 2 and not misctools.check_path(xobj.fmcl[q], **
                                                     kwargs_ov):
            i0 = max(0, 1 - rlz[0])
            np.savetxt(
                xobj.fmcl[q],
                np.concatenate(
                    (qobj.l[None, :], np.average(cl[i0:, :, :], axis=0),
                     np.std(cl[i0:, :, :], axis=0))).T)
コード例 #3
0
    def compute_pol_derivatives(self, fromalm=False):
        """
        Compute derivatives of the input polarization components (healpix).
        Not updated for dichroic for the moment.

        Parameters
        ----------
        fromalm : bool, optional
            If True, loads alm file from disk instead of fourier
            transform the input map. Automatically turns True if you input
            alm files. False otherwise.

        Examples
        ----------
        >>> filename = 's4cmb/data/test_data_set_lensedCls.dat'
        >>> hpmap = HealpixFitsMap(input_filename=filename, fwhm_in=3.5,
        ...     nside_in=16, compute_derivatives=True, map_seed=489237)
        >>> hasattr(hpmap, 'dIdp')
        True

        """
        if fromalm:
            Elm = hp.read_alm(self.input_filename[1])
            Blm = hp.read_alm(self.input_filename[2])
        else:
            alm = hp.map2alm([self.I, self.Q, self.U], self.lmax)
            Elm = alm[1]
            Blm = alm[2]
        # lmax = hp.Alm.getlmax(Elm.size)
        if "P1" in self.derivatives_type:
            out = alm2map_spin_der1([Elm, Blm], self.nside_in, 2)
            self.dQdt = out[1][0]
            self.dUdt = out[1][1]
            self.dQdp = out[2][0]
            self.dUdp = out[2][1]
        else:
            warnings.warn("""
            Computation of second order polarization derivatives not
            implemented yet. Set to 0.
            """)

            out = alm2map_spin_der1([Elm, Blm], self.nside_in, 2)
            self.dQdt = out[1][0]
            self.dUdt = out[1][1]
            self.dQdp = out[2][0]
            self.dUdp = out[2][1]
            self.d2Qd2t = np.zeros_like(self.dQdt)
            self.d2Qd2p = np.zeros_like(self.dQdt)
            self.d2Qdpdt = np.zeros_like(self.dQdt)
            self.d2Ud2t = np.zeros_like(self.dQdt)
            self.d2Ud2p = np.zeros_like(self.dQdt)
            self.d2Udpdt = np.zeros_like(self.dQdt)
コード例 #4
0
    def _get_real(self, ifile):
        from orphics.maps import filter_alms

        alm = hp.read_alm(ifile)
        alm = filter_alms(alm, 8, 2048)
        omap = hp.alm2map(alm, nside=self.nside)
        return omap
コード例 #5
0
def get_cmb_alm_v0p5(
        cmb_set,
        phi_set,
        i,
        path='/scratch/r/rbond/msyriac/data/sims/signal/v0.5_lenstest/'):
    fname = path + f"fullskyLensedUnaberratedCMB_alm_cmb_set_{cmb_set:02d}_phi_set_{phi_set:02d}_{i:05d}.fits"
    return hp.read_alm(fname, hdu=(1, 2, 3))
コード例 #6
0
ファイル: gal2equ_rotation.py プロジェクト: bruno-moraes/M101
def gal2equ(in_file, out_file, smooth, eulers=None):
    
    e2g = np.array([[-0.054882486, -0.993821033, -0.096476249],
                   [ 0.494116468, -0.110993846,  0.862281440],
                   [-0.867661702, -0.000346354,  0.497154957]]) # intrinsic rotation
    g2e = np.linalg.inv(e2g)
    eps = 23.452294 - 0.0130125 - 1.63889E-6 + 5.02778E-7
    eps = eps * np.pi / 180.
    e2q = np.array([[1.,     0.    ,      0.         ],
                   [0., np.cos( eps ), -1. * np.sin( eps )],
                   [0., np.sin( eps ),    np.cos( eps )   ]])
    g2q = np.dot(e2q , g2e)

    psi = np.arctan2(g2q[1,2],g2q[0,2])
    theta = np.arccos(g2q[2,2])
    phi = np.arctan2(g2q[2,1],-g2q[2,0]) # deduced from zyz rotation matrix
    
    fwhm = smooth*((2*np.pi)/360)

    alms = hp.read_alm(in_file)
    hp.smoothalm(alms, fwhm=fwhm)

    if eulers == None:
        hp.rotate_alm(alms, phi, theta, psi) # reverse rotation order ->                                            extrinsic rotation
        print('Euler angles (zyz) = ', str(np.rad2deg(phi)), str(np.rad2deg(theta)), str(np.rad2deg(psi)))
    else:
        eulers = np.deg2rad(eulers)
        hp.rotate_alm(alms, eulers[0], eulers[1], eulers[2])
        print('Euler angles (zyz) = ', str(np.rad2deg(eulers[0])), str(np.rad2deg(eulers[1])), str(np.rad2deg(eulers[2])))

    print(e2q)
    hp.write_alm(out_file, alms)
コード例 #7
0
def klm_2_map(klmname, mapname, nsides):
    # read in planck alm convergence data
    planck_lensing_alm = hp.read_alm(klmname)
    filtered_alm = zero_modes(planck_lensing_alm, 100)
    # generate map from alm data
    planck_lensing_map = hp.sphtfunc.alm2map(filtered_alm, nsides, lmax=4096)
    hp.write_map(mapname, planck_lensing_map, overwrite=True)
コード例 #8
0
ファイル: qest.py プロジェクト: markm42/plancklens
    def get_sim_qlm(self, k, idx, lmax=None):
        """Returns a QE estimate, by computing and caching it if not done previously.

            Args:
                k: quadratic estimator key
                idx: simulation index
                lmax: optionally reduces the lmax of the output healpy array.

        """
        assert k in self.keys, (k, self.keys)
        if lmax is None:
            lmax = self.get_lmax_qlm(k)
        assert lmax <= self.get_lmax_qlm(k)
        if k in ['p_tp', 'x_tp', 'f_tp', 's_tp']:
            return self.get_sim_qlm('%stt' % k[0], idx,
                                    lmax=lmax) + self.get_sim_qlm(
                                        '%s_p' % k[0], idx, lmax=lmax)
        if k in ['p_te', 'p_tb', 'p_eb', 'x_te', 'x_tb', 'x_eb']:
            return self.get_sim_qlm(k[0] + k[2] + k[3], idx,
                                    lmax=lmax) + self.get_sim_qlm(
                                        k[0] + k[3] + k[2], idx, lmax=lmax)

        if '_bh_' in k:  # Bias-hardening
            assert self.resplib is not None, 'resplib arg necessary for this'
            kQE, ksource = k.split('_bh_')
            assert len(ksource) == 1 and ksource + kQE[1:] in self.keys, (
                ksource, kQE)
            assert self.get_lmax_qlm(kQE) == self.get_lmax_qlm(
                ksource + kQE[1:]), 'fix this (easy)'
            lmax = self.get_lmax_qlm(kQE)
            wL = self.resplib.get_response(kQE, ksource) * ut.cli(
                self.resplib.get_response(ksource + kQE[1:], ksource))
            ret = self.get_sim_qlm(kQE, idx, lmax=lmax)
            return ret - hp.almxfl(
                self.get_sim_qlm(ksource + kQE[1:], idx, lmax=lmax), wL)

        assert k in self.keys_fund, (k, self.keys_fund)
        fname = os.path.join(
            self.lib_dir,
            'sim_%s_%04d.fits' % (k, idx) if idx != -1 else 'dat_%s.fits' % k)
        if not os.path.exists(fname):
            if k in ['ptt', 'xtt']: self._build_sim_Tgclm(idx)
            elif k in ['p_p', 'x_p']: self._build_sim_Pgclm(idx)
            elif k in ['p', 'x']: self._build_sim_MVgclm(idx)
            elif k in ['f']: self._build_sim_f(idx)
            elif k in ['stt']: self._build_sim_stt(idx)
            elif k in ['ftt']: self._build_sim_ftt(idx)
            elif k in ['f_p']: self._build_sim_f_p(idx)
            elif k in ['ntt']: self._build_sim_ntt(idx)
            elif k in ['a_p']: self._build_sim_a_p(idx)
            elif k in [
                    'ptt', 'pte', 'pet', 'ptb', 'pbt', 'pee', 'peb', 'pbe',
                    'pbb', 'xtt', 'xte', 'xet', 'xtb', 'xbt', 'xee', 'xeb',
                    'xbe', 'xbb'
            ]:
                self._build_sim_xfiltMVgclm(idx, k)
            else:
                assert 0, k

        return ut.alm_copy(hp.read_alm(fname), lmax=lmax)
コード例 #9
0
ファイル: template.py プロジェクト: healpy/pysm
def read_alm(path, has_polarization=True, unit=None, map_dist=None):
    """Read :math:`a_{\ell m}` from a FITS file

    Parameters
    ----------
    path : str
        absolute or relative path to local file or file available remotely.
    has_polarization : bool
        read only temperature alm from file or also polarization
    map_dist : pysm.MapDistribution
        :math:`\ell_{max}` should be the same of the :math:`\ell_{max}` in the file
        and :math:`m_{max}=\ell_{max}`.
    """

    filename = utils.RemoteData().get(path)

    mpi_comm = None if map_dist is None else map_dist.mpi_comm

    if (mpi_comm is not None and mpi_comm.rank == 0) or (mpi_comm is None):

        alm = np.complex128(
            hp.read_alm(filename, hdu=(1, 2, 3) if has_polarization else 1)
        )
        if unit is None:
            unit = u.Unit(extract_hdu_unit(filename))

    if mpi_comm is not None:
        raise NotImplementedError
    else:
        local_alm = alm

    return local_alm * unit
コード例 #10
0
ファイル: alms.py プロジェクト: zonca/so_pysm_models
    def __init__(
        self,
        filename,
        input_units="uK_CMB",
        input_reference_frequency=None,
        nside=None,
        target_shape=None,
        target_wcs=None,
        precompute_output_map=True,
        has_polarization=True,
        map_dist=None,
    ):
        """Generic component based on Precomputed Alms

        Load a set of Alms from a FITS file and generate maps at the requested
        resolution and frequency assuming the CMB black body spectrum.
        A single set of Alms is used for all frequencies requested by PySM,
        consider that PySM expects the output of components to be in uK_RJ.

        See more details at https://so-pysm-models.readthedocs.io/en/latest/so_pysm_models/models.html

        Parameters
        ----------
        filename : string
            Path to the input Alms in FITS format
        input_units : string
            Input unit strings as defined by pysm.convert_units, e.g. K_CMB, uK_RJ, MJysr
        input_reference_frequency: float
            If input units are K_RJ or Jysr, the reference frequency
        nside : int
            HEALPix NSIDE of the output maps
        precompute_output_map : bool
            If True (default), Alms are transformed into a map in the constructor,
            if False, the object only stores the Alms and generate the map at each
            call of the signal method, this is useful to generate maps convolved
            with different beams
        has_polarization : bool
            whether or not to simulate also polarization maps
            Default: True
        """

        super().__init__(nside=nside, map_dist=map_dist)
        self.shape = target_shape
        self.wcs = target_wcs
        self.filename = filename
        self.input_units = u.Unit(input_units)
        self.has_polarization = has_polarization

        alm = np.complex128(
            hp.read_alm(self.filename,
                        hdu=(1, 2, 3) if self.has_polarization else 1))

        self.equivalencies = (None if input_reference_frequency is None else
                              u.cmb_equivalencies(input_reference_frequency))
        if precompute_output_map:
            self.output_map = self.compute_output_map(alm)

        else:
            self.alm = alm
コード例 #11
0
def load_alms(component, id):
    if component == 'cmb':
        cmb_tlm = hp.read_alm(
            '/project/projectdirs/cmb/data/generic/cmb/ffp10/mc/scalar/ffp10_lensed_scl_cmb_000_alm_mc_%04d.fits'
            % int(id),
            hdu=1)
        cmb_elm = hp.read_alm(
            '/project/projectdirs/cmb/data/generic/cmb/ffp10/mc/scalar/ffp10_lensed_scl_cmb_000_alm_mc_%04d.fits'
            % int(id),
            hdu=2)
        cmb_blm = hp.read_alm(
            '/project/projectdirs/cmb/data/generic/cmb/ffp10/mc/scalar/ffp10_lensed_scl_cmb_000_alm_mc_%04d.fits'
            % int(id),
            hdu=3)
        return cmb_tlm, cmb_elm, cmb_blm
    else:
        print('unclear request of loading alms. Exiting..')
        sys.exit()
コード例 #12
0
    def get_sim_plm(idx):
        r"""
            Args:
                idx: simulation index

            Returns:
               lensing potential :math:`\phi_{LM}` simulation healpy alm array

        """
        return hp.read_alm('/project/projectdirs/cmb/data/generic/cmb/ffp10/mc/scalar/ffp10_unlensed_scl_cmb_000_tebplm_mc_%04d.fits'% idx, hdu=4)
コード例 #13
0
    def get_sim_blm(idx):
        """
            Args:
                idx: simulation index

            Returns:
                unlensed B-polarization simulation healpy alm array

        """
        return 1e6 * hp.read_alm('/project/projectdirs/cmb/data/generic/cmb/ffp10/mc/scalar/ffp10_unlensed_scl_cmb_000_tebplm_mc_%04d.fits'% idx, hdu=3)
コード例 #14
0
    def get_sim_tlm(idx):
        """
            Args:
                idx: simulation index

            Returns:
                lensed temperature simulation healpy alm array

        """
        return 1e6 * hp.read_alm('/project/projectdirs/cmb/data/generic/cmb/ffp10/mc/scalar/ffp10_lensed_scl_cmb_000_alm_mc_%04d.fits'%idx, hdu=1)
コード例 #15
0
    def _load_alm(self):
        """ Load the alm expansion and place it in the node-shared memory

        """
        if self._rank == 0:
            timer = Timer()
            timer.start()
            alm, mmax = hp.read_alm(self._almfile, return_mmax=True)
            nalm = len(alm)
            lmax = hp.Alm.getlmax(nalm, mmax)
            alm = [alm]
            if self._pol:
                for hdu in [2, 3]:
                    alm.append(hp.read_alm(self._almfile, hdu=hdu))
            alm = np.vstack(alm)
            nalm = len(alm)
            # If necessary, truncate the expansion to sufficient lmax
            self._lmax = min(lmax, self._lmax)
            self._mmax = min(mmax, self._lmax)
            if self._lmax < lmax:
                sz = hp.Alm.getsize(self._lmax, self._mmax)
                new_alm = np.zeros([nalm, sz], dtype=np.complex)
                for ell in range(self._lmax + 1):
                    for m in range(min(ell, self._mmax)):
                        i = hp.Alm.getidx(self._lmax, ell, m)
                        j = hp.Alm.getidx(lmax, ell, m)
                        new_alm[:, i] = alm[:, j]
                alm = new_alm
                lmax = self._lmax
                mmax = self._mmax
            # Suppress any primordial monopole or dipole
            for ell in range(min(2, lmax + 1)):
                for m in range(min(ell + 1, mmax + 1)):
                    ind = hp.Alm.getidx(lmax, 1, m)
                    alm[0, ind] = 0
            timer.stop()
            timer.report("load CMB alm")
        else:
            alm, lmax, mmax = None, None, None
        self._alm = self._comm.bcast(alm)
        self._lmax = self._comm.bcast(lmax)
        self._mmax = self._comm.bcast(mmax)
        return
コード例 #16
0
ファイル: local.py プロジェクト: toshiyan/planck-ilens
def sim_iamp(i, M, palm, lmax, rlmin, rlmax, Ag, ocl, lcl, nl, beta, freq):

    fname = '/global/homes/t/toshiyan/scratch/plk_biref/test/glm_' + str(
        freq) + '_' + str(i).zfill(3) + '.pkl'

    if misctools.check_path(fname, verbose=False):

        glm, Ealm, Balm = pickle.load(open(fname, "rb"))

    else:

        alms = hp.read_alm(
            '/project/projectdirs/sobs/v4_sims/mbs/cmb/fullskyLensedUnabberatedCMB_alm_set00_'
            + str(i).zfill(5) + '.fits',
            hdu=(1, 2, 3))
        #Talm = cs.utils.lm_healpy2healpix( alms[0], 5100 ) [:lmax+1,:lmax+1] / CMB.Tcmb
        Ealm = cs.utils.lm_healpy2healpix(
            alms[1], 5100)[:lmax + 1, :lmax + 1] / CMB.Tcmb
        Balm = cs.utils.lm_healpy2healpix(
            alms[2], 5100)[:lmax + 1, :lmax + 1] / CMB.Tcmb
        # biref
        #print('birefringence')
        Ealm, Balm = ana.ebrotate(beta, Ealm, Balm)
        # add noise and filtering (temp)
        #print('add noise')
        #Talm += cs.utils.gauss1alm(lmax,nl[0,:])
        Ealm += cs.utils.gauss1alm(lmax, nl[1, :])
        Balm += cs.utils.gauss1alm(lmax, nl[2, :])
        #print('mask')
        #Talm = cs.utils.mulwin(Talm,M)
        Ealm, Balm = cs.utils.mulwin_spin(Ealm, Balm, M)
        # simple diagonal c-inverse
        #print('reconstruction')
        Fl = np.zeros((3, lmax + 1, lmax + 1))
        for l in range(rlmin, rlmax):
            Fl[:, l, 0:l + 1] = 1. / ocl[:3, l, None]
        #Talm *= Fl[0,:,:]
        fEalm = Ealm * Fl[1, :, :]
        fBalm = Balm * Fl[2, :, :]
        # compute unnormalized estiamtors
        #glm['TE'], clm['TE'] = cs.rec_iamp.qte(lmax,rlmin,rlmax,lcl[3,:],Talm,Ealm)
        #glm['TB'], clm['TB'] = cs.rec_iamp.qtb(lmax,rlmin,rlmax,lcl[3,:],Talm,Balm)
        #glm['EE'], clm['EE'] = cs.rec_iamp.qee(lmax,rlmin,rlmax,lcl[1,:],Ealm,Ealm)
        glm = cs.rec_iamp.qeb(lmax, rlmin, rlmax, ocl[1, :] - ocl[2, :], fEalm,
                              fBalm)
        #glm['BB'], clm['BB'] = cs.rec_iamp.qbb(lmax,rlmin,rlmax,lcl[1,:],Balm,Balm)
        #print('cross spec')
        pickle.dump((glm, Ealm, Balm),
                    open(fname, "wb"),
                    protocol=pickle.HIGHEST_PROTOCOL)

    cl = cs.utils.alm2cl(lmax, Ag['EB'][:, None] * glm, palm)
    W2 = np.mean(M**2)
    EB = cs.utils.alm2cl(lmax, Ealm, Balm) / W2
    return cl, EB
コード例 #17
0
def klm_2_product(klmname, width, maskname, nsides, lmin, subtract_mf=False, writename=None):

    # read in planck alm convergence data
    planck_lensing_alm = hp.read_alm(klmname)
    lmax = hp.Alm.getlmax(len(planck_lensing_alm))

    if subtract_mf:
        mf_alm = hp.read_alm('maps/mf_klm.fits')
        planck_lensing_alm = planck_lensing_alm - mf_alm

    # if you want to smooth with a gaussian
    if width > 0:
        # transform a gaussian of FWHM=width in real space to harmonic space
        k_space_gauss_beam = hp.gauss_beam(fwhm=width.to('radian').value, lmax=lmax)
        # if truncating small l modes
        if lmin > 0:
            # zero out small l modes in k-space filter
            k_space_gauss_beam[:lmin] = 0

        # smooth in harmonic space
        filtered_alm = hp.smoothalm(planck_lensing_alm, beam_window=k_space_gauss_beam)
    else:
        # if not smoothing with gaussian, just remove small l modes
        filtered_alm = zero_modes(planck_lensing_alm, lmin)

    planck_lensing_map = hp.sphtfunc.alm2map(filtered_alm, nsides, lmax=lmax)

    # mask map
    importmask = hp.read_map(maskname)
    if nsides < 2048:
        mask_lowres_proper = hp.ud_grade(importmask.astype(float), nside_out=1024).astype(float)
        finalmask = np.where(mask_lowres_proper == 1., True, False).astype(bool)
    else:
        finalmask = importmask.astype(np.bool)
    # set mask, invert
    smoothed_masked_map = hp.ma(planck_lensing_map)
    smoothed_masked_map.mask = np.logical_not(finalmask)

    if writename:
        hp.write_map('%s.fits' % writename, smoothed_masked_map.filled(), overwrite=True, dtype=np.single)

    return smoothed_masked_map.filled()
コード例 #18
0
def alm2map_masked(mask_path,data_path):
	mask=hp.read_map(mask_path)
	alm=hp.read_alm(data_path)
	map=hp.sphtfunc.alm2map(alm,nside)

	map_masked=hp.ma(map)
	map_masked.mask=np.logical_not(mask)

	plt.figure()
	hp.mollview(map_masked)
	plt.savefig("/home/yhwu/pic/alm2map_masked.png",dpi=1000)
	plt.clf()
コード例 #19
0
def run_cmbmap(pathname, overwr):
    """
    Derives CMB powerspectrum directly from alm data of pure CMB.
    """
    nsi = csu.nside_out[1]
    cmb_tlm = hp.read_alm(
        '/project/projectdirs/cmb/data/generic/cmb/ffp10/mc/scalar/ffp10_lensed_scl_cmb_000_alm_mc_%04d.fits'
        % int(csu.sim_id),
        hdu=1)
    cmb_elm = hp.read_alm(
        '/project/projectdirs/cmb/data/generic/cmb/ffp10/mc/scalar/ffp10_lensed_scl_cmb_000_alm_mc_%04d.fits'
        % int(csu.sim_id),
        hdu=2)
    cmb_blm = hp.read_alm(
        '/project/projectdirs/cmb/data/generic/cmb/ffp10/mc/scalar/ffp10_lensed_scl_cmb_000_alm_mc_%04d.fits'
        % int(csu.sim_id),
        hdu=3)

    # TODO what is a reasonable nside for this?
    CMB = hp.alm2map([cmb_tlm, cmb_elm, cmb_blm], nsi)
    io.save_data(CMB, io.fh.map_cmb_sc_path_name)
コード例 #20
0
ファイル: test_mapper_p18cmbk.py プロジェクト: xC-ell/xCell
def test_alm_cut():
    # Tests alm filtering for CMB kappa alms on low resolution pixels.
    config = get_config()
    config['nside'] = 16
    m = xc.mappers.MapperP18CMBK(config)
    m.get_signal_map()
    alm_all, lmax = hp.read_alm(config['file_klm'], return_mmax=True)
    alm_all = m.rot.rotate_alm(alm_all)
    fl = np.ones(lmax + 1)
    fl[3 * 16:] = 0
    alm_cut = hp.almxfl(alm_all, fl, inplace=True)
    assert np.all(np.real(m.klm - alm_cut) == 0.)
コード例 #21
0
def denoise(mask_path,data_path,tmp_path):
	mask=hp.read_map(mask_path)
	klm=hp.read_alm(data_path)
	tmp=np.loadtxt(tmp_path)

	ell=np.array(tmp[:,0])
	N=np.array(tmp[:,1])
	C=np.array(tmp[:,2]-tmp[:,1])
	nlm=hp.sphtfunc.almxfl(klm,N/(C+N))
	klm=hp.sphtfunc.almxfl(klm,C/(C+N))

	ell,m=hp.sphtfunc.Alm.getlm(lmax=LMAX)
	ell+=1
	ls=klm*2.0/np.sqrt(ell*(ell+1))
	potential=klm*2.0/(ell*(ell+1))
	
	kmap=hp.sphtfunc.alm2map(klm,nside)
	nmap=hp.sphtfunc.alm2map(nlm,nside)
	lsmap=hp.sphtfunc.alm2map(ls,nside)
	potentialmap=hp.sphtfunc.alm2map(potential,nside)
	
	kappa=hp.sphtfunc.alm2cl(klm,lmax=LMAX)
	kappa_name="kappa_cl"
	Cl_plot(kappa,kappa_name)
	lensing=hp.sphtfunc.alm2cl(ls,lmax=LMAX)
	lensing_name="lensing_cl"
	Cl_plot(lensing,lensing_name)
	potential=hp.sphtfunc.alm2cl(potential,lmax=LMAX)
	potential_name="potential_cl"
	Cl_plot(potential,potential_name)

	dec,ra=np.rad2deg(hp.pix2ang(nside,range(hp.nside2npix(nside))))
	dec=90.-dec
	ra=ra[mask>0]
	dec=dec[mask>0]
	kmap=kmap[mask>0]

	return ra,dec,kmap
	
	plt.figure()
	hp.mollview(kmap)
	plt.savefig("/home/yhwu/pic/kappa.png",dpi=1000)
	plt.clf()
	hp.mollview(nmap)
	plt.savefig("/home/yhwu/pic/noise.png",dpi=1000)
	plt.clf()
	hp.mollview(lsmap)
	plt.savefig("/home/yhwu/pic/lensing.png",dpi=1000)
	plt.clf()
	hp.mollview(potentialmap)
	plt.savefig("/home/yhwu/pic/potential.png",dpi=1000)
	plt.clf()
コード例 #22
0
ファイル: ngSWgNL.py プロジェクト: sarojadhikari/powerasym
    def generate_gaus_map(self, readGmap=-1):
        if (readGmap<0):
            self.gausalm=hp.synalm(self.inputCls)
        else:
            # code assumes that self.mapsdir="maps50/"
            self.gausalm=hp.read_alm(self.mapsdir+"gmap_"+str(readGmap)+".fits")
            ns=0.965
            C0N=(1.0-np.exp(-(ns-1)*self.efolds))/(ns-1)
            C050=(1.0-np.exp(-(ns-1)*50))/(ns-1)
            alm0r=np.sqrt(C0N/C050)
            self.gausalm[0]=self.gausalm[0]*alm0r

        self.gausmap=hp.alm2map(self.gausalm, nside=self.NSIDE) # includes the monopole bit
コード例 #23
0
ファイル: mapper_P18CMBK.py プロジェクト: xC-ell/xCell
 def get_signal_map(self):
     if self.signal_map is None:
         # Read alms
         self.klm, lmax = hp.read_alm(self.config['file_klm'],
                                      return_mmax=True)
         if self.rot is not None:
             self.klm = self.rot.rotate_alm(self.klm)
         # Filter if lmax is too large
         if lmax > 3 * self.nside - 1:
             fl = np.ones(lmax + 1)
             fl[3 * self.nside:] = 0
             self.klm = hp.almxfl(self.klm, fl, inplace=True)
         self.signal_map = np.array([hp.alm2map(self.klm, self.nside)])
     return self.signal_map
コード例 #24
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
コード例 #25
0
ファイル: pipeline.py プロジェクト: ACTCollaboration/tilec
def get_websky_sim(qid,shape,wcs,ra_pix_shift=None,components=['cmb','cib','tsz','ksz','ksz_patchy'],
                   bandpassed=True,no_act_color_correction=False,cmb_set=0):
    # load cmb + ksz + tsz + isw alm
    # get cfreq
    # add nearest cib scaled to cfreq

    gmix = lambda x: gen_mix(qid,x,bandpassed=bandpassed,bandpass_shifts=None,no_act_color_correction=no_act_color_correction)

    owcs = wcs.copy()
    if shift is not None: owcs.wcs.crpix -= np.asarray([ra_pix_shift,0])
    lmax = 8192*3
    asize = hp.Alm.getsize(lmax)
    oalms = np.zeros((3,asize))
    
    rpath = sints.dconfig['actsims']['websky_path'] + "/" 
    
    if 'cmb' in components:
        ialm = hp.read_alm(rpath + "lensed_alm_seed%d.fits" % cmb_set,hdu=(1,2,3))
        for i in range(3): oalms[i] = oalms[i] + maps.change_alm_lmax(ialm[i], lmax)        

    if 'tsz' in components:
        tconversion = gmix('tSZ') # !!!
        ialm = hp.read_alm(rpath + "alms/tsz_8192_alm.fits" )
        oalms[0] = oalms[0] + ialm * tconversion
コード例 #26
0
    def get_sim_tlm(self, idx):
        """Returns an inverse-filtered temperature simulation.

            Args:
                idx: simulation index

            Returns:
                inverse-filtered temperature healpy alm array

        """
        tfname = os.path.join(self.lib_dir, 'sim_%04d_tlm.fits'%idx if idx >= 0 else 'dat_tlm.fits')
        if not os.path.exists(tfname):
            tlm = self._apply_ivf_t(self.sim_lib.get_sim_tmap(idx), soltn=None if self.soltn_lib is None else self.soltn_lib.get_sim_tmliklm(idx))
            if self.cache: hp.write_alm(tfname, tlm)
            return tlm
        return hp.read_alm(tfname)
コード例 #27
0
ファイル: qest.py プロジェクト: markm42/plancklens
    def get_sim_qlm_mf(self, k, mc_sims, lmax=None):
        """Returns a QE mean-field estimate, by averaging QE estimates from a set simulations (caches the result).

            Args:
                k: quadratic estimator key
                mc_sims: simulation indices to use for the estimate.
                lmax: optionally reduces the lmax of the output healpy array.

        """
        if lmax is None:
            lmax = self.get_lmax_qlm(k)
        assert lmax <= self.get_lmax_qlm(k)
        if k in ['p_tp', 'x_tp']:
            return (self.get_sim_qlm_mf('%stt' % k[0], mc_sims, lmax=lmax) +
                    self.get_sim_qlm_mf('%s_p' % k[0], mc_sims, lmax=lmax))
        if k in ['p_te', 'p_tb', 'p_eb', 'x_te', 'x_tb', 'x_eb']:
            return  self.get_sim_qlm_mf(k[0] + k[2] + k[3], mc_sims, lmax=lmax)  \
                    + self.get_sim_qlm_mf(k[0] + k[3] + k[2], mc_sims, lmax=lmax)
        if '_bh_' in k:  # Bias-hardening
            assert self.resplib is not None, 'resplib arg necessary for this'
            kQE, ksource = k.split('_bh_')
            assert len(ksource) == 1 and ksource + kQE[1:] in self.keys, (
                ksource, kQE)
            assert self.get_lmax_qlm(kQE) == self.get_lmax_qlm(
                ksource + kQE[1:]), 'fix this (easy)'
            lmax = self.get_lmax_qlm(kQE)
            wL = self.resplib.get_response(kQE, ksource) * ut.cli(
                self.resplib.get_response(ksource + kQE[1:], ksource))
            ret = self.get_sim_qlm_mf(kQE, mc_sims, lmax=lmax)
            return ret - hp.almxfl(
                self.get_sim_qlm_mf(ksource + kQE[1:], mc_sims, lmax=lmax), wL)

        assert k in self.keys_fund, (k, self.keys_fund)
        fname = os.path.join(self.lib_dir,
                             'simMF_k1%s_%s.fits' % (k, ut.mchash(mc_sims)))
        if not os.path.exists(fname):
            this_mcs = np.unique(mc_sims)
            MF = np.zeros(hp.Alm.getsize(lmax), dtype=complex)
            if len(this_mcs) == 0: return MF
            for i, idx in ut.enumerate_progress(this_mcs,
                                                label='calculating %s MF' % k):
                MF += self.get_sim_qlm(k, idx, lmax=lmax)
            MF /= len(this_mcs)
            _write_alm(fname, MF)
            print("Cached ", fname)
        return ut.alm_copy(hp.read_alm(fname), lmax=lmax)
コード例 #28
0
ファイル: test_cmb.py プロジェクト: simonsobs/mapsims
def test_standalone_cmb():
    alm_filename = get_pkg_data_filename(
        "data/fullskyUnlensedUnabberatedCMB_alm_set00_00000.fits")
    cmb_dir = os.path.dirname(alm_filename)
    nside = 32
    cmb_map = cmb.SOStandalonePrecomputedCMB(
        num=0,
        nside=nside,
        cmb_dir=cmb_dir,
        lensed=False,
        aberrated=False,
        input_reference_frequency=148 * u.GHz,
        input_units="uK_RJ",
    ).get_emission(148 * u.GHz, fwhm=1e-5 * u.arcmin)
    input_alm = hp.read_alm(alm_filename, (1, 2, 3))
    expected_cmb_map = hp.alm2map(input_alm, nside=nside) << u.uK_RJ
    assert cmb_map.shape[0] == 3
    assert_quantity_allclose(expected_cmb_map, cmb_map)
コード例 #29
0
 def get_sim_tlm(self, idx):
     fname = self.lib_dir + '/sim_%04d_tlm.fits' % idx
     if not os.path.exists(fname):
         tlm = self.unlcmbs.get_sim_tlm(idx)
         dlm = self.get_sim_plm(idx)
         lmaxd = hp.Alm.getlmax(dlm.size)
         hp.almxfl(dlm,
                   np.sqrt(
                       np.arange(lmaxd + 1, dtype=float) *
                       np.arange(1, lmaxd + 2)),
                   inplace=True)
         hp.write_alm(
             fname,
             lens.lens_tlm(tlm,
                           dlm,
                           nside=self.nside_lens,
                           lmaxout=self.lmax))
     return hp.read_alm(fname)
コード例 #30
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
コード例 #31
0
    def compute_intensity_derivatives(self, fromalm=False):
        """
        Compute derivatives of the input temperature map (healpix).
        Not updated for dichroic for the moment.

        Parameters
        ----------
        fromalm : bool, optional
            If True, loads alm file from disk instead of fourier
            transform the input map. Automatically turns True if you input
            alm files. False otherwise.

        Examples
        ----------
        >>> filename = 's4cmb/data/test_data_set_lensedCls.dat'
        >>> hpmap = HealpixFitsMap(input_filename=filename, fwhm_in=3.5,
        ...     nside_in=16, compute_derivatives=True, map_seed=489237)
        >>> hasattr(hpmap, 'dIdp')
        True

        """
        if fromalm:
            alm = hp.read_alm(self.input_filename[0])
        else:
            alm = hp.map2alm(self.I, self.lmax)

        # lmax = hp.Alm.getlmax(alm.size)
        if "T1" in self.derivatives_type:
            junk, self.dIdt, self.dIdp = hp.alm2map_der1(
                alm, self.nside_in, self.lmax)
        else:
            # computes first and second derivative as derivatives of spin-1
            # transform of a scalar field with _1Elm=sqrt(l(l+1))Ilm _1Blm=0
            l = np.arange(self.lmax + 1)
            grad = np.sqrt(l * (l + 1))
            curl = np.zeros_like(alm)
            dervs = alm2map_spin_der1([hp.almxfl(alm, grad), curl],
                                      self.nside_in, 1)
            self.dIdt = dervs[0][0]
            self.dIdp = dervs[0][1]
            self.d2Id2t = dervs[1][0]
            self.d2Id2p = dervs[2][1]
            self.d2Idpdt = dervs[2][0]
コード例 #32
0
ファイル: planck.py プロジェクト: yiheng-wu/cosmology_0
def denoise(mask_path, data_path, tmp_path):
    mask = hp.read_map(mask_path)
    klm = hp.read_alm(data_path)
    tmp = np.loadtxt(tmp_path)

    ell = np.array(tmp[:, 0])
    N = np.array(tmp[:, 1])
    C = np.array(tmp[:, 2] - tmp[:, 1])
    nlm = hp.sphtfunc.almxfl(klm, N / (C + N))
    klm = hp.sphtfunc.almxfl(klm, C / (C + N))

    ell, m = hp.sphtfunc.Alm.getlm(lmax=LMAX)
    ell += 1
    ls = klm * 2.0 / np.sqrt(ell * (ell + 1))
    lss = klm * 2.0 / (ell * (ell + 1))

    kmap = hp.sphtfunc.alm2map(klm, nside)
    nmap = hp.sphtfunc.alm2map(nlm, nside)
    lsmap = hp.sphtfunc.alm2map(ls, nside)
    lssmap = hp.sphtfunc.alm2map(lss, nside)

    kappa = hp.sphtfunc.alm2cl(klm, lmax=LMAX)
    kappa_name = "kappa_cl"
    #Cl_plot(kappa,kappa_name)
    lensing = hp.sphtfunc.alm2cl(ls, lmax=LMAX)
    lensing_name = "lensing_filtered_cl"
    #Cl_plot(lensing,lensing_name)

    plt.figure()
    '''
	hp.mollview(kmap)
	plt.savefig("/home/yhwu/pic/kappa.png",dpi=1000)
	plt.clf()
	hp.mollview(nmap)
	plt.savefig("/home/yhwu/pic/noise.png",dpi=1000)
	plt.clf()
	'''
    hp.mollview(lsmap)
    plt.savefig("/home/yhwu/pic/lensing.png", dpi=1000)
    plt.clf()
    hp.mollview(lssmap)
    plt.savefig("/home/yhwu/pic/lss.png", dpi=1000)
    plt.clf()
コード例 #33
0
def FilterMap(pixmap, freq, mask=None, lmax=None, pixelwindow=False):
    if mask is None:
        mask = np.ones_like(pixmap)
    else:
        assert hp.isnpixok(mask.size)
    Fl = GetFl(pixmap,freq, mask=mask, lmax=lmax)
    alm_fname='alm_%s.fits'%freq
    if not os.path.exists(alm_fname):
	print "computing alms"
	alm = hp.map2alm(pixmap, lmax=lmax)
	hp.write_alm(alm_fname,alm)
    else:
	print "reading alms",alm_fname
	alm = hp.read_alm(alm_fname)
    if pixelwindow:
	print "Correcting alms for pixelwindow"
        pl=hp.pixwin(hp.npix2nside(pixmap.size))[:lmax+1]
    else: pl=np.ones(len(Fl))
    return hp.alm2map(hp.almxfl(alm, Fl/pl), hp.npix2nside(pixmap.size), lmax=lmax), Fl
コード例 #34
0
def main():

    '''
    MPI Setup
    '''
    o_comm = MPI.COMM_WORLD
    i_rank = o_comm.Get_rank() # current core number -- e.g., i in arange(i_size)
    i_size = o_comm.Get_size() # number of cores assigned to run this program
    o_status = MPI.Status()

    i_work_tag = 0
    i_die_tag = 1

    '''
    Loading and calculating power spectrum components
    '''

    # Get run parameters
    
    s_fn_params = 'data/params.pkl'
    (i_lmax, i_nside, s_fn_map, s_map_name, s_fn_mask, s_fn_mll, s_fn_beam, 
        s_fn_alphabeta, s_fn_cltt) = get_params(s_fn_params)

    #s_fn_cltt = 'sims/cl_fnl_0.dat'

    if (i_rank == 0):

        s_fn_cl21_data = 'output/cl21_data.dat'
        s_fn_cl21_data_no_mll = 'output/cl21_data_no_mll.dat'
        #s_fn_cl21_data = 'output/cl21_ps_smica.dat'
        #s_fn_cl21_data_no_mll = 'output/cl21_ps_smica_no_mll.dat'


        f_t1 = time.time()

        print ""
        print "Run parameters:"
        print "(Using %i cores)" % i_size
        print "lmax: %i, nside: %i, map name: %s" % (i_lmax, i_nside, s_map_name)
        print "beam: %s, alpha_beta: %s, cltt: %s" % (s_fn_beam, s_fn_alphabeta, s_fn_cltt)

        print ""
        print "Loading ell, r, dr, alpha, beta, cltt, and beam..."

    na_mask = hp.read_map(s_fn_mask)
    #s_fn_mll = 'output/na_mll_%i_lmax.npy' % i_lmax
    s_fn_mll = 'output/na_mll_1499_lmax.npy'
    na_mll = np.load(s_fn_mll)
    na_mll_inv = np.linalg.inv(na_mll)

    na_l, na_r, na_dr, na_alpha, na_beta = np.loadtxt(s_fn_alphabeta, 
                                usecols=(0,1,2,3,4), unpack=True, skiprows=3)

    na_l = np.unique(na_l)
    na_r = np.unique(na_r)[::-1]

    i_num_r = len(na_r)

    try:
        na_cltt = np.load(s_fn_cltt)
    except:
        na_cltt = np.loadtxt(s_fn_cltt)

    na_bl = np.load(s_fn_beam)

    na_alpha = na_alpha.reshape(len(na_l), i_num_r)
    na_beta = na_beta.reshape(len(na_l), i_num_r)
    na_dr = na_dr.reshape(len(na_l), i_num_r)
    na_dr = na_dr[0]

    i_num_ell = min(len(na_l), len(na_cltt), len(na_bl), i_lmax)

    na_l = na_l[:i_num_ell]
    na_cltt = na_cltt[:i_num_ell]
    na_bl = na_bl[:i_num_ell]
    na_alpha = na_alpha[:i_num_ell,:]
    na_beta = na_beta[:i_num_ell,:]

    if (i_rank == 0):
        print "i_num_r: %i, i_num_ell: %i" % (i_num_r, i_num_ell)

    # f_t2 = time.time()

    if (i_rank == 0):
        print ""
        print "Calculating full skewness power spectrum..."

    s_fn_alm = 'output/na_alm_data.fits'
    #s_fn_alm = 'data/ps_sim/alm_ps_smica_ell_2000.fits'
    na_alm = hp.read_alm(s_fn_alm)
    na_alm = na_alm[:hp.Alm.getsize(i_num_ell)]

    # f_t3 = time.time()

    na_cl21_data = np.zeros(i_num_ell)
    na_work = np.zeros(1, dtype='i')
    na_result = np.zeros(i_num_ell, dtype='d')

    # master loop
    if (i_rank == 0):

        # send initial jobs

        for i_rank_out in range(1,i_size):

            na_work = np.array([i_rank_out-1], dtype='i')
            o_comm.Send([na_work, MPI.INT], dest=i_rank_out, tag=i_work_tag)

        for i_r in range(i_size-1,i_num_r):

            if (i_r % (i_num_r / 10) == 0):
                print "Finished %i%% of jobs... (%.2f s)" % (i_r * 100 / i_num_r,
                time.time() - f_t1)

            na_work = np.array([i_r], dtype='i')

            o_comm.Recv([na_result, MPI.DOUBLE], source=MPI.ANY_SOURCE, 
                status=o_status, tag=MPI.ANY_TAG)

            #print "received results from core %i" % o_status.Get_source()

            o_comm.Send([na_work,MPI.INT], dest=o_status.Get_source(), 
                tag=i_work_tag)

            na_cl21_data += na_result

        for i_rank_out in range(1,i_size):

            o_comm.Recv([na_result, MPI.DOUBLE], source=MPI.ANY_SOURCE,
                status=o_status, tag=MPI.ANY_TAG)

            na_cl21_data += na_result
            print "cl21_data = %.6f, na_result = %.6f" % (np.average(na_cl21_data), np.average(na_result))

            o_comm.Send([np.array([9999], dtype='i'), MPI.INT], 
                dest=o_status.Get_source(), tag=i_die_tag)

    #slave loop:
    else:

        while(1):

            o_comm.Recv([na_work, MPI.INT], source=0, status=o_status, 
                tag=MPI.ANY_TAG)

            if (o_status.Get_tag() == i_die_tag):

                break

            i_r = na_work[0]

            #print "doing work for r = %i on core %i" % (i_r, i_rank)

            na_Alm = hp.almxfl(na_alm, na_alpha[:,i_r] / na_cltt * na_bl)
            na_Blm = hp.almxfl(na_alm, na_beta[:,i_r] / na_cltt * na_bl)

            # print ("doing work for r=%i, alpha=(%.2f), beta=(%.2f)" % 
            #     (int(na_r[i_r]), na_alpha[0,i_r], na_beta[0,i_r]))

            # f_t4 = time.time()

            na_An = hp.alm2map(na_Alm, nside=i_nside, fwhm=0.00145444104333,
                verbose=False)
            na_Bn = hp.alm2map(na_Blm, nside=i_nside, fwhm=0.00145444104333,
                verbose=False)

            # *REMBER TO MULTIPLY BY THE MASK!* -- already doing this in cltt.py...

            na_An = na_An * na_mask
            na_Bn = na_Bn * na_mask

            # f_t5 = time.time()

            #print "starting map2alm for r = %i on core %i" % (i_r, i_rank)

            na_B2lm = hp.map2alm(na_Bn*na_Bn, lmax=i_num_ell)
            na_ABlm = hp.map2alm(na_An*na_Bn, lmax=i_num_ell)

            #print "finished map2alm for r = %i on core %i" % (i_r, i_rank)

            # f_t6 = time.time()

            na_clAB2 = hp.alm2cl(na_Alm, na_B2lm, lmax=i_num_ell)
            na_clABB = hp.alm2cl(na_ABlm, na_Blm, lmax=i_num_ell)

            #na_clAB2 = na_clAB2[:-1] # just doing this to make things fit...
            #na_clABB = na_clABB[:-1] # just doing this to make things fit...

            na_clAB2 = na_clAB2[1:]
            na_clABB = na_clABB[1:]

            #f_t7 = time.time()

            na_result = np.zeros(i_num_ell, dtype='d')
            na_result += (na_clAB2 + 2 * na_clABB) * na_r[i_r]**2. * na_dr[i_r]

            print ("finished work for r=%i, avg(alpha)=%.2f, avg(beta)=%.2f, avg(result)=%.4g" % 
                (int(na_r[i_r]), np.average(na_alpha[:,i_r]), 
                    np.average(na_beta[:,i_r]), np.average(na_result)))
            #print "finished work for r = %i on core %i" % (i_r, i_rank)

            o_comm.Send([na_result,MPI.DOUBLE], dest=0, tag=1)

            # print "Load time: %.2f s" % (f_t2 - f_t1)
            # print "synalm time: %.2f s" % (f_t3 - f_t2)
            # print "almxfl time: %.2f s" % ((f_t4 - f_t3) / 2.)
            # print "alm2map time: %.2f s" % ((f_t5 - f_t4) / 2.)
            # print "map2alm time: %.2f s" % ((f_t6 - f_t5) / 2.)
            # print "alm2cl time: %.2f s" % ((f_t7 - f_t6) / 2.)

    f_t8 = time.time()

    if (i_rank == 0):
        print ""
        print ("Saving power spectrum to %s (not mll corrected)" 
            % s_fn_cl21_data_no_mll)

        np.savetxt(s_fn_cl21_data_no_mll, na_cl21_data)

        print ""
        print "Saving power spectrum to %s (mll corrected)" % s_fn_cl21_data
        
        na_cl21_data = np.dot(na_mll_inv, na_cl21_data)
        np.savetxt(s_fn_cl21_data, na_cl21_data)

        # print "Finished in %.2f s" % (f_t8 - f_t1)
        # # print "Load time: %.2f s" % (f_t2 - f_t1)
        # # print "synalm time: %.2f s" % (f_t3 - f_t2)
        # # print "almxfl time: %.2f s" % ((f_t4 - f_t3) / 2.)
        # # print "alm2map time: %.2f s" % ((f_t5 - f_t4) / 2.)
        # # print "map2alm time: %.2f s" % ((f_t6 - f_t5) / 2.)
        # # print "alm2cl time: %.2f s" % ((f_t7 - f_t6) / 2.)

    return
コード例 #35
0
ファイル: stack.py プロジェクト: msyriac/HaloLenses
def main(argv):
    
    ras,decs = getCatalogRADecsPlanck()

    pixScale = 0.5
    widthArc = 70.
    width = widthArc/60.
    Np = np.int(width/pixScale*60.+0.5)

    saveRoot = "/astro/astronfs01/workarea/msyriac/SkyData/"
    planckRoot = saveRoot+'cmb/'
    planckMaskPath = planckRoot+'planck2015_mask.fits'

    mask15 = hp.read_map(planckMaskPath,verbose=False)

    saveRoot = "/astro/astronfs01/workarea/msyriac/SkyData/"
    planckRoot = saveRoot+'cmb/'    
    pl15lm = hp.read_alm(planckRoot+'dat_klm.fits')
    hpPlanckK = hp.sphtfunc.alm2map(pl15lm,2048,pol=False)
    

    outN = argv[0]
    tfact = 1.

    if outN=='143':
        p143Loc = '/astro/astronfs01/workarea/msyriac/PlanckClusters/HFI_SkyMap_143_2048_R2.02_full.fits'
        
    elif outN=='com':
        p143Loc = '/astro/astronfs01/workarea/msyriac/PlanckClusters/COM_CMB_IQU-commander-field-Int_2048_R2.00.fits'
    elif outN=='217':    
        p143Loc = '/astro/astronfs01/workarea/msyriac/PlanckClusters/HFI_SkyMap_217_2048_R2.02_full.fits'
    elif outN=='wpr2':
        p143Loc = '/astro/astronfs01/workarea/msyriac/PlanckClusters/WPR2_CMB_muK.fits'
        tfact = 1.e-6
    else:
        print 'invalid input'
        sys.exit()

    Npix = 12.*2048**2.
    print mask15.sum()/Npix
    hpPlanck = hp.read_map(p143Loc)
    hpPlanckCopy = hpPlanck.copy()
    hpPlanckCopy[mask15<0.5]=np.nan
    print np.nanmean(hpPlanckCopy)
    lim = np.nanstd(hpPlanckCopy*tfact)
    print lim
    #sys.exit()

    stack = 0.
    stackK = 0.

    maxN = None
    #maxN = 10
    i=0
    for ra,dec in zip(ras[:maxN],decs[:maxN]):
        i+=1
        print i,ra,dec

        # ra = np.random.uniform(5.,350.)
        # dec = np.random.uniform(-80.,10.)

        raLeft = ra - width/2.
        raRight = ra + width/2.
        decLeft = dec - width/2.
        decRight = dec + width/2.

        fieldCoords = (raLeft,decLeft,raRight,decRight)
        smap = lm.makeEmptyCEATemplateAdvanced(*fieldCoords)
        smapK = lm.makeEmptyCEATemplateAdvanced(*fieldCoords)
        smap.loadDataFromHealpixMap(hpPlanck,hpCoords="GALACTIC")
        smapK.loadDataFromHealpixMap(hpPlanckK,hpCoords="GALACTIC")


        stamp = smap.data.copy() * tfact
        stamp = zoom(stamp,zoom=(float(Np)/stamp.shape[0],float(Np)/stamp.shape[1]))

        stampK = smapK.data.copy() 
        stampK = zoom(stampK,zoom=(float(Np)/stampK.shape[0],float(Np)/stampK.shape[1]))
        
        stack += stamp[:,:]
        stackK += stampK[:,:]



    pl = Plotter()
    pl.plot2d(stack/i)#,lim=lim*3.)
    pl.done("stack"+outN+"6.png")

    pl = Plotter()
    pl.plot2d(stackK/i)#,lim=lim*3.)
    pl.done("stackK6.png")
コード例 #36
0
def main(i_sim=1):

    '''
    MPI Setup
    '''
    o_comm = MPI.COMM_WORLD
    i_rank = o_comm.Get_rank() # current core number -- e.g., i in arange(i_size)
    i_size = o_comm.Get_size() # number of cores assigned to run this program
    o_status = MPI.Status()

    i_work_tag = 0
    i_die_tag = 1

    '''
    Loading and calculating power spectrum components
    '''

    # Get run parameters
    
    s_fn_params = 'data/params.pkl'
    (i_lmax, i_nside, s_fn_map, s_map_name, s_fn_mask, s_fn_mll, s_fn_beam, 
        s_fn_alphabeta, s_fn_cltt) = get_params(s_fn_params)

    #s_fn_cltt = ('data/fnl_sims/cl_fnl_0_sim_%04d.fits' % (i_sim,))

    f_fnl = 1.0

    if (i_rank == 0):

        s_fn_cl21_data = ('data/cl21_fnl_sims/cl21_fnl_%i_sim_%04d.dat' 
            % (int(f_fnl), i_sim))
        s_fn_cl21_data_no_mll = ('data/cl21_fnl_sims/cl21_fnl_%i_sim_%04d_no_mll.dat' 
            % (int(f_fnl), i_sim))

        f_t1 = time.time()

        print ""
        print "Run parameters:"
        print "(Using %i cores)" % i_size
        print "lmax: %i, nside: %i, map name: %s" % (i_lmax, i_nside, s_map_name)
        print "beam: %s, alpha_beta: %s, cltt: %s" % (s_fn_beam, s_fn_alphabeta, s_fn_cltt)

        print ""
        print "Loading ell, r, dr, alpha, beta, cltt, and beam..."

    i_lmax = 1024

    na_mask = hp.read_map(s_fn_mask)
    s_fn_mll = 'output/na_mll_%i_lmax.npy' % i_lmax
    na_mll = np.load(s_fn_mll)
    na_mll_inv = np.linalg.inv(na_mll)

    na_l, na_r, na_dr, na_alpha, na_beta = np.loadtxt(s_fn_alphabeta, 
                                usecols=(0,1,2,3,4), unpack=True, skiprows=3)

    na_l = np.unique(na_l)
    na_r = np.unique(na_r)[::-1]
    na_l = na_l[:i_lmax]

    i_num_ell = len(na_l)
    i_num_r = len(na_r)

    if (i_rank == 0):
        print "i_num_r: %i, i_num_ell: %i" % (i_num_r, i_num_ell)

    # assuming number of r's is set correctly and number of ells isn't necessarily
    # related to lmax, i_num_ell, etc.
    i_num_ell_alpha_beta_r = len(na_alpha)/i_num_r
    na_alpha = na_alpha.reshape(i_num_ell_alpha_beta_r, i_num_r)
    na_beta = na_beta.reshape(i_num_ell_alpha_beta_r, i_num_r)
    na_dr = na_dr.reshape(i_num_ell_alpha_beta_r, i_num_r)
    na_dr = na_dr[0]

    na_alpha = na_alpha[:i_num_ell,:]
    na_beta = na_beta[:i_num_ell,:]
    na_dr = na_dr[:i_num_ell]

    try:
        na_cltt = np.load(s_fn_cltt)
    except:
        na_cltt = np.loadtxt(s_fn_cltt)
    na_cltt = na_cltt[:i_num_ell]

    na_bl = np.load(s_fn_beam)
    na_bl = na_bl[:i_num_ell]

    # f_t2 = time.time()

    if (i_rank == 0):
        print ""
        print "Calculating full skewness power spectrum..."

    #na_alm = hp.synalm(na_cltt, lmax=i_num_ell, verbose=False)

    s_fn_almg = ('data/fnl_sims/alm_l_%04d_v3.fits' % (i_sim,))
    na_almg = hp.read_alm(s_fn_almg)
    na_almg = na_almg[:hp.Alm.getsize(i_num_ell)]
    s_fn_almng = ('data/fnl_sims/alm_nl_%04d_v3.fits' % (i_sim,))
    na_almng = hp.read_alm(s_fn_almng)
    na_almng = na_almng[:hp.Alm.getsize(i_num_ell)]
    na_alm = na_almg + f_fnl * na_almng

    # f_t3 = time.time()

    na_cl21_data = np.zeros(i_num_ell)
    na_work = np.zeros(1, dtype='i')
    na_result = np.zeros(i_num_ell, dtype='d')

    # if (i_rank == 0):
    #     print ("na_alm: %s, na_alpha: %s, na_beta: %s, na_cltt: %s, na_bl: %s" %
    #         (str(np.shape(na_alm)), str(np.shape(na_alpha)), 
    #             str(np.shape(na_beta)), str(np.shape(na_cltt)),
    #             str(np.shape(na_bl)) ))
    # else:
    #     print "core: %i" % i_rank
    #     print ("na_alm: %s, na_alpha: %s, na_beta: %s, na_cltt: %s, na_bl: %s" %
    #         (str(np.shape(na_alm)), str(np.shape(na_alpha)), 
    #             str(np.shape(na_beta)), str(np.shape(na_cltt)),
    #             str(np.shape(na_bl)) ))

    # master loop
    if (i_rank == 0):

        # send initial jobs

        # print ("na_alm: %s, na_alpha: %s, na_beta: %s, na_cltt: %s, na_bl: %s" %
        #         (str(np.shape(na_alm)), str(np.shape(na_alpha)), 
        #             str(np.shape(na_beta)), str(np.shape(na_cltt)),
        #             str(np.shape(na_bl)) ))

        for i_rank_out in range(1,i_size):

            na_work = np.array([i_rank_out-1], dtype='i')
            o_comm.Send([na_work, MPI.INT], dest=i_rank_out, tag=i_work_tag)

        for i_r in range(i_size-1,i_num_r):

            if (i_r % (i_num_r / 10) == 0):
                print "Finished %i%% of jobs... (%.2f s)" % (i_r * 100 / i_num_r,
                time.time() - f_t1)

            na_work = np.array([i_r], dtype='i')

            o_comm.Recv([na_result, MPI.DOUBLE], source=MPI.ANY_SOURCE, 
                status=o_status, tag=MPI.ANY_TAG)

            #print "received results from core %i" % o_status.Get_source()

            o_comm.Send([na_work,MPI.INT], dest=o_status.Get_source(), 
                tag=i_work_tag)

            na_cl21_data += na_result

        for i_rank_out in range(1,i_size):

            o_comm.Recv([na_result, MPI.DOUBLE], source=MPI.ANY_SOURCE,
                status=o_status, tag=MPI.ANY_TAG)

            na_cl21_data += na_result

            print "cl21 so far..."
            print na_cl21_data[:10], na_cl21_data[10:]

            o_comm.Send([np.array([9999], dtype='i'), MPI.INT], 
                dest=o_status.Get_source(), tag=i_die_tag)

    #slave loop:
    else:

        while(1):

            o_comm.Recv([na_work, MPI.INT], source=0, status=o_status, 
                tag=MPI.ANY_TAG)

            if (o_status.Get_tag() == i_die_tag):

                break

            i_r = na_work[0]

            #print "doing work for r = %i on core %i" % (i_r, i_rank)

            # print ("na_alm: %s, na_alpha: %s, na_beta: %s, na_cltt: %s, na_bl: %s" %
            #         (str(np.shape(na_alm)), str(np.shape(na_alpha)), 
            #             str(np.shape(na_beta)), str(np.shape(na_cltt)),
            #             str(np.shape(na_bl)) ))
            na_Alm = hp.almxfl(na_alm, np.nan_to_num(na_alpha[:,i_r] / na_cltt) * na_bl)
            na_Blm = hp.almxfl(na_alm, np.nan_to_num(na_beta[:,i_r] / na_cltt) * na_bl)

            # f_t4 = time.time()

            na_An = hp.alm2map(na_Alm, nside=i_nside, fwhm=0.00145444104333,
                verbose=False)
            na_Bn = hp.alm2map(na_Blm, nside=i_nside, fwhm=0.00145444104333,
                verbose=False)

            # *REMBER TO MULTIPLY BY THE MASK!*

            na_An = na_An * na_mask
            na_Bn = na_Bn * na_mask

            # f_t5 = time.time()

            #print "starting map2alm for r = %i on core %i" % (i_r, i_rank)

            na_B2lm = hp.map2alm(na_Bn*na_Bn, lmax=i_num_ell)
            na_ABlm = hp.map2alm(na_An*na_Bn, lmax=i_num_ell)

            #print "finished map2alm for r = %i on core %i" % (i_r, i_rank)

            # f_t6 = time.time()

            na_clAB2 = hp.alm2cl(na_Alm, na_B2lm, lmax=i_num_ell)
            na_clABB = hp.alm2cl(na_ABlm, na_Blm, lmax=i_num_ell)

            na_clAB2 = na_clAB2[1:]
            na_clABB = na_clABB[1:]

            #f_t7 = time.time()

            # print ("na_clAB2: %s, na_clABB: %s, na_r: %s, na_dr: %s" %
            #         (str(np.shape(na_clAB2)), str(np.shape(na_clABB)), 
            #             str(np.shape(na_r)), str(np.shape(na_dr)) ))

            na_result = np.zeros(i_num_ell, dtype='d')
            na_result += (na_clAB2 + 2 * na_clABB) * na_r[i_r]**2. * na_dr[i_r]

            #print "finished work for r = %i on core %i" % (i_r, i_rank)

            o_comm.Send([na_result,MPI.DOUBLE], dest=0, tag=1)

            # print "Load time: %.2f s" % (f_t2 - f_t1)
            # print "synalm time: %.2f s" % (f_t3 - f_t2)
            # print "almxfl time: %.2f s" % ((f_t4 - f_t3) / 2.)
            # print "alm2map time: %.2f s" % ((f_t5 - f_t4) / 2.)
            # print "map2alm time: %.2f s" % ((f_t6 - f_t5) / 2.)
            # print "alm2cl time: %.2f s" % ((f_t7 - f_t6) / 2.)

    f_t8 = time.time()

    if (i_rank == 0):
        print ""
        print ("Saving power spectrum to %s (not mll corrected)" 
            % s_fn_cl21_data_no_mll)

        np.savetxt(s_fn_cl21_data_no_mll, na_cl21_data)

        print ""
        print "Saving power spectrum to %s (mll corrected)" % s_fn_cl21_data
        
        na_cl21_data = np.dot(na_mll_inv, na_cl21_data)
        np.savetxt(s_fn_cl21_data, na_cl21_data)

        # print "Finished in %.2f s" % (f_t8 - f_t1)
        # # print "Load time: %.2f s" % (f_t2 - f_t1)
        # # print "synalm time: %.2f s" % (f_t3 - f_t2)
        # # print "almxfl time: %.2f s" % ((f_t4 - f_t3) / 2.)
        # # print "alm2map time: %.2f s" % ((f_t5 - f_t4) / 2.)
        # # print "map2alm time: %.2f s" % ((f_t6 - f_t5) / 2.)
        # # print "alm2cl time: %.2f s" % ((f_t7 - f_t6) / 2.)

    return
コード例 #37
0
'''
make_alms_with_fnl.py

Create alms using the Elsner maps (http://gavo.mpe.mpg.de/pub/Elsner/) for
alm_G and alm_NG to create:

alm = alm_G + fnl * alm_NG

where the input parameter to this program is fnl.

'''

import healpy as hp
import numpy as np

nsims = 1000
fnl = 0

for i in range(1,nsims+1):
    fn_alm = 'alm_fnl_%i_sim_%04d.fits' % (fnl, i)
    fn_cl = 'cl_fnl_%i_sim_%04d.fits' % (fnl, i)
    print 'making %s...' % fn_alm
    fn_alm_l = 'alm_l_%04d_v3.fits' % (i,)
    fn_alm_nl = 'alm_nl_%04d_v3.fits' % (i,)
    alm_g = hp.read_alm(fn_alm_l)
    alm_ng = hp.read_alm(fn_alm_nl)
    alm = alm_g + fnl * alm_ng
    hp.write_alm(fn_alm, alm)
    print 'making %s...' % fn_cl
    cl = hp.alm2cl(alm)
    np.savetxt(fn_cl, cl)
コード例 #38
0
def main(run_type='data', nsim=0, fnl=0):

    '''
    MPI Setup
    '''
    o_comm = MPI.COMM_WORLD
    i_rank = o_comm.Get_rank() # current core number -- e.g., i in arange(i_size)
    i_size = o_comm.Get_size() # number of cores assigned to run this program
    o_status = MPI.Status()

    i_work_tag = 0
    i_die_tag = 1

    '''
    Loading and calculating power spectrum components
    '''

    if (run_type == 'fnl'):
        nl = 1024
    else:
        nl = 1499

    if (run_type == 'data'):
        fn_map = h._fn_map
    elif (run_type == 'sim'):
        fn_map = 'output/map_sim_%i.fits' % nsim
    elif (run_type == 'fnl'):
        #print "fnl value: %i" % fnl
        fn_map = 'data/fnl_sims/map_fnl_%i_sim_%i.fits' % (int(fnl), nsim)

    # (1) read map (either map_data or map_sim), mask, mll, and create mll_inv;
    map_in = hp.read_map(fn_map)
    mask = hp.read_map(h._fn_mask)
    if (run_type == 'fnl'):
        mask = 1.
    fn_mll = 'output/na_mll_%i_lmax.npy' % nl
    mll = np.load(fn_mll)
    if (run_type == 'fnl'):
        mll = np.identity(nl)
    mll_inv = np.linalg.inv(mll)

    nside = hp.get_nside(map_in)

    if (i_rank == 0):

        if (run_type == 'data'):
            fn_cl21 = 'output/cl21_data.dat'
            fn_cl21_no_mll = 'output/cl21_data_no_mll.dat'
        elif (run_type == 'sim'):
            fn_cl21 = 'output/cl21_sim_%i.dat' % nsim
            fn_cl21_no_mll = 'output/cl21_no_mll_%i.dat' % nsim
        elif (run_type == 'fnl'):
            fn_cl21 = 'output/cl21_fnl_%i_sim_%i.dat' % (int(fnl), nsim)
            fn_cl21_no_mll = 'output/cl21_fnl_%i_sim_%i_no_mll.dat' % (int(fnl), nsim)

        f_t1 = time.time()

        print ""
        print "Run parameters:"
        print "(Using %i cores)" % i_size
        print "nl: %i, nside: %i, map: %s" % (nl, nside, fn_map)
        print "beam: %s, alpha_beta: %s, cltt: %s" % (h._fn_beam, h._fn_alphabeta, h._fn_cltt)

        print ""
        print "Loading ell, r, dr, alpha, beta, cltt, and beam..."

    # (2) normalize, remove mono-/dipole, and mask map to create map_masked;
    map_in /= (1e6 * 2.7)
    map_in = hp.remove_dipole(map_in)
    map_masked = map_in * mask

    # (3) create alm_masked (map2alm on map_masked), cltt_masked (anafast on 
    #     map_masked), and cltt_corrected (dot cltt_masked with mll_inv)

    if (run_type == 'data' or run_type == 'sim'):
        alm_masked = hp.map2alm(map_masked)
    elif (run_type == 'fnl'):
        fn_almg = ('data/fnl_sims/alm_l_%04d_v3.fits' % (nsim,))
        almg = hp.read_alm(fn_almg)
        fn_almng = ('data/fnl_sims/alm_nl_%04d_v3.fits' % (nsim,))
        almng = hp.read_alm(fn_almng)
        alm = almg + fnl * almng
        alm_masked = alm

    cltt_masked = hp.anafast(map_masked)
    cltt_masked = cltt_masked[:nl]
    cltt_corrected = np.dot(mll_inv, cltt_masked)

    # stuff with alpha, beta, r, dr, and beam

    l, r, dr, alpha, beta = np.loadtxt(h._fn_alphabeta, 
                                usecols=(0,1,2,3,4), unpack=True, skiprows=3)

    l = np.unique(l)
    r = np.unique(r)[::-1]

    nr = len(r)

    if (run_type == 'data' or run_type == 'sim'):
        cltt_denom = np.load('output/cltt_theory.npy') #replace with 'output/na_cltt.npy'
        cltt_denom = cltt_denom[:nl]
    elif (run_type == 'fnl'):
        cltt_denom = np.loadtxt('joe/cl_wmap5_bao_sn.dat', usecols=(1,), unpack=True)

    alpha = alpha.reshape(len(l), nr)
    beta = beta.reshape(len(l), nr)
    dr = dr.reshape(len(l), nr)
    dr = dr[0]
    
    if (run_type != 'fnl'):
        beam = np.load(h._fn_beam)
    else:
        #beam = np.ones(len(cltt_denom))
        beam = np.load(h._fn_beam)
        noise = np.zeros(len(cltt_denom))
        nlm = hp.synalm(noise, lmax=nl)

    ####### TEMPORARY -- change beam #######
    #beam = np.ones(len(cltt_denom))
    #noise = np.zeros(len(cltt_denom))
    #nlm = hp.synalm(noise, lmax=nl)
    ########################################

    l = l[:nl]
    beam = beam[:nl]
    alpha = alpha[:nl,:]
    beta = beta[:nl,:]

    if (i_rank == 0):
        print "nr: %i, nl: %i" % (nr, nl)

    f_t2 = time.time()

    if (i_rank == 0):
        print ""
        print "Time to create alms from maps: %.2f s" % (f_t2 - f_t1)
        print "Calculating full skewness power spectrum..."

    cl21 = np.zeros(nl)
    work = np.zeros(1, dtype='i')
    result = np.zeros(nl, dtype='d')

    # master loop
    if (i_rank == 0):

        # send initial jobs

        for i_rank_out in range(1,i_size):

            work = np.array([i_rank_out-1], dtype='i')
            o_comm.Send([work, MPI.INT], dest=i_rank_out, tag=i_work_tag)

        for i_r in range(i_size-1,nr):

            if (i_r % (nr / 10) == 0):
                print "Finished %i%% of jobs... (%.2f s)" % (i_r * 100 / nr,
                time.time() - f_t2)

            work = np.array([i_r], dtype='i')

            o_comm.Recv([result, MPI.DOUBLE], source=MPI.ANY_SOURCE, 
                status=o_status, tag=MPI.ANY_TAG)

            #print "received results from core %i" % o_status.Get_source()

            o_comm.Send([work,MPI.INT], dest=o_status.Get_source(), 
                tag=i_work_tag)

            cl21 += result

        for i_rank_out in range(1,i_size):

            o_comm.Recv([result, MPI.DOUBLE], source=MPI.ANY_SOURCE,
                status=o_status, tag=MPI.ANY_TAG)

            cl21 += result
            print "cl21 = %.6f, result = %.6f" % (np.average(cl21), np.average(result))

            o_comm.Send([np.array([9999], dtype='i'), MPI.INT], 
                dest=o_status.Get_source(), tag=i_die_tag)

    #slave loop:
    else:

        while(1):

            o_comm.Recv([work, MPI.INT], source=0, status=o_status, 
                tag=MPI.ANY_TAG)

            if (o_status.Get_tag() == i_die_tag):

                break

            i_r = work[0]
            #print ("i_r: %i" % i_r)
            #print ("alm_masked: ", alm_masked)
            #print ("cltt_denom: ", cltt_denom)
            #print ("beam: ", beam)
            #print ("mask: ", mask)
            #print ("fn_map: ", fn_map)

            # create Alm, Blm (almxfl with alm_masked and beta / cltt_denom 
            # * beam, etc.)

            Alm = np.zeros(alm_masked.shape[0],complex)
            Blm = np.zeros(alm_masked.shape[0],complex)
            clAB2 = np.zeros(nl+1)
            clABB = np.zeros(nl+1)

            #Alm = hp.almxfl(alm_masked, alpha[:,i_r] / cltt_denom * beam)
            #Blm = hp.almxfl(alm_masked, beta[:,i_r] / cltt_denom * beam)
            #for li in xrange(2,nl):
            #    I = hp.Alm.getidx(nl,li,np.arange(min(nl,li)+1))
            #    Alm[I]=alpha[li-2][i_r]*(alm_masked[I]*beam[li]+nlm[I])/(cltt_denom[li]*beam[li]**2+noise[li])
            #    Blm[I]=beta[li-2][i_r]*(alm_masked[I]*beam[li]+nlm[I])/(cltt_denom[li]*beam[li]**2+noise[li])
            if (run_type == 'fnl'):
                for li in xrange(2,nl):
                    I = hp.Alm.getidx(nl,li,np.arange(min(nl,li)+1))
                    Alm[I]=alpha[li-2][i_r]*(alm_masked[I]*beam[li]+nlm[I])/(cltt_denom[li]*beam[li]**2+noise[li])
                    Blm[I]=beta[li-2][i_r]*(alm_masked[I]*beam[li]+nlm[I])/(cltt_denom[li]*beam[li]**2+noise[li])
            else:
                for li in xrange(2,nl):
                    I = hp.Alm.getidx(nl,li,np.arange(min(nl,li)+1))
                    Alm[I]=alpha[li-2][i_r]*(alm_masked[I])/cltt_denom[li]*beam[li]
                    Blm[I]=beta[li-2][i_r]*(alm_masked[I])/cltt_denom[li]*beam[li]

            ############################# DEBUG ################################
            if i_r == 0:
                cltt_Alm = hp.alm2cl(Alm)
                cltt_Blm = hp.alm2cl(Blm)
                np.savetxt('debug2/cltt_%s_Alm.dat' % run_type, cltt_Alm)
                np.savetxt('debug2/cltt_%s_Blm.dat' % run_type, cltt_Blm)
            ####################################################################

            #An = hp.alm2map(Alm, nside=nside, fwhm=0.00145444104333,
            #    verbose=False)
            #Bn = hp.alm2map(Blm, nside=nside, fwhm=0.00145444104333,
            #    verbose=False)
            An = hp.alm2map(Alm, nside=nside)
            Bn = hp.alm2map(Blm, nside=nside)

            ############################# DEBUG ################################
            if i_r == 0:
                cltt_An = hp.anafast(An)
                cltt_Bn = hp.anafast(Bn)
                np.savetxt('debug2/cltt_%s_An.dat' % run_type, cltt_An)
                np.savetxt('debug2/cltt_%s_Bn.dat' % run_type, cltt_Bn)
            ####################################################################

            An = An * mask
            Bn = Bn * mask

            ############################# DEBUG ################################
            #if i_r == 0:
            #    print "saving alpha, beta for %i" % i_r
            #    np.savetxt('debug2/alpha_ir_%i' % i_r, alpha[:,i_r])
            #    np.savetxt('debug2/beta_ir_%i' % i_r, beta[:,i_r])
            #    print "(An * Bn)[:10] == An[:10] * Bn[:10]:", (An * Bn)[:10] == An[:10] * Bn[:10]
            
            ####################################################################

            B2lm = hp.map2alm(Bn*Bn, lmax=nl)
            ABlm = hp.map2alm(An*Bn, lmax=nl)

            ############################# DEBUG ################################
            if i_r == 0:
                cltt_B2lm = hp.alm2cl(B2lm)
                cltt_ABlm = hp.alm2cl(ABlm)
                np.savetxt('debug2/cltt_%s_B2lm.dat' % run_type, cltt_B2lm)
                np.savetxt('debug2/cltt_%s_ABlm.dat' % run_type, cltt_ABlm)
            ####################################################################

            #clAB2 = hp.alm2cl(Alm, B2lm, lmax=nl)
            #clABB = hp.alm2cl(ABlm, Blm, lmax=nl)
            for li in xrange(2,nl+1):
                I = hp.Alm.getidx(nl,li,np.arange(min(nl,li)+1))
                clAB2[li] = (Alm[I[0]]*B2lm[I[0]].conj()
                        +2.*sum(Alm[I[1:]]*B2lm[I[1:]].conj()))/(2.0*li+1.0)
                clABB[li] = (Blm[I[0]]*ABlm[I[0]].conj()
                        +2.*sum(Blm[I[1:]]*ABlm[I[1:]].conj()))/(2.0*li+1.0)


            ############################# DEBUG ################################
            if i_r == 0:
                np.savetxt('debug2/clAB2_%s.dat' % run_type, clAB2)
                np.savetxt('debug2/clABB_%s.dat' % run_type, clABB)
            ####################################################################

            clAB2 = clAB2[1:]
            clABB = clABB[1:]

            result = np.zeros(nl, dtype='d')
            result += (clAB2 + 2 * clABB) * r[i_r]**2. * dr[i_r]

            ############################# DEBUG ################################
            np.savetxt('debug2/cl21_%s.dat' % run_type, result)
            ####################################################################

            print ("finished work for r=%i, dr=%.2f, avg(alpha)=%.2f, avg(beta)=%.2f, avg(result)=%.4g" % 
                (int(r[i_r]), dr[i_r], np.average(alpha[:,i_r]), 
                    np.average(beta[:,i_r]), np.average(result)))

            ############################# DEBUG ################################
            #if i_r == 0:
            #    print "finished debug -- goodbye!"
            #    exit()
            ####################################################################
            
            o_comm.Send([result,MPI.DOUBLE], dest=0, tag=1)

    f_t8 = time.time()

    if (i_rank == 0):
        print ""
        print ("Saving power spectrum to %s (not mll corrected)" 
            % fn_cl21_no_mll)

        np.savetxt(fn_cl21_no_mll, cl21)

        print ""
        print "Saving power spectrum to %s (mll corrected)" % fn_cl21
        
        cl21 = np.dot(mll_inv, cl21)
        np.savetxt(fn_cl21, cl21)

    return
'''
desredmapper_clusters_sptpol_field_file = 'data/sanjay_maps_201705xx/final_maps/20170605_downsample_x2_TP/map_150.pkl.gz_cutouts_150ghz_no_downsamplingredmapper_clusters'
dic = pickle.load(gzip.open(desredmapper_clusters_sptpol_field_file, 'rb'))['cutouts']
cat = np.asarray(dic.keys())
ra, dec, z = cat[:,0], cat[:,1], cat[:,2]
cutout_dic_name = 'data/planck/redmapper_DES_sptpol_field.pkl.gz'
'''

desredmapper_clusters_file = 'data/redmapper/y1a1_gold_1.0.3-d10-mof-001b_run_redmapper_v6.4.16_lgt20_desformat_catalog_extracted.txt'
ra, dec, z = np.loadtxt(desredmapper_clusters_file, usecols = [2,3,6], unpack = True)
cutout_dic_name = 'data/planck/redmapper_DES_full_field.pkl.gz'
#sys.exit()

if not smica:
	print("...loading PlanckLens alms...")
	kappa_lm = hp.read_alm(planck_alms)
	print("...done...")

	print("...converting PlanckLens alms to map...")
	kappa = hp.alm2map(kappa_lm, nside)
	print("...done...")

else:
	print("...reading SMICA map now: %s..." %(smica_map_file))
	kappa = hp.read_map(smica_map_file, field=0, verbose=0) #not kappa but SMICA: just T now.
	print("...done...")

print("...loading PlanckLens mask...")
mask = hp.read_map(planck_mask, verbose=0)
print("...done...")
コード例 #40
0
b = b.reshape(1499, nR)
dR = dR.reshape(1499, nR)
dR = dR[0]

###################################

# Put alpha and beta in a format condusive for r dependance
# a = a.reshape(500,1999)
# b = b.reshape(500,1999)
# R = R.reshape(500,1999)

# Initialize arrays
N = 0

# Read In alms and cls
alm = hp.read_alm("Maps/alm_l_" + str(N) + ".fits")
flm = hp.read_alm("Maps/alm_nl_" + str(N) + ".fits")
Alm = zeros(alm.shape[0], complex)
Blm = zeros(alm.shape[0], complex)
CAB2l = zeros((a.shape[0], LMAX + 1))
CABBl = zeros((a.shape[0], LMAX + 1))
clab2 = zeros(CAB2l.shape[1])
clabb = zeros(CAB2l.shape[1])

############## DEBUG ##############
alm_data = alm + fnl * flm
Alm_jon = zeros(alm_data.shape[0], complex)
Blm_jon = zeros(alm_data.shape[0], complex)
clAB2_jon = zeros(nl + 1)
clABB_jon = zeros(nl + 1)
###################################
コード例 #41
0
a = a.reshape(500,1999)
b = b.reshape(500,1999)
R = R.reshape(500,1999)

# Initialize arrays
   
#for N in arange(int(sys.argv[1]),500,int(sys.argv[2])):
for N in xrange(0,10):
    print '#########################################################'
    print ""
    print N
    print ""
    print '#########################################################'
    
    #Read In alms and cls
    alm = hp.read_alm('Maps/alm_l_'+str(N)+'.fits')
    flm = hp.read_alm('Maps/alm_nl_'+str(N)+'.fits')
    Alm = zeros(hp.Alm.getsize(LMAX),complex)
    #Alm = zeros(alm.shape[0],complex)
    Blm = zeros(hp.Alm.getsize(LMAX),complex)
    #Blm = zeros(alm.shape[0],complex)
    CAB2l = zeros((a.shape[0],LMAX+1))
    CABBl = zeros((a.shape[0],LMAX+1))
    clab2 = zeros(CAB2l.shape[1])
    clabb = zeros(CAB2l.shape[1])
   
    for r in xrange(a.shape[0]):
        print r
        for l in xrange(2,LMAX):
            I = hp.Alm.getidx(LMAX,l,arange(min(LMAX,l)+1))
            Alm[I]=a[r][l-2]*(alm[I]+fnl*flm[I])/cl[l]