示例#1
0
def generate_pdf_tables():
    tabout = []
    if (PROJ == "perpendicular"):
        ioncds = ioformat.rcol(fnamex, cols, separator=",", linestart=1)
        foutname = "pdfs/" + modelstr + "_i9_x_pdf.dat"
    else:
        ioncds = ioformat.rcol(fnamey, cols, separator=",", linestart=1)
        foutname = "pdfs/" + modelstr + "_i9_y_pdf.dat"
    edges = linspace(0., 1., NCELLS + 1)
    # pdb.set_trace()
    for i in range(9):
        idx = ionidxs[i]
        if (idx == -1):
            tabout.append(array([0.0] * (NCELLS + 1)))
            print("---")
            continue
        ionname = ionnames[idx]
        print(ionname)
        ioncds[idx - 1].sort()
        # pdb.set_trace()
        prob = log10(ioncds[idx - 1][::-1][:NPIXLIM][::(int)(NPIXLIM /
                                                             NCELLS)][:NCELLS +
                                                                      1])
        # prob = log10(ioncds[idx-1][::-1][:NPIXLIM][::(int)(NPIXLIM/NCELLS)-1])
        tabout.append(prob)

    fout = open(foutname, "w")
    fout.write("#P(>logN) HI HeII CIII CIV OIV OVI NeVIII MgII SiIV\n")
    for i in range(NCELLS + 1):
        line = "%5.3f " % (edges[i])
        for j in range(9):
            line += "%6.3f " % (tabout[j][i])
        line += "\n"
        fout.write(line)
    fout.close()
示例#2
0
def read_gal_data(skidbase, snapstr):
    fgal = "%s/gal_z%s.stat" % (skidbase, snapstr)
    fso = "%s/so_z%s.sovcirc" % (skidbase, snapstr)
    mstar = ioformat.rcol(fgal, [4])
    mvir = ioformat.rcol(fso, [1], linestart=1)
    gals = []
    for i in range(len(mstar)):
        gals.append(skidgal(mstar[i], mvir[i]))
    return gals
示例#3
0
def plot_smhm_model(mi, axs, shade=False, mhcorr=1.0):
    modelname = models[mi]
    clr = clrs[mi]
    smhmlist = [\
             fbase + modelname + "/" + "smhm_" + zstr2[0]+".txt",
             fbase + modelname + "/" + "smhm_" + zstr2[1]+".txt",
             fbase + modelname + "/" + "smhm_" + zstr2[2]+".txt",
             fbase + modelname + "/" + "smhm_" + zstr2[3]+".txt"          
    ]
    for i in range(len(smhmlist)):
        # ms, mvir, flag, mh = ioformat.rcol(smhmlist[i], [0,1,2,3], linestart=1)
        ms, mh, flag = ioformat.rcol(smhmlist[i], [0,1,2], linestart=1)
        x, y = [], []
        mh = array(mh) / mhcorr
        for j in range(len(flag)):
            if(flag[j] == 1.0): # Only plot the central
                x.append(mh[j])
                if(PLOT_MASS_RATIO == True): y.append(ms[j]/mh[j])
                else: y.append(ms[j])
        # plt.plot(x, y, "b.", alpha=0.2)
        x, y = bin1d.subsample(x, y, nonzero=True)
        s = bin1d.bin1d(x, y, nbins=40, logbins=True, bounds=0.95)
        xline, yline = log10(s.cen), log10(s.median)
        uline, lline = log10(s.ubound), log10(s.lbound)
        axs[i].plot(xline, yline, "-", color=clr, linewidth=2)
        maxidx = -4
        if(shade == True):
            axs[i].fill(append(xline[:maxidx],xline[maxidx-1::maxidx+1]), append(uline[:maxidx],lline[maxidx-1::maxidx+1]), color=colors[i], alpha=0.2)
示例#4
0
def build_mvir_bins(stars, soname):
    msub = ioformat.rcol(soname, [6], linestart=1)
    flag = [0] * len(msub)
    mvbins = binned_by_virial_mass(nbins=40, mmin=10.0, mmax=14.0)
    for s in stars: # loop over all stars
        hidx = s['HID']-1
        mvir = msub[hidx] / HUBBLEPARAM
        if(isinf(log10(mvir))): continue
        bidx = mvbins.find_idx_for_bin(log10(mvir))
        mvbins.stotal[bidx] += s['StarMass']
        mvbins.total[bidx] += s['Mass']
        if(s['a_last'] == 0): # primordial
            if(s['Tmax'] > TMAX_CUT):
                mvbins.hot[bidx] += s['Mass'] - s['WindMass']
                mvbins.whot[bidx] += s['WindMass']
            else:
                mvbins.cold[bidx] += s['Mass'] - s['WindMass']
                mvbins.wcold[bidx] += s['WindMass']
        elif(s['a_last'] < 0): # wind
            if(abs(s['Tmax']) > TMAX_CUT): mvbins.whot[bidx] += s['Mass']
            else: mvbins.wcold[bidx] += s['Mass']
        else: mvbins.other[bidx] += s['Mass']
        if(flag[hidx] == 0):
            flag[hidx] = 1
            mvbins.totalmass[bidx] += mvir
    mvbins.totalmass *= (OMEGAB / OMEGAM) * 2.0e33
    return mvbins
示例#5
0
def read_sm(mh):
    fname = SMBASE
    fname += sm_name_prefix
    i = (int)(mh - 11.0)
    fname += mhstrs[i] + sm_name_suffix
    print ("Reading: ", fname)
    a, frac, e1, e2 = ioformat.rcol(fname, [0,1,2,3])
    return a, frac, e1, e2
示例#6
0
def show():
    import matplotlib.pyplot as plt
    x, y, z = ioformat.rcol(foutname, [1, 2, 3])
    plt.plot(x, z, "b.-")
    for i in range(len(x)):
        plt.text(x[i], z[i], str(400 - i), fontsize=6)
    plt.axis([-0.5, 0.5, -0.5, 0.5])
    plt.show()
