Example #1
0
File: 2pf.py Project: sflender/2pf
def xi_dd(r,z,h,Omega_DM,ombh2,w,mnu,smoothing_scale):
    # returns the matter-matter correlation function (dimensionless)
    # at comoving separation r in Mpc/h, and using the given smoothing scale in Mpc/h

    H0 = h*100
    omch2 = Omega_DM * h**2
    Omega_b = ombh2 * h**(-2)
    Omega_M = Omega_DM + Omega_b
    
    pars = camb.CAMBparams() #Set up a new set of parameters for CAMB
    pars.set_cosmology(H0=H0, ombh2=ombh2, omch2=omch2, mnu=mnu, omk=0, tau=0.06)
    pars.InitPower.set_params(ns=0.965, r=0)
    pars.set_dark_energy(w)
    pars.set_for_lmax(2500, lens_potential_accuracy=0);
    results = camb.get_results(pars)
    pars.set_matter_power(redshifts=[z], kmax=2.0)
    pars.NonLinear = model.NonLinear_none #compute the linear power spectrum (i.e. w/o halofit)
    #pars.NonLinear = model.NonLinear_both #using halofit
    results = camb.get_results(pars) #computes the power spectra
    kh, dummy, pk = results.get_matter_power_spectrum(minkh=1e-3, maxkh=2, npoints = 10000)
    curlyP = kh**3 * pk / (2.0*math.pi**2) 
    
    dlnk = log(kh[1])-log(kh[0])

    temp=0
    for i in range(0,size(kh)):
        temp = temp + dlnk * sinc(kh[i]*r) * curlyP[0][i] * window(kh[i]*smoothing_scale)**2
    return temp
Example #2
0
 def testInstances(self):
     pars = camb.set_params(H0=69.1, ombh2=0.032, omch2=0.122, As=3e-9, ns=0.91, omk=0.013,
                            redshifts=[0.], kmax=0.5)
     data = camb.get_background(pars)
     res1 = data.angular_diameter_distance(0.7)
     drag1 = data.get_derived_params()['rdrag']
     pars2 = camb.set_params(H0=65, ombh2=0.022, omch2=0.122, As=3e-9, ns=0.91)
     data2 = camb.get_background(pars2)
     res2 = data2.angular_diameter_distance(1.7)
     drag2 = data2.get_derived_params()['rdrag']
     self.assertAlmostEqual(res1, data.angular_diameter_distance(0.7))
     self.assertAlmostEqual(res2, data2.angular_diameter_distance(1.7))
     self.assertAlmostEqual(drag1, data.get_derived_params()['rdrag'])
     self.assertEqual(pars2.InitPower.ns, data2.Params.InitPower.ns)
     data2.calc_background(pars)
     self.assertEqual(pars.InitPower.ns, data2.Params.InitPower.ns)
     self.assertAlmostEqual(res1, data2.angular_diameter_distance(0.7))
     data3 = camb.get_results(pars2)
     cl3 = data3.get_lensed_scalar_cls(1000)
     self.assertAlmostEqual(res2, data3.angular_diameter_distance(1.7))
     self.assertAlmostEqual(drag2, data3.get_derived_params()['rdrag'], places=3)
     self.assertAlmostEqual(drag1, data.get_derived_params()['rdrag'], places=3)
     pars.set_for_lmax(3000, lens_potential_accuracy=1)
     camb.get_results(pars)
     del data3
     data4 = camb.get_results(pars2)
     cl4 = data4.get_lensed_scalar_cls(1000)
     self.assertTrue(np.allclose(cl4, cl3))
Example #3
0
File: 2pf.py Project: sflender/2pf
def xi_dv(r, z, h, Omega_DM, ombh2, w, mnu, smoothing_scale):
    # comoving matter-velocity correlation function in km/s at comoving distance r (in units Mpc/h) and redshift z
    # the power spectrum is smoothed with a top-hat window function with the specified smoothing scale in Mpc/h.
    # w is the dark energy eq. of state
    # mnu is the sum of the neutrino masses in eV

    H0 = h*100
    omch2 = Omega_DM * h**2
    Omega_b = ombh2 * h**(-2)
    Omega_M = Omega_DM + Omega_b
    
    pars = camb.CAMBparams() #Set up a new set of parameters for CAMB
    pars.set_cosmology(H0=H0, ombh2=ombh2, omch2=omch2, mnu=mnu, omk=0, tau=0.06)
    pars.InitPower.set_params(ns=0.965, r=0)
    pars.set_dark_energy(w)
    pars.set_for_lmax(2500, lens_potential_accuracy=0);
    results = camb.get_results(pars)
    pars.set_matter_power(redshifts=[z], kmax=2.0)
    pars.NonLinear = model.NonLinear_none #compute the linear power spectrum (i.e. w/o halofit)
    #pars.NonLinear = model.NonLinear_both #using halofit
    results = camb.get_results(pars) #compute the power spectra
    kh, dummy, pk = results.get_matter_power_spectrum(minkh=1e-3, maxkh=2, npoints = 10000)
    curlyP = kh**3 * pk / (2.0*math.pi**2)
    # pk in Mpc^3/h^3
    # kh in h/Mpc
    # curlyP is dimensionless
    
    dlnk = log(kh[1])-log(kh[0])
    temp = 0
    norm = -a(z)*Hred(Omega_M,z)*growth_rate(Omega_M,z)
    # units of norm: km/s/(Mpc/h)
    for i in range(0,size(kh)):
        temp = temp + dlnk * j1(kh[i]*r) * curlyP[0][i]/kh[i] * window(kh[i]*smoothing_scale)**2
    return norm*temp
 def setup(self):
     """
     Make a CAMB test run to confirm that everything works for the default
     parametrization.
     """
     self.CAMBparams.set_cosmology(**self.cosmo_constants)
     self.CAMBparams.InitPower.set_params(**self.init_constants)
     camb.get_results(self.CAMBparams)
    def __call__(self, ctx):
        p = ctx.getParams()
        try:
            cosmo_params = {}
            for k,v in self.cosmo_mapping.items():
                cosmo_params[k] = p[v]
            cosmo_params.update(self.cosmo_constants)
            self.CAMBparams.set_cosmology(**cosmo_params)
            
            init_params = {}
            for k,v in self.init_mapping.items():
                init_params[k] = p[v]
            init_params.update(self.init_constants)
            self.CAMBparams.InitPower.set_params(**init_params)

            results = camb.get_results(self.CAMBparams)
            Tcmb = self.CAMBparams.TCMB*1e6
            powers = results.get_cmb_power_spectra(lmax = self.lmax)['total']
            powers *= (Tcmb * Tcmb)
            # The convention in CosmoHammer is to have the spectra in units
            # microK^2 and starting from ell=2 
            ctx.add(CL_TT_KEY, powers[2:,0])
            ctx.add(CL_TE_KEY, powers[2:,3])
            ctx.add(CL_EE_KEY, powers[2:,1])
            ctx.add(CL_BB_KEY, powers[2:,2])
        except camb.baseconfig.CAMBError:
            getLogger().warn("CAMBError catched. Used params [%s]"%( ", ".join([str(i) for i in p]) ) )
            raise LikelihoodComputationException()
Example #6
0
    def theoryCls(self, LMAX):
        """get the theoretical :math:`C_l` values for the current cosmology using CLASS code.
        The cosmological parameters are set from the current :class:`.cosmology`.
        The power sepctra are also set as variables in the cosmology class.

        If the include_polarization switch is set to True, then it also sets

        """
        # using camb
        pars = camb.CAMBparams()
        pars.set_cosmology(H0=self.cosmology.H0, ombh2=self.cosmology.Ob0*self.cosmology.h**2.0, 
                           omch2=self.cosmology.Oc0*self.cosmology.h**2.0, omk=0, 
                           tau=self.cosmology.tau, mnu=self.cosmology.m_nu[-1])
        pars.InitPower.set_params(As=self.cosmology.As, ns=self.cosmology.n, r=self.cosmology.r)
        pars.set_for_lmax(LMAX)

        if (self.cosmology.r > 0.0):
            pars.WantTensors = True

        results = camb.get_results(pars)
        powers = results.get_cmb_power_spectra(pars)
        totCL = powers['total']

        self.cosmology.TTCls = totCL[:LMAX+1,0]
        self.cosmology.ells=np.arange(LMAX+1)

        if (self.include_polarization):
            self.cosmology.TECls = totCL[:LMAX+1,3]
            self.cosmology.BBCls = totCL[:LMAX+1,2]
            self.cosmology.EECls = totCL[:LMAX+1,1]

        return self.cosmology.TTCls
Example #7
0
def getHubbleCosmology(theta,params,precision = 0.00001,H0init = 70.,H0max = 100.,H0min = 40.):
    '''
    Finds H0 for given theta and other cosmo params{} using a bisection search
    '''
    
    H0 = H0init
    err = precision*2.
    pars = camb.CAMBparams()
    pars.set_accuracy(AccuracyBoost=2.0, lSampleBoost=2.0, lAccuracyBoost=2.0)
    #pars.set_accuracy(AccuracyBoost=3.0, lSampleBoost=3.0, lAccuracyBoost=3.0)
    pars.set_dark_energy(w=params['w'])
    pars.InitPower.set_params(As=params['As'],ns=params['ns'],r=params['r'])
    #no need for this: pars.set_for_lmax(lmax=int(params['lmax']), lens_potential_accuracy=1, max_eta_k=2*params['lmax'])

    print "Searching for H0 through bisection..."
    j = 0
    while np.abs(err)>precision:
        pars.set_cosmology(H0=H0, ombh2=params['ombh2'], omch2=params['omch2'], tau=params['tau'],mnu=params['mnu'],nnu=params['nnu'],omk=params['omk'])
        results = camb.get_results(pars)
        HundredTheta = 100.*results.cosmomc_theta()

        err = HundredTheta-theta

        if err<0.:
            H0min = H0
            H0 = (H0+H0max)/2.
        elif err>0.:
            H0max = H0
            H0 = (H0+H0min)/2.

        j+=1
        

    print "Found H0 = ", H0, " in ", j , " iterations."
    return H0
