Ejemplo n.º 1
0
    def sn(self, C):
        ## there are fixed (1+z)**2 factors here for lum distance, which cancel out
        sn = ccl.comoving_angular_distance(C, self.aar)
        sn0 = ccl.comoving_angular_distance(self.CBase, self.aar)
        ratio = sn / sn0
        fact = (interp1d(self.zar, ratio)(self.snz) /
                self.snerr**2).sum() / (1 / self.snerr**2).sum()

        # now normalize ratio so that error weighted is one
        ratio /= fact

        return ratio
Ejemplo n.º 2
0
    def GetCosmo(self, addict):
        ## find the correct h, to kee distance t
        acmb = 1 / (1150.0)
        target = ccl.comoving_angular_distance(self.CBase, acmb) / self.rd(
            self.CBase)

        def _C(h):
            CP = {
                "Omega_c": self.Och2 / h**2,
                "Omega_b": self.Obh2 / h**2,
                "h": h,
                "n_s": self.ns,
                "m_nu": 0.06,
                "A_s": np.exp(self.lnttAs) / 1e10,
            }
            CP.update(addict)
            print(CP)
            return ccl.Cosmology(**CP), CP

        def _t(h):
            C, _ = _C(h)
            d = ccl.comoving_angular_distance(C, acmb) / self.rd(C)
            return d - target

        print(_t(0.3), _t(1.0))
        hout = so.bisect(_t, 0.3, 1.0)  # ,xtol=1e-5,rtol=1e-2)
        return _C(hout)
Ejemplo n.º 3
0
def comoving_dimensions_from_survey(cosmo, angular_extent, freq_range=None, 
                                    z_range=None, line_freq=1420.405752):
    """
    Return the comoving dimensions and central redshift of a survey volume, 
    given its angular extent and redshift/frequency range.
    
    Parameters:
        cosmo (ccl.Cosmology object):
            CCL object that defines the cosmology to use.
        angular_extent (tuple):
            Angular extent of the survey in the x and y directions on the sky, 
            given in degrees. For example, `(10, 30)` denotes a 10 deg x 30 deg 
            survey area.
        freq_range (tuple, optional):
            The frequency range of the survey, given in MHz.
        z_range (tuple, optional):
            The redshift range of the survey.
        line_freq (float, optional):
            Frequency of the emission line used as redshift reference, in MHz.
        
    Returns:
        zc (float):
            Redshift of the centre of the comoving box.
        dimensions (tuple):
            Tuple of comoving dimensions of the survey volume, (Lx, Ly, Lz), 
            in Mpc.
    """
    # Check inputs
    if (freq_range is not None and z_range is not None) \
    or (freq_range is None and z_range is None):
        raise ValueError("Must specify either freq_range of z_range.")
    assert len(angular_extent) == 2, "angular_extent must be tuple of length 2"
    
    # Convert frequency range to z range if needed
    if freq_range is not None:
        assert len(freq_range) == 2, "freq_range must be tuple of length 2"
        z_range = (line_freq/freq_range[0] - 1., 
                   line_freq/freq_range[1] - 1.)
    assert len(z_range) == 2, "z_range must be tuple of length 2"
    
    # Sort z_range
    zmin, zmax = sorted(z_range)
    
    # Convert z_range to comoving r range
    rmin = ccl.comoving_radial_distance(cosmo, 1./(1.+zmin))
    rmax = ccl.comoving_radial_distance(cosmo, 1./(1.+zmax))
    Lz = rmax - rmin
    
    # Get comoving centroid of volume
    _z = np.linspace(zmin, zmax, 100)
    _r = ccl.comoving_radial_distance(cosmo, 1./(1.+_z))
    rc = 0.5 * (rmax + rmin)
    zc = interp1d(_r, _z, kind='linear')(rc)
    
    # Get transverse extent of box, evaluated at centroid redshift
    r_trans = ccl.comoving_angular_distance(cosmo, 1./(1.+zc))
    Lx = angular_extent[0] * np.pi/180. * r_trans
    Ly = angular_extent[1] * np.pi/180. * r_trans
    
    return zc, (Lx, Ly, Lz)
