Example #1
0
def zaemulate(disp, z_ic, z_late, cosmo):
    '''
    Make a Zel'dovich-evolved catalog at late times. 
    Input:
        -disp: displacement field computed from 'makemesh'
        -z_ic: initial redshift
        -z_late: final redshift
        -cosmo: pyCCL cosmology used to compute growth factors
    Output:
        -flatgrid: catalog of positions for files
    '''

    #Get box size and particle number from the displacement
    Lbox = disp[0].BoxSize[0]
    nmesh = disp[0].Nmesh[0]

    #Coordinates to place down the IC particles
    coord = np.linspace(0, Lbox, nmesh + 1)[:-1]
    xx, yy, zz = np.meshgrid(coord, coord, coord, indexing='ij')
    flatgrid = np.stack([xx, yy, zz])

    growthratio = pyccl.growth_factor(cosmo, 1. /
                                      (1 + z_late)) / pyccl.growth_factor(
                                          cosmo, 1. / (1 + z_ic))

    #ZAemulate them to z_late
    for i in range(3):
        flatgrid[i] += disp[i] * growthratio
    flatgrid = flatgrid % Lbox

    #Reshape to catalog
    flatgrid = flatgrid.reshape(3, nmesh**3)

    return flatgrid
Example #2
0
def test_power_sigma8norm_norms_consistent(tf):
    # make a cosmo with A_s
    cosmo = ccl.Cosmology(Omega_c=0.27,
                          Omega_b=0.045,
                          h=0.67,
                          A_s=2e-9,
                          n_s=0.96,
                          transfer_function=tf)
    sigma8 = ccl.sigma8(cosmo)

    # remake same but now give sigma8
    cosmo_s8 = ccl.Cosmology(Omega_c=0.27,
                             Omega_b=0.045,
                             h=0.67,
                             sigma8=sigma8,
                             n_s=0.96,
                             transfer_function=tf)

    # make sure they come out the same-ish
    assert np.allclose(ccl.sigma8(cosmo), ccl.sigma8(cosmo_s8))

    # and that the power spectra look right
    a = 0.8
    gfac = (ccl.growth_factor(cosmo, a) / ccl.growth_factor(cosmo_s8, a))**2
    pk_rat = (ccl.linear_matter_power(cosmo, 1e-4, a) /
              ccl.linear_matter_power(cosmo_s8, 1e-4, a))
    assert np.allclose(pk_rat, gfac)
def test_power_mu_sigma_sigma8norm(tf):
    cosmo = ccl.Cosmology(
        Omega_c=0.27, Omega_b=0.045, h=0.67, sigma8=0.8, n_s=0.96,
        transfer_function=tf)

    cosmo_musig = ccl.Cosmology(
        Omega_c=0.27, Omega_b=0.045, h=0.67, sigma8=0.8, n_s=0.96,
        transfer_function=tf, mu_0=0.1, sigma_0=0.2)

    # make sure sigma8 is correct
    assert np.allclose(ccl.sigma8(cosmo_musig), 0.8)

    if tf != 'boltzmann_isitgr':
        # make sure P(k) ratio is right
        a = 0.8
        gfac = (
            ccl.growth_factor(cosmo, a) / ccl.growth_factor(cosmo_musig, a))**2
        pk_rat = (
            ccl.linear_matter_power(cosmo, 1e-4, a) /
            ccl.linear_matter_power(cosmo_musig, 1e-4, a))
        assert np.allclose(pk_rat, gfac)

    with mock.patch.dict(sys.modules, {'isitgr': None}):
        with assert_raises(ImportError):
            get_isitgr_pk_lin(cosmo)
    # Importing ccl without isitgr is fine.  No ImportError triggered.
    with mock.patch.dict(sys.modules, {'isitgr': None}):
        reload(ccl.boltzmann)
Example #4
0
def test_mgrowth():
    """
    Compare the modified growth function computed by CCL against the exact 
    result for a particular modification of the growth rate.
    """
    # Define differential growth rate arrays
    nz_mg = 128
    z_mg = np.zeros(nz_mg)
    df_mg = np.zeros(nz_mg)
    for i in range(0, nz_mg):
        z_mg[i] = 4. * (i + 0.0) / (nz_mg - 1.)
        df_mg[i] = 0.1 / (1. + z_mg[i])

    # Define two test cosmologies, without and with modified growth respectively
    p1 = ccl.Parameters(Omega_c=0.25,
                        Omega_b=0.05,
                        Omega_k=0.,
                        N_nu_rel=0.,
                        N_nu_mass=0.,
                        m_nu=0.,
                        w0=-1.,
                        wa=0.,
                        h=0.7,
                        A_s=2.1e-9,
                        n_s=0.96)
    p2 = ccl.Parameters(Omega_c=0.25,
                        Omega_b=0.05,
                        Omega_k=0.,
                        N_nu_rel=0.,
                        N_nu_mass=0.,
                        m_nu=0.,
                        w0=-1.,
                        wa=0.,
                        h=0.7,
                        A_s=2.1e-9,
                        n_s=0.96,
                        z_mg=z_mg,
                        df_mg=df_mg)
    cosmo1 = ccl.Cosmology(p1)
    cosmo2 = ccl.Cosmology(p2)

    # We have included a growth modification \delta f = K*a, with K==0.1
    # (arbitrarily). This case has an analytic solution, given by
    # D(a) = D_0(a)*exp(K*(a-1)). Here we compare the growth computed by CCL
    # with the analytic solution.
    a = 1. / (1. + z_mg)

    d1 = ccl.growth_factor(cosmo1, a)
    d2 = ccl.growth_factor(cosmo2, a)
    f1 = ccl.growth_rate(cosmo1, a)
    f2 = ccl.growth_rate(cosmo2, a)

    f2r = f1 + 0.1 * a
    d2r = d1 * np.exp(0.1 * (a - 1.))

    # Check that ratio of calculated and analytic results is within tolerance
    assert_allclose(d2r / d2, np.ones(d2.size), rtol=GROWTH_TOLERANCE)
    assert_allclose(f2r / f2, np.ones(f2.size), rtol=GROWTH_TOLERANCE)
Example #5
0
def plot_model(ax, CBase, C, fmt, name):
    zar = np.linspace(0, 2.5, 100)
    aar = 1 / (1 + zar)
    f = ccl.growth_rate(C, aar)
    s8 = ccl.sigma8(C) * ccl.growth_factor(C, aar)

    f0 = ccl.growth_rate(CBase, aar)
    s80 = ccl.sigma8(CBase) * ccl.growth_factor(CBase, aar)

    ax.plot(zar, (f * s8) / (f0 * s80), fmt, label=name)
    return interp1d(zar, (s80 * f0))
Example #6
0
def check_background(cosmo):
    """
    Check that background and growth functions can be run.
    """
    # Types of scale factor input (scalar, list, array)
    a_scl = 0.5
    a_lst = [0.2, 0.4, 0.6, 0.8, 1.]
    a_arr = np.linspace(0.2, 1., 5)
    
    # growth_factor
    assert_( all_finite(ccl.growth_factor(cosmo, a_scl)) )
    assert_( all_finite(ccl.growth_factor(cosmo, a_lst)) )
    assert_( all_finite(ccl.growth_factor(cosmo, a_arr)) )
    
    # growth_factor_unnorm
    assert_( all_finite(ccl.growth_factor_unnorm(cosmo, a_scl)) )
    assert_( all_finite(ccl.growth_factor_unnorm(cosmo, a_lst)) )
    assert_( all_finite(ccl.growth_factor_unnorm(cosmo, a_arr)) )
    
    # growth_rate
    assert_( all_finite(ccl.growth_rate(cosmo, a_scl)) )
    assert_( all_finite(ccl.growth_rate(cosmo, a_lst)) )
    assert_( all_finite(ccl.growth_rate(cosmo, a_arr)) )
    
    # comoving_radial_distance
    assert_( all_finite(ccl.comoving_radial_distance(cosmo, a_scl)) )
    assert_( all_finite(ccl.comoving_radial_distance(cosmo, a_lst)) )
    assert_( all_finite(ccl.comoving_radial_distance(cosmo, a_arr)) )
    
    # h_over_h0
    assert_( all_finite(ccl.h_over_h0(cosmo, a_scl)) )
    assert_( all_finite(ccl.h_over_h0(cosmo, a_lst)) )
    assert_( all_finite(ccl.h_over_h0(cosmo, a_arr)) )
    
    # luminosity_distance
    assert_( all_finite(ccl.luminosity_distance(cosmo, a_scl)) )
    assert_( all_finite(ccl.luminosity_distance(cosmo, a_lst)) )
    assert_( all_finite(ccl.luminosity_distance(cosmo, a_arr)) )
    
    # scale_factor_of_chi
    assert_( all_finite(ccl.scale_factor_of_chi(cosmo, a_scl)) )
    assert_( all_finite(ccl.scale_factor_of_chi(cosmo, a_lst)) )
    assert_( all_finite(ccl.scale_factor_of_chi(cosmo, a_arr)) )
    
    # omega_m_a
    assert_( all_finite(ccl.omega_x(cosmo, a_scl, 'matter')) )
    assert_( all_finite(ccl.omega_x(cosmo, a_lst, 'matter')) )
    assert_( all_finite(ccl.omega_x(cosmo, a_arr, 'matter')) )
