Beispiel #1
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))
Beispiel #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))
Beispiel #3
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)
Beispiel #4
0
	def __init__(self, params=None, smica_path=None):
		# Setting cosmo params
		if params is None:
			params = def_cosmo.copy()
		else:
			for key, val in def_cosmo.iteritems():
				params.setdefault(key,val)
		self.params = params.copy()

		#Let's initialize CAMB for distances, growth factor ders, and CMB TT spectrum
		self.pars = camb.CAMBparams()
		self.pars.set_cosmology(H0=self.params['H0'], ombh2=self.params['ombh2'], omch2=self.params['omch2'], mnu=self.params['mnu'], omk=self.params['omk'], tau=self.params['tau'])
		self.pars.InitPower.set_params(As=params['As'], ns=params['ns'], r=0)
		self.pars.set_for_lmax(2500, lens_potential_accuracy=0);
		results = camb.get_results(self.pars)
		self.bkd = camb.get_background(self.pars)
		self.eta_star = self.bkd.conformal_time(1089) # conformal time at recombination

		cmb = results.get_cmb_power_spectra(self.pars,lmax=1000, raw_cl=True)
		self.TCMBmuK = 2.726e6
		self.cltt = np.copy(cmb['lensed_scalar'][:,0])*self.TCMBmuK**2 # muK^2
		
		self.zmin = 0
		self.zmax = 8
		self.nz   = 300
		self.z = np.linspace(self.zmin,self.zmax,self.nz)
		ev = results.get_redshift_evolution(1e-2, self.z, ['growth'])

		self.growth_eta = UnivariateSpline(self.bkd.conformal_time(self.z[::-1]), ev[:, 0][::-1], ext=3)
		self.der_growtg_eta = self.growth_eta.derivative()
	
		if smica_path is None:
			self.smica_path = '/Users/fbianchini/Research/pSZ/data/smica_nside512.fits'
		self.smica_init = False
Beispiel #5
0
def GetBackgroundFuncs(samples):
    ixs = samples.randomSingleSamples_indices()[::40]
    DMs = np.zeros((len(ixs), len(redshifts)))
    Hs = np.zeros(DMs.shape)
    rsDV = np.zeros(DMs.shape)
    camb.set_z_outputs(redshifts)
    for i, ix in enumerate(ixs):
        print(i, ix)
        dic = samples.getParamSampleDict(ix)
        pars = get_camb_params(dic)
        results = camb.get_background(pars)
        bao = results.get_background_outputs()
        rsDV[i, :] = 1 / bao[:, 0]
        DMs[i, :] = bao[:, 2] * (1 + reds)
        Hs[i, :] = bao[:, 1]

    Hmeans = np.zeros(len(redshifts))
    Herrs = np.zeros(len(redshifts))
    DMmeans = np.zeros(len(redshifts))
    DMerrs = np.zeros(len(redshifts))
    for i, z in enumerate(redshifts):
        Hmeans[i] = np.mean(Hs[:, i]) / (1 + z)
        Herrs[i] = np.std(Hs[:, i]) / (1 + z)
        DMmeans[i] = np.mean(DMs[:, i])
        DMerrs[i] = np.std(DMs[:, i])

    Hinterp = UnivariateSpline([0] + redshifts, [samples.mean('H0')] + list(Hmeans), s=0)
    DMinterp = UnivariateSpline([0] + redshifts, [0] + list(DMmeans), s=0)
    Herrinterp = UnivariateSpline([0] + redshifts, [samples.std('H0')] + list(Herrs), s=0)
    DMerrinterp = UnivariateSpline([0] + redshifts, [0] + list(DMerrs), s=0)
    return Hinterp, Herrinterp, DMinterp, DMerrinterp, rsDV
Beispiel #6
0
 def _init_cosmology(self,params,halofit):
     try:
         theta = params['theta100']/100.
         H0 = None
         print("WARNING: Using theta100 parameterization. H0 ignored.")
     except:
         H0 = params['H0']
         theta = None
     try:        
         omm = params['omm']        
         h = params['H0']/100.      
         params['omch2'] = omm*h**2-params['ombh2']     
         print("WARNING: omm specified. Ignoring omch2.")       
     except:        
         pass        
     self.pars = camb.set_params(ns=params['ns'],As=params['As'],H0=H0,
                                 cosmomc_theta=theta,ombh2=params['ombh2'],
                                 omch2=params['omch2'], mnu=params['mnu'],
                                 tau=params['tau'],nnu=params['nnu'],
                                 num_massive_neutrinos=
                                 params['num_massive_neutrinos'],
                                 w=params['w0'],wa=params['wa'],
                                 dark_energy_model='ppf',
                                 halofit_version=self.p['default_halofit'] if halofit is None else halofit,
                                 AccuracyBoost=2)
     self.results = camb.get_background(self.pars)
     self.params = params
     self.h = self.params['H0']/100.
     omh2 = self.params['omch2']+self.params['ombh2'] # FIXME: neutrinos
     self.om0 = omh2 / (self.params['H0']/100.)**2.        
     try: self.as8 = self.params['as8']        
     except: self.as8 = 1
Beispiel #7
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 
Beispiel #8
0
def GetBackgroundFuncs(samples):
    ixs = samples.randomSingleSamples_indices()[::40]
    DMs = np.zeros((len(ixs), len(redshifts)))
    Hs = np.zeros(DMs.shape)
    rsDV = np.zeros(DMs.shape)
    camb.set_z_outputs(redshifts)
    for i, ix in enumerate(ixs):
        print(i, ix)
        dic = samples.getParamSampleDict(ix)
        pars = get_camb_params(dic)
        results = camb.get_background(pars)
        bao = results.get_background_outputs()
        rsDV[i, :] = 1 / bao[:, 0]
        DMs[i, :] = bao[:, 2] * (1 + reds)
        Hs[i, :] = bao[:, 1]

    Hmeans = np.zeros(len(redshifts))
    Herrs = np.zeros(len(redshifts))
    DMmeans = np.zeros(len(redshifts))
    DMerrs = np.zeros(len(redshifts))
    for i, z in enumerate(redshifts):
        Hmeans[i] = np.mean(Hs[:, i]) / (1 + z)
        Herrs[i] = np.std(Hs[:, i]) / (1 + z)
        DMmeans[i] = np.mean(DMs[:, i])
        DMerrs[i] = np.std(DMs[:, i])

    Hinterp = UnivariateSpline([0] + redshifts,
                               [samples.mean('H0')] + list(Hmeans),
                               s=0)
    DMinterp = UnivariateSpline([0] + redshifts, [0] + list(DMmeans), s=0)
    Herrinterp = UnivariateSpline([0] + redshifts,
                                  [samples.std('H0')] + list(Herrs),
                                  s=0)
    DMerrinterp = UnivariateSpline([0] + redshifts, [0] + list(DMerrs), s=0)
    return Hinterp, Herrinterp, DMinterp, DMerrinterp, rsDV
Beispiel #9
0
    def get_camb_theory(self, pars):
        kmax = 15 * acc
        results = camb.get_background(pars)

        k_per_logint = None
        if self.use_Weyl:
            PKWeyl = camb.get_matter_power_interpolator(
                pars,
                nonlinear=True,
                hubble_units=False,
                k_hunit=False,
                kmax=kmax,
                k_per_logint=k_per_logint,
                var1=model.Transfer_Weyl,
                var2=model.Transfer_Weyl,
                zmax=self.zmax,
                extrap_kmax=500 * acc)
        else:
            PKWeyl = None

        PKdelta = camb.get_matter_power_interpolator(pars,
                                                     nonlinear=True,
                                                     hubble_units=False,
                                                     k_hunit=False,
                                                     kmax=kmax,
                                                     k_per_logint=k_per_logint,
                                                     zmax=self.zmax,
                                                     extrap_kmax=500 * acc)
        return results, PKdelta, PKWeyl
Beispiel #10
0
def nonlin_ps(z, l_max):
    pars_nl = model.CAMBparams(NonLinear = 1, WantTransfer = True, H0=h * 100, omch2=omch2, ombh2=ombh2, YHe = YHe)
    pars_nl.DarkEnergy.set_params(w=-1.13)
    pars_nl.set_for_lmax(lmax = l_max)
    pars_nl.InitPower.set_params(ns=ns, As = 2.196e-09)
    results = camb.get_background(pars_nl)
    k = np.linspace(- 5, k_max(z, l_max), 1000)
    return get_matter_power_interpolator(pars_nl, nonlinear=True, kmax = k_max(z, l_max), k_hunit = True, hubble_units = True)
Beispiel #11
0
def r_drag_camb(omega_m,H_0,wb = 0.0225):
    pars = camb.CAMBparams()
    h = (H_0/100)
    pars.set_cosmology(H0=H_0, ombh2=wb, omch2=omega_m*h**2-wb)
    results = camb.get_background(pars)
    rd = results.get_derived_params()['rdrag']
    #print('Derived parameter dictionary: %s'%results.get_derived_params()['rdrag'])
    return rd
