def test1(self): print "Test collect_required_attributes" in_memory = self.new_colliders() gravity = BHTree(nbody_system.nbody_to_si(1|units.MSun, 1.0|units.RSun)) gravity.particles.add_particles(in_memory) stellar = SeBa() stellar.particles.add_particles(in_memory) collision = StellarEncounterInHydrodynamics(None, None, verbose=True) self.assertFalse(hasattr(in_memory, "radius")) collision.collect_required_attributes(in_memory, gravity, stellar) self.assertTrue(hasattr(in_memory, "radius")) self.assertAlmostRelativeEqual(in_memory.radius.sum(), 4.2458 | units.RSun, 3) from_stellar = stellar.particles.copy() for attribute in ["x", "y", "z", "vx", "vy", "vz"]: self.assertFalse(hasattr(from_stellar, attribute)) collision.collect_required_attributes(from_stellar, gravity, stellar) gravity.stop() stellar.stop() for attribute in ["x", "y", "z", "vx", "vy", "vz"]: self.assertTrue(hasattr(from_stellar, attribute)) self.assertAlmostEqual(from_stellar.position, in_memory.position) self.assertAlmostEqual(from_stellar.velocity, in_memory.velocity)
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 test1(self): print("Test collect_required_attributes") in_memory = self.new_colliders() gravity = BHTree(nbody_system.nbody_to_si(1|units.MSun, 1.0|units.RSun)) gravity.particles.add_particles(in_memory) stellar = SeBa() stellar.particles.add_particles(in_memory) collision = StellarEncounterInHydrodynamics(None, None, verbose=True) self.assertFalse(hasattr(in_memory, "radius")) collision.collect_required_attributes(in_memory, gravity, stellar) self.assertTrue(hasattr(in_memory, "radius")) self.assertAlmostRelativeEqual(in_memory.radius.sum(), 4.2458 | units.RSun, 3) from_stellar = stellar.particles.copy() for attribute in ["x", "y", "z", "vx", "vy", "vz"]: self.assertFalse(hasattr(from_stellar, attribute)) collision.collect_required_attributes(from_stellar, gravity, stellar) gravity.stop() stellar.stop() for attribute in ["x", "y", "z", "vx", "vy", "vz"]: self.assertTrue(hasattr(from_stellar, attribute)) self.assertAlmostEqual(from_stellar.position, in_memory.position) self.assertAlmostEqual(from_stellar.velocity, in_memory.velocity)
class StellarEvolutionCode: "Stellar evolution object" def __init__(self, evo_code=SeBa, logger=None, time_offset=0 | units.Myr, settings=None, **keyword_arguments): self.typestr = "Evolution" self.namestr = evo_code.__name__ self.logger = logger or logging.getLogger(__name__) self.__evo_code = evo_code self.settings = settings if evo_code is SSE: self.code = SSE( # channel_type="sockets", **keyword_arguments) elif evo_code is SeBa: self.code = SeBa(**keyword_arguments) else: self.code = evo_code(**keyword_arguments) self.parameters = self.code.parameters if time_offset is None: time_offset = 0 | units.Myr self.__time_offset = time_offset @property def particles(self): "return particles in the evolution code" return self.code.particles @property def model_time(self): "return the time of the evolution code" return self.code.model_time + self.__time_offset def evolve_model(self, tend): "Evolve stellar evolution to time and sync" print("Starting stellar evolution evolve_model to %s" % tend) result = self.code.evolve_model(tend - self.__time_offset) print("Finished stellar evolution evolve_model to %s" % tend) return result def save_state(self): """ Store current settings """ self.__state["parameters"] = self.code.parameters.copy() self.__state["evo_code"] = self.__evo_code self.__state["model_time"] = self.code.model_time self.__begin_time = self.model_time def stop( self, save_state=False, ): "Stop stellar evolution code" return self.code.stop()
def simulate_stellar_evolution(particles, endtime): stellar_evolution = SeBa() stellar_evolution.particles.add_particles(particles) from_code_to_model = stellar_evolution.particles.new_channel_to(particles) print("Evolving {0} stars using {1} up to {2}.".format(len(particles), stellar_evolution.__class__.__name__, endtime)) stellar_evolution.evolve_model(endtime) from_code_to_model.copy_all_attributes() stellar_evolution.stop()
def main(N, W0, t_end, dt, filename, Rvir, Mmin, Mmax, z): 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 bodies.scale_to_standard(convert_nbody=converter) gravity = ph4(converter) gravity.parameters.timestep_parameter = 0.01 gravity.particles.add_particles(bodies) stopping_condition = gravity.stopping_conditions.collision_detection stopping_condition.enable() stellar = SeBa() stellar.parameters.metallicity = z stellar.particles.add_particle(bodies) channel_from_se_to_framework = stellar.particles.new_channel_to(bodies) channel_from_gd_to_framework = gravity.particles.new_channel_to(bodies) channel_from_framework_to_gd = bodies.new_channel_to(gravity.particles) channel_from_se_to_framework.copy_attributes(["mass","radius", "age"]) write_set_to_file(bodies.savepoint(0|units.Myr), filename, 'hdf5') E_init = gravity.kinetic_energy + gravity.potential_energy Nenc = 0 #dE_enc = dE_dyn = dE_stellar = zero dE_coll = zero time = zero while time < t_end: time += dt bodies.radius *= 1.e+5 channel_from_framework_to_gd.copy_attributes(["mass", "radius"]) E_dyn = gravity.kinetic_energy + gravity.potential_energy gravity.evolve_model(time) dE_dyn = E_dyn - (gravity.kinetic_energy + gravity.potential_energy) resolve_collision(stopping_condition, gravity, stellar, bodies) E_stellar = gravity.kinetic_energy + gravity.potential_energy stellar.evolve_model(time) dE_stellar = E_stellar - (gravity.kinetic_energy + gravity.potential_energy) channel_from_gd_to_framework.copy() channel_from_se_to_framework.copy_attributes(["age", "mass", "radius"]) write_set_to_file(bodies.savepoint(time), filename, 'hdf5') print_diagnostics(time, bodies.mass.sum(), E_dyn, dE_dyn, dE_coll, dE_stellar) gravity.stop() stellar.stop()
def main(N=10, t_end=10|units.Myr, dt=1|units.Myr, filename="stellar.hdf5", Mmin=1.0|units.MSun, Mmax= 100|units.MSun, z=0.02, C="SeBa"): if C.find("SeBa")>=0: print "SeBa" stellar = SeBa() elif C.find("SSE")>=0: print "SSE" stellar = SSE() elif C.find("MESA")>=0: stellar = MESA() elif C.find("EVtwin")>=0: stellar = EVtwin() else: print "No stellar model specified." return stellar.parameters.metallicity = z mZAMS = new_salpeter_mass_distribution(N, Mmin, Mmax) mZAMS = mZAMS.sorted() bodies = Particles(mass=mZAMS) stellar.particles.add_particles(bodies) stellar.commit_particles() write_set_to_file(stellar.particles, filename, 'hdf5') Mtot_init = stellar.particles.mass.sum() time = 0.0 | t_end.unit while time < t_end: time += dt stellar.evolve_model(time) write_set_to_file(stellar.particles, filename, 'hdf5') Mtot = stellar.particles.mass.sum() print "T=", time, print "M=", Mtot, "dM[SE]=", Mtot/Mtot_init #, stellar.particles[0].stellar_type T = [] L = [] r = [] import math for si in stellar.particles: T.append(math.log10(si.temperature.value_in(units.K))) L.append(math.log10(si.luminosity.value_in(units.LSun))) r.append(1.0+10*si.radius.value_in(units.RSun)) stellar.stop() pyplot.xlim(4.5, 3.3) pyplot.ylim(-4.0, 3.0) scatter(T, L, s=r) pyplot.xlabel("$log_{10}(T/K)$") pyplot.ylabel("$log_{10}(L/L_\odot)$") pyplot.show()
def evolve_binary(mass_of_star1, mass_of_star2, orbital_period, eccentricity): code = SeBa() stars = Particles(2) stars[0].mass = mass_of_star1 stars[1].mass = mass_of_star2 mu = stars.mass.sum() * constants.G semi_major_axis = (((orbital_period / (2.0 * numpy.pi))**2) * mu)**(1.0 / 3.0) binaries = Particles(1) binary = binaries[0] binary.semi_major_axis = semi_major_axis binary.eccentricity = eccentricity binary.child1 = stars[0] binary.child2 = stars[1] # we add the single stars first, as the binaries will refer to these code.particles.add_particles(stars) code.binaries.add_particles(binaries) from_seba_to_model = code.particles.new_channel_to(stars) from_seba_to_model.copy() from_seba_to_model_binaries = code.binaries.new_channel_to(binaries) from_seba_to_model_binaries.copy() previous_type_child1 = binary.child1.stellar_type previous_type_child2 = binary.child2.stellar_type results = [] current_time = 0 | units.Myr while current_time < (1000 | units.Myr): code.update_time_steps() # The next line appears a bit weird, but saves time for this simple # test. deltat = max(1.0 * code.binaries[0].time_step, 0.1 | units.Myr) current_time = current_time + deltat code.evolve_model(current_time) from_seba_to_model.copy() from_seba_to_model_binaries.copy() if not binary.child1.stellar_type == previous_type_child1: print(binary.age, "Child 1, change of stellar type", previous_type_child1, ' -> ', binary.child1.stellar_type) previous_type_child1 = binary.child1.stellar_type if not binary.child2.stellar_type == previous_type_child2: print(binary.age, "Child 2, change of stellar type", previous_type_child2, ' -> ', binary.child2.stellar_type) previous_type_child2 = binary.child2.stellar_type results.append( (binary.age, binary.child1.mass, binary.child1.stellar_type, binary.child2.mass, binary.child2.stellar_type)) code.stop() return results
def evolve_to_age(stars, age, stellar_evolution="SeBa"): "Evolve stars to specified age with specified code" if stellar_evolution == "SeBa": from amuse.community.seba.interface import SeBa stellar_evolution = SeBa() elif stellar_evolution == "SSE": from amuse.community.sse.interface import SSE stellar_evolution = SSE() # SSE can result in nan values for luminosity/radius else: raise "No such stellar evolution code %s or no code specified" % ( stellar_evolution ) stellar_evolution.particles.add_particles(stars) if age > 0 | units.yr: stellar_evolution.evolve_model(age) stars.luminosity = np.nan_to_num( stellar_evolution.particles.luminosity.value_in(units.LSun) ) | units.LSun stars.radius = stellar_evolution.particles.radius # prevent zero/nan radius. x = np.where( np.nan_to_num( stars.radius.value_in(units.RSun) ) == 0. ) stars[x].radius = 0.01 | units.RSun stellar_evolution.stop() return
def evolve_binary(mass_of_star1, mass_of_star2, orbital_period, eccentricity): code = SeBa() stars = Particles(2) stars[0].mass = mass_of_star1 stars[1].mass = mass_of_star2 mu = stars.mass.sum() * constants.G semi_major_axis = (((orbital_period / (2.0 * numpy.pi))**2)*mu)**(1.0/3.0) binaries = Particles(1) binary = binaries[0] binary.semi_major_axis = semi_major_axis binary.eccentricity = eccentricity binary.child1 = stars[0] binary.child2 = stars[1] # we add the single stars first, as the binaries will refer to these code.particles.add_particles(stars) code.binaries.add_particles(binaries) from_seba_to_model = code.particles.new_channel_to(stars) from_seba_to_model.copy() from_seba_to_model_binaries = code.binaries.new_channel_to(binaries) from_seba_to_model_binaries.copy() previous_type_child1 = binary.child1.stellar_type previous_type_child2 = binary.child2.stellar_type results = [] current_time = 0 | units.Myr while current_time < (1000 | units.Myr): code.update_time_steps() # The next line appears a bit weird, but saves time for this simple # test. deltat = max(1.0*code.binaries[0].time_step, 0.1 | units.Myr) current_time = current_time + deltat code.evolve_model(current_time) from_seba_to_model.copy() from_seba_to_model_binaries.copy() if not binary.child1.stellar_type == previous_type_child1: print(binary.age, "Child 1, change of stellar type", previous_type_child1, ' -> ', binary.child1.stellar_type) previous_type_child1 = binary.child1.stellar_type if not binary.child2.stellar_type == previous_type_child2: print(binary.age, "Child 2, change of stellar type", previous_type_child2, ' -> ', binary.child2.stellar_type) previous_type_child2 = binary.child2.stellar_type results.append( (binary.age, binary.child1.mass, binary.child1.stellar_type, binary.child2.mass, binary.child2.stellar_type)) code.stop() return results
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 evolve_population(binaries, stars, end_time, time_step): code = SeBa() # add the stars first, as the binaries will # refer to them code.particles.add_particles(stars) code.binaries.add_particles(binaries) channel_from_code_to_model_for_binaries = code.binaries.new_channel_to( binaries) channel_from_code_to_model_for_stars = code.particles.new_channel_to(stars) # we evolve in steps of timestep, just to get some feedback print("start evolving...") time = 0.0 * end_time while time < end_time: time += time_step code.evolve_model(time) print("evolved to time: ", time.as_quantity_in(units.Myr)) channel_from_code_to_model_for_stars.copy() channel_from_code_to_model_for_binaries.copy()
def evolve_population(binaries, stars, end_time, time_step): code = SeBa() # add the stars first, as the binaries will # refer to them code.particles.add_particles(stars) code.binaries.add_particles(binaries) channel_from_code_to_model_for_binaries = code.binaries.new_channel_to(binaries) channel_from_code_to_model_for_stars = code.particles.new_channel_to(stars) #we evolve in steps of timestep, just to get some feedback print("start evolving...") time = 0.0 * end_time while time < end_time: time += time_step code.evolve_model(time) print("evolved to time: ", time.as_quantity_in(units.Myr)) channel_from_code_to_model_for_stars.copy() channel_from_code_to_model_for_binaries.copy()
def simulate_stellar_evolution(particles, endtime): stellar_evolution = SeBa() stellar_evolution.particles.add_particles(particles) from_code_to_model = stellar_evolution.particles.new_channel_to(particles) print("Evolving {0} stars using {1} up to {2}.".format( len(particles), stellar_evolution.__class__.__name__, endtime)) stellar_evolution.evolve_model(endtime) from_code_to_model.copy_all_attributes() stellar_evolution.stop()
def evolve_double_star(Mprim, Msec, a, e, end_time, n_steps): q = Msec / Mprim 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) channel_from_code_to_model_for_stars = code.particles.new_channel_to(stars) t = [] a = [] e = [] while time < end_time: time += time_step code.evolve_model(time) channel_from_code_to_model_for_stars.copy() channel_from_code_to_model_for_binaries.copy() t.append(time.value_in(units.Myr)) a.append(double_star[0].semi_major_axis.value_in(units.RSun)) e.append(double_star[0].eccentricity) code.stop() fig = pyplot.figure(figsize=(8, 8)) fta = fig.add_subplot(2, 1, 1) # fte = fig.add_subplot(2,2,1) pyplot.title("Binary evolution", fontsize=12) fta.plot(t, a) pyplot.xlabel("time [Myr]") pyplot.ylabel("semi major axis (AU)") # fta.plot(t, e) # pyplot.ylabel('eccentricity') pyplot.show()
def __init__(self, evo_code=SeBa, logger=None, time_offset=0 | units.Myr, settings=None, **keyword_arguments): self.typestr = "Evolution" self.namestr = evo_code.__name__ self.logger = logger or logging.getLogger(__name__) self.__evo_code = evo_code self.settings = settings if evo_code is SSE: self.code = SSE( # channel_type="sockets", **keyword_arguments) elif evo_code is SeBa: self.code = SeBa(**keyword_arguments) else: self.code = evo_code(**keyword_arguments) self.parameters = self.code.parameters if time_offset is None: time_offset = 0 | units.Myr self.__time_offset = time_offset
def main(t_end, mass, z, Tstar, Lstar): stellar_evolution_codes = [SeBa(), SSE(), MESA(), EVtwin()] label = ["SeBa", "SSE", "MESA", "EVtwin"] marker = ["o", "v", "<", ">"] # color = [0, 1, 2, 3, 4] 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.008, 0.004) color = get_distinct(6) pyplot.scatter([0], [0], marker="o", c=color[3], label="Sun", s=400, 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 stellar.particles.add_particles(star) stellar.evolve_model(t_end) T = (stellar.particles.temperature - Tstar) / Tstar L = (stellar.particles.luminosity - Lstar) / Lstar if si == 3: pyplot.scatter(T, L, marker=marker[si], color=color[0], label=label[si], s=300, lw=0) else: pyplot.scatter(T, L, marker=marker[si], color=color[si], label=label[si], s=300, lw=0) stellar.stop() pyplot.legend(scatterpoints=1, loc=2) # pyplot.show() pyplot.savefig("fig_SunComparison")
def setup_supernova(self): numpy.random.seed(123456789) stars = Particles(2) stars.mass = [9, 10] | units.MSun stars[0].position = [1, 1, 1] | units.parsec stars[1].position = [-1, -1, -1] | units.parsec stars[0].velocity = [-1000, 0, 1000] | units.ms stars[1].velocity = [0, 0, 0] | units.ms stev = SeBa() stars = stev.particles.add_particles(stars) r_max = .1 | units.parsec star_wind = stellar_wind.new_stellar_wind(3e-5 | units.MSun, mode="heating", r_max=r_max, derive_from_evolution=True, tag_gas_source=True) star_wind.particles.add_particles(stars) return stev, star_wind, stars
def gravity_and_stellar_evolution(number_of_stars, size, end_time, sync_timestep=1 | units.Myr, plot_timestep=10 | units.Myr): stars, converter = create_stars(number_of_stars, size) gravity = Hermite(converter) stellar = SeBa() bridge = Bridge() gravity.particles.add_particles(stars) stellar.particles.add_particles(stars) bridge.add_system(gravity) bridge.add_system(stellar) bridge.channels.add_channel( stellar.particles.new_channel_to(gravity.particles, attributes=["mass", "radius"])) bridge.timestep = sync_timestep plot_channels = Channels() plot_channels.add_channel(stellar.particles.new_channel_to(stars)) plot_channels.add_channel(gravity.particles.new_channel_to(stars)) time = 0 | units.Myr while time <= end_time: bridge.evolve_model(time) plot_channels.copy() plot_results(stars, time) time += plot_timestep
def evolve_double_star(Mprim, Msec, a, e, end_time, n_steps): q = Msec/Mprim 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) channel_from_code_to_model_for_stars = code.particles.new_channel_to(stars) t = [] a = [] e = [] while time < end_time: time += time_step code.evolve_model(time) channel_from_code_to_model_for_stars.copy() channel_from_code_to_model_for_binaries.copy() t.append(time.value_in(units.Myr)) a.append(double_star[0].semi_major_axis.value_in(units.RSun)) e.append(double_star[0].eccentricity) code.stop() fig = pyplot.figure(figsize = (8,8)) fta = fig.add_subplot(2,1,1) # fte = fig.add_subplot(2,2,1) pyplot.title('Binary evolution', fontsize=12) fta.plot(t, a) pyplot.xlabel('time [Myr]') pyplot.ylabel('semi major axis (AU)') # fta.plot(t, e) #pyplot.ylabel('eccentricity') pyplot.show()
def main(N=10, t_end=10 | units.Myr, dt=1 | units.Myr, filename="stellar.hdf5", Mmin=1.0 | units.MSun, Mmax=100 | units.MSun, z=0.02, C="SeBa"): if C.find("SeBa") >= 0: print("SeBa") stellar = SeBa() elif C.find("SSE") >= 0: print("SSE") stellar = SSE() elif C.find("MESA") >= 0: stellar = MESA() elif C.find("EVtwin") >= 0: stellar = EVtwin() else: print("No stellar model specified.") return stellar.parameters.metallicity = z mZAMS = new_salpeter_mass_distribution(N, Mmin, Mmax) mZAMS = mZAMS.sorted() bodies = Particles(mass=mZAMS) stellar.particles.add_particles(bodies) stellar.commit_particles() write_set_to_file(stellar.particles, filename, 'hdf5') Mtot_init = stellar.particles.mass.sum() time = 0.0 | t_end.unit while time < t_end: time += dt stellar.evolve_model(time) write_set_to_file(stellar.particles, filename, 'hdf5') Mtot = stellar.particles.mass.sum() print("T=", time, end=' ') print("M=", Mtot, "dM[SE]=", Mtot / Mtot_init) #, stellar.particles[0].stellar_type T = [] L = [] r = [] import math for si in stellar.particles: T.append(math.log10(si.temperature.value_in(units.K))) L.append(math.log10(si.luminosity.value_in(units.LSun))) r.append(1.0 + 10 * si.radius.value_in(units.RSun)) stellar.stop() pyplot.xlim(4.5, 3.3) pyplot.ylim(-4.0, 3.0) scatter(T, L, s=r) pyplot.xlabel("$log_{10}(T/K)$") pyplot.ylabel("$log_{10}(L/L_\odot)$") pyplot.show()
def main(N, W0, t_end, dt, filename, Rvir, Mmin, Mmax, z): 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 bodies.scale_to_standard(convert_nbody=converter) gravity = ph4(converter) gravity.parameters.timestep_parameter = 0.01 gravity.particles.add_particles(bodies) stopping_condition = gravity.stopping_conditions.collision_detection stopping_condition.enable() stellar = SeBa() stellar.parameters.metallicity = z stellar.particles.add_particle(bodies) channel_from_se_to_framework = stellar.particles.new_channel_to(bodies) channel_from_gd_to_framework = gravity.particles.new_channel_to(bodies) channel_from_framework_to_gd = bodies.new_channel_to(gravity.particles) channel_from_se_to_framework.copy_attributes(["mass","radius", "age"]) write_set_to_file(bodies.savepoint(0|units.Myr), filename, 'hdf5') E_init = gravity.kinetic_energy + gravity.potential_energy Nenc = 0 #dE_enc = dE_dyn = dE_stellar = zero dE_coll = zero time = zero while time < t_end: time += dt bodies.radius *= 1.e+5 channel_from_framework_to_gd.copy_attributes(["mass", "radius"]) E_dyn = gravity.kinetic_energy + gravity.potential_energy gravity.evolve_model(time) dE_dyn = E_dyn - (gravity.kinetic_energy + gravity.potential_energy) if stopping_condition.is_set(): E_coll = gravity.kinetic_energy + gravity.potential_energy print "At time=", gravity.model_time.in_(units.Myr), "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) merge_two_stars(bodies, particles_in_encounter) bodies.synchronize_to(gravity.particles) bodies.synchronize_to(stellar.particles) Nenc+=1 print "Resolve encounter Number:", Nenc gravity.evolve_model(time) dE_coll = E_coll - (gravity.kinetic_energy + gravity.potential_energy) E_stellar = gravity.kinetic_energy + gravity.potential_energy stellar.evolve_model(time) dE_stellar = E_stellar - (gravity.kinetic_energy + gravity.potential_energy) channel_from_gd_to_framework.copy() channel_from_se_to_framework.copy_attributes(["age", "mass", "radius"]) write_set_to_file(bodies.savepoint(time), filename, 'hdf5') print_diagnostics(time, bodies.mass.sum(), E_dyn, dE_dyn, dE_coll, dE_stellar) gravity.stop() stellar.stop()
def new_stellar_evolution(particles): stellar_evolution = SeBa() stellar_evolution.particles.add_particles(particles) return stellar_evolution
def main(N, W0, t_end, dt, filename, Rvir, Mmin, Mmax, z): numpy.random.seed(1) 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 bodies.scale_to_standard(convert_nbody=converter) gravity = ph4(converter) gravity.parameters.timestep_parameter = 0.01 gravity.particles.add_particles(bodies) collision_detection = gravity.stopping_conditions.collision_detection collision_detection.enable() stellar = SeBa() stellar.parameters.metallicity = z stellar.particles.add_particle(bodies) stellar.evolve_model(0|units.Myr) supernova_detection = stellar.stopping_conditions.supernova_detection supernova_detection.enable() channel_from_se = stellar.particles.new_channel_to(bodies) channel_from_gd = gravity.particles.new_channel_to(bodies) channel_to_gd = bodies.new_channel_to(gravity.particles) channel_from_se.copy_attributes(["mass","radius", "age", "temperature", "luminosity"]) write_set_to_file(bodies.savepoint(0|units.Myr), filename, 'hdf5') E_init = gravity.kinetic_energy + gravity.potential_energy Nenc = 0 Nsn = 0 dE_coll = zero time = zero while time < t_end: dt_min = min(dt, stellar.particles.time_step.min()) print "Time steps:", dt.in_(units.Myr), dt_min.in_(units.Myr) time += dt_min bodies.radius *= 1.e+5 channel_to_gd.copy_attributes(["mass", "radius", "vx", "vy", "vz"]) E_dyn = gravity.kinetic_energy + gravity.potential_energy gravity.evolve_model(time) dE_dyn = E_dyn - (gravity.kinetic_energy + gravity.potential_energy) if collision_detection.is_set(): E_coll = gravity.kinetic_energy + gravity.potential_energy print "At time=", gravity.model_time.in_(units.Myr), "number of encounters=", len(collision_detection.particles(0)) for ci in range(len(collision_detection.particles(0))): particles_in_encounter = Particles(particles=[collision_detection.particles(0)[ci], collision_detection.particles(1)[ci]]) particles_in_encounter = particles_in_encounter.get_intersecting_subset_in(bodies) merge_two_stars(bodies, particles_in_encounter) bodies.synchronize_to(gravity.particles) bodies.synchronize_to(stellar.particles) Nenc+=1 print "Resolve encounter Number:", Nenc dE_coll = E_coll - (gravity.kinetic_energy + gravity.potential_energy) channel_from_gd.copy() time = gravity.model_time E_stellar = gravity.kinetic_energy + gravity.potential_energy stellar.evolve_model(time) dE_stellar = E_stellar - (gravity.kinetic_energy + gravity.potential_energy) if supernova_detection.is_set(): print "At time=", time.in_(units.Myr), "supernova detected=", len(supernova_detection.particles(0)) for ci in range(len(supernova_detection.particles(0))): print supernova_detection.particles(0) particles_in_supernova = Particles(particles=supernova_detection.particles(0)) natal_kick_x = particles_in_supernova.natal_kick_x natal_kick_y = particles_in_supernova.natal_kick_y natal_kick_z = particles_in_supernova.natal_kick_z particles_in_supernova = particles_in_supernova.get_intersecting_subset_in(bodies) particles_in_supernova.vx += natal_kick_x particles_in_supernova.vy += natal_kick_y particles_in_supernova.vz += natal_kick_z Nsn+=1 print "Resolve supernova Number:", Nsn channel_from_se.copy_attributes(["mass", "radius", "age", "temperature", "luminosity"]) write_set_to_file(bodies.savepoint(time), filename, 'hdf5') print_diagnostics(time, bodies.mass.sum(), E_dyn, dE_dyn, dE_coll, dE_stellar) gravity.stop() stellar.stop()
def main(N, W0, t_end, dt, filename, Rvir, Mmin, Mmax, z): 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 bodies.scale_to_standard(convert_nbody=converter) gravity = ph4(converter) gravity.parameters.timestep_parameter = 0.01 gravity.particles.add_particles(bodies) stopping_condition = gravity.stopping_conditions.collision_detection stopping_condition.enable() stellar = SeBa() stellar.parameters.metallicity = z stellar.particles.add_particle(bodies) channel_from_se_to_framework = stellar.particles.new_channel_to(bodies) channel_from_gd_to_framework = gravity.particles.new_channel_to(bodies) channel_from_framework_to_gd = bodies.new_channel_to(gravity.particles) channel_from_se_to_framework.copy_attributes(["mass", "radius", "age"]) write_set_to_file(bodies.savepoint(0 | units.Myr), filename, 'hdf5') E_init = gravity.kinetic_energy + gravity.potential_energy Nenc = 0 #dE_enc = dE_dyn = dE_stellar = zero dE_coll = zero time = zero while time < t_end: time += dt bodies.radius *= 1.e+5 channel_from_framework_to_gd.copy_attributes(["mass", "radius"]) E_dyn = gravity.kinetic_energy + gravity.potential_energy gravity.evolve_model(time) dE_dyn = E_dyn - (gravity.kinetic_energy + gravity.potential_energy) if stopping_condition.is_set(): E_coll = gravity.kinetic_energy + gravity.potential_energy print("At time=", gravity.model_time.in_(units.Myr), "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) merge_two_stars(bodies, particles_in_encounter) bodies.synchronize_to(gravity.particles) bodies.synchronize_to(stellar.particles) Nenc += 1 print("Resolve encounter Number:", Nenc) gravity.evolve_model(time) dE_coll = E_coll - (gravity.kinetic_energy + gravity.potential_energy) E_stellar = gravity.kinetic_energy + gravity.potential_energy stellar.evolve_model(time) dE_stellar = E_stellar - (gravity.kinetic_energy + gravity.potential_energy) channel_from_gd_to_framework.copy() channel_from_se_to_framework.copy_attributes(["age", "mass", "radius"]) write_set_to_file(bodies.savepoint(time), filename, 'hdf5') print_diagnostics(time, bodies.mass.sum(), E_dyn, dE_dyn, dE_coll, dE_stellar) gravity.stop() stellar.stop()
# Setting up Close-Encounter Gravity Code (SmallN) util.init_smalln(unit_converter=SmallScaleConverter) # ---------------------------------------------------------------------------------------------------- # Setting up Encounter Handler (Multiples) multiples_code = multiples.Multiples(gravity_code, util.new_smalln, kep, gravity_constant=units.constants.G) multiples_code.neighbor_perturbation_limit = 0.05 multiples_code.neighbor_veto = True multiples_code.global_debug = 0 # ---------------------------------------------------------------------------------------------------- # Setting up Stellar Evolution Code (SeBa) sev_code = SeBa() sev_code.particles.add_particles(Stellar_Bodies) supernova_detection = sev_code.stopping_conditions.supernova_detection supernova_detection.enable() # ---------------------------------------------------------------------------------------------------- # Setting up Gravity Coupling Code (Bridge) bridge_code = Bridge(verbose=False) bridge_code.add_system(multiples_code, (galactic_code, )) #bridge_code.timestep = delta_t # ---------------------------------------------------------------------------------------------------- # ------------------------------------- # # Setting up Required Channels # # ------------------------------------- #
from amuse.lab import * from amuse.support import options from amuse.community.seba.interface import SeBa options.GlobalOptions.instance().override_value_for_option( "channel_type", "blaa") #stellar_evolution = SeBa() del options.GlobalOptions.instance().overriden_options["channel_type"] stellar_evolution = SeBa()
def evolution_of_the_cluster(self, cluster): ''' Function that makes de cluster evolution. input: cluster -> defined in an inertial frame (centered at the Galactic center) steps in this function: 1. From cluster, another cluster is defined in a rotating frame 2. The gravity code is initialized 3. The stellar evolution is initialized 4. the Galaxy model is constructed 5. The Galaxy and the cluster in the rotating frame are coupled via the Rotating Bridge 6. The evolution of the system is made 7. the cluster properties are transformed back to the inertial frame ''' cluster_in_rotating_frame = self.creation_cluster_in_rotating_frame( cluster) # N body code epsilon = self.softening(cluster) convert_nbody = nbody_system.nbody_to_si(cluster.mass.sum(), cluster.virial_radius()) gravity = Huayno(convert_nbody) gravity.parameters.timestep = self.dt_bridge / 3. gravity.particles.add_particles(cluster_in_rotating_frame) gravity.parameters.epsilon_squared = epsilon**2 channel_from_gravity_to_rotating_cluster = gravity.particles.new_channel_to( cluster_in_rotating_frame) channel_from_rotating_cluster_to_gravity = cluster_in_rotating_frame.new_channel_to( gravity.particles) #stellar evolution code se = SeBa() se.particles.add_particles(cluster_in_rotating_frame) channel_from_rotating_cluster_to_se = cluster_in_rotating_frame.new_channel_to( se.particles) channel_from_se_to_rotating_cluster = se.particles.new_channel_to( cluster_in_rotating_frame) # Galaxy model and Rotating bridge MW = self.galactic_model() system = Rotating_Bridge(self.omega_system, timestep=self.dt_bridge, verbose=False, method=self.method) system.add_system(gravity, (MW, ), False) system.add_system(MW, (), False) X = [] Y = [] T = [] #Cluster evolution while (self.time <= self.t_end - self.dt_bridge / 2): self.time += self.dt_bridge system.evolve_model(self.time) se.evolve_model(self.time) channel_from_gravity_to_rotating_cluster.copy_attributes( ['x', 'y', 'z', 'vx', 'vy', 'vz']) channel_from_se_to_rotating_cluster.copy_attributes([ 'mass', 'radius', 'luminosity', 'age', 'temperature', 'stellar_type' ]) channel_from_rotating_cluster_to_gravity.copy_attributes(['mass']) self.from_noinertial_to_cluster_in_inertial_frame( cluster_in_rotating_frame, cluster) time = self.time.value_in(units.Myr) cm = cluster.center_of_mass() # write data if ((time == 2) or (time == 50) or (time == 100) or (time == 150)): X.append((cluster.x - cm[0]).value_in(units.kpc)) Y.append((cluster.y - cm[1]).value_in(units.kpc)) T.append(time) gravity.stop() se.stop() return T, X, Y
def main(N, W0, t_end, dt, filename, Rvir, Mmin, Mmax, z): numpy.random.seed(1) 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 bodies.scale_to_standard(convert_nbody=converter) gravity = ph4(converter) gravity.parameters.timestep_parameter = 0.01 gravity.particles.add_particles(bodies) collision_detection = gravity.stopping_conditions.collision_detection collision_detection.enable() stellar = SeBa() stellar.parameters.metallicity = z stellar.particles.add_particle(bodies) stellar.evolve_model(0|units.Myr) supernova_detection = stellar.stopping_conditions.supernova_detection supernova_detection.enable() channel_from_se = stellar.particles.new_channel_to(bodies) channel_from_gd = gravity.particles.new_channel_to(bodies) channel_to_gd = bodies.new_channel_to(gravity.particles) channel_from_se.copy_attributes(["mass","radius", "age", "temperature", "luminosity"]) write_set_to_file(bodies.savepoint(0|units.Myr), filename, 'hdf5') E_init = gravity.kinetic_energy + gravity.potential_energy Nsn = 0 dE_coll = zero time = zero while time < t_end: dt_min = min(dt, stellar.particles.time_step.min()) print "Time steps:", dt.in_(units.Myr), dt_min.in_(units.Myr) time += dt_min bodies.radius *= 1.e+5 channel_to_gd.copy_attributes(["mass", "radius", "vx", "vy", "vz"]) E_dyn = gravity.kinetic_energy + gravity.potential_energy gravity.evolve_model(time) dE_dyn = E_dyn - (gravity.kinetic_energy + gravity.potential_energy) resolve_collision(collision_detection, gravity, stellar, bodies) channel_from_gd.copy() time = gravity.model_time E_stellar = gravity.kinetic_energy + gravity.potential_energy stellar.evolve_model(time) dE_stellar = E_stellar - (gravity.kinetic_energy + gravity.potential_energy) resolve_supernova(supernova_detection, bodies, time) channel_from_se.copy_attributes(["mass", "radius", "age", "temperature", "luminosity"]) write_set_to_file(bodies.savepoint(time), filename, 'hdf5') print_diagnostics(time, bodies.mass.sum(), E_dyn, dE_dyn, dE_coll, dE_stellar) gravity.stop() stellar.stop()
def main(N, W0, t_end, dt, filename, Rvir, Mmin, Mmax, z): 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 bodies.scale_to_standard(convert_nbody=converter) gravity = ph4(converter) gravity.parameters.timestep_parameter = 0.01 gravity.particles.add_particles(bodies) stopping_condition = gravity.stopping_conditions.collision_detection stopping_condition.enable() stellar = SeBa() stellar.parameters.metallicity = z stellar.particles.add_particle(bodies) channel_from_stellar = stellar.particles.new_channel_to(bodies, attributes=["mass", "radius", "age"], target_names=["mass", "radius", "age"]) channel_from_gravity = gravity.particles.new_channel_to(bodies, attributes=["x", "y", "z", "vx", "vy", "vz", "mass", "radius"], target_names=["x", "y", "z", "vx", "vy", "vz", "mass", "collision_radius"]) channel_to_gravity = bodies.new_channel_to(gravity.particles, attributes=["mass", "collision_radius"], target_names=["mass", "radius"]) channel_from_stellar.copy() write_set_to_file(bodies.savepoint(0|units.Myr), filename, 'hdf5') E_init = gravity.kinetic_energy + gravity.potential_energy Nenc = 0 dE_coll = zero time = zero ###BOOKLISTSTART3### while time < t_end: time += dt E_stellar = gravity.kinetic_energy + gravity.potential_energy stellar.evolve_model(time) dE_stellar = E_stellar - (gravity.kinetic_energy \ + gravity.potential_energy) channel_from_stellar.copy() bodies.collision_radius = 1.e+5 * bodies.radius channel_to_gravity.copy() E_dyn = gravity.kinetic_energy + gravity.potential_energy gravity.evolve_model(time) dE_dyn = E_dyn - (gravity.kinetic_energy + gravity.potential_energy) channel_from_gravity.copy() resolve_collision(stopping_condition, gravity, stellar, bodies) write_set_to_file(bodies.savepoint(time), filename, 'hdf5') print_diagnostics(time, bodies.mass.sum(), E_dyn, dE_dyn, dE_coll, dE_stellar) ###BOOKLISTSTOP3### gravity.stop() stellar.stop()
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, print "M=", Mtot, "(dM[SE]=", Mtot/Mtriple, ")", print "E= ", Etot, "Q= ", Ekin/Epot, print "dE=", (Etot_init-Etot)/Etot, "ddE=", (Etot_prev-Etot)/Etot, 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(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 main(): numpy.random.seed(42) evo_headstart = 0.0 | units.Myr dt_base = 0.001 | units.Myr dt = dt_base time = 0 | units.Myr time_end = 8 | units.Myr Tmin = 22 | units.K gas_density = 5e3 | units.amu * units.cm**-3 increase_vol = 2 Ngas = increase_vol**3 * 10000 Mgas = increase_vol**3 * 1000 | units.MSun # Mgas = Ngas | units.MSun volume = Mgas / gas_density # 4/3 * pi * r**3 radius = (volume / (pi * 4/3))**(1/3) radius = increase_vol * radius # 15 | units.parsec gasconverter = nbody_system.nbody_to_si(Mgas, radius) # gasconverter = nbody_system.nbody_to_si(1 | units.pc, 1 | units.MSun) # gasconverter = nbody_system.nbody_to_si(1e10 | units.cm, 1e10 | units.g) # NOTE: make stars first - so that it remains the same random # initialisation even when we change the number of gas particles if len(sys.argv) > 1: gas = read_set_from_file(sys.argv[1], "amuse") stars = read_set_from_file(sys.argv[2], "amuse") stars.position = stars.position * 3 else: # stars = new_star_cluster( # stellar_mass=1000 | units.MSun, effective_radius=3 | units.parsec # ) # stars.velocity = stars.velocity * 2.0 from amuse.datamodel import Particles Nstars = 100 stars = Particles(Nstars) stars.position = [0, 0, 0] | units.pc stars.velocity = [0, 0, 0] | units.kms stars.mass = new_kroupa_mass_distribution(Nstars, mass_min=1 | units.MSun).reshape(Nstars) # 25 | units.MSun gas = molecular_cloud(targetN=Ngas, convert_nbody=gasconverter).result # gas.velocity = gas.velocity * 0.5 gas.u = temperature_to_u(100 | units.K) # gas.x = gas.x # gas.y = gas.y # gas.z = gas.z # gas.h_smooth = (gas.mass / gas_density / (4/3) / pi)**(1/3) # print(gas.h_smooth.mean()) # gas = read_set_from_file("gas_initial.hdf5", "amuse") # gas.density = gas_density # print(gas.h_smooth.mean()) # exit() u_now = gas.u #print(gasconverter.to_nbody(gas[0].u)) #print(constants.kB.value_in(units.erg * units.K**-1)) #print((constants.kB * 6.02215076e23).value_in(units.erg * units.K**-1)) #print(gasconverter.to_nbody(temperature_to_u(10 | units.K))) #tempiso = 2.d0/3.d0*ui/(Rg/gmwvar/uergg) # print(nbody_system.length**2 / nbody_system.time**2) # print(gasconverter.to_si(1 | nbody_system.length**2 / nbody_system.time**2).value_in(units.kms**2)) # print(gasconverter.to_nbody(temperature_to_u(Tmin))) # Rg = (constants.kB * 6.02214076e23).value_in(units.erg * units.K**-1) # gmwvar = 1.2727272727 # uergg = nbody_system.length**2 * nbody_system.time**-2 # uergg = 6.6720409999999996E-8 # print(Rg) # print( # 2.0/3.0*gasconverter.to_nbody(temperature_to_u(Tmin))/(Rg/gmwvar/uergg) # ) # #tempiso, ui, Rg, gmwvar, uergg, udist, utime 1.7552962911187030E-018 2.5778500859241771E-003 83140000.000000000 1.2727272727272725 6.6720409999999996E-008 1.0000000000000000 3871.4231866737564 # u = 3./2. * Tmin.value_in(units.K) * (Rg/gmwvar/uergg) # print(u) # print( # 2.0/3.0*u/(Rg/gmwvar/uergg) # ) # print(u, Rg, gmwvar, uergg) # print(temperature_to_u(10 | units.K).value_in(units.kms**2)) u = temperature_to_u(20 | units.K) #print(gasconverter.to_nbody(u)) #print(u_to_temperature(u).value_in(units.K)) # exit() # gas.u = u | units.kms**2 # exit() # print(gasconverter.to_nbody(gas.u.mean())) # print(gasconverter.to_si(gas.u.mean()).value_in(units.kms**2)) # exit() gas.du_dt = (u_now - u_now) / dt # zero, but in the correct units # stars = read_set_from_file("stars.amuse", "amuse") # write_set_to_file(stars, 'stars.amuse', 'amuse', append_to_file=False) # stars.velocity *= 3 # stars.vx += 0 | units.kms # stars.vy += 0 | units.kms M = stars.total_mass() + Mgas R = stars.position.lengths().mean() converter = nbody_system.nbody_to_si(M, R) # exit() # gas = new_plummer_gas_model(Ngas, gasconverter) # gas = molecular_cloud(targetN=Ngas, convert_nbody=gasconverter).result # gas.u = temperature_to_u(Tmin) # gas = read_set_from_file("gas.amuse", "amuse") # print(stars.mass == stars.mass.max()) print(len(stars.mass)) print(len(stars.mass == stars.mass.max())) print(stars[0]) print(stars[stars.mass == stars.mass.max()]) mms = stars[stars.mass == stars.mass.max()] print("Most massive star: %s" % mms.mass) print("Gas particle mass: %s" % gas[0].mass) evo = SeBa() # sph = Fi(converter, mode="openmp") phantomconverter = nbody_system.nbody_to_si( default_settings.gas_rscale, default_settings.gas_mscale, ) sph = Phantom(phantomconverter, redirection="none") sph.parameters.ieos = 2 sph.parameters.icooling = 1 sph.parameters.alpha = 0.1 sph.parameters.gamma = 5/3 sph.parameters.rho_crit = 1e17 | units.amu * units.cm**-3 sph.parameters.h_soft_sinkgas = 0.1 | units.parsec sph.parameters.h_soft_sinksink = 0.1 | units.parsec sph.parameters.h_acc = 0.1 | units.parsec # print(sph.parameters) stars_in_evo = evo.particles.add_particles(stars) channel_stars_evo_from_code = stars_in_evo.new_channel_to( stars, attributes=[ "age", "radius", "mass", "luminosity", "temperature", "stellar_type", ], ) channel_stars_evo_from_code.copy() # try: # sph.parameters.timestep = dt # except: # print("SPH code doesn't support setting the timestep") sph.parameters.stopping_condition_maximum_density = \ 5e-16 | units.g * units.cm**-3 # sph.parameters.beta = 1. # sph.parameters.C_cour = sph.parameters.C_cour / 4 # sph.parameters.C_force = sph.parameters.C_force / 4 print(sph.parameters) stars_in_sph = stars.copy() # sph.sink_particles.add_particles(stars) # stars_in_sph = sph.sink_particles.add_particles(stars) channel_stars_grav_to_code = stars.new_channel_to( # sph.sink_particles, # sph.dm_particles, stars_in_sph, attributes=["mass"] ) channel_stars_grav_from_code = stars_in_sph.new_channel_to( stars, attributes=["x", "y", "z", "vx", "vy", "vz"], ) # We don't want to accrete gas onto the stars/sinks stars_in_sph.radius = 0 | units.RSun # stars_in_sph = sph.dm_particles.add_particles(stars) # try: # sph.parameters.isothermal_flag = True # sph.parameters.integrate_entropy_flag = False # sph.parameters.gamma = 1 # except: # print("SPH code doesn't support setting isothermal flag") gas_in_code = sph.gas_particles.add_particles(gas) # print(gasconverter.to_nbody(gas_in_code[0].u).value_in(nbody_system.specific_energy)) # ui = temperature_to_u(10 | units.K) # Rg = constants.kB * 6.02214179e+23 # gmwvar = (1.4/1.1) | units.g # uergg = 1.# | nbody_system.specific_energy # print("gmwvar = %s"%gasconverter.to_si(gmwvar)) # print("Rg = %s"% gasconverter.to_si(Rg)) # print("ui = %s"% gasconverter.to_si(ui)) # #print("uergg = %s"% gasconverter.to_nbody(uergg)) # print("uergg = %s" % gasconverter.to_si(1 | nbody_system.specific_energy).in_(units.cm**2 * units.s**-2)) # print("****** %s" % ((2.0/3.0)*ui/(Rg/gmwvar/uergg)) + "*****") # print(gasconverter.to_nbody(Rg)) # print((ui).in_(units.cm**2*units.s**-2)) # #exit() # sph.evolve_model(1 | units.day) # write_set_to_file(sph.gas_particles, "gas_initial.hdf5", "amuse") # exit() channel_gas_to_code = gas.new_channel_to( gas_in_code, attributes=[ "x", "y", "z", "vx", "vy", "vz", "u", ] ) # mass is never updated, and if sph is in isothermal mode u is not reliable channel_gas_from_code = gas_in_code.new_channel_to( gas, attributes=[ "x", "y", "z", "vx", "vy", "vz", "density", "pressure", "rho", "u", "h_smooth", ], ) channel_gas_from_code.copy() # Initialise values for density etc sph_particle_mass = gas[0].mass # 0.1 | units.MSun r_max = 0.1 | units.parsec wind = stellar_wind.new_stellar_wind( sph_particle_mass, mode="heating", r_max=r_max, derive_from_evolution=True, tag_gas_source=True, # target_gas=gas, # timestep=dt, ) stars_in_wind = wind.particles.add_particles(stars) channel_stars_wind_to_code = stars.new_channel_to( stars_in_wind, attributes=[ "x", "y", "z", "vx", "vy", "vz", "age", "radius", "mass", "luminosity", "temperature", "stellar_type", ], ) channel_stars_wind_to_code.copy() # reference_mu = 2.2 | units.amu gasvolume = (4./3.) * numpy.pi * ( gas.position - gas.center_of_mass() ).lengths().mean()**3 rho0 = gas.total_mass() / gasvolume print(rho0.value_in(units.g * units.cm**-3)) # exit() # cooling_flag = "thermal_model" # cooling = Cooling( cooling = SimplifiedThermalModelEvolver( # gas_in_code, gas, Tmin=Tmin, # T0=30 | units.K, # n0=rho0/reference_mu ) cooling.model_time = sph.model_time # cooling_to_code = cooling.particles.new_channel_to(gas start_mass = ( stars.mass.sum() + (gas.mass.sum() if not gas.is_empty() else 0 | units.MSun) ) step = 0 plotnr = 0 com = stars_in_sph.center_of_mass() plot_hydro_and_stars( time, sph, stars=stars, sinks=None, L=20, # N=100, filename="phantom-coolthermalwindtestplot-%04i.png" % step, title="time = %06.2f %s" % (time.value_in(units.Myr), units.Myr), gasproperties=["density", "temperature"], # colorbar=True, starscale=1, offset_x=com[0].value_in(units.parsec), offset_y=com[1].value_in(units.parsec), thickness=5 | units.parsec, ) dt = dt_base sph.parameters.time_step = dt delta_t = phantomconverter.to_si(2**(-16) | nbody_system.time) print("delta_t: %s" % delta_t.in_(units.day)) # small_step = True small_step = False plot_every = 100 subplot_factor = 10 subplot_enabled = False subplot = 0 while time < time_end: time += dt print("Gas mean u: %s" % (gas.u.mean().in_(units.erg/units.MSun))) print("Evolving to t=%s (%s)" % (time, gasconverter.to_nbody(time))) step += 1 evo.evolve_model(evo_headstart+time) print(evo.particles.stellar_type.max()) channel_stars_evo_from_code.copy() channel_stars_grav_to_code.copy() if COOLING: channel_gas_from_code.copy() cooling.evolve_for(dt/2) channel_gas_to_code.copy() print( "min/max temp in gas: %s %s" % ( u_to_temperature(gas_in_code.u.min()).in_(units.K), u_to_temperature(gas_in_code.u.max()).in_(units.K), ) ) if small_step: # Take small steps until a full timestep is done. # Each substep is 2* as long as the last until dt is reached print("Doing small steps") # print(u_to_temperature(sph.gas_particles[0].u)) # print(sph.gas_particles[0].u) old_dt = dt_base substeps = 2**8 dt = old_dt / substeps dt_done = 0 * old_dt sph.parameters.time_step = dt print("adjusted dt to %s, base dt is %s" % ( dt.in_(units.Myr), dt_base.in_(units.Myr), ) ) sph.evolve_model(sph.model_time + dt) dt_done += dt while dt_done < old_dt: sph.parameters.time_step = dt print("adjusted dt to %s, base dt is %s" % ( dt.in_(units.Myr), dt_base.in_(units.Myr), ) ) sph.evolve_model(sph.model_time + dt) dt_done += dt dt = min(2*dt, old_dt-dt_done) dt = max(dt, old_dt/substeps) dt = dt_base sph.parameters.time_step = dt print( "adjusted dt to %s" % sph.parameters.time_step.in_(units.Myr) ) small_step = False print("Finished small steps") # print(u_to_temperature(sph.gas_particles[0].u)) # print(sph.gas_particles[0].u) # exit() else: sph.evolve_model(time) channel_gas_from_code.copy() channel_stars_grav_from_code.copy() u_previous = u_now u_now = gas.u gas.du_dt = (u_now - u_previous) / dt channel_stars_wind_to_code.copy() wind.evolve_model(time) # channel_stars_wind_from_code.copy() if COOLING: channel_gas_from_code.copy() cooling.evolve_for(dt/2) channel_gas_to_code.copy() if wind.has_new_wind_particles(): subplot_enabled = True wind_p = wind.create_wind_particles() # nearest = gas.find_closest_particle_to(wind_p.x, wind_p.y, wind_p.z) # wind_p.h_smooth = nearest.h_smooth wind_p.h_smooth = 100 | units.au print("u: %s / T: %s" % (wind_p.u.mean(), u_to_temperature(wind_p.u.mean()))) # max_e = (1e44 | units.erg) / wind_p[0].mass # max_e = 10 * gas.u.mean() # max_e = (1.e48 | units.erg) / wind_p[0].mass # wind_p[wind_p.u > max_e].u = max_e # wind_p[wind_p.u > max_e].h_smooth = 0.1 | units.parsec # print(wind_p.position) print( "time: %s, wind energy: %s" % (time, (wind_p.u * wind_p.mass).sum()) ) print( "wind temperature: %s" % (u_to_temperature(wind_p.u)) ) print( "gas particles: %i (total mass %s)" % (len(wind_p), wind_p.total_mass()) ) # for windje in wind_p: # # print(windje) # source = stars[stars.key == windje.source][0] # windje.position += source.position # windje.velocity += source.velocity # # print(source) # # print(windje) # # exit() gas.add_particles(wind_p) gas_in_code.add_particles(wind_p) # for wp in wind_p: # print(wp) print("Wind particles added") if True: # wind_p.u.max() > gas_in_code.u.max(): print("Setting dt to very short") small_step = True # dt = 0.1 | units.yr h_min = gas.h_smooth.min() # delta_t = determine_short_timestep(sph, wind_p, h_min=h_min) # print("delta_t is set to %s" % delta_t.in_(units.yr)) # else: # small_step = True print( "time: %s sph: %s dM: %s" % ( time.in_(units.Myr), sph.model_time.in_(units.Myr), ( stars.total_mass() + ( gas.total_mass() if not gas.is_empty() else (0 | units.MSun) ) - start_mass ) ) ) # com = sph.sink_particles.center_of_mass() # com = sph.dm_particles.center_of_mass() com = stars.center_of_mass() print("STEP: %i step%%plot_every: %i" % (step, step % plot_every)) if step % plot_every == 0: plotnr = plotnr + 1 plot_hydro_and_stars( time, sph, # stars=sph.sink_particles, # stars=sph.dm_particles, stars=stars, sinks=None, L=20, # N=100, # image_size_scale=10, filename="phantom-coolthermalwindtestplot-%04i.png" % plotnr, # int(step/plot_every), title="time = %06.2f %s" % (time.value_in(units.Myr), units.Myr), gasproperties=["density", "temperature"], # colorbar=True, starscale=1, offset_x=com[0].value_in(units.parsec), offset_y=com[1].value_in(units.parsec), thickness=5 | units.parsec, ) # write_set_to_file(gas, "gas.amuse", "amuse", append_to_file=False) # write_set_to_file(stars, "stars.amuse", "amuse", append_to_file=False) elif ( subplot_enabled and ((step % (plot_every/subplot_factor)) == 0) ): plotnr = plotnr + 1 subplot += 1 plot_hydro_and_stars( time, sph, # stars=sph.sink_particles, # stars=sph.dm_particles, stars=stars, sinks=None, L=20, # N=100, # image_size_scale=10, filename="phantom-coolthermalwindtestplot-%04i.png" % plotnr, # int(step/plot_every), title="time = %06.2f %s" % (time.value_in(units.Myr), units.Myr), gasproperties=["density", "temperature"], # colorbar=True, starscale=1, offset_x=com[0].value_in(units.parsec), offset_y=com[1].value_in(units.parsec), thickness=5 | units.parsec, ) if subplot % subplot_factor == 0: subplot_enabled = False print( "Average temperature of gas: %s" % ( u_to_temperature(gas.u).mean().in_(units.K) ) ) return
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, print "M=", Mtot, "(dM[SE]=", Mtot/Mtriple, ")", print "E= ", Etot, "Q= ", Ekin/Epot, print "dE=", (Etot_init-Etot)/Etot, "ddE=", (Etot_prev-Etot)/Etot, 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 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 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 time_framework = 0 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) t0 = ctime.time() stellar.evolve_model(t_stellar) delta_t = ctime.time() - t0 time_framework += delta_t 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 = Huayno(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 # begin when stars have formed after 4.0 Myr years ain, ein, aout, eout, iin, iout = get_orbital_elements_of_triple(triple) print "Triple elements t=", time, \ "inner:", triple[0].mass, triple[1].mass, ain, ein, iin, \ "outer:", triple[2].mass, aout, eout, iout dt_diag = t_end / float( nsteps) # how often we want to save the generated data 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] inci = [iin] inco = [iout] 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_stellar_with_massloss( ts, time_framework, dt_massloss=15e-9 | units.Myr, max_massloss=3e-4 | units.MSun): # Scheme 3: dt 8*10^-7, dm = 2*10^-5 ( max_massloss = 0.0 | units.MSun # massloss over full gravtiational time step massloss0 #max_massloss= 3e-6 | units.MSun # massloss over full gravtiational time step massloss1 #max_massloss= 1e-6 | units.MSun # massloss over full gravtiational time step massloss2 E0 = gravity.kinetic_energy + gravity.potential_energy massloss = -1 | units.MSun mass_0 = numpy.sum(stellar.particles.mass) dt_stellar = 0 | units.Myr niter = 0 while massloss < max_massloss: ts += dt_massloss dt_stellar += dt_massloss # counter for full time niter += 1 t0 = ctime.time() stellar.evolve_model(ts) delta_t = ctime.time() - t0 time_framework += delta_t massloss = 2. * ( mass_0 - numpy.sum(stellar.particles.mass) ) # massloss over full gravtiational time step is x2 channel_from_stellar.copy_attributes(["mass"]) channel_from_framework_to_gd.copy_attributes(["mass"]) print 'Tstellar:', dt_stellar, ', Total Mloss:', massloss, ' Niter:', niter return ts, time_framework, gravity.kinetic_energy + gravity.potential_energy - E0, dt_stellar def advance_gravity(tg, dt): tg += dt gravity.evolve_model(tg) channel_from_gd_to_framework.copy() return tg global_time = [] global_massloss = [] global_dmdt = [] while time < t_end: Pin = orbital_period(ain, triple[0].mass + triple[1].mass) dt = dtse_fac * Pin dt *= random.random( ) # time step is chosen random between 0 and 50*Pin 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) elif scheme == 3: # inital mass mass_init = stellar.particles.mass.sum() # perform step ts, dE_se = advance_stellar(ts, dt / 2) time = advance_gravity(time, dt) ts, dE = advance_stellar(ts, dt / 2) dE_se += dE # add right vlaues global_time = numpy.append(global_time, time.value_in(units.Myr)) global_massloss = numpy.append( global_massloss, mass_init.value_in(units.MSun) - numpy.sum(stellar.particles.mass).value_in(units.MSun)) else: # our scheme is 4 # inital mass mass_init = stellar.particles.mass.sum() time_init = time.value_in(units.Myr) | units.Myr # get optimal dt to perform a time step without losing too much mass ts, time_framework, dE_se, dt_stellar = advance_stellar_with_massloss( ts, time_framework) # perform time step dt t0 = ctime.time() time = advance_gravity(time, dt_stellar * 2) ts, dE = advance_stellar(ts, dt_stellar) delta_t = ctime.time() - t0 time_framework += delta_t dE_se += dE # save everything global_time = numpy.append(global_time, time.value_in(units.Myr)) global_massloss = numpy.append( global_massloss, mass_init.value_in(units.MSun) - numpy.sum(stellar.particles.mass).value_in(units.MSun)) global_dmdt = numpy.append( global_dmdt, (mass_init.value_in(units.MSun) - numpy.sum(stellar.particles.mass).value_in(units.MSun)) / (time.value_in(units.Myr) - time_init.value_in(units.Myr))) 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 #, #print "M=", Mtot, "(dM[SE]=", Mtot/Mtriple, ")", #print "E= ", Etot, "Q= ", Ekin/Epot, #print "dE=", (Etot_init-Etot)/Etot, "ddE=", (Etot_prev-Etot)/Etot, #print "(dE[SE]=", dE_se/Etot, ")" Etot_init -= dE Etot_prev = Etot ain, ein, aout, eout, iin, iout = 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) inci.append(iin) inco.append(iout) if eout > 1.0 or aout <= zero: print "Binary ionized or merged" break pyplot.close() data = numpy.array(zip(global_time, global_massloss, global_dmdt)) numpy.save('massloss0', data) return t, smai, ecci, smao, ecco, inci, inco, time_framework
def evolution_of_the_cluster(self, cluster): ''' Function that makes de cluster evolution. input: cluster -> defined in an inertial frame (centered at the Galactic center) steps in this function: 1. From cluster, another cluster is defined in a rotating frame 2. The gravity code is initialized 3. The stellar evolution is initialized 4. the Galaxy model is constructed 5. The Galaxy and the cluster in the rotating frame are coupled via the Rotating Bridge 6. The evolution of the system is made 7. the cluster properties are transformed back to the inertial frame ''' cluster_in_rotating_frame = self.creation_cluster_in_rotating_frame( cluster) # N body code epsilon = self.softening(cluster) convert_nbody = nbody_system.nbody_to_si( cluster.mass.sum(), cluster.virial_radius()) gravity = Huayno(convert_nbody) gravity.parameters.timestep = self.dt_bridge/3. gravity.particles.add_particles(cluster_in_rotating_frame) gravity.parameters.epsilon_squared = epsilon**2 channel_from_gravity_to_rotating_cluster = \ gravity.particles.new_channel_to( cluster_in_rotating_frame) channel_from_rotating_cluster_to_gravity = \ cluster_in_rotating_frame.new_channel_to(gravity.particles) # stellar evolution code se = SeBa() se.particles.add_particles(cluster_in_rotating_frame) channel_from_rotating_cluster_to_se = \ cluster_in_rotating_frame.new_channel_to(se.particles) channel_from_se_to_rotating_cluster = se.particles.new_channel_to( cluster_in_rotating_frame) # Galaxy model and Rotating bridge MW = self.galactic_model() system = Rotating_Bridge( self.omega_system, timestep=self.dt_bridge, verbose=False, method=self.method) system.add_system(gravity, (MW,), False) system.add_system(MW, (), False) X = [] Y = [] T = [] # Cluster evolution while (self.time <= self.t_end-self.dt_bridge/2): self.time += self.dt_bridge system.evolve_model(self.time) se.evolve_model(self.time) channel_from_gravity_to_rotating_cluster.copy_attributes( ['x', 'y', 'z', 'vx', 'vy', 'vz']) channel_from_se_to_rotating_cluster.copy_attributes( [ 'mass', 'radius', 'luminosity', 'age', 'temperature', 'stellar_type' ] ) channel_from_rotating_cluster_to_gravity.copy_attributes(['mass']) self.from_noinertial_to_cluster_in_inertial_frame( cluster_in_rotating_frame, cluster) time = self.time.value_in(units.Myr) cm = cluster.center_of_mass() # write data if ((time == 2) or (time == 50) or (time == 100) or (time == 150)): X.append((cluster.x-cm[0]).value_in(units.kpc)) Y.append((cluster.y-cm[1]).value_in(units.kpc)) T.append(time) gravity.stop() se.stop() return T, X, Y
def evolve_galaxy( end_time, time_step, gal_fraction=1e-6, binfraction=1.0, Mmin=0.125, Mmax=125., a_min=0.01, a_max=1e6, e_min=0, e_max=1., ce=0.5, Mmax_NS=2.1, plot = True ): #initialize some variables for monitoring date = str(datetime.datetime.now()) stellar_galaxy_mass = 0.0 number_of_binaries = 0 number_of_systems = 0 number_of_stars = 0 time = 0.0 * end_time try: session_id = session.query(Simulation.id).all()[-1][0] + 1 except: session_id = 0 code = SeBa() #link code #code = BSE() #configure parameters code.parameters.common_envelope_efficiency = ce code.parameters.maximum_neutron_star_mass = Mmax_NS | units.MSun pyplot.ion() pyplot.show() while time < end_time: time += time_step mass_in_timestep = star_formation(15,7e9,time.value_in(units.yr)) - star_formation(15,7e9,(time-time_step).value_in(units.yr)) mass_in_timestep = mass_in_timestep*gal_fraction N = stars_for_given_Mtot(mass_in_timestep,Mmin,Mmax) #N = 4 #for de-bugging number_of_stars += N number_of_binaries = np.int(number_of_stars*binfraction/2) number_of_systems = np.int(number_of_stars*(1-binfraction) + number_of_binaries) stellar_galaxy_mass += mass_in_timestep print print print print "Total stellar mass of the Galaxy [in 1e10 Msun]:", stellar_galaxy_mass/gal_fraction/1e10 print "Age of the disk:",time.value_in(units.Gyr), "Gyr" print "Number of stellar systems:", number_of_systems, "of which", number_of_binaries ,"are binaries" print "Injected", N, "stars in the last timestep. Total number of stars:", number_of_stars print print print if (time == time_step): binaries, stars = generate_initial_population_grid(Mmin, Mmax, N, gal_fraction, binfraction, a_min, a_max, e_min , e_max,binfraction) code.particles.add_particles(stars) code.binaries.add_particles(binaries) else: binaries2, stars2 = generate_initial_population_grid(0.125, 125,N, 1e-5, 1, 0.1, 1e6, 0.0 , 1.0, binfraction) stars.add_particles(stars2) binaries.add_particles(binaries2) code.particles.add_particles(stars2) code.binaries.add_particles(binaries2) channel_from_code_to_model_for_binaries = code.binaries.new_channel_to(binaries) channel_from_code_to_model_for_stars = code.particles.new_channel_to(stars) code.evolve_model(time) channel_from_code_to_model_for_stars.copy() channel_from_code_to_model_for_binaries.copy() if plot: if (time > time_step): make_hr_diagram3(stars) pyplot.clf() #add_sim_info_to_database(end_time=end_time,time_step=time_step, # gal_fraction=gal_fraction,binfraction=binfraction,Mmin=Mmin, # Mmax=Mmax,a_min=a_min,a_max=a_max,date=date,code='BSE',ce=ce,MNSmax = Mmax_NS) #add_stars_to_database(binaries,sim_id = session_id) write_set_to_file(code.particles,'stellar_properties.bse.hdf5',format='hdf5') write_set_to_file(binaries,'binary_properties.bse.hdf5',format='hdf5')
kep = Kepler(unit_converter=SmallScaleConverter, redirection = "none") kep.initialize_code() util.init_smalln(unit_converter=SmallScaleConverter) # Initializing MULTIPLES, Testing to See if a Crash Exists First if read_from_file and crash: time, multiples_code = read.recover_crash(crash_file, gravity, kep, util.new_smalln) else: multiples_code = multiples.Multiples(gravity, util.new_smalln, kep, gravity_constant=units.constants.G) multiples_code.neighbor_perturbation_limit = 0.05 #multiples_code.neighbor_distance_factor = 1.0 multiples_code.neighbor_veto = True # Initializing Stellar Evolution (SeBa) sev_code = SeBa() sev_code.particles.add_particles(MasterSet) # Starting the AMUSE Channel for Stellar Evolution sev_to_MS_channel = sev_code.particles.new_channel_to(MasterSet, attributes=["mass", "luminosity", "stellar_type", "temperature", "age"]) # Initializing Galactic Background Rgal=1. | units.kpc Mgal=1.6e10 | units.MSun alpha=1.2 galactic_code = create.GalacticCenterGravityCode(Rgal, Mgal, alpha) # Move the Cluster into a 1 kpc Orbit rinit_from_galaxy_core = 5.0 | units.kpc galactic_code.move_particles_into_ellipictal_orbit(MasterSet, rinit_from_galaxy_core)
def main(N, W0, t_end, dt, filename, Rvir, Mmin, Mmax, z): 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 bodies.scale_to_standard(convert_nbody=converter) gravity = ph4(converter) gravity.parameters.timestep_parameter = 0.01 gravity.particles.add_particles(bodies) stopping_condition = gravity.stopping_conditions.collision_detection stopping_condition.enable() stellar = SeBa() stellar.parameters.metallicity = z stellar.particles.add_particle(bodies) channel_from_stellar = stellar.particles.new_channel_to( bodies, attributes=["mass", "radius", "age"], target_names=["mass", "radius", "age"]) channel_from_gravity = gravity.particles.new_channel_to( bodies, attributes=["x", "y", "z", "vx", "vy", "vz", "mass", "radius"], target_names=[ "x", "y", "z", "vx", "vy", "vz", "mass", "collision_radius" ]) channel_to_gravity = bodies.new_channel_to( gravity.particles, attributes=["mass", "collision_radius"], target_names=["mass", "radius"]) channel_from_stellar.copy() write_set_to_file(bodies.savepoint(0 | units.Myr), filename, 'hdf5') E_init = gravity.kinetic_energy + gravity.potential_energy Nenc = 0 dE_coll = zero time = zero ###BOOKLISTSTART3### while time < t_end: time += dt E_stellar = gravity.kinetic_energy + gravity.potential_energy stellar.evolve_model(time) dE_stellar = E_stellar - (gravity.kinetic_energy \ + gravity.potential_energy) channel_from_stellar.copy() bodies.collision_radius = 1.e+5 * bodies.radius channel_to_gravity.copy() E_dyn = gravity.kinetic_energy + gravity.potential_energy gravity.evolve_model(time) dE_dyn = E_dyn - (gravity.kinetic_energy + gravity.potential_energy) channel_from_gravity.copy() resolve_collision(stopping_condition, gravity, stellar, bodies) write_set_to_file(bodies.savepoint(time), filename, 'hdf5') print_diagnostics(time, bodies.mass.sum(), E_dyn, dE_dyn, dE_coll, dE_stellar) ###BOOKLISTSTOP3### gravity.stop() stellar.stop()
# Setting up Close-Encounter Gravity Code (SmallN) util.init_smalln(unit_converter=SmallScaleConverter) # ---------------------------------------------------------------------------------------------------- # Setting up Encounter Handler (Multiples) multiples_code = multiples.Multiples(gravity_code, util.new_smalln, kep, gravity_constant=units.constants.G) multiples_code.neighbor_perturbation_limit = 0.05 multiples_code.neighbor_veto = True multiples_code.callback = EncounterHandler().handle_encounter_v5 multiples_code.global_debug = 1 # ---------------------------------------------------------------------------------------------------- # Setting up Stellar Evolution Code (SeBa) sev_code = SeBa() sev_code.particles.add_particles(Stellar_Bodies) # ---------------------------------------------------------------------------------------------------- # Setting up Gravity Coupling Code (Bridge) bridge_code = Bridge(verbose=False) bridge_code.add_system(multiples_code, (galactic_code,)) #bridge_code.timestep = delta_t # ---------------------------------------------------------------------------------------------------- # ------------------------------------- # # Setting up Required Channels # # ------------------------------------- #