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_results(stars, time): mass_loss = stars.zams_mass - stars.mass x = stars.x.in_(units.parsec) y = stars.y.in_(units.parsec) pyplot.figure(figsize=(8,8)) aplot.plot(x, y, "*") for x, y, mass_loss in zip(x.number, y.number, mass_loss): pyplot.annotate("%0.2f"%abs(mass_loss.number), xy=(x,y+2), horizontalalignment='center', verticalalignment='bottom') pyplot.axis('equal') pyplot.xlim([-60, 60]) pyplot.ylim([-60, 60]) aplot.xlabel("x") aplot.ylabel("y") pyplot.title("time = " + str(time)) if not os.path.exists("plots"): os.mkdir("plots") name = "plots/plot_{0:=05}.png".format(int(time.value_in(units.Myr))) print("creating", name) pyplot.savefig(name) pyplot.close()
def temperature_density_plot(data, mass, age): figure = pyplot.figure(figsize = (8, 10)) pyplot.subplot(2, 1, 1) ax = pyplot.gca() plotT = semilogy(data["radius"], data["temperature"], 'r-', label = r'$T(r)$') xlabel('Radius') ylabel('Temperature') ax.twinx() plotrho = semilogy(data["radius"], data["density"], 'g-', label = r'$\rho(r)$') plots = plotT + plotrho labels = [one_plot.get_label() for one_plot in plots] ax.legend(plots, labels, loc=3) ylabel('Density') pyplot.subplot(2, 1, 2) semilogy(data["radius"], data["composition"][0], label = data["species_names"][0]) semilogy(data["radius"], data["composition"][1], label = data["species_names"][1]) semilogy(data["radius"], data["composition"][2], label = data["species_names"][2]) semilogy(data["radius"], data["composition"][3], label = data["species_names"][3]) semilogy(data["radius"], data["composition"][4], label = data["species_names"][4]) pyplot.ylim(0.0, 1.0) xlabel('Radius') ylabel('Mass fraction') pyplot.legend() pyplot.suptitle('Structure of a {0} star at {1}'.format(mass, age)) pyplot.show()
def make_effective_iso_potential_plot(gravity_code): omega = (constants.G * gravity_code.particles.total_mass() / (1.0|units.AU**3)).sqrt() center_of_mass = gravity_code.particles.center_of_mass()[:2] pyplot.rcParams.update({'font.size': 30}) figure = pyplot.figure(figsize = (12, 12)) ax = pyplot.gca() ax.get_yaxis().get_major_formatter().set_useOffset(False) ax.minorticks_on() current_axes = pyplot.subplot(1, 1, 1) current_axes.set_aspect("equal", adjustable = "box") lim = 1.7 effective_iso_potential_plot(gravity_code, omega, xlim = [-lim, lim] | units.AU, ylim = [-lim, lim] | units.AU, center_of_rotation = center_of_mass, fraction_screen_filled=0.8) xlabel('x') ylabel('y') pyplot.text(0.6, -0.06, "$L_1$") pyplot.text(1.35, -0.06, "$L_2$") pyplot.text(-0.99, -0.06, "$L_3$") pyplot.text(0.40, 0.82, "$L_4$") pyplot.text(0.40, -0.92, "$L_5$") # pyplot.show() pyplot.savefig("lagrange_points")
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 make_plot(radius_profile, brunt_profile, mass, age): figure = pyplot.figure() semilogy(radius_profile, -brunt_profile, 'g-', label = r'convective, $N^2$ < 0') semilogy(radius_profile, brunt_profile, 'r-', label = r'radiative, $N^2$ > 0') xlabel('Radius') ylabel(r'$\|N^2\|$') pyplot.title('Brunt-Vaisala frequency squared of a {0} star at {1}'.format(mass, age)) pyplot.legend(loc=3) pyplot.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 plot_track(temperature_at_time, luminosity_at_time): pyplot.figure(figsize=(8, 6)) pyplot.title('Hertzsprung-Russell diagram', fontsize=12) loglog(temperature_at_time, luminosity_at_time) xlabel('Effective Temperature') ylabel('Luminosity') pyplot.xlim(pyplot.xlim()[::-1]) pyplot.ylim(.1, 1.e4) pyplot.show()
def thermal_energy_plot(time, E_therm, figname): if not HAS_MATPLOTLIB: return pyplot.figure(figsize = (5, 5)) plot(time, E_therm.as_quantity_in(units.erg), label='E_therm') xlabel('Time') ylabel('Energy') pyplot.legend(loc=3) pyplot.savefig(figname) print "\nPlot of thermal energy evolution was saved to: ", figname pyplot.close()
def plot_tracks(temperature1, luminosity1, temperature2, luminosity2): from matplotlib import pyplot from amuse.plot import loglog, xlabel, ylabel pyplot.figure(figsize = (8, 6)) pyplot.title('Hertzsprung-Russell diagram', fontsize=12) loglog(temperature1, luminosity1) loglog(temperature2, luminosity2) xlabel('Effective Temperature') ylabel('Luminosity') pyplot.xlim(pyplot.xlim()[::-1]) pyplot.show()
def plot_tracks(temperatures_original, luminosities_original, temperatures_helium, luminosities_helium): pyplot.figure(figsize = (8, 6)) pyplot.title('Hertzsprung-Russell diagram', fontsize=12) loglog(temperatures_original, luminosities_original, label='progenitor') loglog(temperatures_helium, luminosities_helium, label='helium star') xlabel('Effective Temperature') ylabel('Luminosity') pyplot.xlim(pyplot.xlim()[::-1]) pyplot.ylim(1.0,1.0e5) pyplot.legend(loc=3) pyplot.show()
def energy_evolution_plot(time, kinetic, potential, thermal, figname = "energy_evolution.png"): time.prepend(0.0 | units.day) pyplot.figure(figsize = (5, 5)) plot(time, kinetic, label='K') plot(time, potential, label='U') plot(time, thermal, label='Q') plot(time, kinetic + potential + thermal, label='E') xlabel('Time') ylabel('Energy') pyplot.legend(prop={'size':"x-small"}, loc=4) pyplot.savefig(figname) pyplot.close()
def orbit_plot(distance, mass, time): figure = pyplot.figure(figsize=(6, 10), dpi=100) subplot = figure.add_subplot(2, 1, 1) plot(time, distance) xlabel('t') ylabel('separation') pyplot.margins(0.05) subplot = figure.add_subplot(2, 1, 2) plot(time, ((mass - mass[0]) / mass[0]) * 100.0) xlabel('t') ylabel('mass') pyplot.margins(0.05) pyplot.show()
def composition_comparison_plot(radii_SE, comp_SE, radii_SPH, comp_SPH, figname): if not HAS_MATPLOTLIB: return pyplot.figure(figsize = (7, 5)) plot(radii_SE.as_quantity_in(units.RSun), comp_SE, label='stellar evolution model') plot(radii_SPH, comp_SPH, 'go', label='SPH model') xlabel('radius') ylabel('mass fraction') pyplot.legend() pyplot.savefig(figname) print "\nPlot of composition profiles was saved to: ", figname pyplot.close()
def internal_energy_comparison_plot(radii_SE, u_SE, radii_SPH, u_SPH, figname): if not HAS_MATPLOTLIB: return pyplot.figure(figsize = (7, 5)) semilogy(radii_SE.as_quantity_in(units.RSun), u_SE, label='stellar evolution model') semilogy(radii_SPH, u_SPH, 'go', label='SPH model') xlabel('radius') ylabel('internal energy') pyplot.legend() pyplot.savefig(figname) print "\nPlot of internal energy profiles was saved to: ", figname pyplot.close()
def energy_evolution_plot(time, kinetic, potential, thermal, figname="energy_evolution.png"): native_plot.subplot(211) plot(time, kinetic, label='K') plot(time, potential, label='U') plot(time, thermal, label='Q') plot(time, kinetic + potential + thermal, label='E') xlabel('Time') ylabel('Energy') native_plot.legend(prop={'size':"x-small"}, loc=4) native_plot.subplot(212) plot(time, thermal, label='Q') native_plot.savefig(figname) native_plot.clf()
def make_plots(Ncl, Rcl, t_end): """ Not finished """ try: import matplotlib matplotlib.use("Agg") from matplotlib import pyplot except ImportError: print "Unable to produce plots: couldn't find matplotlib" else: fig = pyplot.figure(figsize=[10, 10]) for data in ["hybrid", "tree", "direct"] print "Generating plot data of {0} run".format(data) data_file = "CA_Exam_TLRH_{0}.amuse".format(data) stars_below_cut, stars_above_cut =\ read_set_from_file(data_file, 'amuse', names=("stars_below_cut", "stars_below_cut")) lim = abs(next(stars_below_cut.history).position).max() if data == "hybrid": pass # dashed curve # points = aplot.scatter(dE, time, c='orange', # label='Hybrid') if data == "direct": pass # dotted curve # points = aplot.scatter(dE, time, c='red', # label='Direct') if data == "tree": pass # solid curve # points = aplot.scatter(dE, time, c='green', # label='Tree') aplot.xlabel("Time") aplot.ylabel("Relative Energy Error") pyplot.axis('equal') aplot.xlim(-lim, lim) aplot.ylim(-lim, lim) pyplot.legend() pyplot.title(r'Cluster with $N=${0}, $r=${1}' .format(Ncl, Rcl ) + r', evolved until $t_{\rm end}$={0}' .format(t_end)) pyplot.savefig("out.png") pyplot.close()
def energy_plot(time, E_kin, E_pot, E_therm, figname): if not HAS_MATPLOTLIB: return pyplot.figure(figsize=(5, 5)) plot(time, E_kin.as_quantity_in(units.erg), label="E_kin") plot(time, E_pot, label="E_pot") plot(time, E_therm, label="E_therm") plot(time, E_kin + E_pot + E_therm, label="E_total") xlabel("Time") ylabel("Energy") pyplot.legend(loc=3) pyplot.savefig(figname) print "\nPlot of energy evolution was saved to: ", figname pyplot.close()
def orbit_parameters_plot(semi_major_in,semi_major_out, time, par_symbol="a", par_name="semimajor_axis"): figure = pyplot.figure(figsize = (10, 6), dpi = 100) subplot = figure.add_subplot(2, 1, 1) plot(time,semi_major_in ) xlabel('t') ylabel('$'+par_symbol+'_\mathrm{binary}$') subplot = figure.add_subplot(2, 1, 2) plot(time,semi_major_out ) xlabel('t') ylabel('$'+par_symbol+'_\mathrm{giant}$') pyplot.minorticks_on() pyplot.savefig(par_name+"_evolution.png") pyplot.close()
def orbit_ecc_plot(eccentricity_in,eccentricity_out,time): figure = pyplot.figure(figsize = (10, 6), dpi = 100) subplot = figure.add_subplot(2, 1, 1) plot(time,eccentricity_in) xlabel('t') ylabel('e$_\mathrm{binary}$') subplot = figure.add_subplot(2, 1, 2) plot(time,eccentricity_out ) xlabel('t') ylabel('e$_\mathrm{giant}$') pyplot.minorticks_on() pyplot.savefig("eccentricity_evolution.png") pyplot.close()
def energy_plot(time, E_kin_list, E_pot_list, E_therm_list, figname): if not HAS_MATPLOTLIB: return pyplot.figure(figsize = (5, 5)) for i, (E_kin, E_pot, E_therm) in enumerate(zip(E_kin_list, E_pot_list, E_therm_list)): plot(time, E_kin.as_quantity_in(units.erg), label=labels[i][0]) plot(time, E_pot, label=labels[i][1]) plot(time, E_therm, label=labels[i][2]) plot(time, E_kin+E_pot+E_therm, label=labels[i][3]) xlabel('Time') ylabel('Energy') pyplot.legend(prop={'size':"x-small"}, loc=3) pyplot.savefig(figname) print "\nPlot of energy evolution was saved to: ", figname pyplot.close()
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(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 test2(self): """ Test a basic plot with and without units and labels""" if not HAS_MATPLOTLIB: return self.skip() pyplot.clf() x = numpy.linspace(0, 100, 100) | units.yr y = numpy.linspace(0, 200, 100) aplot.plot(x, y) self.assertEquals("[yr]", self.xaxis().get_label_text()) self.assertEquals("", self.yaxis().get_label_text()) aplot.xlabel("time") aplot.ylabel("radius") self.assertEquals("time [yr]", self.xaxis().get_label_text()) self.assertEquals("radius ", self.yaxis().get_label_text())
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 __init__(self): self.merger = ClusterMerger() timesteps = VectorQuantity.arange(0 | units.Myr, 1 | units.Gyr, 50 | units.Myr) tot = len(timesteps) end_time = timesteps[-1] print "Starting Simulation :-)" print "Generating plots on the fly :-)" gasA_vel_list = [] | (units.km/units.s) dmA_vel_list = [] | (units.km/units.s) gasB_vel_list = [] | (units.km/units.s) dmB_vel_list = [] | (units.km/units.s) time_list = [] | units.Gyr for i, time in enumerate(timesteps): print_progressbar(i, tot) self.merger.code.evolve_model(time) self.merger.dm_gas_sph_subplot(i) gasA_vel_list.append(self.merger.gasA.center_of_mass_velocity()) dmA_vel_list.append(self.merger.dmA.center_of_mass_velocity()) gasB_vel_list.append(self.merger.gasB.center_of_mass_velocity()) dmB_vel_list.append(self.merger.dmB.center_of_mass_velocity()) time_list.append(time) write_set_to_file(self.merger.code.particles, 'out/{0}/data/cluster_{1}.amuse'.format(self.merger.timestamp, i), "amuse") print "Plotting velocity as function of time" fig = pyplot.figure(figsize=(12, 10), dpi=50) plot(time_list.number, gasA_vel_list.number, label="gasA", c='r', ls='solid') plot(time_list.number, dmA_vel_list.number, label="dmA", c='r', ls='dashed') plot(time_list.number, gasB_vel_list.number, label="gasB", c='g', ls='solid') plot(time_list.number, dmB_vel_list.number, label="dmB", c='g', ls='dashed') xlabel("Time") ylabel("Velocity") pyplot.legend() pyplot.show() print "Generating gif :-)" self.merger.create_gif() print "Stopping the code. End of pipeline :-)" self.merger.code.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 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 make_effective_iso_potential_plot(gravity_code): omega = (constants.G * gravity_code.particles.total_mass() / (1.0 | units.AU**3)).sqrt() center_of_mass = gravity_code.particles.center_of_mass()[:2] figure = pyplot.figure(figsize=(9, 8)) current_axes = pyplot.subplot(2, 2, 1) current_axes.set_aspect("equal", adjustable="box") effective_iso_potential_plot(gravity_code, omega, center_of_rotation=center_of_mass, fraction_screen_filled=0.7) xlabel('x') ylabel('y') current_axes = pyplot.subplot(2, 2, 3) current_axes.set_aspect("equal", adjustable="box") effective_iso_potential_plot(gravity_code, omega, center_of_rotation=center_of_mass, xlim=[0.9, 1.1] | units.AU, ylim=[-0.1, 0.1] | units.AU, number_of_contours=20) xlabel('x') ylabel('y') gravity_code.particles[1].mass *= 10000 omega = (constants.G * gravity_code.particles.total_mass() / (1.0 | units.AU**3)).sqrt() center_of_mass = gravity_code.particles.center_of_mass()[:2] current_axes = pyplot.subplot(2, 2, 2) current_axes.set_aspect("equal", adjustable="box") effective_iso_potential_plot(gravity_code, omega, center_of_rotation=center_of_mass, number_of_contours=20, fraction_screen_filled=0.7) xlabel('x') ylabel('y') current_axes = pyplot.subplot(2, 2, 4) current_axes.set_aspect("equal", adjustable="box") effective_iso_potential_plot(gravity_code, omega, center_of_rotation=center_of_mass, xlim=[0.6, 1.4] | units.AU, ylim=[-0.4, 0.4] | units.AU, number_of_contours=20, fraction_screen_filled=0.9) xlabel('x') ylabel('y') pyplot.show()
native_plot, plot, scatter, xlabel, ylabel, hist ) import numpy as np if __name__ == "__main__": # latex_support() x = np.pi / 20.0 * (list(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 = list(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() x = list(range(7)) | units.day
def dm_gas_sph_subplot(self, i=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, i), 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 dm_rvir_gas_sph_3dsubplot(self): fig = pyplot.figure(figsize=(20, 10)) ax_dm = fig.add_subplot(121, aspect='equal', projection='3d') ax_gas = fig.add_subplot(122, aspect='equal', projection='3d', 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) z = outersphere.z.as_quantity_in(units.kpc) plot(x, y, z, 'o', c='red', label=r'$r \geq r_{\rm vir}$') x = innersphere.x.as_quantity_in(units.kpc) y = innersphere.y.as_quantity_in(units.kpc) z = innersphere.z.as_quantity_in(units.kpc) plot(x, y, z, 'o', c='green', label=r'$r < r_{\rm vir}$') xlabel(r'$x$') ylabel(r'$y$') ax_dm.set_zlabel(r'$z$ [{0}]'.format(virial_radius.unit)) 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) ax_gas.scatter(x.number, y.number, z.number, color=colors, s=sizes, edgecolors="none", alpha=alpha) xlabel(r'$x$') ylabel(r'$y$') ax_gas.set_zlabel(r'$z$ [{0}]'.format(virial_radius.unit)) xlim(-2.*virial_radius, 2*virial_radius) ylim(-2.*virial_radius, 2*virial_radius) ax_dm.set_zlim(-2.*virial_radius.number, 2*virial_radius.number) ax_gas.set_zlim(-2.*virial_radius.number, 2*virial_radius.number) pyplot.tight_layout() pyplot.show()
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() x = range(7) | units.day
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)
def __init__(self): self.merger = ClusterMerger() timesteps = VectorQuantity.arange(0 | units.Myr, 1 | units.Gyr, 50 | units.Myr) tot = len(timesteps) end_time = timesteps[-1] print "Starting Simulation :-)" print "Generating plots on the fly :-)" gasA_vel_list = [] | (units.km / units.s) dmA_vel_list = [] | (units.km / units.s) gasB_vel_list = [] | (units.km / units.s) dmB_vel_list = [] | (units.km / units.s) time_list = [] | units.Gyr for i, time in enumerate(timesteps): print_progressbar(i, tot) self.merger.code.evolve_model(time) self.merger.dm_gas_sph_subplot(i) gasA_vel_list.append(self.merger.gasA.center_of_mass_velocity()) dmA_vel_list.append(self.merger.dmA.center_of_mass_velocity()) gasB_vel_list.append(self.merger.gasB.center_of_mass_velocity()) dmB_vel_list.append(self.merger.dmB.center_of_mass_velocity()) time_list.append(time) write_set_to_file( self.merger.code.particles, 'out/{0}/data/cluster_{1}.amuse'.format( self.merger.timestamp, i), "amuse") print "Plotting velocity as function of time" fig = pyplot.figure(figsize=(12, 10), dpi=50) plot(time_list.number, gasA_vel_list.number, label="gasA", c='r', ls='solid') plot(time_list.number, dmA_vel_list.number, label="dmA", c='r', ls='dashed') plot(time_list.number, gasB_vel_list.number, label="gasB", c='g', ls='solid') plot(time_list.number, dmB_vel_list.number, label="dmB", c='g', ls='dashed') xlabel("Time") ylabel("Velocity") pyplot.legend() pyplot.show() print "Generating gif :-)" self.merger.create_gif() print "Stopping the code. End of pipeline :-)" self.merger.code.stop()