Ejemplo n.º 1
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.º 2
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.º 3
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.º 4
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.º 5
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.º 6
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.º 7
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
Ejemplo n.º 8
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
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.º 10
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.º 11
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.º 12
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.º 13
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.º 14
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.º 15
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.º 16
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
Ejemplo n.º 17
0
    def calculate_spectra(self, cosmo_params, force_recalc=False):
        settings = cosmo_params.copy()
        settings.update({
            "output": "tCl,mPk",
            "evolver": "1",
            "gauge": "newtonian",
            "P_k_max_1/Mpc": 10,
            })

        database = Database(config.DATABASE_DIR, "spectra.dat")

        if settings in database and not force_recalc:
            data = database[settings]
            ell = data["ell"]
            tt = data["tt"]
            kh = data["kh"]
            Pkh = data["Pkh"]
            self.z_rec = data["z_rec"]
        else:
            cosmo = Class()
            cosmo.set(settings)
            cosmo.compute()
            # Cl's
            data = cosmo.raw_cl()
            ell = data["ell"]
            tt = data["tt"]
            # Matter spectrum
            k = np.logspace(-3, 1, config.MATTER_SPECTRUM_CLIENT_SAMPLES_PER_DECADE * 4)
            Pk = np.vectorize(cosmo.pk)(k, 0)
            kh = k * cosmo.h()
            Pkh = Pk / cosmo.h()**3
            # Get redshift of decoupling
            z_rec = cosmo.get_current_derived_parameters(['z_rec'])['z_rec']
            self.z_rec = z_rec
            # Store to database
            database[settings] = {
            "ell": data["ell"],
            "tt": data["tt"],

            "kh": k,
            "Pkh": Pk,

            "z_rec": z_rec,
            }

        return ClSpectrum(ell[2:], tt[2:]), PkSpectrum(kh, Pkh)
class ClassCoreModule(object):
    
    def __init__(self, mapping=DEFAULT_PARAM_MAPPING, constants=CLASS_DEFAULT_PARAMS):
        """
        Core Module for the delegation of the computation of the cmb power
        spectrum to the Class wrapper classy.
        The defaults are for the 6 LambdaCDM cosmological parameters.
        
        :param mapping: (optional) dict mapping name of the parameter to the index
        :param constants: (optional) dict with constants overwriting CLASS defaults
        """
        self.mapping = mapping
        if constants is None:
            constants = {}
        self.constants = constants
        
    def __call__(self, ctx):
        p1 = ctx.getParams()
        
        params = self.constants.copy()
        for k,v in self.mapping.items():
            params[k] = p1[v]
        self.cosmo.set(params)
        self.cosmo.compute()
        if self.constants['lensing'] == 'yes':
            cls = self.cosmo.lensed_cl()
        else:
            cls = self.cosmo.raw_cl()
        Tcmb = self.cosmo.T_cmb()*1e6
        frac = Tcmb**2 * cls['ell'][2:] * (cls['ell'][2:] + 1) / 2. / pi
        ctx.add(CL_TT_KEY, frac*cls['tt'][2:])
        ctx.add(CL_TE_KEY, frac*cls['te'][2:])
        ctx.add(CL_EE_KEY, frac*cls['ee'][2:])
        ctx.add(CL_BB_KEY, frac*cls['bb'][2:])
        self.cosmo.struct_cleanup()

    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()
        
class ClassCoreModule(object):
    def __init__(self,
                 mapping=DEFAULT_PARAM_MAPPING,
                 constants=CLASS_DEFAULT_PARAMS):
        """
        Core Module for the delegation of the computation of the cmb power
        spectrum to the Class wrapper classy.
        The defaults are for the 6 LambdaCDM cosmological parameters.
        
        :param mapping: (optional) dict mapping name of the parameter to the index
        :param constants: (optional) dict with constants overwriting CLASS defaults
        """
        self.mapping = mapping
        if constants is None:
            constants = {}
        self.constants = constants

    def __call__(self, ctx):
        p1 = ctx.getParams()

        params = self.constants.copy()
        for k, v in self.mapping.items():
            params[k] = p1[v]
        self.cosmo.set(params)
        self.cosmo.compute()
        if self.constants['lensing'] == 'yes':
            cls = self.cosmo.lensed_cl()
        else:
            cls = self.cosmo.raw_cl()
        Tcmb = self.cosmo.T_cmb() * 1e6
        frac = Tcmb**2 * cls['ell'][2:] * (cls['ell'][2:] + 1) / 2. / pi
        ctx.add(CL_TT_KEY, frac * cls['tt'][2:])
        ctx.add(CL_TE_KEY, frac * cls['te'][2:])
        ctx.add(CL_EE_KEY, frac * cls['ee'][2:])
        ctx.add(CL_BB_KEY, frac * cls['bb'][2:])
        self.cosmo.struct_cleanup()

    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.º 20
0
def calculate_power(cosmology,
                    k_min,
                    k_max,
                    z=0,
                    num_k=500,
                    scaled_by_h=True,
                    n_s=0.9619,
                    logA=3.0980):
    """
    Calculate the power spectrum P(k,z) over the range k_min <= k <= k_max.
    """
    try:
        from classy import Class
        cosmo = Class()
    except ImportError:
        raise RuntimeError('power.calculate_power requires classy.')

    class_parameters = get_class_parameters(cosmology)
    class_parameters['output'] = 'mPk'
    if scaled_by_h:
        class_parameters['P_k_max_h/Mpc'] = k_max
    else:
        class_parameters['P_k_max_1/Mpc'] = k_max
    class_parameters['n_s'] = n_s
    class_parameters['ln10^{10}A_s'] = logA
    cosmo.set(class_parameters)
    cosmo.compute()

    if scaled_by_h:
        k_scale = cosmo.h()
        Pk_scale = cosmo.h()**3
    else:
        k_scale = 1.
        Pk_scale = 1.

    result = np.empty((num_k, ), dtype=[('k', float), ('Pk', float)])
    result['k'][:] = np.logspace(np.log10(k_min), np.log10(k_max), num_k)
    for i, k in enumerate(result['k']):
        result['Pk'][i] = cosmo.pk(k * k_scale, z) * Pk_scale

    cosmo.struct_cleanup()
    cosmo.empty()

    return result
