Ejemplo n.º 1
0
    def setUp(self):
        """
        set up data used in the tests.
        setUp is called before each test function execution.
        """
        self.cosmo = Class()
        self.cosmo_newt = Class()

        if CLASS_VERBOSE:
            self.verbose = {
                'input_verbose': 1,
                'background_verbose': 1,
                'thermodynamics_verbose': 1,
                'perturbations_verbose': 1,
                'transfer_verbose': 1,
                'primordial_verbose': 1,
                'harmonic_verbose': 1,
                'fourier_verbose': 1,
                'lensing_verbose': 1,
                'distortions_verbose': 1,
                'output_verbose': 1,
            }
        else:
            self.verbose = {}
        self.scenario = {}
Ejemplo n.º 2
0
def main(target=args['target'], base=args['base'], new=args['new']):
    # create instance of the class "Class"
    TargetCosmo = Class()

    # pass input parameters
    print("The default cosmology is read from " + target)
    target_param_dict = read_file(target)
    TargetCosmo.set(target_param_dict)

    # run class
    TargetCosmo.compute()
    os.remove(target_param_dict[rootName] + "parameters.ini")
    os.remove(target_param_dict[rootName] + "unused_parameters")
    theta_target = TargetCosmo.theta_s_100()
    print("Target 100*theta_s = ", theta_target)

    # The second (new) cosmology
    print("The new cosmology is read from " + base + " and " + new[1])
    base_param_dict = read_file(base)

    # Create a new table with the final cosmologies
    if new[0] == 'table':
        shutil.copy(new[1], cosmology_table)

    new_params, numCosm = read_input(new)
    # for each new cosmology
    for iCosm in range(numCosm):
        # Check whether the hubble is set to the TBD value (HubbleDef); if not, don't meddle
        if np.abs(new_params[HubbleParam][iCosm] -
                  HubbleDef) > 1.e-7 and new[0] == 'table':
            continue

        NewCosmo = Class()
        # Load the base parameter values
        NewCosmo.set(base_param_dict)
        # Create a dictionary
        new_param_dict = read_line(new_params,
                                   iCosm) if new[0] == 'table' else new_params
        if new_param_dict[rootName][-1:] != '.':
            new_param_dict[rootName] += '.'
        # create new directory with the root name unless it exists already
        dir_par = new_param_dict[rootName][:-1]
        if os.path.isdir(dir_par) != True: os.mkdir(dir_par)
        os.chdir(dir_par)
        NewCosmo.set(new_param_dict)

        # run class
        NewCosmo.compute()
        h = search(NewCosmo, theta_target)
        write_dict_to_ini(new_param_dict, h)
        os.chdir('..')

        # if running in table regime, modify the README table and delete everything else
        if new[0] == 'table':
            # modify the H0 and A_s columns in the final table
            A_s = new_param_dict['A_s']
            modify_table(cosmology_table, new_param_dict[rootName][:-1], h,
                         A_s)
            # Get rid of the evidence
            shutil.rmtree(dir_par)
