def loglkl(self, params): cosmo = Class() cosmo.set(params) cosmo.compute() chi2 = 0. # for each point, compute angular distance da, radial distance dr, # volume distance dv, sound horizon at baryon drag rs_d, # theoretical prediction and chi2 contribution for i in range(self.num_points): da = cosmo.angular_distance(self.z[i]) dr = self.z[i] / cosmo.Hubble(self.z[i]) dv = pow(da * da * (1 + self.z[i]) * (1 + self.z[i]) * dr, 1. / 3.) rs = cosmo.rs_drag() if self.type[i] == 3: theo = dv / rs elif self.type[i] == 4: theo = dv elif self.type[i] == 5: theo = da / rs elif self.type[i] == 6: theo = 1. / cosmo.Hubble(self.z[i]) / rs elif self.type[i] == 7: theo = rs / dv chi2 += ((theo - self.data[i]) / self.error[i]) ** 2 # return ln(L) # lkl = - 0.5 * chi2 # return -2ln(L) lkl = chi2 return lkl
def get_bao_rs_dV(zs,params=None,engine='camb',de='ppf'): #FIXME: camb and class only agree at 3% level!!! import camb params = map_params(params,engine=engine) if engine=='camb': pars = set_camb_pars(params=params,de=de) results = camb.get_results(pars) retval = results.get_BAO(zs,pars)[:,0] elif engine=='class': from classy import Class zs = np.asarray(zs) cosmo = Class() params['output'] = '' cosmo.set(params) cosmo.compute() Hzs = np.array([cosmo.Hubble(z) for z in zs]) D_As = np.array([cosmo.angular_distance(z) for z in zs]) D_Vs = ((1+zs)**2 * D_As**2 * zs/Hzs)**(1/3.) retval = cosmo.rs_drag()/D_Vs cosmo.struct_cleanup() cosmo.empty() return retval
class classy(SlikPlugin): """ Plugin for CLASS. Credit: Brent Follin, Teresa Hamill, Andy Scacco """ def __init__(self): super(classy,self).__init__() try: from classy import Class except ImportError: raise Exception("Failed to import CLASS python wrapper 'Classy'.") self.model = Class() def __call__(self, **kwargs): self.model.set(**kwargs) self.model.compute() ell = arange(l_max_scalar+1) self.cmb_result = {'cl_%s'%x:(self.model.lensed_cl(l_max_scalar)[x.lower()])*Tcmb**2*1e12*ell*(ell+1)/2/pi for x in ['TT','TE','EE','BB','PP','TP']} self.model.struct_cleanup() self.model.empty() return self.cmb_result def get_bao_observables(self, z): return {'H':self.model.Hubble(z), 'D_A':self.model.angular_distance(z), 'c':1.0, 'r_d':(self.model.get_current_derived_parameters(['rs_rec']))['rs_rec']}
class classy(SlikPlugin): """ Plugin for CLASS. Credit: Brent Follin, Teresa Hamill, Andy Scacco """ #{cosmoslik name : class name} - This needs to be done even for variables with the same name (because of for loop in self.model.set)! name_mapping = {#'As':'A_s', #'ns':'n_s', #'r':'r', 'custom1':'custom1', 'custom2':'custom2', 'custom3':'custom3', #'nt':'n_t', 'ombh2':'omega_b', 'omch2':'omega_cdm', 'omnuh2':'omega_ncdm', 'tau':'tau_reio', 'H0':'H0', 'massive_neutrinos':'N_ncdm', 'massless_neutrinos':'N_ur', 'Yp':'YHe', 'pivot_scalar':'k_pivot', 'omk':'Omega_k', 'l_max_scalar':'l_max_scalars', 'l_max_tensor':'l_max_tensors', 'Tcmb':'T_cmb' } def __init__(self): super(classy,self).__init__() try: from classy import Class except ImportError: raise Exception("Failed to import CLASS python wrapper 'Classy'.") self.model = Class() #def __call__(self, # **kwargs): # d={} # for k, v in kwargs.iteritems(): # if k in self.name_mapping and v is not None: # d[self.name_mapping[k]]=v # else: # d[k]=v #def __call__(self, #ombh2, #omch2, #H0, #As, #ns, #custom1, #custom2, #custom3, #tau, #w=None, #r=None, #nrun=None, #omk=0, #Yp=None, #Tcmb=2.7255, #massless_neutrinos=3.046, #l_max_scalar=3000, #l_max_tensor=3000, #pivot_scalar=0.05, #outputs=[], #**kwargs): #print kwargs def __call__(self,**kwargs): #print kwargs #print kwargs['classparamlist'] #print kwargs['d'] d={} for k,v in kwargs.iteritems(): if k in kwargs['classparamlist']: if k in self.name_mapping and v is not None: d[self.name_mapping[k]]=v else: d[k]=v #d['P_k_ini type']='external_Pk' #d['modes'] = 's,t' self.model.set(**d) l_max = d['l_max_scalars'] Tcmb = d['T_cmb'] #print l_max #print d self.model.compute() ell = arange(l_max+1) self.cmb_result = {'cl_%s'%x:(self.model.lensed_cl(l_max)[x.lower()])*Tcmb**2*1e12*ell*(ell+1)/2/pi for x in ['TT','TE','EE','BB','PP','TP']} self.model.struct_cleanup() self.model.empty() return self.cmb_result def get_bao_observables(self, z): return {'H':self.model.Hubble(z), 'D_A':self.model.angular_distance(z), 'c':1.0, 'r_d':(self.model.get_current_derived_parameters(['rs_rec']))['rs_rec']}
class classy(SlikPlugin): """ Plugin for CLASS. Credit: Brent Follin, Teresa Hamill, Andy Scacco """ #{cosmoslik name : class name} - This needs to be done even for variables with the same name (because of for loop in self.model.set)! name_mapping = {'As':'A_s', 'ns':'n_s', 'r':'r', 'phi0':'custom1', 'm6':'custom2', 'nt':'n_t', 'ombh2':'omega_b', 'omch2':'omega_cdm', 'omnuh2':'omega_ncdm', 'tau':'tau_reio', 'H0':'H0', 'massive_neutrinos':'N_ncdm', 'massless_neutrinos':'N_ur', 'Yp':'YHe', 'pivot_scalar':'k_pivot', } def __init__(self): super(classy,self).__init__() try: from classy import Class except ImportError: raise Exception("Failed to import CLASS python wrapper 'Classy'.") self.model = Class() def __call__(self, ombh2, omch2, H0, As, ns, phi0, m6, tau, w=None, r=None, nrun=None, omk=0, Yp=None, Tcmb=2.7255, massless_neutrinos=3.046, l_max_scalar=3000, l_max_tensor=3000, pivot_scalar=0.05, outputs=[], **kwargs): d={self.name_mapping[k]:v for k,v in locals().items() if k in self.name_mapping and v is not None} d['P_k_ini type']='external_Pk' d['modes'] = 's,t' self.model.set(output='tCl, lCl, pCl', lensing='yes', l_max_scalars=l_max_scalar, command = '../LSODAtesnors/pk', **d) self.model.compute() ell = arange(l_max_scalar+1) self.cmb_result = {'cl_%s'%x:(self.model.lensed_cl(l_max_scalar)[x.lower()])*Tcmb**2*1e12*ell*(ell+1)/2/pi for x in ['TT','TE','EE','BB','PP','TP']} self.model.struct_cleanup() self.model.empty() return self.cmb_result def get_bao_observables(self, z): return {'H':self.model.Hubble(z), 'D_A':self.model.angular_distance(z), 'c':1.0, 'r_d':(self.model.get_current_derived_parameters(['rs_rec']))['rs_rec']}
class tsz_gal_cl: def __init__(self): # print 'Class for tSZ Cl' # self.ptilde = np.loadtxt(LIBDIR+'/aux_files/ptilde.txt') self.fort_lib_cl = cdll.LoadLibrary(LIBDIR + "/source/calc_cl") self.fort_lib_cl.calc_cl_.argtypes = [ POINTER(c_double), #h0 POINTER(c_double), #obh2 POINTER(c_double), #och2 POINTER(c_double), #mnu POINTER(c_double), #bias POINTER(c_double), #Mcut POINTER(c_double), #M1 POINTER(c_double), #kappa POINTER(c_double), #sigma_Ncen POINTER(c_double), #alp_Nsat POINTER(c_double), #rmax POINTER(c_double), #rgs POINTER(c_int64), #pk_nk POINTER(c_int64), #pk_nz np.ctypeslib.ndpointer(dtype=np.double), #karr np.ctypeslib.ndpointer(dtype=np.double), #pkarr np.ctypeslib.ndpointer(dtype=np.double), #dndz POINTER(c_int64), #nz_dndz POINTER(c_double), #z1 POINTER(c_double), #z2 POINTER(c_double), #z1_ng POINTER(c_double), #z2_ng POINTER(c_int64), #nl np.ctypeslib.ndpointer(dtype=np.double), #ell np.ctypeslib.ndpointer(dtype=np.double), #gg np.ctypeslib.ndpointer(dtype=np.double), #gy np.ctypeslib.ndpointer(dtype=np.double), #tll POINTER(c_double), #ng(z1<z<z2) POINTER(c_int64), #flag_nu POINTER(c_int64), #flag_tll POINTER(c_int64), #nm POINTER(c_int64) #nz ] self.fort_lib_cl.calc_cl_.restype = c_void_p # Calcualtion setup self.kmin = 1e-3 self.kmax = 5. self.zmax = 4. # should be consistent with fortran code self.nk_pk = 200 self.nz_pk = 51 # Class self.cosmo = Class() def get_tsz_cl(self, ell_arr, params, dndz, z1, z2, z1_ng, z2_ng, nm, nz): self.zmin = z1 self.zmax = z2 obh2 = params['obh2'] och2 = params['och2'] As = params['As'] ns = params['ns'] mnu = params['mnu'] mass_bias = params['mass_bias'] Mcut = params['Mcut'] M1 = params['M1'] kappa = params['kappa'] sigma_Ncen = params['sigma_Ncen'] alp_Nsat = params['alp_Nsat'] rmax = params['rmax'] rgs = params['rgs'] flag_nu_logic = params['flag_nu'] flag_tll_logic = params['flag_tll'] if type(flag_nu_logic) != bool: print 'flag_nu must be boolean.' sys.exit() if flag_nu_logic: flag_nu = 1 else: flag_nu = 0 if type(flag_tll_logic) != bool: print 'flag_tll must be boolean.' sys.exit() if flag_tll_logic: flag_tll = 1 else: flag_tll = 0 if 'theta' in params.keys(): theta = params['theta'] pars = {'output':'mPk','100*theta_s':theta, 'omega_b':obh2,'omega_cdm':och2, 'A_s':As,'n_s':ns,\ 'N_ur':0.00641,'N_ncdm':1,'m_ncdm':mnu/3.,\ 'T_ncdm':0.71611,\ 'P_k_max_h/Mpc': self.kmax,'z_max_pk':self.zmax,\ 'deg_ncdm':3.} self.cosmo.set(pars) self.cosmo.compute() h0 = self.cosmo.h() elif 'h0' in params.keys(): h0 = params['h0'] pars = {'output':'mPk','h':h0, 'omega_b':obh2,'omega_cdm':och2, 'A_s':As,'n_s':ns,\ 'N_ur':0.00641,'N_ncdm':1,'m_ncdm':mnu/3.,\ 'T_ncdm':0.71611,\ 'P_k_max_h/Mpc': self.kmax,'z_max_pk':self.zmax,\ 'deg_ncdm':3.} self.cosmo.set(pars) self.cosmo.compute() derived = self.cosmo.get_current_derived_parameters( ['100*theta_s', 'sigma8']) vz = (self.cosmo.angular_distance(z2_ng)**3*(1+z2_ng)**3 \ -self.cosmo.angular_distance(z1_ng)**3*(1+z1_ng)**3) vz = vz * h0**3 * 4. * np.pi / 3. derived['vz'] = vz # get matter power spectra kh_arr = np.logspace(np.log10(self.kmin), np.log10(self.kmax), self.nk_pk) kh = np.zeros((self.nz_pk, self.nk_pk)) pk = np.zeros((self.nz_pk, self.nk_pk)) pk_zarr = np.linspace(self.zmin, self.zmax, self.nz_pk) for i in range(self.nz_pk): kh[i, :] = kh_arr if flag_nu == 0: pk[i, :] = np.array([ self.cosmo.pk(k * h0, pk_zarr[i]) * h0**3 for k in kh_arr ]) elif flag_nu == 1: pk[i, :] = np.array([ self.cosmo.pk_cb(k * h0, pk_zarr[i]) * h0**3 for k in kh_arr ]) # params h0_in = byref(c_double(h0)) obh2_in = byref(c_double(obh2)) och2_in = byref(c_double(och2)) mnu_in = byref(c_double(mnu)) mass_bias_in = byref(c_double(mass_bias)) Mcut_in = byref(c_double(Mcut)) M1_in = byref(c_double(M1)) kappa_in = byref(c_double(kappa)) sigma_Ncen_in = byref(c_double(sigma_Ncen)) alp_Nsat_in = byref(c_double(alp_Nsat)) rmax_in = byref(c_double(rmax)) rgs_in = byref(c_double(rgs)) flag_nu_in = byref(c_int64(flag_nu)) flag_tll_in = byref(c_int64(flag_tll)) # dNdz nz_dndz = byref(c_int64(len(dndz))) # integration setting z1_in = byref(c_double(self.zmin)) z2_in = byref(c_double(self.zmax)) # outputs nl = len(ell_arr) cl_gg = np.zeros((2, nl)) cl_gy = np.zeros((2, nl)) tll = np.zeros((nl * 2, nl * 2)) ng = c_double(0.0) nl = c_int64(nl) self.fort_lib_cl.calc_cl_( h0_in, obh2_in, och2_in, mnu_in,\ mass_bias_in, \ Mcut_in, M1_in, kappa_in, sigma_Ncen_in, alp_Nsat_in,\ rmax_in, rgs_in,\ byref(c_int64(self.nk_pk)), byref(c_int64(self.nz_pk)),\ np.array(kh),np.array(pk),\ np.array(dndz),nz_dndz,\ z1_in, z2_in,\ byref(c_double(z1_ng)),byref(c_double(z2_ng)),\ nl,np.array(ell_arr),\ cl_gg,cl_gy,tll,ng,\ flag_nu_in,flag_tll_in,\ c_int64(nm), c_int64(nz) ) self.cosmo.struct_cleanup() return cl_gg, cl_gy, tll, ng.value, derived
kmsMpc = 3.33564095198145e-6 rd = cosmo.rs_drag() print('rd=', rd) for j in range(len(chunk)): z = zs[j] b1 = b1ar[j] b2 = b2ar[j] bG2 = bG2ar[j] css0 = css0ar[j] css2 = css2ar[j] Pshot = Pshotar[j] bGamma3 = bGamma3ar[j] b4 = b4ar[j] fz = cosmo.scale_independent_growth_factor_f(z) da = cosmo.angular_distance(z) # print('DA=',da) hz = cosmo.Hubble(z) / kmsMpc # print('Hz=',hz) DV = (z * (1 + z)**2 * da**2 / cosmo.Hubble(z))**(1. / 3.) # print('DV=',DV) fs8 = cosmo.scale_independent_growth_factor( z) * cosmo.scale_independent_growth_factor_f(z) * cosmo.sigma8() # print('fs8=',fs8) # print('sigma8=',cosmo.sigma8()) print('rd/DV=', rd / DV) print('rdH=', rd * cosmo.Hubble(z)) print('rd/DA=', rd / da) P2noW = np.zeros(k_size) P0noW = np.zeros(k_size)
class classy(SlikPlugin): """ Plugin for CLASS. Credit: Brent Follin, Teresa Hamill """ #{cosmoslik name : class name} name_mapping = {'As':'A_s', 'ns':'n_s', 'r':'r', 'nt':'n_t', 'ombh2':'omega_b', 'omch2':'omega_cdm', 'omnuh2':'omega_ncdm', 'tau':'tau_reio', 'H0':'H0', 'massive_neutrinos':'N_ncdm', 'massless_neutrinos':'N_ur', 'Yp':'YHe', 'pivot_scalar':'k_pivot'} def __init__(self): super(classy,self).__init__() try: from classy import Class except ImportError: raise Exception("Failed to import CLASS python wrapper 'Classy'.") self.model = Class() def __call__(self, ombh2, omch2, H0, As, ns, tau, omnuh2, #0.006 w=None, r=None, nrun=None, omk=0, Yp=None, Tcmb=2.7255, massive_neutrinos=1, massless_neutrinos=2.046, l_max_scalar=3000, l_max_tensor=3000, pivot_scalar=0.002, outputs=[], **kwargs): self.model.set(output='tCl, lCl, pCl', lensing='yes', l_max_scalars=l_max_scalar, **{self.name_mapping[k]:v for k,v in locals().items() if k in self.name_mapping and v is not None}) self.model.compute() ell = arange(l_max_scalar+1) self.cmb_result = {'cl_%s'%x:(self.model.lensed_cl(l_max_scalar)[x.lower()])*Tcmb**2*1e12*ell*(ell+1)/2/pi for x in ['TT','TE','EE','BB','PP','TP']} self.model.struct_cleanup() self.model.empty() return self.cmb_result def get_bao_observables(self, z): return {'H':self.model.Hubble(z), 'D_A':self.model.angular_distance(z), 'c':1.0, 'r_d':(self.model.get_current_derived_parameters(['rs_rec']))['rs_rec']}
class classy(SlikPlugin): """ Plugin for CLASS. Credit: Brent Follin, Teresa Hamill, Andy Scacco """ #{cosmoslik name : class name} - This needs to be done even for variables with the same name (because of for loop in self.model.set)! name_mapping = {'As':'A_s', 'ns':'n_s', 'r':'r', 'k_c':'k_c', 'alpha_exp':'alpha_exp', 'nt':'n_t', 'ombh2':'omega_b', 'omch2':'omega_cdm', 'omnuh2':'omega_ncdm', 'tau':'tau_reio', 'H0':'H0', 'massive_neutrinos':'N_ncdm', 'massless_neutrinos':'N_ur', 'Yp':'YHe', 'pivot_scalar':'k_pivot', #'Tcmb':'T_cmb', #'P_k_max_hinvMpc':'P_k_max_h/Mpc' #'w':'w0_fld', #'nrun':'alpha_s', #'omk':'Omega_k', #'l_max_scalar':'l_max_scalars', #'l_max_tensor':'l_max_tensors' } def __init__(self): super(classy,self).__init__() try: from classy import Class except ImportError: raise Exception("Failed to import CLASS python wrapper 'Classy'.") self.model = Class() def __call__(self, ombh2, omch2, H0, As, ns, k_c, alpha_exp, tau, #omnuh2=0, #0.006 #None means that Class will take the default for this, maybe? w=None, r=None, nrun=None, omk=0, Yp=None, Tcmb=2.7255, #massive_neutrinos=0, massless_neutrinos=3.046, l_max_scalar=3000, l_max_tensor=3000, pivot_scalar=0.05, outputs=[], **kwargs): self.model.set(output='tCl, lCl, pCl', lensing='yes', l_max_scalars=l_max_scalar, **{self.name_mapping[k]:v for k,v in locals().items() if k in self.name_mapping and v is not None}) self.model.compute() ell = arange(l_max_scalar+1) self.cmb_result = {'cl_%s'%x:(self.model.lensed_cl(l_max_scalar)[x.lower()])*Tcmb**2*1e12*ell*(ell+1)/2/pi for x in ['TT','TE','EE','BB','PP','TP']} self.model.struct_cleanup() self.model.empty() return self.cmb_result def get_bao_observables(self, z): return {'H':self.model.Hubble(z), 'D_A':self.model.angular_distance(z), 'c':1.0, 'r_d':(self.model.get_current_derived_parameters(['rs_rec']))['rs_rec']}
class classy(SlikPlugin): """ Compute the CMB power spectrum with CLASS. Based on work by: Brent Follin, Teresa Hamill """ #{cosmoslik name : class name} name_mapping = { 'As': 'A_s', 'lmax': 'l_max_scalars', 'mnu': 'm_ncdm', 'Neff': 'N_ncdm', 'ns': 'n_s', 'nt': 'n_t', 'ombh2': 'omega_b', 'omch2': 'omega_cdm', 'omk': 'Omega_k', 'pivot_scalar': 'k_pivot', 'r': 'r', 'tau': 'tau_reio', 'Tcmb': 'T_cmb', 'Yp': 'YHe', } def __init__(self, **defaults): super().__init__() from classy import Class self.model = Class() self.defaults = defaults def convert_params(self, **params): """ Convert from CosmoSlik params to CLASS """ params = {self.name_mapping.get(k, k): v for k, v in params.items()} if 'theta' in params: params['100*theta_s'] = 100 * params.pop('theta') params['lensing'] = 'yes' if params.pop('DoLensing', True) else 'no' return params def __call__(self, As=None, DoLensing=True, H0=None, lmax=None, mnu=None, Neff=None, nrun=None, ns=None, ombh2=None, omch2=None, omk=None, output='tCl, lCl, pCl', pivot_scalar=None, r=None, tau=None, Tcmb=2.7255, theta=None, w=None, Yp=None, nowarn=False, **kwargs): if not nowarn and kwargs: print('Warning: passing unknown parameters to CLASS: ' + str(kwargs) + ' (set nowarn=True to turn off this message.)') params = dict( self.defaults, **{ k: v for k, v in arguments(include_kwargs=False, exclude=["nowarn"]).items() if v is not None }) self.model.set(self.convert_params(**params)) self.model.compute() lmax = params['lmax'] ell = arange(lmax + 1) if params['DoLensing'] == True: self.cmb_result = { x: (self.model.lensed_cl(lmax)[x.lower()]) * Tcmb**2 * 1e12 * ell * (ell + 1) / 2 / pi for x in ['TT', 'TE', 'EE', 'BB', 'PP', 'TP'] } else: self.cmb_result = { x: (self.model.raw_cl(lmax)[x.lower()]) * Tcmb**2 * 1e12 * ell * (ell + 1) / 2 / pi for x in ['TT'] } self.model.struct_cleanup() self.model.empty() return self.cmb_result def get_bao_observables(self, z): return { 'H': self.model.Hubble(z), 'D_A': self.model.angular_distance(z), 'c': 1.0, 'r_d': (self.model.get_current_derived_parameters(['rs_rec']))['rs_rec'] }