Example #7
0
def test_growth():
    # We first define equivalent CCL and jax_cosmo cosmologies
    cosmo_ccl = ccl.Cosmology(
        Omega_c=0.3,
        Omega_b=0.05,
        h=0.7,
        sigma8=0.8,
        n_s=0.96,
        Neff=0,
        transfer_function="eisenstein_hu",
        matter_power_spectrum="linear",
    )

    cosmo_jax = Cosmology(
        Omega_c=0.3,
        Omega_b=0.05,
        h=0.7,
        sigma8=0.8,
        n_s=0.96,
        Omega_k=0.0,
        w0=-1.0,
        wa=0.0,
    )

    # Test array of scale factors
    a = np.linspace(0.01, 1.0)

    gccl = ccl.growth_factor(cosmo_ccl, a)
    gjax = bkgrd.growth_factor(cosmo_jax, a)

    assert_allclose(gccl, gjax, rtol=1e-2)
Example #8
0
def compute_covmat_cv(cosmo, zm, dndz):
    # Area COSMOS
    area_deg2 = 1.7
    area_rad2 = area_deg2 * (np.pi / 180)**2
    theta_rad = np.sqrt(area_rad2 / np.pi)
    # TODO: Where do we get the area

    # Bin widths
    dz = np.mean(zm[1:] - zm[:-1])
    # Number of galaxies in each bin
    dn = dndz * dz
    # z bin edges
    zb = np.append((zm - dz / 2.), zm[-1] + dz / 2.)

    # Comoving distance to bin edges
    chis = ccl.comoving_radial_distance(cosmo, 1. / (1 + zb))
    # Mean comoving distance in each bin
    chi_m = 0.5 * (chis[1:] + chis[:-1])
    # Comoving distance width
    dchi = chis[1:] - chis[:-1]
    # Disc radii
    R_m = theta_rad * chi_m
    # Galaxy bias
    b_m = 0.95 / ccl.growth_factor(cosmo, 1. / (1 + zm))
    # Growth rate (for RSDs)
    f_m = ccl.growth_rate(cosmo, 1. / (1 + zm))
    # Transverse k bins
    n_kt = 512
    # Parallel k bins
    n_kp = 512

    plt.plot(zm, dn, 'b-')
    plt.savefig('N_z.png')
    plt.close()

    # Transverse modes
    kt_arr = np.geomspace(0.00005, 10., n_kt)
    # Parallel modes
    kp_arr = np.geomspace(0.00005, 10., n_kp)
    # Total wavenumber
    k_arr = np.sqrt(kt_arr[None, :]**2 + kp_arr[:, None]**2)
    # B.H. changed a to float(a)
    pk_arr = np.array([(b+f*kp_arr[:,None]**2/k_arr**2)**2*
                     ccl.nonlin_matter_power(cosmo,k_arr.flatten(),float(a)).reshape([n_kp,n_kt])\
                     for a,b,f in zip(1./(1+zm),b_m,f_m)])


    window = np.array([2*jv(1,kt_arr[None,:]*R)/(kt_arr[None,:]*R)*np.sin(0.5*kp_arr[:,None]*dc)/\
                     (0.5*kp_arr[:,None]*dc) for R,dc in zip(R_m,dchi)])

    # Estimating covariance matrix
    # avoiding getting 0s in covariance
    eps = 0.0
    # Changed from dn to dndz B.H. and A.S. TODO: Check
    print("covmat_cv...")
    covmat_cv  =  np.array([[(ni+eps)*(nj+eps)*covar(i,j,window,pk_arr,chi_m,kp_arr,kt_arr) \
                             for i,ni in enumerate(dndz)] \
                            for j,nj in enumerate(dndz)])
    return covmat_cv
Example #9
0
    def get_log_prob(self, theta):
        # Check the priors
        log_prior = self.get_log_prior(theta)
        if not np.isfinite(log_prior):
            return -np.inf

        # Update default cosmological parameters with new sampled parameters
        params = self.cosmology_params.copy()
        for param_name in self.arg_names:
            if param_name in params:
                params[param_name] = theta[self.arg_names.index(param_name)]
        cosmo = ccl.Cosmology(**params)

        # Update data parameters
        z_tail = theta[self.arg_names.index(
            'z_tail')] if 'z_tail' in self.arg_names else self.z_tail
        bias = theta[self.arg_names.index(
            'bias')] if 'bias' in self.arg_names else self.bias

        # Get redshift distribution
        z_arr, n_arr = get_lotss_redshift_distribution(z_tail=z_tail)
        bias_arr = bias * np.ones(len(z_arr))
        bias_arr = bias_arr / ccl.growth_factor(cosmo, 1. / (1 + z_arr))

        # Get correlations
        number_counts_tracer = ccl.NumberCountsTracer(cosmo,
                                                      has_rsd=False,
                                                      dndz=(z_arr, n_arr),
                                                      bias=(z_arr, bias_arr))
        cmb_lensing_tracer = ccl.CMBLensingTracer(cosmo, 1091)
        correlations = {}
        if 'gg' in self.correlation_symbols:
            correlations['gg'] = ccl.angular_cl(cosmo, number_counts_tracer,
                                                number_counts_tracer,
                                                self.l_arr)
        if 'gk' in self.correlation_symbols:
            correlations['gk'] = ccl.angular_cl(cosmo, number_counts_tracer,
                                                cmb_lensing_tracer, self.l_arr)

        # Bin spectra using coupling matrices in workspaces
        for correlation_symbol in self.correlation_symbols:
            correlations[correlation_symbol] = decouple_correlation(
                self.workspaces[correlation_symbol],
                correlations[correlation_symbol])

        # Calculate log prob
        model = np.concatenate([
            correlations[correlation_symbol][:self.n_ells[correlation_symbol]]
            for correlation_symbol in self.correlation_symbols
        ])
        diff = self.data_vector - model
        log_prob = log_prior - np.dot(
            diff, np.dot(self.inverted_covariance, diff)) / 2.0

        return log_prob
Example #10
0
def make_component_weights(icdeltalin, cosmo, z_ic, z_late):
    '''
    Make the component fields so you get weights later on.
    Input:
        icdeltalin: **NOISELESS** linear fields of your simulation
        growthratio: ratio of growthfactors between z_late and z_ic
    Output:
        linfield: linear noiseless density
        delta2: squared density field
        s2: tidal field squared
        gradsqdelta: laplacian of the density
    Notes:
        gradsqdelta currently not implemented
    '''
    Lbox = icdeltalin.BoxSize[0]
    nmesh = icdeltalin.Nmesh[0]

    growthratio = pyccl.growth_factor(cosmo, 1. /
                                      (1 + z_late)) / pyccl.growth_factor(
                                          cosmo, 1. / (1 + z_ic))

    delta = growthratio * icdeltalin

    #Start with tidal field due to memory requirements
    linfield = fftw.byte_align(icdeltalin.value, dtype='float32')

    field_fft = fftw.interfaces.numpy_fft.rfftn(linfield, threads=-1)

    linfield = ArrayMesh(linfield, BoxSize=Lbox).to_real_field()

    tidesq = delta_to_tidesq(field_fft, nmesh=nmesh, lbox=Lbox)
    s2 = tidesq - tidesq.cmean()

    del field_fft
    gc.collect()

    #Make the squared density field
    sqfield = delta**2

    delta2 = sqfield - sqfield.cmean()

    return linfield, delta2, s2