Ejemplo n.º 3
0
    def __init__(self, cosmology=None):
        ''' 
			This is an interface I made to talk to the cython 
			module for class. 
			The inputs are a dictionary containing cosmological parameters.
			If the input cosmology is not given, then the default is Planck 2015. 
		'''

        if (cosmology == None):
            # default to planck cosmology 2015
            params = {
                'output': 'tCl lCl,mPk, mTk',
                'l_max_scalars': 2000,
                'A_s': 2.3e-9,
                'n_s': 0.9624,
                'h': 0.6774,
                'omega_b': 0.02230,
                'omega_cdm': 0.1188,
                'k_pivot': 0.05,
                'A_s': 2.142e-9,
                'n_s': 0.9667,
                'P_k_max_1/Mpc': 500.0,
                'N_eff': 3.04,
                'Omega_fld': 0,
                'YHe': 0.2453,
                'z_reio': 8.8
            }
        else:
            params = cosmology

        self.k_max = params['P_k_max_1/Mpc']
        self.cosmo = Class()
        self.cosmo.set(params)
        self.cosmo.compute()

        params = {
            'output': 'tCl lCl,mPk, mTk',
            'l_max_scalars': 2000,
            'z_pk': 0,
            'A_s': 2.3e-9,
            'n_s': 0.9624,
            'h': 0.6774,
            'omega_b': 0.02230,
            'omega_cdm': 0.1188,
            'k_pivot': 0.05,
            'A_s': 2.142e-9,
            'n_s': 0.9667,
            'P_k_max_1/Mpc': 500.0,
            'N_eff': 3.04,
            'Omega_fld': 0,
            'YHe': 0.2453,
            'z_reio': 8.8,
            'non linear': 'halofit'
        }

        self.non_linear_cosmo = Class()
        self.non_linear_cosmo.set(params)
        self.non_linear_cosmo.compute()
Ejemplo n.º 4
0
    def class_pk(self, z, cosmo_params=None, pk_params=None, return_s8=False):
        if cosmo_params is None:
            cosmo_params = self.cosmo_params
        if pk_params is None:
            pk_params = self.pk_params
        cosmoC = Class()
        h = cosmo_params['h']
        class_params = {
            'h': h,
            'omega_b': cosmo_params['Omb'] * h**2,
            'omega_cdm': (cosmo_params['Om'] - cosmo_params['Omb']) * h**2,
            'A_s': cosmo_params['Ase9'] * 1.e-9,
            'n_s': cosmo_params['ns'],
            'output': 'mPk',
            'z_max_pk': 100,  #max(z)*2, #to avoid class error.
            #Allegedly a compiler error, whatever that means
            'P_k_max_1/Mpc': pk_params['kmax'] * h * 1.1,
        }
        if pk_params['non_linear'] == 1:
            class_params['non linear'] = 'halofit'

        class_params['N_ur'] = 3.04  #ultra relativistic species... neutrinos
        if cosmo_params['mnu'] != 0:
            class_params['N_ur'] -= 1  #one massive neutrino
            class_params['m_ncdm'] = cosmo_params['mnu']
        class_params['N_ncdm'] = 3.04 - class_params['N_ur']

        if cosmo_params['w'] != -1 or cosmo_params['wa'] != 0:
            class_params['Omega_fld'] = cosmo_params['Oml']
            class_params['w0_fld'] = cosmo_params['w']
            class_params['wa_fld'] = cosmo_params['wa']

        for ke in class_accuracy_settings.keys():
            class_params[ke] = class_accuracy_settings[ke]

        cosmoC = Class()
        cosmoC.set(class_params)
        try:
            cosmoC.compute()
        except Exception as err:
            print(class_params, err)
            raise Exception('Class crashed')

        k = self.kh * h
        pkC = np.array([[cosmoC.pk(ki, zj) for ki in k] for zj in z])
        pkC *= h**3
        s8 = cosmoC.sigma8()
        cosmoC.struct_cleanup()
        if return_s8:
            return pkC, self.kh, s8
        else:
            return pkC, self.kh
