def Plot_tRapid():
    '''
    '''
    prettyplot()
    pretty_colors = prettycolors()
    fig = plt.figure(1)
    sub = fig.add_subplot(111)

    m_val = np.array([
        6.37119e+9, 1.05173e+10, 1.54219e+10, 2.55939e+10, 3.98025e+10,
        6.06088e+10, 9.95227e+10, 1.57374e+11
    ])
    t_rap = np.array([
        8.04511e-1, 7.06767e-1, 6.69173e-1, 5.48872e-1, 3.23308e-1, 2.85714e-1,
        2.25564e-1, 1.80451e-1
    ])
    sub.scatter(m_val, t_rap, c='k', s=16)

    m_arr = np.arange(9.5, 12.0, 0.1)
    sub.plot(10**m_arr, tRapid(m_arr), c=pretty_colors[1])
    sub.plot(10**m_arr,
             sfr_evol.getTauQ(m_arr, tau_prop={'name': 'satellite'}),
             c=pretty_colors[3])

    # x-axis
    sub.set_xscale('log')
    sub.set_xlim([5 * 10**9, 2 * 10**11.])
    # y-axis
    sub.set_ylim([0.0, 4.0])
    sub.set_ylabel(r'$\mathtt{t_{Q, rapid}}$', fontsize=25)

    plt.show()
    plt.close()
    return None
def Plot_tRapid(): 
    '''
    '''
    prettyplot()
    pretty_colors = prettycolors()
    fig = plt.figure(1)
    sub = fig.add_subplot(111)

    m_val = np.array([6.37119e+9, 1.05173e+10, 1.54219e+10, 2.55939e+10, 3.98025e+10, 6.06088e+10, 9.95227e+10, 1.57374e+11])
    t_rap = np.array([8.04511e-1, 7.06767e-1, 6.69173e-1, 5.48872e-1, 3.23308e-1, 2.85714e-1, 2.25564e-1, 1.80451e-1]) 
    sub.scatter(m_val, t_rap, c='k', s=16)

    m_arr = np.arange(9.5, 12.0, 0.1) 
    sub.plot(10**m_arr, tRapid(m_arr), c=pretty_colors[1])
    sub.plot(10**m_arr, sfr_evol.getTauQ(m_arr, tau_prop={'name':'satellite'}), c=pretty_colors[3])
    
    # x-axis
    sub.set_xscale('log') 
    sub.set_xlim([5*10**9, 2*10**11.]) 
    # y-axis
    sub.set_ylim([0.0, 4.0])
    sub.set_ylabel(r'$\mathtt{t_{Q, rapid}}$', fontsize=25) 

    plt.show()
    plt.close()
    return None
def plotCMS_SMF_MS(cenque='default', evol_dict=None): 
    '''Plot the stellar mass function of the integrated SFR main sequence population 
    and compare it to the theoretic stellar mass function of the main sequence 
    population 
    '''
    # import evolved galaxy population 
    MSpop = CMS.EvolvedGalPop(cenque=cenque, evol_dict=evol_dict) 
    print MSpop.File()
    MSpop.Read() 
    MSonly = np.where(MSpop.t_quench == 999.)   # remove the quenching galaxies

    smf = Obvs.getSMF(MSpop.mass[MSonly], weights=MSpop.weight_down[MSonly])
    prettyplot() 
    pretty_colors = prettycolors() 

    # analytic SMF 
    theory_smf = Obvs.getSMF(MSpop.M_sham[MSonly], weights=MSpop.weight_down[MSonly])

    fig = plt.figure()
    sub = fig.add_subplot(111)

    sub.plot(theory_smf[0], theory_smf[1], lw=3, c='k', label='Theory')
    sub.plot(smf[0], smf[1], lw=3, c=pretty_colors[3], ls='--', label='MS Only')

    sub.set_ylim([10**-5, 10**-1])
    sub.set_xlim([6., 12.0])
    sub.set_yscale('log')
    sub.set_xlabel(r'Mass $\mathtt{M_*}$', fontsize=25) 
    sub.set_ylabel(r'Stellar Mass Function $\mathtt{\Phi}$', fontsize=25) 
    sub.legend(loc='upper right', frameon=False)
    
    fig_file = ''.join([UT.fig_dir(), 'SMF_MS.CMS', MSpop._Spec_str(), '.png']) 
    fig.savefig(fig_file, bbox_inches='tight') 
    plt.close() 
    return None
Example #4
0
def xi(Mr=20, Nmock=500): 
    '''
    Plot xi(r) of the fake observations
    '''
    prettyplot() 
    pretty_colors = prettycolors() 

    xir, cii = Data.data_xi(Mr=Mr, Nmock=Nmock)
    rbin = Data.data_xi_bins(Mr=Mr) 
    
    fig = plt.figure(1) 
    sub = fig.add_subplot(111)
    sub.plot(rbin, rbin*xir, c='k', lw=1)
    sub.errorbar(rbin, rbin*xir, yerr = rbin*cii**0.5 , fmt="ok", ms=1, capsize=2, alpha=1.)

    sub.set_xlim([0.1, 15])
    sub.set_ylim([1, 10])
    sub.set_yscale("log")
    sub.set_xscale("log")

    sub.set_xlabel(r'$\mathtt{r}\; (\mathtt{Mpc})$', fontsize=25)
    sub.set_ylabel(r'$\mathtt{r} \xi_{\rm gg}$', fontsize=25)

    fig_file = ''.join([util.fig_dir(),
        'xi.Mr', str(Mr), '.Nmock', str(Nmock), '.png'])
    fig.savefig(fig_file, bbox_inches='tight')
    plt.close()
    return None
Example #5
0
def PlotFq_WetzelComp():
    ''' Compare the quiescent function evolution for different analytic prescriptions 
    of Wetzel et al. (2013)
    '''
    lit = ['wetzel', 'wetzel_alternate']

    M_arr = np.arange(9.0, 12.2, 0.2)
    #z_arr = np.arange(0.0, 1.2, 0.2)
    z_arr = np.array([0.0, 0.36, 0.66, 0.88])

    prettyplot()
    pretty_colors = prettycolors()
    fig = plt.figure()
    sub = fig.add_subplot(111)

    qf = gp.Fq()
    for il, l in enumerate(lit):
        if il == 0:
            ls = '-'
        elif il == 1:
            ls = '--'

        for iz, z in enumerate(z_arr):
            if iz == 0:
                label = l.title()
            else:
                label = None
            fq_M = qf.model(M_arr, z, lit=l)
            sub.plot(M_arr,
                     fq_M,
                     c=pretty_colors[iz],
                     lw=3,
                     ls=ls,
                     label=label)

    # Now plot Tinker et al. (2013)'s fQ^cen
    for iz, z in enumerate(z_arr):
        if z != 0.0:
            fq_file = ''.join(
                ['dat/observations/cosmos_fq/', 'stats_z',
                 str(iz), '.fq_cen'])
            mmm, fqcen = np.loadtxt(fq_file, unpack=True, usecols=[0, 1])
            mmm = np.log10(mmm)
        else:
            fq_file = ''.join(
                ['dat/observations/cosmos_fq/', 'fcen_red_sdss_scatter.dat'])
            mmm, fqcen = np.loadtxt(fq_file, unpack=True, usecols=[0, 1])
        sub.scatter(mmm, fqcen, c=pretty_colors[iz], lw=0, s=10)

    sub.set_xlim([9.0, 12.])
    sub.set_xlabel(r'$\mathtt{M_{*}}$', fontsize=25)

    sub.set_ylim([0., 1.])
    sub.set_ylabel(r'$\mathtt{f_Q}$', fontsize=25)
    sub.legend(loc='upper left')
    fig_file = ''.join(['figure/test/', 'Fq_Wetzel_Comparison.png'])
    fig.savefig(fig_file, bbox_inches='tight')
    plt.close()

    return None
Example #6
0
def test_fit_tofz(): 
    z_table, t_table = UT.zt_table()
    
    cosmo = FlatLambdaCDM(H0=70, Om0=0.274)

    prettyplot()
    fig = plt.figure()
    sub = fig.add_subplot(111)

    for deg in range(2,10): 
        coeff = UT.fit_tofz(deg)
        if deg > 5: 
            print 'deg = ', deg, coeff
        tofz = np.poly1d(coeff)
        
        z_arr = np.arange(0., 2., 0.1)
        t_arr = cosmo.age(z_arr).value 

        sub.plot(z_arr, (tofz(z_arr) - t_arr)/t_arr, label='Degree='+str(deg))

    t_of_z = interpolate.interp1d(z_arr, t_arr, kind='cubic') 
    tint = t_of_z(z_table[1:20])#np.interp(t_table[:20], t_arr, z_arr)

    sub.scatter(z_table[1:20], (t_table[1:20] - tint)/tint, c='k', s=30) 
    sub.plot(np.arange(0., 2., 0.1), np.repeat(-0.025, len(np.arange(0., 2., 0.1))), c='k', ls='--', lw=3)
    sub.plot(np.arange(0., 2., 0.1), np.repeat(0.025, len(np.arange(0., 2., 0.1))), c='k', ls='--', lw=3)

    sub.set_ylim([-0.05, 0.05])
    sub.set_xlim([0., 2.])
    sub.legend(loc='upper left')
    plt.show()
def PlotLee2015_SFMS_zdep(): 
    ''' Plot the S0 term (redshift dependence term of the SFMS parmaterization) 
    of the Lee et al. (2015) SFMS fits. 
    '''
    z_mid = np.array([0.36, 0.55, 0.70, 0.85, 0.99, 1.19])
    S0 = np.array([0.80, 0.99, 1.23, 1.35, 1.53, 1.72])
    S0_err = np.array([0.019, 0.015, 0.016, 0.014, 0.017, 0.024])

    zslope, const = Lee2015_SFMS_zslope()

    prettyplot()
    pretty_colors = prettycolors() 

    fig = plt.figure()
    sub = fig.add_subplot(111)
    sub.errorbar(z_mid, S0, yerr=S0_err, c='k', elinewidth=3, capsize=10, label='Lee et al. (2015)') 
    sub.plot(z_mid, zslope * (z_mid - 0.05) + const, c=pretty_colors[1], lw=2, ls='--', label='Best fit')
    
    ztext = '\n'.join(['Redshift slope', r'$\mathtt{A_z='+str(round(zslope,2))+'}$'])

    sub.text(0.1, 1.5, ztext, fontsize=20)

    sub.legend(loc='lower right') 
    sub.set_ylabel('Lee et al. (2015) $S_0$ term', fontsize=25) 
    sub.set_xlim([0.0, 1.5]) 
    sub.set_xlabel('Redshift $(\mathtt{z})$', fontsize=25)

    fig_file = ''.join(['figure/', 'Lee2015_SFMS_zdep.png']) 
    fig.savefig(fig_file, bbox_inches='tight') 
    return None
Example #8
0
def gmf(Mr=20, Nmock=500): 
    '''
    Plot Group Multiplicty Function of fake observations 
    '''
    prettyplot() 
    pretty_colors = prettycolors() 
    
    # import fake obs GMF
    gmf, sig_gmf = Data.data_gmf(Mr=Mr, Nmock=Nmock)
    # group richness bins
    gmf_bin = Data.data_gmf_bins()

    fig = plt.figure(1) 
    sub = fig.add_subplot(111)

    sub.errorbar(
            0.5*(gmf_bin[:-1]+gmf_bin[1:]), gmf, yerr=sig_gmf,
            fmt="ok", capsize=1.0
            )
    sub.set_xlim([1, 60])
    sub.set_yscale('log')
    sub.set_ylabel(r"Group Multiplicity Function (h$^{3}$ Mpc$^{-3}$)", fontsize=20)
    sub.set_xlabel(r"$\mathtt{Group\;\;Richness}$", fontsize=20)
    # save to file 
    fig_file = ''.join([util.fig_dir(), 
        'gmf.Mr', str(Mr), '.Nmock', str(Nmock), '.png'])
    fig.savefig(fig_file, bbox_inches='tight')
    return None
Example #9
0
def LineageFinalDescendantSMF(nsnap_ancestor,
                              subhalo_prop={
                                  'scatter': 0.0,
                                  'source': 'li-march'
                              },
                              sfr_prop={
                                  'fq': {
                                      'name': 'wetzelsmooth'
                                  },
                                  'sfr': {
                                      'name': 'average'
                                  }
                              }):
    ''' Plot SMF of final descendant. Also mark the composition of the final SMF from Subhalos 
    that gain stellar mass at different snapshots in the middle of the simulation. 
    '''
    prettyplot()
    pretty_colors = prettycolors()

    bloodline = Lineage(nsnap_ancestor=nsnap_ancestor,
                        subhalo_prop=subhalo_prop)
    bloodline.Read([1], sfr_prop=sfr_prop)

    final_desc = bloodline.descendant_snapshot1

    mf = SMF()

    smf_plot = plots.PlotSMF()
    smf_plot.cgpop(final_desc, line_color='k')

    for isnap in range(2, nsnap_ancestor + 1)[::-1]:
        started_here = np.where(final_desc.nsnap_genesis == isnap)
        mass, phi = mf._smf(final_desc.mass[started_here])

        try:
            phi_tot += phi
            smf_plot.sub.fill_between(mass,
                                      phi_tot - phi,
                                      phi_tot,
                                      color=pretty_colors[isnap],
                                      label='Nsnap=' + str(isnap))
        except UnboundLocalError:
            phi_tot = phi
            smf_plot.sub.fill_between(mass,
                                      np.zeros(len(phi)),
                                      phi,
                                      color=pretty_colors[isnap],
                                      label='Nsnap=' + str(isnap))

    smf_plot.set_axes()
    fig_file = ''.join([
        'figure/test/', 'LineageFinalDescendantSMF', '.ancestor',
        str(nsnap_ancestor),
        bloodline._file_spec(subhalo_prop=subhalo_prop, sfr_prop=sfr_prop),
        '.png'
    ])
    smf_plot.save_fig(fig_file)

    return None
Example #10
0
def TrueObservables(Mr=21, b_normal=0.25):
    ''' Plot xi and gmf for the data 
    '''
    # xi data
    xi_data = Data.data_xi(Mr=Mr, b_normal=b_normal)
    cov_data = Data.data_cov(Mr=Mr, b_normal=b_normal, inference='mcmc')
    data_xi_cov = cov_data[1:16, 1:16]
    xi_r_bin = Data.data_xi_bin(Mr=Mr)
    # gmf data
    data_gmf = Data.data_gmf(Mr=Mr, b_normal=b_normal)
    cov_data = Data.data_cov(Mr=Mr, b_normal=b_normal, inference='mcmc')
    data_gmf_cov = cov_data[16:, 16:]

    r_binedge = Data.data_gmf_bins()
    gmf_r_bin = 0.5 * (r_binedge[:-1] + r_binedge[1:])

    prettyplot()
    pretty_colors = prettycolors()

    fig = plt.figure(figsize=(12, 6))
    sub_xi = fig.add_subplot(121)
    sub_gmf = fig.add_subplot(122)

    #sub_xi.errorbar(xi_r_bin, xi_data, yerr = np.sqrt(np.diag(data_xi_cov)), fmt="o", color='k',
    #        markersize=0, lw=0, capsize=3, elinewidth=1.5)
    #sub_xi.scatter(xi_r_bin, xi_data, c='k', s=10, lw=0)
    sub_xi.fill_between(xi_r_bin,
                        xi_data - np.sqrt(np.diag(data_xi_cov)),
                        xi_data + np.sqrt(np.diag(data_xi_cov)),
                        color=pretty_colors[1])
    sub_xi.set_yscale('log')
    sub_xi.set_xscale('log')
    sub_xi.set_xlim(0.1, 20)
    sub_xi.set_xlabel(r'$\mathtt{r}\; [\mathtt{Mpc}/h]$', fontsize=25)
    sub_xi.set_ylabel(r'$\xi(r)$', fontsize=25)

    #sub_gmf.errorbar(gmf_r_bin, data_gmf, yerr=np.sqrt(np.diag(data_gmf_cov)),
    #        fmt="o", color='k',
    #        markersize=0, lw=0, capsize=4, elinewidth=2)
    #sub_gmf.scatter(gmf_r_bin, data_gmf, s=15, lw=0, c='k', label='Mock Observation')
    sub_gmf.fill_between(gmf_r_bin,
                         data_gmf - np.sqrt(np.diag(data_gmf_cov)),
                         data_gmf + np.sqrt(np.diag(data_gmf_cov)),
                         color=pretty_colors[1])
    sub_gmf.set_xlim(1, 20)
    sub_gmf.set_xlabel(r'$\mathtt{N}$ (Group Richness)', fontsize=25)

    sub_gmf.yaxis.tick_right()
    sub_gmf.yaxis.set_ticks_position('both')
    sub_gmf.yaxis.set_label_position('right')
    sub_gmf.set_ylim([10**-7, 2.0 * 10**-4])
    sub_gmf.set_yscale('log')
    sub_gmf.set_ylabel(r'$\zeta(\mathtt{N})$', fontsize=25)

    fig.subplots_adjust(hspace=0.05)
    fig_name = ''.join([ut.fig_dir(), 'paper.data_observables', '.pdf'])
    fig.savefig(fig_name, bbox_inches='tight', dpi=150)
    plt.close()
    return None
