Пример #1
0
phi = one_time['phi']
psi = one_time['psi']
theta_b = one_time['t_b']
# compute related quantitites
R = 3. / 4. * M.Omega_b() / M.Omega_g() / (
    1 + z_rec)  # R = 3/4 * (rho_b/rho_gamma) at z_rec
zero_point = -(1. + R) * psi  # zero point of oscillations: -(1.+R)*psi
#
# get Theta0 oscillation amplitude (for vertical scale of plot)
#
Theta0_amp = max(Theta0.max(), -Theta0.min())
#
# use table of background quantitites to find the wavenumbers corresponding to
# Hubble crossing (k = 2 pi a H), sound horizon crossing (k = 2pi / rs)
#
background = M.get_background()  # load background table
#print background.viewkeys()
#
background_tau = background[
    'conf. time [Mpc]']  # read confromal times in background table
background_z = background['z']  # read redshift
background_kh = 2. * math.pi * background['H [1/Mpc]'] / (
    1. + background['z']
) / M.h()  # read kh = 2pi aH = 2pi H/(1+z) converted to [h/Mpc]
background_ks = 2. * math.pi / background['comov.snd.hrz.'] / M.h(
)  # read ks = 2pi/rs converted to [h/Mpc]
#
# define interpolation functions; we want the value of tau when the argument is equal to 2pi
#
kh_at_tau = interp1d(background_tau, background_kh)
ks_at_tau = interp1d(background_tau, background_ks)
Пример #2
0
            '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
                m_axion = 10**cosmo.log10_m_axion()*h*100/_c_
                print "m_axion %f"%(m_axion)
                # k_res_analytical = 0.79*m_axion*Theta_initial[j]*(10**ac[i])
                k_res_analytical = 0.79*m_axion*Theta_initial[j]*(10**ac[i])
                one_time = cosmo.get_transfer(0) # transfer functions at each time tau
                k = one_time['k (h/Mpc)']
                delta_phi_scf = np.abs(one_time['delta_phi_scf']) ##evaluated today
                k_of_delta = interp1d(delta_phi_scf,k)
                background = cosmo.get_background() # load background table
                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)
                phi_enveloppe = Theta_initial[j]*10**cosmo.log10_f_axion()*(2/(10**ac[i]))**(-3.*(1+wn)/2/n_axion) ##evaluated today
                delta_max = np.sqrt(delta_phi_scf*delta_phi_scf*A_s*(k/K_star)**(n_s-1))/(phi_enveloppe)
                print max(delta_max), np.where(delta_max==max(delta_max))
                k_res_numerical = k[np.where(delta_max==max(delta_max))]*h ##evaluated today
                print "k_res analytical %f Mpc-1, k_res numerical %f Mpc-1"%(k_res_analytical,k_res_numerical)
            except CosmoComputationError: # this happens when CLASS fails
                print "bug!"
                k_res_numerical = 0
                k_nl_scf[i][j] = 100 #arbitrary large number: bug
                z_nl_scf[i][j] = 0 #arbitrary large number: bug
                Omega_nl_scf[i][j] = 1e-30 #arbitrary small number
Пример #3
0
from scipy.interpolate import interp1d
import math

common_settings = {# we need to set the output field to something although
                   # the really releveant outpout here will be set with 'k_output_values'
                   'output':'mPk',
                   # value of k we want to polot in [1/Mpc]
                   # LambdaCDM parameters
                   '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 options and settings
                   'compute damping scale':'yes', # needed to output the time of damping scale crossing
                   'gauge':'newtonian'}
M = Class()
M.set(common_settings)
M.compute()

growth = M.get_background()['gr.fac. D'] 
zs = M.get_background()['z']
scalefactor = 1/zs
#plt.semilogx(zs, growth,label = "D(z)")
plt.semilogx(scalefactor, growth,label = "D(a)")
plt.legend()
plt.show()
Пример #4
0
            'adptative_stepsize': 100,
            'scf_evolve_as_fluid': 'no'
        })
        # 2.258053e-02	 1.298650e-01	 9.880137e-01	 2.176655e-09	 6.833666e-02	 1.041246e+00	-3.736778e+00 4.717743e-09	 2.791761e+00

    M.compute()
    #
    # get Cls
    #
    # clM = M.raw_cl(2500
    clM = M.lensed_cl(2500)
    ll = clM['ell'][2:]
    clTT = clM['tt'][2:]
    clTE = clM['te'][2:]
    clEE = clM['ee'][2:]
    bg = M.get_background()
    Omega_scf = bg['(.)Omega_scf']
    H = bg['H [1/Mpc]']
    Da = bg['ang.diam.dist.']
    z = bg['z']
    tau = bg['conf. time [Mpc]']
    tau_interp = interp1d(z, tau)
    tau_0 = tau_interp(0)
    derived = M.get_current_derived_parameters(['z_rec', 'tau_rec'])
    tau_rec = derived['tau_rec']
    for j in range(len(Omega_scf)):
        if Omega_scf[j] > 0.01:
            k = H[j] / (1 + z[j])
            # l.append(k*Da[j])
            l.append(k * (tau_0 - tau_rec))
    print(450. / (tau_0 - tau_rec))