Ejemplo n.º 21
0
def m_Pk(k=np.logspace(-3, 0., 100), z=0.53, nl_model='trg'):
    print k
    cosmo = Class()

    CLASS_INPUT = {}

    CLASS_INPUT['Mnu'] = ([{'N_eff': 0.0, 'N_ncdm': 1, 'm_ncdm': 0.06, 'deg_ncdm': 3.0}], 'normal')
    CLASS_INPUT['Output_spectra'] = ([{'output': 'mPk', 'P_k_max_1/Mpc': 1, 'z_pk': z}], 'power')

    CLASS_INPUT['Nonlinear'] = ([{'non linear': nl_model}], 'power')
            
    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
    #    }

    cosmo.struct_cleanup()
    cosmo.empty()


    INPUTPOWER = []
    INPUTNORMAL = [{}]
    for key, value in CLASS_INPUT.iteritems():
        models, state = value
        if state == 'power':
            INPUTPOWER.append([{}]+models)
        else:
            INPUTNORMAL.extend(models)

        PRODPOWER = list(itertools.product(*INPUTPOWER))

        DICTARRAY = []
        for normelem in INPUTNORMAL:
            for powelem in PRODPOWER:  # itertools.product(*modpower):
                temp_dict = normelem.copy()
                for elem in powelem:
                    temp_dict.update(elem)
                DICTARRAY.append(temp_dict)

    scenario = {}
    for dic in DICTARRAY:
        scenario.update(dic)
    setting = cosmo.set(dict(verbose.items()+scenario.items()))
    cosmo.compute()
    pk_out = [] 
    for k_i in k: 
        pk_out.append(cosmo.pk(k_i,z))
    return pk_out 
    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
Ejemplo n.º 23
0
def get_theory_pk(k, params):
    """Returns theoretical p(k) at z=0 given k values with given cosmo params

    Parameters
    ----------
    k : array-like
        k values at which to evaluate theoretical p(k)
    params : dict
        Cosmological parameters to pass to Class

    Returns
    -------
    Pk*norm : array
       Theoretical p(k), with proper normalization
    """

    # initialize class
    cosmo = Class()

    # set the class parameters
    # cosmo.set(
    #     {
    #         "output": "mPk",
    #         "P_k_max_1/Mpc": 10.0,
    #         "omega_b": params["omega_b"],
    #         "omega_cdm": params["omega_cdm"],
    #         "h": params["h"],
    #         "A_s": params["A_s"],
    #         "n_s": params["n_s"],
    #         "tau_reio": params["tau_reio"],
    #     }
    # )
    cosmo.set({"output": "mPk", "P_k_max_1/Mpc": 10.0, **params})

    # run class
    cosmo.compute()

    # calculate Pk at all k values (note the normalization for k and P_k)
    h = params["h"]
    return [cosmo.pk(kk * h, 0) * h**3 for kk in k]
Ejemplo n.º 24
0
def get_cls(params=None,
            lmax=3000,
            accurate=False,
            engine='camb',
            de='ppf',
            nonlinear=True):
    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=3.0,
                              lSampleBoost=1.0,
                              lAccuracyBoost=3.0)
            pars.set_for_lmax(lmax=int(lmax + 500),
                              lens_potential_accuracy=3.0,
                              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
        else:
            pars.NonLinear = model.NonLinear_none
        return load_theory(pars, lpad=lmax + 2)

    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
Ejemplo n.º 25
0
    def loglkl(self, params):
        cosmo = Class()
        cosmo.set(params)
        cosmo.compute()

        chi2 = 0.

        # for each point, compute angular distance da, radial distance dr,
        # volume distance dv, sound horizon at baryon drag rs_d,
        # theoretical prediction and chi2 contribution
        for i in range(self.num_points):

            da = cosmo.angular_distance(self.z[i])
            dr = self.z[i] / cosmo.Hubble(self.z[i])
            dv = pow(da * da * (1 + self.z[i]) * (1 + self.z[i]) * dr, 1. / 3.)
            rs = cosmo.rs_drag()

            if self.type[i] == 3:
                theo = dv / rs

            elif self.type[i] == 4:
                theo = dv

            elif self.type[i] == 5:
                theo = da / rs

            elif self.type[i] == 6:
                theo = 1. / cosmo.Hubble(self.z[i]) / rs

            elif self.type[i] == 7:
                theo = rs / dv

            chi2 += ((theo - self.data[i]) / self.error[i]) ** 2

        # return ln(L)
        # lkl = - 0.5 * chi2
        # return -2ln(L)
        lkl = chi2

        return lkl
Ejemplo n.º 26
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.º 27
0
def get_bao_rs_dV(zs,params=None,engine='camb',de='ppf'):
    #FIXME: camb and class only agree at 3% level!!!
    import camb
    params = map_params(params,engine=engine)
    if engine=='camb':
        pars = set_camb_pars(params=params,de=de)
        results = camb.get_results(pars)
        retval = results.get_BAO(zs,pars)[:,0]
    elif engine=='class':
        from classy import Class
        zs = np.asarray(zs)
        cosmo = Class()
        params['output'] = ''
        cosmo.set(params)
        cosmo.compute()
        Hzs = np.array([cosmo.Hubble(z) for z in zs])
        D_As = np.array([cosmo.angular_distance(z) for z in zs])
        D_Vs = ((1+zs)**2 * D_As**2 * zs/Hzs)**(1/3.)
        retval = cosmo.rs_drag()/D_Vs
        cosmo.struct_cleanup()
        cosmo.empty()
    return retval
Ejemplo n.º 28
0
def ComputeTransferData(settings, redshift):
    database_key = settings.copy()
    database_key.update({'redshift': tuple(redshift)})

    database = Database.Database(config.DATABASE_DIR)
    if database_key in database:
        return database[database_key], redshift
    else:
        cosmo = Class()
        cosmo.set(settings)
        cosmo.compute()

        outputData = [cosmo.get_transfer(z) for z in redshift]
        # Calculate d_g/4+psi
        for transfer_function_dict in outputData:
            transfer_function_dict["d_g/4 + psi"] = transfer_function_dict["d_g"]/4 + transfer_function_dict["psi"]
        # Now filter the relevant fields
        fields = TRANSFER_QUANTITIES + ["k (h/Mpc)"]
        outputData = [{field: outputData[i][field] for field in fields} for i in range(len(redshift))]

        database[database_key] = outputData
        return outputData, redshift
Ejemplo n.º 29
0
def calculate_power(cosmology, k_min, k_max, z=0, num_k=500, scaled_by_h=True,
                    n_s=0.9619, logA=3.0980):
    """
    Calculate the power spectrum P(k,z) over the range k_min <= k <= k_max.
    """
    try:
        from classy import Class
        cosmo = Class()
    except ImportError:
        raise RuntimeError('power.calculate_power requires classy.')

    class_parameters = get_class_parameters(cosmology)
    class_parameters['output'] = 'mPk'
    if scaled_by_h:
        class_parameters['P_k_max_h/Mpc'] = k_max
    else:
        class_parameters['P_k_max_1/Mpc'] = k_max
    class_parameters['n_s'] = n_s
    class_parameters['ln10^{10}A_s'] = logA
    cosmo.set(class_parameters)
    cosmo.compute()

    if scaled_by_h:
        k_scale = cosmo.h()
        Pk_scale = cosmo.h()**3
    else:
        k_scale = 1.
        Pk_scale = 1.

    result = np.empty((num_k,), dtype=[('k', float), ('Pk', float)])
    result['k'][:] = np.logspace(np.log10(k_min), np.log10(k_max), num_k)
    for i, k in enumerate(result['k']):
        result['Pk'][i] = cosmo.pk(k * k_scale, z) * Pk_scale

    cosmo.struct_cleanup()
    cosmo.empty()

    return result
Ejemplo n.º 30
0
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 setup_class(self):
     obh2, och2, w, ns, ln10As, H0, Neff = self.parameters
     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,
               #'sigma8':sigma8,
               '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':5.,'non linear':'halofit'}
     cosmo = Class()
     cosmo.set(params)
     print("CLASS is computing")
     cosmo.compute()
     print("\tCLASS done")
     self.class_cosmo_object = cosmo
     self.sigma8 = cosmo.sigma8()
     return
