示例#1
0
def test_pgm():

    import halomodel as mmhm
    from orphics import cosmology
    cc = cosmology.Cosmology(hmvec.default_params, skipCls=True, low_acc=False)
    mmhmod = mmhm.HaloModel(cc)

    mthresh = np.array([10.5])
    zs = np.array([0., 1., 2., 3.])
    ms = np.geomspace(1e8, 1e16, 1000)
    ks = np.geomspace(1e-4, 100, 1001)
    # ks,pks = np.loadtxt("mm_k_pk.txt",unpack=True)  # !!!

    eeP = mmhmod.P_gg_2h(ks, zs, mthreshHOD=mthresh) + mmhmod.P_gg_1h(
        ks, zs, mthreshHOD=mthresh)
    meP = mmhmod.P_mg_2h(ks, zs, mthreshHOD=mthresh) + mmhmod.P_mg_1h(
        ks, zs, mthreshHOD=mthresh)
    mmP = mmhmod.P_mm_2h(ks, zs) + mmhmod.P_mm_1h(ks, zs)

    hcos = hmvec.HaloModel(zs,
                           ks,
                           ms=ms,
                           halofit=None,
                           mdef='vir',
                           nfw_numeric=False)

    hcos.add_hod("g", mthresh=(10**mthresh[0]) + zs * 0., corr="max")
    # hcos.add_battaglia_profile("electron",family="AGN",xmax=100,nxs=60000)

    pme_1h = hcos.get_power_1halo(name="g", name2="nfw")
    pme_2h = hcos.get_power_2halo(name="g", name2="nfw")
    pmm_1h = hcos.get_power_1halo("nfw")
    pmm_2h = hcos.get_power_2halo("nfw")
    pee_1h = hcos.get_power_1halo("g")
    pee_2h = hcos.get_power_2halo("g")

    for i in range(zs.size):
        pl = io.Plotter(xyscale='loglin', xlabel='$k$', ylabel='$P$')
        pl.add(ks, (pme_2h[i] + pme_1h[i]) / meP[i], ls="--", color="C%d" % i)
        pl.add(ks, (pmm_2h[i] + pmm_1h[i]) / mmP[i], ls="-", color="C%d" % i)
        pl.add(ks, (pee_2h[i] + pee_1h[i]) / eeP[i], ls=":", color="C%d" % i)
        pl.vline(x=10.)
        pl.hline(y=1.)
        pl._ax.set_ylim(0.8, 1.3)
        pl.done("pgcomp_rat_z_%d.png" % i)