Example #8
0
 def testDarkEnergy(self):
     pars = camb.CAMBparams()
     pars.set_cosmology(H0=71)
     pars.InitPower.set_params(ns=0.965, r=0)
     for m in ['fluid', 'ppf']:
         pars.set_dark_energy(w=-0.7, wa=0.2, dark_energy_model=m)
         C1 = camb.get_results(pars).get_cmb_power_spectra()
         a = np.logspace(-5, 0, 1000)
         w = -0.7 + 0.2 * (1 - a)
         pars2 = pars.copy()
         pars2.set_dark_energy_w_a(a, w, dark_energy_model=m)
         C2 = camb.get_results(pars2).get_cmb_power_spectra()
         for f in ['lens_potential', 'lensed_scalar']:
             self.assertTrue(np.allclose(C1[f][2:, 0], C2[f][2:, 0]))
         pars3 = pars2.copy()
         self.assertAlmostEqual(-0.7, pars3.DarkEnergy.w)
Example #9
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)

        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(redshifts=[0., 0.17, 3.1])
        pars.NonLinear = model.NonLinear_none
        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, 4)
        self.assertAlmostEqual(s8[2], 0.80044, 4)

        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.697, 2)
        self.assertAlmostEqual(pk2[-2][-4], 53.47, 2)

        camb.set_feedback_level(0)
        cls = data.get_cmb_power_spectra(pars)

        cls_tot = data.get_total_cls(2000)
        cls_scal = data.get_unlensed_scalar_cls(2000)
        cls_tensor = data.get_tensor_cls(2000)
        cls_lensed = data.get_lensed_scalar_cls(2000)
        cls_phi = data.get_lens_potential_cls(2000)

        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], 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)
        camb.set_halofit_version('mead')
        _, _, pk = results.get_nonlinear_matter_power_spectrum(params=pars, var1='delta_cdm', var2='delta_cdm')
        self.assertAlmostEqual(pk[0][160], 232.08,1)
Example #10
0
 def testSources(self):
     from camb.sources import GaussianSourceWindow, SplinedSourceWindow
     pars = camb.CAMBparams()
     pars.set_cosmology(H0=64, mnu=0)
     pars.set_for_lmax(1200)
     pars.Want_CMB = False
     pars.SourceWindows = [
         GaussianSourceWindow(redshift=0.17, source_type='counts', bias=1.2, sigma=0.04, dlog10Ndm=-0.2),
         GaussianSourceWindow(redshift=0.5, source_type='lensing', sigma=0.07, dlog10Ndm=0)]
     pars.SourceTerms.limber_windows = True
     results = camb.get_results(pars)
     cls = results.get_source_cls_dict()
     zs = np.arange(0, 0.5, 0.02)
     W = np.exp(-(zs - 0.17) ** 2 / 2 / 0.04 ** 2) / np.sqrt(2 * np.pi) / 0.04
     pars.SourceWindows[0] = SplinedSourceWindow(bias=1.2, dlog10Ndm=-0.2, z=zs, W=W)
     results = camb.get_results(pars)
     cls2 = results.get_source_cls_dict()
     self.assertTrue(np.allclose(cls2["W1xW1"][2:1200], cls["W1xW1"][2:1200], rtol=1e-3))
     pars.SourceWindows = [GaussianSourceWindow(redshift=1089, source_type='lensing', sigma=30)]
     results = camb.get_results(pars)
     cls = results.get_source_cls_dict()
     PP = cls['PxP']
     ls = np.arange(0, PP.shape[0])
     self.assertTrue(np.allclose(PP / 4 * (ls * (ls + 1)), cls['W1xW1'], rtol=1e-3))
     self.assertTrue(np.allclose(PP / 2 * np.sqrt(ls * (ls + 1)), cls['PxW1'], rtol=1e-3))
     # test something sharp with redshift distortions (tricky..)
     from scipy import signal
     zs = np.arange(1.9689, 2.1057, (2.1057 - 1.9689) / 2000)
     W = signal.tukey(len(zs), alpha=0.1)
     pars = camb.CAMBparams()
     pars.set_cosmology(H0=67.5, ombh2=0.022, omch2=0.122)
     pars.InitPower.set_params(As=2e-9, ns=0.965)
     pars.set_for_lmax(4000)
     pars.SourceWindows = [SplinedSourceWindow(z=zs, W=W, source_type='counts')]
     pars.SourceTerms.counts_redshift = True
     results = camb.get_results(pars)
     cls = results.get_source_cls_dict()
     self.assertAlmostEqual(np.sum(cls['PxW1'][10:3000:20]), 0.00020001, places=5)
     self.assertAlmostEqual(np.sum(cls['W1xW1'][10:3000:20]), 2.26348, places=3)
     self.assertAlmostEqual(np.sum(cls['W1xW1'][10]), 0.0001097, places=6)
    def __call__(self, fit_params):
        self.pars.set_cosmology(H0=fit_params['H0'],
                           ombh2=fit_params['ombh2'],
                           omch2=fit_params['omch2'],
                           tau=fit_params['tau']
                           )
                                      
        self.pars.InitPower.set_params(As=fit_params['As'],
                                  ns=fit_params['ns'])
                                                                           
        powers = camb.get_results(self.pars).get_cmb_power_spectra(self.pars)

        return powers['lensed_scalar'][:self.lmax,0]*(1e6)**2 * 2.725**2
    def __call__(self, fit_params):
        self.pars.set_cosmology(H0=None, cosmomc_theta=fit_params['theta']/100.,
                           ombh2=fit_params['ombh2'],
                           omch2=fit_params['ommh2']-fit_params['ombh2'],
                           tau=fit_params['tau']
                           )
                                      
        self.pars.InitPower.set_params(As=fit_params['clamp']*1e-9*exp(2*fit_params['tau']),
                                  ns=fit_params['ns'])
                                                                           
        powers = camb.get_results(self.pars).get_cmb_power_spectra(self.pars)

        return powers['lensed_scalar'][:self.lmax,0]*(1e6)**2 * 2.725**2
Example #13
0
	def PKL_Camb_SingleRedshift(self, kk, zz=0.0):
		pars = camb.CAMBparams()
		pars.set_cosmology(H0=self.h*100, ombh2=self.Omega_b*self.h**2, \
							omch2=(self.Omega_m-self.Omega_b)*self.h**2)
		pars.set_dark_energy(w=self.w0) #re-set defaults
		pars.InitPower.set_params(ns=self.n_s)
		pars.set_matter_power(redshifts=[zz], kmax=10.0)
		results = camb.get_results(pars)
		kh, z, pk = \
			results.get_matter_power_spectrum(minkh=1e-4,maxkh=10.0,npoints=500)
		s8 = np.array(results.get_sigma8())
		pklin = pk[0]*(self.Sigma_8/s8)**2	
		return np.interp(kk, kh, pklin)
Example #14
0
    def get_nonlin_power(self, z=0., KMAX=2.0, nl=True):
        self.cambparams.set_matter_power(redshifts=[z], kmax=KMAX)
        if (nl):
            self.cambparams.NonLinear = camb.model.NonLinear_both
        else:
            self.cambparams.NonLinear = camb.model.NonLinear_none

        self.cambresults = camb.get_results(self.cambparams)
        kh_nonlin, z_nonlin, pk_nonlin = self.cambresults.get_matter_power_spectrum(minkh=1E-5, maxkh=1.5, npoints=500)
        # now that we have the power spectrum; interpolate
        kh_lin, z_lin, pk_lin = self.cambresults.get_linear_matter_power_spectrum()
        self.camb_power_nonlin = interp1d(kh_nonlin, pk_nonlin[0,:])
        self.camb_power_lin = interp1d(kh_lin, pk_lin[0,:])
        return self.camb_power_nonlin