Ejemplo n.º 32
0
def getDl( pii1=0.5e-10, pii2=1e-9, pri1=1e-13 ):
    # Define your cosmology (what is not specified will be set to CLASS default parameters)
    params = {
        'output': 'tCl lCl pCl', 
        'modes': 's', # scalar perturbations
        'lensing': 'yes',
        'ic': 'ad&cdi',
        'l_max_scalars':max_scalars,
        'P_k_ini type': 'two_scales',
        'k1': 0.002,
        'k2': 0.1,
        'P_{RR}^1': 2.34e-9,
        'P_{RR}^2': 2.115e-9,
        'P_{II}^1' : pii1,
        'P_{II}^2' : pii2,
        'P_{RI}^1' : pri1}

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

    # print(dir(cosmo)) # use this command to see what is in the cosmo

    # It is a dictionary that contains the fields: tt, te, ee, bb, pp, tp
    cls = cosmo.raw_cl(max_l)  # Access the  cl until l=1000

    yy = np.array( cls['ee'][1:] )
    zz = np.array( cls['tt'][1:] ) 
    yz = np.array( cls['te'][1:] ) 

    ee = ((ell)*(ell+1) * yy / (2 * math.pi))
    tt =  ((ell)*(ell+1) * zz / (2 * math.pi))
    te = ((ell)*(ell+1) * yz / (2 * math.pi))

    
    cosmo.struct_cleanup()
    return tt, te, ee
Ejemplo n.º 33
0
def calc_power_spec(cosmos, zs, lin=True):
    Nc = len(cosmos)
    Nz = len(zs)
    ps = np.zeros((Nc, Nz, len(k)))
    for i in range(Nc):
        obh2, och2, w, ns, ln10As, H0, Neff, s8 = cosmos[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': 5.
        }
        if not lin:
            params['non linear'] = 'halofit'
        cosmo = Class()
        cosmo.set(params)
        cosmo.compute()
        for j in range(len(zs)):
            if lin:
                ps[i, j] = np.array([cosmo.pk_lin(ki, zs[j]) for ki in k])
            else:
                ps[i, j] = np.array([cosmo.pk(ki, zs[j]) for ki in k])
            continue
        print("Finished box%d" % i)
    return ps
Ejemplo n.º 34
0
    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
Ejemplo n.º 35
0
def get_power(params, l_min, l_max):

    #CLASS gives results in natural units
    #convert to muK^2 to match data
    T_cmb = 2.7255e6  #temp in microkelvins
    #create an instance of CLASS wrapper w/correct params
    cosmo = Class()
    cosmo.set(params)
    #cosmo.set({'output':'tCl,pCl,lCl,mPk','lensing':'yes','P_k_max_1/Mpc':3.0})

    cosmo.compute()

    #lensed cl until l=l_max
    output = cosmo.raw_cl(l_max)  #lensed_cl(l_max)
    ls = output['ell'][l_min:]
    Cls = output['tt'][l_min:]

    Dls = ls * (ls + 1) * Cls * T_cmb**2 / (2 * np.pi)

    #clean ups
    cosmo.struct_cleanup()
    cosmo.empty()

    return ls, Cls, Dls
Ejemplo n.º 36
0
def ComputeTransferData(settings, redshift):
    database_key = settings.copy()
    database_key.update({'redshift': tuple(redshift)})

    database = Database.Database(config.DATABASE_DIR)
    if database_key in database:
        return database[database_key], redshift
    else:
        cosmo = Class()
        cosmo.set(settings)
        cosmo.compute()

        outputData = [cosmo.get_transfer(z) for z in redshift]
        # Calculate d_g/4+psi
        for transfer_function_dict in outputData:
            transfer_function_dict["d_g/4 + psi"] = transfer_function_dict[
                "d_g"] / 4 + transfer_function_dict["psi"]
        # Now filter the relevant fields
        fields = TRANSFER_QUANTITIES + ["k (h/Mpc)"]
        outputData = [{field: outputData[i][field]
                       for field in fields} for i in range(len(redshift))]

        database[database_key] = outputData
        return outputData, redshift