Example #11
0
def test_power_mu_sigma_sigma8norm(tf):
    cosmo = ccl.Cosmology(
        Omega_c=0.27, Omega_b=0.045, h=0.67, sigma8=0.8, n_s=0.96,
        transfer_function=tf)

    cosmo_musig = ccl.Cosmology(
        Omega_c=0.27, Omega_b=0.045, h=0.67, sigma8=0.8, n_s=0.96,
        transfer_function=tf, mu_0=0.1, sigma_0=0.2)

    # make sure sigma8 is correct
    assert np.allclose(ccl.sigma8(cosmo_musig), 0.8)

    # make sure P(k) ratio is right
    a = 0.8
    gfac = (
        ccl.growth_factor(cosmo, a) / ccl.growth_factor(cosmo_musig, a))**2
    pk_rat = (
        ccl.linear_matter_power(cosmo, 1e-4, a) /
        ccl.linear_matter_power(cosmo_musig, 1e-4, a))
    assert np.allclose(pk_rat, gfac)
Example #12
0
def LSSTSpecParams(C):
    biasfunc = lambda z: 0.95 / ccl.growth_factor(C, 1 / (1 + z))
    ndens = 49  ## per /arcmin^2, LSST SRD, page 47
    dndz = lambda z: z**2 * np.exp(-(z / 0.28)**0.94)  ## LSST SRD, page 47
    arcminfsky = 1 / (4 * np.pi / (np.pi / (180 * 60))**2)
    ## volume between z=3
    zmax = 3
    V = 4 * np.pi**3 / 3 * ccl.comoving_radial_distance(C, 1 / (1 + zmax))**3
    dVdz = lambda z: 3e3 / C['h'] * 1 / ccl.h_over_h0(C, 1 / (
        1 + z)) * 4 * np.pi * ccl.comoving_radial_distance(C, 1 / (1 + z))**2
    norm = ndens / (quad(dndz, 0, zmax)[0] * arcminfsky)
    nbarofz = lambda z: norm * dndz(z) / dVdz(z)
    return biasfunc, nbarofz, 0, 3, None
Example #13
0
def summon_bz(N_tomo, z_s_cents_theo, z_s_cents):
    # 6 standard cosmological parameters
    Omb = 0.0493
    Omk = 0.0
    s8 = 0.8111
    h = 0.6736
    n_s = 0.9649
    Omc = 0.264

    N_zsamples_theo = len(z_s_cents_theo)
    N_zsamples = len(z_s_cents)

    # Setting the cosmology
    FID_COSMO_PARAMS = {
        'Omega_b': Omb,
        'Omega_k': Omk,
        'sigma8': s8,
        'h': h,
        'n_s': n_s,
        'Omega_c': Omc,
        'transfer_function': 'boltzmann_class',
        'matter_power_spectrum': 'halofit',
        'mass_function': 'tinker10'
    }
    cosmo_fid = ccl.Cosmology(**FID_COSMO_PARAMS)

    # load biases
    a_s_cents_theo = 1. / (1. + z_s_cents_theo)
    b_zsamples_theo = 0.95 / ccl.growth_factor(cosmo_fid, a_s_cents_theo)

    # create the matrix
    bz_data_theo = np.repeat(b_zsamples_theo.reshape(1, N_zsamples_theo),
                             N_tomo,
                             axis=0)
    bz_data = np.zeros((N_tomo, N_zsamples))

    for i in range(N_tomo):
        bz_data_theo[
            i, :] += 0  #.2*np.random.randn(N_zsamples_theo) # TESTING MAKES A HUGE DIFFERENCE IF VARYING DNDZ only
        # can go down to 0.01 for 7 7 dndz only no reg and 1.6 for 7 20 dndz only D1+D2 or no reg (but f***s up)
        # interpolating to nearest to pass to code
        f = interp1d(np.append(z_s_cents_theo,np.array([z_s_cents[0],z_s_cents[-1]])),\
            np.append(bz_data_theo[i,:],np.array([bz_data_theo[i,0],bz_data_theo[i,-1]])),\
            kind='nearest',bounds_error=0,fill_value=0.)

        b_zsamples = f(z_s_cents)
        bz_data[i, :] = b_zsamples

    return bz_data_theo, bz_data, cosmo_fid
Example #14
0
def DESIParams(C):
    ### the following snippet stolen from PkSNR.py in unimap
    ## cut start
    h = C['h']
    z, _, _, _, _, _, V, nelg, nlrg, nqso, _, _ = np.loadtxt('desi.dat',
                                                             unpack=True)
    V *= 1e9  ## to (Gpc/h)^3
    nelg *= 0.1 * 14e3 / V  ## now in num/(Mpc/h)^3, 0.1 for dz=0.1
    nlrg *= 0.1 * 14e3 / V
    nqso *= 0.1 * 14e3 / V
    belg = 0.84 / ccl.growth_factor(C, 1. / (1. + z))
    blrg = 1.7 / ccl.growth_factor(C, 1. / (1. + z))
    bqso = 1.2 / ccl.growth_factor(C, 1. / (1. + z))
    ## --- cut end
    ### let's use ELGs
    biasfunc = interp1d(z, belg, bounds_error=False, fill_value='extrapolate')
    nbarfunc = interp1d(z,
                        nelg * h**3,
                        bounds_error=False,
                        fill_value='extrapolate')
    Ptfunc = None
    zmin = 0.1
    zmax = 1.8
    return biasfunc, nbarfunc, zmin, zmax, Ptfunc
Example #15
0
def test_iswcl():
    # Cosmology
    Ob = 0.05
    Oc = 0.25
    h = 0.7
    COSMO = ccl.Cosmology(Omega_b=Ob,
                          Omega_c=Oc,
                          h=h,
                          n_s=0.96,
                          sigma8=0.8,
                          transfer_function='bbks')

    # CCL calculation
    ls = np.arange(2, 100)
    zs = np.linspace(0, 0.6, 256)
    nz = np.exp(-0.5 * ((zs - 0.3) / 0.05)**2)
    bz = np.ones_like(zs)
    tr_n = ccl.NumberCountsTracer(COSMO,
                                  has_rsd=False,
                                  dndz=(zs, nz),
                                  bias=(zs, bz))
    tr_i = ccl.ISWTracer(COSMO)
    cl = ccl.angular_cl(COSMO, tr_n, tr_i, ls)

    # Benchmark from Eq. 6 in 1710.03238
    pz = nz / simps(nz, x=zs)
    H0 = h / ccl.physical_constants.CLIGHT_HMPC
    # Prefactor
    prefac = 3 * COSMO['T_CMB'] * (Oc + Ob) * H0**3 / (ls + 0.5)**2
    # H(z)/H0
    ez = ccl.h_over_h0(COSMO, 1. / (1 + zs))
    # Linear growth and derivative
    dz = ccl.growth_factor(COSMO, 1. / (1 + zs))
    gz = np.gradient(dz * (1 + zs), zs[1] - zs[0]) / dz
    # Comoving distance
    chi = ccl.comoving_radial_distance(COSMO, 1 / (1 + zs))
    # P(k)
    pks = np.array([
        ccl.nonlin_matter_power(COSMO, (ls + 0.5) / (c + 1E-6), 1. / (1 + z))
        for c, z in zip(chi, zs)
    ]).T
    # Limber integral
    cl_int = pks[:, :] * (pz * ez * gz)[None, :]
    clbb = simps(cl_int, x=zs)
    clbb *= prefac

    assert np.all(np.fabs(cl / clbb - 1) < 1E-3)
Example #16
0
def ICpk(cosmo, z_ic):
    '''
    Compute the linear theory P(k) at the redshift of initial conditions
    Input:
        -cosmo: cosmological parameters
        -z_ic: initial conditions redshift
    Output:
        -fpk: power spectrum function that takes k in units of h/Mpc
    '''
    k = np.logspace(-5, 2.3, 1000)

    #CCL uses units if 1/Mpc not h/Mpc so we have to convert things
    pk = pyccl.linear_matter_power(cosmo, k * cosmo['h'], 1) * (cosmo['h'])**3
    D = pyccl.growth_factor(cosmo, 1. / (1 + z_ic))
    fpk = interp1d(k, pk * D**2)

    return fpk