示例#7
0
def read_smmr(z, mhthen=False):
    fname = SMMRBASE
    fname += smmr_name_prefix
    if(mhthen == True): fname += "then_"
    i = (int)(z)
    fname += zstrs[i] + smmr_name_suffix
    print ("Reading: ", fname)
    mh, dm, e1, d2 = ioformat.rcol(fname, [0,1,2,3], linestart=1)
    return mh, dm, e1, d2
示例#8
0
def write_starhost_file(modelname, unit_m):
    # modelname = "l50n288-phew-m5"
    # unit_m = 3.4e6 * 8.
    galname, soname, finname, foutname = find_fnames(modelname)
    stars = genfromtxt(finname, names=True)
    mstar = ioformat.rcol(galname, [4], linestart=0)
    msub = ioformat.rcol(soname, [6], linestart=1)
    mstar = log10(array(mstar) * unit_m * 1.e10 / 0.7)
    msub = log10(array(msub) / 0.7)
    stars['Mass'] *= unit_m * 1.e10 / 0.7
    print "Start Writing"
    fout = open(foutname, "w")
    fout.write("#Mass Mstar Msub Tmax Flag\n")
    for s in stars:
        gidx, hidx = (int)(s['GID']) - 1, (int)(s['HID']) - 1
        if (gidx < 0 or hidx < 0): continue
        ms, mh = mstar[gidx], msub[hidx]
        if (gidx == hidx): flag = 1
        else: flag = 0
        line = "%7.5e %6.3f %6.3f %5.3f %d\n" % \
               (s['Mass'], ms, mh, s['Tmax'], flag)
        fout.write(line)
    fout.close()
示例#9
0
def draw(ax=None, pcolor="blue", marker="o", tshift=0.0):
    x, y, z = ioformat.rcol(galname, [18, 19, 20])
    x = (array(x) + 0.5) * LBOX
    y = (array(y) + 0.5) * LBOX
    z = (array(z) + 0.5) * LBOX
    msub, rsub = ioformat.rcol(soname, [6, 7], linestart=1)

    print ("Start Drawing.")
    if(ax == None):
        fig = plt.figure(figsize=(8,8))
        ax = fig.add_subplot(111)
    n = 0
    # xs, ys, sizes = [], [], []
    for i in range(len(x)):
        if(msub[i] == 0): continue
        if(XYRANGE == True):
            if(x[i] < XRANGE[0] or x[i] > XRANGE[1]): continue
            if(y[i] < YRANGE[0] or y[i] > YRANGE[1]): continue
            if(z[i] < ZRANGE[0] or z[i] > ZRANGE[1]): continue            
        if(log10(msub[i] / HUBBLEPARAM) > MSUB_MIN):
            # xs.append(x[i])
            # ys.append(y[i])
            # sizes.append(rsub[i] / 1.e3) # Convert to kpc
            plt.gca().add_artist(Circle((x[i], y[i]), rsub[i]/1.e3, alpha=0.6, fc="blue"))
            if(LABEL == True):
                lbl = "%d %4.1f" % (i+1, log10(msub[i]/HUBBLEPARAM))
                plt.text(x[i], y[i], lbl, fontsize=6)
            # print xs[-1], ys[-1], sizes[-1]
            n += 1
    print ("Number of Galaxies Shown: ", n)
    # ax.scatter(x, y, s=sizes, alpha=0.6, color=pcolor, marker=marker)
    # ax.plot(xs, ys, "r.", markersize=5)
    ax.set_xlim(XBOUNDS)
    ax.set_ylim(YBOUNDS)
    ax.set_xlabel("Mpc/h")
    ax.set_ylabel("Mpc/h")    
    plt.savefig("/scratch/shuiyao/figures/tmp.png")
示例#10
0
def find_total_mass(stars, soname):
    mtot = 0.0
    msub = ioformat.rcol(soname, [6], linestart=1)
    ncount = 0
    for s in stars:
        m = msub[s['HID'] - 1]
        if(m > 0):
            mtot += m
            ncount += 1
            msub[s['HID'] - 1] = 0.0 # Once added, reset to 0 to prevent repeated counting
    mtot = mtot / HUBBLEPARAM
    print ("Total amount of haloes found: %d." % (ncount))
    print ("  - Average mass (log): %5.2f." % log10((mtot / float(ncount))))
    mtot = mtot * 2.e33    
    return mtot
示例#11
0
def draw_frame():
    from matplotlib.lines import Line2D
    from pltastro import legend
    lgd1 = legend.legend(axs[0])
    lgd1.loc = "lower left"
    # lgd1.addLine((lgds[2], "black", ":", 1))
    for i in range(len(lgds)):
        lgd1.addLine((lgds[i], "black", lstyles[i], 1))
    lgd1.draw()
    lgd2 = legend.legend(axs[0])
    lgd2.loc = "lower right"
    lgd2.addLine(("cold", "blue", "-", 1))
    lgd2.addLine(("hot", "red", "-", 1))
    # lgd2.addLine(("cold wind", "cyan", "-", 1))
    # lgd2.addLine(("hot wind", "magenta", "-", 1))
    # lgd2.addLine(("hot wind", "magenta", "-", 1))    
    if(SHOW_ALLWINDS):
        lgd2.addLine(("all wind", color_allw, "-", 1))    
    lgd2.draw()

    FBEHROOZI = DIRS['SCI']+"REFERENCES/behroozi13/smmr/"
    if(REDSHIFT == 2.0):
        snapnum, zstr_behroozi = "058", "2.00"
    if(REDSHIFT == 0.0):
        snapnum, zstr_behroozi = "108", "0.10"
    if(REDSHIFT == 1.0):
        snapnum, zstr_behroozi = "078", "1.00"
    if(REDSHIFT == 0.25):
        snapnum, zstr_behroozi = "098", "0.10"
    mh, ms, err1, err2 = ioformat.rcol(FBEHROOZI+"c_smmr_z"+zstr_behroozi+"_red_all_smf_m1p1s1_bolshoi_fullcosmos_ms.dat", [0,1,2,3], linestart=1)
    ms = array(ms) - log10(0.156)
    axs[0].plot(mh, ms, "o", color="green", markersize=6)
    axs[0].errorbar(mh, ms, yerr=[err1, err2], color="green")

    axs[0].set_title("z = "+str(REDSHIFT)[:3], fontsize=16)

    axs[0].plot([10.9, 10.9], [-4.0, -0.5], "k--")
    axs[0].plot([10.0, 10.0], [-4.0, -0.5], "k-")
    axs[1].plot([10.9, 10.9], [0.0, 1.1], "k--")
    axs[1].plot([10.0, 10.0], [0.0, 1.1], "k-")

    plt.savefig(DIRS['FIGURE']+"tmp.pdf")
    plt.show()
