예제 #1
0
    def testTimeTransfers(self):
        from camb import initialpower
        pars = camb.set_params(H0=69, YHe=0.22, lmax=2000, lens_potential_accuracy=1, ns=0.96, As=2.5e-9)
        results1 = camb.get_results(pars)
        cl1 = results1.get_total_cls()

        pars = camb.set_params(H0=69, YHe=0.22, lmax=2000, lens_potential_accuracy=1)
        results = camb.get_transfer_functions(pars, only_time_sources=True)
        inflation_params = initialpower.InitialPowerLaw()
        inflation_params.set_params(ns=0.96, As=2.5e-9)
        results.power_spectra_from_transfer(inflation_params)
        cl2 = results.get_total_cls()
        np.testing.assert_allclose(cl1, cl2, rtol=1e-4)
        inflation_params.set_params(ns=0.96, As=1.9e-9)
        results.power_spectra_from_transfer(inflation_params)
        inflation_params.set_params(ns=0.96, As=2.5e-9)
        results.power_spectra_from_transfer(inflation_params)
        cl2 = results.get_total_cls()
        np.testing.assert_allclose(cl1, cl2, rtol=1e-4)

        pars = camb.CAMBparams()
        pars.set_cosmology(H0=78, YHe=0.22)
        pars.set_for_lmax(2000, lens_potential_accuracy=1)
        pars.WantTensors = True
        results = camb.get_transfer_functions(pars, only_time_sources=True)
        cls = []
        for r in [0, 0.2, 0.4]:
            inflation_params = initialpower.InitialPowerLaw()
            inflation_params.set_params(ns=0.96, r=r, nt=0)
            results.power_spectra_from_transfer(inflation_params)
            cls += [results.get_total_cls(CMB_unit='muK')]
        self.assertTrue(np.allclose((cls[1] - cls[0])[2:300, 2] * 2, (cls[2] - cls[0])[2:300, 2], rtol=1e-3))
예제 #2
0
    def lnt(self, lnk):
        """
        Natural log of the transfer function

        Parameters
        ----------
        lnk : array_like
            Wavenumbers [Mpc/h]

        Returns
        -------
        lnt : array_like
            The log of the transfer function at lnk.
        """

        camb_transfers = camb.get_transfer_functions(
            self.params['camb_params'])
        T = camb_transfers.get_matter_transfer_data().transfer_data
        T = np.log(T[[0, 6], :, 0])

        if lnk[0] < T[0, 0]:
            lnkout, lnT = self._check_low_k(T[0, :], T[1, :], lnk[0])
        else:
            lnkout = T[0, :]
            lnT = T[1, :]

        return spline(lnkout, lnT, k=1)(lnk)
예제 #3
0
    def compute_transfer(self, accuracy_level=3, lSampleBoost=50):
        """
        Function to compute the transfer functions from the Boltzmann code

        Args:
            accuracy_level (int): The overall accuracy level for computing the transfer functions, as used by
                the CAMB code. Anything in the range 3-5 should provide sufficient accuracy for the bispectrum.
            lSampleBoost (int): Parameter that determines how many transfer functions to compute. By setting this
                to 50, we force CAMB to compute all the transfer functions up to ell=2500
        """

        print('--- Computing transfer functions ---', flush=True)

        # Ensure that CAMB is imported
        import camb

        # Set the CAMB accuracy parameters to the ones given
        self.params.set_accuracy(AccuracyBoost=accuracy_level,
                                 lSampleBoost=lSampleBoost)

        # Compute the transfer functions, and then save them in the class
        self.transfer = camb.get_transfer_functions(
            self.params).get_cmb_transfer_data()

        print('--- Computed transfer functions ---', flush=True)
예제 #4
0
    def __init__(self,omega_m,sigma_8,h,z):
        self.omega_m = omega_m
        self.sigma_8 = sigma_8
        self.h = h
        self.z = z
        self.k_max = 10.0
        self.c = 2.99792e+5
        #=========================
        
        cosmo = camb.CAMBparams()
        cosmo.set_cosmology(H0=100.0*self.h, ombh2=0.048*(self.h**2.0), omch2=(self.omega_m - 0.048)*(self.h**2.0), mnu=0.06, omk=0, tau=0.06)
        cosmo.InitPower.set_params(As=2.0e-9, ns=0.973)
        results = camb.get_results(cosmo)
        cosmo.set_matter_power(redshifts=[0.0], kmax=10.0)
        cambres= camb.get_transfer_functions(cosmo)
        cosmo.NonLinear = model.NonLinear_both
        kh, z, pk = cambres.get_matter_power_spectrum(minkh=1e-3, maxkh=1.0, npoints = 10)
        sigma_8_temp = cambres.get_sigma8()
        As_new  = ((self.sigma_8/sigma_8_temp)**2.0)*(2.0e-9)
        cosmo.InitPower.set_params(As=As_new, ns=0.973)
        cambres = camb.get_results(cosmo)
        backres = camb.get_background(cosmo)

        self.chi = backres.comoving_radial_distance(self.z)
           
        self.PK = camb.get_matter_power_interpolator(cosmo, nonlinear=True, 
                hubble_units=False, k_hunit=False, kmax=self.k_max, zmin = 0.0, zmax=self.z[-1]) 
        
        self.H_z = (backres.hubble_parameter(self.z))/self.c #Hubble parameter in 1/Mpc 