Example #17
0
    def apply(self, cosmo, params, source):
        """Apply a linear alignment systematic.

        Parameters
        ----------
        cosmo : pyccl.Cosmology
            A pyccl.Cosmology object.
        params : dict
            A dictionary mapping parameter names to their current values.
        source : a source object
            The source to which apply the shear bias.
        """
        pref = (((1.0 + source.z_) /
                 (1.0 + params[self.z_piv]))**params[self.alphaz])
        pref *= ccl.growth_factor(cosmo,
                                  1.0 / (1.0 + source.z_))**params[self.alphag]
        source.bias_ia_ *= pref
Example #18
0
def test_pk_cutoff():
    # Tests the exponential cutoff
    ptc1 = ccl.nl_pt.PTCalculator(with_NC=True)
    ptc2 = ccl.nl_pt.PTCalculator(with_NC=True, k_cutoff=10., n_exp_cutoff=2.)
    zs = np.array([0., 1.])
    gs4 = ccl.growth_factor(COSMO, 1. / (1 + zs))**4
    pk_lin_z0 = ccl.linear_matter_power(COSMO, ptc1.ks, 1.)
    ptc1.update_pk(pk_lin_z0)
    ptc2.update_pk(pk_lin_z0)

    Pd1d1 = np.array(
        [ccl.linear_matter_power(COSMO, ptc1.ks, a) for a in 1. / (1 + zs)]).T
    one = np.ones_like(zs)
    zero = np.zeros_like(zs)
    p1 = ptc1.get_pgg(Pd1d1, gs4, one, zero, zero, one, zero, zero, True).T
    p2 = ptc2.get_pgg(Pd1d1, gs4, one, zero, zero, one, zero, zero, True).T
    expcut = np.exp(-(ptc1.ks / 10.)**2)
    assert np.all(np.fabs(p1 * expcut / p2 - 1) < 1E-10)
Example #19
0
def test_k2pk():
    # Tests the k2 term scaling
    ptc = ccl.nl_pt.PTCalculator(with_NC=True)

    zs = np.array([0., 1.])
    gs4 = ccl.growth_factor(COSMO, 1. / (1 + zs))**4
    pk_lin_z0 = ccl.linear_matter_power(COSMO, ptc.ks, 1.)
    ptc.update_pk(pk_lin_z0)

    Pd1d1 = np.array(
        [ccl.linear_matter_power(COSMO, ptc.ks, a) for a in 1. / (1 + zs)]).T
    one = np.ones_like(zs)
    zero = np.zeros_like(zs)
    pmm = ptc.get_pgg(Pd1d1, gs4, one, zero, zero, one, zero, zero, True)
    pmm_b = ptc.get_pgm(Pd1d1, gs4, one, zero, zero)
    pmk = ptc.get_pgg(Pd1d1,
                      gs4,
                      one,
                      zero,
                      zero,
                      one,
                      zero,
                      zero,
                      True,
                      bk21=one)
    pmk_b = ptc.get_pgm(Pd1d1, gs4, one, zero, zero, bk2=one)
    pkk = ptc.get_pgg(Pd1d1,
                      gs4,
                      one,
                      zero,
                      zero,
                      one,
                      zero,
                      zero,
                      True,
                      bk21=one,
                      bk22=one)
    ks = ptc.ks[:, None]
    assert np.all(np.fabs(pmm / Pd1d1 - 1) < 1E-10)
    assert np.all(np.fabs(pmm_b / Pd1d1 - 1) < 1E-10)
    assert np.all(np.fabs(pmk / (pmm * (1 + 0.5 * ks**2)) - 1) < 1E-10)
    assert np.all(np.fabs(pmk_b / (pmm * (1 + 0.5 * ks**2)) - 1) < 1E-10)
    assert np.all(np.fabs(pkk / (pmm * (1 + ks**2)) - 1) < 1E-10)
Example #20
0
    def set_theory_correlations(self):
        # Get cosmology parameters
        with open(os.path.join(PROJECT_PATH, 'cosmologies.yml'),
                  'r') as cosmology_file:
            self.cosmology_params = yaml.full_load(cosmology_file)[
                self.cosmology_name]
        self.cosmology_params[
            'matter_power_spectrum'] = self.cosmology_matter_power_spectrum

        cosmology = ccl.Cosmology(**self.cosmology_params)

        bias_arr = self.bias * np.ones(len(self.z_arr))
        if self.scale_bias:
            bias_arr = bias_arr / ccl.growth_factor(cosmology, 1. /
                                                    (1. + self.z_arr))

        tracers_dict = {
            'g':
            ccl.NumberCountsTracer(cosmology,
                                   has_rsd=False,
                                   dndz=(self.z_arr, self.n_arr),
                                   bias=(self.z_arr, bias_arr)),
            'k':
            ccl.CMBLensingTracer(cosmology, 1091),
            't':
            ISWTracer(cosmology, z_max=6., n_chi=1024),
        }

        for correlation_symbol in self.all_correlation_symbols:
            # Pass if theory correlation was set earlier with maps
            if correlation_symbol not in self.theory_correlations:
                tracer_symbol_a = correlation_symbol[0]
                tracer_symbol_b = correlation_symbol[1]
                correlation_symbol = tracer_symbol_a + tracer_symbol_b
                self.theory_correlations[correlation_symbol] = ccl.angular_cl(
                    cosmology, tracers_dict[tracer_symbol_a],
                    tracers_dict[tracer_symbol_b], self.l_arr)

        for correlation_symbol in self.theory_correlations.keys():
            self.theory_correlations[correlation_symbol] += self.noise_curves[
                correlation_symbol]
Example #21
0
def test_linear_alignment_systematic_smoke():
    src = DummySource()
    src.z_ = np.linspace(0, 2.0, 10)
    src.bias_ia_ = 30.0
    cosmo = ccl.Cosmology(Omega_c=0.27,
                          Omega_b=0.045,
                          Omega_k=0.0,
                          w0=-1.0,
                          wa=0.0,
                          sigma8=0.8,
                          n_s=0.96,
                          h=0.67)
    gf = ccl.growth_factor(cosmo, 1.0 / (1.0 + src.z_))
    params = {'__alphag': 0.2, '__alphaz': 0.5, '__z_piv': 0.4}
    sys = LinearAlignmentSystematic(alphag='__alphag',
                                    alphaz='__alphaz',
                                    z_piv='__z_piv')

    sys.apply(cosmo, params, src)
    bias_ia = 30.0 * gf**0.2 * ((1.0 + src.z_) / (1.0 + 0.4))**0.5
    assert np.allclose(src.bias_ia_, bias_ia)
Example #22
0
def lmax_for_redshift(cosmo, z, kmax0=0.2):
    """
    Calculates an lmax for a bin at a given redshift. This is found by taking
    some k_max at z=0, scaling it by the growth factor, and converting to an
    ell value.

    Parameters:
        cosmo (ccl.Cosmology):
            CCL Cosmology object.
        z (float):
            Redshift.
        kmax (float):
            Max. wavenumber (cutoff) at z=0, in Mpc^-1 units.

    Returns:
        lmax (float):
            Maximum ell for this redshift.
    """
    r = ccl.comoving_radial_distance(cosmo, 1.0 / (1.0 + z))
    D = ccl.growth_factor(cosmo, 1.0 / (1.0 + z))
    lmax = r * D * kmax0
    return lmax