示例#12
0
def plot_last_signal():
    mvir, rvir, rlast, mclast = ioformat.rcol(fwind, [8, 10, 6, 5], linestart=1)
    mbin_min = [11.25, 11.75, 12.25, 12.75]
    mbin_max = [11.75, 12.25, 12.75, 13.75]
    clrs = ["magenta", "red", "orange", "yellow"]
    wpmbin = []
    class mvir_bin():
        def __init__(self, mmin, mmax):
            self.mmin = mmin
            self.mmax = mmax
            self.rlast = []
            self.rratio = []
            self.mclast = []

    ax = plt.figure(1, figsize=(6,6)).add_subplot(111)        
    for i in range(len(mbin_min)):
        wpmbin.append(mvir_bin(mbin_min[i], mbin_max[i]))
        for j in range(len(mvir)):
            if (mbin_min[i] < mvir[j] < mbin_max[i]):
                wpmbin[-1].rlast.append(rlast[j])
                wpmbin[-1].mclast.append(mclast[j])
                wpmbin[-1].rratio.append(rlast[j]/rvir[j])
        # x, y = bin1d.subsample(wpmbin[-1].mclast, wpmbin[-1].rlast, nonzero=True)
        # print len(wpmbin[-1].mclast), len(wpmbin[-1].rratio)
        if(len(wpmbin[-1].mclast) > 0):
            x, y = bin1d.subsample(wpmbin[-1].mclast, wpmbin[-1].rratio, nonzero=True)
            s = bin1d.bin1d(x, y, nbins=10, bounds=boundsvalue)
            xline, yline = s.value, s.median
            uline, lline = s.ubound, s.lbound
            p, = ax.plot(xline, yline, "-", color=clrs[i]) # Draw line for all models    
            pf, = plt.fill(xline+xline[::-1], uline+lline[::-1], color=clrs[i], alpha=alphavalue)
    plt.ylabel(r'$r_{last} / R_{vir}$')
    plt.xlabel(r'$Mc_{last}$')
    legends = []
    legends.append(mpatches.Patch(color="yellow"))
    legends.append(mpatches.Patch(color="orange"))
    legends.append(mpatches.Patch(color="red"))
    legends.append(mpatches.Patch(color="magenta"))
    plt.legend(legends, [r'$12.75<M_{vir}<13.75$',r'$12.25<M_{vir}<12.75$',r'$11.75<M_{vir}<12.25$',r'$11.25<M_{vir}<11.75$'], loc=1, fontsize=12)
    plt.show()
示例#13
0
def Mclast():
    fig = plt.figure(1, figsize=(6,9))
    gs = gridspec.GridSpec(2,1,height_ratios=[4,1])
    ax = plt.subplot(gs[0])
    mvir, mclast, mratio = ioformat.rcol(fwind, [1,5,14], linestart=1)
    print("Mvir Range: ", min(mvir), max(mvir))
    x, y = [], []
    for i in range(len(mclast)):
        if(mclast[i] > mclast_cut and mratio[i] < 20.0):
            x.append(mvir[i])
            y.append(mclast[i])
    xbins = linspace(11.0, 13.5, 30)
    ybins = linspace(0.05, 1.0, 40)
    xgrid, ygrid = meshgrid(xbins, ybins)
    z, edx, edy = histogram2d(x, y, bins=[xbins,ybins])
    z = z.T + 0.01
    zf = ndimage.gaussian_filter(z, sigma=1.0, order=0)
    cont = ax.contour(xbins[1:], ybins[1:], zf, colors="red")
    #plt.pcolor(xgrid, ygrid, z, cmap="Purples", norm=LogNorm(vmin=z.min(), vmax=z.max()))
    ax.pcolor(xgrid, ygrid, z, cmap="Purples")
    setp(ax.get_xticklabels(), visible=False)
    ax.set_ylabel("Mc (Rejoin)")
    plt.title(modelname+", Z~1.0")
    ax = plt.subplot(gs[1])
    plt.subplots_adjust(hspace=0.0, top=0.9, bottom=0.15)
    hist1, bins = histogram(mvir, bins=linspace(11.0,13.5,30))
    hist2, bins = histogram(x, bins=linspace(11.0,13.5,30))
    hist = []
    for i in range(len(hist1)):
        if(hist1[i] > 0): hist.append(float(hist2[i])/float(hist1[i]))
        else: hist.append(0.0)
    #width=0.8*(bins[1]-bins[0])
    center = (bins[:-1] + bins[1:]) / 2.0
    ax.plot(center, hist, "b.-")
    ax.set_ylim(0.0, 1.0)
    ax.set_xlabel("Mvir")
    ax.set_ylabel("f_rej")
    plt.show()