示例#2
0
    def __init__(self):
        #------ red shift binning (as defined in the config)
        self.zbins_nr = conf.N_bins
        self.zbins_z = remote_spectra.zbins_z
        self.zbins_zcentral = remote_spectra.zbins_zcentral
        self.zbins_chi = remote_spectra.zbins_chi
        self.zbins_chicentral = remote_spectra.zbins_chicentral

        #----- useful constants
        #from https://github.com/msyriac/orphics/blob/master/orphics/cosmology.py

        self._cSpeedKmPerSec = 299792.458
        self.G_SI = 6.674e-11
        self.mProton_SI = 1.673e-27
        self.H100_SI = 3.241e-18
        self.thompson_SI = 6.6524e-29
        self.meterToMegaparsec = 3.241e-23

        self.solar_luminosity_per_Megaparsec2_to_Jansky = self.meterToMegaparsec**2 * 1e26 * (
            3.827e+26)

        #----- CMB
        #convention: l goes from 0 to lmax_global. units are muK (not dim less).

        self.lmax_global = conf.estim_smallscale_lmax
        self.ls = np.arange(0, self.lmax_global)

        #small scale ksz
        fname = "data/ClTTksz_halo_latetime_AGN.txt"
        dt = ({'names': ('ls', 'C_l'), 'formats': [np.float, np.float]})
        data = np.loadtxt(fname, dtype=dt)
        l_ksz = data['ls']
        Clksz = data['C_l']
        lin_interp = interp1d(l_ksz, Clksz, bounds_error=False, fill_value=0)
        self.Cl_ksz_TT = lin_interp(self.ls)

        self.kmax = 100.

        self.frequencies = conf.CIB_frequencies

        #power spectra calculation

        #we can switch halomodel off, and get power spectra from camb with a simple bias prescription
        if not conf.use_halomodel:
            print(
                "We don't use the halo model. Now calculating CAMB power spectra."
            )
            #get camb cl power spectrum
            self.cambpars = camb.CAMBparams()
            self.cambpars.set_cosmology(H0=conf.H0,
                                        ombh2=conf.ombh2,
                                        omch2=conf.omch2)
            self.cambpars.InitPower.set_params(ns=conf.ns, r=0)
            #self.cambpars.set_for_lmax(2500, lens_potential_accuracy=0);
            self.cambpars.set_matter_power(redshifts=self.zbins_z.tolist(),
                                           kmax=self.kmax,
                                           k_per_logint=20)
            self.cambresults = camb.get_results(self.cambpars)
            self.PK_nonlin = camb.get_matter_power_interpolator(
                self.cambpars,
                nonlinear=True,
                hubble_units=False,
                k_hunit=False,
                kmax=self.kmax,
                zmax=self.zbins_z[-1])
            print("Power spectra done.")

        #use halo model
        else:
            #make an halo model object
            print(
                "We use the halo model. Now calculating Pgg, Pge, Pee power spectra from halo model."
            )
            self.mthreshHODstellar = galaxies.getmthreshHODstellar(
                LSSexperiment=conf.LSSexperiment,
                zbins_central=remote_spectra.zbins_zcentral
            )  #get the right HOD threshold for the experiment, as a function of red shift
            print("starting halomodel")
            self.hmod = halomodel.HaloModel(ukmversion="new", mdef="200_mean")
            self.logmmin = 8  #we cut by stellar mass, so this essentially integrates over all masses
            self.logmmax = 16
            ks = np.logspace(
                np.log10(1e-5), np.log10(100.), num=1000
            )  #we evaluate the halo model once on a z and k grid and interpolate below from that.
            # zs = np.linspace(0.1,6,50) #TEST sampling sufficient?
            zs = np.linspace(conf.z_min, conf.z_max,
                             50)  #TEST sampling sufficient?
            #     Pgg_sampled = self.hmod.P_gg_1h(ks,zs,logmlow=self.logmmin,logmhigh=self.logmmax,mthreshHOD=self.mthreshHODstellar)+self.hmod.P_gg_2h(ks,zs,logmlow=self.logmmin,logmhigh=self.logmmax,mthreshHOD=self.mthreshHODstellar)
            #     Pge_sampled = self.hmod.P_ge_1h(ks,zs,gasprofile=conf.gasprofile,logmlow=self.logmmin,logmhigh=self.logmmax,mthreshHOD=self.mthreshHODstellar)+self.hmod.P_ge_2h(ks,zs,gasprofile=conf.gasprofile,logmlow=self.logmmin,logmhigh=self.logmmax,mthreshHOD=self.mthreshHODstellar)
            #  Pee_sampled = self.hmod.P_ee_1h(ks,zs,gasprofile=conf.gasprofile,logmlow=self.logmmin,logmhigh=self.logmmax)+self.hmod.P_ee_2h(ks,zs,gasprofile=conf.gasprofile,logmlow=self.logmmin,logmhigh=self.logmmax)
            #   Pgm_sampled = self.hmod.P_gm_1h(ks,zs,logmlow=self.logmmin,logmhigh=self.logmmax,mthreshHOD=self.mthreshHODstellar)+self.hmod.P_gm_2h(ks,zs,logmlow=self.logmmin,logmhigh=self.logmmax,mthreshHOD=self.mthreshHODstellar)
            #   Pmm_sampled = self.hmod.P_mm_1h(ks,zs)+self.hmod.P_mm_2h(ks,zs)

            self.interp_PCIBCIB_1h = []

            self.interp_PCIBCIB_2h = []
            self.interp_PCIBe = []

            # self.interp_Pee = interp2d(ks,zs,Pee_sampled,bounds_error=False,fill_value=0)

            # halomodel._setup_k_z_m_grid_functions(zs,mthreshHODstellar)

            print("set up")

            for frequency_id in range(0, len(self.frequencies)):
                print("doing frequency", frequency_id)
                frequency = self.frequencies[frequency_id]
                t1 = time.time()

                #      PCIBCIB_sampled = self.hmod.P_CIBCIB_1h(ks,zs,self.frequency,logmlow=self.logmmin,logmhigh=self.logmmax,mthreshHOD=self.mthreshHODstellar)+self.hmod.P_CIBCIB_2h(ks,zs,self.frequency,logmlow=self.logmmin,logmhigh=self.logmmax,mthreshHOD=self.mthreshHODstellar)
                PCIBCIB_sampled_1h = self.hmod.P_CIBCIB_1h(
                    ks,
                    zs,
                    frequency,
                    logmlow=self.logmmin,
                    logmhigh=self.logmmax,
                    mthreshHOD=self.mthreshHODstellar)

                print("got one halo in", time.time() - t1, "seconds")
                t1 = time.time()
                PCIBCIB_sampled_2h = self.hmod.P_CIBCIB_2h(
                    ks,
                    zs,
                    frequency,
                    logmlow=self.logmmin,
                    logmhigh=self.logmmax,
                    mthreshHOD=self.mthreshHODstellar)

                np.save(
                    str(frequency) + '_pcibcib2_bothfrs.npy',
                    PCIBCIB_sampled_2h)
                np.save(
                    str(frequency) + '_pcibcib1_bothfrs.npy',
                    PCIBCIB_sampled_1h)

                print("got two halo in", time.time() - t1, "seconds")
                t1 = time.time()
                print("getting PCIBe")
                if compute_electron_cross:
                    PCIBe_sampled = self.hmod.P_CIBe_1h(
                        ks,
                        zs,
                        frequency,
                        gasprofile=conf.gasprofile,
                        logmlow=self.logmmin,
                        logmhigh=self.logmmax,
                        mthreshHOD=self.mthreshHODstellar
                    ) + self.hmod.P_CIBe_2h(ks,
                                            zs,
                                            frequency,
                                            gasprofile=conf.gasprofile,
                                            logmlow=self.logmmin,
                                            logmhigh=self.logmmax,
                                            mthreshHOD=self.mthreshHODstellar)
                print("got cross in", time.time() - t1, "seconds")

                self.interp_PCIBCIB_1h.append(
                    interp2d(ks,
                             zs,
                             PCIBCIB_sampled_1h,
                             bounds_error=False,
                             fill_value=0))
                self.interp_PCIBCIB_2h.append(
                    interp2d(ks,
                             zs,
                             PCIBCIB_sampled_2h,
                             bounds_error=False,
                             fill_value=0))
                if compute_electron_cross:
                    self.interp_PCIBe.append(
                        interp2d(ks,
                                 zs,
                                 PCIBe_sampled,
                                 bounds_error=False,
                                 fill_value=0))

            print("Power spectra done.")

        #now we calculate the binned power spectra that we will need later

        self.Cl_CIBCIB = np.zeros((3, conf.estim_smallscale_lmax))
        self.Cl_CIBCIB_1h = np.zeros((3, conf.estim_smallscale_lmax))

        self.Cl_CIBCIB_2h = np.zeros((3, conf.estim_smallscale_lmax))

        self.Cl_CIBCIB_binned = np.zeros((3, conf.estim_smallscale_lmax))
        self.Cl_CIBCIB_1h_binned = np.zeros(
            (3, conf.zbins_nr, conf.estim_smallscale_lmax))

        self.Cl_CIBCIB_2h_binned = np.zeros(
            (3, conf.zbins_nr, conf.estim_smallscale_lmax))

        self.Cl_CIBtau = np.zeros(
            (3, conf.zbins_nr, conf.estim_smallscale_lmax))

        self.Cl_tautau = np.zeros((conf.zbins_nr, conf.estim_smallscale_lmax))

        self.calc_Cl_CIBCIB()
        print("calculated Cl_CIBCIB")
        if compute_electron_cross:
            self.calc_Cl_CIBtau_tautau()
        print("calculated Cl_CIBtau")
        self.Cl_CIBCIB_tot = np.zeros((3, conf.estim_smallscale_lmax))
        self.Cl_CIBCIB_tot_binned = np.zeros(
            (3, conf.zbins_nr, conf.estim_smallscale_lmax))

        if conf.CIB_model == "minimally_empiricial":
            self.shotnoises = [
                self.hmod.CIB_shot_noise(nu) *
                self.solar_luminosity_per_Megaparsec2_to_Jansky**2
                for nu in self.frequencies
            ]

        else:
            self.shotnoises = [
                self.hmod.CIB_shot_noise(nu) for nu in self.frequencies
            ]

        if conf.cib_experimental_noise:
            #temperature
            CIB_beams = conf.CIB_beamArcmin_T * np.pi / 180. / 60.
            dT = conf.CIB_noiseTuKArcmin_T * np.pi / 180. / 60.
            with np.errstate(over='ignore'):
                self.Nl_CIB_T = (dT[:, np.newaxis]**2.) * np.exp(
                    self.ls * (self.ls + 1.) *
                    (CIB_beams[:, np.newaxis]**2.) / 8. / np.log(2.))

        else:
            self.Nl_CIB_T = [self.ls * 0, self.ls * 0, self.ls * 0]

        for i in range(0, len(self.frequencies)):

            self.Cl_CIBCIB_tot[
                i, :] = self.Cl_CIBCIB_1h[i, :] + self.Cl_CIBCIB_2h[
                    i, :] + self.shotnoises[i] * 0 + self.Nl_CIB_T[i][:]

            self.Cl_CIBCIB_tot_binned[i, :] = self.Cl_CIBCIB_1h_binned[
                i, :] + self.Cl_CIBCIB_2h_binned[
                    i, :]  #+self.shotnoises[i]+self.Nl_CIB_T[i][:]
            from datetime import date

            today = date.today()
            direct = (savepath + str(self.frequencies[i]) + "_" +
                      str(conf.N_bins) + "_" + str(conf.CIB_model) +
                      str(today))
            if not os.path.exists(direct):
                print("making directory")
                os.mkdir(direct)

            np.save(direct + "/" + "CLs_CIBCIB.npy", self.Cl_CIBCIB_tot[i])

            print("saved in", direct)