Ejemplo n.º 5
0
def recover_cosmological_module(data):
    """
    From the cosmological module name, initialise the proper Boltzmann code

    .. note::

        Only CLASS is currently wrapped, but a python wrapper of CosmoMC should
        enter here.

    """
    # Importing the python-wrapped CLASS from the correct folder, defined in
    # the .conf file, or overwritten at this point by the log.param.
    # If the cosmological code is CLASS, do the following to import all
    # relevant quantities
    if data.cosmological_module_name == 'CLASS':
        try:
            classy_path = ''
            for elem in os.listdir(os.path.join(
                    data.path['cosmo'], "python", "build")):
                if elem.find("lib.") != -1:
                    classy_path = os.path.join(
                        data.path['cosmo'], "python", "build", elem)
                    break
        except OSError:
            raise io_mp.ConfigurationError(
                "You probably did not compile the python wrapper of CLASS. " +
                "Please go to /path/to/class/python/ and do\n" +
                "..]$ python setup.py build")

        # Inserting the previously found path into the list of folders to
        # search for python modules.
        sys.path.insert(1, classy_path)
        try:
            from classy import Class
        except ImportError:
            raise io_mp.MissingLibraryError(
                "You must have compiled the classy.pyx file. Please go to " +
                "/path/to/class/python and run the command\n " +
                "python setup.py build")

        # FK: we need two independent instances of Class!
        cosmo1 = Class()
        cosmo2 = Class()

    else:
        raise io_mp.ConfigurationError(
            "Unrecognised cosmological module. " +
            "Be sure to define the correct behaviour in MontePython.py " +
            "and data.py, to support a new one.")

    return cosmo1, cosmo2
Ejemplo n.º 6
0
    def class_pk(self, z, cosmo_params=None, pk_params=None, return_s8=False):
        #output is in same unit as CAMB
        if not cosmo_params:
            cosmo_params = self.cosmo_params
        if not pk_params:
            pk_params = self.pk_params
        kh = np.logspace(np.log10(pk_params['kmin']),
                         np.log10(pk_params['kmax']), pk_params['nk'])
        cosmoC = Class()
        h = cosmo_params['h']
        class_params = {
            'h': h,
            'omega_b': cosmo_params['Omb'] * h**2,
            'omega_cdm': (cosmo_params['Om'] - cosmo_params['Omb']) * h**2,
            'A_s': cosmo_params['As'],
            'n_s': cosmo_params['ns'],
            'output': 'mPk',
            'z_max_pk': max(z) + 0.1,
            'P_k_max_1/Mpc': pk_params['kmax'] * h,
        }
        if pk_params['non_linear'] == 1:
            class_params['non linear'] = 'halofit'

        class_params['N_ur'] = 3.04  #ultra relativistic species... neutrinos
        if cosmo_params['mnu'] != 0:
            class_params['N_ur'] -= 1  #one massive neutrino
            class_params['m_ncdm'] = cosmo_params['mnu']
        class_params['N_ncdm'] = 3.04 - class_params['N_ur']

        if cosmo_params['w'] != -1:
            class_params['Omega_fld'] = cosmo_params['Oml']
            class_params['w0_fld'] = cosmo_params['w']
            class_params['wa_fld'] = cosmo_params['wa']

        for ke in class_accuracy_settings.keys():
            class_params[ke] = class_accuracy_settings[ke]

        cosmoC = Class()
        cosmoC.set(class_params)
        cosmoC.compute()

        k = kh * h  #output is in same unit as CAMB
        pkC = np.array([[cosmoC.pk(ki, zj) for ki in k] for zj in z])
        pkC *= h**3
        s8 = cosmoC.sigma8()
        cosmoC.struct_cleanup()
        if return_s8:
            return pkC, kh, s8
        else:
            return pkC, kh
Ejemplo n.º 7
0
 def compute_power_spectra(self, z):
     try:
         from classy import Class
     except ImportError:
         print("Cannot precompute power spectra because CLASS "+\
               "is not installed.")
         return
     cos = self.args['cosmology']
     h = cos['h']
     params = {
         'output': 'mPk',
         "h": h,
         "sigma8": cos['sigma8'],
         "n_s": cos['ns'],
         "Omega_b": cos['Omega_b'],
         "Omega_cdm": cos['Omega_m'] - cos['Omega_b'],
         'P_k_max_1/Mpc': 1000.,
         'z_max_pk': 1.0,
         'non linear': 'halofit'
     }
     class_cosmo = Class()
     class_cosmo.set(params)
     class_cosmo.compute()
     k = np.logspace(-5, 3, num=4000)  #1/Mpc comoving
     kh = k / h  #h/Mpc comoving
     #P(k) are in Mpc^3/h^3 comoving
     Pnl = np.array([class_cosmo.pk(ki, z) for ki in k]) * h**3
     Plin = np.array([class_cosmo.pk_lin(ki, z) for ki in k]) * h**3
     self.args['k'] = kh
     self.args['Plin'] = Plin
     self.args['Pnl'] = Pnl
     return