Ejemplo n.º 4
0
    def pixel_array(self, redshift=None):
        """
        Return angular pixel coordinate array in degrees.
        
        Parameters:
            redshift (float, optional):
                Redshift to evaluate the centre of the box at. Default: Same value 
                as ``self.redshift``.
        
        Returns:
            pix_x, pix_y (array_like):
                Coordinates of pixel centres in the x and y directions, in degrees. 
                The origin is the centre of the box.
        """
        # Check redshift
        if redshift is None:
            redshift = self.redshift
        scale_factor = 1. / (1. + redshift)

        # Calculate comoving distance to box redshift
        r = ccl.comoving_angular_distance(self.cosmo, scale_factor)

        # Comoving pixel size
        x_px = self.x[1] - self.x[0]
        y_px = self.y[1] - self.y[0]

        # Angular pixel size
        ang_x = (180. / np.pi) * (x_px / r)
        ang_y = (180. / np.pi) * (y_px / r)

        # Pixel index grid; place origin in centre of box
        grid = np.arange(self.N) - 0.5 * (self.N - 1.)

        return ang_x * grid, ang_y * grid
Ejemplo n.º 5
0
def test_background_a_interface(a, func):
    if func is ccl.distance_modulus and np.any(a == 1):
        with pytest.raises(ccl.CCLError):
            func(COSMO, a)
    else:
        val = func(COSMO, a)
        assert np.all(np.isfinite(val))
        assert np.shape(val) == np.shape(a)
        if (func is ccl.angular_diameter_distance):
            val = func(COSMO, a, a)
            assert np.all(np.isfinite(val))
            assert np.shape(val) == np.shape(a)
            if (isinstance(a, float) or isinstance(a, int)):
                val1 = ccl.angular_diameter_distance(COSMO, 1., a)
                val2 = ccl.comoving_angular_distance(COSMO, a) * a
            else:
                val1 = ccl.angular_diameter_distance(COSMO, np.ones(len(a)), a)
                val2 = ccl.comoving_angular_distance(COSMO, a) * a
            assert np.allclose(val1, val2)
Ejemplo n.º 6
0
def create_y_map(painted_planes, z, resolution, map_size, cosmo, order=3, verbose=True):
    def L_pix(cosmo, chi, theta):
        a = ccl.scale_factor_of_chi(cosmo, chi)
        return chi*a*theta

    def A_pix_mean(cosmo, chi_lo, chi_hi, theta):
        f = lambda chi: L_pix(cosmo, chi, theta)**2
        L = scipy.integrate.quad(f, chi_lo, chi_hi)[0]/(chi_hi-chi_lo)
        return L

    y_map = np.zeros((resolution, resolution))
    
    h = cosmo.cosmo.params.h
    d_A = ccl.comoving_angular_distance(cosmo, 1/(1+np.array(z)))
    d_A -= 252.5/h/2
    if d_A[0] < 0:
        d_A[0] = 0 
    d_A = np.append(d_A, d_A[-1] + 252.5/h)

    theta_pix = map_size/resolution*pi/180 # Pixel size in radians
    A_pix_eff = np.array([A_pix_mean(cosmo, d_A[i], d_A[i+1], theta_pix) for i in range(len(z))])
    
    # Low redshift seems to constribute too much
    # Effective distance/redshift might better be estimated by considering volume
    # contributing to that redshift range (i.e., weighted towards higher 
    # redshift, with diminishing effect).
    # d_A_eff = d_A[:-1] # z is already the slice mid-point
    # a_eff = np.array([ccl.scale_factor_of_chi(cosmo, d) for d in d_A_eff])
    
    y_fac = 8.125561e-16 # sigma_T/m_e*c^2 in SI
    mpc = 3.086e22 # m/Mpc
    eV = 1.60218e-19 # Electronvolt in Joules
    cm = 0.01 # Centimetre in metres

    Xe = 1.17
    Xi = 1.08
    
    V_c = (400/h/2048*mpc/cm)**3 # Volume of cell in cm^3
    y_fac = y_fac*eV*mpc**-2 # sigma_T/m_e*c^2 in Mpc^2 eV^-1
    
    # theta_pix = map_size/resolution*pi/180 # Pixel size in radians
    # L_pix = theta_pix*d_A_eff*a_eff # Physical pixel size in Mpc
    
    for i, d in enumerate(painted_planes):
        zoom_factor = resolution/d.shape[0]
        d = d.copy()
        d[np.isnan(d)] = 0
        
        d *= V_c*(Xe+Xi)/Xe*y_fac/A_pix_eff[i]/zoom_factor**2
        if verbose: print(f"z : {z[i]:0.3f}, plane shape: {d.shape}, zoom_factor: {zoom_factor:0.3f}")
        if verbose: print(f"{np.isnan(d).sum()}")
        
        y_map += scipy.ndimage.zoom(d, zoom=zoom_factor, order=order, mode="mirror")
        
    return y_map
    def _func(m, a):
        abs_dzda = 1 / a / a
        dc = ccl.comoving_angular_distance(cosmo, a)
        ez = ccl.h_over_h0(cosmo, a)
        dh = ccl.physical_constants.CLIGHT_HMPC / cosmo['h']
        dvdz = dh * dc**2 / ez
        dvda = dvdz * abs_dzda

        val = hmf.get_mass_function(cosmo, 10**m, a, mdef_other=mdef)
        val *= sel(10**m, a)
        return val[0, 0] * dvda