Пример #5
0
# 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
# (of Hubble crossing, sound horizon crossing, etc.) at different time
#
background = M.get_background() # load background table
#print background.viewkeys()
thermodynamics = M.get_thermodynamics() # load thermodynamics table
#print thermodynamics.viewkeys()
#
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']) # read rho_r / rho_m (to find time of equality)
background_rho_l_over_m =    background['(.)rho_lambda']    /(background['(.)rho_b']+background['(.)rho_cdm']) # read rho_m / rho_lambda (to find time of equality)
thermodynamics_tau = thermodynamics['conf. time [Mpc]'] # read confromal times in thermodynamics table
thermodynamics_kd = 2.*math.pi/thermodynamics['r_d']/M.h() # read 2pi(comoving diffusion scale) in [h/Mpc]
#
# define a bunch of interpolation functions based on previous quantities
#
Пример #6
0
class Binning():
    def __init__(self, fname, outdir='./'):
        self._cosmo = Class()
        self._fname = fname
        self._outdir = outdir
        self._set_default_values()

    def _set_full_filenames(self, filesuffixes):
        """
        Return a list with the fullnames of the others, increasing their number
        in case they exist

        Additionally, set the full file names, of self._fparamsname and
        self.fshootname.
        """
        fullfilenames = []
        for suffix in filesuffixes + ['params', 'shooting']:
            fullfilenames.append(
                os.path.join(self._outdir, self._fname + '-' + suffix))

        i = 0

        bools = [True] * len(fullfilenames)

        while 1:
            for n, f in enumerate(fullfilenames):
                bools[n] = os.path.exists(f + '-%s.txt' % i)

            if True not in bools:
                break

            i += 1

        self._fparamsname = fullfilenames[-2] + '-%s.txt' % i
        self._fshootname = fullfilenames[-1] + '-%s.txt' % i

        return [f + '-%s.txt' % i for f in fullfilenames[:-2]]

    def _set_default_values(self):
        """
        Set default values of parameters lists.
        """
        self.params_smg = []
        self.params_2_smg = []
        self.h = []
        self.Omega_cdm = []

        self.gravity_model = []

        self._params = {
            "Omega_Lambda": 0,
            "Omega_fld": 0,
            "Omega_smg": -1,
            'output': 'mPk',  #
            'z_max_pk': 1000
        }  # Added for relative errors in f.

        self._computed = False
        self._path = []
        self._binType = ''

    def set_Pade(self,
                 n_num,
                 m_den,
                 xvar='a',
                 xReverse=False,
                 accuracy=1e-3,
                 increase=False,
                 maxfev=0):
        """
        Set what Pade polynomial orders, temporal variable and its ordering use.
        """
        self.reset()
        self._PadeOrder = [n_num, m_den]
        self._Pade_xvar = xvar
        self._Pade_xReverse = xReverse
        self._Pade_maxfev = maxfev
        self._Pade_increase = increase
        self._Pade_accuracy = accuracy
        self._binType = 'Pade'

    def set_fit(self,
                fit_function,
                n_coeffs,
                variable_to_fit,
                fit_function_label='',
                z_max_pk=1000,
                bounds=(-np.inf, np.inf),
                p0=[],
                xvar='ln(1+z)'):
        """
        Set the fitting_function and the number of coefficients.

        variable_to_fit must be one of 'F'or 'w'.

        fit_function_label will be written in the header of fit files.
        """
        self.reset()
        self._fit_function = fit_function
        self._n_coeffs = n_coeffs
        self._list_variables_to_fit = ['F', 'w', 'logRho', 'logX', 'X']
        if variable_to_fit in self._list_variables_to_fit:
            self._variable_to_fit = variable_to_fit
        else:
            raise ValueError('variable_to_fit must be one of {}'.format(
                self._list_variables_to_fit))

        self._fit_function_label = fit_function_label
        self._binType = 'fit'
        self._fFitname = self._set_full_filenames(['fit-' + variable_to_fit
                                                   ])[0]
        self._params.update({'z_max_pk': z_max_pk})
        self._fit_bounds = bounds
        self._p0 = p0
        list_fit_xvar = ['ln(1+z)', 'lna', 'a', '(1-a)']
        if xvar in list_fit_xvar:
            self._fit_xvar = xvar
        else:
            raise ValueError('xvar must be one of {}'.format(list_fit_xvar))

    def set_bins(self, zbins, abins):
        """
        Set what bins to use and reset to avoid confusions.
        """
        self.reset()
        self._zbins = zbins
        self._abins = abins
        self._binType = 'bins'
        self._fwzname, self._fwaname = self._set_full_filenames(
            ['wz-bins', 'wa-bins'])

    def _read_from_file(self, path):
        """
        Return params for class from files used in quintessence Marsh.
        """
        with open(path) as f:
            f.readline()
            header = f.readline().split()[3:]  # Remove '#', 'w0', and 'wa'

        columns = np.loadtxt(path, unpack=True)[2:]  # Remove columns w0, wa

        for index_h, head in enumerate(header):
            if head[-1] == 'h':
                break

        self.params_smg = zip(*columns[:index_h])
        self.params_2_smg = [
            list(row[~np.isnan(row)])
            for row in np.array(zip(*columns[index_h + 2:]))
        ]
        self.h = columns[index_h]
        self.Omega_cdm = columns[index_h + 1]

        self.gravity_model = os.path.basename(path).split('-')[0]

    def _params_from_row(self, row):
        """
        Set parameters.
        """
        params = self._params
        params.update({
            'parameters_smg': str(self.params_smg[row]).strip('[()]'),
            'h': self.h[row],
            'Omega_cdm': self.Omega_cdm[row],
            'gravity_model': self.gravity_model
        })

        if len(self.params_2_smg):
            params.update({
                'parameters_2_smg':
                str(self.params_2_smg[row]).strip('[()]')
            })

        return params

    def compute_bins(self, params):
        """
        Compute the w_i bins for the model with params.
        """
        wzbins = np.empty(len(self._zbins))
        wabins = np.empty(len(self._abins))
        self._params = params
        self._cosmo.set(params)
        try:
            self._cosmo.compute()
            for n, z in enumerate(self._zbins):
                wzbins[n] = self._cosmo.w_smg(z)
            for n, a in enumerate(self._abins):
                wabins[n] = self._cosmo.w_smg(1. / a - 1.)
            shoot = self._cosmo.get_current_derived_parameters(
                ['tuning_parameter'])['tuning_parameter']
        except Exception as e:
            self._cosmo.struct_cleanup()
            self._cosmo.empty()
            raise e

        self._cosmo.struct_cleanup()
        self._cosmo.empty()

        return wzbins, wabins, shoot

    def _compute_common_init(self, params):
        """
        Common first steps for compute methods
        """
        self._params.update(params)
        self._cosmo.set(self._params)

        try:
            self._cosmo.compute()
            b = self._cosmo.get_background()
            shoot = self._cosmo.get_current_derived_parameters(
                ['tuning_parameter'])['tuning_parameter']
        except Exception as e:
            self._cosmo.struct_cleanup()
            self._cosmo.empty()
            raise e

        return b, shoot

    def _fit(self, X, Y):
        """
        Fits self._fit_function to X, Y, with self._n_coeffs.
        """
        return wicm.fit(self._fit_function,
                        X,
                        Y,
                        self._n_coeffs,
                        bounds=self._fit_bounds,
                        p0=self._p0)

    def _get_fit_xvar_and_log1Plusz(self, z):
        """
        Return the X array to fit and log(1+z)
        """
        if self._fit_xvar == 'ln(1+z)':
            X = np.log(z + 1)
            lna = X
        elif self._fit_xvar == 'lna':
            X = -np.log(z + 1)
            lna = -X
        elif self._fit_xvar == 'a':
            X = 1. / (1 + z)
            lna = np.log(z + 1)
        elif self._fit_xvar == '(1-a)':
            X = (z / (1 + z))
            lna = np.log(z + 1)

        return X, lna

    def compute_fit_coefficients_for_F(self, params):
        """
        Returns the coefficients of the polynomial fit of f(a) = \int w and the
        maximum and minimum residual in absolute value.
        """
        b, shoot = self._compute_common_init(params)

        # Compute the exact \int dlna a
        ###############################
        z, w = b['z'], b['w_smg']

        Fint = []
        lna = -np.log(1 + z)[::-1]
        for i in lna:
            Fint.append(integrate.trapz(w[::-1][lna >= i], lna[lna >= i]))
        Fint = np.array(Fint)

        #####

        zlim = self._params['z_max_pk']
        # Note that lna is log(1+z). I used this name because is more convenient
        X, lna = self._get_fit_xvar_and_log1Plusz(z[z <= zlim])

        #####################
        zTMP = z[z <= zlim]
        Y1 = Fint[::-1][z < zlim]  # Ordered as in CLASS

        #####################

        # Fit to fit_function
        #####################
        popt1, yfit1 = self._fit(X, Y1)

        # Obtain max. rel. dev. for DA and f.
        #####################

        rhoDE_fit = b['(.)rho_smg'][-1] * np.exp(-3 * yfit1) * (
            1 + zTMP)**3  ###### CHANGE WITH CHANGE OF FITTED THING

        Xw_fit, w_fit = wicm.diff(lna, yfit1)
        w_fit = -interp1d(
            Xw_fit, w_fit, bounds_error=False, fill_value='extrapolate')(lna)

        DA_reldev, f_reldev = self._compute_maximum_relative_error_DA_f(
            rhoDE_fit, w_fit)

        # Free structures
        ###############
        self._cosmo.struct_cleanup()
        self._cosmo.empty()

        return np.concatenate([popt1, [DA_reldev, f_reldev]]), shoot

    def compute_fit_coefficients_for_logX(self, params):
        """
        Returns the coefficients of the polynomial fit of log(rho/rho_0) = -3
        \int dlna (w+1) and the maximum and minimum residual in absolute value.
        """
        b, shoot = self._compute_common_init(params)

        # Compute the exact -3 \int dlna (w + 1)
        ###############################
        z = b['z']

        logX = np.log(b['(.)rho_smg'] / b['(.)rho_smg'][-1])

        #####

        zlim = self._params['z_max_pk']
        # Note that lna is log(1+z). I used this name because is more convenient
        X, lna = self._get_fit_xvar_and_log1Plusz(z[z <= zlim])

        #####################
        Y1 = logX[z <= zlim]

        #####################

        # Fit to fit_function
        #####################
        popt1, yfit1 = self._fit(X, Y1)

        # Obtain max. rel. dev. for DA and f.
        #####################

        rhoDE_fit = b['(.)rho_smg'][-1] * np.exp(
            yfit1)  ###### CHANGE WITH CHANGE OF FITTED THING

        Xw_fit, ThreewPlus1 = wicm.diff(lna, yfit1)
        w_fit = ThreewPlus1 / 3. - 1  # The minus sign is taken into account by the CLASS ordering.
        w_fit = interp1d(Xw_fit,
                         w_fit,
                         bounds_error=False,
                         fill_value='extrapolate')(lna)

        DA_reldev, f_reldev = self._compute_maximum_relative_error_DA_f(
            rhoDE_fit, w_fit)

        # Free structures
        ###############
        self._cosmo.struct_cleanup()
        self._cosmo.empty()

        return np.concatenate([popt1, [DA_reldev, f_reldev]]), shoot

    def compute_fit_coefficients_for_X(self, params):
        """
        Returns the coefficients of the polynomial fit of rho/rho_0 = exp[-3
        \int dlna (w+1)] and the maximum and minimum residual in absolute value.
        """
        b, shoot = self._compute_common_init(params)

        # Compute the exact -3 \int dlna (w + 1)
        ###############################
        z = b['z']

        Y = b['(.)rho_smg'] / b['(.)rho_smg'][-1]

        #####

        zlim = self._params['z_max_pk']
        # Note that lna is log(1+z). I used this name because is more convenient
        X, lna = self._get_fit_xvar_and_log1Plusz(z[z <= zlim])

        #####################
        Y1 = Y[z <= zlim]

        #####################

        # Fit to fit_function
        #####################
        popt1, yfit1 = self._fit(X, Y1)

        # Obtain max. rel. dev. for DA and f.
        #####################

        rhoDE_fit = b['(.)rho_smg'][
            -1] * yfit1  ###### CHANGE WITH CHANGE OF FITTED THING

        Xw_fit, diff = wicm.diff(lna, yfit1)
        diff = interp1d(Xw_fit,
                        diff,
                        bounds_error=False,
                        fill_value='extrapolate')(lna)
        ThreewPlus1 = diff / yfit1
        w_fit = ThreewPlus1 / 3. - 1  # The minus sign is taken into account by the CLASS ordering.

        DA_reldev, f_reldev = self._compute_maximum_relative_error_DA_f(
            rhoDE_fit, w_fit)

        # Free structures
        ###############
        self._cosmo.struct_cleanup()
        self._cosmo.empty()

        return np.concatenate([popt1, [DA_reldev, f_reldev]]), shoot

    def compute_fit_coefficients_for_logRho(self, params):
        """
        Returns the coefficients of the fit of ln(rho_de) and the maximum and
        minimum residual in absolute value.
        """
        b, shoot = self._compute_common_init(params)

        # Compute the exact log(rho)
        ###############################
        z = b['z']

        logX = np.log(b['(.)rho_smg'])

        #####

        zlim = self._params['z_max_pk']
        # Note that lna is log(1+z). I used this name because is more convenient
        X, lna = self._get_fit_xvar_and_log1Plusz(z[z <= zlim])

        #####################
        Y1 = logX[z <= zlim]

        #####################

        # Fit to fit_function
        #####################

        popt1, yfit1 = self._fit(X, Y1)

        # Obtain max. rel. dev. for DA and f.
        #####################

        rhoDE_fit = np.exp(yfit1)  ###### CHANGE WITH CHANGE OF FITTED THING

        Xw_fit, ThreewPlus1 = wicm.diff(lna, yfit1 - yfit1[-1])
        w_fit = ThreewPlus1 / 3. - 1  # The minus sign is taken into account by the CLASS ordering.
        w_fit = interp1d(Xw_fit,
                         w_fit,
                         bounds_error=False,
                         fill_value='extrapolate')(lna)

        DA_reldev, f_reldev = self._compute_maximum_relative_error_DA_f(
            rhoDE_fit, w_fit)

        # Free structures
        ###############
        self._cosmo.struct_cleanup()
        self._cosmo.empty()

        return np.concatenate([popt1, [DA_reldev, f_reldev]]), shoot

    def compute_fit_coefficients_for_w(self, params):
        """
        Returns the coefficients of the polynomial fit of f(a) = \int w and the
        maximum and minimum residual in absolute value.
        """
        b, shoot = self._compute_common_init(params)

        # Compute the exact \int dlna a
        ###############################
        z, w = b['z'], b['w_smg']

        zlim = self._params['z_max_pk']
        # Note that lna is log(1+z). I used this name because is more convenient
        X, lna = self._get_fit_xvar_and_log1Plusz(z[z <= zlim])

        #####################
        zTMP = z[z <= zlim]
        Y1 = w[z <= zlim]

        # Fit to fit_function
        #####################
        popt1, yfit1 = self._fit(X, Y1)

        # Obtain max. rel. dev. for DA and f.
        #####################
        Fint = []
        lna = -np.log(1 + zTMP)[::-1]
        for i in lna:
            Fint.append(integrate.trapz(yfit1[::-1][lna >= i], lna[lna >= i]))
        Fint = np.array(Fint[::-1])

        rhoDE_fit = b['(.)rho_smg'][-1] * np.exp(
            -3 * Fint) * (1 + zTMP)**3  # CHANGE WITH CHANGE OF FITTED THING

        # TODO: needed?
        # Xw_fit, w_fit = X, yfit1
        # w_fit = interp1d(Xw_fit, w_fit, bounds_error=False, fill_value='extrapolate')(X)
        w_fit = yfit1

        DA_reldev, f_reldev = self._compute_maximum_relative_error_DA_f(
            rhoDE_fit, w_fit)

        # Free structures
        ###############
        self._cosmo.struct_cleanup()
        self._cosmo.empty()

        return np.concatenate([popt1, [DA_reldev, f_reldev]]), shoot

    def _compute_maximum_relative_error_DA_f(self, rhoDE_fit, w_fit):
        """
        Return the relative error for the diameter angular distance and the
        growth factor, f.

        rhoDE_fit = array
        wfit = interp1d(w)
        """

        b = self._cosmo.get_background()

        # Compute the exact growth rate
        #####################
        z_max_pk = self._params['z_max_pk']
        zlim = z_max_pk
        z, w = b['z'], b['w_smg']
        zTMP = z[z <= zlim]
        rhoM = (b['(.)rho_b'] + b['(.)rho_cdm'])
        rhoR = (b['(.)rho_g'] + b['(.)rho_ur'])
        DA = b['ang.diam.dist.']

        OmegaDEwF_exact = interp1d(z[z <= z_max_pk],
                                   (b['(.)rho_smg'] / b['(.)rho_crit'] *
                                    w)[z <= z_max_pk])
        OmegaMF = interp1d(z[z <= z_max_pk],
                           (rhoM / b['(.)rho_crit'])[z <= z_max_pk])

        time_boundaries = [z[z <= z_max_pk][0], z[z <= z_max_pk][-1]]

        # Use LSODA integrator as some solutions were wrong with RK45 and OK
        # with this.
        f = integrate.solve_ivp(
            cosmo_extra.fprime(OmegaDEwF_exact, OmegaMF),
            time_boundaries,
            [cosmo_extra.growthrate_at_z(self._cosmo, z_max_pk)],
            method='LSODA',
            dense_output=True)

        # Compute D_A for fitted model
        ################
        H_fit = np.sqrt(rhoM[z <= zlim] + rhoR[z <= zlim] + rhoDE_fit)

        DA_fit = cosmo_extra.angular_distance(z[z <= zlim],
                                              H_fit[zTMP <= zlim])

        # Compute the growth rate for fitted model
        ###############

        OmegaMF_fit = interp1d(
            zTMP, 1 - rhoDE_fit / H_fit**2 - rhoR[z <= zlim] /
            H_fit**2)  ####### THIS FITS OBSERVABLES CORRECTLY
        # OmegaMF_fit = interp1d(zTMP, rhoM[z<=zlim]/H_fit**2)      ####### THIS FITS OBSERVABLES CORRECTLY
        OmegaDEwF_fit = interp1d(zTMP, rhoDE_fit / H_fit**2 * w_fit)

        f_fit = integrate.solve_ivp(
            cosmo_extra.fprime(OmegaDEwF_fit,
                               OmegaMF_fit), [zTMP[0], zTMP[-1]],
            [cosmo_extra.growthrate_at_z(self._cosmo, zTMP[0])],
            method='LSODA',
            dense_output=True)

        # Obtain rel. deviations.
        ################

        # Remove close to 0 points as rel.dev diverges. z = 0.05 is the lowest
        # redshift observed and is done in BOSS survey. arXiv: 1308.4164
        # DA_reldev = max(np.abs(DA_fit[zTMP>=0.04]/DA[ (z>=0.04) & (z<=zlim)] - 1))
        DA_reldev = max(np.abs(DA_fit / DA[z <= zlim] - 1))
        f_reldev = max(np.abs(f_fit.sol(zTMP)[0] / f.sol(zTMP)[0] - 1))

        return DA_reldev, f_reldev

    def compute_Pade_coefficients(self, params):
        """
        Returns the Pade coefficients for w computed from params and the maximum
        and minimum residual in absolute value.
        """
        self._params = params
        self._cosmo.set(params)

        try:
            self._cosmo.compute()
            b = self._cosmo.get_background()
            shoot = self._cosmo.get_current_derived_parameters(
                ['tuning_parameter'])['tuning_parameter']
        except Exception as e:
            self._cosmo.struct_cleanup()
            self._cosmo.empty()
            raise e

        self._cosmo.struct_cleanup()
        self._cosmo.empty()

        xDict = {
            'z': b['z'],
            'z+1': b['z'] + 1,
            'a': 1. / (b['z'] + 1),
            'log(a)': -np.log(b['z'] + 1),
            'log(z+1)': np.log(b['z'] + 1)
        }

        X = xDict[self._Pade_xvar]
        w = b['w_smg']

        if self._Pade_xReverse:
            X = X[::-1]
            w = w[::-1]

        PadeOrder = np.array(self._PadeOrder)

        if not self._Pade_increase:
            reduceOrder = [[0, 0], [1, 0], [0, 1], [2, 0], [2, 1], [3, 1]]
            orderList = PadeOrder - reduceOrder

        else:
            orderList = [[1, 1], [2, 0], [3, 0], [2, 1], [2, 2], [3,
                                                                  1], [4, 0],
                         [2, 3], [3, 2], [4, 1], [5, 0], [3, 3], [4,
                                                                  2], [5, 1],
                         [3, 4], [4, 3], [5, 2], [3, 5], [4, 4], [5, 3],
                         [4, 5], [5, 4], [5, 5]]

        r = np.array([np.inf])
        for order in orderList:
            # Increase order of Pade up to [5/5].
            try:
                padeCoefficientsTMP, padeFitTMP = fit_pade(
                    X, w, *order, maxfev=self._Pade_maxfev)
                rTMP = np.abs(padeFitTMP / w - 1.)
                if self._Pade_increase and (np.max(rTMP) >
                                            self._Pade_accuracy):
                    if np.max(rTMP) < np.max(r):
                        padeCoefficients = padeCoefficientsTMP
                        r = rTMP
                    continue
                else:
                    padeCoefficients = padeCoefficientsTMP
                    r = rTMP
                    break
            except Exception as e:
                if (order == orderList[-1]) and (len(r) == 1):
                    raise e

                continue

        zeros = (PadeOrder - order)

        numCoefficients = np.append(padeCoefficients[:order[0] + 1],
                                    [0.] * zeros[0])
        denCoefficients = np.append(padeCoefficients[order[0] + 1:],
                                    [0.] * zeros[1])
        padeCoefficients = np.concatenate([numCoefficients, denCoefficients])

        return np.concatenate([padeCoefficients, [np.min(r),
                                                  np.max(r)]]), shoot

    def compute_bins_from_params(self, params_func, number_of_rows):
        """
        Compute the w_i bins for the models given by the function
        params_func iterated #iterations.
        """
        self._create_output_files()

        wzbins = []
        wabins = []
        params = []
        shoot = []

        for row in range(number_of_rows):
            sys.stdout.write("{}/{}\n".format(row + 1, number_of_rows))
            params_tmp = params_func().copy()

            try:
                wzbins_tmp, wabins_tmp, shoot_tmp = self.compute_bins(
                    params_tmp)
                wzbins.append(wzbins_tmp)
                wabins.append(wabins_tmp)
                params.append(params_tmp)
                shoot.append(shoot_tmp)
                # Easily generalizable. It could be inputted a list with the
                # desired derived parameters and store the whole dictionary.
            except Exception as e:
                sys.stderr.write(str(self._params) + '\n')
                sys.stderr.write(str(e))
                sys.stderr.write('\n')
                continue

            if len(wzbins) == 5:
                self._save_computed(params, shoot, [wzbins, wabins])

                params = []
                wzbins = []
                wabins = []
                shoot = []

        self._save_computed(params, shoot, [wzbins, wabins])

    def compute_Pade_from_params(self, params_func, number_of_rows):
        """
        Compute the w_i bins for the models given by the function
        params_func iterated #iterations.
        """
        self._create_output_files()

        wbins = []
        params = []
        shoot = []

        for row in range(number_of_rows):
            sys.stdout.write("{}/{}\n".format(row + 1, number_of_rows))
            params_tmp = params_func().copy()

            try:
                wbins_tmp, shoot_tmp = self.compute_Pade_coefficients(
                    params_tmp)
                wbins.append(wbins_tmp)
                params.append(params_tmp)
                shoot.append(shoot_tmp)
                # Easily generalizable. It could be inputted a list with the
                # desired derived parameters and store the whole dictionary.
            except Exception as e:
                sys.stderr.write(str(self._params) + '\n')
                sys.stderr.write(str(e))
                sys.stderr.write('\n')
                continue

            if len(wbins) == 5:
                self._save_computed(params, shoot, wbins)

                params = []
                wbins = []
                shoot = []

        self._save_computed(params, shoot, wbins)

    def compute_fit_from_params(self, params_func, number_of_rows):
        """
        Compute the fit for the models given by the function
        params_func iterated #iterations.

        The variable to fit is chosen in self.set_fit
        """
        # TODO: If this grows, consider creating a separate method
        if self._variable_to_fit == 'F':
            fit_variable_function = self.compute_fit_coefficients_for_F
        elif self._variable_to_fit == 'w':
            fit_variable_function = self.compute_fit_coefficients_for_w
        elif self._variable_to_fit == 'logRho':
            fit_variable_function = self.compute_fit_coefficients_for_logRho
        elif self._variable_to_fit == 'logX':
            fit_variable_function = self.compute_fit_coefficients_for_logX
        elif self._variable_to_fit == 'X':
            fit_variable_function = self.compute_fit_coefficients_for_X

        self._create_output_files()

        coeffs = []
        params = []
        shoot = []

        for row in range(number_of_rows):
            sys.stdout.write("{}/{}\n".format(row + 1, number_of_rows))
            # params_tmp = params_func().copy()

            try:
                coeffs_tmp, shoot_tmp = fit_variable_function(params_func())
                coeffs.append(coeffs_tmp)
                params.append(self._params.copy())
                shoot.append(shoot_tmp)
                # Easily generalizable. It could be inputted a list with the
                # desired derived parameters and store the whole dictionary.
            except Exception as e:
                sys.stderr.write(str(self._params) + '\n')
                sys.stderr.write(str(e))
                sys.stderr.write('\n')
                continue

            if len(coeffs) == 5:
                self._save_computed(params, shoot, coeffs)

                params = []
                coeffs = []
                shoot = []

        self._save_computed(params, shoot, coeffs)

    def compute_bins_from_file(self, path):
        """
        Compute the w_i bins for the models given in path.
        """
        if self._computed is True:
            print(
                "Bins already computed. Use reset if you want to compute it again"
            )
            return

        self._path = path

        self._read_from_file(path)

        def params_gen(length):
            row = 0
            while row < length:
                yield self._params_from_row(row)
                row += 1

        params = params_gen(len(self.params_smg))

        self.compute_bins_from_params(params.next, len(self.params_smg))

    def _create_output_files(self):
        """
        Initialize the output files.
        """
        # TODO: Add check if files exist
        with open(self._fparamsname, 'a') as f:
            f.write('# ' + "Dictionary of params to use with cosmo.set()" +
                    '\n')

        with open(self._fshootname, 'a') as f:
            f.write('# ' + "Shooting variable value" + '\n')

        if self._binType == 'bins':
            with open(self._fwzname, 'a') as f:
                f.write('# ' + "Bins on redshift" + '\n')
                f.write('# ' + str(self._zbins).strip('[]').replace('\n', '') +
                        '\n')

            with open(self._fwaname, 'a') as f:
                f.write('# ' + "Bins on scale factor" + '\n')
                f.write('# ' + str(self._abins).strip('[]').replace('\n', '') +
                        '\n')
        elif self._binType == 'Pade':
            with open(self._fPadename, 'a') as f:
                f.write('# ' + "Pade fit for temporal variable {} \n".format(
                    self._Pade_xvar))
                coeff_header_num = [
                    'num_{}'.format(n) for n in range(self._PadeOrder[0] + 1)
                ]
                coeff_header_den = [
                    'den_{}'.format(n + 1) for n in range(self._PadeOrder[1])
                ]
                res_header = ['min(residual)', 'max(residual)']
                f.write('# ' + ' '.join(coeff_header_num + coeff_header_den +
                                        res_header) + '\n')
        elif self._binType == 'fit':
            with open(self._fFitname, 'a') as f:
                f.write('# ' +
                        "{} fit for temporal variable {} of {}\n".format(
                            self._fit_function_label, self._fit_xvar,
                            self._variable_to_fit))
                coeff_header_num = [
                    'c_{}'.format(n) for n in range(self._n_coeffs)
                ]
                res_header = ['max(rel.dev. D_A)', 'max(rel.dev. f)']
                f.write('# ' + ' '.join(coeff_header_num + res_header) + '\n')

    def _save_computed(self, params, shoot, wbins):
        """
        Save stored iterations in file.
        """
        with open(self._fparamsname, 'a') as f:
            for i in params:
                f.write(str(i) + '\n')

        with open(self._fshootname, 'a') as f:
            np.savetxt(f, shoot)

        if self._binType == 'bins':
            wzbins, wabins = wbins
            with open(self._fwzname, 'a') as f:
                np.savetxt(f, wzbins)

            with open(self._fwaname, 'a') as f:
                np.savetxt(f, wabins)
        elif self._binType == 'Pade':
            with open(self._fPadename, 'a') as f:
                np.savetxt(f, wbins)
        elif self._binType == 'fit':
            with open(self._fFitname, 'a') as f:
                np.savetxt(f, wbins)

    def reset(self):
        """
        Reset class
        """
        self._cosmo.struct_cleanup()
        self._cosmo.empty()
        self._set_default_values()