def SubhaloSMF(type, scatter=0.0, source='li-drory-march', 
        nsnap_ancestor=20 ): 
    ''' Test the Subhalos/CentralSubhalos imported from TreePM by 
    comparing their measured SMFs to the analytic SMFs 

    Parameters
    ----------
    type : string 
        String that specifies whether we're interested in CentralSubhalos 
        or all Subhalos.
    scatter : float
        Float that specifies the scatter in the SMHM relation, which 
        affects the SHAM masses
    source : string
        String that specifies which SMF is used for SHAM
    '''
    prettyplot()
    pretty_colors = prettycolors()

    fig = plt.figure(figsize=(10,10))
    sub = fig.add_subplot(111)
    for i_snap in range(1, nsnap_ancestor+1):
        smf = SMF()
        if type == 'all': 
            subh = Subhalos()
        elif type == 'central': 
            subh = CentralSubhalos()
        else: 
            raise ValueError

        subh.Read(i_snap, scatter=scatter, source=source, nsnap_ancestor=nsnap_ancestor)
        
        subh_mass, subh_phi = smf.Obj(subh, dlogm=0.1, LF=False)
        sub.plot(subh_mass, subh_phi, lw=4, c=pretty_colors[i_snap % 19], alpha=0.5) 

        analytic_mass, analytic_phi = smf.analytic(get_z_nsnap(i_snap), source=source) 
        sub.plot(analytic_mass, analytic_phi, lw=4, ls='--', c=pretty_colors[i_snap % 19], 
                label=r"$ z = "+str(round(get_z_nsnap(i_snap),2))+"$") 

    sub.set_yscale('log')
    sub.set_ylim([10**-5, 10**-1])
    sub.set_xlim([6.0, 12.0])
    #sub.legend(loc='upper right')
    if type == 'all': 
        subhalo_str = 'subhalo' 
    elif type == 'central': 
        subhalo_str = 'central_subhalo' 
    else: 
        raise ValueError
    plt.show()
    fig_file = ''.join(['figure/test/'
        'SubhaloSMF', 
        '.', subhalo_str, 
        '.scatter', str(round(scatter,2)), 
        '.ancestor', str(nsnap_ancestor),
        '.', source, 
        '.png']) 
    fig.savefig(fig_file, bbox_inches='tight')
    plt.close()
Example #12
0
def TrueObservables(Mr=21, b_normal=0.25): 
    ''' Plot xi and gmf for the data 
    '''
    # xi data 
    xi_data = Data.data_xi(Mr=Mr, b_normal=b_normal)
    cov_data = Data.data_cov(Mr=Mr, b_normal=b_normal, inference='mcmc') 
    data_xi_cov = cov_data[1:16, 1:16]
    xi_r_bin = Data.data_xi_bin(Mr=Mr)
    # gmf data 
    data_gmf = Data.data_gmf(Mr=Mr, b_normal=b_normal)
    cov_data = Data.data_cov(Mr=Mr, b_normal=b_normal, inference='mcmc') 
    data_gmf_cov = cov_data[16:, 16:]

    r_binedge = Data.data_gmf_bins()
    gmf_r_bin = 0.5 * (r_binedge[:-1] + r_binedge[1:]) 
   
    prettyplot()
    pretty_colors = prettycolors() 

    fig = plt.figure(figsize=(12,6))
    sub_xi = fig.add_subplot(121) 
    sub_gmf = fig.add_subplot(122)
   
    #sub_xi.errorbar(xi_r_bin, xi_data, yerr = np.sqrt(np.diag(data_xi_cov)), fmt="o", color='k', 
    #        markersize=0, lw=0, capsize=3, elinewidth=1.5)
    #sub_xi.scatter(xi_r_bin, xi_data, c='k', s=10, lw=0)
    sub_xi.fill_between(xi_r_bin, 
            xi_data-np.sqrt(np.diag(data_xi_cov)), xi_data+np.sqrt(np.diag(data_xi_cov)), 
            color=pretty_colors[1])
    sub_xi.set_yscale('log')
    sub_xi.set_xscale('log')
    sub_xi.set_xlim(0.1, 20)
    sub_xi.set_xlabel(r'$\mathtt{r}\; [\mathtt{Mpc}/h]$', fontsize=25)
    sub_xi.set_ylabel(r'$\xi(r)$', fontsize=25)

    #sub_gmf.errorbar(gmf_r_bin, data_gmf, yerr=np.sqrt(np.diag(data_gmf_cov)), 
    #        fmt="o", color='k', 
    #        markersize=0, lw=0, capsize=4, elinewidth=2)
    #sub_gmf.scatter(gmf_r_bin, data_gmf, s=15, lw=0, c='k', label='Mock Observation')
    sub_gmf.fill_between(gmf_r_bin, 
            data_gmf-np.sqrt(np.diag(data_gmf_cov)), data_gmf+np.sqrt(np.diag(data_gmf_cov)), 
            color=pretty_colors[1])
    sub_gmf.set_xlim(1, 20)
    sub_gmf.set_xlabel(r'$\mathtt{N}$ (Group Richness)', fontsize=25)

    sub_gmf.yaxis.tick_right()
    sub_gmf.yaxis.set_ticks_position('both')
    sub_gmf.yaxis.set_label_position('right') 
    sub_gmf.set_ylim([10**-7, 2.0*10**-4])
    sub_gmf.set_yscale('log')
    sub_gmf.set_ylabel(r'$\zeta(\mathtt{N})$', fontsize=25)

    fig.subplots_adjust(hspace=0.05)
    fig_name = ''.join([ut.fig_dir(), 
        'paper.data_observables', 
        '.pdf'])
    fig.savefig(fig_name, bbox_inches='tight', dpi=150) 
    plt.close()
    return None 
Example #13
0
def test_Evolver_logSFRinitiate(sfh, nsnap0=None):
    ''' Test the log(SFR) initiate step within Evolver.Evolve()
    '''
    # load in Subhalo Catalog (pure centrals)
    subhist = Cat.PureCentralHistory(nsnap_ancestor=nsnap0)
    print subhist.File()
    subcat = subhist.Read()

    # load in generic theta (parameter values)
    theta = Evol.defaultTheta(sfh) 
    for k in theta.keys(): 
        print k, '---', theta[k]
    
    eev = Evol.Evolver(subcat, theta, nsnap0=nsnap0)
    eev.Initiate()
    eev.Evolve(forTests=True) 

    #subcat = eev.SH_catalog
    sfr_kwargs = eev.sfr_kwargs  # SFR keyword arguments 
    #logSFR_logM_z = self.logSFR_logM_z # logSFR(logM, z) function 

    prettyplot() 
    pretty_colors = prettycolors() 
    
    if sfh in ['random_step', 'random_step_fluct']:
        #print 'dlogSFR_amp', sfr_kwargs['dlogSFR_amp'].shape
        #print 'tsteps', sfr_kwargs['tsteps'].shape
        i_rand = np.random.choice(range(sfr_kwargs['dlogSFR_amp'].shape[0]), size=10, replace=False)
        
        fig = plt.figure()
        sub = fig.add_subplot(111)

        for ii in i_rand: 
            #print sfr_kwargs['tsteps'][ii, :]
            #print sfr_kwargs['dlogSFR_amp'][ii, :]
            sub.plot(sfr_kwargs['tsteps'][ii, :], sfr_kwargs['dlogSFR_amp'][ii, :])

        sub.set_xlim([UT.t_nsnap(nsnap0), UT.t_nsnap(1)])
        plt.show()

    elif sfh in ['random_step_abias']: 
        i_rand = np.random.choice(range(sfr_kwargs['dlogSFR_amp'].shape[0]), size=10, replace=False)
        
        fig = plt.figure()
        sub = fig.add_subplot(111)

        for ii in i_rand: #range(sfr_kwargs['dlogSFR_amp'].shape[1]): 
            #print sfr_kwargs['tsteps'][ii, :]
            #print sfr_kwargs['dlogSFR_amp'][ii, :]
            sub.scatter(sfr_kwargs['dMhalos'][ii,:], sfr_kwargs['dlogSFR_corr'][ii,:])
        sub.set_xlim([-0.2, 0.2])
        sub.set_ylim([-3.*theta['sfh']['sigma_corr'], 3.*theta['sfh']['sigma_corr']])
        plt.show()

    else: 
        raise NotImplementedError


    return None
def Subhalo_MhaloMag(scatter=0.0, source='cool_ages', nsnap_ancestor=20):
    ''' Test the Subhalos/CentralSubhalos imported from TreePM by 
    comparing their measured SMFs to the analytic SMFs 

    Parameters
    ----------
    scatter : float
        Float that specifies the scatter in the SMHM relation, which 
        affects the SHAM masses
    source : string
        String that specifies which SMF is used for SHAM
    '''
    prettyplot()
    pretty_colors = prettycolors()

    fig = plt.figure(figsize=(10, 10))
    sub = fig.add_subplot(111)
    for i_snap in [7, 4, 1]:

        mu_mag = []
        sig_mag = []

        subh = Subhalos()

        subh.Read(i_snap,
                  scatter=scatter,
                  source=source,
                  nsnap_ancestor=nsnap_ancestor)
        subh.mag_r *= -1.

        m_halo = getattr(subh, 'halo.m.max')
        for m_low in np.arange(10., 15.5, 0.1):
            m_bin = np.where((m_halo > m_low) & (m_halo <= m_low + 0.1))

            mu_mag.append(np.mean(subh.mag_r[m_bin]))
            sig_mag.append(np.std(subh.mag_r[m_bin]))

        #sub.errorbar(np.arange(10.05, 15.55, 0.1), mu_mag, yerr=sig_mag, c=pretty_colors[i_snap])
        sub.fill_between(np.arange(10.05, 15.55, 0.1),
                         np.array(mu_mag) - np.array(sig_mag),
                         np.array(mu_mag) + np.array(sig_mag),
                         color=pretty_colors[i_snap],
                         alpha=0.75,
                         label=r"$ z = " + str(round(get_z_nsnap(i_snap), 2)) +
                         "$")
    sub.set_xlim([10, 15.5])
    sub.set_ylim([-17.8, -23.])
    sub.set_ylabel('$\mathtt{M}_\mathtt{halo}^\mathtt{peak}$', fontsize=25)
    sub.set_ylabel('Magnitude', fontsize=25)
    sub.legend(loc='lower right')
    fig_file = ''.join([
        'figure/test/'
        'Subhalo_Mhalo_Mag', '.scatter',
        str(round(scatter, 2)), '.ancestor',
        str(nsnap_ancestor), '.', source, '.png'
    ])
    fig.savefig(fig_file, bbox_inches='tight')
    plt.close()
def Plot_fQcentrals():
    ''' Plot the quiescent fractions from Tinker et al. (2013)
    '''
    # mass binnning we impose
    m_low = np.array([9.5, 10., 10.5, 11., 11.5])
    m_high = np.array([10., 10.5, 11., 11.5, 12.0])
    m_mid = 0.5 * (m_low + m_high)

    # SDSS
    fq_file = ''.join(
        ['dat/observations/cosmos_fq/', 'fcen_red_sdss_scatter.dat'])
    m_sdss, fqcen_sdss, N_sdss = np.loadtxt(fq_file,
                                            unpack=True,
                                            usecols=[0, 1, 2])

    fqcen_sdss_rebin = []
    for im, m_mid_i in enumerate(m_mid):
        sdss_mbin = np.where((m_sdss >= m_low[im]) & (m_sdss < m_high[im]))

        fqcen_sdss_rebin.append(
            np.sum(fqcen_sdss[sdss_mbin] * N_sdss[sdss_mbin].astype('float')) /
            np.sum(N_sdss[sdss_mbin].astype('float')))
    fqcen_sdss_rebin = np.array(fqcen_sdss_rebin)

    prettyplot()
    pretty_colors = prettycolors()

    fig = plt.figure()
    sub = fig.add_subplot(111)
    sub.plot([9.] + list(m_mid), [0.] + list(fqcen_sdss_rebin), c='k')

    for iz, z in enumerate([0.36, 0.66, 0.88]):
        fq_file = ''.join(
            ['dat/observations/cosmos_fq/', 'stats_z',
             str(iz + 1), '.fq_cen'])

        m_cosmos, fqcen_cosmos, fqcen_cosmos_low, fqcen_cosmos_high = np.loadtxt(
            fq_file, unpack=True, usecols=[0, 1, 2, 3])
        m_cosmos = np.log10(m_cosmos)

        fqcen_interp = interpolate.interp1d(m_cosmos, fqcen_cosmos)
        fqcen_low_interp = interpolate.interp1d(m_cosmos, fqcen_cosmos_low)
        fqcen_high_interp = interpolate.interp1d(m_cosmos, fqcen_cosmos_high)

        fqcen_cosmos_rebin = fqcen_interp(m_mid)
        fqcen_low_cosmos_rebin = fqcen_low_interp(m_mid)
        fqcen_high_cosmos_rebin = fqcen_high_interp(m_mid)

        sub.fill_between([9.] + list(m_mid),
                         [0.] + list(fqcen_low_cosmos_rebin),
                         [0.] + list(fqcen_high_cosmos_rebin),
                         color=pretty_colors[2 * iz + 1])

    sub.set_xlim([8.75, 12.0])
    sub.set_xlabel(r'$\mathtt{M_*}$', fontsize=30)
    sub.set_ylim([0., 1.0])
    sub.set_ylabel(r'$\mathtt{f_Q^{cen}}$', fontsize=30)
    plt.show()
Example #16
0
def plot_predictions(Mr, nburnins, nchains, assembly = True, clotter = False):

    if (assembly == True):
        filename = 'Mr'+str(Mr)+'.hdf5'
    else:
        filename = 'adhoc_Mr'+str(Mr)+'.hdf5'

    sample = h5py.File(filename , "r")["mcmc"]
    npars = sample.shape[2]
    nwalkers = sample.shape[1]
    sample = sample[nchains-nburnins:nchains, : , :]
    sample = sample.reshape(sample.shape[0]*sample.shape[1] , sample.shape[2])
    print np.percentile(sample , [16,50,84] , axis = 0)
    if (clotter==False):
        model = MCMC_model(Mr) 
    
        model_wp = []
        for i in xrange(len(sample) - nwalkers*5 , len(sample)-1):
            print i
            model_wp.append(model._sum_stat(sample[i] , prior_range = None))
            np.savetxt("model_wp_assembly_"+str(Mr)+".dat" , np.array(model_wp)) 
    else:

        theta_best = np.median(sample, axis = 0)
        print theta_best
        model = MCMC_model(Mr)
        wp_best = model._sum_stat(theta_best , prior_range = None)
        if Mr == 19.0:
           cov = np.loadtxt("../../data/wpxicov_dr72_bright0_mr19.0_z0.064_nj400")[:12,:12]
           data_wp = np.loadtxt("../../data/wpxi_dr72_bright0_mr19.0_z0.064_nj400")[:,1]
        if Mr == 20.0:
           cov = np.loadtxt("../../data/wpxicov_dr72_bright0_mr20.0_z0.106_nj400")[:12,:12]
           data_wp = np.loadtxt("../../data/wpxi_dr72_bright0_mr20.0_z0.106_nj400")[:,1]
        prettyplot()
        pretty_colors=prettycolors()
        fig = plt.figure(1, figsize=(16,12))
        ax = fig.add_subplot(111)
        wps = np.loadtxt("model_wp_assembly_"+str(Mr)+".dat")
        a, b, c, d, e = np.percentile(wps, [2.5, 16, 50, 84, 97.5], axis=0)
        rbin = np.loadtxt(path.join(path.dirname(path.abspath(__file__)),
                        "../", "bin"))
        rbin_center = np.mean(rbin , axis = 1)
        
        ax.fill_between(rbin_center, a, e, color=pretty_colors[3], alpha=0.3, edgecolor="none")
        ax.fill_between(rbin_center, b, d, color=pretty_colors[3], alpha=0.5, edgecolor="none")
        ax.errorbar(rbin_center, data_wp, np.diag(cov)**.5, markersize=0, lw=0, capsize=3, elinewidth=1.5) 
        #ax.plot(rbin_center , wp_best , color = "red", lw=1.5) 
        ax.set_xlabel(r'$r_{p}[\mathtt{Mpc}]$', fontsize=27)
        ax.set_ylabel(r'$w_{p}(\mathtt{r_{p}})$', fontsize=27)
        ax.set_title(r"posterior prediction of $w_p$ for $\mathrm{M_r}$<-"+str(Mr))
        ax.set_yscale('log') 
        ax.set_xscale('log')
        ax.set_xticklabels([])
        ax.set_xlim([0.05, 25.])
        #ax.set_ylim([0.09, 1000.])
        fig.savefig("posterior_prediction"+str(Mr)+".pdf", bbox_inches='tight')
        plt.close()
        return None