Ejemplo n.º 8
0
def clkk_gen(Omega_m, A_se9, zs=1.0):
    A_s = A_se9 * 1e-9
    omch2 = (OmegaM - OmegaB) * h**2
    LambdaCDM = Class()
    LambdaCDM.set({
        'omega_b': ombh2,
        'omega_cdm': omch2,
        'h': h,
        'A_s': A_s,
        'n_s': n_s
    })
    LambdaCDM.set({
        'output': 'mPk,sCl',
        'P_k_max_1/Mpc': 10.0,
        'l_switch_limber': 100,
        'selection': 'dirac',
        'selection_mean': zs,
        'l_max_lss': lmax,
        'non linear': 'halofit'
    })
    # run class
    LambdaCDM.compute()

    si8 = LambdaCDM.sigma8()

    cls = LambdaCDM.density_cl(lmax)
    ell = cls['ell'][2:]
    clphiphi = cls['ll'][0][2:]
    clkk = 1.0 / 4 * (ell + 2.0) * (ell + 1.0) * (ell) * (ell - 1.0) * clphiphi

    return si8, ell, clkk
Ejemplo n.º 9
0
    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")
Ejemplo n.º 10
0
 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)
Ejemplo n.º 11
0
    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")
Ejemplo n.º 12
0
def test_class_setup():
    cosmology = astropy.cosmology.Planck13
    assert cosmology.Om0 == cosmology.Odm0 + cosmology.Ob0
    assert 1 == (cosmology.Om0 + cosmology.Ode0 + cosmology.Ok0 +
                 cosmology.Ogamma0 + cosmology.Onu0)
    class_parameters = get_class_parameters(cosmology)
    try:
        from classy import Class
        cosmo = Class()
        cosmo.set(class_parameters)
        cosmo.compute()
        assert cosmo.h() == cosmology.h
        assert cosmo.T_cmb() == cosmology.Tcmb0.value
        assert cosmo.Omega_b() == cosmology.Ob0
        # Calculate Omega(CDM)_0 two ways:
        assert abs((cosmo.Omega_m() - cosmo.Omega_b()) -
                   (cosmology.Odm0 - cosmology.Onu0)) < 1e-8
        assert abs(cosmo.Omega_m() - (cosmology.Om0 - cosmology.Onu0)) < 1e-8
        # CLASS calculates Omega_Lambda itself so this is a non-trivial test.
        calculated_Ode0 = cosmo.get_current_derived_parameters(
            ['Omega_Lambda'])['Omega_Lambda']
        assert abs(calculated_Ode0 - (cosmology.Ode0 + cosmology.Onu0)) < 1e-5
        cosmo.struct_cleanup()
        cosmo.empty()
    except ImportError:
        pass
Ejemplo n.º 13
0
    def cosmo(self):
        """ """
        if not self._cosmo:
            self._cosmo = Class()
            self._cosmo.set(self.class_params)

            self.logger.info("Initializing Class")
            self._cosmo.compute()

            if self.params['fix_sigma8']:
                sig8 = self._cosmo.sigma8()
                A_s = self._cosmo.pars['A_s']
                self._cosmo.struct_cleanup()
                # renormalize to fix sig8
                self.A_s = A_s * (self.params['sigma8'] * 1. / sig8)**2
                self._cosmo.set(A_s=self.A_s)
                self._cosmo.compute()

            sig8 = self._cosmo.sigma8()

            self.params['sigma8'] = sig8
            self.params['A_s'] = self._cosmo.pars['A_s']
            self.params[
                'sigma8z'] = sig8 * self._cosmo.scale_independent_growth_factor(
                    self.class_params['z_pk'])
            self.params['f'] = self._cosmo.scale_independent_growth_factor_f(
                self.class_params['z_pk'])

            self.logger.info(f"          z: {self.class_params['z_pk']}")
            self.logger.info(f"    sigma_8: {self.params['sigma8']}")
            self.logger.info(f" sigma_8(z): {self.params['sigma8z']}")
            self.logger.info(f"       f(z): {self.params['f']}")
            self.logger.info(
                f"f sigma8(z): {self.params['f']*self.params['sigma8z']}")
        return self._cosmo