Пример #7
0
#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']

# In[ ]:

#Get background quantities and recover their names:
baLCDM = LCDM.get_background()
baCDM = CDM.get_background()
baCDM.viewkeys()

# In[ ]:

#Get H_0 in order to plot the distances in this unit
fLCDM = LCDM.Hubble(0)
fCDM = CDM.Hubble(0)

# In[ ]:

namelist = ['lum. dist.', 'comov. dist.', 'ang.diam.dist.']
colours = ['b', 'g', 'r']
for name in namelist:
    idx = namelist.index(name)
Пример #8
0
#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']


# In[ ]:

#Get background quantities and recover their names:
baLCDM = LCDM.get_background()
baCDM = CDM.get_background()
baCDM.viewkeys()


# In[ ]:

#Get H_0 in order to plot the distances in this unit
fLCDM = LCDM.Hubble(0)
fCDM = CDM.Hubble(0)


# In[ ]:

namelist = ['lum. dist.','comov. dist.','ang.diam.dist.']
colours = ['b','g','r']
Пример #9
0
lcdm = Class()
lcdm.set({
        'h': df["H0*"].values[i]/100.0,
        'omega_b': df.omegabh2.values[i],
        'omega_cdm': df.omegach2.values[i],
        'Omega_Lambda': 0.,
        'w0_fld': -1.0,
        'wa_fld': 0.0,
        'background_verbose':1,
        'input_verbose':1,
        'gauge':'Newtonian',
})