Beispiel #12
0
    def __init__(self, redshift=0.0, omega_m=0.3121, omega_b=0.0491, hubble=0.6751, omega_k=0.0, tau=0.063, As=2.130e-9, ns=0.9653,
                neutrino_hierarchy='degenerate', num_massive_neutrinos=1, mnu=0.06, nnu=3.046, w=-1.0, sound_speed=1.0, dark_energy_model='fluid', sigma8=None, r_s=None, r_s_type='CAMB',
                degree=13, sigma=1, weight=0.5, verbose=False):

        import camb

        self.verbose = verbose

        self.redshift = redshift
        self.omega_m = omega_m
        self.omega_b = omega_b
        self.hubble = hubble
        self.ns = ns
        self.sigma8 = sigma8
        self.degree = degree
        self.sigma = sigma
        self.weight = weight

        if (self.verbose):
            print "Using CAMB to generate matter power spectrum"

        params = camb.set_params(omch2=(omega_m-omega_b)*hubble**2, ombh2=omega_b*hubble**2, H0=100.0*hubble, omk=omega_k, tau=tau, As=As, ns=ns,
                                 neutrino_hierarchy=neutrino_hierarchy, num_massive_neutrinos=num_massive_neutrinos, mnu=mnu, nnu=nnu, 
                                 w=w, sound_speed=sound_speed, dark_energy_model=dark_energy_model)
        params.set_matter_power(redshifts=[redshift],kmax=100,accurate_massive_neutrino_transfers=True)
        results = camb.get_results(params)
        self.k, z, self.pk = results.get_matter_power_spectrum(minkh=1e-4, maxkh=100, npoints = 2000)
        self.pk = self.pk[0]

        # Normalise the input power spectrum to the current value of sigma8 if one has been passed
        if (self.sigma8 is None):
            self.sigma8 = results.get_sigma8()[0]
        else:
            pknorm = norm_pk(self.k, self.pk, self.sigma8)
            self.pk *= pknorm

        if (r_s is None):
            if (r_s_type == 'EH98'):
                self.r_s = self.EH98_rs()
                if (self.verbose):
                    print "Setting sound horizon using EH98 formulae: r_s = ", self.r_s
                    print "Note: This is only used for BAOExtractor model"
            elif (r_s_type == 'CAMB'):
                self.r_s = camb.get_background(params).get_derived_params()['rdrag']
                if (self.verbose):
                    print "Setting sound horizon using CAMB value: r_s = ", self.r_s
                    print "Note: This is only used for BAOExtractor model"
            else:
                print "r_s_type not supported (", r_s_type, "), must be either 'EH98' or 'CAMB', or you must pass in a value for r_s"
                exit()
        else:
            self.r_s = r_s
            if (self.verbose):
                print "Setting sound horizon using user-defined value: r_s = ", self.r_s     
                print "Note: This is only used for BAOExtractor model"

        self.set_pksmooth()
Beispiel #13
0
def get_interpolated():
    #For calculating large-scale structure and lensing results yourself, get a power spectrum
    #interpolation object. In this example we calculate the CMB lensing potential power
    #spectrum using the Limber approximation, using PK=camb.get_matter_power_interpolator() function.   
    #calling PK(z, k) will then get power spectrum at any k and redshift z in range.

    nz = 100 #number of steps to use for the radial/redshift integration
    kmax=10  #kmax to use
    #First set up parameters as usual
    pars = camb.CAMBparams()
    #pars.set_cosmology(H0=67.5, ombh2=0.022, omch2=0.122)
    #pars.InitPower.set_params(ns=0.965)


    pars.set_cosmology(H0=100*para5[i, 3], ombh2=para5[i, 1], omch2=para5[i, 0] - para5[i, 1], mnu=0.0, omk=0, tau=0.0)
				

    #pars.set_dark_energy(w=-1.0, sound_speed=1.0, dark_energy_model='fluid')

    # pars.set_dark_energy()  # re-set defaults

    pars.InitPower.set_params(ns=para5[i, 4], r=0)
    # pars.set_for_lmax(lmax, lens_potential_accuracy=0);


    #For Limber result, want integration over \chi (comoving radial distance), from 0 to chi_*.
    #so get background results to find chistar, set up arrage in chi, and calculate corresponding redshifts
    results= camb.get_background(pars)
    chistar = results.conformal_time(0)- model.tau_maxvis.value
    chis = np.linspace(0,chistar,nz)
    zs=results.redshift_at_comoving_radial_distance(chis)
    #Calculate array of delta_chi, and drop first and last points where things go singular
    dchis = (chis[2:]-chis[:-2])/2
    chis = chis[1:-1]
    zs = zs[1:-1]

    #Get the matter power spectrum interpolation object (based on RectBivariateSpline)
    #Here for lensing we want the power spectrum of the Weyl potential.

    #PK = camb.get_matter_power_interpolator(pars, nonlinear=True,hubble_units=False, k_hunit=False, kmax=kmax,var1=model.Transfer_Weyl,var2=model.Transfer_Weyl, zmax=zs[-1])

    PK = camb.get_matter_power_interpolator(pars, nonlinear=True, hubble_units=False, k_hunit=False, kmax=kmax, zmax = zs[-1]) 

    sigma8_camb = results.get_sigma8()  # present value of sigma_8 --- check kman, mikh etc
    #---------------------------------------------------

    sigma8_input = para5[i, 2]

    r = (sigma8_input ** 2) / (sigma8_camb ** 2) # rescale factor

    #Have a look at interpolated power spectrum results for a range of redshifts
    #Expect linear potentials to decay a bit when Lambda becomes important, and change from non-linear growth
    plt.figure(figsize=(8,5))
    #k=np.exp(np.log(10)*np.linspace(-4,5,1000))
    k = kPk[:,0]
    #zplot = [0, 0.5, 1, 4 ,20]
    zplot = [0.0]
Beispiel #14
0
    def __init__(self, H0=67.8, ombh2=0.022, omch2=0.122):
        #First set up parameters as usual
        pars = camb.CAMBparams()
        pars.set_cosmology(H0=H0, ombh2=ombh2, omch2=omch2)
        pars.InitPower.set_params(ns=0.965)
        results = camb.get_background(pars)

        self.pars = pars
        self.results = results
Beispiel #15
0
Datei: sims.py Projekt: mntw/szar
    def __init__(self,sim_path="/gpfs01/astro/workarea/msyriac/data/sims/battaglia/"):
        import camb

        self.root = sim_path
        H0 = 72.0
        om = 0.25
        ob = 0.04
        mnu = 0.
        ns = 0.96
        As = 2.e-9
        h = old_div(H0,100.)
        ombh2 = ob*h**2.
        omh2 = om*h**2.
        omch2 = omh2-ombh2
        self.h = h

        # cosmology for distances
        pars = camb.CAMBparams()
        pars.set_cosmology(H0=H0, ombh2=ombh2, omch2=omch2, mnu=mnu)
        pars.InitPower.set_params(ns=ns,As=As)
        self.results= camb.get_background(pars)

        # Snap to  Z
        alist = np.loadtxt(self.root + 'outputSel.txt')
        zlist = np.array((old_div(1.,alist))-1.)
        snaplist = np.arange(55,55-len(zlist),-1)
        self.snapToZ = lambda s: zlist[snaplist==s][0] 
        self.allSnaps = list(range(54,34,-1))

        # True masses : THIS NEEDS DEBUGGING
        self.NumClust= 300
        self.trueM500 = {}
        self.trueR500 = {}
        for snapNum in self.allSnaps:
            snap = str(snapNum)
            f1 = self.root+'cluster_image_info/CLUSTER_MAP_INFO2PBC.L165.256.FBN2_'+snap+'500.d'
            with open(f1, 'rb') as fd:
                temp = np.fromfile(file=fd, dtype=np.float32)
            data = np.reshape(temp,(self.NumClust,4))

            self.trueM500[snap] = data[:,2]*1.e10 /h # Msun   #/h
            self.trueR500[snap] = data[:,3]*(1.+self.snapToZ(snapNum))/1.e3 #/ self.cc.h # physical Kpc/h -> comoving Mpc R500
        
        # File names

        self.files = {}
        self.files['star'] = lambda massIndex, snap: self.root + "GEN_Cluster_MassStar_"+str(massIndex)+"L165.256.FBN2_snap"+str(snap)+"_comovFINE.d"
        self.files['dm'] = lambda massIndex, snap: self.root + "GEN_Cluster_MassDM_"+str(massIndex)+"L165.256.FBN2_snap"+str(snap)+"_comovFINE.d"
        self.files['gas'] = lambda massIndex, snap: self.root + "GEN_Cluster_MassGas_"+str(massIndex)+"L165.256.FBN2_snap"+str(snap)+"_comovFINE.d"
        self.files['y'] = lambda massIndex, snap: self.root + "GEN_Cluster_"+str(massIndex)+"L165.256.FBN2_snap"+str(snap)+"_comovFINE.d"
        self.files['ksz'] = lambda massIndex, snap: self.root + "GEN_Cluster_kSZ_"+str(massIndex)+"L165.256.FBN2_snap"+str(snap)+"_comovFINE.d"
        self.files['kszN'] = lambda massIndex, snap: self.root + "GEN_Cluster_kSZ_"+str(massIndex)+"L165.256.FBN2_snap"+str(snap)+"MAT2.d"

        self.PIX = 2048
