示例#1
0
 def create_concentration_spline(self):
     """
     Creates a spline for the concentration using colossus.
     """
     try:
         from colossus.halo import concentration
         from colossus.cosmology import cosmology
     except ImportError:
         print("colossus not installed. No concentration spline available.")
         return
     cosmo = self.args['cosmology']
     cos = {
         'flat': True,
         'H0': cosmo['h'] * 100.,
         'Om0': cosmo['Omega_m'],
         'Ob0': cosmo['Omega_b'],
         'sigma8': cosmo['sigma8'],
         'ns': cosmo['ns']
     }
     cosmology.addCosmology('fiducial', cos)
     cosmology.setCosmology('fiducial')
     z = self.args['z']
     M = np.logspace(12, 17, 50)
     c = np.zeros_like(M)
     for i in range(len(M)):
         c[i] = concentration.concentration(M[i],
                                            '200m',
                                            z=z,
                                            model='diemer15')
     self.args['cspline'] = interp.interp1d(M, c)
     return
def get_concentration_spline(cal=False):
    from colossus.halo import concentration
    from colossus.cosmology import cosmology
    cosmo = get_cosmo_default(cal)
    cos = {
        'flat': True,
        'H0': cosmo['h'] * 100.,
        'Om0': cosmo['om'],
        'Ob0': cosmo['ob'],
        'sigma8': cosmo['sigma8'],
        'ns': cosmo['ns']
    }
    cosmology.addCosmology('fiducial', cos)
    cosmology.setCosmology('fiducial')
    N = 20
    M = np.logspace(12, 17, N)
    z = np.linspace(0.2, 0.65, N)
    c_array = np.ones((N, N))
    for i in range(N):
        for j in range(N):
            c_array[j, i] = concentration.concentration(M[i],
                                                        '200m',
                                                        z=z[j],
                                                        model='diemer15')
    return interp2d(M, z, c_array)
def calculate_concentration(redshift,M200m,cosmology):
    from colossus.halo import concentration
    from colossus.cosmology import cosmology as col_cosmology
    params = {'flat': True, 'H0': cosmology['h'], 'Om0': cosmology['om'],
              'Ob0': 1.0-cosmology['om'],
              'sigma8': cosmology['sigma8'], 'ns': cosmology['ns']}
    col_cosmology.addCosmology('fiducial_cosmology',params)
    col_cosmology.setCosmology('fiducial_cosmology')
    concentration = concentration.concentration(M200m,'200m',redshift,model='diemer15')
    print "concentration = ",concentration,2.0
    return 2.0#concentration
def get_conc(M, z):
    colcos = {
        "H0": cosmo['h'] * 100.,
        "Om0": cosmo['om'],
        'Ob0': 0.049017,
        'sigma8': 0.83495,
        'ns': 0.96191,
        'flat': True
    }
    col_cosmology.addCosmology('fox_cosmology', colcos)
    col_cosmology.setCosmology('fox_cosmology')

    om = cosmo['om']
    return conc.concentration(M, '200m', z, model='diemer15')
def test_colossus():
    h = 0.7
    Omega_m = 0.3
    Omega_b = 0.05
    sigma8 = 0.847533481324
    ns = 0.96
    As = 2.215e-9
    #Try importing colossus
    try:
        from colossus.halo import concentration as colc
        from colossus.cosmology import cosmology
        cos = {'flat':True,'H0':h*100.,'Om0':Omega_m,'Ob0':Omega_b,'sigma8':sigma8,'ns':ns}
        cosmology.addCosmology('fiducial', cos)
        colcos = cosmology.setCosmology('fiducial')
        k = np.logspace(-5, 2, num=1000)/h #Mpc^-1
        pcol = colcos.matterPowerSpectrum(k) #(Mpc/h)^3
    except ImportError:
        print("colossus not installed, skipping test")