示例#3
0
def match_ngal_mthreshHOD():

    #FOR pszrcode
    #test red shifts where we match mmin and ngal
    zs_matching = np.arange(0.1, 6.1, 0.1)
    #zs_matching = np.arange(0.1,4.2,0.5)
    #zs_matching = np.array([0.5,1.5,3.,4.5])
    zs_matching_nr = zs_matching.shape[0]
    print("z for matches:", zs_matching)
    #calc ngal_mpc_lsst from ngal_arcmin2_lsst at z_central
    #ngal_arcmin2_lsst_z = n_arcmin2_LSST_Schmittfull(zs_matching)
    #ngal_arcmin2_lsst_z = n_arcmin2_LSST_Wittman(zs_matching)
    ngal_arcmin2_lsst_z = n_arcmin2_LSST_goldsample(zs_matching)
    ngal_mpc3_lsst_z = convert_n_arcmin2_mpc3(ngal_arcmin2_lsst_z, zs_matching)

    #FOR 3d box code
    #zbins_z,zbins_bias,zbins_ngal,zbins_nr = get_bins_lsst_mat()
    #zs_matching_nr = zbins_nr
    #zs_matching = zbins_z[:-1] + np.diff(zbins_z)/2.
    #ngal_mpc3_lsst_z = zbins_ngal

    #----------------- get halo model results (vary HOD mass threshold, integrate over all halo mass)
    hmod = halomodel.HaloModel()
    massbins = np.arange(5., 16.05, 0.005)  #
    ngalMpc3 = np.zeros((zs_matching_nr, massbins.shape[0]))
    nhaloMpc3 = np.zeros((zs_matching_nr, massbins.shape[0]))
    galaxybias = np.zeros((zs_matching_nr, massbins.shape[0]))
    halobias = np.zeros((zs_matching_nr, massbins.shape[0]))
    #grid calc ngal_mpc_halomodel for different mthresh.
    for m_id, m in enumerate(massbins[:-1]):
        log10mlow = 5.  #fixed
        log10mhigh = 16.  #fixed
        mthreshHOD = m * np.ones(zs_matching_nr)  #varied
        ngalMpc3[:,
                 m_id] = hmod.nbar_galaxy(zs_matching, log10mlow, log10mhigh,
                                          mthreshHOD)  #gives [z,m]
        galaxybias[:, m_id] = hmod.bias_galaxy(zs_matching, log10mlow,
                                               log10mhigh, mthreshHOD)

    # fig=plt.figure(figsize=(7,5))
    # ax1 = fig.add_subplot(111)
    # for z_id,z in enumerate(zs_matching):
    #     ax1.plot(massbins,ngalMpc3[z_id],ls='solid',label=r'ngal_hmod at z='+str(z),color="C"+str(z_id))
    #     #plot the constant from LSST
    #     ax1.axhline(y=ngal_mpc3_lsst_z[z_id],ls='dashed',label=r'ngal_LSST at z='+str(z),color="C"+str(z_id))
    # ax1.set_yscale('log')
    # plt.ylim([1e-10,1e2])
    # plt.legend(loc='lower left',frameon=False)
    # plt.grid()
    # plt.xlabel(r'$M_{\rm threshHOD} \ [M_\bigodot]$')
    # ax1.set_ylabel(r'$\bar{n}$ [Mpc]$^{-3}$')
    # fig.tight_layout()
    # plt.show()
    # #fig.savefig('data/ngal_lsst_mthreshHOD.pdf')

    #----------- find the mmin for which the curves and the constant cross.
    mmin_z = np.zeros(zs_matching_nr)
    mmin_id = np.zeros(zs_matching_nr, dtype=np.int)
    for z_id, z in enumerate(
            zs_matching
    ):  #TODO: shuld be done better, esp for sparse mass binning.
        #mmin_id[z_id] = (np.abs(nhaloMpc3[z_id]-ngal_mpc3_lsst_z[z_id])).argmin()
        mmin_id[z_id] = (np.abs(ngalMpc3[z_id] -
                                ngal_mpc3_lsst_z[z_id])).argmin()
        mmin_z[z_id] = massbins[mmin_id[z_id]]
    print("mmin matches:", mmin_z)
    #plot
    fig = plt.figure(figsize=(4.5, 3))
    ax1 = fig.add_subplot(111)
    ax1.plot(zs_matching, 10.**mmin_z, ls='solid', label=r'mmin')
    plt.legend(loc='lower left', frameon=False)
    ax1.set_yscale('log')

    #plot rs ranges
    fname_base = "fnl_zbin_lsst_z4_withphotoz_5bins"  #"fnl_zbin_lsst_z4_photoz"
    fname = "/Users/mmunchmeyer/Work/physics/gitpapers/ksz_tomography/python/plots/" + fname_base + ".txt"
    dt = ({
        'names': ('z', 'zmin', 'zmax', 'bin_V_gpc', 'fnl_gv', 'fnl_g'),
        'formats':
        [np.float, np.float, np.float, np.float, np.float, np.float]
    })
    data = np.loadtxt(fname, dtype=dt)
    for z_id in [0, 2, 4]:
        ax1.axvspan(data['zmin'][z_id], data['zmax'][z_id], alpha=0.5)

    plt.grid()
    plt.xlabel(r'z')
    plt.ylabel(r'$m^{\rm thresh}_{\star} \ [m_\bigodot]$')
    fig.tight_layout()
    plt.show()
    #fig.savefig('data/mstarHOD_lsst_matching.pdf')
    #write to file
    #fname = 'data/mminHOD_lsst_gold.txt' #FOR 3d box code
    fname = "data/mthreshHOD_lsst.txt"  #FOR pszrcode
    f = open(fname, "w")
    for i in range(zs_matching.shape[0]):
        f.write(str(zs_matching[i]) + " " + str(mmin_z[i]) + "\n")
    f.close()

    #now compare bgal_lsst and bgal_halomodel
    #calc bias at these z and mmin from halomodel and compare to lsst prescription
    #bias_lsst = bias_LSST_Schmittfull(zs_matching)
    bias_halomodel = np.zeros(zs_matching_nr)
    bias_lsst = zbins_bias
    for z_id, z in enumerate(zs_matching):
        bias_halomodel[z_id] = galaxybias[
            z_id, mmin_id[z_id]]  #halobias[z_id,mmin_id[z_id]]
    #plot
    fig = plt.figure(figsize=(4.5, 3))
    ax1 = fig.add_subplot(111)
    ax1.plot(zs_matching,
             bias_lsst,
             ls='solid',
             label=r'$b_g$ (LSST)',
             marker="o")
    ax1.plot(zs_matching,
             bias_halomodel,
             ls='solid',
             label=r'$b_g$ (halo model)',
             marker="o")
    plt.legend(loc='upper left', frameon=False)

    #plot rs ranges
    fname_base = "fnl_zbin_lsst_z4_withphotoz_5bins"  #"fnl_zbin_lsst_z4_photoz"
    fname = "/Users/mmunchmeyer/Work/physics/gitpapers/ksz_tomography/python/plots/" + fname_base + ".txt"
    dt = ({
        'names': ('z', 'zmin', 'zmax', 'bin_V_gpc', 'fnl_gv', 'fnl_g'),
        'formats':
        [np.float, np.float, np.float, np.float, np.float, np.float]
    })
    data = np.loadtxt(fname, dtype=dt)
    for z_id in [0, 2, 4]:
        ax1.axvspan(data['zmin'][z_id], data['zmax'][z_id], alpha=0.5)

    plt.grid()
    plt.xlabel(r'z')
    ax1.set_ylabel(r'$b_g$')
    fig.tight_layout()
    plt.show()
