Exemplo n.º 1
0
def crash_test(method=1):
  code=Kepler(redirection="none")

  code.set_method(method)

  smu=1.224744871391589
  mu=smu**2
  r0=2.787802728537455
  rv0=-0.9899959571994231
  alpha=0.01380749549277993
  smudt=2.809925892593303
  v02=(mu*(2/r0-alpha))
  vx=rv0
  vy=(v02-vx**2)**0.5

  sun=Particle()
  sun.mass=mu | nbody_system.mass
  sun.x=0. | nbody_system.length
  sun.y=0. | nbody_system.length
  sun.z=0. | nbody_system.length
  sun.vx=0. | nbody_system.speed
  sun.vy=0. | nbody_system.speed
  sun.vz=0. | nbody_system.speed

  comet=Particle()
  comet.mass= 0 | nbody_system.mass
  comet.x=r0| nbody_system.length
  comet.y=0. | nbody_system.length
  comet.z=0. | nbody_system.length
  comet.vx=vx | nbody_system.speed
  comet.vy=vy | nbody_system.speed
  comet.vz=0. | nbody_system.speed

  tend=(smudt/smu) | nbody_system.time
  print tend

  code.central_particle.add_particle(sun)
  code.orbiters.add_particle(comet)

  a0,eps0=elements(sun.mass,code.orbiters.x,code.orbiters.y,code.orbiters.z,
                     code.orbiters.vx,code.orbiters.vy,code.orbiters.vz,G=nbody_system.G)

  print orbital_elements_from_binary(code.particles[0:2])

  t1=time.time()
  code.evolve_model(tend)
  t2=time.time()

  print orbital_elements_from_binary(code.particles[0:2])

  print code.orbiters.position

  a,eps=elements(sun.mass,code.orbiters.x,code.orbiters.y,code.orbiters.z,
                     code.orbiters.vx,code.orbiters.vy,code.orbiters.vz,G=nbody_system.G)

  da=abs((a-a0)/a0)
  deps=abs(eps-eps0)/eps0

  print da,deps
  print "time:",t2-t1
Exemplo n.º 2
0
def test_kepler_parabolic( tend=1,method=0, sign=+1):
  code=Kepler(redirection="none")

  code.set_method(method)

  sun=Particle()
  sun.mass=1. | nbody_system.mass
  sun.x=0. | nbody_system.length
  sun.y=0. | nbody_system.length
  sun.z=0. | nbody_system.length
  sun.vx=0. | nbody_system.speed
  sun.vy=0. | nbody_system.speed
  sun.vz=0. | nbody_system.speed

  comet=Particle()
  comet.mass= 0 | nbody_system.mass
  comet.x=1. | nbody_system.length
  comet.y=0. | nbody_system.length
  comet.z=0. | nbody_system.length
  comet.vx=0. | nbody_system.speed
  comet.vy=(1.0 + sign * 1.0e-10)*(2*nbody_system.G*sun.mass/comet.x)**0.5
  comet.vz=0. | nbody_system.speed

  tend=tend | nbody_system.time
  print tend

  code.central_particle.add_particle(sun)
  code.orbiters.add_particle(comet)

  a0,eps0=elements(sun.mass,code.orbiters.x,code.orbiters.y,code.orbiters.z,
                     code.orbiters.vx,code.orbiters.vy,code.orbiters.vz,G=nbody_system.G)

  print orbital_elements_from_binary(code.particles[0:2])

  t1=time.time()
  code.evolve_model(tend)
  t2=time.time()

  print orbital_elements_from_binary(code.particles[0:2])

  print code.orbiters.position

  a,eps=elements(sun.mass,code.orbiters.x,code.orbiters.y,code.orbiters.z,
                     code.orbiters.vx,code.orbiters.vy,code.orbiters.vz,G=nbody_system.G)

  da=abs((a-a0)/a0)
  deps=abs(eps-eps0)/eps0

  print da,deps
  print "time:",t2-t1
Exemplo n.º 3
0
    def result(self):
        if self.pickle_file is None:
            self.retrieve_stellar_structure()
        else:
            self.unpickle_stellar_structure()

        if self.with_core_particle:
            self.setup_core_parameters()

        sph_particles = self.convert_to_SPH()
        if self.do_relax:
            for result_string in self.relax(sph_particles):
                print(result_string)

        specific_internal_energy, composition, mu = self.interpolate_internal_energy(
            sph_particles.position.lengths(),
            do_composition_too = self.do_store_composition
        )
        sph_particles.u = specific_internal_energy
        if self.do_store_composition:
            sph_particles.add_vector_attribute("composition", self.species_names)
            sph_particles.composition = composition
            sph_particles.mu = mu

        if self.with_core_particle and self.core_radius:
            core_particle = Particle()
            core_particle.mass = self.core_mass
            core_particle.position = [0.0, 0.0, 0.0] | units.m
            core_particle.velocity = [0.0, 0.0, 0.0] | units.m / units.s
            core_particle.radius = self.core_radius
            return StellarModelInSPH(gas_particles=sph_particles, core_particle=core_particle, core_radius=self.core_radius)
        return StellarModelInSPH(gas_particles=sph_particles, core_particle=None, core_radius=None)
Exemplo n.º 4
0
 def test11(self):
     print "Test that a source is not included when calculating gravity on itself."
     number_of_sources = 100
     mass, length, G = nbody_system.mass, nbody_system.length, nbody_system.G
     sources = Particles(mass=numpy.ones(number_of_sources)|mass, x=0|length, y=0|length, z=0|length)
     point = Particle(x=0|length, y=0|length, z=1.0|length)
     
     instance = self.new_fastkick_instance()
     instance.particles.add_particles(sources)
     potential = instance.get_potential_at_point(0|length, point.x, point.y, point.z)
     ax, ay, az = instance.get_gravity_at_point(0|length, point.x, point.y, point.z)
     self.assertAlmostEqual(ax, G * (0 | mass/length**2), 5)
     self.assertAlmostEqual(ay, G * (0 | mass/length**2), 5)
     self.assertAlmostRelativeEqual(az, -G*sources.total_mass()/point.z**2, 3)
     self.assertAlmostRelativeEqual(potential, -G*sources.total_mass()/point.z, 3)
     
     point.mass = 1e6 | mass
     instance.particles.add_particle(point)
     potential = instance.get_potential_at_point(0|length, point.x, point.y, point.z)
     ax, ay, az = instance.get_gravity_at_point(0|length, point.x, point.y, point.z)
     self.assertAlmostEqual(ax, G * (0 | mass/length**2), 5)
     self.assertAlmostEqual(ay, G * (0 | mass/length**2), 5)
     self.assertAlmostRelativeEqual(az, -G*sources.total_mass()/point.z**2, 3)
     self.assertAlmostRelativeEqual(potential, -G*sources.total_mass()/point.z, 3)
     instance.stop()
Exemplo n.º 5
0
    def test7(self):
        print "Testing Pikachu states"
        stars = new_plummer_model(100)
        black_hole = Particle()
        black_hole.mass = 1.0 | nbody_system.mass
        black_hole.radius = 0.0 | nbody_system.length
        black_hole.position = [0.0, 0.0, 0.0] | nbody_system.length
        black_hole.velocity = [0.0, 0.0, 0.0] | nbody_system.speed

        print "First do everything manually:"
        instance = self.new_instance_of_an_optional_code(
            Pikachu, **default_options)
        self.assertEquals(instance.get_name_of_current_state(),
                          'UNINITIALIZED')
        instance.initialize_code()
        self.assertEquals(instance.get_name_of_current_state(), 'INITIALIZED')
        #~        instance.parameters.rcut_out_star_star = 1.0 | nbody_system.length
        instance.parameters.timestep = 0.001 | nbody_system.time
        instance.commit_parameters()
        self.assertEquals(instance.get_name_of_current_state(), 'EDIT')
        instance.particles.add_particles(stars)
        instance.commit_particles()
        self.assertEquals(instance.get_name_of_current_state(), 'RUN')
        instance.particles.remove_particle(stars[0])
        instance.particles.add_particle(black_hole)
        self.assertEquals(instance.get_name_of_current_state(), 'UPDATE')
        instance.recommit_particles()
        self.assertEquals(instance.get_name_of_current_state(), 'RUN')
        instance.evolve_model(0.001 | nbody_system.time)
        self.assertEquals(instance.get_name_of_current_state(), 'EVOLVED')
        instance.synchronize_model()
        self.assertEquals(instance.get_name_of_current_state(), 'RUN')
        instance.cleanup_code()
        self.assertEquals(instance.get_name_of_current_state(), 'END')
        instance.stop()

        print "initialize_code(), commit_parameters(), (re)commit_particles(), " \
            "synchronize_model(), and cleanup_code() should be called " \
            "automatically before editing parameters, new_particle(), get_xx(), and stop():"
        instance = self.new_instance_of_an_optional_code(
            Pikachu, **default_options)
        self.assertEquals(instance.get_name_of_current_state(),
                          'UNINITIALIZED')
        instance.parameters.timestep = 0.001 | nbody_system.time
        self.assertEquals(instance.get_name_of_current_state(), 'INITIALIZED')
        instance.particles.add_particles(stars)
        self.assertEquals(instance.get_name_of_current_state(), 'EDIT')
        mass = instance.particles[0].mass
        self.assertEquals(instance.get_name_of_current_state(), 'RUN')
        instance.particles.remove_particle(stars[0])
        instance.particles.add_particle(black_hole)
        self.assertEquals(instance.get_name_of_current_state(), 'UPDATE')
        mass = instance.particles[0].mass
        self.assertEquals(instance.get_name_of_current_state(), 'RUN')
        instance.evolve_model(0.001 | nbody_system.time)
        self.assertEquals(instance.get_name_of_current_state(), 'EVOLVED')
        mass = instance.particles[0].mass
        self.assertEquals(instance.get_name_of_current_state(), 'RUN')
        instance.stop()
        self.assertEquals(instance.get_name_of_current_state(), 'STOPPED')
