예제 #1
0
def main(N, t_end, z, C="SeBa", plot=False):
    if "SeBa" not in C:
        x_label = "T [K]"
        y_label = "L [L$_\odot$]"
        figure = single_frame(x_label, y_label, logx=True, logy=True, xsize=14, ysize=10)
        color = get_distinct(4)
        pyplot.xlim(1.e+5, 1.e+3)
        pyplot.ylim(1.e-4, 1.e+4)
        filename = "Stellar_"+"SeBa"+".h5"
        plot_HRD(filename, color[0])
        filename = "Stellar_"+C+".h5"
        plot_HRD(filename, color[1])
        pyplot.savefig("HRD_N3000at4500Myr")
    elif not plot:
        numpy.random.seed(1)
        masses = new_salpeter_mass_distribution(N)
        stars = Particles(mass=masses)
        get_stellar_temperature_and_luminosity(stars, C=C, z=z, t_end=t_end, write=True)
    else:
        x_label = "T [K]"
        y_label = "L [L$_\odot$]"
        figure = single_frame(x_label, y_label, logx=True, logy=True, xsize=14, ysize=10)
        color = get_distinct(4)
        pyplot.xlim(1.e+5, 1.e+3)
        pyplot.ylim(1.e-4, 1.e+4)
        filename = "Stellar_"+C+".h5"
        plot_HRD(filename, color[0])
#        pyplot.show()
        pyplot.savefig("HRD_N3000at4500Myr")
예제 #2
0
def plot_tracks(temperatures_original, luminosities_original,
                temperatures_helium, luminosities_helium):

    x_label = "T [K]"
    y_label = "L [$L_\odot$]"
    figure = single_frame(x_label, y_label, logx=True, logy=True,
                          xsize=14, ysize=10)
    colors = get_distinct(2)
    
    loglog(temperatures_original, luminosities_original, label='progenitor',
           c=colors[0])
    loglog(temperatures_helium, luminosities_helium, label='helium star',
           c=colors[1])
    scatter(temperatures_helium[-1], luminosities_helium[-1], marker='*',
            s=400, c=colors[1])
    xlabel('Effective Temperature')
    ylabel('Luminosity')
    pyplot.xlim(1.0e5, 4000)
    pyplot.ylim(1.0,1.0e5)
    pyplot.legend(loc=4, fontsize=24)

    save_file = 'HertzsprungRussel_HeliumStar.png'
    pyplot.savefig(save_file)
    print('\nSaved figure in file', save_file,'\n')
    pyplot.show()
def plot_XiTau(filename, nj):

    from matplotlib import pyplot
    colors = get_distinct(4)
    figure = pyplot.figure(figsize=(16, 12))
    ax = pyplot.gca()
    ax.minorticks_on() # switch on the minor ticks
    ax.locator_params(nbins=3)
    
    t, a_out, a_new, e_out = retrieve_semi_major_axis_evolution(filename, nj)
    from matplotlib import pyplot
    #pyplot.plot(t.value_in(units.yr), e_out, c=colors[0])
    pyplot.plot(t.value_in(units.yr), a_out.value_in(units.AU), c=colors[0])
    pyplot.plot(t.value_in(units.yr), a_new.value_in(units.AU), c=colors[1])

    t, a_out, a_new, e_out = retrieve_semi_major_axis_evolution(filename, 4.0)
    pyplot.plot(t.value_in(units.yr), a_new.value_in(units.AU), c=colors[2], lw=2)
    t, a_out, a_new, e_out = retrieve_semi_major_axis_evolution(filename, 8.0)
    pyplot.plot(t.value_in(units.yr), a_new.value_in(units.AU), c=colors[3], lw=2)
    
    pyplot.xlim(0, 12)
    pyplot.xlabel("t [year]")
    pyplot.ylabel("$a_{outer}$ [AU]")
    pyplot.savefig("fig_XiTau_orbital_separation")
    pyplot.show()
예제 #4
0
def  plot_galaxy_and_stars(galaxy, stars):
    
    colors = get_distinct(3)
    single_frame('X [pc]', 'Y [pc]')
    xlim = 60
    pyplot.xlim(-xlim, xlim)
    pyplot.ylim(-xlim, xlim)
    ax = pyplot.gca()

    import numpy as np
    import pandas as pd
    from scipy import stats, integrate
    import matplotlib.pyplot as plt
    import seaborn as sns
    sns.set(color_codes=True)

    p = galaxy.select(lambda x: x<60|units.parsec,["x"])
    p = p.select(lambda x: x>-60|units.parsec,["x"])
    p = p.select(lambda y: y<60|units.parsec,["y"])
    p = p.select(lambda y: y>-60|units.parsec,["y"])
    x = p.x.value_in(units.parsec)
    y = p.y.value_in(units.parsec)
    sns.kdeplot(x, y, ax=ax)
    m = 100*numpy.sqrt(stars.mass/stars.mass.max())
    pyplot.scatter(stars.x.value_in(units.parsec), stars.y.value_in(units.parsec), c=colors[0], s=m, lw=0)
#    pyplot.show()
    pyplot.savefig("Fujii_Comparison_Figure")
def main(M, z, output_filename):
    numpy.random.seed(31415)
    x_label = "$R$ [R$_\odot$]"
    y_label = "$\\rho$ [g/cm$^{3}$]"
    fig, ax = figure_frame(x_label, y_label, xsize=12, ysize=8)
    cols = get_distinct(3)

    r, rho = get_density_profile(EVtwin, M, z)
    pyplot.plot(r.value_in(units.RSun),
                rho.value_in(units.g/units.cm**3),
                label="EVtwin", c=cols[0])
    r, rho = get_density_profile(MESA, M, z)
    pyplot.plot(r.value_in(units.RSun),
                rho.value_in(units.g/units.cm**3),
                label="MESA", c=cols[1])

    # Run the merger code.
    
    r, rho = merge_two_stars(0.5*M, 0.5*M, 1|units.yr)
    
    pyplot.plot(r.value_in(units.RSun),
                rho.value_in(units.g/units.cm**3),
                label="MESA", c=cols[2])
    pyplot.semilogy()
    
    if output_filename is not None:
        pyplot.savefig(output_filename)
        print '\nSaved figure in file', output_filename,'\n'
    else:
        output_filename = 'merger_stellar_density_profile.png'
        pyplot.savefig(output_filename)
        print '\nSaved figure in file', output_filename,'\n'
        pyplot.show()
def main():
    x_label = "$log_{10}[(t_{end}-t)/t_{MS}]$"
    y_label = "$\zeta$"
    figure = single_frame(x_label, y_label, logx=False, logy=False, xsize=14, ysize=10)
    color = get_distinct(12)

    pyplot.text(-2.2, 0.8, "giant branch")
    pyplot.text(-0.1, 0.8, "main sequence")
    pyplot.xlim(0.5, -4.)
    pyplot.ylim(-0.6, 1.2)
    fii = 0
    ti=0
    for dmi in dmdt:
        for fi in filenames:
            f = open(fi)
            for line in f:
                t, z, tms = process_file(f, dmi)
                #print t, z, tms
                for i in range(len(t)):
                    if z[i]<0:
                        ti = i
                        break
                for i in range(len(t)):
                    t[i] = numpy.log10((t[-1]-t[i])/tms)
                #            pyplot.scatter(t, z)
                pyplot.plot(t[ti:], z[ti:], c=color[fii], ls=ls[fii], lw=lw[fii])
            f.close()
        fii += 1
    pyplot.show()
def  plot_galaxy_and_stars(galaxy, stars):
    
    colors = get_distinct(3)
    single_frame('X [kpc]', 'Y [kpc]')
    xlim = 10
    pyplot.xlim(-xlim, xlim)
    pyplot.ylim(-xlim, xlim)
    ax = pyplot.gca()

    import numpy as np
    import pandas as pd
    from scipy import stats, integrate
    import matplotlib.pyplot as plt
    import seaborn as sns
    sns.set(color_codes=True)

    lim = 10|units.kpc
    p = galaxy.select(lambda x: x<lim,["x"])
    p = p.select(lambda x: x>-lim,["x"])
    p = p.select(lambda y: y<lim,["y"])
    p = p.select(lambda y: y>-lim,["y"])
    p = p.select(lambda r: r.length()>5|units.kpc,["position"])
    x = p.x.value_in(units.kpc)
    y = p.y.value_in(units.kpc)
    sns.kdeplot(x, y, ax=ax, shade=True, n_levels=20, shade_lowest=False)
    m = 100*numpy.sqrt(stars.mass/stars.mass.max())
    pyplot.scatter(stars.x.value_in(units.kpc), stars.y.value_in(units.kpc), c=colors[0], s=m, lw=0)
    pyplot.savefig("SolarSiblings_life_galaxy")
예제 #8
0
def plot_projected_density(model, xmin=-1, xmax=1, col=0):
    pyplot.xlim(xmin, xmax)
    pyplot.ylim(xmin, xmax)
    cols = get_distinct(4)
    pyplot.scatter(model.x.value_in(nbody_system.length),
                   model.z.value_in(nbody_system.length),
                   c=cols[col], s=80, lw=0)
예제 #9
0
파일: Salpeter.py 프로젝트: jilkoval/amuse
def main(N, m, M, ximf):
    numpy.random.seed(31415)
    x_label = "M$_\odot$"
    y_label = "N"
    fig, ax = figure_frame(x_label, y_label, xsize=12, ysize=8)
    cols = get_distinct(2)

    masses = new_salpeter_mass_distribution(N, m, M, ximf)
    masses = new_salpeter_mass_distribution(N, m, M, ximf)
    lm = math.log10(0.5*m.value_in(units.MSun))
    lM = math.log10(1.5*M.value_in(units.MSun))
    bins = 10**numpy.linspace(lm, lM, 51)
    Nbin, bin_edges= numpy.histogram(masses.value_in(units.MSun), bins=bins)
    bin_sizes = bin_edges[1:] - bin_edges[:-1]
    y = Nbin / bin_sizes
    x = (bin_edges[1:] + bin_edges[:-1]) / 2.0
    for i in range(len(y)):
        y[i] = max(y[i], 1.e-10)
    pyplot.scatter(x, y, s=100, c=cols[0], lw=0)
    
    c = ((M.value_in(units.MSun)**(ximf+1)) - (m.value_in(units.MSun)**(ximf+1))) / (ximf+1)
    pyplot.plot(x, N/ c * (x**ximf), c=cols[1])
    pyplot.loglog()
    pyplot.xlabel('$M [M_\odot]$')
    pyplot.ylabel('N')
    #pyplot.xlim(-3, 3)
#    pyplot.show()
    pyplot.savefig("salpeter")
예제 #10
0
def main(N, W0, t_end, Rvir, Mmin, Mmax):
    bodies = generate_initial_conditions(N, W0, Rvir, Mmin, Mmax)

    x_label = "t [Myr]"
    y_label = "R [pc]"
    fig = single_frame(x_label, y_label, logx=False, logy=False, xsize=14, ysize=12)
    color = get_distinct(4)

    time, Lr25, Lr50, Lr75 = run_only_gravity(bodies.copy(), t_end)
    pyplot.plot(time.value_in(units.Myr), Lr25.value_in(units.parsec), c=color[0], label= 'without mass loss')
    pyplot.plot(time.value_in(units.Myr), Lr50.value_in(units.parsec), c=color[0])
    pyplot.plot(time.value_in(units.Myr), Lr75.value_in(units.parsec), c=color[0])

    time, Lr25, Lr50, Lr75 = run_sequential_gravity_and_stellar(bodies.copy(), t_end)
    pyplot.plot(time.value_in(units.Myr), Lr25.value_in(units.parsec), c=color[1], label= 'with mass loss')
    pyplot.plot(time.value_in(units.Myr), Lr50.value_in(units.parsec), c=color[1])
    pyplot.plot(time.value_in(units.Myr), Lr75.value_in(units.parsec), c=color[1])
    
    time, Lr25, Lr50, Lr75 = run_event_driven_gravity_and_stellar(bodies.copy(), t_end)
    pyplot.plot(time.value_in(units.Myr), Lr25.value_in(units.parsec), c=color[2], label= 'Event driven')
    pyplot.plot(time.value_in(units.Myr), Lr50.value_in(units.parsec), c=color[2])
    pyplot.plot(time.value_in(units.Myr), Lr75.value_in(units.parsec), c=color[2])

    pyplot.legend(loc="upper left", ncol=1, shadow=False, fontsize=24)

    #pyplot.show()
    pyplot.savefig("gravity_stellar_comparison")
예제 #11
0
def plot_ionization(ism, N, which, rmax, t_end, rS, ip):

    r, x, R, X = get_ionization_fraction1d(ism)
    xx, yy, xi, hh, ll = get_ionization_fraction2d(ism)

    w = 14
    if ip > 1:
        pyplot.close('all')
        pyplot.clf()
    pyplot.figure(figsize=(w,6))
    pyplot.rcParams.update({'font.size': 22})

    colors = get_distinct(3)