Example #23
0
    def get_cl(self, ell, cl_types, **kwargs):
        self._get_cosmo(kwargs['sigma8'])
        zs, nz = self.get_nz(**kwargs)
        if self.bias_type == 'constant':
            bzs = kwargs['bias'] * np.ones_like(zs)
        elif self.bias_type == 'inv_growth':
            bzs = kwargs['bias'] / ccl.growth_factor(self.cosmo, 1. / (1 + zs))
        elif self.bias_type == 'plateau':
            zr2 = (zs / 1.5)**2
            bzs = kwargs['bias'] * (1 + 2 * zr2) / (1 + zr2)
        else:
            raise ValueError("Unknown bias type %s" % bias_type)
        trs = {}
        trs['g'] = ccl.NumberCountsTracer(self.cosmo, False, (zs, nz),
                                          (zs, bzs))
        if 'gk' in cl_types:
            trs['k'] = ccl.CMBLensingTracer(self.cosmo, z_source=1100.)

        t = []
        for typ in cl_types:
            t1 = trs[typ[0]]
            t2 = trs[typ[1]]
            t.append(ccl.angular_cl(self.cosmo, t1, t2, ell))
        return np.array(t)
Example #24
0
def set_up(request):
    t0 = time.time()

    nztyp = request.param
    dirdat = os.path.dirname(__file__) + '/data/'
    cosmo = ccl.Cosmology(Omega_c=0.30,
                          Omega_b=0.00,
                          Omega_g=0,
                          Omega_k=0,
                          h=0.7,
                          sigma8=0.8,
                          n_s=0.96,
                          Neff=0,
                          m_nu=0.0,
                          w0=-1,
                          wa=0,
                          T_CMB=2.7,
                          transfer_function='bbks',
                          mass_function='tinker',
                          matter_power_spectrum='linear')
    cosmo.cosmo.gsl_params.INTEGRATION_LIMBER_EPSREL = 1E-4
    cosmo.cosmo.gsl_params.INTEGRATION_EPSREL = 1E-4

    # ell-arrays
    nls = 541
    ells = np.zeros(nls)
    ells[:50] = np.arange(50) + 2
    ells[50:] = ells[49] + 6 * (np.arange(nls - 50) + 1)
    fl_one = np.ones(nls)
    fl_dl = (ells + 0.5)**2 / np.sqrt(
        (ells + 2.) * (ells + 1.) * ells * (ells - 1.))
    fl_ll = fl_dl**2
    fl_lc = ells * (ells + 1) / np.sqrt(
        (ells + 2.) * (ells + 1.) * ells * (ells - 1.))
    fl_li = 2 * fl_dl
    lfacs = {
        'ells': ells,
        'fl_one': fl_one,
        'fl_dl': fl_dl,
        'fl_ll': fl_ll,
        'fl_lc': fl_lc,
        'fl_li': fl_li
    }

    # Initialize tracers
    if nztyp == 'analytic':
        # Analytic case
        zmean_1 = 1.0
        sigz_1 = 0.15
        zmean_2 = 1.5
        sigz_2 = 0.15
        z1, tmp_a1 = np.loadtxt(dirdat + "ia_amp_analytic_1.txt", unpack=True)
        z2, tmp_a2 = np.loadtxt(dirdat + "ia_amp_analytic_2.txt", unpack=True)
        pz1 = np.exp(-0.5 * ((z1 - zmean_1) / sigz_1)**2)
        pz2 = np.exp(-0.5 * ((z2 - zmean_2) / sigz_2)**2)
    elif nztyp == 'histo':
        # Histogram case
        z1, pz1 = np.loadtxt(dirdat + "bin1_histo.txt", unpack=True)[:, 1:]
        _, tmp_a1 = np.loadtxt(dirdat + "ia_amp_histo_1.txt", unpack=True)
        z2, pz2 = np.loadtxt(dirdat + "bin2_histo.txt", unpack=True)[:, 1:]
        _, tmp_a2 = np.loadtxt(dirdat + "ia_amp_histo_2.txt", unpack=True)
    else:
        raise ValueError("Wrong Nz type " + nztyp)
    bz = np.ones_like(pz1)

    # Renormalize the IA amplitude to be consistent with A_IA
    D1 = ccl.growth_factor(cosmo, 1. / (1 + z1))
    D2 = ccl.growth_factor(cosmo, 1. / (1 + z2))
    rho_m = ccl.physical_constants.RHO_CRITICAL * cosmo['Omega_m']
    a1 = -tmp_a1 * D1 / (5e-14 * rho_m)
    a2 = -tmp_a2 * D2 / (5e-14 * rho_m)

    # Initialize tracers
    trc = {}
    trc['g1'] = ccl.NumberCountsTracer(cosmo, False, (z1, pz1), (z2, bz))
    trc['g2'] = ccl.NumberCountsTracer(cosmo, False, (z2, pz2), (z2, bz))
    trc['l1'] = ccl.WeakLensingTracer(cosmo, (z1, pz1))
    trc['l2'] = ccl.WeakLensingTracer(cosmo, (z2, pz2))
    trc['i1'] = ccl.WeakLensingTracer(cosmo, (z1, pz1),
                                      has_shear=False,
                                      ia_bias=(z1, a1))
    trc['i2'] = ccl.WeakLensingTracer(cosmo, (z2, pz2),
                                      has_shear=False,
                                      ia_bias=(z2, a2))
    trc['ct'] = ccl.CMBLensingTracer(cosmo, 1100.)

    # Read benchmarks
    def read_bm(fname):
        _, cl = np.loadtxt(fname, unpack=True)
        return cl[ells.astype('int')]

    pre = dirdat + 'run_'
    post = nztyp + "_log_cl_"
    bms = {}
    bms['dd_11'] = read_bm(pre + 'b1b1' + post + 'dd.txt')
    bms['dd_12'] = read_bm(pre + 'b1b2' + post + 'dd.txt')
    bms['dd_22'] = read_bm(pre + 'b2b2' + post + 'dd.txt')
    bms['dl_11'] = read_bm(pre + 'b1b1' + post + 'dl.txt')
    bms['dl_12'] = read_bm(pre + 'b1b2' + post + 'dl.txt')
    bms['dl_21'] = read_bm(pre + 'b2b1' + post + 'dl.txt')
    bms['dl_22'] = read_bm(pre + 'b2b2' + post + 'dl.txt')
    bms['di_11'] = read_bm(pre + 'b1b1' + post + 'di.txt')
    bms['di_12'] = read_bm(pre + 'b1b2' + post + 'di.txt')
    bms['di_21'] = read_bm(pre + 'b2b1' + post + 'di.txt')
    bms['di_22'] = read_bm(pre + 'b2b2' + post + 'di.txt')
    bms['dc_1'] = read_bm(pre + 'b1b1' + post + 'dc.txt')
    bms['dc_2'] = read_bm(pre + 'b2b2' + post + 'dc.txt')
    bms['ll_11'] = read_bm(pre + 'b1b1' + post + 'll.txt')
    bms['ll_12'] = read_bm(pre + 'b1b2' + post + 'll.txt')
    bms['ll_22'] = read_bm(pre + 'b2b2' + post + 'll.txt')
    bms['li_11'] = read_bm(pre + 'b1b1' + post + 'li.txt')
    bms['li_22'] = read_bm(pre + 'b2b2' + post + 'li.txt')
    bms['lc_1'] = read_bm(pre + 'b1b1' + post + 'lc.txt')
    bms['lc_2'] = read_bm(pre + 'b2b2' + post + 'lc.txt')
    bms['ii_11'] = read_bm(pre + 'b1b1' + post + 'ii.txt')
    bms['ii_12'] = read_bm(pre + 'b1b2' + post + 'ii.txt')
    bms['ii_22'] = read_bm(pre + 'b2b2' + post + 'ii.txt')
    bms['cc'] = read_bm(pre + 'log_cl_cc.txt')
    print('init and i/o time:', time.time() - t0)

    return cosmo, trc, lfacs, bms