Example #17
0
def test_analytical():
    '''
    Quick analystical test for the integration scheme
    '''
    def logsfr(logmass, t0, **kwargs):
        return np.log10(2.0 * np.sqrt(10.0**logmass))

    mass0 = 0.0
    t_arr = np.arange(0.0, 14., 1.0)

    rk4_masses, euler_masses = [0.0], [0.0]
    rk4_sfrs, euler_sfrs = [0.0], [0.0]

    for tt in t_arr[1:]:

        rk4_mass_f, rk4_sfr_f = mass_evol.integrated_rk4(logsfr,
                                                         mass0,
                                                         np.min(t_arr),
                                                         tt,
                                                         f_retain=1.0,
                                                         delt=0.01)
        euler_mass_f, euler_sfr_f = mass_evol.integrated_euler(logsfr,
                                                               mass0,
                                                               np.min(t_arr),
                                                               tt,
                                                               f_retain=1.0,
                                                               delt=0.005)

        rk4_masses.append(rk4_mass_f)
        euler_masses.append(euler_mass_f)

        rk4_sfrs.append(rk4_sfr_f)
        euler_sfrs.append(euler_sfr_f)

    prettyplot()
    pretty_colors = prettycolors()
    fig = plt.figure(1, figsize=(10, 12))
    sub = fig.add_subplot(111)

    analytic = np.log10((t_arr * 10**9.)**2)
    sub.plot(t_arr, (rk4_masses - analytic) / analytic,
             lw=4,
             c=pretty_colors[1],
             label='RK4')
    sub.plot(t_arr, (euler_masses - analytic) / analytic,
             lw=4,
             ls='--',
             c=pretty_colors[3],
             label='Euler')
    sub.set_xlim([0.0, 14.0])
    sub.set_xlabel('fake t', fontsize=25)
    sub.set_ylabel('(fake integrated M - fake analytic M)/ fake analytic M',
                   fontsize=25)
    #sub.set_ylim([17.0, 20.0])
    sub.legend(loc='lower right')
    plt.show()
    return None
Example #18
0
def plotCMS_SFH_AsBias(cenque='default', evol_dict=None): 
    ''' Plot the star formation history of star forming main sequence galaxies
    and their corresponding halo mass acretion history 
    '''
    # import evolved galaxy population 
    egp = CMS.EvolvedGalPop(cenque=cenque, evol_dict=evol_dict) 
    egp.Read() 

    MSonly = np.where(egp.t_quench == 999.)     # only keep main-sequence galaxies
    MSonly_rand = np.random.choice(MSonly[0], size=100)

    z_acc, t_acc = UT.zt_table()
    t_cosmic  = t_acc[1:16]
    dt = 0.1
    
    t_arr = np.arange(t_cosmic.min(), t_cosmic.max()+dt, dt)

    prettyplot() 
    pretty_colors = prettycolors() 
    fig = plt.figure()
    sub1 = fig.add_subplot(211)
    sub2 = fig.add_subplot(212)
    
    dsfrt = np.zeros((len(t_arr), len(MSonly_rand)))
    for i_t, tt in enumerate(t_arr): 
        dsfr = SFR.dSFR_MS(tt, egp.sfh_dict) 
        for ii, i_gal in enumerate(MSonly_rand): 
            dsfrt[i_t,ii] = dsfr[i_gal]
    
    i_col = 0 
    for ii, i_gal in enumerate(MSonly_rand): 
        tlim = np.where(t_arr > egp.tsnap_genesis[i_gal]) 

        tcoslim = np.where(t_cosmic >= egp.tsnap_genesis[i_gal]) 
        halo_hist = (egp.Mhalo_hist[i_gal])[tcoslim][::-1]
        halo_exists = np.where(halo_hist != -999.) 
        if np.power(10, halo_hist[halo_exists]-egp.halo_mass[i_gal]).min() < 0.7:  
            if i_col < 5: 
                sub1.plot(t_arr[tlim], dsfrt[:,ii][tlim], lw=3, c=pretty_colors[i_col])
                sub2.plot(t_cosmic[tcoslim][::-1][halo_exists], 
                        np.power(10, halo_hist[halo_exists]-egp.halo_mass[i_gal]), 
                        lw=3, c=pretty_colors[i_col])
                i_col += 1 

    sub1.set_xlim([5.0, 13.5])
    sub1.set_xticklabels([])
    sub1.set_ylim([-1., 1.])
    sub1.set_ylabel(r'$\mathtt{SFR(t) - <SFR_{MS}(t)>}$', fontsize=25)
    
    sub2.set_xlim([5.0, 13.5])
    sub2.set_xlabel(r'$\mathtt{t_{cosmic}}$', fontsize=25)
    sub2.set_ylim([0.0, 1.1])
    sub2.set_ylabel(r'$\mathtt{M_h(t)}/\mathtt{M_h(t_f)}$', fontsize=25)
    fig_file = ''.join([UT.fig_dir(), 'SFH_AsBias.CMS', egp._Spec_str(), '.png']) 
    fig.savefig(fig_file, bbox_inches='tight') 
    plt.close()
    return None
Example #19
0
def plotCMS_SFMS(cenque='default', evol_dict=None):
    ''' Plot the SFR-M* relation of the SFMS and compare to expectations
    '''
    # import evolved galaxy population 
    cms = CMS.CentralMS(cenque=cenque)
    cms._Read_CenQue()
    MSpop = CMS.EvolvedGalPop(cenque=cenque, evol_dict=evol_dict) 
    MSpop.Read() 
    MSonly = np.where(MSpop.t_quench == 999.) 
    
    delta_m = 0.5
    mbins = np.arange(MSpop.mass[MSonly].min(), MSpop.mass[MSonly].max(), delta_m) 
    
    sfr_percent = np.zeros((len(mbins)-1, 4))
    for im, mbin in enumerate(mbins[:-1]):  
        within = np.where(
                (MSpop.mass[MSonly] > mbin) & 
                (MSpop.mass[MSonly] <= mbin + delta_m) 
                ) 
        #sfr_percent[im,:] = np.percentile(MSpop.sfr[MSonly[0][within]], [2.5, 16, 84, 97.5])
        sfr_percent[im,:] = UT.weighted_quantile(MSpop.sfr[MSonly[0][within]], 
                [0.025, 0.16, 0.84, 0.975], weights=MSpop.weight_down[MSonly[0][within]])
        
    prettyplot() 
    pretty_colors = prettycolors()
    fig = plt.figure()
    sub = fig.add_subplot(111)

    # parameterized observed SFMS 
    obvs_mu_sfr = SFR.AverageLogSFR_sfms(0.5*(mbins[:-1]+mbins[1:]), 0.05, sfms_dict=cms.sfms_dict)
    obvs_sig_sfr = SFR.ScatterLogSFR_sfms(0.5*(mbins[:-1]+mbins[1:]), 0.05, sfms_dict=cms.sfms_dict)
    sub.fill_between(0.5*(mbins[:-1] + mbins[1:]), 
            obvs_mu_sfr - 2.*obvs_sig_sfr, obvs_mu_sfr + 2.*obvs_sig_sfr, 
            color=pretty_colors[1], alpha=0.3, edgecolor=None, lw=0) 
    sub.fill_between(0.5*(mbins[:-1] + mbins[1:]), 
            obvs_mu_sfr - obvs_sig_sfr, obvs_mu_sfr + obvs_sig_sfr, 
            color=pretty_colors[1], alpha=0.5, edgecolor=None, lw=0, label='Observations') 

    # simulation 
    sub.fill_between(0.5*(mbins[:-1] + mbins[1:]), sfr_percent[:,0], sfr_percent[:,-1],  
            color=pretty_colors[3], alpha=0.3, edgecolor=None, lw=0) 
    sub.fill_between(0.5*(mbins[:-1] + mbins[1:]), sfr_percent[:,1], sfr_percent[:,-2], 
            color=pretty_colors[3], alpha=0.5, edgecolor=None, lw=0, label='Simulated') 

    # x,y axis
    sub.set_xlim([9.0, 12.0]) 
    sub.set_xlabel(r'$\mathtt{M_*}\; [\mathtt{M}_\odot]$', fontsize=25)
    sub.set_ylim([-2., 1.]) 
    sub.set_ylabel(r'$\mathtt{SFR}\; [\mathtt{M}_\odot/\mathtt{yr}]$', fontsize=25)

    sub.legend(loc='lower right', numpoints=1, markerscale=1.) 

    fig_file = ''.join([UT.fig_dir(), 'SFMS.CMS', MSpop._Spec_str(), '.png'])
    plt.savefig(fig_file, bbox_inches='tight') 
    plt.close()
    return None
def test_ancestors_without_descendant(nsnap_ancestor = 20, scatter = 0.0, source='li-drory-march'): 
    '''
    What happens to ancestors that do not have descendants at nsnap = 1


    Notes
    -----
    * More than 50% of the subhalos at nsnap=20 do not have descendants at nsnap = 1. 
        What happens to them? 
    * Do they become satellites? --> Some become satellites, others 
        with no mass subhalos don't stay in the catalog at all
    '''
    prettyplot()
    pretty_colors = prettycolors()

    fig = plt.figure(figsize=(10,10))
    sub = fig.add_subplot(111)
    
    # Central subhalo at nsnap_ancestor (ancesotr)
    anc = CentralSubhalos()
    anc.read(nsnap_ancestor, scatter=scatter, source=source)
    
    # Centrals subhalo at nsnap = 1 (descendant)
    des = CentralSubhalos()
    des.read(1, scatter=scatter, source=source)
    
    no_descendants = np.invert(np.in1d(anc.index, des.ancestor20))
    massive_nodescendants = np.where(anc.mass[no_descendants] > 0.0)
    print 'N_SH no descendants ', len(anc.mass[no_descendants])
    print 'N_SH total ', len(anc.mass)
    print np.float(len(anc.mass[no_descendants]))/np.float(len(anc.mass))

    no_des_index = anc.index[no_descendants][massive_nodescendants][:5]
    print anc.mass[no_descendants][massive_nodescendants][:5]
    for isnap in range(1, nsnap_ancestor)[::-1]: 
        i_des = CentralSubhalos()
        i_des.read(isnap, scatter=scatter, source=source)
    
        #print isnap, np.in1d(no_des_index, i_des.ancestor20)

        #if not np.in1d(no_des_index, i_des.ancestor20)[0]: 
        des_sh = Subhalos()
        des_sh.read(isnap, scatter=scatter, source=source)
        #if np.sum(np.in1d(des_sh.ancestor20, no_des_index)) != len(no_des_index): 
        #    raise ValueError
        print des_sh.ilk[np.in1d(des_sh.ancestor20, no_des_index)][np.argsort(des_sh.ancestor20[np.in1d(des_sh.ancestor20, no_des_index)])]
        print 'M* ', des_sh.mass[np.in1d(des_sh.ancestor20, no_des_index)][np.argsort(des_sh.ancestor20[np.in1d(des_sh.ancestor20, no_des_index)])]
        print 'M_halo ', getattr(des_sh, 'halo.m')[np.in1d(des_sh.ancestor20, no_des_index)][np.argsort(des_sh.ancestor20[np.in1d(des_sh.ancestor20, no_des_index)])]
        #print des_sh.mass[np.in1d(des_sh.index, no_des_index)]
        #np.in1d(i_des.ancestor20, no_des_index)

    sub.set_yscale('log')
    sub.set_ylim([10**-5, 10**-1])
    sub.set_xlim([6.0, 12.0])
    sub.legend(loc='upper right')
Example #21
0
def plot_nseriesbox_p_k_mu(imock, plot='2D', Ngrid=3600):
    ''' Plot P(k,mu). Option for plotting the monopole is included.
    '''
    # read k, mu, counts, P(k,mu)
    k_bin, mu_bin, co, avgP = nseriesbox_pkmu(imock, Ngrid=Ngrid)
    
    prettyplot()
    pretty_color = prettycolors()
    fig = plt.figure(figsize=(14,10))
    sub = fig.add_subplot(111)
    if plot == '2D': 
        colormap = plt.cm.afmhot
        cont = sub.pcolormesh(np.arange(-1.0, 1.1, 0.1), k_bin, avgP, cmap=colormap)
        plt.colorbar(cont)
        # y-axis
        sub.set_ylabel(r'$\mathtt{k \;(\mathrm{Mpc}/h})$', fontsize=20)
        # x-axis
        sub.set_xlabel(r'$\mu$', fontsize=20)
    elif plot == 'pk': 
        proj_p0k = [] 
        proj_p2k = [] 
        Leg2 = 2.5 * (3.0 * mu_bin**2 - 1.0)    # L_2(mu)
        for i in range(N_kbin): 
            pkmu_k = avgP[i]
            co_k = co[i]
            
            tot_p0k = np.sum(co_k[~np.isnan(pkmu_k)] * pkmu_k[~np.isnan(pkmu_k)])
            tot_count = np.sum(co_k[~np.isnan(pkmu_k)])
            proj_p0k.append(tot_p0k/tot_count)
            
            tot_p2k = np.sum(co_k[~np.isnan(pkmu_k)] * pkmu_k[~np.isnan(pkmu_k)] * Leg2[~np.isnan(pkmu_k)])
            tot_count = np.sum(co_k[~np.isnan(pkmu_k)])
            proj_p2k.append(tot_p2k/tot_count)
            
        sub.plot(k_bin, proj_p0k, lw=4, c=pretty_color[0], label='Monopole')
        sub.plot(k_bin, proj_p2k, lw=4, c=pretty_color[2], label='Quadrupole')
        k, p0k, p2k = np.loadtxt('/home/users/hahn/power360z_BoxN7.dat', unpack=True, usecols=[0,-1,2])
        sub.plot(k, p0k * (2*np.pi)**3, ls='--', c='k')
        sub.plot(k, p2k * (2*np.pi)**3, ls='--', c='k')

        # x-axis
        sub.set_xlabel(r'$\mathtt{k \;(\mathrm{Mpc}/h})$', fontsize=25)
        sub.set_xlim([10**-3, 10**1])
        sub.set_xscale("log")
        #y-axis
        sub.set_ylabel(r"$\mathtt{P_{l}(k)}$", fontsize=25)
        sub.legend(loc='upper right')
    else:
        raise ValueError

    sub.set_yscale("log")
    fig.savefig(''.join(['figure/', 
        'pkmu_', str(Ngrid), 'z_BoxN', str(imock), '.', plot, '.png']), 
        bbox_inches='tight')
    plt.close()
Example #22
0
def Plot_dFqdt():
    ''' Plot the evolution of the derivative of the quiescent fraction as a function of M* and t
    for different parameterized models of f_Q

    d f_Q / d t 

    '''
    prettyplot()
    pretty_colors = prettycolors()
    dt = 0.01

    M_arr = np.arange(9.0, 12.5, 0.5)
    t_arr = np.arange(6.0, 13.0, 0.2)

    fig = plt.figure()
    sub = fig.add_subplot(111)

    for iM, Mstar in enumerate(M_arr):
        qf = gp.Fq()
        lit = 'wetzelsmooth'
        sub.plot(t_arr, [gp.dFqdt(Mstar, tt, lit=lit, dt=dt) for tt in t_arr],
                 ls='-',
                 lw=3,
                 c=pretty_colors[iM],
                 label=r"$\mathtt{M}_* = " + str(round(Mstar, 2)) + "$")

        lit = 'wetzel'
        sub.plot(t_arr, [gp.dFqdt(Mstar, tt, lit=lit, dt=dt) for tt in t_arr],
                 ls=':',
                 lw=3,
                 c=pretty_colors[iM])

        lit = 'cosmosinterp'
        t_blah = np.arange(8.0, 9.6, 0.1)
        sub.plot(t_blah,
                 [gp.dFqdt(Mstar, tt, lit=lit, dt=dt) for tt in t_blah],
                 ls='--',
                 lw=3,
                 c=pretty_colors[iM])

        lit = 'cosmosfit'
        t_blah = np.arange(8.0, 9.6, 0.1)
        sub.plot(t_blah,
                 [gp.dFqdt(Mstar, tt, lit=lit, dt=dt) for tt in t_blah],
                 ls='-.',
                 lw=3,
                 c=pretty_colors[iM])

    sub.set_xlim([t_arr.min(), t_arr.max()])
    sub.legend(loc='upper left')
    sub.set_ylim([0., 0.2])
    #plt.show()
    fig_file = ''.join(['figure/test/', 'dfqdt.png'])
    fig.savefig(fig_file, bbox_inches='tight')
    return None
