Exemple #1
0
def halocat_init(halo_catalog, z_median):
    """
    Initial population of halo catalog using populate_mock function

    Parameters
    ----------
    halo_catalog: string
        Path to halo catalog
    
    z_median: float
        Median redshift of survey

    Returns
    ---------
    model: halotools model instance
        Model based on behroozi 2010 SMHM
    """
    halocat = CachedHaloCatalog(fname=halo_catalog, update_cached_fname=True)
    """
    prim_haloprop_key : String giving the column name of the primary halo 
    property governing stellar mass.
    """
    model = PrebuiltSubhaloModelFactory('behroozi10', redshift=z_median, \
        prim_haloprop_key='halo_macc')
    model.populate_mock(halocat, seed=5)

    return model
Exemple #2
0
def populate_mock(key,halocat):
    """
    Populates mock halo catalog with galaxies using Behroozi 2010 relation

    Parameters
    ----------
    key: string
        Halo mass property used to populate mock (halo_mvir or halo_macc)
        
    halocat: hdf5 file
        Mock halo catalog

    Returns
    ---------
    model: 
        subhalo-based composite model
    """
    model = PrebuiltSubhaloModelFactory('behroozi10',redshift=0.0186,\
                                        prim_haloprop_key=key) 
    model.populate_mock(halocat)
    return model
Exemple #3
0
def halocat_init(halo_cat, z):
    """
    Initial population of halo catalog using populate_mock function

    Parameters
    ----------
    halo_cat: string
        Path to halo catalog
    
    z: float
        Median redshift of survey

    Returns
    ---------
    model: halotools model instance
        Model based on behroozi 2010 SMHM
    """
    halocat = CachedHaloCatalog(fname=halo_cat, update_cached_fname=True)
    model = PrebuiltSubhaloModelFactory('behroozi10', redshift=z, \
        prim_haloprop_key='halo_macc')
    model.populate_mock(halocat, seed=5)

    return model
eco_nobuff = eco_buff.loc[(eco_buff.grpcz.values >= 3000) & \
    (eco_buff.grpcz.values <= 7000) & (eco_buff.absrmag.values <= -17.33) &\
        (eco_buff.logmstar.values >= 8.9)]

cvar = 0.125
volume = 151829.26 # Survey volume without buffer [Mpc/h]^3

# BMF
eco_nobuff_mstellar = eco_nobuff.logmstar.values
eco_nobuff_mgas = eco_nobuff.logmgas.values
eco_nobuff_mbary = calc_bary(eco_nobuff_mstellar, eco_nobuff_mgas)
maxis, phi, err, bins = diff_bmf(eco_nobuff_mbary, volume, cvar, False)

halocat = CachedHaloCatalog(fname=halo_catalog, update_cached_fname=True)
z_model = np.median(eco_nobuff.grpcz.values) / (3 * 10**5)
model = PrebuiltSubhaloModelFactory('behroozi10', redshift=z_model,
                                    prim_haloprop_key='halo_macc')
model.populate_mock(halocat)

# ensure reproducibility
rseed = 12
np.random.seed(rseed)

behroozi10_param_vals = [12.35,10.72,0.44,0.57,0.15]
nwalkers = 250
ndim = 5
p0 = behroozi10_param_vals + 0.1*np.random.rand(ndim*nwalkers).\
    reshape((nwalkers,ndim))

with Pool(processes=20) as pool:
    sampler = emcee.EnsembleSampler(nwalkers, ndim, lnprob, args=(phi, err)\
        ,pool=pool)
Exemple #5
0
# plt.title('Stellar mass function')

counter = 0
nbins = bins
volume_sim = 130**3

Mhalo_characteristic = np.linspace(11.5, 13.0, 30)
Mstellar_characteristic = np.linspace(9.5, 11.0, 30)
Mlow_slope = np.linspace(0.35, 0.50, 30)
Mhigh_slope = np.linspace(0.50, 0.65, 30)
Mstellar_scatter = np.linspace(0.1, 0.2, 30)

print('Setting up models')
###Models
model1 = PrebuiltSubhaloModelFactory('behroozi10',
                                     redshift=z_median,
                                     prim_haloprop_key='halo_macc')
model2 = PrebuiltSubhaloModelFactory('behroozi10',
                                     redshift=z_median,
                                     prim_haloprop_key='halo_macc')