Ejemplo n.º 14
0
 def grid_cosmo(self,
                parameter,
                parameter_grid,
                classy_dict,
                verbose=False):
     """
     Compute a grid of cosmologies, varying one parameter over a grid.
     
     Parameters
     ----------
     parameter (string) : name of parameter in the CLASS dict
     parameter_grid (list of float) : grid over which the parameter will
         be varied
     classy_dict (dictionary) : base dictionary to be copied for each 
         cosmology evaluation
         
     Returns
     -------
         list of CLASS objects : contains a list of computed cosmologies,
             as a result of varying the parameter over the grid
     """
     cosmo_list = []
     for grid_value in parameter_grid:
         cosmo = Class()
         temp_dict = classy_dict.copy()
         temp_dict[parameter] = grid_value
         if verbose:
             print(temp_dict)
         cosmo.set(temp_dict)
         cosmo.compute()
         cosmo_list.append(cosmo)
     return cosmo_list
Ejemplo n.º 15
0
def run_class(parameters, gettransfer):
    '''
    Run CLASS with the input parameters and return the perturbations and 
    the value of tau_0 (which should be fixed but we still return the value 
    for the purpose of checking) and the earliest transfer (if asked). Print the
    amount of time taken to run. 
    
    Args: 
    parameters: parameters to run CLASS 
    gettransfer (boolean): whether to get the earliest transfer 
    
    Return: (pts, tau_0) if gettransfer=False and  (pts, tau_0, transfer) otherwise
    '''

    start_time = time.time()

    cosmo = Class()
    cosmo.set(parameters)
    cosmo.compute()

    pts = cosmo.get_perturbations()['scalar']
    tau_0 = cosmo.get_current_derived_parameters(['conformal_age'])['conformal_age']
    
    print("--- %s seconds ---" % (time.time() - start_time))
    
    # 45999 is the largest redshift possible 
    if (gettransfer): 
        tf = cosmo.get_transfer(45999)
        return pts, tau_0, tf 
    
    return pts, tau_0
Ejemplo n.º 16
0
def get_cls(params=None,lmax=3000,accurate=False,engine='camb',de='ppf',nonlinear=True,save_raw_camb_output=None):
    from camb import model
    params = map_params(params,engine=engine)
    if engine=='camb':
        pars = set_camb_pars(params=params,de=de)
        if accurate:
            pars.set_accuracy(AccuracyBoost=2.0, lSampleBoost=2.0, lAccuracyBoost=2.0, DoLateRadTruncation=False)
            pars.set_for_lmax(lmax=int(lmax+500), lens_potential_accuracy=8.0, lens_margin=2050, max_eta_k=20000)
        else:
            pars.set_accuracy(AccuracyBoost=1.0, lSampleBoost=1.0, lAccuracyBoost=1.0)
            pars.set_for_lmax(lmax=int(lmax+500), lens_potential_accuracy=1, max_eta_k=2*lmax)
        if nonlinear:
            pars.NonLinear = model.NonLinear_both
            pars.NonLinearModel.set_params('mead2016', HMCode_A_baryon = 3.13, HMCode_eta_baryon = 0.603)
        else:
            pars.NonLinear = model.NonLinear_none
        return load_theory(pars,lpad=lmax+2,save_raw_camb_output=save_raw_camb_output)
        
    elif engine=='class':
        from classy import Class
        cosmo = Class()
        params['output'] = 'lCl,tCl,pCl'
        params['lensing'] = 'yes'
        params['non linear'] = 'hmcode'
        params['l_max_scalars'] = lmax
        cosmo.set(params)
        cosmo.compute()
    return retval
 def setup(self):
     """
     Create an instance of Class and attach it to self.
     """
     self.cosmo = Class()
     self.cosmo.set(self.constants)
     self.cosmo.compute()
     self.cosmo.struct_cleanup()