#    rscolor = 'green'
    
    ax1 = pyplot.subplot(1,2,1)
    #ax1.scatter(r, x, c=colors[0], lw=0, s=10)
    ax1.scatter(r, x, c=x, lw=0, s=20, alpha=0.5, cmap="jet")
    ax1.plot(R[1:], X[1:], c=colors[1], lw=3)
    ax1.plot([rS, rS], [-1,2], color=colors[2], linestyle='dashed', lw=3)
    ax1.text(rS+0.08, 1.06, r'$R_s$', color=colors[2], fontsize=20)
    ax1.set_xlim(0, rmax)
    ax1.set_ylim(-0.04, 1.19)
    ax1.set_xlabel("r [pc]", fontsize=20)
    ax1.set_ylabel(r'$\xi_{\rm ion}$', fontsize=20)

    ax2 = pyplot.subplot(1,2,2)
    h = numpy.array(hh)
    h *= 72*w/(6.*ll)		# approximate scaling
    ax2.set_aspect(1)
    sc2 = ax2.scatter(xx, yy, c=xi, s=numpy.pi*h**2,
                      alpha=0.05, edgecolor=None, cmap="jet")
    if ll < rmax: ll = rmax
    ax2.set_xlim(-ll,ll)
    ax2.set_ylim(-ll,ll)
    ax2.set_xlabel("x [pc]", fontsize=20)
    ax2.set_ylabel("y [pc]", fontsize=20)
    #for axi in ax2.flat:
    ax2.xaxis.set_major_locator(pyplot.MaxNLocator(6))
    ax2.yaxis.set_major_locator(pyplot.MaxNLocator(6))
    #pyplot.colorbar(sc2, ax=ax2, fraction=0.046, pad=0.04)	# magic numbers!
    circle = pyplot.Circle((0, 0), rS, color=colors[2],
                           fill=False, linestyle='dashed', lw=3)
    ax2.add_artist(circle)
    
    if which == 0:
        id_string = 'Plummer_model'
    else:
        id_string = 'Homogeneous_sphere'

    param_string = "_N=%d_t=%.3f_Myr" % (N, t_end)

    #pyplot.suptitle(id_string+param_string, y=0.96, fontsize=16)

    savefile = 'fig_ionization_of_GMC_'+id_string+param_string+'.png'
    pyplot.savefig(savefile, dpi=300)
    print 'Figure saved in file', savefile
    
    if ip == 0: pyplot.show()
def get_color_based_on_stellar_type(istp):
    color = get_distinct(5)
    if istp.value_in(units.stellar_type) < 2:
        c = color[0]
    elif istp.value_in(units.stellar_type) < 6:
        c = color[3]
    else:
        c = color[4]
    return c
예제 #13
0
def plot_single_image(particles, lim):
#    nullfmt   = NullFormatter()         # no labels
    left, width = 0.1, 0.65
    bottom, height = 0.1, 0.65
    bottom_h = left_h = left+width+0.05
    rect_scatter = [left, bottom, width, height]
    rect_histx = [left, bottom_h, width, 0.2]
    rect_histy = [left_h, bottom, 0.2, height]

    colors = get_distinct(4)

#    pyplot.rcParams.update({'font.size': 30})
    fig = pyplot.figure(figsize=(12,12))	
#    ax = pyplot.gca()
#    ax.minorticks_on() # switch on the minor ticks
#    ax.locator_params(nbins=3)

    time = particles.get_timestamp()
#    pyplot.title("Cluster at t="+str(time.in_(units.Gyr)))
    xy = pyplot.axes(rect_scatter)
    xy.text(11,11, "Galaxy at t="+str(time.in_(units.Gyr)),  ha='left', va='bottom')
    xz = pyplot.axes(rect_histx)
    yz = pyplot.axes(rect_histy)
    xy.set_xlabel("X [kpc]")
    xy.set_ylabel("Y [kpc]")
    xz.set_ylabel("Z [kpc]")
    yz.set_xlabel("Z [kpc]")

    xy.scatter([0.0], [0.0], s=200, c=colors[1], marker='+')
    xz.scatter([0.0], [0.0], s=200, c=colors[1], marker='+')
    yz.scatter([0.0], [0.0], s=200, c=colors[1], marker='+')
    xy.scatter([8.5], [0.0], s=100, c=colors[2], marker='o', lw=0)
    xz.scatter([8.5], [0.0], s=100, c=colors[2], marker='o', lw=0)
    yz.scatter([0.0], [0.0], s=100, c=colors[2], marker='o', lw=0)

#    axHistx.xaxis.set_major_formatter(nullfmt)
#    axHisty.yaxis.set_major_formatter(nullfmt)

    positions = particles.position
    x, y, z = positions.x.value_in(units.kpc), positions.y.value_in(units.kpc), positions.z.value_in(units.kpc)

    xy.scatter(x, y, c=colors[0], lw=0)
    xy.set_xlim( (-lim, lim) )
    xy.set_ylim( (-lim, lim) )
    xz.scatter(x, z, c=colors[0], lw=0)
    yz.scatter(z, y, c=colors[0], lw=0)
    xz.set_xlim( xy.get_xlim() )
#    yz.set_xlim( (-0.2*lim, 0.2*lim) )
#    yz.set_xlim( xy.get_xlim() )
    yz.set_ylim( xy.get_xlim() )
    yz.set_xlim( (-0.1*lim, 0.1*lim) )
    xz.set_ylim( (-0.1*lim, 0.1*lim) )
#    pyplot.show()
#    fig.savefig('test.png')
    fig.savefig('SolarSiblings_static_galaxy')
def main():

    """
    Mb = (2. + 1.) | units.MSun
    Mb = 2. | units.MSun
    a0 = 10. | units.AU
#    vs = 35. | units.kms
    vs = 30. | units.kms
    Mdot_donor = 0.11 |units.MSun/units.Myr
    Mdot = Bondi_Hoyle_Littleton_accretion_rate(Mb, vs, a0, Mdot_donor)
    print Mdot.in_(units.MEarth/units.yr)
    t = numpy.arange(0, 3, 0.1) | units.yr
    mdot = Mdot*t
    t += 4 | units.yr
    """
    Mb = (2. + 1.) | units.MSun
    Mb = 2. | units.MSun
    a0 = 10. | units.AU
    #vs = 30. | units.kms
#    vs = 18. | units.kms
    vs = 17.26 | units.kms
    vorb = numpy.sqrt(constants.G*Mb/a0)
    print "vorb=", vorb.in_(units.kms)
    k = vorb/vs
    m1 = 1.924785833858|units.MSun
    m2 = 1.|units.MSun
    mu = m2/(m1+m2)
    Mdot_donor  = 0.11 |units.MSun/units.Myr
    cvw = 0.
    print "k and mu:", k, mu
    Mdot = Mdot_donor  * mu**2 * k**4/(1 + k**2 + cvw**2)**(3./2.)
#    print "Mdot:", Mdot.in_(units.MEarth/units.yr)
    print "Mdot:", Mdot.in_(units.MSun/units.Myr)

    t = numpy.arange(0, 3, 0.1) | units.yr
    mdot = Mdot*t 
    t += 4.2 | units.yr

    c = get_distinct(3)

    x_label = 't [yr]'
    y_label = 'M [$10^{-9}$M$_{\odot}$]'
    figure = single_frame(x_label, y_label, logy=False, xsize=14, ysize=10)
    filename = "hydro_give_or_take.data"

    print t, mdot.value_in(units.MSun)
    mdot /= (1.e-9|units.MSun)
    pyplot.plot(t.value_in(units.yr), mdot, c=c[2])

    plot_accretion_from_wind(filename, c[0])
    filename = "hydro_give_or_take_gravity_NoG.data"
    plot_accretion_from_wind(filename, c[1])

    pyplot.savefig("hydro_accretion_from_windy_star")
예제 #15
0
def plot_ionization_fraction(pos, xion):
    r = [] | units.parsec
    x = []
    for pi, xi in zip(pos, xion):
        r.append(pi.length())
        x.append(xi)
    r, x = zip(*sorted(zip(r.value_in(units.parsec), x)))

    R, X = binned_mean_data(r, x)
    
    from matplotlib import pyplot
    x_label = "r [pc]"
    y_label = r'$\xi_{\rm ion}$'
    figure = single_frame(x_label, y_label, logx=False, logy=False,
                          xsize=14, ysize=8)
    pyplot.scatter(r, x, c=get_distinct(1), lw=0, s=100)
    pyplot.plot(R, X, c=get_distinct(2)[1], lw=2)
    pyplot.xlim(0, 6)
    pyplot.ylim(-0.04, 1.19)
    pyplot.savefig("fig_ionization_of_GMC")
    pyplot.show()
예제 #16
0
def plot_function(data):
    print_times_Myr,print_smas_AU,print_rps_AU,print_parent_is_deg,canonical_rp_min_A_AU,canonical_rp_min_B_AU = data

    N_binaries = len(print_smas_AU)

    pyplot.rc('text',usetex=True)
    pyplot.rc('legend',fancybox=True)
            
    linewidth=4
    dlinewidth=2
    fig=pyplot.figure(figsize=(10,9))
    plot1=fig.add_subplot(2,1,1,yscale="log")
    plot2=fig.add_subplot(2,1,2)

    from distinct_colours import get_distinct

    colors = get_distinct(4)
    labels = ["$A$","$B$","$C$"]
    labels_i = ["$i_{AC}$","$i_{BC}$",None]
    for index_binary in range(N_binaries):
        label = labels[index_binary]
        label_i = labels_i[index_binary]        
        color = colors[index_binary]
        
        plot1.plot(print_times_Myr,print_smas_AU[index_binary],color=color,linestyle='dashed',linewidth=dlinewidth)
        plot1.plot(print_times_Myr,print_rps_AU[index_binary],color=color,linewidth=linewidth,label=label)
        
        plot2.plot(print_times_Myr,print_parent_is_deg[index_binary],color=color,linewidth=linewidth,label=label_i)

    plot1.axhline(y = canonical_rp_min_A_AU, color= colors[0],linestyle='dotted',linewidth=dlinewidth)
    plot1.axhline(y = canonical_rp_min_B_AU, color= colors[1],linestyle='dotted',linewidth=dlinewidth)

    handles,labels = plot1.get_legend_handles_labels()
    plot1.legend(handles,labels,loc="upper right",fontsize=12)

    handles,labels = plot2.get_legend_handles_labels()
    plot2.legend(handles,labels,loc="lower right",fontsize=12)

    plot1.set_xlabel("t [Myr]",fontsize=18)
    plot2.set_xlabel("t [Myr]",fontsize=18)

    plot1.set_ylabel("$a_i [\mathrm{AU}]$",fontsize=18)
    plot2.set_ylabel("$i_{kl} [\mathrm{deg}]$",fontsize=18)

    plot1.set_xlim(0.0,print_times_Myr[-1])
    plot2.set_xlim(0.0,print_times_Myr[-1])

    plot1.tick_params(axis='both', which ='major', labelsize = 18)
    plot2.tick_params(axis='both', which ='major', labelsize = 18)

    fig.savefig("figure.eps")

    pyplot.show()
def plot_temperature_line(radii, electron_temperatures, ci):
  
    colors = get_distinct(4)
    s = 100
    if ci==1:
        s = 50
    
    pyplot.scatter(radii.value_in(units.parsec),
                   electron_temperatures.value_in(units.K),
                   c=colors[ci], lw=0, s=s)
    pyplot.xlabel('R [pc]')
    pyplot.ylabel('T [K]')
    pyplot.xlim(0.8, 3.2)
예제 #18
0
def make_plot(disk1, disk2, filename):
    x_label = "X [kpc]"
    y_label = "Y [kpc]"
    figure = single_frame(x_label, y_label, logy=False, xsize=14, ysize=14)
    from distinct_colours import get_distinct
    c = get_distinct(2)
    pyplot.xlim(-300, 300)
    pyplot.ylim(-300, 300)

    pyplot.scatter(disk1.x.value_in(units.kpc), disk1.y.value_in(units.kpc),
                   c=c[0], alpha=1, s=1, lw=0)
    pyplot.scatter(disk2.x.value_in(units.kpc), disk2.y.value_in(units.kpc),
                   c=c[1], alpha=1, s=1, lw=0)
    pyplot.savefig(filename)