def PlotFq_WetzelComp(): 
    ''' Compare the quiescent function evolution for different analytic prescriptions 
    of Wetzel et al. (2013)
    '''
    lit = ['wetzel', 'wetzel_alternate'] 
    
    M_arr = np.arange(9.0, 12.2, 0.2)
    #z_arr = np.arange(0.0, 1.2, 0.2)
    z_arr = np.array([0.0, 0.36, 0.66, 0.88]) 
    
    prettyplot() 
    pretty_colors = prettycolors() 
    fig = plt.figure()
    sub = fig.add_subplot(111) 

    qf = gp.Fq()
    for il, l in enumerate(lit): 
        if il == 0: 
            ls = '-'
        elif il == 1: 
            ls = '--'

        for iz, z in enumerate(z_arr): 
            if iz == 0: 
                label = l.title()
            else: 
                label = None
            fq_M = qf.model(M_arr, z, lit=l)  
            sub.plot(M_arr, fq_M, c=pretty_colors[iz], lw=3, ls=ls, label=label)

    # Now plot Tinker et al. (2013)'s fQ^cen 
    for iz, z in enumerate(z_arr): 
        if z != 0.0: 
            fq_file = ''.join(['dat/observations/cosmos_fq/', 
                'stats_z', str(iz), '.fq_cen']) 
            mmm, fqcen = np.loadtxt(fq_file, unpack=True, usecols=[0, 1]) 
            mmm = np.log10(mmm)
        else: 
            fq_file = ''.join(['dat/observations/cosmos_fq/', 
                'fcen_red_sdss_scatter.dat']) 
            mmm, fqcen = np.loadtxt(fq_file, unpack=True, usecols=[0, 1]) 
        sub.scatter(mmm, fqcen, c=pretty_colors[iz], lw=0, s=10) 
    
    sub.set_xlim([9.0, 12.]) 
    sub.set_xlabel(r'$\mathtt{M_{*}}$', fontsize=25)

    sub.set_ylim([0., 1.])
    sub.set_ylabel(r'$\mathtt{f_Q}$', fontsize=25) 
    sub.legend(loc='upper left') 
    fig_file = ''.join(['figure/test/', 'Fq_Wetzel_Comparison.png'])
    fig.savefig(fig_file, bbox_inches='tight') 
    plt.close()

    return None
def Subhalo_MhaloMag(scatter=0.0, source='cool_ages', 
        nsnap_ancestor=20 ): 
    ''' Test the Subhalos/CentralSubhalos imported from TreePM by 
    comparing their measured SMFs to the analytic SMFs 

    Parameters
    ----------
    scatter : float
        Float that specifies the scatter in the SMHM relation, which 
        affects the SHAM masses
    source : string
        String that specifies which SMF is used for SHAM
    '''
    prettyplot()
    pretty_colors = prettycolors()

    fig = plt.figure(figsize=(10,10))
    sub = fig.add_subplot(111)
    for i_snap in [7, 4, 1]:

        mu_mag = []
        sig_mag = [] 

        subh = Subhalos()

        subh.Read(i_snap, scatter=scatter, source=source, nsnap_ancestor=nsnap_ancestor)
        subh.mag_r *= -1.
        
        m_halo = getattr(subh, 'halo.m.max') 
        for m_low in np.arange(10., 15.5, 0.1): 
            m_bin = np.where((m_halo > m_low) & (m_halo <= m_low+0.1))

            mu_mag.append(np.mean(subh.mag_r[m_bin]))
            sig_mag.append(np.std(subh.mag_r[m_bin]))
    
        #sub.errorbar(np.arange(10.05, 15.55, 0.1), mu_mag, yerr=sig_mag, c=pretty_colors[i_snap])
        sub.fill_between(np.arange(10.05, 15.55, 0.1), 
                np.array(mu_mag) - np.array(sig_mag), 
                np.array(mu_mag) + np.array(sig_mag), 
                color=pretty_colors[i_snap], alpha=0.75, 
                label=r"$ z = "+str(round(get_z_nsnap(i_snap),2))+"$") 
    sub.set_xlim([10, 15.5])
    sub.set_ylim([-17.8, -23.])
    sub.set_ylabel('$\mathtt{M}_\mathtt{halo}^\mathtt{peak}$', fontsize=25)
    sub.set_ylabel('Magnitude', fontsize=25)
    sub.legend(loc='lower right')
    fig_file = ''.join(['figure/test/'
        'Subhalo_Mhalo_Mag', 
        '.scatter', str(round(scatter,2)), 
        '.ancestor', str(nsnap_ancestor),
        '.', source, 
        '.png']) 
    fig.savefig(fig_file, bbox_inches='tight') 
    plt.close()
Example #25
0
    def __init__(self, **kwargs): 
        '''
        Class that generally encompasses all of the plotting I will do for the CenQue project
        '''
        self.kwargs = kwargs

        prettyplot()
        self.pretty_colors = prettycolors()

        self.fig = plt.figure(figsize=[10, 10])
        self.sub = self.fig.add_subplot(1,1,1)
def SubhaloLF(scatter=0.0, source='cool_ages', nsnap_ancestor=20):
    ''' Test the Subhalos/CentralSubhalos imported from TreePM by 
    comparing their measured SMFs to the analytic SMFs 

    Parameters
    ----------
    scatter : float
        Float that specifies the scatter in the SMHM relation, which 
        affects the SHAM masses
    source : string
        String that specifies which SMF is used for SHAM
    '''
    prettyplot()
    pretty_colors = prettycolors()

    fig = plt.figure(figsize=(10, 10))
    sub = fig.add_subplot(111)
    for i_snap in [11, 7, 4, 1]:
        smf = SMF()
        subh = Subhalos()

        subh.Read(i_snap,
                  scatter=scatter,
                  source=source,
                  nsnap_ancestor=nsnap_ancestor)
        subh.mag_r *= -1.
        mass, phi = smf.Obj(subh,
                            dlogm=0.1,
                            m_arr=np.arange(-24.0, -16., 0.1),
                            LF=True)

        sub.plot(mass, phi, lw=2, ls='-', c=pretty_colors[i_snap % 19])

        analytic_mass, analytic_phi = smf.analytic(get_z_nsnap(i_snap),
                                                   source=source)
        sub.plot(analytic_mass,
                 analytic_phi,
                 lw=4,
                 ls='--',
                 c=pretty_colors[i_snap % 19],
                 label=r"$ z = " + str(round(get_z_nsnap(i_snap), 2)) + "$")

    sub.set_yscale('log')
    sub.set_ylim([10**-7, 10**-1])
    sub.set_xlim([-24.5, -17.8])
    sub.legend(loc='upper right')
    fig_file = ''.join([
        'figure/test/'
        'SubhaloLF', '.scatter',
        str(round(scatter, 2)), '.ancestor',
        str(nsnap_ancestor), '.', source, '.png'
    ])
    fig.savefig(fig_file, bbox_inches='tight')
    plt.close()
def test_analytical(): 
    '''
    Quick analystical test for the integration scheme
    '''

    def logsfr(logmass, t0, **kwargs): 
        return np.log10(2.0 * np.sqrt(10.0**logmass))
    
    mass0 = 0.0 
    t_arr = np.arange(0.0, 14., 1.0)
    
    rk4_masses, euler_masses = [0.0], [0.0]
    rk4_sfrs, euler_sfrs = [0.0], [0.0]

    for tt in t_arr[1:]:

        rk4_mass_f, rk4_sfr_f = mass_evol.integrated_rk4(
                logsfr, 
                mass0, 
                np.min(t_arr), 
                tt, 
                f_retain = 1.0, 
                delt = 0.01
                )
        euler_mass_f, euler_sfr_f = mass_evol.integrated_euler(
                logsfr, 
                mass0, 
                np.min(t_arr), 
                tt, 
                f_retain = 1.0, 
                delt = 0.005
                )

        rk4_masses.append(rk4_mass_f)
        euler_masses.append(euler_mass_f)
        
        rk4_sfrs.append(rk4_sfr_f)
        euler_sfrs.append(euler_sfr_f)

    prettyplot()
    pretty_colors = prettycolors()
    fig = plt.figure(1, figsize=(10,12))
    sub = fig.add_subplot(111)
    
    analytic = np.log10((t_arr * 10**9.)**2)
    sub.plot(t_arr, (rk4_masses-analytic)/analytic, lw=4, c=pretty_colors[1], label='RK4')
    sub.plot(t_arr, (euler_masses-analytic)/analytic, lw=4, ls='--', c=pretty_colors[3], label='Euler')
    sub.set_xlim([0.0, 14.0])
    sub.set_xlabel('fake t', fontsize=25)
    sub.set_ylabel('(fake integrated M - fake analytic M)/ fake analytic M', fontsize=25)
    #sub.set_ylim([17.0, 20.0])
    sub.legend(loc='lower right')
    plt.show()
    return None
def Plot_fQcentrals():
    ''' Plot the quiescent fractions from Tinker et al. (2013)
    '''
    # mass binnning we impose 
    m_low = np.array([9.5, 10., 10.5, 11., 11.5]) 
    m_high = np.array([10., 10.5, 11., 11.5, 12.0])
    m_mid = 0.5 * (m_low + m_high) 

    # SDSS 
    fq_file = ''.join(['dat/observations/cosmos_fq/', 'fcen_red_sdss_scatter.dat']) 
    m_sdss, fqcen_sdss, N_sdss = np.loadtxt(fq_file, unpack=True, usecols=[0,1,2])
    
    fqcen_sdss_rebin = [] 
    for im, m_mid_i in enumerate(m_mid): 
        sdss_mbin = np.where(
                (m_sdss >= m_low[im]) & 
                (m_sdss < m_high[im])) 
    
        fqcen_sdss_rebin.append(
                np.sum(fqcen_sdss[sdss_mbin] * N_sdss[sdss_mbin].astype('float'))/np.sum(N_sdss[sdss_mbin].astype('float'))
                )
    fqcen_sdss_rebin = np.array(fqcen_sdss_rebin)

    prettyplot()
    pretty_colors = prettycolors()
    
    fig = plt.figure()
    sub = fig.add_subplot(111)
    sub.plot([9.]+list(m_mid), [0.]+list(fqcen_sdss_rebin), c='k') 
    
    for iz, z in enumerate([0.36, 0.66, 0.88]): 
        fq_file = ''.join(['dat/observations/cosmos_fq/', 
            'stats_z', str(iz+1), '.fq_cen']) 
        
        m_cosmos, fqcen_cosmos, fqcen_cosmos_low, fqcen_cosmos_high = np.loadtxt(fq_file, unpack=True, usecols=[0,1,2,3])
        m_cosmos = np.log10(m_cosmos)

        fqcen_interp = interpolate.interp1d(m_cosmos, fqcen_cosmos) 
        fqcen_low_interp = interpolate.interp1d(m_cosmos, fqcen_cosmos_low) 
        fqcen_high_interp = interpolate.interp1d(m_cosmos, fqcen_cosmos_high) 
    
        fqcen_cosmos_rebin = fqcen_interp(m_mid)
        fqcen_low_cosmos_rebin = fqcen_low_interp(m_mid)
        fqcen_high_cosmos_rebin = fqcen_high_interp(m_mid)

        sub.fill_between([9.]+list(m_mid), 
                [0.]+list(fqcen_low_cosmos_rebin), [0.]+list(fqcen_high_cosmos_rebin), 
                color=pretty_colors[2*iz+1]) 
    
    sub.set_xlim([8.75, 12.0])
    sub.set_xlabel(r'$\mathtt{M_*}$', fontsize=30) 
    sub.set_ylim([0., 1.0])
    sub.set_ylabel(r'$\mathtt{f_Q^{cen}}$', fontsize=30) 
    plt.show() 
Example #29
0
def plotCMS_SMHMR_MS(cenque='default', evol_dict=None): 
    ''' Plot the Stellar Mass to Halo Mass Relation of the evolved Gal population 
    '''
    # import evolved galaxy population 
    egp = CMS.EvolvedGalPop(cenque=cenque, evol_dict=evol_dict) 
    egp.Read() 
    
    # Calculate the SMHMR for the EvolvedGalPop
    m_halo_bin = np.arange(10., 15.25, 0.25)    # M_halo bins 
    m_halo_mid = 0.5 * (m_halo_bin[:-1] + m_halo_bin[1:]) # M_halo bin mid

    smhmr = np.zeros((len(m_halo_bin)-1, 5)) 
    for im, m_mid in enumerate(m_halo_mid): 
        inbin = np.where(
                (egp.halo_mass > m_halo_bin[im]) &
                (egp.halo_mass <= m_halo_bin[im+1])) 
        smhmr[im,:] = np.percentile(egp.mass[inbin], [2.5, 16, 50, 84, 97.5])
        #smhmr[im,:] = UT.weighted_quantile(egp.mass[inbin], [0.025, 0.16, 0.50, 0.84, 0.975], 
        #        weights=egp.weight_down[inbin])

    # "observations" with observed scatter of 0.2 dex 
    obvs_smhmr = np.zeros((len(m_halo_bin)-1, 2))
    obvs_smhmr[:,0] = smhmr[:,2] - 0.2      
    obvs_smhmr[:,1] = smhmr[:,2] + 0.2      

    prettyplot() 
    pretty_colors = prettycolors() 
    fig = plt.figure()
    sub = fig.add_subplot(111)

    sub.fill_between(m_halo_mid, smhmr[:,0], smhmr[:,-1], 
        color=pretty_colors[1], alpha=0.25, edgecolor=None, lw=0) 
    sub.fill_between(m_halo_mid, smhmr[:,1], smhmr[:,-2], 
        color=pretty_colors[1], alpha=0.5, edgecolor=None, lw=0, 
        label=r'$\mathtt{Simulated}$') 
    
    sub.plot(m_halo_mid, obvs_smhmr[:,0], 
        color='k', ls='--', lw=3) 
    sub.plot(m_halo_mid, obvs_smhmr[:,1], 
        color='k', ls='--', lw=3, 
        label=r"$\sigma = \mathtt{0.2}$") 

    sub.set_xlim([10., 15.0])
    sub.set_ylim([9., 12.0])
    sub.set_xlabel(r'$\mathtt{log}\;\mathtt{M_{halo}}\;\;[\mathtt{M_\odot}]$', fontsize=25) 
    sub.set_ylabel(r'$\mathtt{log}\;\mathtt{M_{*}}\;\;[\mathtt{M_\odot}]$', fontsize=25) 

    sub.legend(loc='upper right') 
    
    fig_file = ''.join([UT.fig_dir(), 'SMHMR_MS.CMS', egp._Spec_str(), '.png']) 
    fig.savefig(fig_file, bbox_inches='tight') 
    plt.close() 
    return None
Example #30
0
def AllSubhaloSFMS(scatter=0.2, source='li-march', age_indicator=None): 
    '''
    '''
    # import AllSubhalo object
    owl = AllSubhalos(scatter=scatter, source=source)
    owl.Build(age_indicator=age_indicator)

    prettyplot()
    pretty_colors = prettycolors()

    fig = plt.figure(figsize=(16,8))

    if age_indicator is None: 
        sub1 = fig.add_subplot(121) # centrals
        sub1.scatter(getattr(owl, 'm.star')[owl.cen_index], owl.sfr[owl.cen_index], c=pretty_colors[3], lw=0)
        sub2 = fig.add_subplot(122) # satellites
        sub2.scatter(getattr(owl, 'm.star')[owl.sat_index], owl.sfr[owl.sat_index], c=pretty_colors[5], lw=0)
    else: 
        sub1 = fig.add_subplot(121) # centrals
        cen = sub1.scatter(getattr(owl, 'm.star')[owl.cen_index], owl.sfr[owl.cen_index], c=owl.central_age, cmap='viridis', lw=0) 
        plt.colorbar(cen) 
        sub2 = fig.add_subplot(122) # satellites 
        sub2.scatter(getattr(owl, 'm.star')[owl.sat_index], owl.sfr[owl.sat_index], c=pretty_colors[5], lw=0) 
    
    sub1.text(9.5, -4., 'Central', fontsize=25)
    sub2.text(9.5, -4., 'Satellite', fontsize=25)

    sub1.set_xlim([9.0, 12.0])
    sub1.set_xlabel(r'$\mathtt{M}_*$', fontsize=25)
    sub1.set_ylim([-5.0, 2.0])
    sub1.set_xlabel('SFR', fontsize=25)

    sub2.set_xlim([9.0, 12.0])
    sub2.set_xlabel(r'$\mathtt{M}_*$', fontsize=25)
    sub2.set_ylim([-5.0, 2.0])
    sub2.set_yticklabels([]) 

    if age_indicator is None: 
        age_str = 'NOagematch'
    else: 
        age_str = 'agematch_'+age_indicator

    fig_file = ''.join(['figure/test/', 
        'AllSubhalosSFMS', 
        '.sham', 
        '.', str(scatter),
        '.', source, 
        '.', age_str, 
        '.png']) 
    fig.savefig(fig_file, bbox_inches='tight') 
    plt.close()
    return None