示例#14
0
def load_files():
    global pids
    global mass
    global hid
    global attrs
    global haloes

    print("Loading Files... ")
    hf = h5py.File(snapname, "r")

    header = hf['Header']
    attrs = header.attrs
    attrs.keys()
    gp = hf['PartType0']
    gp.keys()
    pids = gp['ParticleIDs']
    mass = gp['Masses']

    hid = ioformat.rcol(sogrpname, [0], [0])
    haloes = genfromtxt(sovcircname,
                        usecols=(1, 2, 6, 7),
                        names=['Mvir', 'Rvir', 'Msub', 'Rsub'],
                        skip_header=1)
示例#15
0
mlra = 4.46e-15 * 1.e7**2 / (rho0 * r_c**2)
print log(mlra * 50. * ac.myr)

# https://www.dropbox.com/home/Ion%20Analysis
# Very crudely read from J'Neil's absorption images
# x300v1000:
# OVI 13 - 14;
# HI  13 - 18
# CIV 15 - 17
# x300v1700:
# HI  17 - 18
# CIV 15 - 16
# OVI 13 - 14

ionfile = "/scratch/shuiyao/specexbin/ionfiles/specions_i9_gizmo.dat"
fmass = ioformat.rcol(ionfile, [4])

n_c = 1.0
rho_c = n_c * pc.mh * 0.62
r_c = 100 * ac.pc
M_c = 4. / 3. * pi * r_c**3 * rho_c
Z = Zsolar = 0.0122
print "Mc = ", M_c / ac.msolar
# On average:
N_c = 4. / 3. * n_c * pi * r_c
print "N_c (avg.) = ", N_c
# Scale: n_c ~ r_c ^ (-3), N_c ~ n_c * r_c ~ r_c ^ (-2)

print "N_c (peak) ~ N_c (avg.) * 25."

from ionfrac import IonFrac
示例#16
0

zmin = [2.0, 1.0]
MMIN, MMAX = 10.5, 13.0
NMBINS = 15
fig = plt.figure(1, figsize=(8, 7))
gs = gridspec.GridSpec(3, 2, height_ratios=[4, 1, 1])
patterns = []
for zi in [0, 1]:
    ax1 = plt.subplot(gs[zi])
    ax2 = plt.subplot(gs[zi + 2])
    ax3 = plt.subplot(gs[zi + 4])
    for fi, fwind in enumerate(flist[zi]):
        if (DO_TMAX):
            fwindtmax = fwind[:-3] + "_tmax." + fwind[-2:]
            tmaxs = ioformat.rcol(fwindtmax, [0])
        x, y, xhot, xhotsub, yhot, yhotsub = [], [], [], [], [], []
        # ai, af, msi(FoF), msf(FoF), mstar(SKID), mvir(SO), flag(sopar)
        ai, af, mstar, mvir, flag = ioformat.rcol(fwind, [1, 2, 5, 6, 8], [4],
                                                  linestart=1)
        zs = 1. / array(ai) - 1.
        trec = calc_trec(ai, af, True)
        tlim = calc_trec([1. / (zmin[zi] + 1.)], [0.9999], True)
        for i in range(len(trec)):
            if (mvir[i] > MMIN and flag[i] == 1):
                # WARNING: In some earlier version, there's a bug that for ungrouped particles, mvir = -inf but mstar = mstar[-1]. So make sure use mvir[i] > MMIN is fine, but using mstar[i] would not be fine.
                x.append(mvir[i])
                y.append(trec[i])
                if (DO_TMAX):
                    if (tmaxs[i] > 5.5):  # Winds that became hot
                        xhot.append(mvir[i])
示例#17
0
    elif (REDSHIFT == 1.0):
        AMIN, AMAX, odir = "0.500", amaxs[2], FBASE + "z1/"
    elif (REDSHIFT == 0.2):
        AMIN, AMAX, odir = "0.833333", amaxs[3], FBASE + "z0/"
    else:
        print(errormsg)
        sys.exit(1)
    if (os.path.exists(odir) == 0):
        print(errormsg)
        print("Error: ", FBASE, "not found. Exit.")
        sys.exit(1)
    print("Ncpu = ", NCPU)
    print("Directory: ", odir)

widfile = odir + "wid.dat"
wids = ioformat.rcol(widfile, [0], [0])
wids = set(wids)  # Enabling fast search with wid in wids
print(len(wids), "Wind IDs read...")

tstart = time.time()
tmid = tstart
for icpu in range(NCPU):
    print("Search File #", icpu, " | t = ", time.time() - tmid)
    tmid = time.time()
    ifile = open(FBASE + "phews." + str(icpu), "r")
    ofile = open(odir + "phews." + str(icpu), "w")
    ifile.readline()
    for line in ifile:
        spt = line.split()
        if (spt[0] > "1"): continue  # a > 1, never should happen
        if (spt[0] < AMIN): continue  # a < amin, Not selected
示例#18
0
# mstars = array(mstars)
# hostmask = (halos['Msub'] > 0) & (mstars > 0)
# mstars = mstars[hostmask]
# msubs = log10(halos[hostmask]['Msub'] / HPARAM)
# # mfits = interp1d(msubs[::10], mstars[::10], kind="quadratic")
# mask = (msubs > 11.0) & (mstars > 8.0)
# msubs = msubs[mask]
# mstars = mstars[mask]
# coefs = polyfit(msubs, mstars, 2)
# x = linspace(10., 13.5, 100)
# y = polyval(coefs, x)

# plt.plot(msubs[::3], mstars[::3], "b.", alpha=0.4)
# plt.plot(x, y, "r-")

sohid = ioformat.rcol(sogrpname, [0], [0], linestart=1)

hf = h5py.File(snapname, "r")
print("File Read.")

header = hf['Header']  # Read the header
Ngas = header.attrs['NumPart_Total'][0]
Ndark = header.attrs['NumPart_Total'][1]
Nstar = header.attrs['NumPart_Total'][4]
gp = hf['PartType0']  # Gas Particles
gp.keys()