Ejemplo n.º 37
0
    def compute_Sigma8(self):

        # compute the values of sigma_8
        # given that we have already assigned
        # the cosmologies
        # this part does not depend on the systematics
        cosmo = Class()
        cosmo.set(self.cosmoParams)

        if self.settings.include_neutrino:
            cosmo.set(self.other_settings)
            cosmo.set(self.neutrino_settings)

        cosmo.set(self.class_argumets)

        try:
            cosmo.compute()

        except CosmoComputationError as failure_message:

            print(failure_message)

            self.sigma_8 = np.nan

        except CosmoSevereError as critical_message:

            print(critical_message)

            self.sigma_8 = np.nan

        sigma_8 = cosmo.sigma8()

        cosmo.struct_cleanup()
        cosmo.empty()

        del cosmo

        return sigma_8
Ejemplo n.º 38
0
from classy import Class


# In[ ]:

font = {'size'   : 20, 'family':'STIXGeneral'}
axislabelfontsize='large'
matplotlib.rc('font', **font)
matplotlib.mathtext.rcParams['legend.fontsize']='medium'


# In[ ]:

#Lambda CDM
LCDM = Class()
LCDM.set({'Omega_cdm':0.25,'Omega_b':0.05})
LCDM.compute()


# In[ ]:

#Einstein-de Sitter
CDM = Class()
CDM.set({'Omega_cdm':0.95,'Omega_b':0.05})
CDM.compute()

# Just to cross-check that Omega_Lambda is negligible
# (but not exactly zero because we neglected radiation)
derived = CDM.get_current_derived_parameters(['Omega0_lambda'])
print derived
print "Omega_Lambda =",derived['Omega0_lambda']
Ejemplo n.º 39
0
class TestClass(unittest.TestCase):
    """
    Testing Class and its wrapper classy on different cosmologies

    To run it, do
    ~] nosetest test_class.py

    It will run many times Class, on different cosmological scenarios, and
    everytime testing for different output possibilities (none asked, only mPk,
    etc..)

    """

    def setUp(self):
        """
        set up data used in the tests.
        setUp is called before each test function execution.
        """
        self.cosmo = 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 = {"lensing": "yes"}

    def tearDown(self):
        self.cosmo.struct_cleanup()
        self.cosmo.empty()
        del self.scenario

    @parameterized.expand(
        itertools.product(
            ("LCDM", "Mnu", "Positive_Omega_k", "Negative_Omega_k", "Isocurvature_modes"),
            (
                {"output": ""},
                {"output": "mPk"},
                {"output": "tCl"},
                {"output": "tCl pCl lCl"},
                {"output": "mPk tCl lCl", "P_k_max_h/Mpc": 10},
                {"output": "nCl sCl"},
                {"output": "tCl pCl lCl nCl sCl"},
            ),
            ({"gauge": "newtonian"}, {"gauge": "sync"}),
            ({}, {"non linear": "halofit"}),
        )
    )
    def test_wrapper_implementation(self, name, scenario, gauge, nonlinear):
        """Create a few instances based on different cosmologies"""
        if name == "Mnu":
            self.scenario.update({"N_ncdm": 1, "m_ncdm": 0.06})
        elif name == "Positive_Omega_k":
            self.scenario.update({"Omega_k": 0.01})
        elif name == "Negative_Omega_k":
            self.scenario.update({"Omega_k": -0.01})
        elif name == "Isocurvature_modes":
            self.scenario.update({"ic": "ad,nid,cdi", "c_ad_cdi": -0.5})

        self.scenario.update(scenario)
        if scenario != {}:
            self.scenario.update(gauge)
        self.scenario.update(nonlinear)

        sys.stderr.write("\n\n---------------------------------\n")
        sys.stderr.write("| Test case %s |\n" % name)
        sys.stderr.write("---------------------------------\n")
        for key, value in self.scenario.iteritems():
            sys.stderr.write("%s = %s\n" % (key, value))
        sys.stderr.write("\n")

        setting = self.cosmo.set(dict(self.verbose.items() + self.scenario.items()))
        self.assertTrue(setting, "Class failed to initialize with input dict")

        cl_list = ["tCl", "lCl", "pCl", "nCl", "sCl"]

        # Depending on the cases, the compute should fail or not
        should_fail = True
        output = self.scenario["output"].split()
        for elem in output:
            if elem in ["tCl", "pCl"]:
                for elem2 in output:
                    if elem2 == "lCl":
                        should_fail = False
                        break

        if not should_fail:
            self.cosmo.compute()
        else:
            self.assertRaises(CosmoSevereError, self.cosmo.compute)
            return

        self.assertTrue(self.cosmo.state, "Class failed to go through all __init__ methods")
        if self.cosmo.state:
            print "--> Class is ready"
        # Depending
        if "output" in self.scenario.keys():
            # Positive tests
            output = self.scenario["output"]
            for elem in output.split():
                if elem in cl_list:
                    print "--> testing raw_cl function"
                    cl = self.cosmo.raw_cl(100)
                    self.assertIsNotNone(cl, "raw_cl returned nothing")
                    self.assertEqual(np.shape(cl["tt"])[0], 101, "raw_cl returned wrong size")
                if elem == "mPk":
                    print "--> testing pk function"
                    pk = self.cosmo.pk(0.1, 0)
                    self.assertIsNotNone(pk, "pk returned nothing")
            # Negative tests of output functions
            if not any([elem in cl_list for elem in output.split()]):
                print "--> testing absence of any Cl"
                self.assertRaises(CosmoSevereError, self.cosmo.raw_cl, 100)
            if "mPk" not in self.scenario["output"].split():
                print "--> testing absence of mPk"
                # args = (0.1, 0)
                self.assertRaises(CosmoSevereError, self.cosmo.pk, 0.1, 0)

    @parameterized.expand(
        itertools.product(("massless", "massive", "both"), ("photons", "massless", "exact"), ("t", "s, t"))
    )
    def test_tensors(self, scenario, method, modes):
        """Test the new tensor mode implementation"""
        self.scenario = {}
        if scenario == "massless":
            self.scenario.update({"N_eff": 3.046, "N_ncdm": 0})
        elif scenario == "massiv":
            self.scenario.update({"N_eff": 0, "N_ncdm": 2, "m_ncdm": "0.03, 0.04", "deg_ncdm": "2, 1"})
        elif scenario == "both":
            self.scenario.update({"N_eff": 1.5, "N_ncdm": 2, "m_ncdm": "0.03, 0.04", "deg_ncdm": "1, 0.5"})

        sys.stderr.write("\n\n---------------------------------\n")
        sys.stderr.write("| Test case: %s %s %s |\n" % (scenario, method, modes))
        sys.stderr.write("---------------------------------\n")
        self.scenario.update({"tensor method": method, "modes": modes, "output": "tCl, pCl"})
        for key, value in self.scenario.iteritems():
            sys.stderr.write("%s = %s\n" % (key, value))
        sys.stderr.write("\n")
        self.cosmo.set(dict(self.verbose.items() + self.scenario.items()))
        self.cosmo.compute()

    @parameterized.expand(itertools.izip(powerset(["100*theta_s", "Omega_dcdmdr"]), powerset([1.04, 0.20])))
    def test_shooting_method(self, variables, values):
        Omega_cdm = 0.25

        scenario = {"Omega_b": 0.05}

        for variable, value in zip(variables, values):
            scenario.update({variable: value})

        if "Omega_dcdmdr" in variables:
            scenario.update({"Gamma_dcdm": 100, "Omega_cdm": Omega_cdm - scenario["Omega_dcdmdr"]})
        else:
            scenario.update({"Omega_cdm": Omega_cdm})

        sys.stderr.write("\n\n---------------------------------\n")
        sys.stderr.write("| Test shooting: %s |\n" % (", ".join(variables)))
        sys.stderr.write("---------------------------------\n")
        for key, value in scenario.iteritems():
            sys.stderr.write("%s = %s\n" % (key, value))
        sys.stderr.write("\n")

        scenario.update(self.verbose)
        self.assertTrue(self.cosmo.set(scenario), "Class failed to initialise with this input")
        self.assertRaises
        self.cosmo.compute()

        # Now, check that the values are properly extracted
        for variable, value in zip(variables, values):
            if variable == "100*theta_s":
                computed_value = self.cosmo.get_current_derived_parameters([variable])[variable]
                self.assertAlmostEqual(value, computed_value, places=5)