lcdm.compute()

b = lcdm.get_background()
x = b["comov. dist"]
z = b["xz"]
Chi = int.interpd1(z,x)
Z_s = 0.8
Z = 0.4
Chi_s = Chi(Z_s)
Chi_z = Chi(Z)

Omega_m = np.mean(df["omegach2"].values)
H0 = np.mean(df["H0"].values)
sigma8 = np.mean(df["sigma8*"].values)

for x in range(10000):
    a[i] = random.uniform(0.5,1.6,size=5)
 
Пример #10
0
#Perform rescaling if necessary
D_0 = cosmo.scale_independent_growth_factor(0)
D_f = cosmo.scale_independent_growth_factor(z_f)
D_lin = cosmo.scale_independent_growth_factor(z_lin)
print("D_0: ", D_0)
print("D_f: ", D_f)
print("D_lin: ", D_lin)

#MeshPT needs a z=0 power spectrum, so one can rescale a power spectrum to z=0
#if a different input redshift is desired
if (not z_lin == 0):
    print("Rescaling the linear theory power spectrum")
    Pvec *= (D_0 / D_lin)**2

#Get background quantities from CLASS (reverse the order of the arrays)
background = cosmo.get_background()
bg_t = background['proper time [Gyr]'][::-1]
bg_H = background['H [1/Mpc]'][::-1]
bg_D = background['gr.fac. D'][::-1]
bg_f = background['gr.fac. f'][::-1]
bg_z = background['z'][::-1]
bg_a = 1. / (1 + bg_z)
bg_rho = background['(.)rho_tot'][::-1]
bg_p = background['(.)p_tot'][::-1]