예제 #5
0
파일: camb_test.py 프로젝트: beringueb/PhD
    def testEvolution(self):
        redshifts = [0.4, 31.5]
        pars = camb.set_params(H0=67.5,
                               ombh2=0.022,
                               omch2=0.122,
                               As=2e-9,
                               ns=0.95,
                               redshifts=redshifts,
                               kmax=0.1)
        pars.WantCls = False

        # check transfer function routines and evolution code agree
        # Note transfer function redshifts are re-sorted in outputs
        data = camb.get_transfer_functions(pars)
        mtrans = data.get_matter_transfer_data()
        transfer_k = mtrans.transfer_z('delta_cdm', z_index=1)
        transfer_k2 = mtrans.transfer_z('delta_baryon', z_index=0)

        kh = mtrans.transfer_z('k/h', z_index=1)
        ev = data.get_redshift_evolution(
            mtrans.q,
            redshifts, ['delta_baryon', 'delta_cdm', 'delta_photon'],
            lAccuracyBoost=1)
        self.assertTrue(
            np.all(
                np.abs(transfer_k * kh**2 *
                       (pars.H0 / 100)**2 / ev[:, 0, 1] - 1) < 1e-3))
        ix = 1
        self.assertAlmostEqual(
            transfer_k2[ix] * kh[ix]**2 * (pars.H0 / 100)**2, ev[ix, 1, 0], 4)
예제 #6
0
def test_setting_kmax():
    t = Transfer(
        transfer_params={
            "extrapolate_with_eh": True,
            "kmax": 1.0
        },
        transfer_model="CAMB",
    )
    assert t.transfer.params["camb_params"].Transfer.kmax == 1.0
    camb_transfers = camb.get_transfer_functions(
        t.transfer.params["camb_params"])
    T = camb_transfers.get_matter_transfer_data().transfer_data
    assert np.max(T[0]) < 2.0
예제 #7
0
        def lnt(self, lnk):
            r"""
            Natural log of the transfer function

            Parameters
            ----------
            lnk : array_like
                Wavenumbers [Mpc/h]

            Returns
            -------
            lnt : array_like
                The log of the transfer function at lnk.
            """

            camb_transfers = camb.get_transfer_functions(
                self.params["camb_params"])
            T = camb_transfers.get_matter_transfer_data().transfer_data
            T = np.log(T[[0, 6], :, 0])

            if lnk[0] < T[0, 0]:
                lnkout, lnT = self._check_low_k(T[0, :], T[1, :], lnk[0])
            else:
                lnkout = T[0, :]
                lnT = T[1, :]

            lnT -= lnT[0]

            if self.params["extrapolate_with_eh"]:
                # Now add a point one e-fold above the max, with an EH-generated transfer
                lnkout = np.concatenate((lnkout, [lnkout[-1] + 1]))
                # normalise EH at the final CAMB point.
                norm = self._eh.lnt(lnkout[-2]) - lnT[-1]
                lnT = np.concatenate((lnT, [self._eh.lnt(lnkout[-1]) - norm]))

                lnkmin = lnkout.min()
                lnkmax = lnkout.max()

                inner_spline = spline(lnkout, lnT, k=3)

                out = np.zeros_like(lnk)
                out[lnk < lnkmin] = 0
                out[(lnkmin <= lnk) & (lnk <= lnkmax)] = inner_spline(
                    lnk[(lnkmin <= lnk) & (lnk <= lnkmax)])
                out[lnk >= lnkmax] = self._eh.lnt(lnk[lnk >= lnkmax]) - norm

                return out
            else:
                return spline(lnkout, lnT, k=1)(lnk)
예제 #8
0
파일: camb_test.py 프로젝트: cmbant/CAMB
    def testEvolution(self):
        redshifts = [0.4, 31.5]
        pars = camb.set_params(H0=67.5, ombh2=0.022, omch2=0.122, As=2e-9, ns=0.95,
                               redshifts=redshifts, kmax=0.1)
        pars.WantCls = False

        # check transfer function routines and evolution code agree
        # Note transfer function redshifts are re-sorted in outputs
        data = camb.get_transfer_functions(pars)
        mtrans = data.get_matter_transfer_data()
        transfer_k = mtrans.transfer_z('delta_cdm', z_index=1)
        transfer_k2 = mtrans.transfer_z('delta_baryon', z_index=0)

        kh = mtrans.transfer_z('k/h', z_index=1)
        ev = data.get_redshift_evolution(mtrans.q, redshifts, ['delta_baryon', 'delta_cdm', 'delta_photon'],
                                         lAccuracyBoost=1)
        self.assertTrue(np.all(np.abs(transfer_k * kh ** 2 * (pars.H0 / 100) ** 2 / ev[:, 0, 1] - 1) < 1e-3))
        ix = 1
        self.assertAlmostEqual(transfer_k2[ix] * kh[ix] ** 2 * (pars.H0 / 100) ** 2, ev[ix, 1, 0], 4)
예제 #9
0
    def init_camb_transfer(self, SAVE=True):
        """
        """

        if not(self.camb_transfer_init):
            """
            get the transfer data if it is the first time or if the specified
            accuracy aboost is greater than the one that is saved
            """
            if not(self.camb_init):
                self.init_camb()

            self.cambdata = camb.get_transfer_functions(self.cambparams)
            self.cambtransfer = self.cambdata.get_cmb_transfer_data()
            self.camb_transfer_init = True
            # save the current transfer data
            if (SAVE):
                fname = "glk_"+self.name+"_"+str(self.camb_aboost)+"_"+str(self.camblmax)+".npy"
                np.save(fname, np.array([self.cambtransfer.q, self.cambtransfer.delta_p_l_k]))
            self.klist = self.cambtransfer.q[0:-15]
            self.glk = self.cambtransfer.delta_p_l_k[:,:,0:-15]
        def __init__(self, *args, **kwargs):
            super(CambGrowth, self).__init__(*args, **kwargs)

            # Save the CAMB object properly for use
            # Set the cosmology
            self.p = camb.CAMBparams()

            if self.cosmo.Ob0 is None:
                raise ValueError(
                    "If using CAMB, the baryon density must be set explicitly in the cosmology."
                )

            if self.cosmo.Tcmb0.value == 0:
                raise ValueError(
                    "If using CAMB, the CMB temperature must be set explicitly in the cosmology."
                )

            self.p.set_cosmology(
                H0=self.cosmo.H0.value,
                ombh2=self.cosmo.Ob0 * self.cosmo.h**2,
                omch2=(self.cosmo.Om0 - self.cosmo.Ob0) * self.cosmo.h**2,
                omk=self.cosmo.Ok0,
                nnu=self.cosmo.Neff,
                standard_neutrino_neff=self.cosmo.Neff,
                TCMB=self.cosmo.Tcmb0.value,
            )

            self.p.WantTransfer = True

            # Set the DE equation of state. We only support constant w.
            if hasattr(self.cosmo, "w0"):
                self.p.set_dark_energy(w=self.cosmo.w0)

            # Now find the z=0 transfer
            self._camb_transfers = camb.get_transfer_functions(self.p)
            self._t0 = self._camb_transfers.get_redshift_evolution(
                1.0, 0.0, ["delta_tot"])[0][0]