Beispiel #16
0
def getPKinterp(nz=100, kmax=10, myVar=model.Transfer_tot):
    """
    example code from http://camb.readthedocs.io/en/latest/CAMBdemo.html
      (modified to have nz,kmax,myVar as inputs)
    Purpose:
      For calculating large-scale structure and lensing results yourself, get a power spectrum
      interpolation object. In this example we calculate the CMB lensing potential power
      spectrum using the Limber approximation, using PK=camb.get_matter_power_interpolator() function.
      calling PK(z, k) will then get power spectrum at any k and redshift z in range.
    Inputs:
      nz:   number of steps to use for the radial/redshift integration
      kmax: kmax to use
      myVar: the variable to get autopower spectrum of
        default: model.Transfer_tot for delta_tot
    Returns:
      the PK(z,k) interpolator
      chistar
      chis (array of chi values)
      dchis (delta chi array)
      zs (redshift array)
      pars (CAMB parameters)
  """
    #First set up parameters as usual
    #pars = camb.CAMBparams()
    #pars.set_cosmology(H0=67.5, ombh2=0.022, omch2=0.122)
    #pars.InitPower.set_params(ns=0.965)

    pars = getPars()

    #For Limber result, want integration over \chi (comoving radial distance), from 0 to chi_*.
    #so get background results to find chistar, set up arrage in chi, and calculate corresponding redshifts
    results = camb.get_background(pars)
    chistar = results.conformal_time(0) - model.tau_maxvis.value
    chis = np.linspace(0, chistar, nz)
    zs = results.redshift_at_comoving_radial_distance(chis)
    #Calculate array of delta_chi, and drop first and last points where things go singular
    dchis = (chis[2:] - chis[:-2]) / 2
    chis = chis[1:-1]
    zs = zs[1:-1]

    #Get the matter power spectrum interpolation object (based on RectBivariateSpline).
    #Here for lensing we want the power spectrum of the Weyl potential.
    PK = camb.get_matter_power_interpolator(pars,
                                            nonlinear=True,
                                            hubble_units=False,
                                            k_hunit=False,
                                            kmax=kmax,
                                            var1=myVar,
                                            var2=myVar,
                                            zmax=zs[-1])

    return PK, chistar, chis, dchis, zs, pars
Beispiel #17
0
def lin_ps(z, l_max):
    pars = model.CAMBparams(NonLinear=0,
                            WantTransfer=True,
                            H0=h * 100,
                            omch2=omch2,
                            ombh2=ombh2,
                            YHe=YHe)
    pars.DarkEnergy.set_params(w=-1.13)
    pars.set_for_lmax(lmax=l_max)
    pars.InitPower.set_params(ns=ns, As=2.196e-09)
    results = camb.get_background(pars)
    PK = get_matter_power_interpolator(pars,
                                       nonlinear=False,
                                       kmax=k_max(z, l_max),
                                       k_hunit=True,
                                       hubble_units=True)
    return PK.P(z, k)
Beispiel #18
0
def nonlin_ps(z, l_max):
    pars_nl = model.CAMBparams(NonLinear=1,
                               WantTransfer=True,
                               H0=67.3,
                               omch2=0.1199,
                               ombh2=0.02205,
                               YHe=0.24770)
    pars_nl.DarkEnergy.set_params(w=-1.13)
    pars_nl.set_for_lmax(lmax=l_max)
    pars_nl.InitPower.set_params(ns=0.9603, As=2.196e-09)
    results = camb.get_background(pars_nl)
    k = 10**np.linspace(-6, k_lim(z, l_max), 1000)
    return get_matter_power_interpolator(pars_nl,
                                         nonlinear=True,
                                         kmax=k_max(z, l_max),
                                         k_hunit=True,
                                         hubble_units=True)
Beispiel #19
0
def cps(z):
    pars = model.CAMBparams(NonLinear=1,
                            WantTransfer=True,
                            H0=67.3,
                            omch2=0.1199,
                            ombh2=0.02205,
                            YHe=0.24770)
    pars.DarkEnergy.set_params(w=-1.13)
    #pars.set_for_lmax(lmax = l_max)
    pars.InitPower.set_params(ns=0.9603, As=2.196e-09)
    results = camb.get_background(pars)
    PK = get_matter_power_interpolator(pars,
                                       nonlinear=True,
                                       kmax=10,
                                       k_hunit=True,
                                       hubble_units=True)
    PK.P(z, k)
    return PK.P(z, k)
Beispiel #20
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()
Beispiel #21
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()
Beispiel #22
0
def get_interpolated():
    #For calculating large-scale structure and lensing results yourself, get a power spectrum
    #interpolation object. In this example we calculate the CMB lensing potential power
    #spectrum using the Limber approximation, using PK=camb.get_matter_power_interpolator() function.   
    #calling PK(z, k) will then get power spectrum at any k and redshift z in range.

    nz = 100 #number of steps to use for the radial/redshift integration
    kmax=10  #kmax to use
    #First set up parameters as usual
    pars = camb.CAMBparams()
    pars.set_cosmology(H0=67.5, ombh2=0.022, omch2=0.122)
    pars.InitPower.set_params(ns=0.965)

    #For Limber result, want integration over \chi (comoving radial distance), from 0 to chi_*.
    #so get background results to find chistar, set up arrage in chi, and calculate corresponding redshifts
    results= camb.get_background(pars)
    chistar = results.conformal_time(0)- model.tau_maxvis.value
    chis = np.linspace(0,chistar,nz)
    zs=results.redshift_at_comoving_radial_distance(chis)
    #Calculate array of delta_chi, and drop first and last points where things go singular
    dchis = (chis[2:]-chis[:-2])/2
    chis = chis[1:-1]
    zs = zs[1:-1]

    #Get the matter power spectrum interpolation object (based on RectBivariateSpline)
    #Here for lensing we want the power spectrum of the Weyl potential.

    #PK = camb.get_matter_power_interpolator(pars, nonlinear=True,hubble_units=False, k_hunit=False, kmax=kmax,var1=model.Transfer_Weyl,var2=model.Transfer_Weyl, zmax=zs[-1])

    PK = camb.get_matter_power_interpolator(pars, nonlinear=True, hubble_units=False, k_hunit=False, kmax=kmax)

    #Have a look at interpolated power spectrum results for a range of redshifts
    #Expect linear potentials to decay a bit when Lambda becomes important, and change from non-linear growth
    plt.figure(figsize=(8,5))
    k=np.exp(np.log(10)*np.linspace(-4,5,1000))
    zplot = [0, 0.5, 1, 4 ,20]
    for z in zplot:
        ax0.loglog(k, PK.P(z,k))
        #plt.xlim([1e-4,kmax])
        #plt.xlabel('k Mpc')
        #plt.ylabel('$P_\Psi\, Mpc^{-3}$')
        plt.legend(['z=%s'%z for z in zplot]);
Beispiel #23
0
    def get_camb_theory(self, pars):
        kmax = 15 * acc
        results = camb.get_background(pars)

        k_per_logint = None
        if self.use_Weyl:
            PKWeyl = camb.get_matter_power_interpolator(pars, nonlinear=True,
                                                        hubble_units=False, k_hunit=False, kmax=kmax,
                                                        k_per_logint=k_per_logint,
                                                        var1=model.Transfer_Weyl, var2=model.Transfer_Weyl,
                                                        zmax=self.zmax,
                                                        extrap_kmax=500 * acc)
        else:
            PKWeyl = None

        PKdelta = camb.get_matter_power_interpolator(pars, nonlinear=True,
                                                     hubble_units=False, k_hunit=False, kmax=kmax,
                                                     k_per_logint=k_per_logint,
                                                     zmax=self.zmax, extrap_kmax=500 * acc)
        return results, PKdelta, PKWeyl
Beispiel #24
0
    def get_g_camb(self):
        import camb
        dw_dz = lambda z: 1 / (self.a0 * self.H0 * self.E(z))
        z_vis = np.linspace(0, 20, 5000)
        pars = camb.set_params(H0=100 * self.h,
                               ombh2=self.Omega_Bh2,
                               omch2=self.Omega0 * self.h**2 - self.Omega_Bh2,
                               ns=self.n,
                               tau=self.tau)
        data = camb.get_background(pars)
        back_ev = data.get_background_redshift_evolution(z_vis,
                                                         ['x_e', 'visibility'],
                                                         format='array')
        g_interpolation = glueAsymptode(
            interpolate(z_vis, back_ev[:, 1]),
            min=0.1,
            minAsym=lambda z: interpolate(z_vis, back_ev[:, 1])(0.1) *
            (1 + z)**2)
        norm = self.__num.integrate(lambda z: g_interpolation(z) * dw_dz(z),
                                    min(z_vis), max(z_vis))
        g_func = lambda z: (1 - np.exp(-self.tau)) / norm * g_interpolation(z)

        return g_func