Example #31
0
def AllSubhalosSMF(scatter=0.2, source='li-march', age_indicator=None): 
    ''' Compare the SMF of the AllSubhalo object to analytic SMF 
    '''
    # import AllSubhalo object
    owl = AllSubhalos(scatter=scatter, source=source)
    owl.Build(age_indicator=age_indicator)

    prettyplot()
    pretty_colors = prettycolors()

    fig = plt.figure(figsize=(10,10))
    sub = fig.add_subplot(111)
    smf = SMF()
    
    # AllSubhalo SMF
    owl.mass = getattr(owl, 'm.star') 
    subh_mass, subh_phi = smf.Obj(owl, dlogm=0.1, LF=False)
    sub.plot(subh_mass, subh_phi, lw=4, c=pretty_colors[3]) 
    subh_mass, subh_phi = smf._smf(owl.mass[np.where(owl.sfr != -999.)], dlogm=0.1)
    sub.plot(subh_mass, subh_phi, lw=1, c='k') 
    sub.vlines(9.7, subh_phi.min(), subh_phi.max(), linestyle='--', color='k')
    
    # Analytic SMF
    analytic_mass, analytic_phi = smf.analytic(0.05, source=source) 
    sub.plot(analytic_mass, analytic_phi, lw=4, ls='--', c='k', label='Analytic')
    
    # y-axis
    sub.set_yscale('log')
    sub.set_ylim([10**-5, 10**-1])
    sub.set_ylabel(r'$\Phi$', fontsize=25)
    # x-axis
    sub.set_xlim([6.0, 12.0])
    sub.set_xlabel(r'$\mathtt{M_*}$', fontsize=25)

    sub.legend(loc='lower left') 
    
    if age_indicator is None: 
        age_str = 'NOagematch'
    else: 
        age_str = 'agematch_'+age_indicator

    fig_file = ''.join(['figure/test/', 
        'AllSubhalosSMF', 
        '.sham', 
        '.', str(scatter),
        '.', source, 
        '.', age_str, 
        '.png']) 

    fig.savefig(fig_file, bbox_inches='tight') 
    plt.close() 
    return None 
def Plot_fQcen_SDSS():
    ''' Compare the quiescent fraction of SDSS from the *corrected* SDSS fQ^cen 
    from Tinker et al. (2013) versus the Wetzel et al. (2013) parameterization. 
    '''
    # mass binnning we impose
    m_low = np.array([9.5, 10., 10.5, 11., 11.5])
    m_high = np.array([10., 10.5, 11., 11.5, 12.0])
    m_mid = 0.5 * (m_low + m_high)

    # SDSS
    fq_file = ''.join(
        ['dat/observations/cosmos_fq/', 'fcen_red_sdss_scatter.dat'])
    m_sdss, fqcen_sdss, N_sdss = np.loadtxt(fq_file,
                                            unpack=True,
                                            usecols=[0, 1, 2])

    fqcen_sdss_rebin = []
    for im, m_mid_i in enumerate(m_mid):
        sdss_mbin = np.where((m_sdss >= m_low[im]) & (m_sdss < m_high[im]))

        fqcen_sdss_rebin.append(
            np.sum(fqcen_sdss[sdss_mbin] * N_sdss[sdss_mbin].astype('float')) /
            np.sum(N_sdss[sdss_mbin].astype('float')))
    fqcen_sdss_rebin = np.array(fqcen_sdss_rebin)

    prettyplot()
    pretty_colors = prettycolors()
    fig = plt.figure()
    sub = fig.add_subplot(111)
    qf = Fq()
    fqcen_model = qf.model(m_mid, 0.05, lit='cosmos_tinker')
    sub.plot(m_mid,
             fqcen_model,
             c=pretty_colors[3],
             lw=3,
             label=r'Wetzel et al. (2013) fit')
    sub.scatter(m_mid,
                fqcen_sdss_rebin,
                color=pretty_colors[0],
                lw=0,
                s=40,
                label=r'Tinker et al. (2013)')

    sub.set_xlim([9.0, 12.0])
    sub.set_xlabel(r'$\mathtt{log\;M_*}$', fontsize=25)
    sub.set_ylim([0.0, 1.0])
    sub.set_ylabel(r'$\mathtt{f_Q^{cen}}$', fontsize=25)
    sub.legend(loc='upper left', scatterpoints=1, markerscale=3)
    fig_file = ''.join(['figure/test/', 'Fq_central_SDSS.png'])
    fig.savefig(fig_file, bbox_inches='tight')
    plt.close()
Example #33
0
def Test_Jackknife(n_jack, RADec_bins=[3, 3]):
    ''' Test the Jackknifing
    '''
    cat_dict = {
        'name': 'tinker',
        'Mrcut': 18,
        'primary_delv': 500.,
        'primary_rperp': 0.5,
        'neighbor_delv': 500.,
        'neighbor_rperp': 5.
    }
    # read conformity catalog based on input catalog dictionary
    concat = clog.ConformCatalog(Mrcut=cat_dict['Mrcut'],
                                 primary_delv=cat_dict['primary_delv'],
                                 primary_rperp=cat_dict['primary_rperp'],
                                 neighbor_delv=cat_dict['neighbor_delv'],
                                 neighbor_rperp=cat_dict['neighbor_rperp'])
    catalog = concat.Read()
    jack_catalog = concat.Jackknife(catalog, n_jack, RADec_bins=RADec_bins)
    #jack_catalog = concat.ReadJackknife(n_jack, RADec_bins=RADec_bins)

    prettyplot()
    pretty_colors = prettycolors()
    fig = plt.figure()
    sub = fig.add_subplot(111)

    sub.scatter(catalog['ra'], catalog['dec'], s=6, lw=0, c='k')
    sub.scatter(jack_catalog['ra'],
                jack_catalog['dec'],
                s=6,
                lw=0,
                c=pretty_colors[3])

    # axes
    sub.set_xlabel('RA', fontsize=25)
    sub.set_xlim([-50, 400])
    sub.set_ylabel('Dec', fontsize=25)
    sub.set_ylim([-20, 80])
    sub.minorticks_on()

    fig_file = ''.join([
        UT.dir_fig(), 'test_jackknife.',
        str(n_jack), 'of',
        str(RADec_bins[0]), 'x',
        str(RADec_bins[1]), '.png'
    ])
    fig.savefig(fig_file, bbox_inches='tight')
    plt.close()
    return None
Example #34
0
def PlotkPk(name, version): 
    peek = PK.Pk(name, version) 
    peek.Read()
    
    prettyplot() 
    pretty_colors = prettycolors() 

    fig = plt.figure(figsize=(10,10))
    sub = fig.add_subplot(111)

    sub.plot(peek.k, peek.k * peek.p0k, lw=3, c=pretty_colors[3]) 
    sub.set_xlabel('$\mathtt{k} (h/\mathtt{Mpc})$', fontsize=30)
    sub.set_ylabel('$\mathtt{k P_0(k)}$', fontsize=30)

    plt.show() 
Example #35
0
def IntegTest(): 
    ''' Test the convergence of integration methods by trying both euler and 
    RK4 integration for different time steps and then comparing the resulting SMF 

    Conclusions
    -----------
    * The integration is more or less converged after tstep <= 0.5 dt_min especially for 
        RK4. So for calculations use tstep = 0.5 dt_min. 
    '''
    prettyplot() 
    pretty_colors = prettycolors() 
    fig = plt.figure(figsize=(15,6))
    
    for ii, integ in enumerate(['euler', 'rk4']): 
        sub = fig.add_subplot(1,2,ii+1)
        for i_t, tstep in enumerate([0.001, 0.01, 0.1]): 
            evol_dict = {
                    'sfh': {'name': 'random_step', 'dt_min': 0.1, 'dt_max': 0.5, 'sigma': 0.3,
                        'assembly_bias': 'acc_hist', 'halo_prop': 'frac', 'sigma_bias': 0.3}, 
                    'mass': {'type': integ, 'f_retain': 0.6, 't_step': tstep} 
                    } 
            EGP = CMS.EvolvedGalPop(cenque='default', evol_dict=evol_dict)
            if not os.path.isfile(EGP.File()): 
                EGP.Write() 
            EGP.Read()
            MSonly = np.where(EGP.t_quench == 999.)   # remove the quenching galaxies

            smf = Obvs.getSMF(EGP.mass[MSonly], weights=EGP.weight_down[MSonly])
            sub.plot(smf[0], smf[1], lw=3, 
                    c=pretty_colors[i_t], ls='--', 
                    label=''.join([integ, ';', r'$\mathtt{t_{step} =', str(tstep),'}$']))

        # analytic SMF for comparison 
        theory_smf = Obvs.getSMF(EGP.M_sham[MSonly], weights=EGP.weight_down[MSonly])
        sub.plot(theory_smf[0], theory_smf[1], lw=2, c='k', label='Theory')

        sub.set_ylim([10**-5, 10**-1])
        sub.set_xlim([8., 12.0])
        sub.set_yscale('log')
        sub.set_xlabel(r'Mass $\mathtt{M_*}$', fontsize=25) 
        if ii == 0: 
            sub.set_ylabel(r'Stellar Mass Function $\mathtt{\Phi}$', fontsize=25) 
        sub.legend(loc='upper right', frameon=False)
        
    fig_file = ''.join([UT.fig_dir(), 'IntegTest.png']) 
    fig.savefig(fig_file, bbox_inches='tight') 
    plt.close() 
    return None
Example #36
0
def plot_a_spectrum():
    t_start = time.time()
    sps = fsps.StellarPopulation(zcontinuous=1)
    spec = sps.get_spectrum()
    print time.time() - t_start, ' seconds'  # takes 3 mins... wtf

    prettyplot()
    pretty_colors = prettycolors()
    fig = plt.figure()
    sub = fig.add_subplot(111)
    for i in range(spec[1].shape[0]):
        sub.plot(spec[0], 1.e17 * (spec[1][i, :]), c=pretty_colors[i % 10])

    sub.set_xlabel(r'$\lambda$', fontsize=25)
    sub.set_xlim([1000, 10000])
    fig.savefig('aspectrum.png')
    plt.close()
    return None
def PlotABC_tQdelay(tf, cen_abcrun=None): 
    '''
    '''
    abcrun_flag = cen_abcrun + '_central'
    theta_file = lambda pewl: ''.join([code_dir(), 
        'dat/pmc_abc/', 'Satellite.tQdelay.theta_t', str(pewl), '_', abcrun_flag, '.dat']) 
   
    theta = np.loadtxt(theta_file(tf)) 

    m_arr = np.arange(7.5, 12.0, 0.1) 
    tdels = [] 
    for i in xrange(len(theta)): 
        i_tqdelay_dict = {'name': 'explin', 'm': theta[i][0], 'b': theta[i][1]}
        tdels.append(tDelay(m_arr, **i_tqdelay_dict))
    
    tdels = np.array(tdels)
    a, b, c, d, e = np.percentile(tdels, [2.5, 16, 50, 84, 97.5], axis=0)

    prettyplot()
    pretty_colors = prettycolors()
    fig = plt.figure(figsize=(7,7))
    sub = fig.add_subplot(111)

    mstar = np.array([1.56781e+11, 1.01089e+11, 6.27548e+10, 3.98107e+10, 2.49831e+10, 1.57633e+10, 9.89223e+9, 6.37831e+9])
    tqdel_high = np.array([1.36456e+0 , 2.53148e+0 , 3.06686e+0 , 3.52693e+0 , 3.62625e+0 , 3.99574e+0, 3.99915e+0 ,3.99915e+0])
    tqdel_low = np.array([8.15728e-1, 1.98257e+0, 2.29240e+0, 2.82772e+0, 2.99466e+0, 2.72548e+0, 2.99016e+0, 2.68333e+0])
    sub.fill_between(mstar, tqdel_low, tqdel_high, color=pretty_colors[0], edgecolor="none", label='Roughly Wetzel+(2013)')

    #sub.plot(10**m_arr, tDelay(m_arr, **abc_tqdelay_dict), c=pretty_colors[3], label='ABC Best-fit')
    
    sub.fill_between(10**m_arr, a, e, color=pretty_colors[3], alpha=0.5, edgecolor="none", 
            label='ABC Best-fit')
    sub.fill_between(10**m_arr, b, d, color=pretty_colors[3], alpha=1., edgecolor="none")
    sub.plot(10**m_arr, tDelay(m_arr, **{'name': 'hacked'}))

    sub.set_ylim([0.0, 4.0])
    sub.set_ylabel(r'$\mathtt{t_{Q, delay}}$', fontsize=25) 
    sub.set_xlim([5*10**9, 2*10**11.]) 
    sub.set_xscale("log") 
    sub.set_xlabel(r'$\mathtt{M}_*$', fontsize=25) 
    sub.legend(loc='lower left') 
    
    fig.savefig('figure/sallite_tqdelay_'+cen_abcrun+'.png', bbox_inches='tight') 
    return None
def SubhaloLF(scatter=0.0, source='cool_ages', 
        nsnap_ancestor=20 ): 
    ''' Test the Subhalos/CentralSubhalos imported from TreePM by 
    comparing their measured SMFs to the analytic SMFs 

    Parameters
    ----------
    scatter : float
        Float that specifies the scatter in the SMHM relation, which 
        affects the SHAM masses
    source : string
        String that specifies which SMF is used for SHAM
    '''
    prettyplot()
    pretty_colors = prettycolors()

    fig = plt.figure(figsize=(10,10))
    sub = fig.add_subplot(111)
    for i_snap in [11, 7, 4, 1]:
        smf = SMF()
        subh = Subhalos()

        subh.Read(i_snap, scatter=scatter, source=source, nsnap_ancestor=nsnap_ancestor)
        subh.mag_r *= -1.
        mass, phi = smf.Obj(subh, dlogm=0.1, m_arr=np.arange(-24.0, -16., 0.1), LF=True)

        sub.plot(mass, phi, lw=2, ls='-', c=pretty_colors[i_snap % 19])

        analytic_mass, analytic_phi = smf.analytic(get_z_nsnap(i_snap), source=source) 
        sub.plot(analytic_mass, analytic_phi, lw=4, ls='--', c=pretty_colors[i_snap % 19], 
                label=r"$ z = "+str(round(get_z_nsnap(i_snap),2))+"$") 

    sub.set_yscale('log')
    sub.set_ylim([10**-7, 10**-1])
    sub.set_xlim([-24.5, -17.8])
    sub.legend(loc='upper right')
    fig_file = ''.join(['figure/test/'
        'SubhaloLF', 
        '.scatter', str(round(scatter,2)), 
        '.ancestor', str(nsnap_ancestor),
        '.', source, 
        '.png']) 
    fig.savefig(fig_file, bbox_inches='tight')
    plt.close()
def Plot_fQcen_SDSS(): 
    ''' Compare the quiescent fraction of SDSS from the *corrected* SDSS fQ^cen 
    from Tinker et al. (2013) versus the Wetzel et al. (2013) parameterization. 
    '''
    # mass binnning we impose 
    m_low = np.array([9.5, 10., 10.5, 11., 11.5]) 
    m_high = np.array([10., 10.5, 11., 11.5, 12.0])
    m_mid = 0.5 * (m_low + m_high) 

    # SDSS 
    fq_file = ''.join(['dat/observations/cosmos_fq/', 'fcen_red_sdss_scatter.dat']) 
    m_sdss, fqcen_sdss, N_sdss = np.loadtxt(fq_file, unpack=True, usecols=[0,1,2])
    
    fqcen_sdss_rebin = [] 
    for im, m_mid_i in enumerate(m_mid): 
        sdss_mbin = np.where(
                (m_sdss >= m_low[im]) & 
                (m_sdss < m_high[im])) 
    
        fqcen_sdss_rebin.append(
                np.sum(fqcen_sdss[sdss_mbin] * N_sdss[sdss_mbin].astype('float'))/np.sum(N_sdss[sdss_mbin].astype('float'))
                )
    fqcen_sdss_rebin = np.array(fqcen_sdss_rebin)

    prettyplot() 
    pretty_colors = prettycolors()  
    fig = plt.figure() 
    sub = fig.add_subplot(111)
    qf = Fq()
    fqcen_model = qf.model(m_mid, 0.05, lit='cosmos_tinker') 
    sub.plot(m_mid, fqcen_model, 
            c=pretty_colors[3], lw=3, label=r'Wetzel et al. (2013) fit') 
    sub.scatter(m_mid, fqcen_sdss_rebin, 
            color=pretty_colors[0], lw=0, s=40, label=r'Tinker et al. (2013)') 

    sub.set_xlim([9.0, 12.0]) 
    sub.set_xlabel(r'$\mathtt{log\;M_*}$', fontsize=25) 
    sub.set_ylim([0.0, 1.0]) 
    sub.set_ylabel(r'$\mathtt{f_Q^{cen}}$', fontsize=25) 
    sub.legend(loc='upper left', scatterpoints=1, markerscale=3) 
    fig_file = ''.join(['figure/test/', 
        'Fq_central_SDSS.png']) 
    fig.savefig(fig_file, bbox_inches='tight') 
    plt.close() 