Example #15
0
def getPowerCamb(params,spec='lensed_scalar',AccuracyBoost=False):
    '''
    Get Cls from CAMB
    '''
    
    pars = camb.CAMBparams()
    if AccuracyBoost:
        #pars.set_accuracy(AccuracyBoost=2.0, lSampleBoost=2.0, lAccuracyBoost=2.0)
        pars.set_accuracy(AccuracyBoost=3.0, lSampleBoost=3.0, lAccuracyBoost=3.0)
    pars.set_cosmology(H0=params['H0'], ombh2=params['ombh2'], omch2=params['omch2'], tau=params['tau'],mnu=params['mnu'],nnu=params['nnu'],omk=params['omk'],num_massive_neutrinos=int(params['num_massive_neutrinos']),TCMB=params['TCMB'])
    pars.set_dark_energy(w=params['w'])
    pars.InitPower.set_params(As=params['As'],ns=params['ns'],r=params['r'],pivot_scalar=params['s_pivot'], pivot_tensor=params['t_pivot'])
    pars.set_for_lmax(lmax=int(params['lmax']), lens_potential_accuracy=1, max_eta_k=2*params['lmax'])
    #pars.set_for_lmax(lmax=int(params['lmax']), lens_potential_accuracy=2.0, max_eta_k=50000.0)
    pars.set_for_lmax(lmax=int(params['lmax']), lens_potential_accuracy=3.0, max_eta_k=50*params['lmax'])

    #WantTensors
    if params['r']:
        pars.WantTensors = True
    results = camb.get_results(pars)
    powers =results.get_cmb_power_spectra(pars)

    if spec=='tensor':
        CL = results.get_tensor_cls(int(params['lmax']))*1.e12*params['TCMB']**2.
    else:    
        CL=powers[spec]*1.e12*params['TCMB']**2.

    lensArr = results.get_lens_potential_cls(lmax=int(params['lmax']))
    clphi = lensArr[:,0]
    cltphi = lensArr[:,1]

    j=0.
    CLS = []
    # numpify this!
    for row in CL:
        if j>params['lmax']: break
        raw = row*2.*np.pi/(j*(j+1.))
        rawkk = clphi[j]* (2.*np.pi/4.)
        #rawkt = cltphi[j]*2.*np.pi/4.
        # correct KT (l^2*ClphiT and dimensional - uK)
        rawkt = cltphi[j]* (2.*np.pi/2.) / np.sqrt(j*(j+1.)) * params['TCMB']*1.e6
        CLS.append(np.append(raw,(rawkk,rawkt)))
                   
        j+=1.

    CLS = np.nan_to_num(np.array(CLS))

    return CLS
Example #16
0
def test_nonlin_camb_power():
    import camb

    logT_AGN = 7.93
    Omega_c = 0.25
    Omega_b = 0.05
    A_s = 2.1e-9
    n_s = 0.97
    h = 0.7
    # Needs to be set for good agreements between CCL and CAMB
    T_CMB = 2.725

    p = camb.CAMBparams(WantTransfer=True,
                        NonLinearModel=camb.nonlinear.Halofit(
                            halofit_version="mead2020_feedback",
                            HMCode_logT_AGN=logT_AGN))
    # This affects k_min
    p.WantCls = False
    p.DoLensing = False
    p.Want_CMB = False
    p.Want_CMB_lensing = False
    p.Want_cl_2D_array = False
    p.set_cosmology(H0=h*100, omch2=Omega_c*h**2, ombh2=Omega_b*h**2,
                    mnu=0.0, TCMB=T_CMB)
    p.share_delta_neff = False
    p.InitPower.set_params(As=A_s, ns=n_s)

    z = [0.0, 0.5, 1.0, 1.5]
    p.set_matter_power(redshifts=z, kmax=10.0, nonlinear=True)
    p.set_for_lmax(5000)

    r = camb.get_results(p)

    k, z, pk_nonlin_camb = r.get_nonlinear_matter_power_spectrum(
        hubble_units=False, k_hunit=False)

    ccl_cosmo = ccl.Cosmology(
        Omega_c=Omega_c, Omega_b=Omega_b, h=h, m_nu=0.0,
        A_s=A_s, n_s=n_s,
        transfer_function="boltzmann_camb",
        matter_power_spectrum="camb",
        extra_parameters={"camb": {"halofit_version": "mead2020_feedback",
                                   "HMCode_logT_AGN": logT_AGN}})

    for z_, pk_camb in zip(z, pk_nonlin_camb):
        pk_nonlin_ccl = ccl.nonlin_matter_power(ccl_cosmo, k, 1/(1+z_))

        assert np.allclose(pk_camb, pk_nonlin_ccl, rtol=3e-5)
def get_power_spectrum(h,
                       omc,
                       omb: float = 0.0486,
                       redshift: float = 0,
                       mode: str = 'linear',
                       nkpoints: int = 200) -> Tuple[np.ndarray, np.ndarray]:
    """
    Use CAMB to compute the power spectrum for the given parameters.

    Args:
        h: The reduced Hubble constant: h = H0 / (100 km / s / Mpc).
        omc: Dark matter density parameter.
        omb: Baryon density parameter.
        redshift: Redshift at which to compute the power spectrum.
        mode: Use linear Perturbation Theory or non-linear one.
        nkpoints: Number of points (in k-space) of the spectrum.

    Returns:
        A tuple (kh, pk), where kh is an array of k/h, and pk[j] is the
        value of the power spectrum at k/h[j] (for the given redshift).
    """

    # Convert input parameters to quantities used for simulation
    H0 = 100. * h
    ombh2 = omb * h**2
    omch2 = omc * h**2

    # Set up a CAMB object and define the cosmology
    pars = camb.CAMBparams()
    pars.set_cosmology(H0=H0, ombh2=ombh2, omch2=omch2)
    pars.InitPower.set_params()
    pars.set_matter_power(redshifts=[redshift], kmax=2.0)

    if mode == 'linear':
        pars.NonLinear = model.NonLinear_none
    elif mode == 'non-linear':
        pars.NonLinear = model.NonLinear_both
    else:
        raise ValueError('mode must be either "linear" or "non-linear"!')

    results = camb.get_results(pars)
    results.calc_power_spectra(pars)
    kh, z, pk = \
        results.get_matter_power_spectrum(minkh=1e-2,
                                          maxkh=1,
                                          npoints=nkpoints)

    return kh, pk[0].ravel()  # 0 for only one redshift
Example #18
0
    def test_hillipop(self):
        import camb
        import planck_2020_hillipop

        camb_cosmo = cosmo_params.copy()
        camb_cosmo.update({"lmax": 2500, "lens_potential_accuracy": 1})
        pars = camb.set_params(**camb_cosmo)
        results = camb.get_results(pars)
        powers = results.get_cmb_power_spectra(pars, CMB_unit="muK")
        cl_dict = {k: powers["total"][:, v] for k, v in {"tt": 0, "ee": 1, "te": 3}.items()}

        for mode, chi2 in chi2s.items():
            _hlp = getattr(planck_2020_hillipop, mode)
            my_lik = _hlp({"packages_path": packages_path})
            loglike = my_lik.loglike(cl_dict, **{**calib_params, **nuisance_params[mode]})
            self.assertLess( abs(-2 * loglike - chi2), 1)
Example #19
0
    def test_lollipop(self):
        import camb
        import planck_2020_lollipop

        camb_cosmo = cosmo_params.copy()
        camb_cosmo.update({"lmax": 145, "lens_potential_accuracy": 1})
        pars = camb.set_params(**camb_cosmo)
        results = camb.get_results(pars)
        powers = results.get_cmb_power_spectra(pars, CMB_unit="muK", raw_cl=True)
        cl_dict = {k: powers["total"][:, v] for k, v in {"ee": 1, "bb": 2}.items()}

        for mode, chi2 in chi2s.items():
            _llp = getattr(planck_2020_lollipop, mode)
            my_lik = _llp({"packages_path": packages_path})
            loglike = my_lik.loglike(cl_dict, **{})
            self.assertLess( abs(-2 * loglike - chi2), 1)
Example #20
0
 def test_memory(self):
     if platform.system() != "Windows":
         import gc
         import resource
         last_usage = -1
         for i in range(3):
             pars = camb.CAMBparams()
             pars.set_cosmology(H0=70, ombh2=0.022, omch2=0.12, mnu=0.06, omk=0, tau=0.17)
             results = camb.get_results(pars)
             del pars, results
             gc.collect()
             usage = round(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024.0, 1)
             if 0 < last_usage != usage:
                 print('Memory usage: %2.2f KB vs %2.2f KB' % (usage, last_usage))
                 raise Exception("Apparent memory leak")
             last_usage = usage
Example #21
0
def get_spectrum(pars,lmax=2000):
    H0=pars[0]
    ombh2=pars[1]
    omch2=pars[2]
    As=pars[3]
    ns=pars[4]
    tau=pars[5]
    pars=camb.CAMBparams()
    pars.set_cosmology(H0=H0,ombh2=ombh2,omch2=omch2,mnu=0.06,omk=0,tau=tau)
    pars.InitPower.set_params(As=As,ns=ns,r=0)
    pars.set_for_lmax(lmax,lens_potential_accuracy=0)
    results=camb.get_results(pars)
    powers=results.get_cmb_power_spectra(pars,CMB_unit='muK')
    cmb=powers['total']
    tt=cmb[:,0]    #you could return the full power spectrum here if you wanted to do say EE
    return tt
Example #22
0
def compute_g_star(cosmo, z_star):
    """ Compute logarithmic derivative of Hubble expansion, normalized to EdS:
        g(z) = dln H(z) / dln(1+z)^3/2 = 3/2 (1+z)/H(z) dH/dz """

    results = camb.get_results(cosmo)
    # compute derivative of Hubble
    dz = z_star / 100.0
    z_minus = z_star - dz
    z_plus = z_star + dz
    H_minus = results.hubble_parameter(z=z_minus)
    H_plus = results.hubble_parameter(z=z_plus)
    dHdz = (H_plus - H_minus) / (z_plus - z_minus)
    # compute hubble at z_star, and return g(z_star)
    H_star = results.hubble_parameter(z=z_star)
    g_star = dHdz / H_star * (1 + z_star) * 2 / 3
    return g_star