def check_get_tile():
    import matplotlib.pyplot as plt
    import matplotlib.patches as patches
    
    import pyccl as ccl
    import cosmotools.plotting as plotting
    
    # WMAP9
    Omega_m = 0.2905
    Omega_b = 0.0473
    Omega_L = 0.7095
    h = 0.6898
    sigma_8 = 0.826
    n_s = 0.969
    cosmo = ccl.Cosmology(Omega_c=(1-Omega_L-Omega_b), Omega_b=Omega_b, Omega_k=0,
                          h=h, sigma8=sigma_8, n_s=n_s)

    z_SLICS = 0.042
    d_A_SLICS = ccl.comoving_angular_distance(cosmo, 1/(1+z_SLICS))*h # units of Mpc/h

    
    shifts = np.loadtxt("../data/training_data/SLICS/random_shift_LOS1097")[::-1]

    tile_relative_size = d_A_SLICS*10/180*pi/505

    plane = np.fromfile(f"../data/training_data/SLICS/massplanes/{z_SLICS:.3f}proj_half_finer_xy.dat_LOS1097", dtype=np.float32)[1:].reshape(4096*3, -1).T
    plane *= 64
    plane -= plane.min()

    delta = np.fromfile(f"../data/training_data/SLICS/delta/{z_SLICS:.3f}delta.dat_bicubic_LOS1097", dtype=np.float32).reshape(7745, -1).T
    delta *= 64
    delta -= delta.min()
    delta = delta[::7, ::7]

    expansion_factor = 1.5
    tile = get_tile(plane, shifts[0], tile_relative_size, expansion_factor=expansion_factor)

    delta_region = patches.Rectangle(xy=(0,0), width=1, height=1, fill=False)

    # Plot stuff
    fig, ax = plt.subplots(1, 2, figsize=(10, 5))

    im = ax[0].imshow(np.log(tile+1), extent=(-(expansion_factor-1)/2, 1.0+(expansion_factor-1)/2, 
                                              -(expansion_factor-1)/2, 1.0+(expansion_factor-1)/2))
    plotting.subplot_colorbar(im, ax[0])
    ax[0].add_artist(delta_region)

    im = ax[1].imshow(np.log(delta+1), extent=(0.0, 1.0, 0.0, 1.0))
    plotting.subplot_colorbar(im, ax[1])
    
    ax[0].set_title("Mass plane")
    ax[1].set_title("Delta")
    fig.suptitle("Extract tiles from SLICS")
Ejemplo n.º 9
0
    def angularDiameterDistance(self, z):
        """Compute the distance modulus as a function of redshift

        Parameters
        ----------
        z : array
            redshifts to compute angular diameter distance at

        Returns
        -------
        d_a : array
            comoving angular diameter distance at input redshifts

        """

        d_a = ccl.comoving_angular_distance(self._cosmo, 1 / (z + 1.))
        return d_a