Beispiel #25
0
#import matplotlib.colors as mcolors
from scipy.integrate import quad,simps,romberg
from scipy.special import spherical_jn, gamma

#import rotation as ro
#import lensing as le
import numba
import camb

from IPython import embed

arcmin2rad = np.pi / 180. / 60. 
rad2arcmin = 1./arcmin2rad
#Camb initialisation
pars= camb.CAMBparams()
data= camb.get_background(pars)

#SI constants
Omega_b = 0.0486
p_cr0 = 8.62E-27
chi = (1-0.24)/(1-0.12)
mu_e = 1.14
m_p = 1.6726E-27
sig_t = 6.65246E-29
omega_lamb = 0.6911
omega_k = 0.
omega_r = 9.2364E-5
omega_m = 0.3089
#H_0 = 2.195E-18
#H_0 is in km/s/Mpc
H_0 = 67.74
Beispiel #26
0
    def testBackground(self):
        pars = camb.CAMBparams()
        pars.set_cosmology(H0=68.5, ombh2=0.022, omch2=0.122, YHe=0.2453, mnu=0.07, omk=0)
        zre = camb.get_zre_from_tau(pars, 0.06)
        age = camb.get_age(pars)
        self.assertAlmostEqual(zre, 8.39, 2)
        self.assertAlmostEqual(age, 13.65, 2)

        data = camb.CAMBdata()
        bao = data.get_BAO([0.57, 0.27], pars)

        data = camb.CAMBdata()
        data.calc_background(pars)

        DA = data.angular_diameter_distance(0.57)
        H = data.hubble_parameter(0.27)
        self.assertAlmostEqual(DA, bao[0][2], 3)
        self.assertAlmostEqual(H, bao[1][1], 3)

        age2 = data.physical_time(0)
        self.assertAlmostEqual(age, age2, 4)

        data.comoving_radial_distance(0.48)
        t0 = data.conformal_time(0)
        self.assertAlmostEqual(t0, data.tau0)
        t1 = data.conformal_time(11.5)
        t2 = data.comoving_radial_distance(11.5)
        self.assertAlmostEqual(t2, t0 - t1, 2)
        self.assertAlmostEqual(t1, 4200.78, 2)
        chistar = data.conformal_time(0) - data.tau_maxvis
        chis = np.linspace(0, chistar, 197)
        zs = data.redshift_at_comoving_radial_distance(chis)
        chitest = data.comoving_radial_distance(zs)
        self.assertTrue(np.sum((chitest - chis) ** 2) < 1e-3)

        theta = data.cosmomc_theta()
        self.assertAlmostEqual(theta, 0.0104759965, 5)

        derived = data.get_derived_params()
        self.assertAlmostEqual(derived['age'], age, 2)
        self.assertAlmostEqual(derived['rdrag'], 146.976, 2)
        self.assertAlmostEqual(derived['rstar'], data.sound_horizon(derived['zstar']), 2)

        # Test BBN consistency, base_plikHM_TT_lowTEB best fit model
        pars.set_cosmology(H0=67.31, ombh2=0.022242, omch2=0.11977, mnu=0.06, omk=0)
        self.assertAlmostEqual(pars.YHe, 0.245347, 5)
        data.calc_background(pars)
        self.assertAlmostEqual(data.cosmomc_theta(), 0.010408566, 7)
        self.assertAlmostEqual(data.get_derived_params()['kd'], 0.14055, 4)

        pars.set_cosmology(H0=67.31, ombh2=0.022242, omch2=0.11977, mnu=0.06, omk=0,
                           bbn_predictor=bbn.BBN_table_interpolator())
        self.assertAlmostEqual(pars.YHe, 0.2453469, 5)
        self.assertAlmostEqual(pars.get_Y_p(), bbn.BBN_table_interpolator().Y_p(0.022242, 0), 5)

        # test massive sterile models as in Planck papers
        pars.set_cosmology(H0=68.0, ombh2=0.022305, omch2=0.11873, mnu=0.06, nnu=3.073, omk=0, meffsterile=0.013)
        self.assertAlmostEqual(pars.omnuh2, 0.00078, 5)
        self.assertAlmostEqual(pars.YHe, 0.24573, 5)
        self.assertAlmostEqual(pars.N_eff, 3.073, 4)

        data.calc_background(pars)
        self.assertAlmostEqual(data.get_derived_params()['age'], 13.773, 2)
        self.assertAlmostEqual(data.cosmomc_theta(), 0.0104103, 6)

        # test dark energy
        pars.set_cosmology(H0=68.26, ombh2=0.022271, omch2=0.11914, mnu=0.06, omk=0)
        pars.set_dark_energy(w=-1.0226, dark_energy_model='fluid')

        data.calc_background(pars)
        self.assertAlmostEqual(data.get_derived_params()['age'], 13.789, 2)
        scal = data.luminosity_distance(1.4)
        vec = data.luminosity_distance([1.2, 1.4, 0.1, 1.9])
        self.assertAlmostEqual(scal, vec[1], 5)

        pars.set_dark_energy()  # re-set defaults

        # test theta
        pars.set_cosmology(cosmomc_theta=0.0104085, ombh2=0.022271, omch2=0.11914, mnu=0.06, omk=0)
        self.assertAlmostEqual(pars.H0, 67.5512, 2)
        with self.assertRaises(CAMBParamRangeError):
            pars.set_cosmology(cosmomc_theta=0.0204085, ombh2=0.022271, omch2=0.11914, mnu=0.06, omk=0)
        pars = camb.set_params(cosmomc_theta=0.0104077, ombh2=0.022, omch2=0.122, w=-0.95)
        self.assertAlmostEqual(camb.get_background(pars, no_thermo=True).cosmomc_theta(), 0.0104077, 7)

        pars = camb.set_params(thetastar=0.010311, ombh2=0.022, omch2=0.122)
        self.assertAlmostEqual(camb.get_background(pars).get_derived_params()['thetastar'] / 100, 0.010311, 7)
        pars = camb.set_params(thetastar=0.010311, ombh2=0.022, omch2=0.122, omk=-0.05)
        self.assertAlmostEqual(camb.get_background(pars).get_derived_params()['thetastar'] / 100, 0.010311, 7)
        self.assertAlmostEqual(pars.H0, 49.7148, places=3)

        pars = camb.set_params(cosmomc_theta=0.0104077, ombh2=0.022, omch2=0.122, w=-0.95, wa=0,
                               dark_energy_model='ppf')
        self.assertAlmostEqual(camb.get_background(pars, no_thermo=True).cosmomc_theta(), 0.0104077, 7)

        pars = camb.set_params(cosmomc_theta=0.0104077, ombh2=0.022, omch2=0.122, w=-0.95,
                               dark_energy_model='DarkEnergyFluid', initial_power_model='InitialPowerLaw')
        self.assertAlmostEqual(camb.get_background(pars, no_thermo=True).cosmomc_theta(), 0.0104077, 7)

        with self.assertRaises(CAMBValueError):
            camb.set_params(dark_energy_model='InitialPowerLaw')
        data.calc_background(pars)
        h2 = (data.Params.H0 / 100) ** 2
        self.assertAlmostEqual(data.get_Omega('baryon'), data.Params.ombh2 / h2, 7)
        self.assertAlmostEqual(data.get_Omega('nu'), data.Params.omnuh2 / h2, 7)
        self.assertAlmostEqual(data.get_Omega('photon') + data.get_Omega('neutrino') + data.get_Omega('de') +
                               (pars.ombh2 + pars.omch2 + pars.omnuh2) / h2 + pars.omk, 1, 8)
        pars.set_cosmology(H0=67, mnu=1, neutrino_hierarchy='normal')
        data.calc_background(pars)
        h2 = (pars.H0 / 100) ** 2
        self.assertAlmostEqual(data.get_Omega('photon') + data.get_Omega('neutrino') + data.get_Omega('de') +
                               (pars.ombh2 + pars.omch2 + pars.omnuh2) / h2 + pars.omk, 1, 8)
        redshifts = np.array([0.005, 0.01, 0.3, 0.9342, 4, 27, 321.5, 932, 1049, 1092, 2580, 1e4, 2.1e7])
        self.assertTrue(
            np.allclose(data.redshift_at_conformal_time(data.conformal_time(redshifts)), redshifts, rtol=1e-7))
        pars.set_dark_energy(w=-1.8)
        data.calc_background(pars)
        self.assertTrue(
            np.allclose(data.redshift_at_conformal_time(data.conformal_time(redshifts)), redshifts, rtol=1e-7))
        pars.set_cosmology(cosmomc_theta=0.0104085)
        data.calc_background(pars)
        self.assertAlmostEqual(data.cosmomc_theta(), 0.0104085)
        derived = data.get_derived_params()
        pars.Accuracy.BackgroundTimeStepBoost = 2
        data.calc_background(pars)
        derived2 = data.get_derived_params()
        self.assertAlmostEqual(derived['thetastar'], derived2['thetastar'], places=5)
        pars.set_cosmology(H0=67.5, ombh2=0.022, omch2=0.122, mnu=0.11, neutrino_hierarchy='inverted')
        self.assertEqual(pars.num_nu_massive, 3)
        self.assertEqual(pars.nu_mass_numbers[1], 1)
        self.assertEqual(pars.nu_mass_eigenstates, 2)
        self.assertAlmostEqual(pars.nu_mass_fractions[0], 0.915197, places=4)