Example #23
0
def get_galaxy_power(l,z=0.7,b=1.):
    lmax = np.max([np.max(l),2000])
    pars = camb.CAMBparams()
    pars.set_cosmology(H0=67.5, ombh2=0.022, omch2=0.122)
    pars.InitPower.set_params(As=2e-9, ns=0.965)
    pars.set_for_lmax(lmax, lens_potential_accuracy=1)    
    pars.Want_CMB = False
    pars.NonLinear = model.NonLinear_both
    pars.SourceWindows = [GaussianSourceWindow(redshift=0.7, source_type='counts', sigma=0.1,dlog10Ndm=-0.2, bias = 1.0)]
    results = camb.get_results(pars)
    cls = results.get_source_cls_dict()
    l_model = np.arange(2,lmax+1)
    cl_model = cls['W1xW1'][2:lmax+1]
    # Interpolate this onto the provided grid.
    f = interp1d(l_model,cl_model,kind='cubic')
    return f(l)
Example #24
0
def load_theory(pars, lpad=9000):
    '''
    All ell and 2pi factors are stripped off.
    '''

    import camb
    from camb import model
    uSuffix = "unlensed_total"
    lSuffix = "total"

    results = camb.get_results(pars)
    cmbmat = results.get_cmb_power_spectra(
        pars,
        lmax=lpad,
        spectra=['total', 'unlensed_total', 'lens_potential'],
        raw_cl=True,
        CMB_unit='muK')

    theory = TheorySpectra()
    for i, pol in enumerate(['TT', 'EE', 'BB', 'TE']):
        cls = cmbmat[lSuffix][:, i]
        ells = np.arange(0, len(cls), 1)
        theory.loadCls(ells,
                       cls,
                       pol,
                       lensed=True,
                       interporder="linear",
                       lpad=lpad,
                       fill_zero=True)
        cls = cmbmat[uSuffix][:, i]
        ells = np.arange(0, len(cls), 1)
        theory.loadCls(ells,
                       cls,
                       pol,
                       lensed=False,
                       interporder="linear",
                       lpad=lpad,
                       fill_zero=True)

    lensArr = cmbmat['lens_potential']
    cldd = lensArr[:, 0]
    ells = np.arange(0, len(cldd), 1)
    clkk = cldd.copy()
    clkk[1:] = clkk[1:] / 4. * (ells[1:] * (ells[1:] + 1))**2.
    theory.loadGenericCls(ells, clkk, "kk", lpad=lpad, fill_zero=True)
    theory.dimensionless = False
    return theory
Example #25
0
def getHubbleCosmology(theta,
                       params,
                       precision=0.00001,
                       H0init=70.,
                       H0max=100.,
                       H0min=40.):
    '''
    Finds H0 for given theta and other cosmo params{} using a bisection search
    '''

    H0 = H0init
    err = precision * 2.
    pars = camb.CAMBparams()
    pars.set_accuracy(AccuracyBoost=2.0, lSampleBoost=2.0, lAccuracyBoost=2.0)
    #pars.set_accuracy(AccuracyBoost=3.0, lSampleBoost=3.0, lAccuracyBoost=3.0)
    pars.set_dark_energy(w=params['w'],
                         wa=params['wa'],
                         dark_energy_model='ppf')
    pars.InitPower.set_params(As=params['As'], ns=params['ns'], r=params['r'])
    #no need for this: pars.set_for_lmax(lmax=int(params['lmax']), lens_potential_accuracy=1, max_eta_k=2*params['lmax'])

    print "Searching for H0 through bisection..."
    j = 0
    while np.abs(err) > precision:
        pars.set_cosmology(H0=H0,
                           ombh2=params['ombh2'],
                           omch2=params['omch2'],
                           tau=params['tau'],
                           mnu=params['mnu'],
                           nnu=params['nnu'],
                           omk=params['omk'])
        results = camb.get_results(pars)
        HundredTheta = 100. * results.cosmomc_theta()

        err = HundredTheta - theta

        if err < 0.:
            H0min = H0
            H0 = (H0 + H0max) / 2.
        elif err > 0.:
            H0max = H0
            H0 = (H0 + H0min) / 2.

        j += 1

    print "Found H0 = ", H0, " in ", j, " iterations."
    return H0
Example #26
0
def get_spectrum(pars,lmax=2000):
    #print('pars are ',pars)
    H0=pars[0]    #Hubble Constant
    ombh2=pars[1] #Physical Baryon Density
    omch2=pars[2] #Cold Dark Matter Density
    As=pars[3]    #Primordial Amplitude of Fluctuations
    ns=pars[4]    #Slope of the Primordial Power Law
    tau=pars[5]   #Optical Depth
    pars=camb.CAMBparams()
    pars.set_cosmology(H0=H0,ombh2=ombh2,omch2=omch2,mnu=0.06,omk=0,tau=tau)
    pars.InitPower.set_params(As=As,ns=ns,r=0)
    pars.set_for_lmax(lmax,lens_potential_accuracy=0)
    results=camb.get_results(pars)
    powers=results.get_cmb_power_spectra(pars,CMB_unit='muK')
    cmb=powers['total']
    tt=cmb[:,0]    #you could return the full power spectrum here if you wanted to do say EE
    return tt
Example #27
0
    def _generate_data(self):
        self.logger.info(
            f"Generating CAMB data with {self.om_resolution} x {self.h0_resolution}"
        )
        os.makedirs(self.data_dir, exist_ok=True)
        import camb

        pars = camb.CAMBparams()
        pars.set_dark_energy(w=-1.0, dark_energy_model="fluid")
        pars.InitPower.set_params(As=2.130e-9, ns=self.ns)
        pars.set_matter_power(redshifts=[self.redshift, 0.0001],
                              kmax=self.k_max)
        self.logger.info("Configured CAMB power and dark energy")

        data = np.zeros(
            (self.om_resolution, self.h0_resolution, 1 + 3 * self.k_num))
        for i, omch2 in enumerate(self.omch2s):
            for j, h0 in enumerate(self.h0s):
                self.logger.debug("Generating %d:%d  %0.3f  %0.3f" %
                                  (i, j, omch2, h0))
                pars.set_cosmology(
                    H0=h0 * 100,
                    omch2=omch2,
                    mnu=0.0,
                    ombh2=self.omega_b * h0 * h0,
                    omk=0.0,
                    tau=0.063,
                    neutrino_hierarchy="degenerate",
                    num_massive_neutrinos=1,
                )
                pars.NonLinear = camb.model.NonLinear_none
                results = camb.get_results(pars)
                params = results.get_derived_params()
                rdrag = params["rdrag"]
                kh, z, pk_lin = results.get_matter_power_spectrum(
                    minkh=self.k_min, maxkh=self.k_max, npoints=self.k_num)
                pars.NonLinear = camb.model.NonLinear_pk
                results.calc_power_spectra(pars)
                kh, z, pk_nonlin = results.get_matter_power_spectrum(
                    minkh=self.k_min, maxkh=self.k_max, npoints=self.k_num)
                data[i, j, 0] = rdrag
                data[i, j, 1:1 + self.k_num] = pk_lin[1, :]
                data[i, j, 1 + self.k_num:] = pk_nonlin.flatten()
        self.logger.info(f"Saving to {self.filename}")
        np.save(self.filename, data)
        return data
Example #28
0
def get_spectrum(pars,y,lmax=2000):
    #print('pars are ',pars)
    H0=pars[0]
    ombh2=pars[1]
    omch2=pars[2]
    tau=pars[3]
    As=pars[4]
    ns=pars[5]
    pars=camb.CAMBparams()
    pars.set_cosmology(H0=H0,ombh2=ombh2,omch2=omch2,mnu=0.06,omk=0,tau=tau)
    pars.InitPower.set_params(As=As,ns=ns,r=0)
    pars.set_for_lmax(lmax,lens_potential_accuracy=0)
    results=camb.get_results(pars)
    powers=results.get_cmb_power_spectra(pars,CMB_unit='muK')
    cmb=powers['total']
    tt=cmb[2:len(y)+2,0]    #remove first two entries
    return tt
Example #29
0
def CAMBdemoCl():
    """
    example code from http://camb.readthedocs.io/en/latest/CAMBdemo.html

  """

    #Set up a new set of parameters for CAMB
    #pars = camb.CAMBparams()
    #This function sets up CosmoMC-like settings, with one massive neutrino and helium set using BBN consistency
    #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)

    pars = getPars()
    pars.set_for_lmax(2500, lens_potential_accuracy=0)
    # this line for C_l, not P_k

    #calculate results for these parameters
    results = camb.get_results(pars)

    #get dictionary of CAMB power spectra
    powers = results.get_cmb_power_spectra(pars)
    for name in powers:
        print name

    #plot the total lensed CMB power spectra versus unlensed, and fractional difference
    totCL = powers['total']
    unlensedCL = powers['unlensed_scalar']
    print totCL.shape
    #Python CL arrays are all zero based (starting at L=0), Note L=0,1 entries will be zero by default.
    #The different CL are always in the order TT, EE, BB, TE (with BB=0 for unlensed scalar results).
    ls = np.arange(totCL.shape[0])
    fig, ax = plt.subplots(2, 2, figsize=(12, 12))
    ax[0, 0].plot(ls, totCL[:, 0], color='k')
    ax[0, 0].plot(ls, unlensedCL[:, 0], color='r')
    ax[0, 0].set_title('TT')
    ax[0, 1].plot(ls[2:], 1 - unlensedCL[2:, 0] / totCL[2:, 0])
    ax[0, 1].set_title(r'$\Delta TT$')
    ax[1, 0].plot(ls, totCL[:, 1], color='k')
    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])
    plt.show()