Example #25
0
def main(sim_name, z_nbody, z_ic, R_smooth, machine, want_plot=False):
    # user choices
    k_max = 0.5
    k_min = 1.e-4

    # redshift choice
    #z_s = np.array([3.0, 2.5, 2.0, 1.7, 1.4, 1.1, 0.8, 0.5, 0.4, 0.3, 0.2, 0.1])
    z_s = np.array([0.1, 0.2, 0.3, 0.4, 0.5, 0.8, 1.1])
    a_s = 1. / (1 + z_s)

    # test with class
    class_dir = os.path.expanduser(
        "~/repos/AbacusSummit/Cosmologies/abacus_cosm000/")

    # load parameters
    user_dict, cosmo_dict = load_dict(z_nbody, sim_name, machine)
    R_smooth = user_dict['R_smooth']
    data_dir = user_dict['data_dir']

    # Cosmology
    cosmo = ccl.Cosmology(**cosmo_dict)

    # Redshift distributions
    nz_s = np.exp(-((z_s - 0.8) / 0.05)**2 / 2)

    # Bias
    bz_s = 0.95 / ccl.growth_factor(cosmo, a_s)

    # This tracer will only include the density contribution
    galaxies = ccl.NumberCountsTracer(cosmo,
                                      has_rsd=False,
                                      dndz=(z_s, nz_s),
                                      bias=(z_s, bz_s),
                                      mag_bias=None)

    # read in CLASS power spectra
    ks, Pk = np.loadtxt(class_dir + 'abacus_cosm000.z%d_pk_cb.dat' % (1),
                        unpack=True)
    Pk_a_s = np.zeros((len(a_s), len(ks)))
    for i in range(len(a_s)):
        print(i)
        Pk_a_s[i, :] = np.loadtxt(class_dir + 'abacus_cosm000.z%d_pk_cb.dat' %
                                  (i + 1))[:, 1]

    # generating fake data
    k = np.load("data/AbacusSummit_base_c000_ph006/z1.100/ks.npy")
    dk = k[1] - k[0]
    Lbox = 2000.
    N_modes = k**2 * dk * Lbox**3. / (2. * np.pi**2)
    for i in range(len(a_s)):
        # ccl expects Mpc units todo: improve and ask
        h = cosmo_dict['h']
        # give the ks in Mpc^-1 and get Pk_gg in [Mpc/h]^3
        Pk_gg = ccl.nonlin_matter_power(cosmo, k * h, a_s[i]) * h**3
        cov = np.diag(Pk_gg**2 * (2. / N_modes))
        np.save("data_power/pk_gg_z%4.3f.npy" % z_s[i], Pk_gg)
        np.save("data_power/ks.npy", k)
        np.save("data_power/cov_pk_gg_z%4.3f.npy" % z_s[i], cov)

    # load k and P(k,a)
    ells, cl_tt_tmp = project_Cl(cosmo, galaxies, Pk_a_s, ks, a_s, want_plot)
Example #26
0
r = 0.0

#Call function to evalute growth index for PPNC model
z, H, Omega_M, Omega_DE, f, D, gam = PPNC2(z_final, H0, Omega_M0, k, alpha_0,
                                           p, gamma_0, gamma_cm0, q,
                                           gamma_cDE0, r)
# ignore: PPNC(2.0, H0, 0.3, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, -lam/2.0, 1.0)

################################################################################
import pyccl as ccl
cosmo = ccl.Cosmology(Omega_c=0.25,
                      Omega_b=0.05,
                      h=0.7324,
                      A_s=2.1e-9,
                      n_s=0.96)
ccl_D = ccl.growth_factor(cosmo, 1. / (1. + z))
ccl_f = ccl.growth_rate(cosmo, 1. / (1. + z))

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

#Time code in secs
#print("Time taken", time.clock() - start, "secs")

print('D')
#print('H', H)

#P.subplot(111)
P.figure(1)
aa = 1. / (1. + z)

#Plot growth factor
h0=0.69 #Hubble rate

#Parameters for N(z) \propto z^\alpha \exp[-(z/z0)^\beta]
alpha_nz=2.
beta_nz=1.0
z0_nz=0.3
#Number density in arcmin^-2
ndens_amin2=40.

cosmo=ccl.Cosmology(Omega_c=0.266,Omega_b=0.049,h=h0,sigma8=0.8,n_s=0.96)
karr=10.**(lkmin+(lkmax-lkmin)*np.arange(nk)/(nk-1.))
pklinarr=ccl.linear_matter_power(cosmo,1.,karr*h0)*h0**3
pknlinarr=ccl.nonlin_matter_power(cosmo,1.,karr*h0)*h0**3

zarr=zmax*np.arange(nz)/(nz-1.)
gzarr=ccl.growth_factor(cosmo,1./(1+zarr))
bzarr=0.95/gzarr
nzarr=zarr**alpha_nz*np.exp(-(zarr/z0_nz)**beta_nz)
nzf=interp1d(zarr,nzarr)
#Normalize nz
ntot=quad(nzf,0,zmax)[0]
nzarr*=ndens_amin2*60.**2/ntot
nzf=interp1d(zarr,nzarr)

print "#Gals : %lE"%(0.4*4*np.pi*(180/np.pi)**2*quad(nzf,0,zmax)[0])

np.savetxt("pk_planck.txt",np.transpose([karr,pklinarr]))
np.savetxt("pk_nlin_planck.txt",np.transpose([karr,pknlinarr]))
np.savetxt("bz_lsst.txt",np.transpose([zarr,bzarr]))
np.savetxt("nz_lsst.txt",np.transpose([zarr,nzarr]))
Example #28
0
                  ((z - z0) / sz)**2) * ndens / np.sqrt(2 * np.pi * sz**2)


pars = {
    'h': 0.67,
    'Omega_c': 0.27,
    'Omega_b': 0.045,
    'A_s': 2.1e-9,
    'n_s': 0.96,
    'w_0': -1.,
    'w_a': -0.
}

z_ref = np.linspace(0, 3, 512)
cosmo = get_cosmo_ccl(pars)
bz_ref = 0.95 * ccl.growth_factor(cosmo, 1.) / ccl.growth_factor(
    cosmo, 1. / (1 + z_ref))

z = {}
pz = {}
bz = {}
fsky = {}
cov_sim = {}
cov_th = {}

# pz 1 bin
z[1] = np.tile(z_ref, [1, 1])
pz[1] = np.array([nofz(z_ref, 0.955, 0.13, 7.55)])
bz[1] = np.tile(0.65 * bz_ref, [1, 1])
fsky[1] = 1.  #TODO
Example #29
0
def check_background(cosmo):
    """
    Check that background and growth functions can be run.
    """

    # Types of scale factor input (scalar, list, array)
    a_scl = 0.5
    is_comoving = 0
    a_lst = [0.2, 0.4, 0.6, 0.8, 1.]
    a_arr = np.linspace(0.2, 1., 5)

    # growth_factor
    assert_(all_finite(ccl.growth_factor(cosmo, a_scl)))
    assert_(all_finite(ccl.growth_factor(cosmo, a_lst)))
    assert_(all_finite(ccl.growth_factor(cosmo, a_arr)))

    # growth_factor_unnorm
    assert_(all_finite(ccl.growth_factor_unnorm(cosmo, a_scl)))
    assert_(all_finite(ccl.growth_factor_unnorm(cosmo, a_lst)))
    assert_(all_finite(ccl.growth_factor_unnorm(cosmo, a_arr)))

    # growth_rate
    assert_(all_finite(ccl.growth_rate(cosmo, a_scl)))
    assert_(all_finite(ccl.growth_rate(cosmo, a_lst)))
    assert_(all_finite(ccl.growth_rate(cosmo, a_arr)))

    # comoving_radial_distance
    assert_(all_finite(ccl.comoving_radial_distance(cosmo, a_scl)))
    assert_(all_finite(ccl.comoving_radial_distance(cosmo, a_lst)))
    assert_(all_finite(ccl.comoving_radial_distance(cosmo, a_arr)))

    # comoving_angular_distance
    assert_(all_finite(ccl.comoving_angular_distance(cosmo, a_scl)))
    assert_(all_finite(ccl.comoving_angular_distance(cosmo, a_lst)))
    assert_(all_finite(ccl.comoving_angular_distance(cosmo, a_arr)))

    # h_over_h0
    assert_(all_finite(ccl.h_over_h0(cosmo, a_scl)))
    assert_(all_finite(ccl.h_over_h0(cosmo, a_lst)))
    assert_(all_finite(ccl.h_over_h0(cosmo, a_arr)))

    # luminosity_distance
    assert_(all_finite(ccl.luminosity_distance(cosmo, a_scl)))
    assert_(all_finite(ccl.luminosity_distance(cosmo, a_lst)))
    assert_(all_finite(ccl.luminosity_distance(cosmo, a_arr)))

    # scale_factor_of_chi
    assert_(all_finite(ccl.scale_factor_of_chi(cosmo, a_scl)))
    assert_(all_finite(ccl.scale_factor_of_chi(cosmo, a_lst)))
    assert_(all_finite(ccl.scale_factor_of_chi(cosmo, a_arr)))

    # omega_m_a
    assert_(all_finite(ccl.omega_x(cosmo, a_scl, 'matter')))
    assert_(all_finite(ccl.omega_x(cosmo, a_lst, 'matter')))
    assert_(all_finite(ccl.omega_x(cosmo, a_arr, 'matter')))

    # Fractional density of different types of fluid
    assert_(all_finite(ccl.omega_x(cosmo, a_arr, 'dark_energy')))
    assert_(all_finite(ccl.omega_x(cosmo, a_arr, 'radiation')))
    assert_(all_finite(ccl.omega_x(cosmo, a_arr, 'curvature')))
    assert_(all_finite(ccl.omega_x(cosmo, a_arr, 'neutrinos_rel')))
    assert_(all_finite(ccl.omega_x(cosmo, a_arr, 'neutrinos_massive')))

    # Check that omega_x fails if invalid component type is passed
    assert_raises(ValueError, ccl.omega_x, cosmo, a_scl, 'xyz')

    # rho_crit_a
    assert_(all_finite(ccl.rho_x(cosmo, a_scl, 'critical', is_comoving)))
    assert_(all_finite(ccl.rho_x(cosmo, a_lst, 'critical', is_comoving)))
    assert_(all_finite(ccl.rho_x(cosmo, a_arr, 'critical', is_comoving)))

    # rho_m_a
    assert_(all_finite(ccl.rho_x(cosmo, a_scl, 'matter', is_comoving)))
    assert_(all_finite(ccl.rho_x(cosmo, a_lst, 'matter', is_comoving)))
    assert_(all_finite(ccl.rho_x(cosmo, a_arr, 'matter', is_comoving)))
