repo
stringlengths
2
99
file
stringlengths
13
225
code
stringlengths
0
18.3M
file_length
int64
0
18.3M
avg_line_length
float64
0
1.36M
max_line_length
int64
0
4.26M
extension_type
stringclasses
1 value
amuse
amuse-main/examples/textbook/2017arXiv170307029H_Fig3.py
import numpy from amuse.lab import * from matplotlib import pyplot R_young_stars = [ 0.1012221753955787, 0.2968660204589863, 0.5017430508551541, 0.7046418772801384, 0.8984687805821738, 1.1087212228990806, 1.296848150063784] S_young_stars = [ 69.68021137071266, 21.28302762211248 , 8.871846723535821 , 4.634361707743547 , 0.842276996426784 , 0.35283784451473543, 0.32284672967371486] R_all_stars = [ 0.09966839700574376, 0.29542608638995443, 0.4910636790322119, 0.6989696157755654, 0.9093883458890231, 1.1027718150669223, 1.3041555749011087] S_all_stars = [246.4266804633498 , 108.52660553059054, 59.62962877617595 , 22.170446486030563 , 6.83698178212555 , 2.8123977037860786 , 0.28189901519958876] R_dense_gas = [ 0.10160842129883879, 0.30957902551862887, 0.5005420834356191, 0.6940641257773106, 0.8993648870413651, 1.107381682315753, 1.2954901330586175] S_dense_gas = [587.057496278814, 193.757708949030, 81.05652212929158, 25.83103135675521, 13.72720495792530, 4.161094960653975, 3.939217817754274] R_all_gas = [ 0.09890162549942522, 0.2971536318319011, 0.5047269929821525, 0.6955052866807527, 0.8934247174201266, 1.0960741121502846, 1.296349286674131] S_all_gas = [ 1011.82389615108 , 382.3950057709804, 262.3523868909657 , 154.2500699106347, 107.5704842567941, 88.9640154049995 , 68.72257895441606] pyplot.rcParams.update({'font.size': 30}) fig, ax = pyplot.subplots(figsize=[16,10]) ax.minorticks_on() # switch on the minor ticks ax.tick_params('both', length=15, width=2, which='major') ax.tick_params('both', length=6, width=1, which='minor') from distinct_colours import get_distinct colors = get_distinct(10) pyplot.scatter(R_young_stars, S_young_stars, s=100, marker='s', c=colors[6], lw=0) pyplot.scatter(R_all_stars, S_all_stars, s=100, marker='s', c=colors[0], lw=0) #pyplot.scatter(R_dense_gas, S_dense_gas, s=100, marker='s', c=colors[7], lw=0) pyplot.scatter(R_all_gas, S_all_gas, s=100, marker='s', c=colors[3], lw=0) def plot_radial_distribution(gas, nbin, c, lw): X = [] Ymean = [] Ystd = [] for gi in range(len(gas)-nbin): X.append(gas[gi: gi+nbin].r.value_in(units.parsec).mean()) S = (gas[gi+nbin].r**2-gas[gi].r**2) rho = gas[gi: gi+nbin].mass.sum()/S #if hasattr(gas, "rho"): #rho = gas[gi: gi+nbin].rho.max()*S.sqrt() Ymean.append(rho.value_in(units.MSun/units.parsec**2)) pyplot.plot(X, Ymean, c=colors[c], lw=lw) def plot_radial_density_distribution(gas, stars): com = stars.center_of_mass() gas.r = ((gas.x-com[0])**2 + (gas.y-com[1])**2).sqrt() gas = gas.sorted_by_attributes("r") stars.r = ((stars.x-com[0])**2 + (stars.y-com[1])**2).sqrt() stars = stars.sorted_by_attributes("r") max_age = stars.birth_age.max() young_stars = stars[max_age-stars.birth_age<1.5|units.Myr] mN2H = 2*29.02134 cutoff_density = 1e5 * mN2H * constants.atomic_unit_of_mass/(1|units.cm**3) dense_gas = gas[gas.density>cutoff_density] plot_radial_distribution(gas, 100, c=3, lw=4) # plot_radial_distribution(dense_gas, 100, c=7, lw=2) plot_radial_distribution(stars, 60, c=0, lw=4) plot_radial_distribution(young_stars, 10, c=6, lw=4) pyplot.xlim(0, 1.1) pyplot.ylim(1, 1100) pyplot.semilogy() pyplot.xlabel("R [pc]") pyplot.ylabel("$\Sigma$ [M$_\odot$ pc$^{-2}]$") # pyplot.show() pyplot.savefig("2017arXiv170307029H_Fig3") def main(filename=None): disk = Particles(0) stars = Particles(0) bodies = read_set_from_file(filename, "amuse") for bi in bodies.history: #print(bi) if len(bi)>0: if hasattr(bi, "name") and "gas" in str(bi.name): disk.add_particles(bi.copy()) elif "Star" in str(bi.name): stars.add_particles(bi.copy()) print("Stellar masses:", stars.mass.min().in_(units.MSun), stars.mass.mean().in_(units.MSun), stars.mass.max().in_(units.MSun), stars.mass.median().in_(units.MSun)) #plot_age_gasdensity(disk, stars) plot_radial_density_distribution(disk, stars) def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-f", dest="filename", default ="GMC_R2pcN20k_SE_T45Myr.amuse", help="output filename [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
4,925
36.892308
168
py
amuse
amuse-main/examples/textbook/gravity_stellar_comparison.py
""" Nbody integration of N particles with a Salpeter initial mass function between Mmin and Mmax and with stellar evolution with metallicity z. """ import numpy from matplotlib import pyplot from amuse.lab import * from amuse.ext.LagrangianRadii import LagrangianRadii from prepare_figure import single_frame from distinct_colours import get_distinct class Gravity: def __init__(self, gravity_code, particles): self.particles = particles self.converter = nbody_system.nbody_to_si(1|units.MSun, 1|units.parsec) self.code = gravity_code(self.converter) self.code.particles.add_particles(self.particles) self.channel_to_framework \ = self.code.particles.new_channel_to(self.particles) self.channel_from_framework \ = self.particles.new_channel_to(self.code.particles) def evolve_model(self, time): self.channel_from_framework self.code.evolve_model(time) self.channel_to_framework @property def model_time(self): return self.code.model_time @property def particles(self): return self.code.particles @property def kinetic_energy(self): return self.code.kinetic_energy @property def potential_energy(self): return self.code.potential_energy @property def stop(self): return self.code.stop def generate_initial_conditions(N, W0, Rvir, Mmin, Mmax): numpy.random.seed(123) masses = new_salpeter_mass_distribution(N, Mmin, Mmax) Mtot_init = masses.sum() converter=nbody_system.nbody_to_si(Mtot_init,Rvir) bodies = new_king_model(N, W0,convert_nbody=converter) bodies.mass = masses.copy() bodies.scale_to_standard(convert_nbody=converter) return bodies def run_only_gravity(bodies, t_end): Mtot_init = bodies.mass.sum() time = [] | units.Myr Lr25 = [] |units.parsec Lr50 = [] |units.parsec Lr75 = [] |units.parsec converter = nbody_system.nbody_to_si(bodies.mass.sum(), 1|units.parsec) gravity = ph4(converter) gravity.particles.add_particles(bodies) channel_from_gravity = gravity.particles.new_channel_to(bodies) dt = 0.1|units.Myr while True: time.append(gravity.model_time) Lr25.append(LagrangianRadii(gravity.particles)[5]) Lr50.append(LagrangianRadii(gravity.particles)[6]) Lr75.append(LagrangianRadii(gravity.particles)[7]) gravity.evolve_model(time[-1]+dt) channel_from_gravity.copy_attributes(["x", "y", "z", "vx", "vy", "vz"]) print("G: T=", time[-1], "M=", bodies.mass.sum(), \ "(dM[SE]=", bodies.mass.sum()/Mtot_init, ")") if time[-1] >= t_end: break gravity.stop() return time, Lr25, Lr50, Lr75 def run_sequential_gravity_and_stellar(bodies, t_end): Mtot_init = bodies.mass.sum() time = [] | units.Myr Lr25 = [] |units.parsec Lr50 = [] |units.parsec Lr75 = [] |units.parsec converter = nbody_system.nbody_to_si(bodies.mass.sum(), 1|units.parsec) gravity = ph4(converter) gravity.particles.add_particles(bodies) channel_from_gravity = gravity.particles.new_channel_to(bodies) channel_to_gravity = bodies.new_channel_to(gravity.particles) stellar = SSE() stellar.parameters.metallicity = 0.02 stellar.particles.add_particle(bodies) channel_from_stellar = stellar.particles.new_channel_to(bodies) dt = 0.1|units.Myr while True: stellar.evolve_model(gravity.model_time + dt/2) channel_from_stellar.copy_attributes(["mass"]) channel_to_gravity.copy_attributes(["mass"]) gravity.evolve_model(gravity.model_time+dt) channel_from_gravity.copy_attributes(["x", "y", "z", "vx", "vy", "vz"]) stellar.evolve_model(gravity.model_time + dt) channel_from_stellar.copy_attributes(["mass"]) channel_to_gravity.copy_attributes(["mass"]) time.append(gravity.model_time) Lr25.append(LagrangianRadii(gravity.particles)[5]) Lr50.append(LagrangianRadii(gravity.particles)[6]) Lr75.append(LagrangianRadii(gravity.particles)[7]) print("GS: T=", time[-1], "M=", bodies.mass.sum(), \ "(dM[SE]=", bodies.mass.sum()/Mtot_init, ")") if time[-1] >= t_end: break gravity.stop() stellar.stop() return time, Lr25, Lr50, Lr75 def run_event_driven_gravity_and_stellar(bodies, t_end): Mtot_init = bodies.mass.sum() time = [] | units.Myr Lr25 = [] |units.parsec Lr50 = [] |units.parsec Lr75 = [] |units.parsec converter = nbody_system.nbody_to_si(bodies.mass.sum(), 1|units.parsec) gravity = ph4(converter, number_of_workers=2) gravity.particles.add_particles(bodies) stellar = SSE() stellar.parameters.metallicity = 0.02 stellar.particles.add_particle(bodies) channel_from_gravity = gravity.particles.new_channel_to( bodies, attributes=["mass", "x", "y", "z", "vx", "vy", "vz"]) channel_from_stellar = stellar.particles.new_channel_to( bodies, attributes=["mass"]) channel_from_stellar_to_gravity = stellar.particles.new_channel_to( gravity.particles, attributes=["mass"]) while True: dt = 0.5*stellar.particles.time_step.min() stellar.evolve_model(gravity.model_time + dt/2) channel_from_stellar_to_gravity.copy() dt = 0.5*stellar.particles.time_step.min() gravity.evolve_model(stellar.model_time + dt) channel_from_gravity.copy() stellar.evolve_model(gravity.model_time) channel_from_stellar.copy() time.append(gravity.model_time) Lr25.append(LagrangianRadii(gravity.particles)[5]) Lr50.append(LagrangianRadii(gravity.particles)[6]) Lr75.append(LagrangianRadii(gravity.particles)[7]) stellar.evolve_model() print("GSE: T=", time[-1], "M=", bodies.mass.sum(), \ "(dM[SE]=", bodies.mass.sum()/Mtot_init, ")") if time[-1] >= t_end: break gravity.stop() stellar.stop() return time, Lr25, Lr50, Lr75 def main(N, W0, t_end, Rvir, Mmin, Mmax): bodies = generate_initial_conditions(N, W0, Rvir, Mmin, Mmax) print(numpy.sort(bodies.mass.value_in(units.MSun))) x_label = "t [Myr]" y_label = "R [pc]" fig = single_frame(x_label, y_label, logx=False, logy=False, xsize=14, ysize=12) color = get_distinct(4) time, Lr25, Lr50, Lr75 = run_only_gravity(bodies.copy(), t_end) pyplot.plot(time.value_in(units.Myr), Lr25.value_in(units.parsec), c=color[0], label= 'without mass loss') pyplot.plot(time.value_in(units.Myr), Lr50.value_in(units.parsec), c=color[0]) pyplot.plot(time.value_in(units.Myr), Lr75.value_in(units.parsec), c=color[0]) time, Lr25, Lr50, Lr75 \ = run_sequential_gravity_and_stellar(bodies.copy(), t_end) pyplot.plot(time.value_in(units.Myr), Lr25.value_in(units.parsec), c=color[1], label= 'with mass loss') pyplot.plot(time.value_in(units.Myr), Lr50.value_in(units.parsec), c=color[1]) pyplot.plot(time.value_in(units.Myr), Lr75.value_in(units.parsec), c=color[1]) time, Lr25, Lr50, Lr75 \ = run_event_driven_gravity_and_stellar(bodies.copy(), t_end) pyplot.plot(time.value_in(units.Myr), Lr25.value_in(units.parsec), c=color[2], label= 'event driven') pyplot.plot(time.value_in(units.Myr), Lr50.value_in(units.parsec), c=color[2]) pyplot.plot(time.value_in(units.Myr), Lr75.value_in(units.parsec), c=color[2]) pyplot.legend(loc="upper left", ncol=1, shadow=False, fontsize=24) save_file = 'gravity_stellar_comparison.png' pyplot.savefig(save_file) print('\nSaved figure in file', save_file,'\n') pyplot.show() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-N", dest="N", type="int",default = 1000, help="number of stars [1000]") result.add_option("-M", unit=units.MSun, dest="Mmax", type="float", default = 100|units.MSun, help="maximun stellar mass [100] MSun") result.add_option("-m", unit=units.MSun, dest="Mmin", type="float", default = 1|units.MSun, help="minimum stellar mass [1] MSun") result.add_option("-R", unit=units.parsec, dest="Rvir", type="float", default = 3.0|units.parsec, help="cluster virial radius [3] in parsec") result.add_option("-t", unit=units.Myr, dest="t_end", type="float", default = 10.0|units.Myr, help="end time of the simulation [10] Myr") result.add_option("-W", dest="W0", type="float", default = 3.0, help="dimensionless depth of the King potential (W0) [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
9,435
36.003922
87
py
amuse
amuse-main/examples/textbook/salpeter.py
from amuse.lab import new_powerlaw_mass_distribution def generate_power_law_mass_function(N, Mmin, Mmax, ximf): masses = new_powerlaw_mass_distribution(N, Mmin, Mmax, ximf) plot_mass_function(masses, ximf) ###BOOKLISTSTART### import numpy import math from amuse.units import units from matplotlib import pyplot from prepare_figure import figure_frame, get_distinct def plot_mass_function(masses, ximf): Mmin = masses.min() Mmax = masses.max() lm = math.log10(0.5*Mmin.value_in(units.MSun)) lM = math.log10(1.5*Mmax.value_in(units.MSun)) bins = 10**numpy.linspace(lm, lM, 51) Nbin, bin_edges= numpy.histogram(masses.value_in(units.MSun), bins=bins) y = Nbin / (bin_edges[1:] - bin_edges[:-1]) x = (bin_edges[1:] + bin_edges[:-1]) / 2.0 for i in range(len(y)): y[i] = max(y[i], 1.e-10) fig, ax = figure_frame("M$_\odot$", "N", xsize=12, ysize=8) colors = get_distinct(2) pyplot.scatter(x, y, s=100, c=colors[0], lw=0) c = ((Mmax.value_in(units.MSun)**(ximf+1)) \ - (Mmin.value_in(units.MSun)**(ximf+1))) / (ximf+1) pyplot.plot(x, len(masses)/c * (x**ximf), c=colors[1]) pyplot.loglog() save_file = "salpeter.png" pyplot.savefig(save_file) print('\nSaved figure in file', save_file,'\n') pyplot.show() ###BOOKLISTSTOP### def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-N", dest="N", type="int",default = 1000, help="number of stars [10]") result.add_option("-m", unit=units.MSun, dest="Mmin", type="float",default = 1|units.MSun, help="minimum mass of the mass function [0.1] %unit") result.add_option("-M", unit=units.MSun, dest="Mmax", type="float",default = 100|units.MSun, help="maximum mass of the mass function [100] %unit") result.add_option("-x", dest="ximf", type="float",default = -2.35, help="mass function slope [-2.35]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() numpy.random.seed(31415) generate_power_law_mass_function(**o.__dict__)
2,286
35.887097
76
py
amuse
amuse-main/examples/textbook/plot_riemann_shock_tube_rho.py
from amuse.lab import * from amuse.plot import * from prepare_figure import * from distinct_colours import get_distinct import csv def read_csv(filename): ifile = open(filename, "r") reader = csv.reader(ifile) x = [] rho = [] rownum = 0 for row in reader: # Save header row. if rownum == 0: header = row elif rownum <=2 : units_str = row else: colnum = 0 x.append(float(row[0])) rho.append(float(row[1])) for col in row: print('%-8s: %s' % (header[colnum], col)) colnum += 1 rownum += 1 ifile.close() return x, rho def plot_riemann_shock_tube_rho(): x_label = "[length]" y_label = "[mass/length$^3$]" figure = single_frame(x_label, y_label, logx=False, logy=False, xsize=14, ysize=10) color = get_distinct(3) x, rho = read_csv("riemann_shock_tube_problem_exact.csv") pyplot.plot(x,rho, c=color[0]) x, rho = read_csv("riemann_shock_tube_rho_fiN7.csv") pyplot.scatter(x, rho, c=color[1], s=100, marker="o", lw=0) x, rho = read_csv("riemann_shock_tube_problem_athenaN2.csv") pyplot.scatter(x, rho, c=color[2], s=100, marker="s", lw=0) pyplot.xlim(0.2,0.8) # pyplot.savefig("riemann_shock_tube_rho_"+model.name_of_the_code+".png") pyplot.savefig("riemann_shock_tube_rho") pyplot.show() if __name__ == "__main__": plot_riemann_shock_tube_rho()
1,504
24.948276
87
py
amuse
amuse-main/examples/textbook/two_body_bridge.py
import numpy from amuse.lab import * from amuse.couple import bridge from amuse.ext.solarsystem import new_solar_system def main(): filename = "SunAndEarth.hdf" ss = new_solar_system() star = ss[0] planet = ss[3] converter=nbody_system.nbody_to_si(star.mass,planet.position.length()) ###BOOKLISTSTART### star_gravity = ph4(converter) star_gravity.particles.add_particle(star) planet_gravity = ph4(converter) planet_gravity.particles.add_particle(planet) channel_from_star_to_framework = star_gravity.particles.new_channel_to(ss) channel_from_planet_to_framework = planet_gravity.particles.new_channel_to(ss) gravity = bridge.Bridge(use_threading=False) gravity.add_system(star_gravity, (planet_gravity,) ) gravity.add_system(planet_gravity, (star_gravity,) ) ###BOOKLISTSTOP### write_set_to_file(ss, filename, 'hdf5', append_to_file=False) Etot_init = gravity.kinetic_energy + gravity.potential_energy Etot_prev = Etot_init gravity.timestep = 1|units.day time = zero dt = 10|units.day t_end = 100 | units.yr while time < t_end: time += dt gravity.evolve_model(time) Etot_prev_se = gravity.kinetic_energy + gravity.potential_energy channel_from_star_to_framework.copy() channel_from_planet_to_framework.copy() write_set_to_file(ss, filename, 'hdf5') Ekin = gravity.kinetic_energy Epot = gravity.potential_energy Etot = Ekin + Epot print("T=", time, end=' ') print("E= ", Etot, "Q= ", Ekin/Epot, end=' ') print("dE=", (Etot_init-Etot)/Etot, "ddE=", (Etot_prev-Etot)/Etot) Etot_prev = Etot gravity.stop() if __name__ in ('__main__', '__plot__'): main()
1,766
29.465517
82
py
amuse
amuse-main/examples/textbook/initialize_single_star.py
from amuse.lab import * from matplotlib import pyplot from amuse.plot import plot, xlabel, ylabel ###BOOKLISTSTART### def get_density_profile(code=EVtwin, M=2.0|units.MSun, z=0.02): stellar = code() stellar.parameters.metallicity = z stellar.particles.add_particle(Particle(mass=M)) radius = stellar.particles[0].get_radius_profile() rho = stellar.particles[0].get_density_profile() stellar.stop() return radius, rho ###BOOKLISTSTOP### 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 new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-M", unit= units.MSun, dest="M", type="float",default = 1.0 | units.MSun, help="stellar mass [1.0] %unit") result.add_option("-z", dest="z", type="float", default = 0.02, help="metalicity [0.02]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() initialize_single_star(**o.__dict__)
1,488
33.627907
72
py
amuse
amuse-main/examples/textbook/binary_evolution_example.py
""" Generates a grid of binaries with different, primary mass, mass ratio and separation and evolves these over time. """ from amuse.units import units from amuse.units import quantities from amuse import datamodel from amuse.community.seba.interface import SeBa from matplotlib import pyplot import numpy import time ###BOOKLISTSTART1### def create_double_star(Mprim, Msec, a, e): primary_stars = datamodel.Particles(mass=Mprim) secondary_stars = datamodel.Particles(mass=Msec) stars = datamodel.Particles() primary_stars = stars.add_particles(primary_stars) secondary_stars = stars.add_particles(secondary_stars) double_star = datamodel.Particles(semi_major_axis=a, eccentricity=e) double_star.child1 = list(primary_stars) double_star.child2 = list(secondary_stars) return double_star, stars ###BOOKLISTSTOP1### ###BOOKLISTSTART2### def evolve_double_star(Mprim, Msec, a, e, end_time, n_steps): double_star, stars = create_double_star(Mprim, Msec, a, e) time = 0|units.Myr time_step = end_time/n_steps code = SeBa() code.particles.add_particles(stars) code.binaries.add_particles(double_star) channel_from_code_to_model_for_binaries \ = code.binaries.new_channel_to(double_star) t = [] | units.Myr a = [] | units.RSun e = [] while time < end_time: time += time_step code.evolve_model(time) channel_from_code_to_model_for_binaries.copy() t.append(time) a.append(double_star[0].semi_major_axis) e.append(double_star[0].eccentricity) code.stop() ###BOOKLISTSTOP2### fig = pyplot.figure(figsize=(8,6)) fta = fig.add_subplot(2,1,1) fta.plot(t.value_in(units.Myr), a.value_in(units.AU)) pyplot.ylabel('semi major axis (AU)') fte = fig.add_subplot(2,1,2) fte.plot(t.value_in(units.Myr), e) pyplot.ylabel('eccentricity') pyplot.xlabel('time [Myr]') pyplot.show() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-M", unit=units.MSun, dest="Mprim", type="float",default = 12|units.MSun, help="primar mass [%defailt]") result.add_option("-m", unit=units.MSun, dest="Msec", type="float",default = 10|units.MSun, help="secondary mass [%defailt]") result.add_option("-T", unit=units.Myr, dest="end_time", type="float", default = 25.0 |units.Myr, help="end time of the simulation [%defailt]") result.add_option("-a", unit=units.RSun, dest="a", type="float",default = 205|units.RSun, help="orbital separation [%defailt]") result.add_option("-e", dest="e", type="float", default = 0.0, help="orbital eccentricity [%defailt]") result.add_option("-n", dest="n_steps", type="float", default = 100, help="number of output steps [%defailt]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() evolve_double_star(**o.__dict__)
3,209
34.274725
79
py
amuse
amuse-main/examples/textbook/hydro_outflow_particles.py
import numpy from amuse.lab import * from amuse import datamodel from amuse.ext.evrard_test import uniform_unit_sphere set_printing_strategy("custom", #nbody_converter = converter, preferred_units = [units.MSun, units.AU, units.Myr], precision = 5, prefix = "", separator = " [", suffix = "]" ) ###BOOKLISTSTART1### def new_sph_particles_from_stellar_wind(stars, mgas): new_sph = datamodel.Particles(0) for si in stars: Ngas = int(-si.Mwind/mgas) if Ngas == 0: continue Mgas = mgas*Ngas si.Mwind += Mgas add = datamodel.Particles(Ngas) add.mass = mgas add.h_smooth = 0. | units.parsec dx,dy,dz = uniform_unit_sphere(Ngas).make_xyz() add.x = si.x+(dx * si.radius) add.y = si.y+(dy * si.radius) add.z = si.z+(dz * si.radius) for ri in range(len(add)): r = add[ri].position-si.position r = r/r.length() v_wind = (constants.G*si.mass / (add[ri].position-si.position).length()).sqrt() add[ri].u = 0.5 * (v_wind)**2 add[ri].vx = si.vx + r[0]*si.terminal_wind_velocity add[ri].vy = si.vy + r[1]*si.terminal_wind_velocity add[ri].vz = si.vz + r[2]*si.terminal_wind_velocity new_sph.add_particles(add) return new_sph ###BOOKLISTSTOP1### ###BOOKLISTSTART2### def v_terminal_teff(star): t4 = (numpy.log10(star.temperature.value_in(units.K))-4.).clip(0.,1.) return (30 | units.km/units.s) + ((4000 | units.km/units.s)*t4) ###BOOKLISTSTOP2### def main(): stars = Particles(2) stars.mass = (9.5, 10) | units.MSun stars[0].position = (1, 0, 0) | units.AU stars[0].velocity = (0, 0, 0) | units.kms stars[1].position = (0, 0, 0) | units.AU stars[1].velocity = (0, 0, 0) | units.kms stars.move_to_center() a = stars.position.length().amax() vc = constants.G*stars.mass.sum()/a stellar = SeBa() stellar.particles.add_particles(stars) stellar_to_framework = stellar.particles.new_channel_to(stars) stellar.evolve_model(26|units.Myr) stellar_to_framework.copy_attributes(["mass","radius","temperature"]) dt = 0.1|units.Myr stellar.evolve_model((26|units.Myr)+dt) stars.dmdt = (stellar.particles.mass-stars.mass)/dt stars.Mwind = 0 | units.MSun stars.terminal_wind_velocity=v_terminal_teff(stars) stellar.stop() dt = 0.1|units.day mgas = 0.1*abs(stars.dmdt.sum()*dt) converter = nbody_system.nbody_to_si(1|units.MSun, a) bodies = Particles(0) bodies.mass = mgas bodies.position = (0,0,0)|units.AU bodies.velocity = (0,0,0)|units.kms bodies.u = 0 | units.m**2 * units.s**-2 bodies.h_smooth= 0.01*a hydro = Fi(converter, redirection="none") if len(bodies) > 0: hydro.gas_particles.add_particles(bodies) hydro.parameters.use_hydro_flag = True hydro.parameters.timestep = dt hydro.parameters.periodic_box_size = 1000*a hydro_to_framework = hydro.gas_particles.new_channel_to(bodies) moving_bodies = ParticlesSuperset([stars, bodies]) filename = "hydro_outflow.hdf5" istep = 0 while hydro.model_time < 10|units.yr: stars.Mwind += stars.dmdt*dt new_sph = new_sph_particles_from_stellar_wind(stars, mgas) if len(new_sph) > 0: bodies.add_particles(new_sph) bodies.synchronize_to(hydro.gas_particles) print("time=", hydro.model_time, "Ngas=", len(bodies), mgas*len(bodies)) if len(bodies) > 100: hydro.evolve_model(hydro.model_time+dt) hydro_to_framework.copy() if istep%10 == 0: write_set_to_file(moving_bodies, filename, 'hdf5') istep += 1 hydro.stop() if __name__ in ('__main__', '__plot__'): main()
3,878
34.587156
80
py
amuse
amuse-main/examples/textbook/plot_Nbody_performance.py
import sys, os import numpy import math from matplotlib import pyplot from amuse.plot import scatter, xlabel, ylabel from amuse.lab import * from amuse.io import store from optparse import OptionParser from prepare_figure import single_frame, figure_frame, set_tickmarks from distinct_colours import get_distinct black = '#000000' green = '#00FF00' red = '#FF0000' blue = '#0000FF' lbl = '#FF00FF' magenta = '#00FFFF' Integrator = ["Hermite", "MI6", "ph4", "Huayno", "ph4_GPU", "Gadget2", "BHTree", "Fi_3", "Bonsai"] color = ['r', 'g', 'k', 'b', 'k', lbl, 'm', 'r', 'g', 'b', 'k', 'm'] color = get_distinct(len(color)) lstyles = ['-.', '-.', '-.', '-.', '--', '-', '-', '-', '-'] lwidth = [2, 2, 4, 2, 4, 2, 2, 2, 4] def read_file(filename, column, keyword): x = [] fptr = open(filename) lines = fptr.readlines() for line in lines: l = line.split() if l[1]==keyword: # print line x.append(float(line.split()[column])) fptr.close() return x def main(filename=None, lim=-1): if filename is None: return try: amusedir = os.environ['AMUSE_DIR'] dir = amusedir+'/examples/textbook/' except: print('Environment variable AMUSE_DIR not set') dir = './' filename = dir+filename from matplotlib import pyplot, rc x_label = "N" y_label = "$t_{wall} [s]$" figure = single_frame(x_label, y_label, logx=True, logy=True, xsize=14, ysize=10) npp = [12, 512] ntc = [1024, 2000*1024] tpp = [0.01*x*x for x in npp] ttc = [1.e-6*(x*math.log(x)) for x in ntc] pyplot.plot(npp, tpp, c='k', ls='-', lw=4) pyplot.plot(ntc, ttc, c='k', ls='-', lw=4) pyplot.text(12, 8, '$N^2$') pyplot.text(2.e+3, 0.005, '$N \log (N)$') for ii, I in enumerate(Integrator): # sample line: I= Hermite T= 1 time N= 4 M= 1.0 mass \ # E= -0.250000002735 mass * length**2 * time**-2 \ # Q= -0.451489790632 dE= -1.09402279371e-08 \ # Time= 2.04415297508 0.000992059707642 x = read_file(filename, 6, I) y1 = read_file(filename, 22, I) y2 = read_file(filename, 23, I) for i in range(len(y1)): y1[i] *= 0.1 y2[i] *= 0.1 if len(x) > 0: pyplot.plot(x, y2, label=I, c=color[ii], lw=lwidth[ii], ls=lstyles[ii]) pyplot.scatter(x, y2, c=color[ii], lw=0, s=200) pyplot.legend(loc="lower right", fontsize=18) save_file = "Nbody_performance.png" pyplot.savefig(save_file) print("\nSaved figure in file", save_file,'\n') pyplot.show() def new_option_parser(): result = OptionParser() result.add_option("-f", dest="filename", default='NbodyAMUSE.test', help="output filename [NbodyAMUSE.test]") result.add_option("-l", dest="lim", type="float", default = -1, help="boxsize") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
3,095
29.058252
71
py
amuse
amuse-main/examples/textbook/plot_density_distributions.py
import numpy from amuse.lab import * from optparse import OptionParser from matplotlib import pyplot from amuse.plot import scatter, xlabel, ylabel from amuse.community.fractalcluster.interface import new_fractal_cluster_model from prepare_figure import figure_frame, quad_frame, single_frame from distinct_colours import get_distinct def plot_projected_density(model, xmin=-1, xmax=1, col=0): pyplot.xlim(xmin, xmax) pyplot.ylim(xmin, xmax) cols = get_distinct(4) pyplot.scatter(model.x.value_in(nbody_system.length), model.z.value_in(nbody_system.length), c=cols[col], s=80, lw=0) def plummer_model(N, x_label = 'x [length]', y_label='y [length]'): fig = single_frame(x_label, y_label, xsize=8, ysize=8) model = new_plummer_model(N) plot_projected_density(model, col=0) file = "plummer_model.png" pyplot.savefig(file) print('Saved figure in file', file) def king_model(N, W=9, x_label = 'x [length]', y_label='y [length]'): fig = single_frame(x_label, y_label, xsize=8, ysize=8) ax = pyplot.gca() model = new_king_model(N, W) plot_projected_density(model, col=1) file = "king_model.png" pyplot.savefig(file) print('Saved figure in file', file) def hierarchical_king_model(N, W=9, x_label = 'x [length]', y_label='y [length]'): fig = single_frame(x_label, y_label, xsize=8, ysize=8) ax = pyplot.gca() model_com = new_king_model(6, W/3.) for i in range(6): model = new_king_model(int(N/4.), W) model.position += model_com[i].position plot_projected_density(model, col=1) file = "hierarchical_king_model.png" pyplot.savefig(file) print('Saved figure in file', file) def fractal_model(N, F=1.6, x_label = 'x [length]', y_label='y [length]'): fig = single_frame(x_label, y_label, xsize=8, ysize=8) ax = pyplot.gca() model = new_fractal_cluster_model(N=N, fractal_dimension=1.6, random_seed=42) plot_projected_density(model, col=2) file = "fractal_model.png" pyplot.savefig(file) print('Saved figure in file', file) def galaxy_model(N, x_label = 'x [length]', y_label='y [length]'): fig = single_frame(x_label, y_label, xsize=8, ysize=8) ax = pyplot.gca() model = new_halogen_model(N, alpha=1., beta=5., gamma=0.5) plot_projected_density(model, col=3) file = "galaxy_model.png" pyplot.savefig(file) print('Saved figure in file', file) def main(N=10): numpy.random.seed(42) print('') plummer_model(N) king_model(N) fractal_model(N) galaxy_model(N) hierarchical_king_model(N) print('') def new_option_parser(): result = OptionParser() result.add_option("-N", dest="N", type="int",default = 1000, help="number of stars [1000]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
2,986
33.333333
82
py
amuse
amuse-main/examples/textbook/plot_plummer.py
""" Example AMUSE script to generate a Plummer sphere and plot the results. """ ###BOOKLISTSTART### from matplotlib.pyplot import show, xlim, ylim, figure from amuse.plot import scatter, xlabel, ylabel from amuse.lab import new_plummer_model 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() ###BOOKLISTSTOP### def new_option_parser(): from optparse import OptionParser result = OptionParser() result.add_option("-N", dest="N", type="int", default=1000, help="number of stars [1000]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
801
24.0625
74
py
amuse
amuse-main/examples/textbook/gravity_kepler_disks.py
from amuse.lab import * #from amuse.io import store #from amuse.community.seba.interface import SeBa from amuse.ext.orbital_elements import orbital_elements_from_binary from amuse.community.fractalcluster.interface import new_fractal_cluster_model ###BOOKLISTSTART3### def resolve_close_encounter(time, bodies): orbital_elements = orbital_elements_from_binary(bodies, G=constants.G) a = orbital_elements[2] e = orbital_elements[3] p = a*(1-e) print("Close encounter at t=", time.in_(units.Myr), \ "a=", a.in_(units.AU), "e=", e, "p=", p.in_(units.AU), \ "M=", bodies.mass.max().in_(units.MSun), \ bodies.mass.min().in_(units.MSun)) truncate_disks_due_to_encounter(bodies, p) def truncate_disks_due_to_encounter(bodies, p): q = bodies[1].mass/bodies[0].mass rtr_prim = 0.28*p / q**(0.32) rtr_sec = 0.28*p * q**(0.32) dm0 = truncate_disk_due_to_encounter(bodies[0], rtr_prim) dm1 = truncate_disk_due_to_encounter(bodies[1], rtr_sec) mtot = bodies.mass.sum() bodies[0].accreted_mass += dm1 * bodies[0].mass/mtot bodies[1].accreted_mass += dm0 * bodies[1].mass/mtot bodies[0].radius = min(bodies[0].radius, 0.5*p) bodies[1].radius = min(bodies[1].radius, 0.5*p) bodies[0].mass = bodies[0].stellar_mass + bodies[0].disk_mass \ + bodies[0].accreted_mass bodies[1].mass = bodies[1].stellar_mass + bodies[1].disk_mass \ + bodies[1].accreted_mass ###BOOKLISTSTOP3### def stripped_disk_mass(body, dr): rold = body.disk_radius rnew = rold - dr dm = body.disk_mass * (rold**0.5-rnew**0.5)/rold**0.5 return max(0|units.MSun, dm) def truncate_disk_due_to_encounter(body, r_tr): dr = max(0|units.AU, body.disk_radius-r_tr) dm = stripped_disk_mass(body, dr) body.disk_radius -= dr body.disk_mass -= dm return dm ###BOOKLISTSTART2### def evolve_system_to(time, gravity, bodies, stopping_condition, channel_from_gravity, channel_to_gravity, energy_tolerance = 1.e-10 | units.erg): gravity.evolve_model(time) while stopping_condition.is_set(): channel_from_gravity.copy() Ek_enc = gravity.kinetic_energy Ep_enc = gravity.potential_energy for ci in range(len(stopping_condition.particles(0))): bodies_in_enc \ = Particles(particles=[stopping_condition.particles(0)[ci], stopping_condition.particles(1)[ci]]) local_bodies_in_enc \ = bodies_in_enc.get_intersecting_subset_in(bodies) resolve_close_encounter(gravity.model_time, local_bodies_in_enc) print("At time=", gravity.model_time.value_in(units.Myr), \ "Rdisk=", local_bodies_in_enc.disk_radius.in_(units.AU)) channel_to_gravity.copy_attributes(["radius"]) assert abs(Ek_enc - gravity.kinetic_energy) < energy_tolerance assert abs(Ep_enc - gravity.potential_energy) < energy_tolerance gravity.evolve_model(time) channel_to_gravity.copy_attributes(["mass"]) ###BOOKLISTSTOP2### ###BOOKLISTSTART1### def main(N, Rvir, Qvir, Fd, t_end, filename): masses = new_kroupa_mass_distribution(N, 100|units.MSun) converter=nbody_system.nbody_to_si(masses.sum(),Rvir) bodies = new_fractal_cluster_model(N=N, fractal_dimension=Fd, convert_nbody=converter) bodies.scale_to_standard(converter, virial_ratio=Qvir) bodies.stellar_mass = masses bodies.disk_mass = 0.01*bodies.stellar_mass bodies.mass = bodies.stellar_mass + bodies.disk_mass bodies.accreted_mass = 0 | units.MSun bodies.disk_radius = 400 | units.AU bodies.radius = 10 * bodies.disk_radius gravity = ph4(converter, number_of_workers=2) gravity.parameters.epsilon_squared = (100|units.AU)**2 gravity.particles.add_particles(bodies) channel_from_gravity = gravity.particles.new_channel_to(bodies) channel_to_gravity = bodies.new_channel_to(gravity.particles) stopping_condition = gravity.stopping_conditions.collision_detection stopping_condition.enable() write_set_to_file(bodies.savepoint(0|units.Myr), filename, 'hdf5', append_to_file=False) Etot_init = gravity.kinetic_energy + gravity.potential_energy Etot_prev = Etot_init ###BOOKLISTSTOP1### ###BOOKLISTSTART0### dt = t_end/10. time = 0 | units.yr while gravity.model_time < t_end: time += dt evolve_system_to(time, gravity, bodies, stopping_condition, channel_from_gravity, channel_to_gravity) write_set_to_file(bodies.savepoint(gravity.model_time), filename, 'hdf5') Etot = gravity.kinetic_energy + gravity.potential_energy print("T=", gravity.model_time, end=' ') print("E= ", Etot, "Q= ", \ gravity.kinetic_energy/gravity.potential_energy) print("dE=", (Etot-Etot_init)/Etot, "ddE=", (Etot-Etot_prev)/Etot) Etot_init -= (Etot_prev-Etot) Etot_prev = Etot gravity.stop() ###BOOKLISTSTOP0### def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-N", dest="N", type="int",default = 2000, help="number of stars [%default]") result.add_option("-R", dest="Rvir", type="float", unit=units.parsec, default = 0.5|units.parsec, help="cluser virial radius [%default]") result.add_option("-Q", dest="Qvir", type="float",default = 0.5, help="virial ratio [%default]") result.add_option("-F", dest="Fd", type="float",default = 1.6, help="fractal dimension [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() t_end = 1|units.Myr filename= 'Cl_N%g_R%gpc_Q%g_F%g.h5' \ % (o.N, o.Rvir.value_in(units.parsec), o.Qvir, o.Fd) main(o.N, o.Rvir, o.Qvir, o.Fd, t_end, filename)
6,183
39.684211
78
py
amuse
amuse-main/examples/textbook/gravity_to_virial.py
""" Simple routine for running a gravity code """ from amuse.lab import * from matplotlib import pyplot from prepare_figure import single_frame, figure_frame, set_tickmarks from distinct_colours import get_distinct def virial_ratio_evolution(code, bodies, Q_init, t_end): dt = 0.06125 | t_end.unit bodies.scale_to_standard(virial_ratio=Q_init) bodies.radius = 0 | nbody_system.length gravity = code() gravity.particles.add_particles(bodies) channel_from_gravity_to_framework = gravity.particles.new_channel_to(bodies) Etot_prev = Etot_init = gravity.kinetic_energy + gravity.potential_energy time = [0.0] | t_end.unit Q = [Q_init] while time[-1] < t_end: time.append(time[-1]+dt) gravity.evolve_model(time[-1]) channel_from_gravity_to_framework.copy() Ekin = gravity.kinetic_energy Epot = gravity.potential_energy Etot = Ekin + Epot Q.append(-1*Ekin/Epot) print("T=", time[-1], "Q= ", Q[-1], end=' ') print("M=", bodies.mass.sum(), "E= ", Etot, end=' ') print("dE=", (Etot_init-Etot)/Etot, "ddE=", (Etot_prev-Etot)/Etot) Etot_prev = Etot gravity.stop() return time, Q def main(N, t_end): t_end = t_end | nbody_system.time Q_init = 0.2 particles = new_plummer_model(N) codes = [ph4, Huayno, BHTree] cols = get_distinct(3) ci = 0 x_label = "time [N-body units]" y_label = "virial ratio $Q$" figure = single_frame(x_label, y_label, xsize=14, ysize=10) ax1 = pyplot.gca() ax1.set_xlim(0, t_end.value_in(t_end.unit)) ax1.set_ylim(0, 0.65) pyplot.plot([0, t_end.value_in(t_end.unit)], [0.5, 0.5], lw=1, ls='--', c='k') for code in codes: time, Q = virial_ratio_evolution(code, particles, Q_init, t_end) pyplot.plot(time.value_in(t_end.unit), Q, c=cols[ci]) ci+=1 save_file = 'gravity_to_virial.png' pyplot.savefig(save_file) print("\nOutput saved in", save_file, '\n') pyplot.show() def new_option_parser(): from optparse import OptionParser result = OptionParser() result.add_option("-N", dest="N", type="int",default = 1000, help="number of stars [10]") result.add_option("-t", dest="t_end", type="float", default = 2, help="end time of the simulation [1] N-body units") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
2,527
33.162162
80
py
amuse
amuse-main/examples/textbook/star_to_hydro.py
from amuse.units import units from amuse.community.evtwin.interface import EVtwin from amuse.ext.star_to_sph import convert_stellar_model_to_SPH from amuse.datamodel import Particle def convert_star_to_hydro_model(M, t_end): stellar_evolution = EVtwin() star = stellar_evolution.particles.add_particle(Particle(mass=M)) stellar_evolution.evolve_model(t_end) Ngas = 10000 sph_particles = convert_stellar_model_to_SPH(star, Ngas).gas_particles stellar_evolution.stop() return sph_particles if __name__ in ("__main__", "__plot__"): from amuse.plot import sph_particles_plot, native_plot sph_particles = convert_star_to_hydro_model(2.0|units.MSun, 110|units.Myr) native_plot.figure(figsize = (10, 10), dpi = 50) sph_particles_plot(sph_particles) native_plot.show()
811
37.666667
78
py
amuse
amuse-main/examples/textbook/rad_minimal.py
import numpy from amuse.lab import * from amuse.ic.gasplummer import new_plummer_gas_model from prepare_figure import single_frame, figure_frame from distinct_colours import get_distinct def binned_mean_data(r, x): R = numpy.arange(0, r[-1], 0.1) X = numpy.zeros(len(R)) N = numpy.zeros(len(R)) for i in range(len(R)-1): for j in range(len(r)): if r[j]>=R[i] and r[j]<=R[i+1]: X[i] += x[j] N[i] += 1. for i in range(len(X)): if X[i]>0 and N[i]>0: X[i] = X[i]/float(N[i]) return R, X def plot_ionization_fraction(pos, xion): r = [] | units.parsec x = [] for pi, xi in zip(pos, xion): r.append(pi.length()) x.append(xi) r, x = list(zip(*sorted(zip(r.value_in(units.parsec), x)))) R, X = binned_mean_data(r, x) from matplotlib import pyplot x_label = "r [pc]" y_label = r'$\xi_{\rm ion}$' figure = single_frame(x_label, y_label, logx=False, logy=False, xsize=14, ysize=8) pyplot.scatter(r, x, c=get_distinct(1), lw=0, s=100) pyplot.plot(R, X, c=get_distinct(2)[1], lw=2) pyplot.xlim(0, 6) pyplot.ylim(-0.04, 1.19) pyplot.savefig("fig_ionization_of_GMC") pyplot.show() ###BOOKLISTSTART1### def generate_ism_initial_conditions(N, boxsize): converter = nbody_system.nbody_to_si(10|units.MSun, 3|units.parsec) ism = new_plummer_gas_model(N, converter) ism.flux = 0. | units.s**-1 ism.xion = 0.0 hydro = Fi(converter) hydro.gas_particles.add_particles(ism) hydro.evolve_model(1|units.hour) hydro.gas_particles.new_channel_to(ism).copy() hydro.stop() ism = ism.select(lambda r: r.length() < 0.5*boxsize,["position"]) print("Max density:", ism.rho.max().in_(units.MSun/units.parsec**3), \ ism.rho.max().in_(units.amu/units.cm**3)) return ism ###BOOKLISTSTOP1### ###BOOKLISTSTART### def main(N, Lstar, boxsize, t_end): ism = generate_ism_initial_conditions(N, boxsize) source = Particle() source.position = (0, 0, 0) |units.parsec source.flux = Lstar/(20. | units.eV) source.rho = ism.rho.max() source.xion = ism.xion.max() source.u = (9.|units.kms)**2 radiative = SimpleX() radiative.parameters.box_size = boxsize radiative.particles.add_particle(source) radiative.particles.add_particles(ism) radiative.evolve_model(t_end) print("min ionization:", radiative.particles.xion.min()) print("average ionization:", radiative.particles.xion.mean()) print("max ionization:", radiative.particles.xion.max()) plot_ionization_fraction(radiative.particles.position, radiative.particles.xion) radiative.stop() ###BOOKLISTSTOP### def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-N", dest="N", type="int", default = 10000, help="number of gas particles [%default]") result.add_option("-t", unit=units.Myr, type="float", dest="t_end", default = 1.0|units.Myr, help="radiation time [%default]") result.add_option("-L", unit=units.LSun, type="float", dest="Lstar", default = 100|units.LSun, help="luminosity of ionizing source [%default]") result.add_option("-d", unit=units.parsec, dest="boxsize", default = 10|units.parsec, help="size of the density box [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() numpy.random.seed(12345) main(**o.__dict__)
3,770
32.972973
74
py
amuse
amuse-main/examples/textbook/relax_gas_and_stars.py
import numpy import pickle from amuse.lab import * from amuse.community.fastkick.interface import FastKick from amuse.ext.relax_sph import relax from amuse.ext.spherical_model import new_gas_plummer_distribution from amuse.community.fractalcluster.interface import new_fractal_cluster_model ###BOOKLISTSTART1### def check_energy_conservation(system, i_step, time, n_steps): unit = units.J U = system.potential_energy.value_in(unit) Q = system.thermal_energy.value_in(unit) K = system.kinetic_energy.value_in(unit) print("Step {0} of {1}, t={2}: U={3:.2e}, Q={4:.2e}, K={5:.2e} {5}" \ .format(i_step, n_steps, time.as_quantity_in(units.yr), U, Q, K, unit)) ###BOOKLISTSTOP1### from amuse.couple.bridge import Bridge def local_relax(gas_particles, hydro, gravity_field=None, monitor_func=check_energy_conservation, bridge_options=dict()): """ Relax a set of SPH particles by evolving it with a hydrodynamics code, while imposing critical damping on the particle velocities. :argument gas_particles: The set of SPH particles :argument hydro: The hydrodynamics code :argument gravity_field Background gravitational field, must support get_gravity_at_point :argument monitor_func For monitoring progress each step. User-defined function or "energy" :argument bridge_options: Keyword options passed to Bridge """ if monitor_func == "energy": monitor_func = monitor_energy t_end_in_t_dyn = 0.1 # Relax for this many dynamical timescales t_end = t_end_in_t_dyn \ * gas_particles.dynamical_timescale(mass_fraction=0.9) n_steps = 10 velocity_damp_factor = 1.0 - (2.0*numpy.pi*t_end_in_t_dyn) \ /n_steps # Critical damping in_hydro = hydro.gas_particles.add_particles(gas_particles) if gravity_field is None: system = hydro else: system = Bridge(timestep=(t_end/n_steps).as_quantity_in(units.yr), **bridge_options) system.add_system(hydro, [gravity_field]) for i_step, time in enumerate(t_end * numpy.linspace(1.0/n_steps, 1.0, n_steps)): system.evolve_model(time) hydro.gas_particles.velocity = velocity_damp_factor \ * hydro.gas_particles.velocity monitor_func(system, i_step, time, n_steps) return in_hydro.copy() ###BOOKLISTSTART2### def relax_gas_and_stars(stars, gas): dynamical_timescale = gas.dynamical_timescale() converter = nbody_system.nbody_to_si(dynamical_timescale, 1|units.parsec) hydro = Fi(converter, mode='openmp', redirection="file", redirect_file="fi.log") hydro.parameters.timestep = dynamical_timescale / 100 hydro.parameters.eps_is_h_flag = True gravity_field_code = FastKick(converter, mode="cpu", number_of_workers=2) gravity_field_code.parameters.epsilon_squared = (0.01 | units.parsec)**2 gravity_field_code.particles.add_particles(stars) relaxed_gas = relax(gas, hydro, gravity_field=gravity_field_code, monitor_func=check_energy_conservation, bridge_options=dict(verbose=True, use_threading=False)) gravity_field_code.stop() return hydro ###BOOKLISTSTOP2### def generate_initial_conditions( number_of_stars = 100, number_of_gas_particles = 10**5, star_formation_efficiency = 0.1, virial_radius = 0.33 | units.parsec, virial_ratio = 1.0, use_fractal = False): numpy.random.seed(12345678) seed_fractal = 312357271 masses = new_salpeter_mass_distribution(number_of_stars, mass_min=1|units.MSun) # masses = new_kroupa_mass_distribution(number_of_stars total_stellar_mass = masses.sum() total_mass = total_stellar_mass / star_formation_efficiency converter = nbody_system.nbody_to_si(total_mass, virial_radius) if use_fractal: stars = new_fractal_cluster_model(number_of_stars, convert_nbody=converter, do_scale=False, fractal_dimension=1.6, random_seed=seed_fractal) else: stars = new_plummer_model(number_of_stars, convert_nbody=converter, do_scale=False) stars.mass = masses stars.move_to_center() print("scaling positions to match virial_radius") stars.position *= virial_radius / stars.virial_radius() print("scaling velocities to match virial_ratio") stars.velocity *= numpy.sqrt(virial_ratio * converter.to_si(0.5|nbody_system.energy) * star_formation_efficiency / stars.kinetic_energy()) print("new_gas_plummer_distribution") gas = new_gas_plummer_distribution( number_of_gas_particles, total_mass = (total_mass - total_stellar_mass), virial_radius = virial_radius, type = "fcc") gas.h_smooth = 0.0 | units.parsec # eat away gas. mgas = gas[0].mass print("Ngas=", len(gas)) for si in stars: m = si.mass nremoved = 0 while m>mgas: gi = si.as_set().nearest_neighbour(gas) nremoved += 1 m-= gi.mass gas -= gi print("removed:", nremoved, si.mass.in_(units.MSun)) print("Ngas=", len(gas)) filename = "YSC_{0}_stars{1}_gas{2}k_" \ .format("fractal" if use_fractal else "plummer", number_of_stars, number_of_gas_particles/1000) print("Writing initial conditions to", filename, "+ stars/gas.amuse") write_set_to_file(stars, filename+"stars.amuse", "amuse", append_to_file=False) write_set_to_file(gas, filename+"gas.amuse", "amuse", append_to_file=False) with open(filename+"info.pkl", "wb") as outfile: pickle.dump([converter], outfile) return stars, gas, filename def make_map(sph,N=100,L=1): x,y=numpy.indices( ( N+1,N+1 )) x=L*(x.flatten()-N/2.)/N y=L*(y.flatten()-N/2.)/N z=x*0. vx=0.*x vy=0.*x vz=0.*x x=units.parsec(x) y=units.parsec(y) z=units.parsec(z) vx=units.kms(vx) vy=units.kms(vy) vz=units.kms(vz) rho,rhovx,rhovy,rhovz,rhoe=sph.get_hydro_state_at_point(x,y,z,vx,vy,vz) rho=rho.reshape((N+1,N+1)) return rho def plot_hydro_and_stars(hydro, stars): x_label = "x [pc]" y_label = "y [pc]" from prepare_figure import * fig = single_frame(x_label, y_label, logx=False, logy=False, xsize=12, ysize=12) L = 6 rho=make_map(hydro,N=200,L=L) cax = pyplot.imshow(numpy.log10(1.e-5+rho.value_in(units.amu/units.cm**3)), extent=[-L/2,L/2,-L/2,L/2],vmin=1,vmax=5, origin="lower") cbar = fig.colorbar(cax, orientation='vertical', fraction=0.045) cbar.set_ticks([1.0, 1.5, 2.0, 4.0, 4.5, 5.0]) cbar.set_label('$\log_{10} (\mathrm{n}) \,\,\, [\mathrm{amu/cm}^3]$', rotation=270) cm = pyplot.cm.get_cmap('RdBu') m = 50*numpy.log10(stars.mass/stars.mass.min()) c = numpy.sqrt(stars.mass/stars.mass.max()) pyplot.scatter(-stars.x.value_in(units.parsec), -stars.y.value_in(units.parsec), c=c, s=m, lw=0, cmap=cm) save_file = 'plot_relaxed_gas_and_star.png' pyplot.savefig(save_file) print('\nSaved figure in file', save_file,'\n') pyplot.show() if __name__ == "__main__": stars, gas, filename = generate_initial_conditions() hydro = relax_gas_and_stars(stars, gas) plot_hydro_and_stars(hydro, stars) hydro.stop()
7,874
38.375
142
py
amuse
amuse-main/examples/textbook/cooling_class.py
import numpy from amuse.units import units,constants from amuse.units.quantities import zero # Pelupessy et al. (in prep.) simple thermal model class SimplifiedThermalModel(object): def __init__(self, n0=0.05 | units.cm**-3, T0=1.e4 | units.K, Tmin=20 | units.K, alpha=5., reference_heating=1.e-25 | units.erg/units.s): self.reference_mu=(2.2 | units.amu) self.rho0=n0*self.reference_mu self.T0=T0 self.Tmin=Tmin self.alpha=alpha self.reference_heating=reference_heating def equilibrium_temperature(self,rho): xclip=(rho/self.rho0) return self.Tmin+ (self.T0-self.Tmin)/(1.+numpy.log10(1.+9*xclip)**self.alpha) def mu(self,rho=None): if rho is None: return self.reference_mu else: return numpy.ones(numpy.shape(rho))*self.reference_mu def gamma(self,rho): return numpy.ones(numpy.shape(rho))*(self.reference_heating) def u_from_T(self,T): return constants.kB*T/self.mu() def T_from_u(self,u): return u/constants.kB*self.mu() def equilibrium_u(self,rho): return constants.kB*self.equilibrium_temperature(rho)/self.mu(rho) def tau(self,rho): return (constants.kB*self.equilibrium_temperature(rho)/self.gamma(rho)) def evolve_u(self,dt,rho,u0,dudt=None): u_eq=self.equilibrium_u(rho) tau=self.tau(rho) if dudt is not None: condition1= 1.*(dudt*tau < (u0-u_eq)) condition2= 1.-condition1 fac=1./numpy.maximum(1-dudt/u0*tau ,1.e-5) u_eq=(u_eq*fac)*condition1+(u_eq+dudt*tau)*condition2 tau=(tau*fac)*condition1+tau*condition2 return u_eq+(u0-u_eq)*numpy.exp(-dt/tau) def evolve_u_radiated_energy(self,dt,rho,u0,dudt=None): u_eq0=self.equilibrium_u(rho) tau0=self.tau(rho) u_eq=u_eq0 tau=tau0 if dudt is not None: condition1= 1.*(dudt*tau < (u0-u_eq)) condition2= 1.-condition1 fac=1./numpy.maximum(1-dudt/u0*tau ,1.e-5) u_eq=(u_eq*fac)*condition1+(u_eq+dudt*tau)*condition2 tau = (tau*fac)*condition1+tau*condition2 u1=u_eq+(u0-u_eq)*numpy.exp(-dt/tau) rad=(u_eq-u_eq0)*dt/tau0+(u0-u_eq)*tau/tau0*(1-numpy.exp(-dt/tau)) return u1,rad # rad>0 -> cooling # rad<0 -> heating class SimplifiedThermalModelEvolver(SimplifiedThermalModel): def __init__(self,particles,**kwargs): self.particles=particles SimplifiedThermalModel.__init__(self,**kwargs) self.radiated_energy=zero self.total_luminosity=zero self.model_time=zero self.umin=self.u_from_T(1. | units.K) def evolve_for(self, dt): #print " Do NOT Cool!" #return if dt>0*dt: rho=self.particles.rho u=self.particles.u du_dt=self.particles.du_dt new_u, lum= self.evolve_u_radiated_energy( dt, rho, u, du_dt ) self.radiated_energy+=(lum*self.particles.mass).sum()/dt self.total_luminosity=(lum*self.particles.mass).sum() a=numpy.where(new_u<self.umin)[0] new_u[a]=self.umin self.particles.u = new_u # debug lines nrho=numpy.isnan(rho.number).sum() nu=numpy.isnan(u.number).sum() ndu=numpy.isnan(du_dt.number).sum() nnu=numpy.isnan(new_u.number).sum() if nrho+nu+ndu+nnu>0: print("nan detected in thermal evolution") print(nrho,nu,ndu,nnu) import pickle with open("cooling_dump","w") as f: pickle.dump((dt,rho,u,du_dt,new_u),f) raise Exception("NaNs in thermal evolution") def evolve_model(self,tend): self.evolve_for(tend-self.model_time) self.model_time=tend # COOLING class Cooling(object): def __init__(self, particles): self.particles = particles self.umin=self.u_from_T( 10. | units.K) self.umax=self.u_from_T( 1.e6 | units.K) def evolve_for(self, dt): #print " Do NOT Cool!" #return if dt>0*dt: new_u=self.evolve_internal_energy(self.particles.u, dt,self.particles.rho/self.mu(),self.particles.du_dt) a=numpy.where(new_u<self.umin)[0] new_u[a]=self.umin a=numpy.where(new_u>self.umax)[0] new_u[a]=self.umax self.particles.u = new_u def evolve_internal_energy(self, u_0, dt, n_H, du_dt_adiabatic = zero): function = lambda u: ((self.gerritsen_heating_function() - n_H * self.my_cooling_function(self.T_from_u(u))) / self.mu())#du_dt_adiabatic * u/u_0 + u_out = self.integrate_ode(function, u_0, dt) return u_out def integrate_ode(self,function, x, t_end, eps = 0.01): """ Integrates the given ordinary differential equation of the form: dx/dt = function(x) for a time 't_end', using the initial value 'x'. The routine takes small steps, such that (abs(dx) <= eps * x) """ t = 0 * t_end while t < t_end: fx = function(x) dtinv=(abs(fx)/(eps*x)).amax() step=t_end-t if dtinv!=0*dtinv : step = min( step, 1./dtinv ) t += step x += fx * step return x # Transforming from T to U def u_from_T(self, T): return 3.0/2.0 * constants.kB * T / self.mu() # Transforming from U to T def T_from_u(self, u): return 2.0/3.0 * u * self.mu() / constants.kB # Molecular weight def mu(self, X = None, Y = 0.25, Z = 0.02, x_ion = 0.1): """ Compute the mean molecular weight in kg (the average weight of particles in a gas) X, Y, and Z are the mass fractions of Hydrogen, of Helium, and of metals, respectively. x_ion is the ionisation fraction (0 < x_ion < 1), 1 means fully ionised """ if X is None: X = 1.0 - Y - Z elif abs(X + Y + Z - 1.0) > 1e-6: raise Exception("Error in calculating mu: mass fractions do not sum to 1.0") return constants.proton_mass / (X*(1.0+x_ion) + Y*(1.0+2.0*x_ion)/4.0 + Z*x_ion/2.0) # G depends on nearby sources, see 1997A&A...325..972G def gerritsen_heating_function(self, G_0 = 10, eps = 0.05): return 10.0**-24 * eps * G_0 | units.erg / units.s def gerritsen_cooling_function(self, T, logT = None, a = 3.24, b = 0.170): # x=1e-1 if logT is None: logT = numpy.log10(T.value_in(units.K)) condlist = [logT <= 6.2, logT >= 6.2] choicelist = [10.0**-21.0 * (10**(-0.1-1.88*(5.23-logT)**4) + 10**(-a-b*(4-logT)**2)), 10.0**-22.7] return (units.erg*units.cm**3/units.s).new_quantity(numpy.select(condlist, choicelist)) def my_cooling_function(self, T, logT = None, a = 3.24, b = 0.170): # x=1e-1 if logT is None: logT = numpy.log10(T.value_in(units.K)) condlist = [logT <= 6.2, logT >= 6.2] choicelist = [10.0**-21.0 * (10**(-0.1-1.88*(5.23-logT)**4) + 10**(-a-b*abs(4-logT)**3)), 10.0**-22.7] return (units.erg*units.cm**3/units.s).new_quantity(numpy.select(condlist, choicelist))
7,950
40.847368
164
py
amuse
amuse-main/examples/textbook/hydrodynamics_class.py
import time import numpy from amuse.lab import * from amuse.units import units, nbody_system, constants from amuse.datamodel import Particles from amuse.community.fi.interface import Fi from amuse.community.gadget2.interface import Gadget2 from cooling_class import Cooling, SimplifiedThermalModelEvolver # from amuse.ext.sink import SinkParticles from amuse.ext.sink import new_sink_particles # COOL = False COOL = True class Hydro: def __init__(self, hydro_code, particles, stars): if hydro_code not in [Fi, Gadget2]: raise Exception("unsupported Hydro code: %s" % (hydro_code.__name__)) self.typestr = "Hydro" self.namestr = hydro_code.__name__ system_size = 2 | units.parsec """ rho_mean = (1000|units.MSun)/(4./3*numpy.pi*(3|units.parsec)**3) print particles rhoh3=(6/numpy.pi*particles.mass[0]).in_(units.MSun) print "rhoh3 (approx mass res):", rhoh3 #rhomax = particles.density.max() rhomax = 100*rho_mean eps = (rhoh3/rhomax)**(1./3) print "eps=", eps.in_(units.parsec), "old Eps=", 0.05, "pc" """ eps = 0.05 | units.parsec Mcloud = particles.mass.sum() N = len(particles) dt = 0.004*numpy.pi*numpy.power(eps, 1.5)/numpy.sqrt(constants.G*Mcloud/N) print("Hydro timesteps:", dt, "N=", len(particles)) self.gas_particles = particles self.star_particles = stars self.cooling_flag = "thermal_model" self.density_threshold = (1 | units.MSun)/(eps)**3 self.merge_radius = 0.2*eps self.converter = nbody_system.nbody_to_si(1 | units.MSun, system_size) self.star_attributes = ['name', 'birth_age', 'angular_momentum', 'mass', 'radius', 'x', 'y', 'z', 'vx', 'vy', 'vz', 'Lx', 'Ly', 'Lz'] if hydro_code is Fi: self.code = hydro_code(self.converter, mode="openmp", redirection="file") self.code.parameters.begin_time = 0.0 | units.Myr self.code.parameters.use_hydro_flag = True self.code.parameters.self_gravity_flag = True self.code.parameters.periodic_box_size = 100.*system_size """ isothermal_flag: When True then we have to do our own adiabatic cooling (and Gamma has to be 1.0) When False then we dont do the adjabatic cooling and Fi is changing u """ self.code.parameters.isothermal_flag = True self.code.parameters.integrate_entropy_flag = False self.code.parameters.timestep = 0.5*dt # self.code.parameters.verbosity=99 self.code.parameters.verbosity = 0 self.code.parameters.gamma = 1 self.code.parameters.integrate_entropy_flag = False self.gamma = self.code.parameters.gamma if hydro_code is Gadget2: print("WARNING: Gadget support is WIP") print("check the Gadget2 makefile_options") # todo: variable number_of_workers self.code = hydro_code(self.converter, number_of_workers=4) self.code.parameters.begin_time = 0.0 | units.Myr self.code.parameters.time_max = dt*2**int(numpy.log2(4*(10 | units.Myr)/dt)) self.code.parameters.max_size_timestep = 0.5*dt # ~ self.code.parameters.min_size_timestep= print("Isofag;", self.code.parameters.isothermal_flag) print("gamma=", self.code.parameters.polytropic_index_gamma) # assert self.code.parameters.isothermal_flag == True assert self.code.parameters.no_gravity_flag is False # constant gas smoothing self.code.parameters.gas_epsilon = eps assert self.code.parameters.eps_is_h_flag is False # assert self.code.parameters.polytropic_index_gamma == 1. if self.cooling_flag == "internal": raise Exception("gadget internal cooling not implemented") self.gamma = self.code.parameters.polytropic_index_gamma self.code.parameters.stopping_condition_maximum_density = self.density_threshold self.code.commit_parameters() if len(self.gas_particles) > 0: self.code.gas_particles.add_particles(self.gas_particles) if len(self.star_particles) > 0: self.code.dm_particles.add_particles(self.star_particles) self.parameters = self.code.parameters print(self.code.parameters) # In order to be using the bridge self.get_gravity_at_point = self.code.get_gravity_at_point self.get_potential_at_point = self.code.get_potential_at_point self.get_hydro_state_at_point = self.code.get_hydro_state_at_point # Create a channel self.channel_to_gas = self.code.gas_particles.new_channel_to(self.gas_particles) self.channel_to_stars = self.code.dm_particles.new_channel_to(self.star_particles) self.channel_from_stars = self.star_particles.new_channel_to(self.code.dm_particles) # External Cooling print("Cooling flag:", self.cooling_flag) self.cooling = SimplifiedThermalModelEvolver(self.code.gas_particles) # self.cooling = Cooling(self.code.gas_particles) self.cooling.model_time = self.code.model_time def print_diagnostics(self): print("Time=", self.code.model_time.in_(units.Myr)) print("N=", len(self.gas_particles), len(self.star_particles)) if len(self.star_particles) > 0: print("Sink masses:", len(self.code.dm_particles.mass)) print("Sink masses:", len(self.star_particles.mass)) def write_set_to_file(self, index): filename = "hydro_molecular_cloud_collapse_i{0:04}.amuse".format(index) write_set_to_file(self.gas_particles, filename, "amuse") if len(self.star_particles): write_set_to_file(self.star_particles, filename, "amuse", append_to_file=True) # , attribute_names=self.star_attributes) @property def model_time(self): return self.code.model_time # @property # def gas_particles(self): # return self.code.gas_particles @property def stop(self): return self.code.stop def evolve_model(self, model_time): start_time = time.time() density_limit_detection = self.code.stopping_conditions.density_limit_detection density_limit_detection.enable() model_time_old = self.code.model_time dt = model_time - model_time_old print("Evolve Hydrodynamics:", dt.in_(units.yr)) if COOL: print("Cool gas for dt=", (dt/2).in_(units.Myr)) self.cooling.evolve_for(dt/2) # print "...done." self.code.evolve_model(model_time) # print "gas evolved." while density_limit_detection.is_set(): self.resolve_sinks() print("..done") self.code.evolve_model(model_time) self.channel_to_stars.copy() print("end N=", len(self.star_particles), len(self.code.dm_particles)) if COOL: print("Cool gas for another dt=", (dt/2).in_(units.Myr)) self.cooling.evolve_for(dt/2) # print "...done." self.merge_stars() if len(self.star_particles) > 0: sinks = new_sink_particles(self.star_particles) sinks.accrete(self.gas_particles) for si in range(len(self.star_particles)): self.star_particles[si].Lx += sinks[si].angular_momentum[0] self.star_particles[si].Ly += sinks[si].angular_momentum[1] self.star_particles[si].Lz += sinks[si].angular_momentum[2] self.gas_particles.synchronize_to(self.code.gas_particles) # make sure that the accreted mass is copied to the Hydro code..+++ self.channel_from_stars.copy() # self.code.evolve_model(model_time) print("final N=", len(self.star_particles), len(self.code.dm_particles)) print("final Ngas=", len(self.gas_particles), len(self.code.gas_particles)) self.channel_to_gas.copy() self.channel_to_stars.copy() print("final N=", len(self.star_particles), len(self.code.dm_particles)) if len(self.star_particles) > 0: print("mean star mass:", self.star_particles.mass.min().in_(units.MSun), self.star_particles.mass.mean().in_(units.MSun), self.star_particles.mass.max().in_(units.MSun)) # ~ print "Hydro arrived at:", self.code.model_time.in_(units.Myr) # print "Accrete from ambied gas" # self.accrete_sinks_from_ambiant_gas() def resolve_sinks(self): print("processing high dens particles...", end=' ') highdens = self.gas_particles.select_array(lambda rho: rho > self.density_threshold,["rho"]) print("N=", len(highdens)) candidate_stars = highdens.copy() self.gas_particles.remove_particles(highdens) self.gas_particles.synchronize_to(self.code.gas_particles) print("new sinks...") if len(candidate_stars) > 0: # had to make some changes to prevent double adding particles print("Adding stars, N=", len(candidate_stars)) newstars_in_code = self.code.dm_particles.add_particles(candidate_stars) newstars = Particles() for nsi in newstars_in_code: if nsi not in self.star_particles: newstars.add_particle(nsi) else: print("this star should not exicst") newstars.name = "Star" newstars.birth_age = self.code.model_time newstars.Lx = 0 | (units.g * units.m**2)/units.s newstars.Ly = 0 | (units.g * units.m**2)/units.s newstars.Lz = 0 | (units.g * units.m**2)/units.s print("pre N=", len(self.star_particles), len(newstars), len(self.code.dm_particles)) # self.star_particles.add_sinks(newstars) self.star_particles.add_particles(newstars) print("post N=", len(self.star_particles), len(newstars), len(self.code.dm_particles)) else: print("N candidates:", len(candidate_stars)) def merge_stars(self): if len(self.star_particles) <= 0: return print("Let gravity take care of merging sinks") if self.star_particles.radius.max() <= (0 | units.AU): return print("identify groups..") ccs = self.star_particles.copy().connected_components(threshold=self.merge_radius) if len(ccs): print("merging sink sets... ") nmerge = 0 newstars = Particles() for cc in ccs: if len(cc) > 1: nmerge += 1 print("Merge stars: N= ", len(cc)) merge_two_stars(self.star_particles, cc.copy()) self.star_particles.synchronize_to(self.code.dm_particles) print("stars merged") def merge_two_stars(bodies, particles_in_encounter): com_pos = particles_in_encounter.center_of_mass() com_vel = particles_in_encounter.center_of_mass_velocity() new_particle = Particles(1) mu = particles_in_encounter[0].mass/particles_in_encounter.mass.sum() new_particle.birth_age = particles_in_encounter.birth_age.min() new_particle.mass = particles_in_encounter.total_mass() new_particle.position = com_pos new_particle.velocity = com_vel new_particle.name = "Star" new_particle.radius = particles_in_encounter.radius.max() print("old radius:", particles_in_encounter.radius.value_in(units.AU)) print("new radius:", new_particle.radius.value_in(units.AU)) bodies.add_particles(new_particle) print("Two stars (M=",particles_in_encounter.mass,") collided at d=", com_pos.length()) bodies.remove_particles(particles_in_encounter)
11,904
41.067138
181
py
amuse
amuse-main/examples/textbook/secularmultiples_example.py
""" Simple script to run a `2+2' quadruple system with SecularMultiple. The two `inner' binaries are denoted with `A' and `B'; the wider outer binary (`superorbit') is denoted with `C'. Orbital parameters can be provided with command line arguments. Note: setting N_output to a large value will slow down the script due to Python overhead, but will make nicer-looking plots. Adrian Hamers, December 2017 """ import numpy from amuse.community.secularmultiple.interface import SecularMultiple from amuse.units import quantities,units,constants from amuse.datamodel import Particles from matplotlib import pyplot ###BOOKLISTSTART1### def initialize_multiple_system(N_bodies, masses, semimajor_axis, eccentricity, inclination, argument_of_pericenter, longitude_of_ascending_node): N_binaries = N_bodies-1 particles = Particles(N_bodies+N_binaries) for index in range(N_bodies): particle = particles[index] particle.mass = masses[index] particle.is_binary = False particle.radius = 1.0 | units.RSun particle.child1 = None particle.child2 = None for index in range(N_binaries): particle = particles[index+N_bodies] particle.is_binary = True particle.semimajor_axis = semimajor_axis[index] particle.eccentricity = eccentricity[index] particle.inclination = inclination[index] particle.argument_of_pericenter = argument_of_pericenter[index] particle.longitude_of_ascending_node = longitude_of_ascending_node[index] ### specify the `2+2' hierarchy; this is easy to change to the `3+1' hierarchy if index==0: particle.child1 = particles[0] particle.child2 = particles[1] elif index==1: particle.child1 = particles[2] particle.child2 = particles[3] elif index==2: particle.child1 = particles[4] particle.child2 = particles[5] binaries = particles[particles.is_binary] return particles, binaries ###BOOKLISTSTOP1### def evolve_quadruple(N_output, end_time, m1, m2, m3, m4, aA, aB, aC, eA, eB, eC, iA, iB, iC, ApA, ApB, ApC, LANA, LANB, LANC): masses = [m1, m2, m3, m4] semimajor_axis = [aA, aB, aC] eccentricity = [eA, eB, eC] inclination = numpy.deg2rad([iA, iB, iC]) argument_of_percienter = numpy.deg2rad([ApA, ApB, ApC]) longitude_of_ascending_node = numpy.deg2rad([LANA, LANB, LANC]) print(longitude_of_ascending_node) N_bodies = 4 N_binaries = N_bodies-1 particles, binaries = initialize_multiple_system(N_bodies, masses, semimajor_axis, eccentricity, inclination, argument_of_percienter, longitude_of_ascending_node) code = SecularMultiple() code.particles.add_particles(particles) channel_from_particles_to_code = particles.new_channel_to(code.particles) channel_from_code_to_particles = code.particles.new_channel_to(particles) channel_from_particles_to_code.copy() ### set up some arrays for plotting ### print_smas_AU = [[] for x in range(N_binaries)] print_rps_AU = [[] for x in range(N_binaries)] print_parent_is_deg = [[] for x in range(N_binaries)] print_times_Myr = [] time = 0.0|units.yr output_time_step = end_time/float(N_output) while time <= end_time: time += output_time_step code.evolve_model(time) channel_from_code_to_particles.copy() print('='*50) print('t/Myr',time.value_in(units.Myr)) print('e',binaries.eccentricity) print('i/deg', numpy.rad2deg(binaries.inclination)) print('AP/deg', \ numpy.rad2deg(binaries.argument_of_pericenter)) print('LAN/deg', \ numpy.rad2deg(binaries.longitude_of_ascending_node)) ### write to output arrays ### print_times_Myr.append(time.value_in(units.Myr)) for index_binary in range(N_binaries): print_smas_AU[index_binary].append( binaries[index_binary].semimajor_axis.value_in(units.AU) ) print_rps_AU[index_binary].append( binaries[index_binary].semimajor_axis.value_in(units.AU)*(1.0 - binaries[index_binary].eccentricity) ) print_parent_is_deg[index_binary].append( numpy.rad2deg(binaries[index_binary].inclination_relative_to_parent) ) ### compute the `canonical' maximum eccentricity/periapsis distance that applies in the quadrupole-order test-particle limit if the `outer' binary is replaced by a point mass ### print(inclination[0],inclination[2],longitude_of_ascending_node[0],longitude_of_ascending_node[2]) i_AC_init = compute_mutual_inclination(inclination[0],inclination[2],longitude_of_ascending_node[0],longitude_of_ascending_node[2]) i_BC_init = compute_mutual_inclination(inclination[1],inclination[2],longitude_of_ascending_node[1],longitude_of_ascending_node[2]) canonical_rp_min_A_AU = (semimajor_axis[0]*(1.0 - numpy.sqrt( 1.0 - (5.0/3.0)*numpy.cos(i_AC_init)**2 ) )).value_in(units.AU) canonical_rp_min_B_AU = (semimajor_axis[1]*(1.0 - numpy.sqrt( 1.0 - (5.0/3.0)*numpy.cos(i_BC_init)**2 ) )).value_in(units.AU) data = print_times_Myr,print_smas_AU,print_rps_AU,print_parent_is_deg,canonical_rp_min_A_AU,canonical_rp_min_B_AU return data def compute_mutual_inclination(INCL_k,INCL_l,LAN_k,LAN_l): cos_INCL_rel = numpy.cos(INCL_k)*numpy.cos(INCL_l) + numpy.sin(INCL_k)*numpy.sin(INCL_l)*numpy.cos(LAN_k-LAN_l) return numpy.arccos(cos_INCL_rel) def plot_function(data): print_times_Myr,print_smas_AU,print_rps_AU,print_parent_is_deg,canonical_rp_min_A_AU,canonical_rp_min_B_AU = data N_binaries = len(print_smas_AU) pyplot.rc('text',usetex=True) pyplot.rc('legend',fancybox=True) linewidth=4 dlinewidth=2 fig=pyplot.figure(figsize=(10,9)) plot1=fig.add_subplot(2,1,1,yscale="log") plot2=fig.add_subplot(2,1,2) from distinct_colours import get_distinct colors = get_distinct(4) labels = ["$A$","$B$","$C$"] labels_i = ["$i_{AC}$","$i_{BC}$",None] for index_binary in range(N_binaries): label = labels[index_binary] label_i = labels_i[index_binary] color = colors[index_binary] plot1.plot(print_times_Myr,print_smas_AU[index_binary],color=color,linestyle='dashed',linewidth=dlinewidth) plot1.plot(print_times_Myr,print_rps_AU[index_binary],color=color,linewidth=linewidth,label=label) plot2.plot(print_times_Myr,print_parent_is_deg[index_binary],color=color,linewidth=linewidth,label=label_i) plot1.axhline(y = canonical_rp_min_A_AU, color= colors[0],linestyle='dotted',linewidth=dlinewidth) plot1.axhline(y = canonical_rp_min_B_AU, color= colors[1],linestyle='dotted',linewidth=dlinewidth) handles,labels = plot1.get_legend_handles_labels() plot1.legend(handles,labels,loc="upper right",fontsize=12) handles,labels = plot2.get_legend_handles_labels() plot2.legend(handles,labels,loc="lower right",fontsize=12) plot1.set_xlabel("t [Myr]",fontsize=18) plot2.set_xlabel("t [Myr]",fontsize=18) plot1.set_ylabel("$a_i [\mathrm{AU}]$",fontsize=18) plot2.set_ylabel("$i_{kl} [\mathrm{deg}]$",fontsize=18) plot1.set_xlim(0.0,print_times_Myr[-1]) plot2.set_xlim(0.0,print_times_Myr[-1]) plot1.tick_params(axis='both', which ='major', labelsize = 18) plot2.tick_params(axis='both', which ='major', labelsize = 18) fig.savefig("figure.eps") pyplot.show() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("--end_time", unit=units.Myr, dest="end_time", type="float", default = 5.0|units.Myr, help="integration time [%default]") result.add_option("--N_output", dest="N_output", type="int", default = 400, help="number of output steps [%default]") result.add_option("--m1", unit=units.MSun, dest="m1", type="float", default = 1.0|units.MSun, help="mass of object 1 [%default]") result.add_option("--m2", unit=units.MSun, dest="m2", type="float", default = 0.8|units.MSun, help="mass of object 2 [%default]") result.add_option("--m3", unit=units.MSun, dest="m3", type="float", default = 1.1|units.MSun, help="mass of object 3 [%default]") result.add_option("--m4", unit=units.MSun, dest="m4", type="float", default = 0.9|units.MSun, help="mass of object 4 [%default]") result.add_option("--aA", unit=units.AU, dest="aA", type="float", default = 1.0|units.AU, help="semimajor axis of orbit A [%default]") result.add_option("--aB", unit=units.AU, dest="aB", type="float", default = 1.2|units.AU, help="semimajor axis of orbit B [%default]") result.add_option("--aC", unit=units.AU, dest="aC", type="float", default = 100.0|units.AU, help="semimajor axis of orbit C (the `superorbit') [%default]") result.add_option("--eA", dest="eA", type="float", default = 0.1, help="eccentricity of orbit A [%default]") result.add_option("--eB", dest="eB", type="float", default = 0.1, help="eccentricity of orbit B [%default]") result.add_option("--eC", dest="eC", type="float", default = 0.3, help="eccentricity of orbit C (the `superorbit') [%default]") result.add_option("--iA", dest="iA", type="float", default = 75.0, help="inclination of orbit A in degrees [%default]") result.add_option("--iB", dest="iB", type="float", default = 80.0, help="inclination of orbit B in degrees [%default]") result.add_option("--iC", dest="iC", type="float", default = 0.001, help="inclination of orbit C (the `superorbit') in degrees [%default]") result.add_option("--ApA", dest="ApA", type="float", default = 10.0, help="argument of periapsis of orbit A in degrees [%default]") result.add_option("--ApB", dest="ApB", type="float", default = 30.0, help="argument of periapsis of orbit B in degrees [%default]") result.add_option("--ApC", dest="ApC", type="float", default = 60.0, help="argument of periapsis of orbit C (the `superorbit') in degrees [%default]") result.add_option("--LANA", dest="LANA", type="float", default = 0.001, help="longitude of the ascending node of orbit A in degrees [%default]") result.add_option("--LANB", dest="LANB", type="float", default = 0.001, help="longitude of the ascending node of orbit B in degrees [%default]") result.add_option("--LANC", dest="LANC", type="float", default = 0.001, help="longitude of the ascending node of orbit C (the `superorbit') in degrees [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() data = evolve_quadruple(**o.__dict__) plot_function(data)
11,638
45.931452
182
py
amuse
amuse-main/examples/textbook/cloudshock.py
import os import sys import numpy try: from matplotlib import pyplot IS_PLOT_AVAILABLE = True except ImportError: IS_PLOT_AVAILABLE = False from amuse.ext import cloud from amuse.units import generic_unit_system from amuse.units import units from amuse.community.capreole.interface import Capreole from amuse import io from amuse import datamodel class CalculateCloudShock(object): number_of_workers = 1 number_of_grid_points = 10 mesh_length = 10.0 | generic_unit_system.length gamma = 5.0/3.0 name_of_the_code = "athena" def __init__(self, number_of_grid_points = 10, number_of_workers = 1, name_of_the_code = "capreole"): self.number_of_grid_points = number_of_grid_points self.number_of_workers = number_of_workers self.name_of_the_code = name_of_the_code self.dimensions_of_mesh = ( self.number_of_grid_points, self.number_of_grid_points * 4, self.number_of_grid_points, ) def new_instance_of_code(self): attribute = "new_instance_of_{0}_code".format(self.name_of_the_code.lower()) return getattr(self,attribute)() def new_instance_of_capreole_code(self): result=Capreole(number_of_workers=self.number_of_workers) result.initialize_code() result.parameters.x_boundary_conditions = ("reflective","reflective") result.parameters.y_boundary_conditions = ("outflow","outflow") result.parameters.z_boundary_conditions = ("reflective","reflective") return result def new_instance_of_athena_code(self): from amuse.community.athena.interface import Athena result=Athena(number_of_workers=self.number_of_workers, redirection="none") result.initialize_code() result.parameters.gamma = self.gamma result.parameters.courant_number=0.3 result.parameters.x_boundary_conditions = ("reflective","reflective") result.parameters.y_boundary_conditions = ("outflow","outflow") result.parameters.z_boundary_conditions = ("reflective","reflective") return result def new_instance_of_mpiamrvac_code(self): from amuse.community.mpiamrvac.interface import MpiAmrVac result=MpiAmrVac(number_of_workers=self.number_of_workers) #, redirection="none") result.set_parameters_filename(result.default_parameters_filename) result.initialize_code() result.parameters.maximum_number_of_grid_levels = 3 result.parameters.spatial_discretization_method = 'tvdmu' result.parameters.predictor_step_discretization_method = 'tvdmu' result.parameters.entropy_type = 'powell' result.parameters.courant_number = 0.8 result.parameters.x_boundary_conditions = ("cont","cont") result.parameters.y_boundary_conditions = ("cont","cont") result.parameters.z_boundary_conditions = ("cont","cont") return result def set_parameters(self, instance): instance.parameters.mesh_size = self.dimensions_of_mesh instance.parameters.length_x = self.mesh_length instance.parameters.length_y = 4 * self.mesh_length instance.parameters.length_z = self.mesh_length result = instance.commit_parameters() def new_grid(self): grid = datamodel.Grid.create(self.dimensions_of_mesh, [1,1,1] | generic_unit_system.length) self.clear_grid(grid) return grid def initialize_grid(self, grid): center = self.mesh_length/2.0 * [1.0, 1.0, 1.0] cloud.fill_grid_with_cloud_shock( grid, center = center, radius = 1.0 | generic_unit_system.length, subgridsize = 4 ) def store_grids(self, grids, step): if __name__ == '__plot__': return grids_in_memory = [x.copy() for x in grids] io.write_set_to_file( grids_in_memory, "cloudshock_{2}_{0}_{1}.vtu".format(self.number_of_grid_points, step, self.name_of_the_code), "vtu", is_multiple=True ) def refine_grid(self, instance): if hasattr(instance, 'refine_grid'): must_refine = True while must_refine: must_refine = instance.refine_grid() for x in instance.itergrids(): inmem = x.copy() self.initialize_grid(inmem) from_model_to_code = inmem.new_channel_to(x) from_model_to_code.copy() def get_tau(self): rc=1. xi=10. cs=numpy.sqrt((self.gamma-1.0)) cs_out=numpy.sqrt((self.gamma-1.0)*xi) vs=cs_out*2.7 return (1.6*2*rc*xi**0.5/vs) | generic_unit_system.time def get_solution_at_time(self, time): instance=self.new_instance_of_code() self.set_parameters(instance) for x in instance.itergrids(): inmem = x.copy() self.initialize_grid(inmem) from_model_to_code = inmem.new_channel_to(x) from_model_to_code.copy() self.refine_grid(instance) instance.initialize_grid() self.store_grids(instance.itergrids(), 0) if time > 0.0 | generic_unit_system.time: print("start evolve") dt = time / 10.0 t = dt step = 1 while t <= time: instance.evolve_model(t) print("time : ", t) #self.store_grids(instance.itergrids(), step) t += dt step += 1 print("sampling results") r = 4 sample = datamodel.Grid.create( (1000,1000*r), (10.0,10*r) | generic_unit_system.length ) sample.z = 5.0 | generic_unit_system.length rho, rhovx, rhovy, rhovx, rhoen = instance.get_hydro_state_at_point(sample.x.flatten(), sample.y.flatten(), sample.z.flatten()) sample.rho = rho.reshape(sample.shape) sample.rhovx = rhovx.reshape(sample.shape) sample.rhovy = rhovy.reshape(sample.shape) sample.rhovz = rhovx.reshape(sample.shape) sample.energy = rhoen.reshape(sample.shape) print("terminating code") instance.stop() return sample def main(): number_of_grid_points = 40 notc_string = ['athena', 'capreole', 'mpiamrvac'] notc_string = [notc_string[0]] for name_of_the_code in notc_string: model = CalculateCloudShock( number_of_grid_points = number_of_grid_points, number_of_workers = 4, name_of_the_code = name_of_the_code ) # result = model.get_solution_at_time(0.75 * model.get_tau()) result = model.get_solution_at_time(1.0 * model.get_tau()) rho = result.rho.value_in(generic_unit_system.density) print("done") if not IS_PLOT_AVAILABLE: return levels = numpy.linspace(numpy.min(rho), numpy.max(rho), 255) figure = pyplot.figure(figsize=(10,10)) plot = figure.add_subplot(1,1,1) # cax = plot.imshow(rho, origin = 'lower', cmap='jet', vmin=0.0, vmax=1.0) cax = plot.imshow(rho, origin = 'lower', cmap='jet', vmin=0.0, vmax=0.5) if 'athena' in name_of_the_code: cbar = pyplot.colorbar(cax, orientation='horizontal') cbar.set_label('Density') figure.savefig('cloudshock_{0}_{1}.png'.format(name_of_the_code, number_of_grid_points)) #pyplot.show() if __name__ == "__main__": main()
7,927
33.025751
135
py
amuse
amuse-main/examples/textbook/plot_projected_disk_density_from_top.py
""" Visualization for simple N-body integration. Reads particle set from file (nbody.hdf5) and prints subsequent frames. """ import os import sys import numpy import matplotlib #matplotlib.use('Agg') from matplotlib import pyplot #from matplotlib import pyplot from amuse.plot import scatter, xlabel, ylabel from amuse.lab import * from amuse.io import store from optparse import OptionParser from amuse.units.optparse import OptionParser from time import sleep from amuse.ext.orbital_elements import orbital_elements_from_binary def mu(X = None, Y = 0.25, Z = 0.02, x_ion = 0.1): """ Compute the mean molecular weight in kg (the average weight of particles in a gas) X, Y, and Z are the mass fractions of Hydrogen, of Helium, and of metals, respectively. x_ion is the ionisation fraction (0 < x_ion < 1), 1 means fully ionised """ if X is None: X = 1.0 - Y - Z elif abs(X + Y + Z - 1.0) > 1e-6: raise Exception("Error in calculating mu: mass fractions do not sum to 1.0") return constants.proton_mass / (X*(1.0+x_ion) + Y*(1.0+2.0*x_ion)/4.0 + Z*x_ion/2.0) def plot_single_image(planets, debris, disk, shell, figfile=None): if len(shell)>0: disk.add_particles(shell) lim = 150 """ #centered on the Sun if len(planets)>1: print "Center on COM" com = planets[0].position vcom = planets[0].velocity planets.position -= com planets.velocity -= vcom disk.position -= com disk.velocity -= vcom debris.position -= com debris.velocity -= vcom """ left, width = 0.1, 0.65 bottom, height = 0.1, 0.65 bottom_h = left_h = left+width+0.05 rect_scatter = [left, bottom, width, height] rect_histx = [left, bottom_h, width, 0.2] rect_histy = [left_h, bottom, 0.2, height] fig = pyplot.figure(figsize=(12,12)) time = disk.get_timestamp() # pyplot.title("Cluster at t="+str(time.in_(units.Gyr))) xy = pyplot.axes(rect_scatter) #xy.text(110,110, "protoplanetary disk (img#"+str(index)+")", ha='left', va='bottom') xz = pyplot.axes(rect_histx) yz = pyplot.axes(rect_histy) xy.set_xlabel("X [AU]") xy.set_ylabel("Y [AU]") xz.set_ylabel("Z [AU]") yz.set_xlabel("Z [AU]") positions = disk.position x, y, z = positions.x.value_in(units.AU), positions.y.value_in(units.AU), positions.z.value_in(units.AU) # sizes = 1000 # sizes = 1000*disk.rho/disk.rho.max() alpha = 0.01 us = disk.u if hasattr(disk, "xion"): xs = disk.xion else: xs = numpy.zeros(len(disk)) u_min, u_max = min(us), max(us) xion_min, xion_max = min(xs), max(xs) # if xion_min<=0: # xion_min = xion_max/100. # xs += xion_min # xion_max += xion_min print("u=", u_min, u_max) Ts = mu() / constants.kB * disk.u T_min = max(20|units.K, mu() / constants.kB * u_min) T_max = min(1800|units.K, mu() / constants.kB * u_max) print("T=", T_min, T_max) print("X=", xion_min, xion_max) log_u = numpy.log((us / u_min)) / numpy.log((u_max / u_min)) clipped_log_u = numpy.minimum(numpy.ones_like(log_u), numpy.maximum(numpy.zeros_like(log_u), log_u)) # log_x = numpy.log((xs / xion_min)) / numpy.log((xion_max / xion_min)) # clipped_log_x = numpy.minimum(numpy.ones_like(log_x), numpy.maximum(numpy.zeros_like(log_x), log_x)) # xrange = (xs/xion_min) / (xion_max/xion_min) # print "xrange=", xrange.min(), xrange.max() clipped_log_x = xs log_T = numpy.log((Ts / T_min)) / numpy.log((T_max / T_min)) clipped_log_T = numpy.minimum(numpy.ones_like(log_T), numpy.maximum(numpy.zeros_like(log_T), log_T)) ps = disk.rho p_min, p_max = min(ps), max(ps) log_p = numpy.log((ps / p_min)) / numpy.log((p_max / p_min)) clipped_log_p = numpy.minimum(numpy.ones_like(log_p), numpy.maximum(numpy.zeros_like(log_p), log_p)) # red = 1 - clipped_log_u**(1./2.) # blue = clipped_log_u**(1./2.) # green = numpy.minimum(red, blue) # red = 1.0 - clipped_log_T # red = 1-clipped_log_x**(1./2.) blue = clipped_log_T red = 1-clipped_log_T #green = numpy.minimum(red, blue) green = clipped_log_p colors = numpy.transpose(numpy.array([red, green, blue])) sizes = 2*2000*disk.h_smooth/disk.h_smooth.max() xy.scatter(x, y, sizes, c=colors, edgecolors = "none", alpha = alpha) xy.set_xlim( (-lim, lim) ) xy.set_ylim( (-lim, lim) ) sizes = 2*200*disk.h_smooth/disk.h_smooth.max() xz.scatter(x, z, sizes, c=colors, edgecolors = "none", alpha = alpha) yz.scatter(z, y, sizes, c=colors, edgecolors = "none", alpha = alpha) xz.set_xlim( xy.get_xlim() ) yz.set_ylim( xy.get_xlim() ) yz.set_xlim( (-0.1*lim, 0.1*lim) ) xz.set_ylim( (-0.1*lim, 0.1*lim) ) # yz.set_xlim( (-lim, lim) ) # xz.set_ylim( (-lim, lim) ) if len(debris)>0: c = 'k' m = 0.1 xy.scatter(debris.x.value_in(units.AU), debris.y.value_in(units.AU), s=m, c=c, lw=0) xz.scatter(debris.x.value_in(units.AU), debris.z.value_in(units.AU), s=m, c=c, lw=0) yz.scatter(debris.z.value_in(units.AU), debris.y.value_in(units.AU), s=m, c=c, lw=0) if len(planets)>0: from distinct_colours import get_distinct c = get_distinct(len(planets)) m = 1000 * planets.mass/planets.mass.max() m[0] = min(10*m[1:].max(), 30) xy.scatter(planets.x.value_in(units.AU), planets.y.value_in(units.AU), s=m, c=c, lw=0) xz.scatter(planets.x.value_in(units.AU), planets.z.value_in(units.AU), s=m, c=c, lw=0) yz.scatter(planets.z.value_in(units.AU), planets.y.value_in(units.AU), s=m, c=c, lw=0) filename = "planetary_system.png" fig.savefig(filename) def myplot(x, y, s, bins=1000): from scipy.ndimage.filters import gaussian_filter heatmap, xedges, yedges = numpy.histogram2d(x, y, bins=bins) heatmap = gaussian_filter(heatmap, sigma=s) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] return heatmap.T, extent def plot_view(x, y, z, xlim, ylim, levels=4): from scipy.interpolate import griddata xi = numpy.linspace(-xlim,xlim,100) yi = numpy.linspace(-ylim,ylim,100) # xi = numpy.linspace(-xlim,xlim,xlim) # yi = numpy.linspace(-ylim,ylim,ylim) # grid the data. print(len(x), len(y), len(z)) zi = griddata((x, y), z, (xi[None,:], yi[:,None]), method='linear') # contour the gridded data, plotting dots at the randomly spaced data points. # CS = pyplot.contourf(xi,yi,zi,levels,cmap=pyplot.cm.plasma, # anorm=pyplot.Normalize(vmax=0.0, vmin=0.9*abs(z).max())) CS = pyplot.contourf(xi,yi,zi,levels,cmap=pyplot.cm.plasma, anorm=pyplot.Normalize(vmax=0.0, vmin=9000), vmin=0, vmax=9000) # now determine nice limits by hand: pyplot.xlim((-xlim, xlim)) pyplot.ylim((-ylim, ylim)) return CS def Xplot_density_view(ax_xy, x, y, z, xlim, ylim, levels=5): import numpy as np import matplotlib.pyplot as pl import scipy.stats as st xmin = -xlim xmax = xlim ymin = -ylim ymax = ylim xx, yy = np.mgrid[xmin:xmax:100j, ymin:ymax:100j] positions = np.vstack([xx.ravel(), yy.ravel()]) values = np.vstack([x, y]) kernel = st.gaussian_kde(values) f = np.reshape(kernel(positions).T, xx.shape) ax = ax_xy ax.set_xlim(xmin, xmax) ax.set_ylim(ymin, ymax) # Contourf plot cfset = ax.contourf(xx, yy, f, cmap='Blues') ## Or kernel density estimate plot instead of the contourf plot #ax.imshow(np.rot90(f), cmap='Blues', extent=[xmin, xmax, ymin, ymax]) # Contour plot cset = ax.contour(xx, yy, f, colors='k') return cset def plot_temperature_image(planets, debris, disk, shell, figfile="fig_disk_top_view_temperature.pdf"): from prepare_figure import single_frame, figure_frame, set_tickmarks disk.temperature = mu() / constants.kB * disk.u x = disk.x.value_in(units.AU) y = disk.y.value_in(units.AU) z = disk.z.value_in(units.AU) T = disk.temperature.value_in(units.K) print("min temp=", T.min()) import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import NullFormatter nullfmt = NullFormatter() # no labels if "0000" in figfile: fig = plt.figure(1, figsize=(12, 10)) else: fig = plt.figure(1, figsize=(10, 10)) pyplot.axis('equal') view = 10 img = plot_view(x, y, T, 100, 100, view) if "0000" in figfile: cbar = pyplot.colorbar(img, orientation='vertical') font = matplotlib.font_manager.FontProperties(family='times new roman', size=16) cbar.set_label('T [K]', rotation=270) pyplot.xlabel("X [au]") pyplot.ylabel("Y [au]") pyplot.savefig(figfile) plt.show() def plot_density_view(ax_xy, x, y, z, xlim, ylim, levels=5): import numpy as np import matplotlib.pyplot as pl import scipy.stats as st """ import seaborn as sns sns.set(color_codes=True) ax = sns.kdeplot(x, y, shade=True, ax=ax_xy) cmap = sns.cubehelix_palette(as_cmap=True, dark=0, light=1, reverse=True) sns.kdeplot(x, y, cmap=cmap, n_levels=60, shade=True); return cmap """ xmin = -xlim xmax = xlim ymin = -ylim ymax = ylim xx, yy = np.mgrid[xmin:xmax:100j, ymin:ymax:100j] positions = np.vstack([xx.ravel(), yy.ravel()]) values = np.vstack([x, y]) kernel = st.gaussian_kde(values) f = np.reshape(kernel(positions).T, xx.shape) ax = ax_xy ax.set_xlim(xmin, xmax) ax.set_ylim(ymin, ymax) # Contourf plot # cfset = ax.contourf(xx, yy, f, cmap='Blues') cfset = ax.contourf(xx, yy, f, levels, cmap='jet') # import matplotlib as mpl # norm = mpl.colors.Normalize(vmin=0,vmax=1.) ## Or kernel density estimate plot instead of the contourf plot # ax.imshow(np.rot90(f), cmap='Blues', extent=[xmin, xmax, ymin, ymax], # vmin=0, vmax=1) ax.imshow(np.rot90(f), cmap='Blues', extent=[xmin, xmax, ymin, ymax], norm=matplotlib.colors.LogNorm()) # Contour plot #cset = ax.contour(xx, yy, f, colors='k') return cfset def fmt(x, pos): a, b = '{:.2e}'.format(x).split('e') b = int(b) return r'${} \times 10^{{{}}}$'.format(a, b) def plot_projected_density_image(planets, debris, disk, shell, figfile): from prepare_figure import single_frame, figure_frame, set_tickmarks disk.temperature = mu() / constants.kB * disk.u x = disk.x.value_in(units.AU) y = disk.y.value_in(units.AU) z = disk.z.value_in(units.AU) T = disk.temperature.value_in(units.K) SLICE_DATA = False if SLICE_DATA: selection = z < 10 x = x[selection] y = y[selection] z = z[selection] T = T[selection] selection = z > -10 x = x[selection] y = y[selection] z = z[selection] T = T[selection] print("After slicing the data: N=", len(x)) rho = numpy.log10(disk.rho.value_in(units.g/units.cm**3)) print("Density=", rho.min(), rho.max(), "in log(g/cm^3)") #-12.9251289255 -9.9657991654 in log(g/cm^3) import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import NullFormatter nullfmt = NullFormatter() # no labels left, width = 0.2, 0.45 bottom, height = 0.1, 0.65 bottom_h = left_h = left + width + 0.02 rect_xy = [left, bottom, width, height] rect_xz = [left, bottom_h+0.11, width+0.114, 0.2] rect_zy = [left_h, bottom, 0.15, height] # start with a rectangular Figure fig = plt.figure(1, figsize=(12, 8)) ax_xy = plt.axes(rect_xy) ax_xz = plt.axes(rect_xz) ax_zy = plt.axes(rect_zy) # no labels ax_xz.xaxis.set_major_formatter(nullfmt) ax_zy.yaxis.set_major_formatter(nullfmt) # levels = [-16, -14, -13, -11] levels = 20 plot_density_view(ax_xy, x, y, rho, 100, 100, levels) plot_density_view(ax_xz, x, z, rho, 100, 30, levels) img = plot_density_view(ax_zy, z, y, rho, 30, 100, levels) # import matplotlib.ticker as ticker # cbar = pyplot.colorbar(img, ax=ax_xz, orientation='vertical', format=ticker.FuncFormatter(fmt)) # cbar = pyplot.colorbar(img, ax=ax_xz, orientation='vertical', format='%.0e') from matplotlib.ticker import LogFormatter formatter = LogFormatter(10, labelOnlyBase=False) bounds = [-4, -3, -2, -1] import matplotlib as mpl cmap = mpl.cm.jet ##cool norm = mpl.colors.BoundaryNorm(bounds, cmap.N) cbar = pyplot.colorbar(img, ax=ax_xz, orientation='vertical', format=formatter, norm=norm, ticks=bounds) # cbar = pyplot.colorbar(img, ax=ax_xz, orientation='vertical', format=formatter, # ticks=[-4, -3, -2]) # cb = pyplot.colorbar(ticks=[1,5,10,20,50], format=formatter) ax_bar = cbar.ax text = ax_bar.yaxis.label font = matplotlib.font_manager.FontProperties(family='times new roman', size=16) text.set_font_properties(font) cbar.set_label(r'$log(\rho) [g/cm^3]$', rotation=270, labelpad=+20) ax_xz.set_xlim(ax_xy.get_xlim()) ax_zy.set_ylim(ax_xy.get_ylim()) ax_xy.set_xlabel("X [au]") ax_xy.set_ylabel("Y [au]") ax_xz.set_ylabel("Z [au]") ax_zy.set_xlabel("Z [au]") pyplot.savefig(figfile) plt.show() def main(filename=None, pp=False): source, planets, debris, disk, shell = read_planetary_system(filename) print("N=", len(source), len(planets), len(debris), len(disk), len(shell)) figfile = filename.split(".amuse")[0] + ".pdf" if pp: #plot_temperature_image(planets, debris, disk, shell, figfile) plot_projected_density_image(planets, debris, disk, shell, figfile) #plot_single_image_simple(planets, debris, disk, shell) else: plot_single_image(planets, debris, disk, shell) def calculate_orbital_elements(star, planet): from amuse.ext.orbital_elements import orbital_elements_from_binary p = Particles() p.add_particle(star) p.add_particle(planet) M, m, a, e, ta_out, inc, lan_out, aop_out = orbital_elements_from_binary(p, G=constants.G) #print "Orbital elements:", M, m, a, e, ta_out, inc, lan_out, aop_out return a, e, inc def read_planetary_system(filename): #lim, snapshot_id): planets = Particles(0) debris = Particles(0) source = Particles(0) gas = Particles(0) shell = Particles(0) time = 0 | units.yr bodies = read_set_from_file(filename, "amuse") for bi in bodies.history: print(bi) if len(bi)>0: if "gas" in bi.name: gas.add_particles(bi.copy()) elif "debris" in bi.name: debris.add_particles(bi.copy()) elif "Jupiter" in bi.name: planets.add_particles(bi.copy()) elif "shell" in bi.name: shell.add_particles(bi.copy()) else: source.add_particles(bi.copy()) print(len(gas), len(shell)) # print gas[1] # print shell[1] # shell = gas.select(lambda n: "shell" in n,["name"]) # gas -= shell # print shell[1] print("N=", len(source), len(planets), len(debris), len(gas), len(shell)) print("Read planetary system at time", time.in_(units.yr)) return source, planets, debris, gas, shell def output_single_image(filename): #lim, snapshot_id): bodies = read_set_from_file(filename, "amuse") planets = Particles(0) debris = Particles(0) for bi in bodies.history: if len(bi)>1: if "debris" in bi.name: debris = bi.copy() #print "Orbits at t=", time, debris.name, debris.semimajor_axis.in_(units.AU), debris.eccentricity elif "gas" in bi.name: disk = bi.copy() lim = 150|units.AU snapshot_id = 1 # for pi in planets[1:]: # a, e, inc = calculate_orbital_elements(planets[0], pi) # print "Planet orbits:", a.in_(units.AU), e, inc else: planets = bi.copy() time = bi.get_timestamp() print("Orbits at t=", time, planets.name, planets.semimajor_axis.in_(units.AU), planets.eccentricity) def output_multiple_images(lim): snapshot_id = 0 filename = "planetary_system_i{0:04}.amuse".format(snapshot_id) while os.path.exists(filename): bodies = read_set_from_file(filename, "amuse") for bi in bodies.history: if len(bi)<=20: planets = bi.copy() time = bi.get_timestamp() print("Orbits at t=", time, planets.semimajor_axis.in_(units.AU), planets.eccentricity) else: disk = bi.copy() time = bi.get_timestamp() print("Snapshot=", snapshot_id, time) if image_id<0 or image_id == snapshot_id: plot_single_image(planets, disk, lim.value_in(units.AU), snapshot_id) if image_id == snapshot_id: print("Stop plotting") break snapshot_id += 1 filename = "planetary_system_i{0:04}.amuse".format(snapshot_id) def new_option_parser(): result = OptionParser() result.add_option("-f", dest="filename", default = "ID_Nd5Nr7Ms23Rs02pcff-2_i0009.amuse", help="output filename [%default]") result.add_option("-p", action="store_false", dest="pp", default=True, help="plot temperature") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
17,814
34.488048
113
py
amuse
amuse-main/examples/textbook/rad_minimal_new.py
import numpy from amuse.lab import * from amuse.ic.gasplummer import new_plummer_gas_model from amuse.ext.spherical_model \ import new_uniform_spherical_particle_distribution from matplotlib import pyplot from prepare_figure import single_frame, figure_frame from distinct_colours import get_distinct def binned_mean_data(r, x): R = numpy.arange(0, r[-1], 0.1) X = numpy.zeros(len(R)) N = numpy.zeros(len(R)) for i in range(len(R)-1): for j in range(len(r)): if r[j]>=R[i] and r[j]<=R[i+1]: X[i] += x[j] N[i] += 1. for i in range(len(X)): if X[i]>0 and N[i]>0: X[i] = X[i]/float(N[i]) return R, X def get_ionization_fraction1d(ism): r = [] | units.parsec x = [] for p in ism: r.append(p.position.length()) x.append(p.xion) r, x = list(zip(*sorted(zip(r.value_in(units.parsec), x)))) R, X = binned_mean_data(r, x) return r, x, R, X def get_ionization_fraction2d(ism): x = [] y = [] xi = [] h = [] l = 0 for p in ism: xp = p.x.value_in(units.parsec) yp = p.y.value_in(units.parsec) zp = p.z.value_in(units.parsec) if abs(zp) <= 0.5: x.append(xp) if abs(xp) > l: l = abs(xp) y.append(yp) if abs(yp) > l: l = abs(yp) xi.append(p.xion) h.append(p.h_smooth.value_in(units.parsec)) return x, y, xi, h, l def plot_ionization(ism, N, which, rmax, t_end, rS, ip): r, x, R, X = get_ionization_fraction1d(ism) xx, yy, xi, hh, ll = get_ionization_fraction2d(ism) w = 14 if ip > 1: pyplot.close('all') pyplot.clf() pyplot.figure(figsize=(w,6)) pyplot.rcParams.update({'font.size': 22}) colors = get_distinct(3) # rscolor = 'green' ax1 = pyplot.subplot(1,2,1) #ax1.scatter(r, x, c=colors[0], lw=0, s=10) ax1.scatter(r, x, c=x, lw=0, s=20, alpha=0.5, cmap="jet") ax1.plot(R[1:], X[1:], c=colors[1], lw=3) ax1.plot([rS, rS], [-1,2], color=colors[2], linestyle='dashed', lw=3) ax1.text(rS+0.08, 1.06, r'$R_s$', color=colors[2], fontsize=20) ax1.set_xlim(0, rmax) ax1.set_ylim(-0.04, 1.19) ax1.set_xlabel("r [pc]", fontsize=20) ax1.set_ylabel(r'$\xi_{\rm ion}$', fontsize=20) ax2 = pyplot.subplot(1,2,2) h = numpy.array(hh) h *= 72*w/(6.*ll) # approximate scaling ax2.set_aspect(1) sc2 = ax2.scatter(xx, yy, c=xi, s=numpy.pi*h**2, alpha=0.05, edgecolor=None, cmap="jet") if ll < rmax: ll = rmax ax2.set_xlim(-ll,ll) ax2.set_ylim(-ll,ll) ax2.set_xlabel("x [pc]", fontsize=20) ax2.set_ylabel("y [pc]", fontsize=20) #for axi in ax2.flat: ax2.xaxis.set_major_locator(pyplot.MaxNLocator(6)) ax2.yaxis.set_major_locator(pyplot.MaxNLocator(6)) #pyplot.colorbar(sc2, ax=ax2, fraction=0.046, pad=0.04) # magic numbers! circle = pyplot.Circle((0, 0), rS, color=colors[2], fill=False, linestyle='dashed', lw=3) ax2.add_artist(circle) if which == 0: id_string = 'Plummer_model' else: id_string = 'Homogeneous_sphere' param_string = "_N=%d_t=%.3f_Myr" % (N, t_end) #pyplot.suptitle(id_string+param_string, y=0.96, fontsize=16) savefile = 'fig_ionization_of_GMC_'+id_string+param_string+'.png' pyplot.savefig(savefile, dpi=300) print('Figure saved in file', savefile) if ip == 0: pyplot.show() def plot_density(r, rho, rho0, a): pyplot.figure(figsize=(10,8)) pyplot.scatter(r, rho, lw=0, s=10) rhop = rho0*(1+(r/a)**2)**(-2.5) pyplot.scatter(r, rhop, lw=0, s=10) pyplot.xlim(0, 6) pyplot.ylim(0.005, 10.) pyplot.semilogy() pyplot.show() ###BOOKLISTSTART1### def generate_ism_initial_conditions(N, M=10|units.MSun, R=3|units.parsec, boxsize=10|units.parsec, which=1): converter = nbody_system.nbody_to_si(M, R) # Option 0: Plummer model with mass M and virial radius R. # Option 1: Homogeneous sphere with radius R and same central # density as the Plummer model. a = R/1.7 # Plummer parameter rho0 = 3*M/(4*numpy.pi*a**3) # Plummer model central density rhp = 1.3*a # Plummer model half-mass radius print('a =', a.in_(units.parsec)) print('rhp =', rhp.in_(units.parsec)) print('rho0 =', rho0.in_(units.MSun/units.parsec**3)) if which == 0: rmax = boxsize ism = new_plummer_gas_model(N, converter) else: Ru = R rmax = Ru ism = new_uniform_spherical_particle_distribution(N, Ru, 4*numpy.pi*rho0*Ru**3/3, type="random") rhu = Ru/3**0.5 print('rhu =', rhu.in_(units.parsec)) ism.vx = 0.|units.kms ism.vy = 0.|units.kms ism.vz = 0.|units.kms ism.u = (0.075|units.kms)**2 print('M =', ism.mass.sum().in_(units.MSun)) #print 'mean u =', ism.u.sum().in_(units.kms**2)/N #print 'max u =', ism.u.max().in_(units.kms**2) rr = ((ism.position)**2).sum(axis=1).sqrt().value_in(units.parsec) ii = numpy.argsort(rr) print('rh =', rr[ii[N/2]], 'parsec') ism.flux = 0. | units.s**-1 ism.xion = 0.0 hydro = Fi(converter) hydro.gas_particles.add_particles(ism) hydro.evolve_model(1|units.yr) hydro.gas_particles.new_channel_to(ism).copy() hydro.stop() ''' plot_density(rr, ism.rho.value_in(units.MSun/units.parsec**3), rho0.value_in(units.MSun/units.parsec**3), a.value_in(units.parsec)) ''' #print 'max density =', ism.rho.max().in_(units.MSun/units.parsec**3) rc = a/3. cent = ism.select(lambda r: r.length() < rc, ["position"]) print('approximate central density =', \ (3*cent.mass.sum()/(4*numpy.pi*rc**3)).in_(units.MSun/units.parsec**3)) ism = ism.select(lambda r: r.length() < 0.5*boxsize, ["position"]) #print "max density in box =", \ # ism.rho.max().in_(units.MSun/units.parsec**3), \ # ism.rho.max().in_(units.amu/units.cm**3) if rmax > boxsize/2: rmax = boxsize/2 return ism,rho0,a,M,rmax ###BOOKLISTSTOP1### def radius_containing(mass, ism): rr = ((ism.position)**2).sum(axis=1).sqrt().value_in(units.parsec) isort = numpy.argsort(rr) msum = zero rp = [] mp = [] i = 0 #print msum, mass.in_(units.MSun) while msum < mass: msum += ism.mass[isort[i]] rp.append(rr[isort[i]]) mp.append(msum.value_in(units.MSun)) if i >= len(rr)-1: break i += 1 #pyplot.plot(rp, mp) #pyplot.show() return rp[-1]|units.parsec ###BOOKLISTSTART### def main(N, Lstar, boxsize, t_end, which, np): ism,rho0,a,M,rmax \ = generate_ism_initial_conditions(N, boxsize=boxsize, which=which) print('particles in box =', len(ism)) source = Particle() source.position = (0, 0, 0) |units.parsec source.flux = Lstar/(20. | units.eV) source.rho = ism.rho.max() source.xion = ism.xion.max() source.u = (9.|units.kms)**2 # = kT/m S = source.flux.in_(units.s**-1) print('ionizing flux =', S) print('central density =', rho0.in_(units.MSun/units.parsec**3)) n = rho0/(1|units.amu) print('number density =', n.in_(units.cm**-3)) T = source.u*(1|units.amu)/constants.kB print('temperature =', T.in_(units.K)) alpha = (2.e-16*T.value_in(units.K)**-0.75)|(units.m**3/units.s) print('alpha =', alpha.in_(units.m**3/units.s)) trec = 1/(n*alpha) print('recombination time =', trec.in_(units.Myr)) MS = (S*trec)*1|units.amu if which == 0: rS = a/((M/MS)**(2./3) - 1.)**0.5 # Plummer else: rS = (3*S/(4*numpy.pi*n**2*alpha))**(1./3) # Homogeneous print('Stromgren radius (analytic) =', rS.in_(units.parsec)) rS1 = radius_containing(MS, ism) print('Stromgren radius (measured) =', rS1.in_(units.parsec)) radiative = SimpleX(redirection='none') radiative.parameters.box_size = boxsize radiative.parameters.timestep = 0.125*trec #radiative.parameters.timestep = 0.05|units.Myr radiative.particles.add_particle(source) radiative.particles.add_particles(ism) te = t_end.value_in(units.Myr) tlist = numpy.linspace(te/np, te, np)|units.Myr ip = 0 for t in tlist: radiative.evolve_model(t) print('t =', t, \ 'model_time =', radiative.model_time.in_(units.Myr)) radiative.particles.new_channel_to(ism).copy() print('') print("min ionization:", ism.xion.min()) print("average ionization:", ism.xion.mean()) print("max ionization:", ism.xion.max()) if np > 1: ip += 1 plot_ionization(ism, N, which, rmax.value_in(units.parsec), t.value_in(units.Myr), rS1.value_in(units.parsec), ip) radiative.stop() ###BOOKLISTSTOP### def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-n", type="int", dest="np", default = 1, help="number of plots [%default]") result.add_option("-N", type="int", dest="N", default = 10000, help="number of gas particles [%default]") result.add_option("-t", unit=units.Myr, type="float", dest="t_end", default = 1.0|units.Myr, help="radiation time [%default]") result.add_option("-L", unit=units.LSun, type="float", dest="Lstar", default = 1.e2|units.LSun, help="luminosity of ionizing source [%default]") result.add_option("-d", unit=units.parsec, dest="boxsize", default = 10|units.parsec, help="size of the density box [%default]") result.add_option("-w", type='int', dest="which", default = 1, help="which model [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() numpy.random.seed(12345) main(**o.__dict__)
10,359
32.205128
79
py
amuse
amuse-main/examples/textbook/three_body_bridge_hierarchical.py
import numpy from amuse.lab import * from amuse.couple import bridge def new_system_of_sun_and_earth(): stars = Particles(3) sun = stars[0] sun.mass = units.MSun(1.0) sun.position = units.m(numpy.array((0.0,0.0,0.0))) sun.velocity = units.ms(numpy.array((0.0,0.0,0.0))) sun.radius = units.RSun(1.0) earth = stars[1] earth.mass = units.kg(5.9736e24) earth.radius = units.km(6371) earth.position = units.km(numpy.array((149.5e6,0.0,0.0))) earth.velocity = units.ms(numpy.array((0.0,29800,0.0))) moon = stars[2] moon.mass = units.kg(7.3477e22 ) moon.radius = units.km(1737.10) moon.position = units.km(numpy.array((149.5e6 + 384399.0 ,0.0,0.0))) moon.velocity = ([0.0,1.022,0] | units.km/units.s) + earth.velocity return stars def main(): filename = "SunAndEarthAndMoon.hdf" ss = new_system_of_sun_and_earth() star = ss[0] planet = ss[1] moon = ss[2] converter=nbody_system.nbody_to_si(star.mass,planet.position.length()) star_gravity = ph4(converter) star_gravity.particles.add_particle(star) planet_gravity = ph4(converter) planet_gravity.particles.add_particle(planet) moon_gravity = ph4(converter) moon_gravity.particles.add_particle(moon) channel_from_star_to_framework = star_gravity.particles.new_channel_to(ss) channel_from_planet_to_framework = planet_gravity.particles.new_channel_to(ss) channel_from_moon_to_framework = moon_gravity.particles.new_channel_to(ss) write_set_to_file(ss, filename, 'hdf5', overwrite_file=True) ###BOOKLISTSTART### sp_gravity = bridge.Bridge() sp_gravity.add_system(moon_gravity, (planet_gravity,)) sp_gravity.add_system(planet_gravity, (moon_gravity,)) gravity = bridge.Bridge() gravity.add_system(sp_gravity, (star_gravity,)) gravity.add_system(star_gravity, (sp_gravity,)) ###BOOKLISTSTOP### Etot_init = gravity.kinetic_energy + gravity.potential_energy Etot_prev = Etot_init sp_gravity.timestep = 1|units.day gravity.timestep = 10|units.day time = zero dt = 3|units.day t_end = 1 | units.yr while time < t_end: time += dt gravity.evolve_model(time) Etot_prev_se = gravity.kinetic_energy + gravity.potential_energy channel_from_star_to_framework.copy() channel_from_planet_to_framework.copy() channel_from_moon_to_framework.copy() write_set_to_file(ss, filename, 'hdf5', append_to_file=True) Ekin = gravity.kinetic_energy Epot = gravity.potential_energy Etot = Ekin + Epot print("T=", time, end=' ') print("E= ", Etot, "Q= ", Ekin/Epot, end=' ') print("dE=", (Etot_init-Etot)/Etot, "ddE=", (Etot_prev-Etot)/Etot) Etot_prev = Etot gravity.stop() if __name__ in ('__main__', '__plot__'): main()
2,875
31.314607
82
py
amuse
amuse-main/examples/textbook/lagrange_points.py
import numpy from matplotlib import pyplot from amuse.plot import xlabel, ylabel, effective_iso_potential_plot from amuse.units import units, constants, nbody_system from amuse.community.hermite.interface import Hermite from amuse.datamodel import Particles def new_sun_earth_system(): particles = Particles(2) particles.mass = [1, 0.2] | units.MSun particles.position = [[0, 0, 0], [1.0, 0, 0]] | units.AU particles.velocity = [0, 0, 0] | units.km / units.s particles[1].vy = (constants.G * particles.total_mass() / particles[1].x).sqrt() return particles def setup_gravity_code(): converter = nbody_system.nbody_to_si(1.0|units.MSun, 1.0|units.AU) gravity = Hermite(converter) gravity.particles.add_particles(new_sun_earth_system()) return gravity 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$") save_file = 'lagrange_points.png' pyplot.savefig(save_file) print("\nOutput saved in", save_file) pyplot.show() if __name__ == "__main__": gravity = setup_gravity_code() make_effective_iso_potential_plot(gravity) gravity.stop()
2,199
35.666667
70
py
amuse
amuse-main/examples/textbook/hydro_minimal.py
###BOOKLISTSTART1### from amuse.lab import * def main(N, Mtot, Rvir, t_end): converter=nbody_system.nbody_to_si(Mtot, Rvir) gas = new_plummer_gas_model(N, convert_nbody=converter) hydro = Gadget2(converter) hydro.gas_particles.add_particles(gas) Etot_init = hydro.kinetic_energy \ + hydro.potential_energy + hydro.thermal_energy hydro.evolve_model(t_end) write_set_to_file(hydro.particles, "hydro.h5", "hdf5") Ekin = hydro.kinetic_energy Epot = hydro.potential_energy Eth = hydro.thermal_energy Etot = Ekin + Epot + Eth Q = (Ekin+Eth)/Epot dE = (Etot_init-Etot)/Etot com = hydro.gas_particles.center_of_mass() print("T=", hydro.get_time(), "M=", hydro.gas_particles.mass.sum(), end=' ') print("E= ", Etot, "Q= ", Q, "dE=", dE, "CoM=", com.in_(units.RSun)) hydro.stop() ###BOOKLISTSTOP1### def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-N", dest="N", type="int",default = 100, help="number of gas particles [%default]") result.add_option("-t", unit=units.Myr, dest="t_end", type="float", default = 6|units.hour, help="end time of the simulation [%default]") result.add_option("-M", unit=units.MSun, dest="Mtot", type="float", default = 1|units.MSun, help="Mass of the cloud [%default]") result.add_option("-R", unit=units.RSun, dest="Rvir", type="float", default = 1|units.RSun, help="Radius of the cloud [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
1,793
36.375
81
py
amuse
amuse-main/examples/textbook/stellar_minimal.py
""" Minimal routine for running a stellar evolution code """ ###BOOKLISTSTART### from amuse.lab import * def main(m, z, model_time): stellar = MESA() stellar.parameters.metallicity = z stellar.particles.add_particle(Particle(mass=m)) initial_luminosity = stellar.particles.luminosity dt = 1 | units.Myr while stellar.model_time < model_time: stellar.evolve_model(stellar.model_time+dt) print("at T=", stellar.model_time.in_(units.Myr), \ "L(t=0)=", initial_luminosity, \ ", L (t=", stellar.particles.age.in_(units.Myr), \ ")=", stellar.particles.luminosity.in_(units.LSun), \ ", m=", stellar.particles.mass.in_(units.MSun), \ ", R=", stellar.particles.radius.in_(units.RSun)) stellar.stop() ###BOOKLISTSTOP### ###BOOKLISTSTART2### def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-m", unit=units.MSun, dest="m", type="float", default=1.0|units.MSun, help="stellar mass [%default]") result.add_option("-t", unit=units.Myr, dest="model_time", type="float", default=4700.0|units.Myr, help="end time of the simulation [%default]") result.add_option("-z", dest="z", type="float", default=0.02, help="metallicity [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__) ###BOOKLISTSTOP2###
1,592
32.893617
69
py
amuse
amuse-main/examples/textbook/evolve_XiTauPrimary.py
from amuse.lab import * def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-N", dest="Nsph", type="int", default = 20000, help="number of gas particles [%default]") result.add_option("-M", unit=units.MSun, dest="mass", type="float", default = 5.5|units.MSun, help="mass of the star [%default]") result.add_option("-R", unit=units.AU, dest="radius", type="float", default = 0.42|units.AU, help="Size of star [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() ###BOOKLISTSTART1### stellar = MESA() stellar.particles.add_particle(Particle(mass = o.mass)) XiTau = stellar.particles[0] while XiTau.radius<=o.radius: print("Time=", stellar.model_time.in_(units.Myr), stellar.particles.radius.in_(units.AU), stellar.particles.stellar_type) stellar.evolve_model() target_core_mass = XiTau.core_mass print(XiTau) print("Core mass:", XiTau.core_mass.in_(units.MSun)) sph_model = convert_stellar_model_to_SPH( XiTau, o.Nsph, with_core_particle = True, target_core_mass = target_core_mass, do_store_composition = False, base_grid_options=dict(type="fcc") ) core_particle = sph_model.core_particle.as_set() gas_particles = sph_model.gas_particles print("Ngas=", len(gas_particles), "Ncore=", core_particle) write_set_to_file(core_particle, "Hydro_PrimaryStar_XiTau.amuse", "amuse", append_to_file=False) write_set_to_file(gas_particles, "Hydro_PrimaryStar_XiTau.amuse", "amuse") stellar.stop() ###BOOKLISTSTOP1###
1,800
36.520833
129
py
amuse
amuse-main/examples/textbook/merge_two_stars.py
""" Initialize two stars to a certain age and merge them using MMAMS """ import sys import numpy from amuse.lab import * from amuse.plot import plot, xlabel, ylabel from matplotlib import pyplot ###BOOKLISTSTART### def merge_two_stars(Mprim, Msec, t_coll): bodies = Particles(mass=[Mprim, Msec] |units.MSun) stellar = MESA() primary = stellar.particles.add_particles(bodies[0].as_set()) secondary = stellar.particles.add_particles(bodies[1].as_set()) stellar.evolve_model(t_coll) stellar.merge_colliding(primary.copy(), secondary.copy(), MMAMS, return_merge_products=["se"]) radius = stellar.particles[0].get_radius_profile() rho = stellar.particles[0].get_density_profile() stellar.stop() return radius, rho ###BOOKLISTSTOP### 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() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-M", dest="Mprim", type="float",default = 5, help="Mass of the primary star [%default] MSun") result.add_option("-m", dest="Msec", type="float",default = 3, help="Mass of the secondary star [%default] MSun") result.add_option("-t", unit=units.Myr, dest="t_coll", type="float", default = 1.0|units.Myr, help="end time of the simulation [%default] Myr") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() radius, rho = merge_two_stars(**o.__dict__) plot_density_profile(radius, rho)
1,784
34
72
py
amuse
amuse-main/examples/textbook/plot_molecular_cloud_collapse_with_sinks.py
from cooling_class import SimplifiedThermalModel, SimplifiedThermalModelEvolver import numpy from matplotlib import pyplot import matplotlib.cm as cm from amuse.lab import * from amuse.ext.molecular_cloud import molecular_cloud from prepare_figure import single_frame, figure_frame, set_tickmarks from distinct_colours import get_distinct from hydrodynamics_class import Hydro def make_map(sph,N=100,L=1): x,y=numpy.indices( ( N+1,N+1 )) x=L*(x.flatten()-N/2.)/N y=L*(y.flatten()-N/2.)/N z=x*0. vx=0.*x vy=0.*x vz=0.*x x=units.parsec(x) y=units.parsec(y) z=units.parsec(z) vx=units.kms(vx) vy=units.kms(vy) vz=units.kms(vz) rho,rhovx,rhovy,rhovz,rhoe=sph.get_hydro_state_at_point(x,y,z,vx,vy,vz) rho=rho.reshape((N+1,N+1)) return rho def plot_molecular_cloud(filename): print("read file:", filename) bodies = read_set_from_file(filename, "amuse") i = 0 sinks = Particles(0) for bi in bodies.history: if i==0: gas = bi.as_set() print("N=", len(gas)) i+=1 else: sinks = bi.as_set() print("N=", len(sinks)) # print sinks print("N=", len(gas), len(sinks)) #sinks = bodies.history.next() L = 4.4 # if len(sinks): # sinks = sinks.select(lambda r: r.length()<0.5*L|units.parsec,["position"]) #print sinks hydro = Hydro(Fi, gas, sinks) time = 0 | units.Myr # hydro.code.dm_particles.add_particles(sinks) #plot_hydro_and_stars(time, hydro, L=10) plot_hydro(time, hydro, L) def make_stars(cluster_particle): sfe = 0.3 mmean = 1.0|units.MSun N = int(sfe*cluster_particle.mass/mmean) stars = Particles(0) print("N_cluster=", N) if N>0: masses = new_salpeter_mass_distribution(N, 0.3|units.MSun, min(100|units.MSun, cluster_particle.mass)) r = cluster_particle.h_smooth converter=nbody_system.nbody_to_si(masses.sum(),r) stars = new_plummer_model(N, convert_nbody=converter) stars.mass = masses stars.position += cluster_particle.position stars.velocity += cluster_particle.velocity return stars def get_stars_from_molecular_clous(parts): cutoff_density = 10000 | units.amu/units.cm**3 stars = Particles(0) for ip in parts: if ip.rho>cutoff_density: local_stars = make_stars(ip) stars.add_particles(local_stars) return stars def plot_hydro_and_stars(time, sph, L=10): fig=pyplot.figure(figsize=(12,12)) rho=make_map(sph,N=200,L=L) pyplot.imshow(numpy.log10(1.e-5+rho.value_in(units.amu/units.cm**3)), extent=[-L/2,L/2,-L/2,L/2],vmin=1,vmax=5) # subplot.set_title("GMC at zero age") cbar = fig.colorbar(cax, ticks=[4, 7.5, 11], orientation='vertical', fraction=0.045) cbar.set_label('projected density [$amu/cm^3$]', rotation=270) stars = get_stars_from_molecular_clous(sph.gas_particles) if len(stars): #m = 100.0*stars.mass/max(stars.mass) m = 100.0*stars.mass/stars.mass.mean() c = stars.mass/stars.mass.mean() x = -stars.x.value_in(units.parsec) y = stars.y.value_in(units.parsec) pyplot.scatter(x, y, s=m, c=c, lw=0) pyplot.xlim(-L/2., L/2.) pyplot.ylim(-L/2., L/2.) pyplot.title("Molecular cloud at time="+time.as_string_in(units.Myr)) pyplot.xlabel("x [pc]") pyplot.ylabel("x [pc]") pyplot.title("GMC at time="+time.as_string_in(units.Myr)) #pyplot.savefig("GMC_SC.png") pyplot.show() def plot_hydro(time, sph, L=10): x_label = "x [pc]" y_label = "y [pc]" fig = single_frame(x_label, y_label, logx=False, logy=False, xsize=12, ysize=12) gas = sph.code.gas_particles dmp = sph.code.dm_particles rho=make_map(sph,N=200,L=L) cax = pyplot.imshow(numpy.log10(1.e-5+rho.value_in(units.amu/units.cm**3)), extent=[-L/2,L/2,-L/2,L/2],vmin=1,vmax=5, origin="lower") cbar = fig.colorbar(cax, orientation='vertical', fraction=0.045) # cbar.set_label('projected density [$amu/cm^3$]', rotation=270) cm = pyplot.cm.get_cmap('RdBu') # cm = pyplot.cm.jet #gist_ncar if len(dmp): #m = 10.0*dmp.mass/dmp.mass.max() m = 30*numpy.log10(dmp.mass/dmp.mass.min()) c = numpy.sqrt(dmp.mass/dmp.mass.max()) pyplot.scatter(dmp.y.value_in(units.parsec), dmp.x.value_in(units.parsec), c=c, s=m, lw=0, cmap=cm) pyplot.show() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-f", dest="filename", default = "GMC_R2pcN20k_SE_T45Myr.amuse", help="input filename [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() plot_molecular_cloud(o.filename)
4,867
32.115646
137
py
amuse
amuse-main/examples/textbook/star_to_sph.py
import os import os.path import shutil import numpy from amuse.lab import * """ from amuse.units import units, constants from amuse.datamodel import Particles, Particle from amuse.io import write_set_to_file """ from amuse.community.mesa.interface import MESA as stellar_evolution_code from amuse.ext.star_to_sph import convert_stellar_model_to_SPH from amuse.ext.relax_sph import relax def evolve_star(mass, age): stellar = MESA() stellar.parameters.metallicity = 0.02 star = stellar.particles.add_particle(Particle(mass=mass)) stellar.evolve_model(age) return stellar def evolve_star_and_convert_to_sph(stellar, omega, Nsph): new_age = stellar.model_time star = stellar.particles[0] if star.core_mass>zero: with_core_particle = True target_core_mass = coremass else: with_core_particle = False target_core_mass = 0|units.MSun m_sph = (star.mass-target_core_mass)/float(Nsph) print("N_sph=", Nsph, m_sph.in_(units.MSun)) print("Target core mass:", target_core_mass) model = convert_stellar_model_to_SPH( star, Nsph, with_core_particle = with_core_particle, target_core_mass = target_core_mass, do_store_composition = False, base_grid_options=dict(type="fcc") ) print("Final star:", star) age = stellar.model_time M_scale = star.mass R_scale = star.radius stellar.stop() core = model.core_particle print("core", core) if core is None: print("Make zero mass core") core = Particle(mass=0|units.MSun, radius=1|units.RSun) core.position = (0,0,0) | units.AU core.velocity = (0,0,0) | units.kms sph_star = model.gas_particles print("Add Spin to star:", omega) sph_star.add_spin(omega) relaxed_sph_star, core_particles = relax_sph_realization(sph_star, core) return relaxed_sph_star, core_particles, age def relax_sph_realization(sph_star, core): dynamical_timescale = sph_star.dynamical_timescale() converter = nbody_system.nbody_to_si(dynamical_timescale, 1|units.RSun) hydro = Gadget2(converter, number_of_workers=2) hydro.parameters.time_max = 3 * dynamical_timescale hydro.parameters.max_size_timestep = dynamical_timescale / 100 hydro.parameters.time_limit_cpu = 1.0 | units.Gyr t_end_in_t_dyn = 2.5 # Relax for this many dynamical timescales t_end = t_end_in_t_dyn * sph_star.dynamical_timescale(mass_fraction=0.9) n_steps = 250 velocity_damp_factor = 1.0 - (2.0*numpy.pi*t_end_in_t_dyn)/n_steps # Critical damping hydro.gas_particles.add_particles(sph_star) to_framework = hydro.gas_particles.new_channel_to(sph_star) if core.mass>0|units.MSun: hydro.dm_particles.add_particles(core) for i_step, time in enumerate(t_end * numpy.linspace(1.0/n_steps, 1.0, n_steps)): hydro.evolve_model(time) to_framework.copy() hydro.gas_particles.velocity = velocity_damp_factor * hydro.gas_particles.velocity return hydro.gas_particles, hydro.dm_particles def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-N", dest="Nsph", type="int", default = 1000, help="number of SPH particles[%default]") result.add_option("-M", unit=units.MSun, dest="mass", type="float", default = 0.6 | units.MSun, help="stellar mass [%default]") result.add_option("-o", unit=units.day**-1, dest="omega", type="float", default = 24 | units.day**-1, help="stellar rotation [%default]") result.add_option("-t", unit=units.Myr, dest="age", type="float", default = 10 | units.Myr, help="stellar age [%default]") return result if __name__ == "__main__": o, arguments = new_option_parser().parse_args() stellar = evolve_star(o.mass, o.age) star, core, age = evolve_star_and_convert_to_sph(stellar, o.omega, o.Nsph) print("age=", age.in_(units.Myr)) print(star) print(star.mass.sum().in_(units.MSun), core.mass) filename = 'Hydro_M%2.2dMSun.h5'%o.mass.value_in(units.MSun) print(filename) write_set_to_file(star, filename, format='hdf5', append_to_file=False)
4,457
35.243902
90
py
amuse
amuse-main/examples/textbook/plot_gravity.py
import os ###BOOKLISTSTART### from matplotlib import pyplot from amuse.plot import scatter, xlabel, ylabel from amuse.io import read_set_from_file from amuse.units import units 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() ###BOOKLISTSTOP### if __name__ in ('__main__'): try: amusedir = os.environ['AMUSE_DIR'] dir = amusedir+'/examples/textbook/' except: print('Environment variable AMUSE_DIR not set') dir = './' filename = dir+'gravity.h5' particles = read_set_from_file(filename, "hdf5") x = [] y = [] for si in particles.history: x.append(si.x.value_in(units.AU)) y.append(si.y.value_in(units.AU)) plot(x, y)
1,139
23.782609
70
py
amuse
amuse-main/examples/textbook/evolve_triple_with_wind.py
""" N-body integration of N particles with a Salpeter initial mass function between Mmin and Mmax and with stellar evolution with metallicity z. """ import sys import numpy from optparse import OptionParser from prepare_figure import single_frame from distinct_colours import get_distinct from amuse.units import units, constants, nbody_system from amuse.units.quantities import zero from amuse.datamodel import Particle, Particles from amuse.support.console import set_printing_strategy from amuse.io import store from amuse.ext.orbital_elements import new_binary_from_orbital_elements from amuse.ext.orbital_elements import orbital_elements_from_binary from amuse.community.huayno.interface import Huayno from amuse.community.smalln.interface import SmallN from amuse.community.hermite.interface import Hermite from amuse.community.seba.interface import SeBa from amuse.community.sse.interface import SSE def orbital_period(a, Mtot): return 2*numpy.pi*(a**3/(constants.G*Mtot)).sqrt() def semimajor_axis(P, Mtot): return (constants.G*Mtot*P**2/(4*numpy.pi**2))**(1./3) def get_orbital_elements_of_triple(stars): inner_binary = stars[0]+stars[1] outer_binary = Particles(1) outer_binary[0].mass = inner_binary.mass.sum() outer_binary[0].position = inner_binary.center_of_mass() outer_binary[0].velocity = inner_binary.center_of_mass_velocity() outer_binary.add_particle(stars[2]) M1, M2, ain, ein, ta_in, inc_in, lan_in, aop_in \ = orbital_elements_from_binary(inner_binary, G=constants.G) M12, M3, aout, eout, ta_out, outc_out, lan_out, aop_out \ = orbital_elements_from_binary(outer_binary, G=constants.G) return ain, ein, aout, eout def evolve_triple_with_wind(M1, M2, M3, Pora, Pin_0, ain_0, aout_0, ein_0, eout_0, t_end, nsteps, scheme, dtse_fac): import random from amuse.ext.solarsystem import get_position print("Initial masses:", M1, M2, M3) t_stellar = 4.0|units.Myr triple = Particles(3) triple[0].mass = M1 triple[1].mass = M2 triple[2].mass = M3 stellar = SeBa() stellar.particles.add_particles(triple) channel_from_stellar = stellar.particles.new_channel_to(triple) stellar.evolve_model(t_stellar) channel_from_stellar.copy_attributes(["mass"]) M1 = triple[0].mass M2 = triple[1].mass M3 = triple[2].mass print("T=", stellar.model_time.in_(units.Myr)) print("M=", stellar.particles.mass.in_(units.MSun)) print("Masses at time T:", M1, M2, M3) # Inner binary tmp_stars = Particles(2) tmp_stars[0].mass = M1 tmp_stars[1].mass = M2 if Pora == 1: ain_0 = semimajor_axis(Pin_0, M1+M2) else: Pin_0 = orbital_period(ain_0, M1+M2) print('ain_0 =', ain_0) print('M1+M2 =', M1+M2) print('Pin_0 =', Pin_0.value_in(units.day), '[day]') #print 'semi:', semimajor_axis(Pin_0, M1+M2).value_in(units.AU), 'AU' #print 'period:', orbital_period(ain_0, M1+M2).value_in(units.day), '[day]' dt = 0.1*Pin_0 ma = 180 inc = 30 aop = 180 lon = 0 r, v = get_position(M1, M2, ein_0, ain_0, ma, inc, aop, lon, dt) tmp_stars[1].position = r tmp_stars[1].velocity = v tmp_stars.move_to_center() # Outer binary r, v = get_position(M1+M2, M3, eout_0, aout_0, 0, 0, 0, 0, dt) tertiary = Particle() tertiary.mass = M3 tertiary.position = r tertiary.velocity = v tmp_stars.add_particle(tertiary) tmp_stars.move_to_center() triple.position = tmp_stars.position triple.velocity = tmp_stars.velocity Mtriple = triple.mass.sum() Pout = orbital_period(aout_0, Mtriple) print("T=", stellar.model_time.in_(units.Myr)) print("M=", stellar.particles.mass.in_(units.MSun)) print("Pout=", Pout.in_(units.Myr)) converter = nbody_system.nbody_to_si(triple.mass.sum(), aout_0) gravity = Hermite(converter) gravity.particles.add_particles(triple) channel_from_framework_to_gd = triple.new_channel_to(gravity.particles) channel_from_gd_to_framework = gravity.particles.new_channel_to(triple) Etot_init = gravity.kinetic_energy + gravity.potential_energy Etot_prev = Etot_init gravity.particles.move_to_center() time = 0.0 | t_end.unit ts = t_stellar + time ain, ein, aout, eout = get_orbital_elements_of_triple(triple) print("Triple elements t=", time, \ "inner:", triple[0].mass, triple[1].mass, ain, ein, \ "outer:", triple[2].mass, aout, eout) dt_diag = t_end/float(nsteps) t_diag = dt_diag t = [time.value_in(units.Myr)] smai = [ain/ain_0] ecci = [ein/ein_0] smao = [aout/aout_0] ecco = [eout/eout_0] ain = ain_0 def advance_stellar(ts, dt): E0 = gravity.kinetic_energy + gravity.potential_energy ts += dt stellar.evolve_model(ts) channel_from_stellar.copy_attributes(["mass"]) channel_from_framework_to_gd.copy_attributes(["mass"]) return ts, gravity.kinetic_energy + gravity.potential_energy - E0 def advance_gravity(tg, dt): tg += dt gravity.evolve_model(tg) channel_from_gd_to_framework.copy() return tg while time < t_end: Pin = orbital_period(ain, triple[0].mass+triple[1].mass) dt = dtse_fac*Pin dt *= random.random() if scheme == 1: ts, dE_se = advance_stellar(ts, dt) time = advance_gravity(time, dt) elif scheme == 2: time = advance_gravity(time, dt) ts, dE_se = advance_stellar(ts, dt) else: dE_se = zero #ts, dE_se = advance_stellar(ts, dt/2) time = advance_gravity(time, dt) #ts, dE = advance_stellar(ts, dt/2) #dE_se += dE if time >= t_diag: t_diag = time + dt_diag Ekin = gravity.kinetic_energy Epot = gravity.potential_energy Etot = Ekin + Epot dE = Etot_prev - Etot Mtot = triple.mass.sum() print("T=", time, end=' ') print("M=", Mtot, "(dM[SE]=", Mtot/Mtriple, ")", end=' ') print("E= ", Etot, "Q= ", Ekin/Epot, end=' ') print("dE=", (Etot_init-Etot)/Etot, "ddE=", (Etot_prev-Etot)/Etot, end=' ') print("(dE[SE]=", dE_se/Etot, ")") Etot_init -= dE Etot_prev = Etot ain, ein, aout, eout = get_orbital_elements_of_triple(triple) print("Triple elements t=", (4|units.Myr) + time, \ "inner:", triple[0].mass, triple[1].mass, ain, ein, \ "outer:", triple[2].mass, aout, eout) t.append(time.value_in(units.Myr)) smai.append(ain/ain_0) ecci.append(ein/ein_0) smao.append(aout/aout_0) ecco.append(eout/eout_0) if eout > 1.0 or aout <= zero: print("Binary ionized or merged") break gravity.stop() stellar.stop() return t, smai, ecci, smao, ecco def main(M1, M2, M3, Pora, Pin, ain, aout, ein, eout, t_end, nsteps, scheme, dtse_fac): from matplotlib import pyplot x_label = "$a/a_{0}$" y_label = "$e/e_{0}$" fig = single_frame(x_label, y_label, logx=False, logy=False, xsize=10, ysize=8) color = get_distinct(4) if scheme == 0: srange = [1,2,3] else: srange = [scheme] i = 0 for s in srange: time, ai, ei, ao, eo = evolve_triple_with_wind(M1, M2, M3, Pora, Pin, ain, aout, ein, eout, t_end, nsteps, s, dtse_fac) if i == 0: pyplot.plot(ai, ei, c=color[0], label='inner') pyplot.plot(ao, eo, c=color[1], label='outer') i = 1 else: pyplot.plot(ai, ei, c=color[0]) pyplot.plot(ao, eo, c=color[1]) pyplot.legend(loc='best', ncol=1, shadow=False, fontsize=20) #save_file = 'evolve_triple_with_wind.png' save_file = 'evolve_triple_with_wind' \ +'_s={:d}_dtse={:.3f}'.format(scheme, dtse_fac) \ +'.png' pyplot.savefig(save_file) print('\nSaved figure in file', save_file,'\n') pyplot.show() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-n", dest="nsteps", type="int", default = 10000, help="diagnostic time steps [%default]") result.add_option("--M1", unit=units.MSun, dest="M1", type="float", default = 60 | units.MSun, help="Primary mass [%default]") result.add_option("--M2", unit=units.MSun, dest="M2", type="float", default = 30 | units.MSun, help="secondary mass [%default]") result.add_option("--M3", unit=units.MSun, dest="M3", type="float", default = 20 | units.MSun, help="secondary mass [%default]") result.add_option("--Pora", dest="Pora", type="int", default = 1, help="period (1) or semimajor axis (2) [%default]") result.add_option("--Pin", unit=units.day, dest="Pin", type="float", default = 19|units.day, help="orbital period [%default]") result.add_option("--ain", unit=units.AU, dest="ain", type="float", default = 0.63|units.AU, help="orbital separation [%default]") result.add_option("--aout", unit=units.AU, dest="aout", type="float", default = 100|units.AU, help="orbital separation [%default]") result.add_option("--ein", dest="ein", type="float", default = 0.2, help="orbital eccentricity [%default]") result.add_option("--eout", dest="eout", type="float", default = 0.6, help="orbital eccentricity [%default]") result.add_option("-t", unit=units.Myr, dest="t_end", type="float", default = 0.55 | units.Myr, help="end time of the simulation [%default]") result.add_option("-s", dest="scheme", type="int", default = 3, help="integration scheme [%default]") result.add_option("--dtse", dest="dtse_fac", type="float", default = 0.1, help="stellar mass-loss time step fraction [%default]") return result if __name__ in ('__main__', '__plot__'): set_printing_strategy("custom", preferred_units = [units.MSun, units.AU, units.Myr], precision = 12, prefix = "", separator = " [", suffix = "]") o, arguments = new_option_parser().parse_args() main(**o.__dict__)
11,346
34.570533
88
py
amuse
amuse-main/examples/textbook/plot_stellar_structure.py
from matplotlib import pyplot import numpy from amuse.lab import * from amuse.plot import plot, scatter from prepare_figure import single_frame, figure_frame, set_tickmarks from distinct_colours import get_distinct def stellar_density_profile_at_time(mass, time): stellar = MESA() stellar.parameters.metallicity = 0.02 star = stellar.particles.add_particle(Particle(mass=mass)) stellar.evolve_model(time) rho = star.get_density_profile(star.get_number_of_zones()) L = star.get_luminosity_profile(star.get_number_of_zones()) m = star.get_cumulative_mass_profile(star.get_number_of_zones()) * mass stellar.stop() return m, L, rho if __name__ == "__main__": x_label = "L [LSun]" y_label = "density [$g/cm^{3}$]" figure = single_frame(x_label, y_label, logx=True, logy=True, xsize=12, ysize=10) mass = [1, 1, 5, 5, 10, 10] | units.MSun age = [1, 10000, 1, 90, 1, 20] | units.Myr c = get_distinct(3) color = [] ls = [] for ci in c: color.append(ci) color.append(ci) ls.append("-") ls.append("--") symbol = ['v', 'v', 'o', 'o', '^', '^'] i = 0 for imass in range(len(mass)): dm = 0.2*mass[imass] time = age[imass] m, L, rho = stellar_density_profile_at_time(mass[imass], time) pyplot.plot(L.value_in(units.LSun), rho.value_in(units.g/units.cm**3), lw=4, c=color[imass], label='$10M_\odot$', ls=ls[imass]) mlim = dm for mi in range(len(m)): if m[mi]>mlim: mlim += dm print(mi, len(L), len(rho)) pyplot.scatter(L[mi].value_in(units.LSun), rho[mi].value_in(units.g/units.cm**3), c=color[imass], s=150, marker=symbol[imass], lw=0) pyplot.scatter(L[-1].value_in(units.LSun), rho[-1].value_in(units.g/units.cm**3), c=color[imass], s=150, marker=symbol[imass], lw=0) pyplot.xlabel(x_label) pyplot.ylabel(y_label) save_file = 'fig_1_5_10_MSun_stellar_core_luminosity' pyplot.savefig(save_file) print('\nSaved figure in file', save_file,'\n') pyplot.show()
2,317
32.594203
76
py
amuse
amuse-main/examples/textbook/evolve_star_sph_evolve.py
import os import os.path import shutil import numpy from amuse.lab import * from amuse.community.mesa.interface import MESA as stellar_evolution_code from amuse.ext.star_to_sph import convert_stellar_model_to_SPH from amuse.ext.sph_to_star import convert_SPH_to_stellar_model from matplotlib import pyplot def plot_clumps(groups): number_of_particles_in_group = [] fraction_of_mass_in_group = [] # number_of_particles_in_group.append(len(group)) # fraction = (group.mass.sum()/total_mass) # fraction_of_mass_in_group.append(fraction) print("N=", len(groups)) ci = ['r', 'b', 'g', 'k'] figure = pyplot.figure(figsize= (12,6)) i = 0 alpha = 1 sizes = 50 for group in groups: pyplot.scatter(group.x.value_in(units.RSun), group.y.value_in(units.RSun), sizes, ci[i], edgecolors = "none", alpha = alpha) # pyplot.scatter( # group.x.value_in(units.RSun), # group.y.value_in(units.RSun), # s = 1,#group.mass.value_in(units.MSun), # c = ci[i] # ) i+=1 pyplot.xlabel('x (AU)') pyplot.ylabel('y (A*)') # pyplot.xlim(-30, 30) # pyplot.ylim(-30, 30) pyplot.show() def find_clumps(particles, unit_converter): hop = Hop(unit_converter) hop.particles.add_particles(particles) hop.calculate_densities() mean_densty = hop.particles.density.mean() hop.parameters.peak_density_threshold = mean_densty hop.parameters.saddle_density_threshold = 0.99*mean_densty hop.parameters.outer_density_threshold = 0.01*mean_densty # print "Peak density treshold:", hop.do_hop() result = [x.get_intersecting_subset_in(particles) for x in hop.groups()] hop.stop() return result def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-f", dest="filename", default = "hydro_triple_gas.hdf5", help="input filename [%default]") result.add_option("-t", unit=units.Myr, dest="time", type="float", default = 1|units.Myr, help="evolution time scale [%default]") result.add_option("-M", unit=units.MSun, dest="Mprim", type="float", default = 3|units.MSun, help="stellar mass [%default]") return result if __name__ == "__main__": set_printing_strategy("custom", #nbody_converter = converter, preferred_units = [units.MSun, units.RSun, units.Myr], precision = 11, prefix = "", separator = " [", suffix = "]") o, arguments = new_option_parser().parse_args() print("initialize star") stellar_evolution = EVtwin() stellar_evolution.particles.add_particle(Particle(mass=o.Mprim)) stellar_evolution.evolve_model(o.time) particles = convert_stellar_model_to_SPH( stellar_evolution.particles[0], 500, seed=12345 ).gas_particles stellar_evolution.stop() from amuse.units.generic_unit_converter import ConvertBetweenGenericAndSiUnits print("convert star to SPH") converter = nbody_system.nbody_to_si(1|units.hour, 1|units.RSun) hydrodynamics = Gadget2(converter) hydrodynamics.gas_particles.add_particles(particles) hydrodynamics.evolve_model(1.0|units.s) hydrodynamics.gas_particles.copy_values_of_attributes_to(["density", "u", "pressure"], particles) hydrodynamics.stop() print("convert SPH to stellar model") model = convert_SPH_to_stellar_model(particles) #stellar_evolution = MESA() print("initiate stellar evolution model") stellar_evolution = EVtwin(redirect="none") stellar_evolution.new_particle_from_model(model, 0.0|units.Myr) print("star:", stellar_evolution.particles) print("evolve star") stellar_evolution.evolve_model(2*o.time) print(stellar_evolution.particles)
4,063
32.04065
132
py
amuse
amuse-main/examples/textbook/kelvin_helmholtz.py
""" Runs the Kelvin-Helmholtz Instability problem in two dimensions with Athena. """ import numpy from matplotlib import pyplot #from amuse.lab import * from amuse.community.athena.interface import Athena from amuse.community.capreole.interface import Capreole from amuse.units.generic_unit_system import * from amuse.datamodel import Grid GAMMA = 1.4 DIMENSIONS_OF_MESH = (200,200,1) PERTUBATION_AMPLITUDE = 0.1 | speed def new_instance_of_athena_code(number_of_workers=1): result=Athena(number_of_workers = number_of_workers) result.parameters.gamma = GAMMA result.parameters.courant_number=0.8 set_parameters(result) return result def new_instance_of_capreole_code(number_of_workers=1): result=Capreole(number_of_workers=number_of_workers) result.initialize_code() result.parameters.x_boundary_conditions = ("reflective","reflective") result.parameters.y_boundary_conditions = ("outflow","outflow") result.parameters.z_boundary_conditions = ("reflective","reflective") set_parameters(result) return result def new_instance_of_mpiamrvac_code(number_of_workers=1): from amuse.community.mpiamrvac.interface import MpiAmrVac #result=MpiAmrVac(number_of_workers=number_of_workers) #, redirection="none") result=MpiAmrVac(mode="2d", number_of_workers=number_of_workers) result.set_parameters_filename(result.default_parameters_filename) result.initialize_code() result.parameters.maximum_number_of_grid_levels = 3 # result.parameters.spatial_discretization_method = 'tvdmu' # result.parameters.predictor_step_discretization_method = 'tvdmu' # result.parameters.entropy_type = 'powell' # result.parameters.courant_number = 0.8 # result.parameters.x_boundary_conditions = ("cont","cont") # result.parameters.y_boundary_conditions = ("cont","cont") # result.parameters.z_boundary_conditions = ("cont","cont") result.parameters.length_x = 1 | length result.parameters.length_y = 1 | length result.parameters.length_z = 1 | length result.parameters.x_boundary_conditions = ("periodic","periodic") result.parameters.y_boundary_conditions = ("periodic","periodic") result.parameters.z_boundary_conditions = ("periodic","periodic") return result def set_parameters(instance): instance.parameters.mesh_size = DIMENSIONS_OF_MESH instance.parameters.length_x = 1 | length instance.parameters.length_y = 1 | length instance.parameters.length_z = 1 | length instance.parameters.x_boundary_conditions = ("periodic","periodic") instance.parameters.y_boundary_conditions = ("periodic","periodic") instance.parameters.z_boundary_conditions = ("periodic","periodic") def new_grid(): grid = Grid.create(DIMENSIONS_OF_MESH, [1,1,1] | length) clear_grid(grid) return grid def clear_grid(grid): density = mass / length**3 momentum = speed * density energy = mass / (time**2 * length) grid.rho = 0.0 | density grid.rhovx = 0.0 | momentum grid.rhovy = 0.0 | momentum grid.rhovz = 0.0 | momentum grid.energy = 0.0 | energy return grid def initialize_grid(grid): vx = 0.5 | speed p = 2.5 | (mass / (length * time**2)) halfway = DIMENSIONS_OF_MESH[0]/2 - 1 outerregion = numpy.logical_or(grid.y <= 0.25 | length, grid.y >= 0.75 | length) innerregion = numpy.logical_and(grid.y > 0.25 | length, grid.y < 0.75 | length) grid[outerregion].rho = 1 | density grid[outerregion].rhovx = vx * grid[outerregion].rho grid[innerregion].rho = 2.0 | density grid[innerregion].rhovx = -vx * grid[innerregion].rho grid.energy = p / (GAMMA - 1) def pertubate_grid(grid): grid.rhovx += grid.rho * PERTUBATION_AMPLITUDE * (numpy.random.rand(*grid.shape) - 0.5) grid.rhovy += grid.rho * PERTUBATION_AMPLITUDE * (numpy.random.rand(*grid.shape) - 0.5) grid.energy += 0.5 * (grid.rhovx ** 2 + grid.rhovy ** 2 + grid.rhovz ** 2) / grid.rho def simulate_kelvin_helmholtz_instability(end_time): # instance=new_instance_of_athena_code() # instance=new_instance_of_capreole_code() instance=new_instance_of_mpiamrvac_code() # set_parameters(instance) print("setup grid") for x in instance.itergrids(): inmem = x.copy() clear_grid(inmem) initialize_grid(inmem) pertubate_grid(inmem) from_model_to_code = inmem.new_channel_to(x) from_model_to_code.copy() print("start evolve") dt = end_time / 10.0 t = dt while t < end_time: instance.evolve_model(t) print(("time : ", t)) t += dt print("copying results") result = [] for x in instance.itergrids(): result.append(x.copy()) print("terminating code") instance.stop() return result def plot_grid(grid): rho = grid.rho[...,0].value_in(density) figure = pyplot.figure(figsize=(6,6)) plot = figure.add_subplot(1,1,1) plot.imshow(rho, origin = 'lower', cmap='jet') figure.savefig('kelvin_helmholtz.png') pyplot.show() if __name__ == "__main__": grids = simulate_kelvin_helmholtz_instability(1.0 | time) plot_grid(grids[0])
5,318
32.45283
91
py
amuse
amuse-main/examples/textbook/gravity_minimal.py
from amuse.lab import Hermite from amuse.lab import nbody_system from amuse.lab import new_plummer_model def gravity_minimal(N, t_end): stars = new_plummer_model(N) gravity = Hermite() gravity.particles.add_particles(stars) initial_total_energy = gravity.kinetic_energy + gravity.potential_energy gravity.evolve_model(t_end) total_energy = gravity.kinetic_energy + gravity.potential_energy energy_error = (initial_total_energy-total_energy)/initial_total_energy print("model time =", gravity.model_time) print("total mass = ", stars.total_mass(), "total energy = ", total_energy) print("relative energy error =", energy_error) if __name__ in ('__main__'): N = 100 t_end = 1 | nbody_system.time gravity_minimal(N, t_end)
798
27.535714
79
py
amuse
amuse-main/examples/textbook/1992AA...260..161H.py
import math import numpy from amuse.lab import * from amuse.ext.protodisk import ProtoPlanetaryDisk from optparse import OptionParser from amuse.couple import bridge def main(Mstar=1, Ndisk=100, Mdisk= 0.001, Rmin=1, Rmax=100, t_end=10, n_steps=10, filename="nbody.hdf5"): # numpy.random.seed(111) Mstar = Mstar | units.MSun Mdisk = Mdisk | units.MSun Rmin = Rmin | units.AU Rmax = Rmax | units.AU t_end = t_end | units.yr # converter=nbody_system.nbody_to_si(Mdisk, Rmax) converter=nbody_system.nbody_to_si(Mstar, Rmin) disk = ProtoPlanetaryDisk(Ndisk, convert_nbody=converter, densitypower=1.5, Rmin=Rmin.value_in(units.AU), Rmax=Rmax.value_in(units.AU),q_out=1.0, discfraction=1.0).result disk.move_to_center() center_of_mass = disk.center_of_mass() print(center_of_mass) a_bump = 50 Rbump = 10 | units.AU bump_location = center_of_mass + ([0, a_bump, 0] | units.AU) bump_particles = disk.select(lambda r: (center_of_mass-r).length()<Rbump,["position"]) Mbump =bump_particles.mass.sum() Nbump = len(bump_particles) print("Nbump=", len(bump_particles), Mbump, Rbump, Nbump) print("Mass =", Mstar, Mdisk, disk.mass.sum().in_(units.MSun), disk.mass.sum()/Mstar) bump = new_plummer_gas_model(Nbump, convert_nbody=nbody_system.nbody_to_si(0.1*Mbump, Rbump)) a_bump = a_bump | units.AU bump.x += a_bump r_bump = a_bump inner_particles = disk.select(lambda r: (center_of_mass-r).length()<a_bump,["position"]) M_inner = inner_particles.mass.sum() + Mstar v_circ = (constants.G*M_inner*(2./r_bump - 1./a_bump)).sqrt().value_in(units.kms) bump.velocity += [0, v_circ, 0] | units.kms print("MM=", M_inner, v_circ) disk.add_particles(bump) disk.h_smooth= Rmin/(Ndisk+Nbump) star=Particles(1) star.mass=Mstar star.radius=1. | units.RSun star.position = [0, 0, 0] | units.AU star.velocity = [0, 0, 0] | units.kms # star2=Particles(1) # star2.mass=Mstar # star2.radius=1. | units.RSun # star2.position = [1, 0, 0] | units.AU # star2.velocity = [0, 30, 0] | units.kms hydro=Fi(converter) # hydror = Fi(channel_type="ibis", hostname="galgewater") hydro.parameters.use_hydro_flag=True hydro.parameters.radiation_flag=False hydro.parameters.self_gravity_flag=True hydro.parameters.gamma=1. hydro.parameters.isothermal_flag=True hydro.parameters.integrate_entropy_flag=False hydro.parameters.timestep=0.125 | units.yr hydro.gas_particles.add_particles(disk) gravity = Hermite(converter) gravity.particles.add_particles(star) # gravity.particles.add_particles(star2) # gravity.particles.move_to_center() channel_from_gravity_to_framework = gravity.particles.new_channel_to(star) channel_from_hydro_to_framework = hydro.particles.new_channel_to(disk) # make a repository of the star+disk particles in moving bodies # moving_bodies = star.union(disk) moving_bodies = ParticlesSuperset([star, disk]) moving_bodies.move_to_center() write_set_to_file(moving_bodies, filename, 'hdf5') gravity_hydro = bridge.Bridge(use_threading=False) gravity_hydro.add_system(gravity, (hydro,) ) gravity_hydro.add_system(hydro, (gravity,) ) Etot_init = gravity_hydro.kinetic_energy + gravity_hydro.potential_energy Etot_prev = Etot_init time = 0.0 | t_end.unit dt = t_end/float(n_steps) gravity_hydro.timestep = dt/10. while time < t_end: time += dt gravity_hydro.evolve_model(time) Etot_prev_se = gravity_hydro.kinetic_energy + gravity_hydro.potential_energy channel_from_gravity_to_framework.copy() channel_from_hydro_to_framework.copy() write_set_to_file(moving_bodies, filename, 'hdf5') Ekin = gravity_hydro.kinetic_energy Epot = gravity_hydro.potential_energy Etot = Ekin + Epot print("T=", time, end=' ') print("E= ", Etot, "Q= ", Ekin/Epot, end=' ') print("dE=", (Etot_init-Etot)/Etot, "ddE=", (Etot_prev-Etot)/Etot) print("star=", star) Etot_prev = Etot gravity_hydro.stop() def new_option_parser(): result = OptionParser() result.add_option("-n", dest="n_steps", type="float", default = 10, help="number of diagnostics time steps [10]") result.add_option("-f", dest="filename", default = "gravhydro.hdf5", help="output filename [gravhydro.hdf5]") result.add_option("--Ndisk", dest="Ndisk", type="int",default = 100, help="number of disk particles [100]") result.add_option("--Mstar", dest="Mstar", type="float",default = 1, help="stellar mass [1] MStar") result.add_option("--Mdisk", dest="Mdisk", type="float",default = 0.001, help="disk mass [0.001] MStar") result.add_option("--Rmin", dest="Rmin", type="float",default = 1.0, help="minimal disk radius [1] in AU") result.add_option("--Rmax", dest="Rmax", type="float",default = 100, help="maximal disk radius [150] in AU") result.add_option("-t", dest="t_end", type="float", default = 1.0, help="end time of the simulation [1] year") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
5,533
36.14094
106
py
amuse
amuse-main/examples/textbook/supernova_IIp_Lightcurve.py
## multi-component fits for various supernovae from ## https://arxiv.org/pdf/1404.2004.pdf import numpy from amuse.lab import * #SN 2012au #SN 2013ej class Supernova_Ibc: def __init__(self, tstart=0|units.day): #SN2005hm self.mass = 6 | units.MSun self.A = 113.38 #muJy self.A = (6.7e+42) | units.erg/units.s self.C = 2.461 #muJy self.t0 = tstart self.tfall = 2.54 | units.day self.trise = 5.61 | units.day def luminosity_at_time(self, time): if time > self.t0: F = self.A * numpy.exp(-(time-self.t0)/self.tfall)\ / (1 + numpy.exp(-(time-self.t0)/self.trise)) else: F = 6.4e-5 * self.A return F class Supernova_IIp: def __init__(self, name, tstart=0|units.day): self.tstart = tstart self.t0 = 0 self.particle = Particle() self.set_supernova_parameters(name) self.print_parameters() def print_parameters(self): print("Supernova parameters: ") print("Name=", self.name) print("Etot = ", self.Etot.in_(units.erg)) print("Lpeak= ", self.Lpeak.in_(units.LSun)) print("Mass parameters:", self.Mp, self.A, self.B1, self.B2, \ self.BdN, self.BdC) print("time-scales parameters:", self.t1, self.tp, self.t2, self.td) def set_supernova_parameters(self, name): self.name = name if "12bku" in name: print("Supernova template: PS1-12bku") self.mass = 20.0 | units.MSun self.Etot = 6.84e+51 | units.erg self.Mp = 2.46 self.Lpeak= ((10**42.62)|units.erg/units.s)/self.Mp self.A= numpy.exp(-0.9) self.B1=numpy.exp(-0.5) self.B2=numpy.exp(-3.5) self.BdN=numpy.exp(-3.0) self.BdC=numpy.exp(-5.3) self.t1=1.0 self.tp=5.0 self.t2=105.0 self.td=10.0 elif "11aof" in name: print("Supernova template: PS1-11aof") self.mass = 23.5 | units.MSun self.Etot = 6.84e+51 | units.erg self.Mp = 2.05 self.Lpeak= 10**43.06 |units.erg/units.s self.A= numpy.exp(-1) self.B1=numpy.exp(-6) self.B2=numpy.exp(-3.8) self.BdN=numpy.exp(-3.0) self.BdC=numpy.exp(-4.9) self.t1=1. self.tp=25. self.t2=105. self.td=10. elif "10a" in name: #for SN PS1-10a print("Supernova template: PS1-10a (default)") self.mass = 6 | units.MSun self.Etot = 6.84e+51 | units.erg self.Mp = 2.1 self.Lpeak= 10**42.36 |units.erg/units.s self.A= numpy.exp(-1) self.B1=numpy.exp(-2.4) self.B2=numpy.exp(-3.1) self.BdN=numpy.exp(-2.9) self.BdC=numpy.exp(-5.0) self.t1=1. self.tp=5. self.t2=106. self.td=10. else: print("Supernova template: PS1-10a (default)") self.mass = 20 | units.MSun self.Etot = 6.84e+51 | units.erg self.Mp = 2.1 self.Lpeak= 10**42.36 |units.erg/units.s self.A= numpy.exp(-1) self.B1=numpy.exp(-2.4) self.B2=numpy.exp(-3.1) self.BdN=numpy.exp(-2.9) self.BdC=numpy.exp(-5.0) self.t1=1. self.tp=5. self.t2=106. self.td=10. # def supernova_IIp_lightcurve(self, time): def luminosity_at_time(self, time): t = time.value_in(units.day) - self.tstart.value_in(units.day) L0 = 6.4e-5 L = 0 if t <= self.t0: L = L0 elif t < self.t0+self.t1: L = L0 + self.M1() * (t/self.t1)**self.A elif t < self.t0+self.t1+self.tp: L = L0 + self.M1() * numpy.exp(self.B1*(t-self.t1)) elif t < self.t0+self.t1+self.tp+self.t2: L = L0 + self.Mp * numpy.exp(-self.B2*(t-(self.t1+self.tp))) elif t < self.t0+self.t1+self.tp+self.t2+self.td: L = L0 + self.M2() \ * numpy.exp(-self.BdN*(t-(self.t1+self.t2+self.tp))) elif t>=self.t0+self.t1+self.tp+self.t2+self.td: L = self.Md() \ * numpy.exp(-self.BdC*(t-(self.t1+self.t2+self.tp+self.td))) return self.Lpeak * L def M1(self): return self.Mp / numpy.exp(self.B1*self.tp) def M2(self): return self.Mp * numpy.exp(-self.B2*self.t2) def Md(self): return self.M2() * numpy.exp(-self.BdN*self.td) if __name__ in ('__main__', '__plot__'): PS1_12bku = Supernova_IIp("12bku", 10|units.day) SN2005hm = Supernova_Ibc(10|units.day) PS1_11aof = Supernova_IIp("11aof", 10|units.day) PS1_10a = Supernova_IIp("10a", 10|units.day) SN2005hm = Supernova_Ibc(10|units.day) t = 10**numpy.arange(-2, 2.5, 0.001) | units.day LIb = [] | units.erg/units.s L12bku = [] | units.erg/units.s L10a = [] | units.erg/units.s Laof = [] | units.erg/units.s for ti in t: LIb.append(SN2005hm.luminosity_at_time(ti)) L10a.append(PS1_10a.luminosity_at_time(ti)) L12bku.append(PS1_12bku.luminosity_at_time(ti)) Laof.append(PS1_11aof.luminosity_at_time(ti)) L10a = numpy.log10(L10a.value_in(units.LSun)) L12bku = numpy.log10(L12bku.value_in(units.LSun)) LIb = numpy.log10(LIb.value_in(units.LSun)) Laof = numpy.log10(Laof.value_in(units.LSun)) from matplotlib import pyplot pyplot.scatter(t.value_in(units.day), LIb) pyplot.plot(t.value_in(units.day), L10a, c='r') pyplot.plot(t.value_in(units.day), L12bku, c='b') pyplot.plot(t.value_in(units.day), Laof, c='g') pyplot.show()
5,884
34.029762
77
py
amuse
amuse-main/examples/textbook/plot_stellar_evolution_track.py
from matplotlib import pyplot import numpy from amuse.lab import * from prepare_figure import single_frame, figure_frame, set_tickmarks from distinct_colours import get_distinct def get_stellar_track(mass): stars = Particles(1) stars[0].mass = mass stellar = SSE() stellar.particles.add_particles(stars) attributes = ["temperature", "luminosity", "stellar_type"] to_framework = stellar.particles.new_channel_to(stars, attributes=attributes, target_names=attributes) t = [] | units.Myr T = [] | units.K L = [] | units.LSun stp = [] | units.stellar_type Helium_White_Dwarf = 10 | units.stellar_type # stop here while stellar: stellar.evolve_model() to_framework.copy() if stars[0].stellar_type >= Helium_White_Dwarf: stellar.stop() stellar = False else: t.append(stellar.model_time) T.append(stars[0].temperature) L.append(stars[0].luminosity) stp.append(stars[0].stellar_type) #if mass == 1|units.MSun: # print 'luminosity =', stars[0].luminosity # print 'temperature =', stars[0].temperature # print 'stellar type =', stars[0].stellar_type print(stp[-1], stars[0].stellar_type) print(stp) return t, T, L, stp sigma = constants.Stefan_hyphen_Boltzmann_constant def stellar_radius(L, T): return numpy.sqrt(L/(4*numpy.pi*sigma*T**4)) def stellar_luminosity(R, T): return 4*numpy.pi*R**2*sigma*T**4 def stellar_temperature(R, L): return (L/(4*numpy.pi*sigma*R**2))**(1./4.) def get_color_based_on_stellar_type(istp): color = get_distinct(5) if istp.value_in(units.stellar_type) < 2: c = color[0] elif istp.value_in(units.stellar_type) < 6: c = color[3] else: c = color[4] return c if __name__ == "__main__": x_label = "T [$K$]" y_label = "L [$L_\odot$]" figure = single_frame(x_label, y_label, logx=True, logy=True, xsize=12, ysize=10) pyplot.xlim(1e+6, 1e+3) pyplot.ylim(1.e-1, 3e+5) L = [1, 1.e+5] | units.LSun T = stellar_temperature(0.01|units.RSun, L) pyplot.plot(T.value_in(units.K), L.value_in(units.LSun), lw=1, c='k') pyplot.text(9e+5, 6.e+4, '$0.1 R_\odot$', rotation=-60) L = [1, 1.e+5] | units.LSun T = stellar_temperature(1|units.RSun, L) pyplot.plot(T.value_in(units.K), L.value_in(units.LSun), lw=1, c='k') pyplot.text(1.7e+4, 80, '$1 R_\odot$', rotation=-60) L = [1, 1.e+5] | units.LSun T = stellar_temperature(100|units.RSun, L) pyplot.plot(T.value_in(units.K), L.value_in(units.LSun), lw=1, c='k') pyplot.text(2.85e+3, 600, '$100 R_\odot$', rotation=-60) t, T, L, stp = get_stellar_track(1|units.MSun) for i in range(len(T)-2): c = get_color_based_on_stellar_type(stp[i]) pyplot.plot(T[i:i+2].value_in(units.K), L[i:i+2].value_in(units.LSun), lw=4, c=c, label='$1M_\odot$') t, T, L, stp = get_stellar_track(5|units.MSun) pyplot.plot(T.value_in(units.K), L.value_in(units.LSun), lw=1, c='k') for i in range(len(T)-2): c = get_color_based_on_stellar_type(stp[i]) pyplot.plot(T[i:i+2].value_in(units.K), L[i:i+2].value_in(units.LSun), lw=6, c=c, label='$5M_\odot$') t, T, L, stp = get_stellar_track(20|units.MSun) pyplot.plot(T.value_in(units.K), L.value_in(units.LSun), lw=1, c='k') for i in range(len(T)-2): c = get_color_based_on_stellar_type(stp[i]) pyplot.plot(T[i:i+2].value_in(units.K), L[i:i+2].value_in(units.LSun), lw=4, c=c, label='$20M_\odot$') Ttext = 700000 Ltext = 0.1 stellar_type = ["", "main sequence", "giant", "remnant"] dL = 2.0 i = 0 for sti in range(len(stellar_type)): if sti <= 1: c = get_color_based_on_stellar_type(1|units.stellar_type) elif sti == 2: c = get_color_based_on_stellar_type(5|units.stellar_type) else: c = get_color_based_on_stellar_type(10|units.stellar_type) pyplot.text(Ttext, dL**sti*Ltext, stellar_type[sti], color=c, fontsize=24) save_file = 'fig_stellar_evolution_track.png' pyplot.savefig(save_file) print('\nSaved figure in file', save_file,'\n') pyplot.show()
4,530
34.124031
78
py
amuse
amuse-main/examples/textbook/solar_cluster_in_galaxy_potential.py
import math import numpy from amuse.lab import * from amuse.couple import bridge from amuse.units.optparse import OptionParser from amuse.units import quantities from amuse.community.galaxia.interface import BarAndSpirals3D from amuse.ext.composition_methods import * from matplotlib import pyplot from prepare_figure import single_frame from distinct_colours import get_distinct class drift_without_gravity(object): def __init__(self, particles, time= 0 |units.Myr): self.particles=particles self.model_time= time def evolve_model(self, t_end): dt= t_end- self.model_time self.particles.position += self.particles.velocity*dt self.model_time= t_end def add_particles(self, p): self.particles.add_particles(p) @property def potential_energy(self): return quantities.zero @property def kinetic_energy(self): return \ (0.5*self.particles.mass*self.particles.velocity.lengths()**2).sum() def stop(self): return class MilkyWay_galaxy(object): def __init__(self, Mb=1.40592e10| units.MSun, Md=8.5608e10| units.MSun, Mh=1.07068e11 | units.MSun ): self.Mb= Mb self.Md= Md self.Mh= Mh def get_potential_at_point(self,eps,x,y,z): r=(x**2+y**2+z**2)**0.5 R= (x**2+y**2)**0.5 # buldge b1= 0.3873 |units.kpc pot_bulge= -constants.G*self.Mb/(r**2+b1**2)**0.5 # disk a2= 5.31 |units.kpc b2= 0.25 |units.kpc pot_disk = \ -constants.G*self.Md/(R**2 + (a2+ (z**2+ b2**2)**0.5 )**2 )**0.5 #halo a3= 12.0 |units.kpc cut_off=100 |units.kpc d1= r/a3 c=1+ (cut_off/a3)**1.02 pot_halo= -constants.G*(self.Mh/a3)*d1**1.02/(1+ d1**1.02) \ - (constants.G*self.Mh/(1.02*a3))\ * (-1.02/c +numpy.log(c) + 1.02/(1+d1**1.02) \ - numpy.log(1.0 +d1**1.02) ) return 2*(pot_bulge+pot_disk+ pot_halo) # multiply by 2 because it # is a rigid potential def get_gravity_at_point(self, eps, x,y,z): r= (x**2+y**2+z**2)**0.5 R= (x**2+y**2)**0.5 #bulge b1= 0.3873 |units.kpc force_bulge= -constants.G*self.Mb/(r**2+b1**2)**1.5 #disk a2= 5.31 |units.kpc b2= 0.25 |units.kpc d= a2+ (z**2+ b2**2)**0.5 force_disk=-constants.G*self.Md/(R**2+ d**2 )**1.5 #halo a3= 12.0 |units.kpc d1= r/a3 force_halo= -constants.G*self.Mh*d1**0.02/(a3**2*(1+d1**1.02)) ax= force_bulge*x + force_disk*x + force_halo*x/r ay= force_bulge*y + force_disk*y + force_halo*y/r az= force_bulge*z + force_disk*d*z/(z**2 + b2**2)**0.5 + force_halo*z/r return ax,ay,az def vel_circ(self, r ): z=0 | units.kpc b1= 0.3873 |units.kpc a2= 5.31 |units.kpc b2= 0.25 |units.kpc a3= 12.0 |units.kpc rdphi_b = constants.G*self.Mb*r**2/(r**2+b1**2)**1.5 rdphi_d =constants.G*self.Md*r**2/(r**2+(a2+(z**2+b2**2)**0.5)**2 )**1.5 rdphi_h = constants.G*self.Mh*(r/a3)**0.02*r/(a3**2*(1+(r/a3)**1.02)) vel_circb = rdphi_b vel_circd = rdphi_d vel_circh = rdphi_h return (vel_circb+ vel_circd+ vel_circh)**0.5 def stop(self): return def evolve_cluster_in_potential(gravity, t_end, dt, channel_to_framework): Etot_init = gravity.kinetic_energy + gravity.potential_energy Etot_prev = Etot_init time = 0.0 | t_end.unit x = [] y = [] while time < t_end: time += dt gravity.evolve_model(time) channel_to_framework.copy() x.append(gravity.particles[0].x.value_in(units.kpc)) y.append(gravity.particles[0].y.value_in(units.kpc)) Etot_prev_se = gravity.kinetic_energy + gravity.potential_energy Ekin = gravity.kinetic_energy Epot = gravity.potential_energy Etot = Ekin + Epot """ print "T=", time, print "E= ", Etot, "Q= ", Ekin/Epot, print "dE=", (Etot_init-Etot)/Etot, "ddE=", (Etot_prev-Etot)/Etot """ Etot_prev = Etot return x, y def integrate_single_particle_in_potential(sun, t_end, dt, converter): # cluster_gravity = drift_without_gravity(sun) cluster_gravity = BHTree(converter) cluster_gravity.particles.add_particles(sun) channel_from_gravity_to_framework \ = cluster_gravity.particles.new_channel_to(sun) MWG = MilkyWay_galaxy() gravity = bridge.Bridge(use_threading=False) gravity.add_system(cluster_gravity, (MWG,) ) t_orb = 2*numpy.pi*sun.position.length()/sun.velocity.length() gravity.timestep = min(dt, 10|units.Myr) x, y = evolve_cluster_in_potential(gravity, t_end, dt, channel_from_gravity_to_framework) gravity.stop() return x, y def main(N, W0, t_end, n_steps, filename, Mtot, Rvir, rgc, vgc): numpy.random.seed(111) converter=nbody_system.nbody_to_si(Mtot, Rvir) dt = t_end/float(n_steps) sun = Particles(1) sun.mass= 1 | units.MSun sun.radius= 1 |units.RSun sun.position= [-8400.0, 0.0, 17.0] | units.parsec x_label = "X [kpc]" y_label = "Y [kpc]" fig = pyplot.figure(figsize=(8,8)) pyplot.xlim(-10, 10) pyplot.ylim(-10, 10) pyplot.axis('equal') pyplot.xlabel("X [kpc]") pyplot.ylabel("Y [kpc]") colors = get_distinct(6) MWG = MilkyWay_galaxy() vc = MWG.vel_circ(sun.position.length()) sun.velocity = [11.352, (12.24+vc.value_in(units.kms)), 7.41] | units.kms sun.velocity *= -1 print("Current Sun:") print(sun) print("\nFinding birth location of the Sun...") x, y = integrate_single_particle_in_potential(sun, t_end, dt, converter) pyplot.plot(x, y, lw=4, alpha=0.2, c=colors[1]) print("Initial Sun:") print(sun) sun.velocity *= -1 cluster = new_king_model(N, W0=3, convert_nbody=converter) cluster.mass = new_salpeter_mass_distribution(len(cluster), 0.1|units.MSun, 10.0|units.MSun) eps2 = 0.25*(float(N))**(-0.666667) * Rvir**2 cluster.scale_to_standard(convert_nbody=converter, smoothing_length_squared = eps2) cluster.position += sun.position cluster.velocity += sun.velocity cluster.radius = 0 | units.parsec pyplot.scatter(cluster.x.value_in(units.kpc), cluster.y.value_in(units.kpc), s=10, c=colors[3]) print('\nTracking', N, 'siblings') x, y = integrate_single_particle_in_potential(cluster, t_end, dt, converter) size = cluster.mass/(0.1 |units.MSun) pyplot.scatter(cluster.x.value_in(units.kpc), cluster.y.value_in(units.kpc), c=colors[0], alpha=1.0, lw=0, s=size) pyplot.scatter(sun.x.value_in(units.kpc), sun.y.value_in(units.kpc), marker='+', s=100, c=colors[2]) pyplot.scatter([0], [0], marker="+", s=300, c='r') pyplot.scatter([-8.4], [0], marker="o", s=100, c='g') save_file = 'SolarClusterInPotential.png' pyplot.savefig(save_file) print('\nSaved figure in file', save_file,'\n') pyplot.show() def new_option_parser(): result = OptionParser() result.add_option("-n", dest="n_steps", type="float", default = 2000, help="number of diagnostics time steps [%default]") result.add_option("-f", dest="filename", default = "proto_solar_cluster.hdf5", help="output filename [%default]") result.add_option("-N", dest="N", type="int",default = 1000, help="number of stars [%default]") result.add_option("-M", unit=units.MSun, dest="Mtot", type="float",default = 100 | units.MSun, help="cluster mass [%default]") result.add_option("-R", unit= units.parsec, dest="Rvir", type="float",default = 100 | units.parsec, help="cluser virial radius [%default]") result.add_option("-r", unit= units.parsec, dest="rgc", type="float",default = 8500.0 | units.parsec, help="distance to the galactic center [%default]") result.add_option("-v", unit= units.kms, dest="vgc", type="float",default = 220.0 | units.kms, help="orbital velotiy around the galactic center [%default]") result.add_option("-t", unit= units.Gyr, dest="t_end", type="float", default = 4.8 | units.Gyr, help="end time of the simulation [%default]") result.add_option("-W", dest="W0", type="float", default = 7.0, help="Dimension-less depth of the King potential (W0) [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
9,251
34.312977
80
py
amuse
amuse-main/examples/textbook/plot_projected_density_distributions.py
import numpy from matplotlib import pyplot from amuse.lab import * from amuse.ext.molecular_cloud import molecular_cloud from amuse.plot import sph_particles_plot, native_plot from prepare_figure import figure_frame from distinct_colours import get_distinct ###BOOKLISTSTART1### def stellar_model(N, M, t=0.0|units.Myr): star = Particle(mass=M) stellar_evolution = EVtwin() se_star = stellar_evolution.particles.add_particle(star) print("Evolving", star.mass, "star with", \ stellar_evolution.__class__.__name__, "to t=", t.in_(units.Myr)) stellar_evolution.evolve_model(t) print("Stellar type:", stellar_evolution.particles.stellar_type) print("Creating SPH particles from the (1D) stellar evolution model") sph_particles = convert_stellar_model_to_SPH(se_star, N).gas_particles stellar_evolution.stop() return sph_particles ###BOOKLISTSTOP1# def plot_ZAMS_stellar_model(N, M): sph_particles = stellar_model(N, M) figure = pyplot.figure(figsize=(12, 12)) plot = figure.add_subplot(1,1,1) pyplot.rcParams.update({'font.size': 30}) ax = pyplot.gca() ax.minorticks_on() ax.locator_params(nbins=3) ax.get_yaxis().get_major_formatter().set_useOffset(False) ax.minorticks_on() lim = 2 sph_particles_plot(sph_particles, min_size = 500, max_size = 500, alpha=0.01, view=(-lim, lim, -lim, lim)|units.RSun) ax.set_facecolor('white') pyplot.xlabel("x [R$_\odot$]") pyplot.ylabel("y [R$_\odot$]") file = 'stellar_2MSunZAMS_projected.png' pyplot.savefig(file) print('Saved figure in file', file, '\n') def GMC_model(N, M, R): converter = nbody_system.nbody_to_si(M, R) gmc = molecular_cloud(targetN=N, convert_nbody=converter) parts = gmc.result sph = Fi(converter) sph.gas_particles.add_particle(parts) sph.evolve_model(1|units.day) ch = sph.gas_particles.new_channel_to(parts) ch.copy() sph.stop() return parts def plot_GMC_model(N, M, R): sph_particles = GMC_model(N, M, R) x_label = "x [pc]" y_label = "y [pc]" figure, ax = figure_frame(x_label, y_label, xsize=12, ysize=12) lim = 20 sph_particles_plot(sph_particles, min_size = 500, max_size = 500, alpha=0.01, view=(-lim, lim, -lim, lim)|units.parsec) ax.set_facecolor('white') save_file = 'molecular_cloud_projected.png' pyplot.savefig(save_file) print('Saved figure in file', save_file) if __name__ in ("__main__","__plot__"): N = 10000 M = 10000. | units.MSun R = 10. | units.parsec M = 2 | units.MSun print('') plot_ZAMS_stellar_model(N, M) plot_GMC_model(N, M, R) print('')
2,753
31.785714
74
py
amuse
amuse-main/examples/textbook/plot_XiTau_orbital_evolution.py
import pickle from amuse.lab import * #from read_orbital_elements import read_orbital_elements from NonConservativeMassTransfer import orbital_separation_after_mass_transfer from prepare_figure import * from distinct_colours import get_distinct def read_orbital_elements(filename="orbital_elements_data.pkl"): with open(filename, 'rb') as infile: results = pickle.load(infile) a_in = results["semimajor_axis_binary"] print(list(results.keys())) return results["times"], results["semimajor_axis_giant"], results["eccentricity_giant"], results["giant_mass"], results["ms1_mass"], results["ms2_mass"] def limit_range(t, t_start=0|units.day, t_end=100|units.Myr): istart = 0 for ti in t: istart+=1 if ti>t_start: break iend = 0 for i in t: iend += 1 if ti>t_end: break return istart, iend def retrieve_semi_major_axis_evolution(filename, nj, t_start=0|units.day, t_end=100|units.Myr): t, a_out, e_out, M_out, m1, m2 = read_orbital_elements(filename) m_in = m1+m2 istart, iend = limit_range(t, t_start, t_end) t_new = [] | units.day an_out = [] | units.AU a_new = [] | units.AU en_out = [] for i in range(len(a_out)): if i>=istart and i<=iend: ai = orbital_separation_after_mass_transfer(a_out[istart], M_out[istart], M_out[i], m_in[istart], m_in[i], nj) a_new.append(ai) t_new.append(t[i]) an_out.append(a_out[i]) en_out.append(e_out[i]) if t[i]>t_end: break print(i, len(t), len(an_out), len(a_new)) return t_new, an_out, a_new, en_out def plot_XiTau(filename, nj): from matplotlib import pyplot colors = get_distinct(4) figure = pyplot.figure(figsize=(16, 12)) ax = pyplot.gca() ax.minorticks_on() # switch on the minor ticks ax.locator_params(nbins=3) t, a_out, a_new, e_out = retrieve_semi_major_axis_evolution(filename, nj) from matplotlib import pyplot #pyplot.plot(t.value_in(units.yr), e_out, c=colors[0]) pyplot.plot(t.value_in(units.yr), a_out.value_in(units.AU), c=colors[0]) pyplot.plot(t.value_in(units.yr), a_new.value_in(units.AU), c=colors[1]) t, a_out, a_new, e_out = retrieve_semi_major_axis_evolution(filename, 4.0) pyplot.plot(t.value_in(units.yr), a_new.value_in(units.AU), c=colors[2], lw=2) t, a_out, a_new, e_out = retrieve_semi_major_axis_evolution(filename, 8.0) pyplot.plot(t.value_in(units.yr), a_new.value_in(units.AU), c=colors[3], lw=2) pyplot.xlim(0, 12) pyplot.xlabel("t [year]") pyplot.ylabel("$a_{outer}$ [AU]") pyplot.savefig("fig_XiTau_orbital_separation") pyplot.show() def plot_HD971331(filename): t_end = 4000|units.day t_start = 8000|units.day from matplotlib import pyplot colors = get_distinct(4) figure = pyplot.figure(figsize=(16, 12)) ax = pyplot.gca() ax.minorticks_on() # switch on the minor ticks ax.locator_params(nbins=3) t, a_out, e_out, M_out, m1, m2 = read_orbital_elements(filename) pyplot.plot(t.value_in(units.yr), a_out.value_in(units.AU), c=colors[0]) """ t, a_out, a_new = retrieve_semi_major_axis_evolution(filename, nj=4.0, t_end=8000|units.day) pyplot.plot(t.value_in(units.yr), a_new.value_in(units.AU), c='r') pyplot.scatter(t[-1].value_in(units.yr), a_new[-1].value_in(units.AU), s=50, c=colors[1]) """ t, a_out, a_new = retrieve_semi_major_axis_evolution(filename, nj=6, t_end=2000|units.day) pyplot.plot(t.value_in(units.yr), a_new.value_in(units.AU), c='r') pyplot.scatter(t[-1].value_in(units.yr), a_new[-1].value_in(units.AU), s=50, c=colors[1]) t, a_out, a_new = retrieve_semi_major_axis_evolution(filename, nj=4, t_start=2000|units.day, t_end=5000|units.day) pyplot.plot(t.value_in(units.yr), a_new.value_in(units.AU), c=colors[1]) #pyplot.scatter(t[0].value_in(units.yr), a_new[0].value_in(units.AU), s=50, c=colors[1]) #pyplot.scatter(t[-1].value_in(units.yr), a_new[-1].value_in(units.AU), s=50, c=colors[1]) t, a_out, a_new = retrieve_semi_major_axis_evolution(filename, nj=2, t_start=5000|units.day, t_end=8000|units.day) print(t.value_in(units.yr), a_new.value_in(units.AU)) #pyplot.plot(t.value_in(units.yr), a_new.value_in(units.AU), c=colors[1]) #pyplot.scatter(t[0].value_in(units.yr), a_new[0].value_in(units.AU), s=50, c=colors[1]) #pyplot.scatter(t[-1].value_in(units.yr), a_new[-1].value_in(units.AU), s=50, c=colors[1]) t, a_out, a_new = retrieve_semi_major_axis_evolution(filename, nj=-7, t_start=8000|units.day) pyplot.plot(t.value_in(units.yr), a_new.value_in(units.AU), c=colors[1]) #pyplot.scatter(t[0].value_in(units.yr), a_new[0].value_in(units.AU), s=50, c=colors[1]) pyplot.xlabel("t [year]") pyplot.ylabel("$a_{giant}$ [AU]") pyplot.ylim(0.77, 0.8201) pyplot.xlim(0.0, 50.0) pyplot.show() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-f", dest="filename",default="XiTau_orbital_evolution.pkl") # dest="filename",default="HD97131_orbital_evolution.pkl") result.add_option("--nj", dest="nj",type="float",default=6) result.add_option("-t", unit=units.day, dest="t_start",type="float",default=0|units.day) return result def main(filename, nj, t_start=0|units.day): if "XiTau" in filename: plot_XiTau(filename, nj) else: plot_HD971331(filename) #HD97131_orbital_parameters.pkl if __name__ == "__main__": options, arguments = new_option_parser().parse_args() main(**options.__dict__)
6,083
38.764706
156
py
amuse
amuse-main/examples/textbook/Sun_and_M67_in_the_Galaxy.py
import numpy import math from amuse.lab import * from amuse import datamodel from amuse.units import quantities from amuse.ext.rotating_bridge import Rotating_Bridge from amuse.community.galaxia.interface import BarAndSpirals3D from amuse.ext.composition_methods import * from prepare_figure import * from distinct_colours import get_distinct class drift_without_gravity(object): """ This class is to make the ev of non interactig particles by using bridge. """ def __init__(self, particles, time= 0 |units.Myr): self.particles=particles self.model_time= time def evolve_model(self, t_end): dt= t_end- self.model_time self.particles.position += self.particles.velocity*dt self.model_time= t_end @property def potential_energy(self): return quantities.zero @property def kinetic_energy(self): return (0.5*self.particles.mass*self.particles.velocity.lengths()**2).sum() I = 0 class IntegrateOrbit(object): """ This class makes the integration of the Sun in the Milky Way by using BarAndSpirals3D. galaxy(): Function that sets the desired Galactic model. Any question on the parameters, contact me creation_particles_noinertial(): creates a parti le set in a rotating frame noinertial_to_inertial(): converts data from rotating to inertial frame get_pos_vel_and_orbit(): Makes the evolution of the particle set """ def __init__(self, t_end= 10 |units.Myr, dt_bridge=0.5 |units.Myr, method= SPLIT_6TH_SS_M13, phase_bar= 0, phase_spiral= 0, omega_spiral= -20 |(units.kms/units.kpc), amplitude= 650|(units.kms**2/units.kpc), m=4, omega_bar= -50 |(units.kms/units.kpc), mass_bar= 1.1e10 |units.MSun ): # Simulation parameters self.t_end= t_end self.dt_bridge= dt_bridge self.method= method self.time= 0 |units.Myr #galaxy parameters self.omega= 0 | (units.kms/units.kpc) self.initial_phase= 0 self.bar_phase= phase_bar self.spiral_phase= phase_spiral self.omega_spiral= omega_spiral self.amplitude= amplitude self.rsp= 3.12 |units.kpc self.m= m self.tan_pitch_angle= 0.227194425 self.omega_bar= omega_bar self.mass_bar= mass_bar self.aaxis_bar= 3.12 |units.kpc self.axis_ratio_bar= 0.37 return def galaxy(self): global I galaxy= BarAndSpirals3D(redirection='file', redirect_stdout_file="GAL{0}.log".format(I)) I = I + 1 galaxy.kinetic_energy=quantities.zero galaxy.potential_energy=quantities.zero galaxy.parameters.bar_contribution= True galaxy.parameters.bar_phase= self.bar_phase galaxy.parameters.omega_bar= self.omega_bar galaxy.parameters.mass_bar= self.mass_bar galaxy.parameters.aaxis_bar= self.aaxis_bar galaxy.parameters.axis_ratio_bar= self.axis_ratio_bar galaxy.parameters.spiral_contribution= False galaxy.parameters.spiral_phase= self.spiral_phase galaxy.parameters.omega_spiral= self.omega_spiral galaxy.parameters.amplitude= self.amplitude galaxy.parameters.rsp= self.rsp galaxy.parameters.m= self.m galaxy.parameters.tan_pitch_angle= self.tan_pitch_angle galaxy.commit_parameters() self.omega= galaxy.parameters.omega_system self.initial_phase= galaxy.parameters.initial_phase print("INITIAL_PHASE:", self.initial_phase) galaxy.kinetic_energy=quantities.zero galaxy.potential_energy=quantities.zero return galaxy def creation_particles_noinertial(self, particles): """ makes trans in a counterclockwise frame. If the Galaxy only has bar or only spiral arms, the frame corotates with the bar or with the spiral arms. If the Galaxy has bar and spiral arms, the frame corotates with the bar """ no_inertial_system= particles.copy() angle= self.initial_phase + self.omega*self.time C1= particles.vx + self.omega*particles.y C2= particles.vy - self.omega*particles.x no_inertial_system.x = particles.x*numpy.cos(angle) + particles.y*numpy.sin(angle) no_inertial_system.y = -particles.x*numpy.sin(angle) + particles.y*numpy.cos(angle) no_inertial_system.z = particles.z no_inertial_system.vx = C1*numpy.cos(angle) + C2*numpy.sin(angle) no_inertial_system.vy = C2*numpy.cos(angle) - C1*numpy.sin(angle) no_inertial_system.vz = particles.vz return no_inertial_system def noinertial_to_inertial(self, part_noin, part_in): #makes trans in a counterclockwise frame angle= self.initial_phase + self.omega*self.time C1= part_noin.vx - part_noin.y*self.omega C2= part_noin.vy + part_noin.x*self.omega part_in.x= part_noin.x*numpy.cos(angle)-part_noin.y*numpy.sin(angle) part_in.y= part_noin.x*numpy.sin(angle)+part_noin.y*numpy.cos(angle) part_in.z= part_noin.z part_in.vx= C1*numpy.cos(angle) - C2*numpy.sin(angle) part_in.vy= C1*numpy.sin(angle) + C2*numpy.cos(angle) part_in.vz= part_noin.vz return def testing_potential_and_force(self, galaxy, x, y, z): dx, dy, dz = 0.001 |units.kpc, 0.001 |units.kpc, 0.001 |units.kpc phi1x= galaxy.get_potential_at_point(0 |units.kpc, (x+dx), y, z) phi2x= galaxy.get_potential_at_point(0 |units.kpc, (x-dx), y, z) f1x= -(phi1x-phi2x)/(2*dx) phi1y= galaxy.get_potential_at_point(0 |units.kpc, x, (y+dy), z) phi2y= galaxy.get_potential_at_point(0 |units.kpc, x, (y-dy), z) f1y= -(phi1y-phi2y)/(2*dy) phi1z= galaxy.get_potential_at_point(0 |units.kpc, x, y, (z+dz)) phi2z= galaxy.get_potential_at_point(0 |units.kpc, x, y, (z-dz)) f1z= -(phi1z-phi2z)/(2*dz) fx,fy,fz= galaxy.get_gravity_at_point(0 |units.kpc, x, y, z) print("analytic", "numerical") print(fx.value_in(100*units.kms**2/units.kpc) , f1x.value_in(100*units.kms**2/units.kpc)) print(fy.value_in(100*units.kms**2/units.kpc) , f1y.value_in(100*units.kms**2/units.kpc)) print(fz.value_in(100*units.kms**2/units.kpc) , f1z.value_in(100*units.kms**2/units.kpc)) return def get_pos_vel_and_orbit(self, particle_set): #particle_set.velocity= (-1)*particle_set.velocity filename="sunandM67.hdf5" write_set_to_file(particle_set.savepoint(self.time), filename, "hdf5", append_to_file=False) MW= self.galaxy() print("OMEGA:", self.omega.as_quantity_in(1/units.Gyr)) particle_rot= self.creation_particles_noinertial(particle_set) gravless= drift_without_gravity(particle_rot) system= Rotating_Bridge(self.omega, timestep= self.dt_bridge, verbose= False, method= self.method) system.add_system(gravless, (MW,), False) system.add_system(MW, (), False) # This is to update time inside the interface Ei= system.potential_energy+ system.kinetic_energy+ system.jacobi_potential_energy energy=[] dmin = (particle_set[0].position-particle_set[1].position).length() tmin = 0|units.Myr d = [] | units.kpc t = [] | units.Myr d.append(dmin) t.append(self.time) while (self.time < self.t_end-self.dt_bridge/2): self.time += self.dt_bridge system.evolve_model(self.time) self.noinertial_to_inertial(particle_rot, particle_set) Ef= system.potential_energy+ system.kinetic_energy+ system.jacobi_potential_energy dje= (Ef-Ei)/Ei energy.append(dje) d.append((particle_set[0].position-particle_set[1].position).length()) t.append(self.time) if d[-1]<dmin: dmin = d[-1] tmin = self.time x = particle_set.x y = particle_set.y write_set_to_file(particle_set.savepoint(self.time), filename, "hdf5") print("minimum", tmin.in_(units.Myr), dmin.in_(units.parsec)) bar_angle= self.bar_phase + (self.omega_bar*self.time) spiral_angle= self.spiral_phase + (self.omega_spiral*self.time) return self.time, particle_set[0].x.value_in(units.kpc), particle_set[0].y.value_in(units.kpc),\ particle_set[0].z.value_in(units.kpc), particle_set[0].vx.value_in(units.kms), \ particle_set[0].vy.value_in(units.kms), particle_set[0].vz.value_in(units.kms), \ bar_angle , spiral_angle, t, d def Sun_and_M67_in_the_Galaxy(): bodies = Particles(2) Sun = bodies[0] v_LSR = (-10, 5.2, 7.2) | units.kms Sun.mass = 1|units.MSun Sun.radius = 1|units.RSun Sun.position = (8.4, 0.0, 0.017) | units.kpc Sun.velocity = (-11.4, 232, 7.41) | units.kms # SPZ2009 M67 = bodies[1] M67.mass = 50000 | units.MSun M67.radius = 3 | units.parsec M67.position = Sun.position + ((0.766, 0.0, 0.49) |units.kpc) M67.velocity = Sun.velocity + ((31.92, -21.66, -8.87) |units.kms) bodies.velocity *= -1 simulation_time= 4600. |units.Myr dt_bridge= 5 | units.Myr OS= 20 |(units.kms/units.kpc) OB= 40 |(units.kms/units.kpc) A= 1300 |(units.kms**2/units.kpc) M= 1.4e10 |units.MSun m=2 phi_bar, phi_sp= -0.34906, -0.34906 inte= IntegrateOrbit( t_end= simulation_time, dt_bridge= dt_bridge, phase_bar= phi_bar, phase_spiral= phi_sp, omega_spiral= OS, omega_bar= OB, amplitude= A, m=m, mass_bar= M ) MW= inte.galaxy() print(MW.parameters) print(MW.get_phi21()) print("Backwards integration") time, xf, yf, zf, vxf, vyf, vzf, bar_angle, spiral_angle, t1, d1= inte.get_pos_vel_and_orbit(bodies) print("Birth position of the Sun:", xf, yf, zf, vxf, vyf, vzf) print("---") print('time after backward integration:', time) colors = get_distinct(4) figure = pyplot.figure(figsize=(16, 12)) ax = pyplot.gca() ax.minorticks_on() # switch on the minor ticks ax.locator_params(nbins=3) x_label = "t [Gyr]" y_label = "d [kpc]" pyplot.xlabel(x_label) pyplot.ylabel(y_label) pyplot.plot(-t1.value_in(units.Gyr), d1.value_in(units.kpc), lw=3, c=colors[0]) pyplot.ylim(0, 6) pyplot.xlim(-5, 0) pyplot.savefig("sun_and_M67") pyplot.show() """ from matplotlib import pyplot from amuse.plot import scatter, plot plot(-1*t1, d1, c = "k") pyplot.semilogy() pyplot.show() """ if __name__ in ('__main__', '__plot__'): set_printing_strategy("custom", #nbody_converter = converter, preferred_units = [units.MSun, units.kpc, units.Myr], precision = 4, prefix = "", separator = " [", suffix = "]") Sun_and_M67_in_the_Galaxy()
11,072
39.709559
286
py
amuse
amuse-main/examples/textbook/anim_gravity.py
import os ###BOOKLISTSTART### from matplotlib import pyplot import matplotlib.animation as animation from amuse.io import read_set_from_file from amuse.units import units def animate(x, y): def update(i): while i >= np: i -= np off = [] for j in range(len(x[i])): off.append(x[i][j]) off.append(y[i][j]) scat.set_offsets(off) return scat, np = len(x) fig = pyplot.figure(figsize=(8,8)) ax = fig.add_subplot(1,1,1) ax.set_xlim(-1.2, 1.2) ax.set_ylim(-1.2, 1.2) colormap = ['yellow', 'green', 'blue'] size = [40, 20, 20] edgecolor = ['orange', 'green', 'blue'] scat = ax.scatter(x[0], y[0], c=colormap, s=size, edgecolor=edgecolor) anim = animation.FuncAnimation(fig, update, interval=100) pyplot.show() ###BOOKLISTSTOP### if __name__ in ('__main__'): try: amusedir = os.environ['AMUSE_DIR'] dir = amusedir+'/examples/textbook/' except: print('Environment variable AMUSE_DIR not set') dir = './' filename = dir+'gravity.h5' particles = read_set_from_file(filename, "hdf5") print(particles.history) x = [] y = [] for si in particles.history: x.append(si.x.value_in(units.AU)) y.append(si.y.value_in(units.AU)) animate(x, y)
1,343
23.888889
74
py
amuse
amuse-main/examples/textbook/hydro_experiment.py
""" Simulate the hydrodynamial evolve a disk with a single bump around a star """ from amuse.lab import * from amuse.io import store def main(Mstar = 1|units.MSun, Ndisk=100, Mdisk=0.9|units.MSun, Rmin=1.0|units.AU, Rmax=100.0|units.AU, Mbump=0.1|units.MSun,Rbump=10.0|units.AU, abump=10|units.AU, t_end=1, n_steps=10): converter=nbody_system.nbody_to_si(Mdisk, Rmin) from amuse.ext.protodisk import ProtoPlanetaryDisk bodies = ProtoPlanetaryDisk(Ndisk, convert_nbody=converter, densitypower=1.5, Rmin=1.0, Rmax=Rmax/Rmin, q_out=1.0, discfraction=1.0).result Mdisk = bodies.mass.sum() bodies.move_to_center() com = bodies.center_of_mass() mm = Mdisk/float(Ndisk) Nbump = int(Mbump/mm) bump = new_plummer_gas_model(Nbump, convert_nbody=nbody_system.nbody_to_si(Mbump, Rbump)) bump.x += abump r_bump = abump inner_particles = bodies.select(lambda r: (com-r).length()<abump,["position"]) M_inner = inner_particles.mass.sum() + Mstar v_circ = (constants.G*M_inner*(2./r_bump - 1./abump)).sqrt().value_in(units.kms) bump.velocity += [0, v_circ, 0] | units.kms bodies.add_particles(bump) star=Particles(1) star.mass=Mstar star.radius= Rmin star.position = [0, 0, 0] | units.AU star.velocity = [0, 0, 0] | units.kms import math P_bump = (abump**3*4*math.pi**2/(constants.G*(Mbump+Mstar))).sqrt() t_end *= P_bump hydro = Gadget2(converter) hydro.gas_particles.add_particles(bodies) hydro.dm_particles.add_particles(star) Etot_init = hydro.kinetic_energy + hydro.potential_energy + hydro.thermal_energy particles = ParticlesSuperset([star, bodies]) particles.move_to_center() particles.new_channel_to(hydro.particles).copy() bodies.h_smooth = Rmin # for the plotting routine channel_to_star = hydro.dm_particles.new_channel_to(star) channel_to_bodies = hydro.gas_particles.new_channel_to(bodies) write_set_to_file(star, "stars.hdf5","hdf5") write_set_to_file(bodies, "hydro.hdf5","hdf5") time = 0.0 | t_end.unit dt = t_end/float(n_steps) while time < t_end: time += dt hydro.evolve_model(time) channel_to_star.copy() channel_to_bodies.copy() write_set_to_file(star, "stars.hdf5","hdf5") write_set_to_file(bodies, "hydro.hdf5","hdf5") star.radius = Rmin from hydro_sink_particles import hydro_sink_particles lost = hydro_sink_particles(star, bodies) if len(lost)>0: hydro.particles.remove_particles(lost) hydro.particles.synchronize_to(particles) print("Disk=", hydro.model_time, len(bodies), len(lost), lost.mass.sum(), star.mass) Ekin = hydro.kinetic_energy Epot = hydro.potential_energy Eth = hydro.thermal_energy Etot = Ekin + Epot + Eth print("T=", hydro.get_time(), "M=", hydro.gas_particles.mass.sum(), end=' ') print("E= ", Etot, "Q= ", (Ekin+Eth)/Epot, "dE=", (Etot_init-Etot)/Etot) print("Star=", hydro.model_time, star[0].mass, star[0].position) hydro.stop() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-N", dest="Ndisk", type="int",default = 100, help="number of stars [10]") result.add_option("-n", dest="n_steps", type="int",default = 10, help="number of steps [10]") result.add_option("-t", dest="t_end", type="float", default = 1, help="end time of the simulation in bump orbits") result.add_option("-M", dest="Mstar", type="float", default = 1|units.MSun, help="Mass of the central star [%default]") result.add_option("--Mdisk", dest="Mdisk", type="float", default = 0.9|units.MSun, help="Mass of the disk [%default]") result.add_option("-r", unit=units.AU, dest="Rmin", type="float", default = 10 |units.AU, help="inner disk radius [%default]") result.add_option("-R", unit=units.AU, dest="Rmax", type="float", default = 100 | units.AU, help="outer disk radius [%default]") result.add_option("--Mbump", unit=units.MSun, dest="Mbump", type="float", default = 0.1 | units.MSun, help="bump mass [%default]") result.add_option("--Rbump", unit=units.AU, dest="Rbump", type="float", default = 10 | units.AU, help="bump radius [%default]") result.add_option("-a", unit=units.AU, dest="abump", type="float", default = 20 | units.AU, help="distance of bump from star [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
5,103
39.832
96
py
amuse
amuse-main/examples/textbook/1987ApJ...323..614B.py
from amuse.lab import * from amuse.io import store from amuse.ext.orbital_elements import new_binary_from_orbital_elements def collide_two_stars(t_end, distance, offset, v_vesc, nsteps): filename = "Hydro_AM06MSun.h5" try: pstar = read_set_from_file(filename, format='hdf5') except: from star_to_sph import evolve_star_and_convert_to_sph, evolve_star mass = 0.6|units.MSun age = 8 | units.Gyr omega = 0|units.s**-1 Nsph = 1000 stellar = evolve_star(mass, age) pstar, pcore = evolve_star_and_convert_to_sph(stellar, omega, Nsph) print(pstar) pmass = pstar.mass.sum() print(pmass.in_(units.MSun)) filename = "Hydro_BM06MSun.h5" try: sstar = read_set_from_file(filename, format='hdf5') except: from star_to_sph import evolve_star_and_convert_to_sph, evolve_star mass = 0.6|units.MSun age = 8 | units.Gyr omega = 0|units.s**-1 Nsph = 1000 stellar = evolve_star(mass, age) sstar, score = evolve_star_and_convert_to_sph(stellar, omega, Nsph) print(sstar) smass = sstar.mass.sum() print(smass.in_(units.MSun)) import numpy v_esc = numpy.sqrt(2*constants.G*pmass/distance) velocity = v_vesc*v_esc sstar.x += distance sstar.y += offset sstar.vx -= velocity sph_particles = Particles(0) sph_particles.add_particles(pstar) sph_particles.add_particles(sstar) sph_particles.move_to_center() converter=nbody_system.nbody_to_si(pmass, distance) hydro = Fi(converter) dt = t_end/float(nsteps) hydro.gas_particles.add_particles(pstar) hydro.gas_particles.add_particles(sstar) Etot_init = hydro.kinetic_energy + hydro.potential_energy + hydro.thermal_energy to_framework = hydro.gas_particles.new_channel_to(sph_particles) output_file = "1987ApJ...323..614B.h5" write_set_to_file(sph_particles.savepoint(0.0 | t_end.unit), output_file, "hdf5", append_to_file=False) time = 0.0 | t_end.unit while time < t_end: time += dt print(time) hydro.evolve_model(time) to_framework.copy() """ from amuse.plot import sph_particles_plot sph_particles_plot(hydro.particles) from matplotlib import pyplot pyplot.show() """ write_set_to_file(sph_particles.savepoint(time), output_file, "hdf5") """ Ekin = hydro.kinetic_energy Epot = hydro.potential_energy Eth = hydro.thermal_energy Etot = Ekin + Epot + Eth print "T=", hydro.get_time(), "M=", hydro.gas_particles.mass.sum(), print "E= ", Etot, "Q= ", (Ekin+Eth)/Epot, "dE=", (Etot_init-Etot)/Etot """ from amuse.plot import sph_particles_plot sph_particles_plot(hydro.particles) from matplotlib import pyplot pyplot.show() hydro.stop() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-t", unit=units.hour, dest="t_end", type="float", default = 10|units.hour, help="end time of the simulation [%default]") result.add_option("-r", unit=units.MSun, dest="distance", type="float", default = 1.4|units.RSun, help="initial sepration [%default]") result.add_option("-o", unit=units.RSun, dest="offset", type="float", default = 0|units.RSun, help="offset sepration [%default]") result.add_option("-v", dest="v_vesc", type="float", default = 1.7, help="impact velocity wrt escape speed [%default]") result.add_option("-n", dest="nsteps", type="int", default = 10, help="number of steps [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() collide_two_stars(o.t_end, o.distance, o.offset, o.v_vesc, o.nsteps)
4,070
32.925
107
py
amuse
amuse-main/examples/textbook/rad_experiment.py
""" Simulate the radiative and hydrodynamial evolution of a disk with a single bump around a single star """ from time import time, localtime from amuse.lab import * from amuse.ext.molecular_cloud import ism_cube from amuse.community.simplex.interface import SimpleXInterface, SimpleX,SimpleXSplitSet set_printing_strategy("custom", preferred_units = [units.MSun, units.AU, units.Myr], precision = 5, prefix = "", separator = " [", suffix = "]" ) def new_disk_with_bump(Mstar = 1|units.MSun, Ndisk=100, Mdisk=0.9|units.MSun, Rmin=1.0|units.AU, Rmax=100.0|units.AU, Mbump=0.1|units.MSun,Rbump=10.0|units.AU, abump=10|units.AU): converter=nbody_system.nbody_to_si(Mdisk, Rmin) from amuse.ext.protodisk import ProtoPlanetaryDisk bodies = ProtoPlanetaryDisk(Ndisk, convert_nbody=converter, densitypower=1.5, Rmin=1, Rmax=Rmax/Rmin, q_out=1.0, discfraction=1.0).result Mdisk = bodies.mass.sum() bodies.move_to_center() com = bodies.center_of_mass() mm = Mdisk/float(Ndisk) Nbump = int(Mbump/mm) bump = new_plummer_gas_model(Nbump, convert_nbody=nbody_system.nbody_to_si(Mbump, Rbump)) bump.x += abump r_bump = abump inner_particles = bodies.select(lambda r: (com-r).length()<abump,["position"]) M_inner = inner_particles.mass.sum() + Mstar v_circ = (constants.G*M_inner*(2./r_bump - 1./abump)).sqrt().value_in(units.kms) bump.velocity += [0, v_circ, 0] | units.kms bodies.add_particles(bump) bodies = bodies.select(lambda r: (com-r).length()>Rmin,["position"]) bodies = bodies.select(lambda r: (com-r).length()<Rmax,["position"]) print("Nbump=", Ndisk, Mbump, Rbump, Nbump) print("Mass =", Mstar, Mdisk, bodies.mass.sum().in_(units.MSun), bodies.mass.sum()/Mstar) print("X-min/max:", min(bodies.x), max(bodies.x)) bodies = bodies.select(lambda r: r.length()<1.0*Rmax,["position"]) print("X-min/max:", min(bodies.x), max(bodies.x)) return bodies def read_disk_with_bump(image_id=1, filename="hydro.hdf5"): star = read_set_from_file(filename, "hdf5") ism = read_set_from_file(filename, "hdf5") snapshot_id = 0 for si in ism.history: snapshot_id += 1 print("reading snapshot_id=", snapshot_id) if image_id<0 or image_id == snapshot_id: com = si.center_of_mass() return si def irradiate_disk_with_bump(Mstar = 10|units.MSun, tstar = 20|units.Myr, Ndisk=100, Mdisk=0.9|units.MSun, Rmin=1.0|units.AU, Rmax=100.0|units.AU, Mbump=0.1|units.MSun, Rbump=10.0|units.AU, abump=10|units.AU, t_end=10|units.yr, n_steps=10, filename = None, image_id=1): dt = t_end/float(n_steps) stellar = SeBa() stellar.particles.add_particle(Particle(mass=Mstar)) stellar.evolve_model(tstar) source=Particles(1) source.mass = stellar.particles[0].mass source.position = (0, 0, 0) |units.AU source.velocity = (0, 0, 0) |units.kms source.luminosity = stellar.particles[0].luminosity/(20. | units.eV) source.temperature = stellar.particles[0].temperature Teff = stellar.particles[0].temperature source.flux = source.luminosity source.rho = 1.0|(units.g/units.cm**3) source.xion = 0.0 #ionization_fraction source.u = (9. |units.kms)**2 #internal_energy stellar.stop() ism = new_disk_with_bump(source[0].mass, Ndisk, Mdisk, Rmin, Rmax, Mbump, Rbump, abump) ism.flux = 0 | units.s**-1 ism.xion = 0.0 #ionization_fraction hydro = Gadget2(nbody_system.nbody_to_si(Mdisk, Rmax)) hydro.gas_particles.add_particles(ism) hydro.dm_particles.add_particles(source) hydro.evolve_model(1|units.day) hydro.gas_particles.new_channel_to(ism).copy() hydro.stop() rad = SimpleXSplitSet(redirect="none",numer_of_workers=4) rad.parameters.box_size=2.01*Rmax rad.parameters.timestep=0.1*dt rad.set_source_Teff(Teff) rad.src_particles.add_particle(source) rad.gas_particles.add_particles(ism) rad_to_framework = rad.gas_particles.new_channel_to(ism) particles = ParticlesSuperset([source, ism]) write_set_to_file(particles, "rad.hdf5", 'hdf5') while rad.model_time<t_end: rad.evolve_model(rad.model_time + dt) rad_to_framework.copy_attributes(["x","y", "z", "xion"]) write_set_to_file(particles, "rad.hdf5", 'hdf5') print("Time=", rad.model_time, "Ionization (min, mean, max):", ism.xion.min(), ism.xion.mean(), ism.xion.max()) rad.stop() def _irradiate_disk_with_pump(Mstar = 10|units.MSun, tstar = 20|units.Myr, Ndisk=100, Mdisk=0.9|units.MSun, Rmin=1.0|units.AU, Rmax=100.0|units.AU, Mbump=0.1|units.MSun,Rbump=10.0|units.AU, abump=10|units.AU, t_end=10|units.yr, n_steps=10, filename = None, image_id=1): model_time = 0.0 | t_end.unit dt = t_end/float(n_steps) ionization_fraction = 0.0 internal_energy = (9. |units.kms)**2 stellar = SeBa() stellar.particles.add_particle(Particle(mass=Mstar)) stellar.evolve_model(tstar) print("L=", stellar.particles[0].luminosity.in_(units.LSun), stellar.particles[0].temperature) source=Particles(1) source.mass = stellar.particles[0].mass source.position = (0, 0, 0) |units.AU source.velocity = (0, 0, 0) |units.kms source.luminosity = stellar.particles[0].luminosity/(20. | units.eV) source.temperature = stellar.particles[0].temperature Teff = stellar.particles[0].temperature source.flux = source.luminosity source.rho = 1.0|(units.g/units.cm**3) source.xion = ionization_fraction source.u = internal_energy stellar.stop() Mstar = source[0].mass if filename ==None: ism = new_disk_with_bump(Mstar = Mstar, Ndisk=Ndisk, Mdisk=Mdisk, Rmin=Rmin, Rmax=Rmax, Mbump=Mbump, Rbump=Rbump, abump=abump) else: ism = read_disk_with_bump(image_id=image_id, filename=filename)#, Rmax=Rmax) ism = ism.select(lambda r: r.length()<1.0*Rmax,["position"]) ism.flux = 0 | units.s**-1 ism.xion = ionization_fraction if filename ==None: converter=nbody_system.nbody_to_si(Mdisk, Rmax) hydro = Gadget2(converter) hydro.gas_particles.add_particles(ism) hydro.dm_particles.add_particles(source) hydro.evolve_model(1|units.day) hydro.gas_particles.new_channel_to(ism).copy() hydro.stop() rad = SimpleXSplitSet(redirect="none",numer_of_workers=4) rad.parameters.number_of_freq_bins=5 rad.parameters.thermal_evolution_flag=1 rad.parameters.blackbody_spectrum_flag=1 rad.parameters.metal_cooling_flag=0 rad.parameters.box_size=2.01*Rmax if isinstance(rad, SPHRay): ism.h_smooth = 0.1 | (units.RSun) else: rad.parameters.timestep=0.1*dt rad.set_source_Teff(Teff) rad.src_particles.add_particle(source) rad.gas_particles.add_particles(ism) channel_from_rad_to_framework = rad.gas_particles.new_channel_to(ism) particles = ParticlesSuperset([source, ism]) write_set_to_file(particles, "rad.hdf5", 'hdf5') tCPU = time() while model_time<t_end: model_time += dt rad.evolve_model(model_time) channel_from_rad_to_framework.copy_attributes(["x","y", "z", "xion"]) write_set_to_file(particles, "rad.hdf5", 'hdf5') print("Date:"+str(localtime()[2])+"."+str(localtime()[1])+"."+str(localtime()[1]), "at", str(localtime()[3])+"h", str(localtime()[4])+"m") print("Time=", model_time, "dt_CPU=", time()-tCPU) print("min ionization:", ism.xion.min()) print("average Xion:", ism.xion.mean()) print("max ionization:", ism.xion.max()) tCPU = time() rad.stop() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-N", dest="Ndisk", type="int",default = 1000, help="number of stars [%default]") result.add_option("-t", unit=units.yr, dest="t_end", type="float", default = 1|units.yr, help="radiation time [%default]") # result.add_option("-f", # dest="filename", default = None, # help="input filename [%default]") result.add_option("--tstar", unit=units.Myr, dest="tstar", type="float", default = 20|units.Myr, help="age of the star [%default]") result.add_option("-n", dest="n_steps", type="int",default = 36500, help="number of steps [%default]") result.add_option("-i", dest="image_id", type="int",default = 1, help="id of the input (filename) snapshot [%default]") result.add_option("--Mstar", unit=units.MSun, dest="Mstar", type="float", default = 10|units.MSun, help="Mass of the central star [%default]") result.add_option("--Mdisk", unit=units.MSun, dest="Mdisk", type="float", default = 0.0002|units.MSun, help="Mass of the disk [%default]") result.add_option("-r", unit=units.AU, dest="Rmin", type="float", default = 10 |units.AU, help="inner disk radius [%default]") result.add_option("-R", unit=units.AU, dest="Rmax", type="float", default = 100 | units.AU, help="outer disk radius [%default]") result.add_option("--Mbump", unit=units.MSun, dest="Mbump", type="float", default = 0.0001 | units.MSun, help="bump mass [%default]") result.add_option("--Rbump", unit=units.AU, dest="Rbump", type="float", default = 5 | units.AU, help="bump radius [%default]") result.add_option("-a", unit=units.AU, dest="abump", type="float", default = 10 | units.AU, help="distance of bump from star [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() irradiate_disk_with_bump(**o.__dict__)
10,756
40.057252
146
py
amuse
amuse-main/examples/textbook/merger_stellar_density_profile.py
""" Script to initialize a star and print its structure """ import numpy from amuse.lab import * from matplotlib import pyplot from amuse.plot import plot, xlabel, ylabel from prepare_figure import figure_frame from distinct_colours import get_distinct def merge_two_stars(Mprim, Msec, t_coll): bodies = Particles(mass=[Mprim.value_in(units.MSun), Msec.value_in(units.MSun)] |units.MSun) stellar = MESA() primary = stellar.particles.add_particles(bodies[0].as_set()) secondary = stellar.particles.add_particles(bodies[1].as_set()) stellar.evolve_model(t_coll) print("Pre merger:\n", stellar.particles) stellar.merge_colliding(primary.copy(), secondary.copy(), MMAMS, dict(), dict(target_n_shells_mixing = 2000), return_merge_products=["se"]) print("Post merger:\n", stellar.particles) radius = stellar.particles[0].get_radius_profile() rho = stellar.particles[0].get_density_profile() stellar.stop() return radius, rho def get_density_profile(code=MESA, M=1.0|units.MSun, z=0.02): stellar = code() stellar.parameters.metallicity = z stellar.particles.add_particle(Particle(mass=M)) print("Nzones=", stellar.particles.get_number_of_zones()) radius = stellar.particles[0].get_radius_profile() rho = stellar.particles[0].get_density_profile() stellar.stop() return radius, rho def main(M, z, output_filename): numpy.random.seed(31415) x_label = "$R$ [R$_\odot$]" y_label = "$\\rho$ [g/cm$^{3}$]" fig, ax = figure_frame(x_label, y_label, xsize=12, ysize=8) cols = get_distinct(3) r, rho = get_density_profile(EVtwin, M, z) pyplot.plot(r.value_in(units.RSun), rho.value_in(units.g/units.cm**3), label="EVtwin", c=cols[0]) r, rho = get_density_profile(MESA, M, z) pyplot.plot(r.value_in(units.RSun), rho.value_in(units.g/units.cm**3), label="MESA", c=cols[1]) # Run the merger code. r, rho = merge_two_stars(0.5*M, 0.5*M, 1|units.yr) pyplot.plot(r.value_in(units.RSun), rho.value_in(units.g/units.cm**3), label="MESA", c=cols[2]) pyplot.semilogy() if output_filename is not None: pyplot.savefig(output_filename) print('\nSaved figure in file', output_filename,'\n') else: output_filename = 'merger_stellar_density_profile.png' pyplot.savefig(output_filename) print('\nSaved figure in file', output_filename,'\n') pyplot.show() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-M", unit= units.MSun, dest="M", type="float",default = 2.0 | units.MSun, help="stellar mass [1.0] %unit") result.add_option("-o", dest="output_filename", default=None, help="output filename [%default]") result.add_option("-z", dest="z", type="float", default=0.02, help="metalicity [0.02]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
3,359
34.368421
72
py
amuse
amuse-main/examples/textbook/supernova_sph.py
import numpy from amuse.lab import * #from amuse import plot from amuse.ext import cloud from matplotlib import pyplot from amuse import datamodel from amuse.ext.sph_to_grid import convert_SPH_to_grid from amuse.community.capreole.interface import Capreole from amuse.units.generic_unit_converter import ConvertBetweenGenericAndSiUnits from prepare_figure import single_frame def plot_grid(grid, time= 0.0|units.day): pyplot.rcParams.update({'font.size': 30}) figure = pyplot.figure(figsize=(12, 12)) halfway = len(grid.rho[...,0,0])/2 - 1 rho = grid.rho[...,...,halfway].value_in(units.g/units.cm**3) max_dens = rho.max() plot = figure.add_subplot(1,1,1) # cax = plot.imshow(rho, interpolation='nearest', origin = 'lower', extent=[-5, 5, -5, 5]) cax = plot.imshow(rho, interpolation='bicubic', origin = 'lower', extent=[-5, 5, -5, 5], cmap="hot") rmin = 0.0 rmid = "%.1f" % (0.5*max_dens) rmax = "%.1f" % (max_dens) cbar = figure.colorbar(cax, ticks=[1.e-5, 0.5*max_dens, max_dens], orientation='vertical', fraction=0.045) cbar.ax.set_yticklabels([rmin, ' ', rmax]) # horizontal colorbar #cbar.ax.set_yticklabels(['Low', ' ', 'High']) # horizontal colorbar cbar.set_label('mid-plane density [$g/cm^3$]', rotation=270) pyplot.xlabel("x [R$_\odot$]") pyplot.ylabel("y [R$_\odot$]") t = int(time.value_in(units.s)) filename = "supernova_grid_T"+str(t)+".png" figure.savefig(filename) pyplot.show() def make_map(sph,N=100,L=1): x,y=numpy.indices( ( N+1,N+1 )) x=L*(x.flatten()-N/2.)/N y=L*(y.flatten()-N/2.)/N z=x*0. vx=0.*x vy=0.*x vz=0.*x x=units.parsec(x) y=units.parsec(y) z=units.parsec(z) vx=units.kms(vx) vy=units.kms(vy) vz=units.kms(vz) rho,rhovx,rhovy,rhovz,rhoe=sph.get_hydro_state_at_point(x,y,z,vx,vy,vz) rho=rho.reshape((N+1,N+1)) return rho def make_e_map(sph,N=100,L=1): x,y=numpy.indices( ( N+1,N+1 )) x=L*(x.flatten()-N/2.)/N y=L*(y.flatten()-N/2.)/N z=x*0. vx=0.*x vy=0.*x vz=0.*x x=units.parsec(x) y=units.parsec(y) z=units.parsec(z) vx=units.kms(vx) vy=units.kms(vy) vz=units.kms(vz) rho,rhovx,rhovy,rhovz,rhoe=sph.get_hydro_state_at_point(x,y,z,vx,vy,vz) rho=rhoe.reshape((N+1,N+1)) return rho def plot_sph(time, sph, gas, i=1, L=10): max_dens = sph.rho.max() x_label = "X [R$_\odot$]" y_label = "Y [R$_\odot$]" fig = single_frame(x_label, y_label, logx=False, logy=False, xsize=12, ysize=12) # rho=make_map(sph,N=200,L=L) rho_e=make_e_map(sph,N=200,L=L) print("extrema:", rho_e.value_in(units.erg/units.RSun**3).min(), rho_e.value_in(units.erg/units.RSun**3).max()) # pyplot.imshow(numpy.log10(rho_e.value_in(units.erg/units.RSun**3)), extent=[-L/2,L/2,-L/2,L/2],vmin=23,vmax=40) pyplot.imshow(numpy.log10(rho_e.value_in(units.erg/units.RSun**3)), extent=[-L/2,L/2,-L/2,L/2],vmin=23,vmax=40, interpolation='bicubic', origin = 'lower', cmap="hot") # cax = plot.imshow(rho, interpolation='bicubic', origin = 'lower', extent=[-5, 5, -5, 5], cmap="hot") cbar = figure.colorbar(cax, ticks=[1.e-8, 0.5*max_dens, max_dens], orientation='vertical', fraction=0.045) rmin = 0.0 rmid = "%.1f" % (0.5*max_dens) rmax = "%.1f" % (max_dens) cbar.ax.set_yticklabels([rmin, ' ', rmax]) # horizontal colorbar cbar.set_label('mid-plane density [$g/cm^3$]', rotation=270) pyplot.xlabel("x [R$_\odot$]") pyplot.ylabel("y [R$_\odot$]") t = int(0.5+sph.model_time.value_in(units.s)) filename = "supernova_sph_T"+str(t)+".pdf" pyplot.savefig(filename) def XX_plot_sph(time, sph, gas, i=1, L=10): x_label = "x [R$_\odot$]" y_label = "y [R$_\odot$]" fig = single_frame(x_label, y_label, logx=False, logy=False, xsize=12, ysize=12) # rho=make_map(sph,N=200,L=L) rho_e=make_e_map(sph,N=200,L=L) # pyplot.hist(numpy.log10(rho_e.value_in(units.erg/units.RSun**3))) # pyplot.show() print("extrema:", rho_e.value_in(units.erg/units.RSun**3).min(), rho_e.value_in(units.erg/units.RSun**3).max()) # pyplot.imshow(numpy.log10(1.e-8+rho.value_in(units.amu/units.cm**3)), extent=[-L/2,L/2,-L/2,L/2],vmin=1,vmax=5) pyplot.imshow(numpy.log10(rho_e.value_in(units.erg/units.RSun**3)), extent=[-L/2,L/2,-L/2,L/2],vmin=23,vmax=40) # pyplot.imshow(numpy.log10(1.e-5+rho.value_in(units.amu/units.cm**3)), extent=[-L/2,L/2,-L/2,L/2],vmin=1,vmax=5) #pyplot.scatter(gas.x.value_in(units.RSun), gas.y.value_in(units.RSun))#, alpha=0.05) t = int(0.5+sph.model_time.value_in(units.s)) filename = "supernova_sph_T"+str(t)+".pdf" pyplot.savefig(filename) def X_plot_sph(particles, time= 0.0|units.day): pyplot.rcParams.update({'font.size': 30}) figure = pyplot.figure(figsize=(12, 12)) #f, ax = pyplot.subplots(1,2, sharex=True, sharey=True) x = particles.x.value_in(units.RSun) y = particles.y.value_in(units.RSun) z = particles.rho.value_in(units.g/units.cm**3) cax = pyplot.tripcolor(x,y,z) max_dens = z.max() min_dens = z.min() mid_dens = 0.5*(max_dens+min_dens) # cbar = pyplot.colorbar() print("dens=", min_dens, mid_dens, max_dens) # cbar = figure.colorbar(cax, ticks=[min_dens, mid_dens, max_dens], orientation='vertical', fraction=0.045) # cbar.ax.set_yticklabels(['Low', ' ', 'High']) # cbar.set_label('mid-plane density', rotation=270) pyplot.xlim(0, 10) pyplot.ylim(0, 10) pyplot.xlabel("x [R$_\odot$]") pyplot.ylabel("y [R$_\odot$]") t = int(time.value_in(units.s)) filename = "supernova_sph_T"+str(t)+".png" pyplot.savefig(filename) pyplot.show() def setup_sph_code(sph_code, N, L, rho, u): converter = ConvertBetweenGenericAndSiUnits(L, rho, constants.G) sph_code = sph_code(converter, mode = 'periodic')#, redirection = 'none') sph_code.parameters.periodic_box_size = 10.0 | units.parsec plummer = new_plummer_gas_model(N, convert_nbody=converter) plummer = plummer.select(lambda r: r.length()<0.5*L,["position"]) N = len(plummer) print("N=", len(plummer)) plummer.mass = (rho * L**3) / N gas = Particles(N) gas.mass = 0.001*(rho * L**3) / N numpy.random.seed(12345) gas.x = L * numpy.random.uniform(0.0, 1.0, N) gas.y = L * numpy.random.uniform(0.0, 1.0, N) gas.z = L * numpy.random.uniform(0.0, 1.0, N) gas.vx = numpy.zeros(N) | units.cm / units.s gas.vy = numpy.zeros(N) | units.cm / units.s gas.vz = numpy.zeros(N) | units.cm / units.s gas.u = u if isinstance(sph_code, Fi): sph_code.parameters.self_gravity_flag = False sph_code.parameters.timestep = 0.1 | generic_unit_system.time gas.h_smooth = L / N**(1/3.0) gas.position -= 0.5 * L sph_code.gas_particles.add_particles(gas) sph_code.gas_particles.add_particles(plummer) sph_code.commit_particles() return sph_code def main(stellar_mass, stellar_radius, core_mass, core_radius, t_end, dt_diag, resolution): grid_size = 10 * stellar_radius grid = initialize_grid(stellar_mass, stellar_radius, core_mass, core_radius, resolution, grid_size) if False: hydro = initialize_grid_code(resolution, grid_size) cth = grid.new_channel_to(hydro.grid) cth.copy() hydro.initialize_grid() run_grid_code(hydro, grid, t_end, dt_diag) else: converter = nbody_system.nbody_to_si(1|units.MSun, 1|units.RSun) hydro = Gadget2(converter, number_of_workers=4) from amuse.ext.grid_to_sph import convert_grid_to_SPH particles = convert_grid_to_SPH(grid, number_of_sph_particles=100000) #hydro.particles.add_particles(particles) #channel = hydro.gas_particles.new_channel_to(particles) #hydro.evolve_model(20|units.s) #pyplot.scatter(particles.x.value_in(units.RSun), particles.y.value_in(units.RSun)) #pyplot.show() #R = 1|units.RSun #particles = particles.select(lambda x, y, z: x>R and y>R and z>R,["x", "y", "z"]) #print particles print("N=", len(particles)) run_sph_code(hydro, particles, t_end, dt_diag) def initialize_grid_code(resolution, grid_size): converter = nbody_system.nbody_to_si(1|units.MSun, 1|units.RSun) instance = Athena(converter, number_of_workers=4) instance.initialize_code() instance.parameters.gamma = 5/3.0 instance.parameters.courant_number=0.3 instance.parameters.nx = resolution instance.parameters.ny = resolution instance.parameters.nz = resolution instance.parameters.length_x = grid_size instance.parameters.length_y = grid_size instance.parameters.length_z = grid_size instance.x_boundary_conditions = ("outflow", "outflow") instance.y_boundary_conditions = ("outflow", "outflow") instance.z_boundary_conditions = ("outflow", "outflow") instance.commit_parameters() return instance def initialize_grid(stellar_mass, stellar_radius, core_mass, core_radius, resolution, grid_size): n = resolution r = grid_size.value_in(units.RSun) grid = datamodel.new_regular_grid((n,n,n), [r, r, r] | units.RSun) momentum = units.kg / (units.s * units.m**2) grid_size = units.RSun energy_density = units.erg / grid_size**3 supernova_energy = 1.e+51 | units.erg stellar_energy_density = 0.01*supernova_energy/stellar_radius**3 supernova_energy_density = supernova_energy/core_radius**3 stellar_density = stellar_mass/stellar_radius**3 grid.rho = 1.e-10 * stellar_density grid.rhovx = 0.0 | momentum grid.rhovy = 0.0 | momentum grid.rhovz = 0.0 | momentum grid.energy = 1 | energy_density datamodel.Grid.add_global_vector_attribute("position", ["x","y","z"]) cloud.fill_grid_with_spherical_cloud( grid, center = [5.0, 5.0, 5.0] | units.RSun, radius = stellar_radius, rho = stellar_density, rhovx = 0.0 | momentum, rhovy = 0.0 | momentum, rhovz = 0.0 | momentum, energy = stellar_energy_density ) cloud.fill_grid_with_spherical_cloud( grid, center = [5.0, 5.0, 5.0] | units.RSun, radius = core_radius, rho = core_mass/core_radius**3, rhovx = 0.0 | momentum, rhovy = 0.0 | momentum, rhovz = 0.0 | momentum, energy = supernova_energy_density #subgridsize = 16, ) return grid channel = grid.new_channel_to(instance.grid) channel.copy() def run_grid_code(hydro, grid, t_end, dt_diag): channel = hydro.grid.new_channel_to(grid) dt = 0.2*t_end while hydro.model_time<t_end: print("Time=", hydro.model_time.in_(units.s)) hydro.evolve_model(hydro.model_time + dt) channel.copy() plot_grid(hydro.grid, hydro.model_time) hydro.stop() def run_sph_code(hydro, particles, t_end, dt): hydro.gas_particles.add_particles(particles) write_set_to_file(particles.savepoint(0|units.yr), "supernova_sph.amuse", "amuse", append_to_file=False) index = 1 # plot_sph(0|units.yr, hydro, particles, index) channel = hydro.gas_particles.new_channel_to(particles) while hydro.model_time<t_end: index += 1 print("Time=", hydro.model_time.in_(units.s)) hydro.evolve_model(hydro.model_time + dt) channel.copy_attributes(["x", "y", "z", "rho", "u"]) #plot_sph(particles, hydro.model_time) #plot_sph(hydro.model_time, hydro, particles, index) write_set_to_file(particles.savepoint(hydro.model_time), "supernova_sph.amuse", "amuse") hydro.stop() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-t", unit=units.s, dest="t_end", type="float", default = 500.0|units.s, help="end time of the simulation [%default]") result.add_option("-d", unit=units.s, dest="dt_diag", type="float", default = 50.0|units.s, help="diagnostic time step [%default]") result.add_option("-M", unit=units.MSun, dest="stellar_mass", type="float", default = 3|units.MSun, help="Mass of the star [%default]") result.add_option("-R", unit=units.RSun, dest="stellar_radius", type="float", default = 1|units.RSun, help="Radius of the star [%default]") result.add_option("-m", unit=units.MSun, dest="core_mass", type="float", default = 1.4|units.MSun, help="Mass of the stellar core [%default]") result.add_option("-n", dest="resolution", type="int", default = 300, help="Resolution of the grid [%default]") result.add_option("-r", unit=units.RSun, dest="core_radius", type="float", default = 0.1|units.RSun, help="Radius of the stellar core [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
13,295
37.097421
170
py
amuse
amuse-main/examples/textbook/riemann_shock_tube_problem.py
""" In this script we simulate the riemann shock tube problem in 3d. .. quote: The test set-up consists of two fluids of different densities and pressures separated by a membrane that is then removed. The resulting solution shows all three types of fluid discontinuties; a shock wave moving from the high density fluid to the low density one, a rarefraction (sound) wave moving in the opposite direction and a contact discontinuity which marks the current location of the interface between the two fluids. We follow the directions in the paper: :title: A test suite for quantitative comparison of hydrodynamic codes in astrophyics :authors: Elizabeth J. Tasker, Riccardo Brunino, Nigel L. Mitchell, Dolf Michielsen, Stephen Hopton, Frazer R. Pearce, Greg L. Bryan, Tom Theuns :journal: Monthly Notices of the Royal Astronomical Society :issue: Volume 390, Issue 3, pages 1267-1281, November 2008 :doi: DOI: 10.1111/j.1365-2966.2008.13836.x See also: :site: http://www.astro.ufl.edu/~tasker/codecomparison2/codecomparison_riemann.html Exact solution is based on fortran code from Frank Timmer (who based it on code from Bruce Fryxell), see: http://cococubed.asu.edu/code_pages/exact_riemann.shtml """ from amuse.support.core import late from amuse import io from amuse.io import text from amuse.units import constants from amuse.units.generic_unit_converter import ConvertBetweenGenericAndSiUnits from amuse.units.nbody_system import nbody_to_si from amuse.units.quantities import VectorQuantity from amuse.units.generic_unit_system import * from amuse.community.athena.interface import Athena from amuse.community.capreole.interface import Capreole from amuse.community.mpiamrvac.interface import MpiAmrVac from amuse.community.gadget2.interface import Gadget2 from amuse.community.fi.interface import Fi from amuse.ext.grid_to_sph import convert_grid_to_SPH import numpy try: from amuse import plot from matplotlib import pyplot IS_PLOT_AVAILABLE = True except ImportError: IS_PLOT_AVAILABLE = False from numpy import sqrt, arange, searchsorted from optparse import OptionParser from amuse.datamodel import Grid from amuse.datamodel import Particles from amuse.datamodel.grids import SamplePointsOnMultipleGrids from amuse.datamodel.grids import SamplePointWithIntepolation from amuse.datamodel.grids import SamplePointOnCellCenter class CalculateExactSolutionIn1D(object): number_of_points = 1000 rho1 = 4.0 | density p1 = 1.0 | mass / (length * (time**2)) u1 = 0.0 | speed rho5 = 1.0 | density p5 = 0.1795 | mass / (length * (time**2)) u5 = 0.0 | speed gamma = 5.0/3.0 def get_post_shock_pressure_p4(self, maximum_number_of_iterations = 20, maxium_allowable_relative_error = 1e-5): """solve for post-shock pressure by secant method""" p40 = self.p1 p41 = self.p5 p4 = p41 f0 = self.calculate_p4_from_previous_value(p40) for x in range(maximum_number_of_iterations): f1 = self.calculate_p4_from_previous_value(p41) if (f1 == f0): return p4 p4 = p41 - (p41 - p40) * f1 / (f1 - f0) error = abs (p4 - p41) / p41 if (error < maxium_allowable_relative_error): return p4 p40 = p41 p41 = p4 f0 = f1 raise Exception("solution did not converge in less than {0!r} steps.".format(maximum_number_of_iterations)) def get_post_shock_density_and_velocity_and_shock_speed(self, p4): z = (p4 / self.p5 - 1.0) c5 = (self.gamma * self.p5 / self.rho5).sqrt() gm1 = self.gamma - 1.0 gp1 = self.gamma + 1.0 gmfac1 = 0.5 * gm1 / self.gamma gmfac2 = 0.5 * gp1 / self.gamma fact = sqrt (1. + gmfac2 * z) u4 = c5 * z / (self.gamma * fact) rho4 = self.rho5 * (1.0 + gmfac2 * z) / (1.0 + gmfac1 * z) return u4, rho4, c5 * fact def calculate_p4_from_previous_value(self, p4): c1 = sqrt(self.gamma * self.p1 / self.rho1) c5 = sqrt(self.gamma * self.p5 / self.rho5) gm1 = self.gamma - 1.0 gp1 = self.gamma + 1.0 g2 = 2.0 * self.gamma z= (p4 / self.p5 - 1.0) fact = gm1 / g2 * (c5 / c1) * z / sqrt (1. + gp1 / g2 * z) fact = (1. - fact) ** (g2 / gm1) return self.p1 * fact - p4 def get_solution_at_time(self, t): p4 = self.get_post_shock_pressure_p4() u4, rho4, w = self.get_post_shock_density_and_velocity_and_shock_speed(p4) #compute values at foot of rarefaction p3 = p4 u3 = u4 rho3 = self.rho1 * (p3 / self.p1)**(1. /self.gamma) c1 = sqrt (self.gamma * self.p1 / self.rho1) c3 = sqrt (self.gamma * p3 / rho3) xi = 0.5 | length xr = 1.0 | length xl = 0.0 | length xsh = xi + w * t xcd = xi + u3 * t xft = xi + (u3 - c3) * t xhd = xi - c1 * t gm1 = self.gamma - 1.0 gp1 = self.gamma + 1.0 dx = (xr - xl) / (self.number_of_points - 1) x = xl + dx * arange(self.number_of_points) rho = VectorQuantity.zeros(self.number_of_points, density) p = VectorQuantity.zeros(self.number_of_points, mass / (length * time**2)) u = VectorQuantity.zeros(self.number_of_points, speed) for i in range(self.number_of_points): if x[i] < xhd: rho[i] = self.rho1 p[i] = self.p1 u[i] = self.u1 elif x[i] < xft: u[i] = 2. / (self.gamma + 1.0) * (c1 + (x[i] - xi) / t) fact = 1. - 0.5 * gm1 * u[i] / c1 rho[i] = self.rho1 * fact ** (2. / gm1) p[i] = self.p1 * fact ** (2. * self.gamma / gm1) elif x[i] < xcd: rho[i] = rho3 p[i] = p3 u[i] = u3 elif x[i] < xsh: rho[i] = rho4 p[i] = p4 u[i] = u4 else: rho[i] = self.rho5 p[i] = self.p5 u[i] = self.u5 return x, rho,p,u class CalculateSolutionIn3D(object): number_of_workers = 1 number_of_grid_points = 10 gamma = 5.0/3.0 name_of_the_code = "capreole" hydro_code_options = dict()#redirection="none") convert_generic_units = ConvertBetweenGenericAndSiUnits( 1.0 | units.kpc, 1.0e10 | units.MSun, constants.G) convert_nbody_units = nbody_to_si( 1.0 | units.kpc, 1.0e10 | units.MSun) def __init__(self, **keyword_arguments): for x in keyword_arguments: print(x, keyword_arguments[x]) setattr(self, x, keyword_arguments[x]) self.dimensions_of_mesh = ( self.number_of_grid_points * 3, self.number_of_grid_points, self.number_of_grid_points ) def new_instance_of_code(self): attribute = "new_instance_of_{0}_code".format(self.name_of_the_code.lower()) return getattr(self,attribute)() def new_instance_of_athena_code(self): result=Athena(number_of_workers=self.number_of_workers, **self.hydro_code_options) result.initialize_code() result.parameters.gamma = self.gamma result.parameters.courant_number=0.3 return result def new_instance_of_mpiamrvac_code(self): result=MpiAmrVac(number_of_workers=self.number_of_workers, **self.hydro_code_options) result.set_parameters_filename(result.default_parameters_filename) result.initialize_code() return result def new_instance_of_capreole_code(self): result=Capreole(number_of_workers=self.number_of_workers, **self.hydro_code_options) result.initialize_code() return result grid_hydro_codes = ("athena", "mpiamrvac", "capreole") def new_instance_of_gadget2_code(self): result=Gadget2(self.convert_generic_units, number_of_workers=self.number_of_workers, mode = "periodic", **self.hydro_code_options) result.initialize_code() return result def new_instance_of_fi_code(self): result=Fi(self.convert_nbody_units, number_of_workers=self.number_of_workers, mode = "periodic", **self.hydro_code_options) result.initialize_code() result.parameters.self_gravity_flag = False result.parameters.timestep = 0.01 | time return result sph_hydro_codes = ("gadget2", "fi") def set_parameters(self, instance): if self.name_of_the_code in self.sph_hydro_codes: instance.parameters.periodic_box_size = 1.0 | length else: instance.parameters.mesh_size = self.dimensions_of_mesh instance.parameters.length_x = 1 | length instance.parameters.length_y = 1 | length instance.parameters.length_z = 1 | length instance.parameters.x_boundary_conditions = ("periodic","periodic") instance.parameters.y_boundary_conditions = ("periodic","periodic") instance.parameters.z_boundary_conditions = ("periodic","periodic") result = instance.commit_parameters() def new_grid(self): grid = Grid.create(self.dimensions_of_mesh, [1,1,1] | length) self.clear_grid(grid) return grid def clear_grid(self, grid): density = mass / length**3 momentum = speed * density energy = mass / (time**2 * length) grid.rho = 0.0 | density grid.rhovx = 0.0 | momentum grid.rhovy = 0.0 | momentum grid.rhovz = 0.0 | momentum grid.energy = 0.0 | energy return grid def initialize_grid_with_shock(self, grid): energy = mass / (time**2 * length) halfway = self.dimensions_of_mesh[0]/2 - 1 firsthalf = grid.x <= 0.5 | length secondhalf = grid.x > 0.5 | length grid[firsthalf].rho = 4.0 | density grid[firsthalf].energy = (1.0 | energy)/ (self.gamma - 1) grid[secondhalf].rho = 1.0 | density grid[secondhalf].energy = (0.1795 | energy)/ (self.gamma - 1) def set_initial_conditions(self, instance): if self.name_of_the_code in self.sph_hydro_codes: initial_grid = self.new_grid() self.initialize_grid_with_shock(initial_grid) if self.name_of_the_code == "fi": initial_grid.position -= 0.5 | length sph_particles = convert_grid_to_SPH(initial_grid, self.number_of_particles) instance.gas_particles.add_particles(sph_particles) else: for x in instance.itergrids(): inmem = x.copy() self.clear_grid(inmem) self.initialize_grid_with_shock(inmem) from_model_to_code = inmem.new_channel_to(x) from_model_to_code.copy() instance.initialize_grid() def copy_results(self, instance): if self.name_of_the_code in self.sph_hydro_codes: n_samples = self.number_of_grid_points * 3 result = Particles(n_samples) result.position = [(x, 0.5, 0.5) | length for x in numpy.linspace(0.0, 1.0, n_samples)] x, y, z = result.x, result.y, result.z if self.name_of_the_code == "fi": x -= (0.5 | length) y -= (0.5 | length) z -= (0.5 | length) no_speed = [0.0]*n_samples | speed result.rho, result.rhovx, result.rhovy, result.rhovz, result.energy = [ self.convert_generic_units.to_generic(quantity) for quantity in instance.get_hydro_state_at_point(x, y, z, no_speed, no_speed, no_speed)] else: result = [] for x in instance.itergrids(): result.append(x.copy()) return result def get_solution_at_time(self, time): instance=self.new_instance_of_code() self.set_parameters(instance) self.set_initial_conditions(instance) print("start evolve") instance.evolve_model(time) print("copying results") result = self.copy_results(instance) print("terminating code") instance.stop() return result def store_attributes(x, rho, rhovx, energy, filename): output = text.CsvFileText(filename = filename) output.quantities = (x, rho, rhovx, energy) output.attribute_names = ("x", "rho", "rhovx", "energy") output.store() def store_attributes_of_line(grid, yindex = 0, zindex = 0, **options): store_attributes( grid.x[...,yindex,zindex], grid.rho[...,yindex,zindex], grid.rhovx[...,yindex,zindex], grid.energy[...,yindex,zindex], filename = "riemann_shock_tube_{name_of_the_code}_{number_of_grid_points}_{number_of_workers}.csv".format(**options) ) def new_option_parser(): result = OptionParser() result.add_option( "-n", "--mesh-size", dest="number_of_grid_points", type="int", default = 10, help="number of grid cells in the x, y and z direction" ) result.add_option( "-w", "--workers", dest="number_of_workers", type="int", default = 1, help="number of parallel workers to start" ) result.add_option( "-c", "--code", dest="name_of_the_code", default="athena", help="name of the code to use" ) result.add_option( "-p", "--number_of_particles", dest="number_of_particles", type="int", default = 10000, help="number of particles, in case code is an SPH code" ) return result def test_riemann_shocktube_problem(): exact = CalculateExactSolutionIn1D() x, rho, p, u = exact.get_solution_at_time(0.12 | time) model = CalculateSolutionIn3D() model.name_of_the_code = "capreole" model.dimensions_of_mesh = (500,1,1) grids = model.get_solution_at_time(0.12 | time) grid = grids[0] model_x = grid.x[...,0,0] density = grid.rho[...,0,0] index_in_model = searchsorted(model_x.value_in(length), 0.56) index_in_exact = searchsorted(x.value_in(length), 0.56) #store_attributes_of_line(grid, name_of_the_code = "athena-test", number_of_grid_points = 500, number_of_workers = 1) assert abs((rho[index_in_exact] - density[index_in_model])/ density[index_in_model]) < 1.e-3 |units.none 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 single_frame 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() if __name__ == "__main__": options, arguments = new_option_parser().parse_args() main(**options.__dict__)
16,995
34.408333
124
py
amuse
amuse-main/examples/textbook/electrontemperature_profile_of_H2cloud.py
""" Evolves the steady state solution of a star irridiating a H2 region. """ import numpy import os from matplotlib import pyplot from optparse import OptionParser from amuse.lab import * from amuse.community.mocassin.interface import Mocassin, mocassin_rydberg_unit from amuse.units import units from amuse.units import nbody_system from amuse.ext.protodisk import ProtoPlanetaryDisk from amuse.datamodel import Particle from amuse.datamodel import Grid from amuse.io import write_set_to_file from distinct_colours import get_distinct ###BOOKLISTSTART1### def make_grid(number_of_grid_cells, length, constant_hydrogen_density, inner_radius, outer_radius): grid = Grid.create([number_of_grid_cells] * 3, length.as_vector_with_length(3)) grid.radius = grid.position.lengths() grid.hydrogen_density = constant_hydrogen_density grid.hydrogen_density[grid.radius <= inner_radius] = 0 | units.cm ** -3 grid.hydrogen_density[grid.radius >= outer_radius] = 0 | units.cm ** -3 return grid ###BOOKLISTSTOP1### def setup_abundancies(code): table = code.abundancies_table() for atom in list(table.keys()): table[atom] = 0.0 table['H'] = 1.0 table['He'] = 0.1 table['C'] = 2.2e-4 table['N'] = 4.e-5 table['O'] = 3.3e-4 table['Ne'] = 5.e-5 table['S'] = 9.e-6 def plot_temperature_line(radii, electron_temperatures, ci): colors = get_distinct(4) s = 100 if ci==1: s = 50 pyplot.scatter(radii.value_in(units.parsec), electron_temperatures.value_in(units.K), c=colors[ci], lw=0, s=s) pyplot.xlabel('R [pc]') pyplot.ylabel('T [K]') pyplot.xlim(0.8, 3.2) # pyplot.ylim(6000,9000) # pyplot.show() # pyplot.savefig("electrontemperature_profile_of_H2cloud") def evolve_star(mass, age, position): star=Particles(1) star.position = position star.mass = mass stellar = SeBa() stellar.particles.add_particles(star) stellar.evolve_model(age) star.luminosity = stellar.particles.luminosity star.temperature = stellar.particles.temperature stellar.stop() return star def setup_grid(radiative_transfer, outer_radius, Ngrid): radiative_transfer.parameters.length_x = outer_radius radiative_transfer.parameters.length_y = outer_radius radiative_transfer.parameters.length_z = outer_radius radiative_transfer.parameters.mesh_size = [Ngrid, Ngrid, Ngrid] ###BOOKLISTSTART2### def initiate_radiative_transfer_code(outer_radius, Ngrid): radiative_transfer = Mocassin(number_of_workers = 4) radiative_transfer.set_input_directory( radiative_transfer.get_default_input_directory()) radiative_transfer.set_mocassin_output_directory( radiative_transfer.output_directory + os.sep) radiative_transfer.initialize_code() radiative_transfer.set_symmetricXYZ(True) setup_grid(radiative_transfer, outer_radius, Ngrid) setup_abundancies(radiative_transfer) radiative_transfer.parameters.initial_nebular_temperature = 6000.0 | units.K radiative_transfer.parameters.high_limit_of_the_frequency_mesh \ = 15 | mocassin_rydberg_unit radiative_transfer.parameters.low_limit_of_the_frequency_mesh \ = 1.001e-5 | mocassin_rydberg_unit radiative_transfer.parameters.total_number_of_photons = 10000000 radiative_transfer.parameters.total_number_of_points_in_frequency_mesh = 600 radiative_transfer.parameters.convergence_limit = 0.09 radiative_transfer.parameters.number_of_ionisation_stages = 6 radiative_transfer.commit_parameters() return radiative_transfer ###BOOKLISTSTOP2### def main(number_of_grid_cells = 15, min_convergence = 20): cloud_center = [0.0, 0.0, 0.0] | units.AU star = evolve_star(120|units.MSun, 3.3|units.Myr, cloud_center) outer_radius = 3.0 | units.parsec grid=make_grid(number_of_grid_cells = number_of_grid_cells, length = outer_radius, constant_hydrogen_density = 100 | units.cm**-3, inner_radius = 1.0 | units.parsec, outer_radius = outer_radius) radiative_transfer \ = initiate_radiative_transfer_code(outer_radius, number_of_grid_cells) radiative_transfer.grid.hydrogen_density = grid.hydrogen_density radiative_transfer.commit_grid() radiative_transfer.particles.add_particle(star) radiative_transfer.commit_particles() max_number_of_photons \ = radiative_transfer.parameters.total_number_of_photons * 100 percentage_converged = previous_percentage_converged = 0.0 grid.electron_temperature = radiative_transfer.grid.electron_temperature radius = grid.radius.flatten() electron_temperature = grid.electron_temperature.flatten() selection = electron_temperature > 0 | units.K pyplot.rcParams.update({'font.size': 30}) figure = pyplot.figure(figsize=(16, 12)) ax = pyplot.gca() ax.minorticks_on() # switch on the minor ticks ax.locator_params(nbins=3) plot_temperature_line(radius[selection], electron_temperature[selection], 0) ###BOOKLISTSTART3### step = 0 while percentage_converged < min_convergence: radiative_transfer.step() percentage_converged = radiative_transfer.get_percentage_converged() print("percentage converged :", percentage_converged, ", step :", step, ", photons:", radiative_transfer.parameters.total_number_of_photons) if previous_percentage_converged > 5 and percentage_converged < 95: convergence_increase \ = (percentage_converged - previous_percentage_converged) \ / previous_percentage_converged if convergence_increase < 0.2 \ and radiative_transfer.parameters.total_number_of_photons\ < max_number_of_photons: radiative_transfer.parameters.total_number_of_photons *= 2 step += 1 previous_percentage_converged = percentage_converged ###BOOKLISTSTOP3### grid.electron_temperature = radiative_transfer.grid.electron_temperature radius = grid.radius.flatten() electron_temperature = grid.electron_temperature.flatten() selection = electron_temperature > 0 | units.K plot_temperature_line(radius[selection], electron_temperature[selection], 1) pyplot.savefig("electrontemperature_profile_of_H2cloud") #pyplot.show() write_set_to_file(grid, 'h2region.h5', 'amuse') def new_option_parser(): result = OptionParser() result.add_option( "-n", "--gridcells", default = 13, dest="number_of_grid_cells", help="number of cells in each direction", type="int" ) result.add_option( "-c", "--min-convergence", default = 60, dest="min_convergence", help="stop the iteratation when the solution is converged to the given percentage (in whole numbers between 10 and 100)", type="int" ) return result if __name__ == "__plot__": main(13, 30) if __name__ == "__main__": options, arguments = new_option_parser().parse_args() main(**options.__dict__)
7,291
34.398058
129
py
amuse
amuse-main/examples/textbook/plot_1987ApJ...323..614B.py
from amuse.lab import * #from amuse.plot import sph_particles_plot from amuse.plot import * from prepare_figure import * #from distinct_colours import get_distinct def get_zones(stars): stars.move_to_center() from amuse.ext.LagrangianRadii import LagrangianRadii massf = [0.25, 0.50, 0.75, 1.0] lagrad = LagrangianRadii(stars, massf = massf) for zi in lagrad: print("R=", zi.in_(units.RSun)) center_of_mass = [0,0,0] | units.RSun #initial_stars.center_of_mass() zoneA = stars.select(lambda r: (center_of_mass-r).length()<lagrad[0], ["position"]) zoneB = stars.select(lambda r: (center_of_mass-r).length()<lagrad[1], ["position"]) zoneC = stars.select(lambda r: (center_of_mass-r).length()<lagrad[2], ["position"]) zoneC -= zoneB zoneB -= zoneA zoneD = stars.select(lambda r: (center_of_mass-r).length()>lagrad[2], ["position"]) print("N=", len(zoneA), len(zoneB), len(zoneC), len(zoneD)) return (zoneA, zoneB, zoneC, zoneD) def _get_number_of_particles_in_zone(iz, initial_stars, initial_zones, final_zones): range_list = [0,1,2,3] range_list.pop(iz) print(range_list) fzA = initial_stars.copy() for i in range_list: fzA -= final_zones[i] nzA = [0,0,0,0] for izi in range(len(initial_zones)): for fzi in fzA: if fzi in initial_zones[izi]: nzA[izi] +=1 print("iz=", iz, nzA) return nzA def get_number_of_particles_in_zone(iz, initial_stars, initial_zones, final_star, final_zones): range_list = [0,1,2,3] range_list.pop(iz) print(range_list) fzA = final_zones[iz] not_selected = final_star - final_zones[iz] print(iz, len(initial_stars), len(not_selected)) initial_subset = initial_stars - not_selected print(len(initial_subset)) nzA = [0,0,0,0] for iz in range(len(initial_zones)): for siz in initial_subset: if siz in initial_zones[iz]: nzA[iz] +=1 """ # Normalize import numpy nzA_sum = float(numpy.sum(nzA)) print "sum:", nzA_sum for i in range(len(nzA)): nzA[i] /= nzA_sum print nzA """ """ print nzA from matplotlib import pyplot pyplot.scatter(final_star.x.value_in(units.RSun), final_star.y.value_in(units.RSun), s=1) pyplot.scatter(fzA.x.value_in(units.RSun), fzA.y.value_in(units.RSun)) pyplot.show() """ print(nzA) return nzA def find_clumps(particles): unit_converter = nbody_system.nbody_to_si(1|units.MSun, 1|units.RSun) hop = Hop(unit_converter) hop.particles.add_particles(particles) hop.calculate_densities() mean_densty = hop.particles.density.mean() hop.parameters.peak_density_threshold = mean_densty hop.parameters.saddle_density_threshold = 0.99*mean_densty hop.parameters.outer_density_threshold = 0.01*mean_densty hop.do_hop() result = [x.get_intersecting_subset_in(particles) for x in hop.groups()] hop.stop() return result def plot_collide_two_stars(time, filename): from matplotlib import pyplot figure = pyplot.figure(figsize=(14, 8)) ax1 = figure.add_subplot(111) ax1.axis('off') if filename: process_file(time, filename, figure) else: n = 0.8 bars = ax1.bar(list(range(1, 5)), [n,0,0,0], color='None', ecolor='black', hatch='//') +\ ax1.bar(list(range(1, 5)), [n,0,0,0], color='None', ecolor='black', hatch='\\\\') +\ ax1.bar(list(range(1, 5)), [0,n,0,0], color='None', ecolor='black', hatch='\\\\') +\ ax1.bar(list(range(1, 5)), [0,0,n,0], color='None', ecolor='black', hatch='*') +\ ax1.bar(list(range(1, 5)), [0,0,0,n], color='None', ecolor='black', hatch='.') pyplot.savefig("1987ApJ323_614B") #pyplot.show() def process_file(time, filename, figure): fileA = "Hydro_AM06MSun.h5" pstar = read_set_from_file(fileA, format='hdf5') fileB = "Hydro_BM06MSun.h5" sstar = read_set_from_file(fileB, format='hdf5') initial_stars = Particles(0) initial_stars.add_particles(pstar) initial_stars.add_particles(sstar) final_star = Particles(0) merger = read_set_from_file(filename, "hdf5") for si in merger.history: ts = si.get_timestamp() print(ts, time, len(si)) if ts >= time: final_star.add_particles(si) break """ clumps = find_clumps(final_star) for clump in clumps: print "N=", len(clump) final_star = clumps[0] """ initial_zones = get_zones(initial_stars) final_zones = get_zones(final_star) nA0 = get_number_of_particles_in_zone(0, initial_stars, initial_zones, final_star, final_zones) nA1 = get_number_of_particles_in_zone(1, initial_stars, initial_zones, final_star, final_zones) nA2 = get_number_of_particles_in_zone(2, initial_stars, initial_zones, final_star, final_zones) nA3 = get_number_of_particles_in_zone(3, initial_stars, initial_zones, final_star, final_zones) ax2 = pyplot.gca() from operator import add bars = ax2.bar(list(range(1, 5)), nA0, bottom=[0,0,0,0], color='None', ecolor='black', hatch='//') +\ ax2.bar(list(range(1, 5)), nA0, color='None', ecolor='black', hatch='\\\\') +\ ax2.bar(list(range(1, 5)), nA1, bottom=nA0, color='None', ecolor='black', hatch='\\\\') +\ ax2.bar(list(range(1, 5)), nA2, bottom=list(map(add, nA0, nA1)), color='None', ecolor='black', hatch='/') +\ ax2.bar(list(range(1, 5)), nA3, bottom=list(map(add, nA0, list(map(add, nA1, nA2)))), color='None', ecolor='black', hatch='.') # ax2.set_xticks([1, 2, 3, 4]) #pyplot.show() pyplot.savefig("1987ApJ323_614B") def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-f", dest="filename", default="1987ApJ...323..614B_headon.h5", help="filename [%default]") result.add_option("-t", unit=units.hour, dest="time", type="float", default=7|units.hour, help="plotting time [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() print(o.time) plot_collide_two_stars(o.time, o.filename)
6,385
35.284091
137
py
amuse
amuse-main/examples/textbook/gravity_potential.py
#from __future__ import print_function import numpy from amuse.units import units from amuse.units import quantities from amuse.units import constants from amuse.units import nbody_system from amuse.ext.bridge import bridge from amuse.community.phigrape.interface import PhiGRAPE from amuse.community.ph4.interface import ph4 from amuse.community.fi.interface import Fi from amuse.community.bhtree.interface import BHTree from amuse.community.gadget2.interface import Gadget2 from matplotlib import pyplot from amuse.ic.kingmodel import new_king_model """ Implements a code simulating the galactic center. As the center itself does not evolve we only need to define the 'get_gravity_at_point' and 'get_potential_at_point'. Note that both functions get arrays of points. """ ###BOOKLISTSTART1### class GalacticCenterGravityCode(object): def __init__(self,R, M, alpha): self.radius=R self.mass=M self.alpha=alpha def get_gravity_at_point(self,eps,x,y,z): r2=x**2+y**2+z**2 r=r2**0.5 m=self.mass*(r/self.radius)**self.alpha fr=constants.G*m/r2 ax=-fr*x/r ay=-fr*y/r az=-fr*z/r return ax,ay,az def circular_velocity(self,r): m=self.mass*(r/self.radius)**self.alpha vc=(constants.G*m/r)**0.5 return vc ###BOOKLISTSTOP1### def get_potential_at_point(self,eps,x,y,z): r=(x**2+y**2+z**2)**0.5 c=constants.G*self.mass/self.radius**self.alpha phi=c/(self.alpha-1)*(r**(self.alpha-1)-self.radius**(self.alpha-1)) return phi ###BOOKLISTSTART3### def make_king_model_cluster(nbodycode, N, W0, Mcluster, Rcluster, parameters = []): converter=nbody_system.nbody_to_si(Mcluster,Rcluster) bodies=new_king_model(N,W0,convert_nbody=converter) code=nbodycode(converter) for name,value in parameters: setattr(code.parameters, name, value) code.particles.add_particles(bodies) return code ###BOOKLISTSTOP3### def plot_cluster(x, y): from prepare_figure import single_frame, get_distinct colors = get_distinct(1) f = single_frame('X [pc]', 'Y [pc]') pyplot.xlim(-60, 60) pyplot.ylim(-60, 60) pyplot.scatter(x,y, c=colors[0], s=50, lw=0) save_file = 'Arches Fig. 7.1.png' pyplot.savefig(save_file) print('\nSaved figure in file', save_file, '\n') pyplot.show() def evolve_cluster_in_galaxy(N, W0, Rinit, tend, timestep, M, R): ###BOOKLISTSTART2### Rgal = 1. | units.kpc Mgal = 1.6e10 | units.MSun alpha = 1.2 galaxy_code = GalacticCenterGravityCode(Rgal, Mgal, alpha) cluster_code = make_king_model_cluster(BHTree, N, W0, M, R, parameters=[("epsilon_squared", (0.01 | units.parsec)**2)]) stars = cluster_code.particles.copy() stars.x += Rinit stars.vy = 0.8*galaxy_code.circular_velocity(Rinit) channel = stars.new_channel_to(cluster_code.particles) channel.copy_attributes(["x","y","z","vx","vy","vz"]) system = bridge(verbose=False) system.add_system(cluster_code, (galaxy_code,)) times = quantities.arange(0|units.Myr, tend, timestep) for i,t in enumerate(times): system.evolve_model(t,timestep=timestep) x = system.particles.x.value_in(units.parsec) y = system.particles.y.value_in(units.parsec) cluster_code.stop() ###BOOKLISTSTOP2### return x, y if __name__ == "__main__": N=1024 W0=3 Rinit=50. | units.parsec timestep=0.01 | units.Myr endtime = 2.5 | units.Myr Mcluster = 5.e4 | units.MSun Rcluster = 0.8 | units.parsec x, y = evolve_cluster_in_galaxy(N, W0, Rinit, endtime, timestep, Mcluster, Rcluster) plot_cluster(x, y)
3,883
30.577236
83
py
amuse
amuse-main/examples/textbook/plot_solar_comparison.py
import numpy from amuse.lab import * from amuse.units.optparse import OptionParser from matplotlib import pyplot from amuse.plot import scatter from prepare_figure import single_frame from distinct_colours import get_distinct from amuse.community.seba.interface import SeBa def main(t_end, mass, z, Tstar, Lstar): stellar_evolution_codes = [SeBa(), SSE(), MESA(), EVtwin()] label = ["SeBa", "SSE", "MESA", "EVtwin"] marker = ["o", "v", "<", ">"] x_label = "$(T-T_\odot)/T_\odot)$" y_label = "$(L-L_\odot)/L_\odot)$" figure = single_frame(x_label, y_label, logy=False, xsize=14, ysize=10) pyplot.xlim(-0.006, 0.004) pyplot.ylim(-0.1, 0.1) color = get_distinct(6) pyplot.scatter([0], [0], marker="o", c=color[3], label="Sun", s=200, lw=0) for si in range(len(stellar_evolution_codes)): stellar = stellar_evolution_codes[si] stellar.parameters.metallicity = z star = Particles(1) star.mass = mass t_end = 6000.0 | units.Myr stellar.particles.add_particles(star) attributes = ["temperature", "luminosity","age"] to_framework = stellar.particles.new_channel_to(star, attributes=attributes, target_names=attributes) t = [] | units.Myr T = [] L = [] min_dist_sun = 10000.0 current_time = 3000.0 | units.Myr print(label[si]) #dt = 50 | units.Myr #time = 4000 | units.Myr while stellar: print(stellar.model_time.value_in(units.Myr)) current_time = current_time + stellar.particles[0].time_step stellar.evolve_model(current_time) to_framework.copy() if star[0].age >= t_end: stellar.stop() stellar = False else: L.append((star[0].luminosity - Lstar)/Lstar) T.append((star[0].temperature - Tstar)/Tstar) t.append(star[0].age) deltaL = numpy.abs((star[0].luminosity - Lstar)/Lstar) deltaT = numpy.abs((star[0].temperature - Tstar)/Tstar) dist = numpy.sqrt(deltaL*deltaL + deltaT*deltaT) if min_dist_sun > dist: min_dist_sun = dist L_sim_sun = (star[0].luminosity - Lstar)/Lstar T_sim_sun = (star[0].temperature - Tstar)/Tstar eta = star[0].age print(eta) if si==3: pyplot.plot(T, L,ls='-', marker=marker[si], color=color[5], markersize=10) pyplot.scatter(T_sim_sun, L_sim_sun, marker=marker[si], color=color[5], label=label[si], s=300, lw=1) else: pyplot.plot(T, L,ls='-', marker=marker[si], color=color[si], markersize=10) pyplot.scatter(T_sim_sun, L_sim_sun, marker=marker[si], color=color[si], label=label[si], s=300, lw=1) pyplot.legend(scatterpoints=1, loc='best') save_file = 'fig_SunComparison.png' pyplot.savefig(save_file) print('\nSaved figure in file', save_file,'\n') pyplot.show() def new_option_parser(): result = OptionParser() result.add_option("-T", unit=units.K, dest="Tstar", type="float",default = 5778 |units.K, help="stellar temperature [%defailt]") result.add_option("-L", unit=units.LSun, dest="Lstar", type="float",default = 1 |units.LSun, help="stellar luminosity [%defailt]") result.add_option("-m", unit=units.MSun, dest="mass", type="float",default = 1.0 |units.MSun, help="stellar mass [%defailt]") result.add_option("-t", unit=units.Myr, dest="t_end", type="float", default = 4.6 |units.Gyr, help="end time of the simulation [%defailt]") result.add_option("-z", dest="z", type="float", default = 0.02, help="metalicity [%defailt]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
4,292
36.657895
87
py
amuse
amuse-main/examples/textbook/plot_projected_disk_temp_from_top.py
""" Visualization for simple N-body integration. Reads particle set from file (nbody.hdf5) and prints subsequent frames. """ import os import sys import numpy import matplotlib #matplotlib.use('Agg') from matplotlib import pyplot #from matplotlib import pyplot from amuse.plot import scatter, xlabel, ylabel from amuse.lab import * from amuse.io import store from optparse import OptionParser from amuse.units.optparse import OptionParser from time import sleep from amuse.ext.orbital_elements import orbital_elements_from_binary def mu(X = None, Y = 0.25, Z = 0.02, x_ion = 0.1): """ Compute the mean molecular weight in kg (the average weight of particles in a gas) X, Y, and Z are the mass fractions of Hydrogen, of Helium, and of metals, respectively. x_ion is the ionisation fraction (0 < x_ion < 1), 1 means fully ionised """ if X is None: X = 1.0 - Y - Z elif abs(X + Y + Z - 1.0) > 1e-6: raise Exception("Error in calculating mu: mass fractions do not sum to 1.0") return constants.proton_mass / (X*(1.0+x_ion) + Y*(1.0+2.0*x_ion)/4.0 + Z*x_ion/2.0) def plot_single_image(planets, debris, disk, shell, figfile=None): if len(shell)>0: disk.add_particles(shell) lim = 150 """ #centered on the Sun if len(planets)>1: print "Center on COM" com = planets[0].position vcom = planets[0].velocity planets.position -= com planets.velocity -= vcom disk.position -= com disk.velocity -= vcom debris.position -= com debris.velocity -= vcom """ left, width = 0.1, 0.65 bottom, height = 0.1, 0.65 bottom_h = left_h = left+width+0.05 rect_scatter = [left, bottom, width, height] rect_histx = [left, bottom_h, width, 0.2] rect_histy = [left_h, bottom, 0.2, height] fig = pyplot.figure(figsize=(12,12)) time = disk.get_timestamp() # pyplot.title("Cluster at t="+str(time.in_(units.Gyr))) xy = pyplot.axes(rect_scatter) #xy.text(110,110, "protoplanetary disk (img#"+str(index)+")", ha='left', va='bottom') xz = pyplot.axes(rect_histx) yz = pyplot.axes(rect_histy) xy.set_xlabel("X [AU]") xy.set_ylabel("Y [AU]") xz.set_ylabel("Z [AU]") yz.set_xlabel("Z [AU]") positions = disk.position x, y, z = positions.x.value_in(units.AU), positions.y.value_in(units.AU), positions.z.value_in(units.AU) # sizes = 1000 # sizes = 1000*disk.rho/disk.rho.max() alpha = 0.01 us = disk.u if hasattr(disk, "xion"): xs = disk.xion else: xs = numpy.zeros(len(disk)) u_min, u_max = min(us), max(us) xion_min, xion_max = min(xs), max(xs) # if xion_min<=0: # xion_min = xion_max/100. # xs += xion_min # xion_max += xion_min print("u=", u_min, u_max) Ts = mu() / constants.kB * disk.u T_min = max(20|units.K, mu() / constants.kB * u_min) T_max = min(1800|units.K, mu() / constants.kB * u_max) print("T=", T_min, T_max) print("X=", xion_min, xion_max) log_u = numpy.log((us / u_min)) / numpy.log((u_max / u_min)) clipped_log_u = numpy.minimum(numpy.ones_like(log_u), numpy.maximum(numpy.zeros_like(log_u), log_u)) # log_x = numpy.log((xs / xion_min)) / numpy.log((xion_max / xion_min)) # clipped_log_x = numpy.minimum(numpy.ones_like(log_x), numpy.maximum(numpy.zeros_like(log_x), log_x)) # xrange = (xs/xion_min) / (xion_max/xion_min) # print "xrange=", xrange.min(), xrange.max() clipped_log_x = xs log_T = numpy.log((Ts / T_min)) / numpy.log((T_max / T_min)) clipped_log_T = numpy.minimum(numpy.ones_like(log_T), numpy.maximum(numpy.zeros_like(log_T), log_T)) ps = disk.rho p_min, p_max = min(ps), max(ps) log_p = numpy.log((ps / p_min)) / numpy.log((p_max / p_min)) clipped_log_p = numpy.minimum(numpy.ones_like(log_p), numpy.maximum(numpy.zeros_like(log_p), log_p)) # red = 1 - clipped_log_u**(1./2.) # blue = clipped_log_u**(1./2.) # green = numpy.minimum(red, blue) # red = 1.0 - clipped_log_T # red = 1-clipped_log_x**(1./2.) blue = clipped_log_T red = 1-clipped_log_T #green = numpy.minimum(red, blue) green = clipped_log_p colors = numpy.transpose(numpy.array([red, green, blue])) sizes = 2*2000*disk.h_smooth/disk.h_smooth.max() xy.scatter(x, y, sizes, c=colors, edgecolors = "none", alpha = alpha) xy.set_xlim( (-lim, lim) ) xy.set_ylim( (-lim, lim) ) sizes = 2*200*disk.h_smooth/disk.h_smooth.max() xz.scatter(x, z, sizes, c=colors, edgecolors = "none", alpha = alpha) yz.scatter(z, y, sizes, c=colors, edgecolors = "none", alpha = alpha) xz.set_xlim( xy.get_xlim() ) yz.set_ylim( xy.get_xlim() ) yz.set_xlim( (-0.1*lim, 0.1*lim) ) xz.set_ylim( (-0.1*lim, 0.1*lim) ) # yz.set_xlim( (-lim, lim) ) # xz.set_ylim( (-lim, lim) ) if len(debris)>0: c = 'k' m = 0.1 xy.scatter(debris.x.value_in(units.AU), debris.y.value_in(units.AU), s=m, c=c, lw=0) xz.scatter(debris.x.value_in(units.AU), debris.z.value_in(units.AU), s=m, c=c, lw=0) yz.scatter(debris.z.value_in(units.AU), debris.y.value_in(units.AU), s=m, c=c, lw=0) if len(planets)>0: from distinct_colours import get_distinct c = get_distinct(len(planets)) m = 1000 * planets.mass/planets.mass.max() m[0] = min(10*m[1:].max(), 30) xy.scatter(planets.x.value_in(units.AU), planets.y.value_in(units.AU), s=m, c=c, lw=0) xz.scatter(planets.x.value_in(units.AU), planets.z.value_in(units.AU), s=m, c=c, lw=0) yz.scatter(planets.z.value_in(units.AU), planets.y.value_in(units.AU), s=m, c=c, lw=0) filename = "planetary_system.png" fig.savefig(filename) def myplot(x, y, s, bins=1000): from scipy.ndimage.filters import gaussian_filter heatmap, xedges, yedges = numpy.histogram2d(x, y, bins=bins) heatmap = gaussian_filter(heatmap, sigma=s) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] return heatmap.T, extent def plot_view(x, y, z, xlim, ylim, levels=4): from scipy.interpolate import griddata xi = numpy.linspace(-xlim,xlim,100) yi = numpy.linspace(-ylim,ylim,100) # xi = numpy.linspace(-xlim,xlim,xlim) # yi = numpy.linspace(-ylim,ylim,ylim) # grid the data. print(len(x), len(y), len(z)) zi = griddata((x, y), z, (xi[None,:], yi[:,None]), method='linear') # contour the gridded data, plotting dots at the randomly spaced data points. # CS = pyplot.contourf(xi,yi,zi,levels,cmap=pyplot.cm.plasma, # anorm=pyplot.Normalize(vmax=0.0, vmin=0.9*abs(z).max())) norm = pyplot.Normalize(vmax=0.0, vmin=9000) CS = pyplot.contourf(xi,yi,zi,levels,cmap=pyplot.cm.plasma, norm=norm, vmin=0, vmax=9000) # now determine nice limits by hand: pyplot.xlim((-xlim, xlim)) pyplot.ylim((-ylim, ylim)) return CS def Xplot_density_view(ax_xy, x, y, z, xlim, ylim, levels=5): import numpy as np import matplotlib.pyplot as pl import scipy.stats as st xmin = -xlim xmax = xlim ymin = -ylim ymax = ylim xx, yy = np.mgrid[xmin:xmax:100j, ymin:ymax:100j] positions = np.vstack([xx.ravel(), yy.ravel()]) values = np.vstack([x, y]) kernel = st.gaussian_kde(values) f = np.reshape(kernel(positions).T, xx.shape) ax = ax_xy ax.set_xlim(xmin, xmax) ax.set_ylim(ymin, ymax) # Contourf plot cfset = ax.contourf(xx, yy, f, cmap='Blues') ## Or kernel density estimate plot instead of the contourf plot #ax.imshow(np.rot90(f), cmap='Blues', extent=[xmin, xmax, ymin, ymax]) # Contour plot cset = ax.contour(xx, yy, f, colors='k') return cset def plot_temperature_image(planets, debris, disk, shell, figfile="fig_disk_top_view_temperature.pdf"): # from prepare_figure import single_frame, figure_frame, set_tickmarks disk.temperature = mu() / constants.kB * disk.u x = disk.x.value_in(units.AU) y = disk.y.value_in(units.AU) z = disk.z.value_in(units.AU) T = disk.temperature.value_in(units.K) print("min temp=", T.min()) import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import NullFormatter nullfmt = NullFormatter() # no labels if "0000" in figfile: fig = plt.figure(1, figsize=(10, 10)) else: fig = plt.figure(1, figsize=(10, 10)) pyplot.axis('equal') pyplot.axis('off') view = 10 img = plot_view(x, y, T, 100, 100, view) # fig, ax = pyplot.subplots() if False: #"0000" in figfile: norm = pyplot.Normalize(vmax=0.0, vmin=9000) cbar = pyplot.colorbar(img, orientation='vertical', norm=norm) font = matplotlib.font_manager.FontProperties(family='times new roman', size=16) cbar.set_label('T [K]', rotation=270) # pyplot.xlabel("X [au]") # pyplot.ylabel("Y [au]") pyplot.savefig(figfile) plt.show() def plot_density_view(ax_xy, x, y, z, xlim, ylim, levels=5): import numpy as np import matplotlib.pyplot as pl import scipy.stats as st """ import seaborn as sns sns.set(color_codes=True) ax = sns.kdeplot(x, y, shade=True, ax=ax_xy) cmap = sns.cubehelix_palette(as_cmap=True, dark=0, light=1, reverse=True) sns.kdeplot(x, y, cmap=cmap, n_levels=60, shade=True); return cmap """ xmin = -xlim xmax = xlim ymin = -ylim ymax = ylim xx, yy = np.mgrid[xmin:xmax:100j, ymin:ymax:100j] positions = np.vstack([xx.ravel(), yy.ravel()]) values = np.vstack([x, y]) kernel = st.gaussian_kde(values) f = np.reshape(kernel(positions).T, xx.shape) ax = ax_xy ax.set_xlim(xmin, xmax) ax.set_ylim(ymin, ymax) # Contourf plot # cfset = ax.contourf(xx, yy, f, cmap='Blues') cfset = ax.contourf(xx, yy, f, levels, cmap='jet') # import matplotlib as mpl # norm = mpl.colors.Normalize(vmin=0,vmax=1.) ## Or kernel density estimate plot instead of the contourf plot # ax.imshow(np.rot90(f), cmap='Blues', extent=[xmin, xmax, ymin, ymax], # vmin=0, vmax=1) ax.imshow(np.rot90(f), cmap='Blues', extent=[xmin, xmax, ymin, ymax], norm=matplotlib.colors.LogNorm()) # Contour plot #cset = ax.contour(xx, yy, f, colors='k') return cfset def fmt(x, pos): a, b = '{:.2e}'.format(x).split('e') b = int(b) return r'${} \times 10^{{{}}}$'.format(a, b) def plot_projected_density_image(planets, debris, disk, shell): from prepare_figure import single_frame, figure_frame, set_tickmarks disk.temperature = mu() / constants.kB * disk.u x = disk.x.value_in(units.AU) y = disk.y.value_in(units.AU) z = disk.z.value_in(units.AU) T = disk.temperature.value_in(units.K) SLICE_DATA = False if SLICE_DATA: selection = z < 10 x = x[selection] y = y[selection] z = z[selection] T = T[selection] selection = z > -10 x = x[selection] y = y[selection] z = z[selection] T = T[selection] print("After slicing the data: N=", len(x)) rho = numpy.log10(disk.rho.value_in(units.g/units.cm**3)) print("Density=", rho.min(), rho.max(), "in log(g/cm^3)") #-12.9251289255 -9.9657991654 in log(g/cm^3) import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import NullFormatter nullfmt = NullFormatter() # no labels left, width = 0.2, 0.45 bottom, height = 0.1, 0.65 bottom_h = left_h = left + width + 0.02 rect_xy = [left, bottom, width, height] rect_xz = [left, bottom_h+0.11, width+0.114, 0.2] rect_zy = [left_h, bottom, 0.15, height] # start with a rectangular Figure fig = plt.figure(1, figsize=(12, 8)) ax_xy = plt.axes(rect_xy) ax_xz = plt.axes(rect_xz) ax_zy = plt.axes(rect_zy) # no labels ax_xz.xaxis.set_major_formatter(nullfmt) ax_zy.yaxis.set_major_formatter(nullfmt) # levels = [-16, -14, -13, -11] levels = 20 plot_density_view(ax_xy, x, y, rho, 100, 100, levels) plot_density_view(ax_xz, x, z, rho, 100, 30, levels) img = plot_density_view(ax_zy, z, y, rho, 30, 100, levels) # import matplotlib.ticker as ticker # cbar = pyplot.colorbar(img, ax=ax_xz, orientation='vertical', format=ticker.FuncFormatter(fmt)) # cbar = pyplot.colorbar(img, ax=ax_xz, orientation='vertical', format='%.0e') from matplotlib.ticker import LogFormatter formatter = LogFormatter(10, labelOnlyBase=False) bounds = [-4, -3, -2, -1] import matplotlib as mpl cmap = mpl.cm.jet ##cool norm = mpl.colors.BoundaryNorm(bounds, cmap.N) cbar = pyplot.colorbar(img, ax=ax_xz, orientation='vertical', format=formatter, norm=norm, ticks=bounds) # cbar = pyplot.colorbar(img, ax=ax_xz, orientation='vertical', format=formatter, # ticks=[-4, -3, -2]) # cb = pyplot.colorbar(ticks=[1,5,10,20,50], format=formatter) ax_bar = cbar.ax text = ax_bar.yaxis.label font = matplotlib.font_manager.FontProperties(family='times new roman', size=16) text.set_font_properties(font) cbar.set_label(r'$log(\rho) [g/cm^3]$', rotation=270, labelpad=+20) ax_xz.set_xlim(ax_xy.get_xlim()) ax_zy.set_ylim(ax_xy.get_ylim()) ax_xy.set_xlabel("X [au]") ax_xy.set_ylabel("Y [au]") ax_xz.set_ylabel("Z [au]") ax_zy.set_xlabel("Z [au]") pyplot.savefig("fig_disk_projected_density.pdf") plt.show() def main(filename=None, pp=False): source, planets, debris, disk, shell = read_planetary_system(filename) print("N=", len(source), len(planets), len(debris), len(disk), len(shell)) figfile = filename.split(".amuse")[0] + ".pdf" if pp: plot_temperature_image(planets, debris, disk, shell, figfile) #plot_projected_density_image(planets, debris, disk, shell) #plot_single_image_simple(planets, debris, disk, shell) else: plot_single_image(planets, debris, disk, shell) def calculate_orbital_elements(star, planet): from amuse.ext.orbital_elements import orbital_elements_from_binary p = Particles() p.add_particle(star) p.add_particle(planet) M, m, a, e, ta_out, inc, lan_out, aop_out = orbital_elements_from_binary(p, G=constants.G) #print "Orbital elements:", M, m, a, e, ta_out, inc, lan_out, aop_out return a, e, inc def read_planetary_system(filename): #lim, snapshot_id): planets = Particles(0) debris = Particles(0) source = Particles(0) gas = Particles(0) shell = Particles(0) time = 0 | units.yr bodies = read_set_from_file(filename, "amuse") for bi in bodies.history: print(bi) if len(bi)>0: if "gas" in bi.name: gas.add_particles(bi.copy()) elif "debris" in bi.name: debris.add_particles(bi.copy()) elif "Jupiter" in bi.name: planets.add_particles(bi.copy()) elif "shell" in bi.name: shell.add_particles(bi.copy()) else: source.add_particles(bi.copy()) print(len(gas), len(shell)) # print gas[1] # print shell[1] # shell = gas.select(lambda n: "shell" in n,["name"]) # gas -= shell # print shell[1] print("N=", len(source), len(planets), len(debris), len(gas), len(shell)) print("Read planetary system at time", time.in_(units.yr)) return source, planets, debris, gas, shell def output_single_image(filename): #lim, snapshot_id): bodies = read_set_from_file(filename, "amuse") planets = Particles(0) debris = Particles(0) for bi in bodies.history: if len(bi)>1: if "debris" in bi.name: debris = bi.copy() #print "Orbits at t=", time, debris.name, debris.semimajor_axis.in_(units.AU), debris.eccentricity elif "gas" in bi.name: disk = bi.copy() lim = 150|units.AU snapshot_id = 1 # for pi in planets[1:]: # a, e, inc = calculate_orbital_elements(planets[0], pi) # print "Planet orbits:", a.in_(units.AU), e, inc else: planets = bi.copy() time = bi.get_timestamp() print("Orbits at t=", time, planets.name, planets.semimajor_axis.in_(units.AU), planets.eccentricity) def output_multiple_images(lim): snapshot_id = 0 filename = "planetary_system_i{0:04}.amuse".format(snapshot_id) while os.path.exists(filename): bodies = read_set_from_file(filename, "amuse") for bi in bodies.history: if len(bi)<=20: planets = bi.copy() time = bi.get_timestamp() print("Orbits at t=", time, planets.semimajor_axis.in_(units.AU), planets.eccentricity) else: disk = bi.copy() time = bi.get_timestamp() print("Snapshot=", snapshot_id, time) if image_id<0 or image_id == snapshot_id: plot_single_image(planets, disk, lim.value_in(units.AU), snapshot_id) if image_id == snapshot_id: print("Stop plotting") break snapshot_id += 1 filename = "planetary_system_i{0:04}.amuse".format(snapshot_id) def new_option_parser(): result = OptionParser() result.add_option("-f", dest="filename", default = "ID_Nd5Nr7Ms23Rs02pcff-2_i0009.amuse", help="output filename [%default]") result.add_option("-p", action="store_false", dest="pp", default=True, help="plot temperature") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
17,972
34.519763
113
py
amuse
amuse-main/examples/textbook/plot_supernova_sph.py
import numpy from matplotlib import pyplot from amuse.lab import * from prepare_figure import single_frame def make_e_map(sph,N=100,L=1): x,y=numpy.indices( ( N+1,N+1 )) x=L*(x.flatten()-N/2.)/N y=L*(y.flatten()-N/2.)/N z=x*0. vx=0.*x vy=0.*x vz=0.*x x=units.parsec(x) y=units.parsec(y) z=units.parsec(z) vx=units.kms(vx) vy=units.kms(vy) vz=units.kms(vz) rho,rhovx,rhovy,rhovz,rhoe=sph.get_hydro_state_at_point(x,y,z,vx,vy,vz) rho=rhoe.reshape((N+1,N+1)) return rho def setup_grid(N, L): x,y=numpy.indices( ( N+1,N+1 )) x=L*(x.flatten()-N/2.)/N y=L*(y.flatten()-N/2.)/N z=0.*x vx=0.*x vy=0.*x vz=0.*x x=units.parsec(x) y=units.parsec(y) z=units.parsec(z) vx=units.kms(vx) vy=units.kms(vy) vz=units.kms(vz) return x, y, z, vx, vy, vz def make_hydromap_and_show_picture(sph_particles, N=100, L=10): x_label = "x [R$_\odot$]" y_label = "y [R$_\odot$]" fig = single_frame(x_label, y_label, logx=False, logy=False, xsize=12, ysize=12) hydro = Gadget2(converter) hydro.gas_particles.add_particles(sph_particles) x, y, z, vx, vy, vz = setup_grid(N, L) rho,rhovx,rhovy,rhovz,rhoe=hydro.get_hydro_state_at_point(x,y,z,vx,vy,vz) rho=rhoe.reshape((N+1,N+1)) rho_e=make_map(hydro,N=50,L=L) hydro.stop() print("extrema:", rho_e.value_in(units.erg/units.RSun**3).min(), rho_e.value_in(units.erg/units.RSun**3).max()) cax = pyplot.imshow(numpy.log10(rho_e.value_in(units.erg/units.RSun**3)), extent=[-L/2,L/2,-L/2,L/2],vmin=4,vmax=11) cbar = fig.colorbar(cax, ticks=[4, 7.5, 11], orientation='vertical', fraction=0.045) cbar.ax.set_yticklabels(['Low', ' ', 'High']) # horizontal colorbar cbar.set_label('mid-plane energy-density', rotation=270) t = int(0.5+gas.get_timestamp().value_in(units.s)) filename = "supernova_sph_T"+str(t)+".pdf" pyplot.savefig(filename) # pyplot.show() def make_map(sph,N=100,L=1): x,y=numpy.indices( ( N+1,N+1 )) x=L*(x.flatten()-N/2.)/N y=L*(y.flatten()-N/2.)/N z=x*0. vx=0.*x vy=0.*x vz=0.*x x=units.RSun(x) y=units.RSun(y) z=units.RSun(z) vx=units.kms(vx) vy=units.kms(vy) vz=units.kms(vz) rho,rhovx,rhovy,rhovz,rhoe=sph.get_hydro_state_at_point(x,y,z,vx,vy,vz) rho=rho.reshape((N+1,N+1)) return rho def plot_e_sph(sph, time): # pyplot.rcParams.update({'font.size': 30}) # figure = pyplot.figure(figsize=(12, 12)) L = 10 max_dens = sph.gas_particles.rho.value_in(units.g/units.cm**3).max() print("Density extrema:", max_dens) x_label = "X [R$_\odot$]" y_label = "Y [R$_\odot$]" figure = single_frame(x_label, y_label, logx=False, logy=False, xsize=12, ysize=12) rho_e=make_e_map(sph,N=20,L=L) cax = pyplot.imshow(rho_e.value_in(units.erg/units.MSun**3), extent=[-L/2,L/2,-L/2,L/2], interpolation='bicubic', origin = 'lower', cmap="hot") cbar = figure.colorbar(cax, ticks=[1.e-8, 0.5*max_dens, max_dens], orientation='vertical', fraction=0.045) rmin = 0.0 rmid = "%.1f" % (0.5*max_dens) rmax = "%.1f" % (max_dens) cbar.ax.set_yticklabels([rmin, ' ', rmax]) # horizontal colorbar cbar.set_label('mid-plane density [$erg/M_\odot^3$]', rotation=270) pyplot.xlabel("x [R$_\odot$]") pyplot.ylabel("y [R$_\odot$]") t = int(0.5+time.value_in(units.s)) filename = "supernova_sph_T"+str(t)+".pdf" pyplot.savefig(filename) pyplot.show() def plot_sph(sph, time): L = 10 unit = units.g/units.cm**3 max_dens = sph.gas_particles.rho.value_in(unit).max() print("Density extrema:", max_dens) x_label = "X [R$_\odot$]" y_label = "Y [R$_\odot$]" figure = single_frame(x_label, y_label, logx=False, logy=False, xsize=12, ysize=12) rho_e=make_map(sph,N=50,L=L) max_dens = rho_e.value_in(unit).max() print("extrema:", rho_e.value_in(unit).min(), max_dens) cax = pyplot.imshow(rho_e.value_in(unit), extent=[-L/2,L/2,-L/2,L/2], interpolation='bicubic', origin='lower', cmap="hot", vmin=0.0, vmax=max_dens) # cbar = figure.colorbar(cax, ticks=[-0.4*max_dens, 0.0*max_dens, 0.5*max_dens], orientation='vertical', fraction=0.045) cbar = figure.colorbar(cax, ticks=[0.0, 0.5*max_dens, 0.99*max_dens], orientation='vertical', fraction=0.045) rmin = "0.0" rmid = "%.1f" % (0.5*max_dens) rmax = "%.1f" % (max_dens) print("min/max=", rmin, rmid, rmax) cbar.ax.set_yticklabels([rmin, ' ', rmax]) # horizontal colorbar # cbar.ax.set_yticklabels(['a', 'b', 'c']) # horizontal colorbar cbar.set_label('mid-plane density [$g/cm^3$]', rotation=270) pyplot.xlabel("x [R$_\odot$]") pyplot.ylabel("y [R$_\odot$]") t = int(0.5+time.value_in(units.s)) filename = "supernova_sph_T"+str(t)+".pdf" pyplot.savefig(filename) pyplot.show() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-t", unit=units.s, dest="tplot", type="float", default = 300|units.s, help="plotting time [%default]") result.add_option("-f", dest="filename", default = "supernova_sph_gadget.amuse", help="input filename [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() converter = nbody_system.nbody_to_si(1|units.MSun, 1|units.RSun) bodies = read_set_from_file(o.filename, "amuse") t_end = o.tplot for gas in bodies.history: time = gas.get_timestamp() print("time=", time.in_(units.s), "N=", len(gas)) if int(0.5+time.value_in(units.s)) >= t_end.value_in(units.s): gas.move_to_center() hydro = Gadget2(converter) hydro.gas_particles.add_particles(gas) plot_sph(hydro, time) hydro.stop() break
5,994
32.305556
155
py
amuse
amuse-main/examples/textbook/XiTau.py
import os import os.path import shutil import math import subprocess import numpy import pickle from amuse.units import units, constants, nbody_system from amuse.units.core import enumeration_unit from amuse.units.generic_unit_converter import ConvertBetweenGenericAndSiUnits from amuse.datamodel import Particles, Particle, ParticlesSuperset from amuse.io import write_set_to_file, read_set_from_file from amuse.support.exceptions import AmuseException from amuse.ext.star_to_sph import convert_stellar_model_to_SPH, StellarModelInSPH from amuse.couple.bridge import Bridge, CalculateFieldForParticles from amuse.community.evtwin.interface import EVtwin from amuse.community.mesa.interface import MESA from amuse.community.gadget2.interface import Gadget2 from amuse.community.twobody.twobody import TwoBody from amuse.community.huayno.interface import Huayno import matplotlib matplotlib.use("Agg") from matplotlib import pyplot from amuse.plot import scatter, xlabel, ylabel, plot,loglog,semilogx,semilogy, sph_particles_plot from amuse.plot import pynbody_column_density_plot, HAS_PYNBODY def new_working_directory(): i = 0 current_directory = os.getcwd() while os.path.exists(os.path.join(current_directory, "run_{0:=03}".format(i))): i += 1 new_directory = os.path.join(current_directory, "run_{0:=03}".format(i)) os.mkdir(new_directory) print("Created new directory for output:", new_directory) os.mkdir(os.path.join(new_directory, "plots")) os.mkdir(os.path.join(new_directory, "snapshots")) shutil.copy(__file__, new_directory) if not os.path.exists(os.path.join(current_directory, "giant_models")): os.mkdir(os.path.join(current_directory, "giant_models")) os.chdir(new_directory) def get_relative_velocity(total_mass, semimajor_axis, ecc): return (constants.G * total_mass * ((1.0 + ecc)/(1.0 - ecc)) / semimajor_axis).sqrt() def set_up_initial_conditions(): stars = set_up_inner_binary() giant = set_up_outer_star(stars.total_mass()) view_on_giant = stars.add_particle(giant) stars.move_to_center() return stars, view_on_giant def set_up_inner_binary(): semimajor_axis = 0.133256133158 | units.AU eccentricity = 0 masses = [3.2, 3.1] | units.MSun orbital_period = (4 * numpy.pi**2 * semimajor_axis**3 / (constants.G * masses.sum())).sqrt().as_quantity_in(units.day) print(" Initializing inner binary") print(" Orbital period inner binary:", orbital_period) stars = Particles(2) stars.mass = masses stars.position = [0.0, 0.0, 0.0] | units.AU stars.velocity = [0.0, 0.0, 0.0] | units.km / units.s stars[0].x = semimajor_axis stars[0].vy = get_relative_velocity(stars.total_mass(), semimajor_axis, eccentricity) stars.move_to_center() return stars def set_up_outer_star(inner_binary_mass): semimajor_axis = 1.22726535008 | units.AU eccentricity = 0.15 inclination = math.radians(9.0) print(" Initializing outer star") giant = Particle() giant.mass = 5.5 | units.MSun giant.position = semimajor_axis * ([math.cos(inclination), 0, math.sin(inclination)] | units.none) giant.velocity = get_relative_velocity(giant.mass + inner_binary_mass, semimajor_axis, eccentricity) * ([0, 1, 0] | units.none) return giant def estimate_roche_radius(triple, view_on_giant): # 'mass ratio' of giant to inner binary q = (view_on_giant.mass / (triple-view_on_giant).total_mass()) # Assume ~ circular orbit: a = (view_on_giant.position - (triple-view_on_giant).center_of_mass()).length() q13 = q**(1./3.) q23 = q13**2 return (a*(0.49*q23/(0.6*q23+math.log(1+q13)))).as_quantity_in(units.RSun) def evolve_stars(triple, view_on_giant, stellar_evolution_code, radius_factor): stop_radius = radius_factor * estimate_roche_radius(triple, view_on_giant) stellar_evolution = stellar_evolution_code(redirection='file', redirect_file='stellar_evolution_code_out.log') se_giant = stellar_evolution.particles.add_particle(view_on_giant) while (se_giant.radius < stop_radius): stellar_evolution.evolve_model(keep_synchronous = False) se_binary = stellar_evolution.particles.add_particles(triple - view_on_giant) for particle in se_binary: particle.evolve_for(se_giant.age) return stellar_evolution.particles, stellar_evolution def convert_giant_to_sph(view_on_se_giant, number_of_sph_particles): giant_in_sph = convert_stellar_model_to_SPH( view_on_se_giant, number_of_sph_particles, with_core_particle = True, target_core_mass = 1.4 | units.MSun, do_store_composition = False ) return giant_in_sph def relax_in_isolation(giant_in_sph, sph_code, output_base_name): total_mass = giant_in_sph.gas_particles.total_mass() + giant_in_sph.core_particle.mass total_radius = max(giant_in_sph.gas_particles.position.lengths_squared()).sqrt() dynamical_timescale = (total_radius**3 / (2 * constants.G * total_mass)).sqrt().as_quantity_in(units.day) t_end = (10.0 * dynamical_timescale).as_quantity_in(units.day) n_steps = 100 hydro_code_options = dict(number_of_workers=2, redirection='file', redirect_file='hydrodynamics_code_relax_out.log') unit_converter = ConvertBetweenGenericAndSiUnits(total_radius, total_mass, t_end) hydrodynamics = sph_code(unit_converter, **hydro_code_options) hydrodynamics.parameters.epsilon_squared = giant_in_sph.core_radius**2 hydrodynamics.parameters.max_size_timestep = t_end hydrodynamics.parameters.time_max = 1.1 * t_end hydrodynamics.parameters.time_limit_cpu = 7.0 | units.day hydrodynamics.gas_particles.add_particles(giant_in_sph.gas_particles) hydrodynamics.dm_particles.add_particle(giant_in_sph.core_particle) potential_energies = hydrodynamics.potential_energy.as_vector_with_length(1).as_quantity_in(units.erg) kinetic_energies = hydrodynamics.kinetic_energy.as_vector_with_length(1).as_quantity_in(units.erg) thermal_energies = hydrodynamics.thermal_energy.as_vector_with_length(1).as_quantity_in(units.erg) print(" Relaxing for", t_end, "(10 * dynamical timescale)") times = (t_end * list(range(1, n_steps+1)) / n_steps).as_quantity_in(units.day) for i_step, time in enumerate(times): hydrodynamics.evolve_model(time) print(" Relaxed for:", time) potential_energies.append(hydrodynamics.potential_energy) kinetic_energies.append(hydrodynamics.kinetic_energy) thermal_energies.append(hydrodynamics.thermal_energy) hydrodynamics.gas_particles.copy_values_of_attributes_to( ['mass', 'x','y','z', 'vx','vy','vz', 'u', 'h_smooth'], giant_in_sph.gas_particles) giant_in_sph.core_particle.position = hydrodynamics.dm_particles[0].position giant_in_sph.core_particle.velocity = hydrodynamics.dm_particles[0].velocity hydrodynamics.stop() snapshotfile = output_base_name + "_gas.amuse" write_set_to_file(giant_in_sph.gas_particles, snapshotfile, format='amuse') shutil.copy(snapshotfile, os.path.join("..", "giant_models")) snapshotfile = output_base_name + "_core.amuse" # temporarily store core_radius on the core particle giant_in_sph.core_particle.radius = giant_in_sph.core_radius write_set_to_file(giant_in_sph.core_particle.as_set(), snapshotfile, format='amuse') giant_in_sph.core_particle.radius = 0.0 | units.m shutil.copy(snapshotfile, os.path.join("..", "giant_models")) energy_evolution_plot(times, kinetic_energies, potential_energies, thermal_energies, figname = output_base_name + "_energy_evolution.png") def load_giant_model(file_base_name): snapshotfile = os.path.join("..", "giant_models", file_base_name + "_gas.amuse") sph_particles = read_set_from_file(snapshotfile, format='amuse') snapshotfile = os.path.join("..", "giant_models", file_base_name + "_core.amuse") gd_particles = read_set_from_file(snapshotfile, format='amuse') core_radius = gd_particles[0].radius gd_particles[0].radius = 0.0 | units.m giant_model = StellarModelInSPH( gas_particles = sph_particles, core_particle = gd_particles[0], core_radius = core_radius) return giant_model def prepare_binary_system(dynamics_code, binary_particles): unit_converter = nbody_system.nbody_to_si( binary_particles.total_mass(), (binary_particles[0].position - binary_particles[1].position).length()) system = dynamics_code(unit_converter, redirection="none") system.particles.add_particles(binary_particles) return system def prepare_giant_system(sph_code, giant_model, view_on_giant, time_unit, n_steps): hydro_code_options = dict(number_of_workers=2, redirection='file', redirect_file='hydrodynamics_code_out.log') unit_converter = ConvertBetweenGenericAndSiUnits( 1.0 | units.RSun, giant_model.gas_particles.total_mass() + giant_model.core_particle.mass, time_unit) system = sph_code(unit_converter, **hydro_code_options) system.parameters.epsilon_squared = giant_model.core_radius**2 system.parameters.max_size_timestep = time_unit / n_steps system.parameters.time_max = 1.1 * time_unit system.parameters.time_limit_cpu = 7.0 | units.day giant_model.gas_particles.position += view_on_giant.position giant_model.gas_particles.velocity += view_on_giant.velocity giant_model.core_particle.position += view_on_giant.position giant_model.core_particle.velocity += view_on_giant.velocity system.gas_particles.add_particles(giant_model.gas_particles) system.dm_particles.add_particle(giant_model.core_particle) return system def calculate_orbital_elements(m1, m2, pos1, pos2, vel1, vel2, m3, pos3, vel3): print(" Calculating semimajor axis and eccentricity evolution of the giant's orbit") m12 = m1+m2 rel_position = (m1 * pos1 + m2 * pos2)/m12 - pos3 rel_velocity = (m1 * vel1 + m2 * vel2)/m12 - vel3 mtot = m12 + m3 separation = rel_position.lengths() speed_squared = rel_velocity.lengths_squared() # Now calculate the important quantities: semimajor_axis = (constants.G * mtot * separation / (2 * constants.G * mtot - separation * speed_squared)).as_quantity_in(units.AU) eccentricity = numpy.sqrt(1.0 - (rel_position.cross(rel_velocity)**2).sum(axis=1) / (constants.G * mtot * semimajor_axis)) return semimajor_axis, eccentricity 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") def make_movie(): print(" Creating movie from snapshots") try: subprocess.call(['mencoder', "mf://hydro_triple_small*.png", '-ovc', 'lavc', '-o', '../hydro_triple_small.avi', '-msglevel', 'all=1'], cwd="./plots") subprocess.call(['mencoder', "mf://hydro_triple_large*.png", '-ovc', 'lavc', '-o', '../hydro_triple_large.avi', '-msglevel', 'all=1'], cwd="./plots") except Exception as exc: print(" Failed to create movie, error was:", str(exc)) def continue_evolution(sph_code, dynamics_code, t_end, n_steps, relaxed_giant_output_base_name, do_energy_evolution_plot): print("Loading snapshots...", end=' ') files = os.listdir("snapshots") files.sort() files = files[-4:] print(files) binary = read_set_from_file(os.path.join("snapshots", files[0]), format='amuse') gd_particles = read_set_from_file(os.path.join("snapshots", files[1]), format='amuse') sph_particles = read_set_from_file(os.path.join("snapshots", files[2]), format='amuse') snapshotfile = os.path.join("..", "giant_models", relaxed_giant_output_base_name + "_core.amuse") core_particle = read_set_from_file(snapshotfile, format='amuse') giant_model = StellarModelInSPH( gas_particles = sph_particles, core_particle = gd_particles[0], core_radius = core_particle.radius) view_on_giant = Particle() view_on_giant.position = [0]*3 | units.m view_on_giant.velocity = [0]*3 | units.m / units.s print("\nSetting up {0} to simulate inner binary system".format(dynamics_code.__name__)) binary_system = prepare_binary_system(dynamics_code, binary) print("\nSetting up {0} to simulate giant in SPH".format(sph_code.__name__)) giant_system = prepare_giant_system(sph_code, giant_model, view_on_giant, t_end, n_steps) print("\nEvolving with bridge between", sph_code.__name__, "and", dynamics_code.__name__) evolve_coupled_system(binary_system, giant_system, t_end, n_steps, do_energy_evolution_plot, previous_data = os.path.join("snapshots", files[3])) print("Done") 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_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 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() if __name__ == "__main__": stellar_evolution_code = MESA sph_code = Gadget2 #dynamics_code = TwoBody dynamics_code = Huayno number_of_sph_particles = 50000 # Stop stellar evolution when giant's radius is (radius_factor * Roche lobe radius) radius_factor = 1.0 relaxed_giant_output_base_name = "relaxed_giant_" + str(number_of_sph_particles) + "_" + str(radius_factor) t_end = 300.0 | units.day n_steps = 3000 do_energy_evolution_plot = False if os.path.exists("snapshots"): print("Found snapshots folder, continuing evolution of previous run") continue_evolution(sph_code, dynamics_code, t_end, n_steps, relaxed_giant_output_base_name, do_energy_evolution_plot) exit(0) new_working_directory() print("Initializing triple") triple, view_on_giant = set_up_initial_conditions() print("\nInitialization done:\n", triple) print("\nEvolving with", stellar_evolution_code.__name__) se_stars, se_code_instance = evolve_stars(triple, view_on_giant, stellar_evolution_code, radius_factor) triple.radius = se_stars.radius print("\nStellar evolution done:\n", se_stars) if os.path.exists(os.path.join("..", "giant_models", relaxed_giant_output_base_name + "_gas.amuse")): print("\nLoading SPH model for giant from:", end=' ') print(os.path.join("..", "giant_models", relaxed_giant_output_base_name + "_gas.amuse")) giant_model = load_giant_model(relaxed_giant_output_base_name) se_code_instance.stop() else: print("\nConverting giant to", number_of_sph_particles, "SPH particles") view_on_se_giant = view_on_giant.as_set().get_intersecting_subset_in(se_stars)[0] giant_model = convert_giant_to_sph(view_on_se_giant, number_of_sph_particles) se_code_instance.stop() print("Relaxing giant with", sph_code.__name__) relax_in_isolation(giant_model, sph_code, relaxed_giant_output_base_name) print("\nSetting up {0} to simulate inner binary system".format(dynamics_code.__name__)) binary_system = prepare_binary_system(dynamics_code, triple - view_on_giant) print("\nSetting up {0} to simulate giant in SPH".format(sph_code.__name__)) giant_system = prepare_giant_system(sph_code, giant_model, view_on_giant, t_end, n_steps) print("\nEvolving with bridge between", sph_code.__name__, "and", dynamics_code.__name__) evolve_coupled_system(binary_system, giant_system, t_end, n_steps, do_energy_evolution_plot) print("Done")
24,999
47.543689
177
py
amuse
amuse-main/examples/textbook/plot_triple_with_wind.py
import os import numpy from amuse.lab import * from prepare_figure import single_frame from distinct_colours import get_distinct from matplotlib import pyplot def read_triple_data(filename): t = [] ain = [] aout = [] ein = [] eout = [] a0in = 0 a0out = 0 for line in open(filename): if "Triple" in line: l = line.split() ti = float(l[3]) if ti <= 0: a0in = float(l[10]) a0out = float(l[16]) e0in = float(l[12]) e0out = float(l[18]) if ti >= 4: t.append(float(l[3])) ain.append(float(l[10])/a0in) ein.append(float(l[12])/e0in) aout.append(float(l[16])/a0out) eout.append(float(l[18])/e0out) return t, ain, ein, aout, eout try: amusedir = os.environ['AMUSE_DIR'] dir = amusedir+'/examples/textbook/' except: print('Environment variable AMUSE_DIR not set') dir = './' filename = dir+'evolve_triple_with_wind.data' t, ain, ein, aout, eout = read_triple_data(filename) x_label = "$a/a_{0}$" y_label = "$e/e_{0}$" fig = single_frame(x_label, y_label, logx=False, logy=False, xsize=10, ysize=8) color = get_distinct(2) pyplot.plot(ain, ein, c=color[0], label= 'inner') pyplot.plot(aout, eout, c=color[1], label= 'outer') pyplot.legend(loc='best', ncol=1, shadow=False, fontsize=20) save_file = 'evolve_triple_with_wind.png' pyplot.savefig(save_file) print('\nSaved figure in file', save_file,'\n') pyplot.show()
1,585
26.344828
60
py
amuse
amuse-main/examples/textbook/stellar_massloss_response.py
""" Calculate the response of a star as a result of mass loss. """ from amuse.lab import * Second_Asymptotic_Giant_Branch = 6 | units.stellar_type MASS_UNIT = units.MSun LENGTH_UNIT = units.RSun TIME_UNIT = units.Myr MASSLOSS_UNIT = units.MSun / units.yr set_printing_strategy("custom", preferred_units = [MASS_UNIT, LENGTH_UNIT, TIME_UNIT, MASSLOSS_UNIT], precision = 6, prefix = "", separator = " [", suffix = "]") ###BOOKLISTSTART1### def calculate_zeta(star, z, dmdt): stellar = MESA() stellar.parameters.metallicity = z stellar.particles.add_particles(star) stellar.commit_particles() rold = star.radius star.mass_change = dmdt dm = 0.01*star.mass star.time_step = dm/dmdt stellar.particles.evolve_one_step() rnew = stellar.particles[0].radius dlnr = (rnew-rold)/rold dlnm = (stellar.particles[0].mass-star.mass)/star.mass zeta = dlnr/dlnm stellar.stop() return zeta ###BOOKLISTSTOP1### ###BOOKLISTSTART2### def main(Mstar, z, dmdt): stellar = MESA() stellar.parameters.metallicity = z bodies = Particles(mass=Mstar) stellar.particles.add_particles(bodies) stellar = turnon_massloss(stellar) channel_to_framework = stellar.particles.new_channel_to(bodies) copy_argument = ["age", "mass", "radius", "stellar_type"] while stellar.particles[0].stellar_type < Second_Asymptotic_Giant_Branch: stellar.particles.evolve_one_step() channel_to_framework.copy_attributes(copy_argument) star = stellar.particles.copy() zeta = calculate_zeta(star, z, dmdt) print("Zeta=", zeta[0], bodies[0].age, bodies[0].mass, \ bodies[0].radius, dmdt, bodies[0].stellar_type) stellar.stop() ###BOOKLISTSTOP2### def turnon_massloss(stellar): if stellar.mesa_version == '2208': return stellar # Mass loss defaults to on in this version else: for particle in stellar.particles: particle.set_control('cool_wind_RGB_scheme','Reimers') particle.set_control('Reimers_scaling_factor',0.1) particle.set_control('cool_wind_AGB_scheme','Blocker') particle.set_control('Blocker_scaling_factor',0.5) particle.set_control('RGB_to_AGB_wind_switch',10**-4) return stellar def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-M", unit=MASS_UNIT, dest="Mstar", type="float", default=1. | MASS_UNIT, help="stellar mass [%default]") result.add_option("--dmdt", unit=MASSLOSS_UNIT, dest="dmdt", type="float", default=-0.01 | (MASSLOSS_UNIT), help="dmdt [%default]") result.add_option("-z", dest="z", type="float", default = 0.02, help="metallicity [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
3,047
35.722892
92
py
amuse
amuse-main/examples/textbook/molecular_cloud_collapse.py
""" Example of molecular cloud evolution with explictly split SPH and gravity evolution Initial condition is a smooth spherical cloud with random velocities as in Bonnell et al. (2003) """ import numpy from matplotlib import pyplot from amuse.lab import * from amuse.ext.molecular_cloud import molecular_cloud from amuse.ext.evrard_test import body_centered_grid_unit_cube from prepare_figure import single_frame, figure_frame, set_tickmarks from distinct_colours import get_distinct def make_map(sph, N=100, L=1): x,y = numpy.indices((N+1,N+1)) x = L*(x.flatten()-N/2.)/N y = L*(y.flatten()-N/2.)/N z = x*0. vx = 0*x vy = 0*x vz = 0*x x = units.parsec(x) y = units.parsec(y) z = units.parsec(z) vx = units.kms(vx) vy = units.kms(vy) vz = units.kms(vz) rho,rhovx,rhovy,rhovz,rhoe = sph.get_hydro_state_at_point(x,y,z,vx,vy,vz) rho = rho.reshape((N+1,N+1)) return rho def write_output(filename, parts, conv): particles_nbody \ = ParticlesWithUnitsConverted(parts, conv.as_converter_from_nbody_to_si()) write_set_to_file(particles_nbody, filename, "txt", attribute_names=('rho', 'mass', 'x', 'y', 'z', 'vx', 'vy', 'vz')) return 0 def plot_hydro(time, sph, i, L=10): x_label = "x [pc]" y_label = "y [pc]" fig = single_frame(x_label, y_label, logx=False, logy=False, xsize=12, ysize=12) rho = make_map(sph,N=200,L=L) cax = pyplot.imshow(numpy.log10(1.e-5+rho.value_in(units.amu/units.cm**3)), cmap="jet", extent=[-L/2,L/2,-L/2,L/2],vmin=2,vmax=5) if i==5: cbar = fig.colorbar(cax, ticks=[2, 3, 4, 5], orientation='vertical', fraction=0.05) cbar.ax.set_yticklabels([2, " ", " ", 5]) # horizontal colorbar cbar.set_label('log projected density [$amu/cm^3$]', rotation=270) """ rhomin = numpy.log10(rho.value_in(units.amu/units.cm**3)).min() rhomax = numpy.log10(rho.value_in(units.amu/units.cm**3)).max() cax = pyplot.imshow(numpy.log10(1.e-5+rho.value_in(units.amu/units.cm**3)), extent=[-L/2,L/2,-L/2,L/2],vmin=rhomin,vmax=rhomax) rhomid = 0.5*(rhomin + rhomax) print rhomin, rhomid, rhomax cbar = fig.colorbar(cax, ticks=[rhomin, rhomid, rhomax], orientation='vertical', fraction=0.045) # cbar.ax.set_yticklabels(['Low', ' ', 'High']) # horizontal colorbar low = "%.2f" % rhomin mid = "%.1f" % rhomid mx = "%.2f" % rhomax cbar.ax.set_yticklabels([low, mid, mx]) # horizontal colorbar cbar.set_label('projected density [$amu/cm^3$]', rotation=270) """ pyplot.savefig("GMC_"+str(i)+".png") def run_molecular_cloud(N=100, Mcloud=100. | units.MSun, Rcloud=1. | units.parsec): conv = nbody_system.nbody_to_si(Mcloud,Rcloud) rho_cloud = 3.*Mcloud/(4.*numpy.pi*Rcloud**3) print(rho_cloud) tff = 0.5427/numpy.sqrt(constants.G*rho_cloud) print("t_ff=", tff.value_in(units.Myr), 'Myr') dt = 5.e-2 | units.Myr t_end = 1.0 | units.Myr parts = molecular_cloud(targetN=N,convert_nbody=conv, base_grid=body_centered_grid_unit_cube, seed=100).result sph = Fi(conv) sph.parameters.use_hydro_flag = True sph.parameters.radiation_flag = False sph.parameters.gamma = 1 sph.parameters.isothermal_flag = True sph.parameters.integrate_entropy_flag = False sph.parameters.timestep = dt sph.parameters.verbosity = 0 sph.parameters.eps_is_h_flag = False # h_smooth is constant eps = 0.1 | units.parsec sph.parameters.gas_epsilon = eps sph.parameters.sph_h_const = eps parts.h_smooth= eps print('eps-h flag', sph.get_eps_is_h(), sph.get_consthsm()) expected_dt = 0.2*numpy.pi*numpy.power(eps, 1.5) \ / numpy.sqrt(constants.G*Mcloud/N) print("dt_exp=", expected_dt.value_in(units.Myr)) print("dt=", dt) print("eps=", sph.parameters.gas_epsilon.in_(units.parsec)) sph.gas_particles.add_particles(parts) channel_from_sph_to_parts= sph.gas_particles.new_channel_to(parts) channel_from_parts_to_sph= parts.new_channel_to(sph.gas_particles) i = 0 L = 6 E0 = 0.0 ttarget = 0.0 | units.Myr plot_hydro(ttarget, sph, i, L) while ttarget < t_end: ttarget = float(i)*dt print(ttarget) sph.evolve_model(ttarget, timestep=dt) E = sph.gas_particles.kinetic_energy() \ + sph.gas_particles.potential_energy() \ + sph.gas_particles.thermal_energy() E_th = sph.gas_particles.thermal_energy() if i == 0: E0 = E Eerr = (E-E0)/E0 print('energy=', E, 'energy_error=', Eerr, 'e_th=', E_th) channel_from_sph_to_parts.copy() plot_hydro(ttarget, sph, i, L) i += 1 sph.stop() return parts if __name__ in ("__main__","__plot__"): parts = run_molecular_cloud( 1000, Mcloud=10000. | units.MSun, Rcloud=3. | units.parsec, )
5,223
30.46988
100
py
amuse
amuse-main/examples/textbook/hierarchical_quadruple.py
""" Simple script to run a `2+2' quadruple system with SecularMultiple. The two `inner' binaries are denoted with `A' and `B'; the wider outer binary (`superorbit') is denoted with `C'. Orbital parameters can be provided with command line arguments. Note: setting N_output to a large value will slow down the script due to Python overhead, but will make nicer-looking plots. Adrian Hamers, December 2017 """ import numpy from amuse.community.secularmultiple.interface import SecularMultiple from amuse.units import quantities,units,constants from amuse.datamodel import Particles from matplotlib import pyplot ###BOOKLISTSTART1### def initialize_multiple_system(N_bodies, masses, semimajor_axis, eccentricity, inclination, argument_of_pericenter, longitude_of_ascending_node): N_binaries = N_bodies-1 particles = Particles(N_bodies+N_binaries) for index in range(N_bodies): particle = particles[index] particle.mass = masses[index] particle.is_binary = False particle.radius = 1.0 | units.RSun particle.child1 = None particle.child2 = None for index in range(N_binaries): particle = particles[index+N_bodies] particle.is_binary = True particle.semimajor_axis = semimajor_axis[index] particle.eccentricity = eccentricity[index] particle.inclination = inclination[index] particle.argument_of_pericenter = argument_of_pericenter[index] particle.longitude_of_ascending_node = longitude_of_ascending_node[index] # Specify the `2+2' hierarchy: if index==0: particle.child1 = particles[0] particle.child2 = particles[1] elif index==1: particle.child1 = particles[2] particle.child2 = particles[3] elif index==2: particle.child1 = particles[4] particle.child2 = particles[5] binaries = particles[particles.is_binary] return particles, binaries ###BOOKLISTSTOP1### def evolve_quadruple(N_output, end_time, m1, m2, m3, m4, aA, aB, aC, eA, eB, eC, iA, iB, iC, ApA, ApB, ApC, LANA, LANB, LANC): masses = [m1, m2, m3, m4] semimajor_axis = [aA, aB, aC] eccentricity = [eA, eB, eC] inclination = numpy.deg2rad([iA, iB, iC]) argument_of_percienter = numpy.deg2rad([ApA, ApB, ApC]) longitude_of_ascending_node = numpy.deg2rad([LANA, LANB, LANC]) print(longitude_of_ascending_node) N_bodies = 4 N_binaries = N_bodies-1 particles, binaries = initialize_multiple_system(N_bodies, masses, semimajor_axis, eccentricity, inclination, argument_of_percienter, longitude_of_ascending_node) code = SecularMultiple() code.particles.add_particles(particles) channel_from_particles_to_code = particles.new_channel_to(code.particles) channel_from_code_to_particles = code.particles.new_channel_to(particles) channel_from_particles_to_code.copy() ### set up some arrays for plotting ### print_smas_AU = [[] for x in range(N_binaries)] print_rps_AU = [[] for x in range(N_binaries)] print_parent_is_deg = [[] for x in range(N_binaries)] print_times_Myr = [] time = 0.0|units.yr output_time_step = end_time/float(N_output) while time <= end_time: time += output_time_step code.evolve_model(time) channel_from_code_to_particles.copy() print('='*50) print('t/Myr',time.value_in(units.Myr)) print('e',binaries.eccentricity) print('i/deg', numpy.rad2deg(binaries.inclination)) print('AP/deg', \ numpy.rad2deg(binaries.argument_of_pericenter)) print('LAN/deg', \ numpy.rad2deg(binaries.longitude_of_ascending_node)) ### write to output arrays ### print_times_Myr.append(time.value_in(units.Myr)) for index_binary in range(N_binaries): print_smas_AU[index_binary].append( binaries[index_binary].semimajor_axis.value_in(units.AU) ) print_rps_AU[index_binary].append( binaries[index_binary].semimajor_axis.value_in(units.AU)*(1.0 - binaries[index_binary].eccentricity) ) print_parent_is_deg[index_binary].append( numpy.rad2deg(binaries[index_binary].inclination_relative_to_parent) ) ### compute the `canonical' maximum eccentricity/periapsis distance that applies in the quadrupole-order test-particle limit if the `outer' binary is replaced by a point mass ### print(inclination[0],inclination[2],longitude_of_ascending_node[0],longitude_of_ascending_node[2]) i_AC_init = compute_mutual_inclination(inclination[0],inclination[2],longitude_of_ascending_node[0],longitude_of_ascending_node[2]) i_BC_init = compute_mutual_inclination(inclination[1],inclination[2],longitude_of_ascending_node[1],longitude_of_ascending_node[2]) canonical_rp_min_A_AU = (semimajor_axis[0]*(1.0 - numpy.sqrt( 1.0 - (5.0/3.0)*numpy.cos(i_AC_init)**2 ) )).value_in(units.AU) canonical_rp_min_B_AU = (semimajor_axis[1]*(1.0 - numpy.sqrt( 1.0 - (5.0/3.0)*numpy.cos(i_BC_init)**2 ) )).value_in(units.AU) data = print_times_Myr,print_smas_AU,print_rps_AU,print_parent_is_deg,canonical_rp_min_A_AU,canonical_rp_min_B_AU return data def compute_mutual_inclination(INCL_k,INCL_l,LAN_k,LAN_l): cos_INCL_rel = numpy.cos(INCL_k)*numpy.cos(INCL_l) + numpy.sin(INCL_k)*numpy.sin(INCL_l)*numpy.cos(LAN_k-LAN_l) return numpy.arccos(cos_INCL_rel) def plot_function(data): print_times_Myr,print_smas_AU,print_rps_AU,print_parent_is_deg,canonical_rp_min_A_AU,canonical_rp_min_B_AU = data N_binaries = len(print_smas_AU) pyplot.rc('text',usetex=True) pyplot.rc('legend',fancybox=True) linewidth=4 dlinewidth=2 fig=pyplot.figure(figsize=(10,9)) plot1=fig.add_subplot(2,1,1,yscale="log") plot2=fig.add_subplot(2,1,2) from distinct_colours import get_distinct colors = get_distinct(4) labels = ["$A$","$B$","$C$"] labels_i = ["$i_{AC}$","$i_{BC}$",None] for index_binary in range(N_binaries): label = labels[index_binary] label_i = labels_i[index_binary] color = colors[index_binary] plot1.plot(print_times_Myr,print_smas_AU[index_binary],color=color,linestyle='dashed',linewidth=dlinewidth) plot1.plot(print_times_Myr,print_rps_AU[index_binary],color=color,linewidth=linewidth,label=label) plot2.plot(print_times_Myr,print_parent_is_deg[index_binary],color=color,linewidth=linewidth,label=label_i) plot1.axhline(y = canonical_rp_min_A_AU, color= colors[0],linestyle='dotted',linewidth=dlinewidth) plot1.axhline(y = canonical_rp_min_B_AU, color= colors[1],linestyle='dotted',linewidth=dlinewidth) handles,labels = plot1.get_legend_handles_labels() plot1.legend(handles,labels,loc="upper right",fontsize=12) handles,labels = plot2.get_legend_handles_labels() plot2.legend(handles,labels,loc="lower right",fontsize=12) plot1.set_xlabel("t [Myr]",fontsize=18) plot2.set_xlabel("t [Myr]",fontsize=18) plot1.set_ylabel("$a_i [\mathrm{AU}]$",fontsize=18) plot2.set_ylabel("$i_{kl} [\mathrm{deg}]$",fontsize=18) plot1.set_xlim(0.0,print_times_Myr[-1]) plot2.set_xlim(0.0,print_times_Myr[-1]) plot1.tick_params(axis='both', which ='major', labelsize = 18) plot2.tick_params(axis='both', which ='major', labelsize = 18) fig.savefig("figure.eps") pyplot.show() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("--end_time", unit=units.Myr, dest="end_time", type="float", default = 5.0|units.Myr, help="integration time [%default]") result.add_option("--N_output", dest="N_output", type="int", default = 400, help="number of output steps [%default]") result.add_option("--m1", unit=units.MSun, dest="m1", type="float", default = 1.0|units.MSun, help="mass of object 1 [%default]") result.add_option("--m2", unit=units.MSun, dest="m2", type="float", default = 0.8|units.MSun, help="mass of object 2 [%default]") result.add_option("--m3", unit=units.MSun, dest="m3", type="float", default = 1.1|units.MSun, help="mass of object 3 [%default]") result.add_option("--m4", unit=units.MSun, dest="m4", type="float", default = 0.9|units.MSun, help="mass of object 4 [%default]") result.add_option("--aA", unit=units.AU, dest="aA", type="float", default = 1.0|units.AU, help="semimajor axis of orbit A [%default]") result.add_option("--aB", unit=units.AU, dest="aB", type="float", default = 1.2|units.AU, help="semimajor axis of orbit B [%default]") result.add_option("--aC", unit=units.AU, dest="aC", type="float", default = 100.0|units.AU, help="semimajor axis of orbit C (the `superorbit') [%default]") result.add_option("--eA", dest="eA", type="float", default = 0.1, help="eccentricity of orbit A [%default]") result.add_option("--eB", dest="eB", type="float", default = 0.1, help="eccentricity of orbit B [%default]") result.add_option("--eC", dest="eC", type="float", default = 0.3, help="eccentricity of orbit C (the `superorbit') [%default]") result.add_option("--iA", dest="iA", type="float", default = 75.0, help="inclination of orbit A in degrees [%default]") result.add_option("--iB", dest="iB", type="float", default = 80.0, help="inclination of orbit B in degrees [%default]") result.add_option("--iC", dest="iC", type="float", default = 0.001, help="inclination of orbit C (the `superorbit') in degrees [%default]") result.add_option("--ApA", dest="ApA", type="float", default = 10.0, help="argument of periapsis of orbit A in degrees [%default]") result.add_option("--ApB", dest="ApB", type="float", default = 30.0, help="argument of periapsis of orbit B in degrees [%default]") result.add_option("--ApC", dest="ApC", type="float", default = 60.0, help="argument of periapsis of orbit C (the `superorbit') in degrees [%default]") result.add_option("--LANA", dest="LANA", type="float", default = 0.001, help="longitude of the ascending node of orbit A in degrees [%default]") result.add_option("--LANB", dest="LANB", type="float", default = 0.001, help="longitude of the ascending node of orbit B in degrees [%default]") result.add_option("--LANC", dest="LANC", type="float", default = 0.001, help="longitude of the ascending node of orbit C (the `superorbit') in degrees [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() data = evolve_quadruple(**o.__dict__) plot_function(data)
11,599
45.586345
182
py
amuse
amuse-main/examples/textbook/merge_two_stars_sph.py
import sys import numpy from matplotlib import pyplot from amuse.lab import * from amuse.plot import plot from amuse.ext.sph_to_star import convert_SPH_to_stellar_model ###BOOKLISTSTART1### def return_evolved_star_hydro(mass, time, Nsph): star = Particle(mass=mass) stellar = EVtwin() star = stellar.particles.add_particle(star) stellar.evolve_model(time) Nsph = Nsph * int(mass.value_in(units.MSun)) star_in_sph = convert_stellar_model_to_SPH(star, Nsph).gas_particles stellar.stop() return star_in_sph ###BOOKLISTSTOP1### ###BOOKLISTSTART2### def merge_two_stars_sph(Mprim, Msec, t_coll, Nsph): primary_in_sph = return_evolved_star_hydro(Mprim, t_coll, Nsph) primary_in_sph = relax_sph_realization(primary_in_sph) secondary_in_sph = return_evolved_star_hydro(Msec, t_coll, Nsph) secondary_in_sph = relax_sph_realization(secondary_in_sph) R = primary_in_sph.x.max() + secondary_in_sph.x.max() M = primary_in_sph.mass.sum() + secondary_in_sph.mass.sum() secondary_in_sph.x += 0.8*R secondary_in_sph.y += 0.6*R secondary_in_sph.vx -= (constants.G*M/R).sqrt() converter=nbody_system.nbody_to_si(Mprim, 1.0|units.AU) hydro = Gadget2(converter) hydro.gas_particles.add_particles(primary_in_sph) hydro.gas_particles.add_particles(secondary_in_sph) hydro.evolve_model(2.0|units.hour) hydro.gas_particles.new_channel_to(primary_in_sph).copy() hydro.gas_particles.new_channel_to(secondary_in_sph).copy() hydro.stop() return primary_in_sph, secondary_in_sph ###BOOKLISTSTOP2### ###BOOKLISTSTART3### def relax_sph_realization(sph_star): dynamical_timescale = sph_star.dynamical_timescale() converter = nbody_system.nbody_to_si(dynamical_timescale, 1|units.RSun) hydro = Gadget2(converter, number_of_workers=2) hydro.gas_particles.add_particles(sph_star) to_hydro = sph_star.new_channel_to(hydro.gas_particles) to_framework = hydro.gas_particles.new_channel_to(sph_star) ts_factor = 2.5 t_end = ts_factor * sph_star.dynamical_timescale(mass_fraction=0.9) n_steps = ts_factor * 100 velocity_damp_factor = 1.0 - (ts_factor*2*numpy.pi)/n_steps dt = t_end/float(n_steps) time = 0|units.day while time < t_end: time += dt hydro.evolve_model(time) hydro.gas_particles.velocity = velocity_damp_factor * hydro.gas_particles.velocity to_framework.copy() hydro.stop() return sph_star ###BOOKLISTSTOP3### def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-M", unit=units.MSun, dest="Mprim", type="float",default = 10|units.MSun, help="Mass of the primary star [%default] MSun") result.add_option("-m", unit=units.MSun, dest="Msec", type="float",default = 1|units.MSun, help="Mass of the secondary star [%default] MSun") result.add_option("-N", dest="Nsph", type="int",default = 100, help="Number of sph particles per MSun [%default]") result.add_option("-t", unit=units.Myr, dest="t_coll", type="float", default = 0.01|units.Myr, help="end time of the simulation [%default] Myr") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() p, s = merge_two_stars_sph(**o.__dict__) pyplot.scatter(p.x.value_in(units.RSun), p.y.value_in(units.RSun), c='b') pyplot.scatter(s.x.value_in(units.RSun), s.y.value_in(units.RSun), c='r') pyplot.show()
3,666
38.858696
90
py
amuse
amuse-main/examples/textbook/compare_disk_size_Trapezium.py
import sys import os import numpy import math from matplotlib import pyplot from amuse.lab import * from prepare_figure import single_frame, figure_frame, set_tickmarks from distinct_colours import get_distinct import pickle try: amusedir = os.environ['AMUSE_DIR'] dir = amusedir+'/examples/textbook/' except: print('Environment variable AMUSE_DIR not set') dir = './' filename = dir+'Obs_Trapezium_disksizes.pkl' filepointer = open(filename, 'rb') (R_obs, yc_obs) = pickle.load(filepointer, encoding="bytes") filepointer.close() filename = dir+'Tr_N2000_R0.5pc_Q0.5_F1.6.pkl' filepointer = open(filename, 'rb') (R_sim, yc_sim) = pickle.load(filepointer, encoding="bytes") filepointer.close() print(len(R_obs), len(yc_obs)) print(len(R_sim), len(yc_sim)) from scipy import stats ks = stats.ks_2samp(R_obs, R_sim) print("Perform KS test on both sambles:", ks) color = get_distinct(2) x_label = 'R [$R_\odot$]' y_label = '$f_{<R}$' figure = single_frame(x_label, y_label, xsize=14, ysize=10) pyplot.plot(R_obs, 95*yc_obs, c=color[0]) pyplot.plot(R_sim, 95*yc_sim, c=color[1], ls="--") save_file = 'Tr_N2000_R05pc_Q05_F16_r1.png' pyplot.savefig(save_file) print('\nSaved figure in file', save_file,'\n') pyplot.show()
1,243
23.392157
68
py
amuse
amuse-main/examples/textbook/solar_cluster_in_live_galaxy.py
""" Nbody integration of N particles in N-body units from t=0 to t_end=1 Myr. The initial cluster is a King (1966) model with dimension-less depth of the potential of W0=7. The initial distribution of stars is in virial equilibrium. At this moment a 4th order Hermite integrator is used for the integration. Stellar masses are selected randomly from a Salpeter initial mass function between a minimum mass of Mmin=0.1MSun and Mmax=100MSun. In order to assure proper scaling to astrophysical units, we have to define the cluster radius in physical units, in this case, we opted for a virial radius of 1pc. cluster in orbit in static potential """ import math import numpy from amuse.lab import * from optparse import OptionParser from amuse.units.optparse import OptionParser from amuse.couple import bridge from amuse.community.halogen.interface import HalogenInterface, Halogen import amuse.community.halogen def initialize_galaxy_model(N, converter): #default_options = dict(redirection = "none") instance = Halogen(converter) instance.initialize_code() instance.parameters.alpha = 2.0 instance.parameters.beta = 5.0 instance.parameters.gamma = 0.0 instance.parameters.number_of_particles = N instance.parameters.random_seed = 1 instance.commit_parameters() instance.generate_particles() galaxy = instance.particles.copy() instance.cleanup_code() instance.stop() return galaxy def main(N=1000, n=100, W0=7.0, t_end=10|units.Myr, dt_diag=1|units.Myr, filename="nbody.hdf5", Mtot=100|units.MSun, Rvir=1|units.parsec): pos = [-1.72566460731, -11.0998897304, -0.0790965379539] | units.kpc vel = [174.619387484, -36.7939713616, 0.85020621627] | units.kms masses = new_salpeter_mass_distribution(n, 0.1|units.MSun, 10.0|units.MSun) converter=nbody_system.nbody_to_si(masses.sum(),Rvir) cluster = new_king_model(n, W0,convert_nbody=converter) cluster.mass = masses cluster.scale_to_standard(convert_nbody=converter) cluster.position += pos cluster.velocity += vel cluster.radius = 0 | units.parsec cluster_gravity = ph4(converter) cluster_gravity.parameters.timestep_parameter = 0.1 cluster_gravity.parameters.epsilon_squared = (100|units.AU)**2 cluster_gravity.particles.add_particles(cluster) channel_from_cluster_to_framework = cluster_gravity.particles.new_channel_to(cluster) stellar = SeBa() stellar.particles.add_particles(cluster) channel_from_stellar_to_cluster_gravity = stellar.particles.new_channel_to(cluster_gravity.particles) converter=nbody_system.nbody_to_si(2.067352e+11|units.MSun,1|units.kpc) galaxy = initialize_galaxy_model(N=N, converter=converter) print(len(galaxy)) galaxy_gravity = BHTree(converter) galaxy_gravity.parameters.timestep_parameter = 0.1 galaxy_gravity.parameters.epsilon_squared = (100|units.parsec)**2 galaxy_gravity.particles.add_particles(galaxy) channel_from_galaxy_to_framework = galaxy_gravity.particles.new_channel_to(galaxy) moving_bodies = ParticlesSuperset([cluster, galaxy]) time = 0.0 | t_end.unit write_set_to_file(galaxy.savepoint(time), filename, 'hdf5', append_to_file=False) write_set_to_file(cluster.savepoint(time), filename, 'hdf5') gravity = bridge.Bridge(use_threading=False) gravity.add_system(cluster_gravity, (galaxy_gravity,) ) gravity.add_system(galaxy_gravity, (cluster_gravity,) ) Etot_init = gravity.kinetic_energy + gravity.potential_energy Etot_prev = Etot_init dt = dt_diag t_orb = 2*numpy.pi*pos.length()/vel.length() gravity.timestep = t_orb/32. while time < t_end: time += dt stellar.evolve_model(time) channel_from_stellar_to_cluster_gravity.copy() gravity.evolve_model(time) Etot_prev_se = gravity.kinetic_energy + gravity.potential_energy channel_from_cluster_to_framework.copy() channel_from_galaxy_to_framework.copy() write_set_to_file(galaxy.savepoint(time), filename, 'hdf5') write_set_to_file(cluster.savepoint(time), filename, 'hdf5') Ekin = gravity.kinetic_energy Epot = gravity.potential_energy Etot = Ekin + Epot print("T=", time, end=' ') print("E= ", Etot, "Q= ", Ekin/Epot, end=' ') print("dE=", (Etot_init-Etot)/Etot, "ddE=", (Etot_prev-Etot)/Etot) Etot_prev = Etot gravity.stop() def new_option_parser(): result = OptionParser() result.add_option("-d", unit=units.Myr, dest="dt_diag", type="float", default = 0.5|units.Gyr, help="diagnostics output time steps [%default]") result.add_option("-f", dest="filename", default = "proto_solar_cluster_life.hdf5", help="output filename [%default]") result.add_option("-N", dest="N", type="int",default = 10000, help="number of stars in the Galaxy [%default]") result.add_option("-n", dest="n", type="int",default = 1000, help="number of stars in the cluster [%default]") result.add_option("-M", unit=units.MSun, dest="Mtot", type="float",default = 10000|units.MSun, help="cluster mass [100] MSun") result.add_option("-r", unit=units.parsec, dest="Rvir", type="float",default = 100.0|units.parsec, help="cluser virial radius [%default]") result.add_option("-t", unit=units.Myr, dest="t_end", type="float", default = 4.6|units.Gyr, help="end time of the simulation [1] %unit") result.add_option("-W", dest="W0", type="float", default = 3.0, help="Dimension-less depth of the King potential (W0) [7.0]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
6,000
41.260563
138
py
amuse
amuse-main/examples/textbook/evolve_triple_with_wind_2.py
""" N-body integration of N partcles with a Salpeter initial mass function between Mmin and Mmax and with stellar evolution with metallicity z. """ import sys import math, numpy from optparse import OptionParser import matplotlib #matplotlib.use('Agg') from matplotlib import pyplot as plt from prepare_figure import single_frame from distinct_colours import get_distinct from amuse.units import units, constants, nbody_system from amuse.units.quantities import zero from amuse.datamodel import Particle, Particles from amuse.support.console import set_printing_strategy from amuse.io import store from amuse.ext.orbital_elements import new_binary_from_orbital_elements from amuse.ext.orbital_elements import orbital_elements_from_binary from amuse.community.symple.interface import symple # symplectic from amuse.community.huayno.interface import Huayno # symplectic from amuse.community.smalln.interface import SmallN # time reversible from amuse.community.hermite.interface import Hermite # not symplectic from amuse.community.seba.interface import SeBa from amuse.community.sse.interface import SSE def orbital_period(a, Mtot): return 2*numpy.pi*(a**3/(constants.G*Mtot)).sqrt() def semimajor_axis(P, Mtot): return (constants.G*Mtot*P**2/(4*numpy.pi**2))**(1./3) def get_orbital_elements_of_triple(stars): inner_binary = stars[0]+stars[1] outer_binary = Particles(1) outer_binary[0].mass = inner_binary.mass.sum() outer_binary[0].position = inner_binary.center_of_mass() outer_binary[0].velocity = inner_binary.center_of_mass_velocity() outer_binary.add_particle(stars[2]) M1, M2, ain, ein, ta_in, inc_in, lan_in, aop_in \ = orbital_elements_from_binary(inner_binary, G=constants.G) M12, M3, aout, eout, ta_out, outc_out, lan_out, aop_out \ = orbital_elements_from_binary(outer_binary, G=constants.G) return ain, ein, aout, eout def evolve_triple_with_wind(M1, M2, M3, Pora, Pin_0, ain_0, aout_0, ein_0, eout_0, t_end, nsteps, scheme, integrator, t_stellar, dt_se, dtse_fac, interp): import random from amuse.ext.solarsystem import get_position numpy.random.seed(42) print("Initial masses:", M1, M2, M3) triple = Particles(3) triple[0].mass = M1 triple[1].mass = M2 triple[2].mass = M3 stellar = SeBa() stellar.particles.add_particles(triple) channel_from_stellar = stellar.particles.new_channel_to(triple) # Evolve to t_stellar. stellar.evolve_model(t_stellar) channel_from_stellar.copy_attributes(["mass"]) M1 = triple[0].mass M2 = triple[1].mass M3 = triple[2].mass print("t=", stellar.model_time.in_(units.Myr)) print("M=", stellar.particles.mass.in_(units.MSun)) print("R=", stellar.particles.radius.in_(units.RSun)) print("L=", stellar.particles.luminosity.in_(units.LSun)) print("T=", stellar.particles.temperature.in_(units.K)) print("Mdot=", \ -stellar.particles.wind_mass_loss_rate.in_(units.MSun/units.yr)) # Start the dynamics. # Inner binary: tmp_stars = Particles(2) tmp_stars[0].mass = M1 tmp_stars[1].mass = M2 if Pora == 1: ain_0 = semimajor_axis(Pin_0, M1+M2) else: Pin_0 = orbital_period(ain_0, M1+M2) print('Pin =', Pin_0) print('ain_0 =', ain_0) print('M1+M2 =', M1+M2) print('Pin_0 =', Pin_0.value_in(units.day), '[day]') #print 'semi:', semimajor_axis(Pin_0, M1+M2).value_in(units.AU), 'AU' #print 'period:', orbital_period(ain_0, M1+M2).value_in(units.day), '[day]' dt_init = 0.01*Pin_0 ma = 180 inc = 60 aop = 180 lon = 0 r,v = get_position(M1, M2, ein_0, ain_0, ma, inc, aop, lon, dt_init) tmp_stars[1].position = r tmp_stars[1].velocity = v tmp_stars.move_to_center() # Outer binary: r,v = get_position(M1+M2, M3, eout_0, aout_0, 0, 0, 0, 0, dt_init) tertiary = Particle() tertiary.mass = M3 tertiary.position = r tertiary.velocity = v tmp_stars.add_particle(tertiary) tmp_stars.move_to_center() triple.position = tmp_stars.position triple.velocity = tmp_stars.velocity Mtriple = triple.mass.sum() Pout = orbital_period(aout_0, Mtriple) print("T=", stellar.model_time.in_(units.Myr)) print("M=", stellar.particles.mass.in_(units.MSun)) print("Pout=", Pout.in_(units.Myr)) print('tK =', ((M1+M2)/M3)*Pout**2*(1-eout_0**2)**1.5/Pin_0) converter = nbody_system.nbody_to_si(triple.mass.sum(), aout_0) if integrator == 0: gravity = Hermite(converter) gravity.parameters.timestep_parameter = 0.01 elif integrator == 1: gravity = SmallN(converter) gravity.parameters.timestep_parameter = 0.01 gravity.parameters.full_unperturbed = 0 elif integrator == 2: gravity = Huayno(converter) gravity.parameters.inttype_parameter = 20 gravity.parameters.timestep = (1./256)*Pin_0 else: gravity = symple(converter) gravity.parameters.integrator = 10 #gravity.parameters.timestep_parameter = 0. gravity.parameters.timestep = (1./128)*Pin_0 print(gravity.parameters) gravity.particles.add_particles(triple) channel_from_framework_to_gd = triple.new_channel_to(gravity.particles) channel_from_gd_to_framework = gravity.particles.new_channel_to(triple) Etot_init = gravity.kinetic_energy + gravity.potential_energy Etot_prev = Etot_init gravity.particles.move_to_center() # Note: time = t_diag = 0 at the start of the dynamical integration. dt_diag = t_end/float(nsteps) t_diag = dt_diag time = 0.0 | t_end.unit t_se = t_stellar + time print('t_end =', t_end) print('dt_diag =', dt_diag) ain, ein, aout, eout = get_orbital_elements_of_triple(triple) print("Triple elements t=", time, \ "inner:", triple[0].mass, triple[1].mass, ain, ein, \ "outer:", triple[2].mass, aout, eout) t = [time.value_in(units.Myr)] Mtot = triple.mass.sum() mtot = [Mtot.value_in(units.MSun)] smai = [ain/ain_0] ecci = [ein/ein_0] smao = [aout/aout_0] ecco = [eout/eout_0] if interp: # Create arrays of stellar times and masses for interpolation. times = [time] masses = [triple.mass.copy()] while time < t_end: time += dt_se stellar.evolve_model(t_stellar+time) channel_from_stellar.copy_attributes(["mass"]) times.append(time) masses.append(triple.mass.copy()) time = 0.0 | t_end.unit print('\ntimes:', times, '\n') # Evolve the system. def advance_stellar(t_se, dt): E0 = gravity.kinetic_energy + gravity.potential_energy t_se += dt if interp: t = t_se-t_stellar i = int(t/dt_se) mass = masses[i] + (t-times[i])*(masses[i+1]-masses[i])/dt_se triple.mass = mass #print 't_se =', t_se, 'masses =', mass else: stellar.evolve_model(t_se) channel_from_stellar.copy_attributes(["mass"]) channel_from_framework_to_gd.copy_attributes(["mass"]) return t_se, gravity.kinetic_energy + gravity.potential_energy - E0 def advance_gravity(tg, dt): tg += dt gravity.evolve_model(tg) channel_from_gd_to_framework.copy() return tg while time < t_end: if scheme == 1: # Advance to the next diagnostic time. dE_se = zero dt = t_diag - time if dt > 0|dt.unit: time = advance_gravity(time, dt) elif scheme == 2: # Derive dt from Pin using dtse_fac. dt = dtse_fac*Pin_0 if time + dt > t_diag: dt = t_diag - time if dt > 0|dt.unit: t_se, dE_se = advance_stellar(t_se, dt) time = advance_gravity(time, dt) elif scheme == 3: # Derive dt from Pin using dtse_fac. dt = dtse_fac*Pin_0 if time + dt > t_diag: dt = t_diag - time if dt > 0|dt.unit: time = advance_gravity(time, dt) t_se, dE_se = advance_stellar(t_se, dt) elif scheme == 4: # Derive dt from Pin using dtse_fac. dt = dtse_fac*Pin_0 if time + dt > t_diag: dt = t_diag - time if dt > 0|dt.unit: t_se, dE_se = advance_stellar(t_se, 0.5*dt) time = advance_gravity(time, dt) t_se, dE_se2 = advance_stellar(t_se, 0.5*dt) dE_se += dE_se2 elif scheme == 5: # Use the specified dt_se. dE_se = zero dt = dt_se if time + dt > t_diag: dt = t_diag - time if dt > 0|dt.unit: # For use with symple only: set up average mass loss. channel_from_stellar.copy_attributes(["mass"]) m0 = triple.mass.copy() stellar.evolve_model(t_se+dt) channel_from_stellar.copy_attributes(["mass"]) t_se = stellar.model_time m1 = triple.mass dmdt = (m1-m0)/dt for i in range(len(dmdt)): gravity.set_dmdt(i, dmdt[i]) time = advance_gravity(time, dt) else: print('unknown option') sys.exit(0) if time >= t_diag: t_diag = time + dt_diag Ekin = gravity.kinetic_energy Epot = gravity.potential_energy Etot = Ekin + Epot dE = Etot_prev - Etot Mtot = triple.mass.sum() print("T=", time, end=' ') print("M=", Mtot, "(dM[SE]=", Mtot/Mtriple, ")", end=' ') print("E= ", Etot, "Q= ", Ekin/Epot, end=' ') print("dE=", (Etot_init-Etot)/Etot, "ddE=", (Etot_prev-Etot)/Etot, end=' ') print("(dE[SE]=", dE_se/Etot, ")") Etot_init -= dE Etot_prev = Etot ain, ein, aout, eout = get_orbital_elements_of_triple(triple) print("Triple elements t=", t_stellar + time, \ "inner:", triple[0].mass, triple[1].mass, ain, ein, \ "outer:", triple[2].mass, aout, eout) t.append(time.value_in(units.yr)) mtot.append(Mtot.value_in(units.MSun)) smai.append(ain/ain_0) ecci.append(ein/ein_0) smao.append(aout/aout_0) ecco.append(eout/eout_0) if eout > 1 or aout <= zero: print("Binary ionized or merged") break gravity.stop() stellar.stop() return t, mtot, smai, ecci, smao, ecco def main(M1, M2, M3, Pora, Pin, ain, aout, ein, eout, t_end, nsteps, scheme, integrator, t_stellar, dt_se, dtse_fac, interp, show): two_frames = False plot_ae = True color = get_distinct(4) if two_frames: plt.figure(figsize=(10, 8)) else: plt.figure(figsize=(12, 8)) if scheme == 5: if integrator != 3: print('Warning: scheme = 5 forces integrator = 3') integrator = 3 srange = [1,scheme] # 1 = no mass loss; other = mass loss # assume scheme > 1 i = 0 lw = [1,2] srange = [1, scheme] for s in srange: time, mtot, ai, ei, ao, eo \ = evolve_triple_with_wind(M1, M2, M3, Pora, Pin, ain, aout, ein, eout, t_end, nsteps, s, integrator, t_stellar, dt_se, dtse_fac, interp) if i == 0: if two_frames: plt.subplot(1,2,1) plt.plot(time, ai, c=color[0], linewidth=lw[i], label='inner, no mass loss') plt.plot(time, ao, c=color[3], linewidth=lw[i], label='outer, no mass loss') plt.xlabel('time (yr)') plt.ylabel('$a/a_0$') if two_frames: plt.subplot(1,2,2) if plot_ae: plt.plot(ai, ei, c=color[0], linewidth=lw[i]) plt.plot(ao, eo, c=color[3], linewidth=lw[i]) plt.xlabel('$a/a_0$') plt.ylabel('$e/e_0$') else: plt.plot(time, mtot, c=color[0], linewidth=lw[i]) plt.xlabel('time (yr)') plt.ylabel('M') i = 1 else: if two_frames: plt.subplot(1,2,1) plt.plot(time, ai, c=color[1], linewidth=lw[i], label='inner, mass loss') plt.plot(time, ao, c=color[2], linewidth=lw[i], label='outer, mass loss') if two_frames: plt.subplot(1,2,2) if plot_ae: plt.plot(ai, ei, c=color[1], linewidth=lw[i]) plt.plot(ao, eo, c=color[2], linewidth=lw[i]) else: plt.plot(time, mtot, c=color[1], linewidth=lw[i]) if two_frames: plt.subplot(1,2,1) plt.legend(loc='best') integrators = ['hermite', 'smalln', 'huayno', 'symple'] label = integrators[integrator] label += ' integrator, stellev scheme= {:d}'.format(scheme) save_file \ = 'evolve_triple_with_wind_t={:.3f}'.format(t_end.value_in(units.Myr)) \ +'_i={:d}_s={:d}'.format(integrator, scheme) if scheme < 5: label += ', dtse_fac = {:.3f}'.format(dtse_fac) save_file += '_dtsefac={:.3f}'.format(dtse_fac) else: label += ', dt_se = {:.1f}'.format(dt_se.value_in(units.yr)) save_file += '_dtse={:.1f}'.format(dt_se.value_in(units.yr)) save_file += '.png' if two_frames: plt.tight_layout() plt.subplots_adjust(top=0.88) #plt.suptitle(label, y=0.97, fontsize=15) ax = plt.gca() ax.minorticks_on() # switch on the minor ticks ax.tick_params(axis='both', which='both', direction='in') ax.locator_params(nbins=3) ax.get_yaxis().get_major_formatter().set_useOffset(False) plt.savefig(save_file, dpi=300) print('\nSaved figure in file', save_file,'\n') if show: plt.show() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("--ain", unit=units.AU, dest="ain", type="float", default = 0.63|units.AU, help="orbital separation [%default]") result.add_option("--aout", unit=units.AU, dest="aout", type="float", default = 100|units.AU, help="orbital separation [%default]") result.add_option("--dtse", unit=units.Myr, dest="dt_se", type="float", default = 1.e-3|units.Myr, help="stellar mass-loss time step [%default]") result.add_option("--dtse_fac", dest="dtse_fac", type="float", default = 0.1, help="stellar mass-loss time step fraction [%default]") result.add_option("--ein", dest="ein", type="float", default = 0.2, help="orbital eccentricity [%default]") result.add_option("--eout", dest="eout", type="float", default = 0.6, help="orbital eccentricity [%default]") result.add_option("-i", dest="integrator", type="int", default = 2, help="integration scheme [%default]") result.add_option("-I", dest="interp", action="store_false", default = True, help="interpolate stellar evolution [%default]") result.add_option("--M1", unit=units.MSun, dest="M1", type="float", default = 60|units.MSun, help="Primary mass [%default]") result.add_option("--M2", unit=units.MSun, dest="M2", type="float", default = 30|units.MSun, help="secondary mass [%default]") result.add_option("--M3", unit=units.MSun, dest="M3", type="float", default = 20|units.MSun, help="secondary mass [%default]") result.add_option("-n", dest="nsteps", type="int", default = 1000, help="number of data points [%default]") result.add_option("--Pin", unit=units.day, dest="Pin", type="float", default = 19|units.day, help="orbital period [%default]") result.add_option("--Pora", dest="Pora", type="int", default = 1, help="period (1) or semimajor axis (2) [%default]") result.add_option("-s", dest="scheme", type="int", default = 3, help="stellar integration method [%default]") result.add_option("-S", dest="show", action="store_false", default = True, help="show plot on display [%default]") result.add_option("-t", unit=units.Myr, dest="t_end", type="float", default = 1.e-3|units.Myr, help="end time of the dynamical simulation [%default]") result.add_option("--ts", unit=units.Myr, dest="t_stellar", type="float", default = 4.|units.Myr, help="stellar evolution time [%default]") return result if __name__ in ('__main__', '__plot__'): #set_printing_strategy("custom", # preferred_units = [units.MSun, units.AU, units.Myr], # precision = 12, prefix = "", # separator = " [", suffix = "]") o, arguments = new_option_parser().parse_args() print(o.__dict__) main(**o.__dict__)
18,275
34.765166
88
py
amuse
amuse-main/examples/textbook/plot_wind_disk_interaction.py
""" Visualization for simple N-body integration. Reads particle set from file (nbody.hdf5) and prints subsequent frames. """ import sys import numpy from matplotlib import pyplot from amuse.plot import scatter, xlabel, ylabel from amuse.lab import * from amuse.io import store #from optparse import OptionParser from time import sleep from amuse.units.optparse import OptionParser from amuse.plot import sph_particles_plot import matplotlib.pyplot as plt import matplotlib.cm as cm from matplotlib.colors import LogNorm import numpy as np from prepare_figure import single_frame #from distinct_colours import get_distinct def main(filename = "hydro.hdf5", lim=None, image_id=-1, nice_plot=1): x_label = 'x' y_label = 'y' figure = single_frame(x_label, y_label, logy=False, xsize=14, ysize=10) stars = read_set_from_file(filename, "hdf5") print(stars) snapshot_id = 0 isgas = True snapshot_id = 0 sinks = Particles(0) for si in stars.history: if isgas: gas = si isgas = False else: sinks = si isgas = True if not isgas: snapshot_id += 1 time = gas.get_timestamp() if image_id<0 or image_id == snapshot_id: pyplot.hist2d(gas.x.value_in(units.AU), gas.y.value_in(units.AU), (200, 200), cmap=plt.cm.jet) pyplot.scatter(gas.x.value_in(units.AU), gas.y.value_in(units.AU), c='y', s=100) if False: for gi in gas: pyplot.arrow(gi.x.value_in(units.AU), gi.y.value_in(units.AU), gi.vx.value_in(units.AU/units.yr), gi.vy.value_in(units.AU/units.yr), head_width=0.05, head_length=0.1) # sph_particles_plot(gas, u_range=[min(gas.u), max(gas.u)], width=lim, alpha = 1) # if len(sinks): # scatter(sinks.x.value_in(units.AU), sinks.y.value_in(units.AU), c='y', s=100) if image_id == snapshot_id: break pyplot.xlabel("X [pc]") pyplot.ylabel("Y [pc]") pyplot.show() def new_option_parser(): result = OptionParser() result.add_option("-f", dest="filename", default = "DiskWind.h5", help="output filename [DiskWind.h5]") result.add_option("-l", unit=units.parsec, dest="lim", type="float", default = None, help="boxsize [%default]") result.add_option("-i", dest="image_id", type="int", default = -1, help="image id [%default]") result.add_option("-p", dest="nice_plot", type="int", default = 1, help="nice plot [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() filename = "hydro_GMC.h5" gas = read_set_from_file(filename, "hdf5") main(**o.__dict__)
3,061
33.795455
98
py
amuse
amuse-main/examples/textbook/plot_SunAndEarthAndMoon.py
import numpy from matplotlib import pyplot from amuse.lab import * from prepare_figure import * from distinct_colours import get_distinct def orbital_elements(primary, secondary): stellar_pair = Particles() stellar_pair.add_particle(primary) stellar_pair.add_particle(secondary) Johannes.initialize_from_particles(stellar_pair) return Johannes.get_elements() def read_and_process_file(filename): stars = read_set_from_file(filename, "hdf5") t = [] | units.yr Ek = [] | units.erg Ep = [] | units.erg for si in stars.history: Ek.append(si.kinetic_energy()) Ep.append(si.potential_energy()) time = si.get_timestamp() t.append(time) Etot = Ek + Ep ENorm = Etot[0] Etot = (Etot-ENorm)/ENorm return t, Etot def main(): colors = get_distinct(4) figure = pyplot.figure(figsize=(16, 12)) ax = pyplot.gca() ax.minorticks_on() # switch on the minor ticks ax.locator_params(nbins=3) x_label = "t [year]" y_label = "$\Delta E/E_0$" pyplot.xlabel(x_label) pyplot.ylabel(y_label) pyplot.xlim(0, 110) t, E = read_and_process_file("SunAndEarthAndMoon_ISS.h5") pyplot.plot(t.value_in(units.yr), E, c=colors[0], label="ph4 ($dt_{param}=0.15$)") t, E = read_and_process_file("SunAndEarthAndMoon_TBwB.h5") pyplot.plot(t.value_in(units.yr), E, c=colors[3], label="Bridge with ph4 (E&M)") t, E = read_and_process_file("SunAndEarthAndMoon_TBB.h5") pyplot.plot(t.value_in(units.yr), E, c=colors[1], label="Three-body bridge") # pyplot.plot(t.value_in(units.year), E) t, E = read_and_process_file("SunAndEarthAndMoon_TBBH.h5") pyplot.plot(t.value_in(units.yr), E, c=colors[2], label="Hierarchical bridge") pyplot.legend(loc=4, borderaxespad=0.) pyplot.savefig("fig_three_body_bridge") pyplot.show() if __name__ == '__main__': main()
1,922
24.64
86
py
amuse
amuse-main/examples/textbook/plot_fractal_clumpy_cluster.py
import numpy from amuse.lab import * from amuse.ext.orbital_elements import orbital_elements_from_binary from amuse.community.fractalcluster.interface import new_fractal_cluster_model from matplotlib import pyplot def plot_single_image(groups_of_particles, lim=10): left, width = 0.1, 0.4 bottom, height = 0.1, 0.4 bottom_h = left_h = left+width+0.05 rect_xy = [left, bottom, width, height] rect_xz = [left, bottom_h, width, 0.4] rect_yz = [left_h, bottom, 0.4, height] from distinct_colours import get_distinct colors = get_distinct(12) fig = pyplot.figure(figsize=(10,10)) xy = pyplot.axes(rect_xy) xz = pyplot.axes(rect_xz) yz = pyplot.axes(rect_yz) xy.set_xlabel("X [pc]") xy.set_ylabel("Y [pc]") xz.set_ylabel("Z [pc]") yz.set_xlabel("Z [pc]") i = 0 for group in groups_of_particles: x = group.x.value_in(units.parsec) y = group.y.value_in(units.parsec) z = group.z.value_in(units.parsec) xy.scatter(x, y, lw=0, c=colors[min(11, i)], s=8) xz.scatter(x, z, lw=0, c=colors[min(11, i)], s=8) yz.scatter(z, y, lw=0, c=colors[min(11, i)], s=8) i += 1 xy.set_xlim((-lim, lim)) xy.set_ylim((-lim, lim)) xz.set_xlim(xy.get_xlim()) yz.set_ylim(xy.get_xlim()) yz.set_xlim(xy.get_xlim()) xz.set_ylim(xy.get_xlim()) save_file = 'FractalClusterHop.png' pyplot.savefig(save_file) print('\nSaved figure in file', save_file,'\n') pyplot.show() def find_clumps_with_hop(particles, unit_converter): ###BOOKLISTSTART### hop = Hop(unit_converter) hop.particles.add_particles(particles) hop.calculate_densities() mean_density = hop.particles.density.mean() hop.parameters.peak_density_threshold = mean_density hop.parameters.saddle_density_threshold = 0.99*mean_density hop.parameters.outer_density_threshold = 0.01*mean_density hop.do_hop() result = [x.get_intersecting_subset_in(particles) for x in hop.groups()] hop.stop() ###BOOKLISTSTOP### return result def main(N, Rvir, Qvir, Fd, seed): numpy.random.seed(seed) masses = new_kroupa_mass_distribution(N) converter = nbody_system.nbody_to_si(masses.sum(), Rvir) bodies = new_fractal_cluster_model(N=N, fractal_dimension=Fd, random_seed=seed, convert_nbody=converter) bodies.mass = masses bodies.move_to_center() bodies.scale_to_standard(converter, virial_ratio=Qvir) clumps = find_clumps_with_hop(bodies, converter) for clump in clumps: clump.scale_to_standard(converter, virial_ratio=0.5) plot_single_image(clumps, lim=50) def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-N", dest="N", type="int",default = 2000, help="number of stars [%default]") result.add_option("-R", dest="Rvir", type="float", unit=units.parsec, default = 0.5|units.parsec, help="cluser virial radius [%default]") result.add_option("-Q", dest="Qvir", type="float",default = 0.5, help="virial ratio [%default]") result.add_option("-F", dest="Fd", type="float",default = 1.6, help="fractal dimension [%default]") result.add_option("-s", dest="seed", type="int",default = 12345, help="random number seed [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
3,657
32.87037
78
py
amuse
amuse-main/examples/textbook/gravity_hydro.py
""" example code for bridging a gravity solver with a hydrodynamics solver """ import numpy from amuse.lab import * from amuse.couple import bridge from amuse.ext.orbital_elements import new_binary_from_orbital_elements from amuse.ext.orbital_elements import orbital_elements_from_binary ###BOOKLISTSTART1### class BaseCode: def __init__(self, code, particles, eps=0|units.RSun): self.local_particles = particles m = self.local_particles.mass.sum() l = self.local_particles.position.length() self.converter = nbody_system.nbody_to_si(m, l) self.code = code(self.converter) self.code.parameters.epsilon_squared = eps**2 def evolve_model(self, time): self.code.evolve_model(time) def copy_to_framework(self): self.channel_to_framework.copy() def get_gravity_at_point(self, r, x, y, z): return self.code.get_gravity_at_point(r, x, y, z) def get_potential_at_point(self, r, x, y, z): return self.code.get_potential_at_point(r, x, y, z) def get_timestep(self): return self.code.parameters.timestep @property def model_time(self): return self.code.model_time @property def particles(self): return self.code.particles @property def total_energy(self): return self.code.kinetic_energy + self.code.potential_energy @property def stop(self): return self.code.stop ###BOOKLISTSTOP1### ###BOOKLISTSTART2### class Gravity(BaseCode): def __init__(self, code, particles, eps=0|units.RSun): BaseCode.__init__(self, code, particles, eps) self.code.particles.add_particles(self.local_particles) self.channel_to_framework \ = self.code.particles.new_channel_to(self.local_particles) self.channel_from_framework \ = self.local_particles.new_channel_to(self.code.particles) self.initial_total_energy = self.total_energy ###BOOKLISTSTOP2### ###BOOKLISTSTART3### class Hydro(BaseCode): def __init__(self, code, particles, eps=0|units.RSun, dt=None, Rbound=None): BaseCode.__init__(self, code, particles, eps) self.channel_to_framework \ = self.code.gas_particles.new_channel_to(self.local_particles) self.channel_from_framework \ = self.local_particles.new_channel_to(self.code.gas_particles) self.code.gas_particles.add_particles(particles) m = self.local_particles.mass.sum() l = self.code.gas_particles.position.length() if Rbound is None: Rbound = 10*l self.code.parameters.periodic_box_size = Rbound if dt is None: dt = 0.01*numpy.sqrt(l**3/(constants.G*m)) self.code.parameters.timestep = dt/8. self.initial_total_energy = self.total_energy @property def total_energy(self): return self.code.kinetic_energy \ + self.code.potential_energy \ + self.code.thermal_energy ###BOOKLISTSTOP3### ###BOOKLISTSTART4### def gravity_hydro_bridge(Mprim, Msec, a, ecc, t_end, n_steps, Rgas, Mgas, Ngas): stars = new_binary_from_orbital_elements(Mprim, Msec, a, ecc, G=constants.G) eps = 1 | units.RSun gravity = Gravity(ph4, stars, eps) converter = nbody_system.nbody_to_si(1.0|units.MSun, Rgas) ism = new_plummer_gas_model(Ngas, convert_nbody=converter) ism.move_to_center() ism = ism.select(lambda r: r.length()<2*a,["position"]) hydro = Hydro(Fi, ism, eps) model_time = 0 | units.Myr filename = "gravhydro.hdf5" write_set_to_file(stars.savepoint(model_time), filename, 'amuse') write_set_to_file(ism, filename, 'amuse') gravhydro = bridge.Bridge(use_threading=False) gravhydro.add_system(gravity, (hydro,)) gravhydro.add_system(hydro, (gravity,)) gravhydro.timestep = 2*hydro.get_timestep() while model_time < t_end: orbit = orbital_elements_from_binary(stars, G=constants.G) dE_gravity = gravity.initial_total_energy/gravity.total_energy dE_hydro = hydro.initial_total_energy/hydro.total_energy print(("Time:", model_time.in_(units.yr), \ "ae=", orbit[2].in_(units.AU), orbit[3], \ "dE=", dE_gravity, dE_hydro)) model_time += 10*gravhydro.timestep gravhydro.evolve_model(model_time) gravity.copy_to_framework() hydro.copy_to_framework() write_set_to_file(stars.savepoint(model_time), filename, 'amuse') write_set_to_file(ism, filename, 'amuse') print("P=", model_time.in_(units.yr), gravity.particles.x.in_(units.au)) gravity.stop() hydro.stop() ###BOOKLISTSTOP4### def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-n", dest="n_steps", type="int", default = 1000, help="number of diagnostics time steps [%default]") result.add_option("-N", dest="Ngas", type="int", default = 1024, help="number of gas particles [%default]") result.add_option("--Mprim", unit=units.MSun, dest="Mprim", type="float", default = 3.2|units.MSun, help="Mass of the primary star [%default]") result.add_option("--Msec", unit=units.MSun, dest="Msec", type="float", default = 3.1|units.MSun, help="Mass of the secondary star [%default]") result.add_option("-M", unit=units.MSun, dest="Mgas", type="float", default = 1|units.MSun, help="Mass of the gas [%default]") result.add_option("-R", unit=units.AU, dest="Rgas", type="float", default = 10|units.AU, help="Size of the gas distribution [%default]") result.add_option("-a", unit=units.AU, dest="a", type="float", default = 1|units.AU, help="initial orbital separation [%default]") result.add_option("-e", dest="ecc", type="float", default = 0.6, help="initial orbital eccentricity [%default]") result.add_option("-t", unit=units.yr, dest="t_end", type="float", default = 10000|units.yr, help="end time of the simulation [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() numpy.random.seed(123) gravity_hydro_bridge(**o.__dict__)
6,596
40.490566
80
py
amuse
amuse-main/examples/textbook/gravity_drifter.py
import numpy from amuse.lab import * from amuse.units import units from amuse.units import quantities from amuse.units import constants from amuse.units import nbody_system from amuse.ext.bridge import bridge from amuse.community.phigrape.interface import PhiGRAPE from amuse.community.ph4.interface import ph4 from amuse.community.fi.interface import Fi from amuse.community.bhtree.interface import BHTree from amuse.community.gadget2.interface import Gadget2 from matplotlib import pyplot from amuse.ic.kingmodel import new_king_model ###BOOKLISTSTART1### class drift_without_gravity(object): def __init__(self, convert_nbody, time= 0 |units.Myr): self.model_time = time self.convert_nbody = convert_nbody self.particles = Particles() def evolve_model(self, t_end): dt = t_end - self.model_time self.particles.position += self.particles.velocity*dt self.model_time = t_end @property def potential_energy(self): return quantities.zero @property def kinetic_energy(self): return (0.5*self.particles.mass \ *self.particles.velocity.lengths()**2).sum() def stop(self): pass ###BOOKLISTSTOP1### class MilkyWay_galaxy(object): def __init__(self, Mb=1.40592e10| units.MSun, Md=8.5608e10| units.MSun, Mh=1.07068e11 | units.MSun): self.Mb = Mb self.Md = Md self.Mh = Mh def get_potential_at_point(self,eps,x,y,z): r = (x**2+y**2+z**2)**0.5 R = (x**2+y**2)**0.5 # bulge b1 = 0.3873 |units.kpc pot_bulge = -constants.G*self.Mb/(r**2+b1**2)**0.5 # disk a2 = 5.31 |units.kpc b2 = 0.25 |units.kpc pot_disk = -constants.G*self.Md/(R**2+(a2+(z**2+b2**2)**0.5)**2)**0.5 #halo a3 = 12.0 |units.kpc cut_off = 100 |units.kpc d1 = r/a3 c = 1+ (cut_off/a3)**1.02 pot_halo = -constants.G*(self.Mh/a3)*d1**1.02/(1+ d1**1.02) \ - (constants.G*self.Mh/(1.02*a3))\ * (-1.02/c +numpy.log(c) + 1.02/(1+d1**1.02) \ - numpy.log(1.0+d1**1.02)) return 2*(pot_bulge+pot_disk+ pot_halo) # multiply by 2 for # a rigid potential def get_gravity_at_point(self, eps, x,y,z): r = (x**2+y**2+z**2)**0.5 R = (x**2+y**2)**0.5 #bulge b1 = 0.3873 |units.kpc force_bulge = -constants.G*self.Mb/(r**2+b1**2)**1.5 #disk a2 = 5.31 |units.kpc b2 = 0.25 |units.kpc d = a2+ (z**2+ b2**2)**0.5 force_disk =-constants.G*self.Md/(R**2+ d**2 )**1.5 #halo a3 = 12.0 |units.kpc d1 = r/a3 force_halo = -constants.G*self.Mh*d1**0.02/(a3**2*(1+d1**1.02)) ax = force_bulge*x + force_disk*x + force_halo*x/r ay = force_bulge*y + force_disk*y + force_halo*y/r az = force_bulge*z + force_disk*d*z/(z**2 + b2**2)**0.5 \ + force_halo*z/r return ax,ay,az def circular_velocity(self,r): z = 0 | units.kpc b1 = 0.3873 |units.kpc a2 = 5.31 |units.kpc b2 = 0.25 |units.kpc a3 = 12.0 |units.kpc rdphi_b = constants.G*self.Mb*r**2/(r**2+b1**2)**1.5 rdphi_d = constants.G*self.Md*r**2/(r**2+(a2+(z**2+b2**2)**0.5)**2)**1.5 rdphi_h = constants.G*self.Mh*(r/a3)**0.02*r/(a3**2*(1+(r/a3)**1.02)) vel_circb = rdphi_b vel_circd = rdphi_d vel_circh = rdphi_h return (vel_circb + vel_circd + vel_circh)**0.5 def make_king_model_cluster(nbodycode, N, W0, Mcluster, Rcluster, parameters = []): converter = nbody_system.nbody_to_si(Mcluster,Rcluster) bodies = new_king_model(N,W0,convert_nbody=converter) code = nbodycode(converter) for name,value in parameters: setattr(code.parameters, name, value) code.particles.add_particles(bodies) return code def plot_cluster(x, y): from prepare_figure import single_frame, get_distinct colors = get_distinct(1) f = single_frame('X [kpc]', 'Y [kpc]') pyplot.xlim(-10, 10) pyplot.ylim(-10, 10) pyplot.scatter(x,y, c=colors[0], s=50, lw=0) pyplot.show() def evolve_cluster_in_galaxy(N, W0, Rinit, tend, timestep, M, R): galaxy_code = MilkyWay_galaxy() converter = nbody_system.nbody_to_si(M, R) cluster_code = drift_without_gravity(convert_nbody=converter) bodies = new_king_model(N, W0, convert_nbody=converter) cluster_code.particles.add_particles(bodies) stars = cluster_code.particles.copy() stars.x += Rinit stars.vy = 0.8*galaxy_code.circular_velocity(Rinit) channel = stars.new_channel_to(cluster_code.particles) channel.copy_attributes(["x","y","z","vx","vy","vz"]) system = bridge(verbose=False) system.add_system(cluster_code, (galaxy_code,)) times = quantities.arange(0|units.Myr, tend, 100*timestep) for i,t in enumerate(times): print("Time=", t.in_(units.Myr)) system.evolve_model(t, timestep=timestep) x = system.particles.x.value_in(units.kpc) y = system.particles.y.value_in(units.kpc) cluster_code.stop() return x, y if __name__ == "__main__": N = 1024 W0 = 3 Rinit = 8.5 | units.kpc timestep = 0.1 | units.Myr endtime = 4.6 | units.Gyr Mcluster = 5.e4 | units.MSun Rcluster = 1.0 | units.parsec x, y = evolve_cluster_in_galaxy(N, W0, Rinit, endtime, timestep, Mcluster, Rcluster) plot_cluster(x, y)
5,664
32.323529
80
py
amuse
amuse-main/examples/textbook/kira.py
#!/usr/bin/env python3 from amuse.lab import SmallN, Kepler, Hermite, SeBa from amuse.datamodel import Particles from amuse.units.quantities import as_vector_quantity from amuse.couple import encounters from amuse.units import constants, units, quantities, nbody_system from amuse.ic.salpeter import new_salpeter_mass_distribution from amuse.ic.plummer import new_plummer_model from amuse.support.console import set_printing_strategy import numpy import logging def new_smalln(converter): result = SmallN(converter) result.parameters.timestep_parameter = 0.1 result.parameters.cm_index = 2001 return result def new_kepler(converter): kepler = Kepler(converter) kepler.initialize_code() kepler.set_longitudinal_unit_vector(1.0, 0.0, 0.0) kepler.set_transverse_unit_vector(0.0, 1.0, 0) return kepler def new_binary_orbit(mass1, mass2, semi_major_axis, eccentricity=0, keyoffset=1): total_mass = mass1 + mass2 mass_fraction_particle_1 = mass1 / (total_mass) binary = Particles(2) binary[0].mass = mass1 binary[1].mass = mass2 mu = constants.G * total_mass velocity_perihelion \ = numpy.sqrt( mu / semi_major_axis * ((1.0 + eccentricity) / (1.0 - eccentricity))) radius_perihelion = semi_major_axis * (1.0 - eccentricity) print(velocity_perihelion) binary[0].position = ((1.0 - mass_fraction_particle_1) * radius_perihelion * [1.0, 0.0, 0.0]) binary[1].position = -(mass_fraction_particle_1 * radius_perihelion * [1.0, 0.0, 0.0]) binary[0].velocity = ((1.0 - mass_fraction_particle_1) * velocity_perihelion * [0.0, 1.0, 0.0]) binary[1].velocity = -(mass_fraction_particle_1 * velocity_perihelion * [0.0, 1.0, 0.0]) return binary # see Eggleton 2006 Equation 1.6.3 (2006epbm.book.....E) def random_semimajor_axis_PPE(Mprim, Msec, P_min=10. | units.day, P_max=100. | units.yr): Pmax = P_max.value_in(units.day) Pmin = P_min.value_in(units.day) mpf = (Mprim.value_in(units.MSun)**2.5)/5.e+4 rnd_max = (Pmax * mpf)**(1./3.3) / (1 + (Pmin * mpf)**(1./3.3)) rnd_min = (Pmin * mpf)**(1./3.3) / (1 + (Pmax * mpf)**(1./3.3)) rnd_max = min(rnd_max, 1) rnd = numpy.random.uniform(rnd_min, rnd_max, 1) Porb = ((rnd/(1.-rnd))**3.3)/mpf | units.day Mtot = Mprim + Msec a = ((constants.G*Mtot) * (Porb/(2*numpy.pi))**2)**(1./3.) return a def make_secondaries(center_of_masses, Nbin): resulting_binaries = Particles() singles_in_binaries = Particles() binaries = center_of_masses.random_sample(Nbin) mmin = center_of_masses.mass.min() for bi in binaries: mp = bi.mass ms = numpy.random.uniform(mmin.value_in(units.MSun), mp.value_in(units.MSun)) | units.MSun a = random_semimajor_axis_PPE(mp, ms) e = numpy.sqrt(numpy.random.random()) nb = new_binary_orbit(mp, ms, a, e) nb.position += bi.position nb.velocity += bi.velocity nb = singles_in_binaries.add_particles(nb) nb.radius = 0.01 * a bi.radius = 3*a binary_particle = bi.copy() binary_particle.child1 = nb[0] binary_particle.child2 = nb[1] binary_particle.semi_major_axis = a binary_particle.eccentricity = e resulting_binaries.add_particle(binary_particle) single_stars = center_of_masses-binaries return single_stars, resulting_binaries, singles_in_binaries def calculate_orbital_elementss(bi, converter): kep = new_kepler(converter) comp1 = bi.child1 comp2 = bi.child2 mass = (comp1.mass + comp2.mass) pos = (comp2.position - comp1.position) vel = (comp2.velocity - comp1.velocity) kep.initialize_from_dyn(mass, pos[0], pos[1], pos[2], vel[0], vel[1], vel[2]) a, e = kep.get_elements() kep.stop() return a, e ###BOOKLISTSTART### def resolve_changed_binaries(stopping_condition, stellar, converter): new_binaries = stopping_condition.particles(0) for bi in new_binaries: print(("add new binary:", bi)) a, e = calculate_orbital_elementss(bi, converter) bi.semi_major_axis = a bi.eccentricity = e stellar.binaries.add_particle(bi) print(("new binary parameters", a, e)) print(bi) lost_binaries = stopping_condition.particles(1) for bi in lost_binaries: print(("remove old binary:", bi.key)) stellar.binaries.remove_particle(bi) changed_binaries = stopping_condition.particles(2) for bi in changed_binaries: bs = bi.as_particle_in_set(stellar.binaries) a, e = calculate_orbital_elementss(bi, converter) bs.semi_major_axis = a bs.eccentricity = e print(("Modified binary parameters", a, e)) print(bs) ###BOOKLISTSTOP### def update_dynamical_binaries_from_stellar(stellar, multiples_code, converter): kep = new_kepler(converter) # THIS NEEDS TO BE CHECKED! print("++++++++++++ THIS NEEDS TO BE CHECKED ++++++++++++++++++++") print(("Number of binaries=", len(stellar.binaries))) for bi in stellar.binaries: bs = bi.as_particle_in_set(multiples_code.binaries) total_mass = bi.child1.mass+bi.child2.mass kep.initialize_from_elements(total_mass, bi.semi_major_axis, bi.eccentricity) rel_position = as_vector_quantity(kep.get_separation_vector()) rel_velocity = as_vector_quantity(kep.get_velocity_vector()) mu = bi.child1.mass / total_mass bs.child1.position = mu * rel_position bs.child2.position = -(1-mu) * rel_position bs.child1.velocity = mu * rel_velocity bs.child2.velocity = -(1-mu) * rel_velocity print(("semi_major_axis=", bi.semi_major_axis, total_mass, bi.child1.mass, bi.child2.mass, bi.eccentricity)) kep.stop() def kira(tend, N, R, Nbin): logging.basicConfig(level=logging.ERROR) mass = new_salpeter_mass_distribution(N, mass_min=10 | units.MSun) converter = nbody_system.nbody_to_si(mass.sum(), R) code = Hermite(converter) stars = new_plummer_model(N, convert_nbody=converter) stars.mass = mass stars.radius = 0.01/len(stars) | R.unit single_stars, binary_stars, singles_in_binaries \ = make_secondaries(stars, Nbin) print(binary_stars) stellar = SeBa() stellar.particles.add_particles(single_stars) stellar.particles.add_particles(singles_in_binaries) stellar.binaries.add_particles(binary_stars) channel_to_stars = stellar.particles.new_channel_to(stars) encounter_code = encounters.HandleEncounter( kepler_code=new_kepler(converter), resolve_collision_code=new_smalln(converter), interaction_over_code=None, G=constants.G ) multiples_code = encounters.Multiples( gravity_code=code, handle_encounter_code=encounter_code, G=constants.G ) multiples_code.particles.add_particles((stars-binary_stars).copy()) multiples_code.singles_in_binaries.add_particles(singles_in_binaries) multiples_code.binaries.add_particles(binary_stars) multiples_code.commit_particles() channel_from_stars_to_particles \ = stellar.particles.new_channel_to(multiples_code.particles) stopping_condition \ = multiples_code.stopping_conditions.binaries_change_detection stopping_condition.enable() from matplotlib import pyplot from distinct_colours import get_distinct pyplot.rcParams.update({'font.size': 30}) figure = pyplot.figure(figsize=(12, 9)) ax = pyplot.gca() ax.get_yaxis().get_major_formatter().set_useOffset(False) ax.xaxis._autolabelpos = True ax.yaxis._autolabelpos = True color = get_distinct(2) pyplot.scatter(numpy.log10(stellar.binaries.semi_major_axis. value_in(units.AU)), stellar.binaries.eccentricity, c=color[0], s=200, lw=0) t = quantities.linspace(0*tend, tend, 11) for ti in t: print(("t, Energy=", ti, multiples_code.particles.mass.sum(), multiples_code.get_total_energy())) multiples_code.evolve_model(ti) print(("at t=", multiples_code.model_time, "Nmultiples:", len(multiples_code.multiples))) if stopping_condition.is_set(): resolve_changed_binaries(stopping_condition, stellar, converter) stellar.evolve_model(ti) channel_from_stars_to_particles.copy_attributes(["mass", "radius"]) update_dynamical_binaries_from_stellar(stellar, multiples_code, converter) print(("Lagrangian radii:", multiples_code.all_singles.LagrangianRadii(converter))) print(("MC.particles", multiples_code.particles)) print(("Lagrangian radii:", multiples_code.particles.LagrangianRadii(converter))) print(("t, Energy=", ti, multiples_code.get_total_energy())) pyplot.scatter(numpy.log10(stellar.binaries.semi_major_axis .value_in(units.AU)), stellar.binaries.eccentricity, c=color[1], lw=0, s=50) pyplot.xlabel("$\log_{10}(a/R_\odot)$") pyplot.ylabel("eccentricity") save_file = 'kira_a_vs_e.pdf' pyplot.savefig(save_file) print('\nSaved figure in file', save_file, '\n') pyplot.show() stellar.stop() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-t", unit=units.Myr, dest="tend", type="float", default=10. | units.Myr) result.add_option("-R", unit=units.parsec, dest="R", type="float", default=1 | units.parsec) result.add_option("-N", dest="N", type="float", default=100) result.add_option("--Nbin", dest="Nbin", type="int", default=50) result.add_option("--seed", dest="seed", type="int", default=2) return result if __name__ == "__main__": set_printing_strategy( "custom", preferred_units=[units.MSun, units.parsec, units.Myr], precision=4, prefix="", separator=" [", suffix="]") options, arguments = new_option_parser().parse_args() if options.seed >= 0: numpy.random.seed(options.seed) # This is only for random.sample, which apparently does not use numpy import random random.seed(options.seed) kira(options.tend, options.N, options.R, options.Nbin)
10,802
35.251678
79
py
amuse
amuse-main/examples/textbook/plot_sun_and_M67.py
import sys import numpy from numpy import random from amuse.lab import * from amuse.units.optparse import OptionParser from amuse.units.quantities import as_vector_quantity from matplotlib import pyplot from prepare_figure import * from distinct_colours import get_distinct def movie_all(time, sun_and_planets): colors = ['r', 'b', 'g'] print(time.in_(units.Gyr)) R = [] | units.kpc for sp in sun_and_planets: R.append(sp.position.length()) pyplot.subplot(2,2,1) pyplot.scatter(sun_and_planets.x.value_in(units.kpc), sun_and_planets.y.value_in(units.kpc), c=['k', 'r'], s=10, lw=0) pyplot.subplot(2,2,2) pyplot.scatter(R.value_in(units.kpc), sun_and_planets.z.value_in(units.kpc), c=['k', 'r'], s=10, lw=0) pyplot.xlabel("R [kpc]") pyplot.ylabel("Z [kpc]") R = [] | units.kpc R.append((sun_and_planets[1].position-sun_and_planets[0].position).length()) pyplot.subplot(2,2,3) pyplot.scatter(-time.value_in(units.Gyr), R.value_in(units.kpc), c=['k', 'r'], s=10, lw=0) pyplot.xlabel("t [Gyr]") pyplot.ylabel("r [kpc]") def new_option_parser(): result = OptionParser() result.add_option("--seed", dest="seed", type="int", default = 666, help="random number seed [%default]") result.add_option("-N", dest="Nstars", type="int", default = 3, help="Number of stars [%default]") result.add_option("-f", dest="filename", default = "initial_cluster.amuse", help="input filename") result.add_option("-R", unit=units.parsec, dest="Rcluster", type="int", default = 1000|units.AU, help="Cluster size [%default]") result.add_option("-n", dest="n", type="int", default = 100, help="Number of pebbels per star [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() filename = "sunandM67.hdf5" sun_and_planets = read_set_from_file(filename, "amuse") colors = get_distinct(4) figure = pyplot.figure(figsize=(16, 12)) ax = pyplot.gca() ax.minorticks_on() # switch on the minor ticks ax.locator_params(nbins=3) x_label = "t [Gyr]" y_label = "$Z [kpc]$" pyplot.xlabel(x_label) pyplot.ylabel(y_label) # pyplot.ylim(0, 1) R = [] Z = [] | units.kpc d = [] | units.kpc t = [] | units.Gyr dmin = 100| units.kpc tmin = 0| units.Gyr zEmin = 0| units.kpc zMmin = 0| units.kpc rEmin = 0| units.kpc rMmin = 0| units.kpc for saps in sun_and_planets.history: R.append([saps[0].position.length().value_in(units.kpc), saps[1].position.length().value_in(units.kpc)]) Z.append(saps.z) t.append(saps.get_timestamp()) d.append((saps[1].position-saps[0].position).length()) if d[-1]<dmin: dmin = d[-1] tmin = t[-1] zEmin = Z[-1][0] zMmin = Z[-1][0] rEmin = saps[0].position.length() rMmin = saps[1].position.length() print("minimal distance:", tmin.value_in(units.Myr), dmin.in_(units.parsec), rEmin.in_(units.parsec), rMmin.in_(units.parsec), zEmin.in_(units.parsec), zMmin.in_(units.parsec)) plot_td = True plot_RZ = False if plot_RZ: pyplot.plot(R, Z.value_in(units.kpc), lw=2) pyplot.xlabel("R [kpc]") pyplot.ylabel("Z [kpc]") pyplot.xlim(8.0, 10.2) pyplot.ylim(-1.0, 1.0) pyplot.scatter(R[0], Z[0].value_in(units.kpc), lw=1, s=100, c=colors[0]) pyplot.scatter(R[-1], Z[-1].value_in(units.kpc), lw=1, s=100, c=colors[1]) pyplot.scatter(rMmin.value_in(units.kpc), zMmin.value_in(units.kpc), lw=1, s=100, c=colors[2]) elif plot_td: pyplot.plot(-t.value_in(units.Gyr), d.value_in(units.kpc), lw=3, c=colors[0]) pyplot.xlabel("t [Gyr]") pyplot.ylabel("d [kpc]") pyplot.ylim(0, 6) pyplot.xlim(-5, 0) pyplot.savefig("sun_and_M67") pyplot.show()
4,270
33.723577
180
py
amuse
amuse-main/examples/textbook/XiTau_RLOF.py
""" example code bridging a gravity solver with a hydrodynamics solver """ import numpy from amuse.lab import * from amuse.couple import bridge def evolve_binary_in_common_envelope(stars, envelope, t_end): R = stars.position.length() converter=nbody_system.nbody_to_si(stars.mass.sum(), R) gravity = ph4(converter) gravity.particles.add_particles(stars) channel_from_gravity = gravity.particles.new_channel_to(stars) channel_from_to_gravity = stars.new_channel_to(gravity.particles) n_steps = 10 dt = t_end/float(n_steps) hydro = Fi(converter, redirection="none") tdyn = numpy.sqrt((0.05*R)**3/(constants.G*stars.mass.sum())) print("tdyn=", tdyn) hydro.parameters.timestep = tdyn hydro.parameters.epsilon_squared = (1|units.RSun)**2 hydro.gas_particles.add_particles(envelope) hydro.parameters.periodic_box_size = 100*R channel_from_hydro = hydro.gas_particles.new_channel_to(envelope) channel_from_to_hydro = envelope.new_channel_to(hydro.gas_particles) model_time = 0 | units.Myr filename = "XiTau_Hydro.amuse" write_set_to_file(stars.savepoint(model_time), filename, 'amuse', append_to_file=False) write_set_to_file(envelope, filename, 'amuse') gravhydro = bridge.Bridge(use_threading=False) gravhydro.add_system(gravity, (hydro,) ) gravhydro.add_system(hydro, (gravity,) ) gravhydro.timestep = min(dt, 10*hydro.parameters.timestep) while model_time < t_end: model_time += dt print("Time=", model_time.in_(units.day)) gravhydro.evolve_model(model_time) channel_from_gravity.copy() channel_from_hydro.copy() write_set_to_file(stars.savepoint(model_time), filename, 'amuse') write_set_to_file(envelope, filename, 'amuse') gravity.stop() hydro.stop() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-t", unit=units.Myr, dest="t_end", type="float", default = 20|units.day, help="end time of the simulation [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() a = 0.133 | units.AU e = 0.0 m1 = 3.2|units.MSun m2 = 3.1|units.MSun from amuse.ext.orbital_elements import new_binary_from_orbital_elements inner_binary = new_binary_from_orbital_elements(m1, m2, a, e, G=constants.G) XiTau = read_set_from_file("Hydro_PrimaryStar_XiTau.amuse", "amuse") for ci in XiTau.history: if len(ci) == 1: XiTau_core = ci.copy() else: XiTau_envelope = ci.copy() ao = 1.23 | units.AU eo = 0.15 m12 = inner_binary.mass.sum() m3 = XiTau_core.mass + XiTau_envelope.mass.sum() print("M3=", m3.in_(units.MSun)) outer_binary = new_binary_from_orbital_elements(m12, m3, ao, eo, G=constants.G) inner_binary.position += outer_binary[0].position inner_binary.velocity += outer_binary[0].velocity XiTau_envelope.position += outer_binary[1].position XiTau_envelope.velocity += outer_binary[1].velocity outer_binary[1].mass = XiTau_core.mass triple = Particles() triple.add_particles(inner_binary) triple.add_particle(outer_binary[1]) print(triple) evolve_binary_in_common_envelope(triple, XiTau_envelope, o.t_end)
3,535
33
75
py
amuse
amuse-main/examples/textbook/distinct_colours.py
# -*- coding: iso-8859-1 -*- """ Colour-blind proof distinct colours module, based on work by Paul Tol Pieter van der Meer, 2011 SRON - Netherlands Institute for Space Research """ # colour table in HTML hex format hexcols = ['#332288', '#88CCEE', '#44AA99', '#117733', '#999933', '#DDCC77', '#CC6677', '#882255', '#AA4499', '#661100', '#6699CC', '#AA4466', '#4477AA'] greysafecols = ['#809BC8', '#FF6666', '#FFCC66', '#64C204'] xarr = [[12], [12, 6], [12, 6, 5], [12, 6, 5, 3], [0, 1, 3, 5, 6], [0, 1, 3, 5, 6, 8], [0, 1, 2, 3, 5, 6, 8], [0, 1, 2, 3, 4, 5, 6, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 9, 6, 7, 8], [0, 10, 1, 2, 3, 4, 5, 9, 6, 7, 8], [0, 10, 1, 2, 3, 4, 5, 9, 6, 11, 7, 8]] # get specified nr of distinct colours in HTML hex format. # in: nr - number of colours [1..12] # returns: list of distinct colours in HTML hex def get_distinct(nr): # check if nr is in correct range if nr < 1 or nr > 12: print("wrong nr of distinct colours!") return # get list of indices lst = xarr[nr-1] # generate colour list by stepping through indices and looking them up # in the colour table i_col = 0 col = [0] * nr for idx in lst: col[i_col] = hexcols[idx] i_col+=1 return col # gets 4 colours, which also look distinct in black&white # returns: list of 4 colours in #def get_distinct_grey(): import sys # display usage information and produce example plot. if __name__ == '__main__': import numpy as np import matplotlib.mlab as mlab import matplotlib.pyplot as plt print(__doc__) print("usage examples: ") print("print distinct_colours.get_distinct(2)") print(get_distinct(2)) print("print distinct_colours.greysafecols") print(greysafecols) print("generating example plot: distinct_colours_example.png") plt.close() t = np.arange(0.0, 2.0, 0.01) n = 12 if len(sys.argv) > 1: n = int(sys.argv[1]) cols = get_distinct(n) d = 2./n for i in range(n): s = np.sin(i*d*np.pi*t) plt.plot(t, s, linewidth=2.0, c=cols[i], label=str(i)) plt.xlabel('time (s)') plt.ylabel('voltage (mV)') plt.title('Distinct colours example (n = '+str(n)+')') plt.grid(True) plt.legend(loc=3, ncol=2) plt.savefig("distinct_colours_example.png") plt.show()
2,484
25.72043
77
py
amuse
amuse-main/examples/textbook/explode_evolved_star.py
import numpy import os.path from amuse.test.amusetest import get_path_to_results try: from matplotlib import pyplot HAS_MATPLOTLIB = True from amuse.plot import plot, semilogy, xlabel, ylabel, loglog except ImportError: HAS_MATPLOTLIB = False from amuse.units import units from amuse.units import generic_unit_system from amuse.units import nbody_system from amuse.units import constants from amuse.units.generic_unit_converter import ConvertBetweenGenericAndSiUnits from amuse.support.exceptions import AmuseException from amuse.community.mesa.interface import MESA from amuse.community.gadget2.interface import Gadget2 from amuse.community.fi.interface import Fi from amuse.ext.star_to_sph import * from amuse.datamodel import Particles from amuse.datamodel import Grid def setup_stellar_evolution_model(): out_pickle_file = os.path.join(get_path_to_results(), "super_giant_stellar_structure.pkl") if os.path.exists(out_pickle_file): return out_pickle_file print("Creating initial conditions from a MESA stellar evolution model...") stellar_evolution = MESA(redirection = "none") stars = Particles(1) stars.mass = 10.0 | units.MSun stellar_evolution.particles.add_particles(stars) while stellar_evolution.particles[0].stellar_type <= 12|units.stellar_type: stellar_evolution.evolve_model() pickle_stellar_model(stellar_evolution.particles[0], out_pickle_file) stellar_evolution.stop() return out_pickle_file def inject_supernova_energy(gas_particles): Rinner = 10|units.RSun inner = gas_particles.select( lambda pos : pos.length_squared() < Rinner**2, ["position"]) print("Adding", (1.0e51 | units.erg) / inner.total_mass(), end=' ') print("to each of", len(inner), "innermost particles") print(" of the exploding star") inner.u += (1.0e51 | units.erg) / inner.total_mass() from prepare_figure import single_frame, figure_frame, set_tickmarks from distinct_colours import get_distinct def hydro_plot(view, hydro_code, image_size, time, figname): """ Produce a series of images suitable for conversion into a movie. view: the (physical) region to plot [xmin, xmax, ymin, ymax] hydro_code: hydrodynamics code in which the gas to be plotted is defined image_size: size of the output image in pixels (x, y) time: current hydro code time """ if not HAS_MATPLOTLIB: return shape = (image_size[0], image_size[1], 1) size = image_size[0] * image_size[1] axis_lengths = [0.0, 0.0, 0.0] | units.m axis_lengths[0] = view[1] - view[0] axis_lengths[1] = view[3] - view[2] grid = Grid.create(shape, axis_lengths) grid.x += view[0] grid.y += view[2] speed = grid.z.reshape(size) * (0 | 1/units.s) rho, rhovx, rhovy, rhovz, rhoe \ = hydro_code.get_hydro_state_at_point( grid.x.reshape(size), grid.y.reshape(size), grid.z.reshape(size), speed, speed, speed) min_v = 800.0 | units.km / units.s max_v = 3000.0 | units.km / units.s min_rho = 3.0e-9 | units.g / units.cm**3 max_rho = 1.0e-5 | units.g / units.cm**3 min_E = 1.0e11 | units.J / units.kg max_E = 1.0e13 | units.J / units.kg v_sqr = (rhovx**2 + rhovy**2 + rhovz**2) / rho**2 E = rhoe / rho log_v = numpy.log((v_sqr/min_v**2)) / numpy.log((max_v**2/min_v**2)) log_rho = numpy.log((rho/min_rho)) / numpy.log((max_rho/min_rho)) log_E = numpy.log((E/min_E)) / numpy.log((max_E/min_E)) red = numpy.minimum(numpy.ones_like(rho.number), numpy.maximum(numpy.zeros_like(rho.number), log_rho)).reshape(shape) green = numpy.minimum(numpy.ones_like(rho.number), numpy.maximum(numpy.zeros_like(rho.number), log_v)).reshape(shape) blue = numpy.minimum(numpy.ones_like(rho.number), numpy.maximum(numpy.zeros_like(rho.number), log_E)).reshape(shape) alpha = numpy.minimum(numpy.ones_like(log_v), numpy.maximum(numpy.zeros_like(log_v), numpy.log((rho / (10*min_rho))))).reshape(shape) rgba = numpy.concatenate((red, green, blue, alpha), axis = 2) pyplot.figure(figsize = (image_size[0]/100.0, image_size[1]/100.0), dpi = 100) im = pyplot.figimage(rgba, origin='lower') pyplot.savefig(figname, transparent=True, dpi = 100, facecolor='k', edgecolor='k') print("Saved hydroplot at time", time, "in file") print(' ', figname) pyplot.close() def energy_plot(time, E_kin, E_pot, E_therm, figname): if not HAS_MATPLOTLIB: return x_label = 'Time [hour]' y_label = 'Energy [foe]' single_frame(x_label, y_label, logx=False, logy=False, xsize=14, ysize=10, ymin=-1, ymax=-1) cols = get_distinct(4) FOE = 1.e+51 | units.erg hour = 1|units.hour pyplot.plot(time/hour, E_kin/FOE, label='E_kin', c=cols[0]) pyplot.plot(time/hour, E_pot/FOE, label='E_pot', c=cols[1]) pyplot.plot(time/hour, E_therm/FOE, label='E_therm', c=cols[2]) pyplot.plot(time/hour, (E_kin+E_pot+E_therm)/FOE, label='E_total', c=cols[3]) pyplot.legend(loc='best') pyplot.savefig(figname) print('\nSaved energy evolution figure in file', figname, '\n') pyplot.show() pyplot.close() def run_supernova(): use_hydro_code = Gadget2 hydro_code_options = dict(number_of_workers=3) number_of_sph_particles = 3000 t_end = 1.0e4 | units.s pickle_file = setup_stellar_evolution_model() model = convert_stellar_model_to_SPH(None, number_of_sph_particles, seed = 12345, pickle_file = pickle_file, with_core_particle = True, target_core_mass = 1.4|units.MSun) print("model=", model.core_particle) core, gas_without_core, core_radius \ = model.core_particle, model.gas_particles, model.core_radius inject_supernova_energy(gas_without_core) print("\nEvolving (SPH) to:", t_end) n_steps = 100 unit_converter = ConvertBetweenGenericAndSiUnits(1.0 | units.RSun, constants.G, t_end) hydro_code = use_hydro_code(unit_converter, **hydro_code_options) try: hydro_code.parameters.timestep = t_end / n_steps except Exception as exc: if not "parameter is read-only" in str(exc): raise hydro_code.parameters.epsilon_squared = core_radius**2 hydro_code.parameters.n_smooth_tol = 0.01 hydro_code.gas_particles.add_particles(gas_without_core) hydro_code.dm_particles.add_particle(core) times = [] | units.s potential_energies = [] | units.J kinetic_energies = [] | units.J thermal_energies = [] | units.J for time, i_step in [(i*t_end/n_steps, i) for i in range(0, n_steps+1)]: hydro_code.evolve_model(time) times.append(time) potential_energies.append(hydro_code.potential_energy) kinetic_energies.append( hydro_code.kinetic_energy) thermal_energies.append( hydro_code.thermal_energy) hydro_plot([-1.0, 1.0, -1.0, 1.0] * (350 | units.RSun), hydro_code, (100, 100), time, os.path.join(get_path_to_results(), "supernova_hydro_image{0:=03}.png".format(i_step)) ) energy_plot(times, kinetic_energies, potential_energies, thermal_energies, "supernova_energy_evolution.pdf") hydro_code.stop() if __name__ == "__main__": print("Test run to mimic a supernova in SPH") print("Details:") print(" A high-mass star is evolved to the supergiant phase using MESA.") print(" Then it is converted to SPH particles using", \ "convert_stellar_model_to_SPH") print(" (with a non-SPH 'core' particle).", \ "Finally the internal energies of") print(" the innermost particles are increased so that the star gains the") print(" 10^51 erg released in a typical supernova explosion.") run_supernova()
8,582
39.295775
81
py
amuse
amuse-main/examples/textbook/solar_cluster_in_semilive_galaxy.py
import math import numpy from amuse.lab import * from amuse.couple import bridge from amuse.units.optparse import OptionParser from amuse.units import quantities from amuse.community.galaxia.interface import BarAndSpirals3D from amuse.ext.composition_methods import * from matplotlib import pyplot from prepare_figure import figure_frame, get_distinct class drift_without_gravity(object): def __init__(self, particles, time= 0 |units.Myr): self.particles=particles self.model_time= time self.softening_lengths_squared = (100|units.parsec)**2 self.gravity_constant = constants.G def evolve_model(self, t_end): dt= t_end- self.model_time self.particles.position += self.particles.velocity*dt self.model_time= t_end def add_particles(self, p): self.particles.add_particles(p) @property def potential_energy(self): return quantities.zero def get_potential_at_point(self,radius,x,y,z): positions = self.particles.position result = quantities.AdaptingVectorQuantity() for i in range(len(x)): dx = x[i] - positions.x dy = y[i] - positions.y dz = z[i] - positions.z dr_squared = (dx * dx) + (dy * dy) + (dz * dz) dr = (dr_squared + self.softening_lengths_squared).sqrt() energy_of_this_particle = (self.particles.mass / dr).sum() result.append(-self.gravity_constant * energy_of_this_particle) return result def get_gravity_at_point(self,radius,x,y,z): positions = self.particles.position m1 = self.particles.mass result_ax = quantities.AdaptingVectorQuantity() result_ay = quantities.AdaptingVectorQuantity() result_az = quantities.AdaptingVectorQuantity() for i in range(len(x)): dx = x[i] - positions.x dy = y[i] - positions.y dz = z[i] - positions.z dr_squared = ((dx * dx) + (dy * dy) + (dz * dz) + self.softening_lengths_squared + radius[i]**2) ax = -self.gravity_constant * (m1*dx/dr_squared**1.5).sum() ay = -self.gravity_constant * (m1*dy/dr_squared**1.5).sum() az = -self.gravity_constant * (m1*dz/dr_squared**1.5).sum() result_ax.append(ax) result_ay.append(ay) result_az.append(az) return result_ax, result_ay, result_az @property def kinetic_energy(self): return (0.5*self.particles.mass \ * self.particles.velocity.lengths()**2).sum() def stop(self): return class MilkyWay_galaxy(object): def __init__(self, Mb=1.40592e10| units.MSun, Md=8.5608e10| units.MSun, Mh=1.07068e11 | units.MSun ): self.Mb = Mb self.Md = Md self.Mh = Mh def get_potential_at_point(self,eps,x,y,z): r = (x**2+y**2+z**2)**0.5 R = (x**2+y**2)**0.5 # bulge b1 = 0.3873 |units.kpc pot_bulge = -constants.G*self.Mb/(r**2+b1**2)**0.5 # disk a2 = 5.31 |units.kpc b2 = 0.25 |units.kpc pot_disk = -constants.G*self.Md/(R**2+(a2+(z**2+b2**2)**0.5)**2)**0.5 #halo a3 = 12.0 |units.kpc cut_off = 100 |units.kpc d1 = r/a3 c = 1+ (cut_off/a3)**1.02 pot_halo = -constants.G*(self.Mh/a3)*d1**1.02/(1 + d1**1.02) \ - (constants.G*self.Mh/(1.02*a3))\ *(-1.02/c + numpy.log(c) \ + 1.02/(1+d1**1.02) \ - numpy.log(1.0 +d1**1.02)) return 2*(pot_bulge + pot_disk + pot_halo) # multiply by 2 for # rigid potential def get_gravity_at_point(self, eps, x,y,z): r = (x**2+y**2+z**2)**0.5 R = (x**2+y**2)**0.5 #bulge b1 = 0.3873 |units.kpc force_bulge = -constants.G*self.Mb/(r**2+b1**2)**1.5 #disk a2 = 5.31 |units.kpc b2 = 0.25 |units.kpc d = a2+ (z**2+ b2**2)**0.5 force_disk = -constants.G*self.Md/(R**2+ d**2 )**1.5 #halo a3 = 12.0 |units.kpc d1 = r/a3 force_halo = -constants.G*self.Mh*d1**0.02/(a3**2*(1+d1**1.02)) ax = force_bulge*x + force_disk*x + force_halo*x/r ay = force_bulge*y + force_disk*y + force_halo*y/r az = force_bulge*z + force_disk*d*z/(z**2 + b2**2)**0.5 \ + force_halo*z/r return ax,ay,az def vel_circ(self, r ): z = 0 | units.kpc b1 = 0.3873 |units.kpc a2 = 5.31 |units.kpc b2 = 0.25 |units.kpc a3 = 12.0 |units.kpc rdphi_b = constants.G*self.Mb*r**2 \ / (r**2+b1**2)**1.5 rdphi_d = constants.G*self.Md*r**2 \ / (r**2+ (a2+(z**2+b2**2)**0.5)**2 )**1.5 rdphi_h = constants.G*self.Mh*(r/a3)**0.02*r \ / (a3**2*(1+(r/a3)**1.02)) vel_circb = rdphi_b vel_circd = rdphi_d vel_circh = rdphi_h return (vel_circb+ vel_circd+ vel_circh)**0.5 def stop(self): return def plot(stars, GMCs): figure = figure_frame("X [kpc]", "Y [kpc]", xsize=8, ysize=8) colors = get_distinct(2) print(numpy.mean(stars.mass.value_in(units.MSun))) print(numpy.mean(GMCs.mass.value_in(units.MSun))) size = stars.mass/(0.1 |units.MSun) pyplot.scatter(stars.x.value_in(units.kpc), stars.y.value_in(units.kpc), s=size, c=colors[0]) size = numpy.sqrt(GMCs.mass/(100 |units.MSun)) pyplot.scatter(GMCs.x.value_in(units.kpc), GMCs.y.value_in(units.kpc), s=size, alpha = 0.5, lw=0, c=colors[1]) pyplot.scatter([0], [0], marker="+", s=300, c='r') pyplot.scatter([-8.4], [0], marker="o", s=100, c='g') pyplot.axis("equal") pyplot.xlim(-10, 10) pyplot.ylim(-10, 10) pyplot.show() def evolve_cluster_in_potential(gravity, t_end, dt, channels_to_framework, sun=None, GMCs=None, filename=False): Etot_init = gravity.kinetic_energy + gravity.potential_energy Etot_prev = Etot_init time = 0.0 | t_end.unit if filename: write_set_to_file(sun, filename, "hdf5", timestamp = time, append_to_file=False) write_set_to_file(GMCs, filename, "hdf5", timestamp = time) x = [] y = [] while time < t_end: time += dt gravity.evolve_model(time) for ch in channels_to_framework: ch.copy() if filename: write_set_to_file(sun, filename, "hdf5", timestamp = time) write_set_to_file(GMCs, filename, "hdf5", timestamp = time) x.append(gravity.particles[0].x.value_in(units.kpc)) y.append(gravity.particles[0].y.value_in(units.kpc)) Etot_prev_se = gravity.kinetic_energy + gravity.potential_energy Ekin = gravity.kinetic_energy Epot = gravity.potential_energy Etot = Ekin + Epot print("T=", time, end=' ') print("E= ", Etot, "Q= ", Ekin/Epot, end=' ') print("dE=", (Etot_init-Etot)/Etot, "ddE=", (Etot_prev-Etot)/Etot) Etot_prev = Etot return x, y def integrate_single_particle_in_potential(sun, t_end, dt): MWG = MilkyWay_galaxy() cluster_gravity = drift_without_gravity(sun) channel_from_gravity_to_framework \ = cluster_gravity.particles.new_channel_to(sun) gravity = bridge.Bridge(use_threading=False) gravity.add_system(cluster_gravity, (MWG,) ) t_orb = 2*numpy.pi*sun.position.length()/sun.velocity.length() gravity.timestep = min(dt, 10|units.Myr) x, y = evolve_cluster_in_potential(gravity, t_end, dt, [channel_from_gravity_to_framework]) gravity.stop() return x, y def integrate_cluster_and_GMCs_in_potential(sun, GMCs, t_end, dt, filename): MWG = MilkyWay_galaxy() GMC_gravity = drift_without_gravity(GMCs) channels = [] channels.append(GMC_gravity.particles.new_channel_to(GMCs)) converter = nbody_system.nbody_to_si(sun.mass.sum(), sun[0].position.length()) cluster_gravity = BHTree(converter) cluster_gravity.particles.add_particles(sun) channels.append(cluster_gravity.particles.new_channel_to(sun)) gravity = bridge.Bridge(use_threading=False) gravity.add_system(cluster_gravity, (MWG, GMC_gravity) ) gravity.add_system(GMC_gravity, (MWG,) ) gravity.timestep = min(dt, 10|units.Myr) t_orb = 2*numpy.pi*sun.position.length()/sun.velocity.length() gravity.timestep = min(dt, 10|units.Myr) x, y = evolve_cluster_in_potential(gravity, t_end, dt, channels, sun, GMCs, filename) gravity.stop() return x, y def initialize_sun_in_milky_way(): sun = Particles(1) sun.mass= 1 | units.MSun sun.radius= 1 |units.RSun sun.position= [-8400.0, 0.0, 17.0] | units.parsec MWG = MilkyWay_galaxy() vc = MWG.vel_circ(sun.position.length()) sun.velocity= [11.352, (12.24+vc.value_in(units.kms)), 7.41] | units.kms current_sun = sun.copy() sun.velocity *= -1 print("current:", sun) return sun def make_giant_molecular_clouds(Ngmc): N_thick_disk = int(0.5*Ngmc) N_thin_disk = int(0.5*Ngmc) converter=nbody_system.nbody_to_si(1.e+8|units.MSun, 1.0|units.kpc) from amuse.ext.protodisk import ProtoPlanetaryDisk Rin = 3.5 | units.kpc Rout = 7.5 | units.kpc masses = new_powerlaw_mass_distribution(N_thick_disk, alpha=-1.6, mass_min=1.0e+3|units.MSun, mass_max=1.0e+8|units.MSun) MGMCs = masses.sum() MWG = MilkyWay_galaxy() v_inner = MWG.vel_circ(Rout) MGalaxy = v_inner**2*Rout/constants.G print("Masses:", MGMCs.in_(units.MSun), MGalaxy.in_(units.MSun), \ MGMCs/MGalaxy) GMCs = ProtoPlanetaryDisk(len(masses), convert_nbody=converter, Rmin=Rin.value_in(units.kpc), Rmax=Rout.value_in(units.kpc), q_out=30.0, discfraction=MGMCs/MGalaxy).result #second population of GMCs masses = new_powerlaw_mass_distribution(len(GMCs), alpha=-1.6, mass_min=1.e+3|units.MSun, mass_max=1.0e+8|units.MSun) GMCs.mass = masses MGMCs = masses.sum() thin_disk_GMCs = ProtoPlanetaryDisk(N_thin_disk, convert_nbody=converter, Rmin=Rin.value_in(units.kpc), Rmax=2*Rout.value_in(units.kpc), q_out=10.0, discfraction=MGMCs/MGalaxy).result thin_disk_GMCs.masses = masses GMCs.add_particles(thin_disk_GMCs) GMCs.velocity *= -1 GMCs.mass = new_powerlaw_mass_distribution(len(GMCs), alpha=-1.6, mass_min=1.e+3|units.MSun, mass_max=1.0e+8|units.MSun) print("v=", v_inner.in_(units.kms)) print("GMC mass=", GMCs.mass.sum().in_(units.MSun)) for gi in range(len(GMCs)): r = GMCs[gi].position.length() vc = MWG.vel_circ(r) GMCs[gi].velocity = GMCs[gi].velocity * (vc/GMCs[gi].velocity.length()) return GMCs def make_new_cluster(Ncl, Rvir, W0, sun): masses = new_salpeter_mass_distribution(Ncl, 0.1|units.MSun, 10.0|units.MSun) converter = nbody_system.nbody_to_si(masses.sum(), Rvir) cluster = new_king_model(len(masses), W0=3, convert_nbody=converter) cluster.mass = masses eps2 = 0.25*len(masses)**(-2./3.) * Rvir**2 cluster.scale_to_standard(convert_nbody=converter, smoothing_length_squared = eps2) cluster.position += sun.position cluster.velocity += sun.velocity cluster.radius = 0 | units.AU return cluster def main(Ngmc, Ncl, W0, t_end, n_steps, filename, Rvir): numpy.random.seed(111) dt = t_end/float(n_steps) sun = initialize_sun_in_milky_way() print("Find birth location of the Sun.") x, y = integrate_single_particle_in_potential(sun, t_end, dt) sun.velocity *= -1 print("Birth location of the Sun:", sun) GMCs = make_giant_molecular_clouds(Ngmc) cluster = make_new_cluster(Ncl, Rvir, W0, sun) integrate_cluster_and_GMCs_in_potential(cluster, GMCs, t_end, dt, filename) plot(cluster, GMCs) def new_option_parser(): result = OptionParser() result.add_option("-n", dest="n_steps", type="float", default = 200, help="number of diagnostics time steps [%default]") result.add_option("-f", dest="filename", default = "proto_solar_cluster.hdf5", help="output filename [%default]") result.add_option("--Ncl", dest="Ncl", type="int",default = 1000, help="number of stars [%default]") result.add_option("--Ngmc", dest="Ngmc", type="int",default = 1000, help="number of GMCs [%default]") result.add_option("-R", unit= units.parsec, dest="Rvir", type="float",default = 100 | units.parsec, help="cluser virial radius [%default]") result.add_option("-t", unit= units.Gyr, dest="t_end", type="float", default = 4.6 | units.Gyr, help="end time of the simulation [%default]") result.add_option("-W", dest="W0", type="float", default = 7.0, help="Dimensionless King potential depth (W0) [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
14,033
37.03252
80
py
amuse
amuse-main/examples/textbook/supernova_disk_irradiation.py
import numpy from amuse.lab import * from amuse.ext.protodisk import ProtoPlanetaryDisk from matplotlib import pyplot from supernova_IIp_Lightcurve import Supernova_IIp def mu(X = None, Y = 0.25, Z = 0.02, x_ion = 0.1): """ Compute the mean molecular weight in kg (the average weight of particles in a gas) X, Y, and Z are the mass fractions of Hydrogen, of Helium, and of metals, respectively. x_ion is the ionisation fraction (0 < x_ion < 1), 1 means fully ionised. """ if X is None: X = 1.0 - Y - Z elif abs(X + Y + Z - 1.0) > 1e-6: raise Exception( "Error in calculating mu: mass fractions do not sum to 1.0") return constants.proton_mass / (X*(1.0+x_ion) + Y*(1.0+2.0*x_ion)/4.0 + Z*x_ion/2.0) def update_source_particle(rad, time, old_source, efficiency_factor, supernova_IIp): source=Particle() source.position = old_source.position source.luminosity = efficiency_factor**2 \ * supernova_IIp.luminosity_at_time(time)/(20.|units.eV) source.flux = source.luminosity source.xion = old_source.xion source.u = old_source.u rad.src_particles.remove_particle(old_source) rad.src_particles.add_particle(source) return source def print_diagnostics(time, supernova, disk): umin = disk.u.min() umean = disk.u.mean() umax = disk.u.max() Tmin = mu() / constants.kB * umax Tmean = mu() / constants.kB * umean Tmax = mu() / constants.kB * umin print("Time=", time.in_(units.day)) print("Supernova luminosity:", \ (supernova.luminosity*(20.|units.eV)).in_(units.LSun)) print("Ionization:", disk.xion.min(), disk.xion.mean(), disk.xion.max()) print("Intenal energy:", umin, umean, umax) print("Temperature:", Tmin, Tmean, Tmax) print("Density:", disk.density.min().in_(units.amu/units.cm**3), \ disk.density.mean().in_(units.amu/units.cm**3), \ disk.density.max().in_(units.amu/units.cm**3)) print("scaleheight:", abs(disk.z.value_in(units.AU)).mean()) def main(Ndisk, Mstar, Mdisk, Rin, Rout, t_end, Nray, x, y, z): time = 0 | units.Myr supernova_IIp = Supernova_IIp(10|units.day) efficiency_factor = 0.1 Rsn = efficiency_factor * (x**2 + y**2 + z**2)**0.5 supernova = Particle() supernova.position = (x.value_in(units.parsec), y.value_in(units.parsec), z.value_in(units.parsec)) |units.parsec supernova.position *= efficiency_factor supernova_IIp.particles.add_particle(supernova) supernova_IIp.evolve_model(time) supernova.luminosity = efficiency_factor**2 * supernova.luminosity supernova.xion = 0.0 supernova.u = (10**51 | units.erg)/(10|units.MSun) stellar = SeBa() star = Particle() star.mass = Mstar star.position = (0,0,0) | units.AU star.velocity = (0,0,0) | units.kms stellar.particles.add_particle(star) stellar.evolve_model(1|units.Myr) star.luminosity = stellar.particles[0].luminosity/(20. | units.eV) star.temperature = stellar.particles[0].temperature stellar.stop() star.u = (9. |units.kms)**2 star.xion = 0.0 print(star) print("M=", Mdisk/Mstar) converter=nbody_system.nbody_to_si(Mstar, 1 | units.AU) disk = ProtoPlanetaryDisk(Ndisk, convert_nbody=converter, Rmin=Rin.value_in(units.AU), Rmax=Rout.value_in(units.AU), q_out=25.0, discfraction=Mdisk/Mstar).result #### q_out=2.0, discfraction=Mdisk/Mstar).result print(disk.x.max().in_(units.AU)) print(disk.mass.sum().in_(units.MSun)) print(disk.u.max().in_(units.kms**2)) print(disk.mass.min().in_(units.MSun)) disk.flux = 0. | units.s**-1 disk.xion = 0.0 dt = t_end/1000. hydro = Fi(converter) hydro.parameters.use_hydro_flag=True hydro.parameters.radiation_flag=False hydro.parameters.self_gravity_flag=True hydro.parameters.gamma=1. hydro.parameters.isothermal_flag=True # Non-isothermal: lowest temperature remains constat at 20K # hydro.parameters.gamma=1.66667 # hydro.parameters.isothermal_flag=False hydro.parameters.integrate_entropy_flag=False hydro.parameters.timestep=0.5 | units.hour #0.125 | units.day # hydro.parameters.verbosity=99 hydro.parameters.epsilon_squared=0.1 | units.AU**2 hydro.parameters.courant=0.2 hydro.parameters.artificial_viscosity_alpha = 0.1 hydro.gas_particles.add_particles(disk) hydro.dm_particles.add_particle(star) hydro_to_disk = hydro.gas_particles.new_channel_to(disk) hydro_to_star = hydro.dm_particles.new_channel_to(star.as_set()) disk_to_hydro = disk.new_channel_to(hydro.gas_particles) star_to_hydro = star.as_set().new_channel_to(hydro.dm_particles) hydro.evolve_model(1|units.hour) hydro_to_disk.copy() hydro_to_star.copy() radiative = SPHRay(redirection="file", number_of_workers=4)#, debugger="gdb") radiative.parameters.number_of_rays=Nray/dt print(dt.in_(units.yr)) radiative.parameters.default_spectral_type=-3. radiative.parameters.box_size=10000. | units.AU radiative.parameters.ionization_temperature_solver=2 print(radiative.parameters) # radiative.src_particles.add_particle(star) radiative.src_particles.add_particle(supernova) radiative.gas_particles.add_particles(disk) gas_to_rad = disk.new_channel_to(radiative.gas_particles) rad_to_gas = radiative.gas_particles.new_channel_to(disk) print("Before") print("Luminosity:", radiative.src_particles.luminosity) print("min ionization:", radiative.gas_particles.xion.min()) print("average Xion:", radiative.gas_particles.xion.mean()) print("max ionization:", radiative.gas_particles.xion.max()) print("min u:", radiative.gas_particles.u.min()) print("average u:", radiative.gas_particles.u.mean()) print("max u:", radiative.gas_particles.u.max()) Tmean = [] | units.K Tmin = [] | units.K Tmax = [] | units.K t = [] | units.day while radiative.model_time<t_end: supernova = update_source_particle(radiative, time+0.5*dt, supernova, efficiency_factor, supernova_IIp) radiative.evolve_model(time+0.5*dt) print("RT done at time:", time.in_(units.day)) rad_to_gas.copy() disk_to_hydro.copy() star_to_hydro.copy() hydro.evolve_model(time + dt) hydro_to_disk.copy() hydro_to_star.copy() supernova = update_source_particle(radiative, time+dt, supernova, efficiency_factor, supernova_IIp) radiative.evolve_model(time+dt) print("RT done at time:", time.in_(units.day)) rad_to_gas.copy() time += dt print_diagnostics(time, supernova, disk) Temperature = mu() / constants.kB * disk.u t.append(time) Tmean.append(Temperature.mean()) Tmin.append(Temperature.min()) Tmax.append(Temperature.max()) #write_set_to_file(disk, "disk_irradiation.amuse", "amuse") print("timescale:", (disk.mass.sum().value_in(units.amu) \ / ((Rout/Rsn)**2*supernova.luminosity)).in_(units.yr)) print("scaleheight:", abs(disk.z.value_in(units.AU)).mean()) #pyplot.hist2d(abs(disk.x.value_in(units.AU)), abs(numpy.log10(Temperature.value_in(units.K))), bins=200) # pyplot.hist2d(abs(disk.x.value_in(units.AU)), abs(disk.z.value_in(units.AU)), bins=200) #,norm=LogNorm()) #, Temperature.in_(units.K)) # pyplot.tripcolor(abs(disk.x.value_in(units.AU)), abs(disk.y.value_in(units.AU)), Temperature.in_(units.K)) #pyplot.hist(abs(disk.x.value_in(units.AU)), 100) # pyplot.show() print_diagnostics(time, supernova, disk) #plot_ionization_fraction(disk.position, disk.xion) # plot_ionization_fraction(disk.z, disk.u.value_in(units.kms**2)) # plot_ionization_fraction(disk.x, disk.u.value_in(units.kms**2)) radiative.stop() plot_temperature(t, Tmin, Tmean, Tmax) #~ from prepare_figure import single_frame, figure_frame #~ from distinct_colours import get_distinct def plot_temperature(t, tmin, tmean, tmax): x_label = "t [day]" y_label = 'T [K]' figure = single_frame(x_label, y_label, logx=False, logy=False, xsize=14, ysize=8) pyplot.plot(t.value_in(units.day), tmean.value_in(units.K), c='k') pyplot.plot(t.value_in(units.day), tmin.value_in(units.K), c='r') pyplot.plot(t.value_in(units.day), tmax.value_in(units.K), c='b') pyplot.show() def plot_ionization_fraction(pos, xion): r = [] x = [] for pi, xi in zip(pos, xion): #r.append(pi.length()) r.append(numpy.log10(pi.value_in(units.AU)+0.000001)) r.append(pi.value_in(units.AU)) x.append(numpy.log10(xi+0.000001)) r, x = list(zip(*sorted(zip(r, x)))) from matplotlib import pyplot x_label = "r [pc]" y_label = r'$\xi_{\rm ion}$' figure = single_frame(x_label, y_label, logx=False, logy=False, xsize=14, ysize=8) pyplot.scatter(r, x, c=get_distinct(1), lw=0, s=100) # pyplot.xlim(-1, 1) # pyplot.ylim(-0.04, 1.19) #pyplot.savefig("fig_ionization_of_GMC") pyplot.show() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("--Ndisk", dest="Ndisk", type="int", default = 10000, help="number of disk particles [%default]") result.add_option("-t", unit=units.yr, dest="t_end", type="float", default = 2|units.yr, help="radiation time [%default]") result.add_option("-r", unit=units.AU, type="float", dest="Rin", default = 1.|units.AU, help="inner disk radius [%default]") result.add_option("-R", unit=units.AU, type="float", dest="Rout", default = 100.|units.AU, help="outer disk radius [%default]") result.add_option("--Mstar", unit=units.MSun, type="float", dest="Mstar", default = 1|units.MSun, help="stellar mass") result.add_option("--Mdisk", unit=units.MSun, type="float", dest="Mdisk", default = 0.01|units.MSun, help="disk mass") result.add_option("-x", unit=units.parsec, type="float", dest="x", default = 0.1|units.parsec, help="supnova x-position") result.add_option("-y", unit=units.parsec, type="float", dest="y", default = 0|units.parsec, help="supnova y-position") result.add_option("-z", unit=units.parsec, type="float", dest="z", default = 0.01|units.parsec, help="supnova z-position") result.add_option("--Nray", type="int", dest="Nray", default = 10**7, help="number of rays [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
11,491
38.764706
114
py
amuse
amuse-main/examples/textbook/make_planets_oligarch.py
""" Make planets based on the an assumption of oligarchical planetary growth. (the formalism of Kokubo & Ida (1998)) After: @article{0004-637X-807-2-157, author={Scott Tremaine}, title={The Statistical Mechanics of Planet Orbits}, journal={The Astrophysical Journal}, volume={807}, number={2}, pages={157}, url={http://stacks.iop.org/0004-637X/807/i=2/a=157}, year={2015}, abstract={The final phase of terrestrial planet formation is believed to begin with a large number of planetary on nearly circular, coplanar orbits. Mutual gravitational interactions gradually excite their eccentricities until their orbits cross and they collide and merge; through this process the number of surviving bodies declines until the system contains a small number of planets on well-separated, stable orbits. In this paper we explore a simple statistical model for the orbit distribution of planets formed by this process, based on the sheared-sheet approximation and the ansatz that the planets explore uniformly all of the stable region of phase space. The model provides analytic predictions for the distribution of eccentricities and semimajor axis differences, correlations between orbital elements of nearby planets, and the complete N -planet distribution function, in terms of a single parameter, the that is determined by the planetary masses. The predicted properties are generally consistent with N -body simulations of the giant-impact phase and with the distribution of semimajor axis differences in the Kepler catalog of extrasolar planets. A similar model may apply to the orbits of giant planets if these orbits are determined mainly by dynamical evolution after the planets have formed and the gas disk has disappeared.} } Refers to (with the actual method as implemented here): @article{0004-637X-775-1-53, author={Brad M. S. Hansen and Norm Murray}, title={Testing in Situ Assembly with the Kepler Planet Candidate Sample}, journal={The Astrophysical Journal}, volume={775}, number={1}, pages={53}, url={http://stacks.iop.org/0004-637X/775/i=1/a=53}, year={2013} } Actual model: @article{0004-637X-581-1-666, author={Eiichiro Kokubo and Shigeru Ida}, title={Formation of Protoplanet Systems and Diversity of Planetary Systems}, journal={The Astrophysical Journal}, volume={581}, number={1}, pages={666}, url={http://stacks.iop.org/0004-637X/581/i=1/a=666}, year={2002}, } """ import numpy from numpy import random import time as pytime import os.path from amuse.units import quantities from amuse.units import units from amuse.units import nbody_system from amuse.units.core import named_unit from amuse.units.optparse import OptionParser from amuse.datamodel import Particle, Particles from amuse.community.kepler.interface import Kepler from amuse.io import write_set_to_file MEarth = named_unit("MEarth", "MEarth", 5.97219e+24 * units.kg) def get_mass(a, surface_density_factor = 1.0, mstar = 1 | units.MSun): s = surface_density_factor * (10.0 | (units.g / units.cm**2)) z = 2 * numpy.pi * a * s * ((a / (5.0|units.AU) ) ** -(3.0/2.0)) * 4.0 * a return (2.0 * z ** 3 / (3.0 * mstar)).sqrt() def get_orbital_separation(mass, a, mstar = 1 | units.MSun): return 10.0 * a * (2*mass/(3.0 * mstar)) ** (1.0/3.0) def get_mass_and_orbital_separation(a, surface_density_factor = 1.0, mstar = 1 | units.MSun): mass = get_mass(a, surface_density_factor = surface_density_factor, mstar = mstar) orbital_separation = get_orbital_separation(mass, a, mstar = mstar) return mass, orbital_separation def new_distribution(x0, x1, surface_density_factor = 1.0, mstar = 1 | units.MSun): x = x0 masses = [] positions = [] while x < x1: mass, orbital_separation = get_mass_and_orbital_separation(x, surface_density_factor = surface_density_factor, mstar = mstar) masses.append(mass) positions.append(x) x += orbital_separation return ( quantities.as_vector_quantity(masses), quantities.as_vector_quantity(positions) ) def is_hit(mass, target_total_mass, accurancy): return abs((mass - target_total_mass) / target_total_mass) < accurancy def new_planet_distribution(x0, x1, target_total_mass, accurancy, max_iterations = 1000, mstar = 1 | units.MSun): min_surface_density_factor = 0.1 max_surface_density_factor = 10000.0 current_surface_density_factor = min_surface_density_factor mass, pos = new_distribution(x0,x1,current_surface_density_factor, mstar = mstar) total_mass = mass.sum() iteration = 0 while not is_hit(total_mass, target_total_mass, accurancy): #print iteration, total_mass / (1 | MEarth), current_surface_density_factor iteration += 1 if iteration >= max_iterations: break if total_mass < target_total_mass: min_surface_density_factor = current_surface_density_factor elif total_mass > target_total_mass: max_surface_density_factor = current_surface_density_factor current_surface_density_factor = (min_surface_density_factor + max_surface_density_factor) / 2.0 mass, pos = new_distribution(x0,x1,current_surface_density_factor, mstar = mstar) total_mass = mass.sum() return mass, pos, current_surface_density_factor def new_rotation_matrix_from_euler_angles(phi, theta, chi): cosp=numpy.cos(phi) sinp=numpy.sin(phi) cost=numpy.cos(theta) sint=numpy.sin(theta) cosc=numpy.cos(chi) sinc=numpy.sin(chi) #see wikipedia: http://en.wikipedia.org/wiki/Rotation_matrix return numpy.array( [[cost*cosc, -cosp*sinc + sinp*sint*cosc, sinp*sinc + cosp*sint*cosc], [cost*sinc, cosp*cosc + sinp*sint*sinc, -sinp*cosc + cosp*sint*sinc], [-sint, sinp*cost, cosp*cost]]) def rotate(position, velocity, phi, theta, psi): # theta and phi in radians Runit = position.unit Vunit = velocity.unit matrix = new_rotation_matrix_from_euler_angles(phi, theta, psi) return (numpy.dot(matrix, position.value_in(Runit)) | Runit, numpy.dot(matrix, velocity.value_in(Vunit)) | Vunit) # select Eurler angles randomly. def random_Euler_angles(): phi = 2*numpy.pi*random() theta = numpy.acos(1-2*random()) chi = 2*numpy.pi*random() return phi, theta, chi def posvel_from_orbital_elements(Mstar, semimajor_axis, eccentricity, kepler, rng = None): if rng is None: rng = random mean_anomaly = rng.uniform(0, 2*numpy.pi, 1) kepler.initialize_from_elements( Mstar, semimajor_axis, eccentricity, mean_anomaly=mean_anomaly) position = quantities.as_vector_quantity(kepler.get_separation_vector()) velocity = quantities.as_vector_quantity(kepler.get_velocity_vector()) return position, velocity def make_planets(central_particle, masses, radii, density = 3 | units.g/units.cm**3, phi=None, theta=None, eccentricity = 0.0, kepler = None, rng = None): volumes = masses / density planet_radii = (3.0 * volumes / (4.0 * numpy.pi))**(1.0/3.0) n = len(masses) planet_particles = Particles(n) planet_particles.semimajor_axis = radii if eccentricity is None: eccentricity = numpy.abs(rng.normal(-0.00001,0.00001,n)) planet_particles.eccentricity = eccentricity planet_particles.mass = masses planet_particles.radius = planet_radii if phi is None: phi = numpy.radians(rng.uniform(0.0, 90.0, 1)[0])#rotate under x if theta is None: theta0 = numpy.radians((rng.normal(-90.0,90.0,1)[0]))#rotate under y theta0 = 0 theta_inclination = numpy.radians(rng.normal(0, 1.0, n )) theta_inclination[0] = 0 theta = theta0 + theta_inclination #psi = numpy.radians(rng.uniform(0, 180, 1))[0] #0 # numpy.radians(90) # numpy.radians(rng.uniform(0, 180, 1))[0] psi = numpy.radians(rng.uniform(0.0, 180.0, 1))[0] #0 # numpy.radians(90) # numpy.radians(rng.uniform(0, 180, 1))[0] com_particle = central_particle.copy() for x, t in zip(iter(planet_particles), theta): pos,vel = posvel_from_orbital_elements(com_particle.mass + x.mass, x.semimajor_axis, x.eccentricity, kepler, rng) pos,vel = rotate(pos, vel, 0, 0, psi) # theta and phi in radians pos,vel = rotate(pos, vel, 0, t, 0) # theta and phi in radians pos,vel = rotate(pos, vel, phi, 0, 0) # theta and phi in radians x.position = pos + com_particle.position x.velocity = vel + com_particle.velocity if False: two_body = Particles(particles=[com_particle, x]) print("dp:", (com_particle.position - two_body.center_of_mass()).as_quantity_in(units.AU)) com_particle.mass = two_body.mass.sum() com_particle.position = two_body.center_of_mass() com_particle.velocity = two_body.center_of_mass_velocity() #planet_particles.position += central_particle.position #planet_particles.velocity += central_particle.velocity return planet_particles def new_system( star_mass = 1|units.MSun, star_radius = 1|units.RSun, disk_minumum_radius = 0.05 | units.AU, disk_maximum_radius = 10 | units.AU, disk_mass = 20 | MEarth, accurancy = 0.0001, planet_density = 3 | units.g/units.cm**3, rng = None, kepler = None): central_particle = Particle() central_particle.mass = star_mass central_particle.position = (0,0,0) | units.AU central_particle.velocity = (0,0,0) | units.kms central_particle.radius = star_radius if rng is None: rng = numpy.random converter = nbody_system.nbody_to_si(1|units.MSun, 1 | units.AU) if kepler is None: kepler = Kepler(converter) kepler.initialize_code() m, r, f = new_planet_distribution( disk_minumum_radius, disk_maximum_radius, disk_mass, accurancy ) planets = make_planets( central_particle, m, r, density = planet_density, phi = 0, theta = None, kepler = kepler, rng = rng ) central_particle.planets = planets kepler.stop() p = Particles() p.add_particle(central_particle) return p def new_option_parser(): result = OptionParser() result.add_option("--seed", dest="seed", type="int", default = -1, help="random number seed [%default]") result.add_option("-o", "--output", dest="output_filename", default = "star.h5", help="name of the output filename [%default]") result.add_option("-m", "--star-mass", unit=units.MSun, type="float", default = 1|units.MSun, dest="star_mass", help='mass of the star [%default]') result.add_option("-r", "--star-radius", unit=units.RSun, type="float", default = 1|units.RSun, dest="star_radius", help='radius of the star [%default]') result.add_option("--disk-r0", unit=units.AU, type="float", default = 1|units.AU, dest="disk_minumum_radius", help='minimum radius of the disk [%default]') result.add_option("--disk-r1", unit=units.AU, type="float", default = 100|units.AU, dest="disk_maximum_radius", help='maximum radius of the disk [%default]') result.add_option("--disk-mass", unit=MEarth, type="float", default = 100|MEarth, dest="disk_mass", help='mass of the disk [%default]') result.add_option("--planet-density", unit=units.g/units.cm**3, type="float", default = 3 | units.g/units.cm**3, dest="planet_density", help='density of the planets (used for planet radii calculation) [%default]') result.add_option("--accurancy", type="float", default = 0.0001, dest="accurancy", help='how accurate should the disk mass be integrated to[%default]') #result.add_option("--plot", # action="store_true", dest="make_plot", default=False, # help="make a plot of the planets") return result def main( star_mass = 1|units.MSun, star_radius = 1|units.RSun, disk_minumum_radius = 0.05 | units.AU, disk_maximum_radius = 10 | units.AU, disk_mass = 200 | MEarth, accurancy = 0.0001, planet_density = 3 | units.g/units.cm**3, output_filename = 'star.h5', seed = -1): if seed < 0: rng = random.RandomState() else: rng = random.RandomState(seed) output = new_system( star_mass, star_radius, disk_minumum_radius, disk_maximum_radius, disk_mass, accurancy, planet_density, rng = rng) star = output[0] print("Number of planets generated:", len(star.planets)) print("Total mass:", star.planets.mass.sum().as_quantity_in(MEarth)) for i, planet in enumerate(star.planets): print("Planet: {0: 3d} , mass: {1: 8.3f} MEarth, a: {2: 8.2f} AU".format(i, planet.mass.value_in(MEarth), planet.semimajor_axis.value_in(units.AU))) write_set_to_file(output, output_filename, 'hdf5', version="2.0",append_to_file = False) if __name__ == "__main__": main(**new_option_parser().parse_args()[0].__dict__)
13,570
38.797654
1,350
py
amuse
amuse-main/examples/textbook/plot_solar_cluster_in_life_galaxy.py
import sys import numpy import matplotlib from matplotlib import pyplot from amuse.lab import * from distinct_colours import get_distinct from prepare_figure import single_frame def plot_galaxy_and_stars(galaxy, stars): colors = get_distinct(3) single_frame('X [kpc]', 'Y [kpc]') xlim = 10 pyplot.xlim(-xlim, xlim) pyplot.ylim(-xlim, xlim) ax = pyplot.gca() import numpy as np import pandas as pd from scipy import stats, integrate import matplotlib.pyplot as plt import seaborn as sns sns.set(color_codes=True) lim = 10|units.kpc p = galaxy.select(lambda x: x<lim,["x"]) p = p.select(lambda x: x>-lim,["x"]) p = p.select(lambda y: y<lim,["y"]) p = p.select(lambda y: y>-lim,["y"]) p = p.select(lambda r: r.length()>5|units.kpc,["position"]) x = p.x.value_in(units.kpc) y = p.y.value_in(units.kpc) sns.kdeplot(x, y, ax=ax, shade=True, n_levels=20, shade_lowest=False) m = 100*numpy.sqrt(stars.mass/stars.mass.max()) pyplot.scatter(stars.x.value_in(units.kpc), stars.y.value_in(units.kpc), c=colors[0], s=m, lw=0) pyplot.savefig("SolarSiblings_life_galaxy") def main(filename, tplot): sc = read_set_from_file(filename, "hdf5") # particles time = 0 | units.Myr snapshot_id = 0 for si in sc.history: si = si.copy() snapshot_id += 1 print(snapshot_id) if snapshot_id%2: print("convert") gc = si else: time = si.get_timestamp() if time>=tplot: break gc.move_to_center() print("Snapshot=", snapshot_id, time.in_(units.Gyr), len(gc), len(si)) plot_galaxy_and_stars(gc, si) def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-f", dest="filename", default = "proto_solar_cluster_life.hdf5", help="output filename [%default]") result.add_option("-t", unit=units.Gyr, dest="tplot", type="float", default = 3|units.Gyr, help="moment of the plot [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
2,270
30.109589
100
py
amuse
amuse-main/examples/textbook/plot_planetary_system.py
""" Visualization for simple N-body integration. Reads particle set from file (nbody.hdf5) and prints subsequent frames. """ import os import sys import numpy import matplotlib matplotlib.use('Agg') from matplotlib import pyplot #from matplotlib import pyplot from amuse.plot import scatter, xlabel, ylabel from amuse.lab import * from amuse.io import store from optparse import OptionParser from amuse.units.optparse import OptionParser from time import sleep from amuse.ext.orbital_elements import orbital_elements_from_binary def plot_single_image(planets, disk, lim, index): #centered on the Sun com = planets[0].position planets.position -= com disk.position -= com left, width = 0.1, 0.65 bottom, height = 0.1, 0.65 bottom_h = left_h = left+width+0.05 rect_scatter = [left, bottom, width, height] rect_histx = [left, bottom_h, width, 0.2] rect_histy = [left_h, bottom, 0.2, height] fig = pyplot.figure(figsize=(12,12)) time = disk.get_timestamp() # pyplot.title("Cluster at t="+str(time.in_(units.Gyr))) xy = pyplot.axes(rect_scatter) xy.text(110,110, "protoplanetary disk (img#"+str(index)+")", ha='left', va='bottom') xz = pyplot.axes(rect_histx) yz = pyplot.axes(rect_histy) xy.set_xlabel("X [AU]") xy.set_ylabel("Y [AU]") xz.set_ylabel("Z [AU]") yz.set_xlabel("Z [AU]") positions = disk.position x, y, z = positions.x.value_in(units.AU), positions.y.value_in(units.AU), \ positions.z.value_in(units.AU) alpha = 0.01 us = disk.u u_min, u_max = min(us), max(us) print("u=", u_min, u_max) log_u = numpy.log((us / u_min)) / numpy.log((u_max / u_min)) clipped_log_u = numpy.minimum(numpy.ones_like(log_u), numpy.maximum(numpy.zeros_like(log_u), log_u)) ps = disk.rho p_min, p_max = min(ps), max(ps) log_p = numpy.log((ps / p_min)) / numpy.log((p_max / p_min)) clipped_log_p = numpy.minimum(numpy.ones_like(log_p), numpy.maximum(numpy.zeros_like(log_p), log_p)) red = 1.0 - clipped_log_u blue = clipped_log_u green = clipped_log_p colors = numpy.transpose(numpy.array([red, green, blue])) sizes = 2000*disk.h_smooth/disk.h_smooth.max() xy.scatter(x, y, sizes, c=colors, edgecolors = "none", alpha = alpha) xy.set_xlim( (-lim, lim) ) xy.set_ylim( (-lim, lim) ) sizes = 100*disk.h_smooth/disk.h_smooth.max() xz.scatter(x, z, sizes, c=colors, edgecolors = "none", alpha = alpha) yz.scatter(z, y, sizes, c=colors, edgecolors = "none", alpha = alpha) xz.set_xlim( xy.get_xlim() ) yz.set_ylim( xy.get_xlim() ) yz.set_xlim( (-0.05*lim, 0.05*lim) ) xz.set_ylim( (-0.05*lim, 0.05*lim) ) from distinct_colours import get_distinct c = get_distinct(len(planets)) # m = 1000 * planets.mass/planets.mass.max() m = 100 * numpy.log10(1+planets.mass/planets.mass.min()) #m[0] = min(10*m[1:].max(), 30) xy.scatter(planets.x.value_in(units.AU), planets.y.value_in(units.AU), s=m, c=c, lw=0) xz.scatter(planets.x.value_in(units.AU), planets.z.value_in(units.AU), s=m, c=c, lw=0) yz.scatter(planets.z.value_in(units.AU), planets.y.value_in(units.AU), s=m, c=c, lw=0) filename = "planetary_system_i{0:04}.png".format(index) fig.savefig(filename) def XX_main(filename, lim=-1|units.AU, image_id=-1): if image_id < 0: pyplot.ion() star = read_set_from_file("earlysolarsystem.amuse", "amuse") planet = read_set_from_file("earlysolarsystem.amuse", "amuse") disk = read_set_from_file("earlysolarsystem.amuse", "amuse") mc = read_set_from_file(filename, "hdf5") # particles time = 0 snapshot_id = 0 for si, ssi in zip(mc.history, star.history): snapshot_id += 1 time = si.get_timestamp() print("Snapshot=", snapshot_id, time) if image_id < 0 or image_id == snapshot_id: m = 1 plot_single_image(si, ssi, lim.value_in(units.AU), snapshot_id) if image_id == snapshot_id: print("Stop plotting") break if image_id<0: pyplot.draw() pyplot.cla() def calculate_orbital_elements(star, planet): p = Particles() p.add_particle(star) p.add_particle(planet) M, m, a, e, ta_out, inc_out, lan_out, aop_out \ = orbital_elements_from_binary(p, G=constants.G) return a, e def main(filename, lim=-1|units.AU, image_id=-1): if image_id < 0: output_multiple_images(lim) else: output_single_image(lim, image_id) def output_single_image(lim, snapshot_id): filename = "planetary_system_i{0:04}.amuse".format(snapshot_id) bodies = read_set_from_file(filename, "amuse") for bi in bodies.history: if len(bi)<=20: planets = bi.copy() time = bi.get_timestamp() print("Orbits at t=", time, planets.semimajor_axis.in_(units.AU), \ planets.eccentricity) else: disk = bi.copy() time = bi.get_timestamp() print("Snapshot=", snapshot_id, time) plot_single_image(planets, disk, lim.value_in(units.AU), snapshot_id) def output_multiple_images(lim): snapshot_id = 0 filename = "planetary_system_i{0:04}.amuse".format(snapshot_id) while os.path.exists(filename): bodies = read_set_from_file(filename, "amuse") for bi in bodies.history: if len(bi) <= 20: planets = bi.copy() time = bi.get_timestamp() print("Orbits at t=", time, \ planets.semimajor_axis.in_(units.AU), planets.eccentricity) else: disk = bi.copy() time = bi.get_timestamp() print("Snapshot=", snapshot_id, time) if image_id < 0 or image_id == snapshot_id: plot_single_image(planets, disk, lim.value_in(units.AU), snapshot_id) if image_id == snapshot_id: print("Stop plotting") break snapshot_id += 1 filename = "planetary_system_i{0:04}.amuse".format(snapshot_id) def new_option_parser(): result = OptionParser() result.add_option("-f", dest="filename", default = "hydro.hdf5", help="output filename [%default]") result.add_option("-l", unit=units.AU, dest="lim", type="float", default = 100|units.AU, help="axis length [%default]") result.add_option("-i", dest="image_id", type="int", default = 281, help="image id [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
7,006
35.118557
80
py
amuse
amuse-main/examples/textbook/merge_two_stars_and_evolve.py
import numpy from matplotlib import pyplot from amuse.lab import * from amuse.community.mmams.interface import MMAMSInterface from amuse.community.mmams.interface import MMAMS from amuse.couple.collision_handler import CollisionHandler from prepare_figure import single_frame from distinct_colours import get_distinct default_options = dict() def evolve_single_star(mass, tend): star = Particles(1) star.mass = mass stellar_evolution = MESA() stellar_evolution.particles.add_particles(star) time = [] | units.Myr stellar_type = [] mass = [] | units.MSun radius = [] | units.RSun temperature = [] | units.K luminosity = [] | units.LSun while stellar_evolution.model_time < tend: stellar_evolution.evolve_model() time.append(stellar_evolution.model_time) stellar_type.append(stellar_evolution.particles[0].stellar_type) mass.append(stellar_evolution.particles[0].mass) radius.append(stellar_evolution.particles[0].radius) temperature.append(stellar_evolution.particles[0].temperature) luminosity.append(stellar_evolution.particles[0].luminosity) print("Time=", time[-1], stellar_type[-1], mass[-1], radius[-1], \ temperature[-1].in_(units.K), luminosity[-1].in_(units.LSun)) if stellar_type[-1] >= 4 | units.stellar_type: break stellar_evolution.stop() return time, stellar_type, mass, radius, temperature, luminosity def print_stars(stellar_evolution): print("Primary: Time=", stellar_evolution.model_time.in_(units.Myr), \ stellar_evolution.particles[0].mass.in_(units.MSun), \ stellar_evolution.particles[0].radius.in_(units.RSun), \ stellar_evolution.particles[0].temperature.in_(units.K), \ stellar_evolution.particles[0].luminosity.in_(units.LSun)) print("Secondary: Time=", stellar_evolution.model_time.in_(units.Myr), \ stellar_evolution.particles[1].mass.in_(units.MSun), \ stellar_evolution.particles[1].radius.in_(units.RSun), \ stellar_evolution.particles[1].temperature.in_(units.K), \ stellar_evolution.particles[1].luminosity.in_(units.LSun)) ###BOOKLISTSTART1### def merge_two_stars_and_evolve(Mprim, Msec, tcoll, tend): stars = Particles(2) stars.mass = [Mprim.value_in(units.MSun), Msec.value_in(units.MSun)] | units.MSun stellar_evolution = MESA() stellar_evolution.particles.add_particles(stars) while stellar_evolution.model_time < tcoll: stellar_evolution.evolve_model() print_stars(stellar_evolution) n_shell = min(stellar_evolution.particles[0].get_number_of_zones(), stellar_evolution.particles[1].get_number_of_zones()) merger_code = MMAMS(**default_options) merger_code.parameters.target_n_shells = n_shell merger_code.parameters.dump_mixed_flag = True merger_code.parameters.do_shock_heating_flag = True merger_code.commit_parameters() ###BOOKLISTSTOP1### ###BOOKLISTSTART2### handler = CollisionHandler(merger_code, stellar_evolution_code = stellar_evolution) merger_product = handler.handle_collision(stellar_evolution.particles[0], stellar_evolution.particles[1]) merged = stellar_evolution.particles[0] ###BOOKLISTSTOP2### print("Stars merged:", merged) time = [] | units.Myr stellar_type = [] mass = [] | units.MSun radius = [] | units.RSun temperature = [] | units.K luminosity = [] | units.LSun ###BOOKLISTSTART3### stellar_evolution.evolve_model(keep_synchronous=True) p = stellar_evolution.particles[0] while stellar_evolution.model_time < tend: stellar_evolution.evolve_model() ###BOOKLISTSTOP3### time.append(stellar_evolution.model_time) stellar_type.append(p.stellar_type) mass.append(p.mass) radius.append(p.radius) temperature.append(p.temperature) luminosity.append(p.luminosity) ###BOOKLISTSTART4### print("Time=", stellar_evolution.model_time, p.stellar_type, \ p.mass, p.radius, p.temperature.in_(units.K), \ p.luminosity.in_(units.LSun)) if p.stellar_type >= 4 | units.stellar_type: break merger_code.stop() stellar_evolution.stop() ###BOOKLISTSTOP4### return time, stellar_type, mass, radius, temperature, luminosity def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("--tcoll", unit=units.Myr, dest="tcoll", type="float", default = 150|units.Myr, help="moment of collision [%default]") result.add_option("--tend", unit=units.Myr, dest="tend", type="float", default = 2|units.Gyr, help="evolution after the collision [%default]") result.add_option("-M", unit=units.MSun, dest="Mprim", type="float", default = 3|units.MSun, help="Primary ZAMS mass [%default]") result.add_option("-m", unit=units.MSun, dest="Msec", type="float", default = 1|units.MSun, help="Secondary ZAMS mass [%default]") return result if __name__ in ('__main__','__plot__'): # High-level structure of merge_two_stars_and_evolve.py and # merge_two_stars_sph_evolve.py are designed to be identical. set_printing_strategy("custom", #nbody_converter = converter, precision = 11, prefix = "", separator = " [", suffix = "]") o, arguments = new_option_parser().parse_args() Mprim = o.Mprim Msec = o.Msec tend = o.tend tcoll = o.tcoll color = get_distinct(4) # 0 = cyan, 1 = red, 2 = mustard, 3 = green x_label = "T [K]" y_label = "L [$L_\odot$]" figure = single_frame(x_label, y_label, logx=True, logy=True, xsize=14, ysize=10) pyplot.xlim(2.e+4, 3.e3) pyplot.ylim(20., 2.e+3) print("Evolve single star of mass", Mprim.in_(units.MSun)) time, stp, mass, radius, temperature, luminosity \ = evolve_single_star(Mprim, tend) pyplot.plot(temperature.value_in(units.K), luminosity.value_in(units.LSun), c=color[1], lw=2, zorder=1) pyplot.scatter(temperature[0].value_in(units.K), luminosity[0].value_in(units.LSun), c=color[1], s=150, marker='^', edgecolor='k', zorder=2) tms = 0 |units.Myr for i in range(len(stp)): if stp[i] < 2 | units.stellar_type: tms = time[i] if tms <= 1|units.Myr: tms = 10|units.Myr print("Main-sequence lifetime =", tms.in_(units.Myr)) tcoll = 0.5*tms icoll = 0 for i in range(len(stp)): if time[i] <= tcoll: icoll = i pyplot.scatter(temperature[icoll].value_in(units.K), luminosity[icoll].value_in(units.LSun), c=color[2], s=150, marker='o', edgecolor='k', zorder=2) print("Evolve single star of mass", (Mprim+Msec).in_(units.MSun)) time, stp, mass, radius, temperature, luminosity \ = evolve_single_star(Mprim+Msec, tend) pyplot.plot(temperature.value_in(units.K), luminosity.value_in(units.LSun), c=color[0], lw=2, zorder=1) pyplot.scatter(temperature[0].value_in(units.K), luminosity[0].value_in(units.LSun), c=color[0], s=150, marker='^', edgecolor='k', zorder=2) print("Evolve two single stars and collide at", tcoll.in_(units.Myr)) time, stp, mass, radius, temperature, luminosity \ = merge_two_stars_and_evolve(Mprim, Msec, tcoll, tend) pyplot.plot(temperature.value_in(units.K), luminosity.value_in(units.LSun), c=color[2], ls="--", lw=3, zorder=1) pyplot.scatter(temperature[0].value_in(units.K), luminosity[0].value_in(units.LSun), c=color[2], s=150, marker='o', edgecolor='k', zorder=3) Mmerger = mass[0] print("Evolve single star of mass", Mmerger) time, stp, mass, radius, temperature, luminosity \ = evolve_single_star(Mmerger, tend) pyplot.plot(temperature.value_in(units.K), luminosity.value_in(units.LSun), c=color[3], lw=2, zorder=1) pyplot.scatter(temperature[0].value_in(units.K), luminosity[0].value_in(units.LSun), c=color[3], s=150, marker='^', edgecolor='k', zorder=2) ax = pyplot.gca() ax.tick_params(axis='both', which='both', direction='in') save_file = 'merge_two_stars_and_evolve.pdf' pyplot.savefig(save_file) print('\nSaved figure in file', save_file,'\n') pyplot.show()
9,071
38.443478
77
py
amuse
amuse-main/examples/textbook/multiple_stellar_threaded.py
try: import queue except: import Queue as queue import threading import multiprocessing from amuse.lab import * ###BOOKLISTSTART1### code_queue = queue.Queue() def remote_worker_code(): code = code_queue.get() evolve_single_star(code) code_queue.task_done() def evolve_with_different_stellar_model(codes): for ci in codes: code_queue.put(ci) n_cpu = multiprocessing.cpu_count() for i in range(n_cpu): th = threading.Thread(target=remote_worker_code) th.daemon = True th.start() code_queue.join() # block until all tasks are done ###BOOKLISTSTOP1### ###BOOKLISTSTART2### def evolve_single_star(code): stars = Particles(mass=10|units.MSun) stellar = code() stellar.particles.add_particles(stars) channel = stellar.particles.new_channel_to(stars) stellar.evolve_model(1|units.Myr) channel.copy() print("Star evolved to time=", stellar.model_time, \ " M=", stars.mass, "R=", stars.radius) stellar.stop() ###BOOKLISTSTOP2### def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-t", action="store_true", dest="threaded", help="run threaded [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() set_printing_strategy("custom",\ preferred_units = [units.MSun, units.RSun, units.Myr],\ precision = 6, prefix = "", separator = "[", suffix = "]") codes = [SeBa, MESA, SSE, EVtwin] if o.threaded: print("Run threaded") evolve_with_different_stellar_model(codes) else: print("Run sequentially") for ci in codes: evolve_single_star(ci)
1,799
26.692308
70
py
amuse
amuse-main/examples/textbook/Vostok1999temperature.py
import os import numpy from matplotlib import pyplot from prepare_figure import single_frame, figure_frame, set_tickmarks from distinct_colours import get_distinct def read_vostok1999temperaturedata(datafile): t = [] T = [] for line in open(datafile): if '***' not in line and '#' not in line: sl = line.split() t.append(float(sl[1])) T.append(float(sl[3])) return t, T def read_Earthorbit(datafile): t = [] e = [] a = [] tmax = 1.e+6 for line in open(datafile): if '#' not in line: sl = line.split() t.append(float(sl[0])) a.append(float(sl[1])) e.append(float(sl[2])) if t[-1]>tmax: break return t, a, e if __name__ in ('__main__', '__plot__'): try: amusedir = os.environ['AMUSE_DIR'] dir = amusedir+'/examples/textbook/' except: print('Environment variable AMUSE_DIR not set') dir = './' tv, T = read_vostok1999temperaturedata(dir+'vostok1999temperature.data') te, ae, ee = read_Earthorbit(dir+'EarthOrbit_Eps-3.data') q = [] q0 = ae[0]*(1-ee[0]**2) ao = ae[0] T_mean = numpy.mean(T) Tmin = numpy.min(T) Tmax = numpy.max(T) dT = Tmax-Tmin for i in range(len(te)): te[i] -= 0 ae[i] = 2e+5*(ae[i]-ao)/ao te[i] = te[i]/1000. for i in range(len(tv)): tv[i] = tv[i]/1000. 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) ax1 = pyplot.gca() cols = get_distinct(2) font = {'size' : 20} rc('font', **font) ax1.plot(tv, T, ls='-', c=cols[0]) ax1.set_xlabel('time before present (kyr)') ax1.set_xlim(450, 0) # Make the y-axis label and tick labels match the line color. ax1.set_ylabel('temperature [$^o$]', color=cols[0]) for tl in ax1.get_yticklabels(): tl.set_color(cols[0]) ax2 = ax1.twinx() ax2.plot(te, ee, cols[1]) ax2.set_ylabel('eccentricity', color=cols[1]) for tl in ax2.get_yticklabels(): tl.set_color(cols[1]) save_file = 'vostok1999temperature.png' pyplot.savefig(save_file) print("\nSaved figure in file", save_file,'\n') pyplot.show()
2,359
25.222222
76
py
amuse
amuse-main/examples/textbook/gravity_collision.py
import math, numpy from matplotlib import pyplot from amuse.lab import * from optparse import OptionParser from amuse.ext.LagrangianRadii import LagrangianRadii def merge_two_stars(bodies, particles_in_encounter, tcoll): com_pos = particles_in_encounter.center_of_mass() com_vel = particles_in_encounter.center_of_mass_velocity() new_particle=Particles(1) new_particle.mass = particles_in_encounter.total_mass() new_particle.collision_time = tcoll new_particle.position = com_pos new_particle.velocity = com_vel new_particle.radius = \ particles_in_encounter.radius.sum()/len(particles_in_encounter.radius) bodies.add_particles(new_particle) bodies.remove_particles(particles_in_encounter) return new_particle def main(N=10, W0=7.0, t_end=10, nsteps=10, filename="gravity_stellar.hdf5", Mmax=100, Qvir=0.5): t_end = t_end | nbody_system.time dt = t_end/float(nsteps) bodies = new_king_model(N, W0) masses = new_powerlaw_mass_distribution(N, mass_min=0.1|units.MSun, mass_max=10|units.MSun, alpha=-2.35) masses /= masses.sum() bodies.mass = masses | nbody_system.mass bodies.radius = 0.001 | nbody_system.length Mtot_init = 1 | nbody_system.mass gravity = ph4(number_of_workers=4) gravity.particles.add_particles(bodies) bodies.scale_to_standard(virial_ratio=Qvir) channel_from_gd_to_framework = gravity.particles.new_channel_to(bodies) stopping_condition = gravity.stopping_conditions.collision_detection stopping_condition.enable() Etot_init = gravity.kinetic_energy + gravity.potential_energy Etot_prev = Etot_init time = 0.0 | t_end.unit Nenc = 0 dEk_enc = zero dEp_enc = zero t = [] rcore = [] MassFraction = [0.005, 0.01, 0.02, 0.05, 0.1, 0.25, 0.5, 0.75, 0.9, 1.0] r50 = [] r90 = [] tcoll = [] rcoll = [] mcoll = [] while time < t_end: RL = LagrangianRadii(gravity.particles, massf=MassFraction) pos,coreradius,coredens = \ gravity.particles.densitycentre_coreradius_coredens() print("Cluster at time=", time, "core_radius=", coreradius, \ "L_radii =", end=' ') for rl in RL: print(rl.number, " ", end=' ') print("length") t.append(time.number) rcore.append(coreradius.number) r50.append(RL[6].number) r90.append(RL[8].number) gravity.evolve_model(time+dt) time = gravity.model_time if stopping_condition.is_set(): Ek_enc = gravity.kinetic_energy Ep_enc = gravity.potential_energy print("At time=", time, "number of encounters=", \ len(stopping_condition.particles(0))) for ci in range(len(stopping_condition.particles(0))): particles_in_encounter = Particles( particles=[stopping_condition.particles(0)[ci], stopping_condition.particles(1)[ci]]) particles_in_encounter = \ particles_in_encounter.get_intersecting_subset_in(bodies) new_particle = merge_two_stars(bodies, particles_in_encounter, gravity.model_time) bodies.synchronize_to(gravity.particles) Nenc+=1 RL = LagrangianRadii(gravity.particles, massf=MassFraction) print("Resolve encounter number", Nenc) pos,coreradius,coredens = \ gravity.particles.densitycentre_coreradius_coredens() print("Collision at time=", time, new_particle.mass.sum(), \ new_particle.position.length(), "Nstars= ", len(bodies), \ "Ncoll=", Nenc, "core_radius=", coreradius, "L_radii=", end=' ') for rl in RL: print(rl.number, " ", end=' ') print("length") pos = new_particle[0].position.number rc = math.sqrt(numpy.sum(pos**2)) mc = new_particle[0].mass.number tcoll.append(time.number) rcoll.append(rc) mcoll.append(mc) dEk_enc += Ek_enc - gravity.kinetic_energy dEp_enc += Ep_enc - gravity.potential_energy bodies.move_to_center() channel_from_gd_to_framework.copy() Ekin = gravity.kinetic_energy Epot = gravity.potential_energy Etot = Ekin + Epot dE = Etot_prev-Etot Mtot = bodies.mass.sum() print("T=", time, end=' ') print("M=", Mtot, "(dM[SE]=", Mtot/Mtot_init, ")", end=' ') print("E=", Etot, "Q=", Ekin/Epot, end=' ') print("dE=", (Etot_init-Etot)/Etot, "ddE=", (Etot_prev-Etot)/Etot, end=' ') print("dE(enc)=", dEk_enc, dEp_enc) Etot_init -= dE Etot_prev = Etot gravity.stop() pyplot.figure(figsize=(8,6)) pyplot.plot(t, rcore, 'b') pyplot.plot(t, r50, 'r') pyplot.plot(t, r90, 'y') size = numpy.array(mcoll) mmin = numpy.amin(size) size = 2 + 15*numpy.log10(size/mmin) pyplot.scatter(tcoll, rcoll, c='g', s=size) pyplot.xlabel('t [N-body]') pyplot.ylabel('R [N-body]') pyplot.yscale('log') save_file = 'gravity_collision.png' pyplot.savefig(save_file) print('\nSaved figure in file', save_file,'\n') pyplot.show() def new_option_parser(): result = OptionParser() result.add_option("-f", dest="filename", default = "gravity_stellar.hdf5", help="output filename [gravity_stellar.hdf5]") result.add_option("-N", dest="N", type="int",default = 1000, help="number of stars [100]") result.add_option("-n", dest="nsteps", type="int",default = 100, help="number of output steps [10]") result.add_option("-M", dest="Mmax", type="float",default = 100, help="maximal stellar mass [100]") result.add_option("-t", dest="t_end", type="float", default = 100, help="end time of the simulation [1]") result.add_option("-Q", dest="Qvir", type="float", default = 0.5, help="initial virial radio [%default]") result.add_option("-W", dest="W0", type="float", default = 7.0, help="Dimensionless depth of the King potential (W0) [7.0]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
6,683
36.762712
85
py
amuse
amuse-main/examples/textbook/hydro_grid_minimal.py
import numpy from amuse.lab import * from amuse.units import units, constants from amuse.ext.sph_to_grid import convert_SPH_to_grid from amuse.units.generic_unit_converter import ConvertBetweenGenericAndSiUnits def plot_grid(grid): from matplotlib import pyplot density = units.g / units.cm**3 rho = grid.rho[:, :, 0].value_in(density) figure = pyplot.figure(figsize=(6, 6)) plot = figure.add_subplot(1, 1, 1) plot.imshow(rho, origin='lower') figure.savefig('kelvin_helmholtz.png') pyplot.show() def setup_sph_code(sph_code, N, L, rho, u): converter = ConvertBetweenGenericAndSiUnits(L, rho, constants.G) sph_code = sph_code(converter, mode='periodic') sph_code.parameters.periodic_box_size = 10.0 | units.parsec plummer = new_plummer_gas_model(N, convert_nbody=converter) plummer = plummer.select(lambda r: r.length()<0.5*L,["position"]) N = len(plummer) print("N=", len(plummer)) plummer.mass = (rho * L**3) / N gas = Particles(N) gas.mass = 0.01*(rho * L**3) / N numpy.random.seed(12345) gas.x = L * numpy.random.uniform(0.0, 1.0, N) gas.y = L * numpy.random.uniform(0.0, 1.0, N) gas.z = L * numpy.random.uniform(0.0, 1.0, N) gas.vx = numpy.zeros(N) | units.cm / units.s gas.vy = numpy.zeros(N) | units.cm / units.s gas.vz = numpy.zeros(N) | units.cm / units.s gas.u = u if isinstance(sph_code, Fi): sph_code.parameters.self_gravity_flag = False sph_code.parameters.timestep = 0.1 | generic_unit_system.time gas.h_smooth = L / N**(1/3.0) gas.position -= 0.5 * L sph_code.gas_particles.add_particles(gas) sph_code.gas_particles.add_particles(plummer) sph_code.commit_particles() return sph_code def main(N, Mtot, Rvir, t_end): rho = 1.14 | units.amu/units.cm**3 u = 5.e11 | units.cm**2 / units.s**2 sph_code = setup_sph_code(Fi, N, Rvir, rho, u) grid = convert_SPH_to_grid(sph_code, (10, 10, 10), do_scale = True) print(grid) sph_code.stop() plot_grid(grid) exit() # the code below is not yet used, to be fixed? hydro = Athena(converter) hydro.parameters.gamma = 1.4 hydro.parameters.courant_number=0.8 hydro.parameters.mesh_size hydro.gas_particles.add_particles(gas) Etot_init = hydro.kinetic_energy \ + hydro.potential_energy + hydro.thermal_energy hydro.evolve_model(t_end) write_set_to_file(hydro.particles, "hydro.h5", "hdf5") Ekin = hydro.kinetic_energy Epot = hydro.potential_energy Eth = hydro.thermal_energy Etot = Ekin + Epot + Eth Q = (Ekin+Eth)/Epot dE = (Etot_init-Etot)/Etot com = hydro.gas_particles.center_of_mass() print("T=", hydro.get_time(), "M=", hydro.gas_particles.mass.sum(), end=' ') print("E= ", Etot, "Q= ", Q, "dE=", dE, "CoM=", com.in_(units.RSun)) hydro.stop() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-N", dest="N", type="int",default = 10000, help="number of gas particles [%default]") result.add_option("-t", unit=units.Myr, dest="t_end", type="float", default = 1|units.Myr, help="end time of the simulation [%default]") result.add_option("-M", unit=units.MSun, dest="Mtot", type="float", default = 1000|units.MSun, help="Mass of the cloud [%default]") result.add_option("-R", unit=units.RSun, dest="Rvir", type="float", default = 10|units.parsec, help="Radius of the cloud [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
3,829
35.47619
81
py
amuse
amuse-main/examples/tutorial/CDG_gd.py
from amuse.lab import * def main(Ncl, mcl, rcl, W0, t_end, n_steps): converter = nbody_system.nbody_to_si(mcl, rcl) bodies = new_king_model(Ncl, W0, convert_nbody=converter) gravity = Hermite(converter) gravity.particles.add_particles(bodies) channel_from_gravity_to_framework = gravity.particles.new_channel_to( bodies) write_set_to_file(bodies.savepoint(0.0 | t_end.unit), "nbody.hdf5", "hdf5", append_to_file=False) Etot_init = gravity.kinetic_energy + gravity.potential_energy time = zero dt = t_end/float(n_steps) while time < t_end: Etot_prev = Etot_init time += dt gravity.evolve_model(time) channel_from_gravity_to_framework.copy() write_set_to_file(bodies.savepoint(time), "nbody.hdf5", "hdf5") Ekin = gravity.kinetic_energy Epot = gravity.potential_energy Etot = Ekin + Epot print "T=", time, "M=", bodies.mass.sum(), "E= ", Etot, "Q= ", \ Ekin/Epot, print "dE=", (Etot_init-Etot)/Etot, "ddE=", (Etot_prev-Etot)/Etot gravity.stop() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-N", dest="Ncl", type="int", default=100, help="number of stars [%default]") result.add_option("-t", unit=units.Myr, dest="t_end", type="float", default=1 | units.Myr, help="end time of the simulation [%default]") result.add_option("-n", dest="n_steps", type="float", default=100, help="number of output steps [%default]") result.add_option("-m", unit=units.parsec, dest="mcl", type="float", default=10**7 | units.MSun, help="cluster mass [%default]") result.add_option("-r", unit=units.parsec, dest="rcl", type="float", default=10 | units.parsec, help="cluster half-mass radius [%default]") result.add_option("-W", dest="W0", type="float", default=7.0, help="King model structure parameter [%default]") return result if __name__ in ('__main__'): set_printing_strategy( "custom", preferred_units=[ units.MSun, units.RSun, units.yr], precision=4, prefix="", separator=" [", suffix="]") o, arguments = new_option_parser().parse_args() main(**o.__dict__)
2,488
35.602941
76
py
amuse
amuse-main/examples/tutorial/galaxy_model.py
import numpy from amuse.lab import * class MilkyWay_galaxy(object): def get_gravity_at_point(self, eps, x, y, z): phi_0 = self.get_potential_at_point(eps, x, y, z) # grav = AdaptingVectorQuantity() dpos = 0.001*(x**2+y**2+z**2).sqrt() phi_dx = self.get_potential_at_point(0, x+dpos, y, z) - phi_0 phi_dy = self.get_potential_at_point(0, x, y+dpos, z) - phi_0 phi_dz = self.get_potential_at_point(0, x, y, z+dpos) - phi_0 return phi_dx/dpos, phi_dy/dpos, phi_dz/dpos def disk_and_bulge_potentials(self, x, y, z, a, b, mass): r = (x**2+y**2).sqrt() return constants.G * mass /\ (r**2 + (a + (z**2 + b**2).sqrt())**2).sqrt() def halo_potential( self, x, y, z, Mc=5.0E+10 | units.MSun, Rc=1.0 | units.kpc**2): r = (x**2+y**2+z**2).sqrt() rr = (r/Rc) return ( -constants.G * (Mc/Rc)*( 0.5*numpy.log(1 + rr**2) + numpy.arctan(rr)/rr ) ) def get_potential_at_point(self, eps, x, y, z): pot_disk = self.disk_and_bulge_potentials( x, y, z, 0.0 | units.kpc, 0.277 | units.kpc, 1.12E+10 | units.MSun) pot_bulge = self.disk_and_bulge_potentials( x, y, z, 3.7 | units.kpc, 0.20 | units.kpc, 8.07E+10 | units.MSun) pot_halo = self.halo_potential( x, y, z, Mc=5.0E+10 | units.MSun, Rc=6.0 | units.kpc) return pot_disk + pot_bulge + pot_halo if __name__ in ('__main__', '__plot__'): set_printing_strategy("custom", # nbody_converter = converter, preferred_units=[units.MSun, units.RSun, units.yr], precision=4, prefix="", separator=" [", suffix="]") mwg = MilkyWay_galaxy() sun_pos = [8.5, 0, 0] | units.kpc eps = 1 | units.AU print "Milky Way Galaxy:" print "gravity at solar location:", \ mwg.get_gravity_at_point(eps, sun_pos[0], sun_pos[1], sun_pos[2]) print "potential at solar location:", \ mwg.get_potential_at_point(eps, sun_pos[0], sun_pos[1], sun_pos[2])
2,215
38.571429
77
py
amuse
amuse-main/examples/tutorial/CDG_gd_Galaxy_imf.py
""" Nbody integration of N particles in N-body units from t=0 to t_end=1 N-body time units. The initial cluster is a King (1966) model with dimension-less depth of the potential of W0=7. The initial distribution of stars is in virial equilibrium. At this moment a 4th order Hermite integrator is used for the integration. """ from amuse.lab import * from amuse.couple import bridge from galaxy_model import MilkyWay_galaxy def main(Ncl, rcl, W0, Rgal, vgal, t_end, n_steps): masses = new_salpeter_mass_distribution( Ncl, 0.1 | units.MSun, 100 | units.MSun) converter = nbody_system.nbody_to_si(masses.sum(), rcl) bodies = new_king_model(Ncl, W0, convert_nbody=converter) bodies.mass = masses bodies.scale_to_standard(convert_nbody=converter) bodies.x += Rgal bodies.vy += vgal CDG = BHTree(converter) CDG.particles.add_particles(bodies) channel_from_gravity_to_framework = CDG.particles.new_channel_to(bodies) gravity = bridge.Bridge() gravity.add_system(CDG, (MilkyWay_galaxy(),)) dt = t_end/float(n_steps) gravity.timestep = dt filename = "nbody.hdf5" write_set_to_file(bodies.savepoint(0.0 | t_end.unit), filename, "hdf5", append_to_file=False) Etot_init = gravity.kinetic_energy + gravity.potential_energy Etot_prev = Etot_init time = zero dt = t_end/float(n_steps) while time < t_end: time += dt gravity.evolve_model(time) channel_from_gravity_to_framework.copy() write_set_to_file(bodies.savepoint(time), filename, "hdf5") Ekin = gravity.kinetic_energy Epot = gravity.potential_energy Etot = Ekin + Epot print "T=", time, "M=", bodies.mass.sum(), print "E= ", Etot, "Q= ", Ekin/Epot, print "dE=", (Etot_init-Etot)/Etot, "ddE=", (Etot_prev-Etot)/Etot Etot_prev = Etot gravity.stop() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-N", dest="Ncl", type="int", default=100, help="number of stars [%default]") result.add_option("-t", unit=units.Myr, dest="t_end", type="float", default=1 | units.Gyr, help="end time of the simulation [%default]") result.add_option("-n", dest="n_steps", type="float", default=300, help="number of diagnostics output steps [%default]") result.add_option("-r", unit=units.parsec, dest="rcl", type="float", default=100 | units.parsec, help="cluster half-mass radius [%default]") result.add_option("-R", unit=units.kpc, dest="Rgal", type="float", default=8.5 | units.kpc, help="distance to the GC [%default]") result.add_option("-v", unit=units.parsec, dest="vgal", type="float", default=100 | units.kms, help="orbital velocity of the CDG [%default]") result.add_option("-W", dest="W0", type="float", default=7.0, help="Dimension-less depth of the King potential (W0) [%default]") return result if __name__ in ('__main__', '__plot__'): set_printing_strategy("custom", # nbody_converter = converter, preferred_units=[units.MSun, units.RSun, units.yr], precision=4, prefix="", separator=" [", suffix="]") o, arguments = new_option_parser().parse_args() main(**o.__dict__)
3,582
37.117021
88
py
amuse
amuse-main/examples/tutorial/CDG_gd_Galaxy_imf_se.py
""" Nbody integration of N particles in N-body units from t=0 to t_end=1 N-body time units. The initial cluster is a King (1966) model with dimension-less depth of the potential of W0=7. The initial distribution of stars is in virial equilibrium. At this moment a 4th order Hermite integrator is used for the integration. """ from amuse.lab import * from amuse.couple import bridge from galaxy_model import MilkyWay_galaxy def main(Ncl, rcl, W0, Rgal, vgal, t_end, n_steps): masses = new_salpeter_mass_distribution( Ncl, 1 | units.MSun, 100 | units.MSun) converter = nbody_system.nbody_to_si(masses.sum(), rcl) bodies = new_king_model(Ncl, W0, convert_nbody=converter) bodies.mass = masses bodies.scale_to_standard(convert_nbody=converter) stellar = SeBa() stellar.particles.add_particles(bodies) channel_from_stellar_to_framework = stellar.particles.new_channel_to( bodies) channel_from_stellar_to_framework.copy() bodies.x += Rgal bodies.vy += vgal CDG = BHTree(converter) CDG.particles.add_particles(bodies) channel_from_gravity_to_framework = CDG.particles.new_channel_to(bodies) gravity = bridge.Bridge() gravity.add_system(CDG, (MilkyWay_galaxy(),)) dt = t_end/float(n_steps) gravity.timestep = dt filename = "nbody.hdf5" write_set_to_file(bodies.savepoint(0.0 | t_end.unit), filename, "hdf5", append_to_file=False) Etot_init = gravity.kinetic_energy + gravity.potential_energy Etot_prev = Etot_init time = zero dt = t_end/float(n_steps) while time < t_end: time += dt stellar.evolve_model(time) channel_from_stellar_to_framework.copy() gravity.evolve_model(time) channel_from_gravity_to_framework.copy() write_set_to_file(bodies.savepoint(time), filename, "hdf5") Ekin = gravity.kinetic_energy Epot = gravity.potential_energy Etot = Ekin + Epot print "T=", time, "M=", bodies.mass.sum(), print "E= ", Etot, "Q= ", Ekin/Epot, print "dE=", (Etot_init-Etot)/Etot, "ddE=", (Etot_prev-Etot)/Etot Etot_prev = Etot gravity.stop() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-N", dest="Ncl", type="int", default=100, help="number of stars [%default]") result.add_option("-t", unit=units.Gyr, dest="t_end", type="float", default=1 | units.Gyr, help="end time of the simulation [%default]") result.add_option("-n", dest="n_steps", type="float", default=300, help="number of diagnostics output steps [%default]") result.add_option("-r", unit=units.parsec, dest="rcl", type="float", default=100 | units.parsec, help="cluster half-mass radius [%default]") result.add_option("-R", unit=units.kpc, dest="Rgal", type="float", default=8.5 | units.kpc, help="distance to the GC [%default]") result.add_option("-v", unit=units.kms, dest="vgal", type="float", default=100 | units.kms, help="orbital velocity of the CDG [%default]") result.add_option("-W", dest="W0", type="float", default=7.0, help="Dimension-less depth of the King potential (W0) [%default]") return result if __name__ in ('__main__', '__plot__'): set_printing_strategy("custom", # nbody_converter = converter, preferred_units=[units.MSun, units.parsec, units.Myr], precision=4, prefix="", separator=" [", suffix="]") o, arguments = new_option_parser().parse_args() main(**o.__dict__)
3,909
36.596154
88
py
amuse
amuse-main/examples/tutorial/plot_stellar.py
""" Visualization for simple N-body integration. Reads particle set from file (stellar.hdf5) and prints subsequent frames. """ # import sys # import numpy from matplotlib import pyplot from amuse.plot import scatter from amuse.lab import * from optparse import OptionParser 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 new_option_parser(): result = OptionParser() result.add_option("-f", dest="filename", default="stellar.hdf5", help="output filename [stellar.hdf5]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
1,489
29.408163
76
py
amuse
amuse-main/examples/tutorial/plot_cluster.py
""" Visualization for simple N-body integration. Reads particle set from file (nbody.hdf5) and prints subsequent frames. """ from matplotlib import pyplot from amuse.plot import scatter, xlabel, ylabel from amuse.io import store from optparse import OptionParser 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 new_option_parser(): result = OptionParser() result.add_option("-f", dest="filename", default="nbody.hdf5", help="output filename [nbody.hdf5]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
1,289
29
74
py
amuse
amuse-main/examples/tutorial/CDG_gd_Galaxy.py
from amuse.lab import * from amuse.couple import bridge from galaxy_model import MilkyWay_galaxy def main(Ncl, mcl, rcl, W0, Rgal, vgal, t_end, n_steps): converter = nbody_system.nbody_to_si(mcl, rcl) bodies = new_king_model(Ncl, W0, convert_nbody=converter) bodies.x += Rgal bodies.vy += vgal CDG = BHTree(converter) CDG.particles.add_particles(bodies) channel_from_gravity_to_framework = CDG.particles.new_channel_to(bodies) gravity = bridge.Bridge() gravity.add_system(CDG, (MilkyWay_galaxy(),)) dt = t_end/float(n_steps) gravity.timestep = dt filename = "nbody.hdf5" write_set_to_file(bodies.savepoint(0.0 | t_end.unit), filename, "hdf5", append_to_file=False) Etot_init = gravity.kinetic_energy + gravity.potential_energy Etot_prev = Etot_init time = zero dt = t_end/float(n_steps) while time < t_end: time += dt gravity.evolve_model(time) channel_from_gravity_to_framework.copy() write_set_to_file(bodies.savepoint(time), filename, "hdf5") Ekin = gravity.kinetic_energy Epot = gravity.potential_energy Etot = Ekin + Epot print "T=", time, "M=", bodies.mass.sum(), print "E= ", Etot, "Q= ", Ekin/Epot, print "dE=", (Etot_init-Etot)/Etot, "ddE=", (Etot_prev-Etot)/Etot Etot_prev = Etot gravity.stop() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-N", dest="Ncl", type="int", default=100, help="number of stars [%default]") result.add_option("-t", unit=units.Gyr, dest="t_end", type="float", default=1 | units.Gyr, help="end time of the simulation [%default]") result.add_option("-n", dest="n_steps", type="float", default=300, help="number of diagnostics output steps [%default]") result.add_option("-m", unit=units.parsec, dest="mcl", type="float", default=10**7 | units.MSun, help="cluster mass [%default]") result.add_option("-r", unit=units.parsec, dest="rcl", type="float", default=100 | units.parsec, help="cluster half-mass radius [%default]") result.add_option("-R", unit=units.kpc, dest="Rgal", type="float", default=8.5 | units.kpc, help="distance to the GC [%default]") result.add_option("-v", unit=units.parsec, dest="vgal", type="float", default=100 | units.kms, help="orbital velocity of the CDG [%default]") result.add_option("-W", dest="W0", type="float", default=7.0, help="Dimension-less depth of the King potential (W0) [%default]") return result if __name__ in ('__main__', '__plot__'): set_printing_strategy("custom", # nbody_converter = converter, preferred_units=[units.MSun, units.RSun, units.yr], precision=4, prefix="", separator=" [", suffix="]") o, arguments = new_option_parser().parse_args() main(**o.__dict__)
3,238
37.105882
88
py
amuse
amuse-main/examples/tutorial/CDG_gd_imf.py
from amuse.lab import * def main(Ncl, rcl, W0, t_end, n_steps): masses = new_salpeter_mass_distribution( Ncl, 0.1 | units.MSun, 100 | units.MSun) converter = nbody_system.nbody_to_si(masses.sum(), rcl) bodies = new_king_model(Ncl, W0, convert_nbody=converter) bodies.mass = masses bodies.scale_to_standard(convert_nbody=converter) gravity = BHTree(converter) gravity.particles.add_particles(bodies) channel_from_gravity_to_framework = gravity.particles.new_channel_to( bodies) filename = "nbody.hdf5" write_set_to_file(bodies.savepoint(0.0 | t_end.unit), filename, "hdf5", append_to_file=False) Etot_init = gravity.kinetic_energy + gravity.potential_energy Etot_prev = Etot_init time = zero dt = t_end/float(n_steps) while time < t_end: time += dt gravity.evolve_model(time) channel_from_gravity_to_framework.copy() write_set_to_file(bodies.savepoint(time), filename, "hdf5") Ekin = gravity.kinetic_energy Epot = gravity.potential_energy Etot = Ekin + Epot print "T=", time, "M=", bodies.mass.sum(), print "E= ", Etot, "Q= ", Ekin/Epot, print "dE=", (Etot_init-Etot)/Etot, "ddE=", (Etot_prev-Etot)/Etot Etot_prev = Etot gravity.stop() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-N", dest="Ncl", type="int", default=100, help="number of stars [%default]") result.add_option("-t", unit=units.Myr, dest="t_end", type="float", default=1 | units.Gyr, help="end time of the simulation [%default]") result.add_option("-n", dest="n_steps", type="float", default=100, help="number of diagnostics output steps [%default]") result.add_option("-r", unit=units.parsec, dest="rcl", type="float", default=10 | units.parsec, help="cluster half-mass radius [%default]") result.add_option("-W", dest="W0", type="float", default=7.0, help="Dimension-less depth of the King potential (W0) [%default]") return result if __name__ in ('__main__', '__plot__'): set_printing_strategy("custom", # nbody_converter = converter, preferred_units=[units.MSun, units.RSun, units.yr], precision=4, prefix="", separator=" [", suffix="]") o, arguments = new_option_parser().parse_args() main(**o.__dict__)
2,625
35.472222
88
py
amuse
amuse-main/examples/tutorial/parallel_amuse_script.py
import time import numpy from amuse.lab import Huayno from amuse.lab import Hermite from amuse.lab import nbody_system from amuse.lab import new_king_model from matplotlib import pyplot def gravity_minimal(bodies, t_end, nproc): gravity = Hermite(number_of_workers=nproc) gravity.particles.add_particles(bodies) Etot_init = gravity.kinetic_energy + gravity.potential_energy start_time = time.time() gravity.evolve_model(t_end) dtime = time.time() - start_time Ekin = gravity.kinetic_energy Epot = gravity.potential_energy Etot = Ekin + Epot dE = (Etot_init-Etot)/Etot print() print("T =", gravity.get_time(), " CPU time:", dtime, "[s]") print("M =", bodies.mass.sum(), " E = ", Etot, " Q = ", -Ekin/Epot) print("dE =", dE) gravity.stop() return dtime if __name__ in ('__main__'): N = 1024 W0 = 7.0 t_end = 0.1 | nbody_system.time bodies = new_king_model(N, W0) bodies.scale_to_standard() nproc= 6 proc = numpy.arange(1, nproc+1, 1) tcpu = [] for npi in proc: tcpu.append(gravity_minimal(bodies, t_end, npi)) pyplot.scatter(proc, tcpu) pyplot.xlabel("n proc") pyplot.ylabel("CPU time [s]") pyplot.savefig("fig_parallel_performance_N1k_Hermite.pdf")
1,293
24.372549
71
py
amuse
amuse-main/examples/applications/mercury_solarsystem2.py
import numpy from amuse.community.mercury.interface import MercuryWayWard from amuse.ext.solarsystem import new_solar_system_for_mercury from amuse.units import units from amuse.plot import ( plot, native_plot, ) try: from matplotlib import pyplot HAS_MATPLOTLIB = True except ImportError: HAS_MATPLOTLIB = False 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() if __name__ == "__main__": planetplot()
1,116
23.822222
62
py
amuse
amuse-main/examples/applications/test_stellar_merger.py
import os.path from amuse.test.amusetest import get_path_to_results try: from matplotlib import pyplot HAS_MATPLOTLIB = True from amuse.plot import plot, semilogy, xlabel, ylabel except ImportError: HAS_MATPLOTLIB = False from amuse.units import units from amuse.units import constants from amuse.units.generic_unit_converter import ConvertBetweenGenericAndSiUnits from amuse.support.exceptions import AmuseException from amuse.community.mesa.interface import MESA # from amuse.community.gadget2.interface import Gadget2 from amuse.community.fi.interface import Fi from amuse.ext.star_to_sph import ( convert_stellar_model_to_SPH, pickle_stellar_model, StellarModel2SPH ) from optparse import OptionParser import numpy from amuse.datamodel import Particles from amuse.datamodel import ParticlesSuperset from amuse.datamodel import Grid def slowtest1(): head_on_stellar_merger() def head_on_stellar_merger( masses=[0.3, 3.0] | units.MSun, star_age=310.0 | units.Myr, maximally_evolved_stars=False, initial_separation=4.0 | units.RSun, angle=numpy.pi / 3, initial_speed=3000.0 | units.km / units.s, initial_speed_perpendicular=30.0 | units.km / units.s, number_of_sph_particles=1000, t_end=1.0e4 | units.s, sph_code=Fi, steps_per_snapshot=4, snapshot_size=100, use_stored_stellar_models=True ): """ masses: Mass of the two stars star_age: Initial age of the stars (if maximally_evolved_stars is False) maximally_evolved_stars: Evolve stars as far as the Stellar Evolution code can get number_of_sph_particles: Total number of particles of both stars, divided according to their masses t_end: (Physical, not computational) duration of the hydrodynamics simulation sph_code: Code to use for the hydrodynamics simulation steps_per_snapshot: A hydroplot snapshot is generated each time after this many steps (0 or None means no snapshots) snapshot_size: Size of the snapshot in pixels along one dimension use_stored_stellar_models: Flag to use previously stored stellar model files (for speed-up). """ # Convert some of the input parameters to string, for use in output file # names: n_string = "n" + ("%1.0e" % (number_of_sph_particles) ).replace("+0", "").replace("+", "") t_end_string = "t" + ("%1.0e" % (t_end.value_in(units.s)) ).replace("+0", "").replace("+", "") masses_string = ( "m1_" + ( "%0.3e" % (masses[0].value_in(units.MSun)) ).replace("+0", "").replace("+", "") + "_m2_" + ( "%0.3e" % (masses[1].value_in(units.MSun)) ).replace("+0", "").replace("+", "") ) if maximally_evolved_stars: star_age_string = "a_max" else: star_age_string = "a" + \ ("%0.3e" % (star_age.value_in(units.Myr))).replace( "+0", "").replace("+", "") base_output_file_name = os.path.join( get_path_to_results(), "stellar_merger_"+n_string+"_"+t_end_string) pickle_file_1 = os.path.join(get_path_to_results( ), "stellar_merger_"+masses_string+"_"+star_age_string+"_1.pkl") pickle_file_2 = os.path.join(get_path_to_results( ), "stellar_merger_"+masses_string+"_"+star_age_string+"_2.pkl") if not use_stored_stellar_models or not (os.path.exists(pickle_file_1) and os.path.exists(pickle_file_2)): stars = Particles(2) stars.mass = masses try: stellar_evolution = MESA() stellar_evolution.initialize_code() except: print("MESA was not built. Returning.") return stellar_evolution.commit_parameters() stellar_evolution.particles.add_particles(stars) stellar_evolution.commit_particles() if maximally_evolved_stars: try: while True: stellar_evolution.evolve_model() except AmuseException as exception: print(exception) else: stellar_evolution.evolve_model(star_age) if os.path.exists(pickle_file_1): print("Could not save stellar model 1: file already exists.") else: pickle_stellar_model(stellar_evolution.particles[0], pickle_file_1) print("Stellar model 1 saved at:", pickle_file_1) if os.path.exists(pickle_file_2): print("Could not save stellar model 2: file already exists.") else: pickle_stellar_model(stellar_evolution.particles[1], pickle_file_2) print("Stellar model 2 saved at:", pickle_file_2) stellar_evolution.stop() model_1 = StellarModel2SPH(None, None, pickle_file=pickle_file_1) model_2 = StellarModel2SPH(None, None, pickle_file=pickle_file_2) model_1.unpickle_stellar_structure() model_2.unpickle_stellar_structure() composition = model_2.composition_profile midpoints = model_2.midpoints_profile[1:-1] specific_internal_energy = model_2.specific_internal_energy_profile number_of_sph_particles_1 = int( round( number_of_sph_particles * (model_1.mass / (model_1.mass + model_2.mass)) ) ) number_of_sph_particles_2 = ( number_of_sph_particles - number_of_sph_particles_1 ) print("Creating initial conditions from a MESA stellar evolution model:") print( model_1.mass, "star consisting of", number_of_sph_particles_1, "particles." ) sph_particles_1 = convert_stellar_model_to_SPH( None, number_of_sph_particles_1, seed=12345, pickle_file = pickle_file_1 ).gas_particles print( model_2.mass, "star consisting of", number_of_sph_particles_2, "particles." ) sph_particles_2 = convert_stellar_model_to_SPH( None, number_of_sph_particles_2, pickle_file=pickle_file_2 ).gas_particles initial_separation += model_1.radius + model_2.radius sph_particles_2.x += numpy.cos(angle) * initial_separation sph_particles_2.y += numpy.sin(angle) * initial_separation sph_particles_1.vx += ( numpy.cos(angle) * initial_speed - numpy.sin(angle) * initial_speed_perpendicular ) sph_particles_1.vy += ( numpy.cos(angle) * initial_speed_perpendicular + numpy.sin(angle) * initial_speed ) view = ( [-0.5, 0.5, -0.5, 0.5] * (initial_separation + model_1.radius + model_2.radius) ) all_sph_particles = ParticlesSuperset([sph_particles_1, sph_particles_2]) all_sph_particles.move_to_center() unit_converter = ConvertBetweenGenericAndSiUnits( 1.0 | units.RSun, constants.G, t_end) hydro_legacy_code = sph_code(unit_converter) n_steps = 100 hydro_legacy_code.parameters.n_smooth = 96 try: hydro_legacy_code.parameters.timestep = t_end / n_steps except Exception as exc: if "parameter is read-only" not in str(exc): raise hydro_legacy_code.gas_particles.add_particles(all_sph_particles) times = [] | units.Myr kinetic_energies = [] | units.J potential_energies = [] | units.J thermal_energies = [] | units.J print("Evolving to:", t_end) for time, i_step in [(i*t_end/n_steps, i) for i in range(1, n_steps+1)]: hydro_legacy_code.evolve_model(time) times.append(time) kinetic_energies.append(hydro_legacy_code.kinetic_energy) potential_energies.append(hydro_legacy_code.potential_energy) thermal_energies.append(hydro_legacy_code.thermal_energy) if steps_per_snapshot and (not i_step % steps_per_snapshot): hydro_plot( view, hydro_legacy_code, (snapshot_size, snapshot_size), base_output_file_name + "_hydro_image{0:=03}.png".format(i_step) ) hydro_legacy_code.gas_particles.new_channel_to( all_sph_particles ).copy_attributes( ['mass', 'x', 'y', 'z', 'vx', 'vy', 'vz', 'u'] ) center_of_mass = all_sph_particles.center_of_mass( ).as_quantity_in(units.RSun) center_of_mass_velocity = all_sph_particles.center_of_mass_velocity( ).as_quantity_in(units.km / units.s) print() print("center_of_mass:", center_of_mass) print("center_of_mass_velocity:", center_of_mass_velocity) all_sph_particles.position -= center_of_mass sph_midpoints = all_sph_particles.position.lengths() energy_plot( times, kinetic_energies, potential_energies, thermal_energies, base_output_file_name+"_energy_evolution.png" ) thermal_energy_plot( times, thermal_energies, base_output_file_name+"_thermal_energy_evolution.png" ) composition_comparison_plot( midpoints, composition[0], sph_midpoints, all_sph_particles.h1, base_output_file_name+"_composition_h1.png" ) internal_energy_comparison_plot( midpoints, specific_internal_energy, sph_midpoints, all_sph_particles.u, base_output_file_name+"_new_u.png" ) hydro_plot( [-2.0, 2.0, -2.0, 2.0] | units.RSun, hydro_legacy_code, (100, 100), base_output_file_name + "_hydro_image.png" ) hydro_legacy_code.stop() print("All done!\n") 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_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 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 hydro_plot(view, hydro_code, image_size, figname): """ view: the (physical) region to plot [xmin, xmax, ymin, ymax] hydro_code: hydrodynamics code in which the gas to be plotted is defined image_size: size of the output image in pixels (x, y) """ if not HAS_MATPLOTLIB: return shape = (image_size[0], image_size[1], 1) size = image_size[0] * image_size[1] axis_lengths = [0.0, 0.0, 0.0] | units.m axis_lengths[0] = view[1] - view[0] axis_lengths[1] = view[3] - view[2] grid = Grid.create(shape, axis_lengths) grid.x += view[0] grid.y += view[2] speed = grid.z.reshape(size) * (0 | 1/units.s) rho, rhovx, rhovy, rhovz, rhoe = hydro_code.get_hydro_state_at_point( grid.x.reshape(size), grid.y.reshape(size), grid.z.reshape(size), speed, speed, speed) min_v = 800.0 | units.km / units.s max_v = 3000.0 | units.km / units.s min_rho = 3.0e-4 | units.g / units.cm**3 max_rho = 0.1 | units.g / units.cm**3 min_E = 1.0e11 | units.J / units.kg max_E = 1.0e13 | units.J / units.kg v_sqr = (rhovx**2 + rhovy**2 + rhovz**2) / rho**2 E = rhoe / rho log_v = numpy.log((v_sqr / min_v**2)) / numpy.log((max_v**2 / min_v**2)) log_rho = numpy.log((rho / min_rho)) / numpy.log((max_rho / min_rho)) log_E = numpy.log((E / min_E)) / numpy.log((max_E / min_E)) red = numpy.minimum(numpy.ones_like(rho.number), numpy.maximum( numpy.zeros_like(rho.number), log_rho)).reshape(shape) green = numpy.minimum(numpy.ones_like(rho.number), numpy.maximum( numpy.zeros_like(rho.number), log_v)).reshape(shape) blue = numpy.minimum(numpy.ones_like(rho.number), numpy.maximum( numpy.zeros_like(rho.number), log_E)).reshape(shape) alpha = numpy.minimum( numpy.ones_like(log_v), numpy.maximum( numpy.zeros_like(log_v), numpy.log((rho / (10*min_rho))) ) ).reshape(shape) rgba = numpy.concatenate((red, green, blue, alpha), axis=2) pyplot.figure(figsize=(image_size[0]/100.0, image_size[1]/100.0), dpi=100) im = pyplot.figimage(rgba, origin='lower') pyplot.savefig(figname, transparent=True, dpi=100) print("\nHydroplot was saved to: ", figname) pyplot.close() def new_option_parser(): result = OptionParser() result.add_option( "-n", "--n_sph", dest="number_of_sph_particles", type="int", default=300, help="Number of sph particles per star in solar mass" ) result.add_option( "-a", "--mass1", dest="mass1", type="float", default=1.0, help="Mass of the first star" ) result.add_option( "-b", "--mass2", dest="mass2", type="float", default=1.0, help="Mass of the second star in solar mass" ) result.add_option( "-d", "--distance", dest="initial_separation", type="float", default=4.0, help="Initial_separation between the two stars in solar radii" ) result.add_option( "-v", "--speed", dest="initial_speed", type="float", default=100.0, help="Initial relative speed between the two stars in km/s" ) result.add_option( "-t", "--end_time", dest="end_time", type="float", default=2.0e4, help="Time to evolve to in s" ) result.add_option( "-s", "--t_star", dest="t_star", type="float", default=1.0e4, help="Age of both stars in Myr" ) result.add_option( "-e", "--max_evolved", default=False, action="store_true", dest="maximally_evolved_stars", help="Flag to use maximally evolved stars, i.e. until MESA exits" ) return result if __name__ == "__main__": options, arguments = new_option_parser().parse_args() print("Simulating a head on collision between two stars.") print("Options used:", options) masses = [options.mass1, options.mass2] | units.MSun head_on_stellar_merger( masses=masses, star_age=options.t_star | units.Myr, initial_separation=options.initial_separation | units.RSun, initial_speed=options.initial_speed | units.km / units.s, number_of_sph_particles=options.number_of_sph_particles, t_end=options.end_time | units.s, maximally_evolved_stars=options.maximally_evolved_stars )
16,140
33.342553
110
py
amuse
amuse-main/examples/applications/job_server_example.py
from amuse.ext.job_server import JobServer from time import sleep import sys def somework(x): sleep(0.5) return x*x def example_parallel_jobs_1(N): # from socket import gethostname jobserver = JobServer(["localhost"]*2, channel_type="mpi") print() for i in range(N): jobserver.submit_job(somework, (i,)) i = 0 while jobserver.wait(): job = jobserver.last_finished_job print(job.args[0], job.result) def example_parallel_jobs_2(N): # from socket import gethostname jobserver = JobServer(["localhost"]*2, channel_type="mpi") print() for i in range(N): jobserver.submit_job(somework, (i,)) print("waiting") jobserver.waitall() print("done") for job in jobserver.finished_jobs: print(job.args[0], job.result) if __name__ == "__main__": # this is needed in order for all the functions and classes to be # pickled with full module name from job_server_example import ( example_parallel_jobs_1, example_parallel_jobs_2 ) example_parallel_jobs_1(10) example_parallel_jobs_2(10)
1,132
21.66
69
py
amuse
amuse-main/examples/applications/vader_gidisk.py
import numpy as np import matplotlib.pyplot as plt import scipy.constants as physcons from amuse.units import units from amuse.community.vader.interface import Vader G = physcons.G*1e3 | units.cm**3 / units.g / units.s**2 def setup_vader (params): torb = 2.*np.pi*params['R_out']/params['vphi'] chi = G*params['mdot']/params['vphi']**3 s = 1./2.**0.5 * (chi/params['eta'])**(1./3.) h_steady = params['gamma']/(params['gamma']-1.) * (s*params['vphi'])**2 torb = 2.*np.pi*params['R_out']/params['vphi'] viscous = Vader(mode='gidisk', redirection='none') viscous.parameters.alpha_function = True viscous.parameters.inner_pressure_boundary_type = 3 viscous.parameters.inner_boundary_function = True viscous.parameters.outer_pressure_boundary_type = 1 viscous.parameters.outer_pressure_boundary_mass_flux = -params['mdot'] viscous.parameters.outer_enthalpy_boundary_enthalpy = h_steady * \ params['obc_vdisp']**2 / params['init_col'] viscous.parameters.gamma = params['gamma'] viscous.parameters.internal_energy_source_function = True viscous.parameters.number_of_user_parameters = 3 viscous.parameters.verbosity = 1 viscous.parameters.initial_timestep = params['dt_init'] * torb viscous.initialize_flat_grid(512, False, 3.09e20|units.cm, params['R_out'], params['vphi']) viscous.set_parameter(0, params['eta']) viscous.set_parameter(1, chi) viscous.set_parameter(2, params['t_Q']) return viscous def setup_initial_conditions (viscous, params): chi = G*params['mdot']/params['vphi']**3 s = 1./2.**0.5 * (chi/params['eta'])**(1./3.) col1 = params['vphi']**2 * (chi/params['eta'])**(1./3.) / \ (np.pi*G*params['R_out']) colSteady = col1 * (params['R_out']/viscous.grid.r) presSteady = colSteady * (s*params['vphi'])**2 col = colSteady * params['init_col'] pres = presSteady * params['init_col'] * params['init_vdisp']**2 viscous.grid.column_density = col viscous.grid.pressure = pres def run_gidisk (params): viscous = setup_vader(params) setup_initial_conditions(viscous, params) grid_copy = viscous.grid.copy() ch_from_code = viscous.grid.new_channel_to(grid_copy) fig = plt.figure() ax1 = fig.add_subplot(311) ax2 = fig.add_subplot(312) ax3 = fig.add_subplot(313) ax1.plot(grid_copy.r/params['R_out'], params['R_out']/grid_copy.r, c='k', linestyle='--', label='Steady state', lw=4) ax2.plot(grid_copy.r/params['R_out'], np.ones(len(grid_copy.r))*2.**-0.5 * \ (G*params['mdot']/params['vphi']**3/params['eta'])**(1./3.), c='k', linestyle='--', lw=4) ax3.plot(grid_copy.r/params['R_out'], np.ones(len(grid_copy.r)), c='k', linestyle='--', lw=4) ax1.plot(grid_copy.r/params['R_out'], grid_copy.column_density/grid_copy.column_density[-1], c='b', label='Simulation, $T=${a}'.format(a=0.)) ax2.plot(grid_copy.r/params['R_out'], (grid_copy.pressure/grid_copy.column_density)**0.5/params['vphi'], c='b') Q = 2.**0.5 * grid_copy.rotational_velocity/grid_copy.r * \ (grid_copy.pressure/grid_copy.column_density)**0.5 / \ (np.pi*G*grid_copy.column_density) ax3.plot(grid_copy.r/params['R_out'], Q, c='b') torb = 2.*np.pi*params['R_out']/params['vphi'] times = np.array([0.001, 0.1, 1.]) * torb colors = ['g', 'r', 'c'] for i in range(len(times)): viscous.evolve_model( times[i] ) ch_from_code.copy() ax1.plot(grid_copy.r/params['R_out'], grid_copy.column_density/grid_copy.column_density[-1], c=colors[i], label='Simulation, $T=${a}'.format(a=times[i]/torb)) ax2.plot(grid_copy.r/params['R_out'], (grid_copy.pressure/grid_copy.column_density)**0.5/params['vphi'], c=colors[i]) Q = 2.**0.5 * grid_copy.rotational_velocity/grid_copy.r * \ (grid_copy.pressure/grid_copy.column_density)**0.5 / \ (np.pi*G*grid_copy.column_density) ax3.plot(grid_copy.r/params['R_out'], Q, c=colors[i]) ax1.set_xscale('log') ax1.set_yscale('log') ax2.set_xscale('log') ax2.set_yscale('log') ax3.set_xscale('log') ax1.set_xlim(1e-2, 1e0) ax1.set_ylim(1e0, 3e3) ax2.set_xlim(1e-2, 1e0) ax2.set_ylim(1e-2, 2e-1) ax3.set_xlim(1e-2, 1e0) ax3.set_ylim(0., 2.5) ax3.set_xlabel('$r/R$') ax1.set_ylabel('$\\Sigma/\\Sigma(R)$') ax2.set_ylabel('$\\sigma/v_\\phi$') ax3.set_ylabel('$Q$') ax1.axes.get_xaxis().set_visible(False) ax2.axes.get_xaxis().set_visible(False) ax1.legend(loc='upper right', ncol=2, frameon=False) plt.subplots_adjust(hspace=0) plt.savefig('KrumholzForbes2015_Fig6.pdf') if __name__ == '__main__': params = { 'eta': 1.5, 'n_orbit': 4., 't_Q': 1., 'init_col': 1., 'init_vdisp': 0.5, 'obc_vdisp': 0.5, 'dt_init': 1e-5, 'gamma': 1.666666666667, 'vphi': 2.2e7 | units.cm/units.s, 'mdot': 6.3e25 | units.g/units.s, 'R_out': 3.09e22 | units.cm, } print ("Reproduction of Figure 6 in Krumholz & Forbes 2015") run_gidisk(params)
5,262
29.598837
81
py
amuse
amuse-main/examples/applications/distributed_amuse.py
#!/usr/bin/python import sys # import webbrowser from amuse.units import units from amuse.community.distributed.interface import ( # DistributedAmuseInterface, DistributedAmuse ) from amuse.community.distributed.interface import ( # Resource, # Resources, Pilot, # Pilots, ) # Example on how to use the distributed code. This example should run most (if # not all) existing scripts. # This example only uses local resources to run on. Add remote resources to get # it to do something interesting. if (len(sys.argv) < 2): print("usage: amuse.sh distributed_amuse.py existing_amuse_script.py") sys.exit(1) print("Setting up distributed code") instance = DistributedAmuse(redirection='none') instance.initialize_code() # open the address of the webinterface in a brower window # webbrowser.open(instance.get_webinterface_url()) # Add some resources # resource = Resource() # resource.name='DAS4-VU' # resource.location="user@fs0.das4.cs.vu.nl" # resource.scheduler_type="sge" # resource.amuse_dir="/home/user/amuse" # instance.resources.add_resource(resource) print("Resources:") print(instance.resources) # Claim nodes on the resources. In this example simply the "local" machine pilot = Pilot() pilot.resource_name = 'local' pilot.node_count = 1 pilot.time = 2 | units.hour pilot.slots_per_node = 22 pilot.label = 'local' instance.pilots.add_pilot(pilot) print("Pilots:") print(instance.pilots) print("Waiting for pilots") instance.wait_for_pilots() print("setting distributed as default channel") instance.use_for_all_workers() print("Running script") script = sys.argv[1] sys.argv = sys.argv[1:] if sys.hexversion > 0x03000000: exec(compile(open(script).read(), script, 'exec')) else: execfile(script) print("script done, stopping distributed code") instance.stop()
1,862
24.175676
79
py
amuse
amuse-main/examples/applications/validate_bridge.py
""" first test of Fujii et al 2007 (not yet fully checked) """ # import numpy import os from amuse.io import store from amuse.units import (nbody_system, units) # from amuse.units import constants # from amuse.community.hermite.interface import Hermite from amuse.community.phigrape.interface import PhiGRAPE from amuse.community.bhtree.interface import BHTree from amuse.community.fi.interface import Fi from amuse.ext.bridge import bridge from amuse.ext.derived_grav_systems import copycat from amuse.ic.kingmodel import new_king_model def sys_from_parts( base_class, parts, converter, eps=None, timestep=None, usegl=False, mode=None): if mode is None: if usegl: interface = base_class(converter, use_gl=True) else: interface = base_class(converter) else: if usegl: interface = base_class(converter, use_gl=True, mode=mode) else: interface = base_class(converter, mode=mode) interface.initialize_code() if eps is not None: interface.parameters.epsilon_squared = eps**2 if timestep is not None: interface.parameters.timestep = timestep interface.particles.add_particles(parts) return interface def sys_from_king(base_class, N, W, converter, eps=None, timestep=None, usegl=False, mode=None): parts = new_king_model(N, W0=W, convert_nbody=converter) parts.radius = 0. | nbody_system.length return sys_from_parts( base_class, parts, converter, eps, timestep, usegl, mode) def shift_sys(system, dx, dy, dz, dvx, dvy, dvz): parts = system.particles.copy() parts.x = parts.x+dx parts.y = parts.y+dy parts.z = parts.z+dz parts.vx = parts.vx+dvx parts.vy = parts.vy+dvy parts.vz = parts.vz+dvz parts.copy_values_of_all_attributes_to(system.particles) def validate_bridge(): convert_clu = nbody_system.nbody_to_si( 1.e5 | units.MSun, 1.0 | units.parsec) convert_gal = nbody_system.nbody_to_si( 1.e7 | units.MSun, 10. | units.parsec) def convert_gal_to_clu(x): return convert_clu.to_nbody( convert_gal.to_si(x)) def convert_clu_to_gal(x): return convert_gal.to_nbody( convert_clu.to_si(x)) total_sim_time = convert_clu_to_gal(200 | nbody_system.time) total_sim_time = 200 | nbody_system.time sim_step = 1./128 | nbody_system.time dt_diag = 1./64 | nbody_system.time eps_clu = convert_gal_to_clu(2.e-4 | nbody_system.length) eps_gal = 6.25e-3 | nbody_system.length cluster = sys_from_king(PhiGRAPE, 1000, 7, convert_clu, eps_clu, usegl=False, mode="gpu") galaxy = sys_from_king(Fi, 10000, 9, convert_gal, eps_gal, sim_step, usegl=False) shift_sys( cluster, convert_clu.to_si( convert_gal_to_clu( 2.5 | nbody_system.length ) ), 0 | units.m, 0 | units.m, 0 | units.m/units.s, convert_clu.to_si( convert_gal_to_clu(0.65 | nbody_system.speed) ), 0 | units.m/units.s) if hasattr(cluster, "start_viewer"): cluster.start_viewer() if hasattr(galaxy, "viewer"): galaxy.viewer() clustercopy = copycat(BHTree, cluster, convert_clu) bridgesys = bridge(verbose=False) bridgesys.add_system(galaxy, (clustercopy,), False) bridgesys.add_system(cluster, (galaxy,), True) t = 0. | nbody_system.time if os.path.exists("cluster.hdf"): os.remove("cluster.hdf") storage = store.StoreHDF("cluster.hdf") bridgesys.synchronize_model() Ep0 = bridgesys.potential_energy Ek0 = bridgesys.kinetic_energy Esp0 = cluster.kinetic_energy Esk0 = cluster.potential_energy tc = cluster.model_time tg = galaxy.model_time print(convert_gal.to_nbody(tg)) print(0.) # print Ep0,Ek0 # print Esp0,Esk0 for x in cluster.get_center_of_mass_position(): print(convert_gal.to_nbody(x), end=' ') print() part = bridgesys.particles.copy() part.savepoint(tg) storage.store(part.previous_state()) while(t < total_sim_time): t = t+dt_diag bridgesys.evolve_model(convert_gal.to_si(t), timestep=convert_gal.to_si(sim_step)) bridgesys.synchronize_model() Ep = bridgesys.potential_energy Ek = bridgesys.kinetic_energy Esp = cluster.kinetic_energy Esk = cluster.potential_energy tc = cluster.model_time tg = galaxy.model_time print(convert_gal.to_nbody(tg)) print((Ep+Ek-Ep0-Ek0)/(Ep0+Ek0)) # print (Esp+Esk-Esp0-Esk0)/(Esp0+Esk0) for x in cluster.get_center_of_mass_position(): print(convert_gal.to_nbody(x), end=' ') print() part = bridgesys.particles.copy() part.savepoint(tg) storage.store(part.previous_state()) if __name__ == '__main__': validate_bridge()
5,135
28.181818
69
py