Ejemplo n.º 1
0
 def test_cosmologies(self):
     cosmolist = [
         'WMAP1', 'WMAP3', 'WMAP5', 'WMAP7', 'WMAP9', 'Planck13', 'Planck15'
     ]
     conclist = [
         8.84952005507872, 6.570929526400634, 7.663081978810533,
         7.906741464320479, 8.883912548303279, 9.250262507139139,
         9.044999285760362
     ]
     for ival, cosmo in enumerate(cosmolist):
         output = commah.run(cosmo, Mi=[1e12], verbose=True)
         assert (np.allclose(output['c'].flatten()[0],
                             conclist[ival],
                             rtol=1e-3))
Ejemplo n.º 2
0
    def __init__(self, Mvir, zvir, c, cosm):
        self.Mvir = Mvir  # Msun
        self.zvir = zvir
        self.c = c
        self.cosm = cosm
        fb = 1. / 6

        if c == None:
            print "Automatically generating concentration from COMMAH"
            output = commah.run("Planck13", zi=zvir, Mi=Mvir,
                                z=[zvir])  # TODO use cosm
            c = np.ravel(output['c'])[0]
            self.c = c

        self.Msun = 2.e33  # g
        self.yr = 3.156e7  # s
        self.pc = 3.086e18  # cm
        self.kpc = 3.086e21  # cm
        self.kB = 1.38e-16  # erg/K
        self.Gc = 6.67e-8  # (cm/s)^2 cm/g
        self.mu = 0.59  # for ionized primordial gas
        self.mp = 1.67e-24  # g

        self.Delta_c = 200.
        self.rhoc = cosm.rho_c(zvir)  # g/cc
        self.rhovir = self.Delta_c * self.rhoc  # g/cc
        self.Rvir = (3 * Mvir * self.Msun /
                     (4 * np.pi * self.rhovir))**(1. / 3) / self.kpc  # kpc
        self.rs = self.Rvir / c  # kpc
        self.rho0 = self.rhovir * c * c * c / (self.F(c) * 3.)  # g/cc

        self.Vvir = np.sqrt(self.Gc * Mvir * self.Msun /
                            (self.Rvir * self.kpc)) / 1.e5  #km/s
        self.Vmax = self.Vvir * np.sqrt(0.2162 * c / (self.F(c)))  # km/s
        self.RVmax = 2.1626 * self.rs  # kpc TODO check
        self.Tvir = self.mp * (self.Vvir * 1e5)**2 / (2. * self.kB) * self.mu

        # for isothermal density profile
        self.Vesc0 = np.sqrt(2) * self.Vvir * np.sqrt(self.c / self.F(self.c))
        self.mbar = self.mu * self.mp
        A = 2 * c / self.F(c)
        denom = quad(lambda t: (1 + t)**(A / t) * t * t, 0, c)[0]
        self.rhoiso0 = cosm.rho_c(zvir) * (200. / 3) * (
            c**3) * fb * cosm.Om * np.exp(A) / denom
Ejemplo n.º 3
0
    def __init__(self, Mvir, zvir, c, cosm):
        self.Mvir = Mvir  # Msun
        self.zvir = zvir
        self.c = c
        self.cosm = cosm
        fb = 1.0 / 6

        if c == None:
            print "Automatically generating concentration from COMMAH"
            output = commah.run("Planck13", zi=zvir, Mi=Mvir, z=[zvir])  # TODO use cosm
            c = np.ravel(output["c"])[0]
            self.c = c

        self.Msun = 2.0e33  # g
        self.yr = 3.156e7  # s
        self.pc = 3.086e18  # cm
        self.kpc = 3.086e21  # cm
        self.kB = 1.38e-16  # erg/K
        self.Gc = 6.67e-8  # (cm/s)^2 cm/g
        self.mu = 0.59  # for ionized primordial gas
        self.mp = 1.67e-24  # g

        self.Delta_c = 200.0
        self.rhoc = cosm.rho_c(zvir)  # g/cc
        self.rhovir = self.Delta_c * self.rhoc  # g/cc
        self.Rvir = (3 * Mvir * self.Msun / (4 * np.pi * self.rhovir)) ** (1.0 / 3) / self.kpc  # kpc
        self.rs = self.Rvir / c  # kpc
        self.rho0 = self.rhovir * c * c * c / (self.F(c) * 3.0)  # g/cc

        self.Vvir = np.sqrt(self.Gc * Mvir * self.Msun / (self.Rvir * self.kpc)) / 1.0e5  # km/s
        self.Vmax = self.Vvir * np.sqrt(0.2162 * c / (self.F(c)))  # km/s
        self.RVmax = 2.1626 * self.rs  # kpc TODO check
        self.Tvir = self.mp * (self.Vvir * 1e5) ** 2 / (2.0 * self.kB) * self.mu

        # for isothermal density profile
        self.Vesc0 = np.sqrt(2) * self.Vvir * np.sqrt(self.c / self.F(self.c))
        self.mbar = self.mu * self.mp
        A = 2 * c / self.F(c)
        denom = quad(lambda t: (1 + t) ** (A / t) * t * t, 0, c)[0]
        self.rhoiso0 = cosm.rho_c(zvir) * (200.0 / 3) * (c ** 3) * fb * cosm.Om * np.exp(A) / denom