示例#4
0
def test_pmm():

    matt = True  # set to False if you don't have Matt and Moritz's halomodel.py for comparison

    if matt:
        import halomodel as mmhm
        from orphics import cosmology
        cc = cosmology.Cosmology(hmvec.default_params,
                                 skipCls=True,
                                 low_acc=False)
        mmhmod = mmhm.HaloModel(cc)

    zs = np.array([0., 2., 3.])  #,1.,2.,3.])
    #zs = np.array([0.,2.,4.,6.])
    ms = np.geomspace(1e7, 1e17, 2000)
    #ks = np.geomspace(1e-4,100,1001)
    ks = np.geomspace(1e-5, 100, 10000)

    if matt:
        mmP = mmhmod.P_mm_2h(ks, zs) + mmhmod.P_mm_1h(
            ks, zs)  #,logmlow=log10mlow,logmhigh=log10mhigh)[z_id,:]
    # print(mmhmod.halobias[:,0])

    #print(mmP2h.shape)

    hcos = hmvec.HaloModel(zs,
                           ks,
                           ms=ms,
                           halofit='mead',
                           mdef='vir',
                           nfw_numeric=True)

    mmhb = mmhmod.halobias  #np.load("mm_halobias.npy",)
    mmnfn = mmhmod.nfn  #np.load("mm_nfn.npy")

    # pl = io.Plotter(xyscale='loglin')
    # for i in range(zs.size):
    #     pl.add(ks,(hcos.nPzk[i]-mmhmod.pknl[i])/hcos.nPzk[i])
    #     pl.add(ks,(hcos.Pzk[i]-mmhmod.pk[i])/hcos.Pzk[i])
    # pl.hline(y=0)
    # pl.done()

    # pl = io.Plotter(xyscale='loglog')
    # for i in range(3):
    #     pl.add(ms,hcos.nzm[i,:],color="C%d" % i)
    #     pl.add(ms,mmnfn[:,i],ls='--',color="C%d" % i)
    # pl.done()
    # pl = io.Plotter(xyscale='loglog')
    # for i in range(3):
    #     pl.add(ms,hcos.bh[i,:],color="C%d" % i)
    #     pl.add(ms,mmhb[:,i],ls='--',color="C%d" % i)
    # pl.done()

    # pl = io.Plotter(xyscale='loglog')
    # pl.add(10**mmhmod.logm,mmhmod.halobias[:,1])
    # pl.add(ms,hcos.bh[1,:])
    # pl.done()

    pmm_1h = hcos.get_power_1halo(name="nfw")
    pmm_2h = hcos.get_power_2halo(name="nfw")

    # sys.exit()
    print(pmm_1h.shape)
    for i in range(zs.size):
        pl = io.Plotter(xyscale='loglog', xlabel='$k$', ylabel='$P$')
        pl.add(ks,
               pmm_1h[i],
               label="z=%.1f" % zs[i],
               color="C%d" % i,
               ls="--",
               alpha=0.2)
        # pl.add(ks,pmm_2h[i],label="z=%.1f" % zs[i],ls="--",color="C%d" % i)
        pl.add(ks, pmm_2h[i] + pmm_1h[i], ls="--", color="C%d" % i)
        pl.add(ks, hcos.nPzk[i], ls="-", color="k", alpha=0.7)
        if matt: pl.add(ks, mmP[i], ls="-.", color="C%d" % i)
        pl.vline(x=10.)
        pl._ax.set_ylim(1e-1, 1e5)
        pl.done("nonlincomp_z_%d.png" % i)

    for i in range(zs.size):
        pl = io.Plotter(xyscale='loglin',
                        xlabel='$k$',
                        ylabel='$P/P_{\\mathrm{NL}}$')
        pl.add(ks, (pmm_2h[i] + pmm_1h[i]) / hcos.nPzk[i],
               ls="-",
               color="C%d" % i)
        if matt: pl.add(ks, mmP[i] / hcos.nPzk[i], ls="--", color="C%d" % i)
        pl.hline(y=1)
        pl.hline(y=0.9)
        pl.hline(y=1.1)
        pl.vline(x=10.)
        pl._ax.set_ylim(0.5, 1.5)
        pl.done("nonlindiff_z_%d.png" % i)

    for i in range(zs.size):
        pl = io.Plotter(xyscale='loglin',
                        xlabel='$k$',
                        ylabel='$P/P_{\\mathrm{L}}$')
        pl.add(ks, (pmm_2h[i] + pmm_1h[i]) / hcos.Pzk[i],
               ls="-",
               color="C%d" % i)
        if matt: pl.add(ks, mmP[i] / hcos.Pzk[i], ls="--", color="C%d" % i)
        pl.vline(x=10.)
        pl.hline(y=1)
        # pl.hline(y=0.9)
        # pl.hline(y=1.1)
        # pl._ax.set_ylim(0.5,1.5)
        pl.done("lindiff_z_%d.png" % i)