Example #30
0
    def calc_linear(self, z):
        self.pars.set_matter_power(
            redshifts=[z], kmax=4.0
        )  ## Note: non-linear corrections couples to smaller scales than you want

        self.pars.NonLinear = model.NonLinear_none  ## Linear spectrum
        self.pkresults = camb.get_results(self.pars)
        self.kh, self.z, self.linpk = self.pkresults.get_matter_power_spectrum(
            minkh=1e-2, maxkh=2., npoints=200)
        self.lpower_interpolatek = interp1d(self.kh,
                                            self.linpk,
                                            kind=splinetype,
                                            bounds_error=False,
                                            fill_value=0.0)
        self.sig8 = self.pkresults.get_sigma8()

        return self.lpower_interpolatek
Example #31
0
def createCldata(oBar):
    pars = camb.CAMBparams()
    #This function sets up CosmoMC-like settings, with one massive neutrino and helium set using BBN consistency
    pars.set_cosmology(H0=67.5,
                       ombh2=oBar,
                       omch2=0.122,
                       mnu=0.06,
                       omk=0,
                       tau=0.06)
    pars.InitPower.set_params(As=2e-9, ns=0.965, r=0)
    pars.set_for_lmax(2500, lens_potential_accuracy=0)

    results = camb.get_results(pars)
    powers = results.get_cmb_power_spectra(pars, CMB_unit='muK')
    totCL_new = powers['total']
    ls = np.arange(totCL_new.shape[0])

    np.savetxt("data/Cl_%.3f.dat" % oBar, (ls, totCL_new[:, 0]))
Example #32
0
def get_cmb(params,lmax=2000):
    
    H0,ombh2,omch2,tau,As,ns = params

    params = camb.CAMBparams()
    params.set_cosmology(H0=H0,ombh2=ombh2,omch2=omch2,mnu=0.06,omk=0,tau=tau)
    params.InitPower.set_params(As=As,ns=ns,r=0)
    params.set_for_lmax(lmax,lens_potential_accuracy=0)
    
    results = camb.get_results(params)
    powers = results.get_cmb_power_spectra(params,CMB_unit='muK')
    cmb = powers['total']
    cmb = cmb[:,0]  
    
    # Remove the monopole and dipole
    cmb = cmb[2:]
    
    return cmb[:1199]
Example #33
0
def getBAOCamb(zrange,params,AccuracyBoost=False):
    '''
    Get BAO's fk=rs/D_V from CAMB. Return 1D array of fk for all redshifts z
    '''
    pars = camb.CAMBparams()
    if AccuracyBoost:
        pars.set_accuracy(AccuracyBoost=2.0, lSampleBoost=2.0, lAccuracyBoost=2.0)
        #pars.set_accuracy(AccuracyBoost=3.0, lSampleBoost=3.0, lAccuracyBoost=3.0)
    pars.set_cosmology(H0=params['H0'], ombh2=params['ombh2'], omch2=params['omch2'], tau=params['tau'],mnu=params['mnu'],nnu=params['nnu'],omk=params['omk'])
    pars.set_dark_energy(w=params['w'])
    pars.InitPower.set_params(As=params['As'],ns=params['ns'],r=params['r'])
    #pars.set_for_lmax(lmax=int(params['lmax']), lens_potential_accuracy=1, max_eta_k=2*params['lmax'])
    camb.set_z_outputs(zrange)
    results = camb.get_results(pars)
    fk = results.get_background_outputs() #results.get_BAO(zrange,pars)[:,0]
    #print fk
    fk = np.nan_to_num(fk[:,0])
    return fk
Example #34
0
def C_l(r, tau, ps='BB'):
    pars.set_cosmology(H0=67.81, ombh2=0.02226, omch2=0.1197, mnu=0.06, omk=0, tau=tau)
    pars.InitPower.set_params(ns=0.9677, r=r, As=2.13e-9)
    pars.set_for_lmax(2500, lens_potential_accuracy=0)
    pars.WantTensors = True
    pars.AccurateReionization = 1
    
    results = camb.get_results(pars)
    powers = results.get_cmb_power_spectra(pars)
    cl = powers['total']*(1e6*pars.TCMB)**2 # in uK_CMB^2
    if ps == 'EE':
        return cl[:200,1]
    elif ps == 'BB':
        return cl[:200,2]
    elif ps == 'EB':
        return cl[:200,1], cl[:200,2]
    else:
        return cl
def generate_cls():
    lmin, lmax = 2, 2000  # \ell range where the monopole and dipole are zero
    #Set Planck 2018 cosmological parameters
    pars = camb.CAMBparams()
    pars.set_cosmology(H0=67.66,
                       ombh2=0.02242,
                       omch2=0.11933,
                       mnu=0.120,
                       nnu=2.99,
                       omk=0.0007,
                       tau=0.0561,
                       YHe=0.242)
    pars.InitPower.set_params(As=np.exp(3.047) / 10**10, ns=0.9665)

    #Set \ell max again
    pars.set_for_lmax(lmax, lens_potential_accuracy=1)
    pars.Want_CMB = True  #Because we want the CMB

    powers = camb.get_results(pars).get_cmb_power_spectra(pars, CMB_unit="muK")
    l = np.arange(lmin, lmax)
    #cl = powers['total'][lmin:lmax,0]/(l*(l+1))*2*np.pi

    # Ordering TT, EE, BB, TE angular power expectra (CL).
    # We add 2 zeros because the monopoles and the dipoles are zero
    # *WARNING* this is very important, if not we get other simulation complitely different

    cl_tt = np.zeros(2).tolist()
    cl_tt.extend(
        (powers['total'][lmin:lmax, 0] / (l * (l + 1)) * 2 * np.pi).tolist())
    cl_tt = np.array(cl_tt)  #Simulation of the CMB temperature CL
    cl_ee = np.zeros(2).tolist()
    cl_ee.extend(
        (powers['total'][lmin:lmax, 1] / (l * (l + 1)) * 2 * np.pi).tolist())
    cl_ee = np.array(cl_ee)  #Simulation of the CMB E polarization CL
    cl_bb = np.zeros(2).tolist()
    cl_bb.extend(
        (powers['total'][lmin:lmax, 2] / (l * (l + 1)) * 2 * np.pi).tolist())
    cl_bb = np.array(cl_bb)  #Simulation of the CMB B polarization CL
    cl_te = np.zeros(2).tolist()
    cl_te.extend(
        (powers['total'][lmin:lmax, 3] / (l * (l + 1)) * 2 * np.pi).tolist())
    cl_te = np.array(cl_te)

    return cl_tt
Example #36
0
def rspectrum(nu, r, sig, scaling=1.0):
    """
    Calculates the CMB amplituded given a value of r and requested modes
    """
    import camb
    from camb import model, initialpower
    import healpy as hp
    #Set up a new set of parameters for CAMB
    pars = camb.CAMBparams()
    #This function sets up CosmoMC-like settings, with one massive neutrino and helium set using BBN consistency
    pars.set_cosmology(H0=67.5,
                       ombh2=0.022,
                       omch2=0.122,
                       mnu=0.06,
                       omk=0,
                       tau=0.06)
    pars.InitPower.set_params(As=2e-9, ns=0.965, r=r)
    lmax = 6000
    pars.set_for_lmax(lmax, lens_potential_accuracy=0)
    pars.WantTensors = True
    results = camb.get_results(pars)
    powers = results.get_cmb_power_spectra(
        params=pars,
        lmax=lmax,
        CMB_unit='muK',
        raw_cl=True,
    )

    l = np.arange(2, lmax + 1)

    if sig == "TT":
        cl = powers['unlensed_scalar']
        signal = 0
    elif sig == "EE":
        cl = powers['unlensed_scalar']
        signal = 1
    elif sig == "BB":
        cl = powers['tensor']
        signal = 2

    bl = hp.gauss_beam(40 / (180 / np.pi * 60), lmax, pol=True)
    A = np.sqrt(
        sum(4 * np.pi * cl[2:, signal] * bl[2:, signal]**2 / (2 * l + 1)))
    return cmb(nu, A * scaling)
Example #37
0
def a_s_to_sigma_8(cosmology_parameters):

    pars = camb.CAMBparams()
    pars.set_cosmology(
        H0=cosmology_parameters['H0'],
        ombh2=cosmology_parameters['Ob0'] * cosmology_parameters['h']**2,
        omch2=cosmology_parameters['Oc0'] * cosmology_parameters['h']**2,
        omk=0.,
        mnu=cosmology_parameters['Mnu'],
        standard_neutrino_neff=cosmology_parameters['Neff'],
        nnu=cosmology_parameters['Neff'],
        TCMB=cosmology_parameters['TCMB'])
    pars.InitPower.set_params(ns = cosmology_parameters['ns'], \
                              As = cosmology_parameters['As'], \
                              pivot_scalar = cosmology_parameters['pivot_scalar'])
    pars.NonLinear = model.NonLinear_none
    pars.set_matter_power(redshifts=[0.], kmax=20.)
    results = camb.get_results(pars)
    return results.get_sigma8()[0]