#Size of arrays of background quantities
nz = 1000
zmax = max(1000, z_f * 1.05, z_i * 1.05)
zmin = 0

#Curvature parameter
Пример #11
0
def constraints(params, zs):
    cosmo = Class()
    cosmo.set(params)
    cosmo.compute()
    h = cosmo.Hubble(0) * 299792.458
    om0 = cosmo.Omega0_m()
    #print(cosmo.pars)
    zarr2 = cosmo.get_background().get('z')
    hz = cosmo.get_background().get('H [1/Mpc]')
    hf = interpolate.InterpolatedUnivariateSpline(zarr2[-1:0:-1], hz[-1:0:-1])
    chiz = cosmo.get_background().get('comov. dist.')
    chif = interpolate.InterpolatedUnivariateSpline(zarr2[-1:0:-1],
                                                    chiz[-1:0:-1])

    pkz = np.zeros((nk, nz))
    pklz2 = np.zeros((nk, nz))
    dprime = np.zeros((nk, 1))
    zarr = np.linspace(0, zmax, nz)
    karr = np.logspace(-3, np.log10(20), nk)
    rcollarr = np.zeros(nz)
    kcarr = np.zeros(nz)
    delz = 0.01

    for i in np.arange(nz):
        Dz = (cosmo.scale_independent_growth_factor(zarr[i]) /
              cosmo.scale_independent_growth_factor(0))
        sigz = lambda x: Dz * cosmo.sigma(x, zarr[i]) - 1.192182033080519
        if (sigz(1e-5) > 0) & (sigz(10) < 0):
            rcollarr[i] = optimize.brentq(sigz, 1e-5, 10)
        else:
            rcollarr[i] = 0
        for j in np.arange(nk):
            pkz[j, i] = cosmo.pk(karr[j], zarr[i])
    for i in np.arange(nk):
        pklz0 = np.log(cosmo.pk(karr[i], zs - delz) / cosmo.pk(karr[i], 0))
        pklz1 = np.log(cosmo.pk(karr[i], zs + delz) / cosmo.pk(karr[i], 0))
        pklz2[i] = cosmo.pk(karr[i], 0)
        dprime[i] = -hf(zs) * np.sqrt(
            cosmo.pk(karr[i], zs) / pklz2[i, 0]) * (pklz1 - pklz0) / 4 / delz
        #divided by 2 for step size, another for defining D'

    w0 = params.get('w0_fld')
    wa = params.get('wa_fld')
    mt = 5 * np.log10(cosmo.luminosity_distance(zs))
    #mt = 5*np.log10(fanal.dlatz(zs, om0, og0, w0, wa))
    Rc = (2 * 4.302e-9 * Mc / h**2 / om0)**(1 / 3)
    mask = (0 < rcollarr) & (rcollarr < Rc)
    kcarr[mask] = 2 * np.pi / rcollarr[mask]
    mask = (rcollarr >= Rc)
    kcarr[mask] = 2 * np.pi / Rc
    #plt.semilogy(zarr, kcarr)
    pksmooth = pdf.pkint(karr, zarr, pkz, kcarr)

    par2 = {'w0': w0, 'wa': wa, 'Omega_m': om0}
    print(par2)
    #kmin = conv.kmin(zs, chif, hf)*(-3./2.*hf(0)**2*om0)
    kvar = conv.kvar(zs, pksmooth, chif, hf) * (3. / 2. * hf(0)**2 * om0)**2
    #sigln = np.log(1+kvar/np.abs(kmin)**2)
    #L = pdf.convpdf(kmin, sigln, sig, mfid-mt)
    #sigln = np.sqrt(sig**2+(5/np.log(10))**2*kvar)
    #L = pdf.gausspdf(sig, mfid-mt)
    #lnL = mt/sig
    vvar = np.trapz(pklz2[:, 0] * dprime[:, 0]**2,
                    karr) / 6 / np.pi**2 * (1 -
                                            (1 + zs) / hf(zs) / chif(zs))**2
    #var_tot = norm*kvar+sig**2
    lnL = -mt**2 / 2
    print('Sigmasq = {}, {}, Likelihood = {}'.format(kvar, vvar, lnL))
    cosmo.struct_cleanup()
    cosmo.empty()
    return [mt, kvar, vvar]