Example #40
0
def PlotCovariance(obvs, Mr=21, b_normal=0.25, inference='mcmc'):
    ''' Plot the covariance matrix for a specified obvs 
    '''
    # import the covariance matrix 
    covar = Data.data_cov(Mr=Mr, b_normal=b_normal, inference=inference)

    if obvs == 'xi': 
        obvs_cov = covar[1:16 , 1:16]
        r_bin = Data.xi_binedges()
    elif obvs == 'gmf': 
        obvs_cov = covar[17:, 17:]
        binedges = Data.data_gmf_bins()
        r_bin = 0.5 * (binedges[:-1] + binedges[1:]) 
    
    n_bin = int(np.sqrt(obvs_cov.size))
    
    # calculate the reduced covariance for plotting
    red_covar = np.zeros([n_bin, n_bin])
    for ii in range(n_bin): 
        for jj in range(n_bin): 
            red_covar[ii][jj] = obvs_cov[ii][jj]/np.sqrt(obvs_cov[ii][ii] * obvs_cov[jj][jj])
    
    prettyplot()
    fig = plt.figure()
    sub = fig.add_subplot(111)
    cont = sub.pcolormesh(r_bin, r_bin, red_covar, cmap=plt.cm.afmhot_r)
    plt.colorbar(cont)

    sub.set_xlim([r_bin[0], r_bin[-1]])
    sub.set_ylim([r_bin[0], r_bin[-1]])
    sub.set_xscale('log')
    sub.set_yscale('log')

    sub.set_xlabel(r'$\mathtt{r}\;[\mathtt{Mpc/h}$]', fontsize=25)
    sub.set_ylabel(r'$\mathtt{r}\;[\mathtt{Mpc/h}$]', fontsize=25)
    fig_file = ''.join([util.fig_dir(),
        obvs.upper(), 'covariance',
        '.Mr', str(Mr), 
        '.bnorm', str(round(b_normal,2)), 
        '.', inference, '_inf.png'])
    fig.savefig(fig_file, bbox_inches='tight') 
    plt.close()
    return None 
Example #41
0
def Test_KauffmannParent_Pssfr():
    ''' look at the P(sSFR) of the Kauffmann et al. sample
    '''
    catalog = clog.KauffmannParent()
    is_notnan = np.isnan(catalog['ssfr_fib']) == False
    fib_ssfr = catalog['ssfr_fib'][is_notnan]
    print len(catalog['ssfr_fib']) - np.sum(is_notnan), ' out of ', len(
        catalog['ssfr_fib']), ' galaxies have NaN SSFR'

    ssfr_min, ssfr_max = -13., -8.75
    pdf, bins = np.histogram(fib_ssfr,
                             range=[ssfr_min, ssfr_max],
                             bins=20,
                             normed=True)

    prettyplot()
    pretty_colors = prettycolors()
    fig = plt.figure()
    sub = fig.add_subplot(111)
    sub.plot(0.5 * (bins[:-1] + bins[1:]), pdf, c=pretty_colors[3], lw=3)
    sub.text(-12.8,
             0.5,
             'median sSFR = ' + str(round(np.median(fib_ssfr), 3)),
             fontsize=20)
    sub.vlines(np.median(fib_ssfr),
               0.,
               10.,
               color=pretty_colors[1],
               linewidth=3,
               linestyle='--')
    sub.set_title('Kauffmann et al.(2013) cuts on dr72bright34')
    # axes
    sub.set_xlabel(r'log(SSFR)', fontsize=25)
    sub.set_xlim([ssfr_min, ssfr_max])
    sub.set_xticks([-13, -11, -9])
    sub.set_ylabel(r'P(SSFR)', fontsize=25)
    sub.set_ylim([0.0, 0.6])
    sub.set_yticks([0., 0.2, 0.4, 0.6])
    sub.minorticks_on()
    fig_file = ''.join([UT.dir_fig(), 'KauffmannParent.Pssfr.png'])
    fig.savefig(fig_file)
    plt.close()
    return None
def PlotFq_WetzelTinker_comparison(): 
    ''' Compare the quiescent function evolution for different analytic prescriptions 
    '''
    lit = ['wetzel', 'wetzel_alternate', 'cosmos_tinker']
    prettyplot()
    pretty_colors = prettycolors()
    
    M_arr = np.arange(9.0, 12.2, 0.2)
    z_arr = np.arange(0.0, 1.2, 0.2)
    
    prettyplot() 
    pretty_colors = prettycolors() 
    fig = plt.figure(figsize=(20,5))
    
    qf = gp.Fq()
    for il, l in enumerate(lit): 
        sub = fig.add_subplot(1,4,il+1) 
        
        for iz, z in enumerate(z_arr): 
            if iz == 0: 
                label = (l.replace('_', ' ')).title()
            else: 
                label = None
            fq_M = qf.model(M_arr, z, lit=l)  
            sub.plot(M_arr, fq_M, c=pretty_colors[iz], lw=3, label=label)
    
        sub.set_xlim([9.0, 12.]) 
        sub.set_xlabel(r'$\mathtt{M_{*}}$', fontsize=25)

        sub.set_ylim([0., 1.])
        if il == 0: 
            sub.set_ylabel(r'$\mathtt{f_Q}$', fontsize=25) 
        else: 
            sub.set_yticklabels([]) 

        sub.legend(loc='upper left') 
    fig_file = ''.join(['figure/test/', 
        'Fq_Comparison.', '_'.join(lit), '.png'])
    fig.savefig(fig_file, bbox_inches='tight') 
    plt.close()

    return None
def PlotLee2015_SFMS_zdep():
    ''' Plot the S0 term (redshift dependence term of the SFMS parmaterization) 
    of the Lee et al. (2015) SFMS fits. 
    '''
    z_mid = np.array([0.36, 0.55, 0.70, 0.85, 0.99, 1.19])
    S0 = np.array([0.80, 0.99, 1.23, 1.35, 1.53, 1.72])
    S0_err = np.array([0.019, 0.015, 0.016, 0.014, 0.017, 0.024])

    zslope, const = Lee2015_SFMS_zslope()

    prettyplot()
    pretty_colors = prettycolors()

    fig = plt.figure()
    sub = fig.add_subplot(111)
    sub.errorbar(z_mid,
                 S0,
                 yerr=S0_err,
                 c='k',
                 elinewidth=3,
                 capsize=10,
                 label='Lee et al. (2015)')
    sub.plot(z_mid,
             zslope * (z_mid - 0.05) + const,
             c=pretty_colors[1],
             lw=2,
             ls='--',
             label='Best fit')

    ztext = '\n'.join(
        ['Redshift slope', r'$\mathtt{A_z=' + str(round(zslope, 2)) + '}$'])

    sub.text(0.1, 1.5, ztext, fontsize=20)

    sub.legend(loc='lower right')
    sub.set_ylabel('Lee et al. (2015) $S_0$ term', fontsize=25)
    sub.set_xlim([0.0, 1.5])
    sub.set_xlabel('Redshift $(\mathtt{z})$', fontsize=25)

    fig_file = ''.join(['figure/', 'Lee2015_SFMS_zdep.png'])
    fig.savefig(fig_file, bbox_inches='tight')
    return None
Example #44
0
def PlotFq_WetzelTinker_comparison():
    ''' Compare the quiescent function evolution for different analytic prescriptions 
    '''
    lit = ['wetzel', 'wetzel_alternate', 'cosmos_tinker']
    prettyplot()
    pretty_colors = prettycolors()

    M_arr = np.arange(9.0, 12.2, 0.2)
    z_arr = np.arange(0.0, 1.2, 0.2)

    prettyplot()
    pretty_colors = prettycolors()
    fig = plt.figure(figsize=(20, 5))

    qf = gp.Fq()
    for il, l in enumerate(lit):
        sub = fig.add_subplot(1, 4, il + 1)

        for iz, z in enumerate(z_arr):
            if iz == 0:
                label = (l.replace('_', ' ')).title()
            else:
                label = None
            fq_M = qf.model(M_arr, z, lit=l)
            sub.plot(M_arr, fq_M, c=pretty_colors[iz], lw=3, label=label)

        sub.set_xlim([9.0, 12.])
        sub.set_xlabel(r'$\mathtt{M_{*}}$', fontsize=25)

        sub.set_ylim([0., 1.])
        if il == 0:
            sub.set_ylabel(r'$\mathtt{f_Q}$', fontsize=25)
        else:
            sub.set_yticklabels([])

        sub.legend(loc='upper left')
    fig_file = ''.join(
        ['figure/test/', 'Fq_Comparison.', '_'.join(lit), '.png'])
    fig.savefig(fig_file, bbox_inches='tight')
    plt.close()

    return None
Example #45
0
def plotCMS_SMF(cenque='default', evol_dict=None): 
    ''' Plot the stellar mass function of the integrated SFR population 
    and compare it to the theoretic stellar mass function
    '''
    # calculate SMF 
    cq = CMS.CentralQuenched(cenque=cenque)  # quenched population
    cq._Read_CenQue()
    # import evolved galaxy population 
    MSpop = CMS.EvolvedGalPop(cenque=cenque, evol_dict=evol_dict) 
    MSpop.Read() 

    smf = Obvs.getSMF(
            np.array(list(MSpop.mass)+list(cq.mass)), 
            weights=np.array(list(MSpop.weight_down) + list(cq.weight_down))
            )
    prettyplot() 
    pretty_colors = prettycolors() 

    # analytic SMF 
    theory_smf = Obvs.getSMF(
            np.array(list(MSpop.M_sham)+list(cq.M_sham)),
            weights=np.array(list(MSpop.weight_down) + list(cq.weight_down))
            )
    #Obvs.analyticSMF(0.1, source='li-march')

    fig = plt.figure()
    sub = fig.add_subplot(111)

    sub.plot(theory_smf[0], theory_smf[1], lw=3, c='k', label='Theory')
    sub.plot(smf[0], smf[1], lw=3, c=pretty_colors[3], ls='--', label='Simul.')

    sub.set_ylim([10**-5, 10**-1])
    sub.set_xlim([6., 12.0])
    sub.set_yscale('log')
    sub.set_xlabel(r'Mass $\mathtt{M_*}$', fontsize=25) 
    sub.set_ylabel(r'Stellar Mass Function $\mathtt{\Phi}$', fontsize=25) 
    sub.legend(loc='upper right', frameon=False)
    
    fig_file = ''.join([UT.fig_dir(), 'SMF.CMS', MSpop._Spec_str(), '.png']) 
    fig.savefig(fig_file, bbox_inches='tight') 
    plt.close() 
    return None
Example #46
0
def plot_spectrum_tage():
    t_start = time.time()
    sps = fsps.StellarPopulation(zcontinuous=1)
    print time.time() - t_start, ' seconds'  # takes 3 mins... wtf

    prettyplot()
    pretty_colors = prettycolors()
    fig = plt.figure()
    sub = fig.add_subplot(111)
    for i, tage in enumerate(np.arange(1., 15., 2.)):
        wave, spec = sps.get_spectrum(tage=tage)
        sub.plot(wave,
                 1.e17 * spec,
                 c=pretty_colors[i],
                 label=r'$\mathtt{t_{age} = ' + str(tage) + '}$')

    sub.set_xlabel(r'$\lambda$', fontsize=25)
    sub.set_xlim([1000, 10000])
    sub.set_xlabel(r'$f_\lambda$ (unknown scale)', fontsize=25)
    sub.legend(loc='upper left')
    fig.savefig('spectrum_tage.png', bbox_inches='tight')
    plt.close()
    return None
Example #47
0
def ABCvsMCMC_histogram(obvs, nwalkers=100, nburns=9000):
    ''' Plots that compare the ABC posteriors to the MCMC posteriors 
    '''
    if obvs == 'nbargmf':
        abc_dir = ''.join([
            ut.dat_dir(),
            'paper/ABC',
            obvs,
            '/run1/',
        ])
        abc_theta_file = lambda tt: ''.join(
            [abc_dir, 'nbar_gmf_theta_t',
             str(tt), '.ABCnbargmf.dat'])
        tf = 8
        mcmc_dir = ''.join([ut.dat_dir(), 'paper/'])
        mcmc_filename = ''.join([mcmc_dir, 'nbar_gmf.mcmc.mcmc_chain.p'])
    elif obvs == 'nbarxi':
        abc_dir = ''.join([
            ut.dat_dir(),
            'paper/ABC',
            obvs,
            '/',
        ])
        abc_theta_file = lambda tt: ''.join(
            [abc_dir, 'nbar_xi_theta_t',
             str(tt), '.abc.dat'])
        tf = 9
        mcmc_dir = ''.join([ut.dat_dir(), 'paper/'])
        mcmc_filename = ''.join([mcmc_dir, 'nbar_xi.mcmc.mcmc_chain.p'])
    else:
        raise ValueError

    prior_min, prior_max = PriorRange('first_try')
    prior_range = np.zeros((len(prior_min), 2))
    prior_range[:, 0] = prior_min
    prior_range[:, 1] = prior_max

    # true HOD parameter
    true_dict = Data.data_hod_param(Mr=21)
    truths = [
        true_dict['logM0'],  # log M0
        np.log(true_dict['sigma_logM']),  # log(sigma)
        true_dict['logMmin'],  # log Mmin
        true_dict['alpha'],  # alpha
        true_dict['logM1']  # log M1
    ]

    mcmc_sample = pickle.load(open(mcmc_filename, 'rb'))[nburns * nwalkers:, :]
    abc_sample = np.loadtxt(abc_theta_file(tf))

    normie = norm()
    sig1lo = normie.cdf(-1)
    sig1hi = normie.cdf(1)
    sig2lo = normie.cdf(-2)
    sig2hi = normie.cdf(2)

    nsamples_mcmc = len(mcmc_sample[:, 2])
    nsamples_abc = len(abc_sample[:, 2])

    sig1lo_mcmc = int(sig1lo * nsamples_mcmc)
    sig2lo_mcmc = int(sig2lo * nsamples_mcmc)
    sig1hi_mcmc = int(sig1hi * nsamples_mcmc)
    sig2hi_mcmc = int(sig2hi * nsamples_mcmc)

    sig1lo_abc = int(sig1lo * nsamples_abc)
    sig2lo_abc = int(sig2lo * nsamples_abc)
    sig1hi_abc = int(sig1hi * nsamples_abc)
    sig2hi_abc = int(sig2hi * nsamples_abc)

    par_labels = [
        r'$\mathtt{log}\;\mathcal{M}_{0}$',
        r'$\mathtt{log}\;\sigma_\mathtt{log\;M}$',
        r'$\mathtt{log}\;\mathcal{M}_\mathtt{min}$', r'$\alpha$',
        r'$\mathtt{log}\;\mathcal{M}_{1}$'
    ]

    prettyplot()
    pretty_colors = prettycolors()
    fig = plt.figure(1, figsize=(20, 8))
    gs = gridspec.GridSpec(2, 3, height_ratios=[2.75, 1])

    # first panel
    for i in [0, 1, 2]:
        if i == 0:
            i_col = 2
            prior_range[i_col, 0] = 12.5
            prior_range[i_col, 1] = 13.
            plot_range = prior_range[i_col, :]
        elif i == 1:
            i_col = 3
            plot_range = prior_range[i_col, :]
        elif i == 2:
            i_col = 4
            prior_range[i_col, 0] = 13.5
            prior_range[i_col, 1] = 14.25
            plot_range = np.array([13.5, 14.5])

        ax = plt.subplot(gs[i])
        q = ax.hist(mcmc_sample[:, i_col],
                    bins=20,
                    range=[prior_range[i_col, 0], prior_range[i_col, 1]],
                    normed=True,
                    alpha=0.75,
                    color=pretty_colors[1],
                    linewidth=2,
                    histtype='stepfilled',
                    edgecolor=None)
        qq = ax.hist(abc_sample[:, i_col],
                     bins=20,
                     range=[prior_range[i_col, 0], prior_range[i_col, 1]],
                     normed=True,
                     alpha=0.75,
                     color=pretty_colors[3],
                     linewidth=2,
                     histtype='stepfilled',
                     edgecolor=None)
        ax.axvline(truths[i_col], color='k', ls='--', linewidth=3)
        ax.set_xticklabels([])
        ax.set_xlim([plot_range[0], plot_range[1]])

        if i == 2:
            thick_line2 = mlines.Line2D(
                [], [],
                ls='-',
                c=pretty_colors[1],
                linewidth=4,
                label='$\mathcal{L}^\mathtt{Gauss}$ \nMCMC')
            thick_line1 = mlines.Line2D([], [],
                                        ls='-',
                                        c=pretty_colors[3],
                                        linewidth=4,
                                        label='ABC-PMC')

            ax.legend(loc='upper right',
                      handles=[thick_line2, thick_line1],
                      frameon=False,
                      fontsize=25,
                      handletextpad=-0.0)

        # general box properties
        boxprops = {'color': 'k'}
        medianprops = {'alpha': 0.}
        bplots1 = []
        ax = plt.subplot(gs[i + 3])
        # stats dict for each box
        bplots1.append({
            'med': np.median(mcmc_sample[:, i_col]),
            'q1': np.sort(mcmc_sample[:, i_col])[sig1lo_mcmc],
            'q3': np.sort(mcmc_sample[:, i_col])[sig1hi_mcmc],
            'whislo': np.sort(mcmc_sample[:, i_col])[sig2lo_mcmc],
            'whishi': np.sort(mcmc_sample[:, i_col])[sig2hi_mcmc],
            'fliers': []
        })
        bplots1.append({
            'med': np.median(abc_sample[:, i_col]),
            'q1': np.sort(abc_sample[:, i_col])[sig1lo_abc],
            'q3': np.sort(abc_sample[:, i_col])[sig1hi_abc],
            'whislo': np.sort(abc_sample[:, i_col])[sig2lo_abc],
            'whishi': np.sort(abc_sample[:, i_col])[sig2hi_abc],
            'fliers': []
        })
        whiskprop = dict(linestyle='-', linewidth=2, color='k')
        boxprops = dict(linestyle='-', linewidth=2, color='k')
        bxp1 = ax.bxp(bplots1,
                      positions=[1, 2],
                      vert=False,
                      patch_artist=True,
                      showfliers=False,
                      boxprops=boxprops,
                      medianprops=medianprops,
                      whiskerprops=whiskprop)

        for ibox, box in enumerate(bxp1['boxes']):
            if ibox == 0:
                box.set(facecolor=pretty_colors[1], alpha=0.75)
            elif ibox == 1:
                box.set(facecolor=pretty_colors[3], alpha=0.75)
        ax.axvline(truths[i_col], color='k', ls='--', linewidth=3)

        ax.set_xlim([plot_range[0], plot_range[1]])
        ax.set_xlabel(par_labels[i_col], fontsize=25, labelpad=15)

        if i == 0:
            ax.set_yticks([1, 2])
            ax.set_yticklabels([r"$\mathtt{MCMC}$", r"$\mathtt{ABC}$"])
        else:
            ax.set_yticks([])

    fig.subplots_adjust(wspace=0.2, hspace=0.0)
    fig_name = ''.join([ut.fig_dir(), 'paper.ABCvsMCMC', '.', obvs, '.pdf'])
    print fig_name
    fig.savefig(fig_name, bbox_inches='tight', dpi=150)
    return None