Exemplo n.º 6
0
    def result(self):
        if self.pickle_file is None:
            self.retrieve_stellar_structure()
        else:
            self.unpickle_stellar_structure()

        if self.with_core_particle:
            self.setup_core_parameters()

        sph_particles = self.convert_to_SPH()
        if self.do_relax:
            for result_string in self.relax(sph_particles):
                print result_string

        specific_internal_energy, composition, mu = self.interpolate_internal_energy(
            sph_particles.position.lengths(),
            do_composition_too = self.do_store_composition
        )
        sph_particles.u = specific_internal_energy
        if self.do_store_composition:
            sph_particles.add_vector_attribute("composition", self.species_names)
            sph_particles.composition = composition
            sph_particles.mu = mu

        if self.with_core_particle and self.core_radius:
            core_particle = Particle()
            core_particle.mass = self.core_mass
            core_particle.position = [0.0, 0.0, 0.0] | units.m
            core_particle.velocity = [0.0, 0.0, 0.0] | units.m / units.s
            core_particle.radius = self.core_radius
            return StellarModelInSPH(gas_particles=sph_particles, core_particle=core_particle, core_radius=self.core_radius)
        return StellarModelInSPH(gas_particles=sph_particles, core_particle=None, core_radius=None)
Exemplo n.º 7
0
def make_binary_star(mprim, msec, semimajor_axis, eccentricity):
    double_star = Particle()
    double_star.is_binary = True
    double_star.mass = mprim + msec
    double_star.semimajor_axis = semimajor_axis
    double_star.eccentricity = eccentricity

    period = (2 * numpy.pi *
              (semimajor_axis * semimajor_axis * semimajor_axis /
               (constants.G * double_star.mass)).sqrt())
    print("Period =", period.as_string_in(units.yr))

    stars = new_binary_from_orbital_elements(mprim,
                                             msec,
                                             semimajor_axis,
                                             eccentricity,
                                             G=constants.G)
    stars.is_binary = False
    double_star.child1 = stars[0]
    double_star.child1.name = "primary"

    double_star.child2 = stars[1]
    double_star.child2.name = "secondary"

    for star in stars:
        star.radius = (star.mass.value_in(units.MSun)**0.8) | units.RSun

    return double_star, stars
Exemplo n.º 8
0
def new_single_star(mass, pos, vel):
    single_star = Particle()
    single_star.mass = mass
    single_star.position = pos
    single_star.velocity = vel
    single_star.radius = 1.0 | units.RSun
    return single_star
Exemplo n.º 9
0
def form_new_star(
    densest_gas_particle,
    gas_particles,
    # density_threshold=
):
    """
    Forms a new star by merging all gas particles within a Jeans radius of the
    densest particle. Returns the new star and all particles used to make it.
    """
    new_star = Particle()
    gas_copy = gas_particles.copy()

    # densest_gas_particle = gas_copy.sorted_by_attribute("density")[0]
    jeans_radius = 0.025 | units.parsec  # 100 | units.AU
    gas_copy.position -= densest_gas_particle.position
    gas_copy.distance_to_core = gas_copy.position.lengths()
    dense_gas = gas_copy.select(lambda x: x < jeans_radius,
                                ["distance_to_core"])
    new_star.mass = dense_gas.mass.sum()
    new_star.position = (dense_gas.center_of_mass() +
                         densest_gas_particle.position)
    new_star.velocity = dense_gas.center_of_mass_velocity()
    new_star.radius = jeans_radius
    absorbed_gas = dense_gas

    return new_star, absorbed_gas
Exemplo n.º 10
0
def new_single_star(mass, pos, vel):
    single_star = Particle()
    single_star.mass = mass
    single_star.position = pos
    single_star.velocity = vel
    single_star.radius = 1.0 | units.RSun
    return single_star
Exemplo n.º 11
0
def main():
    temperatures_original = [] | units.K
    luminosities_original = [] | units.LSun
    temperatures_helium = [] | units.K
    luminosities_helium = [] | units.LSun
    
    star =  Particle()
    star.mass = 12.0 | units.MSun
    stop_radius = 100 | units.RSun
    
    stellar_evolution = MESA()
    se_star = stellar_evolution.particles.add_particle(star)
    
    print("Evolving a", star.mass, "star with",
          stellar_evolution.__class__.__name__, end=' ') 
    print("until its radius exceeds", stop_radius)
    while (se_star.radius < stop_radius):
        se_star.evolve_one_step()
        temperatures_original.append(se_star.temperature)
        luminosities_original.append(se_star.luminosity)

###BOOKLISTSTART1###
    number_of_zones = se_star.get_number_of_zones()
    composition     = se_star.get_chemical_abundance_profiles()
    index = (composition[0] > 1.0e-9).nonzero()[0][0] # first zone with X > 1.0e-9
    
    print("Creating helium star, from the inner", index,
          "(out of", str(number_of_zones)+") shells.")
    helium_star = stellar_evolution.new_particle_from_model(dict(
        mass = (se_star.get_cumulative_mass_profile() * se_star.mass)[:index],
        radius = se_star.get_radius_profile()[:index],
        rho    = se_star.get_density_profile()[:index],
        temperature = se_star.get_temperature_profile()[:index],
        luminosity  = se_star.get_luminosity_profile()[:index],
        X_H  = composition[0][:index],
        X_He = composition[1][:index] + composition[2][:index],
        X_C  = composition[3][:index],
        X_N  = composition[4][:index],
        X_O  = composition[5][:index],
        X_Ne = composition[6][:index],
        X_Mg = composition[7][:index],
        X_Si = composition[7][:index]*0.0,
        X_Fe = composition[7][:index]*0.0), 0.0 | units.Myr)
###BOOKLISTSTOP1###

    print("\nStar properties before helium star evolution:\n",
          stellar_evolution.particles)
    for i in range(1000):
        helium_star.evolve_one_step()
        temperatures_helium.append(helium_star.temperature)
        luminosities_helium.append(helium_star.luminosity)
    print("\nStar properties after helium star evolution:\n",
          stellar_evolution.particles)
    
    stellar_evolution.stop()
    return temperatures_original, luminosities_original, \
           temperatures_helium, luminosities_helium
Exemplo n.º 12
0
def main():
    temperatures_original = [] | units.K
    luminosities_original = [] | units.LSun
    temperatures_helium = [] | units.K
    luminosities_helium = [] | units.LSun
    
    star =  Particle()
    star.mass = 12.0 | units.MSun
    stop_radius = 100 | units.RSun
    
    stellar_evolution = MESA()
    se_star = stellar_evolution.particles.add_particle(star)
    
    print("Evolving a", star.mass, "star with",
          stellar_evolution.__class__.__name__, end=' ') 
    print("until its radius exceeds", stop_radius)
    while (se_star.radius < stop_radius):
        se_star.evolve_one_step()
        temperatures_original.append(se_star.temperature)
        luminosities_original.append(se_star.luminosity)