model3 = PrebuiltSubhaloModelFactory('behroozi10',
                                     redshift=z_median,
                                     prim_haloprop_key='halo_macc')
model4 = PrebuiltSubhaloModelFactory('behroozi10',
                                     redshift=z_median,
                                     prim_haloprop_key='halo_macc')
model5 = PrebuiltSubhaloModelFactory('behroozi10',
                                     redshift=z_median,
                                     prim_haloprop_key='halo_macc')

print('Setting up halocats')
Exemple #6
0
mdef = args.mdef
radmin = args.radmin
inc = args.inc
z = args.z

# set cosmology
redshift = 1/scale - 1
cosmo = Planck15
h = Planck15.h
conc = 5

# needs to run first to initialize package
# halotools.test_installation()

# determine dark mass and virial radius
model = PrebuiltSubhaloModelFactory('behroozi10', redshift = redshift)
stars_mass = 60850451172.24926
# stars_mass in units Msun from simulation
log_stars_mass = np.log10(stars_mass)
log_dark_mass = model.mean_log_halo_mass(log_stellar_mass=log_stars_mass)
dm_stellar = 10**log_dark_mass
virial = halo_mass_to_halo_radius(dm_stellar, cosmo, redshift, mdef)
virial_kpc = (virial * u.Mpc).to('kpc') / h
virial_rad = np.arange(radmin, virial_kpc.value, inc)
scaled_rad = virial_rad / np.max(virial_rad)

# calculate the density threshold for dimensionless mass density calculation
nfw = NFWProfile()
rho_thresh = density_threshold(cosmo, redshift, mdef)
# rho_thresh in units Msun*h^2/Mpc^3
rho_units = (rho_thresh * u.Msun / u.Mpc**3).to('Msun/kpc3') * h**2
Exemple #7
0
def plot_SMHM(halocat_galcat_merged,mass_to_plot_key,populate_mock_key):
    """
    Plots SM-HM relation
    
    Parameters
    ----------
    halocat_galcat_merged: Pandas dataframe
        Merged dataframe containing halo and galaxy information   
        
    mass_to_plot_key: string
        Halo mass property that will be plotted on the X-axis
        
    populate_mock_key: string
        Halo mass property used to populate mock

    """
    print('    -> Separating centrals and satellites')
    cens = halocat_galcat_merged.loc[halocat_galcat_merged.C_S.values == 1]
    sats = halocat_galcat_merged.loc[halocat_galcat_merged.C_S.values == 0]
    
    print('    -> Overplotting Behroozi 2010 relation for centrals (halotools)')
    mstar_arr = np.linspace(cens.stellar_mass.values.min(),\
                            cens.stellar_mass.values.max(),\
                            1000000)
    log_mstar_arr_B10 = np.log10(mstar_arr)
    model = PrebuiltSubhaloModelFactory('behroozi10',redshift=0.0186,\
                                         prim_haloprop_key=populate_mock_key)   
    log_halo_mass_B10 = model.mean_log_halo_mass(log_stellar_mass=\
                                                 log_mstar_arr_B10,\
                                                 redshift=0.0186)
    
        
    if mass_to_plot_key == 'halo_mvir':
        print('    -> Calculating statistics using {0}'.format\
              (mass_to_plot_key))
        stats_cens = stats_cens_func(cens,mass_to_plot_key)


        print('    -> Plotting')
        fig1 = plt.figure()
        plt.scatter(np.log10(sats.halo_mvir_host_halo.values),\
                    np.log10(sats.stellar_mass.values),color='g',s=5,\
                    alpha=0.5,label='Satellites')
        plt.plot(log_halo_mass_B10,log_mstar_arr_B10,'-k',\
                 label='Behroozi 2010 cosmoutils')
        plt.errorbar(stats_cens[0],stats_cens[1],yerr=stats_cens[2],color='r',\
                     label='Centrals')
        plt.xlabel(r'$\mathrm{Halo\ mass\ (mvir)}/\mathrm{[\frac{M_\odot}{h}]'\
                              '})$')
        plt.ylabel(r'$\mathrm{Stellar\ mass}/\mathrm{[\frac{M_\odot}{h}]})$')
        plt.title('SM-HM relation using {0} to populate mocks'.format\
                  (populate_mock_key.split('_')[1]))


    elif mass_to_plot_key == 'halo_macc':
        print('    -> Calculating statistics using {0}'.format\
              (mass_to_plot_key))
        stats_cens = stats_cens_func(cens,mass_to_plot_key)
        print('    -> Plotting')
        fig1 = plt.figure()
        plt.scatter(np.log10(sats.halo_macc_host_halo.values),\
                    np.log10(sats.stellar_mass.values),color='g',s=5,\
                    alpha=0.5,label='Satellites')
        plt.plot(log_halo_mass_B10,log_mstar_arr_B10,'-k',\
                 label='Behroozi 2010 cosmoutils')
        plt.errorbar(stats_cens[0],stats_cens[1],yerr=stats_cens[2],color='r',\
                     label='Centrals')
        plt.xlabel(r'$\mathrm{Halo\ mass\ (macc)}/\mathrm{[\frac{M_\odot}{h}]'\
                              '})$')
        plt.ylabel(r'$\mathrm{Stellar\ mass}/\mathrm{[\frac{M_\odot}{h}]})$')
        plt.title('SM-HM relation using {0} to populate mocks'.format\
                  (populate_mock_key.split('_')[1]))

    
    plt.legend(loc='best',prop={'size': 6})
    fig1.tight_layout()
    print('    -> Saving figure')
    fig1.savefig('../reports/figures/SMHM_{0}_hosthalo.png'.format\
                 (mass_to_plot_key.split('_')[1]))