Example #30
0
def compute_mean_covariance(tomo_bin, z, what):
    """Compute a mean and covariance for the chosen distribution of objects.

    value can be 'ww' for shear-shear only, 'gg' for galaxy clustering and
    '3x2' for full '3x2pt'
    This assumes a cosmology, and the varions parameters affecting the noise
    and signal: the f_sky, ell choices, sigma_e, and n_eff

    """
    import pyccl as ccl
    # 10,000 sq deg
    f_sky = 0.25
    # pretend there is no evolution in measurement error.
    # because LSST is awesome
    sigma_e = 0.26
    # assumed total over all bins, divided proportionally
    n_eff_total_arcmin2 = 20.0
    # Use this fiducial cosmology, which is what I have for TXPipe
    config = yaml.safe_load(open(default_config_path))
    cosmo = ccl.Cosmology(**config['parameters'])

    # ell values we will use.  Computed centrally
    # since we want to avoid mismatches elsewhere.
    # should really sort this out better.
    ell, delta_ell = ell_binning()
    n_ell = len(ell)

    # work out the number density per steradian
    steradian_to_arcmin2 = (180 * 60 / np.pi)**2
    n_eff_total = n_eff_total_arcmin2 * steradian_to_arcmin2

    nbin = int(tomo_bin.max()) + 1

    z_mid, n_of_z = get_n_of_z(tomo_bin, z)
    bz = 1 / ccl.growth_factor(cosmo, 1 / (1 + z_mid))
    bofz = (z_mid, bz)
    galaxy_galaxy_tracer_bias = [(bz * nz_bin).sum() / (nz_bin).sum()
                                 for nz_bin in n_of_z]
    #print ('biases=',galaxy_galaxy_tracer_bias)

    tracers = []
    counts = [nz_bin.sum() for nz_bin in n_of_z]
    tracers = []
    tracer_type = get_tracer_type(nbin, what)
    # start with number counts
    if (what == 'gg' or what == '3x2'):
        tracers += [
            ccl.NumberCountsTracer(cosmo,
                                   has_rsd=False,
                                   dndz=(z_mid, nz_bin),
                                   bias=bofz) for nz_bin in n_of_z
        ]
    if (what == 'ww' or what == '3x2'):
        tracers += [
            ccl.WeakLensingTracer(cosmo, dndz=(z_mid, nz_bin))
            for nz_bin in n_of_z
        ]

    ntracers = len(tracers)
    #print (tracer_type)
    # Get the fraction of the total possible number of objects
    # in each bin, and the consequent effective number density.
    # We pretend here that all objects have the same weight.
    fractions = [c / tomo_bin.size for c in counts]
    n_eff = [n_eff_total * f for f in fractions]

    # Define an ordering of the theory vector
    blocks = []
    for i in range(ntracers):
        for j in range(i, ntracers):
            blocks.append((i, j))

    # Get all the spectra, both the signal-only version (for the mean)
    # and the version with noise (for the covmat)
    C_sig = {}
    C_obs = {}
    for ci, cj in blocks:
        # ci, cj are tracer numbers as in (g1, g2, g3, g4, s1, s2,s3,s4 etc.)
        # nbin is 4 in the example above
        # so ci %n bin gives the tomographic bin
        i = ci % nbin
        j = cj % nbin
        Ti = tracers[ci]
        Tj = tracers[cj]
        C_sig[ci, cj] = ccl.angular_cl(cosmo, Ti, Tj, ell)
        # Noise contribution, if an auto-bin
        if ci == cj:
            if tracer_type[ci] == 'g':
                C_obs[ci, cj] = C_sig[ci, cj] + 1 / n_eff[i]
            elif tracer_type[ci] == 'w':
                C_obs[ci, cj] = C_sig[ci, cj] + sigma_e**2 / n_eff[i]
            else:
                raise NotImplementedError("Unknown tracer")
        else:
            C_obs[ci, cj] = C_sig[ci, cj]
            C_obs[cj, ci] = C_sig[ci, cj]

    # concatenate all the theory predictions as our mean
    mu = np.concatenate([C_sig[i, j] for i, j in blocks])

    # empty space for the covariance matrix
    C = np.zeros((mu.size, mu.size))

    # normalization.  This and the bit below are Takada & Jain
    # equation 14
    norm = (2 * ell + 1) * delta_ell * f_sky

    # Fill in each covmat block.  We waste time here
    # doing the flip elements but not significant
    for a, (i, j) in enumerate(blocks[:]):
        for b, (m, n) in enumerate(blocks[:]):
            start_a = a * n_ell
            start_b = b * n_ell
            end_a = start_a + n_ell
            end_b = start_b + n_ell
            c2 = (C_obs[i, m] * C_obs[j, n] + C_obs[i, n] * C_obs[j, m])
            C[start_a:end_a, start_b:end_b] = (c2 / norm) * np.eye(n_ell)

    return mu, C, galaxy_galaxy_tracer_bias
