Exemplo n.º 1
0
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()
Exemplo n.º 2
0
 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)
Exemplo n.º 3
0
 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)
Exemplo n.º 4
0
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()
Exemplo n.º 5
0
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()
Exemplo n.º 6
0
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
Exemplo n.º 7
0
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()
Exemplo n.º 8
0
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
Exemplo n.º 9
0
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
Exemplo n.º 10
0
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()
Exemplo n.º 11
0
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()
Exemplo n.º 12
0
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()
Exemplo n.º 13
0
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 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()
Exemplo n.º 15
0
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()
Exemplo n.º 16
0
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
Exemplo n.º 17
0
    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
Exemplo n.º 18
0
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()
Exemplo n.º 19
0
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
Exemplo n.º 20
0
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()
Exemplo n.º 21
0
    # Increase the Step Counter
        step_index += 1
    # Log that a Step was Taken
        print '\n-------------'
        print '[UPDATE] Step Taken at %s!' %(tp.strftime("%Y/%m/%d-%H:%M:%S", tp.gmtime()))
        print '-------------\n'
        sys.stdout.flush()
    
# Log that the Simulation Ended & Switch to Terminal Output
    print '\n[UPDATE] Run Finished at %s! \n' %(tp.strftime("%Y/%m/%d-%H:%M:%S", tp.gmtime()))
    sys.stdout = orig_stdout
    f.close()

# Pickle the Final Encounter Information Dictionary
    encounter_file = open("Encounters/"+cluster_name+"_encounters.pkl", "wb")
    pickle.dump(encounterInformation, encounter_file)
    encounter_file.close()

# Alerts the Terminal User that the Run has Ended!
    print '\n[UPDATE] Run Finished at %s! \n' %(tp.strftime("%Y/%m/%d-%H:%M:%S", tp.gmtime()))
    sys.stdout.flush()
    print_diagnostics(multiples_code, E0)

# Closes PH4, Kepler & SmallN Instances
    sev_code.stop()
    gravity.stop()
    kep.stop()
    util.stop_smalln()
    bridge_code.stop()
Exemplo n.º 22
0
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
Exemplo n.º 23
0
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()
Exemplo n.º 24
0
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()
Exemplo n.º 25
0
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()
Exemplo n.º 26
0
    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
Exemplo n.º 27
0
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()
Exemplo n.º 28
0
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