Ejemplo n.º 4
0
def plotcommand(cosmology='WMAP5', plotname=None):
    """ Example ways to interrogate the dataset and plot the commah output """

    # Plot the c-M relation as a functon of redshift
    xarray = 10**(np.arange(1, 15, 0.2))
    yval = 'c'

    # Specify the redshift range
    zarray = np.arange(0, 5, 0.5)

    xtitle = r"Halo Mass (M$_{sol}$)"
    ytitle = r"Concentration"
    linelabel = "z="

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_xlabel(xtitle)
    ax.set_ylabel(ytitle)
    plt.ylim([2, 30])

    colors = cm.rainbow(np.linspace(0, 1, len(zarray)))

    for zind, zval in enumerate(zarray):
        output = commah.run(cosmology=cosmology, zi=zval, Mi=xarray)

        # Access the column yval from the data file
        yarray = output[yval].flatten()

        # Plot each line in turn with different colour
        ax.plot(xarray,
                yarray,
                label=linelabel + str(zval),
                color=colors[zind])
        # Overplot the D08 predictions in black
        ax.plot(xarray, commah.commah.cduffy(zval, xarray), color="black")

    ax.set_xscale('log')
    ax.set_yscale('log')

    leg = ax.legend(loc=1)
    # Make box totally transparent
    leg.get_frame().set_alpha(0)
    leg.get_frame().set_edgecolor('white')
    for label in leg.get_texts():
        label.set_fontsize('small')  # the font size
    for label in leg.get_lines():
        label.set_linewidth(4)  # the legend line width

    if plotname:
        fig.tight_layout(pad=0.2)
        print("Plotting to '%s_CM_relation.png'" % (plotname))
        fig.savefig(plotname + "_CM_relation.png", dpi=fig.dpi * 5)
    else:
        plt.show()

    # Plot the c-z relation as a function of mass (so always Mz=M0)
    xarray = 10**(np.arange(0, 1, 0.05)) - 1
    yval = 'c'

    # Specify the mass range
    zarray = 10**np.arange(6, 14, 2)

    xtitle = r"Redshift"
    ytitle = r"NFW Concentration"
    linelabel = r"log$_{10}$ M$_{z}$(M$_{sol}$)="

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_xlabel(xtitle)
    ax.set_ylabel(ytitle)
    colors = cm.rainbow(np.linspace(0, 1, len(zarray)))

    for zind, zval in enumerate(zarray):
        output = commah.run(cosmology=cosmology, zi=xarray, Mi=zval)

        # Access the column yval from the data file
        yarray = output[yval].flatten()

        # Plot each line in turn with different colours
        ax.plot(
            xarray,
            yarray,
            label=linelabel + "{0:.1f}".format(np.log10(zval)),
            color=colors[zind],
        )

    leg = ax.legend(loc=1)
    # Make box totally transparent
    leg.get_frame().set_alpha(0)
    leg.get_frame().set_edgecolor('white')
    for label in leg.get_texts():
        label.set_fontsize('small')  # the font size
    for label in leg.get_lines():
        label.set_linewidth(4)  # the legend line width

    if plotname:
        fig.tight_layout(pad=0.2)
        print("Plotting to '%s_Cz_relation.png'" % (plotname))
        fig.savefig(plotname + "_Cz_relation.png", dpi=fig.dpi * 5)
    else:
        plt.show()

    # Plot the zf-z relation for different masses (so always Mz=M0)
    xarray = 10**(np.arange(0, 1, 0.05)) - 1
    yval = 'zf'

    # Specify the mass range
    zarray = 10**np.arange(6, 14, 2)

    xtitle = r"Redshift"
    ytitle = r"Formation Redshift"
    linelabel = r"log$_{10}$ M$_{z}$(M$_{sol}$)="

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_xlabel(xtitle)
    ax.set_ylabel(ytitle)
    colors = cm.rainbow(np.linspace(0, 1, len(zarray)))

    for zind, zval in enumerate(zarray):
        output = commah.run(cosmology=cosmology, zi=xarray, Mi=zval)

        yarray = output[yval].flatten()

        # Plot each line in turn with different colour
        ax.plot(
            xarray,
            yarray,
            label=linelabel + "{0:.1f}".format(np.log10(zval)),
            color=colors[zind],
        )

    leg = ax.legend(loc=2)
    # Make box totally transparent
    leg.get_frame().set_alpha(0)
    leg.get_frame().set_edgecolor('white')
    for label in leg.get_texts():
        label.set_fontsize('small')  # the font size
    for label in leg.get_lines():
        label.set_linewidth(4)  # the legend line width

    if plotname:
        fig.tight_layout(pad=0.2)
        print("Plotting to '%s_zfz_relation.png'" % (plotname))
        fig.savefig(plotname + "_zfz_relation.png", dpi=fig.dpi * 5)
    else:
        plt.show()

    # Plot the dM/dt-z relation for different masses (so always Mz=M0)
    xarray = 10**(np.arange(0, 1, 0.05)) - 1
    yval = 'dMdt'

    # Specify the mass range
    zarray = 10**np.arange(10, 14, 0.5)

    xtitle = r"log$_{10}$ (1+z)"
    ytitle = r"log$_{10}$ Accretion Rate M$_{sol}$ yr$^{-1}$"
    linelabel = r"log$_{10}$ M$_z$(M$_{sol}$)="

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_xlabel(xtitle)
    ax.set_ylabel(ytitle)
    colors = cm.rainbow(np.linspace(0, 1, len(zarray)))

    cosmo = commah.getcosmo(cosmology)
    for zind, zval in enumerate(zarray):
        output = commah.run(cosmology=cosmology,
                            zi=xarray,
                            Mi=zval,
                            com=False,
                            mah=True)

        yarray = output[yval].flatten()

        # Plot each line in turn with different colour
        ax.plot(
            np.log10(xarray + 1.),
            np.log10(yarray),
            label=linelabel + "{0:.1f}".format(np.log10(zval)),
            color=colors[zind],
        )

        # Plot the semi-analytic approximate formula from Correa et al 2015b
        semianalytic_approx = 71.6 * (zval / 1e12) * (cosmo['h'] / 0.7) *\
            (-0.24 + 0.75 * (xarray + 1)) * np.sqrt(
            cosmo['omega_M_0'] * (xarray + 1)**3 + cosmo['omega_lambda_0'])

        ax.plot(np.log10(xarray + 1),
                np.log10(semianalytic_approx),
                color='black')

    leg = ax.legend(loc=2)
    # Make box totally transparent
    leg.get_frame().set_alpha(0)
    leg.get_frame().set_edgecolor('white')
    for label in leg.get_texts():
        label.set_fontsize('small')  # the font size
    for label in leg.get_lines():
        label.set_linewidth(4)  # the legend line width

    if plotname:
        fig.tight_layout(pad=0.2)
        print("Plotting to '%s_dMdtz_relation.png'" % (plotname))
        fig.savefig(plotname + "_dMdtz_relation.png", dpi=fig.dpi * 5)
    else:
        plt.show()

    # Plot the dMdt-M relation as a function of redshift
    xarray = 10**(np.arange(10, 14, 0.5))
    yval = 'dMdt'

    # Specify the redshift range
    zarray = np.arange(0, 5, 0.5)

    xtitle = r"Halo Mass M$_{sol}$"
    ytitle = r"Accretion Rate M$_{sol}$ yr$^{-1}$"
    linelabel = "z="

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_xlabel(xtitle)
    ax.set_ylabel(ytitle)
    colors = cm.rainbow(np.linspace(0, 1, len(zarray)))

    for zind, zval in enumerate(zarray):
        output = commah.run(cosmology=cosmology,
                            zi=zval,
                            Mi=xarray,
                            com=False,
                            mah=True)

        yarray = output[yval].flatten()

        # Plot each line in turn with different colour
        ax.plot(
            xarray,
            yarray,
            label=linelabel + str(zval),
            color=colors[zind],
        )

    ax.set_xscale('log')
    ax.set_yscale('log')

    leg = ax.legend(loc=2)
    # Make box totally transparent
    leg.get_frame().set_alpha(0)
    leg.get_frame().set_edgecolor('white')
    for label in leg.get_texts():
        label.set_fontsize('small')  # the font size
    for label in leg.get_lines():
        label.set_linewidth(4)  # the legend line width

    if plotname:
        fig.tight_layout(pad=0.2)
        print("Plotting to '%s_MAH_M_relation.png'" % (plotname))
        fig.savefig(plotname + "_MAH_M_relation.png", dpi=fig.dpi * 5)
    else:
        plt.show()

    # Plot the (dM/M)dt-M relation as a function of redshift
    xarray = 10**(np.arange(10, 14, 0.5))
    yval = 'dMdt'

    # Specify the redshift range
    zarray = np.arange(0, 5, 0.5)

    xtitle = r"Halo Mass M$_{sol}$"
    ytitle = r"Specific Accretion Rate yr$^{-1}$"
    linelabel = "z="

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_xlabel(xtitle)
    ax.set_ylabel(ytitle)
    colors = cm.rainbow(np.linspace(0, 1, len(zarray)))

    for zind, zval in enumerate(zarray):
        output = commah.run(cosmology=cosmology,
                            zi=zval,
                            Mi=xarray,
                            mah=True,
                            com=False)

        yarray = output[yval].flatten()

        # Plot each line in turn with different colour
        ax.plot(
            xarray,
            yarray / xarray,
            label=linelabel + str(zval),
            color=colors[zind],
        )

    ax.set_xscale('log')
    ax.set_yscale('log')

    leg = ax.legend(loc=1)
    # Make box totally transparent
    leg.get_frame().set_alpha(0)
    leg.get_frame().set_edgecolor('white')
    for label in leg.get_texts():
        label.set_fontsize('small')  # the font size
    for label in leg.get_lines():
        label.set_linewidth(4)  # the legend line width

    if plotname:
        fig.tight_layout(pad=0.2)
        print("Plotting to '%s_specificMAH_M_relation.png'" % (plotname))
        fig.savefig(plotname + "_specificMAH_M_relation.png", dpi=fig.dpi * 5)
    else:
        plt.show()

    # Plot the Mz-z relation as a function of mass
    # (so mass is decreasing to zero as z-> inf)
    xarray = 10**(np.arange(0, 1, 0.05)) - 1
    yval = 'Mz'

    # Specify the mass range
    zarray = 10**np.arange(10, 14, 0.5)

    xtitle = r"Redshift"
    ytitle = r"M(z) (M$_{sol}$)"
    linelabel = r"log$_{10}$ M$_{0}$(M$_{sol}$)="

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_xlabel(xtitle)
    ax.set_ylabel(ytitle)
    colors = cm.rainbow(np.linspace(0, 1, len(zarray)))

    for zind, zval in enumerate(zarray):
        output = commah.run(cosmology=cosmology, zi=0, Mi=zval, z=xarray)

        yarray = output[yval].flatten()

        # Plot each line in turn with different colour
        ax.plot(
            xarray,
            yarray,
            label=linelabel + "{0:.1f}".format(np.log10(zval)),
            color=colors[zind],
        )

    ax.set_yscale('log')

    leg = ax.legend(loc=1)
    # Make box totally transparent
    leg.get_frame().set_alpha(0)
    leg.get_frame().set_edgecolor('white')
    for label in leg.get_texts():
        label.set_fontsize('small')  # the font size
    for label in leg.get_lines():
        label.set_linewidth(4)  # the legend line width

    if plotname:
        fig.tight_layout(pad=0.2)
        print("Plotting to '%s_Mzz_relation.png'" % (plotname))
        fig.savefig(plotname + "_Mzz_relation.png", dpi=fig.dpi * 5)
    else:
        plt.show()

    # Plot the Mz/M0-z relation as a function of mass
    xarray = 10**(np.arange(0, 1, 0.02)) - 1
    yval = 'Mz'

    # Specify the mass range
    zarray = 10**np.arange(10, 14, 0.5)

    xtitle = r"Redshift"
    ytitle = r"log$_{10}$ M(z)/M$_{0}$"
    linelabel = r"log$_{10}$ M$_{0}$(M$_{sol}$)="

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_xlabel(xtitle)
    ax.set_ylabel(ytitle)
    colors = cm.rainbow(np.linspace(0, 1, len(zarray)))

    for zind, zval in enumerate(zarray):
        output = commah.run(cosmology=cosmology, zi=0, Mi=zval, z=xarray)

        yarray = output[yval].flatten()

        # Plot each line in turn with different colour
        ax.plot(
            xarray,
            np.log10(yarray / zval),
            label=linelabel + "{0:.1f}".format(np.log10(zval)),
            color=colors[zind],
        )

    leg = ax.legend(loc=3)
    # Make box totally transparent
    leg.get_frame().set_alpha(0)
    leg.get_frame().set_edgecolor('white')
    for label in leg.get_texts():
        label.set_fontsize('small')  # the font size
    for label in leg.get_lines():
        label.set_linewidth(4)  # the legend line width

    if plotname:
        fig.tight_layout(pad=0.2)
        print("Plotting to '%s_MzM0z_relation.png'" % (plotname))
        fig.savefig(plotname + "_MzM0z_relation.png", dpi=fig.dpi * 5)
    else:
        plt.show()

    return ("Done")