Beispiel #27
0
import sys, platform, os
from matplotlib import pyplot as plt
import numpy as np
import camb
from camb import model, initialpower

import h5py, os
pars = camb.CAMBparams()
pars.set_cosmology(H0=67.5, ombh2=0.022, omch2=0.122)
cambdata = camb.get_background(pars)
h5f = h5py.File(os.environ['PCAT_DATA_PATH'] + '/data/inpt/adis.h5', 'w')
redssour = np.linspace(0., 5., 100)
redshost = np.linspace(0., 5., 100)
adis = cambdata.angular_diameter_distance(redssour)
adistdim = np.zeros((100, 100))
for k, z0 in enumerate(redssour):
    for l, z1 in enumerate(redshost):
        adistdim[k, l] = cambdata.angular_diameter_distance2(z0, z1)
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)
Beispiel #28
0
    def testBackground(self):
        pars = camb.CAMBparams()
        pars.set_cosmology(H0=68.5,
                           ombh2=0.022,
                           omch2=0.122,
                           YHe=0.2453,
                           mnu=0.07,
                           omk=0)

        zre = camb.get_zre_from_tau(pars, 0.06)
        age = camb.get_age(pars)
        self.assertAlmostEqual(zre, 8.39, 2)
        self.assertAlmostEqual(age, 13.65, 2)

        data = camb.CAMBdata()
        bao = data.get_BAO([0.57, 0.27], pars)

        data = camb.CAMBdata()
        data.calc_background(pars)
        DA = data.angular_diameter_distance(0.57)
        H = data.hubble_parameter(0.27)
        self.assertAlmostEqual(DA, bao[0][2], 3)
        self.assertAlmostEqual(H, bao[1][1], 3)

        age2 = data.physical_time(0)
        self.assertAlmostEqual(age, age2, 4)

        data.comoving_radial_distance(0.48)
        t0 = data.conformal_time(0)
        t1 = data.conformal_time(11.5)
        t2 = data.comoving_radial_distance(11.5)
        self.assertAlmostEqual(t2, t0 - t1, 2)
        self.assertAlmostEqual(t1, 4200.78, 2)
        chistar = data.conformal_time(0) - model.tau_maxvis.value
        chis = np.linspace(0, chistar, 197)
        zs = data.redshift_at_comoving_radial_distance(chis)
        chitest = data.comoving_radial_distance(zs)
        self.assertTrue(np.sum((chitest - chis)**2) < 1e-3)

        theta = data.cosmomc_theta()
        self.assertAlmostEqual(theta, 0.0104759965, 5)

        derived = data.get_derived_params()
        self.assertAlmostEqual(derived['age'], age, 2)
        self.assertAlmostEqual(derived['rdrag'], 146.976, 2)

        # Test BBN consistency, base_plikHM_TT_lowTEB best fit model
        pars.set_cosmology(H0=67.31,
                           ombh2=0.022242,
                           omch2=0.11977,
                           mnu=0.06,
                           omk=0)
        self.assertAlmostEqual(pars.YHe, 0.245336, 5)
        data.calc_background(pars)
        self.assertAlmostEqual(data.cosmomc_theta(), 0.01040862, 7)
        self.assertAlmostEqual(data.get_derived_params()['kd'], 0.14055, 4)

        pars.set_cosmology(H0=67.31,
                           ombh2=0.022242,
                           omch2=0.11977,
                           mnu=0.06,
                           omk=0,
                           bbn_predictor=bbn.BBN_table_interpolator())
        self.assertAlmostEqual(pars.YHe, 0.2453469, 5)
        self.assertAlmostEqual(pars.get_Y_p(),
                               bbn.BBN_table_interpolator().Y_p(0.022242, 0),
                               5)

        # test massive sterile models as in Planck papers
        pars.set_cosmology(H0=68.0,
                           ombh2=0.022305,
                           omch2=0.11873,
                           mnu=0.06,
                           nnu=3.073,
                           omk=0,
                           meffsterile=0.013)
        self.assertAlmostEqual(pars.omegan * (pars.H0 / 100)**2, 0.00078, 5)
        self.assertAlmostEqual(pars.YHe, 0.24573, 5)
        self.assertAlmostEqual(pars.N_eff(), 3.073, 4)

        data.calc_background(pars)
        self.assertAlmostEqual(data.get_derived_params()['age'], 13.773, 2)
        self.assertAlmostEqual(data.cosmomc_theta(), 0.0104103, 6)

        # test dark energy
        pars.set_cosmology(H0=68.26,
                           ombh2=0.022271,
                           omch2=0.11914,
                           mnu=0.06,
                           omk=0)
        pars.set_dark_energy(w=-1.0226, dark_energy_model='fluid')

        data.calc_background(pars)
        self.assertAlmostEqual(data.get_derived_params()['age'], 13.789, 2)
        scal = data.luminosity_distance(1.4)
        vec = data.luminosity_distance([1.2, 1.4, 0.1, 1.9])
        self.assertAlmostEqual(scal, vec[1], 5)
        pars.set_dark_energy()  # re-set defaults

        # test theta
        pars.set_cosmology(cosmomc_theta=0.0104085,
                           H0=None,
                           ombh2=0.022271,
                           omch2=0.11914,
                           mnu=0.06,
                           omk=0)
        self.assertAlmostEqual(pars.H0, 67.5512, 2)
        with self.assertRaises(CAMBParamRangeError):
            pars.set_cosmology(cosmomc_theta=0.0204085,
                               H0=None,
                               ombh2=0.022271,
                               omch2=0.11914,
                               mnu=0.06,
                               omk=0)
        pars = camb.set_params(cosmomc_theta=0.0104077,
                               H0=None,
                               ombh2=0.022,
                               omch2=0.122,
                               w=-0.95)
        self.assertAlmostEqual(
            camb.get_background(pars, no_thermo=True).cosmomc_theta(),
            0.0104077, 7)
        pars.set_dark_energy()