Ejemplo n.º 18
0
 def initialize(self):
     """Importing CLASS from the correct path, if given, and if not, globally."""
     # If path not given, try using general path to modules
     if not self.path and self.path_install:
         self.path = self.get_path(self.path_install)
     if self.path:
         self.log.info("Importing *local* classy from " + self.path)
         classy_build_path = os.path.join(self.path, "python", "build")
         post = next(d for d in os.listdir(classy_build_path)
                     if d.startswith("lib."))
         classy_build_path = os.path.join(classy_build_path, post)
         if not os.path.exists(classy_build_path):
             # If path was given as an install path, try to install global one anyway
             if self.path_install:
                 self.log.info(
                     "Importing *global* CLASS (because not installed).")
             else:
                 raise LoggedError(
                     self.log, "Either CLASS is not in the given folder, "
                     "'%s', or you have not compiled it.", self.path)
         else:
             # Inserting the previously found path into the list of import folders
             sys.path.insert(0, classy_build_path)
     else:
         self.log.info("Importing *global* CLASS.")
     try:
         from classy import Class, CosmoSevereError, CosmoComputationError
     except ImportError:
         raise LoggedError(
             self.log, "Couldn't find the CLASS python interface. "
             "Make sure that you have compiled it, and that you either\n"
             " (a) specify a path (you didn't) or\n"
             " (b) install the Python interface globally with\n"
             "     '/path/to/class/python/python setup.py install --user'")
     self.classy = Class()
     # Propagate errors up
     global CosmoComputationError, CosmoSevereError
     # Generate states, to avoid recomputing
     self.n_states = 3
     self.states = [{
         "params": None,
         "derived": None,
         "derived_extra": None,
         "last": 0
     } for i in range(self.n_states)]
     # Dict of named tuples to collect requirements and computation methods
     self.collectors = {}
     # Additional input parameters to pass to CLASS
     self.extra_args = deepcopy_where_possible(self.extra_args) or {}
     # Add general CLASS stuff
     self.extra_args["output"] = self.extra_args.get("output", "")
     if "sBBN file" in self.extra_args:
         self.extra_args["sBBN file"] = (
             self.extra_args["sBBN file"].format(classy=self.path))
     # Set aliases
     self.planck_to_classy = self.renames
     # Derived parameters that may not have been requested, but will be necessary later
     self.derived_extra = []
Ejemplo n.º 19
0
 def __init__(self):
     """ """
     self.data = {}
     omm = class_params['Omega_b'] + class_params['Omega_cdm']
     logging.info("Omega_m = %f" % omm)
     self.dist = FlatLambdaCDM(100, omm)
     self.cosmo = Class()
     self.cosmo.set(class_params)
     self.cosmo.compute()
Ejemplo n.º 20
0
def fetch_planck_cosmology(z_max):
    
    cosmo = Class()
    cosmo.set({'H0' : 67.36, 'T_cmb' : 2.7255, 'A_s' : 2.14e-9, 'n_s' : 0.9649,
               'reio_parametrization' : 'reio_camb', 'tau_reio' : 0.0544, 'reionization_exponent' : 1.5,
               'reionization_width' : 0.5, 'helium_fullreio_redshift' : 3.5, 'helium_fullreio_width' : 0.5,
               'omega_b' : 0.02237, 'omega_cdm' : 0.1200, 'Omega_k' : 0., 'Omega_Lambda' : 0.6847,              
               'output' : 'mPk', 'P_k_max_1/Mpc' : 100, 'z_max_pk' : z_max, 'non linear' : 'halofit'})
    cosmo.compute()
    return cosmo