Ejemplo n.º 5
0
def runcommand(cosmology='WMAP5'):
    """ Example interface commands """

    # Return the WMAP5 cosmology concentration predicted for
    # z=0 range of masses
    Mi = [1e8, 1e9, 1e10]
    zi = 0
    print("Concentrations for haloes of mass %s at z=%s" % (Mi, zi))
    output = commah.run(cosmology=cosmology, zi=zi, Mi=Mi)

    print(output['c'].flatten())

    # Return the WMAP5 cosmology concentration predicted for
    # z=0 range of masses AND cosmological parameters
    Mi = [1e8, 1e9, 1e10]
    zi = 0
    print("Concentrations for haloes of mass %s at z=%s" % (Mi, zi))
    output, cosmo = commah.run(cosmology=cosmology,
                               zi=zi,
                               Mi=Mi,
                               retcosmo=True)

    print(output['c'].flatten())
    print(cosmo)

    # Return the WMAP5 cosmology concentration predicted for MW
    # mass (2e12 Msol) across redshift
    Mi = 2e12
    z = [0, 0.5, 1, 1.5, 2, 2.5]
    output = commah.run(cosmology=cosmology, zi=0, Mi=Mi, z=z)
    for zval in z:
        print("M(z=0)=%s has c(z=%s)=%s" %
              (Mi, zval, output[output['z'] == zval]['c'].flatten()))

    # Return the WMAP5 cosmology concentration predicted for MW
    # mass (2e12 Msol) across redshift
    Mi = 2e12
    zi = [0, 0.5, 1, 1.5, 2, 2.5]
    output = commah.run(cosmology=cosmology, zi=zi, Mi=Mi)
    for zval in zi:
        print("M(z=%s)=%s has concentration %s" %
              (zval, Mi, output[(output['zi'] == zval)
                                & (output['z'] == zval)]['c'].flatten()))

    # Return the WMAP5 cosmology concentration and
    # rarity of high-z cluster
    Mi = 2e14
    zi = 6
    output = commah.run(cosmology=cosmology, zi=zi, Mi=Mi)
    print("Concentrations for haloes of mass %s at z=%s" % (Mi, zi))
    print(output['c'].flatten())
    print("Mass variance sigma of haloes of mass %s at z=%s" % (Mi, zi))
    print(output['sig'].flatten())
    print("Fluctuation for haloes of mass %s at z=%s" % (Mi, zi))
    print(output['nu'].flatten())

    # Return the WMAP5 cosmology accretion rate prediction
    # for haloes at range of redshift and mass
    Mi = [1e8, 1e9, 1e10]
    zi = [0]
    z = [0, 0.5, 1, 1.5, 2, 2.5]
    output = commah.run(cosmology=cosmology, zi=zi, Mi=Mi, z=z)
    for Mval in Mi:
        print("dM/dt for halo of mass %s at z=%s across redshift %s is: " %
              (Mval, zi, z))
        print(output[output['Mi'] == Mval]['dMdt'].flatten())

    # Return the WMAP5 cosmology Halo Mass History for haloes with M(z=0) = 1e8
    M = [1e8]
    z = [0, 0.5, 1, 1.5, 2, 2.5]
    print("Halo Mass History for z=0 mass of %s across z=%s" % (M, z))
    output = commah.run(cosmology=cosmology, zi=0, Mi=M, z=z)
    print(output['Mz'].flatten())

    # Return the WMAP5 cosmology formation redshifts for haloes at
    # range of redshift and mass
    M = [1e8, 1e9, 1e10]
    z = [0]
    print("Formation Redshifts for haloes of mass %s at z=%s" % (M, z))
    output = commah.run(cosmology=cosmology, zi=0, Mi=M, z=z)
    for Mval in M:
        print(output[output['Mi'] == Mval]['zf'].flatten())

    return ("Done")