Ejemplo n.º 10
0
def test_distances_flat():
    # 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)

    chi_ccl = ccl.comoving_radial_distance(cosmo_ccl, a)
    chi_jax = bkgrd.radial_comoving_distance(cosmo_jax, a) / cosmo_jax.h
    assert_allclose(chi_ccl, chi_jax, rtol=0.5e-2)

    chi_ccl = ccl.comoving_angular_distance(cosmo_ccl, a)
    chi_jax = bkgrd.transverse_comoving_distance(cosmo_jax, a) / cosmo_jax.h
    assert_allclose(chi_ccl, chi_jax, rtol=0.5e-2)

    chi_ccl = ccl.angular_diameter_distance(cosmo_ccl, a)
    chi_jax = bkgrd.angular_diameter_distance(cosmo_jax, a) / cosmo_jax.h
    assert_allclose(chi_ccl, chi_jax, rtol=0.5e-2)
Ejemplo n.º 11
0
def kmax2lmax(kmax, zeff, cosmo=None):
    """
    Determine lmax corresponding to given kmax at an effective redshift zeff according to
    kmax = (lmax + 1/2)/chi(zeff)
    :param kmax: maximal wavevector in h Mpc^-1
    :param zeff: effective redshift of sample
    :return lmax: maximal angular multipole corresponding to kmax
    """

    if cosmo is None:
        print(
            'CCL cosmology object not supplied. Initializing with Planck 2018 cosmological parameters.'
        )
        cosmo = ccl.Cosmology(n_s=0.9649,
                              A_s=2.1e-9,
                              h=0.6736,
                              Omega_c=0.264,
                              Omega_b=0.0493)

    # Comoving angular diameter distance in Mpc/h
    chi_A = ccl.comoving_angular_distance(cosmo, 1. / (1. + zeff)) * cosmo['h']
    lmax = kmax * chi_A - 1. / 2.

    return lmax
Ejemplo n.º 12
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)))
Ejemplo n.º 13
0
p = params
cosmo = ccl.Cosmology(Omega_c=p['omegaM'] - p['omegaB'],
                      Omega_b=p['omegaB'],
                      h=p['h'],
                      Omega_k=0.,
                      w0=-1.,
                      A_s=2.1e-9,
                      n_s=0.96,
                      m_nu=0.06)

# Plot low-redshift D_A(z) and H(z)
z = np.logspace(-3., 3.1, 1000)
a = 1. / (1. + z)

# CCL quantities
ccl_DA = a * ccl.comoving_angular_distance(cosmo, a)
ccl_Hz = (100. * p['h']) * ccl.h_over_h0(cosmo, a)

# My quantities
this_Hz = model.Hz(a, params)
this_DA = model.DAz(a, params)

#-------------------------------------------------------------------------------

# Load CCL benchmark file
dat = np.genfromtxt("CCL_TEST_CHI.dat").T
bench_z = dat[0]
#bench_chi = dat[1] # flat, no massive neutrinos, 3 massless
bench_chi = dat[3]  # flat, 1 massive neutrino, 0.1 eV

#P.title("massless")
                              Neff=3.046, Omega_k=0., baryons_power_spectrum='bcm', 
                              bcm_log10Mc=14.079181246047625, bcm_etab=0.5, bcm_ks=55.0)

# Cosmology where the power spectrum will be computed with an emulator.
cosmo_emu = ccl.Cosmology(Omega_c=0.27, Omega_b=0.05, h=0.67, sigma8=0.83, n_s=0.96, 
                          Neff=3.04, Omega_k=0., transfer_function='emulator', 
                          matter_power_spectrum="emu")

# background quantities
z = np.linspace(0.0001, 5., 100)
a = 1. / (1.+z)


# Compute distances
chi_rad = ccl.comoving_radial_distance(cosmo, a) 
chi_ang = ccl.comoving_angular_distance(cosmo,a)
lum_dist = ccl.luminosity_distance(cosmo, a)
dist_mod = ccl.distance_modulus(cosmo, a)


# Plot the comoving radial distance as a function of redshift, as an example.
plt.figure()
plt.plot(z, chi_rad, 'k', linewidth=2)
plt.xlabel('$z$', fontsize=20)
plt.ylabel('Comoving distance, Mpc', fontsize=15)
plt.tick_params(labelsize=13)
# plt.show()
plt.close()