print("Reading HDF5: ", snapname)
# Get gas properties
mass = array(gp['Masses'])  # Mass
u = array(gp['InternalEnergy'])  # Temperature in K
示例#19
0
def V25Vc(fname, ax1, ax2, titlename, simname):
    import cosmology
    if (FFORMAT == "OLD"):
        mvir, rvir, vinit, v25 = ioformat.rcol(fname, [1, 2, 3, 4],
                                               linestart=1)
    else:
        mvir, rvir, vinit, v25, rreturn = ioformat.rcol(fname, [1, 2, 3, 4, 5],
                                                        linestart=1)
    # vc = sqrt(pc.G * 10.**array(mvir) * ac.msolar / (array(rvir) * ac.kpc)) / 1.e5
    vc = []
    for i in range(len(mvir)):
        vc.append(cosmology.Vc(10.**mvir[i] * ac.msolar, REDSHIFT) / 1.e5)
    print("Mvir Range: ", min(mvir), max(mvir))
    print("Vc Range: ", min(vc), max(vc))
    # ax1.plot(vc[::100], v25[::100], "b.")
    # ax1.plot(vc2, v252, ".", color="teal")
    if (FFORMAT == "NEW"):
        # Rreturn < 0.25 Rvir!
        for i in range(len(v25)):
            if (0.0 < rreturn[i] < 0.25 * rvir[i]):
                v25[i] = -1
    plotmedian(vc, v25, "cyan", nbins=15, ax=ax1, xmin=XMIN, xmax=XMAX)
    plotmedian(vc, vinit, "red", nbins=15, ax=ax1, xmin=XMIN, xmax=XMAX)
    xbins = logspace(log10(XMIN), log10(XMAX), (int)(XBINS))
    ybins = logspace(log10(YMIN), log10(YMAX), (int)(YBINS))
    xgrid, ygrid = meshgrid(xbins, ybins)
    z, edx, edy = histogram2d(vc, v25, bins=[xbins, ybins])
    z = z + 0.1
    z = z.T
    zf = ndimage.gaussian_filter(z, sigma=0.3, order=0)
    ax1.pcolor(xbins[1:],
               ybins[1:],
               zf,
               cmap=plt.cm.Purples,
               norm=LogNorm(vmin=z.min(), vmax=z.max()))

    # Lines from Muratov 2015
    xline = linspace(XMIN, XMAX, 100)
    y50line = 0.854 * xline**1.12
    y95line = 1.85 * xline**1.10
    xsig16 = array([50., 85.])
    ysig16 = 0.7 * xsig16**1.60
    ax1.plot(xline, y50line, "k-")
    ax1.plot(xline, y95line, "k--")
    # ax1.plot(xsig16, ysig16, "g-")

    # Figure captions
    ax1.set_xlim(XMIN, XMAX)
    ax1.set_ylim(YMIN, YMAX)
    ax1.set_title(titlename)
    ax1.text(0.20, 0.02, simname, fontsize=12, transform=ax1.transAxes)
    ax1.set_xscale("log")
    ax1.set_yscale("log")
    ax1.legend([r"$V_{25}$", r"$V_{init}$"], fontsize=16)
    fig.subplots_adjust(hspace=0)
    setp(ax1.get_xticklabels(), visible=False)

    # Count the fraction that makes NOT to R25
    FRAC_STEP = 25.
    frac = [0.] * int(XMAX / FRAC_STEP)
    Ncount = [0.] * int(XMAX / FRAC_STEP)
    x = linspace(10., XMAX, int(XMAX / FRAC_STEP)) - 5.
    for i in range(len(vc)):
        idx = int(vc[i] / FRAC_STEP)
        if (idx > int(XMAX / FRAC_STEP) - 1):
            idx = int(XMAX / FRAC_STEP) - 1
        Ncount[idx] += 1.
        if (v25[i] != -1):
            frac[idx] += 1.
    Ntot = sum(Ncount)
    for i in range(len(frac)):
        if (Ncount[i] > 0.):
            frac[i] = frac[i] / Ncount[i]
    ax2.plot(x, frac, "k.-")
    print("Ncount = ", Ncount)
    print("frac = ", frac)
    Ncount_Norm = 2. * max(Ncount) / Ntot
    ax2.bar(x, (array(Ncount) / Ntot) / Ncount_Norm,
            align="center",
            width=0.8 * (x[1] - x[0]),
            color="grey")
    ax2.set_xlim(XMIN, XMAX)
    ax2.set_ylim(0., 1.1)
    ax2.set_xscale("log")
    ax2.yaxis.set_ticks([0., 0.2, 0.4, 0.6, 0.8, 1.0])
    ax2.axhline(1.0, XMIN, XMAX, color="grey", linestyle=":")
    ax2.set_xlabel(r"$V_c [km/s]$")
示例#20
0
                    xerr=Merr[0],
                    yerr=0.05,
                    uplims=True,
                    color="black",
                    fmt='o')
    # axs[1].plot(Merb, Zmid-OHSOLAR-0.3, color="purple", linestyle="-", linewidth=2)
    axs[1].text(0.02,
                0.02,
                "Erb+ (2006)",
                transform=axs[1].transAxes,
                fontsize=12,
                color="black")
if PLOT_T04 == True:
    ax = axs[3]
    Mt04, Z16t04, Z50t04, Z84t04 = ioformat.rcol("../mzr/tremonti04.dat",
                                                 [0, 2, 3, 4],
                                                 linestart=1)
    Z16t04 = array(Z16t04) - OHSOLAR
    Z50t04 = array(Z50t04) - OHSOLAR
    Z84t04 = array(Z84t04) - OHSOLAR
    p, = ax.plot(Mt04, Z50t04, color="black", linestyle="-")
    # ax.plot(Mt04, Z50t04-0.3, color="purple", linestyle="-", linewidth=2)
    ax.plot(Mt04, Z16t04, color="black", linestyle="--")
    ax.plot(Mt04, Z84t04, color="black", linestyle="--")
    plist.append(p)
    axs[3].text(0.02,
                0.02,
                "Tremonti+ (2004)",
                transform=axs[3].transAxes,
                fontsize=12,
                color="black")