Example #48
0
def Plot_rhoSFR(source='li-march',
                sfms_prop=None,
                fq_lit='wetzel',
                zslope=None):
    ''' Calculate the SFR density by integrating 
    
    rho_SFR = int n(M*) SFR_MS(M*) (1 - fQ(M*)) dM*  

    where n(M*) is given by the stellar mass function, SFR_MS is the SFMS SFR 
    fQ is the quiescent fraction 
    '''
    if sfms_prop is None:
        if zslope is None:
            sfms_prop = {'name': 'linear', 'zslope': 1.5}
        else:
            sfms_prop = {'name': 'linear', 'zslope': zslope}

    # SMF
    smf_obj = gp.SMF()
    n_smf = smf_obj.analytic
    # SFMS Star Formation Rate
    sfr_ms = sfr_evol.AverageLogSFR_sfms
    # Quiescent Fraction
    qf_obj = gp.Fq()
    fq_model = qf_obj.model

    def rhoSFR_integrand(Mstar, z):
        M_smf, phi_smf = n_smf(z, source=source)
        n_smf_M = interpolate.interp1d(M_smf, phi_smf)

        return n_smf_M(Mstar) * 10.**sfr_ms(Mstar, z, sfms_prop=sfms_prop) * (
            1. - fq_model(Mstar, z, lit=fq_lit))

    z_range = np.array([0.1, 0.5, 1.0])  #np.arange(0.1, 1.0, 0.2)
    rhoSFR_z = []
    for zz in z_range:
        print zz
        rhoSFR_int_wrap = lambda mm: rhoSFR_integrand(mm, zz)
        rhoSFR_int, rhoSFR_int_err = quad(rhoSFR_int_wrap,
                                          7.5,
                                          12.0,
                                          epsrel=0.1)

        rhoSFR_z.append(rhoSFR_int)

    z_behroozi = [
        0.036209892874743854, 0.40889165564288144, 0.6761600913028816,
        0.9616372266749669, 1.170544445309055, 1.4822192825461054,
        1.6049075298939122
    ]
    sfr_cosmic = [
        0.010063810047184728, 0.02228775362744163, 0.03802861399461939,
        0.06050175265988725, 0.0805521892279678, 0.10063810047184728,
        0.10862045113189879
    ]

    prettyplot()
    pretty_colors = prettycolors()

    fig = plt.figure()
    sub = fig.add_subplot(111)
    sub.scatter(z_range, rhoSFR_z, s=10)
    sub.plot(z_range, rhoSFR_z, c='k', lw=2)
    sub.plot(z_behroozi, sfr_cosmic, lw=3, c='r', label='Behroozi Best-fit')

    sub.set_xlabel(r'Redshift $\mathtt{(z)}$', fontsize=25)
    sub.set_xlim([0.0, z_range.max()])

    sub.set_ylim([0.001, 0.1])
    sub.set_ylabel(r'$\rho_\mathtt{SFR}$', fontsize=25)
    sub.set_yscale('log')
    sub.legend(loc='upper left')
    plt.show()

    fig_name = ''.join([
        'figure/test/', 'rhoSFR', '.SMF_', source, '.fq_', fq_lit,
        '.SFMS_zslope',
        str(round(sfms_prop['zslope'], 1)), '.png'
    ])
    fig.savefig(fig_name, bbox_inches='tight')
    plt.close()

    return None
Example #49
0
def PoolEvolution(obvs):
    ''' Demostrative plot for the evolution of the pool. Illustrate the pool evolution for
    log M_min versus log M_1, which has the starkest evolution from its prior. 

    '''
    if obvs == 'nbargmf':
        result_dir = ''.join([
            ut.dat_dir(),
            'paper/ABC',
            obvs,
            '/run1/',
        ])
        theta_file = lambda tt: ''.join(
            [result_dir, 'nbar_gmf_theta_t',
             str(tt), '.ABCnbargmf.dat'])
        t_list = [0, 1, 2, 3, 5, 8]
    elif obvs == 'nbarxi':
        result_dir = ''.join([ut.dat_dir(), 'paper/ABC', obvs, '/'])
        theta_file = lambda tt: ''.join(
            [result_dir, 'nbar_xi_theta_t',
             str(tt), '.abc.dat'])
        t_list = [0, 1, 2, 3, 7, 9]
    else:
        raise ValueError

    prior_min, prior_max = PriorRange('first_try')
    prior_range = np.zeros((2, 2))
    prior_range[:, 0] = np.array([prior_min[2], prior_min[4]])
    prior_range[:, 1] = np.array([prior_max[2], prior_max[4]])

    # true HOD parameter
    true_dict = Data.data_hod_param(Mr=21)
    true_pair = [true_dict['logMmin'], true_dict['logM1']]

    prettyplot()
    pretty_colors = prettycolors()
    fig = plt.figure(figsize=(12, 8))
    all_fig = fig.add_subplot(111)

    for i_t, t in enumerate(t_list):
        sub = fig.add_subplot(2, len(t_list) / 2, i_t + 1)

        theta_Mmin, theta_M1 = np.loadtxt(theta_file(t),
                                          unpack=True,
                                          usecols=[2, 4])
        corner.hist2d(theta_Mmin,
                      theta_M1,
                      bins=20,
                      range=prior_range,
                      levels=[0.68, 0.95],
                      color='c',
                      fill_contours=True,
                      smooth=1.0)

        t_label = r"$\mathtt{t = " + str(t) + "}$"
        sub.text(13.0, 15.0, t_label, fontsize=25)

        if i_t == len(t_list) - 1:
            true_label = r'$``\mathtt{true}"$'
        else:
            true_label = None

        plt.scatter(np.repeat(true_pair[0], 2),
                    np.repeat(true_pair[1], 2),
                    s=75,
                    marker='*',
                    c='k',
                    lw=0,
                    label=true_label)
        if i_t == len(t_list) - 1:
            plt.legend(loc='lower left',
                       scatterpoints=1,
                       markerscale=2.5,
                       handletextpad=-0.25,
                       scatteryoffsets=[0.5])

        if i_t == 0:
            sub.set_xticklabels([])
            sub.set_yticklabels([13., 13.5, 14., 14.5, 15., 15.5])
        elif (i_t > 0) and (i_t < len(t_list) / 2):
            sub.set_xticklabels([])
            sub.set_yticklabels([])
        elif i_t == len(t_list) / 2:
            sub.set_yticklabels([13., 13.5, 14., 14.5, 15.])
        elif i_t > len(t_list) / 2:
            sub.set_yticklabels([])

    all_fig.set_xticklabels([])
    all_fig.set_yticklabels([])
    all_fig.set_ylabel(r'$\mathtt{log}\;\mathcal{M}_\mathtt{1}$',
                       fontsize=30,
                       labelpad=50)
    all_fig.set_xlabel(r'$\mathtt{log}\;\mathcal{M}_\mathtt{min}$',
                       fontsize=30,
                       labelpad=25)

    fig.subplots_adjust(hspace=0.0)
    fig_name = ''.join(
        [ut.fig_dir(), 'paper_ABC_poolevolution', '.', obvs, '.pdf'])
    fig.savefig(fig_name, bbox_inches='tight', dpi=150)
    plt.close()
Example #50
0
def ABCvsMCMC_contour(obvs, nwalkers=100, nburns=9000, sigma=False):
    ''' Plots that compare the ABC posteriors to the MCMC posteriors 
    '''
    if obvs == 'nbargmf':
        abc_dir = ''.join([
            ut.dat_dir(),
            'paper/ABC',
            obvs,
            '/run1/',
        ])
        abc_theta_file = lambda tt: ''.join(
            [abc_dir, 'nbar_gmf_theta_t',
             str(tt), '.ABCnbargmf.dat'])
        tf = 8
        mcmc_dir = ''.join([ut.dat_dir(), 'paper/'])
        mcmc_filename = ''.join([mcmc_dir, 'nbar_gmf.mcmc.mcmc_chain.p'])
    elif obvs == 'nbarxi':
        abc_dir = ''.join([
            ut.dat_dir(),
            'paper/ABC',
            obvs,
            '/',
        ])
        abc_theta_file = lambda tt: ''.join(
            [abc_dir, 'nbar_xi_theta_t',
             str(tt), '.abc.dat'])
        tf = 9
        mcmc_dir = ''.join([ut.dat_dir(), 'paper/'])
        mcmc_filename = ''.join([mcmc_dir, 'nbar_xi.mcmc.mcmc_chain.p'])
    else:
        raise ValueError

    prior_min, prior_max = PriorRange('first_try')
    prior_range = np.zeros((len(prior_min), 2))
    prior_range[:, 0] = prior_min
    prior_range[:, 1] = prior_max

    # true HOD parameter
    true_dict = Data.data_hod_param(Mr=21)
    truths = [
        true_dict['logM0'],  # log M0
        np.log(true_dict['sigma_logM']),  # log(sigma)
        true_dict['logMmin'],  # log Mmin
        true_dict['alpha'],  # alpha
        true_dict['logM1']  # log M1
    ]

    mcmc_sample = pickle.load(open(mcmc_filename, 'rb'))[nburns * nwalkers:, :]
    abc_sample = np.loadtxt(abc_theta_file(tf))

    par_labels = [
        r'$\mathtt{log}\;\mathcal{M}_{0}$',
        r'$\mathtt{log}\;\sigma_\mathtt{log\;M}$',
        r'$\mathtt{log}\;\mathcal{M}_\mathtt{min}$', r'$\alpha$',
        r'$\mathtt{log}\;\mathcal{M}_{1}$'
    ]

    prettyplot()
    pretty_colors = prettycolors()
    fig = plt.figure(1, figsize=(20, 6))
    gs = gridspec.GridSpec(1, 3)

    # first panel
    for i in [0, 1, 2]:
        plot_range = np.zeros((2, 2))
        if i == 0:
            col_pair = [2, 3]
            plot_range[0, 0] = 12.5
            plot_range[0, 1] = 13.0
            plot_range[1, 0] = prior_range[3, 0]
            plot_range[1, 1] = prior_range[3, 1]
        elif i == 2:
            col_pair = [4, 2]
            plot_range[0, 0] = 13.6
            plot_range[0, 1] = 14.2
            plot_range[1, 0] = 12.5
            plot_range[1, 1] = 13.0
        elif i == 1:
            col_pair = [3, 4]
            plot_range[0, 0] = prior_range[3, 0]
            plot_range[0, 1] = prior_range[3, 1]
            plot_range[1, 0] = 13.6
            plot_range[1, 1] = 14.2

        if i == 2:
            mcmc_label = r'$\mathcal{L}^\mathtt{Gauss}$ MCMC'
            abc_label = 'ABC-PMC'
        else:
            mcmc_label = None
            abc_label = None

        mcmc_par1 = mcmc_sample[:, col_pair[0]]
        mcmc_par2 = mcmc_sample[:, col_pair[1]]

        abc_par1 = abc_sample[:, col_pair[0]]
        abc_par2 = abc_sample[:, col_pair[1]]

        ax = plt.subplot(gs[i])

        if sigma:
            lvls = [1 - np.exp(-0.5), 1 - np.exp(-0.125)]
        else:
            lvls = [0.68, 0.95]

        corner.hist2d(mcmc_par1,
                      mcmc_par2,
                      bins=20,
                      range=plot_range,
                      ax=ax,
                      plot_datapoints=False,
                      levels=lvls,
                      color='#1F77B4',
                      fill_contours=True,
                      smooth=1.0,
                      label=mcmc_label)

        corner.hist2d(abc_par1,
                      abc_par2,
                      bins=20,
                      range=plot_range,
                      ax=ax,
                      levels=lvls,
                      color='#FF7F0E',
                      fill_contours=True,
                      smooth=1.0,
                      label=abc_label)

        ax.scatter(np.repeat(truths[col_pair[0]], 2),
                   np.repeat(truths[col_pair[1]], 2),
                   s=100,
                   marker='*',
                   c='k',
                   lw=0,
                   label=None)
        #ax.axvline(truths[i_col], color='k', ls='--', linewidth=3)
        #ax.set_xticklabels([])
        ax.set_xlim([plot_range[0, 0], plot_range[0, 1]])
        ax.set_ylim([plot_range[1, 0], plot_range[1, 1]])

        if i == 2:
            thick_line1 = mlines.Line2D([], [],
                                        ls='-',
                                        c='#FF7F0E',
                                        linewidth=12,
                                        alpha=0.5,
                                        label='ABC-PMC')
            ax.legend(loc='upper right',
                      handles=[thick_line1],
                      frameon=False,
                      fontsize=25,
                      handletextpad=0.1,
                      scatteryoffsets=[0.5])
        elif i == 1:
            thick_line2 = mlines.Line2D(
                [], [],
                ls='-',
                c='#1F77B4',
                linewidth=12,
                alpha=0.5,
                label='$\mathcal{L}^\mathtt{Gauss}$ \nMCMC')
            ax.legend(loc='upper right',
                      handles=[thick_line2],
                      frameon=False,
                      fontsize=25,
                      handletextpad=0.1,
                      scatteryoffsets=[0.5])

        ax.set_xlabel(par_labels[col_pair[0]], fontsize=25, labelpad=15)
        ax.set_ylabel(par_labels[col_pair[1]], fontsize=25)

    if sigma:
        sigma_str = '.true1sigma'
    else:
        sigma_str = ''

    fig.subplots_adjust(wspace=0.3)
    fig_name = ''.join([
        ut.fig_dir(), 'paper.ABCvsMCMC.contour', '.', obvs, sigma_str, '.pdf'
    ])
    fig.savefig(fig_name, bbox_inches='tight', dpi=150)
    return None