#[mt, var_tot]
Пример #12
0
class MultiCorr(object):
    """
        This class computes the relativistic 2PCF and power-spectra multipoles
        
        !!! -> Fiducial cosmology must be directly altered in this file! <- !!!
            This makes the code more flexible, so you can compute the 
            multipoles at any redshift and with all the parameters you 
            wish.
        
        OBS: non-Gaussian corrections have not been implemented here yet.
             Once it is functional, this class will depend on halo tools.
        
        No variables are needed to initialize the class  
    
    """

    init = False

    def __init__(self):

        print '[Initializing MultiCorr]: Relativistic 2PCF and power-spectra multipoles\n'

        # Fiducial cosmology
        c = 299792.458
        self.c = c
        h = 0.67556
        self.h = h
        n_s = 0.9619
        self.n_s = n_s
        A_s = 2.215e-9
        self.A_s = A_s
        omega_cdm = 0.12038
        self.omega_cdm = omega_cdm
        omega_b = 0.022032
        self.omega_b = omega_b
        omega_k = 0.0
        self.omega_k = omega_k
        k_pivot = 0.05
        self.k_pivot = k_pivot
        N_ur = 3.046
        self.N_ur = N_ur
        N_ncdm = 0.0
        self.N_ncdm = N_ncdm
        T_cmb = 2.7255
        self.T_cmb = T_cmb
        Omega_m = (omega_cdm + omega_b) / h**2
        self.Omega_m = Omega_m
        w = -1.0
        self.w = w

        print '(Pre-defined cosmology)'
        print 'h:', h
        print 'n_s:', n_s
        print 'A_s:', A_s
        print 'N_ur:', N_ur
        print 'N_ncdm:', N_ncdm
        print 'T_cmb:', T_cmb
        print 'Omega_m:', Omega_m
        print 'w:', w
        print '\n'

        self.kvec = np.logspace(-7., np.log10(500), 1000)
        self.k_ = np.logspace(-3, 2, 2000)

        # Linear power-spectrum
        class_settings = {
            'output': 'mPk',
            'lensing': 'no',
            'h': h,
            'n_s': n_s,
            'A_s': A_s,
            'omega_cdm': omega_cdm,
            'omega_b': omega_b,
            'Omega_k': 0.0,
            'k_pivot': k_pivot,
            'z_max_pk': 10.,
            'N_ur': N_ur,
            'N_ncdm': N_ncdm,
            'T_cmb': T_cmb,
            'P_k_max_1/Mpc': 500
        }
        self.pclass = Class()
        self.pclass.set(class_settings)
        self.pclass.compute()

        # These are the CLASS functions (has 0.5% accuracy wrt to the ones I implement by hand)
        self.bg = self.pclass.get_background()
        self.H = interp1d(self.bg['z'], (c / h) * self.bg['H [1/Mpc]'])
        self.comov = interp1d(self.bg['z'], h * self.bg['comov. dist.'])
        self.fz = interp1d(self.bg['z'], self.bg['gr.fac. f'])

        # Non-linear power-spectrum
        class_settings_nl = {
            'output': 'mPk',
            'lensing': 'no',
            'h': h,
            'n_s': n_s,
            'A_s': A_s,
            'omega_cdm': omega_cdm,
            'omega_b': omega_b,
            'Omega_k': 0.0,
            'k_pivot': k_pivot,
            'z_max_pk': 10.,
            'non linear': 'halofit',
            'N_ur': N_ur,
            'N_ncdm': N_ncdm,
            'T_cmb': T_cmb,
            'P_k_max_1/Mpc': 500
        }

        self.pnlclass = Class()
        self.pnlclass.set(class_settings_nl)
        self.pnlclass.compute()

        print '[MultiCorr Initialized]'
        self.init = True

    ######################################################################################################
    # Useful functions
    def Om(self, z):
        """
            Returns the evolving matter density Omega_m(z)
        """

        self.z = z
        self.H0Hz2 = pow(1 + self.z, 3.0) * self.Omega_m + (1 - self.Omega_m)

        return pow(1 + self.z, 3.0) * self.Omega_m / self.H0Hz2

    ######################################################################################################
    # RSD

    def Doppler(self, z_, be_):
        """
            Computes the doppler assuming the magnification bias s = 0.
        """

        self.z_ = z_
        self.be_ = be_
        self.scale_factor = 1.0 / (1.0 + self.z_)
        self.Hubble = self.H(self.z_)  # (h/Mpc) (Km/s)
        self.R_at_z = self.comov(self.z_)  # (Mpc/h)

        return self.be_ - (1.0 - 1.5 * self.Om(self.z_)) - (
            2.0 / (self.scale_factor * (self.Hubble / self.c) * self.R_at_z))

    def DopplerMag(self, z_, be_, sm_):
        """
            Computes the doppler assuming a non-vanishing magnification bias s != 0.
        """

        self.z_ = z_
        self.be_ = be_
        self.sm_ = sm_
        self.scale_factor = 1.0 / (1.0 + self.z_)
        self.Hubble = self.H(self.z_)  # (h/Mpc) (Km/s)
        self.R_at_z = self.comov(self.z_)  # (Mpc/h)

        return self.be_ - 5 * self.sm_ - (1.0 - 1.5 * self.Om(self.z_)) - (
            1.0 /
            (self.scale_factor *
             (self.Hubble / self.c) * self.R_at_z)) * (2.0 - 5 * self.sm_)

    def c0(self, z_, b_alpha_, b_beta_):
        self.z_ = z_
        self.b_alpha_ = b_alpha_
        self.b_beta_ = b_beta_
        return self.b_alpha_ * self.b_beta_ + (1.0 / 3.0) * self.fz(
            self.z_) * (self.b_alpha_ + self.b_beta_) + (1.0 / 5.0) * pow(
                self.fz(self.z_), 2.0)

    def c1(self, z_, b_alpha_, b_beta_, be_alpha_, be_beta_):

        self.z_ = z_
        self.scale_factor = 1.0 / (1.0 + self.z_)
        self.b_alpha_ = b_alpha_
        self.b_beta_ = b_beta_
        self.be_alpha_ = be_alpha_
        self.be_beta_ = be_beta_
        self.Hubble = self.H(self.z_)  # (h/Mpc) (Km/s)
        self.term1 = self.Doppler(self.z_, self.be_alpha_) * (
            3 * self.fz(self.z_) + 5 * self.b_beta_)
        self.term2 = self.Doppler(self.z_, self.be_beta_) * (
            3 * self.fz(self.z_) + 5 * self.b_alpha_)
        return (self.fz(self.z_) / 5.0) * (self.Hubble /
                                           (self.c * self.k_)) * (self.term1 -
                                                                  self.term2)

    def c1_Mag(self, z_, b_alpha_, b_beta_, be_alpha_, be_beta_, s_alpha,
               s_beta):

        self.z_ = z_
        self.scale_factor = 1.0 / (1.0 + self.z_)
        self.b_alpha_ = b_alpha_
        self.b_beta_ = b_beta_
        self.be_alpha_ = be_alpha_
        self.be_beta_ = be_beta_
        self.s_alpha = s_alpha
        self.s_beta = s_beta
        self.Hubble = self.H(self.z_)  # (h/Mpc) (Km/s)
        self.term1 = self.DopplerMag(self.z_, self.be_alpha_, self.s_alpha) * (
            3 * self.fz(self.z_) + 5 * self.b_beta_)
        self.term2 = self.DopplerMag(self.z_, self.be_beta_, self.s_beta) * (
            3 * self.fz(self.z_) + 5 * self.b_alpha_)

        return (self.fz(self.z_) / 5.0) * (self.scale_factor * self.Hubble /
                                           (self.c * self.k_)) * (self.term1 -
                                                                  self.term2)

    def c2(self, z_, b_alpha_, b_beta_):

        self.z_ = z_
        self.b_alpha_ = b_alpha_
        self.b_beta_ = b_beta_
        return (2.0 / 3.0) * self.fz(
            self.z_) * (self.b_alpha_ + self.b_beta_) + (4.0 / 7.0) * pow(
                self.fz(self.z_), 2.0)

    def c3(self, z_, b_alpha_, b_beta_, be_alpha_, be_beta_):

        self.z_ = z_
        self.scale_factor = 1.0 / (1.0 + self.z_)
        self.b_alpha_ = b_alpha_
        self.b_beta_ = b_beta_
        self.be_alpha_ = be_alpha_
        self.be_beta_ = be_beta_
        self.Hubble = self.H(self.z_)  # (h/Mpc) (Km/s)
        self.term1 = self.Doppler(self.z_, self.be_alpha_)
        self.term2 = self.Doppler(self.z_, self.be_beta_)
        return (2.0 / 5.0) * pow(self.fz(
            self.z_), 2.0) * (self.scale_factor * self.Hubble /
                              (self.c * self.k_)) * (self.term1 - self.term2)

    def c4(self, z_):

        self.z_ = z_
        return (8.0 / 35.0) * pow(self.fz(self.z_), 2.0)

    ######################################################################################################
    # Plane-parallel power-spectrum

    ## First order in $\mathcal{H}/k$
    def P0_pp(self, z_, b_alpha_, b_beta_, linear):
        self.z_ = z_
        self.b_alpha_ = b_alpha_
        self.b_beta_ = b_beta_
        self.linear = linear

        if linear == 'linear' or linear == True:
            self.Pk = interp1d(
                self.kvec / self.h,
                np.array([self.pclass.pk(_k, self.z_)
                          for _k in self.kvec]) * (self.h**3.))
        else:
            self.Pk = interp1d(
                np.logspace(-5, 2, 1000) / self.h,
                np.array([
                    self.pnlclass.pk(_k, self.z_)
                    for _k in np.logspace(-5, 2, 1000)
                ]) * (self.h**3.))
        return self.c0(self.z_, self.b_alpha_, self.b_beta_) * self.Pk(k_)

    def P1_pp(self, z_, b_alpha_, b_beta_, be_alpha_, be_beta_, linear):
        self.z_ = z_
        self.b_alpha_ = b_alpha_
        self.b_beta_ = b_beta_
        self.be_alpha_ = be_alpha_
        self.be_beta_ = be_beta_
        self.linear = linear
        if linear == 'linear' or linear == True:
            self.Pk = interp1d(
                self.kvec / self.h,
                np.array([self.pclass.pk(_k, self.z_)
                          for _k in self.kvec]) * (self.h**3.))
        else:
            self.Pk = interp1d(
                np.logspace(-5, 2, 1000) / self.h,
                np.array([
                    self.pnlclass.pk(_k, self.z_)
                    for _k in np.logspace(-5, 2, 1000)
                ]) * (self.h**3.))
        return self.c1(self.z_, self.b_alpha_, self.b_beta_, self.be_alpha_,
                       self.be_beta_) * self.Pk(self.k_)

    def P1Mag_pp(self, z_, b_alpha_, b_beta_, be_alpha_, be_beta_, s_alpha,
                 s_beta, linear):
        self.z_ = z_
        self.b_alpha_ = b_alpha_
        self.b_beta_ = b_beta_
        self.be_alpha_ = be_alpha_
        self.be_beta_ = be_beta_
        self.s_alpha = s_alpha
        self.s_beta = s_beta
        self.linear = linear

        if linear == 'linear' or linear == True:
            self.Pk = interp1d(
                self.kvec / self.h,
                np.array([self.pclass.pk(_k, self.z_)
                          for _k in self.kvec]) * (self.h**3.))
        else:
            self.Pk = interp1d(
                np.logspace(-5, 2, 1000) / self.h,
                np.array([
                    self.pnlclass.pk(_k, self.z_)
                    for _k in np.logspace(-5, 2, 1000)
                ]) * (self.h**3.))
        return self.c1_Mag(self.z_, self.b_alpha_, self.b_beta_,
                           self.be_alpha_, self.be_beta_, self.s_alpha,
                           self.s_beta) * self.Pk(self.k_)

    def P2_pp(self, z_, b_alpha_, b_beta_, linear):
        self.z_ = z_
        self.b_alpha_ = b_alpha_
        self.b_beta_ = b_beta_
        self.linear = linear

        if linear == 'linear' or linear == True:
            self.Pk = interp1d(
                self.kvec / self.h,
                np.array([self.pclass.pk(_k, self.z_)
                          for _k in self.kvec]) * (self.h**3.))
        else:
            self.Pk = interp1d(
                np.logspace(-5, 2, 1000) / self.h,
                np.array([
                    self.pnlclass.pk(_k, self.z_)
                    for _k in np.logspace(-5, 2, 1000)
                ]) * (self.h**3.))
        return self.c2(self.z_, self.b_alpha_, self.b_beta_) * self.Pk(self.k_)

    def P3_pp(self, z_, b_alpha_, b_beta_, be_alpha_, be_beta_, linear):
        self.z_ = z_
        self.b_alpha_ = b_alpha_
        self.b_beta_ = b_beta_
        self.be_alpha_ = be_alpha_
        self.be_beta_ = be_beta_
        self.linear = linear

        if linear == 'linear' or linear == True:
            self.Pk = interp1d(
                self.kvec / self.h,
                np.array([self.pclass.pk(_k, self.z_)
                          for _k in self.kvec]) * (self.h**3.))
        else:
            self.Pk = interp1d(
                np.logspace(-5, 2, 1000) / self.h,
                np.array([
                    self.pnlclass.pk(_k, self.z_)
                    for _k in np.logspace(-5, 2, 1000)
                ]) * (self.h**3.))
        return self.c3(self.k_, self.z_, self.b_alpha_, self.b_beta_,
                       self.be_alpha_, self.be_beta_) * self.Pk(self.k_)

    def P4_pp(self, z_, b_alpha_, b_beta_, linear):

        self.z_ = z_
        self.b_alpha_ = b_alpha_
        self.b_beta_ = b_beta_
        self.linear = linear

        if linear == 'linear' or linear == True:
            self.Pk = interp1d(
                self.kvec / self.h,
                np.array([self.pclass.pk(_k, self.z_)
                          for _k in self.kvec]) * (self.h**3.))
        else:
            self.Pk = interp1d(
                np.logspace(-5, 2, 1000) / self.h,
                np.array([
                    self.pnlclass.pk(_k, self.z_)
                    for _k in np.logspace(-5, 2, 1000)
                ]) * (self.h**3.))
        return self.c4(self.z_) * self.Pk(self.k_)

    #################################################################################################################################
    # Correlation function multipoles

    import scipy

    def integrand(self, s, ell):
        self.s = s
        self.ell = ell
        return (pow(self.k_, 2.) * scipy.special.spherical_jn(
            self.ell, self.k_ * self.s)) / (2 * pow(np.pi, 2.))

    def matter_real_space(self, s, z_, args):
        self.s = s
        self.z_ = z_
        self.args = args

        self.linear = self.args[0]

        if self.linear == 'linear' or self.linear == True:
            self.interpol = interp1d(
                self.kvec / self.h,
                np.array([self.pclass.pk(_k, self.z_)
                          for _k in self.kvec]) * (self.h**3.))
        else:
            self.interpol = interp1d(
                np.logspace(-5, 2, 1000) / self.h,
                np.array([
                    self.pnlclass.pk(_k, self.z_)
                    for _k in np.logspace(-5, 2, 1000)
                ]) * (self.h**3.))

        self.MONO = []

        for i in s:
            self.MONO.append(
                integrate.simps(
                    self.integrand(i, 0) * self.interpol(self.k_) *
                    np.exp(-self.k_**5), self.k_))

        self.MONO = np.array(self.MONO)

        return self.MONO

    def multipoles(self, s, z_, b_alpha_, b_beta_, be_alpha_, be_beta_, args):
        self.s = s
        self.z_ = z_
        self.b_alpha_ = b_alpha_
        self.b_beta_ = b_beta_
        self.be_alpha_ = be_alpha_
        self.be_beta_ = be_beta_
        self.args = args
        """
            This gives the non-vanishing ODD multipoles (l=1,3) for the correlation function. 
            Inputs are:
            1) s: a vector of configuration space positions;
            2) z: redshift of calculation;
            3) b_alpha, b_beta: linear biases of tracers alpha and beta (may be the same);
            4) be_alpha, be_beta: evolution biases for the tracers computed at z;
            5) args: a list or array with like 
                     args = ['linear',s_alpha,s_beta] (s = magnification biases)
                  or args = ['linear']
                  or True/False to select linear or non-linear correlation functions;
        """

        if len(self.args) > 1:
            self.linear, self.s_alpha, self.s_beta = self.args[0], self.args[
                1], self.args[2]
            self.coef_dipo = self.c1_Mag(self.z_, self.b_alpha_, self.b_beta_,
                                         self.be_alpha_, self.be_beta_,
                                         self.s_alpha, self.s_beta)
        if len(self.args) == 1:
            self.linear = self.args[0]
            self.coef_dipo = self.c1(self.z_, self.b_alpha_, self.b_beta_,
                                     self.be_alpha_, self.be_beta_)

        self.coef_mono = self.c0(self.z_, self.b_alpha_, self.b_beta_)
        self.coef_quad = self.c2(self.z_, self.b_alpha_, self.b_beta_)
        self.coef_octu = self.c3(self.z_, self.b_alpha_, self.b_beta_,
                                 self.be_alpha_, self.be_beta_)
        self.coef_hexa = self.c4(self.z_)

        if self.linear == 'linear' or self.linear == True:
            self.interpol = interp1d(
                self.kvec / self.h,
                np.array([self.pclass.pk(_k, self.z_)
                          for _k in self.kvec]) * (self.h**3.))
        else:
            self.interpol = interp1d(
                np.logspace(-5, 2, 1000) / self.h,
                np.array([
                    self.pnlclass.pk(_k, self.z_)
                    for _k in np.logspace(-5, 2, 1000)
                ]) * (self.h**3.))

        self.MONO = []
        self.DIPO = []
        self.QUAD = []
        self.OCTU = []
        self.HEXA = []

        for i in s:
            self.MONO.append(
                integrate.simps(
                    self.coef_mono * self.integrand(i, 0) *
                    self.interpol(self.k_) * np.exp(-self.k_**5), self.k_))
            self.DIPO.append(
                integrate.simps(
                    self.coef_dipo * self.integrand(i, 1) *
                    self.interpol(self.k_) * np.exp(-self.k_**5), self.k_))
            self.QUAD.append(
                integrate.simps(
                    self.coef_quad * self.integrand(i, 2) *
                    self.interpol(self.k_) * np.exp(-self.k_**5), self.k_))
            self.OCTU.append(
                integrate.simps(
                    self.coef_octu * self.integrand(i, 3) *
                    self.interpol(self.k_) * np.exp(-self.k_**5), self.k_))
            self.HEXA.append(
                integrate.simps(
                    self.coef_hexa * self.integrand(i, 4) *
                    self.interpol(self.k_) * np.exp(-self.k_**5), self.k_))

        self.MONO = pow(1j, 0).real * np.array(self.MONO)
        self.DIPO = pow(1j, 1).imag * np.array(self.DIPO)
        self.QUAD = pow(1j, 2).real * np.array(self.QUAD)
        self.OCTU = pow(1j, 3).imag * np.array(self.OCTU)
        self.HEXA = pow(1j, 4).real * np.array(self.HEXA)

        return self.MONO, self.DIPO, self.QUAD, self.OCTU, self.HEXA

    def odd_multipoles(self, s, z_, b_alpha_, b_beta_, be_alpha_, be_beta_,
                       args):
        self.s = s
        self.z_ = z_
        self.b_alpha_ = b_alpha_
        self.b_beta_ = b_beta_
        self.be_alpha_ = be_alpha_
        self.be_beta_ = be_beta_
        self.args = args
        """
            This gives the non-vanishing ODD multipoles (l=1,3) for the correlation function. 
            Inputs are:
            1) s: a vector of configuration space positions;
            2) z: redshift of calculation;
            3) b_alpha, b_beta: linear biases of tracers alpha and beta (may be the same);
            4) be_alpha, be_beta: evolution biases for the tracers computed at z;
            5) args: a list or array with like 
                     args = ['linear',s_alpha,s_beta] (s = magnification biases)
                  or args = ['linear']
                  or True/False to select linear or non-linear correlation functions;
        """

        if len(self.args) > 1:
            self.linear, self.s_alpha, self.s_beta = self.args[0], self.args[
                1], self.args[2]
            self.coef_dipo = self.c1_Mag(self.z_, self.b_alpha_, self.b_beta_,
                                         self.be_alpha_, self.be_beta_,
                                         self.s_alpha, self.s_beta)
        if len(self.args) == 1:
            self.linear = self.args[0]
            self.coef_dipo = self.c1(self.z_, self.b_alpha_, self.b_beta_,
                                     self.be_alpha_, self.be_beta_)

        self.coef_octu = self.c3(self.z_, self.b_alpha_, self.b_beta_,
                                 self.be_alpha_, self.be_beta_)

        if self.linear == 'linear' or self.linear == True:
            self.interpol = interp1d(
                self.kvec / self.h,
                np.array([self.pclass.pk(_k, self.z_)
                          for _k in self.kvec]) * (self.h**3.))
        else:
            self.interpol = interp1d(
                np.logspace(-5, 2, 1000) / self.h,
                np.array([
                    self.pnlclass.pk(_k, self.z_)
                    for _k in np.logspace(-5, 2, 1000)
                ]) * (self.h**3.))

        self.DIPO = []
        self.OCTU = []

        for i in s:
            self.DIPO.append(
                integrate.simps(
                    self.coef_dipo * self.integrand(i, 1) *
                    self.interpol(self.k_) * np.exp(-self.k_**5), self.k_))
            self.OCTU.append(
                integrate.simps(
                    self.coef_octu * self.integrand(i, 3) *
                    self.interpol(self.k_) * np.exp(-self.k_**5), self.k_))

        self.DIPO = pow(1j, 1).imag * np.array(self.DIPO)
        self.OCTU = pow(1j, 3).imag * np.array(self.OCTU)

        return self.DIPO, self.OCTU

    def help(self):
        print '[Reaching help for MultiCorr]\n'
        print 'Full list of functions and their entries:\n'
        print '(Auxiliary functions)'
        print 'Om(z): Evolving matter density Omega_m(z) - Inputs: z (redshift).'
        print 'Doppler(z, be): Doppler term assuming magnification bias s = 0 - Inputs: z (redshift) and be (evolution bias at z).'
        print 'DopplerMag(z, be,s): Doppler term - Inputs: z (redshift), be (evolution bias at z) and s (magnification bias at z).'
        print 'c0(z,ba,bb): Monopole coefficient - Inputs: z (redshift) and bi (linear bias of tracer i at z).'
        print 'c1(z,ba,bb,be_a,be_b): Dipole coefficient - Inputs: z (redshift), bi (linear bias of tracer i at z) and be_i (evolution bias of tracer i at z).'
        print 'c1_Mag(z,ba,bb,be_a,be_b,sa,sb): Dipole coefficient with magnification - Inputs: z (redshift), bi (linear bias of tracer i at z), be_i (evolution bias of tracer i at z) and si (magnification of tracer i at z).'
        print 'c2(z,ba,bb): Quadrupole coefficient - Inputs: z (redshift) and bi (linear bias of tracer i at z).'
        print 'c3(z,ba,bb,be_a,be_b): Octupole coefficient assuming no magnification - Inputs: z (redshift), bi (linear bias of tracer i at z) and be_i (evolution bias of tracer i at z).'
        print 'c4(z): Hexadecapole coefficient - Inputs: z (redshift).\n'
        print '(Power-spectrum multipoles)'
        print 'P0_pp(z,ba,bb,linear) - linear = True or False'
        print 'P1_pp(z,ba,bb,be_a,be_b,linear) - linear = True or False'
        print 'P1Mag_pp(z,ba,bb,be_a,be_b,sa,sb,linear) - linear = True or False'
        print 'P2_pp(z,ba,bb,linear) - linear = True or False'
        print 'P3_pp(z,ba,bb,be_a,be_b,linear) - linear = True or False'
        print 'P4_pp(z,ba,bb,linear) - linear = True or False\n'
        print '(Correlation function multipoles)'
        print 'integrand(s,ell): returns the integrand of the correlation function.'
        print 'multipoles(s,z,ba,bb,be_a,be_b,args) - args: [True] or [True, sa, sb], si (magnification bias of tracer i)'
        print 'odd_multipoles(s,z,ba,bb,be_a,be_b,args) - args: [True] or [True, sa, sb], si (magnification bias of tracer i)\n'
        print '[End of help]'