示例#21
0
import ioformat
a = ioformat.rcol("./outputs_z108.txt", [0])

fout = open("redshifts.txt", "w")
fout.write("#snapnum a zred\n")
for i in range(len(a)):
    z = 1. / a[i] - 1.
    line = "%3d %7.5f %7.5f\n" % (i, a[i], z)
    fout.write(line)
fout.close()

print("DONE.")
示例#22
0
def V25Vc(fname=fwindsinfo):
    import ioformat
    from matplotlib import gridspec

    fig = plt.figure(1, figsize=(8, 8))
    gs = gridspec.GridSpec(2, 1, height_ratios=[4, 1])
    ax1 = plt.subplot(gs[0])
    ax2 = plt.subplot(gs[1])
    mvir, rvir, vinit, v25, rreturn = ioformat.rcol(fname, [1, 2, 3, 4, 5],
                                                    linestart=1)
    vc = sqrt(pc.G * 10.**array(mvir) * ac.msolar /
              (array(rvir) * ac.kpc)) / 1.e5
    print("Mvir Range: ", min(mvir), max(mvir))
    print("Vc Range: ", min(vc), max(vc))
    # ax1.plot(vc[::100], v25[::100], "b.")
    # ax1.plot(vc2, v252, ".", color="teal")
    # Rreturn < 0.25 Rvir!
    for i in range(len(v25)):
        if (0.0 < rreturn[i] < 0.25 * rvir[i]):
            v25[i] = -1
    plotmedian(vc, v25, "blue", nbins=15, ax=ax1, xmin=XMIN, xmax=XMAX)
    plotmedian(vc, vinit, "red", nbins=15, ax=ax1, xmin=XMIN, xmax=XMAX)
    xbins = logspace(log10(XMIN), log10(XMAX), XBINS)
    ybins = logspace(log10(YMIN), log10(YMAX), YBINS)
    xgrid, ygrid = meshgrid(xbins, ybins)
    z, edx, edy = histogram2d(vc, v25, bins=[xbins, ybins])
    z = z + 0.1
    z = z.T
    zf = ndimage.gaussian_filter(z, sigma=0.3, order=0)
    # cont = ax1.contour(xbins[1:], ybins[1:], zf, 10, colors="black")
    # cont = ax1.contourf(xbins[1:], ybins[1:], zf, CONTLEVELS, cmap=plt.cm.Purples, norm=LogNorm(vmin=z.min(), vmax=z.max()))
    # cont = ax1.contour(xbins[1:], ybins[1:], zf, CONTLEVELS, cmap=plt.cm.Reds, norm=LogNorm(vmin=z.min(), vmax=z.max()))
    # cont = ax1.contourf(xbins[1:], ybins[1:], zf, 6, cmap=plt.cm.Purples, vmin=z.min(), vmax=z.max())
    # ax1.plot(vc[::200], v25[::200], "k.", markersize=2)
    ax1.pcolor(xbins[1:],
               ybins[1:],
               zf,
               cmap=plt.cm.Purples,
               norm=LogNorm(vmin=z.min(), vmax=z.max()))
    xline = linspace(XMIN, XMAX, 100)
    y50line = 0.854 * xline**1.12
    y95line = 1.85 * xline**1.10
    ax1.plot(xline, y50line, "k-")
    ax1.plot(xline, y95line, "k--")
    ax2.set_xlabel(r"$V_c [km/s]$")
    ax1.set_ylabel(r"$V_{25} [km/s]$")
    ax1.set_xlim(XMIN, XMAX)
    ax1.set_ylim(YMIN, YMAX)
    # ax1.set_ylim(9.,12.)
    ax1.set_title(modelname + ", Z = " + str(REDSHIFT))
    ax1.set_xscale("log")
    ax1.set_yscale("log")
    ax1.legend([r"$V_{25}$", r"$V_{init}$"], fontsize=16)
    fig.subplots_adjust(hspace=0)
    setp(ax1.get_xticklabels(), visible=False)
    # Count the fraction that makes NOT to R25
    FRAC_STEP = 25.
    frac = [0.] * int(XMAX / FRAC_STEP)
    Ncount = [0.] * int(XMAX / FRAC_STEP)
    x = linspace(10., XMAX, int(XMAX / FRAC_STEP)) - 5.
    for i in range(len(vc)):
        idx = int(vc[i] / FRAC_STEP)
        if (idx > int(XMAX / FRAC_STEP) - 1):
            idx = int(XMAX / FRAC_STEP) - 1
        Ncount[idx] += 1.
        if (v25[i] != -1):
            frac[idx] += 1.
        # if(FFORMAT == "NEW"):
        #     if(0. < rreturn[i] < 0.25 * rvir[i]):
        #         frac[idx] -= 1. # Rreturn < 0.25 Rvir!
    Ntot = sum(Ncount)
    for i in range(len(frac)):
        if (Ncount[i] > 0.):
            frac[i] = frac[i] / Ncount[i]
    ax2.plot(x, frac, "k.-")
    # ax2.plot(x, array(Ncount)/Ntot, "-", color="teal")
    Ncount_Norm = 2. * max(Ncount) / Ntot
    ax2.bar(x, (array(Ncount) / Ntot) / Ncount_Norm,
            align="center",
            width=0.8 * (x[1] - x[0]),
            color="grey")
    ax2.set_xlim(XMIN, XMAX)
    ax2.set_ylim(0., 1.1)
    ax2.set_xscale("log")
    ax2.xaxis.set_ticks([XMIN, 50., 100., 200., XMAX])
    ax2.xaxis.set_ticklabels([str(XMIN), "50", "100", "200", str(XMAX)])
    ax2.yaxis.set_ticks([0., 0.2, 0.4, 0.6, 0.8])
    # ax2.set_ylabel(r"$f(R_{25} < R_{return})$")
    ax2.set_ylabel(r"$f(R_{25} < R_{recouple})$")
    plt.savefig("/scratch/shuiyao/figures/tmp.pdf")
    plt.show()