Ejemplo n.º 21
0
 def initialize(self):
     """Importing CLASS from the correct path, if given, and if not, globally."""
     # If path not given, try using general path to external packages
     if not self.path and self.packages_path:
         self.path = self.get_path(self.packages_path)
     if self.path:
         self.log.info("Importing *local* classy from " + self.path)
         classy_build_path = os.path.join(self.path, "python", "build")
         py_version = "%d.%d" % (sys.version_info.major,
                                 sys.version_info.minor)
         try:
             post = next(d for d in os.listdir(classy_build_path)
                         if (d.startswith("lib.") and py_version in d))
             classy_build_path = os.path.join(classy_build_path, post)
             if not os.path.exists(classy_build_path):
                 # If path was given as an install path, try to load global one anyway
                 if self.packages_path:
                     self.log.info(
                         "Importing *global* CLASS (because not compiled?)."
                     )
                 else:
                     raise StopIteration
         except StopIteration:
             raise LoggedError(
                 self.log, "Either CLASS is not in the given folder, "
                 "'%s', or you have not compiled it.", self.path)
     else:
         classy_build_path = None
         self.log.info("Importing *global* CLASS.")
     try:
         self.classy_module = load_module(
             'classy',
             path=classy_build_path,
             min_version=self._classy_repo_version)
         from classy import Class, CosmoSevereError, CosmoComputationError
     except ImportError:
         raise LoggedError(
             self.log, "Couldn't find the CLASS python interface. "
             "Make sure that you have compiled it, and that you either\n"
             " (a) specify a path (you didn't) or\n"
             " (b) install the Python interface globally with\n"
             "     '/path/to/class/python/python setup.py install --user'")
     except VersionCheckError as e:
         raise LoggedError(self.log, str(e))
     self.classy = Class()
     # Propagate errors up
     global CosmoComputationError, CosmoSevereError
     super().initialize()
     # Add general CLASS stuff
     self.extra_args["output"] = self.extra_args.get("output", "")
     if "sBBN file" in self.extra_args:
         self.extra_args["sBBN file"] = (
             self.extra_args["sBBN file"].format(classy=self.path))
     # Derived parameters that may not have been requested, but will be necessary later
     self.derived_extra = []
def get_cosmo(i):
    obh2, och2, w, ns, ln10As, H0, Neff, s8 = AD.test_box_cosmologies()[i]
    h = H0/100.
    Omega_b = obh2/h**2
    Omega_c = och2/h**2
    Omega_m = Omega_b+Omega_c
    params = {'output': 'mPk', 'h': h, 'ln10^{10}A_s': ln10As, 'n_s': ns, 'w0_fld': w, 'wa_fld': 0.0, 'Omega_b': Omega_b, 'Omega_cdm': Omega_c, 'Omega_Lambda': 1.- Omega_m, 'N_eff': Neff, 'P_k_max_1/Mpc':10., 'z_max_pk':10. }
    cosmo = Class()
    cosmo.set(params)
    cosmo.compute()
    return cosmo, h, Omega_m
Ejemplo n.º 23
0
    def setUp(self):
        """
        set up data used in the tests.
        setUp is called before each test function execution.
        """
        self.cosmo = Class()
        self.cosmo_newt = Class()

        self.verbose = {
            'input_verbose': 1,
            'background_verbose': 1,
            'thermodynamics_verbose': 1,
            'perturbations_verbose': 1,
            'transfer_verbose': 1,
            'primordial_verbose': 1,
            'spectra_verbose': 1,
            'nonlinear_verbose': 1,
            'lensing_verbose': 1,
            'output_verbose': 1
        }
        self.scenario = {}
Ejemplo n.º 24
0
    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)