Beispiel #29
0
    def testBackground(self):
        pars = camb.CAMBparams()
        pars.set_cosmology(H0=68.5, ombh2=0.022, omch2=0.122, YHe=0.2453, mnu=0.07, omk=0)
        zre = camb.get_zre_from_tau(pars, 0.06)
        age = camb.get_age(pars)
        self.assertAlmostEqual(zre, 8.39, 2)
        self.assertAlmostEqual(age, 13.65, 2)

        data = camb.CAMBdata()
        bao = data.get_BAO([0.57, 0.27], pars)

        data = camb.CAMBdata()
        data.calc_background(pars)

        DA = data.angular_diameter_distance(0.57)
        H = data.hubble_parameter(0.27)
        self.assertAlmostEqual(DA, bao[0][2], 3)
        self.assertAlmostEqual(H, bao[1][1], 3)

        age2 = data.physical_time(0)
        self.assertAlmostEqual(age, age2, 4)

        data.comoving_radial_distance(0.48)
        t0 = data.conformal_time(0)
        self.assertAlmostEqual(t0, data.tau0)
        t1 = data.conformal_time(11.5)
        t2 = data.comoving_radial_distance(11.5)
        self.assertAlmostEqual(t2, t0 - t1, 2)
        self.assertAlmostEqual(t1, 4200.78, 2)
        chistar = data.conformal_time(0) - data.tau_maxvis
        chis = np.linspace(0, chistar, 197)
        zs = data.redshift_at_comoving_radial_distance(chis)
        chitest = data.comoving_radial_distance(zs)
        self.assertTrue(np.sum((chitest - chis) ** 2) < 1e-3)

        theta = data.cosmomc_theta()
        self.assertAlmostEqual(theta, 0.0104759965, 5)

        derived = data.get_derived_params()
        self.assertAlmostEqual(derived['age'], age, 2)
        self.assertAlmostEqual(derived['rdrag'], 146.976, 2)
        self.assertAlmostEqual(derived['rstar'], data.sound_horizon(derived['zstar']), 2)

        # Test BBN consistency, base_plikHM_TT_lowTEB best fit model
        pars.set_cosmology(H0=67.31, ombh2=0.022242, omch2=0.11977, mnu=0.06, omk=0)
        self.assertAlmostEqual(pars.YHe, 0.245347, 5)
        data.calc_background(pars)
        self.assertAlmostEqual(data.cosmomc_theta(), 0.010408566, 7)
        self.assertAlmostEqual(data.get_derived_params()['kd'], 0.14055, 4)

        pars.set_cosmology(H0=67.31, ombh2=0.022242, omch2=0.11977, mnu=0.06, omk=0,
                           bbn_predictor=bbn.BBN_table_interpolator())
        self.assertAlmostEqual(pars.YHe, 0.2453469, 5)
        self.assertAlmostEqual(pars.get_Y_p(), bbn.BBN_table_interpolator().Y_p(0.022242, 0), 5)

        # test massive sterile models as in Planck papers
        pars.set_cosmology(H0=68.0, ombh2=0.022305, omch2=0.11873, mnu=0.06, nnu=3.073, omk=0, meffsterile=0.013)
        self.assertAlmostEqual(pars.omnuh2, 0.00078, 5)
        self.assertAlmostEqual(pars.YHe, 0.24573, 5)
        self.assertAlmostEqual(pars.N_eff, 3.073, 4)

        data.calc_background(pars)
        self.assertAlmostEqual(data.get_derived_params()['age'], 13.773, 2)
        self.assertAlmostEqual(data.cosmomc_theta(), 0.0104103, 6)

        # test dark energy
        pars.set_cosmology(H0=68.26, ombh2=0.022271, omch2=0.11914, mnu=0.06, omk=0)
        pars.set_dark_energy(w=-1.0226, dark_energy_model='fluid')

        data.calc_background(pars)
        self.assertAlmostEqual(data.get_derived_params()['age'], 13.789, 2)
        scal = data.luminosity_distance(1.4)
        vec = data.luminosity_distance([1.2, 1.4, 0.1, 1.9])
        self.assertAlmostEqual(scal, vec[1], 5)

        pars.set_dark_energy()  # re-set defaults

        # test theta
        pars.set_cosmology(cosmomc_theta=0.0104085, ombh2=0.022271, omch2=0.11914, mnu=0.06, omk=0)
        self.assertAlmostEqual(pars.H0, 67.5512, 2)
        with self.assertRaises(CAMBParamRangeError):
            pars.set_cosmology(cosmomc_theta=0.0204085, ombh2=0.022271, omch2=0.11914, mnu=0.06, omk=0)
        pars = camb.set_params(cosmomc_theta=0.0104077, ombh2=0.022, omch2=0.122, w=-0.95)
        self.assertAlmostEqual(camb.get_background(pars, no_thermo=True).cosmomc_theta(), 0.0104077, 7)

        pars = camb.set_params(thetastar=0.010311, ombh2=0.022, omch2=0.122)
        self.assertAlmostEqual(camb.get_background(pars).get_derived_params()['thetastar'] / 100, 0.010311, 7)
        pars = camb.set_params(thetastar=0.010311, ombh2=0.022, omch2=0.122, omk=-0.05)
        self.assertAlmostEqual(camb.get_background(pars).get_derived_params()['thetastar'] / 100, 0.010311, 7)
        self.assertAlmostEqual(pars.H0, 49.7148, places=3)

        pars = camb.set_params(cosmomc_theta=0.0104077, ombh2=0.022, omch2=0.122, w=-0.95, wa=0,
                               dark_energy_model='ppf')
        self.assertAlmostEqual(camb.get_background(pars, no_thermo=True).cosmomc_theta(), 0.0104077, 7)

        pars = camb.set_params(cosmomc_theta=0.0104077, ombh2=0.022, omch2=0.122, w=-0.95,
                               dark_energy_model='DarkEnergyFluid', initial_power_model='InitialPowerLaw')
        self.assertAlmostEqual(camb.get_background(pars, no_thermo=True).cosmomc_theta(), 0.0104077, 7)

        with self.assertRaises(CAMBValueError):
            camb.set_params(dark_energy_model='InitialPowerLaw')
        data.calc_background(pars)
        h2 = (data.Params.H0 / 100) ** 2
        self.assertAlmostEqual(data.get_Omega('baryon'), data.Params.ombh2 / h2, 7)
        self.assertAlmostEqual(data.get_Omega('nu'), data.Params.omnuh2 / h2, 7)
        self.assertAlmostEqual(data.get_Omega('photon') + data.get_Omega('neutrino') + data.get_Omega('de') +
                               (pars.ombh2 + pars.omch2 + pars.omnuh2) / h2 + pars.omk, 1, 8)
        pars.set_cosmology(H0=67, mnu=1, neutrino_hierarchy='normal')
        data.calc_background(pars)
        h2 = (pars.H0 / 100) ** 2
        self.assertAlmostEqual(data.get_Omega('photon') + data.get_Omega('neutrino') + data.get_Omega('de') +
                               (pars.ombh2 + pars.omch2 + pars.omnuh2) / h2 + pars.omk, 1, 8)
        redshifts = np.array([0.005, 0.01, 0.3, 0.9342, 4, 27, 321.5, 932, 1049, 1092, 2580, 1e4, 2.1e7])
        self.assertTrue(
            np.allclose(data.redshift_at_conformal_time(data.conformal_time(redshifts)), redshifts, rtol=1e-7))
        pars.set_dark_energy(w=-1.8)
        data.calc_background(pars)
        self.assertTrue(
            np.allclose(data.redshift_at_conformal_time(data.conformal_time(redshifts)), redshifts, rtol=1e-7))
        pars.set_cosmology(cosmomc_theta=0.0104085)
        data.calc_background(pars)
        self.assertAlmostEqual(data.cosmomc_theta(), 0.0104085)
        derived = data.get_derived_params()
        pars.Accuracy.BackgroundTimeStepBoost = 2
        data.calc_background(pars)
        derived2 = data.get_derived_params()
        self.assertAlmostEqual(derived['thetastar'], derived2['thetastar'], places=5)
        pars.set_cosmology(H0=67.5, ombh2=0.022, omch2=0.122, mnu=0.11, neutrino_hierarchy='inverted')
        self.assertEqual(pars.num_nu_massive, 3)
        self.assertEqual(pars.nu_mass_numbers[1], 1)
        self.assertEqual(pars.nu_mass_eigenstates, 2)
        self.assertAlmostEqual(pars.nu_mass_fractions[0], 0.915197, places=4)
Beispiel #30
0
    def testAssigments(self):
        ini = os.path.join(os.path.dirname(__file__), '..', 'inifiles', 'planck_2018.ini')
        if os.path.exists(ini):
            pars = camb.read_ini(ini)
            self.assertTrue(np.abs(camb.get_background(pars).cosmomc_theta() * 100 / 1.040909 - 1) < 2e-5)
        pars = camb.CAMBparams()
        pars.set_cosmology(H0=68.5, ombh2=0.022, mnu=0, omch2=0.1)
        self.assertAlmostEqual(pars.omegam, (0.022 + 0.1) / 0.685 ** 2)
        with self.assertRaises(AttributeError):
            # noinspection PyPropertyAccess
            pars.omegam = 1
        pars.InitPower.set_params(ns=0.01)
        data = camb.CAMBdata()
        data.Params = pars
        self.assertEqual(data.Params.InitPower.ns, pars.InitPower.ns)
        d = dark_energy.DarkEnergyFluid(w=-0.95)
        pars.DarkEnergy = d
        self.assertEqual(pars.DarkEnergy.w, -0.95)
        pars.DarkEnergy = dark_energy.AxionEffectiveFluid(w_n=0.4)
        data.Params = pars
        self.assertEqual(pars.DarkEnergy.w_n, 0.4)
        pars.z_outputs = [0.1, 0.4]
        self.assertEqual(pars.z_outputs[1], 0.4)
        pars.z_outputs[0] = 0.3
        self.assertEqual(pars.z_outputs[0], 0.3)
        pars.z_outputs = pars.z_outputs
        pars.z_outputs = []
        pars.z_outputs = None
        self.assertFalse(len(pars.z_outputs))
        with self.assertRaises(TypeError):
            pars.DarkEnergy = initialpower.InitialPowerLaw()
        pars.NonLinear = model.NonLinear_both
        printstr = str(pars)
        self.assertTrue('Want_CMB_lensing = True' in printstr and
                        "NonLinear = NonLinear_both" in printstr)
        pars.NonLinear = model.NonLinear_lens
        self.assertTrue(pars.NonLinear == model.NonLinear_lens)
        with self.assertRaises(ValueError):
            pars.NonLinear = 4
        pars.nu_mass_degeneracies = np.zeros(3)
        self.assertTrue(len(pars.nu_mass_degeneracies) == 3)
        pars.nu_mass_degeneracies = [1, 2, 3]
        self.assertTrue(pars.nu_mass_degeneracies[1] == 2)
        pars.nu_mass_degeneracies[1] = 5
        self.assertTrue(pars.nu_mass_degeneracies[1] == 5)
        with self.assertRaises(CAMBParamRangeError):
            pars.nu_mass_degeneracies = np.zeros(7)
        pars.nu_mass_eigenstates = 0
        self.assertFalse(len((pars.nu_mass_degeneracies[:1])))
        pars = camb.set_params(**{'InitPower.ns': 1.2, 'WantTransfer': True})
        self.assertEqual(pars.InitPower.ns, 1.2)
        self.assertTrue(pars.WantTransfer)
        pars.DarkEnergy = None

        from camb.sources import GaussianSourceWindow
        pars = camb.CAMBparams()
        pars.SourceWindows = [GaussianSourceWindow(), GaussianSourceWindow(redshift=1)]
        self.assertEqual(pars.SourceWindows[1].redshift, 1)
        pars.SourceWindows[0].redshift = 2
        self.assertEqual(pars.SourceWindows[0].redshift, 2)
        self.assertTrue(len(pars.SourceWindows) == 2)
        pars.SourceWindows[0] = GaussianSourceWindow(redshift=3)
        self.assertEqual(pars.SourceWindows[0].redshift, 3)
        self.assertTrue('redshift = 3.0' in str(pars))
        pars.SourceWindows = pars.SourceWindows[0:1]
        self.assertTrue(len(pars.SourceWindows) == 1)
        pars.SourceWindows = []
        self.assertTrue(len(pars.SourceWindows) == 0)