示例#23
0
        frac_red(x, y)
    x, y = bin1d.subsample(x, y, nonzero=True)
    s = bin1d.bin1d(x, y, nbins=40, logbins=True, bounds=0.84)
    xline, yline = s.cen, s.median
    uline, lline = s.ubound, s.lbound
    f.close()
    p, = axs[i].plot(log10(array(xline)), yline, "-", color="magenta") # Draw line for all models
    if(i == 0):
        plist.append(p)

# axs[2].legend([plist[0], plist[1], plist[-1], pflist[0], pflist[1]], ["ezwDESPH","RefHres","Ref", "ezwDESPH","RefHres"], prop={'size':12}, loc=1)
# axs[2].legend([plist[0], plist[1], plist[-1], pflist[0]], ["ezwDESPH","RefHres","Ref", "RefHres"], prop={'size':12}, loc=1)
axs[2].legend([plist[0], plist[1], plist[-1], pflist[0]], lgds, prop={'size':12}, loc=1)

if PLOT_T04 ==True:
    Mt04, Z16t04, Z50t04, Z84t04 = ioformat.rcol("../mzr/tremonti04.dat", [0,2,3,4], linestart=1)
    Z16t04 = array(Z16t04) - OHSOLAR
    Z50t04 = array(Z50t04) - OHSOLAR
    Z84t04 = array(Z84t04) - OHSOLAR
    p, = ax.plot(Mt04, Z50t04, color="green", linestyle="-")
    ax.plot(Mt04, Z16t04, color="green", linestyle="--")
    ax.plot(Mt04, Z84t04, color="green", linestyle="--")
    plist.append(p)
    axs[3].text(0.02, 0.02, "Tremonti+ (2004)", transform=axs[3].transAxes, fontsize=12, color="green")    

if PLOT_P14 == True:
    # Mp14, F50p14, F16p14, F84p14 = ioformat.rcol("../fgas/peeples14.dat", [0,1,2,3], linestart=5)
    from numpy import loadtxt
    Mp14, F50p14, F16p14, F84p14 = loadtxt("../fgas/peeples14.dat", unpack=True)    
    F50p14 = array(F50p14) / (1. + array(F50p14))
    F16p14 = array(F16p14) / (1. + array(F16p14))
示例#24
0
        phib.append(log10(phi[i] / 0.7**3))
        # phib.append(log10(phi[i]))
ms = fm18(mhb)

fig, ax = plt.subplots(1, 1, figsize=(6, 6))
ax.plot(ms, phib, "k--")

if (REDSHIFT == 1.0):
    gsmfs_tomczak14 = [ \
        "../REFERENCES/tomczak14/t14_z0.2_z0.5.dat",\
        "../REFERENCES/tomczak14/t14c_z0.75_z1.25.dat",\
        "../REFERENCES/tomczak14/t14c_z1.5_z2.5.dat",\
    ]
    colors = ["green", "red", "blue"]
    i = 1
    ms, phi, e1, e2 = ioformat.rcol(gsmfs_tomczak14[i], [0, 1, 2, 3],
                                    linestart=3)
    lower = -array(e2)
    upper = array(e1)
    ax.errorbar(ms, phi, yerr=[lower, upper], color=colors[i], fmt='o')

if (REDSHIFT == 0.0):
    gsmf_baldry12 = "../REFERENCES/Baldry12/gsmf_baldry12_z0.dat"
    ms, phi, err = ioformat.rcol(gsmf_baldry12, [0, 2, 3], linestart=3)
    phi = array(phi) / 1.e3
    err = array(err) / 1.e3
    lower = log10(phi) - log10(phi - err)
    upper = log10(phi + err) - log10(phi)
    phi = log10(phi)
    ax.errorbar(ms, phi, yerr=[lower, upper], color="black", fmt='o')

plt.show()
示例#25
0
unit_mass = 4.3e5 * (BOXSIZE / 25000.)**3
XTOL = 0.02
MTOL = 1.0
fbase = "/scratch/shuiyao/data/"
model = "l12n144-phew-movie"
gid = 1477

foutname = "progen_" + ("00000" + str(gid))[-5:]
fout = open(foutname, "w")

snapi = snapend
dtime = tcosmic(ascales[snapi]) - tcosmic(ascales[snapi - 1])
dtime = dtime * ac.yr / unit_Time
snapstr = ("000" + str(snapi))[-3:]
fgalname = fbase + model + "/gal_z" + snapstr + ".stat"
mgal, xgal, ygal, zgal, vxgal, vygal, vzgal = ioformat.rcol(
    fgalname, [4, 18, 19, 20, 15, 16, 17])
idx = gid - 1
xprev = xgal[idx] - vxgal[idx] * dtime
yprev = ygal[idx] - vygal[idx] * dtime
zprev = zgal[idx] - vzgal[idx] * dtime
mprev = mgal[idx]
fout.write("%5d %7.5f %7.5f %7.5f %6.3f\n" % (idx, xprev, yprev, zprev,\
            log10(mprev * unit_mass * 1.e10 / 0.7)))

mgalz0 = log10(mprev * unit_mass * 1.e10 / 0.7)

for snapi in range(snapbeg, snapend)[::-1]:
    dtime = tcosmic(ascales[snapi]) - tcosmic(ascales[snapi - 1])
    dtime = dtime * ac.yr / unit_Time
    snapstr = ("000" + str(snapi))[-3:]
    fgalname = fbase + model + "/gal_z" + snapstr + ".stat"
示例#26
0
from numpy import genfromtxt, array, exp, mean, median
import ioformat
import matplotlib.pyplot as plt
from math import factorial

f = "example.wind"
h, rc = ioformat.rcol(f, [5, 6])
ratio = array(rc) / array(h)
y = (ratio**2) * 1000.0


def p(n, y):
    return y**n * exp(-y) / (float)(factorial(n))


