def test_radius_from_time(self): self.skip_no_scipy() func = stellar_wind.RSquaredAcceleration() star = Particle() star.radius = 312. | units.RSun star.acc_cutoff = 312*5. | units.RSun star.initial_wind_velocity = 2 | units.kms star.terminal_wind_velocity = 20 | units.kms times = [0., 25., 100.] | units.yr print "times", times radii = func.radius_from_time(times, star) print "radii", radii self.assertAlmostEquals(radii[0], 312. | units.RSun) self.assertAlmostEquals(radii[1], 22644.6086263 | units.RSun) self.assertAlmostEquals(radii[2], 90704.1183516 | units.RSun) return times = numpy.linspace(0., 1, 100) | units.yr radii = func.radius_from_time(times, star) print radii from matplotlib import pyplot from amuse import plot as aplot aplot.plot(times, radii/star.radius) pyplot.show()
def test_compensate_gravity(self): numpy.random.seed(123457) star = self.create_star() star_wind = stellar_wind.new_stellar_wind( 1e-8 | units.MSun, compensate_gravity=True, grid_type="random", rotate=False) star_wind.particles.add_particles(star) star_wind.evolve_model(1 | units.yr) wind = star_wind.create_wind_particles() self.assertEqual(len(wind), 100) radii = (wind.position - star.position).lengths() wind_velocities = (wind.velocity - star.velocity).lengths() r_sort = radii.argsort() v_sorted = wind_velocities[r_sort] print v_sorted self.assertDecreasing(v_sorted) self.assertAlmostEquals(v_sorted[0], 615.945250201 | units.kms) self.assertAlmostEquals(v_sorted[-1], 176.050310315 | units.kms) return from matplotlib import pyplot from amuse import plot as aplot aplot.plot(radii[r_sort], v_sorted) pyplot.show()
def planetplot(): sun, planets = new_solar_system_for_mercury() timerange = units.day(numpy.arange(0, 120 * 365.25, 12)) instance = MercuryWayWard() instance.initialize_code() instance.central_particle.add_particles(sun) instance.orbiters.add_particles(planets) instance.commit_particles() channels = instance.orbiters.new_channel_to(planets) for time in timerange: err = instance.evolve_model(time) channels.copy() planets.savepoint(time) instance.stop() for planet in planets: t, x = planet.get_timeline_of_attribute_as_vector("x") t, y = planet.get_timeline_of_attribute_as_vector("y") plot(x, y, '.') native_plot.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 make_plots(all_particles, disk_only, i=0): for j, particles in enumerate([all_particles, disk_only]): if HAS_PYNBODY: temp_particles = particles.copy() temp_particles.u = 1 | units.ms**2 temp = Gadget2() temp.gas_particles.add_particles(temp_particles) temp.commit_particles() pynbody_column_density_plot( temp.gas_particles, width=300 | units.kpc, units='m_p cm^-2', vmin=17, vmax=23) temp.stop() else: native_plot.gca().set_aspect("equal") native_plot.xlim(-150, 150) native_plot.ylim(-150, 150) plot(particles.x.as_quantity_in(units.kpc), particles.y.as_quantity_in(units.kpc), 'r.') native_plot.savefig( os.path.join( "plots", "plot_galaxy_merger_{0}_{1:=04}.png".format( "disk" if j else "total", i) ) ) native_plot.close()
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 main(M, z): r, rho = get_density_profile(EVtwin, M, z) plot(r.in_(units.RSun), rho, label="EVtwin") r, rho = get_density_profile(MESA, M, z) plot(r.in_(units.RSun), rho, label="MESA") pyplot.xlabel("$R$ [$R_\odot$]") pyplot.ylabel("density [$g/cm^3$]") pyplot.semilogy() 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 initialize_single_star(M, z): r, rho = get_density_profile(EVtwin, M, z) plot(r.in_(units.RSun), rho, label="EVtwin") r, rho = get_density_profile(MESA, M, z) plot(r.in_(units.RSun), rho, label="MESA") pyplot.xlabel("$R$ [$R_\odot$]") pyplot.ylabel("density [$g/cm^3$]") pyplot.semilogy() save_file = 'initialize_single_star.png' pyplot.savefig(save_file) print '\nSaved figure in file', save_file,'\n' pyplot.show()
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 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 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 test3(self): """ Test a plot with preferred units """ if not HAS_MATPLOTLIB: return self.skip() pyplot.clf() x = numpy.linspace(0, 100, 100) | units.yr y = numpy.linspace(0, 200, 100) | units.RSun set_printing_strategy('custom', preferred_units=[units.Myr, units.AU]) aplot.plot(x, y) self.assertEquals("[Myr]", self.xaxis().get_label_text()) self.assertEquals("[AU]", self.yaxis().get_label_text()) self.assertEquals((0., 0.0001), pyplot.xlim())
def planetplot(): sun, planets = new_solar_system_for_mercury() initial = 12.2138 | units.Gyr final = 12.3300 | units.Gyr step = 10000.0 | units.yr timerange = VectorQuantity.arange(initial, final, step) gd = MercuryWayWard() gd.initialize_code() # gd.stopping_conditions.timeout_detection.disable() gd.central_particle.add_particles(sun) gd.orbiters.add_particles(planets) gd.commit_particles() se = SSE() # se.initialize_code() se.commit_parameters() se.particles.add_particles(sun) se.commit_particles() channelp = gd.orbiters.new_channel_to(planets) channels = se.particles.new_channel_to(sun) for time in timerange: err = gd.evolve_model(time-initial) channelp.copy() # planets.savepoint(time) err = se.evolve_model(time) channels.copy() gd.central_particle.mass = sun.mass print( sun[0].mass.value_in(units.MSun), time.value_in(units.Myr), planets[4].x.value_in(units.AU), planets[4].y.value_in(units.AU), planets[4].z.value_in(units.AU) ) gd.stop() se.stop() for planet in planets: t, x = planet.get_timeline_of_attribute_as_vector("x") t, y = planet.get_timeline_of_attribute_as_vector("y") plot(x, y, '.') native_plot.gca().set_aspect('equal') native_plot.show()
def test7(self): """ Test setting the x and y limits in various ways""" if not HAS_MATPLOTLIB: return self.skip() pyplot.clf() set_printing_strategy('default') x = numpy.linspace(0, 100, 100) y = numpy.linspace(0, 200, 100) | units.RSun line = aplot.plot(x, y) aplot.xlim(-10, 80) self.assertEqual(-10, pyplot.xlim()[0]) self.assertEqual(80, pyplot.xlim()[1]) print(pyplot.xlim()) aplot.xlim(xmax=90) print(pyplot.xlim()) self.assertEqual(-10, pyplot.xlim()[0]) self.assertEqual(90, pyplot.xlim()[1]) aplot.ylim([-12, 110] | units.RSun) self.assertEqual(-12, pyplot.ylim()[0]) self.assertEqual(110, pyplot.ylim()[1]) aplot.ylim(ymin=1e6 | units.km) self.assertAlmostEqual(1.43781452, pyplot.ylim()[0]) self.assertEqual(110, pyplot.ylim()[1])
def test7(self): """ Test setting the x and y limits in various ways""" if not HAS_MATPLOTLIB: return self.skip() pyplot.clf() set_printing_strategy('default') x = numpy.linspace(0, 100, 100) y = numpy.linspace(0, 200, 100) | units.RSun line = aplot.plot(x, y) aplot.xlim(-10, 80) self.assertEquals(-10, pyplot.xlim()[0]) self.assertEquals(80, pyplot.xlim()[1]) print pyplot.xlim() aplot.xlim(xmax=90) print pyplot.xlim() self.assertEquals(-10, pyplot.xlim()[0]) self.assertEquals(90, pyplot.xlim()[1]) aplot.ylim([-12, 110]|units.RSun) self.assertEquals(-12, pyplot.ylim()[0]) self.assertEquals(110, pyplot.ylim()[1]) aplot.ylim(ymin=1e6|units.km) self.assertAlmostEquals(1.43781452, pyplot.ylim()[0]) self.assertEquals(110, pyplot.ylim()[1])
def test4(self): """ Test text in a plot """ if not HAS_MATPLOTLIB: return self.skip() pyplot.clf() set_printing_strategy('default') x = numpy.linspace(0, 100, 100) | units.yr y = numpy.linspace(0, 200, 100) | units.RSun aplot.plot(x, y) text = aplot.text(50|units.yr, 0.5|units.AU, "test text") self.assertEquals(50., text.get_position()[0]) self.assertAlmostEquals(107.546995464, text.get_position()[1])
def plot_individual_cluster_temperature(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)] numerical.set_gas_temperature() pyplot.scatter(numerical.gas.r.value_in(units.kpc), numerical.gas.T.value_in(units.K), c=data_colour[0], edgecolor="face", s=5 if poster_style else 1, label="Gas, sampled") # Analytical solutions. Sample radii and plug into analytical expression. # Plot analytical temperature (Donnert 2014) # NB the temperature is set by both gas and dark matter # because it follows from hydrostatic equation, which contains M(<r), # where M(<r) is the total gravitating mass delivered by gas+dm! amuse_plot.plot(analytical.radius, analytical.temperature(), ls="dotted", c=fit_colour, lw=5 if poster_style else 1, label="Analytical") pyplot.axhline(analytical.characteristic_temperature().value_in(units.K)) pyplot.axvline(analytical.rc.value_in(units.kpc)) pyplot.xlabel(r"Radius [kpc]") pyplot.ylabel(r"Temperature [K]") pyplot.gca().set_xscale("log") pyplot.gca().set_yscale("log") pyplot.gca().set_xlim(xmin=1, xmax=1e4) pyplot.legend(loc=3)
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 main(n=10, mmin=1.0, mmax=100, z=0.02): dm = (mmax-mmin)/n mZAMS = numpy.arange(mmin, mmax, dm) | units.MSun mmin = mmin | units.MSun mmax = mmax | units.MSun print(mZAMS) t_sse = [] | units.Myr t_analytic = [] | units.Myr for mi in mZAMS: t_sse.append(stellar_lifetime(mi, z)) t_analytic.append(power_law_fit_to_main_sequence_lifetime(mi)) plot(mZAMS, t_sse, label="sse") plot(mZAMS, t_analytic, label="analytic") plt.loglog() plt.legend() plt.title("comparison between SSE and analytic with z="+str(z)) plt.show()
def main(n=10, mmin=1.0, mmax=100, z=0.02): dm = (mmax - mmin) / n mZAMS = numpy.arange(mmin, mmax, dm) | units.MSun mmin = mmin | units.MSun mmax = mmax | units.MSun print(mZAMS) t_sse = [] | units.Myr t_analytic = [] | units.Myr for mi in mZAMS: t_sse.append(stellar_lifetime(mi, z)) t_analytic.append(power_law_fit_to_main_sequence_lifetime(mi)) plot(mZAMS, t_sse, label="sse") plot(mZAMS, t_analytic, label="analytic") plt.loglog() plt.legend() plt.title("comparison between SSE and analytic with z=" + str(z)) plt.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 planetplot(): sun, planets = new_solar_system_for_mercury() initial = 12.2138 | units.Gyr final = 12.3300 | units.Gyr step = 10000.0 | units.yr timerange = VectorQuantity.arange(initial, final, step) gd = MercuryWayWard() gd.initialize_code() # gd.stopping_conditions.timeout_detection.disable() gd.central_particle.add_particles(sun) gd.orbiters.add_particles(planets) gd.commit_particles() se = SSE() # se.initialize_code() se.commit_parameters() se.particles.add_particles(sun) se.commit_particles() channelp = gd.orbiters.new_channel_to(planets) channels = se.particles.new_channel_to(sun) for time in timerange: err = gd.evolve_model(time - initial) channelp.copy() # planets.savepoint(time) err = se.evolve_model(time) channels.copy() gd.central_particle.mass = sun.mass print( (sun[0].mass.value_in(units.MSun), time.value_in(units.Myr), planets[4].x.value_in(units.AU), planets[4].y.value_in(units.AU), planets[4].z.value_in(units.AU))) gd.stop() se.stop() for planet in planets: t, x = planet.get_timeline_of_attribute_as_vector("x") t, y = planet.get_timeline_of_attribute_as_vector("y") plot(x, y, '.') native_plot.gca().set_aspect('equal') native_plot.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 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 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 plot_densities(self): print "Plotting x-density as function of time" if not os.path.exists('out/{0}/plots/density'.format(self.timestamp)): os.mkdir('out/{0}/plots/density'.format(self.timestamp)) density_gasA_list = [] | (units.MSun / units.Mpc**3) density_dmA_list = [] | (units.MSun / units.Mpc**3) density_gasB_list = [] | (units.MSun / units.Mpc**3) density_dmB_list = [] | (units.MSun / units.Mpc**3) time_list = [] | units.Gyr paths = sorted(glob.glob('out/{0}/data/gasA_*'.format(self.timestamp)), key=os.path.getmtime) tot = len(paths) - 1 for i, path in enumerate(paths): time = path[28:-6] # fix due to round error when storing the data. print_progressbar(i, tot) gasA = read_set_from_file( "out/{0}/data/gasA_{1}.amuse".format(self.timestamp, time), "amuse") dmA = read_set_from_file( "out/{0}/data/dmA_{1}.amuse".format(self.timestamp, time), "amuse") gasB = read_set_from_file( "out/{0}/data/gasB_{1}.amuse".format(self.timestamp, time), "amuse") dmB = read_set_from_file( "out/{0}/data/dmB_{1}.amuse".format(self.timestamp, time), "amuse") density_gasA = gasA.mass / (4. / 3 * numpy.pi * gasA.h_smooth**3) density_dmA = dmA.mass / (4. / 3 * numpy.pi * dmA.radius**3) density_gasB = gasB.mass / (4. / 3 * numpy.pi * gasB.h_smooth**3) density_dmB = dmA.mass / (4. / 3 * numpy.pi * dmA.radius**3) fig = pyplot.figure(figsize=(12, 10), dpi=50) plot(gasA.x, density_gasA, label="gasA", c="r", ls="solid") plot(dmA.x, density_dmA, label="dmA", c="r", ls="dashed") plot(gasB.x, density_gasB, label="gasB", c="g", ls="solid") plot(dmB.x, density_dmB, label="dmB", c="g", ls="dashed") xlabel("x") ylabel("Density") pyplot.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) pyplot.show() pyplot.savefig('out/{0}/plots/density/density_{1}'.format( self.timestamp, time), dpi=50) pyplot.close() if i > 10: break print
def test_density_distribution(self): numpy.random.seed(1234567) N = 100000 rmin = 1 | units.RSun rmax = 10 | units.RSun gen = stellar_wind.PositionGenerator() p, _ = gen.generate_positions(N, rmin, rmax) r = p.lengths() print 'rmin', r.min() print 'rmax', r.max() print r.mean() self.assertEquals(len(r), N) self.assertGreaterEqual(r.min(), rmin) self.assertLessEqual(r.max(), rmax) self.assertAlmostEquals(r.mean(), 5.49955427602 | units.RSun) return r = r.value_in(units.RSun) n_bins = 50 n, bins = numpy.histogram(r, n_bins, range=(1, 10)) bin_volume = 4. / 3. * numpy.pi * (bins[1:]**3 - bins[:-1]**3) dens = n / bin_volume bin_means = (bins[1:] + bins[:-1]) / 2. s = p[abs(p[:, 2]) < (0.1 | units.RSun)] from matplotlib import pyplot from amuse import plot as aplot aplot.plot(s[:, 0], s[:, 1], '.') pyplot.axis('equal') pyplot.savefig("scatter.pdf") pyplot.clf() x = numpy.linspace(1, 10, num=200) y = 300. / x**2 # y = 0. * x + dens.mean() from matplotlib import pyplot # pyplot.plot(x, y) pyplot.loglog(x, y) pyplot.plot(bin_means, dens, '*') pyplot.savefig("dens.pdf")
def test_density_distribution(self): numpy.random.seed(1234567) N = 100000 rmin = 1 | units.RSun rmax = 10 | units.RSun gen = stellar_wind.PositionGenerator() p, _ = gen.generate_positions(N, rmin, rmax) r = p.lengths() print 'rmin', r.min() print 'rmax', r.max() print r.mean() self.assertEquals(len(r), N) self.assertGreaterEqual(r.min(), rmin) self.assertLessEqual(r.max(), rmax) self.assertAlmostEquals(r.mean(), 5.49955427602 | units.RSun) return r = r.value_in(units.RSun) n_bins = 50 n, bins = numpy.histogram(r, n_bins, range=(1, 10)) bin_volume = 4./3. * numpy.pi * (bins[1:]**3 - bins[:-1]**3) dens = n / bin_volume bin_means = (bins[1:] + bins[:-1])/2. s = p[abs(p[:, 2]) < (0.1 | units.RSun)] from matplotlib import pyplot from amuse import plot as aplot aplot.plot(s[:, 0], s[:, 1], '.') pyplot.axis('equal') pyplot.savefig("scatter.pdf") pyplot.clf() x = numpy.linspace(1, 10, num=200) y = 300. / x**2 # y = 0. * x + dens.mean() from matplotlib import pyplot # pyplot.plot(x, y) pyplot.loglog(x, y) pyplot.plot(bin_means, dens, '*') pyplot.savefig("dens.pdf")
def get_r200(self): # TODO: implement this function from analytical solution cc = CosmologyCalculator() rhocrit200 = 200 * cc.rho_crit() M_gas_below_r = self.gas_mass() M_dm_below_r = M_gas_below_r / 0.17 rho_average = (M_dm_below_r / (4. / 3 * numpy.pi * self.radius**3)).value_in( units.g / units.cm**3) r200 = self.radius[(numpy.abs(rho_average - rhocrit200)).argmin()] print rhocrit200 print r200 pyplot.figure() amuse_plot.plot(self.radius, self.gas_density()) amuse_plot.plot(self.radius, rho_average) pyplot.gca().set_xscale("log") pyplot.gca().set_yscale("log") pyplot.axhline(rhocrit200) pyplot.show()
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 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 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 testsse(): sse = SSEWithMassEvolve() sse.commit_parameters() sun, planets = new_solar_system_for_mercury() sse.particles.add_particles(sun) sse.commit_particles() channel = sse.particles.new_channel_to(sun) channel.copy() massrange = units.MSun(numpy.arange(1, 0.8, -0.001)) masses = [] | units.MSun timerange = [] | units.Myr for mass in massrange: sse.evolve_mass(mass) t, m = sse.evolve_mass(mass) timerange.append(t) channel.copy() masses.append(sse.particles[0].mass) sse.stop() plot(massrange, timerange, '.') native_plot.show()
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 run_simulation(): 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 = [] dmA_vel_list = [] gasB_vel_list = [] dmB_vel_list = [] time_list = [] for i, time in enumerate(timesteps): print_progressbar(i, tot, end_time) merger.code.evolve_model(time) merger.dm_gas_sph_subplot(i) gasA_vel_list.append(merger.gasA.center_of_mass_velocity()) dmA_vel_list.append(merger.dmA.center_of_mass_velocity()) gasB_vel_list.append(merger.gasB.center_of_mass_velocity()) dmB_vel_list.append(merger.dmB.center_of_mass_velocity()) time_list.append(time) write_set_to_file( merger.code.particles, '{0}/data/cluster_{1}.amuse'.format(merger.timestamp, i), "amuse") print "Plotting velocity as functio of time" fig = pyplot.figure(figsize=(12, 10), dpi=50) plot(time_list, gasA_vel, label="gasA", c='r', ls='solid') plot(time_list, dmA_vel, label="dmA", c='r', ls='dashed') plot(time_list, gasB_vel, label="gasB", c='g', ls='solid') plot(time_list, dmB_vel, label="dmB", c='g', ls='dashed') xlabel("Time") ylabel("Velocity") pyplot.legend() pyplot.show() print "Generating gif :-)" merger.create_gif() print "Stopping the code. End of pipeline :-)" merger.code.stop()
def test6(self): """ Test setting the x limits on a plot """ if not HAS_MATPLOTLIB: return self.skip() pyplot.clf() set_printing_strategy('default') x = numpy.linspace(0, 100, 100) | units.yr y = numpy.linspace(0, 200, 100) | units.RSun line = aplot.plot(x, y) aplot.xlim(0 | units.yr, 2e9 | units.s) self.assertAlmostEquals(0, pyplot.xlim()[0]) self.assertAlmostEquals(63.37752924, pyplot.xlim()[1])
def test6(self): """ Test setting the x limits on a plot """ if not HAS_MATPLOTLIB: return self.skip() pyplot.clf() set_printing_strategy('default') x = numpy.linspace(0, 100, 100) | units.yr y = numpy.linspace(0, 200, 100) | units.RSun line = aplot.plot(x, y) aplot.xlim(0|units.yr, 2e9|units.s) self.assertAlmostEquals(0, pyplot.xlim()[0]) self.assertAlmostEquals(63.37752924, pyplot.xlim()[1])
def plot_velocities(self): print "Plotting velocity as function of time" 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(self.timesteps): gasA = read_set_from_file( "out/{0}/data/gasA_{1}.amuse".format( self.timestamp, int(time.value_in(units.Myr))), "amuse") dmA = read_set_from_file( "out/{0}/data/dmA_{1}.amuse".format( self.timestamp, int(time.value_in(units.Myr))), "amuse") gasB = read_set_from_file( "out/{0}/data/gasB_{1}.amuse".format( self.timestamp, int(time.value_in(units.Myr))), "amuse") dmB = read_set_from_file( "out/{0}/data/dmB_{1}.amuse".format( self.timestamp, int(time.value_in(units.Myr))), "amuse") gasA_vel_list.append(gasA.center_of_mass_velocity().x) dmA_vel_list.append(dmA.center_of_mass_velocity().x) gasB_vel_list.append(gasB.center_of_mass_velocity().x) dmB_vel_list.append(dmB.center_of_mass_velocity().x) time_list.append(time) print fig = pyplot.figure(figsize=(12, 10), dpi=50) plot(time_list, gasA_vel_list, label="gasA", c="r", lw=10, ls="solid") plot(time_list, dmA_vel_list, label="dmA", c="r", lw=10, ls="dashed") plot(time_list, gasB_vel_list, label="gasB", c="g", lw=10, ls="solid") plot(time_list, dmB_vel_list, label="dmB", c="g", lw=10, ls="dashed") xlabel("Time") ylabel("Velocity") pyplot.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) pyplot.show() print gasA_vel_list print dmA_vel_list print gasB_vel_list print dmB_vel_list print time_list
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 plot_individual_cluster_mass(cluster): pyplot.figure(figsize=(24, 18)) # TODO: use different method :-)... get_mass_via_number_density(cluster) # get_mass_via_number_density_parallel(cluster) # get_mass_via_density(cluster) pyplot.gca().set_xscale("log") pyplot.gca().set_yscale("log") # M_gas = (cluster.gas.mass.value_in(units.MSun)) # M_dm = (cluster.dm.mass.value_in(units.MSun)) # amuse_plot.scatter(cluster.gas.r, units.MSun(M_gas), c="g", label="Gas") # amuse_plot.scatter(cluster.dm.r, units.MSun(M_dm), c="b", label="DM") # Analytical solutions. Sample radii and plug into analytical expression. r = VectorQuantity.arange(units.kpc(1), units.kpc(10000), units.parsec(100)) # Plot analytical Hernquist model for the DM mass M(<r) amuse_plot.plot(r, cluster.dm_cummulative_mass(r), ls="solid", c="k", label="DM") # Plot analytical beta model (Donnert 2014) for the gas mass M(<r) amuse_plot.plot(r, cluster.gas_cummulative_mass_beta(r), ls="dotted", c="k", label=r"$\beta$-model") # Plot analytical double beta model (Donnert et al. 2016, in prep) gas M(<r) amuse_plot.plot(r, cluster.gas_cummulative_mass_double_beta(r), ls="dashed", c="k", label=r"double $\beta$-model") pyplot.xlabel(r"$r$ [kpc]") pyplot.ylabel(r"$M (<r)$ [MSun]") pyplot.gca().set_xscale("log") pyplot.gca().set_yscale("log") pyplot.legend(loc=4)
# the imports needed to read and write a set from amuse.io import write_set_to_file from amuse.io import read_set_from_file import os.path if __name__ == "__main__": if os.path.exists('plummer128.hdf'): os.remove('plummer128.hdf') # generate a particle set plummer = new_plummer_model(128) # write the set to file 'testfile' # the third argument is the file format, 'amuse' is an hdf5 based format # that saves all information. Other formats # available are e.g. csv, txt, gadget, starlab write_set_to_file(plummer, 'plummer128.hdf', 'amuse') # reading back the file # we close the file, causing all data to be copied to memory # instead of being read from an open file particles = read_set_from_file('plummer128.hdf', 'amuse', close_file=True) # plotting plot(particles.x, particles.y, 'r.') native_plot.xlim(-5, 5) native_plot.ylim(-5, 5) native_plot.show()
run = JeansInstability( 1.5e7 | units.g / units.cm**3, 1.5e7 | dyn / units.cm**2, ncells=ncells ) run.setup() t = 0 | units.s x = [] | units.s y = [] | units.g / units.cm**3 x.append(t) y.append(run.code.grid[2, 2, 0].rho) while t < 10 | units.s: t += 0.01 | units.s run.evolve_model(t) x.append(t) y.append(run.code.grid[2, 2, 0].rho) print "evolved to", t, run.code.grid[2, 2, 0].rho if IS_PLOT_AVAILABLE: figure = pyplot.figure(figsize=(10, 5)) plot = figure.add_subplot(1, 1, 1) plot.plot(x.value_in(units.s), y.value_in(units.g / units.cm**3)) if RUN_WITH_SELF_GRAVITY: figure.savefig('jeans_instability_grav.png') else: figure.savefig('jeans_instability_nograv.png') pyplot.show()
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))
while(model_time<end_time): dt = 10.0 | units.Myr model_time += dt gravity.evolve_model(model_time) ch_g2l.copy() x.append(galaxies.x) y.append(galaxies.y) resolve_collision(stopping_condition, gravity, galaxies) a = 0 b = 4 #plt.scatter(galaxies.x.value_in(units.kpc),galaxies.y.value_in(units.kpc),c = 'r') plot(x, y, lw=1) plt.gca().set_aspect("equal", adjustable="box") plt.ylim((a,b)) plt.show() gravity.stop() # In[6]: # from amuse.lab import BHTree # galaxies = MW_and_M31() # converter=nbody_system.nbody_to_si(galaxies.mass.sum(), galaxies[1].position.length())
run = JeansInstability( 1.5e7 | units.g / units.cm**3, 1.5e7 | dyn / units.cm**2, ncells=ncells ) run.setup() t = 0 | units.s x = [] | units.s y = [] | units.g / units.cm**3 x.append(t) y.append(run.code.grid[2, 2, 0].rho) while t < 10 | units.s: t += 0.01 | units.s run.evolve_model(t) x.append(t) y.append(run.code.grid[2, 2, 0].rho) print("evolved to", t, run.code.grid[2, 2, 0].rho) if IS_PLOT_AVAILABLE: figure = pyplot.figure(figsize=(10, 5)) plot = figure.add_subplot(1, 1, 1) plot.plot(x.value_in(units.s), y.value_in(units.g / units.cm**3)) if RUN_WITH_SELF_GRAVITY: figure.savefig('jeans_instability_grav.png') else: figure.savefig('jeans_instability_nograv.png') pyplot.show()
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()
def plot_fit_results(observed, analytical, numerical=None, mass_density=False, save=False, poster_style=False, fix_cygA=False): if poster_style: pyplot.style.use(["dark_background"]) pyplot.rcParams.update({"font.weight": "bold"}) # 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)] fit_colour = "white" else: data_colour = ["g", "r", "b"] fit_colour = "k" if mass_density: observed_density = observed.density observed_density_std = observed.density_std analytical_density = analytical.gas_density().value_in(units.g / units.cm**3) else: # using number density as density observed_density = observed.number_density observed_density_std = observed.number_density_std analytical_density = analytical.gas_number_density().value_in( 1 / units.cm**3) fig, (ax, ax_r) = pyplot.subplots(2, 2, sharex=True, figsize=(16, 12)) gs1 = matplotlib.gridspec.GridSpec(3, 3) gs1.update(hspace=0) ax = pyplot.subplot(gs1[:-1, :]) ax_r = pyplot.subplot(gs1[-1, :]) # residuals # Plot data pyplot.sca(ax) # pyplot.title(observed.name) pyplot.errorbar(observed.radius+observed.binsize/2, observed_density, xerr=observed.binsize/2, yerr=observed_density_std, marker='o', ms=5 if poster_style else 3, elinewidth=3 if poster_style else 1, ls="", c=data_colour[0] if observed.name=="cygA" else data_colour[2], label="800" if observed.oldICs else "982"+\ " ks Chandra\n(Wise et al. in prep)",) label = "model: " + analytical.modelname + "\n\t" label += r"$n_{{e,0}} \,$ = {0:.2e} cm$^{{-3}}$".format( analytical.ne0.number ) if not mass_density else r"$\rho_{{0}} \,$ = {0:.2e} g cm$^{{-3}}$".format( analytical.rho0.number) label += "\n\t" + r"$r_c \,$ = {0:.2f} kpc".format(analytical.rc.number) if analytical.rcut is not None and not analytical.free_beta: label += "\n\t" + r"$r_{{\rm cut}}$ = {0:.2f} kpc".format( analytical.rcut.number) if analytical.free_beta: label += "\n\t" + r"$\beta$ = {0:.2f}".format(analytical.beta) if analytical.rho0_cc is not None: label += "\n\t" + r"$n_{{e,0,cc}}$ = {0:.2f} cm$^{{-3}}$".format( analytical.ne0_cc.number ) if not mass_density else "\n\t" + r"$\rho_{{0,cc}}$ = {0:.2f} kpc".format( analytical.rho0_cc.number) label += "\n\t" + r"$r_{{c,cc}}$ = {0:.2f} kpc".format( analytical.rc_cc.number) label = r"\begin{tabular}{lll}" if analytical.free_beta: label += " model & = & free beta \\\\" else: label += " model & = & fixed beta \\\\" label += r" rho0 & = & {0:.2e} g$\cdot$cm$^{{-3}}$ \\".format( analytical.rho0.number) label += " rc & = & {0:.2f} kpc \\\\".format(analytical.rc.number) if analytical.free_beta: label += " beta & = & {0:.3f} kpc \\\\".format(analytical.beta) label += (" \end{tabular}") amuse_plot.plot(analytical.radius, analytical_density, c=fit_colour, lw=3 if poster_style else 1, label=label) if numerical: pyplot.scatter(numerical.gas.r.value_in(units.kpc), numerical.gas.rho.value_in(units.g / (units.cm**3)), c="g", edgecolor="face", s=4, label=r"Gas, numerical") ax.set_xscale("log") ax.set_yscale("log") if mass_density: ax.set_ylabel(r"Gas density [g/cm$**$3]", fontsize=38) ax.set_ylim(min(observed_density) / 1.5, max(observed_density) * 1.3) else: ax.set_ylabel(r"Gas density [1/cm$**$3]", fontsize=38) ax.legend(loc=3, prop={'size': 30}) # Plot Residuals pyplot.sca(ax_r) residual_density = (observed_density - analytical_density) / observed_density pyplot.errorbar(observed.radius + observed.binsize / 2, 100 * residual_density, yerr=100 * observed_density_std / observed_density, c=fit_colour, lw=3 if poster_style else 1, elinewidth=1 if poster_style else 1, drawstyle="steps-mid") ax_r.axhline(y=0, lw=3 if poster_style else 1, ls="dashed", c=fit_colour) ax_r.set_xscale("log") # ax_r.set_yscale("log") ax.set_xlim(min(observed.radius) - 0.3, max(observed.radius) + 2000) ax_r.set_xlim(min(observed.radius) - 0.3, max(observed.radius) + 2000) # Show 50% deviations from the data if fix_cygA: ax_r.set_ylim(-20, 100) else: ax_r.set_ylim(-50, 50) # Fix for overlapping y-axis markers from matplotlib.ticker import MaxNLocator ax.tick_params(labelbottom='off') nbins = len(ax_r.get_yticklabels()) ax_r.yaxis.set_major_locator(MaxNLocator(nbins=nbins, prune='upper')) ax_r.set_xlabel(r"Radius [kpc]", fontsize=38) ax_r.set_ylabel(r"Residuals [\%]", fontsize=38) ax.axvline(x=analytical.rc.value_in(units.kpc), lw=3 if poster_style else 1, ls="dashed", c=fit_colour) ax_r.axvline(x=analytical.rc.value_in(units.kpc), lw=3 if poster_style else 1, ls="dashed", c=fit_colour) # Force axis labels to align ax.get_yaxis().set_label_coords(-0.15, 0.5) ax_r.get_yaxis().set_label_coords(-0.15, 0.5) pyplot.sca(ax) ylim = pyplot.gca().get_ylim() pyplot.text(1.05 * analytical.rc.value_in(units.kpc), 0.95 * ylim[1], r"$r_c$", ha="left", va="top", color="k", fontsize=38) if save and not analytical.free_beta: pyplot.savefig("out/density_betamodel_fit_{0}{1}{2}.png"\ .format(observed.name, "_800ksec" if observed.oldICs else "_900ksec", "_dark" if poster_style else ""), dpi=300) if save and analytical.free_beta: pyplot.savefig("out/density_free_betamodel_fit_{0}{1}{2}.png"\ .format(observed.name, "_800ksec" if observed.oldICs else "_900ksec", "_dark" if poster_style else ""), dpi=300) if not save: pyplot.show()
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()
def plot_energies(self): print "Plotting energies as function of time" thermal_list = [] | (units.erg) kinetic_list = [] | (units.erg) potential_list = [] | (units.erg) total_list = [] | (units.erg) time_list = [] | units.Gyr paths = sorted(glob.glob('out/{0}/data/gasA_*'.format(self.timestamp)), key=os.path.getmtime) tot = len(paths) - 1 for i, path in enumerate(paths): time = path[28:-6] # fix due to round error when storing the data. print_progressbar(i, tot) gasA = read_set_from_file( "out/{0}/data/gasA_{1}.amuse".format(self.timestamp, time), "amuse") dmA = read_set_from_file( "out/{0}/data/dmA_{1}.amuse".format(self.timestamp, time), "amuse") gasB = read_set_from_file( "out/{0}/data/gasB_{1}.amuse".format(self.timestamp, time), "amuse") dmB = read_set_from_file( "out/{0}/data/dmB_{1}.amuse".format(self.timestamp, time), "amuse") thermal = gasA.thermal_energy() + gasB.thermal_energy() kinetic = gasA.kinetic_energy() + dmA.kinetic_energy( ) + gasB.kinetic_energy() + dmB.kinetic_energy() potential = gasA.potential_energy() + dmA.potential_energy( ) + gasB.potential_energy() + dmB.potential_energy() thermal_list.append(thermal) kinetic_list.append(kinetic) potential_list.append(potential) total_list.append(thermal + kinetic + potential) time_list.append((int(time) | units.Myr)) print fig = pyplot.figure(figsize=(12, 10), dpi=50) plot(time_list, thermal_list, label="thermal", c="m", lw=10, ls="solid") plot(time_list, kinetic_list, label="kinetic", c="g", lw=10, ls="solid") plot(time_list, potential_list, label="potential", c="y", lw=10, ls="solid") plot(time_list, total_list, label="total", c="r", lw=10, ls="solid") xlabel("Time") ylabel("Energy") pyplot.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) pyplot.show() print thermal_list print kinetic_list print potential_list print total_list print time_list
def plot_density_profile(radius, rho): plot(radius.in_(units.RSun), rho) pyplot.xlabel("$R$ [$R_\odot$]") pyplot.ylabel("density [$g/cm^3$]") pyplot.semilogy() pyplot.show()
instance.particles.add_particles(particles) channelp = instance.particles.new_channel_to(particles) start = 0 | units.yr end = 150 | units.yr step = 10 | units.day timerange = VectorQuantity.arange(start, end, step) masses = [] | units.MSun for i, time in enumerate(timerange): instance.evolve_model(time) channelp.copy() particles.savepoint(time) if (i % 220 == 0): instance.particles[0].mass = simulate_massloss(time) masses.append(instance.particles[0].mass) instance.stop() particle = particles[1] t, pos = particle.get_timeline_of_attribute_as_vector("position") distances = pos.lengths().as_quantity_in(units.AU) plot(timerange, distances, timerange, masses) native_plot.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 xtest4(self): """ test if get_gravity_at_point is consistent with the default, (which uses get_potential_at_point). It seems that this doesn't really make sense """ static_potential = static_potentials.Galactic_Center_Potential_Kruijssen( ) r = numpy.logspace(1, 3, 10) | units.parsec z = numpy.zeros(r.shape) | units.parsec gravity = static_potential.get_gravity_at_point(z, r, z, z) orig_gravity = static_potentials.Abstract_Potential.get_gravity_at_point( static_potential, z, r, z, z) # quick plot for testing from matplotlib import pyplot from amuse import plot as aplot aplot.plot(r, gravity[0], marker="*", color='black') aplot.plot(r, orig_gravity[0], ls=":", marker="^", color='black') aplot.plot(r, gravity[1], marker="*", color='red') aplot.plot(r, orig_gravity[1], ls=":", marker="^", color='red') aplot.plot(r, gravity[2], marker="*", color='green') aplot.plot(r, orig_gravity[2], ls=":", marker="^", color='green') pyplot.show() TODO