def plot_HD971331(filename):
    t_end = 4000|units.day
    t_start = 8000|units.day
    from matplotlib import pyplot

    colors = get_distinct(4)
    figure = pyplot.figure(figsize=(16, 12))
    ax = pyplot.gca()
    ax.minorticks_on() # switch on the minor ticks
    ax.locator_params(nbins=3)
    
    t, a_out, e_out, M_out, m1, m2  = read_orbital_elements(filename)
    pyplot.plot(t.value_in(units.yr), a_out.value_in(units.AU), c=colors[0])

    """
    t, a_out, a_new = retrieve_semi_major_axis_evolution(filename, nj=4.0, t_end=8000|units.day)
    pyplot.plot(t.value_in(units.yr), a_new.value_in(units.AU), c='r')
    pyplot.scatter(t[-1].value_in(units.yr), a_new[-1].value_in(units.AU), s=50, c=colors[1])

    """

    t, a_out, a_new = retrieve_semi_major_axis_evolution(filename, nj=6, t_end=2000|units.day)
    pyplot.plot(t.value_in(units.yr), a_new.value_in(units.AU), c='r')
    pyplot.scatter(t[-1].value_in(units.yr), a_new[-1].value_in(units.AU), s=50, c=colors[1])

    t, a_out, a_new = retrieve_semi_major_axis_evolution(filename, nj=4, t_start=2000|units.day, t_end=5000|units.day)
    pyplot.plot(t.value_in(units.yr), a_new.value_in(units.AU), c=colors[1])
    #pyplot.scatter(t[0].value_in(units.yr), a_new[0].value_in(units.AU), s=50, c=colors[1])
    #pyplot.scatter(t[-1].value_in(units.yr), a_new[-1].value_in(units.AU), s=50, c=colors[1])

    t, a_out, a_new = retrieve_semi_major_axis_evolution(filename, nj=2, t_start=5000|units.day, t_end=8000|units.day)
    print t.value_in(units.yr), a_new.value_in(units.AU)
    #pyplot.plot(t.value_in(units.yr), a_new.value_in(units.AU), c=colors[1])
    #pyplot.scatter(t[0].value_in(units.yr), a_new[0].value_in(units.AU), s=50, c=colors[1])
    #pyplot.scatter(t[-1].value_in(units.yr), a_new[-1].value_in(units.AU), s=50, c=colors[1])

    t, a_out, a_new = retrieve_semi_major_axis_evolution(filename, nj=-7, t_start=8000|units.day)
    pyplot.plot(t.value_in(units.yr), a_new.value_in(units.AU), c=colors[1])
    #pyplot.scatter(t[0].value_in(units.yr), a_new[0].value_in(units.AU), s=50, c=colors[1])

    pyplot.xlabel("t [year]")
    pyplot.ylabel("$a_{giant}$ [AU]")
    pyplot.ylim(0.77, 0.8201)
    pyplot.xlim(0.0, 50.0)
    pyplot.show()
예제 #20
0
def plot_riemann_shock_tube_rho():

    x_label = "[length]"
    y_label = "[mass/length$^3$]"
    figure = single_frame(x_label, y_label, logx=False, logy=False, xsize=14, ysize=10)
    color = get_distinct(3)
        
    x, rho = read_csv("riemann_shock_tube_problem_exact.csv")
    pyplot.plot(x,rho, c=color[0])
    x, rho = read_csv("riemann_shock_tube_problem_fiN5.csv")
    pyplot.scatter(x, rho, c=color[1], s=100, marker="o", lw=0)
    x, rho = read_csv("riemann_shock_tube_problem_athenaN2.csv")
    pyplot.scatter(x, rho, c=color[2], s=100, marker="s", lw=0)

    pyplot.xlim(0.0,1.0)

#        pyplot.savefig("riemann_shock_tube_rho_"+model.name_of_the_code+".png")
    pyplot.savefig("riemann_shock_tube_rho")
    pyplot.show()
예제 #21
0
def energy_plot(time, E_kin, E_pot, E_therm, figname):
    if not HAS_MATPLOTLIB:
        return
    x_label = 'Time [hour]'
    y_label = 'Energy [foe]'
    single_frame(x_label, y_label, logx=False, logy=False, xsize=14, ysize=10, ymin=-1, ymax=-1)
    cols = get_distinct(4)

    FOE = 1.e+51 | units.erg
    hour = 1|units.hour
    pyplot.plot(time/hour, E_kin/FOE, label='E_kin', c=cols[0])
    pyplot.plot(time/hour, E_pot/FOE, label='E_pot', c=cols[1])
    pyplot.plot(time/hour, E_therm/FOE, label='E_therm', c=cols[2])
    pyplot.plot(time/hour, (E_kin+E_pot+E_therm)/FOE, label='E_total', c=cols[3])

    pyplot.legend(loc=4)
    pyplot.savefig(figname)
    print "\nPlot of energy evolution was saved to: ", figname
    pyplot.close()
예제 #22
0
def plot_single_image(groups_of_particles, lim=10):
    left, width = 0.1, 0.4
    bottom, height = 0.1, 0.4
    bottom_h = left_h = left+width+0.05
    rect_xy = [left, bottom, width, height]
    rect_xz = [left, bottom_h, width, 0.4]
    rect_yz = [left_h, bottom, 0.4, height]

    from distinct_colours import get_distinct
    colors = get_distinct(12)

    fig = pyplot.figure(figsize=(10,10))

    xy = pyplot.axes(rect_xy)
    xz = pyplot.axes(rect_xz)
    yz = pyplot.axes(rect_yz)
    xy.set_xlabel("X [pc]")
    xy.set_ylabel("Y [pc]")
    xz.set_ylabel("Z [pc]")
    yz.set_xlabel("Z [pc]")

    i = 0
    for group in groups_of_particles:
        x = group.x.value_in(units.parsec)
        y = group.y.value_in(units.parsec)
        z = group.z.value_in(units.parsec)
        xy.scatter(x, y, lw=0, c=colors[min(11, i)], s=8)
        xz.scatter(x, z, lw=0, c=colors[min(11, i)], s=8)
        yz.scatter(z, y, lw=0, c=colors[min(11, i)], s=8)
        i += 1

    xy.set_xlim((-lim, lim))
    xy.set_ylim((-lim, lim))
    xz.set_xlim(xy.get_xlim())
    yz.set_ylim(xy.get_xlim())
    yz.set_xlim(xy.get_xlim())
    xz.set_ylim(xy.get_xlim())

    save_file = 'FractalClusterHop.png'
    pyplot.savefig(save_file)
    print '\nSaved figure in file', save_file,'\n'
    pyplot.show()
def main(M, z, output_filename):
    numpy.random.seed(31415)
    x_label = "$R$ [R$_\odot$]"
    y_label = "$\\rho$ [g/cm$^{3}$]"
    fig, ax = figure_frame(x_label, y_label, xsize=12, ysize=8)
    cols = get_distinct(3)

    r, rho = get_density_profile(EVtwin, M, z)
    pyplot.plot(r.value_in(units.RSun), rho.value_in(units.g/units.cm**3), label="EVtwin", c=cols[0])
    r, rho = get_density_profile(MESA, M, z)
    pyplot.plot(r.value_in(units.RSun), rho.value_in(units.g/units.cm**3), label="MESA", c=cols[1])
    # run merger
    r, rho = merge_two_stars(0.5*M, 0.5*M, 1|units.yr)
    pyplot.plot(r.value_in(units.RSun), rho.value_in(units.g/units.cm**3), label="MESA", c=cols[2])

    pyplot.semilogy()
    if output_filename:
        pyplot.savefig(output_filename)
    else:
        pyplot.show()
예제 #24
0
def main(M1, M2, M3, Pora, Pin, ain, aout, ein, eout,
         t_end, nsteps, scheme, dtse_fac):

    from matplotlib import pyplot
    
    x_label = "$a/a_{0}$"
    y_label = "$e/e_{0}$"
    fig = single_frame(x_label, y_label, logx=False, logy=False,
                       xsize=10, ysize=8)
    color = get_distinct(4)

    if scheme == 0:
        srange = [1,2,3]
    else:
        srange = [scheme]

    i = 0
    for s in srange:
        time, ai, ei, ao, eo = evolve_triple_with_wind(M1, M2, M3,
                                                       Pora, Pin,
                                                       ain, aout,
                                                       ein, eout,
                                                       t_end, nsteps,
                                                       s, dtse_fac)
        if i == 0:
            pyplot.plot(ai, ei, c=color[0], label='inner')
            pyplot.plot(ao, eo, c=color[1], label='outer')
            i = 1
        else:
            pyplot.plot(ai, ei, c=color[0])
            pyplot.plot(ao, eo, c=color[1])

    pyplot.legend(loc='best', ncol=1, shadow=False, fontsize=20)
    
    #save_file = 'evolve_triple_with_wind.png'
    save_file = 'evolve_triple_with_wind' \
                    +'_s={:d}_dtse={:.3f}'.format(scheme, dtse_fac) \
                    +'.png'
    pyplot.savefig(save_file)
    print '\nSaved figure in file', save_file,'\n'
    pyplot.show()
예제 #25
0
def main(N, t_end):
    t_end = t_end | nbody_system.time
    Q_init = 0.2
    particles = new_plummer_model(N)
    codes = [ph4, Huayno, BHTree]
    cols = get_distinct(3)
    ci = 0
    x_label = "time [N-body units]"
#    y_label = "$Q [\equiv -E_{\rm kin}/E_{\rm pot}]$"
    y_label = "virial ratio $Q$"
    figure = single_frame(x_label, y_label, xsize=14, ysize=10)
    ax1 = pyplot.gca()
    ax1.set_xlim(0, t_end.value_in(t_end.unit))
    ax1.set_ylim(0, 0.65)
    pyplot.plot([0, t_end.value_in(t_end.unit)], [0.5, 0.5], lw=1, ls='--', c='k')
    for code in codes:
        time, Q = virial_ratio_evolution(code, particles, Q_init, t_end)
        pyplot.plot(time.value_in(t_end.unit), Q, c=cols[ci])
        ci+=1
#    pyplot.show()
    pyplot.savefig("gravity_to_virial")
예제 #26
0
def main(M1, M2, M3, ain, aout, ein, eout, t_end, nsteps):

    from matplotlib import pyplot

    x_label = "$a/a_{0}$"
    #    x_label = "$t [Myr]$"
    y_label = "ecc, $a/a_{0}$"
    fig = single_frame(x_label, y_label, logx=False, logy=False, xsize=14, ysize=12)
    color = get_distinct(4)

    time, ain, ein, aout, eout = evolve_triple_with_wind(M1, M2, M3, ain, aout, ein, eout, t_end, nsteps)
    pyplot.plot(ain, ein, c=color[0], label="inner")
    pyplot.plot(aout, eout, c=color[1], label="outer")
    """
    pyplot.plot(time, ein, c=color[0], label= '$e_{inner}$')
    pyplot.plot(time, ain, c=color[1], label= '$a_{inner}$')
    pyplot.plot(time, eout, c=color[2], label= '$e_{outer}$')
    pyplot.plot(time, aout, c=color[3], label= '$a_{outer}$')
    """
    pyplot.legend(loc="upper left", ncol=1, shadow=False, fontsize=24)

    #    pyplot.show()
    pyplot.savefig("evolve_triple_with_wind")
예제 #27
0
    0.09890162549942522, 0.2971536318319011, 0.5047269929821525,
    0.6955052866807527, 0.8934247174201266, 1.0960741121502846,
    1.296349286674131
]
S_all_gas = [
    1011.82389615108, 382.3950057709804, 262.3523868909657, 154.2500699106347,
    107.5704842567941, 88.9640154049995, 68.72257895441606
]

pyplot.rcParams.update({'font.size': 30})
fig, ax = pyplot.subplots(figsize=[16, 10])
ax.minorticks_on()  # switch on the minor ticks
ax.tick_params('both', length=15, width=2, which='major')
ax.tick_params('both', length=6, width=1, which='minor')
from distinct_colours import get_distinct
colors = get_distinct(10)

pyplot.scatter(R_young_stars,
               S_young_stars,
               s=100,
               marker='s',
               c=colors[6],
               lw=0)
pyplot.scatter(R_all_stars, S_all_stars, s=100, marker='s', c=colors[0], lw=0)
#pyplot.scatter(R_dense_gas, S_dense_gas, s=100, marker='s', c=colors[7], lw=0)
pyplot.scatter(R_all_gas, S_all_gas, s=100, marker='s', c=colors[3], lw=0)


def plot_radial_distribution(gas, nbin, c, lw):
    X = []
    Ymean = []
예제 #28
0
                      help="Dimension-less depth of the King potential (W0) [7.0]")
    result.add_option("-z", dest="z", type="float", default = 0.02,
                      help="metalicity [0.02]")
    return result

if __name__ in ('__main__', '__plot__'):
    o, arguments  = new_option_parser().parse_args()
    time, Lr_stars25, Lr_bodies25, Lr_stars50, Lr_bodies50, Lr_stars75, Lr_bodies75 = main(**o.__dict__)
    from matplotlib import pyplot
    from prepare_figure import single_frame
    from distinct_colours import get_distinct

    x_label = "t [Myr]"
    y_label = "R [pc]"
    fig = single_frame(x_label, y_label, logx=False, logy=False, xsize=14, ysize=12)
    color = get_distinct(4)

#    import numpy
#    Lr_stars = numpy.matrix.transpose(numpy.matrix(Lr_stars))
#    Lr_bodies = numpy.matrix.transpose(numpy.matrix(Lr_bodies))
    
#    print Lr_stars[6], Lr_bodies[6]
    pyplot.plot(time.value_in(units.Myr), Lr_stars25.value_in(units.parsec), c=color[0], label= 'with mass loss')
    pyplot.plot(time.value_in(units.Myr), Lr_bodies25.value_in(units.parsec), c=color[1], label= 'without mass loss')

    pyplot.plot(time.value_in(units.Myr), Lr_stars50.value_in(units.parsec), c=color[0])
    pyplot.plot(time.value_in(units.Myr), Lr_bodies50.value_in(units.parsec), c=color[1])

    pyplot.plot(time.value_in(units.Myr), Lr_stars75.value_in(units.parsec), c=color[0])
    pyplot.plot(time.value_in(units.Myr), Lr_bodies75.value_in(units.parsec), c=color[1])
    