Example #38
0
    def __init__(self, cosmo, sips, kmax=200., npoints=350, nonlinear=True,
                 zvec=zvec_default):
        try:
            import camb
        except:
            print "camb (http://camb.info/) could not be loaded. is it installed?"
            raise

        self.cosmo = cosmo
        # Define the model parameters
        par           = camb.model.CAMBparams()
        par.H0        = cosmo.H0
        par.omegab    = cosmo.omb
        par.omegac    = cosmo.omc
        par.omegav    = cosmo.oml
        par.NonLinear = nonlinear

        par.InitPower.set_params(As=sips.amp,
                                 ns=sips.n_s,
                                 nrun=sips.n_r,
                                 pivot_scalar=sips.k_pivot)

        par.set_matter_power(redshifts=zvec, kmax=kmax)

        self.par = par

        # Calculate the matter power spectrum
        camb_data = camb.get_results(par)
        p_kz = camb_data.get_matter_power_spectrum(minkh=1e-6, maxkh=kmax, npoints=npoints)
        kh, z, pk = camb_data.get_matter_power_spectrum(minkh=1e-6, maxkh=kmax, npoints=npoints)
        self.arr_z = z
        self.arr_k = kh * (self.cosmo.h)
        self.mat_p = pk / (self.cosmo.h)**3
        for iz, z in enumerate(self.arr_z):
            self.mat_p[iz, :] *= (1. + z)**2

        self.spl_p = scipy.interpolate.RectBivariateSpline(self.arr_z, np.log(self.arr_k), self.mat_p, kx=3, ky=3, s=0)

        self.kmin = self.arr_k[+0] * 0.999
        self.kmax = self.arr_k[-1] * 1.001

        self.zmin = np.min(zvec)
        self.zmax = np.max(zvec)
Example #39
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))
Example #40
0
def get_bao_dr12(params=None,engine='camb',de='ppf',rs_fid = 147.78,zs=[0.38,0.51,0.61]):
    import camb
    params = map_params(params,engine=engine)
    zs = np.asarray(zs)
    if engine=='camb':
        pars = set_camb_pars(params=params,de=de)
        results = camb.get_results(pars)
        rdrag = results.get_derived_params()['rdrag']
        rs_rescale = 1 / rs_fid
        rs = rdrag * rs_rescale
        retdict = {}
        retdict["DM_over_rs"] = np.zeros((zs.size,))
        retdict["bao_Hz_rs"] = np.zeros((zs.size,))
        for i,z in enumerate(zs):
            retdict["DM_over_rs"][i] = (1 + z) * results.angular_diameter_distance(z) / rs
            retdict["bao_Hz_rs"][i] = results.hubble_parameter(z) * rs
    else:
        raise NotImplementedError
    return zs,retdict
Example #41
0
def matterps2corr2esd(redshift, cosmology):
    z = redshift
    H_null, Ombh2, Omch2 = cosmology
    pars = camb.CAMBparams()
    pars.set_cosmology(H0=H_null, ombh2=Ombh2, omch2=Omch2)
    pars.set_dark_energy()
    pars.InitPower.set_params(ns=nps)
    pars.set_matter_power(redshifts=[0.0, z], kmax=2.0)

    #Linear spectra--------
    pars.NonLinear = model.NonLinear_none
    results = camb.get_results(pars)
    kh, znon, pk = results.get_matter_power_spectrum(minkh=1e-4,
                                                     maxkh=1000.0,
                                                     npoints=1024)
    xi = mcfit.P2xi(kh, l=0)
    #Calculate corr from PS------
    nxx = 50
    Rmin = -2.0
    Rmax = 2.5
    rr = np.logspace(Rmin, Rmax, nxx)
    rx, corrfunc = xi(pk, extrap=True)
    corr = np.interp(rr, rx, corrfunc[0, :])
    #Calculate ESD from corr------
    nxx = 300
    Rp = np.linspace(0.1, 300., nxx)
    ESD = np.zeros(nxx)

    for i in range(nxx):
        tmp1 = integrate.quad(simR,
                              Rp[i] + 0.001,
                              90.0,
                              args=(rr, corr, Rp[i]),
                              epsabs=1e-4)
        tmp2 = integrate.quad(simLR,
                              0.001,
                              Rp[i],
                              args=(rr, corr, Rp[i]),
                              epsabs=1e-4)
        ESD[i] = (4.0 * tmp2[0] / Rp[i] / Rp[i] - 2.0 *
                  tmp1[0]) * omega_m * h  #Luo et al 2017ApJ 836 38L EQ. 39-40

    return {'Rp': Rp, 'ESD': ESD}
Example #42
0
def getcorrCAMB(theta, data, centers):
    Nz, be = np.histogram(data['z'], bins=8, range=(0.05, 0.15))
    lmax = 3750
    pars = camb.CAMBparams()  # Set up the CAMB parameters
    h = 0.675  # Planck value for h (Hubble parameter)
    Ob = 0.044  # Planck value for Omega_b (Baryon energy density)
    Om = theta[1]  # Planck value for Omega_m (Matter energy density)
    Oc = Om - Ob  # Value for Omega_c (Cold dark matter energy density)
    As = 2e-9  # Amplitude of initial fluctuations
    ns = 0.965  # Scalar index
    pars.set_cosmology(H0=100 * h, ombh2=Ob * h**2, omch2=Oc *
                       h**2)  # This sets the cosmological parameters
    pars.InitPower.set_params(
        As=As, ns=ns)  # This also sets the cosmological parameters
    pars.set_for_lmax(lmax, lens_potential_accuracy=1)  # Set the maximum ell
    #set Want_CMB to true if you also want CMB spectra or correlations
    pars.Want_CMB = False  # We don't want the CMB
    #NonLinear_both or NonLinear_lens will use non-linear corrections
    pars.NonLinear = model.NonLinear_both  # We want non-linear corrections
    #Set up W(z) window functions, later labelled W1, W2.
    zs = 0.5 * (be[1:] + be[:-1])  #z # Range of zs
    W = Nz  # Window function
    pars.SourceWindows = [
        SplinedSourceWindow(source_type='counts', bias=theta[0], z=zs, W=W)
    ]  # Set up the window function

    results = camb.get_results(pars)
    cls = results.get_source_cls_dict()
    ls = np.arange(2, lmax + 1)

    angles = centers  #np.logspace(-2, 1) # Angles from 0.01 to 10 deg
    x = np.cos(np.radians(
        angles))  # Convert them to radians and compute cosine to passs to CAMB
    cls_in = np.array([
        cls['W1xW1'][1:lmax + 1],
        np.zeros(lmax),
        np.zeros(lmax),
        np.zeros(lmax)
    ]).T
    #cl2corr needs TT (temperature/density), EE (E-mode), BB (B-mode), TE (Temperature-polarization cross correlation) -> we only care about TT
    w_camb = camb.correlations.cl2corr(cls_in, x)

    return w_camb
def get_cmb( Nside, Npix ):
    pars = camb.CAMBparams()
    #This function sets up CosmoMC-like settings, with one massive neutrino and helium set using BBN consistency
    pars.set_cosmology( H0 = 67.74, ombh2 = 0.0223, omch2 = 0.1188, omk = 0, tau = 0.066 ) ;
    # Tensors on
    pars.WantTensors = True
    pars.InitPower.set_params( ns = 0.9667, r = 0.5 ) ;
    # Power spectrum will be 3 * Nside - 1
    pars.set_for_lmax( 3 * Nside - 1, lens_potential_accuracy=0);
    #calculate results for these parameters
    results = camb.get_results(pars) ;
    #get dictionary of CAMB power spectra
    cl_total = results.get_total_cls( 3 * Nside - 1 )
    # Needs to be re-arranged
    tmp = [ cl_total[ :, 0 ] , cl_total[ :, 1 ], cl_total[ :, 2 ], cl_total[ :, 3 ] ]
    cmb_synfast = hp.synfast( tmp, Nside, new = True )
    # K->micro K!
    cmb_out = [ cmb_synfast[ 0 ][ Npix ] * 1e6, cmb_synfast[ 1 ][ Npix ] * 1e6, cmb_synfast[ 2 ][ Npix ] * 1e6 ]
    return cmb_out
Example #44
0
def A(x, pars, lmax=2000):
    print(pars)
    # Gets the spectrum for a set of parameters
    H0, ombh2, omch2, As, ns, tau = pars
    pars = camb.CAMBparams()
    pars.set_cosmology(H0=H0,
                       ombh2=ombh2,
                       omch2=omch2,
                       mnu=0.06,
                       omk=0,
                       tau=tau)
    pars.InitPower.set_params(As=As, ns=ns, r=0)
    pars.set_for_lmax(lmax, lens_potential_accuracy=0)
    results = camb.get_results(pars)
    powers = results.get_cmb_power_spectra(pars, CMB_unit='muK')
    cmb = powers['total']
    tt = cmb[:, 0]
    print('done')
    return tt[x.astype(int)]