###BOOKLISTSTART1###
    number_of_zones = se_star.get_number_of_zones()
    composition     = se_star.get_chemical_abundance_profiles()
    index = (composition[0] > 1.0e-9).nonzero()[0][0] # first zone with X > 1.0e-9
    
    print("Creating helium star, from the inner", index,
          "(out of", str(number_of_zones)+") shells.")
    helium_star = stellar_evolution.new_particle_from_model(dict(
        mass = (se_star.get_cumulative_mass_profile() * se_star.mass)[:index],
        radius = se_star.get_radius_profile()[:index],
        rho    = se_star.get_density_profile()[:index],
        temperature = se_star.get_temperature_profile()[:index],
        luminosity  = se_star.get_luminosity_profile()[:index],
        X_H  = composition[0][:index],
        X_He = composition[1][:index] + composition[2][:index],
        X_C  = composition[3][:index],
        X_N  = composition[4][:index],
        X_O  = composition[5][:index],
        X_Ne = composition[6][:index],
        X_Mg = composition[7][:index],
        X_Si = composition[7][:index]*0.0,
        X_Fe = composition[7][:index]*0.0), 0.0 | units.Myr)
###BOOKLISTSTOP1###

    print("\nStar properties before helium star evolution:\n",
          stellar_evolution.particles)
    for i in range(1000):
        helium_star.evolve_one_step()
        temperatures_helium.append(helium_star.temperature)
        luminosities_helium.append(helium_star.luminosity)
    print("\nStar properties after helium star evolution:\n",
          stellar_evolution.particles)
    
    stellar_evolution.stop()
    return temperatures_original, luminosities_original, \
           temperatures_helium, luminosities_helium
Exemplo n.º 13
0
 def new_particle_from_model(self,
                             internal_structure,
                             current_age,
                             key=None):
     tmp_star = Particle(key=key)
     tmp_star.mass = internal_structure["mass"]
     tmp_star.radius = internal_structure["radius"]
     tmp_star.type = "new particle from model"
     return self.particles.add_particle(tmp_star)
Exemplo n.º 14
0
    def test7(self):
        print "Testing Pikachu states"
        stars = new_plummer_model(100)
        black_hole = Particle()
        black_hole.mass = 1.0 | nbody_system.mass
        black_hole.radius =  0.0 | nbody_system.length
        black_hole.position = [0.0, 0.0, 0.0] | nbody_system.length
        black_hole.velocity = [0.0, 0.0, 0.0] | nbody_system.speed
        
        print "First do everything manually:"
        instance = self.new_instance_of_an_optional_code(Pikachu, **default_options)
        self.assertEquals(instance.get_name_of_current_state(), 'UNINITIALIZED')
        instance.initialize_code()
        self.assertEquals(instance.get_name_of_current_state(), 'INITIALIZED')
#~        instance.parameters.rcut_out_star_star = 1.0 | nbody_system.length
        instance.parameters.timestep = 0.001 | nbody_system.time
        instance.commit_parameters()
        self.assertEquals(instance.get_name_of_current_state(), 'EDIT')
        instance.particles.add_particles(stars)
        instance.commit_particles()
        self.assertEquals(instance.get_name_of_current_state(), 'RUN')
        instance.particles.remove_particle(stars[0])
        instance.particles.add_particle(black_hole)
        self.assertEquals(instance.get_name_of_current_state(), 'UPDATE')
        instance.recommit_particles()
        self.assertEquals(instance.get_name_of_current_state(), 'RUN')
        instance.evolve_model(0.001 | nbody_system.time)
        self.assertEquals(instance.get_name_of_current_state(), 'EVOLVED')
        instance.synchronize_model()
        self.assertEquals(instance.get_name_of_current_state(), 'RUN')
        instance.cleanup_code()
        self.assertEquals(instance.get_name_of_current_state(), 'END')
        instance.stop()
        
        print "initialize_code(), commit_parameters(), (re)commit_particles(), " \
            "synchronize_model(), and cleanup_code() should be called " \
            "automatically before editing parameters, new_particle(), get_xx(), and stop():"
        instance = self.new_instance_of_an_optional_code(Pikachu, **default_options)
        self.assertEquals(instance.get_name_of_current_state(), 'UNINITIALIZED')
        instance.parameters.timestep = 0.001 | nbody_system.time
        self.assertEquals(instance.get_name_of_current_state(), 'INITIALIZED')
        instance.particles.add_particles(stars)
        self.assertEquals(instance.get_name_of_current_state(), 'EDIT')
        mass = instance.particles[0].mass
        self.assertEquals(instance.get_name_of_current_state(), 'RUN')
        instance.particles.remove_particle(stars[0])
        instance.particles.add_particle(black_hole)
        self.assertEquals(instance.get_name_of_current_state(), 'UPDATE')
        mass = instance.particles[0].mass
        self.assertEquals(instance.get_name_of_current_state(), 'RUN')
        instance.evolve_model(0.001 | nbody_system.time)
        self.assertEquals(instance.get_name_of_current_state(), 'EVOLVED')
        mass = instance.particles[0].mass
        self.assertEquals(instance.get_name_of_current_state(), 'RUN')
        instance.stop()
        self.assertEquals(instance.get_name_of_current_state(), 'STOPPED')
Exemplo n.º 15
0
def merge_two_stars(primary, secondary):
    "Merge two colliding stars into one new one"
    colliders = Particles()
    colliders.add_particle(primary)
    colliders.add_particle(secondary)
    new_particle = Particle()
    new_particle.mass = colliders.mass.sum()
    new_particle.position = colliders.center_of_mass()
    new_particle.velocity = colliders.center_of_mass_velocity()

    return new_particle
Exemplo n.º 16
0
    def xtest7(self):
        instance = self.new_instance_of_an_optional_code(SeBa)
        instance.parameters.metallicity = 0.03
        p = Particle()
        p.mass = 99.1605930967 | units.MSun

        p = instance.particles.add_particle(p)
        instance.evolve_model(614 | units.Myr)
        print(p.stellar_type)
        self.assertEqual(str(p.stellar_type), 'Black Hole')
        self.assertAlmostRelativeEqual(p.mass, 0.9906 | units.MSun, 4)
Exemplo n.º 17
0
    def xtest7(self):
        instance = self.new_instance_of_an_optional_code(SeBa)
        instance.parameters.metallicity = 0.03
        p = Particle()
        p.mass = 99.1605930967 | units.MSun

        p = instance.particles.add_particle(p)
        instance.evolve_model(614 | units.Myr)
        print p.stellar_type
        self.assertEquals(str(p.stellar_type),'Black Hole')
        self.assertAlmostRelativeEqual(p.mass, 0.9906 | units.MSun, 4)
Exemplo n.º 18
0
def set_up_outer_star(inner_binary_mass):
    semimajor_axis = 1.22726535008 | units.AU
    eccentricity = 0.15
    inclination = math.radians(9.0)
    
    print "   Initializing outer star"
    giant = Particle()
    giant.mass = 5.5 | units.MSun
    giant.position = semimajor_axis * ([math.cos(inclination), 0, math.sin(inclination)] | units.none)
    giant.velocity = get_relative_velocity(giant.mass + inner_binary_mass, 
        semimajor_axis, eccentricity) * ([0, 1, 0] | units.none)
    return giant
Exemplo n.º 19
0
def set_up_outer_star(inner_binary_mass):
    semimajor_axis = 1.22726535008 | units.AU
    eccentricity = 0.15
    inclination = math.radians(9.0)
    
    print("   Initializing outer star")
    giant = Particle()
    giant.mass = 5.5 | units.MSun
    giant.position = semimajor_axis * ([math.cos(inclination), 0, math.sin(inclination)] | units.none)
    giant.velocity = get_relative_velocity(giant.mass + inner_binary_mass, 
        semimajor_axis, eccentricity) * ([0, 1, 0] | units.none)
    return giant
Exemplo n.º 20
0
    def test2(self):
        instance = self.new_instance_of_an_optional_code(SeBa)

        p = Particle()
        p.mass = 5 | units.MSun
        p.metallicity = 0.02

        p = instance.particles.add_particle(p)
        instance.evolve_model(130 | units.Myr)
        print(p)

        self.assertAlmostRelativeEqual(p.mass, 0.9906 | units.MSun, 4)
Exemplo n.º 21
0
    def test2(self):
        instance = self.new_instance_of_an_optional_code(SeBa)

        p = Particle()
        p.mass = 5 | units.MSun
        p.metallicity = 0.02

        p = instance.particles.add_particle(p)
        instance.evolve_model(130 | units.Myr)
        print p

        self.assertAlmostRelativeEqual(p.mass, 0.9906 | units.MSun, 4)
Exemplo n.º 22
0
def set_up_outer_star(inner_binary_mass):
    semimajor_axis = triple_parameters["a_out"]
    eccentricity = triple_parameters["eccentricity_out"]
    print "   Initializing outer star"
    giant = Particle()
    giant.mass = triple_parameters["mass_out"]
    giant.position = semimajor_axis * (1 + eccentricity) * ([1, 0, 0]
                                                            | units.none)
    giant.velocity = get_relative_velocity_at_apastron(
        giant.mass + inner_binary_mass, semimajor_axis,
        eccentricity) * ([0, 1, 0] | units.none)
    return giant