示例#6
0
    def hmf(self, z,  Mmin, Mmax, q_out = 'dndlnM', hmf_code='colossus', print_cosmo=False):
        if(hmf_code=='colossus'):
            params = {'flat': True, 'H0': self.H0, 'Om0': self.om, 'Ob0': self.ob, 'sigma8': self.sigma8, 'ns': self.ns}
            col_cosmology.addCosmology('myCosmo', params)
            colcosmo=col_cosmology.setCosmology('myCosmo')
            
            if print_cosmo:
                print(colcosmo)
    
            #Mass_bin = np.logspace(np.log10(Mmin),np.log10(Mmax), num=500)
            
            Mh = 10**(np.linspace(np.log10(Mmin),np.log10(Mmax), num=200))
            
            Mh=Mh/self.h
            
            #mfunc = mass_function.massFunction(Mh, z, mdef = self.halo_model_mdef, model = self.halo_model, q_out = q_out)
            
            mfunc = mass_function.massFunction(Mh, z, mdef = '200m', model = 'tinker08', q_out = q_out)
            
            mpc_to_m= 3.086e+22
            
            mfunc*=(mpc_to_m)**-3
                    
            dndm=mfunc
            
            return Mh, dndm
        
        
        if(hmf_code=='hmf'):
            from hmf import cosmo as cosmo_hmf
            my_cosmo = cosmo_hmf.Cosmology()
            my_cosmo.update(cosmo_params={"H0":self.H0,"Om0":self.om,"Ode0":self.ol,"Ob0":self.ob})

            mf=MassFunction(Mmin=np.log10(Mmin), Mmax=np.log10(Mmax), hmf_model= 'ST')
            mf.update(z=z)
            
            mpc_to_m= 3.086e+22
            #hm, dndm= mf.m, mf.dndlnm
            
            hm, dndm= mf.m/self.h, mf.dndlnm *(mpc_to_m)**-3 #* self.h**4*(mpc_to_m)**-3
            
           # dndm*=(mpc_to_m)**-3
    
            return hm, dndm
示例#7
0
VT = (4 * np.pi / 3) * (chi_max**3 - chi_min**3)
dndz = (4 * np.pi) * (chi_array_r**2) * dchi_dz_array_r / VT

dndm_model = 'crocce10'
bias_model = 'bhattacharya11'
mdef = 'fof'
cosmo_params = {
    'flat': True,
    'H0': 70.0,
    'Om0': 0.25,
    'Ob0': 0.0448,
    'sigma8': 0.8,
    'ns': 0.95
}

cosmology.addCosmology('mock_cosmo', cosmo_params)
cosmo_colossus = cosmology.setCosmology('mock_cosmo')
h = cosmo_params['H0'] / 100.


