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 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 
Ejemplo n.º 3
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.º 4
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.º 5
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.º 6
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.º 7
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.º 8
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.º 9
0
    cosmo.set({
        'output': 'mPk',
        'Omega_cdm': omM0 - omB0,
        'Omega_k': 1. - omM0 - omL0,
        'h': h,
        'sigma8': sig8,
        'n_s': ns,
        'non linear': '',
        'P_k_max_h/Mpc': 10.,
        'z_pk': zlist,
        'output_verbose': 1
    })
    cosmo.compute()
    print "----"
    klin = 10**np.linspace(-4, 0.0, 100)
    pk0 = np.array([cosmo.pk(kk, 0.) for kk in klin])
    pkz = np.array([cosmo.pk(kk, zred) for kk in klin])

    # save P(k) lin to be used for TNS model
    np.savetxt("pklin_z0_wmap9.dat", zip(klin, pk0))

    print "----"
    #"""

    zlist_nl = str("0, %.1f" % (zred))
    print zlist_nl
    cosmo = Class()
    print omM0 - omB0, 1. - omM0 - omL0, h, sig8, ns, zlist_nl
    cosmo.set({
        'output': 'mPk',
        'Omega_cdm': omM0 - omB0,
Ejemplo n.º 10
0
    DV = (z * (1 + z)**2 * da**2 / cosmo.Hubble(z))**(1. / 3.)
    # print('DV=',DV)
    fs8 = cosmo.scale_independent_growth_factor(
        z) * cosmo.scale_independent_growth_factor_f(z) * cosmo.sigma8()
    # print('fs8=',fs8)
    # print('sigma8=',cosmo.sigma8())
    print('rd/DV=', rd / DV)
    print('rdH=', rd * cosmo.Hubble(z))
    print('rd/DA=', rd / da)

    P2noW = np.zeros(k_size)
    P0noW = np.zeros(k_size)
    for i in range(k_size):
        kinloop1 = k[i] * h
        P2noW[i] = (
            norm**2. * cosmo.pk(kinloop1, z)[18] + norm**4. *
            (cosmo.pk(kinloop1, z)[24]) +
            norm**1. * b1 * cosmo.pk(kinloop1, z)[19] + norm**3. * b1 *
            (cosmo.pk(kinloop1, z)[25]) + b1**2. * norm**2. *
            cosmo.pk(kinloop1, z)[26] + b1 * b2 * norm**2. * cosmo.pk(
                kinloop1, z)[34] + b2 * norm**3. * cosmo.pk(kinloop1, z)[35] +
            b1 * bG2 * norm**2. * cosmo.pk(kinloop1, z)[36] +
            bG2 * norm**3. * cosmo.pk(kinloop1, z)[37] + 2. *
            (css2) * norm**2. * cosmo.pk(kinloop1, z)[12] / h**2. +
            (2. * bG2 + 0.8 * bGamma3) * norm**3. * cosmo.pk(kinloop1, z)[9]
        ) * h**3. + fz**2. * b4 * k[i]**2. * (
            (norm**2. * fz**2. * 70. + 165. * fz * b1 * norm + 99. * b1**2.) *
            4. / 693.) * (35. / 8.) * cosmo.pk(kinloop1, z)[13] * h
        P0noW[i] = (
            norm**2. * cosmo.pk(kinloop1, z)[15] + norm**4. *
            (cosmo.pk(kinloop1, z)[21]) +
Ejemplo n.º 11
0
    # 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()
    # extract h value to convert k from 1/Mpc to h/Mpc
    h = NH.h()
    plt.semilogx(kvec/h,1-np.array(pkNH)/np.array(pkIH))
    legarray.append(r'$\Sigma m_i = '+str(sum_masses)+'$eV')

plt.axhline(0,color='k')
plt.xlim(kvec[0]/h,kvec[-1]/h)
plt.xlabel(r'$k [h \mathrm{Mpc}^{-1}]$')
plt.ylabel(r'$1-P(k)^\mathrm{NH}/P(k)^\mathrm{IH}$')
plt.legend(legarray)

Ejemplo n.º 12
0
    # 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()
    # extract h value to convert k from 1/Mpc to h/Mpc
    h = NH.h()
    plt.semilogx(kvec / h, 1 - np.array(pkNH) / np.array(pkIH))
    legarray.append(r'$\Sigma m_i = ' + str(sum_masses) + '$eV')

plt.axhline(0, color='k')
plt.xlim(kvec[0] / h, kvec[-1] / h)
plt.xlabel(r'$k [h \mathrm{Mpc}^{-1}]$')
plt.ylabel(r'$1-P(k)^\mathrm{NH}/P(k)^\mathrm{IH}$')
plt.legend(legarray)

# In[6]:
Ejemplo n.º 13
0
# with all the struct_init() methods called.
cosmo.compute()

# Access the lensed cl
cls = cosmo.lensed_cl()

# Print on screen to see the output
print "cls contains:", cls.viewkeys()
#print cls
# It is a dictionnary that contains the fields: tt, te, ee, bb, pp, tp

#cosmo.get_current_derived_parameters(['Omega_Lambda'])

#cosmo.pk(k, z)   # function that returns P(k,z). Watch that there is no h factor anywhere
K = np.logspace(np.log10(1.e-4), np.log10(3.), 501, 10.)
f = lambda k: cosmo.pk(k, 0.)
Plin = np.array(map(f, K))

plt.loglog(K, Plin)
plt.show()

# Clean CLASS (the equivalent of the struct_free() in the `main`
# of CLASS. This step is primordial when running in a loop over different
# cosmologies, as you will saturate your memory very fast if you ommit
# it.
#cosmo.struct_cleanup()

# If you want to change completely the cosmology, you should also
# clean the arguments, otherwise, if you are simply running on a loop
# of different values for the same parameters, this step is not needed
#cosmo.empty()
Ejemplo n.º 14
0
# one_k = all_k['scalar'][0]     # this contains only the scalar perturbations for the requested k values

clM = M.lensed_cl(2500)
ll_LCDM = clM['ell'][2:]
clTT_LCDM = clM['tt'][2:]
clEE_LCDM = clM['ee'][2:]
clTE_LCDM = clM['te'][2:]
clPP_LCDM = clM['pp'][2:]
# ax_TT.semilogx(ll_LCDM,(ll_LCDM)*(ll_LCDM+1)/(2*np.pi)*(clTT_LCDM),'k',lw=5)
# ax_EE.semilogx(ll_LCDM,(ll_LCDM)*(ll_LCDM+1)/(2*np.pi)*(clEE_LCDM),'k',lw=5)
# ax_PP.semilogx(ll_LCDM,(ll_LCDM)*(ll_LCDM+1)/(2*np.pi)*(clPP_LCDM),'k',lw=5)

pkM_LCDM = []

for k in kvec:
    pkM_LCDM.append(M.pk(k, 0.))

#     i=i+1
fTT = interp1d(ll_LCDM, clTT_LCDM)
fEE = interp1d(ll_LCDM, clEE_LCDM)
fTE = interp1d(ll_LCDM, clTE_LCDM)

M.struct_cleanup()
for i in range(var_num):
    #
    # deal with varying parameters:
    #
    dashes = dashes_array[i]
    #
    l = []
    print(' * Compute with %s=%d' % (var_name1, n[i]))
delta_b_ary = one_time['d_b']
delta_chi_ary = one_time['d_chi']

n_s = M.n_s()

# Primordial PS
k_pivot = 0.05
P_s = 2.105e-9 * (k_ary / k_pivot) ** (n_s - 1)

# Power spectra from transfer function
# In units of Mpc^3 / h^3
Pk_b_ary = P_s * (delta_b_ary) ** 2 / (k_ary ** 3 / (2 * np.pi ** 2)) * h ** 3
Pk_chi_ary = P_s * (delta_chi_ary) ** 2 / \
    (k_ary ** 3 / (2 * np.pi ** 2)) * h ** 3
Pk_chi_b_ary = P_s * (delta_chi_ary * delta_b_ary) / \
    (k_ary ** 3 / (2 * np.pi ** 2)) * h ** 3
Pk_tot_lin_ary = np.array([M.pk_lin(k, z_compute) * h ** 3 for k in k_ary])
Pk_tot_nonlin_ary = np.array([M.pk(k, z_compute) * h ** 3 for k in k_ary])

np.savez(output_dir + "p_k_chi_k_max_500_z_" + str(iz_compute),
         k_ary=k_ary / h,  # Convert back to h / Mpc
         Pk_b_ary=Pk_b_ary,
         Pk_chi_ary=Pk_chi_ary,
         Pk_chi_b_ary=Pk_chi_b_ary,
         Pk_e_ary=Pk_b_ary + Pk_chi_ary + 2 * Pk_chi_b_ary,
         Pk_e_b_ary=Pk_chi_b_ary + Pk_b_ary,
         Pk_tot_lin_ary=Pk_tot_lin_ary,
         Pk_tot_nonlin_ary=Pk_tot_nonlin_ary
         )
Ejemplo n.º 16
0
class class_interface:
    def __init__(self, cosmology=None):
        ''' 
			This is an interface I made to talk to the cython 
			module for class. 
			The inputs are a dictionary containing cosmological parameters.
			If the input cosmology is not given, then the default is Planck 2015. 
		'''

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

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

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

        self.non_linear_cosmo = Class()
        self.non_linear_cosmo.set(params)
        self.non_linear_cosmo.compute()

    def nl_power(self, k, z):
        P = np.zeros(k.size)
        for i in range(k.size):
            P[i] = self.non_linear_cosmo.pk(k[i], z)
        return P

    def linear_power(self, k):
        if k[-1] > self.k_max:
            print 'power spectrum requested is out of bounds'
            print 'adjust parameters sent to class'
            sys.exit()
        P = np.zeros(k.size)
        for i in range(k.size):
            P[i] = self.cosmo.pk(k[i], 0)
        return P
Ejemplo n.º 17
0
    'Ob0': Omega_b,
    'sigma8': sigma8,
    'ns': n_s
}

cosmology.addCosmology('fox', foxcolossus)
cosmology.setCosmology('fox')
cosmo = cosmology.setCosmology('fox')

Om = Omega_m

# Power spectrum
k = np.logspace(-4, 2, num=1000)  # 1/Mpc
z = 0.
Plin = np.array([classcosmo.pk_lin(ki, z) for ki in k])
Pnl = np.array([classcosmo.pk(ki, z) for ki in k])
# NOTE: You will need to convert these to h/Mpc and (Mpc/h)^3
# to use in the toolkit. To do this you would do:
k /= foxclass['h']
Plin *= foxclass['h']**3
Pnl *= foxclass['h']**3
# End of set cosmology

# Read xihm data
################# Mbin 2e14-5e14 Msun/h #################
xihm = np.loadtxt('data/xihm1_2e14_5e14_z0.0_down10')
covxihm = np.loadtxt('data/covxihm1_2e14_5e14_z0.0_down10')
r = np.loadtxt('data/r')

# Parameters
rt = 1.832
Ejemplo n.º 18
0
def Sijkl(z_arr,
          windows,
          cosmo_params=default_cosmo_params,
          precision=10,
          tol=1e-3,
          cosmo_Class=None):

    # Assert everything as the good type and shape, and find number of redshifts, bins etc
    zz = np.asarray(z_arr)
    win = np.asarray(windows)

    assert zz.ndim == 1, 'z_arr must be a 1-dimensional array'
    assert win.ndim == 2, 'windows must be a 2-dimensional array'

    nz = len(zz)
    nbins = win.shape[0]
    assert win.shape[1] == nz, 'windows must have shape (nbins,nz)'

    assert zz.min() > 0, 'z_arr must have values > 0'

    # If the cosmology is not provided (in the same form as CLASS), run CLASS
    if cosmo_Class is None:
        cosmo = Class()
        dico_for_CLASS = cosmo_params
        dico_for_CLASS['output'] = 'mPk'
        cosmo.set(dico_for_CLASS)
        cosmo.compute()
    else:
        cosmo = cosmo_Class

    h = cosmo.h()  #for  conversions Mpc/h <-> Mpc

    # Define arrays of r(z), k, P(k)...
    zofr = cosmo.z_of_r(zz)
    comov_dist = zofr[0]  #Comoving distance r(z) in Mpc
    dcomov_dist = 1 / zofr[1]  #Derivative dr/dz in Mpc
    dV = comov_dist**2 * dcomov_dist  #Comoving volume per solid angle in Mpc^3/sr
    growth = np.zeros(nz)  #Growth factor
    for iz in range(nz):
        growth[iz] = cosmo.scale_independent_growth_factor(zz[iz])

    #Index pairs of bins
    npairs = (nbins * (nbins + 1)) // 2
    pairs = np.zeros((2, npairs), dtype=int)
    count = 0
    for ibin in range(nbins):
        for jbin in range(ibin, nbins):
            pairs[0, count] = ibin
            pairs[1, count] = jbin
            count += 1

    # Compute normalisations
    Inorm = np.zeros(npairs)
    Inorm2D = np.zeros((nbins, nbins))
    for ipair in range(npairs):
        ibin = pairs[0, ipair]
        jbin = pairs[1, ipair]
        integrand = dV * windows[ibin, :] * windows[jbin, :]
        integral = integrate.simps(integrand, zz)
        Inorm[ipair] = integral
        Inorm2D[ibin, jbin] = integral
        Inorm2D[jbin, ibin] = integral
    #Flag pairs with too small overlap as unreliable
    #Note: this will also speed up later computations
    #Default tolerance : tol=1e-3
    flag = np.zeros(npairs, dtype=int)
    for ipair in range(npairs):
        ibin = pairs[0, ipair]
        jbin = pairs[1, ipair]
        ratio = abs(Inorm2D[ibin, jbin]) / np.sqrt(
            abs(Inorm2D[ibin, ibin] * Inorm2D[jbin, jbin]))
        if ratio < tol:
            flag[ipair] = 1

    # Compute U(i,j;kk)
    keq = 0.02 / h  #Equality matter radiation in 1/Mpc (more or less)
    klogwidth = 10  #Factor of width of the integration range. 10 seems ok
    kmin = min(keq, 1. / comov_dist.max()) / klogwidth
    kmax = max(keq, 1. / comov_dist.min()) * klogwidth
    nk = 2**precision  #10 seems to be enough. Increase to test precision, reduce to speed up.
    #kk          = np.linspace(kmin,kmax,num=nk)                   #linear grid on k
    logkmin = np.log(kmin)
    logkmax = np.log(kmax)
    logk = np.linspace(logkmin, logkmax, num=nk)
    kk = np.exp(logk)  #logarithmic grid on k
    Pk = np.zeros(nk)
    for ik in range(nk):
        Pk[ik] = cosmo.pk(kk[ik], 0.)  #In Mpc^3
    Uarr = np.zeros((npairs, nk))
    for ipair in range(npairs):
        if flag[ipair] == 0:
            ibin = pairs[0, ipair]
            jbin = pairs[1, ipair]
            for ik in range(nk):
                kr = kk[ik] * comov_dist
                integrand = dV * windows[ibin, :] * windows[
                    jbin, :] * growth * np.sin(kr) / kr
                Uarr[ipair, ik] = integrate.simps(integrand, zz)

    # Compute Sijkl finally
    Cl_zero = np.zeros((nbins, nbins, nbins, nbins))
    #For ipair<=jpair
    for ipair in range(npairs):
        if flag[ipair] == 0:
            U1 = Uarr[ipair, :] / Inorm[ipair]
            ibin = pairs[0, ipair]
            jbin = pairs[1, ipair]
            for jpair in range(ipair, npairs):
                if flag[jpair] == 0:
                    U2 = Uarr[jpair, :] / Inorm[jpair]
                    kbin = pairs[0, jpair]
                    lbin = pairs[1, jpair]
                    integrand = kk**2 * Pk * U1 * U2
                    #integral = 2/(i * integrate.simps(integrand,kk)     #linear integration
                    integral = 2 / pi * integrate.simps(integrand * kk,
                                                        logk)  #log integration
                    #Run through all valid symmetries to fill the 4D array
                    #Symmetries: i<->j, k<->l, (i,j)<->(k,l)
                    Cl_zero[ibin, jbin, kbin, lbin] = integral
                    Cl_zero[ibin, jbin, lbin, kbin] = integral
                    Cl_zero[jbin, ibin, kbin, lbin] = integral
                    Cl_zero[jbin, ibin, lbin, kbin] = integral
                    Cl_zero[kbin, lbin, ibin, jbin] = integral
                    Cl_zero[kbin, lbin, jbin, ibin] = integral
                    Cl_zero[lbin, kbin, ibin, jbin] = integral
                    Cl_zero[lbin, kbin, jbin, ibin] = integral
    Sijkl = Cl_zero / (4 * pi)

    return Sijkl


# End of PySSC.py
Ejemplo n.º 19
0
def turboSij(zstakes=default_zstakes,
             cosmo_params=default_cosmo_params,
             cosmo_Class=None):

    # If the cosmology is not provided (in the same form as CLASS), run CLASS
    if cosmo_Class is None:
        cosmo = Class()
        dico_for_CLASS = cosmo_params
        dico_for_CLASS['output'] = 'mPk'
        cosmo.set(dico_for_CLASS)
        cosmo.compute()
    else:
        cosmo = cosmo_Class

    h = cosmo.h()  #for  conversions Mpc/h <-> Mpc

    # Define arrays of z, r(z), k, P(k)...
    nzbins = len(zstakes) - 1
    nz_perbin = 10
    z_arr = np.zeros((nz_perbin, nzbins))
    comov_dist = np.zeros((nz_perbin, nzbins))
    for j in range(nzbins):
        z_arr[:, j] = np.linspace(zstakes[j], zstakes[j + 1], nz_perbin)
        comov_dist[:, j] = (cosmo.z_of_r(z_arr[:, j]))[0]  #In Mpc
    keq = 0.02 / h  #Equality matter radiation in 1/Mpc (more or less)
    klogwidth = 10  #Factor of width of the integration range. 10 seems ok ; going higher needs to increase nk_fft to reach convergence (fine cancellation issue noted in Lacasa & Grain)
    kmin = min(keq, 1. / comov_dist.max()) / klogwidth
    kmax = max(keq, 1. / comov_dist.min()) * klogwidth
    nk_fft = 2**11  #seems to be enough. Increase to test precision, reduce to speed up.
    k_4fft = np.linspace(kmin, kmax,
                         nk_fft)  #linear grid on k, as we need to use an FFT
    Deltak = kmax - kmin
    Dk = Deltak / nk_fft
    Pk_4fft = np.zeros(nk_fft)
    for ik in range(nk_fft):
        Pk_4fft[ik] = cosmo.pk(k_4fft[ik], 0.)  #In Mpc^3
    dr_fft = np.linspace(0, nk_fft // 2, nk_fft // 2 + 1) * 2 * pi / Deltak

    # Compute necessary FFTs and make interpolation functions
    fft2 = np.fft.rfft(Pk_4fft / k_4fft**2) * Dk
    dct2 = fft2.real
    dst2 = -fft2.imag
    km2Pk_dct = interp1d(dr_fft, dct2, kind='cubic')
    fft3 = np.fft.rfft(Pk_4fft / k_4fft**3) * Dk
    dct3 = fft3.real
    dst3 = -fft3.imag
    km3Pk_dst = interp1d(dr_fft, dst3, kind='cubic')
    fft4 = np.fft.rfft(Pk_4fft / k_4fft**4) * Dk
    dct4 = fft4.real
    dst4 = -fft4.imag
    km4Pk_dct = interp1d(dr_fft, dct4, kind='cubic')

    # Compute Sij finally
    Sij = np.zeros((nzbins, nzbins))
    for j1 in range(nzbins):
        rmin1 = (comov_dist[:, j1]).min()
        rmax1 = (comov_dist[:, j1]).max()
        zmean1 = ((z_arr[:, j1]).min() + (z_arr[:, j1]).max()) / 2
        growth1 = cosmo.scale_independent_growth_factor(zmean1)
        pref1 = 3. * growth1 / (rmax1**3 - rmin1**3)
        for j2 in range(nzbins):
            rmin2 = (comov_dist[:, j2]).min()
            rmax2 = (comov_dist[:, j2]).max()
            zmean2 = ((z_arr[:, j2]).min() + (z_arr[:, j2]).max()) / 2
            growth2 = cosmo.scale_independent_growth_factor(zmean2)
            pref2 = 3. * growth2 / (rmax2**3 - rmin2**3)
            #p1p2: rmax1 & rmax2
            rsum = rmax1 + rmax2
            rdiff = abs(rmax1 - rmax2)
            rprod = rmax1 * rmax2
            Icp2 = km2Pk_dct(rsum)
            Icm2 = km2Pk_dct(rdiff)
            Isp3 = km3Pk_dst(rsum)
            Ism3 = km3Pk_dst(rdiff)
            Icp4 = km4Pk_dct(rsum)
            Icm4 = km4Pk_dct(rdiff)
            Fp1p2 = -Icp4 + Icm4 - rsum * Isp3 + rdiff * Ism3 + rprod * (Icp2 +
                                                                         Icm2)
            #p1m2: rmax1 & rmin2
            rsum = rmax1 + rmin2
            rdiff = abs(rmax1 - rmin2)
            rprod = rmax1 * rmin2
            Icp2 = km2Pk_dct(rsum)
            Icm2 = km2Pk_dct(rdiff)
            Isp3 = km3Pk_dst(rsum)
            Ism3 = km3Pk_dst(rdiff)
            Icp4 = km4Pk_dct(rsum)
            Icm4 = km4Pk_dct(rdiff)
            Fp1m2 = -Icp4 + Icm4 - rsum * Isp3 + rdiff * Ism3 + rprod * (Icp2 +
                                                                         Icm2)
            #m1p2: rmin1 & rmax2
            rsum = rmin1 + rmax2
            rdiff = abs(rmin1 - rmax2)
            rprod = rmin1 * rmax2
            Icp2 = km2Pk_dct(rsum)
            Icm2 = km2Pk_dct(rdiff)
            Isp3 = km3Pk_dst(rsum)
            Ism3 = km3Pk_dst(rdiff)
            Icp4 = km4Pk_dct(rsum)
            Icm4 = km4Pk_dct(rdiff)
            Fm1p2 = -Icp4 + Icm4 - rsum * Isp3 + rdiff * Ism3 + rprod * (Icp2 +
                                                                         Icm2)
            #m1m2: rmin1 & rmin2
            rsum = rmin1 + rmin2
            rdiff = abs(rmin1 - rmin2)
            rprod = rmin1 * rmin2
            Icp2 = km2Pk_dct(rsum)
            Icm2 = km2Pk_dct(rdiff)
            Isp3 = km3Pk_dst(rsum)
            Ism3 = km3Pk_dst(rdiff)
            Icp4 = km4Pk_dct(rsum)
            Icm4 = km4Pk_dct(rdiff)
            Fm1m2 = -Icp4 + Icm4 - rsum * Isp3 + rdiff * Ism3 + rprod * (Icp2 +
                                                                         Icm2)
            #now group everything
            Fsum = Fp1p2 - Fp1m2 - Fm1p2 + Fm1m2
            Sij[j1, j2] = pref1 * pref2 * Fsum / (4 * pi**2)

    return Sij
Ejemplo n.º 20
0
def Sij_alt(z_arr,
            windows,
            cosmo_params=default_cosmo_params,
            cosmo_Class=None):

    # Assert everything as the good type and shape, and find number of redshifts, bins etc
    zz = np.asarray(z_arr)
    win = np.asarray(windows)

    assert zz.ndim == 1, 'z_arr must be a 1-dimensional array'
    assert win.ndim == 2, 'windows must be a 2-dimensional array'

    nz = len(zz)
    nbins = win.shape[0]
    assert win.shape[1] == nz, 'windows must have shape (nbins,nz)'

    assert zz.min() > 0, 'z_arr must have values > 0'

    # If the cosmology is not provided (in the same form as CLASS), run CLASS
    if cosmo_Class is None:
        cosmo = Class()
        dico_for_CLASS = cosmo_params
        dico_for_CLASS['output'] = 'mPk'
        cosmo.set(dico_for_CLASS)
        cosmo.compute()
    else:
        cosmo = cosmo_Class

    h = cosmo.h()  #for  conversions Mpc/h <-> Mpc

    # Define arrays of r(z), k, P(k)...
    zofr = cosmo.z_of_r(zz)
    comov_dist = zofr[0]  #Comoving distance r(z) in Mpc
    dcomov_dist = 1 / zofr[1]  #Derivative dr/dz in Mpc
    dV = comov_dist**2 * dcomov_dist  #Comoving volume per solid angle in Mpc^3/sr
    growth = np.zeros(nz)  #Growth factor
    for iz in range(nz):
        growth[iz] = cosmo.scale_independent_growth_factor(zz[iz])

    keq = 0.02 / h  #Equality matter radiation in 1/Mpc (more or less)
    klogwidth = 10  #Factor of width of the integration range.
    #10 seems ok ; going higher needs to increase nk_fft to reach convergence (fine cancellation issue noted in Lacasa & Grain)
    kmin = min(keq, 1. / comov_dist.max()) / klogwidth
    kmax = max(keq, 1. / comov_dist.min()) * klogwidth
    nk_fft = 2**11  #seems to be enough. Increase to test precision, reduce to speed up.
    k_4fft = np.linspace(kmin, kmax,
                         nk_fft)  #linear grid on k, as we need to use an FFT
    Deltak = kmax - kmin
    Dk = Deltak / nk_fft
    Pk_4fft = np.zeros(nk_fft)
    for ik in range(nk_fft):
        Pk_4fft[ik] = cosmo.pk(k_4fft[ik], 0.)  #In Mpc^3
    dr_fft = np.linspace(0, nk_fft // 2, nk_fft // 2 + 1) * 2 * pi / Deltak

    # Compute necessary FFTs and make interpolation functions
    fft0 = np.fft.rfft(Pk_4fft) * Dk
    dct0 = fft0.real
    dst0 = -fft0.imag
    Pk_dct = interp1d(dr_fft, dct0, kind='cubic')

    # Compute sigma^2(z1,z2)
    sigma2_nog = np.zeros((nz, nz))
    #First with P(k,z=0) and z1<=z2
    for iz in range(nz):
        r1 = comov_dist[iz]
        for jz in range(iz, nz):
            r2 = comov_dist[jz]
            rsum = r1 + r2
            rdiff = abs(r1 - r2)
            Icp0 = Pk_dct(rsum)
            Icm0 = Pk_dct(rdiff)
            sigma2_nog[iz, jz] = (Icm0 - Icp0) / (4 * pi**2 * r1 * r2)
    #Now fill by symmetry and put back growth functions
    sigma2 = np.zeros((nz, nz))
    for iz in range(nz):
        growth1 = growth[iz]
        for jz in range(nz):
            growth2 = growth[jz]
            sigma2[iz, jz] = sigma2_nog[min(iz, jz),
                                        max(iz, jz)] * growth1 * growth2

    # Compute normalisations
    Inorm = np.zeros(nbins)
    for i1 in range(nbins):
        integrand = dV * windows[i1, :]**2
        Inorm[i1] = integrate.simps(integrand, zz)

    # Compute Sij finally
    prefactor = sigma2 * (dV * dV[:, None])
    Sij = np.zeros((nbins, nbins))
    #For i<=j
    for i1 in range(nbins):
        for i2 in range(i1, nbins):
            integrand = prefactor * (windows[i1, :]**2 *
                                     windows[i2, :, None]**2)
            Sij[i1, i2] = integrate.simps(integrate.simps(integrand, zz),
                                          zz) / (Inorm[i1] * Inorm[i2])
    #Fill by symmetry
    for i1 in range(nbins):
        for i2 in range(nbins):
            Sij[i1, i2] = Sij[min(i1, i2), max(i1, i2)]

    return Sij
Ejemplo n.º 21
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 list(somedict.items())])
        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 list(self.scenario.items()):
            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(list(self.verbose.items()) + list(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 list(self.scenario.keys()):
            # Positive tests of raw cls
            output = self.scenario['output']
            for elem in output.split():
                if elem in list(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 list(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(list(self.verbose.items()) + list(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 list(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 list(self.scenario.keys()):
            if 'output' not in list(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 list(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 list(self.scenario.keys()):
            if 'output' not in list(self.scenario.keys()):
                should_fail = True

        # If we ask for Cl's of lensing potential, we must have scalar modes.
        if 'output' in list(self.scenario.keys()
                            ) and 'lCl' in self.scenario['output'].split():
            if 'modes' in list(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 list(self.scenario.keys()):
            if 'modes' in list(self.scenario.keys()
                               ) and self.scenario['modes'].find('s') == -1:
                should_fail = True
            if 'output' not in list(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 list(self.scenario.keys(
        )) and self.scenario['P_k_ini type'].find('inflation') != -1:
            if 'modes' not in list(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 list(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 list(ref.items()):
                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 list(value.keys()):
                                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 list(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(
            list(self.verbose.items()) + list(self.scenario.items()))
        with open(path + '.ini', 'w') as param_file:
            for key, value in list(parameters.items()):
                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(
            list(self.verbose.items()) + list(self.scenario.items()))
        with open(path + '.ini', 'w') as param_file:
            for key, value in list(parameters.items()):
                param_file.write(key + " = " + str(value) + '\n')
Ejemplo n.º 22
0
start_time = time.time()

cosmo2 = Class()
cosmo2.set(params2)
cosmo2.compute()

print("--- %s seconds ---" % (time.time() - start_time))

pks = []
pks2 = []

# get the pk at each redshift
for j in range(len(zs)):
    pk, pk2 = [], []
    for ki in k_magnitudes_full[:-1]:
        pk.append(cosmo.pk(ki, zs[j]))
        pk2.append(cosmo2.pk(ki, zs[j]))

    pks.append(pk)
    pks2.append(pk2)

os.makedirs('./arrays/', exist_ok=True)
# save arrays
np.savez('./arrays/cdmpk_k{}to{}'.format(k_min, k_max),
         ks=k_magnitudes_full,
         zs=zs,
         pks=pks)
np.savez('./arrays/wdmpk_k{}to{}'.format(k_min, k_max),
         ks=k_magnitudes_full,
         zs=zs,
         pks=pks2)
Ejemplo n.º 23
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")
Ejemplo n.º 24
0
# Create an instance of the CLASS wrapper
cosmo = Class()
# Set the parameters to the cosmological code
cosmo.set(params_def)
cosmo.compute()
#### Define the linear growth factor and growth rate (growth factor f in class)
h = cosmo.h()
# ~mcu = cosmo.N_ur()
# ~print(mcu)

Plin = np.zeros(len(karray))
Pnonlin = np.zeros(len(karray))
for i, k in enumerate(karray):
    Plin[i] = (cosmo.pk_lin(k, z))  # function .pk(k,z)
    Pnonlin[i] = (cosmo.pk(k, z))  # function .pk(k,z)

Plin *= h**3
Pnonlin *= h**3

#-------------------------------------------------------------------------
#-------------------------------------------------------------------------
m_1 = 0.02
ocdm_1 = 0.261205 - m_1 * 3 / (93.14 * h**2)
params_1 = {
    'output': 'mPk',
    'non linear': 'halofit',
    'Omega_cdm': ocdm_1,
    'N_ncdm': 3,
    'N_ur': 0.00441,
    'm_ncdm': str(m_1) + ',' + str(m_1) + ',' + str(m_1)
Ejemplo n.º 25
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.º 26
0
Om = 0.31834
Ocdm = Om - Ob
h = 0.670435
params = {
        'output': 'mPk',
        "h":h,
        "A_s":2.1e-9,
        "n_s":0.96191,
        "Omega_b":Ob,
        "Omega_cdm":Ocdm,
        'YHe':0.24755048455476272,#By hand, default value
        'P_k_max_h/Mpc':3000.,
        'z_max_pk':1.0,
        'non linear':'halofit'}

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


k = np.logspace(-5, 3, base=10, num=4000) #1/Mpc, apparently
np.savetxt("txt_files/P_files/k.txt", k/h) #h/Mpc now
for i in range(len(zs)):
    z = zs[i]

    Pmm  = np.array([cosmo.pk(ki, z) for ki in k]) 
    Plin = np.array([cosmo.pk_lin(ki, z) for ki in k]) 
    np.savetxt("txt_files/P_files/Pnl_z%.2f.txt"%(z), Pmm*h**3) #Mpc^3/h^3
    np.savetxt("txt_files/P_files/Plin_z%.2f.txt"%(z), Plin*h**3) #Mpc^3/h^3
    print "Done with z%.2f"%z
#k1 = 0.7*1.028185622909e-5
#k1 = 1.e-6
#z = 0.0
#k1 = 0.1
#print(cosmo.pk(k1,z))
#print(cosmo.pk_lin(k1,z))

k = np.linspace(log(0.0001), log(50), 400)
k = np.exp(k)
testout = [[0 for x in range(42)] for y in range(len(k))]
for i in range(len(k)):
    testout[i][0] = k[i]
    testout[i][41] = cosmo.pk_lin(k[i], z)
    for j in range(40):
        #        print("j=",j)
        testout[i][j + 1] = cosmo.pk(k[i], z)[j]
#        testout[i][0] = k[i]
#        testout[i][1] = cosmo.pk(k[i],z)[0]
#        testout[i][2] = cosmo.pk(k[i],z)[1]
#        testout[i][3] = cosmo.pk(k[i],z)[2]
#        testout[i][4] = cosmo.pk(k[i],z)[3]
#        testout[i][5] = cosmo.pk(k[i],z)[4]
#        testout[i][6] = cosmo.pk(k[i],z)[5]
#        testout[i][7] = cosmo.pk(k[i],z)[6]
#        testout[i][8] = cosmo.pk(k[i],z)[7]
#        testout[i][9] = cosmo.pk(k[i],z)[8]
#	testout[i][10] = cosmo.pk_lin(k[i],0)
np.savetxt('las_damas_pk_nl.dat', testout)
t2 = time()
print("overall elapsed time=", t2 - t1)
### everything is in units Mpc!
Ejemplo n.º 28
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.º 29
0
s8 = np.array(results.get_sigma8())

PCLASS = np.array([cosmo.pk_lin(ki * cosmo.h(), 0) for ki in kh])

# plt.loglog(kh, Pmm, '-')
plt.loglog(kh, PCLASS / (cosmo.h())**(-3), '-')
plt.loglog(kh, pk[0, :], '-')
plt.title('LINEAR')

# P(k) Comparison

plt.loglog(kh, np.abs((PCLASS / (cosmo.h())**(-3) - pk[0, :]) / pk[0, :]))
plt.xlabel(r'$k/h$')
plt.ylabel(r'$|\Delta P(k)| / P(k)$')

# Nonlinear P(k) Difference

pars.NonLinear = model.NonLinear_both
results.calc_power_spectra(pars)
kh_nonlin, z_nonlin, pk_nonlin = results.get_matter_power_spectrum(minkh=1e-4,
                                                                   maxkh=1,
                                                                   npoints=200)

PCLASS = np.array([cosmo.pk(ki * cosmo.h(), 0) for ki in kh])

plt.loglog(
    kh, np.abs(
        (PCLASS / (cosmo.h())**(-3) - pk_nonlin[0, :]) / pk_nonlin[0, :]))
plt.xlabel(r'$k/h$')
plt.ylabel(r'$|\Delta P(k)| / P(k)$')
Ejemplo n.º 30
0
from math import pi
import numpy as np

## ---BEST FIT MATTER POWER SPECTRUM P(k)---
# 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()
# get P(k) at redhsift z=0
kk = np.logspace(-4,np.log10(3),1000)
Pk = []
for k in kk:
    Pk.append(LambdaCDM.pk(k,0.)) # function .pk(k,z)

#Upper limit on h
LambdaCDM2 = Class()
LambdaCDM2.set({'omega_b':0.022032,'omega_cdm':0.12038,'h':2.70224,'A_s':2.215e-9,'n_s':0.9619,'tau_reio':0.0925})
LambdaCDM2.set({'output':'tCl,pCl,lCl,mPk','lensing':'yes','P_k_max_1/Mpc':3.0})
LambdaCDM2.compute()
kk2 = np.logspace(-4,np.log10(3),1000)
Pk2 = []
for k in kk2:
    Pk2.append(LambdaCDM2.pk(k,0.)) # function .pk(k,z)
    
#Lower limit on h
LambdaCDM3 = Class()
LambdaCDM3.set({'omega_b':0.022032,'omega_cdm':0.12038,'h':0.16889,'A_s':2.215e-9,'n_s':0.9619,'tau_reio':0.0925})
LambdaCDM3.set({'output':'tCl,pCl,lCl,mPk','lensing':'yes','P_k_max_1/Mpc':3.0})
Ejemplo n.º 31
0
#k1 = 0.7*1.028185622909e-5
#k1 = 1.e-6
#z = 0.0
#k1 = 0.1
#print(cosmo.pk(k1,z))
#print(cosmo.pk_lin(k1,z))

k = np.linspace(log(0.0001), log(50), 200)
k = np.exp(k)
testout = [[0 for x in range(42)] for y in range(len(k))]
for i in range(len(k)):
    testout[i][0] = k[i]
    testout[i][41] = cosmo.pk_lin(k[i] * h, z) * h**3
    for j in range(40):
        #        print("j=",j)
        testout[i][j + 1] = cosmo.pk(k[i] * h, z)[j] * h**3
#        testout[i][0] = k[i]
#        testout[i][1] = cosmo.pk(k[i],z)[0]
#        testout[i][2] = cosmo.pk(k[i],z)[1]
#        testout[i][3] = cosmo.pk(k[i],z)[2]
#        testout[i][4] = cosmo.pk(k[i],z)[3]
#        testout[i][5] = cosmo.pk(k[i],z)[4]
#        testout[i][6] = cosmo.pk(k[i],z)[5]
#        testout[i][7] = cosmo.pk(k[i],z)[6]
#        testout[i][8] = cosmo.pk(k[i],z)[7]
#        testout[i][9] = cosmo.pk(k[i],z)[8]
#	testout[i][10] = cosmo.pk_lin(k[i],0)
# np.savetxt('ede_pk_nl_bestfit_z038.dat', testout)
np.savetxt('ede_pk_nl_bestfit_z061.dat', testout)
t2 = time()
print("overall elapsed time=", t2 - t1)
Ejemplo n.º 32
0
class tsz_gal_cl:
    def __init__(self):
        # print 'Class for tSZ Cl'
        # self.ptilde = np.loadtxt(LIBDIR+'/aux_files/ptilde.txt')
        self.fort_lib_cl = cdll.LoadLibrary(LIBDIR + "/source/calc_cl")

        self.fort_lib_cl.calc_cl_.argtypes = [
            POINTER(c_double),  #h0
            POINTER(c_double),  #obh2
            POINTER(c_double),  #och2
            POINTER(c_double),  #mnu
            POINTER(c_double),  #bias
            POINTER(c_double),  #Mcut
            POINTER(c_double),  #M1
            POINTER(c_double),  #kappa
            POINTER(c_double),  #sigma_Ncen
            POINTER(c_double),  #alp_Nsat
            POINTER(c_double),  #rmax
            POINTER(c_double),  #rgs
            POINTER(c_int64),  #pk_nk
            POINTER(c_int64),  #pk_nz
            np.ctypeslib.ndpointer(dtype=np.double),  #karr
            np.ctypeslib.ndpointer(dtype=np.double),  #pkarr
            np.ctypeslib.ndpointer(dtype=np.double),  #dndz
            POINTER(c_int64),  #nz_dndz
            POINTER(c_double),  #z1
            POINTER(c_double),  #z2
            POINTER(c_double),  #z1_ng
            POINTER(c_double),  #z2_ng
            POINTER(c_int64),  #nl
            np.ctypeslib.ndpointer(dtype=np.double),  #ell
            np.ctypeslib.ndpointer(dtype=np.double),  #gg
            np.ctypeslib.ndpointer(dtype=np.double),  #gy
            np.ctypeslib.ndpointer(dtype=np.double),  #tll
            POINTER(c_double),  #ng(z1<z<z2)
            POINTER(c_int64),  #flag_nu
            POINTER(c_int64),  #flag_tll
            POINTER(c_int64),  #nm
            POINTER(c_int64)  #nz
        ]
        self.fort_lib_cl.calc_cl_.restype = c_void_p

        # Calcualtion setup
        self.kmin = 1e-3
        self.kmax = 5.
        self.zmax = 4.  # should be consistent with fortran code
        self.nk_pk = 200
        self.nz_pk = 51

        # Class
        self.cosmo = Class()

    def get_tsz_cl(self, ell_arr, params, dndz, z1, z2, z1_ng, z2_ng, nm, nz):
        self.zmin = z1
        self.zmax = z2
        obh2 = params['obh2']
        och2 = params['och2']
        As = params['As']
        ns = params['ns']
        mnu = params['mnu']
        mass_bias = params['mass_bias']
        Mcut = params['Mcut']
        M1 = params['M1']
        kappa = params['kappa']
        sigma_Ncen = params['sigma_Ncen']
        alp_Nsat = params['alp_Nsat']
        rmax = params['rmax']
        rgs = params['rgs']
        flag_nu_logic = params['flag_nu']
        flag_tll_logic = params['flag_tll']
        if type(flag_nu_logic) != bool:
            print 'flag_nu must be boolean.'
            sys.exit()
        if flag_nu_logic:
            flag_nu = 1
        else:
            flag_nu = 0
        if type(flag_tll_logic) != bool:
            print 'flag_tll must be boolean.'
            sys.exit()
        if flag_tll_logic:
            flag_tll = 1
        else:
            flag_tll = 0

        if 'theta' in params.keys():
            theta = params['theta']
            pars = {'output':'mPk','100*theta_s':theta,
                    'omega_b':obh2,'omega_cdm':och2,
                    'A_s':As,'n_s':ns,\
                    'N_ur':0.00641,'N_ncdm':1,'m_ncdm':mnu/3.,\
                    'T_ncdm':0.71611,\
                    'P_k_max_h/Mpc': self.kmax,'z_max_pk':self.zmax,\
                    'deg_ncdm':3.}
            self.cosmo.set(pars)
            self.cosmo.compute()
            h0 = self.cosmo.h()
        elif 'h0' in params.keys():
            h0 = params['h0']
            pars = {'output':'mPk','h':h0,
                    'omega_b':obh2,'omega_cdm':och2,
                    'A_s':As,'n_s':ns,\
                    'N_ur':0.00641,'N_ncdm':1,'m_ncdm':mnu/3.,\
                    'T_ncdm':0.71611,\
                    'P_k_max_h/Mpc': self.kmax,'z_max_pk':self.zmax,\
                    'deg_ncdm':3.}
            self.cosmo.set(pars)
            self.cosmo.compute()

        # get matter power spectra
        kh_arr = np.logspace(np.log10(self.kmin), np.log10(self.kmax),
                             self.nk_pk)
        kh = np.zeros((self.nz_pk, self.nk_pk))
        pk = np.zeros((self.nz_pk, self.nk_pk))
        pk_zarr = np.linspace(self.zmin, self.zmax, self.nz_pk)
        for i in range(self.nz_pk):
            kh[i, :] = kh_arr
            if flag_nu == 0:
                pk[i, :] = np.array([
                    self.cosmo.pk(k * h0, pk_zarr[i]) * h0**3 for k in kh_arr
                ])
            elif flag_nu == 1:
                pk[i, :] = np.array([
                    self.cosmo.pk_cb(k * h0, pk_zarr[i]) * h0**3
                    for k in kh_arr
                ])

        # params
        h0_in = byref(c_double(h0))
        obh2_in = byref(c_double(obh2))
        och2_in = byref(c_double(och2))
        mnu_in = byref(c_double(mnu))
        mass_bias_in = byref(c_double(mass_bias))
        Mcut_in = byref(c_double(Mcut))
        M1_in = byref(c_double(M1))
        kappa_in = byref(c_double(kappa))
        sigma_Ncen_in = byref(c_double(sigma_Ncen))
        alp_Nsat_in = byref(c_double(alp_Nsat))
        rmax_in = byref(c_double(rmax))
        rgs_in = byref(c_double(rgs))
        flag_nu_in = byref(c_int64(flag_nu))
        flag_tll_in = byref(c_int64(flag_tll))

        # dNdz
        nz_dndz = byref(c_int64(len(dndz)))

        # integration setting
        z1_in = byref(c_double(self.zmin))
        z2_in = byref(c_double(self.zmax))

        # outputs
        nl = len(ell_arr)
        cl_gg = np.zeros((2, nl))
        cl_gy = np.zeros((2, nl))
        tll = np.zeros((nl * 2, nl * 2))
        ng = c_double(0.0)
        nl = c_int64(nl)

        self.fort_lib_cl.calc_cl_(
                h0_in, obh2_in, och2_in, mnu_in,\
                mass_bias_in, \
                Mcut_in, M1_in, kappa_in, sigma_Ncen_in, alp_Nsat_in,\
                rmax_in, rgs_in,\
                byref(c_int64(self.nk_pk)), byref(c_int64(self.nz_pk)),\
                np.array(kh),np.array(pk),\
                np.array(dndz),nz_dndz,\
                z1_in, z2_in,\
                byref(c_double(z1_ng)),byref(c_double(z2_ng)),\
                nl,np.array(ell_arr),\
                cl_gg,cl_gy,tll,ng,\
                flag_nu_in,flag_tll_in,\
                c_int64(nm), c_int64(nz)
                )

        self.cosmo.struct_cleanup()
        return cl_gg, cl_gy, tll, ng.value
Ejemplo n.º 33
0
 M.set({var_name: var})
 M.compute()
 #
 # get Cls
 #
 clM = M.lensed_cl(2500)
 ll = clM['ell'][2:]
 clTT = clM['tt'][2:]
 clEE = clM['ee'][2:]
 clPP = clM['pp'][2:]
 #
 # store P(k) for common k values
 #
 pkM = []
 for k in kvec:
     pkM.append(M.pk(k, 0.))
 #
 # plot P(k)
 #
 ax_Pk.loglog(kvec,
              np.array(pkM),
              color=var_color,
              alpha=var_alpha,
              linestyle='-')
 #
 # plot C_l^TT
 #
 ax_TT.semilogx(ll,
                clTT * ll * (ll + 1) / twopi,
                color=var_color,
                alpha=var_alpha,
Ejemplo n.º 34
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(cls):
        cls.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(cls.faulty_figs_path):
            shutil.rmtree(cls.faulty_figs_path)

        os.mkdir(cls.faulty_figs_path)

    @classmethod
    def tearDownClass(cls):
        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()

        if CLASS_VERBOSE:
            self.verbose = {
                'input_verbose': 1,
                'background_verbose': 1,
                'thermodynamics_verbose': 1,
                'perturbations_verbose': 1,
                'transfer_verbose': 1,
                'primordial_verbose': 1,
                'harmonic_verbose': 1,
                'fourier_verbose': 1,
                'lensing_verbose': 1,
                'distortions_verbose': 1,
                'output_verbose': 1,
            }
        else:
            self.verbose = {}
        self.scenario = {}

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

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

    @parameterized.expand(TUPLE_ARRAY,
                          doc_func=custom_name_func,
                          custom_name_func=custom_name_func)
    @attr('dump_ini_files')
    def test_Valgrind(self, inputdict):
        """Dump files"""
        self.scenario.update(inputdict)
        self.name = self._testMethodName
        if self.has_incompatible_input():
            return
        path = os.path.join(self.faulty_figs_path, self.name)
        self.store_ini_file(path)
        self.scenario.update({'gauge': 'Newtonian'})
        self.store_ini_file(path + 'N')

    @parameterized.expand(TUPLE_ARRAY,
                          doc_func=custom_name_func,
                          custom_name_func=custom_name_func)
    @attr('test_scenario')
    def test_scenario(self, inputdict):
        """Test scenario"""
        self.scenario.update(inputdict)
        self.name = self._testMethodName
        self.cosmo.set(
            dict(itertools.chain(self.verbose.items(), self.scenario.items())))

        cl_dict = {
            'tCl': ['tt'],
            'lCl': ['pp'],
            'pCl': ['ee', 'bb'],
            'nCl': ['dd'],
            'sCl': ['ll'],
        }

        # 'lensing' is always set to yes. Therefore, trying to compute 'tCl' or
        # 'pCl' will fail except if we also ask for 'lCl'.
        if self.has_incompatible_input():
            self.assertRaises(CosmoSevereError, self.cosmo.compute)
            return
        else:
            self.cosmo.compute()

        self.assertTrue(self.cosmo.state,
                        "Class failed to go through all __init__ methods")
        # 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]:
                        is_density_cl = (elem == 'nCl' or elem == 'sCl')
                        if is_density_cl:
                            cl = self.cosmo.density_cl(100)
                        else:
                            cl = self.cosmo.raw_cl(100)
                        self.assertIsNotNone(cl, "raw_cl returned nothing")
                        cl_length = np.shape(
                            cl[cl_type][0])[0] if is_density_cl else np.shape(
                                cl[cl_type])[0]
                        self.assertEqual(cl_length, 101,
                                         "raw_cl returned wrong size")
                if elem == 'mPk':
                    pk = self.cosmo.pk(0.1, 0)
                    self.assertIsNotNone(pk, "pk returned nothing")
            # Negative tests of output functions
            if not any(
                [elem in list(cl_dict.keys()) for elem in output.split()]):
                # testing absence of any Cl
                self.assertRaises(CosmoSevereError, self.cosmo.raw_cl, 100)
            if 'mPk' not in output.split():
                # testing absence of mPk
                self.assertRaises(CosmoSevereError, self.cosmo.pk, 0.1, 0)

        if COMPARE_OUTPUT_REF or COMPARE_OUTPUT_GAUGE:
            # Now compute same scenario in Newtonian gauge
            self.cosmo_newt.set(
                dict(list(self.verbose.items()) + list(self.scenario.items())))
            self.cosmo_newt.set({'gauge': 'newtonian'})
            self.cosmo_newt.compute()

        if COMPARE_OUTPUT_GAUGE:
            # Compare synchronous and Newtonian gauge
            self.assertTrue(
                self.cosmo_newt.state,
                "Class failed to go through all __init__ methods in Newtonian gauge"
            )

            self.compare_output(self.cosmo, "Synchronous", self.cosmo_newt,
                                'Newtonian', COMPARE_CL_RELATIVE_ERROR_GAUGE,
                                COMPARE_PK_RELATIVE_ERROR_GAUGE)

        if COMPARE_OUTPUT_REF:
            # Compute reference models in both gauges and compare
            cosmo_ref = classyref.Class()
            cosmo_ref.set(self.cosmo.pars)
            cosmo_ref.compute()
            status = self.compare_output(cosmo_ref, "Reference", self.cosmo,
                                         'Synchronous',
                                         COMPARE_CL_RELATIVE_ERROR,
                                         COMPARE_PK_RELATIVE_ERROR)
            assert status, 'Reference comparison failed in Synchronous gauge!'

            cosmo_ref = classyref.Class()
            cosmo_ref.set(self.cosmo_newt.pars)
            cosmo_ref.compute()
            self.compare_output(cosmo_ref, "Reference", self.cosmo_newt,
                                'Newtonian', COMPARE_CL_RELATIVE_ERROR,
                                COMPARE_PK_RELATIVE_ERROR)
            assert status, 'Reference comparison failed in Newtonian gauge!'

    def has_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 list(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 list(self.scenario.keys()):
            if 'output' not in list(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 list(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 list(self.scenario.keys()):
            if 'output' not in list(self.scenario.keys()):
                should_fail = True

        # If we ask for Cl's of lensing potential, number counts or cosmic shear, we must have scalar modes.
        # The same applies to density and velocity transfer functions and the matter power spectrum:
        if 'output' in self.scenario and 'modes' in self.scenario and self.scenario[
                'modes'].find('s') == -1:
            requested_output_types = set(self.scenario['output'].split())
            for scalar_output_type in [
                    'lCl', 'nCl', 'dCl', 'sCl', 'mPk', 'dTk', 'mTk', 'vTk'
            ]:
                if scalar_output_type in requested_output_types:
                    should_fail = True
                    break

        # If we specify initial conditions (for scalar modes), we must have
        # perturbations and scalar modes.
        if 'ic' in list(self.scenario.keys()):
            if 'modes' in list(self.scenario.keys()
                               ) and self.scenario['modes'].find('s') == -1:
                should_fail = True
            if 'output' not in list(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 list(self.scenario.keys(
        )) and self.scenario['P_k_ini type'].find('inflation') != -1:
            if 'modes' not in list(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 list(self.scenario.keys()
                            ) and self.scenario['ic'].find('i') != -1:
                should_fail = True

        return should_fail

    def compare_output(self, reference, reference_name, candidate,
                       candidate_name, rtol_cl, rtol_pk):
        status_pass = True
        for elem in ['raw_cl', 'lensed_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 list(ref.items()):
                if key != 'ell':
                    # 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 list(value.keys()):
                                try:
                                    np.testing.assert_allclose(
                                        value[subkey],
                                        to_test[key][subkey],
                                        rtol=rtol_cl,
                                        atol=COMPARE_CL_ABSOLUTE_ERROR)
                                except AssertionError:
                                    self.cl_faulty_plot(
                                        elem + "_" + key, value[subkey][2:],
                                        reference_name,
                                        to_test[key][subkey][2:],
                                        candidate_name, rtol_cl)
                                except TypeError:
                                    self.cl_faulty_plot(
                                        elem + "_" + key, value[subkey][2:],
                                        reference_name,
                                        to_test[key][subkey][2:],
                                        candidate_name, rtol_cl)
                        else:
                            try:
                                np.testing.assert_allclose(
                                    value,
                                    to_test[key],
                                    rtol=rtol_cl,
                                    atol=COMPARE_CL_ABSOLUTE_ERROR)
                            except (AssertionError, TypeError) as e:
                                self.cl_faulty_plot(elem + "_" + key,
                                                    value[2:], reference_name,
                                                    to_test[key][2:],
                                                    candidate_name, rtol_cl)
                                status_pass = False
                    # 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:],
                                                reference_name,
                                                to_test[key][2:],
                                                candidate_name, rtol_cl)
                            status_pass = False

        if 'output' in list(self.scenario.keys()):
            if self.scenario['output'].find('mPk') != -1:
                # testing equality of Pk
                k = np.logspace(-2, log10(self.scenario['P_k_max_1/Mpc']), 50)
                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=rtol_pk,
                                               atol=COMPARE_PK_ABSOLUTE_ERROR)
                except AssertionError:
                    self.pk_faulty_plot(k, reference_pk, reference_name,
                                        candidate_pk, candidate_name, rtol_pk)
                    status_pass = False

        return status_pass

    def store_ini_file(self, path):
        parameters = dict(
            list(self.verbose.items()) + list(self.scenario.items()))
        with open(path + '.ini', 'w') as param_file:
            param_file.write('# ' + str(parameters) + '\n')
            if len(parameters) == 0:
                # CLASS complains if the .ini file does not do anything.
                param_file.write('write warnings = yes\n')
            for key, value in list(parameters.items()):
                param_file.write(key + " = " + str(value) + '\n')

    def cl_faulty_plot(self, cl_type, reference, reference_name, candidate,
                       candidate_name, rtol):
        path = os.path.join(self.faulty_figs_path, self.name)
        fig, axes = plt.subplots(2, 1, sharex=True)
        ell = np.arange(max(np.shape(candidate))) + 2
        factor = ell * (ell + 1) / (2 *
                                    np.pi) if cl_type[-2:] != 'pp' else ell**5
        axes[0].plot(ell, factor * reference, label=reference_name)
        axes[0].plot(ell, factor * candidate, label=candidate_name)
        axes[1].semilogy(ell,
                         100 * abs(candidate / reference - 1),
                         label=cl_type)
        axes[1].axhline(y=100 * rtol, color='k', ls='--')

        axes[-1].set_xlabel(r'$\ell$')
        if cl_type[-2:] == 'pp':
            axes[0].set_ylabel(r'$\ell^5 C_\ell^\mathrm{{{_cl_type}}}$'.format(
                _cl_type=cl_type[-2:].upper()))
        else:
            axes[0].set_ylabel(
                r'$\ell(\ell + 1)/(2\pi)C_\ell^\mathrm{{{_cl_type}}}$'.format(
                    _cl_type=cl_type[-2:].upper()))
        axes[1].set_ylabel('Relative error [%]')

        for ax in axes:
            ax.legend(loc='upper right')

        fig.tight_layout()
        fname = '{}_{}_{}_vs_{}.pdf'.format(path, cl_type, reference_name,
                                            candidate_name)
        fig.savefig(fname, bbox_inches='tight')
        plt.close(fig)

        # Store parameters (contained in self.scenario) to text file
        self.store_ini_file(path)

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

        fig, axes = plt.subplots(2, 1, sharex=True)
        axes[0].loglog(k, k**1.5 * reference, label=reference_name)
        axes[0].loglog(k, k**1.5 * candidate, label=candidate_name)
        axes[0].legend(loc='upper right')

        axes[1].loglog(k, 100 * np.abs(candidate / reference - 1))
        axes[1].axhline(y=100 * rtol, color='k', ls='--')

        axes[-1].set_xlabel(r'$k\quad [\mathrm{Mpc}^{-1}]$')
        axes[0].set_ylabel(r'$k^\frac{3}{2}P(k)$')
        axes[1].set_ylabel(r'Relative error [%]')

        fig.tight_layout()
        fname = path + '_pk_{}_vs_{}.pdf'.format(reference_name,
                                                 candidate_name)
        fig.savefig(fname, bbox_inches='tight')
        plt.close(fig)

        # Store parameters (contained in self.scenario) to text file
        self.store_ini_file(path)
Ejemplo n.º 35
0

# In[ ]:

plt.savefig('warmup_cltt.pdf')


# In[ ]:

# get P(k) at redhsift z=0
import numpy as np
kk = np.logspace(-4,np.log10(3),1000) # k in h/Mpc
Pk = [] # P(k) in (Mpc/h)**3
h = LambdaCDM.h() # get reduced Hubble for conversions to 1/Mpc
for k in kk:
    Pk.append(LambdaCDM.pk(k*h,0.)*h**3) # function .pk(k,z)


# In[ ]:

# plot P(k)
plt.figure(2)
plt.xscale('log');plt.yscale('log');plt.xlim(kk[0],kk[-1])
plt.xlabel(r'$k \,\,\,\, [h/\mathrm{Mpc}]$')
plt.ylabel(r'$P(k) \,\,\,\, [\mathrm{Mpc}/h]^3$')
plt.plot(kk,Pk,'b-')


# In[ ]:

plt.savefig('warmup_pk.pdf')
Ejemplo n.º 36
0
print(cl_gg_tmp)
print((cl_gg - cl_gg_tmp) / cl_gg)
plt.plot(ells, cl_gg)
plt.plot(ells, cl_gg_tmp)
plt.xscale('log')
plt.yscale('log')
plt.show()
quit()

for i in range(7):
    z_test = z_templates['ztmp%d' % i]
    NL = ccl.nonlin_matter_power(cosmo_ccl, ks * h, a=1. / (1 + z_test))
    print(z_test, h)

    class_ks = np.logspace(-5, np.log10(1), 1000)
    class_pk = np.array([class_cosmo.pk(ki, z_test) for ki in class_ks])
    lk = Pk_a_ij['lk_arr']
    Pk = Pk_a_ij['1_1'][i, :]

    plt.figure(i + 1)
    '''
    plt.semilogy(lk, NL, label="CCL")
    plt.semilogy(lk, Pk, label="N-body")
    plt.plot(lk, np.interp(lk, np.log(class_ks), class_pk), label="CLASS")
    '''
    plt.plot(lk, np.ones(len(lk)), 'k--')
    plt.plot(lk, Pk / NL, label="N-body/CCL")
    try:
        Pk_11 = np.load("Pk_11_" + par + "_ztmp%d.npy" % i) / h**3
        plt.plot(lk, Pk_11 / NL, label="N-body der/CCL")
    except:
Ejemplo n.º 37
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()