Ejemplo n.º 40
0
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']}
Ejemplo n.º 41
0
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']}
params = {
	    '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 = {
Ejemplo n.º 43
0
                   #'k_step_sub':'0.01',
                   'k_per_decade_for_pk':k_per_decade,
                   'k_per_decade_for_bao':k_per_decade,
                   'k_min_tau0':k_min_tau0, # this value controls the minimum k value in the figure
                   'perturb_sampling_stepsize':'0.05',
                   'P_k_max_1/Mpc':P_k_max_inv_Mpc,
                   'compute damping scale':'yes', # needed to output and plot Silk damping scale
                   'gauge':'newtonian'}

###############
#
# call CLASS
#
###############
M = Class()
M.set(common_settings)
M.compute()
#
# define conformal time sampling array
#
times = M.get_current_derived_parameters(['tau_rec','conformal_age'])
tau_rec=times['tau_rec']
tau_0 = times['conformal_age']
tau1 = np.logspace(math.log10(tau_ini),math.log10(tau_rec),tau_num_early)
tau2 = np.logspace(math.log10(tau_rec),math.log10(tau_0),tau_num_late)[1:]
tau2[-1] *= 0.999 # this tiny shift avoids interpolation errors
tau = np.concatenate((tau1,tau2))
tau_num = len(tau)
#
# use table of background and thermodynamics quantitites to define some functions
# returning some characteristic scales
Ejemplo n.º 44
0
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']}
Ejemplo n.º 45
0
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']}
Ejemplo n.º 46
0
class TestClass(unittest.TestCase):
    """
    Testing Class and its wrapper classy on different cosmologies

    To run it, do
    ~] nosetest test_class.py

    It will run many times Class, on different cosmological scenarios, and
    everytime testing for different output possibilities (none asked, only mPk,
    etc..)

    """

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

        self.verbose = {
            '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 = {'lensing':'yes'}

    def tearDown(self):
        self.cosmo.struct_cleanup()
        self.cosmo.empty()
        del self.scenario

    @parameterized.expand(
        itertools.product(
            ('LCDM',
             'Mnu',
             'Positive_Omega_k',
             'Negative_Omega_k',
             'Isocurvature_modes', ),
            ({'output': ''}, {'output': 'mPk'}, {'output': 'tCl'},
             {'output': 'tCl pCl lCl'}, {'output': 'mPk tCl lCl', 'P_k_max_h/Mpc':10},
             {'output': 'nCl sCl'}, {'output': 'tCl pCl lCl nCl sCl'}),
            ({'gauge': 'newtonian'}, {'gauge': 'sync'}),
            ({}, {'non linear': 'halofit'})))
    def test_parameters(self, name, scenario, gauge, nonlinear):
        """Create a few instances based on different cosmologies"""
        if name == 'Mnu':
            self.scenario.update({'N_ncdm': 1, 'm_ncdm': 0.06})
        elif name == 'Positive_Omega_k':
            self.scenario.update({'Omega_k': 0.01})
        elif name == 'Negative_Omega_k':
            self.scenario.update({'Omega_k': -0.01})
        elif name == 'Isocurvature_modes':
            self.scenario.update({'ic': 'ad,nid,cdi', 'c_ad_cdi': -0.5})

        self.scenario.update(scenario)
        if scenario != {}:
            self.scenario.update(gauge)
        self.scenario.update(nonlinear)

        sys.stderr.write('\n\n---------------------------------\n')
        sys.stderr.write('| Test case %s |\n' % name)
        sys.stderr.write('---------------------------------\n')
        for key, value in self.scenario.iteritems():
            sys.stderr.write("%s = %s\n" % (key, value))
        sys.stderr.write("\n")

        setting = self.cosmo.set(
            dict(self.verbose.items()+self.scenario.items()))
        self.assertTrue(setting, "Class failed to initialize with input dict")

        cl_list = ['tCl', 'lCl', 'pCl', 'nCl', 'sCl']

        # Depending on the cases, the compute should fail or not
        should_fail = True
        output = self.scenario['output'].split()
        for elem in output:
            if elem in ['tCl', 'pCl']:
                for elem2 in output:
                    if elem2 == 'lCl':
                        should_fail = False
                        break

        if not should_fail:
            self.cosmo.compute()
        else:
            self.assertRaises(CosmoSevereError, self.cosmo.compute)
            return

        self.assertTrue(
            self.cosmo.state,
            "Class failed to go through all __init__ methods")
        if self.cosmo.state:
            print '--> Class is ready'
        # Depending
        if 'output' in self.scenario.keys():
            # Positive tests
            output = self.scenario['output']
            for elem in output.split():
                if elem in cl_list:
                    print '--> testing raw_cl function'
                    cl = self.cosmo.raw_cl(100)
                    self.assertIsNotNone(cl, "raw_cl returned nothing")
                    self.assertEqual(
                        np.shape(cl['tt'])[0], 101,
                        "raw_cl returned wrong size")
                if elem == 'mPk':
                    print '--> testing pk function'
                    pk = self.cosmo.pk(0.1, 0)
                    self.assertIsNotNone(pk, "pk returned nothing")
            # Negative tests of output functions
            if not any([elem in cl_list for elem in output.split()]):
                print '--> testing absence of any Cl'
                self.assertRaises(CosmoSevereError, self.cosmo.raw_cl, 100)
            if 'mPk' not in self.scenario['output'].split():
                print '--> testing absence of mPk'
                #args = (0.1, 0)
                self.assertRaises(CosmoSevereError, self.cosmo.pk, 0.1, 0)

        print '~~~~~~~~ passed ? '

    @parameterized.expand(
        itertools.product(
            ('massless', 'massive', 'both'),
            ('photons', 'massless', 'exact'),
            ('t', 's, t')))
    def test_tensors(self, scenario, method, modes):
        """Test the new tensor mode implementation"""
        self.scenario = {}
        if scenario == 'massless':
            self.scenario.update({'N_eff': 3.046, 'N_ncdm':0})
        elif scenario == 'massiv':
            self.scenario.update(
                {'N_eff': 0, 'N_ncdm': 2, 'm_ncdm': '0.03, 0.04',
                 'deg_ncdm': '2, 1'})
        elif scenario == 'both':
            self.scenario.update(
                {'N_eff': 1.5, 'N_ncdm': 2, 'm_ncdm': '0.03, 0.04',
                 'deg_ncdm': '1, 0.5'})

        self.scenario.update({
            'tensor method': method, 'modes': modes,
            'output': 'tCl, pCl'})
        for key, value in self.scenario.iteritems():
            sys.stderr.write("%s = %s\n" % (key, value))
        sys.stderr.write("\n")
        self.cosmo.set(
            dict(self.verbose.items()+self.scenario.items()))
        self.cosmo.compute()
Ejemplo n.º 47
0
                   'h':0.67556,
                   'omega_b':0.022032,
                   'omega_cdm':0.12038,
                   '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'})