Example #31
0
def set_up(request):
    t0 = time.time()
    nztyp = request.param
    dirdat = os.path.dirname(__file__) + '/data/'
    cosmo = ccl.Cosmology(Omega_c=0.30,
                          Omega_b=0.00,
                          Omega_g=0,
                          Omega_k=0,
                          h=0.7,
                          sigma8=0.8,
                          n_s=0.96,
                          Neff=0,
                          m_nu=0.0,
                          w0=-1,
                          wa=0,
                          T_CMB=2.7,
                          transfer_function='bbks',
                          mass_function='tinker',
                          matter_power_spectrum='linear')
    cosmo.cosmo.gsl_params.INTEGRATION_LIMBER_EPSREL = 2.5E-5
    cosmo.cosmo.gsl_params.INTEGRATION_EPSREL = 2.5E-5

    # Ell-dependent correction factors
    # Set up array of ells
    fl = {}
    lmax = 10000
    nls = (lmax - 400) // 20 + 141
    ells = np.zeros(nls)
    ells[:101] = np.arange(101)
    ells[101:121] = ells[100] + (np.arange(20) + 1) * 5
    ells[121:141] = ells[120] + (np.arange(20) + 1) * 10
    ells[141:] = ells[140] + (np.arange(nls - 141) + 1) * 20
    fl['lmax'] = lmax
    fl['ells'] = ells

    # Initialize tracers
    if nztyp == 'analytic':
        # Analytic case
        zmean_1 = 1.0
        sigz_1 = 0.15
        zmean_2 = 1.5
        sigz_2 = 0.15
        z1, tmp_a1 = np.loadtxt(dirdat + "ia_amp_analytic_1.txt", unpack=True)
        z2, tmp_a2 = np.loadtxt(dirdat + "ia_amp_analytic_2.txt", unpack=True)
        pz1 = np.exp(-0.5 * ((z1 - zmean_1) / sigz_1)**2)
        pz2 = np.exp(-0.5 * ((z2 - zmean_2) / sigz_2)**2)
    elif nztyp == 'histo':
        # Histogram case
        z1, pz1 = np.loadtxt(dirdat + "bin1_histo.txt", unpack=True)[:, 1:]
        _, tmp_a1 = np.loadtxt(dirdat + "ia_amp_histo_1.txt", unpack=True)
        z2, pz2 = np.loadtxt(dirdat + "bin2_histo.txt", unpack=True)[:, 1:]
        _, tmp_a2 = np.loadtxt(dirdat + "ia_amp_histo_2.txt", unpack=True)
    else:
        raise ValueError("Wrong Nz type " + nztyp)
    bz = np.ones_like(pz1)

    # Renormalize the IA amplitude to be consistent with A_IA
    D1 = ccl.growth_factor(cosmo, 1. / (1 + z1))
    D2 = ccl.growth_factor(cosmo, 1. / (1 + z2))
    rho_m = ccl.physical_constants.RHO_CRITICAL * cosmo['Omega_m']
    a1 = -tmp_a1 * D1 / (5e-14 * rho_m)
    a2 = -tmp_a2 * D2 / (5e-14 * rho_m)

    # Initialize tracers
    trc = {}
    trc['g1'] = ccl.NumberCountsTracer(cosmo, False, (z1, pz1), (z2, bz))
    trc['g2'] = ccl.NumberCountsTracer(cosmo, False, (z2, pz2), (z2, bz))
    trc['l1'] = ccl.WeakLensingTracer(cosmo, (z1, pz1))
    trc['l2'] = ccl.WeakLensingTracer(cosmo, (z2, pz2))
    trc['i1'] = ccl.WeakLensingTracer(cosmo, (z1, pz1),
                                      has_shear=False,
                                      ia_bias=(z1, a1))
    trc['i2'] = ccl.WeakLensingTracer(cosmo, (z2, pz2),
                                      has_shear=False,
                                      ia_bias=(z2, a2))
    trc['ct'] = ccl.CMBLensingTracer(cosmo, 1100.)

    # Read benchmarks
    def read_bm(fname):
        th, xi = np.loadtxt(fname, unpack=True)
        return th, xi

    pre = dirdat + 'run_'
    post = nztyp + "_log_wt_"
    bms = {}
    theta, bms['dd_11'] = read_bm(pre + 'b1b1' + post + 'dd.txt')
    _, bms['dd_12'] = read_bm(pre + 'b1b2' + post + 'dd.txt')
    _, bms['dd_22'] = read_bm(pre + 'b2b2' + post + 'dd.txt')
    _, bms['dl_11'] = read_bm(pre + 'b1b1' + post + 'dl.txt')
    _, bms['dl_12'] = read_bm(pre + 'b1b2' + post + 'dl.txt')
    _, bms['dl_21'] = read_bm(pre + 'b2b1' + post + 'dl.txt')
    _, bms['dl_22'] = read_bm(pre + 'b2b2' + post + 'dl.txt')
    _, bms['di_11'] = read_bm(pre + 'b1b1' + post + 'di.txt')
    _, bms['di_12'] = read_bm(pre + 'b1b2' + post + 'di.txt')
    _, bms['di_21'] = read_bm(pre + 'b2b1' + post + 'di.txt')
    _, bms['di_22'] = read_bm(pre + 'b2b2' + post + 'di.txt')
    _, bms['ll_11_p'] = read_bm(pre + 'b1b1' + post + 'll_pp.txt')
    _, bms['ll_12_p'] = read_bm(pre + 'b1b2' + post + 'll_pp.txt')
    _, bms['ll_22_p'] = read_bm(pre + 'b2b2' + post + 'll_pp.txt')
    _, bms['ll_11_m'] = read_bm(pre + 'b1b1' + post + 'll_mm.txt')
    _, bms['ll_12_m'] = read_bm(pre + 'b1b2' + post + 'll_mm.txt')
    _, bms['ll_22_m'] = read_bm(pre + 'b2b2' + post + 'll_mm.txt')
    _, bms['li_11_p'] = read_bm(pre + 'b1b1' + post + 'li_pp.txt')
    _, bms['li_12_p'] = read_bm(pre + 'b1b2' + post + 'li_pp.txt')
    _, bms['li_22_p'] = read_bm(pre + 'b2b2' + post + 'li_pp.txt')
    _, bms['li_11_m'] = read_bm(pre + 'b1b1' + post + 'li_mm.txt')
    _, bms['li_12_m'] = read_bm(pre + 'b1b2' + post + 'li_mm.txt')
    _, bms['li_22_m'] = read_bm(pre + 'b2b2' + post + 'li_mm.txt')
    _, bms['ii_11_p'] = read_bm(pre + 'b1b1' + post + 'ii_pp.txt')
    _, bms['ii_12_p'] = read_bm(pre + 'b1b2' + post + 'ii_pp.txt')
    _, bms['ii_22_p'] = read_bm(pre + 'b2b2' + post + 'ii_pp.txt')
    _, bms['ii_11_m'] = read_bm(pre + 'b1b1' + post + 'ii_mm.txt')
    _, bms['ii_12_m'] = read_bm(pre + 'b1b2' + post + 'ii_mm.txt')
    _, bms['ii_22_m'] = read_bm(pre + 'b2b2' + post + 'ii_mm.txt')
    bms['theta'] = theta

    # Read error bars
    ers = {}
    d = np.loadtxt("benchmarks/data/sigma_clustering_Nbin5", unpack=True)
    ers['dd_11'] = interp1d(d[0] / 60.,
                            d[1],
                            fill_value=d[1][0],
                            bounds_error=False)(theta)
    ers['dd_22'] = interp1d(d[0] / 60.,
                            d[2],
                            fill_value=d[2][0],
                            bounds_error=False)(theta)
    d = np.loadtxt("benchmarks/data/sigma_ggl_Nbin5", unpack=True)
    ers['dl_12'] = interp1d(d[0] / 60.,
                            d[1],
                            fill_value=d[1][0],
                            bounds_error=False)(theta)
    ers['dl_11'] = interp1d(d[0] / 60.,
                            d[2],
                            fill_value=d[2][0],
                            bounds_error=False)(theta)
    ers['dl_22'] = interp1d(d[0] / 60.,
                            d[3],
                            fill_value=d[3][0],
                            bounds_error=False)(theta)
    ers['dl_21'] = interp1d(d[0] / 60.,
                            d[4],
                            fill_value=d[4][0],
                            bounds_error=False)(theta)
    d = np.loadtxt("benchmarks/data/sigma_xi+_Nbin5", unpack=True)
    ers['ll_11_p'] = interp1d(d[0] / 60.,
                              d[1],
                              fill_value=d[1][0],
                              bounds_error=False)(theta)
    ers['ll_22_p'] = interp1d(d[0] / 60.,
                              d[2],
                              fill_value=d[2][0],
                              bounds_error=False)(theta)
    ers['ll_12_p'] = interp1d(d[0] / 60.,
                              d[3],
                              fill_value=d[3][0],
                              bounds_error=False)(theta)
    d = np.loadtxt("benchmarks/data/sigma_xi-_Nbin5", unpack=True)
    ers['ll_11_m'] = interp1d(d[0] / 60.,
                              d[1],
                              fill_value=d[1][0],
                              bounds_error=False)(theta)
    ers['ll_22_m'] = interp1d(d[0] / 60.,
                              d[2],
                              fill_value=d[2][0],
                              bounds_error=False)(theta)
    ers['ll_12_m'] = interp1d(d[0] / 60.,
                              d[3],
                              fill_value=d[3][0],
                              bounds_error=False)(theta)
    print('setup time:', time.time() - t0)
    return cosmo, trc, bms, ers, fl