Exemplo n.º 23
0
 def test1(self):
     print "Testing FastKick (SI)"
     sun = Particle()
     sun.mass = 1.0|units.MSun
     sun.position = [0, 0, 0] | units.m
     convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.AU)
     fastkick = self.new_fastkick_instance(convert_nbody)
     fastkick.particles.add_particle(sun)
     ax, ay, az = fastkick.get_gravity_at_point(0|units.AU, 1|units.AU, 0|units.AU, 0|units.AU)
     fastkick.stop()
     self.assertAlmostRelativeEqual(ax, -4*math.pi**2 | units.AU / units.yr**2, 3)
     self.assertAlmostRelativeEqual(ay, 0 | units.m * units.s**-2, 6)
     self.assertAlmostRelativeEqual(az, 0 | units.m * units.s**-2, 6)
def new_system(star_mass=1 | units.MSun,
               star_radius=1 | units.RSun,
               disk_minimum_radius=0.05 | units.AU,
               disk_maximum_radius=10 | units.AU,
               disk_mass=20 | MEarth,
               accurancy=0.0001,
               planet_density=3 | units.g / units.cm**3,
               rng=None,
               kepler=None):

    central_particle = Particle()
    central_particle.mass = star_mass
    central_particle.position = (0, 0, 0) | units.AU
    central_particle.velocity = (0, 0, 0) | units.kms
    central_particle.radius = star_radius
    central_particle.name = "star"
    central_particle.type = "star"
    central_particle.id = 0

    if rng is None:
        rng = numpy.random

    converter = nbody_system.nbody_to_si(1 | units.MSun, 1 | units.AU)

    if kepler is None:
        kepler = Kepler(converter)
        kepler.initialize_code()

    m, r, f = new_planet_distribution(disk_minimum_radius, disk_maximum_radius,
                                      disk_mass, accurancy)

    planets = make_planets(central_particle,
                           m,
                           r,
                           density=planet_density,
                           phi=0,
                           theta=None,
                           kepler=kepler,
                           rng=rng)
    planets.name = "planet"
    planets.type = "planet"
    for i in range(len(planets)):
        planets[i].id = i

    central_particle.planets = planets
    kepler.stop()
    p = Particles()
    p.add_particle(central_particle)
    return p
Exemplo n.º 25
0
def create_particles():
    star = Particle()
    star.mass = 3.0 | units.MSun

    stellar_evolution = EVtwin()
    se_star = stellar_evolution.particles.add_particle(star)

    print("Evolving", star.mass, "star with",
          stellar_evolution.__class__.__name__, "up to", 100 | units.Myr)
    stellar_evolution.evolve_model(100 | units.Myr)

    print("Creating SPH particles from the (1D) stellar evolution model")
    sph_particles = convert_stellar_model_to_SPH(se_star, 1000).gas_particles
    stellar_evolution.stop()
    return sph_particles
def get_moons_for_planet(planet, delta_JD=0. | units.day):
    """
  The Earth's moon
  as for JD = 2457099.500000000 = A.D. 2015-Mar-18 00:00:00.0000 (CT)
  https://ssd.jpl.nasa.gov/?sat_elem
  """

    data = numpy.array([tuple(entry) for entry in _lunar_data],
                       dtype=[('planet_name', 'S10'), ('name', 'S10'),
                              ('mass', '<f8'), ('radius', '<f8'),
                              ('semimajor_axis', '<f8'),
                              ('eccentricity', '<f8'),
                              ('argument_of_peri', '<f8'),
                              ('mean_anomaly', '<f8'), ('inclination', '<f8'),
                              ('longitude_oan', '<f8')])
    moon_data = data[data['planet_name'] == planet.name.encode('UTF-8')]
    print("Planet=", planet.name, "moon=", moon_data["name"])
    moons = Particles()
    if len(moon_data["name"]):
        print(len(moon_data["name"]))
        for moon in moon_data:
            #Ignore the moon for now, because it's complicated
            if planet.name == "EarthMoon":
                planet.mass -= moon["mass"] * 1.e+16 | units.kg
                planet.name = "Earth"
            #print moon
            r, v = get_position(planet.mass,
                                moon["mass"] * 1.e+16 | units.kg,
                                moon["eccentricity"],
                                moon["semimajor_axis"] | units.km,
                                numpy.deg2rad(moon["mean_anomaly"]),
                                numpy.deg2rad(moon["inclination"]),
                                numpy.deg2rad(moon["longitude_oan"]),
                                numpy.deg2rad(moon["argument_of_peri"]),
                                delta_t=delta_JD)
            single_moon = Particle()
            single_moon.type = "moon"
            single_moon.name = moon["name"]
            single_moon.mass = moon["mass"] * 1.e+16 | units.kg
            single_moon.hostname = moon["planet_name"]
            single_moon.radius = moon["radius"] | units.km
            single_moon.position = r
            single_moon.position += planet.position
            single_moon.velocity = v
            single_moon.velocity += planet.velocity
            moons.add_particle(single_moon)

    return moons
Exemplo n.º 27
0
 def test1(self):
     print("Testing FastKick (SI)")
     sun = Particle()
     sun.mass = 1.0 | units.MSun
     sun.position = [0, 0, 0] | units.m
     convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun,
                                              1.0 | units.AU)
     fastkick = self.new_fastkick_instance(convert_nbody)
     fastkick.particles.add_particle(sun)
     ax, ay, az = fastkick.get_gravity_at_point(0 | units.AU, 1 | units.AU,
                                                0 | units.AU, 0 | units.AU)
     fastkick.stop()
     self.assertAlmostRelativeEqual(
         ax, -4 * math.pi**2 | units.AU / units.yr**2, 3)
     self.assertAlmostRelativeEqual(ay, 0 | units.m * units.s**-2, 6)
     self.assertAlmostRelativeEqual(az, 0 | units.m * units.s**-2, 6)
Exemplo n.º 28
0
def create_particles():
    star =  Particle()
    star.mass = 3.0 | units.MSun
    
    stellar_evolution = EVtwin()
    se_star = stellar_evolution.particles.add_particle(star)
    
    print("Evolving", star.mass, "star with", stellar_evolution.__class__.__name__, "up to", 100 | units.Myr)
    stellar_evolution.evolve_model(100 | units.Myr)
    
    print("Creating SPH particles from the (1D) stellar evolution model")
    sph_particles = convert_stellar_model_to_SPH(
        se_star, 
        1000
    ).gas_particles
    stellar_evolution.stop()
    return sph_particles
Exemplo n.º 29
0
def new_system(
        star_mass = 1|units.MSun, 
        star_radius = 1|units.RSun, 
        disk_minumum_radius = 0.05 | units.AU,
        disk_maximum_radius = 10 | units.AU,
        disk_mass = 20 | MEarth,
        accurancy = 0.0001, 
        planet_density =  3 | units.g/units.cm**3,
        rng = None,
        kepler = None):
            
    central_particle = Particle()
    central_particle.mass =  star_mass
    central_particle.position = (0,0,0) | units.AU
    central_particle.velocity = (0,0,0) | units.kms
    central_particle.radius = star_radius
    
    if rng is None:
        rng = numpy.random
        
    converter = nbody_system.nbody_to_si(1|units.MSun, 1 | units.AU)
    
    if kepler is None:
        kepler = Kepler(converter)
        kepler.initialize_code()
        
    m, r, f = new_planet_distribution(
        disk_minumum_radius, disk_maximum_radius, 
        disk_mass,
        accurancy
    )
    
    planets = make_planets(
        central_particle, 
        m, r, 
        density = planet_density, 
        phi = 0, theta = None, 
        kepler = kepler, 
        rng = rng
    )
    
    central_particle.planets = planets
    kepler.stop()
    p = Particles()
    p.add_particle(central_particle)
    return p
Exemplo n.º 30
0
def set_up_outer_star(inner_binary_mass):
    orbital_period = 4020.0 | units.day
    mass = 1.3 | units.MSun
    semimajor_axis = (((constants.G *
                        (inner_binary_mass + mass) * orbital_period**2) /
                       (4 * numpy.pi**2))**(1.0 / 3.0)).as_quantity_in(
                           units.RSun)

    print "   Initializing outer star"
    print "   Semimajor axis outer binary:", semimajor_axis
    giant = Particle()
    giant.mass = mass
    giant.position = semimajor_axis * ([1, 0, 0] | units.none)
    giant.velocity = get_relative_velocity(giant.mass + inner_binary_mass,
                                           semimajor_axis,
                                           0) * ([0, 1, 0] | units.none)
    return giant