P0 = p(0, y)
P1 = p(1, y)
P2 = p(2, y)

# P(x) = y^xe^-y/x!, y = mean(x)
示例#27
0
                     "--",
                     color=clrs_t[2])
     axs[panel].plot(tabref['Ncen'] + Ncorr,
                     rcumsum(tabref['t25y']) / ncorr,
                     "--",
                     color=clrs_t[3])
     axs[panel].text(0.4,
                     0.85,
                     ionname,
                     fontsize=12,
                     transform=axs[panel].transAxes)
 else:
     print "Creating New Files."
     fout = open(foutname, "w")
     fout.write("#Ncen t90x t75x t50x t25x t90y t75y t50y t25y\n")
     ioncds = ioformat.rcol(fnamex, cols, separator=",", linestart=1)
     hx = []
     for ioni in range(len(ioncds)):  # t90 t75 t50 t25
         ioncds[ioni] = convert_list(ioncds[ioni])
         hist, edges = histogram(ioncds[ioni], bins=nbins)
         hx.append(hist)
     ioncds = ioformat.rcol(fnamey, cols, separator=",", linestart=1)
     hy = []
     for ioni in range(len(ioncds)):  # t90 t75 t50 t25
         ioncds[ioni] = convert_list(ioncds[ioni])
         hist, edges = histogram(ioncds[ioni], bins=nbins)
         hy.append(hist)
     cen = 0.5 * (edges[1:] + edges[:-1])
     for i in range(len(cen)):
         fout.write("%5.2f %6d %6d %6d %6d %6d %6d %6d %6d\n" % \
                    (cen[i], hx[0][i], hx[1][i], hx[2][i], hx[3][i], \
示例#28
0
def convert_list(lst):
    lst = array(lst)
    lst = lst[lst > 0]
    lst = log10(lst)
    return lst

# 1   2   3  4   5      6    7    8     9    10
# OVI CIV NV CII NeVIII CIII MgII SiIII SiIV HI
ionnames = ["XX","OVI","CIV","NV","CII","NeVIII","CIII","MgII","SiIII","SiIV","HI"]
ionorder = [-1, 5, 3, -1, -1, 6, 2, 7, -1, 8, 0]

# cols = array([1, 5, 10]) # High-ions
# cols = array([2, 6, 7, 9, 10])

cols = array([1, 2, 5, 6, 7, 9, 10])
tab = ioformat.rcol(fnamey, cols + offset, separator=",", linestart=1)
for i in range(len(tab)): tab[i] = array(tab[i])
idxs = (tab[-1] > 1.e16)
for i in range(len(tab)): tab[i] = log10(tab[i][idxs])

# Strong Correlations
# HI: MgII, CIII       2
# OVI: NeVIII          1
# CIV: SiIV            1
# No/Weak Correlations
# HI: CIV, OVI         2
# CIV: CIII, OVI       2

from pltastro import frame, draw
frm = frame.multi(4,2)
pars = frm.params
示例#29
0
import matplotlib.pyplot as plt
from numpy import genfromtxt, array, log10, linspace
import config_mpl
import ioformat

f1 = "/proj/shuiyao/l25n144-phew-rcloud/WINDS/winds.45"
f2 = "/proj/shuiyao/l25n288-phew-m5/WINDS.red/winds.45"

# f1 = "/proj/shuiyao/P50N288s/p50n288fiducial/WINDS/winds.3"
# f2 = "/proj/shuiyao/p50n576fi/WINDS/winds.3"

# tab1 = genfromtxt(f1, names=True)
# tab2 = genfromtxt(f2, names=True)

a1, sig1 = ioformat.rcol(f1, [0,3], linestart=1)
a2, sig2 = ioformat.rcol(f2, [0,3], linestart=1)

# step = 10
# plt.plot(tab1['a'][::step], tab1['Siggal'][::step], "b.", alpha=0.2)
# plt.plot(tab2['a'][::step], tab2['Siggal'][::step], "r.", alpha=0.2)

# plt.hist(tab1['Siggal'], bins=linspace(0., 300., 50), color="blue", histtype="step")
# plt.hist(tab2['Siggal'][::8], bins=linspace(0., 300., 50), color="red", histtype="step")

a1, a2 = array(a1), array(a2)
sig1, sig2 = array(sig1), array(sig2)
sig1b = sig1[a1 > 0.5]
sig2b = sig2[a2 > 0.5]

plt.hist(sig1, bins=linspace(0., 150., 50), color="blue", histtype="step")
plt.hist(sig2[::4], bins=linspace(0., 150., 50), color="red", histtype="step")
示例#30
0

def load_central_stars(fname):
    stars = read_starinfo(fname)
    nstars = len(stars)
    stars = stars[stars['GID'] == stars['HID']]  # Only central galaxies
    print "Stars from central galaxies: %d/%d (%4.1f%%)" % \
        (len(stars), nstars, (float)(len(stars)) / (float)(nstars) * 100.)
    return stars


galsm11 = ("m11", 11.0, 11.5)
galsm12 = ("m12", 11.85, 12.15)
galsm13 = ("m13", 12.85, 13.15)
galss = [galsm11, galsm12, galsm13]
redz = ioformat.rcol("redshifts.txt", [0])


def show_lineage_of_selected_galaxies(modelname, gal_selection, ax=None):
    name, mmin, mmax = gal_selection[0], gal_selection[1], gal_selection[2]
    # folder = "/scratch/shuiyao/scidata/mergertree/"+modelname+"_old/"
    folder = "/scratch/shuiyao/scidata/mergertree/" + modelname + "/"
    fin = open(folder + "lineages_" + name + ".dat", "r")
    xs = log10(array(redz) + 1)
    xarr, yarr = [], []
    for line in fin:
        spt = line.split()[1:]
        mstars = array(spt, dtype='float')[::-1]
        for i in range(len(mstars)):
            xarr.append(xs[i])
            yarr.append(mstars[i])