Example #45
0
    def testSymbolic(self):
        if fast:
            return
        import camb.symbolic as s

        monopole_source, ISW, doppler, quadrupole_source = s.get_scalar_temperature_sources()
        temp_source = monopole_source + ISW + doppler + quadrupole_source

        pars = camb.set_params(H0=67.5, ombh2=0.022, omch2=0.122, As=2e-9, ns=0.95, omk=0.1)
        data = camb.get_background(pars)
        tau = np.linspace(1, 1200, 300)
        ks = [0.001, 0.05, 1]
        monopole2 = s.make_frame_invariant(s.newtonian_gauge(monopole_source), 'Newtonian')
        Delta_c_N = s.make_frame_invariant(s.Delta_c, 'Newtonian')
        Delta_c_N2 = s.make_frame_invariant(s.synchronous_gauge(Delta_c_N), 'CDM')

        ev = data.get_time_evolution(ks, tau, ['delta_photon', s.Delta_g, Delta_c_N, Delta_c_N2,
                                               monopole_source, monopole2,
                                               temp_source, 'T_source'])
        self.assertTrue(np.allclose(ev[:, :, 0], ev[:, :, 1]))
        self.assertTrue(np.allclose(ev[:, :, 2], ev[:, :, 3]))
        self.assertTrue(np.allclose(ev[:, :, 4], ev[:, :, 5]))
        self.assertTrue(np.allclose(ev[:, :, 6], ev[:, :, 7]))

        pars = camb.set_params(H0=67.5, ombh2=0.022, omch2=0.122, As=2e-9, ns=0.95)
        pars.set_accuracy(lSampleBoost=2)
        try:
            pars.set_custom_scalar_sources([monopole_source + ISW + doppler + quadrupole_source,
                                            s.scalar_E_source], source_names=['T2', 'E2'],
                                           source_ell_scales={'E2': 2})
            data = camb.get_results(pars)
            dic = data.get_cmb_unlensed_scalar_array_dict(CMB_unit='muK')
            self.assertTrue(np.all(np.abs(dic['T2xT2'][2:2000] / dic['TxT'][2:2000] - 1) < 1e-3))
            self.assertTrue(np.all(np.abs(dic['TxT2'][2:2000] / dic['TxT'][2:2000] - 1) < 1e-3))
            # default interpolation errors much worse for E
            self.assertTrue(np.all(np.abs(dic['E2xE2'][10:2000] / dic['ExE'][10:2000] - 1) < 2e-3))
            self.assertTrue(np.all(np.abs(dic['E2xE'][10:2000] / dic['ExE'][10:2000] - 1) < 2e-3))
            dic1 = data.get_cmb_power_spectra(CMB_unit='muK')
            self.assertTrue(np.allclose(dic1['unlensed_scalar'][2:2000, 1], dic['ExE'][2:2000]))
        finally:
            pars.set_accuracy(lSampleBoost=1)

        s.internal_consistency_checks()
Example #46
0
 def test_quintessence(self):
     n = 3
     # set zc and fde_zc
     pars = camb.set_params(ombh2=0.022,
                            omch2=0.122,
                            thetastar=0.01044341764253,
                            dark_energy_model='EarlyQuintessence',
                            m=8e-53,
                            f=0.05,
                            n=n,
                            theta_i=3.1,
                            use_zc=True,
                            zc=1e4,
                            fde_zc=0.1)
     camb.get_background(pars)
     results = camb.get_results(pars)
     self.assertAlmostEqual(results.get_derived_params()['thetastar'],
                            1.044341764253,
                            delta=1e-5)
Example #47
0
def get_camb_results(pars,zs=None,fast_camb=False):
    """Call camb.get_results, the slowest function in CAMB calls.
        - pars: CAMBparams object describing the cosmology
        - zs (optional): redshifts where we want to evaluate the linear power
        - fast_camb (optional): tune settings for fast computations"""

    if zs is not None:
        # check if we want to use fast version
        if fast_camb:
            set_fast_camb_options(pars)
            kmax_Mpc=camb_fit_kmax_Mpc
        else:
            kmax_Mpc=camb_kmax_Mpc

        # camb_extra_kmax will allow to evaluate the power later on at kmax
        pars.set_matter_power(redshifts=zs,kmax=camb_extra_kmax*kmax_Mpc,
                nonlinear=False,silent=True)

    return camb.get_results(pars)
Example #48
0
    def testSymbolic(self):
        if fast: return
        import camb.symbolic as s

        monopole_source, ISW, doppler, quadrupole_source = s.get_scalar_temperature_sources()
        temp_source = monopole_source + ISW + doppler + quadrupole_source

        pars = camb.set_params(H0=67.5, ombh2=0.022, omch2=0.122, As=2e-9, ns=0.95, omk=0.1)
        data = camb.get_background(pars)
        tau = np.linspace(1, 1200, 300)
        ks = [0.001, 0.05, 1]
        monopole2 = s.make_frame_invariant(s.newtonian_gauge(monopole_source), 'Newtonian')
        Delta_c_N = s.make_frame_invariant(s.Delta_c, 'Newtonian')
        Delta_c_N2 = s.make_frame_invariant(s.synchronous_gauge(Delta_c_N), 'CDM')

        ev = data.get_time_evolution(ks, tau, ['delta_photon', s.Delta_g, Delta_c_N, Delta_c_N2,
                                               monopole_source, monopole2,
                                               temp_source, 'T_source'])
        self.assertTrue(np.allclose(ev[:, :, 0], ev[:, :, 1]))
        self.assertTrue(np.allclose(ev[:, :, 2], ev[:, :, 3]))
        self.assertTrue(np.allclose(ev[:, :, 4], ev[:, :, 5]))
        self.assertTrue(np.allclose(ev[:, :, 6], ev[:, :, 7]))

        pars = camb.set_params(H0=67.5, ombh2=0.022, omch2=0.122, As=2e-9, ns=0.95)
        pars.set_accuracy(lSampleBoost=2)
        try:
            pars.set_custom_scalar_sources([monopole_source + ISW + doppler + quadrupole_source,
                                            s.scalar_E_source], source_names=['T2', 'E2'],
                                           source_ell_scales={'E2': 2})
            data = camb.get_results(pars)
            dic = data.get_cmb_unlensed_scalar_array_dict(CMB_unit='muK')
            self.assertTrue(np.all(np.abs(dic['T2xT2'][2:2000] / dic['TxT'][2:2000] - 1) < 1e-3))
            self.assertTrue(np.all(np.abs(dic['TxT2'][2:2000] / dic['TxT'][2:2000] - 1) < 1e-3))
            # default interpolation errors much worse for E
            self.assertTrue(np.all(np.abs(dic['E2xE2'][10:2000] / dic['ExE'][10:2000] - 1) < 2e-3))
            self.assertTrue(np.all(np.abs(dic['E2xE'][10:2000] / dic['ExE'][10:2000] - 1) < 2e-3))
            dic1 = data.get_cmb_power_spectra(CMB_unit='muK')
            self.assertTrue(np.allclose(dic1['unlensed_scalar'][2:2000, 1], dic['ExE'][2:2000]))
        finally:
            pars.set_accuracy(lSampleBoost=1)

        s.internal_consistency_checks()
Example #49
0
	def PKNL_CAMB_MultipleRedshift(self, kk, zz):
		if len(zz)<2:
			print "zz must be a list, if you need to compute \
			only for single redshift, use PowerSpectrumNonLinear_SingleRedshift"
			exit()
		pars = camb.CAMBparams()
		pars.set_cosmology(H0=self.h*100, ombh2=self.Omega_b*self.h**2, \
								omch2=(self.Omega_m-self.Omega_b)*self.h**2)
		pars.set_dark_energy(w=self.w0) #re-set defaults
		pars.InitPower.set_params(ns=self.n_s)
		pars.set_matter_power(redshifts=zz, kmax=10.0)
		results = camb.get_results(pars)
		pars.NonLinear = camb.model.NonLinear_both
		results.calc_power_spectra(pars)
		kh_nonlin, z_nonlin, pk_nonlin = \
		results.get_matter_power_spectrum(minkh=1e-4,maxkh=10.0,npoints=500)
		s8 = np.array(results.get_sigma8())
		for i in range(len(s8)):
			pk_nonlin[:,i] = pk_nonlin[:,i]*(self.Sigma_8*np.interp(zz[i], self.z_gf, self.gff)/s8[i])**2
		function = interp2d(kh_nonlin, z_nonlin, pk_nonlin)
		return np.transpose(function(kk, zz))