# Compute growth quantities :
D = ccl.growth_factor(cosmo, a)
Ejemplo n.º 15
0
def plot_lss_deviations():
    """
    Plot D_V, D_M, and D_H, relative to a LambdaCDM model
    """
    P.subplot(111)
    colours = {'DV': 'b', 'DM': 'r', 'DH': 'g'}

    for dp in data:
        dname, dtype, zc, dval, derr = dp  # Data have already been divided by r_d

        DV, DM, DH = lss_distances(zc,
                                   pdict(w0=-1., winf=-1., zc=2., deltaz=0.5))
        if dtype == 'DV': fac = DV / r_d
        if dtype == 'DM': fac = DM / r_d
        if dtype == 'DH': fac = DH / r_d

        P.errorbar(zc,
                   dval / fac - 1.,
                   yerr=derr / fac,
                   color=colours[dtype],
                   label=dname,
                   marker='.',
                   mew=1.8,
                   capsize=5.)

    # Plot theory curves
    #z = np.logspace(-3., np.log10(3.), 200)
    z = np.logspace(-3., np.log10(1500.), 500)

    P.axhline(0., color='k', lw=1.8, alpha=0.4)

    # LambdaCDM
    DV0, DM0, DH0 = lss_distances(z, pdict(w0=-1., winf=-1., zc=0.,
                                           deltaz=0.5))

    # Alternative model (1)
    pmodel = pdict(w0=-1., winf=-0.5, zc=0.3, deltaz=0.2, omegaK=0.03)
    DV, DM, DH = lss_distances(z, pmodel)
    P.plot(z,
           DV / DV0 - 1.,
           lw=1.8,
           color=colours['DV'],
           ls='dashed',
           alpha=0.5)
    P.plot(z,
           DM / DM0 - 1.,
           lw=1.8,
           color=colours['DM'],
           ls='dashed',
           alpha=0.5)
    P.plot(z,
           DH / DH0 - 1.,
           lw=1.8,
           color=colours['DH'],
           ls='dashed',
           alpha=0.5)

    # Alternative model (1)
    #pmodel = pdict(w0=-1., winf=-0.5, zc=0.3, deltaz=0.2, omegaK=0.0)

    pmodel = pdict(omegaM=0.323,
                   omegaK=-0.199,
                   w0=-1.298,
                   h=0.743,
                   deltaz=4.748,
                   omegaB=0.100,
                   winf=-0.297,
                   z_eq=13434.643,
                   zc=147.897)

    DV, DM, DH = lss_distances(z, pmodel)
    P.plot(z,
           DV / DV0 - 1.,
           lw=1.8,
           color=colours['DV'],
           ls='dotted',
           alpha=0.5)
    P.plot(z,
           DM / DM0 - 1.,
           lw=1.8,
           color=colours['DM'],
           ls='dotted',
           alpha=0.5)
    P.plot(z,
           DH / DH0 - 1.,
           lw=1.8,
           color=colours['DH'],
           ls='dotted',
           alpha=0.5)

    # FIXME: Planck 2015 CMB
    plcdm = pdict(w0=-1., winf=-1., zc=0., deltaz=0.5, zeq=3394.)
    DVs, DMs, DHs = lss_distances(1090., plcdm)
    ob = (0.02222, 0.00023)
    om = (0.1426, 0.0020)
    rstar = (144.61, 0.49)
    theta_s = (1.04105, 0.00046)  # theta_* = r_s(z*) / D_A(z*)
    #theta_s = (1.04085, x) # theta_* = r_s(z*) / D_A(z*)

    zq = 3393.
    #DM = da / a

    theta_s_model = 144.61 / DMs
    print("Delta(100 theta_s) =", (theta_s_model * 100. - theta_s[0]))
    print("Frac(100 theta_s) =",
          (theta_s_model * 100. - theta_s[0]) / theta_s[1])
    #print("D_A,model =", DAz(1./(1.+1090.), plcdm))

    import pyccl as ccl
    cosmo = ccl.Cosmology(Omega_c=plcdm['omegaM'] - plcdm['omegaB'],
                          Omega_b=plcdm['omegaB'],
                          h=plcdm['h'],
                          Omega_k=0.,
                          w0=-1.,
                          wa=0.,
                          A_s=2.1e-9,
                          n_s=0.96,
                          m_nu=0.06)
    zstar = 1090.
    da_co = ccl.comoving_angular_distance(cosmo, 1. / (1. + zstar))
    theta_s_ccl = 144.61 / da_co
    print("Delta(100 theta_s) =", (theta_s_ccl * 100. - theta_s[0]))
    print("Frac(100 theta_s) =",
          (theta_s_ccl * 100. - theta_s[0]) / theta_s[1])

    exit()
    """
    # Try CCL plot
    import pyccl as ccl
    p = default_params
    OmegaB = 0.045
    cosmo = ccl.Cosmology(Omega_c=p['omegaM']-OmegaB, Omega_b=OmegaB, h=p['h'], 
                           Omega_k=0.02, w0=-1., wa=0., A_s=2.1e-9, n_s=0.96, 
                           m_nu=0.06)
    P.plot(z, ccl.comoving_angular_distance(cosmo, 1./(1.+z)) / DM0 - 1., 'm-')
    """

    # Physical matter fraction
    cmb_om = 0.1386
    cmb_om_err = 0.019 * 0.1386  # 1.9%
    this_om = pmodel['omegaM'] * pmodel['h']**2.
    P.text(30.,
           -0.1,
           "$\Delta\omega_m/\sigma_{\omega_m} = %+3.3f$" %
           ((this_om - cmb_om) / cmb_om_err),
           fontsize=13)

    P.xlabel("$z$", fontsize=16.)
    P.ylabel(r"$\Delta D / D$", fontsize=16.)

    #P.xlim((0.08, 3.))
    P.xlim((0.08, 1500.))
    #P.ylim((-0.5, 30.))
    P.xscale('log')

    P.legend(loc='upper right', frameon=False, ncol=2)

    P.tight_layout()
    P.show()