Exemplo n.º 31
0
    def test10(self):
        """ Test supernova stopping condition """
        instance = self.new_instance_of_an_optional_code(SeBa)
        instance.stopping_conditions.supernova_detection.enable()

        p = Particle()
        p.mass = 10 | units.MSun
        p.metallicity = 0.02

        p = instance.particles.add_particle(p)
        instance.set_supernova_kick_velocity(0.0|units.kms)
        instance.evolve_model(30 | units.Myr)
        self.assertEquals(instance.stopping_conditions.supernova_detection.is_set(), True)
        self.assertEquals(instance.stopping_conditions.supernova_detection.particles(0)[0].key, p.key)

        self.assertAlmostRelativeEqual(p.age, 27.35866 | units.Myr, 4)

        self.assertAlmostRelativeEqual(p.mass, 1.22632 | units.MSun, 4)
        self.assertAlmostRelativeEqual(p.natal_kick_velocity, [0,0,0] | units.kms, 4)
Exemplo n.º 32
0
def old_new_solar_system():
    """
    Create initial conditions describing the solar system. Returns a single 
    particle set containing the sun, planets and Pluto. The model is centered at 
    the origin (center-of-mass(-velocity) coordinates).
    
    Defined attributes: 
    name, mass, radius, x, y, z, vx, vy, vz
    """
    sun = Particle()
    sun.name = 'SUN'
    sun.mass = 1.0 | units.MSun
    sun.radius = 1.0 | units.RSun
    planets = _planets_only()
    
    particles = Particles()
    particles.add_particle(sun)
    particles.add_particles(planets)
    particles.move_to_center()
    return particles
Exemplo n.º 33
0
def get_moons_for_planet(planet, delta_JD=0.|units.day):
  """
  The Earth's moon
  as for JD = 2457099.500000000 = A.D. 2015-Mar-18 00:00:00.0000 (CT)
  https://ssd.jpl.nasa.gov/?sat_elem
  """

  data = numpy.array([tuple(entry) for entry in _lunar_data],
        dtype=[('planet_name','S10'), ('name','S10'), 
        ('mass','<f8'), ('radius','<f8'), ('semimajor_axis','<f8'), 
        ('eccentricity','<f8'), ('argument_of_peri','<f8'),
        ('mean_anomaly','<f8'), ('inclination','<f8'), ('longitude_oan','<f8')])
  moon_data = data[data['planet_name']==planet.name]
  print "Planet=", planet.name, "moon=", moon_data["name"]
  moons = Particles()
  if len(moon_data["name"]):
      print len(moon_data["name"])
      for moon in moon_data:
          #print moon
          r, v = get_position(planet.mass,
                              moon["mass"] * 1.e+16 | units.kg,
                              moon["eccentricity"],
                              moon["semimajor_axis"]|units.km,
                              numpy.deg2rad(moon["mean_anomaly"]),
                              numpy.deg2rad(moon["inclination"]),
                              numpy.deg2rad(moon["longitude_oan"]),
                              numpy.deg2rad(moon["argument_of_peri"]),
                              delta_t=delta_JD)
          single_moon = Particle()
          single_moon.type = "moon"
          single_moon.name = moon["name"]
          single_moon.mass = moon["mass"] * 1.e+16 | units.kg
          single_moon.hostname = moon["planet_name"]
          single_moon.radius = moon["radius"] | units.km
          single_moon.position = r
          single_moon.position += planet.position
          single_moon.velocity = v
          single_moon.velocity += planet.velocity
          moons.add_particle(single_moon)
    
  return moons
Exemplo n.º 34
0
    def test11(self):
        print(
            "Test that a source is not included when calculating gravity on itself."
        )
        number_of_sources = 100
        mass, length, G = nbody_system.mass, nbody_system.length, nbody_system.G
        sources = Particles(mass=numpy.ones(number_of_sources) | mass,
                            x=0 | length,
                            y=0 | length,
                            z=0 | length)
        point = Particle(x=0 | length, y=0 | length, z=1.0 | length)

        instance = self.new_fastkick_instance()
        instance.particles.add_particles(sources)
        potential = instance.get_potential_at_point(0 | length, point.x,
                                                    point.y, point.z)
        ax, ay, az = instance.get_gravity_at_point(0 | length, point.x,
                                                   point.y, point.z)
        self.assertAlmostEqual(ax, G * (0 | mass / length**2), 5)
        self.assertAlmostEqual(ay, G * (0 | mass / length**2), 5)
        self.assertAlmostRelativeEqual(az,
                                       -G * sources.total_mass() / point.z**2,
                                       3)
        self.assertAlmostRelativeEqual(potential,
                                       -G * sources.total_mass() / point.z, 3)

        point.mass = 1e6 | mass
        instance.particles.add_particle(point)
        potential = instance.get_potential_at_point(0 | length, point.x,
                                                    point.y, point.z)
        ax, ay, az = instance.get_gravity_at_point(0 | length, point.x,
                                                   point.y, point.z)
        self.assertAlmostEqual(ax, G * (0 | mass / length**2), 5)
        self.assertAlmostEqual(ay, G * (0 | mass / length**2), 5)
        self.assertAlmostRelativeEqual(az,
                                       -G * sources.total_mass() / point.z**2,
                                       3)
        self.assertAlmostRelativeEqual(potential,
                                       -G * sources.total_mass() / point.z, 3)
        instance.stop()
Exemplo n.º 35
0
    def test10(self):
        """ Test supernova stopping condition """
        instance = self.new_instance_of_an_optional_code(SeBa)
        instance.stopping_conditions.supernova_detection.enable()

        p = Particle()
        p.mass = 10 | units.MSun
        p.metallicity = 0.02

        p = instance.particles.add_particle(p)
        instance.set_supernova_kick_velocity(0.0 | units.kms)
        instance.evolve_model(30 | units.Myr)
        self.assertEqual(
            instance.stopping_conditions.supernova_detection.is_set(), True)
        self.assertEqual(
            instance.stopping_conditions.supernova_detection.particles(0)
            [0].key, p.key)

        self.assertAlmostRelativeEqual(p.age, 27.35866 | units.Myr, 4)

        self.assertAlmostRelativeEqual(p.mass, 1.22632 | units.MSun, 4)
        self.assertAlmostRelativeEqual(p.natal_kick_velocity,
                                       [0, 0, 0] | units.kms, 4)
Exemplo n.º 36
0
def crash_test2(method=1):
  code=Kepler(redirection="none")

  code.set_method(method)

  """
  mu=struct.unpack('!d','3ff7ffffffffffff'.decode('hex'))[0]
  dt=struct.unpack('!d','40025ab746b00001'.decode('hex'))[0]
  pos1=struct.unpack('!d','bfed36dc82998ed4'.decode('hex'))[0]
  pos2=struct.unpack('!d','40051297fc6e5256'.decode('hex'))[0]
  pos3=struct.unpack('!d','0000000000000000'.decode('hex'))[0]
  vel1=struct.unpack('!d','3fb09d8008ba33b9'.decode('hex'))[0]
  vel2=struct.unpack('!d','bff06788b551b81d'.decode('hex'))[0]
  vel3=struct.unpack('!d','0000000000000000'.decode('hex'))[0]
  """
  mu=float.fromhex("0x1.8p+0")
  dt=float.fromhex("0x1.25ab746bp+1")
  pos1=float.fromhex("-0x1.d36dc82998ed4p-1")
  pos2=float.fromhex("0x1.51297fc6e5256p+1")
  pos3=float.fromhex("0x0p+0")
  vel1=float.fromhex("0x1.09d8008ba33b9p-4")
  vel2=float.fromhex("-0x1.06788b551b81ep+0")
  vel3=float.fromhex("0x0p+0")

  sun=Particle()
  sun.mass=mu | nbody_system.mass
  sun.x=0. | nbody_system.length
  sun.y=0. | nbody_system.length
  sun.z=0. | nbody_system.length
  sun.vx=0. | nbody_system.speed
  sun.vy=0. | nbody_system.speed
  sun.vz=0. | nbody_system.speed

  comet=Particle()
  comet.mass= 0 | nbody_system.mass
  comet.x=pos1 | nbody_system.length
  comet.y=pos2 | nbody_system.length
  comet.z=pos3 | nbody_system.length
  comet.vx=vel1 | nbody_system.speed
  comet.vy=vel2 | nbody_system.speed
  comet.vz=vel3 | nbody_system.speed

  tend=dt | nbody_system.time
  print tend,mu

  code.central_particle.add_particle(sun)
  code.orbiters.add_particle(comet)

  a0,eps0=elements(sun.mass,code.orbiters.x,code.orbiters.y,code.orbiters.z,
                     code.orbiters.vx,code.orbiters.vy,code.orbiters.vz,G=nbody_system.G)

  print orbital_elements_from_binary(code.particles[0:2])

  t1=time.time()
  code.evolve_model(tend)
  t2=time.time()

  print orbital_elements_from_binary(code.particles[0:2])

  print code.orbiters.position

  a,eps=elements(sun.mass,code.orbiters.x,code.orbiters.y,code.orbiters.z,
                     code.orbiters.vx,code.orbiters.vy,code.orbiters.vz,G=nbody_system.G)

  da=abs((a-a0)/a0)
  deps=abs(eps-eps0)/eps0

  print da,deps
  print "time:",t2-t1