Ejemplo n.º 6
0
 def test_startingz(self):
     zlist = np.array([0, 1, 2])
     conclist = np.array([4.55295, 4.43175, 4.26342])
     output = commah.run('WMAP5', zi=zlist, Mi=[1e12], z=2)
     assert (np.allclose(output['c'].flatten(), conclist, rtol=1e-3))
Ejemplo n.º 7
0
 def test_evolution(self):
     zlist = np.array([0, 1, 2])
     conclist = np.array([7.66308, 5.70009, 4.55295])
     output = commah.run('WMAP5', zi=[0], Mi=[1e12], z=zlist)
     assert (np.allclose(output['c'].flatten(), conclist, rtol=1e-3))
Ejemplo n.º 8
0
#!/usr/bin/env python

from __future__ import absolute_import, division, print_function
import commah

# Here's an example run script, modify as preferred
commah.run('WMAP5',
           zi=0,
           Mi=[1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14],
           z=[0, 0.5, 1, 1.5, 2],
           filename='WMAP5_Test.txt')
Ejemplo n.º 9
0
def main(argv):
    z_list_lgal = loadtxt(snapfile)
    lastsnap = len(z_list_lgal)-1
    gadget_m_conv = 1.e10
    hubble_h = 0.7
    #m6 = [9.,10.0,10.5,11.0,11.5]
    color = 'r'#['r''r','r','r','r','r']
    minz = z_start
    maxz = 30.
    dz = 0.25
    #limit = 300
    zlist = arange(minz,maxz,dz)
    #rc('text', usetex=True)
    (nTrees,nHalos,nTreeHalos,output_Halos,output_HaloIDs) = read_lgal_input_fulltrees_withids(folder,lastsnap,firstfile,lastfile,verbose=True)
    rootindex = numpy.cumsum(nTreeHalos)-nTreeHalos
    lastleafindex = numpy.cumsum(nTreeHalos)
    for j in range(len(m6)):
        fig = figure()
        ax = fig.add_subplot(111)
        t_m6 = m6[j]
        maxmass = 15.0
        minmass = 9.0
        mbin = len(zlist)
        dm = (maxmass-minmass)/mbin
        mz = commah.run('planck15',zi=z_start,Mi=10.**t_m6,z=zlist)['Mz'][0]
        mass = zeros(len(z_list_lgal),dtype=float64)
        count = zeros(len(z_list_lgal),dtype=int64)
        mask = ones(len(z_list_lgal),dtype=int32)
        count_2d = zeros((mbin,len(zlist)),dtype=int64)
        l_m = t_m6-0.1
        r_m = t_m6+0.1
        stsn = 1000
        for ii in range(len(nTreeHalos)):
            listrange = numpy.arange(rootindex[ii],lastleafindex[ii])
            r_list =  numpy.where((log10(output_Halos[listrange]['M_Crit200']*gadget_m_conv) <=r_m) & (log10(output_Halos[listrange]['M_Crit200']*gadget_m_conv) >=l_m) & (output_Halos[listrange]['SnapNum']==lastsnap) & (output_HaloIDs[listrange]["HaloID"] == output_HaloIDs[listrange]["FirstHaloInFOFgroup"]))[0]
            #print "r_list",listrange[r_list]
            for i in r_list:
                root = listrange[i]
                M0 = output_Halos[root]["M_Crit200"]*Gadget2Msun
                nexthaloid = output_Halos[root]['FirstProgenitor']
                if (nexthaloid > -1) & (output_Halos[root]['Len'] >= limit):
                    bin_m = (log10(M0) - minmass)/dm
                    mass[output_Halos[root]["SnapNum"]] += M0
                    count[output_Halos[root]["SnapNum"]] += 1
                    if (bin_m < mbin) & (bin_m >= 0):
                        z = z_list_lgal[output_Halos[root]["SnapNum"]]
                        bin_z = (z-minz)/dz
                        if (z >= minz) & (z < maxz):
                            count_2d[bin_m,bin_z] += 1
                while nexthaloid > -1:
                    nexthalo = output_Halos[rootindex[ii]+nexthaloid]
                    if nexthalo['Len'] >= limit:
                        mass[nexthalo["SnapNum"]] += nexthalo["M_Crit200"]*Gadget2Msun
                        bin_m = (log10(nexthalo["M_Crit200"]*Gadget2Msun) - minmass)/dm
                        count[nexthalo["SnapNum"]] += 1
                        if (bin_m < mbin) & (bin_m >= 0):
                            z = z_list_lgal[nexthalo["SnapNum"]]
                            bin_z = (z-minz)/dz
                            if (z >= minz) & (z < maxz):
                                count_2d[bin_m,bin_z] += 1
                        nexthaloid = nexthalo['FirstProgenitor']
                        stsn = min(stsn,nexthalo["SnapNum"])
                    else:
                        nexthaloid = -1
        #mask = count > count[len(z_list_lgal)-1]/2
        #print count_2d
        
        numpy.savetxt("count_2D_"+str(t_m6)+"_"+str(limit)+"p.txt",count_2d)
        numpy.savetxt("summass_"+str(t_m6)+"_"+str(limit)+"p.txt",mass)
        numpy.savetxt("countcol_"+str(t_m6)+"_"+str(limit)+"p.txt",count)
        print "min snap",stsn
        #mass = mass*mask
        if numpy.sum(count) > 0:
            ax.plot(z_list_lgal,log10(mass/count), color='r',linestyle='--',label="Average ("+str(limit)+"+ particles)")
            mask = count > count[len(z_list_lgal)-1]/2
            mass = mass*mask
            ax.plot(z_list_lgal,log10(mass/count), color='k',linestyle='-',label="Average ("+str(limit)+"+ particles,50\% limit)")
            extent = [minz,maxz,minmass,maxmass]
            #print extent
            im = ax.imshow(count_2d,origin='lower',aspect='auto',norm=LogNorm(),extent=extent,interpolation='none')
            fig.colorbar(im,ax=ax)
            ax.plot(zlist,log10(mz),color='r',linestyle = '-',label="Correa et al. (2015)")
            ax.set_xlim([minz,maxz])
            ax.set_ylim([minmass,maxmass])
            ax.set_xlabel(r"$z$")
            ax.set_ylabel(r"$\log(h M_{200c}/M_\odot)$")
            leg = ax.legend(loc='best', handlelength = 10,ncol=1, fancybox=True, prop={'size':10})
            leg.get_frame().set_linewidth(0)
            #fig.savefig(str(t_m6)+"_"+str(limit)+"p.pgf")
            fig.savefig(str(t_m6)+"_"+str(limit)+"p.pdf")
            close(fig)
            #ax.imshow(count_2d,origin='lower')
            #fig.show()
    return 0