Example #51
0
def ABC_Convergence(weighted=False):
    ''' Plot the error bars on the parameters as a function of time step
    '''
    prettyplot()
    pretty_colors = prettycolors()
    fig = plt.figure(figsize=(20, 10))

    for i_obv, obvs in enumerate(['nbargmf', 'nbarxi']):
        if obvs == 'nbargmf':
            result_dir = ''.join([
                ut.dat_dir(),
                'paper/ABC',
                obvs,
                '/run1/',
            ])
            theta_file = lambda tt: ''.join(
                [result_dir, 'nbar_gmf_theta_t',
                 str(tt), '.ABCnbargmf.dat'])
            w_file = lambda tt: ''.join(
                [result_dir, 'nbar_gmf_w_t',
                 str(tt), '.ABCnbargmf.dat'])
            tf = 8
        elif obvs == 'nbarxi':
            result_dir = ''.join([ut.dat_dir(), 'paper/ABC', obvs, '/'])
            theta_file = lambda tt: ''.join(
                [result_dir, 'nbar_xi_theta_t',
                 str(tt), '.abc.dat'])
            w_file = lambda tt: ''.join(
                [result_dir, 'nbar_xi_w_t',
                 str(tt), '.abc.dat'])
            tf = 9
        else:
            raise ValueError

        t_list = range(tf + 1)

        columns = [
            r"$\mathtt{log}\;\mathcal{M}_0$",
            r"$\sigma_{\mathtt{log}\;\mathcal{M}}$",
            r"$\mathtt{log}\;\mathcal{M}_\mathtt{min}$", r"$\alpha$",
            r"$\mathtt{log}\;\mathcal{M}_1$"
        ]

        true_dict = Data.data_hod_param(Mr=21)
        true_theta = [
            true_dict['logM0'],
            np.log(true_dict['sigma_logM']), true_dict['logMmin'],
            true_dict['alpha'], true_dict['logM1']
        ]

        prior_min, prior_max = PriorRange('first_try')

        a_theta = np.zeros((len(t_list), 5))
        b_theta = np.zeros((len(t_list), 5))
        d_theta = np.zeros((len(t_list), 5))
        e_theta = np.zeros((len(t_list), 5))
        for i_t, tt in enumerate(t_list):
            theta_i = np.loadtxt(theta_file(tt), unpack=True)
            w_i = np.loadtxt(w_file(tt))
            for i_par in range(len(theta_i)):
                if not weighted:
                    a, b, d, e = np.percentile(theta_i[i_par],
                                               [2.5, 16, 84, 97.5],
                                               axis=0)
                else:
                    a = ut.quantile_1D(theta_i[i_par], w_i, 0.025)
                    b = ut.quantile_1D(theta_i[i_par], w_i, 0.16)
                    d = ut.quantile_1D(theta_i[i_par], w_i, 0.84)
                    e = ut.quantile_1D(theta_i[i_par], w_i, 0.975)

                a_theta[i_t, i_par] = a
                b_theta[i_t, i_par] = b
                d_theta[i_t, i_par] = d
                e_theta[i_t, i_par] = e

        keep_index = [2, 3, 4]
        for ii, i in enumerate(keep_index):
            if i == keep_index[-1]:
                true_label = r'$``\mathtt{true}"$'
                abc_1sig_label = r'ABC Pool'
            else:
                true_label = None
                abc_1sig_label = None

            sub = fig.add_subplot(2, len(keep_index),
                                  i_obv * len(keep_index) + ii + 1)
            sub.fill_between(t_list,
                             a_theta[:, i],
                             e_theta[:, i],
                             color=pretty_colors[3],
                             alpha=0.3,
                             edgecolor="none")
            sub.fill_between(t_list,
                             b_theta[:, i],
                             d_theta[:, i],
                             color=pretty_colors[3],
                             alpha=0.5,
                             edgecolor="none",
                             label=abc_1sig_label)
            sub.plot(t_list,
                     np.repeat(true_theta[i], len(t_list)),
                     c='k',
                     ls='--',
                     lw=2,
                     label=true_label)

            if ii == 0:
                if obvs == 'nbargmf':
                    sub.text(4.85,
                             13.4,
                             r"$\bar{\mathtt{n}}$ and $\zeta(\mathtt{N})$",
                             fontsize=25)
                elif obvs == 'nbarxi':
                    sub.text(4.85,
                             13.4,
                             r"$\bar{\mathtt{n}}$ and $\xi(\mathtt{r})$",
                             fontsize=25)

            sub.set_ylabel(columns[i], fontsize=25)
            sub.set_ylim([prior_min[i], prior_max[i]])

            sub.set_xlim([-1, 10])
            if i_obv == 1:
                sub.legend(loc='upper right', borderpad=1.)
                sub.set_xlabel('iterations', fontsize=25)
                if i == 4:
                    sub.set_yticklabels([13.0, 13.5, 14.0, 14.5, 15.])
            else:
                sub.set_xticklabels([])

    fig.subplots_adjust(wspace=0.3, hspace=0.0)
    if weighted:
        weight_str = '.weighted'
    else:
        weight_str = ''

    fig_name = ''.join(
        [ut.fig_dir(), 'paper', '.ABCconvergence', weight_str, '.pdf'])
    fig.savefig(fig_name, bbox_inches='tight', dpi=150)
    plt.close()
    return None
def OrphanSubhaloSMF(type,
                     nsnap_ancestor=20,
                     scatter=0.0,
                     source='li-drory-march'):
    ''' SMF for orphan central subhalos that do not have ancestors at snapshot 
    nsnap_ancestor.
    '''
    prettyplot()
    pretty_colors = prettycolors()

    fig = plt.figure(figsize=(10, 10))
    sub = fig.add_subplot(111)

    # Central subhalo at nsnap_ancestor
    if type == 'central':
        subh = CentralSubhalos()
    elif type == 'all':
        subh = Subhalos()
    subh.Read(nsnap_ancestor,
              scatter=scatter,
              source=source,
              nsnap_ancestor=nsnap_ancestor)
    ancestor_index = subh.index
    ancestor_mass = subh.mass

    for i_snap in [1, 5, 10, 15]:
        if i_snap >= nsnap_ancestor:
            continue

        smf = SMF()
        if type == 'central':
            subh = CentralSubhalos()
        elif type == 'all':
            subh = Subhalos()
        subh.Read(i_snap,
                  scatter=scatter,
                  source=source,
                  nsnap_ancestor=nsnap_ancestor)

        # total central subhalo SMF
        subh_mass, subh_phi = smf.centralsubhalos(subh)
        sub.plot(subh_mass, subh_phi, lw=4, c=pretty_colors[i_snap], alpha=0.5)

        # SMF of central subhalos who's ancestors are centrals at snapshot 20
        if i_snap == 1:
            label = 'Galaxies that do not have Ancestors'
        else:
            label = None
        orphan = np.invert(
            np.in1d(getattr(subh, 'ancestor' + str(nsnap_ancestor)),
                    ancestor_index))
        orph_mass, orph_phi = smf.smf(subh.mass[orphan])
        sub.plot(orph_mass,
                 orph_phi,
                 lw=2,
                 ls='--',
                 c=pretty_colors[i_snap],
                 label=label)

    anc_mass, anc_phi = smf.smf(ancestor_mass)
    sub.plot(anc_mass, anc_phi, lw=4, c='gray', label='Total')

    sub.set_yscale('log')
    sub.set_ylim([10**-5, 10**-1])
    sub.set_xlim([6.0, 12.0])
    sub.legend(loc='upper right')

    fig_file = ''.join([
        'figure/test/'
        'OrphanSubhaloSMF', '.', type, '_subhalo', '.scatter',
        str(round(scatter, 2)), '.ancestor',
        str(nsnap_ancestor), '.', source, '.png'
    ])
    fig.savefig(fig_file, bbox_inches='tight')
    plt.close()
    return None
Example #53
0
def PosteriorObservable(Mr=21, b_normal=0.25, clobber=False):
    ''' Plot 1\sigma and 2\sigma model predictions from ABC-PMC posterior likelihood
    '''
    prettyplot()
    pretty_colors = prettycolors()
    fig = plt.figure(1, figsize=(16, 12))
    gs = gridspec.GridSpec(2, 2, height_ratios=[2.5, 1], width_ratios=[1, 1])

    for obvs in ['nbargmf', 'nbarxi']:

        if obvs == 'nbargmf':
            result_dir = ''.join([
                ut.dat_dir(),
                'paper/ABC',
                obvs,
                '/run1/',
            ])
            theta_file = lambda tt: ''.join(
                [result_dir, 'nbar_gmf_theta_t',
                 str(tt), '.ABCnbargmf.dat'])
            tf = 8
            obvs_list = ['gmf']
        elif obvs == 'nbarxi':
            result_dir = ''.join([ut.dat_dir(), 'paper/ABC', obvs, '/'])
            theta_file = lambda tt: ''.join(
                [result_dir, 'nbar_xi_theta_t',
                 str(tt), '.abc.dat'])
            tf = 9
            obvs_list = ['xi']
        else:
            raise ValueError

        theta = np.loadtxt(theta_file(tf))  # import thetas
        #theta = theta[:10]

        obvs_file = ''.join(
            theta_file(tf).rsplit('.dat')[:-1] + ['.', obvs_list[0], '.p'])
        print obvs_file

        HODsimulator = ABC_HODsim(Mr=Mr, b_normal=b_normal)
        if not os.path.isfile(obvs_file) or clobber:
            model_obv = []
            for i in xrange(len(theta)):
                print i
                obv_i = HODsimulator(theta[i],
                                     prior_range=None,
                                     observables=obvs_list)
                model_obv.append(obv_i[0])
            model_obv = np.array(model_obv)
            pickle.dump(model_obv, open(obvs_file, 'wb'))
        else:
            model_obv = pickle.load(open(obvs_file, 'rb'))

        if 'xi' in obvs:
            r_bin = Data.data_xi_bin(Mr=Mr)
        elif 'gmf' in obvs:
            r_binedge = Data.data_gmf_bins()
            r_bin = 0.5 * (r_binedge[:-1] + r_binedge[1:])

        a, b, c, d, e = np.percentile(model_obv, [2.5, 16, 50, 84, 97.5],
                                      axis=0)

        # plotting
        if obvs == 'nbarxi':
            ax = plt.subplot(gs[0])
        elif obvs == 'nbargmf':
            ax = plt.subplot(gs[1])

        if 'xi' in obvs:  # 2PCF
            xi_data = Data.data_xi(Mr=Mr, b_normal=b_normal)
            cov_data = Data.data_cov(Mr=Mr,
                                     b_normal=b_normal,
                                     inference='mcmc')
            data_xi_cov = cov_data[1:16, 1:16]

            ax.fill_between(r_bin,
                            a,
                            e,
                            color=pretty_colors[3],
                            alpha=0.3,
                            edgecolor="none")
            ax.fill_between(r_bin,
                            b,
                            d,
                            color=pretty_colors[3],
                            alpha=0.5,
                            edgecolor="none")
            ax.errorbar(r_bin,
                        xi_data,
                        yerr=np.sqrt(np.diag(data_xi_cov)),
                        fmt="o",
                        color='k',
                        markersize=0,
                        lw=0,
                        capsize=3,
                        elinewidth=1.5)
            ax.scatter(r_bin, xi_data, c='k', s=10, lw=0)
            ax.set_ylabel(r'$\xi_\mathtt{gg}(\mathtt{r})$', fontsize=27)
            ax.set_yscale('log')
            ax.set_xscale('log')
            ax.set_xticklabels([])
            ax.set_xlim([0.1, 20.])
            ax.set_ylim([0.09, 1000.])

            ax = plt.subplot(gs[2])
            ax.fill_between(r_bin,
                            a / xi_data,
                            e / xi_data,
                            color=pretty_colors[3],
                            alpha=0.3,
                            edgecolor="none")
            ax.fill_between(r_bin,
                            b / xi_data,
                            d / xi_data,
                            color=pretty_colors[3],
                            alpha=0.5,
                            edgecolor="none")
            ax.errorbar(r_bin,
                        np.repeat(1., len(xi_data)),
                        yerr=np.sqrt(np.diag(data_xi_cov)) / xi_data,
                        fmt="o",
                        color='k',
                        markersize=0,
                        lw=0,
                        capsize=3,
                        elinewidth=1.5)
            ax.plot(np.arange(0.1, 20., 0.1),
                    np.repeat(1., len(np.arange(0.1, 20, 0.1))),
                    c='k',
                    ls='--',
                    lw=2)
            ax.set_xlim([0.1, 20.])
            ax.set_xscale('log')
            ax.set_ylim([0.5, 1.5])
            ax.set_xlabel(r'$\mathtt{r}\;[\mathtt{Mpc}/h]$', fontsize=25)
            ax.set_ylabel(r'$\xi_\mathtt{gg}/\xi_\mathtt{gg}^\mathtt{obvs}$',
                          fontsize=25)

        elif 'gmf' in obvs:  # GMF
            data_gmf = Data.data_gmf(Mr=Mr, b_normal=b_normal)
            cov_data = Data.data_cov(Mr=Mr,
                                     b_normal=b_normal,
                                     inference='mcmc')
            data_gmf_cov = cov_data[16:, 16:]

            ax.fill_between(r_bin,
                            a,
                            e,
                            color=pretty_colors[3],
                            alpha=0.3,
                            edgecolor="none")
            ax.fill_between(r_bin,
                            b,
                            d,
                            color=pretty_colors[3],
                            alpha=0.5,
                            edgecolor="none",
                            label='ABC Posterior')
            ax.errorbar(r_bin,
                        data_gmf,
                        yerr=np.sqrt(np.diag(data_gmf_cov)),
                        fmt="o",
                        color='k',
                        markersize=0,
                        lw=0,
                        capsize=4,
                        elinewidth=2)
            ax.scatter(r_bin,
                       data_gmf,
                       s=15,
                       lw=0,
                       c='k',
                       label='Mock Observation')
            ax.legend(loc='upper right',
                      scatterpoints=1,
                      prop={'size': 25},
                      borderpad=1.0)

            ax.yaxis.tick_right()
            ax.yaxis.set_ticks_position('both')
            ax.yaxis.set_label_position('right')
            ax.set_ylabel(r'$\zeta$ $[(\mathrm{h}/\mathtt{Mpc})^{3}]$',
                          fontsize=25)

            ax.set_yscale('log')
            ax.set_xlim([1., 20.])
            ax.set_xticklabels([])
            ax.set_ylim([10.**-7.2, 2 * 10**-4.])

            ax = plt.subplot(gs[3])
            ax.fill_between(r_bin,
                            a / data_gmf,
                            e / data_gmf,
                            color=pretty_colors[3],
                            alpha=0.3,
                            edgecolor="none")
            ax.fill_between(r_bin,
                            b / data_gmf,
                            d / data_gmf,
                            color=pretty_colors[3],
                            alpha=0.5,
                            edgecolor="none")

            ax.errorbar(r_bin,
                        np.repeat(1., len(data_gmf)),
                        yerr=np.sqrt(np.diag(data_gmf_cov)) / data_gmf,
                        fmt="o",
                        color='k',
                        markersize=0,
                        lw=0,
                        capsize=3,
                        elinewidth=1.5)
            ax.plot(np.arange(1., 20., 1),
                    np.repeat(1., len(np.arange(1., 20, 1))),
                    c='k',
                    ls='--',
                    lw=1.75)

            ax.yaxis.tick_right()
            ax.yaxis.set_label_position('right')
            ax.set_ylim([-0.1, 2.1])
            ax.set_ylabel(r'$\zeta/\zeta^\mathtt{obvs}$', fontsize=25)
            ax.set_xlim([1., 20.])
            ax.set_xlabel(r'$\mathtt{N}$ [Group Richness]', fontsize=25)

    fig.subplots_adjust(wspace=0.05, hspace=0.0)
    fig_name = ''.join([ut.fig_dir(), 'paper', '.ABCposterior', '.pdf'])
    fig.savefig(fig_name, bbox_inches='tight')
    plt.close()
    return None
def test_ancestors_without_descendant(nsnap_ancestor=20,
                                      scatter=0.0,
                                      source='li-drory-march'):
    '''
    What happens to ancestors that do not have descendants at nsnap = 1


    Notes
    -----
    * More than 50% of the subhalos at nsnap=20 do not have descendants at nsnap = 1. 
        What happens to them? 
    * Do they become satellites? --> Some become satellites, others 
        with no mass subhalos don't stay in the catalog at all
    '''
    prettyplot()
    pretty_colors = prettycolors()

    fig = plt.figure(figsize=(10, 10))
    sub = fig.add_subplot(111)

    # Central subhalo at nsnap_ancestor (ancesotr)
    anc = CentralSubhalos()
    anc.read(nsnap_ancestor, scatter=scatter, source=source)

    # Centrals subhalo at nsnap = 1 (descendant)
    des = CentralSubhalos()
    des.read(1, scatter=scatter, source=source)

    no_descendants = np.invert(np.in1d(anc.index, des.ancestor20))
    massive_nodescendants = np.where(anc.mass[no_descendants] > 0.0)
    print 'N_SH no descendants ', len(anc.mass[no_descendants])
    print 'N_SH total ', len(anc.mass)
    print np.float(len(anc.mass[no_descendants])) / np.float(len(anc.mass))

    no_des_index = anc.index[no_descendants][massive_nodescendants][:5]
    print anc.mass[no_descendants][massive_nodescendants][:5]
    for isnap in range(1, nsnap_ancestor)[::-1]:
        i_des = CentralSubhalos()
        i_des.read(isnap, scatter=scatter, source=source)

        #print isnap, np.in1d(no_des_index, i_des.ancestor20)

        #if not np.in1d(no_des_index, i_des.ancestor20)[0]:
        des_sh = Subhalos()
        des_sh.read(isnap, scatter=scatter, source=source)
        #if np.sum(np.in1d(des_sh.ancestor20, no_des_index)) != len(no_des_index):
        #    raise ValueError
        print des_sh.ilk[np.in1d(des_sh.ancestor20, no_des_index)][np.argsort(
            des_sh.ancestor20[np.in1d(des_sh.ancestor20, no_des_index)])]
        print 'M* ', des_sh.mass[np.in1d(
            des_sh.ancestor20, no_des_index)][np.argsort(
                des_sh.ancestor20[np.in1d(des_sh.ancestor20, no_des_index)])]
        print 'M_halo ', getattr(des_sh, 'halo.m')[np.in1d(
            des_sh.ancestor20,
            no_des_index)][np.argsort(des_sh.ancestor20[np.in1d(
                des_sh.ancestor20, no_des_index)])]
        #print des_sh.mass[np.in1d(des_sh.index, no_des_index)]
        #np.in1d(i_des.ancestor20, no_des_index)

    sub.set_yscale('log')
    sub.set_ylim([10**-5, 10**-1])
    sub.set_xlim([6.0, 12.0])
    sub.legend(loc='upper right')