Ejemplo n.º 1
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.º 2
0
                'omega_cdm':0.1198,
                'A_s':A_s,
                'n_s':n_s,
                'tau_reio':0.079,
                'k_output_values':k_res_numerical[0],
                'output':'tCl,lCl,mPk,dTk,vTk',
                'use_big_theta_scf': 'yes',
                'scf_has_perturbations': 'yes',
                'attractor_ic_scf': 'no',
                'write background':'yes',
                'compute damping scale':'yes'}
                try:
                    cosmo.set(params) # Set the parameters to the cosmological code
                    cosmo.compute() # solve physics

                    all_k = cosmo.get_perturbations()  # this potentially constains scalars/tensors and all k values
                    one_k = all_k['scalar'][0]     # this contains only the scalar perturbations for the requested k values
                    #
                    background = cosmo.get_background() # load background table
                    tau = one_k['tau [Mpc]']
                    delta_phi = one_k['delta_phi_scf']
                    background_tau = background['conf. time [Mpc]'] # read conformal times in background table
                    background_z = background['z'] # read redshift
                    background_Om_scf = background['(.)Omega_scf'] # read redshift
                    background_z_at_tau = interp1d(background_tau,background_z)
                    fudge = 1.6
                    phi_enveloppe = Theta_initial[j]*10**cosmo.log10_f_axion()*(fudge/(10**ac[i]*background_z_at_tau(tau)))**(-3.*(1+wn)/2/n_axion)
                    background_Om_scf_at_z = interp1d(background_z,background_Om_scf)
                    dimensionless_power_spectrum = np.sqrt(delta_phi*delta_phi*A_s*(k_res_numerical[0]/K_star)**(n_s-1))/(phi_enveloppe)
                    tau_at_delta_phi_over_phi = interp1d(dimensionless_power_spectrum,tau)
                    if max(1,max(abs(dimensionless_power_spectrum))) > 1:
Ejemplo n.º 3
0
#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
# (of Hubble crossing, sound horizon crossing, etc.) at different time
#

background = M.get_background()  # load background table
print background.viewkeys()
perturbations = M.get_perturbations()
print perturbations.viewkeys()
thermodynamics = M.get_thermodynamics()  # load thermodynamics table
print thermodynamics.viewkeys()
quit()
#
background_tau = background[
    'conf. time [Mpc]']  # read conformal times in background table
background_z = background['z']  # read redshift
background_aH = 2. * math.pi * background['H [1/Mpc]'] / (
    1. + background['z']) / M.h()  # read 2pi * aH in [h/Mpc]
background_ks = 2. * math.pi / background['comov.snd.hrz.'] / M.h(
)  # read 2pi/(comoving sound horizon) in [h/Mpc]
background_rho_m_over_r = (background['(.)rho_b'] +
                           background['(.)rho_cdm']) / (
                               background['(.)rho_g'] + background['(.)rho_ur']
Ejemplo n.º 4
0
        'nonlinear_verbose': 1,
        'output_verbose': 1,
        'transfer_verbose': 1,
        'tau_reio': 0.079,
        'headers': 'yes',
        'modes': 's',
        'k_output_values': 0.0001 + i * 0.0005,
        'lensing_verbose': 1,
        'radiation_streaming_trigger_tau_over_tau_k': 10000
    }
    cosmo = Class()
    cosmo.set(params)
    cosmo.compute()
    #	kval = 0.0001 + i/(10000*1.0)
    kval = 0.0001 + i * 0.0005
    data = cosmo.get_perturbations()['scalar']

    print kval

    print data[0]['a']
    print len(data[0]['a'])

    out = np.zeros(shape=(len(data[0]['a']), 4))

    out[:, 0] = kval
    out[:, 1] = 1.0 / data[0]['a'] - 1
    # Here comes conformal time
    #out[:,2] = 3.086e19*np.sqrt(Omega_r + Omega_m*data[0]['a'])/(50*h*Omega_m)
    out[:, 2] = 2 * 3.086e+19 * np.sqrt(Omega_r + Omega_m /
                                        (1 + out[:, 1])) / (100 * h * Omega_m)
    out[:, 3] = -5.0 * (data[0]['pol0_g'] + data[0]['pol2_g']) / (4.0 *
Ejemplo n.º 5
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.º 6
0
                   # Take fixed value for primordial Helium (instead of automatic BBN adjustment)
                   'YHe':0.246,
                   # other options and settings
                   'compute damping scale':'yes', # needed to output the time of damping scale crossing
                   'gauge':'newtonian'}
##############
#
# call CLASS
#
M = Class()
M.set(common_settings)
M.compute()
#
# load perturbations
#
all_k = M.get_perturbations()  # this potentially constains scalars/tensors and all k values
print all_k['scalar'][0].viewkeys()
#
one_k = all_k['scalar'][0]     # this contains only the scalar perturbations for the requested k values
#
tau = one_k['tau [Mpc]']
Theta0 = 0.25*one_k['delta_g']
phi = one_k['phi']
psi = one_k['psi']
theta_b = one_k['theta_b']
a = one_k['a']
# compute related quantitites
R = 3./4.*M.Omega_b()/M.Omega_g()*a    # R = 3/4 * (rho_b/rho_gamma)
zero_point = -(1.+R)*psi               # zero point of oscillations: -(1.+R)*psi
#
# get Theta0 oscillation amplitude (for vertical scale of plot)