# get the halo mass function and halo bias using the colossus module
def get_dndm_bias(M_mat, z_array, mdef):

    dndm_array_Mz, bm_array_Mz = np.zeros(M_mat.shape), np.zeros(M_mat.shape)

    for j in range(len(z_array)):
        M_array = M_mat[j, :]
        dndm_array_Mz[j, :] = (1. / M_array) * mass_function.massFunction(
            M_array, z_array[j], mdef=mdef, model=dndm_model, q_out='dndlnM')

        bm_array_Mz[j, :] = bias.haloBias(M_array,
示例#8
0
 def set_cosmo_colossus(self):
     params = {'flat': True, 'H0': self.H0, 'Om0': self.om, 'Ob0': self.ob, 'sigma8': self.sigma8, 'ns': self.ns}
     col_cosmology.addCosmology('myCosmo', params)
     cosmo_col=col_cosmology.setCosmology('myCosmo')
     
     print(cosmo_col)
示例#9
0
def DStheo(theta, args):
    """
    Computes de theoretical :math:`\Delta\Sigma_{NFW}` profile for a given mass
    :math:`m_{200}`, z and cosmology.

    Parameters
    ----------
    theta: tuple
        Parameters for the mcmc
    args: dict
        Contains the cosmology and other mean values computed from the data

    Returns
    -------
    ds: np.array
        The thoretical :math:`\Delta\Sigma_{NFW}` profile

    Notes
    -----
    The parameters for the NFW function are the mass :math:`m_{200}` and the
    concentration :math:`c_{200}`. However, in this anlysis, we use the
    Duffy et al. (2008) concetration-mass relation to get the profile only
    as a function of the mass. See: https://github.com/joergdietrich/NFW for
    more details on the NFW function.
    """
    runtype = args['runtype']
    runconfig = args['runconfig']

    if runtype == 'data':
        if runconfig == 'Full':
            m200, pcc, Am, B0, Rs = theta  #M200c [Msun]
        elif runconfig == 'OnlyM':
            m200 = theta[0]
        elif runconfig == 'FixAm':
            m200, pcc, B0, Rs = theta
    elif runtype == 'cal':
        m200 = theta[0]
    elif runtype == 'calsys':
        if runconfig == 'Full':
            m200, pcc, Am, B0, Rs = theta  #M200c [Msun]

    h = args['h']
    z_mean = args['z_mean']
    R = args['R']  #in physical [Mpc]
    cosmo = args['cosmo']  #astropy cosmology object
    cmodel = args[
        'cmodel']  #diemer18 (obs.: lastest version of Colossus renamed to diemer19)
    twohalo = args['twohalo']
    factor2h = args['factor2h']  #boolean, if True multiply 2-halo term by h
    cosmodict = args['cosmodict']
    omega_m = cosmodict['om']
    sigma_crit_inv = args['Sigma_crit_inv']

    #Setting up the cosmology for Colossus
    params = {
        'flat': True,
        'H0': cosmodict['h'] * 100.,
        'Om0': cosmodict['om'],
        'Ob0': cosmodict['ob'],
        'sigma8': cosmodict['sigma8'],
        'ns': cosmodict['ns']
    }
    cosmology.addCosmology('myCosmo', params)
    cosmoc = cosmology.setCosmology('myCosmo')
    cmodel = cmodel

    c200c = concentration.concentration(
        m200 * h, '200c', z_mean, model=cmodel,
        conversion_profile='nfw')  #m200c_in is [Msun/h], m200c_out is [Msun/h]
    nfw = NFW(m200,
              c200c,
              z_mean,
              cosmology=cosmo,
              overdensity_type='critical')  #input mass should be in [Msun]

    #For DeltaSigma calculation, data and sim, the radius has to be in physical [Mpc]
    if runtype == 'cal':
        ds = (nfw.delta_sigma(R).value
              ) / 1.e12  #DeltaSigma is in units of physical [M_sun/Mpc^2]
        #This two-halo part was not used in the analysis, the compuation is too slow
        if twohalo:
            #Adding the 2-halo term
            b = bias.haloBias(m200 * h, z_mean, '200c',
                              model='tinker10')  #mass_in is [Msun/h]
            outer_term_xi = profile_outer.OuterTermCorrelationFunction(
                z=z_mean, bias=b)
            p_nfw = profile_nfw.NFWProfile(
                M=m200 * h,
                c=c200c,
                z=z_mean,
                mdef='200c',
                outer_terms=[outer_term_xi])  #mass_in is [Msun/h]

            #Radius in physical kpc/h
            two_nfw0 = p_nfw.deltaSigmaOuter((R * 1e3) * h,
                                             interpolate=True,
                                             interpolate_surface_density=False,
                                             min_r_interpolate=1.e-6 * h,
                                             max_r_integrate=2.e5 * h,
                                             max_r_interpolate=2.e5 * h)
            two_nfw1 = two_nfw0 / 1.e6  #in physical [h Msun/pc^2]

            if factor2h:
                two_nfw = h * (two_nfw1 * h
                               )  #something like physical [Msun/(h pc^2)]
            else:
                two_nfw = (
                    two_nfw1 * h
                )  #in physical [Msun/pc^2] #This should be the right one

            ds_model = ds + two_nfw  #NFW + 2-halo in physical [Msun/pc^2] if factor2h=False
        else:
            ds_model = ds
        return ds_model  #physical [M_sun/pc^2]

    if runtype == 'data' or runtype == 'calsys':

        ds = (
            nfw.delta_sigma(R).value
        ) / 1.e12  #units of h Msun/pc^2 physical (but h=1, so actually is M_sun/pc^2)
        sigma = (nfw.sigma(R).value) / 1.e12

        # Computing miscetering correction from data
        m200p = m200
        z = np.array([z_mean])

        if runtype == 'data':
            cluster = ClusterEnsemble(z,
                                      cosmology=FlatLambdaCDM(H0=100, Om0=0.3),
                                      cm='Diemer18',
                                      cmval=c200c)
            misc_off = 0.1326  #here in [Mpc], since h=1

        elif runtype == 'calsys':
            cluster = ClusterEnsemble(z,
                                      cosmology=FlatLambdaCDM(H0=h * 100,
                                                              Om0=omega_m),
                                      cm='Diemer18',
                                      cmval=c200c)
            misc_off = 0.1326 / h  #input needs to be in units of [Mpc]

        if np.shape(m200p) == (1, 1):
            m200p = np.reshape(m200p, (1, ))
        try:
            cluster.m200 = m200p  #M200c [Msun]
        except TypeError:
            cluster.m200 = np.array([m200p])

        rbins = R  # in physical [Mpc]

        offsets = np.ones(cluster.z.shape[0]) * misc_off
        cluster.calc_nfw(rbins, offsets=offsets)  #NFW with offset

        dsigma_offset = cluster.deltasigma_nfw.mean(
            axis=0)  #physical [M_sun/pc^2], but if h=1 is [h M_sun/pc**2]
        DSmisc = dsigma_offset.value  #physical [Msun/pc^2]

        sigma_offset = cluster.sigma_nfw.mean(
            axis=0)  #physical [M_sun/pc**2], but if h=1 is [h M_sun/pc**2]
        Smisc = sigma_offset.value  #physical [Msun/pc^2]

        if runconfig == 'OnlyM':
            pcc = 0.75
            B0 = 0.50
            Rs = 2.00

        #The final model
        full_Sigma = pcc * sigma + (1 - pcc) * Smisc

        full_model = pcc * ds + (1 - pcc) * DSmisc

        if runconfig == 'Full':
            full_model *= Am  #shear+photo-z bias correction
        elif runconfig == 'OnlyM' or 'FixAm':
            full_model = full_model

        #Note: R (rbins) and Rs are in physical [Mpc], need to be comoving [Mpc/h]
        boost_model = ct.boostfactors.boost_nfw_at_R(rbins * h * (1 + z_mean),
                                                     B0, Rs * h * (1 + z_mean))

        full_model /= boost_model  #boost-factor

        full_model /= (1 - full_Sigma * sigma_crit_inv)  #Reduced shear

        return full_model  # in physical [M_sun/pc^2]
示例#10
0
#Get the power spectra wavenumbers
k = np.loadtxt("txt_files/P_files/k.txt")

#This is the fox sim cosmology
h = 0.670435
cosmo = {"h": h, "om": 0.31834, "ok": 0.0}
cosmo["ode"] = 1.0 - cosmo["om"]
colcos = {
    "H0": cosmo['h'] * 100.,
    "Om0": cosmo['om'],
    'Ob0': 0.049017,
    'sigma8': 0.83495,
    'ns': 0.96191,
    'flat': True
}
col_cosmology.addCosmology('fiducial_cosmology', colcos)
col_cosmology.setCosmology('fiducial_cosmology')
params = {
    "NR": 300,
    "Rmin": 0.01,
    "Rmax": 200.0,
    "Nbins": 15,
    "delta": 200,
    "Rmis": 0.2,
    "fmis": 0.0,
    "miscentering": 0,
    "averaging": 1
}

#masses = np.loadtxt("txt_files/BF_masses.txt")
masses = np.loadtxt("txt_files/mcmc_masses.txt")
示例#11
0
################### Pinocchio Cosmological Quantities ###################

(a, t, D, D2, D31, D32) = np.loadtxt(params.pincosmofile,
                                     usecols=(0, 1, 2, 3, 4, 5),
                                     unpack=True)
(R, DeltaRGauss, k, Pk) = np.loadtxt(params.pincosmofile,
                                     usecols=(9, 10, 12, 13),
                                     unpack=True)

k = k * 100 / params.h0true
Pk = Pk / (100 / params.h0true)**3

# Setting cosmology for concentrations
pdict = {'flat': True, 'H0': params.h0true, 'Om0': params.omega0, 'Ob0': params.omegabaryon,\
          'sigma8': params.sigma8, 'ns': params.ns}
colossus.addCosmology('myCosmo', pdict)
colossus.setCosmology('myCosmo')
del pdict


class PolyFitOrderTooLow(Exception):
    pass


class PolyFitIsNotMonotonic(Exception):
    pass


def getWisePolyFit(x, y, dtype=np.float32):

    for norder in range(1, params.norder + 1):
示例#12
0
文件: tabcorr.py 项目: j-dr/TabCorr
    def predict(self,
                model,
                separate_gal_type=False,
                baryon_kwargs={},
                **occ_kwargs):
        """
        Predicts the number density and correlation function for a certain
        model.

        Parameters
        ----------
        model : HodModelFactory
            Instance of ``halotools.empirical_models.HodModelFactory``
            describing the model for which predictions are made.

        separate_gal_type : boolean, optional
            If True, the return values are dictionaries divided by each galaxy
            types contribution to the output result.

        **occ_kwargs : dict, optional
                Keyword arguments passed to the ``mean_occupation`` functions
                of the model.

        Returns
        -------
        ngal : numpy.array or dict
            Array or dictionary of arrays containing the number densities for
            each galaxy type stored in self.gal_type. The total galaxy number
            density is the sum of all elements of this array.

        xi : numpy.array or dict
            Array or dictionary of arrays storing the prediction for the
            correlation function.
        """

        try:
            assert (sorted(model.gal_types) == sorted(
                ['centrals', 'satellites']))
        except AssertionError:
            raise RuntimeError('The model instance must only have centrals ' +
                               'and satellites as galaxy types. Check the ' +
                               'gal_types attribute of the model instance.')

        try:
            assert (model._input_model_dictionary['centrals_occupation'].
                    prim_haloprop_key == self.attrs['prim_haloprop_key'])
            assert (model._input_model_dictionary['satellites_occupation'].
                    prim_haloprop_key == self.attrs['prim_haloprop_key'])
        except AssertionError:
            raise RuntimeError('Mismatch in the primary halo properties of ' +
                               'the model and the TabCorr instance.')

        try:
            if hasattr(model._input_model_dictionary['centrals_occupation'],
                       'sec_haloprop_key'):
                assert (model._input_model_dictionary['centrals_occupation'].
                        sec_haloprop_key == self.attrs['sec_haloprop_key'])
            if hasattr(model._input_model_dictionary['satellites_occupation'],
                       'sec_haloprop_key'):
                assert (model._input_model_dictionary['satellites_occupation'].
                        sec_haloprop_key == self.attrs['sec_haloprop_key'])
        except AssertionError:
            raise RuntimeError('Mismatch in the secondary halo properties ' +
                               'of the model and the TabCorr instance.')

        try:
            assert np.abs(model.redshift - self.attrs['redshift']) < 0.05
        except AssertionError:
            raise RuntimeError('Mismatch in the redshift of the model and ' +
                               'the TabCorr instance.')

        mean_occupation = np.zeros(len(self.gal_type))

        mask = self.gal_type['gal_type'] == 'centrals'
        mean_occupation[mask] = model.mean_occupation_centrals(
            prim_haloprop=self.gal_type['prim_haloprop'][mask],
            sec_haloprop_percentile=(
                self.gal_type['sec_haloprop_percentile'][mask]),
            **occ_kwargs)
        mean_occupation[~mask] = model.mean_occupation_satellites(
            prim_haloprop=self.gal_type['prim_haloprop'][~mask],
            sec_haloprop_percentile=(
                self.gal_type['sec_haloprop_percentile'][~mask]),
            **occ_kwargs)

        ngal = mean_occupation * self.gal_type['n_h'].data

        if self.attrs['mode'] == 'auto':
            ngal_sq = np.outer(ngal, ngal)
            ngal_sq = 2 * ngal_sq - np.diag(np.diag(ngal_sq))
            ngal_sq = symmetric_matrix_to_array(ngal_sq)
            xi = self.tpcf_matrix * ngal_sq / np.sum(ngal_sq)
        elif self.attrs['mode'] == 'cross':
            xi = self.tpcf_matrix * ngal / np.sum(ngal)

        # baryonification
        if (len(baryon_kwargs) > 0) & (has_bcm):
            #params = {'flat': True, 'H0': 67.2, 'Om0': 0.31, 'Ob0': 0.049, 'sigma8': 0.81, 'ns': 0.95}
            params = baryon_kwargs['cosmo_params']
            params['flat'] = True
            use_2h = baryon_kwargs.pop('use_2h', True)
            use_clf_fsat = baryon_kwargs.pop('use_clf_fsat', False)
            print(use_clf_fsat)
            cosmology.addCosmology('myCosmo', params)
            cosmology.setCosmology('myCosmo')

            halo_mass = np.array(self.gal_type['prim_haloprop'])

            par = bfc.par()
            par.baryon.eta_tot = baryon_kwargs['eta_tot']
            par.baryon.eta_cga = baryon_kwargs['eta_cga']

            if 'transfct' in baryon_kwargs.keys():
                par.files.transfct = baryon_kwargs['transfct']
            else:
                dirname = os.path.dirname(os.path.abspath(__file__))
                par.files.transfct = '{}/files/CDM_PLANCK_tk.dat'.format(
                    dirname)

            rbin = annular_area_weighted_midpoints(self.tpcf_args[1])
            rho_r = annular_area_weighted_midpoints(np.logspace(-2, 2, 100))

            n_mhalo = 10
            mhalo_min = np.min(np.log10(halo_mass))
            mhalo_max = np.max(np.log10(halo_mass))
            mhalo_grid = np.logspace(mhalo_min, mhalo_max, n_mhalo)

            halo_conc_grid = concentration.concentration(
                mhalo_grid, 'vir', self.attrs['redshift'], model='diemer19')
            # fudge factor accounting for scatter in mvir-c relation
            halo_conc_grid = halo_conc_grid * 0.93

            if use_clf_fsat:
                f_sat = np.array([
                    model.model_dictionary['satellites_occupation'].
                    stellar_mass_fraction(m) for m in mhalo_grid
                ])
                f_cen = np.array([
                    model.model_dictionary['centrals_occupation'].
                    stellar_mass_fraction(m) for m in mhalo_grid
                ])
                f_star = f_sat + f_cen
                print(f_star)
                sys.stdout.flush()
            else:
                f_star = [None] * n_mhalo
                f_cen = [None] * n_mhalo

            # baryon params
            par.baryon.Mc = baryon_kwargs['Mc']
            par.baryon.mu = baryon_kwargs['mu']
            par.baryon.thej = baryon_kwargs['thej']
            if use_2h:
                # 2h term
                vc_r, vc_m, vc_bias, vc_corr = bfc.cosmo(par)
                # print('2h term took {}s'.format(end - start))

                bias_tck = splrep(vc_m, vc_bias, s=0)
                corr_tck = splrep(vc_r, vc_corr, s=0)

                cosmo_bias_grid = splev(mhalo_grid, bias_tck)
                cosmo_corr = splev(rho_r, corr_tck)

                profs = [
                    bfc.profiles(rho_r,
                                 mhalo_grid[i],
                                 halo_conc_grid[i],
                                 cosmo_corr,
                                 cosmo_bias_grid[i],
                                 par,
                                 fstar=f_star[i],
                                 fcga=f_cen[i])[1]
                    for i in range(len(mhalo_grid))
                ]
            else:
                profs = [
                    bfc.onehalo_profiles(rho_r,
                                         mhalo_grid[i],
                                         halo_conc_grid[i],
                                         par,
                                         fstar=f_star[i],
                                         fcga=f_cen[i])[1]
                    for i in range(len(mhalo_grid))
                ]

            correction_factors_grid = [
                dens_to_ds(rbin, rho_r, profs[i], epsabs=1e-1, epsrel=1e-3)[2]
                for i in range(len(mhalo_grid))
            ]
            correction_factors_grid = np.array(correction_factors_grid)
            correction_factors_spl = interp1d(mhalo_grid,
                                              correction_factors_grid.T,
                                              fill_value='extrapolate',
                                              bounds_error=False)
            correction_factors = correction_factors_spl(halo_mass)

            xi = correction_factors * xi

        elif (len(baryon_kwargs) > 0):
            raise ImportError(
                "You passed me baryon correction module parameters, but I couldn't import the baryonification module"
            )

        if not separate_gal_type:
            ngal = np.sum(ngal)
            xi = np.sum(xi, axis=1).reshape(self.tpcf_shape)
            return ngal, xi
        else:
            ngal_dict = {}
            xi_dict = {}

            for gal_type in np.unique(self.gal_type['gal_type']):
                mask = self.gal_type['gal_type'] == gal_type
                ngal_dict[gal_type] = np.sum(ngal[mask])

            if self.attrs['mode'] == 'auto':
                for gal_type_1, gal_type_2 in (
                        itertools.combinations_with_replacement(
                            np.unique(self.gal_type['gal_type']), 2)):
                    mask = symmetric_matrix_to_array(
                        np.outer(gal_type_1 == self.gal_type['gal_type'],
                                 gal_type_2 == self.gal_type['gal_type'])
                        | np.outer(gal_type_2 == self.gal_type['gal_type'],
                                   gal_type_1 == self.gal_type['gal_type']))
                    xi_dict['%s-%s' % (gal_type_1, gal_type_2)] = np.sum(
                        xi * mask, axis=1).reshape(self.tpcf_shape)

            elif self.attrs['mode'] == 'cross':
                for gal_type in np.unique(self.gal_type['gal_type']):
                    mask = self.gal_type['gal_type'] == gal_type
                    xi_dict[gal_type] = np.sum(xi * mask,
                                               axis=1).reshape(self.tpcf_shape)

            return ngal_dict, xi_dict
示例#13
0
cosmo = {"h": 0.7, "om": 0.3}


def get_cosmo():
    return cosmo


default_cos = {
    "H0": cosmo['h'] * 100.,
    "Om0": cosmo['om'],
    'Ob0': 0.05,
    'sigma8': 0.8,
    'ns': 0.96
}
cosmology.addCosmology('fiducial', default_cos)
cosmology.setCosmology('fiducial')


def get_concentration(M, z):
    return concentration.concentration(M, '200m', z=z, model='diemer15')


def get_lams():
    return 0


def get_zs():
    return 0.4  # BS value for now

示例#14
0
from astropy import units as u
import kmeans_radec
from scipy.optimize import curve_fit
from astropy.cosmology import FlatLambdaCDM
cosmo = FlatLambdaCDM(H0=70, Om0=0.3)
from colossus.halo import *
from colossus.cosmology import cosmology
params = {
    'flat': True,
    'H0': 70.,
    'Om0': 0.3,
    'Ob0': 0.05,
    'sigma8': 0.8,
    'ns': 0.95
}
cosmology.addCosmology('SimpleCosmo', params)
Cosmo = cosmology.setCosmology('SimpleCosmo')
h = Cosmo.H0 / 100

### DES data ###
clusters = pf.open(
    'y3_gold_2.2.1_wide_sofcol_run2_redmapper_v6.4.22+2_lgt20_vl02_catalog.fit'
)[1].data
#redshift and richness cut
l_t = clusters['LAMBDA_CHISQ']
z_t = clusters['Z_LAMBDA']
indcl = (l_t > 56.) * (z_t > 0.25) * (z_t < 0.7)

clusters = clusters[indcl]
memid_rm = clusters['MEM_MATCH_ID']
ra_rm = clusters['RA']
示例#15
0
import colossus
from colossus.cosmology import cosmology
from colossus.halo import mass_so

# Colossus params for HSC
params_hsc = {
    'flat': True,
    'H0': 70.0,
    'Om0': 0.3,
    'Ob0': 0.049,
    'sigma8': 0.81,
    'ns': 0.95
}

h_song = .7
cosmology.addCosmology('huang18', params_hsc)

# Colossus params for UM
params_um = {
    'flat': True,
    'H0': 67.77,
    'Om0': 0.307115,
    'Ob0': 0.048206,
    'sigma8': 0.8228,
    'ns': 0.96
}

h_smdpl = 0.6777
cosmology.addCosmology(
    'SMDPL', params_um)  # this is what Song had me use when doing the sat frac
cosmo_um = cosmology.setCosmology('SMDPL')
示例#16
0
classcosmo = Class()
classcosmo.set(foxclass)
classcosmo.compute()

# Fox cosmology for Colossus
foxcolossus = {
    'flat': True,
    'H0': h * 100,
    'Om0': Omega_m,
    '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
示例#17
0
             label='data')
plt.xscale('log')
plt.yscale('log')
plt.xlabel(r'$M_{\odot}$', fontsize=18)
plt.ylabel(r'dn/dM $[(Mpc/h)^{-3}]$', fontsize=18)
plt.grid(True)
plt.tight_layout()

#Now I want to fit it
#consider the model (comparat17, tinker08...)
#NB: z will have to be the same of the simulation analyzed!!!
from colossus.lss import mass_function as mf
from colossus.cosmology import cosmology
from colossus.lss import peaks
#cosmology.setCosmology('planck18')
cosmology.addCosmology('myCosmo', params)  #params was defined at line 24
cosmo = cosmology.setCosmology('myCosmo')

#print(cosmo.rho_m(0.0))


#fitting with Bhattacharya 2011
def mass_function_rseppi(Mass):
    cosmo = cosmology.getCurrent()
    delta_c = peaks.collapseOverdensity(z=z)
    R = peaks.lagrangianR(Mass)
    sigma = cosmo.sigma(R=R, z=z)
    nu = delta_c / sigma
    nu2 = nu**2
    zp1 = 1.0 + z
    A = 0.333 * zp1**-0.11
示例#18
0
# plotting and showing
PLOT = True
SHOW = True
# rotation applied to mollweide view plots - not a healpy rotator
rotmoll=[40,55,-90]

# COSMOLOGY SECTION
LCDMmodel    = FlatLambdaCDM(Om0 = 0.319, H0 = 67.0)
LCDMmodelLF  = FlatLambdaCDM(Om0 = 0.300, H0 = 70.0)
Mpc_h    = u.def_unit('Mpc_h', u.Mpc/LCDMmodel.h)
Mpc_h_LF = u.def_unit('Mpc_h_LF', u.Mpc/LCDMmodel.h)
cm_LF    = u.def_unit('cm_LF', u.cm)
l_unit   = Mpc_h
params = {'flat': True, 'H0': 67.0, 'Om0': 0.319, 'Ob0': 0.049, 'sigma8': 0.83, 'ns': 0.96, 'relspecies':False}
cosmology.addCosmology('FS', params)
cosmo = cosmology.setCosmology('FS')
cmrelation = "diemer19"

# LE3 CATALOGS SECTION
cat4le3_format="fits"
WriteLE3Random=True
max_PKs_in_script=50
max_2PCFs_in_script=50
# PK parameters; with Lbox=None compute_Lbox is set to 'true'
Lbox = 2500.
ngrid = 512

###############################################
# What is written below should not be changed #
###############################################
示例#19
0
beta_def = 1.0
eta_def  = 0.7
Nmah = 9999
Nradii = 500
N_r200m_mult = 2
# NOTE: We use zi=30., which works to be the equivalent of starting
# at the redshift where the halo mass reaches psi_res=10^-4
zi=30.
zobs = 0.0

# four extremes with low/high Om0 and sigma8
# note that the Omega_Lambda is changed accordingly by varying Om0
fiducial_params = cosmology.cosmologies['planck18'].copy()
fiducial_params['Om0'] = 0.1
cosmology.addCosmology('planck18_vlO', fiducial_params)
fiducial_params = cosmology.cosmologies['planck18'].copy()
fiducial_params['Om0'] = 0.5
cosmology.addCosmology('planck18_vhO', fiducial_params)
fiducial_params = cosmology.cosmologies['planck18'].copy()
fiducial_params['sigma8'] = 0.5
cosmology.addCosmology('planck18_vlS', fiducial_params)
fiducial_params = cosmology.cosmologies['planck18'].copy()
fiducial_params['sigma8'] = 1.2
cosmology.addCosmology('planck18_vhS', fiducial_params)


# six low/high Om0, sigma8, H0
fiducial_params = cosmology.cosmologies['planck18'].copy()
fiducial_params['Om0'] = 0.25
cosmology.addCosmology('planck18_lO', fiducial_params)
示例#20
0
    'sigma8': 0.834,
    'ns': 0.9624,
    'relspecies': False
}
sim_cosmos['planck1-nbody'] = {
    'flat': True,
    'H0': 67.0,
    'Om0': 0.32,
    'Ob0': 0.0491,
    'sigma8': 0.834,
    'ns': 0.9624,
    'relspecies': False
}

