def main(filename="stellar.hdf5"): Tmax = 100000 #| untis.K Tmin = 1000 #| untis.K Lmax = 1.e+6 #| untis.LSun Lmin = 0.01 #| untis.LSun pyplot.ion() filename = "nbody.hdf5" stars = read_set_from_file(filename, 'hdf5') m = 1 + 3.0 * stars.mass / min(stars.mass) lim = 2 * max( max(stars.x).value_in(stars.x.unit), stars.center_of_mass().length().value_in(stars.x.unit)) for si in reversed(list(stars.iter_history())): c = si.temperature.value_in(units.K) scatter(si.temperature.value_in(units.K), si.luminosity.value_in(units.LSun), s=m, c=c, cmap=pyplot.cm.hsv) pyplot.xlabel("T [K]") pyplot.ylabel("L [$L_\odot$]") pyplot.xlim(Tmax, Tmin) pyplot.ylim(Lmin, Lmax) pyplot.loglog() pyplot.draw() pyplot.cla() pyplot.show()
def make_movie(input_filename, output_filename): cluster, gas = read_set_from_file(input_filename, 'amuse', names=("cluster", "gas")) lim = abs(next(cluster.history).position).max() fig = pyplot.figure(figsize=[10,10]) artists = [] for cl, gas in zip(cluster.history, gas.history): print "Creating frame at time", cl.get_timestamp() points = aplot.scatter(cl.x, cl.y, c='black') gas_points = aplot.scatter(gas.x, gas.y, s=100, c='b', edgecolors='none', alpha=0.3, rasterized=True) time_label = "t = {:.2f} Myr".format( cl.get_timestamp().value_in(units.Myr)) text = aplot.text(-4./5.*lim, 4./5.*lim, time_label) aplot.xlabel("X") aplot.ylabel("Y") pyplot.axis('equal') aplot.xlim(-lim, lim) aplot.ylim(-lim, lim) pyplot.savefig("plots/test."+str(cl.get_timestamp().value_in(units.Myr))+".png") pyplot.close() artists.append((points, gas_points, text))
def test_wind_creation_constant(self): numpy.random.seed(123457) star = self.create_star() star.initial_wind_velocity = star.terminal_wind_velocity star_wind = stellar_wind.new_stellar_wind( 3e-11 | units.MSun, mode="accelerate", acceleration_function="constant_velocity", ) star_wind.particles.add_particles(star) star_wind.evolve_model(10 | units.day) wind = star_wind.create_wind_particles() self.assertEqual(len(wind), 912) radii = (wind.position - star.position).lengths() velocities = (wind.velocity - star.velocity).lengths() self.assertGreaterEqual(radii.min(), star.radius) self.assertLessEqual(radii.max(), 8.212 | units.RSun) self.assertAlmostEqual(radii.mean(), 2.32897955194 | units.RSun) self.assertAlmostEqual(velocities.min(), star.initial_wind_velocity) self.assertAlmostEqual(velocities.max(), star.initial_wind_velocity) return from matplotlib import pyplot from amuse import plot as aplot import pylab n, bins, patches = pylab.hist(radii.value_in(units.RSun), 10) pylab.show() pyplot.clf() aplot.scatter(radii, velocities) pyplot.show()
def main(N=10, t_end=10 | units.Myr, dt=1 | units.Myr, filename="stellar.hdf5", Mmin=1.0 | units.MSun, Mmax=100 | units.MSun, z=0.02, C="SeBa"): if C.find("SeBa") >= 0: print "SeBa" stellar = SeBa() elif C.find("SSE") >= 0: print "SSE" stellar = SSE() elif C.find("MESA") >= 0: stellar = MESA() elif C.find("EVtwin") >= 0: stellar = EVtwin() else: print "No stellar model specified." return stellar.parameters.metallicity = z mZAMS = new_salpeter_mass_distribution(N, Mmin, Mmax) mZAMS = mZAMS.sorted() bodies = Particles(mass=mZAMS) stellar.particles.add_particles(bodies) stellar.commit_particles() write_set_to_file(stellar.particles, filename, 'hdf5') Mtot_init = stellar.particles.mass.sum() time = 0.0 | t_end.unit while time < t_end: time += dt stellar.evolve_model(time) write_set_to_file(stellar.particles, filename, 'hdf5') Mtot = stellar.particles.mass.sum() print "T=", time, print "M=", Mtot, "dM[SE]=", Mtot / Mtot_init #, stellar.particles[0].stellar_type T = [] L = [] r = [] import math for si in stellar.particles: T.append(math.log10(si.temperature.value_in(units.K))) L.append(math.log10(si.luminosity.value_in(units.LSun))) r.append(1.0 + 10 * si.radius.value_in(units.RSun)) stellar.stop() pyplot.xlim(4.5, 3.3) pyplot.ylim(-4.0, 3.0) scatter(T, L, s=r) pyplot.xlabel("$log_{10}(T/K)$") pyplot.ylabel("$log_{10}(L/L_\odot)$") pyplot.show()
def plot_sph(gas): # Adjusted code from amuse.plot.sph_particles_plot pyplot.gcf().sca(ax_gas) min_size = 100 max_size = 10000 alpha = 0.1 x = gas.x y = gas.y z = gas.z z, x, y, us, h_smooths = z.sorted_with(x, y, gas.u, gas.h_smooth) u_min, u_max = min(us), max(us) 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)) red = 1.0 - clipped_log_u**4 blue = clipped_log_u**4 green = numpy.minimum(red, blue) colors = numpy.transpose(numpy.array([red, green, blue])) n_pixels = pyplot.gcf().get_dpi() * pyplot.gcf().get_size_inches() ax_gas.set_axis_bgcolor('#101010') ax_gas.set_aspect("equal", adjustable="datalim") length_unit = smart_length_units_for_vector_quantity(x) phys_to_pix2 = n_pixels[0]*n_pixels[1] / ((max(x)-min(x))**2 + (max(y)-min(y))**2) sizes = numpy.minimum(numpy.maximum((h_smooths**2 * phys_to_pix2), min_size), max_size) scatter(x.as_quantity_in(length_unit), y.as_quantity_in(length_unit), color=colors, s=sizes, edgecolors="none", alpha=alpha)
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 main(**options): print "calculating shock using exact solution" exact = CalculateExactSolutionIn1D() xpositions, rho, p, u = exact.get_solution_at_time(0.12 | time) print "calculating shock using code" model = CalculateSolutionIn3D(**options) grids = model.get_solution_at_time(0.12 | time) print "sampling grid" if model.name_of_the_code in model.sph_hydro_codes: samples = grids else: samplepoints = [(x, 0.5, 0.5) | length for x in numpy.linspace(0.0, 1.0, 2000)] print len(grids) samples = SamplePointsOnMultipleGrids(grids, samplepoints, SamplePointOnCellCenter) print len(samples) samples.filterout_duplicate_indices() print len(samples) print "saving data" store_attributes(xpositions,rho,u,p,filename="exact_riemann_shock_tube_problem.csv") store_attributes(samples.x,samples.rho,samples.rhovx,samples.energy,filename="riemann_shock_tube_problem.csv") if IS_PLOT_AVAILABLE: print "plotting solution" plot.plot(xpositions,rho) plot.scatter(samples.x, samples.rho) pyplot.xlim(0.3,0.7) pyplot.ylim(0.5,4.5) pyplot.savefig("riemann_shock_tube_rho_"+model.name_of_the_code+".png") pyplot.show()
def get_mass_via_number_density(cluster): # progressbar import sys pbwidth = 42 # TODO: find different method to calculate M(<r) print "Counting particles for which radii < r to obtain M(<r)" radii = VectorQuantity.arange(units.kpc(1), units.kpc(10000), units.parsec(1000)) M_gas_below_r = numpy.zeros(len(radii)) M_dm_below_r = numpy.zeros(len(radii)) N = len(radii) for i, r in enumerate(radii): M_gas_below_r[i] = ((numpy.where(cluster.gas.r < r)[0]).size) M_dm_below_r[i] = ((numpy.where(cluster.dm.r < r)[0]).size) if i % 1000 == 0: # update the bar progress = float(i + 1000) / N block = int(round(pbwidth * progress)) text = "\rProgress: [{0}] {1:.1f}%".format( "#" * block + "-" * (pbwidth - block), progress * 100) sys.stdout.write(text) sys.stdout.flush() sys.stdout.write("\n") print "Done counting particles :-)... TODO: improve this method?!" M_gas_below_r *= cluster.M_gas / cluster.raw_data.Ngas M_dm_below_r *= cluster.M_dm / cluster.raw_data.Ndm amuse_plot.scatter(radii, M_gas_below_r, c="g", label="Gas") amuse_plot.scatter(radii, M_dm_below_r, c="b", label="DM")
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 main(filename): pyplot.figure(figsize=(12, 12)) particles = read_set_from_file(filename, "amuse") for si in particles.history: scatter(si.x, si.y, s=100) xlabel("x") ylabel("y") pyplot.show()
def main(filename): pyplot.figure(figsize=(12,12)) particles = read_set_from_file(filename, "hdf5") for si in particles.history: scatter(si.x, si.y, s=100) xlabel("x") ylabel("y") pyplot.show()
def plot_individual_cluster_mass(numerical, analytical, poster_style=False): pyplot.figure(figsize=(16, 12)) if poster_style: pyplot.style.use(["dark_background"]) pyplot.rcParams.update({"font.weight": "bold"}) fit_colour = "white" else: fit_colour = "k" # magenta, dark blue, orange, green, light blue (?) data_colour = [(255. / 255, 64. / 255, 255. / 255), (0. / 255, 1. / 255, 178. / 255), (255. / 255, 59. / 255, 29. / 255), (45. / 255, 131. / 255, 18. / 255), (41. / 255, 239. / 255, 239. / 255)] amuse_plot.scatter(numerical.gas_radii, numerical.M_gas_below_r, c=data_colour[0], edgecolor="face", s=4 if poster_style else 1, label="Gas, sampled") amuse_plot.scatter(numerical.dm_radii, numerical.M_dm_below_r, c=data_colour[2], edgecolor="face", s=4 if poster_style else 1, label="DM, sampled") pyplot.gca().set_xscale("log") pyplot.gca().set_yscale("log") # Analytical solutions. Sample radii and plug into analytical expression. # Plot analytical Hernquist model for the DM mass M(<r) amuse_plot.plot(analytical.radius, analytical.dm_cummulative_mass(), ls="solid", c=fit_colour, lw=5 if poster_style else 1, label="DM: Hernquist") # Plot analytical cut-off beta model (Donnert 2014) for the gas mass M(<r) amuse_plot.plot(analytical.radius, analytical.gas_mass(), ls="dotted", c=fit_colour, lw=5 if poster_style else 1, label="Gas: " + analytical.modelname) pyplot.xlabel(r"Radius [kpc]") pyplot.ylabel(r"Cummulative Mass [MSun]") pyplot.gca().set_xscale("log") pyplot.gca().set_yscale("log") pyplot.gca().set_xlim(xmin=1, xmax=1e4) pyplot.legend(loc=4)
def main(N=10): figure(figsize=(5,5)) bodies = new_plummer_model(N) scatter(bodies.x, bodies.y) xlim(-1, 1) ylim(-1, 1) xlabel("X") ylabel("Y") show()
def main(N=10): figure(figsize=(5, 5)) bodies = new_plummer_model(N) scatter(bodies.x, bodies.y) xlim(-1, 1) ylim(-1, 1) xlabel("X") ylabel("Y") show()
def main(**options): print "calculating shock using exact solution" exact = CalculateExactSolutionIn1D() xpositions, rho, p, u = exact.get_solution_at_time(0.12 | time) print "calculating shock using code" model = CalculateSolutionIn3D(**options) grids = model.get_solution_at_time(0.12 | time) print "sampling grid" if model.name_of_the_code in model.sph_hydro_codes: samples = grids else: samplepoints = [(x, 0.5, 0.5) | length for x in numpy.linspace(0.0, 1.0, 2000)] print len(grids) samples = SamplePointsOnMultipleGrids(grids, samplepoints, SamplePointOnCellCenter) print len(samples) samples.filterout_duplicate_indices() print len(samples) print "saving data" filename = "riemann_shock_tube_rho_" + model.name_of_the_code store_attributes(xpositions, rho, u, p, filename=filename + "_exact.csv") store_attributes(samples.x, samples.rho, samples.rhovx, samples.energy, filename=filename + ".csv") if IS_PLOT_AVAILABLE: print "plotting solution" from prepare_figure import * from distinct_colours import get_distinct x_label = "[length]" y_label = "[mass/length$^3$]" figure = single_frame(x_label, y_label, logx=False, logy=True, xsize=14, ysize=10) color = get_distinct(2) plot.plot(xpositions, rho, c=color[0]) plot.scatter(samples.x, samples.rho, c=color[1], s=100) # pyplot.xlim(0.3,0.7) # pyplot.ylim(0.5,4.5) pyplot.xlim(0.0, 1.0) # pyplot.ylim(0.5,4.5) pyplot.xlabel("[length]") pyplot.ylabel("[mass/length$^3$]") # pyplot.savefig("riemann_shock_tube_rho_"+model.name_of_the_code+".png") pyplot.savefig(filename) pyplot.show()
def group_plot(groups, no_group, figname="group_plot.png"): colors = ["r", "g", "b", "y", "k", "w"] * 100 for group, color in zip(groups, colors): scatter(group.x, group.y, c=color) if len(no_group): scatter(no_group.x, no_group.y, c="m", marker="s") native_plot.gca().set_aspect("equal", adjustable="datalim") native_plot.savefig(figname) native_plot.clf()
def group_plot(groups, no_group, figname="group_plot.png"): colors = ["r", "g", "b", "y", "k", "w"]*100 for group, color in zip(groups, colors): scatter(group.x, group.y, c=color) if len(no_group): scatter(no_group.x, no_group.y, c="m", marker="s") native_plot.gca().set_aspect("equal", adjustable = "datalim") native_plot.savefig(figname) native_plot.clf()
def main(N=10, t_end=10|units.Myr, dt=1|units.Myr, filename="stellar.hdf5", Mmin=1.0|units.MSun, Mmax= 100|units.MSun, z=0.02, C="SeBa"): if C.find("SeBa")>=0: print "SeBa" stellar = SeBa() elif C.find("SSE")>=0: print "SSE" stellar = SSE() elif C.find("MESA")>=0: stellar = MESA() elif C.find("EVtwin")>=0: stellar = EVtwin() else: print "No stellar model specified." return stellar.parameters.metallicity = z mZAMS = new_salpeter_mass_distribution(N, Mmin, Mmax) mZAMS = mZAMS.sorted() bodies = Particles(mass=mZAMS) stellar.particles.add_particles(bodies) stellar.commit_particles() write_set_to_file(stellar.particles, filename, 'hdf5') Mtot_init = stellar.particles.mass.sum() time = 0.0 | t_end.unit while time < t_end: time += dt stellar.evolve_model(time) write_set_to_file(stellar.particles, filename, 'hdf5') Mtot = stellar.particles.mass.sum() print "T=", time, print "M=", Mtot, "dM[SE]=", Mtot/Mtot_init #, stellar.particles[0].stellar_type T = [] L = [] r = [] import math for si in stellar.particles: T.append(math.log10(si.temperature.value_in(units.K))) L.append(math.log10(si.luminosity.value_in(units.LSun))) r.append(1.0+10*si.radius.value_in(units.RSun)) stellar.stop() pyplot.xlim(4.5, 3.3) pyplot.ylim(-4.0, 3.0) scatter(T, L, s=r) pyplot.xlabel("$log_{10}(T/K)$") pyplot.ylabel("$log_{10}(L/L_\odot)$") pyplot.show()
def density_plot(coupled_system, i_step): if not HAS_PYNBODY: return figname = os.path.join("plots", "hydro_giant{0:=04}.png".format(i_step)) print " - Hydroplot saved to: ", figname pynbody_column_density_plot(coupled_system.gas_particles, width=3 | units.AU, vmin=26, vmax=33) scatter(coupled_system.dm_particles.x, coupled_system.dm_particles.y, c="w") pyplot.savefig(figname) pyplot.close()
def main(**options): print "calculating shock using exact solution" exact = CalculateExactSolutionIn1D() xpositions, rho, p, u = exact.get_solution_at_time(0.12 | time) print "calculating shock using code {0}".format( options["name_of_the_code"]) model = CalculateSolutionIn3D(**options) grids = model.get_solution_at_time(0.12 | time) print "sampling grid" if model.name_of_the_code in model.sph_hydro_codes: samples = grids else: samplepoints = [(x, 0.5, 0.5) | length for x in numpy.linspace(0.0, 1.0, 2000)] print len(grids) samples = SamplePointsOnMultipleGrids(grids, samplepoints, SamplePointOnCellCenter) print len(samples) samples.filterout_duplicate_indices() print len(samples) print "saving data" store_attributes( xpositions, rho, u, p, filename="exact_riemann_shock_tube_problem_{0}.csv".format( model.name_of_the_code)) store_attributes(samples.x, samples.rho, samples.rhovx, samples.energy, filename="riemann_shock_tube_problem_{0}.csv".format( model.name_of_the_code)) if IS_PLOT_AVAILABLE: print "plotting solution" plot.plot(xpositions, rho) plot.scatter(samples.x, samples.rho) pyplot.xlim(0.3, 0.7) pyplot.ylim(0.5, 4.5) pyplot.savefig("riemann_shock_tube_rho_" + model.name_of_the_code + ".png") pyplot.show()
def plot_cluster(stars, filename, t, rcl): filename += ".png" #lim = 10*stars.center_of_mass().length().value_in(stars.x.unit) lim = (R * 2).value_in(units.m) m = 1 + 3.0*stars.mass/min(stars.mass) pyplot.title("Cluster at distance "+str(R)+" with cluster radius "+ str(rcl)+"\nat t="+str(t)) scatter(stars.x, stars.y) # s size (in point^2) xlabel("X") ylabel("Y") pyplot.xlim(-lim, lim) pyplot.ylim(-lim, lim) pyplot.savefig(filename) pyplot.clf()
def plot_cluster(stars, filename, t, rcl, V): filename += ".png" #lim = 10*stars.center_of_mass().length().value_in(stars.x.unit) lim = (R * 2).value_in(units.m) m = 1 + 3.0 * stars.mass / min(stars.mass) pyplot.title("Cluster at distance " + str(R) + " with cluster radius " + str(rcl) + "\nvelocity " + str(V) + "\nat t=" + str(t)) scatter(stars.x, stars.y) # s size (in point^2) xlabel("X") ylabel("Y") pyplot.xlim(-lim, lim) pyplot.ylim(-lim, lim) pyplot.savefig(filename) pyplot.clf()
def main(filename, lim): pyplot.ion() particles = read_set_from_file(filename, "hdf5") if lim <= zero: lim = max(particles.x).value_in(lim.unit) time = 0 for si in particles.history: pyplot.title("Cluster at t=" + str(time)) scatter(si.x.as_quantity_in(lim.unit), si.y.as_quantity_in(lim.unit)) xlabel("X") ylabel("Y") if lim > zero: pyplot.xlim(-lim.value_in(lim.unit), lim.value_in(lim.unit)) pyplot.ylim(-lim.value_in(lim.unit), lim.value_in(lim.unit)) pyplot.draw() pyplot.cla() pyplot.show()
def plot(x, y): pyplot.figure(figsize=(8,8)) colormap = ['yellow', 'green', 'blue'] # specific to a 3-body plot size = [40, 20, 20] edgecolor = ['orange', 'green', 'blue'] for si in particles.history: scatter(si.x, si.y, c=colormap, s=size, edgecolor=edgecolor) xlabel("x") ylabel("y") save_file = 'plot_gravity.png' pyplot.savefig(save_file) print '\nSaved figure in file', save_file,'\n' pyplot.show()
def main(filename, lim): pyplot.ion() particles = read_set_from_file(filename, "hdf5") if lim<=zero: lim = max(particles.x).value_in(lim.unit) time = 0 for si in particles.history: pyplot.title("Cluster at t="+str(time)) scatter(si.x.as_quantity_in(lim.unit), si.y.as_quantity_in(lim.unit)) xlabel("X") ylabel("Y") if lim>zero: pyplot.xlim(-lim.value_in(lim.unit), lim.value_in(lim.unit)) pyplot.ylim(-lim.value_in(lim.unit), lim.value_in(lim.unit)) pyplot.draw() pyplot.cla() pyplot.show()
def plot(x, y): pyplot.figure(figsize=(8,8)) colormap = ['yellow', 'green', 'blue'] # specific to a 3-body plot size = [40, 20, 20] edgecolor = ['orange', 'green', 'blue'] for si in particles.history: scatter(si.x, si.y, c=colormap, s=size, edgecolor=edgecolor) xlabel("x") ylabel("y") save_file = 'plot_gravity.png' pyplot.savefig(save_file) print('\nSaved figure in file', save_file,'\n') pyplot.show()
def subplot(potential, orbits, codes, fit_orbit, labels): hor, vert = labels X = numpy.linspace(-160, 160, 100) | units.parsec Y = numpy.linspace(-160, 160, 100) | units.parsec X, Y = quantities.meshgrid(X, Y) if labels == 'xy': pot_args = [X, Y, 0 | units.parsec] fit_horizontal = fit_orbit[0] fit_vertical = fit_orbit[1] elif labels == 'xz': pot_args = [X, 0 | units.parsec, Y] fit_horizontal = fit_orbit[0] fit_vertical = fit_orbit[2] elif labels == 'yz': pot_args = [0 | units.parsec, X, Y] fit_horizontal = fit_orbit[1] fit_vertical = fit_orbit[2] phi = potential.get_potential_at_point(None, *pot_args) aplot.imshow_color_plot(X, Y, phi, cmap="Blues") del aplot.UnitlessArgs.arg_units[2] aplot.scatter(0 | units.parsec, 0 | units.parsec, c='black') aplot.plot(fit_horizontal, fit_vertical, c="green", ls="--", label="Kruijssen et al. 2014") colors = cycle(['red', 'black', 'yellow', 'grey', 'green']) for full_orbit, code in zip(orbits, codes): horizontal = full_orbit.x if hor == 'x' else full_orbit.y vertical = full_orbit.y if vert == 'y' else full_orbit.z color = next(colors) aplot.plot(horizontal, vertical, c=color, label=code) aplot.scatter(horizontal[-1], vertical[-1], c=color, edgecolor=color) pyplot.axis('equal') aplot.xlim([-150, 150] | units.parsec) aplot.ylim([-150, 150] | units.parsec) aplot.xlabel(hor) aplot.ylabel(vert)
def evolve_system(system, t_end, n_steps): times = (t_end * range(1, n_steps+1) / n_steps).as_quantity_in(units.day) for i_step, time in enumerate(times): system.evolve_model(time) print " Evolved to:", time, figname = os.path.join("plots", "hydro_giant_{0:=04}.png".format(i_step)) print " - Hydroplot saved to: ", figname pynbody_column_density_plot(system.gas_particles, width=30|units.AU, vmin=26, vmax=33) scatter(system.dm_particles.x, system.dm_particles.y, c="w") pyplot.savefig(figname) pyplot.close() file_base_name = os.path.join("snapshots", "hydro_giant_{0:=04}_".format(i_step)) write_set_to_file(system.gas_particles, file_base_name+"gas.amuse", format='amuse') write_set_to_file(system.dm_particles, file_base_name+"dm.amuse", format='amuse') system.stop()
def main(filename = "nbody.hdf5", lim=3): pyplot.ion() storage = store.StoreHDF(filename,"r") stars = storage.load() # lim = 4*stars.center_of_mass().length().value_in(stars.x.unit) lim = 2*max(max(stars.x).value_in(stars.x.unit), stars.center_of_mass().length().value_in(stars.x.unit)) m = 1 + 3.0*stars.mass/min(stars.mass) for si in stars.history: time = si.get_timestamp() pyplot.title("Cluster at t="+str(time)) print "time = ", time scatter(si.x, si.y, s=m) xlabel("X") ylabel("Y") pyplot.xlim(-lim, lim) pyplot.ylim(-lim, lim) pyplot.draw() pyplot.cla() pyplot.show()
def main(filename="nbody.hdf5", lim=3): pyplot.ion() storage = store.StoreHDF(filename, "r") stars = storage.load() # lim = 4*stars.center_of_mass().length().value_in(stars.x.unit) lim = 2 * max( max(stars.x).value_in(stars.x.unit), stars.center_of_mass().length().value_in(stars.x.unit)) m = 1 + 3.0 * stars.mass / min(stars.mass) for si in stars.history: time = si.get_timestamp() pyplot.title("Cluster at t=" + str(time)) print "time = ", time scatter(si.x, si.y, s=m) xlabel("X") ylabel("Y") pyplot.xlim(-lim, lim) pyplot.ylim(-lim, lim) pyplot.draw() pyplot.cla() pyplot.show()
def main(filename = "stellar.hdf5"): Tmax = 100000 #| untis.K Tmin = 1000 #| untis.K Lmax = 1.e+6 #| untis.LSun Lmin = 0.01 #| untis.LSun pyplot.ion() filename="nbody.hdf5" stars = read_set_from_file(filename, 'hdf5') m = 1 + 3.0*stars.mass/min(stars.mass) lim = 2*max(max(stars.x).value_in(stars.x.unit), stars.center_of_mass().length().value_in(stars.x.unit)) for si in reversed(list(stars.iter_history())): c = si.temperature.value_in(units.K) scatter(si.temperature.value_in(units.K), si.luminosity.value_in(units.LSun), s=m, c=c, cmap=pyplot.cm.hsv) pyplot.xlabel("T [K]") pyplot.ylabel("L [$L_\odot$]") pyplot.xlim(Tmax, Tmin) pyplot.ylim(Lmin, Lmax) pyplot.loglog() pyplot.draw() pyplot.cla() pyplot.show()
def dm_rvir_gas_sph_subplot(self): fig = pyplot.figure(figsize=(20, 10)) ax_dm = fig.add_subplot(121, aspect='equal') ax_gas = fig.add_subplot(122, aspect='equal', sharex=ax_dm, sharey=ax_dm) # plot dark matter center_of_mass = self.dm.center_of_mass() virial_radius = self.dm.virial_radius().as_quantity_in(units.kpc) innersphere = self.dm.select(lambda r: (center_of_mass-r).length()<virial_radius,["position"]) outersphere = self.dm.select(lambda r: (center_of_mass-r).length()>= virial_radius,["position"]) pyplot.gcf().sca(ax_dm) x = outersphere.x.as_quantity_in(units.kpc) y = outersphere.y.as_quantity_in(units.kpc) scatter(x, y, c='red', edgecolor='red', label=r'$r \geq r_{\rm vir}$') x = innersphere.x.as_quantity_in(units.kpc) y = innersphere.y.as_quantity_in(units.kpc) scatter(x, y, c='green', edgecolor='green', label=r'$r < r_{\rm vir}$') xlabel(r'$x$') ylabel(r'$y$') pyplot.legend() # plot gas as sph plot # Adjusted code from amuse.plot.sph_particles_plot pyplot.gcf().sca(ax_gas) min_size = 100 max_size = 10000 alpha = 0.1 x = self.gas.x.as_quantity_in(units.kpc) y = self.gas.y.as_quantity_in(units.kpc) z = self.gas.z.as_quantity_in(units.kpc) z, x, y, us, h_smooths = z.sorted_with(x, y, self.gas.u, self.gas.h_smooth) u_min, u_max = min(us), max(us) 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)) red = 1.0 - clipped_log_u**4 blue = clipped_log_u**4 green = numpy.minimum(red, blue) colors = numpy.transpose(numpy.array([red, green, blue])) n_pixels = pyplot.gcf().get_dpi() * pyplot.gcf().get_size_inches() ax_gas.set_axis_bgcolor('#101010') ax_gas.set_aspect("equal", adjustable="datalim") phys_to_pix2 = n_pixels[0]*n_pixels[1] / ((max(x)-min(x))**2 + (max(y)-min(y))**2) sizes = numpy.minimum(numpy.maximum((h_smooths**2 * phys_to_pix2), min_size), max_size) scatter(x, y, color=colors, s=sizes, edgecolors="none", alpha=alpha) xlabel(r'$x$') ylabel(r'$y$') xlim(-2.*virial_radius, 2*virial_radius) ylim(-2.*virial_radius, 2*virial_radius) pyplot.tight_layout() pyplot.show()
from amuse.units import units, quantities from amuse.plot import ( native_plot, plot, scatter, xlabel, ylabel, hist ) import numpy as np if __name__ == "__main__": # latex_support() x = np.pi/20.0 * (range(-10, 10) | units.m) y1 = units.MSun.new_quantity(np.sin(x.number)) y2 = units.MSun.new_quantity(x.number) native_plot.subplot(2, 2, 1) plot(x, y2, label='model') scatter(x, y1, label='data') xlabel('x') ylabel('mass [$M_\odot$]') # overrides auto unit! native_plot.legend(loc=2) x = range(50) | units.Myr y1 = quantities.new_quantity( np.sin(np.arange(0, 1.5, 0.03)), 1e50*units.erg) y2 = -(1e43 | units.J) - y1 native_plot.subplot(2, 2, 2) plot(x, y1, label='$E_\mathrm{kin}$') plot(x, y2, label='$E_\mathrm{pot}$') xlabel('t') ylabel('E') native_plot.legend()
def evolve_coupled_system(binary_system, giant_system, t_end, n_steps, do_energy_evolution_plot, previous_data=None): directsum = CalculateFieldForParticles(particles=giant_system.particles, gravity_constant=constants.G) directsum.smoothing_length_squared = giant_system.parameters.gas_epsilon**2 coupled_system = Bridge(timestep=(t_end / (2 * n_steps)), verbose=False, use_threading=True) coupled_system.add_system(binary_system, (directsum,), False) coupled_system.add_system(giant_system, (binary_system,), False) times = (t_end * range(1, n_steps+1) / n_steps).as_quantity_in(units.day) if previous_data: with open(previous_data, 'rb') as file: (all_times, potential_energies, kinetic_energies, thermal_energies, giant_center_of_mass, ms1_position, ms2_position, giant_center_of_mass_velocity, ms1_velocity, ms2_velocity) = pickle.load(file) all_times.extend(times + all_times[-1]) else: all_times = times if do_energy_evolution_plot: potential_energies = coupled_system.particles.potential_energy().as_vector_with_length(1).as_quantity_in(units.erg) kinetic_energies = coupled_system.particles.kinetic_energy().as_vector_with_length(1).as_quantity_in(units.erg) thermal_energies = coupled_system.gas_particles.thermal_energy().as_vector_with_length(1).as_quantity_in(units.erg) else: potential_energies = kinetic_energies = thermal_energies = None giant_center_of_mass = [] | units.RSun ms1_position = [] | units.RSun ms2_position = [] | units.RSun giant_center_of_mass_velocity = [] | units.km / units.s ms1_velocity = [] | units.km / units.s ms2_velocity = [] | units.km / units.s i_offset = len(giant_center_of_mass) giant_total_mass = giant_system.particles.total_mass() ms1_mass = binary_system.particles[0].mass ms2_mass = binary_system.particles[1].mass print " Evolving for", t_end for i_step, time in enumerate(times): coupled_system.evolve_model(time) print " Evolved to:", time, if do_energy_evolution_plot: potential_energies.append(coupled_system.particles.potential_energy()) kinetic_energies.append(coupled_system.particles.kinetic_energy()) thermal_energies.append(coupled_system.gas_particles.thermal_energy()) giant_center_of_mass.append(giant_system.particles.center_of_mass()) ms1_position.append(binary_system.particles[0].position) ms2_position.append(binary_system.particles[1].position) giant_center_of_mass_velocity.append(giant_system.particles.center_of_mass_velocity()) ms1_velocity.append(binary_system.particles[0].velocity) ms2_velocity.append(binary_system.particles[1].velocity) a_giant, e_giant = calculate_orbital_elements(ms1_mass, ms2_mass, ms1_position, ms2_position, ms1_velocity, ms2_velocity, giant_total_mass, giant_center_of_mass, giant_center_of_mass_velocity) print "Outer Orbit:", time.in_(units.day), a_giant[-1].in_(units.AU), e_giant[-1], ms1_mass.in_(units.MSun), ms2_mass.in_(units.MSun), giant_total_mass.in_(units.MSun) if i_step % 10 == 9: snapshotfile = os.path.join("snapshots", "hydro_triple_{0:=04}_gas.amuse".format(i_step + i_offset)) write_set_to_file(giant_system.gas_particles, snapshotfile, format='amuse') snapshotfile = os.path.join("snapshots", "hydro_triple_{0:=04}_core.amuse".format(i_step + i_offset)) write_set_to_file(giant_system.dm_particles, snapshotfile, format='amuse') snapshotfile = os.path.join("snapshots", "hydro_triple_{0:=04}_binary.amuse".format(i_step + i_offset)) write_set_to_file(binary_system.particles, snapshotfile, format='amuse') datafile = os.path.join("snapshots", "hydro_triple_{0:=04}_info.amuse".format(i_step + i_offset)) with open(datafile, 'wb') as outfile: pickle.dump((all_times[:len(giant_center_of_mass)], potential_energies, kinetic_energies, thermal_energies, giant_center_of_mass, ms1_position, ms2_position, giant_center_of_mass_velocity, ms1_velocity, ms2_velocity), outfile) figname1 = os.path.join("plots", "hydro_triple_small{0:=04}.png".format(i_step + i_offset)) figname2 = os.path.join("plots", "hydro_triple_large{0:=04}.png".format(i_step + i_offset)) print " - Hydroplots are saved to: ", figname1, "and", figname2 for plot_range, plot_name in [(8|units.AU, figname1), (40|units.AU, figname2)]: if HAS_PYNBODY: pynbody_column_density_plot(coupled_system.gas_particles, width=plot_range, vmin=26, vmax=32) scatter(coupled_system.dm_particles.x, coupled_system.dm_particles.y, c="w") else: pyplot.figure(figsize = [16, 16]) sph_particles_plot(coupled_system.gas_particles, gd_particles=coupled_system.dm_particles, view=plot_range*[-0.5, 0.5, -0.5, 0.5]) pyplot.savefig(plot_name) pyplot.close() coupled_system.stop() make_movie() if do_energy_evolution_plot: energy_evolution_plot(all_times[:len(kinetic_energies)-1], kinetic_energies, potential_energies, thermal_energies) print " Calculating semimajor axis and eccentricity evolution for inner binary" # Some temporary variables to calculate semimajor_axis and eccentricity evolution total_mass = ms1_mass + ms2_mass rel_position = ms1_position - ms2_position rel_velocity = ms1_velocity - ms2_velocity separation_in = rel_position.lengths() speed_squared_in = rel_velocity.lengths_squared() # Now calculate the important quantities: semimajor_axis_binary = (constants.G * total_mass * separation_in / (2 * constants.G * total_mass - separation_in * speed_squared_in)).as_quantity_in(units.AU) eccentricity_binary = numpy.sqrt(1.0 - (rel_position.cross(rel_velocity)**2).sum(axis=1) / (constants.G * total_mass * semimajor_axis_binary)) print " Calculating semimajor axis and eccentricity evolution of the giant's orbit" # Some temporary variables to calculate semimajor_axis and eccentricity evolution rel_position = ((ms1_mass * ms1_position + ms2_mass * ms2_position)/total_mass - giant_center_of_mass) rel_velocity = ((ms1_mass * ms1_velocity + ms2_mass * ms2_velocity)/total_mass - giant_center_of_mass_velocity) total_mass += giant_total_mass separation = rel_position.lengths() speed_squared = rel_velocity.lengths_squared() # Now calculate the important quantities: semimajor_axis_giant = (constants.G * total_mass * separation / (2 * constants.G * total_mass - separation * speed_squared)).as_quantity_in(units.AU) eccentricity_giant = numpy.sqrt(1.0 - (rel_position.cross(rel_velocity)**2).sum(axis=1) / (constants.G * total_mass * semimajor_axis_giant)) orbit_parameters_plot(semimajor_axis_binary, semimajor_axis_giant, all_times[:len(semimajor_axis_binary)]) orbit_ecc_plot(eccentricity_binary, eccentricity_giant, all_times[:len(eccentricity_binary)]) orbit_parameters_plot(separation_in.as_quantity_in(units.AU), separation.as_quantity_in(units.AU), all_times[:len(eccentricity_binary)], par_symbol="r", par_name="separation") orbit_parameters_plot(speed_squared_in.as_quantity_in(units.km**2 / units.s**2), speed_squared.as_quantity_in(units.km**2 / units.s**2), all_times[:len(eccentricity_binary)], par_symbol="v^2", par_name="speed_squared")
def evolve_coupled_system(binary_system, giant_system, t_end, n_steps, do_energy_evolution_plot, previous_data=None): directsum = CalculateFieldForParticles(particles=giant_system.particles, gravity_constant=constants.G) directsum.smoothing_length_squared = giant_system.parameters.gas_epsilon**2 coupled_system = Bridge(timestep=(t_end / (2 * n_steps)), verbose=False, use_threading=True) coupled_system.add_system(binary_system, (directsum,), False) coupled_system.add_system(giant_system, (binary_system,), False) times = (t_end * list(range(1, n_steps+1)) / n_steps).as_quantity_in(units.day) if previous_data: with open(previous_data, 'rb') as file: (all_times, potential_energies, kinetic_energies, thermal_energies, giant_center_of_mass, ms1_position, ms2_position, giant_center_of_mass_velocity, ms1_velocity, ms2_velocity) = pickle.load(file) all_times.extend(times + all_times[-1]) else: all_times = times if do_energy_evolution_plot: potential_energies = coupled_system.particles.potential_energy().as_vector_with_length(1).as_quantity_in(units.erg) kinetic_energies = coupled_system.particles.kinetic_energy().as_vector_with_length(1).as_quantity_in(units.erg) thermal_energies = coupled_system.gas_particles.thermal_energy().as_vector_with_length(1).as_quantity_in(units.erg) else: potential_energies = kinetic_energies = thermal_energies = None giant_center_of_mass = [] | units.RSun ms1_position = [] | units.RSun ms2_position = [] | units.RSun giant_center_of_mass_velocity = [] | units.km / units.s ms1_velocity = [] | units.km / units.s ms2_velocity = [] | units.km / units.s i_offset = len(giant_center_of_mass) giant_total_mass = giant_system.particles.total_mass() ms1_mass = binary_system.particles[0].mass ms2_mass = binary_system.particles[1].mass print(" Evolving for", t_end) for i_step, time in enumerate(times): coupled_system.evolve_model(time) print(" Evolved to:", time, end=' ') if do_energy_evolution_plot: potential_energies.append(coupled_system.particles.potential_energy()) kinetic_energies.append(coupled_system.particles.kinetic_energy()) thermal_energies.append(coupled_system.gas_particles.thermal_energy()) giant_center_of_mass.append(giant_system.particles.center_of_mass()) ms1_position.append(binary_system.particles[0].position) ms2_position.append(binary_system.particles[1].position) giant_center_of_mass_velocity.append(giant_system.particles.center_of_mass_velocity()) ms1_velocity.append(binary_system.particles[0].velocity) ms2_velocity.append(binary_system.particles[1].velocity) a_giant, e_giant = calculate_orbital_elements(ms1_mass, ms2_mass, ms1_position, ms2_position, ms1_velocity, ms2_velocity, giant_total_mass, giant_center_of_mass, giant_center_of_mass_velocity) print("Outer Orbit:", time.in_(units.day), a_giant[-1].in_(units.AU), e_giant[-1], ms1_mass.in_(units.MSun), ms2_mass.in_(units.MSun), giant_total_mass.in_(units.MSun)) if i_step % 10 == 9: snapshotfile = os.path.join("snapshots", "hydro_triple_{0:=04}_gas.amuse".format(i_step + i_offset)) write_set_to_file(giant_system.gas_particles, snapshotfile, format='amuse') snapshotfile = os.path.join("snapshots", "hydro_triple_{0:=04}_core.amuse".format(i_step + i_offset)) write_set_to_file(giant_system.dm_particles, snapshotfile, format='amuse') snapshotfile = os.path.join("snapshots", "hydro_triple_{0:=04}_binary.amuse".format(i_step + i_offset)) write_set_to_file(binary_system.particles, snapshotfile, format='amuse') datafile = os.path.join("snapshots", "hydro_triple_{0:=04}_info.amuse".format(i_step + i_offset)) with open(datafile, 'wb') as outfile: pickle.dump((all_times[:len(giant_center_of_mass)], potential_energies, kinetic_energies, thermal_energies, giant_center_of_mass, ms1_position, ms2_position, giant_center_of_mass_velocity, ms1_velocity, ms2_velocity), outfile) figname1 = os.path.join("plots", "hydro_triple_small{0:=04}.png".format(i_step + i_offset)) figname2 = os.path.join("plots", "hydro_triple_large{0:=04}.png".format(i_step + i_offset)) print(" - Hydroplots are saved to: ", figname1, "and", figname2) for plot_range, plot_name in [(8|units.AU, figname1), (40|units.AU, figname2)]: if HAS_PYNBODY: pynbody_column_density_plot(coupled_system.gas_particles, width=plot_range, vmin=26, vmax=32) scatter(coupled_system.dm_particles.x, coupled_system.dm_particles.y, c="w") else: pyplot.figure(figsize = [16, 16]) sph_particles_plot(coupled_system.gas_particles, gd_particles=coupled_system.dm_particles, view=plot_range*[-0.5, 0.5, -0.5, 0.5]) pyplot.savefig(plot_name) pyplot.close() coupled_system.stop() make_movie() if do_energy_evolution_plot: energy_evolution_plot(all_times[:len(kinetic_energies)-1], kinetic_energies, potential_energies, thermal_energies) print(" Calculating semimajor axis and eccentricity evolution for inner binary") # Some temporary variables to calculate semimajor_axis and eccentricity evolution total_mass = ms1_mass + ms2_mass rel_position = ms1_position - ms2_position rel_velocity = ms1_velocity - ms2_velocity separation_in = rel_position.lengths() speed_squared_in = rel_velocity.lengths_squared() # Now calculate the important quantities: semimajor_axis_binary = (constants.G * total_mass * separation_in / (2 * constants.G * total_mass - separation_in * speed_squared_in)).as_quantity_in(units.AU) eccentricity_binary = numpy.sqrt(1.0 - (rel_position.cross(rel_velocity)**2).sum(axis=1) / (constants.G * total_mass * semimajor_axis_binary)) print(" Calculating semimajor axis and eccentricity evolution of the giant's orbit") # Some temporary variables to calculate semimajor_axis and eccentricity evolution rel_position = ((ms1_mass * ms1_position + ms2_mass * ms2_position)/total_mass - giant_center_of_mass) rel_velocity = ((ms1_mass * ms1_velocity + ms2_mass * ms2_velocity)/total_mass - giant_center_of_mass_velocity) total_mass += giant_total_mass separation = rel_position.lengths() speed_squared = rel_velocity.lengths_squared() # Now calculate the important quantities: semimajor_axis_giant = (constants.G * total_mass * separation / (2 * constants.G * total_mass - separation * speed_squared)).as_quantity_in(units.AU) eccentricity_giant = numpy.sqrt(1.0 - (rel_position.cross(rel_velocity)**2).sum(axis=1) / (constants.G * total_mass * semimajor_axis_giant)) orbit_parameters_plot(semimajor_axis_binary, semimajor_axis_giant, all_times[:len(semimajor_axis_binary)]) orbit_ecc_plot(eccentricity_binary, eccentricity_giant, all_times[:len(eccentricity_binary)]) orbit_parameters_plot(separation_in.as_quantity_in(units.AU), separation.as_quantity_in(units.AU), all_times[:len(eccentricity_binary)], par_symbol="r", par_name="separation") orbit_parameters_plot(speed_squared_in.as_quantity_in(units.km**2 / units.s**2), speed_squared.as_quantity_in(units.km**2 / units.s**2), all_times[:len(eccentricity_binary)], par_symbol="v^2", par_name="speed_squared")
from matplotlib import pyplot import pickle from amuse.plot import scatter, xlabel, ylabel if __name__ in '__main__': datapoints = pickle.load(open("bound_mass.dat", "rb")) filename = "plots/bound_mass_at_6000_pc" pyplot.title("bound mass fraction of cluster orbiting at 6kpc") for datapoint in datapoints: scatter(datapoint["radius"], datapoint["hop_mass_fraction"]) xlabel("cluster radius") ylabel("bound fraction of cluster mass") pyplot.savefig(filename)
converter = nbody_system.nbody_to_si(1 | units.MSun, 1 | units.parsec) G_si = converter.to_si(nbody_system.G) milkyway_mass = 1.26e12 | units.MSun M = milkyway_mass def escape_velocity(impact_parameter): return ((2 * G_si * M) / impact_parameter).sqrt() def v_infinity(escape_v, v): return (v**2 - escape_v**2).sqrt() pyplot.title("d,v-plane") for i in numpy.arange(0.01, 1, 0.01): d = 100000 | units.parsec * i esc_velocity = escape_velocity(d) for j in numpy.arange(0.01, 1, 0.01): v = 10000 * j | units.parsec / units.Myr if v < esc_velocity: scatter(d, v, color='blue', s=2) else: scatter(d, v, color='red', s=2) xlabel("d") ylabel("v") pyplot.xlim(0, 10000000) pyplot.ylim(0, 10000) pyplot.savefig("plots/dv_plot")
def integrate_solar_system(particles, end_time): convert_nbody = nbody_system.nbody_to_si(particles.mass.sum(), particles[1].position.length()) gravity = Huayno(convert_nbody) gravity.particles.add_particles(particles) SunEarth = Particles() SunEarth.add_particle(particles[0]) SunEarth.add_particle(particles[3]) channel_from_to_SunEarth = gravity.particles.new_channel_to(SunEarth) from matplotlib import pyplot, rc x_label = "$a-a_0$ [AU]" y_label = "eccentricty" figure = single_frame(x_label, y_label, xsize=14, ysize=10) from amuse.plot import scatter from matplotlib import pyplot, rc kep = Kepler(convert_nbody) kep.initialize_from_particles(SunEarth) a, e = kep.get_elements() a0 = a color = get_distinct(1) scatter((a-a0).in_(units.AU), e, c=color[0], lw=0) pyplot.text((a-a0).value_in(units.AU)-0.0003, e, "{0:.0f}".format(0.001*gravity.model_time.value_in(units.yr))+"kyr") dt = 100 | units.yr dt_dia = 10000 |units.yr while gravity.model_time < end_time: kep.initialize_from_particles(SunEarth) a, e = kep.get_elements() scatter((a-a0).in_(units.AU), e, c=color[0], lw=0) if gravity.model_time> dt_dia: dt_dia += 10000 |units.yr if gravity.model_time<=(100|units.yr): pyplot.text(-0.0006, e, "{0:.0f}".format(0.001*gravity.model_time.value_in(units.yr))+"kyr") elif gravity.model_time<=(15000|units.yr): pyplot.text(0.0003, e, "{0:.0f}".format(0.001*gravity.model_time.value_in(units.yr))+"kyr") elif gravity.model_time<=(25000|units.yr): pyplot.text(0.0017, e, "{0:.0f}".format(0.001*gravity.model_time.value_in(units.yr))+"kyr") elif gravity.model_time<=(35000|units.yr): pyplot.text(0.0031, e, "{0:.0f}".format(0.001*gravity.model_time.value_in(units.yr))+"kyr") elif gravity.model_time<=(45000|units.yr): pyplot.text(0.0028, e, "{0:.0f}".format(0.001*gravity.model_time.value_in(units.yr))+"kyr") elif gravity.model_time<=(55000|units.yr): pyplot.text(0.0021, e, "{0:.0f}".format(0.001*gravity.model_time.value_in(units.yr))+"kyr") elif gravity.model_time<=(65000|units.yr): pyplot.text(0.0017, e+0.002, "{0:.0f}".format(0.001*gravity.model_time.value_in(units.yr))+"kyr") elif gravity.model_time<=(75000|units.yr): pyplot.text(0.0014, e-0.002, "{0:.0f}".format(0.001*gravity.model_time.value_in(units.yr))+"kyr") elif gravity.model_time<=(85000|units.yr): pyplot.text(0.0014, e, "{0:.0f}".format(0.001*gravity.model_time.value_in(units.yr))+"kyr") else: pyplot.text((a-a0).value_in(units.AU), e, "{0:.0f}".format(0.001*gravity.model_time.value_in(units.yr))+"kyr") gravity.evolve_model(gravity.model_time + dt) channel_from_to_SunEarth.copy() gravity.stop() pyplot.xlabel(x_label) pyplot.ylabel(y_label) # pyplot.show() pyplot.savefig("EarthOrbitVariation") return
def integrate_solar_system(particles, end_time): convert_nbody = nbody_system.nbody_to_si(particles.mass.sum(), particles[1].position.length()) gravity = Huayno(convert_nbody) gravity.particles.add_particles(particles) SunEarth = Particles() SunEarth.add_particle(particles[0]) SunEarth.add_particle(particles[3]) channel_from_to_SunEarth = gravity.particles.new_channel_to(SunEarth) from matplotlib import pyplot, rc x_label = "$a-a_0$ [AU]" y_label = "eccentricty" figure = single_frame(x_label, y_label, xsize=14, ysize=10) from amuse.plot import scatter from matplotlib import pyplot, rc kep = Kepler(convert_nbody) kep.initialize_from_particles(SunEarth) a, e = kep.get_elements() a0 = a color = get_distinct(1) scatter((a-a0).in_(units.AU), e, c=color[0], lw=0) pyplot.text((a-a0).value_in(units.AU)-0.0003, e, "{0:.0f}".format(0.001*gravity.model_time.value_in(units.yr))+"kyr") dt = 100 | units.yr dt_dia = 10000 |units.yr while gravity.model_time < end_time: kep.initialize_from_particles(SunEarth) a, e = kep.get_elements() scatter((a-a0).in_(units.AU), e, c=color[0], lw=0, s=80) if gravity.model_time> dt_dia: dt_dia += 10000 |units.yr if gravity.model_time<=(100|units.yr): pyplot.text(-0.0006, e, "{0:.0f}".format(0.001*gravity.model_time.value_in(units.yr))+"kyr") elif gravity.model_time<=(15000|units.yr): pyplot.text(0.0003, e, "{0:.0f}".format(0.001*gravity.model_time.value_in(units.yr))+"kyr") elif gravity.model_time<=(25000|units.yr): pyplot.text(0.0017, e, "{0:.0f}".format(0.001*gravity.model_time.value_in(units.yr))+"kyr") elif gravity.model_time<=(35000|units.yr): pyplot.text(0.0031, e, "{0:.0f}".format(0.001*gravity.model_time.value_in(units.yr))+"kyr") elif gravity.model_time<=(45000|units.yr): pyplot.text(0.0028, e, "{0:.0f}".format(0.001*gravity.model_time.value_in(units.yr))+"kyr") elif gravity.model_time<=(55000|units.yr): pyplot.text(0.0021, e, "{0:.0f}".format(0.001*gravity.model_time.value_in(units.yr))+"kyr") elif gravity.model_time<=(65000|units.yr): pyplot.text(0.0017, e+0.002, "{0:.0f}".format(0.001*gravity.model_time.value_in(units.yr))+"kyr") elif gravity.model_time<=(75000|units.yr): pyplot.text(0.0014, e-0.002, "{0:.0f}".format(0.001*gravity.model_time.value_in(units.yr))+"kyr") #elif gravity.model_time<=(85000|units.yr): # pyplot.text(0.0014, e, "{0:.0f}".format(0.001*gravity.model_time.value_in(units.yr))+"kyr") else: pass # pyplot.text((a-a0).value_in(units.AU), e, "{0:.0f}".format(0.001*gravity.model_time.value_in(units.yr))+"kyr") gravity.evolve_model(gravity.model_time + dt) channel_from_to_SunEarth.copy() gravity.stop() pyplot.xlabel(x_label) pyplot.ylabel(y_label) pyplot.xlim(-0.001, 0.004) # pyplot.show() pyplot.savefig("EarthOrbitVariation") return
def plot_individual_cluster_density(numerical, analytical, observed=None, poster_style=False): """ Plot the particles' density radial profile and compare to model """ pyplot.figure(figsize=(12, 9)) if poster_style: pyplot.style.use(["dark_background"]) pyplot.rcParams.update({"font.weight": "bold"}) # magenta, dark blue, orange, green, light blue (?) fit_colour = "white" else: fit_colour = "k" data_colour = [(255. / 255, 64. / 255, 255. / 255), (0. / 255, 1. / 255, 178. / 255), (255. / 255, 59. / 255, 29. / 255), (45. / 255, 131. / 255, 18. / 255), (41. / 255, 239. / 255, 239. / 255)] if observed: obs_colour = "k" if observed.name == "cygA" else "k" pyplot.errorbar(observed.radius + observed.binsize / 2, observed.density, xerr=observed.binsize / 2, yerr=observed.density_std, marker="o", ms=7 if poster_style else 3, alpha=1, elinewidth=5 if poster_style else 1, ls="", c=obs_colour, label=observed.name) # Gas RHO and RHOm from Toycluster living in AMUSE datamodel # cut = numpy.where(numerical.gas.r < numerical.R200) amuse_plot.scatter(numerical.gas.r, numerical.gas.rho, c=data_colour[3], edgecolor="face", s=10 if poster_style else 4, label=r"Gas, sampled") # amuse_plot.scatter(numerical.gas.r, # numerical.gas.rhom, # c="r", edgecolor="face", s=1, label=r"Generated IC: gas $\rho_{\rm model}$") # DM density obtained from mass profile (through number density) amuse_plot.scatter(numerical.dm_radii, numerical.rho_dm_below_r, c=data_colour[1], edgecolor="face", s=10 if poster_style else 4, label=r"DM, sampled") # Analytical solutions. # Plot analytical cut-off beta model (Donnert 2014) for the gas density amuse_plot.plot(analytical.radius, analytical.gas_density(), c=fit_colour, lw=5 if poster_style else 1, ls="dashed", label="Gas: " + analytical.modelname) #+"\n"+\ #r"$\rho_0$ = {0:.3e} g/cm$^3$; $rc = ${1:.2f} kpc"\ #.format(analytical.rho0.number, analytical.rc.number)) # Plot analytical Hernquist model for the DM density amuse_plot.plot( analytical.radius, analytical.dm_density(), c=fit_colour, lw=5 if poster_style else 1, ls="solid", label=r"DM: Hernquist" ) # "\n" r"$M_{{\rm dm}}= ${0:.2e} MSun; $a = $ {1} kpc".format( #analytical.M_dm.number, analytical.a.number)) amuse_plot.ylabel(r"Density [g/cm$^3$]") amuse_plot.xlabel(r"Radius [kpc]") pyplot.gca().set_xlim(xmin=1, xmax=1e4) pyplot.gca().set_ylim(ymin=1e-32, ymax=9e-24) pyplot.gca().set_xscale("log") pyplot.gca().set_yscale("log") pyplot.axvline(x=numerical.R200.value_in(units.kpc), lw=1, c=fit_colour) pyplot.text(numerical.R200.value_in(units.kpc) + 100, 4e-24, r"$r_{200}$", ha="left", fontsize=22) pyplot.fill_between(numpy.arange(numerical.R200.value_in(units.kpc), 1e4, 0.01), 1e-32, 9e-24, facecolor="grey", edgecolor="grey", alpha=0.1) ymin = analytical.gas_density(numerical.rc.as_quantity_in(units.kpc)) pyplot.vlines(x=numerical.rc.value_in(units.kpc), ymin=ymin.value_in(units.g / units.cm**3), ymax=9e-24, lw=1, linestyles="dashed", color=fit_colour) pyplot.text(numerical.rc.value_in(units.kpc) + 25 if (observed and observed.name == "cygB") else numerical.rc.value_in(units.kpc), 4e-24, r"$r_c$", ha="left", fontsize=22) ymin = analytical.dm_density(numerical.a.as_quantity_in(units.kpc)) pyplot.vlines(x=numerical.a.value_in(units.kpc), ymin=ymin.value_in(units.g / units.cm**3), ymax=9e-24, lw=1, linestyles="solid", color=fit_colour) pyplot.text(numerical.a.value_in(units.kpc) - 25, 4e-24, r"$a$", ha="right", fontsize=22) # Maximum value in histogram of numerical.gas.h ymin = analytical.gas_density(107.5 | units.kpc) pyplot.vlines(x=107.5, ymin=ymin.value_in(units.g / units.cm**3), ymax=9e-24, lw=4, linestyles="dashed", color=data_colour[3]) pyplot.text(107.5 - 10, 4e-24, r"$2h_{\rm sml}$", color=data_colour[3], ha="right", fontsize=22) # pyplot.savefig("out/actuallyran.png") # pyplot.legend(loc=3, fontsize=28) pyplot.tight_layout()
G_si = converter.to_si(nbody_system.G) milkyway_mass = 1.26e12 | units.MSun M = milkyway_mass def escape_velocity(impact_parameter): return ((2 * G_si * M)/impact_parameter).sqrt() def v_infinity(escape_v, v): return (v**2 - escape_v**2).sqrt() pyplot.title("d,v-plane") for i in numpy.arange(0.01,1,0.01): d = 100000|units.parsec * i esc_velocity = escape_velocity(d) for j in numpy.arange(0.01,1,0.01): v = 10000*j|units.parsec/units.Myr if v < esc_velocity: scatter(d,v, color='blue', s=2) else: scatter(d,v, color='red', s=2) xlabel("d") ylabel("v") pyplot.xlim(0,10000000) pyplot.ylim(0,10000) pyplot.savefig("plots/dv_plot")
def dm_gas_sph_subplot(self, time=0): fig = pyplot.figure(figsize=(20, 12)) gs = gridspec.GridSpec(2, 2, height_ratios=[1, 4]) # gs.update(left=0.05, right=0.48, wspace=0.05) ax_text = pyplot.subplot(gs[0, :]) ax_text.axis('off') time_text = ax_text.text(0.02, 1.0, '', transform=ax_text.transAxes, fontsize=42) time_text.set_text('Time: {0:.1f} Myr'.format( self.code.model_time.value_in(units.Myr))) energy_text = ax_text.text(0.02, -0.2, '', transform=ax_text.transAxes, fontsize=42) Ekin = self.code.kinetic_energy.value_in(units.erg) Epot = self.code.potential_energy.value_in(units.erg) Eth = self.code.thermal_energy.value_in(units.erg) energy_text.set_text( 'Ekin: {0:.3e} erg\nEpot: {1:.3e} erg\nEth: {2:.3e} erg'.format( Ekin, Epot, Eth)) # lim = max(abs((self.dmA.center_of_mass() - self.dmB.center_of_mass()).value_in(units.Mpc))) lim = 2.5 ax_dm = pyplot.subplot(gs[1, 0], xlim=(-4 * lim, 4 * lim), ylim=(-4 * lim, 4 * lim)) ax_gas = pyplot.subplot(gs[1, 1], aspect='equal', sharex=ax_dm, sharey=ax_dm, xlim=(-4 * lim, 4 * lim), ylim=(-4 * lim, 4 * lim)) # ax_dm = fig.add_subplot(121, aspect='equal') # ax_gas = fig.add_subplot(122, aspect='equal', # sharex=ax_dm, sharey=ax_dm) # plot dark matter pyplot.gcf().sca(ax_dm) x = self.dmA.x.as_quantity_in(units.Mpc) y = self.dmA.y.as_quantity_in(units.Mpc) scatter(x, y, c='red', edgecolor='red', label=str(self.subClusterA.name)) x = self.dmB.x.as_quantity_in(units.Mpc) y = self.dmB.y.as_quantity_in(units.Mpc) scatter(x, y, c='green', edgecolor='green', label=str(self.subClusterB.name)) xlabel(r'$x$') ylabel(r'$y$') pyplot.legend() # plot gas as sph plot def plot_sph(gas): # Adjusted code from amuse.plot.sph_particles_plot pyplot.gcf().sca(ax_gas) min_size = 100 max_size = 10000 alpha = 0.1 x = gas.x y = gas.y z = gas.z z, x, y, us, h_smooths = z.sorted_with(x, y, gas.u, gas.h_smooth) u_min, u_max = min(us), max(us) 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)) red = 1.0 - clipped_log_u**4 blue = clipped_log_u**4 green = numpy.minimum(red, blue) colors = numpy.transpose(numpy.array([red, green, blue])) n_pixels = pyplot.gcf().get_dpi() * pyplot.gcf().get_size_inches() ax_gas.set_axis_bgcolor('#101010') ax_gas.set_aspect("equal", adjustable="datalim") length_unit = smart_length_units_for_vector_quantity(x) phys_to_pix2 = n_pixels[0] * n_pixels[1] / ((max(x) - min(x))**2 + (max(y) - min(y))**2) sizes = numpy.minimum( numpy.maximum((h_smooths**2 * phys_to_pix2), min_size), max_size) scatter(x.as_quantity_in(length_unit), y.as_quantity_in(length_unit), color=colors, s=sizes, edgecolors="none", alpha=alpha) plot_sph(self.gasA) plot_sph(self.gasB) xlabel(r'$x$') ylabel(r'$y$') pyplot.tight_layout() pyplot.savefig('out/{0}/plots/dm_gas_sph_subplot_{1}.png'.format( self.timestamp, time), dpi=50) # pyplot.show() pyplot.close()
def plot_individual_cluster_density(cluster): """ Plot the particles' density radial profile and compare to model """ pyplot.figure(figsize=(24, 18)) # AMUSE datamodel particles. Gas has RHO and RHOm; dm rho from model. amuse_plot.scatter(cluster.gas.r, cluster.gas.rho, c="g", edgecolor="face", s=1, label=r"Generated IC: gas $\rho$") # amuse_plot.scatter(cluster.gas.r, # cluster.gas.rhom, # c="r", edgecolor="face", s=1, label=r"Generated IC: gas $\rho_{\rm model}$") amuse_plot.scatter(cluster.dm.r, cluster.dm.rho, c="b", edgecolor="none", label=r"Generated IC: DM $\rho$") # Analytical solutions. Sample radii and plug into analytical expression. r = VectorQuantity.arange(units.kpc(1), units.kpc(10000), units.parsec(100)) # Plot analytical beta model (Donnert 2014) for the gas density amuse_plot.plot(r, cluster.gas_density_double_beta(r), c="k", ls="dashed", label=r"Analytical, $\beta$-model:" "\n" r"$\rho_0$ = {0} g/cm$^3$; $rc = ${1} kpc".format( cluster.rho0gas.number, cluster.rc.number)) # Plot analytical double beta model (Donnert et al. 2016, in prep) for gas amuse_plot.plot( r, cluster.gas_density_beta(r), c="k", ls="dotted", label=r"Analytical, double $\beta$-model:" "\n" r"$\rho_0$ = {0} g/cm$^3$; $rc =$ {1} kpc; $r_{{\rm cut}}$ = {2} kpc". format(cluster.rho0gas.number, cluster.rc.number, cluster.rcut.number)) # Plot analytical Hernquist model for the DM density amuse_plot.plot(r, cluster.dm_density(r), c="k", ls="solid", label=r"Analytical, Hernquist-model" "\n" r"$M_{{\rm dm}}= ${0:.2e} MSun; $a = $ {1} kpc".format( cluster.M_dm.number, cluster.a.number)) pyplot.legend(loc=3) amuse_plot.xlabel(r"$r$") amuse_plot.ylabel(r"$\rho$") pyplot.gca().set_xlim(xmin=10, xmax=1e4) pyplot.gca().set_ylim(ymin=1e-30, ymax=9e-24) pyplot.gca().set_xscale("log") pyplot.gca().set_yscale("log") pyplot.axvline(x=cluster.R200.value_in(units.kpc), lw=1, c="grey") pyplot.text(cluster.R200.value_in(units.kpc), 5e-24, r"$r_{{cut}} =$ {0}".format(cluster.rcut)) pyplot.axvline(x=cluster.rc.value_in(units.kpc), lw=1, c="grey") pyplot.text(cluster.rc.value_in(units.kpc), 5e-24, r"$rc =$ {0}".format(cluster.rc)) pyplot.axvline(x=cluster.a.value_in(units.kpc), lw=1, c="grey") pyplot.text(cluster.a.value_in(units.kpc), 1e-24, r"$a =$ {0}".format(cluster.a))
def test4(self): random.seed(1001) print "Test 4: complicated density field." # A separate group below peak_density_threshold -> should be dropped particles0 = new_plummer_model(90, convert_nbody=nbody_system.nbody_to_si( 0.9 | units.MSun, 1.0 | units.RSun)) # A nearby group below peak_density_threshold -> should be attached to proper group particles1 = new_plummer_model(80, convert_nbody=nbody_system.nbody_to_si( 0.8 | units.MSun, 1.0 | units.RSun)) particles1.x += 10 | units.RSun # A proper group very nearby other proper group -> groups should merge particles2a = new_plummer_model(200, convert_nbody=nbody_system.nbody_to_si( 2.0 | units.MSun, 1.0 | units.RSun)) particles2b = new_plummer_model(300, convert_nbody=nbody_system.nbody_to_si( 3.0 | units.MSun, 1.0 | units.RSun)) particles2a.x += 11.0 | units.RSun particles2b.x += 11.2 | units.RSun # A separate proper group other proper group -> groups should be preserved particles3 = new_plummer_model(400, convert_nbody=nbody_system.nbody_to_si( 4.0 | units.MSun, 1.0 | units.RSun)) particles3.x += 20 | units.RSun hop = Hop( unit_converter=nbody_system.nbody_to_si(10.7 | units.MSun, 1.0 | units.RSun)) hop.parameters.number_of_neighbors_for_local_density = 100 hop.parameters.saddle_density_threshold_factor = 0.5 hop.parameters.relative_saddle_density_threshold = True hop.commit_parameters() for set in [ particles0, particles1, particles2a, particles2b, particles3 ]: hop.particles.add_particles(set) hop.calculate_densities() hop.parameters.outer_density_threshold = 0.1 * hop.particles.density.mean( ) hop.parameters.peak_density_threshold = hop.particles.density.amax( ) / 4.0 hop.recommit_parameters() hop.do_hop() groups = list(hop.groups()) self.assertEquals(len(hop.particles), 1070) self.assertEquals(len(groups), 2) self.assertEquals( hop.particles.select(lambda x: x < 5 | units.RSun, "x").group_id, -1) self.assertEquals(hop.get_number_of_particles_outside_groups(), 299) self.assertEquals(1070 - len(groups[0]) - len(groups[1]), 299) expected_size = [ 477, 294 ] # Less than [580, 400], because particles below outer_density_threshold are excluded expected_average_x = [11.0, 20] | units.RSun for index, group in enumerate(groups): self.assertEquals(group.id_of_group(), index) self.assertAlmostEquals(group.center_of_mass()[0], expected_average_x[index], 1) self.assertEquals(len(group), expected_size[index]) if False: # Make a plot original = hop.particles.copy() from amuse.plot import scatter, native_plot colors = ["r", "g", "b", "y", "k", "w"] * 100 for group, color in zip(hop.groups(), colors): scatter(group.x, group.y, c=color) original -= group scatter(original.x, original.y, c="m", marker="s") native_plot.show() hop.stop()
def test4(self): random.seed(1001) print "Test 4: complicated density field." # A separate group below peak_density_threshold -> should be dropped particles0 = new_plummer_model(90, convert_nbody=nbody_system.nbody_to_si(0.9 | units.MSun, 1.0 | units.RSun)) # A nearby group below peak_density_threshold -> should be attached to proper group particles1 = new_plummer_model(80, convert_nbody=nbody_system.nbody_to_si(0.8 | units.MSun, 1.0 | units.RSun)) particles1.x += 10 | units.RSun # A proper group very nearby other proper group -> groups should merge particles2a = new_plummer_model(200, convert_nbody=nbody_system.nbody_to_si(2.0 | units.MSun, 1.0 | units.RSun)) particles2b = new_plummer_model(300, convert_nbody=nbody_system.nbody_to_si(3.0 | units.MSun, 1.0 | units.RSun)) particles2a.x += 11.0 | units.RSun particles2b.x += 11.2 | units.RSun # A separate proper group other proper group -> groups should be preserved particles3 = new_plummer_model(400, convert_nbody=nbody_system.nbody_to_si(4.0 | units.MSun, 1.0 | units.RSun)) particles3.x += 20 | units.RSun hop = Hop(unit_converter=nbody_system.nbody_to_si(10.7 | units.MSun, 1.0 | units.RSun)) hop.parameters.number_of_neighbors_for_local_density = 100 hop.parameters.saddle_density_threshold_factor = 0.5 hop.parameters.relative_saddle_density_threshold = True hop.commit_parameters() for set in [particles0, particles1, particles2a, particles2b, particles3]: hop.particles.add_particles(set) hop.calculate_densities() hop.parameters.outer_density_threshold = 0.1 * hop.particles.density.mean() hop.parameters.peak_density_threshold = hop.particles.density.amax() / 4.0 hop.recommit_parameters() hop.do_hop() groups = list(hop.groups()) self.assertEquals(len(hop.particles), 1070) self.assertEquals(len(groups), 2) self.assertEquals(hop.particles.select(lambda x: x < 5|units.RSun, "x").group_id, -1) self.assertEquals(hop.get_number_of_particles_outside_groups(), 299) self.assertEquals(1070 - len(groups[0]) - len(groups[1]), 299) expected_size = [477, 294] # Less than [580, 400], because particles below outer_density_threshold are excluded expected_average_x = [11.0, 20] | units.RSun for index, group in enumerate(groups): self.assertEquals(group.id_of_group(), index) self.assertAlmostEquals(group.center_of_mass()[0], expected_average_x[index], 1) self.assertEquals(len(group), expected_size[index]) if False: # Make a plot original = hop.particles.copy() from amuse.plot import scatter, native_plot colors = ["r", "g", "b", "y", "k", "w"]*100 for group, color in zip(hop.groups(), colors): scatter(group.x, group.y, c=color) original -= group scatter(original.x, original.y, c="m", marker="s") native_plot.show() hop.stop()
#We calculate v_{i+1/2} over the x y and z (I tried adding directly but got mismatched units) #and we calculate x_{i+1} with the velocity v_{i+1/2} Tracker[ i].velocity = Tracker[i].velocity + Accelout * gravity.timestep Tracker[i].position = Tracker[ i].position + Tracker[i].velocity * gravity.timestep k += 1 gravity.stop() # In[6]: for i in range(100): scatter(Tracker[i].position[0], Tracker[i].position[1]) for i in range(41): scatter(Galaxies[i].x, Galaxies[i].y) #Quick plot to see end result, need to make some actual data analysis functions and such which will come later #The other cell's are mostly just me randomly testing stuff to make sure things work, they can be ignored # In[7]: print(Tracker.position) # In[12]: a = 8 b = 9
# print "file " + out_file + " already exists, skip plotting" # continue print "ouputing " + out_file cluster, gascloud = read_set_from_file(data_file, 'amuse', names=("cluster", "gas")) lim = abs(next(cluster.history).position).max() fig = pyplot.figure(figsize=[10, 10]) artists = [] cl = None gas = None for c, g in zip(cluster.history, gascloud.history): cl = c gas = g points = aplot.scatter(cl.x, cl.y, c='black', label='Stellar Cluster') gas_points = aplot.scatter(gas.x, gas.y, s=100, c='b', edgecolors='none', alpha=0.3, rasterized=True, label='Giant Molecular Cloud') time_label = r'$t_{\rm end}$ ' + "= {:.2f} Myr".format(cl.get_timestamp(). value_in(units.Myr)) text = aplot.text(-4./5.*lim, 4./5.*lim, time_label) aplot.xlabel("X") aplot.ylabel("Y") pyplot.axis('equal') aplot.xlim(-lim, lim) aplot.ylim(-lim, lim) pyplot.legend() pyplot.title(r'Cluster orbitting GMC with $d$={0}, $v_\infty$={1}'