예제 #29
0
fig = plt.figure(figsize=(8.5, 9.))
jj = 111
ax = fig.add_subplot(jj)

x = np.array([0, 1, 2, 3])
elabels = ['Voids', 'Sheets', 'Filaments', 'Knots']
plt.xticks(x, elabels)
ax.tick_params(axis='x', which='minor', bottom='off')

ytit = "$log_{10}(\Phi/ \\rm{h^{3} Mpc^{-3}})$"
ax.set_ylabel(ytit)
ymin = -7.
ymax = -1.
ax.set_ylim(ymin, ymax)

cols = get_distinct(nfiles)

# Bins
emin = -0.5
emax = 3.5
dm = 1.
frac = 0.85
lbar = dm * frac / nfiles
ebins = np.arange(emin, emax, dm)

vol = 500.**3.  # Simulation volume in (Mpc/h)^3
for ii, ending in enumerate(endings):
    infile = epath + root[ii] + survey + ending
    if (not os.path.isfile(infile)):
        print('STOP: {} not found'.format(infile))
        sys.exit()
예제 #30
0
if __name__ in ('__main__','__plot__'):

    # High-level structure of merge_two_stars_and_evolve.py and
    # merge_two_stars_sph_evolve.py are designed to be identical.
    
    set_printing_strategy("custom", #nbody_converter = converter, 
                          precision = 11, prefix = "", 
                          separator = " [", suffix = "]")

    o, arguments  = new_option_parser().parse_args()
    Mprim = o.Mprim
    Msec = o.Msec
    tend = o.tend
    tcoll = o.tcoll

    color = get_distinct(4)  # 0 = cyan, 1 = red, 2 = mustard, 3 = green

    x_label = "T [K]"
    y_label = "L [$L_\odot$]"
    figure = single_frame(x_label, y_label, logx=True, logy=True,
                          xsize=14, ysize=10)
    pyplot.xlim(2.e+4, 3.e3)
    pyplot.ylim(20., 2.e+3)

    print "Evolve single star of mass", Mprim.in_(units.MSun)
    time, stp, mass, radius, temperature, luminosity \
        = evolve_single_star(Mprim, tend)
    pyplot.plot(temperature.value_in(units.K),
                luminosity.value_in(units.LSun),
                c=color[1], lw=2, zorder=1)
    pyplot.scatter(temperature[0].value_in(units.K),
예제 #31
0
def plot_single_image(planets, disk, lim, index):

    #centered on the Sun
    com = planets[0].position
    planets.position -= com
    disk.position -= com

    left, width = 0.1, 0.65
    bottom, height = 0.1, 0.65
    bottom_h = left_h = left + width + 0.05
    rect_scatter = [left, bottom, width, height]
    rect_histx = [left, bottom_h, width, 0.2]
    rect_histy = [left_h, bottom, 0.2, height]

    fig = pyplot.figure(figsize=(12, 12))
    time = disk.get_timestamp()
    # pyplot.title("Cluster at t="+str(time.in_(units.Gyr)))
    xy = pyplot.axes(rect_scatter)
    xy.text(110,
            110,
            "protoplanetary disk (img#" + str(index) + ")",
            ha='left',
            va='bottom')
    xz = pyplot.axes(rect_histx)
    yz = pyplot.axes(rect_histy)
    xy.set_xlabel("X [AU]")
    xy.set_ylabel("Y [AU]")
    xz.set_ylabel("Z [AU]")
    yz.set_xlabel("Z [AU]")

    positions = disk.position
    x, y, z = positions.x.value_in(units.AU), positions.y.value_in(units.AU), \
              positions.z.value_in(units.AU)

    alpha = 0.01
    us = disk.u
    u_min, u_max = min(us), max(us)
    print "u=", u_min, u_max
    log_u = numpy.log((us / u_min)) / numpy.log((u_max / u_min))
    clipped_log_u = numpy.minimum(
        numpy.ones_like(log_u), numpy.maximum(numpy.zeros_like(log_u), log_u))

    ps = disk.rho
    p_min, p_max = min(ps), max(ps)
    log_p = numpy.log((ps / p_min)) / numpy.log((p_max / p_min))
    clipped_log_p = numpy.minimum(
        numpy.ones_like(log_p), numpy.maximum(numpy.zeros_like(log_p), log_p))

    red = 1.0 - clipped_log_u
    blue = clipped_log_u
    green = clipped_log_p
    colors = numpy.transpose(numpy.array([red, green, blue]))

    sizes = 2000 * disk.h_smooth / disk.h_smooth.max()
    xy.scatter(x, y, sizes, c=colors, edgecolors="none", alpha=alpha)
    xy.set_xlim((-lim, lim))
    xy.set_ylim((-lim, lim))
    sizes = 100 * disk.h_smooth / disk.h_smooth.max()
    xz.scatter(x, z, sizes, c=colors, edgecolors="none", alpha=alpha)
    yz.scatter(z, y, sizes, c=colors, edgecolors="none", alpha=alpha)
    xz.set_xlim(xy.get_xlim())
    yz.set_ylim(xy.get_xlim())
    yz.set_xlim((-0.05 * lim, 0.05 * lim))
    xz.set_ylim((-0.05 * lim, 0.05 * lim))

    from distinct_colours import get_distinct
    c = get_distinct(len(planets))
    #    m = 1000 * planets.mass/planets.mass.max()
    m = 100 * numpy.log10(1 + planets.mass / planets.mass.min())
    #m[0] = min(10*m[1:].max(), 30)
    xy.scatter(planets.x.value_in(units.AU),
               planets.y.value_in(units.AU),
               s=m,
               c=c,
               lw=0)
    xz.scatter(planets.x.value_in(units.AU),
               planets.z.value_in(units.AU),
               s=m,
               c=c,
               lw=0)
    yz.scatter(planets.z.value_in(units.AU),
               planets.y.value_in(units.AU),
               s=m,
               c=c,
               lw=0)

    filename = "planetary_system_i{0:04}.png".format(index)
    fig.savefig(filename)
예제 #32
0
        dEi = energy_error_of_integrated_Nbody_system(code, particles, t_end,
                                                      pri)
        dE.append(abs(dEi))
        print "integrated with precision=", pri, "dE/E=", dEi
    return dE


if __name__ in ('__main__', '__plot__'):

    numpy.random.seed(31415)

    particles = new_plummer_model(1000)
    precision = 10.**numpy.linspace(0., -3., 10)

    t_end = 1.0 | nbody_system.time
    cols = get_distinct(2)

    print 'ph4'
    code = ph4
    dE = get_dE(code, precision, t_end)
    pyplot.scatter(precision, dE, c=cols[0], lw=0, s=50, marker='o')

    print 'BHTree'
    code = BHTree
    dE = get_dE(code, precision, t_end)
    pyplot.scatter(precision, dE, c=cols[1], lw=0, s=50, marker='^')

    t0 = 0.8
    t1 = 0.02
    ep = 4.e-5
    eb = 0.07
def showSurveyStatistics(simulatedSurvey,
                         pdfFile=None,
                         pngFile=None,
                         usekde=False):
    """
    Produce a plot with the survey statistics.

    Parameters
    ----------

    simulatedSurvey : Object containing the simulated survey.

    Keywords
    --------

    pdfFile : string
        Name of optional PDF file in which to save the plot.
    pngFile : string
        Name of optional PNG file in which to save the plot.
    usekde  : boolean
        If true use kernel density estimates to show the distribution of survey quantities instead of
        histograms.
    """
    try:
        _ = simulatedSurvey.observedParallaxes.shape
    except AttributeError:
        stderr.write("You have not generated the observations yet!\n")
        return

    parLimitPlot = 50.0
    plxSnrLim = 5.0

    positiveParallaxes = (simulatedSurvey.observedParallaxes > 0.0)
    goodParallaxes = (simulatedSurvey.observedParallaxes /
                      simulatedSurvey.parallaxErrors >= plxSnrLim)
    estimatedAbsMags = (
        simulatedSurvey.observedMagnitudes[positiveParallaxes] +
        5.0 * np.log10(simulatedSurvey.observedParallaxes[positiveParallaxes])
        - 10.0)
    relParErr = (simulatedSurvey.parallaxErrors[positiveParallaxes] /
                 simulatedSurvey.observedParallaxes[positiveParallaxes])
    deltaAbsMag = estimatedAbsMags - simulatedSurvey.absoluteMagnitudes[
        positiveParallaxes]

    useagab(usetex=False, fontfam='sans')
    fig = plt.figure(figsize=(27, 12))

    axA = fig.add_subplot(2, 3, 1)
    apply_tufte(axA, withgrid=False)
    axA.set_prop_cycle(cycler('color', get_distinct(3)))

    minPMinThird = np.power(simulatedSurvey.minParallax, -3.0)
    maxPMinThird = np.power(parLimitPlot, -3.0)
    x = np.linspace(simulatedSurvey.minParallax,
                    np.min([parLimitPlot, simulatedSurvey.maxParallax]), 1001)
    axA.plot(x,
             3.0 * np.power(x, -4.0) / (minPMinThird - maxPMinThird),
             '--',
             label='model',
             lw=3)

    if usekde:
        scatter = rse(simulatedSurvey.trueParallaxes)
        bw = 1.06 * scatter * simulatedSurvey.numberOfStarsInSurvey**(-0.2)
        kde = KernelDensity(bandwidth=bw)
        kde.fit(simulatedSurvey.trueParallaxes[:, None])
        samples = np.linspace(simulatedSurvey.trueParallaxes.min(),
                              simulatedSurvey.trueParallaxes.max(), 200)[:,
                                                                         None]
        logdens = kde.score_samples(samples)
        axA.plot(samples, np.exp(logdens), '-', lw=3, label='true')
    else:
        axA.hist(simulatedSurvey.trueParallaxes,
                 bins='auto',
                 density=True,
                 histtype='step',
                 lw=3,
                 label='true')

    if usekde:
        scatter = rse(simulatedSurvey.observedParallaxes)
        bw = 1.06 * scatter * simulatedSurvey.numberOfStarsInSurvey**(-0.2)
        kde = KernelDensity(bandwidth=bw)
        kde.fit(simulatedSurvey.observedParallaxes[:, None])
        samples = np.linspace(simulatedSurvey.observedParallaxes.min(),
                              simulatedSurvey.observedParallaxes.max(),
                              200)[:, None]
        logdens = kde.score_samples(samples)
        axA.plot(samples, np.exp(logdens), '-', lw=3, label='observed')
    else:
        axA.hist(simulatedSurvey.observedParallaxes,
                 bins='auto',
                 density=True,
                 histtype='step',
                 lw=3,
                 label='observed')

    axA.set_xlabel(r'$\varpi$,  $\varpi_\mathrm{true}$ [mas]')
    axA.set_ylabel(r'$p(\varpi)$, $p(\varpi_\mathrm{true})$')
    leg = axA.legend(loc='best', handlelength=1.0)
    for t in leg.get_texts():
        t.set_fontsize(14)
    axA.text(0.025,
             0.9,
             'a',
             horizontalalignment='center',
             verticalalignment='center',
             transform=axA.transAxes,
             weight='bold',
             fontsize=30)

    axB = fig.add_subplot(2, 3, 2)
    apply_tufte(axB, withgrid=False)
    axB.set_prop_cycle(cycler('color', get_distinct(3)))

    m = np.linspace(simulatedSurvey.observedMagnitudes.min(),
                    simulatedSurvey.observedMagnitudes.max(), 1000)
    axB.plot(m,
             np.exp(simulatedSurvey.apparentMagnitude_lpdf(m)),
             '--',
             lw=3,
             label='model')

    if usekde:
        scatter = rse(simulatedSurvey.apparentMagnitudes)
        bw = 1.06 * scatter * simulatedSurvey.numberOfStarsInSurvey**(-0.2)
        kde = KernelDensity(bandwidth=bw)
        kde.fit(simulatedSurvey.apparentMagnitudes[:, None])
        samples = np.linspace(simulatedSurvey.apparentMagnitudes.min(),
                              simulatedSurvey.apparentMagnitudes.max(),
                              200)[:, None]
        logdens = kde.score_samples(samples)
        axB.plot(samples, np.exp(logdens), '-', label='true', lw=3)
    else:
        axB.hist(simulatedSurvey.apparentMagnitudes,
                 bins='auto',
                 density=True,
                 histtype='step',
                 lw=3,
                 label='true')

    if usekde:
        scatter = rse(simulatedSurvey.observedMagnitudes)
        bw = 1.06 * scatter * simulatedSurvey.numberOfStarsInSurvey**(-0.2)
        kde = KernelDensity(bandwidth=bw)
        kde.fit(simulatedSurvey.observedMagnitudes[:, None])
        samples = np.linspace(simulatedSurvey.observedMagnitudes.min(),
                              simulatedSurvey.observedMagnitudes.max(),
                              200)[:, None]
        logdens = kde.score_samples(samples)
        axB.plot(samples, np.exp(logdens), '-', label='observed', lw=3)
    else:
        axB.hist(simulatedSurvey.observedMagnitudes,
                 bins='auto',
                 density=True,
                 histtype='step',
                 lw=3,
                 label='observed')

    axB.set_xlabel("$m$, $m_\mathrm{true}$")
    axB.set_ylabel("$p(m)$, $p(m_\mathrm{true})$")
    leg = axB.legend(loc=(0.03, 0.55), handlelength=1.0)
    for t in leg.get_texts():
        t.set_fontsize(14)
    axB.text(0.025,
             0.9,
             'b',
             horizontalalignment='center',
             verticalalignment='center',
             transform=axB.transAxes,
             weight='bold',
             fontsize=30)

    axC = fig.add_subplot(2, 3, 3)
    apply_tufte(axC, withgrid=False)
    axC.set_prop_cycle(cycler('color', get_distinct(3)))

    x = np.linspace(simulatedSurvey.absoluteMagnitudes.min(),
                    simulatedSurvey.absoluteMagnitudes.max(), 300)
    axC.plot(x,
             norm.pdf(x,
                      loc=simulatedSurvey.meanAbsoluteMagnitude,
                      scale=simulatedSurvey.stddevAbsoluteMagnitude),
             '--',
             lw=3,
             label='model')

    if usekde:
        scatter = rse(simulatedSurvey.absoluteMagnitudes)
        bw = 1.06 * scatter * simulatedSurvey.numberOfStarsInSurvey**(-0.2)
        kde = KernelDensity(bandwidth=bw)
        kde.fit(simulatedSurvey.absoluteMagnitudes[:, None])
        samples = np.linspace(simulatedSurvey.absoluteMagnitudes.min(),
                              simulatedSurvey.absoluteMagnitudes.max(),
                              200)[:, None]
        logdens = kde.score_samples(samples)
        axC.plot(samples, np.exp(logdens), '-', label='true', lw=3)
    else:
        axC.hist(simulatedSurvey.absoluteMagnitudes,
                 bins='auto',
                 density=True,
                 histtype='step',
                 lw=3,
                 label='true')

    if (simulatedSurvey.absoluteMagnitudes[goodParallaxes].size >= 3):
        if usekde:
            scatter = rse(simulatedSurvey.absoluteMagnitudes[goodParallaxes])
            bw = 1.06 * scatter * simulatedSurvey.absoluteMagnitudes[
                goodParallaxes].size**(-0.2)
            kde = KernelDensity(bandwidth=bw)
            kde.fit(simulatedSurvey.absoluteMagnitudes[goodParallaxes][:,
                                                                       None])
            samples = np.linspace(
                simulatedSurvey.absoluteMagnitudes[goodParallaxes].min(),
                simulatedSurvey.absoluteMagnitudes[goodParallaxes].max(),
                200)[:, None]
            logdens = kde.score_samples(samples)
            axC.plot(
                samples,
                np.exp(logdens),
                '-',
                label=r'$\varpi/\sigma_\varpi\geq{0:.1f}$'.format(plxSnrLim),
                lw=3)
        else:
            axC.hist(
                simulatedSurvey.absoluteMagnitudes[goodParallaxes],
                bins='auto',
                density=True,
                histtype='step',
                lw=3,
                label=r'$\varpi/\sigma_\varpi\geq{0:.1f}$'.format(plxSnrLim))

    axC.set_xlabel("$M$")
    axC.set_ylabel("$p(M)$")
    leg = axC.legend(loc=(0.03, 0.55), handlelength=1.0)
    for t in leg.get_texts():
        t.set_fontsize(14)
    axC.text(0.025,
             0.9,
             'c',
             horizontalalignment='center',
             verticalalignment='center',
             transform=axC.transAxes,
             weight='bold',
             fontsize=30)

    axD = fig.add_subplot(2, 3, 4)
    apply_tufte(axD, withgrid=False)
    axD.set_prop_cycle(cycler('color', get_distinct(3)))
    axD.plot(simulatedSurvey.trueParallaxesNoLim,
             simulatedSurvey.observedParallaxesNoLim -
             simulatedSurvey.trueParallaxesNoLim,
             'k,',
             label=r'$m_\mathrm{lim}=\infty$')
    axD.plot(simulatedSurvey.trueParallaxes,
             simulatedSurvey.observedParallaxes -
             simulatedSurvey.trueParallaxes,
             '.',
             label=r'$m_\mathrm{{lim}}={0}$'.format(
                 simulatedSurvey.apparentMagnitudeLimit))
    axD.plot(simulatedSurvey.trueParallaxes[positiveParallaxes],
             simulatedSurvey.observedParallaxes[positiveParallaxes] -
             simulatedSurvey.trueParallaxes[positiveParallaxes],
             '.',
             label=r'$\varpi>0$')
    axD.plot(simulatedSurvey.trueParallaxes[goodParallaxes],
             simulatedSurvey.observedParallaxes[goodParallaxes] -
             simulatedSurvey.trueParallaxes[goodParallaxes],
             'o',
             label=r'$\varpi/\sigma_\varpi\geq{0:.1f}$'.format(plxSnrLim))
    axD.set_xlabel(r"$\varpi_\mathrm{true}$ [mas]")
    axD.set_ylabel("$\\varpi-\\varpi_\\mathrm{true}$ [mas]")
    leg = axD.legend(loc='best', handlelength=0.5, ncol=2)
    for t in leg.get_texts():
        t.set_fontsize(14)
    axD.text(0.025,
             0.9,
             'd',
             horizontalalignment='center',
             verticalalignment='center',
             transform=axD.transAxes,
             weight='bold',
             fontsize=30)

    axE = fig.add_subplot(2, 3, 5)
    apply_tufte(axE, withgrid=False)
    axE.set_prop_cycle(cycler('color', get_distinct(3)))
    axE.plot(simulatedSurvey.trueParallaxesNoLim,
             simulatedSurvey.absoluteMagnitudesNoLim,
             'k,',
             label=r'$m_\mathrm{lim}=\infty$')
    axE.plot(simulatedSurvey.trueParallaxes,
             simulatedSurvey.absoluteMagnitudes,
             '.',
             label=r'$m_\mathrm{{lim}}={0}$'.format(
                 simulatedSurvey.apparentMagnitudeLimit))
    axE.plot(simulatedSurvey.trueParallaxes[positiveParallaxes],
             simulatedSurvey.absoluteMagnitudes[positiveParallaxes],
             '.',
             label=r'$\varpi>0$')
    axE.plot(simulatedSurvey.trueParallaxes[goodParallaxes],
             simulatedSurvey.absoluteMagnitudes[goodParallaxes],
             'o',
             label=r'$\varpi/\sigma_\varpi\geq{0:.1f}$'.format(plxSnrLim))
    axE.set_xlabel(r"$\varpi_\mathrm{true}$ [mas]")
    axE.set_ylabel("$M_\\mathrm{true}$")
    axE.axhline(y=simulatedSurvey.meanAbsoluteMagnitude)
    leg = axE.legend(loc='best', handlelength=0.5, ncol=2)
    for t in leg.get_texts():
        t.set_fontsize(14)
    axE.text(0.025,
             0.9,
             'e',
             horizontalalignment='center',
             verticalalignment='center',
             transform=axE.transAxes,
             weight='bold',
             fontsize=30)

    plt.suptitle(
        "Simulated survey statistics: $N_\\mathrm{{stars}}={0}$, ".format(
            simulatedSurvey.numberOfStars) +
        "$m_\\mathrm{{lim}}={0}$, ".format(
            simulatedSurvey.apparentMagnitudeLimit) +
        "$N_\\mathrm{{survey}}={0}$, ".format(
            simulatedSurvey.numberOfStarsInSurvey) +
        "${0}\\leq\\varpi\\leq{1}$, ".format(simulatedSurvey.minParallax,
                                             simulatedSurvey.maxParallax) +
        "$\\mu_M={0}$, ".format(simulatedSurvey.meanAbsoluteMagnitude) +
        "$\\sigma_M={0:.2f}$".format(simulatedSurvey.stddevAbsoluteMagnitude))

    if pdfFile is not None:
        plt.savefig(pdfFile)
    if pngFile is not None:
        plt.savefig(pngFile)
    if (pdfFile is None and pngFile is None):
        plt.show()
예제 #34
0
    # merge_two_stars_sph_evolve.py are designed to be identical.

    set_printing_strategy(
        "custom",  #nbody_converter = converter, 
        precision=11,
        prefix="",
        separator=" [",
        suffix="]")

    o, arguments = new_option_parser().parse_args()
    Mprim = o.Mprim
    Msec = o.Msec
    tend = o.tend
    tcoll = o.tcoll

    color = get_distinct(4)  # 0 = cyan, 1 = red, 2 = mustard, 3 = green

    x_label = "T [K]"
    y_label = "L [$L_\odot$]"
    figure = single_frame(x_label,
                          y_label,
                          logx=True,
                          logy=True,
                          xsize=14,
                          ysize=10)
    pyplot.xlim(2.e+4, 3.e+3)
    pyplot.ylim(20., 2.e+3)

    print("Evolve single star of mass", Mprim.in_(units.MSun))
    time, stp, mass, radius, temperature, luminosity \
        = evolve_single_star(Mprim, tend)
def main(M1, M2, M3, Pora, Pin, ain, aout, ein, eout,
         t_end, nsteps, scheme, integrator,
         t_stellar, dt_se, dtse_fac, interp, show):

    two_frames = False
    plot_ae = True

    color = get_distinct(4)
    if two_frames:
        plt.figure(figsize=(10, 8))
    else:
        plt.figure(figsize=(12, 8))

    if scheme == 5:
        if integrator != 3:
            print 'Warning: scheme = 5 forces integrator = 3'
        integrator = 3
    srange = [1,scheme]		# 1 = no mass loss; other = mass loss
    				# assume scheme > 1
    
    i = 0
    lw = [1,2]
    
    srange = [1, scheme]

    for s in srange:
        time, mtot, ai, ei, ao, eo \
            = evolve_triple_with_wind(M1, M2, M3,
                                      Pora, Pin, ain, aout,
                                      ein, eout,
                                      t_end, nsteps,
                                      s, integrator,
                                      t_stellar, dt_se,
                                      dtse_fac, interp)
        if i == 0:
            if two_frames: plt.subplot(1,2,1)
            plt.plot(time, ai, c=color[0], linewidth=lw[i],
                     label='inner, no mass loss')
            plt.plot(time, ao, c=color[3], linewidth=lw[i],
                     label='outer, no mass loss')
            plt.xlabel('time (yr)')
            plt.ylabel('$a/a_0$')
            if two_frames:
                plt.subplot(1,2,2)
                if plot_ae:
                    plt.plot(ai, ei, c=color[0], linewidth=lw[i])
                    plt.plot(ao, eo, c=color[3], linewidth=lw[i])
                    plt.xlabel('$a/a_0$')
                    plt.ylabel('$e/e_0$')
                else:
                    plt.plot(time, mtot, c=color[0], linewidth=lw[i])
                    plt.xlabel('time (yr)')
                    plt.ylabel('M')
            i = 1
        else:
            if two_frames: plt.subplot(1,2,1)
            plt.plot(time, ai, c=color[1], linewidth=lw[i],
                     label='inner, mass loss')
            plt.plot(time, ao, c=color[2], linewidth=lw[i],
                     label='outer, mass loss')
            if two_frames:
                plt.subplot(1,2,2)
                if plot_ae:
                    plt.plot(ai, ei, c=color[1], linewidth=lw[i])
                    plt.plot(ao, eo, c=color[2], linewidth=lw[i])
                else:
                    plt.plot(time, mtot, c=color[1], linewidth=lw[i])

    if two_frames: plt.subplot(1,2,1)
    plt.legend(loc='best')

    integrators = ['hermite', 'smalln', 'huayno', 'symple']
    label = integrators[integrator]
    label += ' integrator, stellev scheme= {:d}'.format(scheme)
    save_file \
        = 'evolve_triple_with_wind_t={:.3f}'.format(t_end.value_in(units.Myr)) \
        	+'_i={:d}_s={:d}'.format(integrator, scheme)
    if scheme < 5:
        label += ', dtse_fac = {:.3f}'.format(dtse_fac)
        save_file += '_dtsefac={:.3f}'.format(dtse_fac)
    else:
        label += ', dt_se = {:.1f}'.format(dt_se.value_in(units.yr))
        save_file += '_dtse={:.1f}'.format(dt_se.value_in(units.yr))
    save_file += '.png'

    if two_frames:
        plt.tight_layout()
        plt.subplots_adjust(top=0.88)
    #plt.suptitle(label, y=0.97, fontsize=15)

    ax = plt.gca()
    ax.minorticks_on()		# switch on the minor ticks
    ax.tick_params(axis='both', which='both', direction='in')
    ax.locator_params(nbins=3)
    ax.get_yaxis().get_major_formatter().set_useOffset(False)

    plt.savefig(save_file, dpi=300)
    print '\nSaved figure in file', save_file,'\n'
    if show: plt.show()
예제 #36
0
파일: config.py 프로젝트: dstoppacher/myPy
    def load_matplot_stylefiles(self, catname, ncolours=0):

        color = {}
        linestyle = {}
        marker = {}
        markercol = {}
        colormap = {}
        colorbar = {}
        plottype = {}
        alpha = {}
        plotlegend = {}
        add_xaxis = {}
        add_yaxis = {}

        myData = aD.ArangeData()

        mypaths = {
            '0': self.mypath_handler['MATPLOT_LINESTYLE'],
            'dic0': linestyle,
            '1': self.mypath_handler['MATPLOT_COL'],
            'dic1': color,
            '2': self.mypath_handler['MATPLOT_MARKERSTYLE'],
            'dic2': marker,
            '3': self.mypath_handler['MATPLOT_MARKERCOL'],
            'dic3': markercol,
            '4': self.mypath_handler['MATPLOT_COLORMAP'],
            'dic4': colormap,
            '5': self.mypath_handler['MATPLOT_COLORBAR'],
            'dic5': colorbar,
            '6': self.mypath_handler['MATPLOT_PLOTTYPE'],
            'dic6': plottype,
            '7': self.mypath_handler['MATPLOT_ALPHA'],
            'dic7': alpha,
            '8': self.mypath_handler['MATPLOT_PLOTLEGEND'],
            'dic8': plotlegend,
            '9': self.mypath_handler['MATPLOT_ADD_XAXIS'],
            'dic9': add_xaxis,
            '10': self.mypath_handler['MATPLOT_ADD_YAXIS'],
            'dic10': add_yaxis
        }
        a = 0
        while a <= 10:
            data_array = myData.readAnyFormat(config=False,
                                              mydtype=np.str_,
                                              mypath=mypaths[str(a)],
                                              data_shape='shaped',
                                              comment='',
                                              delim='= ')
            #print 'mypath:', mypaths[str(a)]
            #print 'data_array:', data_array
            if data_array.size == 2:
                data_array = np.expand_dims(data_array, axis=0)

            i = 0
            while i < data_array[:, 0].size:
                mypaths['dic' + str(a)].update(
                    {data_array[i, 0]: data_array[i, 1]})
                i += 1
            a += 1

        if ncolours != 0:
            import distinct_colours as cb_col
            #print 'use color-blind friendly colors!'
            # print catname
            cb_colours = cb_col.get_distinct(ncolours)
            if ncolours == 1:
                if catname.find('Galacticus') != -1:
                    #print 'Gal'
                    color['0'] = '#225588'
                elif catname.find('SAG_') != -1 or str(catname).find(
                        'SAG_1Gpc_v2') != -1:
                    #print 'SAG'
                    color['0'] = '#CC6677'
                elif catname.find('SAGE') != -1:
                    #print 'SAGE'
                    color['0'] = '#DDCC77'
                else:
                    #print 'else'
                    color['0'] = cb_colours[0]
            else:
                i = 0
                while i < ncolours:
                    color[str(i)] = cb_colours[i]
                    i += 1

        return linestyle, color, marker, markercol, colormap, colorbar, plottype, alpha, plotlegend, add_xaxis, add_yaxis
예제 #37
0
#path = '/gpfs/data/violeta/Galform_Out/v2.6.0/aquarius_trees/'
#model = 'MillGas/gp15newmg.anders/' #.anders 'MillGas/gp15newmg/'

path = '/gpfs/data/violeta/Galform_Out/v2.7.0/stable/'
#model = 'MillGas/gp17/'  #model = 'MillGas/gp17.spin/'
#model = 'MillGas/gp17.spin.ramt0.01/'
#model = 'MillGas/gp17.spin.ramt0.01.griffinBH/'
#model = 'MillGas/gp17.spin.ramt0.01.griffinBH.stb075/'
model = 'MillGas/gp17.spin.ramt0.01.stabledisk0.75.ac085/'

line = 'OII3727'
lline = '[OII]'
outdir = '/gpfs/data/violeta/lines/desi_hod_o2/'

ntypes = len(inleg)
cols = get_distinct(ntypes - 1)
cols.insert(0, 'k')

# Initialize GSMF
mmin = 8.
mmax = 15.
dm = 0.1
mbins = np.arange(mmin, mmax, dm)
mhist = mbins + dm * 0.5
# Initialize SSFR
smin = 3.
smax = 12.
ds = 0.1
sbins = np.arange(smin, smax, ds)
shist = sbins + ds * 0.5
예제 #38
0
def plot_function(data):
    print_times_Myr, print_smas_AU, print_rps_AU, print_parent_is_deg, canonical_rp_min_A_AU, canonical_rp_min_B_AU = data

    N_binaries = len(print_smas_AU)

    pyplot.rc('text', usetex=True)
    pyplot.rc('legend', fancybox=True)

    linewidth = 4
    dlinewidth = 2
    fig = pyplot.figure(figsize=(10, 9))
    plot1 = fig.add_subplot(2, 1, 1, yscale="log")
    plot2 = fig.add_subplot(2, 1, 2)

    from distinct_colours import get_distinct

    colors = get_distinct(4)
    labels = ["$A$", "$B$", "$C$"]
    labels_i = ["$i_{AC}$", "$i_{BC}$", None]
    for index_binary in range(N_binaries):
        label = labels[index_binary]
        label_i = labels_i[index_binary]
        color = colors[index_binary]

        plot1.plot(print_times_Myr,
                   print_smas_AU[index_binary],
                   color=color,
                   linestyle='dashed',
                   linewidth=dlinewidth)
        plot1.plot(print_times_Myr,
                   print_rps_AU[index_binary],
                   color=color,
                   linewidth=linewidth,
                   label=label)

        plot2.plot(print_times_Myr,
                   print_parent_is_deg[index_binary],
                   color=color,
                   linewidth=linewidth,
                   label=label_i)

    plot1.axhline(y=canonical_rp_min_A_AU,
                  color=colors[0],
                  linestyle='dotted',
                  linewidth=dlinewidth)
    plot1.axhline(y=canonical_rp_min_B_AU,
                  color=colors[1],
                  linestyle='dotted',
                  linewidth=dlinewidth)

    handles, labels = plot1.get_legend_handles_labels()
    plot1.legend(handles, labels, loc="upper right", fontsize=12)

    handles, labels = plot2.get_legend_handles_labels()
    plot2.legend(handles, labels, loc="lower right", fontsize=12)

    plot1.set_xlabel("t [Myr]", fontsize=18)
    plot2.set_xlabel("t [Myr]", fontsize=18)

    plot1.set_ylabel("$a_i [\mathrm{AU}]$", fontsize=18)
    plot2.set_ylabel("$i_{kl} [\mathrm{deg}]$", fontsize=18)

    plot1.set_xlim(0.0, print_times_Myr[-1])
    plot2.set_xlim(0.0, print_times_Myr[-1])

    plot1.tick_params(axis='both', which='major', labelsize=18)
    plot2.tick_params(axis='both', which='major', labelsize=18)

    fig.savefig("figure.eps")

    pyplot.show()
예제 #39
0
# Prep plot

path = '/cosma5/data/durham/violeta/lines/cosmicweb/fsat/' + model + '/'
outplot = path + prop + '.pdf'

ytit = ('% satellites (>x)')

fig = plt.figure(figsize=(8., 9.))
ax = plt.subplot()
ax.set_xlabel(xtit)
ax.set_ylabel(ytit)
ax.set_xlim(xmin, xmax)
ax.set_ylim(0., 30.)

cols = get_distinct(len(surveys))

#################

# Loop over the snapshots, reading the percenage of satellites

lstyle = ['-', '--']
for iz, sn in enumerate(snap_list):
    #infile = path+'test.dat'
    infile = path + prop + '_' + str(sn) + '.dat'

    # Read data
    data = np.loadtxt(infile)
    xdata = data[:, 0]

    for isy, survey in enumerate(surveys):
예제 #40
0
def plot_ionization(ism, N, which, rmax, t_end, rS, ip):

    r, x, R, X = get_ionization_fraction1d(ism)
    xx, yy, xi, hh, ll = get_ionization_fraction2d(ism)

    w = 14
    if ip > 1:
        pyplot.close('all')
        pyplot.clf()
    pyplot.figure(figsize=(w, 6))
    pyplot.rcParams.update({'font.size': 22})

    colors = get_distinct(3)
    #    rscolor = 'green'

    ax1 = pyplot.subplot(1, 2, 1)
    #ax1.scatter(r, x, c=colors[0], lw=0, s=10)
    ax1.scatter(r, x, c=x, lw=0, s=20, alpha=0.5, cmap="jet")
    ax1.plot(R[1:], X[1:], c=colors[1], lw=3)
    ax1.plot([rS, rS], [-1, 2], color=colors[2], linestyle='dashed', lw=3)
    ax1.text(rS + 0.08, 1.06, r'$R_s$', color=colors[2], fontsize=20)
    ax1.set_xlim(0, rmax)
    ax1.set_ylim(-0.04, 1.19)
    ax1.set_xlabel("r [pc]", fontsize=20)
    ax1.set_ylabel(r'$\xi_{\rm ion}$', fontsize=20)

    ax2 = pyplot.subplot(1, 2, 2)
    h = numpy.array(hh)
    h *= 72 * w / (6. * ll)  # approximate scaling
    ax2.set_aspect(1)
    sc2 = ax2.scatter(xx,
                      yy,
                      c=xi,
                      s=numpy.pi * h**2,
                      alpha=0.05,
                      edgecolor=None,
                      cmap="jet")
    if ll < rmax: ll = rmax
    ax2.set_xlim(-ll, ll)
    ax2.set_ylim(-ll, ll)
    ax2.set_xlabel("x [pc]", fontsize=20)
    ax2.set_ylabel("y [pc]", fontsize=20)
    #for axi in ax2.flat:
    ax2.xaxis.set_major_locator(pyplot.MaxNLocator(6))
    ax2.yaxis.set_major_locator(pyplot.MaxNLocator(6))
    #pyplot.colorbar(sc2, ax=ax2, fraction=0.046, pad=0.04)	# magic numbers!
    circle = pyplot.Circle((0, 0),
                           rS,
                           color=colors[2],
                           fill=False,
                           linestyle='dashed',
                           lw=3)
    ax2.add_artist(circle)

    if which == 0:
        id_string = 'Plummer_model'
    else:
        id_string = 'Homogeneous_sphere'

    param_string = "_N=%d_t=%.3f_Myr" % (N, t_end)

    #pyplot.suptitle(id_string+param_string, y=0.96, fontsize=16)

    savefile = 'fig_ionization_of_GMC_' + id_string + param_string + '.png'
    pyplot.savefig(savefile, dpi=300)
    print 'Figure saved in file', savefile

    if ip == 0: pyplot.show()
예제 #41
0
def main(N, W0, t_end, n_steps, filename, Mtot, Rvir, rgc, vgc):
    numpy.random.seed(111)
    converter = nbody_system.nbody_to_si(Mtot, Rvir)
    dt = t_end / float(n_steps)

    sun = Particles(1)
    sun.mass = 1 | units.MSun
    sun.radius = 1 | units.RSun
    sun.position = [-8400.0, 0.0, 17.0] | units.parsec
    x_label = "X [kpc]"
    y_label = "Y [kpc]"
    fig = pyplot.figure(figsize=(8, 8))
    pyplot.xlim(-10, 10)
    pyplot.ylim(-10, 10)
    pyplot.axis('equal')
    pyplot.xlabel("X [kpc]")
    pyplot.ylabel("Y [kpc]")
    colors = get_distinct(6)

    MWG = MilkyWay_galaxy()
    vc = MWG.vel_circ(sun.position.length())
    sun.velocity = [11.352, (12.24 + vc.value_in(units.kms)), 7.41] | units.kms
    sun.velocity *= -1

    print "Current Sun:"
    print sun

    print "\nFinding birth location of the Sun..."
    x, y = integrate_single_particle_in_potential(sun, t_end, dt, converter)
    pyplot.plot(x, y, lw=4, alpha=0.2, c=colors[1])

    print "Initial Sun:"
    print sun
    sun.velocity *= -1

    cluster = new_king_model(N, W0=3, convert_nbody=converter)
    cluster.mass = new_salpeter_mass_distribution(len(cluster),
                                                  0.1 | units.MSun,
                                                  10.0 | units.MSun)
    eps2 = 0.25 * (float(N)) ** (-0.666667) * Rvir ** 2
    cluster.scale_to_standard(convert_nbody=converter,
                              smoothing_length_squared=eps2)
    cluster.position += sun.position
    cluster.velocity += sun.velocity
    cluster.radius = 0 | units.parsec

    pyplot.scatter(cluster.x.value_in(units.kpc),
                   cluster.y.value_in(units.kpc),
                   s=10, c=colors[3])
    print '\nTracking', N, 'siblings'
    x, y = integrate_single_particle_in_potential(cluster, t_end, dt,
                                                  converter)
    size = cluster.mass / (0.1 | units.MSun)
    pyplot.scatter(cluster.x.value_in(units.kpc),
                   cluster.y.value_in(units.kpc),
                   c=colors[0], alpha=1.0, lw=0, s=size)
    pyplot.scatter(sun.x.value_in(units.kpc),
                   sun.y.value_in(units.kpc),
                   marker='+', s=100, c=colors[2])

    pyplot.scatter([0], [0], marker="+", s=300, c='r')
    pyplot.scatter([-8.4], [0], marker="o", s=100, c='g')

    save_file = 'SolarClusterInPotential.png'
    pyplot.savefig(save_file)
    print '\nSaved figure in file', save_file, '\n'
    pyplot.show()
예제 #42
0
파일: lf_K.py 프로젝트: viogp/cosmicwebSnap
ymax = -1.

xtit = "${{\\rm M_{AB}(" + iband + ")}\, -\, 5log{\\rm h}}$"
ytit = "$log(\Phi/ \\rm{h^{3} Mpc^{-3} mag^{-1}})$"
fig = plt.figure(figsize=(8.5, 9.))
jj = 111
ax = fig.add_subplot(jj)
ax.set_autoscale_on(False)
ax.set_xlim(xmin, xmax)
ax.set_ylim(ymin, ymax)
ax.set_xlabel(xtit)
ax.set_ylabel(ytit)
#ax.tick_params(labelsize=fs-2)
start, end = ax.get_xlim()

cols = get_distinct(len(models))
colors = cols
g = ['grey']
colors.extend(g)

# Observational data
dobs = '/cosma/home/violeta/Galform2/galform-2.6.0/Obs_Data2/'
fobs = 'lfk_z0_driver12.data'

# Plot observations
file = dobs + fobs
# Driver observations
mag, den, err, num = np.loadtxt(file, unpack=True)
ind = np.where(den > 0.)
x = mag[ind]
y = np.log10(den[ind] / 0.5)  # Observations are per 0.5 mag
예제 #43
0
def Sun_and_M67_in_the_Galaxy():

    bodies = Particles(2)
    Sun = bodies[0]
    v_LSR = (-10, 5.2, 7.2) | units.kms
    Sun.mass = 1 | units.MSun
    Sun.radius = 1 | units.RSun
    Sun.position = (8.4, 0.0, 0.017) | units.kpc
    Sun.velocity = (-11.4, 232, 7.41) | units.kms  # SPZ2009

    M67 = bodies[1]
    M67.mass = 50000 | units.MSun
    M67.radius = 3 | units.parsec
    M67.position = Sun.position + ((0.766, 0.0, 0.49) | units.kpc)
    M67.velocity = Sun.velocity + ((31.92, -21.66, -8.87) | units.kms)

    bodies.velocity *= -1

    simulation_time = 4600. | units.Myr
    dt_bridge = 5 | units.Myr
    OS = 20 | (units.kms / units.kpc)
    OB = 40 | (units.kms / units.kpc)
    A = 1300 | (units.kms**2 / units.kpc)
    M = 1.4e10 | units.MSun
    m = 2
    phi_bar, phi_sp = -0.34906, -0.34906
    inte = IntegrateOrbit(t_end=simulation_time,
                          dt_bridge=dt_bridge,
                          phase_bar=phi_bar,
                          phase_spiral=phi_sp,
                          omega_spiral=OS,
                          omega_bar=OB,
                          amplitude=A,
                          m=m,
                          mass_bar=M)

    MW = inte.galaxy()
    print(MW.parameters)
    print(MW.get_phi21())

    print("Backwards integration")
    time, xf, yf, zf, vxf, vyf, vzf, bar_angle, spiral_angle, t1, d1 = inte.get_pos_vel_and_orbit(
        bodies)
    print("Birth position of the Sun:", xf, yf, zf, vxf, vyf, vzf)
    print("---")
    print('time after backward integration:', time)

    colors = get_distinct(4)
    figure = pyplot.figure(figsize=(16, 12))
    ax = pyplot.gca()
    ax.minorticks_on()  # switch on the minor ticks
    ax.locator_params(nbins=3)

    x_label = "t [Gyr]"
    y_label = "d [kpc]"
    pyplot.xlabel(x_label)
    pyplot.ylabel(y_label)
    pyplot.plot(-t1.value_in(units.Gyr),
                d1.value_in(units.kpc),
                lw=3,
                c=colors[0])
    pyplot.ylim(0, 6)
    pyplot.xlim(-5, 0)
    pyplot.savefig("sun_and_M67")
    pyplot.show()
    """
예제 #44
0
#snap_list = [44, 42, 40, 37, 34] #MillGas
snap_list = [42, 40]
nvol = 3 #64

#path = '/gpfs/data/violeta/Galform_Out/v2.6.0/aquarius_trees/'
#model = 'MillGas/gp15newmg.anders/' #.anders 'MillGas/gp15newmg/'

path = '/gpfs/data/violeta/Galform_Out/v2.7.0/stable/'
#model = 'MillGas/gp17/'  #model = 'MillGas/gp17.spin/' 
model = 'MillGas/gp17.spin.ramt0.01/'

line = 'OII3727' ; lline = '[OII]'
outdir = '/gpfs/data/violeta/lines/desi_hod_o2/'

ntypes = len(inleg) 
cols = get_distinct(ntypes-1) ; cols.insert(0,'k')

# Initialize GSMF
mmin = 8.
mmax = 15.
dm = 0.1
mbins = np.arange(mmin,mmax,dm)
mhist = mbins + dm*0.5
# Initialize SSFR
smin = 3.
smax = 12.
ds = 0.1
sbins = np.arange(smin,smax,ds)
shist = sbins + ds*0.5

nlevel = 10
예제 #45
0
from optparse import OptionParser

from prepare_figure import single_frame, figure_frame, set_tickmarks
from distinct_colours import get_distinct

black = '#000000'
green = '#00FF00'
red = '#FF0000'
blue = '#0000FF'
lbl = '#FF00FF'
magenta = '#00FFFF'

Integrator = ["Hermite", "MI6", "ph4", "Huayno", "ph4_GPU",
              "Gadget2", "BHTree", "Fi_3", "Bonsai"]
color = ['r', 'g', 'k', 'b', 'k', lbl, 'm', 'r', 'g', 'b', 'k', 'm']
color = get_distinct(len(color))
lstyles = ['-.', '-.', '-.', '-.', '--', '-', '-', '-', '-']
lwidth = [2, 2, 4, 2, 4, 2, 2, 2, 4]

def read_file(filename, column, keyword):
    x = []
    fptr = open(filename)
    lines = fptr.readlines()
    for line in lines:
        l = line.split()
        if l[1]==keyword:
            # print line
            x.append(float(line.split()[column]))
    fptr.close()
    return x
예제 #46
0
def kira(tend, N, R, Nbin):
    logging.basicConfig(level=logging.ERROR)

    mass = new_salpeter_mass_distribution(N, mass_min=10 | units.MSun)
    converter = nbody_system.nbody_to_si(mass.sum(), R)
    code = Hermite(converter)
    stars = new_plummer_model(N, convert_nbody=converter)
    stars.mass = mass
    stars.radius = 0.01 / len(stars) | R.unit

    single_stars, binary_stars, singles_in_binaries \
        = make_secondaries(stars, Nbin)
    print(binary_stars)

    stellar = SeBa()
    stellar.particles.add_particles(single_stars)
    stellar.particles.add_particles(singles_in_binaries)
    stellar.binaries.add_particles(binary_stars)
    channel_to_stars = stellar.particles.new_channel_to(stars)

    encounter_code = encounters.HandleEncounter(
        kepler_code=new_kepler(converter),
        resolve_collision_code=new_smalln(converter),
        interaction_over_code=None,
        G=constants.G)
    multiples_code = encounters.Multiples(gravity_code=code,
                                          handle_encounter_code=encounter_code,
                                          G=constants.G)
    multiples_code.particles.add_particles((stars - binary_stars).copy())
    multiples_code.singles_in_binaries.add_particles(singles_in_binaries)
    multiples_code.binaries.add_particles(binary_stars)
    multiples_code.commit_particles()
    channel_from_stars_to_particles \
        = stellar.particles.new_channel_to(multiples_code.particles)

    stopping_condition \
        = multiples_code.stopping_conditions.binaries_change_detection
    stopping_condition.enable()

    from matplotlib import pyplot
    from distinct_colours import get_distinct
    pyplot.rcParams.update({'font.size': 30})
    figure = pyplot.figure(figsize=(12, 9))
    ax = pyplot.gca()
    ax.get_yaxis().get_major_formatter().set_useOffset(False)
    ax.xaxis._autolabelpos = True
    ax.yaxis._autolabelpos = True

    color = get_distinct(2)
    pyplot.scatter(numpy.log10(
        stellar.binaries.semi_major_axis.value_in(units.AU)),
                   stellar.binaries.eccentricity,
                   c=color[0],
                   s=200,
                   lw=0)

    t = quantities.linspace(0 * tend, tend, 11)
    for ti in t:
        print(("t, Energy=", ti, multiples_code.particles.mass.sum(), \
              multiples_code.get_total_energy()))
        multiples_code.evolve_model(ti)
        print(("at t=", multiples_code.model_time, \
              "Nmultiples:", len(multiples_code.multiples)))

        if stopping_condition.is_set():
            resolve_changed_binaries(stopping_condition, stellar, converter)

        stellar.evolve_model(ti)
        channel_from_stars_to_particles.copy_attributes(["mass", "radius"])
        update_dynamical_binaries_from_stellar(stellar, multiples_code,
                                               converter)

        print(("Lagrangian radii:", \
              multiples_code.all_singles.LagrangianRadii(converter)))
        print(("MC.particles", multiples_code.particles))
        print(("Lagrangian radii:", \
              multiples_code.particles.LagrangianRadii(converter)))
        print(("t, Energy=", ti, multiples_code.get_total_energy()))

    pyplot.scatter(numpy.log10(
        stellar.binaries.semi_major_axis.value_in(units.AU)),
                   stellar.binaries.eccentricity,
                   c=color[1],
                   lw=0,
                   s=50)
    pyplot.xlabel("$\log_{10}(a/R_\odot)$")
    pyplot.ylabel("eccentricity")

    save_file = 'kira_a_vs_e.pdf'
    pyplot.savefig(save_file)
    print('\nSaved figure in file', save_file, '\n')
    pyplot.show()

    stellar.stop()
예제 #47
0

if __name__ == "__main__":

    x_label = "L [LSun]"
    y_label = "density [$g/cm^{3}$]"
    figure = single_frame(x_label,
                          y_label,
                          logx=True,
                          logy=True,
                          xsize=12,
                          ysize=10)

    mass = [1, 1, 5, 5, 10, 10] | units.MSun
    age = [1, 10000, 1, 90, 1, 20] | units.Myr
    c = get_distinct(3)
    color = []
    ls = []
    for ci in c:
        color.append(ci)
        color.append(ci)
        ls.append("-")
        ls.append("--")
    symbol = ['v', 'v', 'o', 'o', '^', '^']
    i = 0
    for imass in range(len(mass)):
        dm = 0.2 * mass[imass]
        time = age[imass]
        m, L, rho = stellar_density_profile_at_time(mass[imass], time)
        pyplot.plot(L.value_in(units.LSun),
                    rho.value_in(units.g / units.cm**3),
def plot_single_image(planets, debris, disk, shell, figfile=None):

    if len(shell)>0:
        disk.add_particles(shell)
    lim = 150
    """
    #centered on the Sun
    if len(planets)>1:
        print "Center on COM"
        com = planets[0].position
        vcom = planets[0].velocity
        planets.position -= com
        planets.velocity -= vcom
        disk.position -= com
        disk.velocity -= vcom
        debris.position -= com
        debris.velocity -= vcom
    """
    
    left, width = 0.1, 0.65
    bottom, height = 0.1, 0.65
    bottom_h = left_h = left+width+0.05
    rect_scatter = [left, bottom, width, height]
    rect_histx = [left, bottom_h, width, 0.2]
    rect_histy = [left_h, bottom, 0.2, height]

    fig = pyplot.figure(figsize=(12,12))	
    time = disk.get_timestamp()
#    pyplot.title("Cluster at t="+str(time.in_(units.Gyr)))
    xy = pyplot.axes(rect_scatter)
    #xy.text(110,110, "protoplanetary disk (img#"+str(index)+")",  ha='left', va='bottom')
    xz = pyplot.axes(rect_histx)
    yz = pyplot.axes(rect_histy)
    xy.set_xlabel("X [AU]")
    xy.set_ylabel("Y [AU]")
    xz.set_ylabel("Z [AU]")
    yz.set_xlabel("Z [AU]")

    positions = disk.position
    x, y, z = positions.x.value_in(units.AU), positions.y.value_in(units.AU), positions.z.value_in(units.AU)

#    sizes = 1000
#    sizes = 1000*disk.rho/disk.rho.max()
    alpha = 0.01
    us        = disk.u
    if hasattr(disk, "xion"):
        xs        = disk.xion
    else:
        xs = numpy.zeros(len(disk))
    u_min, u_max = min(us), max(us)
    xion_min, xion_max = min(xs), max(xs)
#    if xion_min<=0:
#        xion_min = xion_max/100.
#        xs += xion_min
#        xion_max += xion_min
    print "u=", u_min, u_max
    Ts = mu() / constants.kB * disk.u
    T_min = max(20|units.K, mu() / constants.kB * u_min)
    T_max = min(1800|units.K, mu() / constants.kB * u_max)
    print "T=", T_min, T_max
    print "X=", xion_min, xion_max

    log_u = numpy.log((us / u_min)) / numpy.log((u_max / u_min))
    clipped_log_u = numpy.minimum(numpy.ones_like(log_u), numpy.maximum(numpy.zeros_like(log_u), log_u))

#    log_x = numpy.log((xs / xion_min)) / numpy.log((xion_max / xion_min))
#    clipped_log_x = numpy.minimum(numpy.ones_like(log_x), numpy.maximum(numpy.zeros_like(log_x), log_x))
#    xrange = (xs/xion_min) / (xion_max/xion_min)
#    print "xrange=", xrange.min(), xrange.max()
    clipped_log_x = xs


    log_T = numpy.log((Ts / T_min)) / numpy.log((T_max / T_min))
    clipped_log_T = numpy.minimum(numpy.ones_like(log_T), numpy.maximum(numpy.zeros_like(log_T), log_T))
    
    ps = disk.rho
    p_min, p_max = min(ps), max(ps)
    log_p = numpy.log((ps / p_min)) / numpy.log((p_max / p_min))
    clipped_log_p = numpy.minimum(numpy.ones_like(log_p), numpy.maximum(numpy.zeros_like(log_p), log_p))

    #    red   = 1 - clipped_log_u**(1./2.)
#    blue  = clipped_log_u**(1./2.)
#    green = numpy.minimum(red, blue)
#    red   = 1.0 - clipped_log_T
#    red   = 1-clipped_log_x**(1./2.)
    blue  = clipped_log_T
    red  = 1-clipped_log_T
    #green = numpy.minimum(red, blue)
    green = clipped_log_p
    colors = numpy.transpose(numpy.array([red, green, blue]))

    sizes = 2*2000*disk.h_smooth/disk.h_smooth.max()
    xy.scatter(x, y, sizes, c=colors, edgecolors = "none", alpha = alpha)
    xy.set_xlim( (-lim, lim) )
    xy.set_ylim( (-lim, lim) )
    sizes = 2*200*disk.h_smooth/disk.h_smooth.max()
    xz.scatter(x, z, sizes, c=colors, edgecolors = "none", alpha = alpha)
    yz.scatter(z, y, sizes, c=colors, edgecolors = "none", alpha = alpha)
    xz.set_xlim( xy.get_xlim() )
    yz.set_ylim( xy.get_xlim() )
    yz.set_xlim( (-0.1*lim, 0.1*lim) )
    xz.set_ylim( (-0.1*lim, 0.1*lim) )
#    yz.set_xlim( (-lim, lim) )
#    xz.set_ylim( (-lim, lim) )

    if len(debris)>0:
        c = 'k'
        m = 0.1
        xy.scatter(debris.x.value_in(units.AU), debris.y.value_in(units.AU), s=m, c=c, lw=0) 
        xz.scatter(debris.x.value_in(units.AU), debris.z.value_in(units.AU), s=m, c=c, lw=0) 
        yz.scatter(debris.z.value_in(units.AU), debris.y.value_in(units.AU), s=m, c=c, lw=0) 

    if len(planets)>0:
        from distinct_colours import get_distinct
        c = get_distinct(len(planets))
        m = 1000 * planets.mass/planets.mass.max()
        m[0] = min(10*m[1:].max(), 30)
        xy.scatter(planets.x.value_in(units.AU), planets.y.value_in(units.AU), s=m, c=c, lw=0) 
        xz.scatter(planets.x.value_in(units.AU), planets.z.value_in(units.AU), s=m, c=c, lw=0) 
        yz.scatter(planets.z.value_in(units.AU), planets.y.value_in(units.AU), s=m, c=c, lw=0) 

    filename = "planetary_system.png"
    fig.savefig(filename)
예제 #49
0
    result.add_option("-R", unit=units.parsec,
                      dest="Rcluster", type="int", default = 1000|units.AU,
                      help="Cluster size [%default]")
    result.add_option("-n", 
                      dest="n", type="int", default = 100,
                      help="Number of pebbels per star [%default]")
    return result


if __name__ in ('__main__', '__plot__'):
    o, arguments  = new_option_parser().parse_args()

    filename = "sunandM67.hdf5"
    sun_and_planets = read_set_from_file(filename, "amuse")

    colors = get_distinct(4)
    figure = pyplot.figure(figsize=(16, 12))
    ax = pyplot.gca()
    ax.minorticks_on() # switch on the minor ticks
    ax.locator_params(nbins=3)

    x_label = "t [Gyr]"
    y_label = "$Z [kpc]$"
    pyplot.xlabel(x_label)
    pyplot.ylabel(y_label)
    
#    pyplot.ylim(0, 1)
    R = [] 
    Z = [] | units.kpc
    d = [] | units.kpc
    t = [] | units.Gyr
예제 #50
0
def main(M1, M2, M3, Pora, Pin, ain, aout, ein, eout, t_end, nsteps, scheme,
         dtse_fac):

    t_begin = ctime.time()

    x_label = "$a/a_{0}$"
    y_label = "$e/e_{0}$"
    fig = single_frame(x_label,
                       y_label,
                       logx=False,
                       logy=False,
                       xsize=10,
                       ysize=8)
    color = get_distinct(4)

    if scheme == 0:
        srange = [1, 2, 3]
    else:
        srange = [scheme]

    i = 0
    for s in srange:
        time, ai, ei, ao, eo, inci, inco, time_framework = evolve_triple_with_wind(
            M1, M2, M3, Pora, Pin, ain, aout, ein, eout, t_end, nsteps, s,
            dtse_fac)
        if i == 0:
            pyplot.plot(ai, ei, c=color[0], label='inner')
            pyplot.plot(ao, eo, c=color[1], label='outer')
            i = 1
        else:
            pyplot.plot(ai, ei, c=color[0])
            pyplot.plot(ao, eo, c=color[1])

    pyplot.legend(loc='best', ncol=1, shadow=False, fontsize=20)
    pyplot.title('Relative orbital parameters for t=0.1Myr')
    pyplot.xlabel('$a/a_0$')
    pyplot.ylabel('$e/e_0$')
    #save_file = 'evolve_triple_with_wind.png'
    save_file = 'evolve_triple_with_wind' \
                    +'_s={:d}_dtse={:.3f}'.format(scheme, dtse_fac) \
                    +'.png'
    pyplot.savefig(save_file)
    print '\nSaved figure in file', save_file, '\n'
    #pyplot.show()
    data = numpy.array(zip(ai, ei))
    numpy.save('aiei0', data)

    data = numpy.array(zip(inci, inco))
    numpy.save('incoinci0', data)

    data = numpy.array(zip(ao, eo))
    numpy.save('aoeo0', data)

    t_end = ctime.time()

    total_time = t_end - t_begin

    print 'Total time, ', total_time
    print 'Total time in framework, ', time_framework
    print time_framework / total_time * 100, '% spend in non-Amuse framework'
    data = numpy.array(
        [total_time, time_framework, time_framework / total_time * 100])
    numpy.save('time0', data)
예제 #51
0
    for pri in precision:
        dEi = energy_error_of_integrated_Nbody_system(code, particles,
                                                      t_end, pri)
        dE.append(abs(dEi))
        print "integrated with precision=", pri, "dE/E=", dEi
    return dE
    
if __name__ in ('__main__','__plot__'):

    numpy.random.seed(31415)

    particles = new_plummer_model(1000)
    precision = 10.**numpy.linspace(0., -3., 10)

    t_end = 1.0| nbody_system.time
    cols = get_distinct(2)
    
    print 'ph4'
    code = ph4
    dE = get_dE(code, precision, t_end)
    pyplot.scatter(precision, dE, c=cols[0], lw=0, s=50, marker='o')

    print 'BHTree'
    code = BHTree
    dE = get_dE(code, precision, t_end)
    pyplot.scatter(precision, dE, c=cols[1], lw=0, s=50, marker='^')

    t0 = 0.8
    t1 = 0.02
    ep = 4.e-5
    eb = 0.07
예제 #52
0
                      help="Cluster size [%default]")
    result.add_option("-n",
                      dest="n",
                      type="int",
                      default=100,
                      help="Number of pebbels per star [%default]")
    return result


if __name__ in ('__main__', '__plot__'):
    o, arguments = new_option_parser().parse_args()

    filename = "sunandM67.hdf5"
    sun_and_planets = read_set_from_file(filename, "amuse")

    colors = get_distinct(4)
    figure = pyplot.figure(figsize=(16, 12))
    ax = pyplot.gca()
    ax.minorticks_on()  # switch on the minor ticks
    ax.locator_params(nbins=3)

    x_label = "t [Gyr]"
    y_label = "$Z [kpc]$"
    pyplot.xlabel(x_label)
    pyplot.ylabel(y_label)

    #    pyplot.ylim(0, 1)
    R = []
    Z = [] | units.kpc
    d = [] | units.kpc
    t = [] | units.Gyr
예제 #53
0
matplotlib.use('Agg')
from matplotlib import pyplot as plt
from Cosmology import *
import scipy.ndimage
from distinct_colours import get_distinct
import mpl_style
from astropy.io import fits

plt.style.use(mpl_style.style1)

dir = '/cosma5/data/durham/violeta/Galform_Out/v2.7.0/stable/MillGas/'
nvol = 64
model = 'gp19/'

zlist = [61, 44, 41, 39, 34]  #z=0.6, 0.83, 1., 1.5
cols = get_distinct(len(zlist))

#############################
line = 'OII3727'
lline = '[OII]'
outdir = '/cosma5/data/durham/violeta/lines/cosmicweb/plots/' + model
plotfile = outdir + line + '_decam.pdf'

fluxcut = 8. * 10.**-17.

#############################
# Prepare plots
fig = plt.figure(figsize=(8.5, 9.))

plt.xlabel("$(r-z)_{\\rm DECam}$")
plt.ylabel("$(g-r)_{\\rm DECam}$")
예제 #54
0
for i in range(len(mbins)):
    if ntot[index, i] > 0.:
        npas[index, i] = npas[index, i] / ntot[index, i]
        nsp[index, i] = nsp[index, i] / ntot[index, i]
        nsat[index, i] = nsat[index, i] / ntot[index, i]
    else:
        npas[index, i] = -999.
        nsp[index, i] = -999.
        nsat[index, i] = -999.

############

# Figure http://matplotlib.org/users/gridspec.html
fig = plt.figure(figsize=(8.5, 9.))
ax = plt.subplot()
cols = get_distinct(len(inleg) + 1)
colors = cols
g = ['grey']  #; colors.extend(g) ; colors.extend(g)
colors[len(colors) - 1] = 'grey'
colors.extend(g)

xtit = "$log(\\rm{M_{*}/M_{\odot} h^{-1}})$"
ytit = "Passive fraction"
ax.set_xlabel(xtit)
ax.set_ylabel(ytit)
ax.set_autoscale_on(False)
ax.minorticks_on()
ax.set_xlim(mmin, 12)
ax.set_ylim(0., 1.)

# Observations
예제 #55
0
                      help="metalicity [0.02]")
    return result


if __name__ in ('__main__', '__plot__'):
    o, arguments = new_option_parser().parse_args()

    x_label = "T [$K$]"
    y_label = "L [$L_\odot$]"
    figure = single_frame(x_label,
                          y_label,
                          logx=False,
                          logy=True,
                          xsize=14,
                          ysize=10)
    color = get_distinct(6)

    L, T = single_star_evolution(M=1.4 | units.MSun,
                                 z=0.04,
                                 model_time=4 | units.Gyr)
    pyplot.plot(T.value_in(units.K), L.value_in(units.LSun), c=color[0])

    L, T = single_star_evolution(**o.__dict__)
    pyplot.plot(T.value_in(units.K), L.value_in(units.LSun), c=color[4])

    m67 = plot_M67Data.Cluster()
    m67.read()
    pyplot.scatter(m67.Teff, m67.L, c=color[1], lw=0, s=100)

    pyplot.scatter(TBSS, LBSS, c=color[3], lw=0, s=250)
    pyplot.scatter(TBSS[3], LBSS[3], c=color[2], lw=0, s=250)
예제 #56
0
snap_list = [42]
nvol = 3  #64

zleg = []
bands = ['DEIMOS-R', 'MegaCam-i-atmos', 'MegaCam-i-atmos']
mcuts = [24.1, 22.5, 24]
fcuts = [
    2.7 * 10.**-17., 3.5 * 10.**-17., 1.9 * 10.**-17., 10.**-16.,
    8. * 10.**-17.
]
inleg = [
    'DEEP2 cuts', 'VVDS-Wide cuts', 'VVDS-Deep cuts', 'eBOSS cuts', 'DESI cuts'
]

cols = ['gray']
cols.extend(get_distinct(len(inleg)))
# Initialize histogram
lmin = 8.5
lmax = 16.
dl = 0.1
lbins = np.arange(lmin, lmax, dl)
lhist = lbins + dl * 0.5

############################################
# Initialize the parameters for the figures
ytit = "$log_{10} (\\rm M_{*}/M_{\odot}h^{-1})$"
xtit = "$log_{10} (\\rm M_{\\rm halo}/M_{\odot}h^{-1})$"

ymin = 8.
ymax = 11.5
xmin = 10.5