Beispiel #31
0
for name in like.names:
    common.append(name in JLA.names or 'SDSS' + name in JLA.names
                  or 'sn' + name in JLA.names)
common = np.array(common, dtype=np.bool)
print(like.nsn, np.sum(common), like.nsn - np.sum(common))

redshifts = np.logspace(-2, 1, 1000)
samples = g.sampleAnalyser.samplesForRoot(
    'base_plikHM_TTTEEE_lowl_lowE_lensing')
ixs = samples.randomSingleSamples_indices()
dists = np.zeros((len(ixs), len(redshifts)))
sndists = np.zeros((len(ixs), like.nsn))
for i, ix in enumerate(ixs):
    dic = samples.getParamSampleDict(ix)
    camb_pars = get_camb_params(dic)
    results = camb.get_background(camb_pars)
    dists[i, :] = 5 * np.log10(
        (1 + redshifts)**2 * results.angular_diameter_distance(redshifts))
    sndists[i, :] = 5 * np.log10(
        (1 + like.zcmb)**2 * results.angular_diameter_distance(like.zcmb))

paramdic = g.bestfit('base_plikHM_TTTEEE_lowl_lowE_lensing').getParamDict()
camb_pars = get_camb_params(paramdic)
results = camb.get_background(camb_pars)

invvars = 1.0 / like.pre_vars
wtval = np.sum(invvars)

offset = 5 * np.log10(1e-5)
lumdists = 5 * np.log10(
    (1 + like.zcmb) *
Beispiel #32
0
 def get_background(self, z=0.0):
     self.backresults = camb.get_background(self.pars)
     ##  self.chistar = self.backresults.conformal_time(0) - model.tau_maxvis.value
     self.zstar = self.backresults.get_derived_params()['zstar']
Beispiel #33
0
import pickle
import rotation as ro
import lensing as le
import numba
import camb

from IPython import embed

#embed()

arcmin2rad = np.pi / 180. / 60.
rad2arcmin = 1. / arcmin2rad
#Camb initialisation
pars = camb.CAMBparams()
data_camb = camb.get_background(pars)

cosmo = Cosmo()
cmbspec = cosmo.cmb_spectra(7000)
#cmbspec_r = Cosmo({'r':0.1}).cmb_spectra(12000,spec='tensor')[:,2]
clbb_r = Cosmo({'r': 1.}).cmb_spectra(400, spec='tensor')[:, 2]

MC_lin = pickle.load(open("MAGCAMB_ONLY_linear.pkl", "rb"))
MC_log = pickle.load(open("MAGCAMB_ONLY_log.pkl", "rb"))
FR = pickle.load(open("FINAL_FR.pkl", "rb"))
FR_lin = FR['mydic']
FR_log = FR['mydic1']

#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
Beispiel #34
0
def TestAgainstCAMB(results_dir):
    """ Function to compare our implementation to CAMB for the comoving angular
    diameter distance, Hubble rate, and ionization fraction, as well as the 
    redshift of baryon drag, and sound horizon at baryon drag.
    """
    # Parameters from PL18
    p = Params(omega_b=0.02212,
               omega_c=0.1206,
               H0=66.88,
               Nnu_massive=1.0,
               Nnu_massless=2.046,
               mnu=0.06 * eV,
               Omega_k=0.,
               Tcmb=2.7255,
               w=-1,
               Gamma_P=0.24,
               F=1.14,
               fDM=0.)

    # Redshift range of interest for recombination
    z = np.linspace(500, 2500, 1000)
    # Compute recfast
    zarr, Xe_H, Xe_He, Xe, TM = recfast.Xe_frac(p.Gamma_P,
                                                p.Tcmb,
                                                p.Omega_c,
                                                p.Omega_b,
                                                p.Omega_lambda,
                                                p.Omega_k,
                                                np.sqrt(p.hsquared),
                                                p.Nnu_massless + p.Nnu_massive,
                                                p.F,
                                                p.fDM,
                                                switch=1)
    xe = interp1d(zarr, Xe, kind='cubic')
    # Comopute ionization history from CAMB (also uses RECFAST)
    camb_res = camb.get_background(
        camb.set_params(H0=p.H0,
                        ombh2=p.omega_b,
                        omch2=p.omega_c,
                        mnu=p.mnu,
                        nnu=p.Nnu_massive + p.Nnu_massless,
                        tau=0.07,
                        YHe=p.Gamma_P,
                        recombination_model='Recfast'))
    back_ev = camb_res.get_background_redshift_evolution(z, ['x_e'],
                                                         format='array')

    # 1. Plot comparison of ionization histories
    fig, ax = plt.subplots(1, 1)
    ax.plot(z, xe(z), label=r"${\rm Ours}$")
    ax.plot(z, back_ev[:, 0], label=r"${\rm CAMB}$")
    ax.legend(loc=4, frameon=False)
    ax.tick_params(axis='both', direction='inout')
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.set_ylabel(r"${\rm Ionization~Fraction,}~X_{\rm e}$")
    ax.set_xlabel(r"${\rm Redshift,}~z$")
    fig.savefig(results_dir / "CompareXeCAMB.pdf")

    # 2. Plot comparison of comoving angular diameter distance
    z = np.linspace(0, 4, 100)
    DA = camb_res.angular_diameter_distance(z)
    ourda = np.vectorize(lambda x: angular_diameter_distance(x, p))
    fig, ax = plt.subplots(1, 1)
    ax.plot(z, DA, label=r"${\rm CAMB}$")
    ax.plot(z, ourda(z) / Mpc / (1 + z), '--', label=r"${\rm Ours}$")
    ax.legend(loc=2, frameon=False)
    ax.set_ylabel(
        r"${\rm Comoving~Angular~Diameter~Distance,}~D_A(z)~({\rm Mpc})$")
    ax.set_xlabel(r"${\rm Redshift,}~z$")
    ax.tick_params(axis='both', direction='inout')
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    fig.savefig(results_dir / "CompareDACAMB.pdf")

    # 3. Plot comparison of Hubble rate
    z = np.linspace(0, 4, 100)
    CAMB_H = camb_res.hubble_parameter(z)
    ourH = np.vectorize(lambda x: H(x, p))
    fig, ax = plt.subplots(1, 1)
    ax.plot(z, CAMB_H, label=r"${\rm CAMB}$")
    ax.plot(z, ourH(z) / km * second * Mpc, '--', label=r"${\rm Ours}$")
    ax.legend(loc=2, frameon=False)
    ax.set_ylabel(r"${\rm Hubble~Rate,}~H(z)~({\rm km/s/Mpc})$")
    ax.set_xlabel(r"${\rm Redshift,}~z$")
    ax.tick_params(axis='both', direction='inout')
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    fig.savefig(results_dir / "CompareHCAMB.pdf")

    # Compare derived parameters
    CAMB_params = camb_res.get_derived_params()
    print("Dark Energy")
    print("-----------------------")
    print("CAMB: ", camb_res.get_Omega('de'))
    print("Ours: ", p.Omega_lambda)

    print("Redshift of baryon drag")
    print("-----------------------")
    print("CAMB: ", CAMB_params['zdrag'])
    print("Ours: ", z_drag(p))

    print("Sound Horizon at Baryon Drag")
    print("----------------------------")
    print("CAMB :", camb_res.sound_horizon(CAMB_params['zdrag']))
    print("Ours :", r_drag(p) / Mpc)
    return
Beispiel #35
0
common = []
for name in like.names:
    common.append(name in JLA.names or 'SDSS' + name in JLA.names or 'sn' + name in JLA.names)
common = np.array(common, dtype=np.bool)
print(like.nsn, np.sum(common), like.nsn - np.sum(common))

redshifts = np.logspace(-2, 1, 1000)
samples = g.sampleAnalyser.samplesForRoot('base_plikHM_TTTEEE_lowl_lowE_lensing')
ixs = samples.randomSingleSamples_indices()
dists = np.zeros((len(ixs), len(redshifts)))
sndists = np.zeros((len(ixs), like.nsn))
for i, ix in enumerate(ixs):
    dic = samples.getParamSampleDict(ix)
    camb_pars = get_camb_params(dic)
    results = camb.get_background(camb_pars)
    dists[i, :] = 5 * np.log10((1 + redshifts) ** 2 * results.angular_diameter_distance(redshifts))
    sndists[i, :] = 5 * np.log10((1 + like.zcmb) ** 2 * results.angular_diameter_distance(like.zcmb))

paramdic = g.bestfit('base_plikHM_TTTEEE_lowl_lowE_lensing').getParamDict()
camb_pars = get_camb_params(paramdic)
results = camb.get_background(camb_pars)

invvars = 1.0 / like.pre_vars
wtval = np.sum(invvars)

offset = 5 * np.log10(1e-5)
lumdists = 5 * np.log10((1 + like.zcmb) ** 2 * results.angular_diameter_distance(like.zcmb))

redshifts = np.logspace(-2, 1, 1000)
d = results.angular_diameter_distance(redshifts)
Beispiel #36
0
def Cl_kk(theta, acc_npts):
    
    global chis
    global zs
    global dzs
    global pars
    global K_k
    global om_tot
    global w_DE
    global w1
    global kmax
    global PK_kk
    
    H0, ombh2, omch2, ns, As, mnu, w_DE, tau, wa = theta

    #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_accuracy(AccuracyBoost=3.0, lSampleBoost=3.0, lAccuracyBoost=3.0)
    pars.set_cosmology(H0=H0, cosmomc_theta = None, ombh2=ombh2, omch2=omch2, mnu=mnu, omk=0, tau=tau, nnu=3.046, standard_neutrino_neff=3.046, num_massive_neutrinos = 1, neutrino_hierarchy='degenerate')
    pars.InitPower.set_params(ns=ns, r=0, As=As)
    pars.set_for_lmax(3000, lens_potential_accuracy=3, max_eta_k=30*3000)
    
    pars.set_dark_energy(w=w_DE,wa=wa,dark_energy_model='ppf') 

    #calculate results for these parameters
    results = camb.get_results(pars)
    
    om_tot = ( ombh2+omch2+mnu/94.07*(3.046/3.0)**0.75 )/((pars.H0/100)**2)


    nz = acc_npts #number of steps to use for the radial/redshift integration
    kmax=10  #kmax to use
    # #First set up parameters as usual
    # pars = camb.CAMBparams()
    # pars.set_cosmology(H0=67.5, ombh2=0.022, omch2=0.122)
    # pars.InitPower.set_params(ns=0.965)

    #For Limber result, want integration over \chi (comoving radial distance), from 0 to chi_*.
    #so get background results to find chistar, set up arrage in chi, and calculate corresponding redshifts
    results= camb.get_background(pars)
    chistar = results.conformal_time(0)- results.tau_maxvis
    chis = np.linspace(0,chistar,nz)
    zs=results.redshift_at_comoving_radial_distance(chis)
    #Calculate array of delta_chi, and drop first and last points where things go singular
    dchis = (chis[2:]-chis[:-2])/2
    dzs = (zs[2:]-zs[:-2])/2
    chis = chis[1:-1]
    zs = zs[1:-1]

    #Get the matter power spectrum interpolation object (based on RectBivariateSpline). 
    #Here for lensing we want the power spectrum of the Weyl potential.
    PK_kk = camb.get_matter_power_interpolator(pars, nonlinear=False, 
        hubble_units=False, k_hunit=False, kmax=kmax, var1=model.Transfer_tot, var2=model.Transfer_tot,
        zmax=zs[-1])
        

    ls = np.arange(2,2001+1, dtype=np.float64)

    w1 = np.ones(chis.shape)
    const = 3*om_tot*(pars.H0**2)/2/(pars.H0*np.sqrt(om_tot*(1+zs)**3 + 4.2*(10**(-5))/((pars.H0/100.)**2)*(1+zs)**4 + (1-om_tot)*(1+zs)**(3*(1+w_DE)) ))/(2.99792*(10**5))
    win = ((chistar-chis)/(chistar))
    K_k = const*(1+zs)*win*chis

    pool = Pool(processes = 32) 
    cl_kk = []
    cl_kk = pool.map(getCl, ls)
    
    pool.close() 
    pool.join()
    
    pars.set_dark_energy() 
    return cl_kk
Beispiel #37
0
}
l_plot_low_limit = 10
l_plot_upp_limit = 600
redshift = 2
l_max = 600