Ejemplo n.º 48
0
if False: # In case you want to plot the N(z)s
	fig, axs = plt.subplots(1, 2, figsize=(14, 5))
	finer_z_grid = np.linspace(0, 2, num=2000)
	for i, nz in enumerate(redshiftdistributions):
		ic = str(i+1)
		nz_grid = nz.eval(z_grid)
		finer_nz_grid = nz.eval(finer_z_grid)
		axs[i].plot(finer_z_grid, finer_nz_grid, label='Gaussian Mixture')
		axs[i].plot(z_grid, nz_grid, label='Histogram-ized', ls='steps')
	plt.show()

# Now run Class!
cosmo = Class()
# Scenario 1
cosmo.set(dict(mainparams.items()+scenario1.items()))
cosmo.compute()
cl1 = cosmo.density_cl(mainparams['l_max_lss'])
cosmo.struct_cleanup()
cosmo.empty()
# Scenario 2
cosmo.set(dict(mainparams.items()+scenario2.items()))
cosmo.compute()
cl2 = cosmo.density_cl(mainparams['l_max_lss'])
cosmo.struct_cleanup()
cosmo.empty()

# The Cls should be very close if the histogram is binned finely
nbins = len(redshiftdistributions)
print 'Comparing accuracy of N(z) representation: multigaussian vs histograms'
for i in range(nbins*(nbins+1)/2): 
Ejemplo n.º 49
0
                  'ncdm_fluid_approximation':3,
                  # You may uncomment this line to get more info on the ncdm sector from Class:
                  'background_verbose':1
                 }

# array of k values in 1/Mpc
kvec = np.logspace(-4,np.log10(3),100)
# array for storing legend
legarray = []

# loop over total mass values
for sum_masses in [0.1, 0.115, 0.13]:
    # normal hierarchy
    [m1, m2, m3] = get_masses(2.45e-3,7.50e-5, sum_masses, 'NH')
    NH = Class()
    NH.set(commonsettings)
    NH.set({'m_ncdm':str(m1)+','+str(m2)+','+str(m3)})
    NH.compute()
    # inverted hierarchy
    [m1, m2, m3] = get_masses(2.45e-3,7.50e-5, sum_masses, 'IH')
    IH = Class()
    IH.set(commonsettings)
    IH.set({'m_ncdm':str(m1)+','+str(m2)+','+str(m3)})
    IH.compute()
    pkNH = []
    pkIH = []
    for k in kvec:
        pkNH.append(NH.pk(k,0.))
        pkIH.append(IH.pk(k,0.))
    NH.struct_cleanup()
    IH.struct_cleanup()