Exemplo n.º 37
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.º 38
0
 def new_particle_from_model(self, internal_structure, current_age, key=None):
     tmp_star = Particle(key=key)
     tmp_star.mass = internal_structure["mass"]
     tmp_star.radius = internal_structure["radius"]
     tmp_star.type = "new particle from model" | units.string
     return self.particles.add_particle(tmp_star)
Exemplo n.º 39
0
def test_softening(method=1):
  code=Kepler(redirection="none")

  code.set_method(method)

  dt=float.fromhex("0x1.67b39e372f04dp+4")
  mu=float.fromhex("0x1.fffffffffffdfp-3")
  e2=float.fromhex("0x1.0000000000003p+0")
  pos1=float.fromhex("0x1.1b76542265052p-1")
  pos2=float.fromhex("0x1.0c4dbda42097cp-6")
  pos3=float.fromhex("0x1.54fd66cd1e212p-3")
  vel1=float.fromhex("0x1.d6ef43d58ca7ep-2")
  vel2=float.fromhex("0x1.7a85379e59794p-2")
  vel3=float.fromhex("-0x1.5421044d1acffp-1")

  sun=Particle()
  sun.mass=mu | nbody_system.mass
  sun.x=0. | nbody_system.length
  sun.y=0. | nbody_system.length
  sun.z=0. | nbody_system.length
  sun.vx=0. | nbody_system.speed
  sun.vy=0. | nbody_system.speed
  sun.vz=0. | nbody_system.speed

  comet=Particle()
  comet.mass= 0 | nbody_system.mass
  comet.x=pos1 | nbody_system.length
  comet.y=pos2 | nbody_system.length
  comet.z=pos3 | nbody_system.length
  comet.vx=vel1 | nbody_system.speed
  comet.vy=vel2 | nbody_system.speed
  comet.vz=vel3 | nbody_system.speed

  tend=dt | nbody_system.time
  print tend,mu

  code.central_particle.add_particle(sun)
  code.orbiters.add_particle(comet)

  code.parameters.epsilon_squared = e2 | nbody_system.length**2

  a0,eps0=elements(sun.mass,code.orbiters.x,code.orbiters.y,code.orbiters.z,
                     code.orbiters.vx,code.orbiters.vy,code.orbiters.vz,G=nbody_system.G)

  print orbital_elements_from_binary(code.particles[0:2])

  t1=time.time()
  code.evolve_model(tend)
  t2=time.time()

  print orbital_elements_from_binary(code.particles[0:2])

  print code.orbiters.position

  a,eps=elements(sun.mass,code.orbiters.x,code.orbiters.y,code.orbiters.z,
                     code.orbiters.vx,code.orbiters.vy,code.orbiters.vz,G=nbody_system.G)

  da=abs((a-a0)/a0)
  deps=abs(eps-eps0)/eps0

  print da,deps
  print "time:",t2-t1
Exemplo n.º 40
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.º 41
0
def get_sun_and_planets(delta_JD=0.|units.day):
  """
  eight planets of the Solar System
  as for JD = 2457099.500000000 = A.D. 2015-Mar-18 00:00:00.0000 (CT)
  http://ssd.jpl.nasa.gov/horizons.cgi
  """
  planets = Particles(8)
  
  # mass
  planets.mass = [3.302e23,
                  48.685e23,
                  5.97219e24,
                  6.4185e23,
                  1898.13e24,
                  5.68319e26,
                  86.8103e24,
                  102.41e24] | units.kg
  
  # eccentricity
  planets_ecc = [2.056263501026885E-01,
                 6.756759719005901E-03,
                 1.715483324953308E-02,
                 9.347121362500883E-02,
                 4.877287772914470E-02,
                 5.429934603664216E-02,
                 4.911406962716518E-02,
                 8.494660388602767E-03]
  
  # semi-major axis
  planets_semi = [3.870989725156447E-01,
                  7.233252880006816E-01,
                  1.000816989613834E+00,
                  1.523624142457679E+00,
                  5.203543088590996E+00,
                  9.547316304899041E+00,
                  1.915982879739036E+01,
                  2.997013749028780E+01] | units.AU
  
  # mean anomaly [degrees]
  planets_mean_anomaly = [2.256667460183225E+02,
                          3.096834722926926E+02,
                          6.970055236286768E+01,
                          5.013506750245609E+01,
                          1.213203242081277E+02,
                          1.423311616732398E+02,
                          2.079860620353052E+02,
                          2.712246916734600E+02]
  planets_mean_anomaly = numpy.array(planets_mean_anomaly) * pi_over_180
  
  # inclination [IN degrees]
  planets_inclination = [7.004026765179669E+00,
                         3.394480103844425E+00,
                         3.563477431351056E-03,
                         1.848403408106458E+00,
                         1.303457729562742E+00,
                         2.488017444885577E+00,
                         7.728000142736371E-01,
                         1.767720502209091E+00]
  planets_inclination = numpy.array(planets_inclination) * pi_over_180
  
  # Longitude of Ascending Node [OM degrees]
  planets_longitude = [4.831163083479358E+01,
                       7.663982595051040E+01,
                       1.775515437672556E+02,
                       4.951282677064384E+01,
                       1.005036717671826E+02,
                       1.135683875842263E+02,
                       7.388411509910506E+01,
                       1.317497218434830E+02]
  planets_longitude = numpy.array(planets_longitude) * pi_over_180
  
  # Argument of Perihelion [W degrees]
  planets_argument = [2.916964171964058E+01,
                      5.469102797401222E+01,
                      2.877495001117996E+02,
                      2.865420083537150E+02,
                      2.740725976811202E+02,
                      3.398666856578898E+02,
                      9.666856264946740E+01,
                      2.951871807292030E+02]
  planets_argument = numpy.array(planets_argument) * pi_over_180
  
  planets.name = ['Mercury',
                  'Venus',
                  'Earth',
                  'Mars',
                  'Jupiter',
                  'Satrun',
                  'Uranus',
                  'Neptune']
  
  ### to compare with JPL, mass of the Sun needs to be rescaled
  #mg_nasa = 1.32712440018e20 | (units.m**3 / units.s**2)
  #g_nasa = 6.67259e-11 | (units.m**3 / units.kg / units.s**2)
  #ms = mg_nasa / g_nasa
  
  sun = Particle()
  sun.name = 'Sun'
  #sun.mass = ms
  sun.mass = 1.0 | units.MSun
  sun.position = [0.,0.,0.] | units.AU
  sun.velocity = [0.,0.,0.] | units.kms
  
  # get the position and velocity vectors relative to sun 
  # by evolving in Kepler
  for i,ecc_i in enumerate(planets_ecc):
    r, v = get_position(sun.mass,
                        planets[i].mass,
                        planets_ecc[i],
                        planets_semi[i],
                        planets_mean_anomaly[i],
                        planets_inclination[i],
                        planets_longitude[i],
                        planets_argument[i],
                        delta_t=delta_JD)
    planets[i].position = r
    planets[i].velocity = v
    
  return sun, planets