Пример #13
0

M = Class()
# Table I of 1908.06995, third column, best-fit values
# Note: f and m found by trial-and-error to give the best-fit fEDE=.12, zc=10^3.562=3647.
M.set({'f_scf': 3.98e+26, 'm_scf': 5.31e-28, 'thetai_scf': 2.83, 'A_s': 2.215e-09, 'n_s': 0.9889, '100*theta_s': 1.04152, 'omega_b': 0.02253, 'omega_cdm': 0.1306, 'm_ncdm': 0.06, 'tau_reio': 0.072})


#'non linear':can choose 'halofit' or 'HMCODE'
M.set({'non linear':'HMCODE','N_ncdm':1, 'N_ur':2.0328, 'Omega_Lambda':0.0, 'Omega_fld':0, 'Omega_scf':-1, 'n_scf':3, 'CC_scf':1, 'scf_parameters':'1, 1, 1, 1, 1, 0.0', 'scf_tuning_index':3, 'attractor_ic_scf':'no', 'output':'tCl pCl lCl mPk', 'lensing':'yes', 'l_max_scalars':2508, 'P_k_max_h/Mpc':20,'z_max_pk':4.})
M.compute()

print(M.Omega_m())


baM = M.get_background()

fEDE = M.fEDE()
z_c = M.z_c()

baH = baM['H [1/Mpc]']
baT = baM['conf. time [Mpc]']
baa = 1/(1 + baM['z'])
bV = baM['V_e_scf']
bpp = baM["phi'_scf"]
baCrit = baM['(.)rho_crit']
rho_scf = (bpp*bpp/(2*baa*baa) + bV)/3.


plt.figure(figsize=(10,10))
plt.rcParams.update({'font.size': 18})