Ejemplo n.º 50
0
# coding: utf-8

# In[ ]:

# import classy module
from classy import Class


# 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:]
Ejemplo n.º 51
0
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()
Ejemplo n.º 52
0
class TestClass(unittest.TestCase):
    """
    Testing Class and its wrapper classy on different cosmologies

    To run it, do
    ~] nosetest test_class.py

    It will run many times Class, on different cosmological scenarios, and
    everytime testing for different output possibilities (none asked, only mPk,
    etc..)

    """

    @classmethod
    def setUpClass(self):
        self.faulty_figs_path = os.path.join(
            os.path.sep.join(os.path.realpath(__file__).split(os.path.sep)[:-1]), "faulty_figs"
        )

        if os.path.isdir(self.faulty_figs_path):
            shutil.rmtree(self.faulty_figs_path)

        os.mkdir(self.faulty_figs_path)

    @classmethod
    def tearDownClass(self):
        pass

    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 = {}

    def tearDown(self):
        self.cosmo.struct_cleanup()
        self.cosmo.empty()
        self.cosmo_newt.struct_cleanup()
        self.cosmo_newt.empty()
        del self.scenario

    def poormansname(self, somedict):
        string = "_".join([k + "=" + str(v) for k, v in somedict.iteritems()])
        string = string.replace("/", "%")
        string = string.replace(",", "")
        string = string.replace(" ", "")
        return string

    @parameterized.expand(TUPLE_ARRAY)
    def test_0wrapper_implementation(self, inputdict):
        """Create a few instances based on different cosmologies"""
        self.scenario.update(inputdict)

        self.name = self.poormansname(inputdict)

        sys.stderr.write("\n\n---------------------------------\n")
        sys.stderr.write("| Test case %s |\n" % self.name)
        sys.stderr.write("---------------------------------\n")
        for key, value in self.scenario.iteritems():
            sys.stderr.write("%s = %s\n" % (key, value))
            sys.stdout.write("%s = %s\n" % (key, value))
        sys.stderr.write("\n")

        setting = self.cosmo.set(dict(self.verbose.items() + self.scenario.items()))
        self.assertTrue(setting, "Class failed to initialize with input dict")

        cl_dict = {"tCl": ["tt"], "lCl": ["pp"], "pCl": ["ee", "bb"]}
        density_cl_list = ["nCl", "sCl"]

        # 'lensing' is always set to yes. Therefore, trying to compute 'tCl' or
        # 'pCl' will fail except if we also ask for 'lCl'. The flag
        # 'should_fail' stores this status.
        sys.stderr.write("Should")
        should_fail = self.test_incompatible_input()
        if should_fail:
            sys.stderr.write(" fail...\n")
        else:
            sys.stderr.write(" not fail...\n")

        if not should_fail:
            self.cosmo.compute()
        else:
            self.assertRaises(CosmoSevereError, self.cosmo.compute)
            return

        self.assertTrue(self.cosmo.state, "Class failed to go through all __init__ methods")
        if self.cosmo.state:
            print "--> Class is ready"
        # Depending
        if "output" in self.scenario.keys():
            # Positive tests of raw cls
            output = self.scenario["output"]
            for elem in output.split():
                if elem in cl_dict.keys():
                    for cl_type in cl_dict[elem]:
                        sys.stderr.write("--> testing raw_cl for %s\n" % cl_type)
                        cl = self.cosmo.raw_cl(100)
                        self.assertIsNotNone(cl, "raw_cl returned nothing")
                        self.assertEqual(np.shape(cl[cl_type])[0], 101, "raw_cl returned wrong size")
                    # TODO do the same for lensed if 'lCl' is there, and for
                    # density cl
                if elem == "mPk":
                    sys.stderr.write("--> testing pk function\n")
                    pk = self.cosmo.pk(0.1, 0)
                    self.assertIsNotNone(pk, "pk returned nothing")
            # Negative tests of output functions
            if not any([elem in cl_dict.keys() for elem in output.split()]):
                sys.stderr.write("--> testing absence of any Cl\n")
                self.assertRaises(CosmoSevereError, self.cosmo.raw_cl, 100)
            if "mPk" not in output.split():
                sys.stderr.write("--> testing absence of mPk\n")
                self.assertRaises(CosmoSevereError, self.cosmo.pk, 0.1, 0)

        if COMPARE_OUTPUT:
            # Now, compute with Newtonian gauge, and compare the results
            self.cosmo_newt.set(dict(self.verbose.items() + self.scenario.items()))
            self.cosmo_newt.set({"gauge": "newtonian"})
            self.cosmo_newt.compute()
            # Check that the computation worked
            self.assertTrue(self.cosmo_newt.state, "Class failed to go through all __init__ methods in Newtonian gauge")

            self.compare_output(self.cosmo, self.cosmo_newt)

    def test_incompatible_input(self):

        should_fail = False

        # If we have tensor modes, we must have one tensor observable,
        # either tCl or pCl.
        if has_tensor(self.scenario):
            if "output" not in self.scenario.keys():
                should_fail = True
            else:
                output = self.scenario["output"].split()
                if "tCl" not in output and "pCl" not in output:
                    should_fail = True

        # If we have specified lensing, we must have lCl in output,
        # otherwise lensing will not be read (which is an error).
        if "lensing" in self.scenario.keys():
            if "output" not in self.scenario.keys():
                should_fail = True
            else:
                output = self.scenario["output"].split()
                if "lCl" not in output:
                    should_fail = True
                elif "tCl" not in output and "pCl" not in output:
                    should_fail = True

        # If we have specified a tensor method, we must have tensors.
        if "tensor method" in self.scenario.keys():
            if not has_tensor(self.scenario):
                should_fail = True

        # If we have specified non linear, we must have some form of
        # perturbations output.
        if "non linear" in self.scenario.keys():
            if "output" not in self.scenario.keys():
                should_fail = True

        # If we ask for Cl's of lensing potential, we must have scalar modes.
        if "output" in self.scenario.keys() and "lCl" in self.scenario["output"].split():
            if "modes" in self.scenario.keys() and self.scenario["modes"].find("s") == -1:
                should_fail = True

        # If we specify initial conditions (for scalar modes), we must have
        # perturbations and scalar modes.
        if "ic" in self.scenario.keys():
            if "modes" in self.scenario.keys() and self.scenario["modes"].find("s") == -1:
                should_fail = True
            if "output" not in self.scenario.keys():
                should_fail = True

        # If we use inflation module, we must have scalar modes,
        # tensor modes, no vector modes and we should only have adiabatic IC:
        if "P_k_ini type" in self.scenario.keys() and self.scenario["P_k_ini type"].find("inflation") != -1:
            if "modes" not in self.scenario.keys():
                should_fail = True
            else:
                if self.scenario["modes"].find("s") == -1:
                    should_fail = True
                if self.scenario["modes"].find("v") != -1:
                    should_fail = True
                if self.scenario["modes"].find("t") == -1:
                    should_fail = True
            if "ic" in self.scenario.keys() and self.scenario["ic"].find("i") != -1:
                should_fail = True

        return should_fail

    def compare_output(self, reference, candidate):
        sys.stderr.write("\n\n---------------------------------\n")
        sys.stderr.write("| Comparing synch and Newt: |\n")
        sys.stderr.write("---------------------------------\n")

        for elem in ["raw_cl", "lensed_cl", "density_cl"]:
            # Try to get the elem, but if they were not computed, a
            # CosmoComputeError should be raised. In this case, ignore the
            # whole block.
            try:
                to_test = getattr(candidate, elem)()
            except CosmoSevereError:
                continue
            ref = getattr(reference, elem)()
            for key, value in ref.iteritems():
                if key != "ell":
                    sys.stderr.write("--> testing equality of %s %s\n" % (elem, key))
                    # For all self spectra, try to compare allclose
                    if key[0] == key[1]:
                        # If it is a 'dd' or 'll', it is a dictionary.
                        if isinstance(value, dict):
                            for subkey in value.iterkeys():
                                try:
                                    np.testing.assert_allclose(
                                        value[subkey], to_test[key][subkey], rtol=1e-03, atol=1e-20
                                    )
                                except AssertionError:
                                    self.cl_faulty_plot(elem + "_" + key, value[subkey][2:], to_test[key][subkey][2:])
                                except TypeError:
                                    self.cl_faulty_plot(elem + "_" + key, value[subkey][2:], to_test[key][subkey][2:])
                        else:
                            try:
                                np.testing.assert_allclose(value, to_test[key], rtol=1e-03, atol=1e-20)
                            except AssertionError:
                                self.cl_faulty_plot(elem + "_" + key, value[2:], to_test[key][2:])
                            except TypeError:
                                self.cl_faulty_plot(elem + "_" + key, value[2:], to_test[key][2:])
                    # For cross-spectra, as there can be zero-crossing, we
                    # instead compare the difference.
                    else:
                        # First, we multiply each array by the biggest value
                        norm = max(np.abs(value).max(), np.abs(to_test[key]).max())
                        value *= norm
                        to_test[key] *= norm
                        try:
                            np.testing.assert_array_almost_equal(value, to_test[key], decimal=3)
                        except AssertionError:
                            self.cl_faulty_plot(elem + "_" + key, value[2:], to_test[key][2:])

        if "output" in self.scenario.keys():
            if self.scenario["output"].find("mPk") != -1:
                sys.stderr.write("--> testing equality of Pk")
                k = np.logspace(-2, log10(self.scenario["P_k_max_1/Mpc"]))
                reference_pk = np.array([reference.pk(elem, 0) for elem in k])
                candidate_pk = np.array([candidate.pk(elem, 0) for elem in k])
                try:
                    np.testing.assert_allclose(reference_pk, candidate_pk, rtol=5e-03, atol=1e-20)
                except AssertionError:
                    self.pk_faulty_plot(k, reference_pk, candidate_pk)

    def cl_faulty_plot(self, cl_type, reference, candidate):
        path = os.path.join(self.faulty_figs_path, self.name)

        fig = plt.figure()
        ax_lin = plt.subplot(211)
        ax_log = plt.subplot(212)
        ell = np.arange(max(np.shape(candidate))) + 2
        ax_lin.plot(ell, 1 - candidate / reference)
        ax_log.loglog(ell, abs(1 - candidate / reference))

        ax_lin.set_xlabel("l")
        ax_log.set_xlabel("l")
        ax_lin.set_ylabel("1-candidate/reference")
        ax_log.set_ylabel("abs(1-candidate/reference)")

        ax_lin.set_title(self.name)
        ax_log.set_title(self.name)

        ax_lin.legend([cl_type])
        ax_log.legend([cl_type])

        fig.savefig(path + "_" + cl_type + ".pdf")

        # Store parameters (contained in self.scenario) to text file
        parameters = dict(self.verbose.items() + self.scenario.items())
        with open(path + ".ini", "w") as param_file:
            for key, value in parameters.iteritems():
                param_file.write(key + " = " + str(value) + "\n")

    def pk_faulty_plot(self, k, reference, candidate):
        path = os.path.join(self.faulty_figs_path, self.name)

        fig = plt.figure()
        ax_lin = plt.subplot(211)
        ax_log = plt.subplot(212)
        ax_lin.plot(k, 1 - candidate / reference)
        ax_log.loglog(k, abs(1 - candidate / reference))

        ax_lin.set_xlabel("k")
        ax_log.set_xlabel("k")
        ax_lin.set_ylabel("1-candidate/reference")
        ax_log.set_ylabel("abs(1-candidate/reference)")

        ax_lin.set_title(self.name)
        ax_log.set_title(self.name)

        ax_lin.legend("$P_k$")
        ax_log.legend("$P_k$")

        fig.savefig(path + "_" + "pk" + ".pdf")

        # Store parameters (contained in self.scenario) to text file
        parameters = dict(self.verbose.items() + self.scenario.items())
        with open(path + ".ini", "w") as param_file:
            for key, value in parameters.iteritems():
                param_file.write(key + " = " + str(value) + "\n")