pars = model.CAMBparams(NonLinear=0,
                        WantTransfer=True,
                        H0=67.3,
                        omch2=0.1199,
                        ombh2=0.02205,
                        YHe=0.24770)
pars.DarkEnergy.set_params(w=-1.13)
pars.set_for_lmax(lmax=l_max)
pars.InitPower.set_params(ns=0.9603, As=2.196e-09)
results = camb.get_background(pars)
k = 10**np.linspace(-6, 1, 1000)
PK = get_matter_power_interpolator(pars,
                                   nonlinear=False,
                                   kmax=1,
                                   k_hunit=True,
                                   hubble_units=True)

pars_nl = model.CAMBparams(NonLinear=1,
                           WantTransfer=True,
                           H0=67.3,
                           omch2=0.1199,
                           ombh2=0.02205,
                           YHe=0.24770)
pars_nl.DarkEnergy.set_params(w=-1.13)
pars_nl.set_for_lmax(lmax=l_max)
Beispiel #38
0
    def testAssigments(self):
        ini = os.path.join(os.path.dirname(__file__), '..', 'inifiles', 'planck_2018.ini')
        if os.path.exists(ini):
            pars = camb.read_ini(ini)
            self.assertTrue(np.abs(camb.get_background(pars).cosmomc_theta() * 100 / 1.040909 - 1) < 2e-5)
        pars = camb.CAMBparams()
        pars.set_cosmology(H0=68.5, ombh2=0.022, mnu=0, omch2=0.1)
        self.assertAlmostEqual(pars.omegam, (0.022 + 0.1) / 0.685 ** 2)
        with self.assertRaises(AttributeError):
            pars.omegam = 1
        pars.InitPower.set_params(ns=0.01)
        data = camb.CAMBdata()
        data.Params = pars
        self.assertEqual(data.Params.InitPower.ns, pars.InitPower.ns)
        d = dark_energy.DarkEnergyFluid(w=-0.95)
        pars.DarkEnergy = d
        self.assertEqual(pars.DarkEnergy.w, -0.95)
        pars.DarkEnergy = dark_energy.AxionEffectiveFluid(w_n=0.4)
        data.Params = pars
        self.assertEqual(pars.DarkEnergy.w_n, 0.4)
        pars.z_outputs = [0.1, 0.4]
        self.assertEqual(pars.z_outputs[1], 0.4)
        pars.z_outputs[0] = 0.3
        self.assertEqual(pars.z_outputs[0], 0.3)
        pars.z_outputs = pars.z_outputs
        pars.z_outputs = []
        pars.z_outputs = None
        self.assertFalse(len(pars.z_outputs))
        with self.assertRaises(TypeError):
            pars.DarkEnergy = initialpower.InitialPowerLaw()
        pars.NonLinear = model.NonLinear_both
        printstr = str(pars)
        self.assertTrue('Want_CMB_lensing = True' in printstr and
                        "NonLinear = NonLinear_both" in printstr)
        pars.NonLinear = model.NonLinear_lens
        self.assertTrue(pars.NonLinear == model.NonLinear_lens)
        with self.assertRaises(ValueError):
            pars.NonLinear = 4
        pars.nu_mass_degeneracies = np.zeros(3)
        self.assertTrue(len(pars.nu_mass_degeneracies) == 3)
        pars.nu_mass_degeneracies = [1, 2, 3]
        self.assertTrue(pars.nu_mass_degeneracies[1] == 2)
        pars.nu_mass_degeneracies[1] = 5
        self.assertTrue(pars.nu_mass_degeneracies[1] == 5)
        with self.assertRaises(CAMBParamRangeError):
            pars.nu_mass_degeneracies = np.zeros(7)
        pars.nu_mass_eigenstates = 0
        self.assertFalse(len((pars.nu_mass_degeneracies[:1])))
        pars = camb.set_params(**{'InitPower.ns': 1.2, 'WantTransfer': True})
        self.assertEqual(pars.InitPower.ns, 1.2)
        self.assertTrue(pars.WantTransfer)
        pars.DarkEnergy = None

        from camb.sources import GaussianSourceWindow
        pars = camb.CAMBparams()
        pars.SourceWindows = [GaussianSourceWindow(), GaussianSourceWindow(redshift=1)]
        self.assertEqual(pars.SourceWindows[1].redshift, 1)
        pars.SourceWindows[0].redshift = 2
        self.assertEqual(pars.SourceWindows[0].redshift, 2)
        self.assertTrue(len(pars.SourceWindows) == 2)
        pars.SourceWindows[0] = GaussianSourceWindow(redshift=3)
        self.assertEqual(pars.SourceWindows[0].redshift, 3)
        self.assertTrue('redshift = 3.0' in str(pars))
        pars.SourceWindows = pars.SourceWindows[0:1]
        self.assertTrue(len(pars.SourceWindows) == 1)
        pars.SourceWindows = []
        self.assertTrue(len(pars.SourceWindows) == 0)