Exemplo n.º 42
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.º 43
0
def t_linear(tend=1,N=100,method=0):
  code=Kepler(redirection="none")

  code.set_method(method)

  mass=1. | nbody_system.mass
  x=1. | nbody_system.length
  vx=0 | nbody_system.speed

  e=0.5*vx**2-nbody_system.G*mass/x

  semimajor_axis=-nbody_system.G*mass/2/e

  p=2*numpy.pi*(semimajor_axis**3/nbody_system.G/mass)**0.5

  print semimajor_axis
  print p

  tend=tend*p
  dt=p/N

  sun=Particle()
  sun.mass=mass
  sun.x=0. | nbody_system.length
  sun.y=0. | nbody_system.length
  sun.z=0. | nbody_system.length
  sun.vx=0. | nbody_system.speed
  sun.vy=0. | nbody_system.speed
  sun.vz=0. | nbody_system.speed

  comet=Particle()
  comet.mass= 0 | nbody_system.mass
  comet.x=x
  comet.y=0. | nbody_system.length
  comet.z=0. | nbody_system.length
  comet.vx=vx
  comet.vy=0. | nbody_system.speed
  comet.vz=0. | nbody_system.speed

  code.central_particle.add_particle(sun)
  code.orbiters.add_particle(comet)

  a0,eps0=elements(sun.mass,code.orbiters.x,code.orbiters.y,code.orbiters.z,
                     code.orbiters.vx,code.orbiters.vy,code.orbiters.vz,G=nbody_system.G)

  print orbital_elements_from_binary(code.particles[0:2])

  #pyplot.ion()
  #f=pyplot.figure(figsize=(8,6))
  #pyplot.show()

  tnow=0*tend
  time=[]
  xs=[]
  while tnow<tend:
    tnow+=dt
    print tnow,int(tnow/dt)
    code.evolve_model(tnow)
    #f.clf()
    time.append(tnow/tend)
    xs.append(code.orbiters.x[0].number)
  #pyplot.plot(time,xs,"r+")
  #pyplot.xlim(-0.1,1.1)
  #pyplot.ylim(-1.1,3.1)
  #pyplot.draw()

  print orbital_elements_from_binary(code.particles[0:2])

  print code.orbiters.position

  a,eps=elements(sun.mass,code.orbiters.x,code.orbiters.y,code.orbiters.z,
                     code.orbiters.vx,code.orbiters.vy,code.orbiters.vz,G=nbody_system.G)

  da=abs((a-a0)/a0)
  deps=abs(eps-eps0)/eps0

  print da,deps
  raw_input()
Exemplo n.º 44
0
    def xtest2(self):
        print "Testing FallbackStellarEvolution: evolve tests"

        # results of original code  (not really check the numbers, tests have been relaxed because
        # different timestepping of evolve_model and evolve_one_step)
        results = dict()
        results["10.0 MSun"] = dict(sse_age=3644655.52487 | units.yr,
                                    sse_mass=9.99289747724 | units.MSun,
                                    sse_rad=4.24764389443 | units.RSun,
                                    sse_L=5993.72678228 | units.LSun,
                                    evtwin_age=2999999.99732 | units.yr,
                                    evtwin_mass=9.99832250931 | units.MSun,
                                    evtwin_rad=4.1727904434 | units.RSun,
                                    evtwin_L=6175.5214329 | units.LSun)
        results["20.0 MSun"] = dict(sse_age=2609167.84395 | units.yr,
                                    sse_mass=19.8895071502 | units.MSun,
                                    sse_rad=7.07713598137 | units.RSun,
                                    sse_L=51232.436257 | units.LSun,
                                    evtwin_age=2999999.99792 | units.yr,
                                    evtwin_mass=19.877338008 | units.MSun,
                                    evtwin_rad=6.77369109826 | units.RSun,
                                    evtwin_L=54123.7589452 | units.LSun)
        results["40.0 MSun"] = dict(sse_age=2627093.59096 | units.yr,
                                    sse_mass=38.3702723816 | units.MSun,
                                    sse_rad=13.6137662257 | units.RSun,
                                    sse_L=303498.877464 | units.LSun,
                                    evtwin_age=2999999.99923 | units.yr,
                                    evtwin_mass=37.0862227121 | units.MSun,
                                    evtwin_rad=13.5982316053 | units.RSun,
                                    evtwin_L=320099.608846 | units.LSun)

        for m in [40.] | units.MSun:  #,20.,10.] | units.MSun:
            instance = FallbackStellarEvolution()
            instance._main_se.parameters.max_age_stop_condition = 3. | units.Myr

            star = Particle(1)
            star.mass = m
            star = instance.particles.add_particle(star)
            instance.commit_particles()

            while instance.ActiveModel[star].__class__.__name__ == "EVtwin":
                instance.evolve_model()

            print "%s\t%s\t%s\t%s\t%s\t%s" % (
                star.age, star.mass, star.radius, star.luminosity,
                star.stellar_type,
                instance.ActiveModel[star].__class__.__name__)

            self.assertAlmostRelativeEqual(
                results[str(m)]["sse_age"],
                instance._FBTimeseries[star].particles[0].SSEAgeAtSwitch, 7)
            self.assertAlmostRelativeEqual(results[str(m)]["sse_mass"],
                                           star.mass, 7)
            self.assertAlmostRelativeEqual(results[str(m)]["sse_rad"],
                                           star.radius, 7)
            self.assertAlmostRelativeEqual(results[str(m)]["sse_L"],
                                           star.luminosity, 7)

            star = instance._main_se.particles[0]

            self.assertAlmostRelativeEqual(results[str(m)]["evtwin_age"],
                                           star.age, 7)
            self.assertAlmostRelativeEqual(results[str(m)]["evtwin_mass"],
                                           star.mass, 2)
            self.assertAlmostRelativeEqual(results[str(m)]["evtwin_rad"],
                                           star.radius, 2)
            self.assertAlmostRelativeEqual(results[str(m)]["evtwin_L"],
                                           star.luminosity, 2)

            print "%s\t%s\t%s\t%s\t%s" % (star.age, star.mass, star.radius,
                                          star.luminosity, star.stellar_type)

            instance.stop()
Exemplo n.º 45
0
    def xtest2(self):
        print "Testing FallbackStellarEvolution: evolve tests"


# results of original code  (not really check the numbers, tests have been relaxed because
# different timestepping of evolve_model and evolve_one_step)
        results=dict()
        results["10.0 MSun"]=dict(sse_age=3644655.52487 | units.yr,
                                      sse_mass=9.99289747724 | units.MSun,
                                      sse_rad=4.24764389443 | units.RSun,
                                      sse_L=5993.72678228 | units.LSun,
                                      evtwin_age=2999999.99732 | units.yr,
                                      evtwin_mass=9.99832250931 | units.MSun,
                                      evtwin_rad=4.1727904434 | units.RSun,
                                      evtwin_L=6175.5214329 | units.LSun)
        results["20.0 MSun"]=dict(sse_age= 2609167.84395| units.yr,
                                      sse_mass= 19.8895071502| units.MSun,
                                      sse_rad=7.07713598137| units.RSun,
                                      sse_L=51232.436257| units.LSun,
                                      evtwin_age= 2999999.99792| units.yr,
                                      evtwin_mass=19.877338008| units.MSun,
                                      evtwin_rad=6.77369109826| units.RSun,
                                      evtwin_L= 54123.7589452| units.LSun)
        results["40.0 MSun"]=dict(sse_age= 2627093.59096| units.yr,
                                      sse_mass=38.3702723816| units.MSun,
                                      sse_rad=13.6137662257 | units.RSun,
                                      sse_L=303498.877464 | units.LSun,
                                      evtwin_age= 2999999.99923| units.yr,
                                      evtwin_mass=37.0862227121 | units.MSun,
                                      evtwin_rad= 13.5982316053| units.RSun,
                                      evtwin_L=320099.608846| units.LSun)


        for m in [40.]| units.MSun:#,20.,10.] | units.MSun:
          instance = FallbackStellarEvolution()
          instance._main_se.parameters.max_age_stop_condition=3.| units.Myr

          star = Particle(1)
          star.mass = m
          star = instance.particles.add_particle(star)
          instance.commit_particles()

          while instance.ActiveModel[star].__class__.__name__=="EVtwin":
              instance.evolve_model()

          print "%s\t%s\t%s\t%s\t%s\t%s" % (star.age, star.mass, star.radius,
           star.luminosity, star.stellar_type, instance.ActiveModel[star].__class__.__name__)

          self.assertAlmostRelativeEqual(results[str(m)]["sse_age"],instance._FBTimeseries[star].particles[0].SSEAgeAtSwitch,7)
          self.assertAlmostRelativeEqual(results[str(m)]["sse_mass"],star.mass,7)
          self.assertAlmostRelativeEqual(results[str(m)]["sse_rad"],star.radius,7)
          self.assertAlmostRelativeEqual(results[str(m)]["sse_L"],star.luminosity,7)


          star=instance._main_se.particles[0]

          self.assertAlmostRelativeEqual(results[str(m)]["evtwin_age"],star.age,7)
          self.assertAlmostRelativeEqual(results[str(m)]["evtwin_mass"],star.mass,2)
          self.assertAlmostRelativeEqual(results[str(m)]["evtwin_rad"],star.radius,2)
          self.assertAlmostRelativeEqual(results[str(m)]["evtwin_L"],star.luminosity,2)

          print "%s\t%s\t%s\t%s\t%s" % (star.age, star.mass, star.radius,
           star.luminosity, star.stellar_type)

          instance.stop()