Example #50
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)

        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(redshifts=[0.0, 0.17, 3.1])
        pars.NonLinear = model.NonLinear_none
        data = camb.get_results(pars)

        #        transfer = data.get_cmb_transfer_data()

        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.247, 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.697, 2)
        self.assertAlmostEqual(pk2[-2][-4], 53.47, 2)

        camb.set_feedback_level(0)
        cls = data.get_cmb_power_spectra(pars)

        cls_tot = data.get_total_cls(2000)
        cls_scal = data.get_unlensed_scalar_cls(2000)
        cls_tensor = data.get_tensor_cls(2000)
        cls_lensed = data.get_lensed_scalar_cls(2000)
        cls_phi = data.get_lens_potential_cls(2000)
    def __init__(self, Omega_m=0.3175, Omega_b=0.049, h=0.6711, ns=0.9624, s8=None,
                 Mnu=0.0, As=2.13e-9, Omega_k=0.0, 
                 pivot_scalar=0.05, pivot_tensor=0.05, 
                 Nnu=3, hierarchy='degenerate', Neff=3.046, tau=None,
                 redshifts=[0, 0.5, 1, 2, 3], kmax=10.0, k_per_logint=50,
                 verbose=False):

        Omega_c  = Omega_m - Omega_b - Mnu/(93.14*h**2)
        Omega_cb = Omega_c + Omega_b

        pars = camb.CAMBparams()

        # set accuracy of the calculation
        pars.set_accuracy(AccuracyBoost=5.0, lSampleBoost=5.0, 
                          lAccuracyBoost=5.0, HighAccuracyDefault=True, 
                          DoLateRadTruncation=True)

        # set value of the cosmological parameters
        pars.set_cosmology(H0=h*100.0, ombh2=Omega_b*h**2, omch2=Omega_c*h**2, 
                           mnu=Mnu, omk=Omega_k, 
                           neutrino_hierarchy=hierarchy, 
                           num_massive_neutrinos=Nnu, nnu=Neff,
                           tau=tau)
                   
        # set the value of the primordial power spectrum parameters
        pars.InitPower.set_params(As=As, ns=ns, 
                                  pivot_scalar=pivot_scalar, 
                                  pivot_tensor=pivot_tensor)
    
        # set redshifts, k-range and k-sampling
        pars.set_matter_power(redshifts=redshifts, kmax=kmax, 
                              k_per_logint=k_per_logint)

        # compute results
        results = camb.get_results(pars)

        # get raw matter P(k) and transfer functions with weird k-binning
        #k, zs, Pk = results.get_linear_matter_power_spectrum()
        #Tk        = (results.get_matter_transfer_data()).transfer_data

        # interpolate to get Pmm, Pcc...etc
        k,z,Pmm = results.get_matter_power_spectrum(minkh=2e-5, maxkh=kmax, 
                                                    npoints=500, var1=7, var2=7,
                                                    have_power_spectra=True, 
                                                    params=None)

        k,z,Pcc = results.get_matter_power_spectrum(minkh=2e-5, maxkh=kmax, 
                                                    npoints=500, var1=2, var2=2,
                                                    have_power_spectra=True, 
                                                    params=None)

        k,z,Pbb = results.get_matter_power_spectrum(minkh=2e-5, maxkh=kmax, 
                                                    npoints=500, var1=3, var2=3,
                                                    have_power_spectra=True, 
                                                    params=None)

        k,z,Pcb = results.get_matter_power_spectrum(minkh=2e-5, maxkh=kmax, 
                                                    npoints=500, var1=2, var2=3,
                                                    have_power_spectra=True, 
                                                    params=None)

        Pcb = (Omega_c**2*Pcc + Omega_b**2*Pbb +\
               2.0*Omega_b*Omega_c*Pcb)/Omega_cb**2

        k,z,Pnn = results.get_matter_power_spectrum(minkh=2e-5, maxkh=kmax, 
                                                    npoints=500, var1=6, var2=6,
                                                    have_power_spectra=True, 
                                                    params=None)

        # rescale by sigma_8
        s8_linear = results.get_sigma8()[-1]
        if s8!=None and z[0]!=0.0:
            raise Exception('To rescale by s8 we need to generate the linear Pk at z=0')
        factor = (s8/s8_linear)**2

        # get sigma_8 and Hz in km/s/(kpc/h)
        self.s8 = np.array(results.get_sigma8())[::-1]*np.sqrt(factor)
        self.Hz = np.array([results.hubble_parameter(red) for red in z])

        self.z    = z;    self.k   = k 
        self.Pkmm = Pmm*factor;  self.Pknn = Pnn*factor
        self.Pkcc = Pcc*factor;  self.Pkbb = Pbb*factor;  self.Pkcb = Pcb*factor
        
        if verbose:  print pars
Example #52
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)

        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(redshifts=[0., 0.17, 3.1])
        pars.NonLinear = model.NonLinear_none
        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, 4)
        self.assertAlmostEqual(s8[2], 0.80044, 4)

        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.697, 2)
        self.assertAlmostEqual(pk2[-2][-4], 53.47, 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], 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)
        camb.set_halofit_version('mead')
        _, _, pk = results.get_nonlinear_matter_power_spectrum(params=pars, var1='delta_cdm', var2='delta_cdm')
        self.assertTrue(np.abs(pk[0][160] / 232.08 - 1) < 1e-3)

        lmax = 4000
        pars.set_for_lmax(lmax)
        cls = data.get_cmb_power_spectra(pars)
        cls_tot = data.get_total_cls(2000)
        cls_scal = data.get_unlensed_scalar_cls(2500)
        cls_tensor = data.get_tensor_cls(2000)
        cls_lensed = data.get_lensed_scalar_cls(3000)
        cls_phi = 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)
        self.assertTrue(np.all(np.abs(cls_lensed2[2:2000, 2] / cls_lensed[2:2000, 2] - 1) < 1e-3))
        self.assertTrue(np.all(np.abs(cls_lensed2[2:3000, 0] / cls_lensed[2:3000, 0] - 1) < 1e-3))
        self.assertTrue(np.all(np.abs(cls_lensed2[2:3000, 1] / cls_lensed[2:3000, 1] - 1) < 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))


# In[20]:

import camb
from camb import model, initialpower
#Set up a new set of parameters for CAMB
pars = camb.CAMBparams()
#This function sets up CosmoMC-like settings, with one massive neutrino and helium set using BBN consistency
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)
pars.set_for_lmax(1100, lens_potential_accuracy=0);

#calculate results for these parameters
results = camb.get_results(pars)

#get dictionary of CAMB power spectra
powers =results.get_cmb_power_spectra(pars)
unlencl = powers['unlensed_scalar']

cls0 = unlencl[:,0][2:1101]
print(len(cls0))


# In[21]:

# 
# Multiply by 1e10 to avoid underflow
#
Example #54
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)

        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)
Example #55
0
File: infl.py Project: tdaylan/tdgu
h5f.create_dataset('reds', data=redssour)
h5f.create_dataset('adis', data=adis)
h5f.create_dataset('adistdim', data=adistdim)
h5f.close()


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)
pars.set_for_lmax(2500, lens_potential_accuracy=0);

path = '/Users/tansu/Desktop/infl/'
os.system('mkdir -p %s' % path)

#os.environ["FERM_IGAL_DATA_PATH"]
cambdata = camb.get_results(pars)
psec = cambdata.get_cmb_power_spectra(pars)
psectotl = psec['total']
pseculen = psec['unlensed_scalar']

ls = np.arange(psectotl.shape[0])
fig, ax = plt.subplots(2,2, figsize = (12,12))
ax[0,0].plot(ls,psectotl[:,0], color='k')
ax[0,0].plot(ls,pseculen[:,0], color='r')
ax[0,0].set_title('TT')
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')
Example #56
0
    def testInitialPower(self):
        pars = camb.CAMBparams()
        pars.set_cosmology(H0=67)
        import ctypes
        P = camb.InitialPowerLaw()
        P2 = ctypes.pointer(P)
        self.assertEqual(P.As, pars.InitPower.As)
        As = 1.8e-9
        ns = 0.8
        P.set_params(As=As, ns=ns)
        self.assertEqual(P.As, As)
        self.assertEqual(P2.contents.As, As)

        pars2 = camb.CAMBparams()
        pars2.set_cosmology(H0=67)
        pars2.InitPower.set_params(As=1.7e-9, ns=ns)
        self.assertEqual(pars2.InitPower.As, 1.7e-9)
        pars.set_initial_power(pars2.InitPower)
        self.assertEqual(pars.InitPower.As, 1.7e-9)
        pars.set_initial_power(P)
        self.assertEqual(pars.InitPower.As, As)

        ks = np.logspace(-5.5, 2, 1000)
        pk = (ks / P.pivot_scalar) ** (ns - 1) * As
        pars2.set_initial_power_table(ks, pk)
        self.assertAlmostEqual(pars2.scalar_power(1.1), pars.scalar_power(1.1), delta=As * 1e-4)
        sp = camb.SplinedInitialPower(ks=ks, PK=pk)
        pars2.set_initial_power(sp)
        self.assertAlmostEqual(pars2.scalar_power(1.1), pars.scalar_power(1.1), delta=As * 1e-4)
        self.assertFalse(sp.has_tensors())
        self.assertFalse(pars2.InitPower.has_tensors())

        sp = camb.SplinedInitialPower()
        sp.set_scalar_log_regular(10 ** (-5.5), 10. ** 2, pk)
        pars2.set_initial_power(sp)
        self.assertAlmostEqual(pars2.scalar_power(1.1), pars.scalar_power(1.1), delta=As * 1e-4)

        sp.set_tensor_log_regular(10 ** (-5.5), 10. ** 2, pk)
        pars2.set_initial_power(sp)
        self.assertAlmostEqual(pars2.tensor_power(1.1), pars.scalar_power(1.1), delta=As * 1e-4)
        self.assertTrue(sp.has_tensors())
        sp.set_tensor_table([], [])
        self.assertFalse(sp.has_tensors())
        pars2.set_initial_power(sp)

        results = camb.get_results(pars2)
        cl = results.get_lensed_scalar_cls(CMB_unit='muK')
        pars.InitPower.set_params(As=As, ns=ns)
        results2 = camb.get_results(pars)
        cl2 = results2.get_lensed_scalar_cls(CMB_unit='muK')
        self.assertTrue(np.allclose(cl, cl2, rtol=1e-4))
        P = camb.InitialPowerLaw(As=2.1e-9, ns=0.9)
        pars2.set_initial_power(P)
        pars.InitPower.set_params(As=2.1e-9, ns=0.9)
        self.assertAlmostEqual(pars2.scalar_power(1.1), pars.scalar_power(1.1), delta=As * 1e-4)

        def PK(k, As, ns):
            return As * (k / 0.05) ** (ns - 1) * (1 + 0.1 * np.sin(10 * k))

        pars.set_initial_power_function(PK, args=(3e-9, 0.95))
        P = pars.scalar_power(ks)
        np.testing.assert_almost_equal(P, PK(ks, 3e-9, 0.95), decimal=4)
Example #57
0
 def get_camb_results(self):
     self.cambresults = camb.get_results(self.cambparams)
     self.totalCl = self.cambresults.get_cmb_power_spectra(self.cambparams)['total']
     return self.cambresults