Exemple #8
0
def predict_model(param,
                  config,
                  obs_data,
                  sim_data,
                  smf_only=False,
                  ds_only=False):
    """Return all model predictions.
    Parameters
    ----------
    param: list, array, or tuple.
        Input model parameters.
    config : dict
        Configurations of the data and model.
    obs_data: dict
        Dictionary for observed data.
    sim_data: dict
        Dictionary for UniverseMachine data.
    constant_bin : boolen
        Whether to use constant bin size for logMs_tot or not.
    return_all : bool, optional
        Return all model information.
    show_smf : bool, optional
        Show the comparison of SMF.
    show_dsigma : bool, optional
        Show the comparisons of WL.
    """

    mass_x_field = config['sim_mass_x_field']
    halotools = config['sim_halotools']

    if halotools:
        print("USING HALOTOOLS with halo_mvir")
        # build_model and populate mock
        if 'model' in sim_data:  # save memory if model already exists
            for i, model_param in enumerate(config['param_labels']):
                sim_data['model'].param_dict[model_param] = param[i]

            # set redshift dependence to 0
            for i, model_param in enumerate(config['redshift_param_labels']):
                sim_data['model'].param_dict[model_param] = 0

            sim_data['model'].mock.populate()
            print('mock.populate')

        else:
            sim_data['model'] = PrebuiltSubhaloModelFactory(
                'behroozi10',
                redshift=config['sim_z'],
                scatter_abscissa=[12, 15],
                scatter_ordinates=[param[0], param[1]])

            for i, model_param in enumerate(config['param_labels']):
                sim_data['model'].param_dict[model_param] = param[i]

            # set redshift dependence to 0
            for i, model_param in enumerate(config['redshift_param_labels']):
                sim_data['model'].param_dict[model_param] = 0

            # populate mock
            # sim_data['model'].populate_mock(deepcopy(sim_data['halocat']))
            sim_data['model'].populate_mock(sim_data['halocat'])
            print('populate_mock')

        print(sim_data['model'].param_dict)

        stellar_masses = np.log10(
            sim_data['model'].mock.galaxy_table['stellar_mass'])

    else:  #use Chris' code instead of halotools
        print("USING CHRIS' CODE with {0}".format(mass_x_field))
        stellar_masses = get_chris_stellar_masses(param, config, sim_data)

    # Predict SMFs
    smf_mass_bins, smf_log_phi = compute_SMF(stellar_masses, config, nbins=100)
    print('SMF computed')
    if smf_only:
        return smf_mass_bins, smf_log_phi, None, None, stellar_masses

    # Predict DeltaSigma profiles
    wl_r, wl_ds = compute_deltaSigma(stellar_masses, config, obs_data,
                                     sim_data)
    print('DS computed')
    if ds_only:
        return None, None, wl_r, wl_ds, stellar_masses

    return smf_mass_bins, smf_log_phi, wl_r, wl_ds, stellar_masses