示例#5
0
def match_ngal_mminhalo_halogalmatch():
    #test red shifts where we match mmin and ngal
    #zs_matching = np.arange(0.1,6.1,0.1)
    #zs_matching = np.arange(0.4,4.1,0.1)
    #zs_matching = np.array([0.5,1.5,3.,4.5])
    #zs_matching_nr = zs_matching.shape[0]

    zbins_z, zbins_bias, zbins_ngal, zbins_nr = get_bins_lsst_mat()
    zs_matching_nr = zbins_nr
    zs_matching = zbins_z[:-1] + np.diff(zbins_z) / 2.

    print("z for matches:", zs_matching)

    #calc ngal_mpc_lsst from ngal_arcmin2_lsst at z_central
    #ngal_arcmin2_lsst_z = n_arcmin2_LSST_Schmittfull(zs_matching)
    #ngal_arcmin2_lsst_z = n_arcmin2_LSST_Wittman(zs_matching)
    #ngal_arcmin2_lsst_z = n_arcmin2_LSST_goldsample(zs_matching)
    #ngal_mpc3_lsst_z = convert_n_arcmin2_mpc3(ngal_arcmin2_lsst_z,zs_matching) #convert arcmin to mpc

    ngal_mpc3_lsst_z = zbins_ngal

    #------------- get halo model results (single HOD mass threshold, vary the halo mass cut)
    hmod = halomodel.HaloModel()
    massbins = np.arange(8., 16.05, 0.005)  #0.1
    ngalMpc3 = np.zeros((zs_matching_nr, massbins.shape[0]))
    nhaloMpc3 = np.zeros((zs_matching_nr, massbins.shape[0]))
    galaxybias = np.zeros((zs_matching_nr, massbins.shape[0]))
    halobias = np.zeros((zs_matching_nr, massbins.shape[0]))
    #grid calc ngal_mpc_halomodel for different mmin.
    for m_id, m in enumerate(massbins[:-1]):
        log10mlow = massbins[m_id]
        log10mhigh = massbins[-1]
        #ngalMpc3[:,m_id] = hmod.nbar_galaxy(zs_matching,log10mlow,log10mhigh) #gives [z,m]
        #galaxybias[:,m_id] = hmod.bias_galaxy(zs_matching,log10mlow,log10mhigh)
        nhaloMpc3[:, m_id] = hmod.nbar_halo(zs_matching, log10mlow, log10mhigh)
        halobias[:, m_id] = hmod.bias_halo(zs_matching, log10mlow, log10mhigh)

    #for each z plot ngal_mpc3_halo(mmin) and a constant ngal_mpc3_LSST
    # fig=plt.figure(figsize=(7,5))
    # ax1 = fig.add_subplot(111)
    # for z_id,z in enumerate(zs_matching):
    #     #ax1.plot(massbins,ngalMpc3[z_id],ls='solid',label=r'ngal_hmod at z='+str(z),color="C"+str(z_id))
    #     ax1.plot(massbins,nhaloMpc3[z_id],ls='dotted',label=r'nhalo_hmod at z='+str(z),color="C"+str(z_id))
    #     #plot the constant from LSST
    #     ax1.axhline(y=ngal_mpc3_lsst_z[z_id],ls='dashed',label=r'ngal_LSST at z='+str(z),color="C"+str(z_id))
    # ax1.set_yscale('log')
    # plt.ylim([1e-10,1e2])
    # plt.legend(loc='lower left',frameon=False)
    # plt.grid()
    # plt.xlabel(r'$M_{\rm min} \ [M_\bigodot]$')
    # ax1.set_ylabel(r'$\bar{n}$ [Mpc]$^{-3}$')
    # fig.tight_layout()
    # plt.show()
    # fig.savefig('data/ngal_lsst_halogalmatching.pdf') #lsst schmittfull

    #----------- find the mmin for which the curves and the constant cross.
    mmin_z = np.zeros(zs_matching_nr)
    mmin_id = np.zeros(zs_matching_nr, dtype=np.int)
    for z_id, z in enumerate(
            zs_matching
    ):  #TODO: should be done better, esp for sparse mass binning.
        mmin_id[z_id] = (np.abs(nhaloMpc3[z_id] -
                                ngal_mpc3_lsst_z[z_id])).argmin()
        #mmin_id[z_id] = (np.abs(ngalMpc3[z_id]-ngal_mpc3_lsst_z[z_id])).argmin()
        mmin_z[z_id] = massbins[mmin_id[z_id]]
    print("mmin matches:", mmin_z)
    #plot
    fig = plt.figure(figsize=(4.5, 3))
    ax1 = fig.add_subplot(111)
    ax1.plot(zs_matching, 10**mmin_z, ls='solid', label=r'mmin', marker="o")
    #plt.legend(loc='lower left',frameon=False)
    ax1.set_yscale('log')
    plt.grid()
    plt.xlabel(r'z')
    plt.ylabel(r'$M_{\rm min} \ [M_\bigodot]$')
    fig.tight_layout()
    plt.show()
    fig.savefig('data/mminhalo_lsst_halogalmatching_z4.pdf')
    #write to file
    fname = 'data/mminhalo_lsst_halogalmatching.txt'
    f = open(fname, "w")
    for i in range(zs_matching.shape[0]):
        f.write(str(zs_matching[i]) + " " + str(mmin_z[i]) + "\n")
    f.close()

    #now compare bgal_lsst and bgal_halomodel
    #calc bias at these z and mmin from halomodel and compare to lsst prescription
    #bias_lsst = bias_LSST_Schmittfull(zs_matching)
    bias_lsst = zbins_bias
    bias_halomodel = np.zeros(zs_matching_nr)
    dm = 0.1
    for z_id, z in enumerate(zs_matching):
        bias_halomodel[z_id] = halobias[
            z_id, mmin_id[z_id]]  #galaxybias[z_id,mmin_id[z_id]]
    #plot
    fig = plt.figure(figsize=(4.5, 3))
    ax1 = fig.add_subplot(111)
    ax1.plot(zs_matching, bias_lsst, ls='solid', label=r'b_lsst', marker="o")
    ax1.plot(zs_matching,
             bias_halomodel,
             ls='solid',
             label=r'b_halomodel',
             marker="o")
    plt.legend(loc='lower left', frameon=False)
    plt.grid()
    plt.xlabel(r'z')
    ax1.set_ylabel(r'$b_g$')
    fig.tight_layout()
    plt.show()
    fig.savefig('data/bias_lsst_abundancematching.pdf')