Ejemplo n.º 16
0
import pyccl as ccl
import matplotlib.pyplot as plt

zcmb, mb, mberr = np.loadtxt("Pantheon/lcparam_full_long_zhel.txt",
                             skiprows=1,
                             usecols=[1, 4, 5],
                             unpack=True)
N = len(zcmb)
cov = np.loadtxt("Pantheon/sys_full_long.txt", skiprows=1).reshape((N, N))
cov += np.diag(mberr**2)
assert (cov[3, 2] == cov[2, 3])  ## sanity

## Ok, now we will subtract magnitude in standard cosmology so that we can bin numbers than don't vary much across the inb

t = tc.ThinCandy()
D = ccl.comoving_angular_distance(t.CBase, 1 / (1 + zcmb)) * (1 + zcmb)
mu = 5 * np.log10(D)
mb -= mu

dz = 0.1
print("zmax=", zcmb.max())
#bins = np.digitize(zcmb,list(np.linspace(0,0.1,20))+list(np.logspace(np.log10(0.1),np.log10(zcmb.max()+0.1),20)))
binl = list(np.arange(0.1, 1.1, 0.15)) + list(np.arange(1.2, 2.5, 0.3))
bins = np.digitize(zcmb, binl)
Nbins = bins.max()

out = []
for bin in range(Nbins):
    w = np.where(bins == bin)[0]
    if (len(w) == 0):
        continue