예제 #11
0
pars.set_cosmology(H0=100.*params['h_100'], ombh2 = params['om_b']*params['h_100']**2., omch2 = params['om_cm']*params['h_100']**2., mnu=0.00, omk=0.)

pars.set_matter_power(redshifts = [2.0], kmax=10.0) 

pars.NonLinear = model.NonLinear_none

linpk          = camb.get_results(pars)

sigma8         = linpk.get_sigma8()

k, z, linpk    = linpk.get_matter_power_spectrum(minkh=1e-4, npoints = 4000, maxkh=10.)
linpk          = linpk[0]


CAMBTK         = camb.get_transfer_functions(pars)

CAMBTK         = CAMBTK.get_matter_transfer_data()

CAMBTKk        = CAMBTK.transfer_data[0,:]
CAMBTK         = CAMBTK.transfer_data[6,:][:,0]
CAMBTK        /= CAMBTK[0]

'''
- Transfer_kh              = 1  (k / h).
- Transfer_cdm             = 2  (cdm).
- Transfer_b               = 3  (baryons).
- Transfer_g               = 4  (photons).
- Transfer_r               = 5  (massless neutrinos).
- Transfer_nu              = 6  (massive neutrinos).
- Transfer_tot             = 7  (total matter).
예제 #12
0
def run_camb(lmax,
             k_eta_fac=5,
             AccuracyBoost=3,
             lSampleBoost=2,
             lAccuracyBoost=2,
             verbose=True):
    '''
    Run camb to get transfer functions and power spectra.

    Arguments
    ---------
    lmax : int
        Max multipole used in calculation transfer functions.

    Keyword arguments
    -----------------
    k_eta_fac : scalar
        Determines k_eta_max for transfer functions through
        k_eta_max = k_eta_fac * lmax. (default : 5)
    AccuracyBoost : int
        Overall accuracy CAMB, pick 1 to 3. (default : 3)
    lSampleBoost : int
        Factor determining multipole sampling of transfer 
        functions, pick 1 to 50. (default : 2)
    lAccuracyBoost : int
        Factor determining truncation of Boltzmann hierarchy,
        pick 1 to 3 (default : 2)
    verbose : bool

    Returns
    -------
    transfer : dict
        Contains transfer functions, wavenumbers, multipoles.
        Transfer function have shape (numsources, lmax-1, k_size)
        numsources is 3 for lensed scalar (T, E, P) and 3 for
        tensor (T, E, B).
    cls : dict
        Contains power spectra and corresponding multipoles.
            cls : dict
                TT, EE, BB, TE spectra, shape: (4, lmax-1)
            ells : ndarray
    opts : dict
        Contains accuracy, cosmology and primordial
        options.
    '''

    transfer = {}
    cls = {}
    opts = {}

    # Accuracy options.
    acc_opts = dict(AccuracyBoost=AccuracyBoost,
                    lSampleBoost=lSampleBoost,
                    lAccuracyBoost=lAccuracyBoost,
                    DoLateRadTruncation=False)

    # Hardcoded LCDM+ parameters.
    cosmo_opts = dict(H0=67.66,
                      TCMB=2.7255,
                      YHe=0.24,
                      standard_neutrino_neff=True,
                      ombh2=0.02242,
                      omch2=0.11933,
                      tau=0.0561,
                      mnu=0.06,
                      omk=0)

    prim_opts = dict(ns=0.9665,
                     r=1.,
                     pivot_scalar=0.05,
                     As=2.1056e-9,
                     nt=0,
                     parameterization=2)

    pars = camb.CAMBparams()
    pars.set_cosmology(**cosmo_opts)
    pars.InitPower.set_params(**prim_opts)
    pars.set_accuracy(**acc_opts)

    pars.WantScalars = True
    pars.WantTensors = True

    # CAMB becomes unstable for too low ell and k.
    lmax = max(300, lmax)
    max_eta_k = k_eta_fac * lmax
    max_eta_k = max(max_eta_k, 1000)

    pars.max_l = lmax
    pars.max_l_tensor = lmax
    pars.max_eta_k = max_eta_k
    pars.max_eta_k_tensor = max_eta_k

    pars.AccurateBB = True
    pars.AccurateReionization = True
    pars.AccuratePolarization = True

    acc_opts['k_eta_fac'] = k_eta_fac
    opts['acc'] = acc_opts
    opts['cosmo'] = cosmo_opts
    opts['prim'] = prim_opts

    if pars.validate() is False:
        raise ValueError('Invalid CAMB input')

    if verbose:
        print('Calculating transfer functions\n')
        print('lmax: {} \nmax_eta_k : {} \nAccuracyBoost : {} \n'
              'lSampleBoost : {} \nlAccuracyBoost : {}\n'.format(
                  lmax, max_eta_k, AccuracyBoost, lSampleBoost,
                  lAccuracyBoost))

    data = camb.get_transfer_functions(pars)
    transfer_s = data.get_cmb_transfer_data('scalar')
    transfer_t = data.get_cmb_transfer_data('tensor')

    if verbose:
        print('Calculating power spectra')

    # NOTE that l=0, l=1 are also included here.
    data.calc_power_spectra()
    cls_camb = data.get_cmb_power_spectra(lmax=None,
                                          CMB_unit='muK',
                                          raw_cl=True)

    # CAMB cls are column-major, so convert.
    # NOTE this is wrong. You need to do transpose + ascontingousarray <- fixed
    for key in cls_camb:
        cls_cm = cls_camb[key]
        n_ell, n_pol = cls_cm.shape  # 2d tuple.
        #        cls_camb[key] = cls_cm.reshape(n_pol, n_ell)

        #        s0, s1 = cls.shape
        #        cls = cls.reshape(s1, s0)
        temp = np.ascontiguousarray(cls_cm.transpose())
        # Remove monopole and dipole.
        cls_camb[key] = temp[:, 2:]

    ells_cls = np.arange(2, n_ell)
    cls['ells'] = ells_cls
    cls['cls'] = cls_camb

    # We need to modify scalar E-mode and tensor I transfer functions,
    # see Zaldarriaga 1997 eq. 18 and 39. (CAMB applies these factors
    # at a later stage).
    try:
        ells = transfer_s.l
    except AttributeError:
        ells = transfer_s.L
    # CAMB ells are in int32, gives nan in sqrt, so convert first.
    ells = ells.astype(int)
    prefactor = np.sqrt((ells + 2) * (ells + 1) * ells * (ells - 1))

    transfer_s.delta_p_l_k[1, ...] *= prefactor[:, np.newaxis]
    transfer_t.delta_p_l_k[0, ...] *= prefactor[:, np.newaxis]

    # both scalar and tensor have to be scaled with monopole in uK
    transfer_s.delta_p_l_k *= (pars.TCMB * 1e6)
    transfer_t.delta_p_l_k *= (pars.TCMB * 1e6)

    # Scale tensor transfer by 1/4 to correct for CAMB output.
    transfer_t.delta_p_l_k /= 4.

    # Check for nans.
    if tools.has_nan(transfer_s.delta_p_l_k):
        raise ValueError('nan in scalar transfer')
    if tools.has_nan(transfer_t.delta_p_l_k):
        raise ValueError('nan in tensor transfer')
    if tools.has_nan(transfer_s.q):
        raise ValueError('nan in k array')

    transfer['scalar'] = transfer_s.delta_p_l_k
    transfer['tensor'] = transfer_t.delta_p_l_k
    transfer['k'] = transfer_s.q
    transfer['ells'] = ells  # sparse and might differ from cls['ells']

    print(transfer['k'].shape)
    print(transfer['tensor'].shape)

    return transfer, cls, opts
예제 #13
0
파일: infl.py 프로젝트: tdaylan/tdgu
ax[0,1].plot(ls[2:], 1-pseculen[2:,0]/psectotl[2:,0]);
ax[0,1].set_title(r'$\Delta TT$')
ax[1,0].plot(ls,psectotl[:,1], color='k')
ax[1,0].plot(ls,pseculen[:,1], color='r')
ax[1,0].set_title(r'$EE$')
ax[1,1].plot(ls,psectotl[:,3], color='k')
ax[1,1].plot(ls,pseculen[:,3], color='r')
ax[1,1].set_title(r'$TE$');
for ax in ax.reshape(-1):
    ax.set_xlim([2,2500])
plt.savefig(path + 'psec.pdf')
plt.close()


pars.WantTensors = True
cambdata = camb.get_transfer_functions(pars)
lmax=2000
rs = np.linspace(0,0.2,6)
for r in rs:
    inflation_params = initialpower.InitialPowerParams()
    inflation_params.set_params(ns=0.96, r=r)
    cambdata.power_spectra_from_transfer(inflation_params)
    cl = cambdata.get_total_cls(lmax)
    plt.loglog(np.arange(lmax+1),cl[:,2])
plt.xlim([2,lmax])
plt.legend(rs, loc='lower right');
plt.savefig(path + 'tens.pdf')
plt.close()

pars = camb.CAMBparams()
pars.set_cosmology(H0=67.5, ombh2=0.022, omch2=0.122)
# Camb initialization
camb_params = camb.CAMBparams()
camb_params.set_cosmology(
    H0=LCDM.H0, ombh2=LCDM.omega_b, omch2=LCDM.omega_cdm,
    omk=LCDM.omega_k, nnu=LCDM.Neff, TCMB=LCDM.Tcmb, tau=LCDM.tau_reio
)
camb_params.WantTransfer = True
camb_params.WantCls = True
camb_params.InitPower.set_params(ns=LCDM.n_s, As=LCDM.A_s)
camb_params.set_accuracy(
    AccuracyBoost=3.0, lAccuracyBoost=3.0, lSampleBoost=3.0,
    DoLateRadTruncation=False
)

camb_res = camb.get_results(camb_params)
camb_trans = camb.get_transfer_functions(camb_params)
camb_trans = camb_trans.get_matter_transfer_data().transfer_data[[0,6],:,0] # Returns [k, T_tot(k)]
print("Initialized CAMB")

# Class Initialization
class_params = {
    'h': LCDM.h,
    'omega_b': LCDM.omega_b,
    'omega_cdm': LCDM.omega_cdm,
    'Omega_k': LCDM.omega_k,
    'N_ur': LCDM.Neff,
    'A_s': LCDM.A_s,
    'n_s': LCDM.n_s,
    'T_cmb': LCDM.Tcmb,
    'tau_reio': LCDM.tau_reio,
    'P_k_max_1/Mpc': 100,
예제 #15
0
    def testPowers(self):
        pars = camb.CAMBparams()
        pars.set_cosmology(H0=67.5, ombh2=0.022, omch2=0.122, mnu=0.07, omk=0)
        pars.set_dark_energy()  # re-set defaults
        pars.InitPower.set_params(ns=0.965, As=2e-9)
        pars.NonLinearModel.set_params(halofit_version='takahashi')

        self.assertAlmostEqual(pars.scalar_power(1), 1.801e-9, 4)
        self.assertAlmostEqual(pars.scalar_power([1, 1.5])[0], 1.801e-9, 4)

        pars.set_matter_power(nonlinear=True)
        self.assertEqual(pars.NonLinear, model.NonLinear_pk)
        pars.set_matter_power(redshifts=[0., 0.17, 3.1], silent=True, nonlinear=False)
        data = camb.get_results(pars)

        kh, z, pk = data.get_matter_power_spectrum(1e-4, 1, 20)

        kh2, z2, pk2 = data.get_linear_matter_power_spectrum()

        s8 = data.get_sigma8()
        self.assertAlmostEqual(s8[0], 0.24686, 3)
        self.assertAlmostEqual(s8[2], 0.80044, 3)
        fs8 = data.get_fsigma8()
        self.assertAlmostEqual(fs8[0], 0.2431, 3)
        self.assertAlmostEqual(fs8[2], 0.424712, 3)

        pars.NonLinear = model.NonLinear_both

        data.calc_power_spectra(pars)
        kh3, z3, pk3 = data.get_matter_power_spectrum(1e-4, 1, 20)
        self.assertAlmostEqual(pk[-1][-3], 51.909, 2)
        self.assertAlmostEqual(pk3[-1][-3], 57.709, 2)
        self.assertAlmostEqual(pk2[-2][-4], 56.436, 2)
        camb.set_feedback_level(0)

        PKnonlin = camb.get_matter_power_interpolator(pars, nonlinear=True)
        pars.set_matter_power(redshifts=[0, 0.09, 0.15, 0.42, 0.76, 1.5, 2.3, 5.5, 8.9],
                              silent=True, kmax=10, k_per_logint=5)
        pars.NonLinear = model.NonLinear_both
        results = camb.get_results(pars)
        kh, z, pk = results.get_nonlinear_matter_power_spectrum()
        pk_interp = PKnonlin.P(z, kh)
        self.assertTrue(np.sum((pk / pk_interp - 1) ** 2) < 0.005)
        PKnonlin2 = results.get_matter_power_interpolator(nonlinear=True, extrap_kmax=500)
        pk_interp2 = PKnonlin2.P(z, kh)
        self.assertTrue(np.sum((pk_interp / pk_interp2 - 1) ** 2) < 0.005)

        pars.NonLinearModel.set_params(halofit_version='mead')
        _, _, pk = results.get_nonlinear_matter_power_spectrum(params=pars, var1='delta_cdm', var2='delta_cdm')
        self.assertAlmostEqual(pk[0][160], 824.6, delta=0.5)

        lmax = 4000
        pars.set_for_lmax(lmax)
        cls = data.get_cmb_power_spectra(pars)
        data.get_total_cls(2000)
        data.get_unlensed_scalar_cls(2500)
        data.get_tensor_cls(2000)
        cls_lensed = data.get_lensed_scalar_cls(3000)
        cphi = data.get_lens_potential_cls(2000)

        # check lensed CL against python; will only agree well for high lmax as python has no extrapolation template
        cls_lensed2 = correlations.lensed_cls(cls['unlensed_scalar'], cls['lens_potential'][:, 0], delta_cls=False)
        np.testing.assert_allclose(cls_lensed2[2:2000, 2], cls_lensed[2:2000, 2], rtol=1e-3)
        np.testing.assert_allclose(cls_lensed2[2:2000, 1], cls_lensed[2:2000, 1], rtol=1e-3)
        np.testing.assert_allclose(cls_lensed2[2:2000, 0], cls_lensed[2:2000, 0], rtol=1e-3)
        self.assertTrue(np.all(np.abs((cls_lensed2[2:3000, 3] - cls_lensed[2:3000, 3]) /
                                      np.sqrt(cls_lensed2[2:3000, 0] * cls_lensed2[2:3000, 1])) < 1e-4))

        corr, xvals, weights = correlations.gauss_legendre_correlation(cls['lensed_scalar'])
        clout = correlations.corr2cl(corr, xvals, weights, 2500)
        self.assertTrue(np.all(np.abs(clout[2:2300, 2] / cls['lensed_scalar'][2:2300, 2] - 1) < 1e-3))

        pars = camb.CAMBparams()
        pars.set_cosmology(H0=78, YHe=0.22)
        pars.set_for_lmax(2000, lens_potential_accuracy=1)
        pars.WantTensors = True
        results = camb.get_transfer_functions(pars)
        from camb import initialpower
        cls = []
        for r in [0, 0.2, 0.4]:
            inflation_params = initialpower.InitialPowerLaw()
            inflation_params.set_params(ns=0.96, r=r, nt=0)
            results.power_spectra_from_transfer(inflation_params, silent=True)
            cls += [results.get_total_cls(CMB_unit='muK')]
        self.assertTrue(np.allclose((cls[1] - cls[0])[2:300, 2] * 2, (cls[2] - cls[0])[2:300, 2], rtol=1e-3))

        # Check generating tensors and scalars together
        pars = camb.CAMBparams()
        pars.set_cosmology(H0=67)
        lmax = 2000
        pars.set_for_lmax(lmax, lens_potential_accuracy=1)
        pars.InitPower.set_params(ns=0.96, r=0)
        pars.WantTensors = False
        results = camb.get_results(pars)
        cl1 = results.get_total_cls(lmax, CMB_unit='muK')
        pars.InitPower.set_params(ns=0.96, r=0.1, nt=0)
        pars.WantTensors = True
        results = camb.get_results(pars)
        cl2 = results.get_lensed_scalar_cls(lmax, CMB_unit='muK')
        ctensor2 = results.get_tensor_cls(lmax, CMB_unit='muK')
        results = camb.get_transfer_functions(pars)
        results.Params.InitPower.set_params(ns=1.1, r=1)
        inflation_params = initialpower.InitialPowerLaw()
        inflation_params.set_params(ns=0.96, r=0.05, nt=0)
        results.power_spectra_from_transfer(inflation_params, silent=True)
        cl3 = results.get_lensed_scalar_cls(lmax, CMB_unit='muK')
        ctensor3 = results.get_tensor_cls(lmax, CMB_unit='muK')
        self.assertTrue(np.allclose(ctensor2, ctensor3 * 2, rtol=1e-4))
        self.assertTrue(np.allclose(cl1, cl2, rtol=1e-4))
        # These are identical because all scalar spectra were identical (non-linear corrections change it  otherwise)
        self.assertTrue(np.allclose(cl1, cl3, rtol=1e-4))

        pars = camb.CAMBparams()
        pars.set_cosmology(H0=67.5, ombh2=0.022, omch2=0.122, mnu=0.07, omk=0)
        pars.set_for_lmax(2500)
        pars.min_l = 2
        res = camb.get_results(pars)
        cls = res.get_lensed_scalar_cls(2000)
        pars.min_l = 1
        res = camb.get_results(pars)
        cls2 = res.get_lensed_scalar_cls(2000)
        np.testing.assert_allclose(cls[2:, 0:2], cls2[2:, 0:2], rtol=1e-4)
        self.assertAlmostEqual(cls2[1, 0], 1.30388e-10, places=13)
        self.assertAlmostEqual(cls[1, 0], 0)
예제 #16
0
파일: camb_test.py 프로젝트: cmbant/CAMB
    def testPowers(self):
        pars = camb.CAMBparams()
        pars.set_cosmology(H0=67.5, ombh2=0.022, omch2=0.122, mnu=0.07, omk=0)
        pars.set_dark_energy()  # re-set defaults
        pars.InitPower.set_params(ns=0.965, As=2e-9)
        pars.NonLinearModel.set_params(halofit_version='takahashi')

        self.assertAlmostEqual(pars.scalar_power(1), 1.801e-9, 4)
        self.assertAlmostEqual(pars.scalar_power([1, 1.5])[0], 1.801e-9, 4)

        pars.set_matter_power(nonlinear=True)
        self.assertEqual(pars.NonLinear, model.NonLinear_pk)
        pars.set_matter_power(redshifts=[0., 0.17, 3.1], silent=True, nonlinear=False)
        data = camb.get_results(pars)

        kh, z, pk = data.get_matter_power_spectrum(1e-4, 1, 20)

        kh2, z2, pk2 = data.get_linear_matter_power_spectrum()

        s8 = data.get_sigma8()
        self.assertAlmostEqual(s8[0], 0.24686, 3)
        self.assertAlmostEqual(s8[2], 0.80044, 3)

        pars.NonLinear = model.NonLinear_both

        data.calc_power_spectra(pars)
        kh3, z3, pk3 = data.get_matter_power_spectrum(1e-4, 1, 20)
        self.assertAlmostEqual(pk[-1][-3], 51.909, 2)
        self.assertAlmostEqual(pk3[-1][-3], 57.709, 2)
        self.assertAlmostEqual(pk2[-2][-4], 56.436, 2)
        camb.set_feedback_level(0)

        PKnonlin = camb.get_matter_power_interpolator(pars, nonlinear=True)
        pars.set_matter_power(redshifts=[0, 0.09, 0.15, 0.42, 0.76, 1.5, 2.3, 5.5, 8.9],
                              silent=True, kmax=10, k_per_logint=5)
        pars.NonLinear = model.NonLinear_both
        results = camb.get_results(pars)
        kh, z, pk = results.get_nonlinear_matter_power_spectrum()
        pk_interp = PKnonlin.P(z, kh)
        self.assertTrue(np.sum((pk / pk_interp - 1) ** 2) < 0.005)
        PKnonlin2 = results.get_matter_power_interpolator(nonlinear=True, extrap_kmax=500)
        pk_interp2 = PKnonlin2.P(z, kh)
        self.assertTrue(np.sum((pk_interp / pk_interp2 - 1) ** 2) < 0.005)

        pars.NonLinearModel.set_params(halofit_version='mead')
        _, _, pk = results.get_nonlinear_matter_power_spectrum(params=pars, var1='delta_cdm', var2='delta_cdm')
        self.assertAlmostEqual(pk[0][160], 824.6, delta=0.5)

        lmax = 4000
        pars.set_for_lmax(lmax)
        cls = data.get_cmb_power_spectra(pars)
        data.get_total_cls(2000)
        data.get_unlensed_scalar_cls(2500)
        data.get_tensor_cls(2000)
        cls_lensed = data.get_lensed_scalar_cls(3000)
        cphi = data.get_lens_potential_cls(2000)

        # check lensed CL against python; will only agree well for high lmax as python has no extrapolation template
        cls_lensed2 = correlations.lensed_cls(cls['unlensed_scalar'], cls['lens_potential'][:, 0], delta_cls=False)
        np.testing.assert_allclose(cls_lensed2[2:2000, 2], cls_lensed[2:2000, 2], rtol=1e-3)
        np.testing.assert_allclose(cls_lensed2[2:2000, 1], cls_lensed[2:2000, 1], rtol=1e-3)
        np.testing.assert_allclose(cls_lensed2[2:2000, 0], cls_lensed[2:2000, 0], rtol=1e-3)
        self.assertTrue(np.all(np.abs((cls_lensed2[2:3000, 3] - cls_lensed[2:3000, 3]) /
                                      np.sqrt(cls_lensed2[2:3000, 0] * cls_lensed2[2:3000, 1])) < 1e-4))

        corr, xvals, weights = correlations.gauss_legendre_correlation(cls['lensed_scalar'])
        clout = correlations.corr2cl(corr, xvals, weights, 2500)
        self.assertTrue(np.all(np.abs(clout[2:2300, 2] / cls['lensed_scalar'][2:2300, 2] - 1) < 1e-3))

        pars = camb.CAMBparams()
        pars.set_cosmology(H0=78, YHe=0.22)
        pars.set_for_lmax(2000, lens_potential_accuracy=1)
        pars.WantTensors = True
        results = camb.get_transfer_functions(pars)
        from camb import initialpower
        cls = []
        for r in [0, 0.2, 0.4]:
            inflation_params = initialpower.InitialPowerLaw()
            inflation_params.set_params(ns=0.96, r=r, nt=0)
            results.power_spectra_from_transfer(inflation_params, silent=True)
            cls += [results.get_total_cls(CMB_unit='muK')]
        self.assertTrue(np.allclose((cls[1] - cls[0])[2:300, 2] * 2, (cls[2] - cls[0])[2:300, 2], rtol=1e-3))

        # Check generating tensors and scalars together
        pars = camb.CAMBparams()
        pars.set_cosmology(H0=67)
        lmax = 2000
        pars.set_for_lmax(lmax, lens_potential_accuracy=1)
        pars.InitPower.set_params(ns=0.96, r=0)
        pars.WantTensors = False
        results = camb.get_results(pars)
        cl1 = results.get_total_cls(lmax, CMB_unit='muK')
        pars.InitPower.set_params(ns=0.96, r=0.1, nt=0)
        pars.WantTensors = True
        results = camb.get_results(pars)
        cl2 = results.get_lensed_scalar_cls(lmax, CMB_unit='muK')
        ctensor2 = results.get_tensor_cls(lmax, CMB_unit='muK')
        results = camb.get_transfer_functions(pars)
        results.Params.InitPower.set_params(ns=1.1, r=1)
        inflation_params = initialpower.InitialPowerLaw()
        inflation_params.set_params(ns=0.96, r=0.05, nt=0)
        results.power_spectra_from_transfer(inflation_params, silent=True)
        cl3 = results.get_lensed_scalar_cls(lmax, CMB_unit='muK')
        ctensor3 = results.get_tensor_cls(lmax, CMB_unit='muK')
        self.assertTrue(np.allclose(ctensor2, ctensor3 * 2, rtol=1e-4))
        self.assertTrue(np.allclose(cl1, cl2, rtol=1e-4))
        # These are identical because all scalar spectra were identical (non-linear corrections change it  otherwise)
        self.assertTrue(np.allclose(cl1, cl3, rtol=1e-4))

        pars = camb.CAMBparams()
        pars.set_cosmology(H0=67.5, ombh2=0.022, omch2=0.122, mnu=0.07, omk=0)
        pars.set_for_lmax(2500)
        pars.min_l = 2
        res = camb.get_results(pars)
        cls = res.get_lensed_scalar_cls(2000)
        pars.min_l = 1
        res = camb.get_results(pars)
        cls2 = res.get_lensed_scalar_cls(2000)
        np.testing.assert_allclose(cls[2:, 0:2], cls2[2:, 0:2], rtol=1e-4)
        self.assertAlmostEqual(cls2[1, 0], 1.30388e-10, places=13)
        self.assertAlmostEqual(cls[1, 0], 0)
예제 #17
0
import sys, platform, os
from matplotlib import pyplot as plt
import numpy as np
import camb
from camb import model, initialpower

#GENERATING TRANSFERS
#NOTE TO SELF: for normalization purposes, the ell for subhorizon/superhorizon crossing is 150, which corresponds to transfer.l[36] (this may change depending on accuracy setttings)

pars=camb.CAMBparams()
pars.set_cosmology(H0=67.5, ombh2=0.022, omch2=0.122, mnu=0.06, omk=0, tau=0.06)
pars.InitPower.set_params(ns=0.965, r=0)
results = camb.get_results(pars)
powers = results.get_cmb_power_spectra(pars)
data = camb.get_transfer_functions(pars)
transfer = data.get_cmb_transfer_data()
totCL=powers['total']

dTl5=np.loadtxt("/Users/darshkodwani/Desktop/CAMB-0.1.6.1/pycamb/decay_trnsf_l150.txt",unpack=True)

#MAKE PLOTS

# plt.semilogx(transfer.q,transfer.delta_p_l_k[0,36,:],'b',label="Grow l=150")
# plt.semilogx(transfer.q,dTl5,'r',label="Decay l=150")
# 
# plt.legend()
# plt.show()

#Cls comparison

clgrow=np.loadtxt("/Users/darshkodwani/Desktop/CAMB-0.1.6.1/pycamb/grow_cl.txt",unpack=True)
예제 #18
0
    def compute_transfer(self, lmax, verbose=True):
        '''
        Call CAMB to calculate radiation transfer functions.

        Parameters
        ----------
        lmax : int
            Maximum multipole.
        verbose : bool, optional
            Print if CAMB parameter values change.

        Raises
        ------
        AttributeError
            If CAMB parameters have not been initialized.
        ValueError
            If lmax is too low (lmax < 300).
        '''

        if lmax < 300:
            # CAMB crashes for too low lmax.
            raise ValueError('Pick lmax >= 300.')

        k_eta_fac = 2.5  # Default used by CAMB.
        self.camb_params.set_for_lmax(lmax, lens_margin=0, k_eta_fac=k_eta_fac)

        if self.camb_params.validate() is False:
            raise ValueError(
                'Value {} for lmax makes params invalid'.format(lmax))

        # Make CAMB do the actual calculations (slow).
        data = camb.get_transfer_functions(self.camb_params)
        self._camb_data = data

        # Copy in resulting transfer functions (fast).
        tr = data.get_cmb_transfer_data('scalar')
        # Modify scalar E-mode, see Zaldarriaga 1997 Eqs. 18 and 39.
        # (CAMB applies these factors at a later stage).
        try:
            # CAMB changed this at least one time.
            # See Nov 19 CAMB commit: Formatting; py 3.8 test.
            ells = tr.L
        except AttributeError:
            ells = tr.l
        # CAMB ells are in int32, so convert.
        ells = ells.astype(int)
        prefactor = np.sqrt((ells + 2) * (ells + 1) * ells * (ells - 1))
        tr.delta_p_l_k[1, ...] *= prefactor[:, np.newaxis]
        # Scale with CMB temperature in uK.
        tr.delta_p_l_k *= (self.camb_params.TCMB * 1e6)

        # Transfer function is now of shape (NumSources, nell, nk),
        # where NumSources = 3 (T, E, lensing potential).
        # We want the shape to be (nell, nk, npol=2).
        nk = tr.q.size
        nell = ells.size
        npol = 2
        tr_ell_k = np.empty((nell, nk, npol), dtype=float)

        tr_view = tr.delta_p_l_k[:2, ...]
        tr_view = np.swapaxes(tr_view, 0, 2)  # (nk, nell, npol).
        tr_view = np.swapaxes(tr_view, 0, 1)  # (nell, nk, npol).
        tr_ell_k[:] = np.ascontiguousarray(tr_view)

        self.transfer['tr_ell_k'] = tr_ell_k
        self.transfer['k'] = tr.q
        self.transfer['ells'] = ells  # Probably sparse.
예제 #19
0
파일: Cl_CAMB.py 프로젝트: nesar/AstroVAE
ax[1, 0].plot(ls, unlensedCL[:, 1], color='r')
ax[1, 0].set_title(r'$EE$')
ax[1, 1].plot(ls, totCL[:, 3], color='k')
ax[1, 1].plot(ls, unlensedCL[:, 3], color='r')
ax[1, 1].set_title(r'$TE$')
for ax in ax.reshape(-1):
    ax.set_xlim([2, 2500])

#-------------------------------------------------------------------------------
print(pars)  # Shows all parameters
# -------------------------------------------------------------------------------

#You can calculate spectra for different primordial power spectra without recalculating everything
#for example, let's plot the BB spectra as a function of r
pars.WantTensors = True
results = camb.get_transfer_functions(pars)
lmax = 2000
rs = np.linspace(0, 0.2, 6)
for r in rs:
    inflation_params = initialpower.InitialPowerParams()
    inflation_params.set_params(ns=0.96, r=r)
    results.power_spectra_from_transfer(inflation_params)
    cl = results.get_total_cls(lmax, CMB_unit='muK')
    plt.loglog(np.arange(lmax + 1), cl[:, 2])
plt.xlim([2, lmax])
plt.legend(["$r = %s$" % r for r in rs], loc='lower right')
plt.ylabel(r'$\ell(\ell+1)C_\ell^{BB}/ (2\pi \mu{\rm K}^2)$')
plt.xlabel(r'$\ell$')

#Now get matter power spectra and sigma8 at redshift 0 and 0.8
pars = camb.CAMBparams()
예제 #20
0
파일: utils.py 프로젝트: parnalte/HODfit
def get_camb_pk(redshift=0,
                OmegaM0=0.27,
                OmegaL0=0.73,
                OmegaB0=0.04,
                H0=70.0,
                Pinit_As=2.2e-9,
                Pinit_n=0.96,
                nonlinear=False,
                halofit_model=None,
                kmin=1e-4,
                kmax=20.0,
                k_per_logint=10):
    """
    Function that obtains a sampled matter Power Spectrum for a set of
    parameters using the CAMB library. We print also the value of \sigma_8
    obtained for these parameters (comparable to the 'standard' one if
    redshift=0 and nonlinear=False).

    Parameters:
    - redshift: redshift for which we calculate the P(k). It should be a single
                value.
    - Cosmological parameters to pass to CAMB (OmegaM0, OmegaL0, OmegaB0,
        H0, Pinit_As, Pinit_n): will convert to 'physical densities' when
        needed. We'll leave the parameters related to neutrino content at the
        default values.
    - nonlinear: whether to compute the non-linear P(k) (using HaloFit)
    - halofit_model: If nonlinear, which HaloFit version to use. If it is None,
        use CAMB's default model (currently, `mead`). See documentation for
        `camb.nonlinear.Halofit.set_params` for valid options.
    - kmin, kmax, k_per_logint: parameters defining the output array in k, following
        CAMB's terminology

    Output:
    - A PowerSpectrum object
    """

    # Get default set of CAMB Parameters
    params = camb.CAMBparams()

    # Set cosmology parameters
    h = H0 / 100
    ombh2 = OmegaB0 * h * h
    omch2 = (OmegaM0 - OmegaB0) * h * h
    omk = 1 - OmegaM0 - OmegaL0
    if np.abs(omk) < 1e-5:
        omk = 0
    if omk != 0:
        print(f"You are using a non-flat cosmology (OmegaK = {omk})."
              "Are you sure this is what you really want?")
#        raise UserWarning("You are using a non-flat cosmology. \
#            Are you sure that is what you really want?")

    params.set_cosmology(H0=H0, ombh2=ombh2, omch2=omch2, omk=omk)
    params.InitPower.set_params(As=Pinit_As, ns=Pinit_n)

    # Set non-linearity parameters
    if nonlinear:
        nl_label = "Non-linear"
        params.NonLinear = camb.model.NonLinear_both
        if halofit_model is not None:
            params.NonLinearModel.set_params(halofit_version=halofit_model)
    else:
        nl_label = "Linear"
        params.NonLinear = camb.model.NonLinear_none

    # Set parameters for P(k)
    params.set_matter_power(redshifts=(redshift, ),
                            kmax=kmax,
                            k_per_logint=k_per_logint)

    # Do the calculation
    # results = camb.get_results(params)
    results = camb.get_transfer_functions(params)
    npoints = (np.log(kmax) - np.log(kmin)) * k_per_logint
    npoints = np.int(npoints)
    kh, _, pk = results.get_matter_power_spectrum(minkh=kmin,
                                                  maxkh=kmax,
                                                  npoints=npoints)
    sigma8 = results.get_sigma8()

    print(
        f"{nl_label} power spectrum calculated at z={redshift} for the given parameters."
    )
    print(f"For this P(k) we obtain \sigma_8={sigma8[0]:.5}")

    # Get the output as a PowerSpectrum object
    return PowerSpectrum(kvals=kh, pkvals=pk[0])