Exemplo n.º 46
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

    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
Exemplo n.º 47
0
def t_linear(tend=1, N=100, method=0):
    code = Kepler(redirection="none")

    code.set_method(method)

    mass = 1. | nbody_system.mass
    x = 1. | nbody_system.length
    vx = 0 | nbody_system.speed

    e = 0.5 * vx**2 - nbody_system.G * mass / x

    semimajor_axis = -nbody_system.G * mass / 2 / e

    p = 2 * numpy.pi * (semimajor_axis**3 / nbody_system.G / mass)**0.5

    print(semimajor_axis)
    print(p)

    tend = tend * p
    dt = p / N

    sun = Particle()
    sun.mass = mass
    sun.x = 0. | nbody_system.length
    sun.y = 0. | nbody_system.length
    sun.z = 0. | nbody_system.length
    sun.vx = 0. | nbody_system.speed
    sun.vy = 0. | nbody_system.speed
    sun.vz = 0. | nbody_system.speed

    comet = Particle()
    comet.mass = 0 | nbody_system.mass
    comet.x = x
    comet.y = 0. | nbody_system.length
    comet.z = 0. | nbody_system.length
    comet.vx = vx
    comet.vy = 0. | nbody_system.speed
    comet.vz = 0. | nbody_system.speed

    code.central_particle.add_particle(sun)
    code.orbiters.add_particle(comet)

    a0, eps0 = elements(sun.mass,
                        code.orbiters.x,
                        code.orbiters.y,
                        code.orbiters.z,
                        code.orbiters.vx,
                        code.orbiters.vy,
                        code.orbiters.vz,
                        G=nbody_system.G)

    print(orbital_elements_from_binary(code.particles[0:2]))

    #pyplot.ion()
    #f=pyplot.figure(figsize=(8,6))
    #pyplot.show()

    tnow = 0 * tend
    time = []
    xs = []
    while tnow < tend:
        tnow += dt
        print(tnow, int(tnow / dt))
        code.evolve_model(tnow)
        #f.clf()
        time.append(tnow / tend)
        xs.append(code.orbiters.x[0].number)
    #pyplot.plot(time,xs,"r+")
    #pyplot.xlim(-0.1,1.1)
    #pyplot.ylim(-1.1,3.1)
    #pyplot.draw()

    print(orbital_elements_from_binary(code.particles[0:2]))

    print(code.orbiters.position)

    a, eps = elements(sun.mass,
                      code.orbiters.x,
                      code.orbiters.y,
                      code.orbiters.z,
                      code.orbiters.vx,
                      code.orbiters.vy,
                      code.orbiters.vz,
                      G=nbody_system.G)

    da = abs((a - a0) / a0)
    deps = abs(eps - eps0) / eps0

    print(da, deps)
    input()
Exemplo n.º 48
0
def test_softening(method=1):
    code = Kepler(redirection="none")

    code.set_method(method)

    dt = float.fromhex("0x1.67b39e372f04dp+4")
    mu = float.fromhex("0x1.fffffffffffdfp-3")
    e2 = float.fromhex("0x1.0000000000003p+0")
    pos1 = float.fromhex("0x1.1b76542265052p-1")
    pos2 = float.fromhex("0x1.0c4dbda42097cp-6")
    pos3 = float.fromhex("0x1.54fd66cd1e212p-3")
    vel1 = float.fromhex("0x1.d6ef43d58ca7ep-2")
    vel2 = float.fromhex("0x1.7a85379e59794p-2")
    vel3 = float.fromhex("-0x1.5421044d1acffp-1")

    sun = Particle()
    sun.mass = mu | nbody_system.mass
    sun.x = 0. | nbody_system.length
    sun.y = 0. | nbody_system.length
    sun.z = 0. | nbody_system.length
    sun.vx = 0. | nbody_system.speed
    sun.vy = 0. | nbody_system.speed
    sun.vz = 0. | nbody_system.speed

    comet = Particle()
    comet.mass = 0 | nbody_system.mass
    comet.x = pos1 | nbody_system.length
    comet.y = pos2 | nbody_system.length
    comet.z = pos3 | nbody_system.length
    comet.vx = vel1 | nbody_system.speed
    comet.vy = vel2 | nbody_system.speed
    comet.vz = vel3 | nbody_system.speed

    tend = dt | nbody_system.time
    print(tend, mu)

    code.central_particle.add_particle(sun)
    code.orbiters.add_particle(comet)

    code.parameters.epsilon_squared = e2 | nbody_system.length**2

    a0, eps0 = elements(sun.mass,
                        code.orbiters.x,
                        code.orbiters.y,
                        code.orbiters.z,
                        code.orbiters.vx,
                        code.orbiters.vy,
                        code.orbiters.vz,
                        G=nbody_system.G)

    print(orbital_elements_from_binary(code.particles[0:2]))

    t1 = time.time()
    code.evolve_model(tend)
    t2 = time.time()

    print(orbital_elements_from_binary(code.particles[0:2]))

    print(code.orbiters.position)

    a, eps = elements(sun.mass,
                      code.orbiters.x,
                      code.orbiters.y,
                      code.orbiters.z,
                      code.orbiters.vx,
                      code.orbiters.vy,
                      code.orbiters.vz,
                      G=nbody_system.G)

    da = abs((a - a0) / a0)
    deps = abs(eps - eps0) / eps0

    print(da, deps)
    print("time:", t2 - t1)
Exemplo n.º 49
0
def crash_test2(method=1):
    code = Kepler(redirection="none")

    code.set_method(method)
    """
  mu=struct.unpack('!d','3ff7ffffffffffff'.decode('hex'))[0]
  dt=struct.unpack('!d','40025ab746b00001'.decode('hex'))[0]
  pos1=struct.unpack('!d','bfed36dc82998ed4'.decode('hex'))[0]
  pos2=struct.unpack('!d','40051297fc6e5256'.decode('hex'))[0]
  pos3=struct.unpack('!d','0000000000000000'.decode('hex'))[0]
  vel1=struct.unpack('!d','3fb09d8008ba33b9'.decode('hex'))[0]
  vel2=struct.unpack('!d','bff06788b551b81d'.decode('hex'))[0]
  vel3=struct.unpack('!d','0000000000000000'.decode('hex'))[0]
  """
    mu = float.fromhex("0x1.8p+0")
    dt = float.fromhex("0x1.25ab746bp+1")
    pos1 = float.fromhex("-0x1.d36dc82998ed4p-1")
    pos2 = float.fromhex("0x1.51297fc6e5256p+1")
    pos3 = float.fromhex("0x0p+0")
    vel1 = float.fromhex("0x1.09d8008ba33b9p-4")
    vel2 = float.fromhex("-0x1.06788b551b81ep+0")
    vel3 = float.fromhex("0x0p+0")

    sun = Particle()
    sun.mass = mu | nbody_system.mass
    sun.x = 0. | nbody_system.length
    sun.y = 0. | nbody_system.length
    sun.z = 0. | nbody_system.length
    sun.vx = 0. | nbody_system.speed
    sun.vy = 0. | nbody_system.speed
    sun.vz = 0. | nbody_system.speed

    comet = Particle()
    comet.mass = 0 | nbody_system.mass
    comet.x = pos1 | nbody_system.length
    comet.y = pos2 | nbody_system.length
    comet.z = pos3 | nbody_system.length
    comet.vx = vel1 | nbody_system.speed
    comet.vy = vel2 | nbody_system.speed
    comet.vz = vel3 | nbody_system.speed

    tend = dt | nbody_system.time
    print(tend, mu)

    code.central_particle.add_particle(sun)
    code.orbiters.add_particle(comet)

    a0, eps0 = elements(sun.mass,
                        code.orbiters.x,
                        code.orbiters.y,
                        code.orbiters.z,
                        code.orbiters.vx,
                        code.orbiters.vy,
                        code.orbiters.vz,
                        G=nbody_system.G)

    print(orbital_elements_from_binary(code.particles[0:2]))

    t1 = time.time()
    code.evolve_model(tend)
    t2 = time.time()

    print(orbital_elements_from_binary(code.particles[0:2]))

    print(code.orbiters.position)

    a, eps = elements(sun.mass,
                      code.orbiters.x,
                      code.orbiters.y,
                      code.orbiters.z,
                      code.orbiters.vx,
                      code.orbiters.vy,
                      code.orbiters.vz,
                      G=nbody_system.G)

    da = abs((a - a0) / a0)
    deps = abs(eps - eps0) / eps0

    print(da, deps)
    print("time:", t2 - t1)
Exemplo n.º 50
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