Ejemplo n.º 17
0
    def realise_foreground_amp(self,
                               amp,
                               beta,
                               monopole,
                               smoothing_scale=None,
                               redshift=None):
        """
        Create realisation of the matter power spectrum by randomly sampling 
        from Gaussian distributions of variance P(k) for each k mode.
        
        Parameters:
            amp (float):
                Amplitude of foreground power spectrum, in units of the field 
                squared (e.g. if the field is in units of mK, this should be in 
                [mK]^2).
            
            beta (float):
                Angular power-law index.
            
            monopole (float):
                Zero-point offset of the foreground at the reference frequency. 
                Should be in the same units as the field, e.g. mK.
            
            smoothing_scale (float, optional):
                Additional angular smoothing scale, in degrees. Default: None 
                (no smoothing). 
                
            redshift (float, optional):
                Redshift to evaluate the centre of the box at. Default: Same value 
                as `self.box.redshift`.
        """
        # Check redshift
        if redshift is None:
            redshift = self.box.redshift
        scale_factor = 1. / (1. + redshift)

        # Calculate comoving distance to box redshift
        r = ccl.comoving_angular_distance(self.box.cosmo, scale_factor)

        # Angular Fourier modes (in 2D)
        k_perp = 2. * np.pi * np.sqrt(
            (self.box.Kx[:, :, 0] / self.box.Lx)**2. +
            (self.box.Ky[:, :, 0] / self.box.Ly)**2.)

        # Foreground angular power spectrum
        # \ell ~ k_perp r / 2
        # Use FG power spectrum model from Santos et al. (2005)
        C_ell = amp * (0.5 * k_perp * r / 1000.)**(beta)
        C_ell[np.isinf(C_ell)] = 0.  # Remove inf at k=0

        # Normalise the power spectrum properly (factor of area, and norm.
        # factor of 2D DFT)
        C_ell *= (self.box.N**4.) / (self.box.Lx * self.box.Ly)

        # Generate Gaussian random field with given power spectrum
        re = np.random.normal(0.0, 1.0, np.shape(k_perp))
        im = np.random.normal(0.0, 1.0, np.shape(k_perp))
        fg_k = (re + 1.j * im) * np.sqrt(C_ell)  # factor of 2x larger variance
        fg_k[k_perp == 0.] = 0.  # remove zero mode

        # Transform to real space. Discarding the imag part fixes the extra
        # factor of 2x in variance from above
        fg_x = fft.ifftn(fg_k).real + monopole

        # Apply angular smoothing
        if smoothing_scale is not None:
            ang_x, ang_y = self.box.pixel_array(redshift=redshift)
            sigma = smoothing_scale / (ang_x[1] - ang_x[0])
            fg_x = scipy.ndimage.gaussian_filter(fg_x,
                                                 sigma=sigma,
                                                 mode='wrap')

        return fg_x