for c in sim_cosmos:
    cosmology.addCosmology(c, sim_cosmos[c])

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

sims = {}
sims['L2000'] = {
    'cosmo': 'bolshoi',
    'box_size': 2000.0,
    'Np': 1024,
    'epsilon': 65.0,
    'folder': 'Box_L2000_N1024_CBol',
    'Nfiles': 512,
    'Nsnapdigits': 3,
    'code': 'uberLGadget'
}
sims['L1000'] = {
import emcee
from models_profiles import *
from astropy.cosmology import LambdaCDM
from fit_profiles_curvefit import *
# import corner
import os
from colossus.cosmology import cosmology
params = {
    'flat': True,
    'H0': 70.0,
    'Om0': 0.25,
    'Ob0': 0.044,
    'sigma8': 0.8,
    'ns': 0.95
}
cosmology.addCosmology('MICE', params)
cosmo = cosmology.setCosmology('MICE')
from colossus.halo import concentration
cmodel = 'diemer19'
'''
folder = '/home/elizabeth/Documentos/proyectos/HALO-SHAPE/MICEv2.0/profiles/'
cont = False
file_name = 'profile_bin_140.fits'
angle = 'standard'
ncores = 3
nit = 250
RIN = 0.
ROUT =5000.
# '''

parser = argparse.ArgumentParser()
plt.rc("font", family='serif', size=20)

Om = 0.3
h = 0.7

from colossus.halo import concentration
from colossus.cosmology import cosmology
cos = {
    'flat': True,
    'H0': h * 100,
    'Om0': Om,
    'Ob0': 0.05,
    'sigma8': 0.92,
    'ns': 0.96
}
cosmology.addCosmology('fiducial', cos)
cosmology.setCosmology('fiducial')

z = 0
r = np.logspace(-2, np.log10(200), 1000)
k = np.loadtxt("datafiles/knl.txt")
P = np.loadtxt("datafiles/pnl.txt")
klin = np.loadtxt("datafiles/klin.txt")
Plin = np.loadtxt("datafiles/plin.txt")
M = 1e14 * h  #1e14 Msun
c = concentration.concentration(M, '200m', z=z, model='diemer15')

xi_nfw = ct.xi.xi_nfw_at_R(r, M, c, Om)
xi_mm = ct.xi.xi_mm_at_R(r, k, P)
bias = ct.bias.bias_at_M(M, klin, Plin, Om)
xi_2halo = ct.xi.xi_2halo(bias, xi_mm)
示例#23
0
    area_tink[i] = simps(mass_func_tink, M)
plt.legend()
plt.tight_layout()
plt.grid(True)
plt.show()

#Mass function for the cosmology defined by params 1 - flat and full of matter
params1 = {
    'flat': True,
    'H0': 67.2,
    'Om0': 1.0 - 0.049,
    'Ob0': 0.049,
    'sigma8': 0.81,
    'ns': 0.96
}
cosmology.addCosmology('myCosmo1', params1)
cosmo = cosmology.setCosmology('myCosmo1')

plt.figure()
plt.title(r'HMF - $\Omega_{0M}=1$', fontsize=25)
plt.xlabel(r'$ Mvir\ [M_\odot]$', fontsize=18)
plt.ylabel(r'$dn/dln(M)\ [Mpc^{-3}]$', fontsize=18)
plt.ylim(1e-7, 1e-1)
plt.xscale('log')
plt.yscale('log')
for i in range(len(z)):
    mass_func = mf.massFunction(M,
                                z[i],
                                mdef='200m',
                                model='tinker08',
                                q_out='dndlnM')
示例#24
0
get_subhalos = True
if get_subhalos:
  print( 'Getting parent IDs')
  for file_indx in cholla_indices:
    in_file_name = input_dir_cholla + f'out_{file_indx}.list'
    out_file_name = input_dir_cholla + f'catalog_{file_indx:02}.dat'
    find_parents(in_file_name, Lbox, out_file_name, rockstar_dir )



 
# cosmology.setCosmology('planck18')
# cosmo = cosmology.getCurrent()

params = {'flat': True, 'H0': 68.14, 'Om0': 0.3036, 'Ob0': 0.0479, 'sigma8': 0.81, 'ns': 0.95}
cosmology.addCosmology('myCosmo', params)
cosmo = cosmology.setCosmology('myCosmo')
cosmo_h = cosmo.h


data = {}
snap_id = 0
for snap_id in range( 0, 10 ):

  if snap_id > 0: continue

  print( f'\nLoading snap: {snap_id}' )
  crocs_file = input_dir_crocs + crocs_files[snap_id]
  halo_catalog_crocs = load_list_file_crocs( crocs_file )
  h_mass_crocs = halo_catalog_crocs['Mvir(10)'] / cosmo_h
  min_mass = h_mass_crocs.min()