def do_model_setup(self, params): """ Method to calculate the power spectrum primordial and lensing templates for a given set of cosmological parameters. This computation requires that the lmax be set much higher that the lmax required in the final analys.s Parameters ---------- params: dict Dictionary of cosmological parameters to be sent to CLASS. Returns ------- tuple(array_like(float)) Tuple containing the BB primordial and lensing templates. """ try: params.pop('a_lens') except: pass params.update({ 'output': 'tCl pCl lCl', 'l_max_scalars': 5000, 'l_max_tensors': 2000, 'modes': 's, t', 'r': 1, 'lensing': 'yes', }) cosm = Class() cosm.set(params) cosm.compute() # get the lensed and raw power spectra up to the maximum # multipole used in the likelihood analysis. Multiply by # T_CMB ^ 2 to get from dimensionless to uK^2 units. lensed_cls = cosm.lensed_cl(3 * self.nside - 1)['bb'] * (2.7225e6)**2 raw_cls = cosm.raw_cl(3 * self.nside - 1)['bb'] * (2.7225e6)**2 # get ells, used in the calculation of the foreground model # over the same range. ells = cosm.raw_cl(3 * self.nside - 1)['ell'] # do the house keeping for the CLASS code. cosm.struct_cleanup() cosm.empty() # calculate the lensing-only template lens_template = self.apply_coupling(lensed_cls - raw_cls) raw_cls = self.apply_coupling(raw_cls) # now separately do the foreground template setup. if self.marg: fg_template = np.zeros(3 * self.nside) fg_template[1:] = (ells[1:] / 80.)**-2.4 fg_template = self.apply_coupling(fg_template) return (raw_cls, lens_template, fg_template) return (raw_cls, lens_template)
def class_spectrum(params): """ Function to generate the theoretical CMB power spectrum for a given set of parameters. Parameters ---------- params: dict dict containing the parameters expected by CLASS and their values. Returns ------- array_like(float) Array of shape (4, lmax + 1) containing the TT, EE, BB, TE power spectra. """ # This line is crucial to prevent pop from removing the lensing efficieny # from future runs in the same script. class_pars = {**params} try: # if lensing amplitude is set, remove it from dictionary that will # be passed to CLASS. a_lens = class_pars.pop('a_lens') except KeyError: # if not set in params dictionary just set to 1. a_lens = 1 # generate the CMB realizations. print("Running CLASS with lensing efficiency: ", a_lens) cos = Class() cos.set(class_pars) cos.compute() # returns CLASS format, 0 to lmax, dimensionless, Cls. # multiply by (2.7225e6) ** 2 to get in uK_CMB ^ 2 lensed_cls = cos.lensed_cl() raw_bb = cos.raw_cl()['bb'][:class_pars['l_max_scalars'] + 1] # calculate the lensing contribution to BB and rescale by # the lensing amplitude factor. lensing_bb = a_lens * (lensed_cls['bb'] - raw_bb) cos.struct_cleanup() cos.empty() synfast_cls = np.zeros((4, class_pars['l_max_scalars'] + 1)) synfast_cls[0, :] = lensed_cls['tt'] synfast_cls[1, :] = lensed_cls['ee'] synfast_cls[2, :] = lensing_bb + raw_bb synfast_cls[3, :] = lensed_cls['te'] return synfast_cls * (2.7225e6)**2
def get_theoretical_TT_TE_EE_unbinned_power_spec_D_ell(self, class_dict): ellmin = self.lmin_class ellmax = self.plmax cosmo = Class() cosmo.set(class_dict) cosmo.compute() cls = cosmo.lensed_cl(3000) cosmo.struct_cleanup() cosmo.empty() #get in units of microkelvin squared T_fac=(self.T_cmb*1e6)**2 ell=cls['ell'] D_fac=ell*(ell+1.)/(2*np.pi) Dltt=(T_fac*D_fac*cls['tt'])[ellmin:ellmax+1] Dlte=(T_fac*D_fac*cls['te'])[ellmin:ellmax+1] Dlee=(T_fac*D_fac*cls['ee'])[ellmin:ellmax+1] return cls['ell'][ellmin:ellmax+1], Dltt, Dlte, Dlee
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']}
def _run_class(self, **kwargs): """Method to run class and return the lensed and unlensed spectra as dictionaries. Returns ------- cls_l : `dict` Dictionary containing the lensed spectra for a given run of CLASS. cls_u : `dict` Dictionary containing the unlensed spectra for the same run of CLASS. """ cosmo = Class() # Set some parameters we want that are not in the default CLASS setting. class_pars = { 'output': 'tCl pCl lCl', 'modes': 's, t', 'lensing': self.lensing, 'r': self.r, } # Update CLASS run with any kwargs that were passed. This is useful in # Pyranha.compute_cosmology in order to compute the r=1 case. class_pars.update(kwargs) cosmo.set(class_pars) cosmo.compute() # Get the lensed and unlensed spectra as dictionaries. cls_l = cosmo.lensed_cl(2500) cls_u = cosmo.raw_cl(2500) # Do the memory cleanup. cosmo.struct_cleanup() cosmo.empty() return cls_l, cls_u
'omega_b': 0.02225, 'omega_cdm': 0.1198, 'ln10^{10}A_s': 3.094, 'n_s': 0.9645, 'tau_reio': 0.079, 'do_shooting': 'yes' }) # M.compute() all_k = M.get_perturbations( ) # this potentially constains scalars/tensors and all k values conversion = pow(2.7255 * 1.e6, 2) # one_k = all_k['scalar'][0] # this contains only the scalar perturbations for the requested k values clM = M.lensed_cl(2500) ll_LCDM = clM['ell'][2:] clTT_LCDM = clM['tt'][2:] clEE_LCDM = clM['ee'][2:] clTE_LCDM = clM['te'][2:] clPP_LCDM = clM['pp'][2:] # ax_TT.semilogx(ll_LCDM,(ll_LCDM)*(ll_LCDM+1)/(2*np.pi)*(clTT_LCDM),'k',lw=5) # ax_EE.semilogx(ll_LCDM,(ll_LCDM)*(ll_LCDM+1)/(2*np.pi)*(clEE_LCDM),'k',lw=5) # ax_PP.semilogx(ll_LCDM,(ll_LCDM)*(ll_LCDM+1)/(2*np.pi)*(clPP_LCDM),'k',lw=5) pkM_LCDM = [] for k in kvec: pkM_LCDM.append(M.pk(k, 0.)) # i=i+1
'omega_b': 0.022032, 'omega_cdm': 0.12038, 'h': 0.67556, 'A_s': 2.215e-9, 'tau_reio': 0.0925, 'ic': 'cdi' }) LambdaCDM1.set({ 'output': 'tCl,pCl,lCl,mPk', 'lensing': 'yes', 'P_k_max_1/Mpc': 3.0 }) # run class LambdaCDM1.compute() # get all C_l output cls1 = LambdaCDM1.lensed_cl(2500) # To check the format of cls # ~cls.viewkeys() ll1 = cls1['ell'][2:] clTT1 = cls1['tt'][2:] clEE1 = cls1['ee'][2:] clPP1 = cls1['pp'][2:] # create instance of the class "Class" LambdaCDM2 = Class() # pass input parameters LambdaCDM2.set({ 'omega_b': 0.022032, 'omega_cdm': 0.12038, 'h': 0.67556,
class Peturbations: def __init__(self): self.cosmo = Class() def cosmo_Cl_GR(self): """ Compute cosmology for General Relativity with Planck15 parameters. """ #zstr=','.join(map(str,zlist+zlist[-1]+2)) lcdmpars = {'output': 'tCl, pCl, lCl', 'lensing': 'yes', #'P_k_max_h/Mpc':20, #'z_pk': zstr, 'background_verbose': 1, #Info 'tau_reio': 0.07, 'omega_cdm': 0.11987, 'A_s': 2.204e-9, 'h': 0.6715918, #computed from 100*theta_s=1.042143 'N_ur': 3.046-1., 'N_ncdm': 1., 'm_ncdm': 0.06, 'omega_b': 0.022252, 'n_s': 0.96475, } self.cosmo.set(lcdmpars) self.cosmo.compute() def cosmo_Cl_MG(self, alpha_b, alpha_m, a_trans, r): """ Compute cosmology for Modified gravity with a LCDM background expansion (with Planck15 parameters) and 'hill_scale' parameterization for the property functions. """ #zstr=','.join(map(str,zlist+zlist[-1]+2)) mgpars = {'output': 'tCl, pCl, lCl', 'lensing': 'yes', 'background_verbose': 1, #Info 'tau_reio': 0.07, 'omega_cdm': 0.11987, 'A_s': 2.204e-9, 'h': 0.6715918, #computed from 100*theta_s=1.042143 'N_ur': 3.046-1., 'N_ncdm': 1., 'm_ncdm': 0.06, 'omega_b': 0.022252, 'n_s': 0.96475, 'Omega_Lambda': 0, 'Omega_fld': 0, 'Omega_smg': -1, 'expansion_model': 'lcdm', 'gravity_model': 'hill_scale', } # Planck Mass Mstarsq = 1. # Property Functions alpha_t = 0. alpha_k = 0.001 mgpars['parameters_smg'] = "{}, {}, {}, {}, {}, {}, {}".format( Mstarsq, alpha_k, alpha_b, alpha_m, alpha_t, a_trans, r) self.cosmo.set(mgpars) self.cosmo.compute() def Cl_kappa_kappa_GR(self, llist): """ Get C_ell^kappakappa for General Relativity """ self.cosmo_Cl_GR() lmax = llist[-1] Cl_phi_phi_GR = self.cosmo.lensed_cl(lmax)['pp'][2:] Cl_kap_kap_GR = (1./4.) * ((llist * (llist + 1.))**2.) * Cl_phi_phi_GR return Cl_kap_kap_GR def Cl_kappa_kappa_MG(self, llist, alpha_b, alpha_m, a_trans, r): """ Get C_ell^kappakappa for Modified Gravity with a LCDM background expansion and hill_scale parameterization for the property functions. """ self.cosmo_Cl_MG(alpha_b, alpha_m, a_trans, r) lmax = llist[-1] Cl_phi_phi_MG = self.cosmo.lensed_cl(lmax)['pp'][2:] Cl_kap_kap_MG = (1./4.) * ((llist * (llist + 1.))**2.) * Cl_phi_phi_MG return Cl_kap_kap_MG
'A_s':2.215e-9, 'n_s':0.9619, 'tau_reio':0.0925, # Take fixed value for primordial Helium (instead of automatic BBN adjustment) 'YHe':0.246, # other output and precision parameters 'l_max_scalars':5000} ############### # # call CLASS # M = Class() M.set(common_settings) M.compute() cl_tot = M.raw_cl(3000) cl_lensed = M.lensed_cl(3000) M.struct_cleanup() # clean output M.empty() # clean input # M.set(common_settings) # new input M.set({'temperature contributions':'tsw'}) M.compute() cl_tsw = M.raw_cl(3000) M.struct_cleanup() M.empty() # M.set(common_settings) M.set({'temperature contributions':'eisw'}) M.compute() cl_eisw = M.raw_cl(3000) M.struct_cleanup()
"transfer_neglect_delta_k_V_t1": 100., "transfer_neglect_delta_k_V_t2": 100., "transfer_neglect_delta_k_V_e": 100., "transfer_neglect_delta_k_V_b": 100., "transfer_neglect_delta_k_T_t2": 100., "transfer_neglect_delta_k_T_e": 100., "transfer_neglect_delta_k_T_b": 100., "neglect_CMB_sources_below_visibility": 1.e-30, "transfer_neglect_late_source": 3000. # 'm_ncdm' : 0.06 } cosmo = Class() cosmo.set(params) cosmo.compute() cls = cosmo.lensed_cl(ell_max) ttCLASS = cls['ell'] * (cls['ell'] + 1) * cls['tt'] * (1e6 * 2.7255)**2 / (2 * np.pi) cosmo.struct_cleanup() ## Commented cosmo.empty() ## Commented ################################################################## ######## HIGH ELL TT #################################33 #################################################### plt.plot((ttCLASS[:ell_max + 1] - ttCAMB[:ell_max + 1]) / ttCAMB[:ell_max + 1], '-') plt.xlabel(r'$\ell$') plt.ylabel(r'$\Delta C_{\ell}^{TT} / C_{\ell}^{TT}$') plt.title('TT Comparison of CAMB and CLASS')
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'] }
from classy import Class import healpy as hp import numpy as np params = [('output', 'tCl pCl lCl'), ('l_max_scalars', 5000), ('lensing', 'yes'), ('n_s', 0.9665), ('omega_b', 0.02242), ('omega_cdm', 0.11933), ('100*theta_s', 1.04101), ('ln10^{10}A_s', 3.047), ('tau_reio', 0.0561)] cosmo = Class() cosmo.set(params) cosmo.compute() cls = cosmo.lensed_cl(5000) cls_list = [it for _, it in cls.items()] eb_tb = np.zeros(shape=cls["tt"].shape) I, Q, U = hp.synfast( (cls['tt'], cls['ee'], cls['bb'], cls['te'], eb_tb, eb_tb), nside=32, new=True) print(Q.shape) cosmo.struct_cleanup() cosmo.empty()
import numpy as np from classy import Class params = {'output': 'tCl pCl lCl', 'lensing': 'yes'} cosmo = Class() cosmo.set(params) cosmo.compute() cls = cosmo.lensed_cl(768) for k in ['tt', 'te', 'ee', 'bb']: cls[k] *= 1e12 np.savetxt('data/example_cls.txt', np.array([cls['ell'], cls['tt'], cls['te'], cls['ee'], cls['bb']]).T, fmt=('%i %e %e %e %e'), header='ell TT TE EE BB', delimiter=',')
class Sampler: def __init__(self, NSIDE): self.NSIDE = NSIDE self.Npix = 12 * NSIDE**2 print("Initialising sampler") self.cosmo = Class() print("Maps") self.templates_map, self.templates_var = aggregate_pixels_params( get_pixels_params(self.NSIDE)) print("betas") self.matrix_mean, self.matrix_var = aggregate_mixing_params( get_mixing_matrix_params(self.NSIDE)) print("Cosmo params") self.cosmo_means = np.array(COSMO_PARAMS_MEANS) self.cosmo_var = (np.diag(COSMO_PARAMS_SIGMA) / 2)**2 plt.hist(self.templates_map) plt.savefig("mean_values.png") plt.close() plt.hist(self.templates_var) plt.savefig("std_values.png") plt.close() self.instrument = pysm.Instrument( get_instrument('litebird', self.NSIDE)) self.components = [CMB(), Dust(150.), Synchrotron(150.)] self.mixing_matrix = MixingMatrix(*self.components) self.mixing_matrix_evaluator = self.mixing_matrix.evaluator( self.instrument.Frequencies) print("End of initialisation") def __getstate__(self): state_dict = self.__dict__.copy() del state_dict["mixing_matrix_evaluator"] del state_dict["cosmo"] del state_dict["mixing_matrix"] del state_dict["components"] return state_dict def __setstate__(self, state): self.__dict__.update(state) self.cosmo = Class() self.components = [CMB(), Dust(150.), Synchrotron(150.)] self.mixing_matrix = MixingMatrix(*self.components) self.mixing_matrix_evaluator = self.mixing_matrix.evaluator( self.instrument.Frequencies) def sample_normal(self, mu, sigma, s=None): return np.random.multivariate_normal(mu, sigma, s) def sample_model_parameters(self): #sampled_cosmo = self.sample_normal(self.cosmo_means, self.cosmo_var) sampled_cosmo = np.array([ 0.9665, 0.02242, 0.11933, 1.04101, 3.047, 0.0561 ]) - 2 * np.array(COSMO_PARAMS_SIGMA) #sampled_beta = self.sample_normal(self.matrix_mean, self.matrix_var).reshape((self.Npix, -1), order = "F") sampled_beta = self.matrix_mean.reshape((self.Npix, -1), order="F") return sampled_cosmo, sampled_beta def sample_CMB_QU(self, cosmo_params): params = { 'output': OUTPUT_CLASS, 'l_max_scalars': L_MAX_SCALARS, 'lensing': LENSING } params.update(cosmo_params) self.cosmo.set(params) self.cosmo.compute() cls = self.cosmo.lensed_cl(L_MAX_SCALARS) eb_tb = np.zeros(shape=cls["tt"].shape) _, Q, U = hp.synfast( (cls['tt'], cls['ee'], cls['bb'], cls['te'], eb_tb, eb_tb), nside=self.NSIDE, new=True) self.cosmo.struct_cleanup() self.cosmo.empty() return Q, U def sample_mixing_matrix(self, betas): mat_pixels = [] for i in range(self.Npix): m = self.mixing_matrix_evaluator(betas[i, :]) mat_pixels.append(m) mixing_matrix = np.stack(mat_pixels, axis=0) return mixing_matrix def sample_model(self): cosmo_params, sampled_beta = self.sample_model_parameters() #maps = self.sample_normal(self.templates_map, self.templates_var) cosmo_dict = { l[0]: l[1] for l in zip(COSMO_PARAMS_NAMES, cosmo_params.tolist()) } tuple_QU = self.sample_CMB_QU(cosmo_dict) map_CMB = np.stack(tuple_QU, axis=1) ''' mixing_matrix = self.sample_mixing_matrix(sampled_beta) map_Sync = np.stack([maps[0:self.Npix], maps[self.Npix:2*self.Npix]], axis = 1) map_Dust = np.stack([maps[2*self.Npix:3*self.Npix], maps[3*self.Npix:]], axis = 1) entire_map = np.stack([map_CMB, map_Dust, map_Sync], axis = 1) dot_prod = [] for j in range(self.Npix): m = np.dot(mixing_matrix[j, :, :], entire_map[j, :, :]) dot_prod.append(m) sky_map = np.stack(dot_prod, axis = 0) ''' sky_map = map_CMB return { "sky_map": sky_map, "cosmo_params": cosmo_params, "betas": sampled_beta } #sampler = Sampler(NSIDE) #r = sampler.sample_model(1) #['beta_d' 'temp' 'beta_pl'] #['beta_d' 'temp'] #['beta_pl']
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 Model(): def __init__(self, cosmo=None): """ Initialize the Model class. By default Model uses its own Class instance. cosmo = external Class instance. Default is None """ if cosmo: self.cosmo = cosmo else: self.cosmo = Class() self.computed = {} self.texnames = {} def __set_scale(self, axes, xscale, yscale): """ Set scales for axes in axes array. axes = axes array (e.g. f, ax = plt.subplots(2,2)) xscale = linear array of xscale. yscale = linear array of yscale. Scales are set once axes is flatten. Each plot is counted from left to right an from top to bottom. """ for i, ax in enumerate(axes.flat): ax.set_xscale(xscale[i]) ax.set_yscale(yscale[i]) def __set_label(self, axes, xlabel, ylabel): """ Set labels for axes in axes array. axes = axes array (e.g. f, ax = plt.subplots(2,2)) xlabel = linear array of xlabels. ylabel = linear array of ylabels. Labels are set once axes is flatten. Each plot is counted from left to right an from top to bottom. """ for i, ax in enumerate(axes.flat): ax.set_xlabel(xlabel[i]) ax.set_ylabel(ylabel[i]) def __store_cl(self, cl_dic): """ Store cl's as (l*(l+1)/2pi)*cl, which is much more useful. """ ell = cl_dic['ell'][2:] for cl, list_val in cl_dic.iteritems(): list_val = list_val[2:] if (list_val == ell).all(): cl_dic[cl] = list_val continue list_val = (ell * (ell + 1) / (2 * np.pi)) * list_val cl_dic[cl] = list_val # Remove first two null items (l=0,1) return cl_dic def add_derived(self, varied_name, keys, value): """ Add a derived parameter for varied_name dictionary. varied_name = varied variable's name. keys = list of keys in descending level. value = value to store for new dictionary key. """ dic = self.computed[varied_name] for key in keys: if key not in dic: dic[key] = {} dic = dic[key] dic.update(value) def compute_models(self, params, varied_name, index_variable, values, back=[], thermo=[], prim=[], pert=[], trans=[], pk=[0.0001, 0.1, 100], extra=[], update=True, cosmo_msg=False, texname=""): """ Fill dic with the hi_class output structures for the model with given params, modifying the varied_name value with values. params = parameters to be set in Class. They must be in agreement with what is asked for. varied_name = the name of the variable you are modifying. It will be used as key in dic assigned to its background structures. index_variable = variable's index in parameters_smg array. values = varied variable values you want to compute the cosmology for. back = list of variables to store from background. If 'all', store the whole dictionary. thermo = list of variables to store from thermodynamics. If 'all', store the whole dictionary. prim = list of variables to store from primordial. If 'all', store the whole dictionary. pert = list of variables to store from perturbations. If 'all', store the whole dictionary. trans = list of variables to store from transfer. If 'all', store the whole dictionary. get_transfer accept two optional arguments: z=0 and output_format='class' (avaible options are 'class' or 'camb'). If different values are desired, first item of trans must be {'z': value, 'output_format': value}. pk = list with the minimum and maximum k values to store the present matter power spectrum and the number of points [k_min, k_max, number_points]. Default [10^-4, 10^1, 100]. extra = list of any of the method or objects defined in cosmo, e.g. w0_smg(). It will store {'method': cosmo.w0_smg()} update = if True update old computed[key] dictionary elsewise create a new one. Default: True. cosmo_msg = if True, print cosmo.compute() messages. Default: False. """ key = varied_name if texname: self.set_texnames({varied_name: texname}) elif key not in self.texnames: # texname will not be set at this stage. No check required self.set_texnames({varied_name: varied_name}) if (not update) or (key not in self.computed.keys()): self.computed[key] = od() for val in values: # key = "{}={}".format(varied_name, val) params["parameters_smg"] = inip.vary_params(params["parameters_smg"], [[index_variable, val]]) # It might be after the try to not store empty dictionaries. # Nevertheless, I find more useful having them to keep track of # those failed and, perhaps, to implement a method to obtain them # with Omega_smg_debug. d = self.computed[key][val] = {} self.cosmo.empty() self.cosmo.set(params) try: self.cosmo.compute() except Exception, e: print "Error: skipping {}={}".format(key, val) if cosmo_msg: print e continue d['tunned'] = self.cosmo.get_current_derived_parameters(['tuning_parameter'])['tuning_parameter'] for lst in [[back, 'back', self.cosmo.get_background], [thermo, 'thermo', self.cosmo.get_thermodynamics], [prim, 'prim', self.cosmo.get_thermodynamics]]: if lst[0]: output = lst[2]() if lst[0][0] == 'all': d[lst[1]] = output else: d[lst[1]] = {} for item in back: if type(item) is list: d[lst[1]].update({item[0]: output[item[0]][item[1]]}) else: d[lst[1]].update({item: output[item]}) if pert: # Perturbation is tricky because it can accept two optional # argument for get_perturbations and this method returns a # dictionary {'kind_of_pert': [{variable: list_values}]}, where # each item in the list is for a k (chosen in params). if type(pert[0]) is dict: output = self.cosmo.get_perturbations(pert[0]['z'], pert[0]['output_format']) if pert[1] == 'all': d['pert'] = output else: output = self.cosmo.get_perturbations() if pert[0] == 'all': d['pert'] = output if (type(pert[0]) is not dict) and (pert[0] != 'all'): d['pert'] = {} for subkey, lst in output.iteritems(): d['pert'].update({subkey: []}) for n, kdic in enumerate(lst): # Each item is for a k d['pert'][subkey].append({}) for item in pert: if type(item) is list: d['pert'][subkey][n].update({item[0]: kdic[item[0]][item[1]]}) else: d['pert'][subkey][n].update({item: kdic[item]}) for i in extra: exec('d[i] = self.cosmo.{}'.format(i)) try: d['cl'] = self.__store_cl(self.cosmo.raw_cl()) except CosmoSevereError: pass try: d['lcl'] = self.__store_cl(self.cosmo.lensed_cl()) except CosmoSevereError: pass try: d['dcl'] = self.cosmo.density_cl() except CosmoSevereError: pass if ("output" in self.cosmo.pars) and ('mPk' in self.cosmo.pars['output']): k_array = np.linspace(*pk) pk_array = np.array([self.cosmo.pk(k, 0) for k in k_array]) d['pk'] = {'k': k_array, 'pk': pk_array} self.cosmo.struct_cleanup()
'lensing': 'yes', 'P_k_ini type': 'external_Pk', 'command': 'python /home/andrew/Research/tools/class_public-2.4.3/external_Pk/generate_Pk_cosines.py', 'custom1': 0, 'custom2': 0, 'custom3': 0, 'custom4': 0, 'custom5': 0 } #Get the unperturbed cls for comparison cosmo = Class() cosmo.set(params) cosmo.compute() clso = cosmo.lensed_cl(2508)['tt'][30:] ell = cosmo.lensed_cl(2508)['ell'][30:] for i in range(len(clso)): clso[i] = ell[i] * (ell[i] + 1) / (4 * np.pi) * ((2.726e6)**2) * clso[i] a = np.zeros(5) cosmo.struct_cleanup() cosmo.empty() dcls = np.zeros([clso.shape[0], 5]) h = 1e-6 for m in range(5): a[m] = h # Define your cosmology (what is not specified will be set to CLASS default parameters) params = { 'output': 'tCl lCl', 'l_max_scalars': 2508,
def calculate_derivative_param(params, param_to_test, param_fiducial, percentage_difference, param_list, der_param, write_file, i): cosmo = Class() # Create an instance of the CLASS wrapper param = np.zeros((N, 3, len(param_list))) for j in range(3): # going over a_c and Om_fld values # if j==0: # params['Omega_fld_ac'] = Omega_ac_fid[i] # if j==1: # params['Omega_fld_ac'] = Omega_ac_fid[i]+percentage_difference*Omega_ac_fid[i] # if j==2: # params['Omega_fld_ac'] = Omega_ac_fid[i]-percentage_difference*Omega_ac_fid[i] if param_to_test == 'scf_parameters': if j == 0: params['scf_parameters'] = '%.5f,0.0' % (param_fiducial) if j == 1: params['scf_parameters'] = '%.5f,0.0' % ( param_fiducial + percentage_difference * param_fiducial) if j == 2: params['scf_parameters'] = '%.5f,0.0' % ( param_fiducial - percentage_difference * param_fiducial) else: if j == 0: params[param_to_test] = param_fiducial if j == 1: params[ param_to_test] = param_fiducial + percentage_difference * param_fiducial if j == 2: params[ param_to_test] = param_fiducial - percentage_difference * param_fiducial # if j==0: # params['Omega_many_fld'] = Omega0_fld # if j==1: # params['Omega_many_fld'] = Omega0_fld+percentage_difference*Omega0_fld # if j==2: # params['Omega_many_fld'] = Omega0_fld-percentage_difference*Omega0_fld print params[param_to_test], param_fiducial # try to solve with a certain cosmology, no worries if it cannot # l_theta_s = np.pi/(theta_s) # print "here:",l_theta_s # try: cosmo.set(params) # Set the parameters to the cosmological code cosmo.compute() # solve physics cl = cosmo.lensed_cl(2500) ell = cl['ell'][2:] tt = cl['tt'][2:] fTT = interp1d(ell, tt * ell * (ell + 1)) for k in range(len(param_list)): print 'k', k, len(param_list) #calculate height peak difference if (param_list[k] == 'HP'): # param[i][j][k] = max(tt)-fTT(10) param[i][j][k] = max(tt * ell * (ell + 1)) elif (param_list[k] == 'rs_rec'): param[i][j][k] = cosmo.rs_rec() elif (param_list[k] == 'rd_rec'): param[i][j][k] = cosmo.rd_rec() elif (param_list[k] == 'rs_rec_over_rd_rec'): # print cosmo.rs_rec()/cosmo.rd_rec() param[i][j][k] = cosmo.rs_rec() / cosmo.rd_rec() elif (param_list[k] == 'da_rec'): param[i][j][k] = cosmo.da_rec() elif (param_list[k] == 'theta_s'): param[i][j][k] = cosmo.theta_s() elif (param_list[k] == 'H0'): param[i][j][k] = cosmo.Hubble(0) print max(tt * ell * (ell + 1)), cosmo.theta_s(), cosmo.da_rec( ), cosmo.rs_rec(), cosmo.z_rec() # for l in range(len(tt)): # # print l, tt[l], max(tt*ell*(ell+1)) # if tt[l]*ell[l]*(ell[l]+1) == max(tt*ell*(ell+1)): # print "l:", l,max(tt*ell*(ell+1)) # except CosmoComputationError: # this happens when CLASS fails # print CosmoComputationError # pass # eh, don't do anything #calculate derivative # der_HP[i]= (HP[i][1]-HP[i][2])/(Omega_ac_fid[i]+percentage_difference*Omega_ac_fid[i]-(Omega_ac_fid[i]-percentage_difference*Omega_ac_fid[i]))*Omega_ac_fid[0]/HP[i][0] cosmo.empty() cosmo.struct_cleanup() if write_file == True: f.write(str(ac_values[i]) + '\t\t') print "calculating derivative" for k in range(len(param_list)): # der_HP[i]= (HP[i][1]-HP[i][2])/(fraction_fiducial+percentage_difference*fraction_fiducial-(fraction_fiducial-percentage_difference*fraction_fiducial))*fraction_fiducial/HP[i][0] der_param[i][k] = (param[i][1][k] - param[i][2][k]) / ( param_fiducial + percentage_difference * param_fiducial - (param_fiducial - percentage_difference * param_fiducial) ) * param_fiducial / param[i][0][k] if write_file == True: f.write(str(der_param[i][k]) + '\t\t') # info on format print param_list[k], der_param[i][k] if write_file == True: f.write('\n') return
# Create an instance of the CLASS wrapper cosmo = Class() # Set the parameters to the cosmological code cosmo.set(params) # Run the whole code. Depending on your output, it will call the # CLASS modules more or less fast. For instance, without any # output asked, CLASS will only compute background quantities, # thus running almost instantaneously. # This is equivalent to the beginning of the `main` routine of CLASS, # with all the struct_init() methods called. cosmo.compute() # Access the lensed cl until l=2000 cls = cosmo.lensed_cl(2000) # Print on screen to see the output print cls # It is a dictionnary that contains the fields: tt, te, ee, bb, pp, tp # plot something with matplotlib... # Clean CLASS (the equivalent of the struct_free() in the `main` # of CLASS. This step is primordial when running in a loop over different # cosmologies, as you will saturate your memory very fast if you ommit # it. cosmo.struct_cleanup() # If you want to change completely the cosmology, you should also # clean the arguments, otherwise, if you are simply running on a loop
# In[ ]: # create instance of the class "Class" LambdaCDM = Class() # pass input parameters LambdaCDM.set({'omega_b':0.022032,'omega_cdm':0.12038,'h':0.67556,'A_s':2.215e-9,'n_s':0.9619,'tau_reio':0.0925}) LambdaCDM.set({'output':'tCl,pCl,lCl,mPk','lensing':'yes','P_k_max_1/Mpc':3.0}) # run class LambdaCDM.compute() # In[ ]: # get all C_l output cls = LambdaCDM.lensed_cl(2500) # To check the format of cls cls.viewkeys() # In[ ]: ll = cls['ell'][2:] clTT = cls['tt'][2:] clEE = cls['ee'][2:] clPP = cls['pp'][2:] # In[ ]: # uncomment to get plots displayed in notebook
'output': 'tCl lCl', 'l_max_scalars': 2508, 'lensing': 'yes', 'P_k_ini type': 'external_Pk', 'command': 'python /home/andrew/Research/tools/class_public-2.4.3/external_Pk/generate_Pk_cosines.py', 'custom1': 0, 'custom2': 0, 'custom3': 0, 'custom4': 0, 'custom5': 0} #Get the unperturbed cls for comparison cosmo = Class() cosmo.set(params) cosmo.compute() clso=cosmo.lensed_cl(2508)['tt'][30:] ell = cosmo.lensed_cl(2508)['ell'][30:] for i in range(len(clso)): clso[i]=ell[i]*(ell[i]+1)/(4*np.pi)*((2.726e6)**2)*clso[i] a=np.zeros(5) cosmo.struct_cleanup() cosmo.empty() dcls=np.zeros([clso.shape[0],5]) h=1e-6 for m in range(5): a[m]=h # Define your cosmology (what is not specified will be set to CLASS default parameters) params = { 'output': 'tCl lCl', 'l_max_scalars': 2508,
M.empty( ) # reset input parameters to default, before passing a new parameter set M.set(common_settings) M.set({ 'output': 'tCl,pCl,lCl', 'modes': 's,t', 'lensing': 'yes', 'n_s': 0.9660499, 'r': 0.1, 'n_t': 0, 'l_max_scalars': l_max_scalars, 'l_max_tensors': l_max_tensors }) M.compute() cl_tot = M.raw_cl(l_max_scalars) cl_lensed = M.lensed_cl(l_max_scalars) # In[ ]: # modules and esthetic definitions for the plots # # uncomment to get plots displayed in notebook #get_ipython().run_line_magic('matplotlib', 'inline') # import matplotlib import matplotlib.pyplot as plt # font = {'size': 16, 'family': 'STIXGeneral'} axislabelfontsize = 'large' matplotlib.rc('font', **font) matplotlib.mathtext.rcParams['legend.fontsize'] = 'medium'
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']}
# M = Class() M.set(common_settings) M.set({ 'output': 'tCl,pCl,lCl', 'modes': 's,t', 'lensing': 'yes', 'r': 0.1, 'n_s': 0.9619, 'n_t': 0, 'l_max_scalars': 3000, 'l_max_tensors': l_max_tensors }) M.compute() cl_tot = M.raw_cl(3000) cl_lensed = M.lensed_cl(3000) M.struct_cleanup() M.empty() # ################# # # start plotting # ################# # plt.xlim([2, 3000]) plt.ylim([1.e-8, 10]) plt.xlabel(r"$\ell$") plt.ylabel(r"$\ell (\ell+1) C_l^{XY} / 2 \pi \,\,\, [\times 10^{10}]$") plt.title(r"$r=0.1$") plt.grid()
cosmo.set({ '100*theta_s': 1.04077, 'omega_b': 0.02225, 'omega_cdm': 0.1198, 'ln10^{10}A_s': 3.094, 'n_s': 0.9645, 'tau_reio': 0.079, 'do_shooting': 'yes', 'output': 'tCl,pCl,lCl', 'lensing': 'yes' }) # cosmo.compute() # cosmo.view_keys() clM = cosmo.lensed_cl(2500) ll_LCDM = clM['ell'][2:] clTT_LCDM = clM['tt'][2:] for i in range(N): print ac[i] # params['m_axion'] = 10**mu[i] for j in range(N): # print i,j # going over a_c and Om_fld values print Theta_initial[j] params = { 'scf_potential': 'axion', 'n_axion': n_axion, 'scf_parameters': '%.2f,0.0' % (Theta_initial[j]), 'log10_axion_ac': ac[i],
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 Sampler: def __init__(self, NSIDE, As): self.NSIDE = NSIDE self.Npix = 12 * NSIDE**2 self.As = As print("Initialising sampler") self.cosmo = Class() #print("Maps") #A recommenter #self.Qs, self.Us, self.sigma_Qs, self.sigma_Us = aggregate_by_pixels_params(get_pixels_params(self.NSIDE)) #print("betas") self.matrix_mean, self.matrix_var = aggregate_mixing_params( get_mixing_matrix_params(self.NSIDE)) print("Cosmo params") self.cosmo_means = np.array(COSMO_PARAMS_MEANS) self.cosmo_stdd = np.diag(COSMO_PARAMS_SIGMA) self.instrument = pysm.Instrument( get_instrument('litebird', self.NSIDE)) self.components = [CMB(), Dust(150.), Synchrotron(150.)] self.mixing_matrix = MixingMatrix(*self.components) self.mixing_matrix_evaluator = self.mixing_matrix.evaluator( self.instrument.Frequencies) self.noise_covar_one_pix = self.noise_covariance_in_freq(self.NSIDE) #A recommenter #self.noise_stdd_all = np.concatenate([np.sqrt(self.noise_covar_one_pix) for _ in range(2*self.Npix)]) print("End of initialisation") def __getstate__(self): state_dict = self.__dict__.copy() del state_dict["mixing_matrix_evaluator"] del state_dict["cosmo"] del state_dict["mixing_matrix"] del state_dict["components"] return state_dict def __setstate__(self, state): self.__dict__.update(state) self.cosmo = Class() self.components = [CMB(), Dust(150.), Synchrotron(150.)] self.mixing_matrix = MixingMatrix(*self.components) self.mixing_matrix_evaluator = self.mixing_matrix.evaluator( self.instrument.Frequencies) def prepare_sigma(self, input): sampled_beta, i = input mixing_mat = list(self.sample_mixing_matrix_parallel(sampled_beta)) mean = np.dot(mixing_mat, (self.Qs + self.Us)[i]) sigma = np.diag(self.noise_covar_one_pix) + np.einsum( "ij,jk,lk", mixing_mat, (np.diag( (self.sigma_Qs + self.sigma_Us)[i])**2), mixing_mat) sigma_symm = (sigma + sigma.T) / 2 log_det = np.log(scipy.linalg.det(2 * np.pi * sigma_symm)) return mean, sigma_symm, log_det def sample_mixing_matrix_parallel(self, betas): return self.mixing_matrix_evaluator(betas)[:, 1:] def sample_normal(self, mu, stdd, diag=False): standard_normal = np.random.normal(0, 1, size=mu.shape[0]) if diag: normal = np.multiply(stdd, standard_normal) else: normal = np.dot(stdd, standard_normal) normal += mu return normal def noise_covariance_in_freq(self, nside): cov = LiteBIRD_sensitivities**2 / hp.nside2resol(nside, arcmin=True)**2 return cov def sample_model_parameters(self): #sampled_cosmo = self.sample_normal(self.cosmo_means, self.cosmo_stdd) sampled_cosmo = np.array( [0.9665, 0.02242, 0.11933, 1.04101, self.As, 0.0561]) #sampled_beta = self.sample_normal(self.matrix_mean, self.matrix_var, diag = True).reshape((self.Npix, -1), order = "F") sampled_beta = self.matrix_mean.reshape((self.Npix, -1), order="F") return sampled_cosmo, sampled_beta def sample_CMB_QU(self, cosmo_params): params = { 'output': OUTPUT_CLASS, 'l_max_scalars': L_MAX_SCALARS, 'lensing': LENSING } params.update(cosmo_params) print(params) self.cosmo.set(params) self.cosmo.compute() cls = self.cosmo.lensed_cl(L_MAX_SCALARS) eb_tb = np.zeros(shape=cls["tt"].shape) _, Q, U = hp.synfast( (cls['tt'], cls['ee'], cls['bb'], cls['te'], eb_tb, eb_tb), nside=self.NSIDE, new=True) self.cosmo.struct_cleanup() self.cosmo.empty() return Q, U def sample_mixing_matrix(self, betas): #mat_pixels = [] #for i in range(self.Npix): # m = self.mixing_matrix_evaluator(betas[i,:])[:, 1:] # mat_pixels.append(m) mat_pixels = (self.mixing_matrix_evaluator(beta)[:, 1:] for beta in betas) return mat_pixels def sample_mixing_matrix_full(self, betas): #mat_pixels = [] #for i in range(self.Npix): # m = self.mixing_matrix_evaluator(betas[i,:]) # mat_pixels.append(m) mat_pixels = (self.mixing_matrix_evaluator(beta) for beta in betas) return mat_pixels def sample_model(self, input_params): random_seed = input_params np.random.seed(random_seed) cosmo_params, _ = self.sample_model_parameters() cosmo_dict = { l[0]: l[1] for l in zip(COSMO_PARAMS_NAMES, cosmo_params.tolist()) } tuple_QU = self.sample_CMB_QU(cosmo_dict) map_CMB = np.concatenate(tuple_QU) result = {"map_CMB": map_CMB, "cosmo_params": cosmo_params} with open("B3DCMB/data/temp" + str(random_seed), "wb") as f: pickle.dump(result, f) return cosmo_params def compute_weight(self, input): observed_data = config.sky_map noise_level, random_seed = input np.random.seed(random_seed) with open("B3DCMB/data/temp" + str(random_seed), "rb") as f: data = pickle.load(f) map_CMB = data["map_CMB"] print("Duplicating CMB") duplicate_CMB = (l for l in map_CMB for _ in range(15)) print("Splitting for computation") #Le problème est surement que chaque ligne de X doit être en fortran order, ce qui du coup est aussi C order !!! x = np.ascontiguousarray( (observed_data - np.array(list(duplicate_CMB)) - np.array(config.means)).reshape(self.Npix * 2, -1)) print("Computing log weights") #r = np.sum((np.dot(l[1], scipy.linalg.solve(l[0], l[1].T)) for l in zip(config.sigmas_symm, x))) r = compute_exponent(config.sigmas_symm, x, 2 * self.Npix) lw = (-1 / 2) * r + config.denom return lw def sample_data(self): print("Sampling parameters") cosmo_params, sampled_beta = self.sample_model_parameters() print("Computing mean and cov of map") mean_map = np.array([i for l in self.Qs + self.Us for i in l]) stdd_map = [i for l in self.sigma_Qs + self.sigma_Us for i in l] print("Sampling maps Dust and Sync") maps = self.sample_normal(mean_map, stdd_map, diag=True) print("Computing cosmo params") cosmo_dict = { l[0]: l[1] for l in zip(COSMO_PARAMS_NAMES, cosmo_params.tolist()) } print("Sampling CMB signal") tuple_QU = self.sample_CMB_QU(cosmo_dict) map_CMB = np.concatenate(tuple_QU) print("Creating mixing matrix") mixing_matrix = self.sample_mixing_matrix(sampled_beta) print("Scaling to frequency maps") #freq_maps = np.dot(scipy.linalg.block_diag(*2*mixing_matrix), maps.T) freq_pixels = [] mix1, mix2 = tee(mixing_matrix) for i, mat in enumerate(chain(mix1, mix2)): freq_pix = np.dot(mat, maps[2 * i:(2 * i + 2)].T) freq_pixels.append(freq_pix) freq_maps = np.concatenate(freq_pixels) print("Adding CMB to frequency maps") duplicated_cmb = np.repeat(map_CMB, 15) print("Creating noise") noise = self.sample_normal(np.zeros(2 * 15 * self.Npix), self.noise_stdd_all, diag=True) print("Adding noise to the maps") sky_map = np.add(np.add(freq_maps, duplicated_cmb), noise) #sky_map = np.add(freq_maps, duplicated_cmb) return { "sky_map": sky_map, "cosmo_params": cosmo_params, "betas": sampled_beta }
## Create a Class instance #cosmo = Class () ## Set the instance to the cosmology #cosmo . set ( params ) ## Run the _init methods #cosmo . compute () ## Do something with the pk #pk = cosmo . pk (0 , 0.1) ## Clean #cosmo . struct_cleanup () ; cosmo . empty () cosmo = Class() cosmo.set({' output ': 'tCl , pCl , lCl ', ' lensing ': ' yes '}) cosmo.compute() l = np.array(range(2, 2501)) factor = l * (l + 1) / (2 * np.pi) lensed_cl = cosmo.lensed_cl(2500) lensed_cl.viewkeys() #plt . loglog (l , factor * lensed_cl [ ' tt ' ][2:] , l , factor * lensed_cl [ 'ee ' ][2:]) #plt . xlabel ( r " $ \ ell$ " ) #plt . ylabel ( r " $ \ ell (\ ell +1) /(2\ pi ) C_ \ ell$ " #plt . tight_layout () #plt . savefig ( " output / T T_ EE _ La mb da C DM . pdf " )
# In[ ]: # create instance of the class "Class" LambdaCDM = Class() # pass input parameters LambdaCDM.set({'omega_b':0.022032,'omega_cdm':0.12038,'h':0.67556,'A_s':2.215e-9,'n_s':0.9619,'tau_reio':0.0925}) LambdaCDM.set({'output':'tCl,pCl,lCl,mPk','lensing':'yes','P_k_max_1/Mpc':3.0}) # run class LambdaCDM.compute() # In[ ]: # get all C_l output cls = LambdaCDM.lensed_cl(2500) # To check the format of cls cls.viewkeys() # In[ ]: ll = cls['ell'][2:] clTT = cls['tt'][2:] clEE = cls['ee'][2:] clPP = cls['pp'][2:] # In[ ]: # to get plots displayed in notebook
COSMO_PARAMS_MEANS = [0.9665, 0.02242, 0.11933, 1.04101, 3.047, 0.0561] cosmo = Class() start = time.clock() cosmo_params = { l[0]: l[1] for l in zip(COSMO_PARAMS_NAMES, COSMO_PARAMS_MEANS) } params = { 'output': OUTPUT_CLASS, 'l_max_scalars': L_MAX_SCALARS, 'lensing': LENSING } params.update(cosmo_params) cosmo.set(params) cosmo.compute() cls = cosmo.lensed_cl(L_MAX_SCALARS) eb_tb = np.zeros(shape=cls["tt"].shape) I, Q, U = hp.synfast( (cls['tt'], cls['ee'], cls['bb'], cls['te'], eb_tb, eb_tb), nside=NSIDE, new=True) print(cls["tt"].shape) end_generation = time.clock() - start cosmo.struct_cleanup() cosmo.empty() start = time.clock() res = sphtfunc.map2alm((I, Q, U), lmax=L_MAX_SCALARS) #res = sphtfunc.map2alm(U) print(res.shape) print(cls["tt"].shape)
# Take fixed value for primordial Helium (instead of automatic BBN adjustment) 'YHe': 0.246, # other output and precision parameters 'l_max_scalars': 5000 } ############### # # call CLASS # ### normal one ##### M = Class() M.set(common_settings) M.compute() cl_tot_normal = M.raw_cl(3000) cl_lensed_normal = M.lensed_cl(3000) M.struct_cleanup() # clean output M.empty() M = Class() M.set(common_settings_entang) M.compute() cl_tot = M.raw_cl(3000) cl_lensed = M.lensed_cl(3000) M.struct_cleanup() # clean output M.empty() # clean input # M.set(common_settings_entang) # new input M.set({'temperature contributions': 'tsw'}) M.compute() cl_tsw = M.raw_cl(3000)
# Create an instance of the CLASS wrapper cosmo = Class() # Set the parameters to the cosmological code cosmo.set(params) # Run the whole code. Depending on your output, it will call the # CLASS modules more or less fast. For instance, without any # output asked, CLASS will only compute background quantities, # thus running almost instantaneously. # This is equivalent to the beginning of the `main` routine of CLASS, # with all the struct_init() methods called. cosmo.compute() # Access the lensed cl cls = cosmo.lensed_cl() # Print on screen to see the output print "cls contains:", cls.viewkeys() #print cls # It is a dictionnary that contains the fields: tt, te, ee, bb, pp, tp #cosmo.get_current_derived_parameters(['Omega_Lambda']) #cosmo.pk(k, z) # function that returns P(k,z). Watch that there is no h factor anywhere K = np.logspace(np.log10(1.e-4), np.log10(3.), 501, 10.) f = lambda k: cosmo.pk(k, 0.) Plin = np.array(map(f, K)) plt.loglog(K, Plin) plt.show()
class Peturbations: def __init__(self): self.cosmo = Class() def cosmo_GR(self, zlist): """ Compute cosmology for General Relativity with Planck15 parameters. """ zstr = ','.join(map(str, zlist + zlist[-1] + 2)) lcdmpars = { 'output': 'mPk, tCl, pCl, lCl', 'lensing': 'yes', 'P_k_max_h/Mpc': 20, 'z_pk': zstr, 'background_verbose': 1, #Info 'tau_reio': 0.07, 'omega_cdm': 0.11987, 'A_s': 2.204e-9, 'h': 0.6715918, #computed from 100*theta_s=1.042143 'N_ur': 3.046 - 1., 'N_ncdm': 1., 'm_ncdm': 0.06, 'omega_b': 0.022252, 'n_s': 0.96475, } self.cosmo.set(lcdmpars) self.cosmo.compute() def cosmo_MG(self, zlist, alpha_b, alpha_m, a_trans, r): """ Compute cosmology for Modified gravity with a LCDM background expansion (with Planck15 parameters) and 'hill_scale' parameterization for the property functions. """ zstr = ','.join(map(str, zlist + zlist[-1] + 2)) mgpars = { 'output': 'mPk, tCl, pCl, lCl', 'lensing': 'yes', 'P_k_max_h/Mpc': 20, 'z_pk': zstr, 'background_verbose': 1, #Info 'tau_reio': 0.07, 'omega_cdm': 0.11987, 'A_s': 2.204e-9, 'h': 0.6715918, #computed from 100*theta_s=1.042143 'N_ur': 3.046 - 1., 'N_ncdm': 1., 'm_ncdm': 0.06, 'omega_b': 0.022252, 'n_s': 0.96475, 'Omega_Lambda': 0, 'Omega_fld': 0, 'Omega_smg': -1, 'expansion_model': 'lcdm', 'gravity_model': 'hill_scale', } # Planck Mass Mstarsq = 1. # Property Functions alpha_t = 0. alpha_k = 0.001 mgpars['parameters_smg'] = "{}, {}, {}, {}, {}, {}, {}".format( Mstarsq, alpha_k, alpha_b, alpha_m, alpha_t, a_trans, r) self.cosmo.set(mgpars) self.cosmo.compute() def D(self, z): """ Linear growth function D(z) = ( P(k_ls, z) / P(k_ls, 0) )^(1 / 2) where k_ls is a large-scale mode. """ k = 0.01 #Our choice of large-scale mode mPk = self.cosmo.pk(k, z) mPk_norm = self.cosmo.pk(k, 0) #Normalize at z=0 D = np.sqrt(mPk / mPk_norm) return D def f(self, z): """ Linear growth rate f(z) where f(a) = d log D / d log a where a = 1 / (1 + z) is the scale factor. """ a = 1. / (1. + z) da = 0.01 #*a gp, g, gm = [self.D(1. / ia - 1.) for ia in [a + da, a, a - da]] f = a * (gp - gm) / (2 * g * da) return f def sigma8(self, z): """ sigma8(z) = sigma8*D(z) """ s8 = self.cosmo.sigma8() * self.D(z) return s8 def fsigma8(self, z): """ Growth rate of structure fsigma8(z) = f(z) * sigma8(z) """ fs8 = self.f(z) * self.sigma8(z) return fs8 def fsigma8_GR(self, zlist): """ Get fsigma8 for General Relativity """ self.cosmo_GR(zlist) fs8_GR = np.array([self.fsigma8(z) for z in zlist]) return fs8_GR def fsigma8_MG(self, zlist, alpha_b, alpha_m, a_trans, r): """ Get fsigma8 for Modified Gravity with a LCDM background expansion and hill_scale parameterization for the property functions. """ self.cosmo_MG(zlist, alpha_b, alpha_m, a_trans, r) fs8_MG = np.array([self.fsigma8(z) for z in zlist]) return fs8_MG def fsigma8_MG_fit(self, zlist, alpha_b, a_trans, r): """ Get fsigma8 for Modified Gravity with a LCDM background expansion and hill_scale parameterization for the property functions. """ alpha_m = 0.1 #a_trans = 1./(1.+7.) #r = 4. self.cosmo_MG(zlist, alpha_b, alpha_m, a_trans, r) fs8_MG = np.array([self.fsigma8(z) for z in zlist]) return fs8_MG def sigma8_GR(self, zlist): """ Get fsigma8 for General Relativity """ self.cosmo_GR(zlist) s8_GR = np.array([self.sigma8(z) for z in zlist]) return s8_GR def sigma8_MG(self, zlist, alpha_b, alpha_m, a_trans, r): """ Get sigma8 for Modified Gravity with a LCDM background expansion and hill_scale parameterization for the property functions. """ self.cosmo_MG(zlist, alpha_b, alpha_m, a_trans, r) s8_MG = np.array([self.sigma8(z) for z in zlist]) return s8_MG def Cl_TT_GR(self, zlist, llist): """ Get C_ell^TT for General Relativity """ self.cosmo_GR(zlist) lmax = llist[-1] Cl_TT_GR = self.cosmo.lensed_cl(lmax)['tt'][2:] Cl_TT_GR = (1. / (2. * np.pi)) * (llist * (llist + 1.)) * Cl_TT_GR return Cl_TT_GR def Cl_TT_MG(self, zlist, llist, alpha_b, alpha_m, a_trans, r): """ Get C_ell^TT for Modified Gravity with a LCDM background expansion and hill_scale parameterization for the property functions. """ self.cosmo_MG(zlist, alpha_b, alpha_m, a_trans, r) lmax = llist[-1] Cl_TT_MG = self.cosmo.lensed_cl(lmax)['tt'][2:] Cl_TT_MG = (1. / (2. * np.pi)) * (llist * (llist + 1.)) * Cl_TT_MG return Cl_TT_MG def Cl_kappa_kappa_GR(self, zlist, llist): """ Get C_ell^kappakappa for General Relativity """ self.cosmo_GR(zlist) lmax = llist[-1] Cl_phi_phi_GR = self.cosmo.lensed_cl(lmax)['pp'][2:] Cl_kap_kap_GR = (1. / 4.) * ((llist * (llist + 1.))**2.) * Cl_phi_phi_GR return Cl_kap_kap_GR def Cl_kappa_kappa_MG(self, zlist, llist, alpha_b, alpha_m, a_trans, r): """ Get C_ell^kappakappa for Modified Gravity with a LCDM background expansion and hill_scale parameterization for the property functions. """ self.cosmo_MG(zlist, alpha_b, alpha_m, a_trans, r) lmax = llist[-1] Cl_phi_phi_MG = self.cosmo.lensed_cl(lmax)['pp'][2:] Cl_kap_kap_MG = (1. / 4.) * ((llist * (llist + 1.))**2.) * Cl_phi_phi_MG return Cl_kap_kap_MG