Ejemplo n.º 18
0
    def bgplot(self):
        print(ccl.sigma8(self.CBase), self.rd(self.CBase))
        print("getting open")

        # [(aiso,'isotropic BAO'), (aperp, 'transverse BAO'), (apar,
        #'radial BAO'), (sn, 'SN distance '), (fs8, 'fsigma8'),
        # (shearshear, 'WL shear auto')]):

        self.getModels()

        f, axl = plt.subplots(
            3,
            2,
            facecolor="w",
            gridspec_kw={
                "width_ratios": (3, 1),
                "hspace": 0.0,
                "wspace": 0.05
            },
            figsize=(10, 6),
        )

        print(axl)  # [(self.aiso,'BAO $\\bigcirc$'),
        for i, ((fun, name), (axl, axr)) in enumerate(
                zip(
                    [
                        (self.aperp, "BAO $\perp$"),
                        (self.apar, "BAO $\parallel$"),
                        (self.sn, "SN"),
                    ],
                    axl,
                )):

            for model, label, style in [
                (self.CBase, "LCDM", "k:"),
                (self.Copen, "OLCDM", "r--"),
                (self.Cw, "wCDM", "g-."),
                (self.Cmnu, "$\\nu$CDM", "b-"),
            ]:
                vals = fun(model)
                axl.plot(self.zar[:self.Nl],
                         vals[:self.Nl],
                         style,
                         label=label)
                axr.plot(self.zar[-self.Nr:], vals[-self.Nr:], style)

            if "perp" in name:
                for zb, iso, isoe, perp, perpe, par, pare in self.baodata:
                    axr.errorbar(1150, 1, yerr=0.000605211, fmt="ko")
                    if perp > 0:
                        norm = ccl.comoving_angular_distance(
                            self.CBase, 1 / (1 + zb)) / self.rd(self.CBase)
                        # print (zb,norm,perp,perpe,perp/norm,perpe/norm)
                        axl.errorbar(zb,
                                     perp / norm,
                                     yerr=perpe / norm,
                                     fmt="ko")
                    if iso > 0:
                        print(self.rd(self.CBase))
                        normperp = ccl.comoving_angular_distance(
                            self.CBase, 1 / (1 + zb)) / self.rd(self.CBase)
                        normpar = 299792.45 / (ccl.h_over_h0(
                            self.CBase, 1 /
                            (1 + zb)) * self.CBase["H0"] * self.rd(self.CBase))
                        norm = (zb * normpar)**(1 / 3) * normperp**(2 / 3)
                        axl.errorbar(zb,
                                     iso / norm,
                                     yerr=isoe / norm,
                                     fmt="ko")

            elif "par" in name:

                for zb, iso, isoe, perp, perpe, par, pare in self.baodata:
                    if par > 0:
                        norm = 299792.45 / (ccl.h_over_h0(
                            self.CBase, 1 /
                            (1 + zb)) * self.CBase["H0"] * self.rd(self.CBase))
                        # print (zb,norm,par,pare,par/norm,pare/norm)
                        axl.errorbar(zb,
                                     par / norm,
                                     yerr=pare / norm,
                                     fmt="ko")

            elif "SN" in name:
                axl.errorbar(self.snz, self.snval, yerr=self.snerr, fmt="ko")

            if i == 1:
                axl.legend(fontsize=12,
                           ncol=2,
                           frameon=False,
                           loc="lower center")

            axl.set_ylabel(name, fontsize=14)
            axl.spines["right"].set_visible(False)
            axr.spines["left"].set_visible(False)
            # axl.yaxis.tick_left()
            # axl.tick_params(labelright='off')
            axl.tick_params(axis="x", direction="inout", length=5)
            axr.tick_params(axis="x", direction="inout", length=5)
            axl.patch.set_alpha(0.0)
            axr.patch.set_alpha(0.0)

            axl.set_xlim(0.0, 3.1)
            axr.set_xlim(1100, 1200)
            axr.set_xticks([1120, 1200])

            if i < 2:
                axl.set_ylim(0.85, 1.15)
                axl.set_yticks([0.90, 1.0, 1.1])
            else:
                axl.set_ylim(0.8, 1.2)
                axl.set_yticks([0.9, 1.0, 1.1])

            if i == 0:
                axr.set_ylim(0.995, 1.005)
                axr.set_yticks([0.997, 1.0, 1.003])
            elif i == 1:
                axr.set_ylim(0.995, 1.005)
                axr.set_yticks([0.997, 1.0, 1.003])
            elif i == 2:
                axr.set_ylim(0.8, 1.2)
                axr.set_yticks([0.9, 1.0, 1.1])

            if i < 2:
                for l in axl.get_xticklabels():
                    l.set_visible(False)
                for l in axr.get_xticklabels():
                    l.set_visible(False)
            for l in axr.get_yticklabels():
                l.set_visible(False)
            axr.get_yaxis().tick_right()  # set_visible(False)

            d = 0.05
            kwargs = dict(transform=axl.transAxes, color="k", clip_on=False)
            axl.plot((1 - d / 5, 1 + d / 5), (-d, +d), **kwargs)
            axl.plot((1 - d / 5, 1 + d / 5), (1 - d, 1 + d), **kwargs)
            kwargs = dict(transform=axr.transAxes, color="k", clip_on=False)
            axr.plot((-d * 3 / 5, +d * 3 / 5), (-d, +d), **kwargs)
            axr.plot((-d * 3 / 5, +d * 3 / 5), (1 - d, 1 + d), **kwargs)
            if i == 2:
                axl.set_xlabel("$z$", fontsize=14)

        # plt.tight_layout()
        plt.savefig(f"output/thincandy_bg.pdf")

        plt.show()
Ejemplo n.º 19
0
 def shearpower(self, C, z):
     tracer = ccl.WeakLensingTracer(
         C, dndz=(self.zar, np.exp(-((z - self.zar)**2) / (2 * 0.1**2))))
     ell = 0.2 * ccl.comoving_angular_distance(C, 1 / (1 + z))
     return ccl.angular_cl(C, tracer, tracer, ell)
Ejemplo n.º 20
0
 def _t(h):
     C, _ = _C(h)
     d = ccl.comoving_angular_distance(C, acmb) / self.rd(C)
     return d - target
Ejemplo n.º 21
0
 def aperp(self, C):
     aperp = ccl.comoving_angular_distance(C, self.aar) / self.rd(C)
     aperp0 = ccl.comoving_angular_distance(self.CBase, self.aar) / self.rd(
         self.CBase)
     return aperp / aperp0