Ejemplo n.º 25
0
    def set_cosmology(self, params):
        """
        Set the cosmological parameters of the emulator. One must
        call this function before actually computing mass functions.
        :param params:
            A dictionary of parameters, where the key is the parameter name and
            value is its value.
        :return:
            None
        """
        try:
            from classy import Class
        except ImportError:
            print("Class not installed. Cannot compute the mass function " +
                  "directly, only predict " +
                  "parameters from the GPs using the predict() function.")
            return

        self.mf_slopes_and_intercepts = self.predict(params)
        #Set up a CLASS dictionary
        self.h = params['H0'] / 100.
        self.Omega_m = (params["omega_b"] + params["omega_cdm"]) / self.h**2
        class_cosmology = {
            'output': 'mPk',
            'H0': params['H0'],
            'ln10^{10}A_s': params['ln10As'],
            'n_s': params['n_s'],
            'w0_fld': params['w0'],
            'wa_fld': 0.0,
            'omega_b': params['omega_b'],
            'omega_cdm': params['omega_cdm'],
            'Omega_Lambda': 1 - self.Omega_m,
            'N_eff': params['N_eff'],
            'P_k_max_1/Mpc': 10.,
            'z_max_pk': 5.03
        }
        #Seed splines in CLASS
        cc = Class()
        cc.set(class_cosmology)
        cc.compute()
        #Make everything attributes
        self.cc = cc
        self.k = np.logspace(-5, 1, num=1000)  # Mpc^-1 comoving
        self.M = np.logspace(10, 16.5, num=1000)  # Msun/h
        self.computed_sigma2 = {}
        self.computed_dsigma2dM = {}
        self.computed_sigma2_splines = {}
        self.computed_dsigma2dM_splines = {}
        self.computed_pk = {}
        self.cosmology_is_set = True
        return
Ejemplo n.º 26
0
    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()
Ejemplo n.º 27
0
    def initialize_class_inst(self):
        """ Get electron ionization fraction from CLASS
        """
        class_parameters = {
            "H0": self.cosmo.H0.value,
            "Omega_b": self.cosmo.Ob0,
            "N_ur": self.cosmo.Neff,
            "Omega_cdm": self.cosmo.Odm0,
            "YHe": self.Y_p,
            "z_reio": self.z_reio
        }

        self.CLASS_inst = Class()
        self.CLASS_inst.set(class_parameters)
        self.CLASS_inst.compute()
Ejemplo n.º 28
0
    def get_cosmo(self, classy_dict):
        """
        Compute a cosmology with CLASS.

        This is purely for convenience.
        Parameters
        ----------
        classy_dict (dictionary) : contains the inputs for the CLASS python
            wrapper such as 'output' and 'l_max_scalars'.

        """
        cosmo = Class()
        cosmo.set(classy_dict)
        cosmo.compute()
        return cosmo
Ejemplo n.º 29
0
def get_cosmo(i):
    obh2, och2, w, ns, ln10As, H0, Neff, s8 = AD.building_box_cosmologies()[i]
    aemcosmo={'Obh2':obh2, 'Och2':och2, 'w0':w, 'n_s':ns, 'ln10^{10}A_s':ln10As, 'N_eff':Neff, 'H0':H0}
    import aemHMF
    hmf = aemHMF.Aemulus_HMF()
    hmf.set_cosmology(aemcosmo)

    h = H0/100.
    Omega_b = obh2/h**2
    Omega_c = och2/h**2
    Omega_m = Omega_b+Omega_c
    params = {'output': 'mPk', 'h': h, 'ln10^{10}A_s': ln10As, 'n_s': ns, 'w0_fld': w, 'wa_fld': 0.0, 'Omega_b': Omega_b, 'Omega_cdm': Omega_c, 'Omega_Lambda': 1.- Omega_m, 'N_eff': Neff, 'P_k_max_1/Mpc':10., 'z_max_pk':10. }
    cosmo = Class()
    cosmo.set(params)
    cosmo.compute()
    return cosmo, h, Omega_m, hmf
Ejemplo n.º 30
0
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