Beispiel #1
0
def timefractal(N=1000,
                fd=1.6,
                tend=0.25 | nbody_system.time,
                inttype=Huayno.inttypes.HOLD_DKD,
                seed=12345678):

    stars = new_fractal_cluster_model(N=N,
                                      fractal_dimension=fd,
                                      random_seed=seed,
                                      virial_ratio=0.5,
                                      do_scale=True,
                                      verbose=False)
    code = Huayno()
    code.parameters.inttype_parameter = inttype
    code.parameters.timestep_parameter = 0.01
    code.particles.add_particles(stars)

    E0 = code.kinetic_energy + code.potential_energy
    p0 = code.particles.total_momentum()
    t1 = time()
    code.evolve_model(tend)
    t2 = time()
    E = code.kinetic_energy + code.potential_energy
    p = code.particles.total_momentum()
    code.stop()
    return t2 - t1, abs(E0 - E) / E0, p0 - p
Beispiel #2
0
    def test15(self):
        particles = plummer.new_plummer_model(512)
        expected_positions = None
        for mode in ["cpu", "openmp", "opencl"]:
            try:
                instance = Huayno(mode=mode,
                                  number_of_workers=1)  #, debugger="xterm")
            except:
                print("Running huayno with mode=", mode, " was unsuccessful.")
                continue
            else:
                print("Running huayno with mode=", mode, "... ")

            instance.initialize_code()
            instance.parameters.epsilon_squared = 0.01 | nbody_system.length**2
            instance.particles.add_particles(particles)

            instance.evolve_model(0.2 | nbody_system.time)
            instance.synchronize_model()
            if expected_positions is None:
                expected_positions = instance.particles.position
            else:
                self.assertAlmostRelativeEquals(expected_positions,
                                                instance.particles.position, 8)
            instance.stop()
Beispiel #3
0
    def test3(self):
        convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 149.5e6 | units.km)

        instance = Huayno(convert_nbody)
        instance.initialize_code()
        instance.parameters.epsilon_squared = 0.00001 | units.AU**2
        
        stars = datamodel.Stars(2)
        star1 = stars[0]
        star2 = stars[1]

        star1.mass = units.MSun(1.0)
        star1.position = units.AU(numpy.array((-1.0,0.0,0.0)))
        star1.velocity = units.AUd(numpy.array((0.0,0.0,0.0)))
        star1.radius = units.RSun(1.0)

        star2.mass = units.MSun(1.0)
        star2.position = units.AU(numpy.array((1.0,0.0,0.0)))
        star2.velocity = units.AUd(numpy.array((0.0,0.0,0.0)))
        star2.radius = units.RSun(100.0)
        
        instance.particles.add_particles(stars)
    
        for x in range(1,2000,10):
            instance.evolve_model(x | units.day)
            instance.particles.copy_values_of_all_attributes_to(stars)
            stars.savepoint()
Beispiel #4
0
    def test3(self):
        convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun,
                                                 149.5e6 | units.km)

        instance = Huayno(convert_nbody)
        instance.initialize_code()
        instance.parameters.epsilon_squared = 0.00001 | units.AU**2

        stars = datamodel.Stars(2)
        star1 = stars[0]
        star2 = stars[1]

        star1.mass = units.MSun(1.0)
        star1.position = units.AU(numpy.array((-1.0, 0.0, 0.0)))
        star1.velocity = units.AUd(numpy.array((0.0, 0.0, 0.0)))
        star1.radius = units.RSun(1.0)

        star2.mass = units.MSun(1.0)
        star2.position = units.AU(numpy.array((1.0, 0.0, 0.0)))
        star2.velocity = units.AUd(numpy.array((0.0, 0.0, 0.0)))
        star2.radius = units.RSun(100.0)

        instance.particles.add_particles(stars)

        for x in range(1, 2000, 10):
            instance.evolve_model(x | units.day)
            instance.particles.copy_values_of_all_attributes_to(stars)
            stars.savepoint()
Beispiel #5
0
    def _run_collision_with_integrator(self, inttype_parameter):
        particles = datamodel.Particles(7)
        particles.mass = 0.001 | nbody_system.mass
        particles.radius = 0.01 | nbody_system.length
        particles.x = [-101.0, -100.0, -0.5, 0.5, 100.0, 101.0, 104.0
                       ] | nbody_system.length
        particles.y = 0 | nbody_system.length
        particles.z = 0 | nbody_system.length
        particles.velocity = [[2, 0, 0], [-2, 0, 0]
                              ] * 3 + [[-4, 0, 0]] | nbody_system.speed

        instance = Huayno()
        instance.parameters.inttype_parameter = inttype_parameter
        instance.particles.add_particles(particles)
        collisions = instance.stopping_conditions.collision_detection
        collisions.enable()
        instance.evolve_model(1.0 | nbody_system.time)

        self.assertTrue(collisions.is_set())
        self.assertTrue(instance.model_time < 0.5 | nbody_system.time)
        self.assertEqual(len(collisions.particles(0)), 3)
        self.assertEqual(len(collisions.particles(1)), 3)
        self.assertEqual(
            len(particles - collisions.particles(0) - collisions.particles(1)),
            1)
        self.assertEqual(
            abs(collisions.particles(0).x - collisions.particles(1).x) <=
            (collisions.particles(0).radius + collisions.particles(1).radius),
            [True, True, True])

        sticky_merged = datamodel.Particles(len(collisions.particles(0)))
        sticky_merged.mass = collisions.particles(
            0).mass + collisions.particles(1).mass
        sticky_merged.radius = collisions.particles(0).radius
        for p1, p2, merged in zip(collisions.particles(0),
                                  collisions.particles(1), sticky_merged):
            merged.position = (p1 + p2).center_of_mass()
            merged.velocity = (p1 + p2).center_of_mass_velocity()

        instance.particles.remove_particles(
            collisions.particles(0) + collisions.particles(1))
        instance.particles.add_particles(sticky_merged)

        instance.evolve_model(1.0 | nbody_system.time)
        self.assertTrue(collisions.is_set())
        self.assertTrue(instance.model_time < 1.0 | nbody_system.time)
        self.assertEqual(len(collisions.particles(0)), 1)
        self.assertEqual(len(collisions.particles(1)), 1)
        self.assertEqual(
            len(instance.particles - collisions.particles(0) -
                collisions.particles(1)), 2)
        self.assertEqual(
            abs(collisions.particles(0).x - collisions.particles(1).x) <=
            (collisions.particles(0).radius + collisions.particles(1).radius),
            [True])
        instance.stop()
Beispiel #6
0
 def test13(self):
     particles = plummer.new_plummer_model(31)
    
     instance = Huayno(number_of_workers=1)#, debugger="xterm")
     instance.initialize_code()
     instance.parameters.epsilon_squared = 0.01 | nbody_system.length ** 2
     instance.particles.add_particles(particles)
     
     instance.evolve_model(0.1 | nbody_system.time)
     instance.synchronize_model()
     expected_positions = instance.particles.position
     instance.stop()
Beispiel #7
0
    def test14(self):
        import hashlib

        numpy.random.seed(123456)
        particles = plummer.new_plummer_model(64)
        sha = hashlib.sha1()

        class inttypes(object):
            SHARED2 = 1
            EXTRAPOLATE = 5
            PASS_KDK = 2
            PASS_DKD = 7
            HOLD_KDK = 3
            HOLD_DKD = 8
            PPASS_DKD = 9
            BRIDGE_KDK = 4
            BRIDGE_DKD = 10
            CC = 11
            CC_KEPLER = 12
            OK = 13
            KEPLER = 14
            SHARED4 = 15
            SHARED6 = 18
            SHARED8 = 19
            SHARED10 = 20
            SHAREDBS = 21

            @classmethod
            def _list(cls):
                return set(
                    [x for x in cls.__dict__.keys() if not x.startswith('_')])

        for itype in sorted(inttypes._list()):
            if itype in ("KEPLER"): continue
            instance = Huayno()
            instance.parameters.inttype_parameter = getattr(
                Huayno.inttypes, itype)
            instance.particles.add_particles(particles)
            instance.evolve_model(0.125 | nbody_system.time)
            part_out = instance.particles.copy()
            position = part_out.position.number
            if hasattr(position, 'tobytes'):
                as_bytes = position.tobytes()
            else:
                as_bytes = numpy.array(position.data, copy=True, order='C')
            sha.update(as_bytes)

            instance.stop()

        # this result is probably dependent on system architecture hence no good for assert
        print
        print sha.hexdigest()
        print "8e71f9441578a43af4af927943577ad2c4130e4c"
Beispiel #8
0
    def test13(self):
        particles = plummer.new_plummer_model(31)

        instance = Huayno(number_of_workers=1)  #, debugger="xterm")
        instance.initialize_code()
        instance.parameters.epsilon_squared = 0.01 | nbody_system.length**2
        instance.particles.add_particles(particles)

        instance.evolve_model(0.1 | nbody_system.time)
        instance.synchronize_model()
        expected_positions = instance.particles.position
        instance.stop()
Beispiel #9
0
def binary_with_planet_run(m1=1.|units.MSun, m2=1.| units.MSun, m_planet=1|units.MJupiter,
                           r1=None, r2=None, r_planet=None, ecc_binary=0, P_binary=20 | units.day,
                           ecc_planet=0., P_planet=1.| units.yr, pangle_planet=0., a_planet=None,
                           tend=100. | units.yr,hostname=''):

    dEcrit=1.e-6

    three=binary_with_planet(m1=m1,m2=m2,m_planet=m_planet,r1=r1,r2=r2,r_planet=r_planet,
             ecc_binary=ecc_binary,P_binary=P_binary,
             ecc_planet=ecc_planet,a_planet=a_planet,pangle_planet=pangle_planet)
    
    convert=nbody_system.nbody_to_si(1|units.MSun,1|units.AU)
    code=Huayno(convert,hostname=hostname)
    
    code.parameters.inttype_parameter=code.inttypes.SHARED10
    code.parameters.timestep_parameter=.2
    code.parameters.timestep=100. | units.day
        
    dt=10000. | units.day
    
    code.particles.add_particles(three)

    E0=code.potential_energy+code.kinetic_energy
    a0,eps0,pangle0=elements( three.total_mass(),
          code.particles.x[2],
          code.particles.y[2],
          code.particles.z[2],
          code.particles.vx[2],
          code.particles.vy[2],
          code.particles.vz[2] )

    t=0. | units.day
    result="stable"
    while(t < tend-dt/2):
        t=t+dt
        code.evolve_model(t)
        E=code.potential_energy+code.kinetic_energy    
        dE=abs(((E-E0)/E0))
        a,eps,pangle=elements( three.total_mass(),
          code.particles.x[2],
          code.particles.y[2],
          code.particles.z[2],
          code.particles.vx[2],
          code.particles.vy[2],
          code.particles.vz[2] )
        if dE > dEcrit or a<0.5*a0 or a>2.*a0:
          result="unstable"
          if dE > dEcrit:
            result="failed"
          break
    code.stop()
    return result,t,dE,a.in_(units.AU),eps,pangle
Beispiel #10
0
    def test14(self):
        import hashlib

        numpy.random.seed(123456)
        particles = plummer.new_plummer_model(64)
        sha=hashlib.sha1()

        class inttypes(object):
            SHARED2=1
            EXTRAPOLATE=5
            PASS_KDK=2
            PASS_DKD=7
            HOLD_KDK=3
            HOLD_DKD=8
            PPASS_DKD=9
            BRIDGE_KDK=4
            BRIDGE_DKD=10
            CC=11
            CC_KEPLER=12
            OK=13
            KEPLER=14
            SHARED4=15
            SHARED6=18
            SHARED8=19
            SHARED10=20
            SHAREDBS=21
           
            @classmethod
            def _list(cls):
                  return set([x for x in cls.__dict__.keys() if not x.startswith('_')])

        for itype in sorted(inttypes._list()):
            if itype in ("KEPLER"): continue
            instance = Huayno()
            instance.parameters.inttype_parameter=getattr(Huayno.inttypes,itype)
            instance.particles.add_particles(particles)
            instance.evolve_model(0.125 | nbody_system.time)
            part_out= instance.particles.copy()
            position = part_out.position.number
            if hasattr(position,'tobytes'):
                as_bytes = position.tobytes()
            else:
                as_bytes = numpy.copy(position.data, order='C')
            sha.update(as_bytes)
            
            instance.stop()
        
        # this result is probably dependent on system architecture hence no good for assert
        print 
        print sha.hexdigest()
        print "8e71f9441578a43af4af927943577ad2c4130e4c"
Beispiel #11
0
 def _run_collision_with_integrator(self, inttype_parameter):
     particles = datamodel.Particles(7)
     particles.mass = 0.001 | nbody_system.mass
     particles.radius = 0.01 | nbody_system.length
     particles.x = [-101.0, -100.0, -0.5, 0.5, 100.0, 101.0, 104.0] | nbody_system.length
     particles.y = 0 | nbody_system.length
     particles.z = 0 | nbody_system.length
     particles.velocity = [[2, 0, 0], [-2, 0, 0]]*3 + [[-4, 0, 0]] | nbody_system.speed
     
     instance = Huayno()
     instance.parameters.inttype_parameter = inttype_parameter
     instance.particles.add_particles(particles)
     collisions = instance.stopping_conditions.collision_detection
     collisions.enable()
     instance.evolve_model(1.0 | nbody_system.time)
     
     self.assertTrue(collisions.is_set())
     self.assertTrue(instance.model_time < 0.5 | nbody_system.time)
     self.assertEquals(len(collisions.particles(0)), 3)
     self.assertEquals(len(collisions.particles(1)), 3)
     self.assertEquals(len(particles - collisions.particles(0) - collisions.particles(1)), 1)
     self.assertEquals(abs(collisions.particles(0).x - collisions.particles(1).x) <= 
             (collisions.particles(0).radius + collisions.particles(1).radius),
             [True, True, True])
     
     sticky_merged = datamodel.Particles(len(collisions.particles(0)))
     sticky_merged.mass = collisions.particles(0).mass + collisions.particles(1).mass
     sticky_merged.radius = collisions.particles(0).radius
     for p1, p2, merged in zip(collisions.particles(0), collisions.particles(1), sticky_merged):
         merged.position = (p1 + p2).center_of_mass()
         merged.velocity = (p1 + p2).center_of_mass_velocity()
     
     print instance.model_time
     print instance.particles
     instance.particles.remove_particles(collisions.particles(0) + collisions.particles(1))
     instance.particles.add_particles(sticky_merged)
     
     instance.evolve_model(1.0 | nbody_system.time)
     print
     print instance.model_time
     print instance.particles
     self.assertTrue(collisions.is_set())
     self.assertTrue(instance.model_time < 1.0 | nbody_system.time)
     self.assertEquals(len(collisions.particles(0)), 1)
     self.assertEquals(len(collisions.particles(1)), 1)
     self.assertEquals(len(instance.particles - collisions.particles(0) - collisions.particles(1)), 2)
     self.assertEquals(abs(collisions.particles(0).x - collisions.particles(1).x) <= 
             (collisions.particles(0).radius + collisions.particles(1).radius),
             [True])
     instance.stop()
Beispiel #12
0
 def _compare_integrator_with_collision_integrator(self, inttype_parameter1, inttype_parameter2):
     numpy.random.seed(12345)
     particles = plummer.new_plummer_model(101)
     instance = Huayno()
     instance.parameters.inttype_parameter = inttype_parameter1
     instance.particles.add_particles(particles)
     instance.evolve_model(0.2 | nbody_system.time)
     expected_position = instance.particles.position
     expected_velocity = instance.particles.velocity
     instance.reset()
     instance.parameters.inttype_parameter = inttype_parameter2
     instance.particles.add_particles(particles)
     instance.evolve_model(0.2 | nbody_system.time)
     self.assertAlmostRelativeEquals(expected_position, instance.particles.position, 8)
     self.assertAlmostRelativeEquals(expected_velocity, instance.particles.velocity, 8)
     instance.stop()
Beispiel #13
0
 def _compare_integrator_with_collision_integrator(self, inttype_parameter1, inttype_parameter2):
     numpy.random.seed(12345)
     particles = plummer.new_plummer_model(101)
     instance = Huayno()
     instance.parameters.inttype_parameter = inttype_parameter1
     instance.particles.add_particles(particles)
     instance.evolve_model(0.2 | nbody_system.time)
     expected_position = instance.particles.position
     expected_velocity = instance.particles.velocity
     instance.reset()
     instance.parameters.inttype_parameter = inttype_parameter2
     instance.particles.add_particles(particles)
     instance.evolve_model(0.2 | nbody_system.time)
     self.assertAlmostRelativeEquals(expected_position, instance.particles.position, 8)
     self.assertAlmostRelativeEquals(expected_velocity, instance.particles.velocity, 8)
     instance.stop()
def orbit_evolve(bodies, time_peri, eta, n_steps=100):
    converter = nbody_system.nbody_to_si(1 | units.MSun, 1 | units.AU)

    gravity = Huayno(converter, channel_type="sockets")
    gravity.particles.add_particles(bodies)
    gravity.commit_particles()
    gravity.parameters.timestep_parameter = eta

    channel_from_gravity_to_framework = gravity.particles.new_channel_to(
        bodies)

    Etot_init = gravity.kinetic_energy + gravity.potential_energy
    Etot = Etot_init

    file_snap = "orbit_ini.hdf5"

    t_end = 2.0 * abs(time_peri.value_in(units.yr)) | units.yr
    dt = t_end / float(n_steps)
    time = 0.0 | units.yr

    while time <= t_end:

        gravity.evolve_model(time)
        channel_from_gravity_to_framework.copy()
        bodies.age = time

        # checking energy conservation
        Ekin = gravity.kinetic_energy
        Epot = gravity.potential_energy
        Etot = Ekin + Epot
        dE = Etot_init - Etot

        # output centerd on the bodies[0] star
        bodies.position -= bodies[0].position
        bodies.velocity -= bodies[0].velocity
        write_set_to_file(bodies, file_snap, "hdf5")

        rel_r = (bodies[1].position - bodies[0].position).lengths()
        print " \t\t", time, "\t", dE / Etot_init, rel_r.in_(units.AU)
        time += dt

    gravity.stop()
    bodies.position -= bodies[0].position
    bodies.velocity -= bodies[0].velocity
    print bodies

    return
Beispiel #15
0
    def test14c(self):
        import hashlib

        numpy.random.seed(123456)
        particles = plummer.new_plummer_model(16)
        particles.mass *= 0.25
        p2 = plummer.new_plummer_model(16)
        p2.mass *= 0.75
        sha = hashlib.sha1()

        test_set = [
            "CONSTANT", "SHARED2", "EXTRAPOLATE", "PASS_KDK", "PASS_DKD",
            "HOLD_KDK", "HOLD_DKD", "PPASS_DKD", "BRIDGE_KDK", "BRIDGE_DKD",
            "CC", "CC_KEPLER", "CC_BS", "CC_BSA", "OK", "SHAREDBS", "SHARED4",
            "SHARED6", "SHARED8", "SHARED10"
        ]

        #~ test_set=["CC_BS"]

        for itype in test_set:
            #~ print()
            #~ print(itype)
            instance = Huayno(redirection="none")
            instance.parameters.inttype_parameter = Huayno.all_inttypes[itype]
            instance.parameters.accelerate_zero_mass = True
            instance.particles.add_particles(particles)
            instance.particles.add_particles(p2)
            E1 = instance.kinetic_energy + instance.potential_energy
            instance.evolve_model(0.125 | nbody_system.time)
            E2 = instance.kinetic_energy + instance.potential_energy
            #~ if itype!="CONSTANT":
            #~ self.assertLess(abs(E2-E1).number, 1.e-5)
            #~ print((E2-E1).number)
            part_out = instance.particles.copy()
            position = part_out.position.number
            if hasattr(position, 'tobytes'):
                as_bytes = position.tobytes()
            else:
                as_bytes = numpy.array(position.data, copy=True, order='C')
            sha.update(as_bytes)

            instance.stop()

        # this result is probably dependent on system architecture hence no good for assert
        print()
        print(sha.hexdigest())
        print("0af7eaea472989ea4be1bb0e2b8633d6b9af41e4")
Beispiel #16
0
    def test24(self):
        print("test massless particles/ kepler integrator")
        N = 20
        tend = 2. | units.yr
        numpy.random.seed(12345)
        conv = nbody_system.nbody_to_si(4. | units.MSun, 5. | units.AU)
        orbiters = plummer.new_plummer_model(N, conv)
        sun = datamodel.Particle(mass=1. | units.MSun)
        sun.position = [12.3, 1., -.2] | units.AU
        sun.velocity = [10, 50., -20.] | units.kms
        orbiters.mass *= 0.

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

        orbiters.position += sun.position
        orbiters.velocity += sun.velocity

        pos = dict()
        for inttype in [20, 14]:
            code = Huayno(conv)
            code.parameters.inttype_parameter = inttype
            code.parameters.timestep_parameter = 0.1
            code.particles.add_particle(sun)
            orbiters2 = code.particles.add_particles(orbiters).copy()
            orbiters2.position -= sun.position
            orbiters2.velocity -= sun.velocity
            code.evolve_model(tend)
            a, eps = elements(sun.mass, orbiters2.x, orbiters2.y, orbiters2.z,
                              orbiters2.vx, orbiters2.vy, orbiters2.vz)

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

            dev = numpy.where(da > 1.e-12)[0]
            self.assertEqual(len(dev), 0)
            dev = numpy.where(deps > 1.e-12)[0]
            self.assertEqual(len(dev), 0)
            pos[inttype] = [
                orbiters2.x.value_in(units.AU),
                orbiters2.y.value_in(units.AU),
                orbiters2.z.value_in(units.AU)
            ]
        self.assertAlmostEqual(pos[20][0], pos[14][0], 12)
        self.assertAlmostEqual(pos[20][1], pos[14][1], 12)
        self.assertAlmostEqual(pos[20][2], pos[14][2], 12)
Beispiel #17
0
def timerun(N=1000,f_bin=1.,tend=0.25| nbody_system.time,inttype=Huayno.inttypes.HOLD_DKD,seed=12345678,logamin=-4):

  stars = plummer_w_binaries(N=N,f_bin=f_bin,seed=seed,logamin=logamin)
  code=Huayno()
  code.parameters.inttype_parameter=inttype
  code.parameters.timestep_parameter=0.01
  code.particles.add_particles(stars)

  E0=code.kinetic_energy+code.potential_energy
  p0=code.particles.total_momentum()
  t1=time()
  code.evolve_model(tend)
  t2=time()
  E=code.kinetic_energy+code.potential_energy
  p=code.particles.total_momentum()
  code.stop()
  return t2-t1,abs((E0-E)/E0),p0-p
def orbit_evolve(bodies, time_peri, eta, n_steps=100):
  converter=nbody_system.nbody_to_si(1|units.MSun,1|units.AU)
  
  gravity = Huayno(converter,channel_type="sockets")
  gravity.particles.add_particles(bodies)
  gravity.commit_particles()
  gravity.parameters.timestep_parameter = eta
  
  channel_from_gravity_to_framework = gravity.particles.new_channel_to(bodies)
  
  Etot_init = gravity.kinetic_energy + gravity.potential_energy
  Etot = Etot_init
  
  file_snap = "orbit_ini.hdf5"
  
  t_end = 2.0*abs(time_peri.value_in(units.yr)) | units.yr
  dt = t_end / float(n_steps)
  time = 0.0 | units.yr
  
  while time <= t_end:
    
    gravity.evolve_model(time)
    channel_from_gravity_to_framework.copy()
    bodies.age = time
    
    # checking energy conservation
    Ekin = gravity.kinetic_energy
    Epot = gravity.potential_energy
    Etot = Ekin + Epot
    dE = Etot_init-Etot
    
    # output centerd on the bodies[0] star
    bodies.position -= bodies[0].position
    bodies.velocity -= bodies[0].velocity
    write_set_to_file(bodies, file_snap, "hdf5")
    
    rel_r = (bodies[1].position - bodies[0].position).lengths()
    print " \t\t", time, "\t", dE/Etot_init, rel_r.in_(units.AU)
    time += dt
  
  gravity.stop()
  bodies.position -= bodies[0].position
  bodies.velocity -= bodies[0].velocity
  print bodies
  
  return
Beispiel #19
0
    def test14(self):
        import hashlib

        numpy.random.seed(123456)
        particles = plummer.new_plummer_model(32)
        sha = hashlib.sha1()

        test_set = [
            "CONSTANT", "SHARED2", "EXTRAPOLATE", "PASS_KDK", "PASS_DKD",
            "HOLD_KDK", "HOLD_DKD", "PPASS_DKD", "BRIDGE_KDK", "BRIDGE_DKD",
            "CC", "CC_KEPLER", "CC_BS", "CC_BSA", "OK", "SHAREDBS", "SHARED4",
            "SHARED6", "SHARED8", "SHARED10"
        ]

        #~ test_set=["CONSTANT"]

        for itype in test_set:
            #~ print()
            #~ print(itype)
            instance = Huayno()
            instance.parameters.inttype_parameter = Huayno.all_inttypes[itype]
            #~ instance.parameters.accelerate_zero_mass=False
            instance.particles.add_particles(particles)
            E1 = instance.kinetic_energy + instance.potential_energy
            instance.evolve_model(0.125 | nbody_system.time)
            E2 = instance.kinetic_energy + instance.potential_energy
            if itype != "CONSTANT":
                self.assertLess(abs(E2 - E1).number, 1.e-5)
            #~ print((E2-E1).number)

            part_out = instance.particles.copy()
            position = part_out.position.number
            if hasattr(position, 'tobytes'):
                as_bytes = position.tobytes()
            else:
                as_bytes = numpy.array(position.data, copy=True, order='C')
            sha.update(as_bytes)

            instance.stop()

        # this result is probably dependent on system architecture hence no good for assert
        print()
        print(sha.hexdigest())
        print("4f2aac4d8761f3b07545dcea53f1a65f84a5275b")
Beispiel #20
0
 def test29(self):
     instance = Huayno()
     instance.parameters.epsilon_squared = 0.0 | nbody_system.length**2
     
     particles = datamodel.Particles(2)
     particles.position = ([0,0,0], [1,0,0] )| nbody_system.length
     particles.velocity = ([-1,0,0], [2,0,0] )| nbody_system.speed
     particles.radius = 0| nbody_system.length
     particles.mass = 0.1| nbody_system.mass
             
     instance.particles.add_particles(particles)
     instance.stopping_conditions.out_of_box_detection.enable()
     instance.parameters.stopping_conditions_out_of_box_size = 2 | nbody_system.length
     instance.parameters.stopping_conditions_out_of_box_use_center_of_mass = False
     instance.evolve_model(1 | nbody_system.time)
     self.assertTrue(instance.stopping_conditions.out_of_box_detection.is_set())
     self.assertEqual(len(instance.stopping_conditions.out_of_box_detection.particles(0)), 1)
     self.assertEqual(instance.stopping_conditions.out_of_box_detection.particles(0)[0].key, particles[1].key)
     instance.stop()
Beispiel #21
0
 def test29(self):
     instance = Huayno()
     instance.parameters.epsilon_squared = 0.0 | nbody_system.length**2
     
     particles = datamodel.Particles(2)
     particles.position = ([0,0,0], [1,0,0] )| nbody_system.length
     particles.velocity = ([-1,0,0], [2,0,0] )| nbody_system.speed
     particles.radius = 0| nbody_system.length
     particles.mass = 0.1| nbody_system.mass
             
     instance.particles.add_particles(particles)
     instance.stopping_conditions.out_of_box_detection.enable()
     instance.parameters.stopping_conditions_out_of_box_size = 2 | nbody_system.length
     instance.parameters.stopping_conditions_out_of_box_use_center_of_mass = False
     instance.evolve_model(1 | nbody_system.time)
     self.assertTrue(instance.stopping_conditions.out_of_box_detection.is_set())
     self.assertEquals(len(instance.stopping_conditions.out_of_box_detection.particles(0)), 1)
     self.assertEquals(instance.stopping_conditions.out_of_box_detection.particles(0)[0].key, particles[1].key)
     instance.stop()
Beispiel #22
0
    def test7(self):
        print("Test7: Testing effect of Huayno parameter epsilon_squared")
        convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun,
                                                 1.0 | units.AU)

        particles = datamodel.Particles(2)
        sun = particles[0]
        sun.mass = 1.0 | units.MSun
        sun.position = [0.0, 0.0, 0.0] | units.AU
        sun.velocity = [0.0, 0.0, 0.0] | units.AU / units.yr
        sun.radius = 1.0 | units.RSun

        earth = particles[1]
        earth.mass = 5.9736e24 | units.kg
        earth.radius = 6371.0 | units.km
        earth.position = [0.0, 1.0, 0.0] | units.AU
        earth.velocity = [2.0 * numpy.pi, -0.0001, 0.0] | units.AU / units.yr

        initial_direction = math.atan((earth.velocity[0] / earth.velocity[1]))
        final_direction = []
        for log_eps2 in range(-9, 10, 2):
            instance = Huayno(convert_nbody)
            instance.initialize_code()
            instance.parameters.epsilon_squared = 10.0**log_eps2 | units.AU**2
            instance.particles.add_particles(particles)
            instance.commit_particles()
            instance.evolve_model(0.25 | units.yr)
            final_direction.append(
                math.atan((instance.particles[1].velocity[0] /
                           instance.particles[1].velocity[1])))
            instance.stop()
        # Small values of epsilon_squared should result in normal earth-sun dynamics: rotation of 90 degrees
        self.assertAlmostEqual(abs(final_direction[0]),
                               abs(initial_direction + math.pi / 2.0), 2)
        # Large values of epsilon_squared should result in ~ no interaction
        self.assertAlmostEqual(final_direction[-1], initial_direction, 2)
        # Outcome is most sensitive to epsilon_squared when epsilon_squared = d(earth, sun)^2
        delta = [
            abs(final_direction[i + 1] - final_direction[i])
            for i in range(len(final_direction) - 1)
        ]
        self.assertEqual(delta[len(final_direction) // 2 - 1], max(delta))
Beispiel #23
0
    def test24(self):
        print "test massless particles/ kepler integrator"
        N=20        
        tend=2.| units.yr
        numpy.random.seed(12345)
        conv=nbody_system.nbody_to_si(4.| units.MSun, 5.|units.AU)
        orbiters=plummer.new_plummer_model(N,conv)
        sun=datamodel.Particle(mass=1.|units.MSun)
        sun.position=[12.3,1.,-.2]|units.AU
        sun.velocity=[10,50.,-20.]|units.kms
        orbiters.mass*=0.
        
        a0,eps0=elements(sun.mass,orbiters.x,orbiters.y,orbiters.z,
                      orbiters.vx,orbiters.vy,orbiters.vz)

        orbiters.position+=sun.position
        orbiters.velocity+=sun.velocity

        pos=dict()
        for inttype in [20,14]:
          code=Huayno(conv)
          code.parameters.inttype_parameter=inttype
          code.parameters.timestep_parameter=0.1
          code.particles.add_particle(sun)
          orbiters2=code.particles.add_particles(orbiters).copy()
          orbiters2.position-=sun.position
          orbiters2.velocity-=sun.velocity
          code.evolve_model(tend)
          a,eps=elements(sun.mass,orbiters2.x,orbiters2.y,orbiters2.z,
                    orbiters2.vx,orbiters2.vy,orbiters2.vz)

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

          dev=numpy.where(da > 1.e-12)[0]
          self.assertEqual( len(dev),0)
          dev=numpy.where(deps > 1.e-12)[0]
          self.assertEqual( len(dev),0)
          pos[inttype]=[orbiters2.x.value_in(units.AU),orbiters2.y.value_in(units.AU),orbiters2.z.value_in(units.AU)]
        self.assertAlmostEqual(pos[20][0],pos[14][0],12)
        self.assertAlmostEqual(pos[20][1],pos[14][1],12)
        self.assertAlmostEqual(pos[20][2],pos[14][2],12)
Beispiel #24
0
    def test25(self):
        print("test massless particles/ kepler integrator, smoothed")
        N = 10
        tend = 20. | units.yr
        numpy.random.seed(12345)
        conv = nbody_system.nbody_to_si(4. | units.MSun, 5. | units.AU)
        orbiters = plummer.new_plummer_model(N, conv)
        sun = datamodel.Particle(mass=1. | units.MSun)
        sun.position = [0, 0, 0] | units.AU
        sun.velocity = [0, 0, 0] | units.kms
        orbiters.mass *= 0.
        eps = (5. | units.AU)

        e0 = energy(sun.mass, eps, orbiters)
        l0 = angular_momentum(orbiters)

        pos = dict()
        for inttype in [20, 14]:
            code = Huayno(conv)
            code.parameters.inttype_parameter = inttype
            code.parameters.timestep_parameter = 0.1
            code.parameters.epsilon_squared = eps**2
            code.particles.add_particle(sun)
            orbiters2 = code.particles.add_particles(orbiters)
            code.evolve_model(tend)

            e1 = energy(sun.mass, eps, orbiters2)
            l1 = angular_momentum(orbiters2)
            de, dl = abs((e1 - e0) / e0).max(), abs((l1 - l0) / l1).max()
            self.assertTrue(numpy.all(de < 1.e-8))
            self.assertTrue(numpy.all(dl < 1.e-8))

            pos[inttype] = [
                orbiters2.x.value_in(units.AU),
                orbiters2.y.value_in(units.AU),
                orbiters2.z.value_in(units.AU)
            ]
        self.assertAlmostRelativeEqual(pos[20][0], pos[14][0],
                                       4)  # still not clear why 4
        self.assertAlmostRelativeEqual(pos[20][1], pos[14][1], 4)
        self.assertAlmostRelativeEqual(pos[20][2], pos[14][2], 4)
Beispiel #25
0
 def test1(self):
     convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 149.5e6 | units.km)
 
     huayno = Huayno(convert_nbody)
     huayno.initialize_code()
     huayno.parameters.epsilon_squared = 0.0 | units.AU**2
     
     stars = self.new_system_of_sun_and_earth()
     earth = stars[1]
     
     huayno.particles.add_particles(stars)
     
     huayno.evolve_model(365.0 | units.day)
     huayno.particles.copy_values_of_all_attributes_to(stars)
     
     position_at_start = earth.position.value_in(units.AU)[0]
     position_after_full_rotation = earth.position.value_in(units.AU)[0]
     self.assertAlmostEqual(position_at_start, position_after_full_rotation, 6)
     
     huayno.evolve_model(365.0 + (365.0 / 2) | units.day)
     
     huayno.particles.copy_values_of_all_attributes_to(stars)
     position_after_half_a_rotation = earth.position.value_in(units.AU)[0]
     self.assertAlmostEqual(-position_at_start, position_after_half_a_rotation, 2)
             
     huayno.evolve_model(365.0 + (365.0 / 2) + (365.0 / 4)  | units.day)
     
     huayno.particles.copy_values_of_all_attributes_to(stars)
     position_after_half_a_rotation = earth.position.value_in(units.AU)[1]
     self.assertAlmostEqual(-position_at_start, position_after_half_a_rotation, 3)
     
     huayno.cleanup_code()
     
     huayno.stop()
Beispiel #26
0
    def test22(self):
        print(
            "Testing zero-mass test particles in Huayno, can be used for removing particles when inside recursive evolve loop"
        )
        sun_and_earth = self.new_system_of_sun_and_earth()
        period = (4.0 * math.pi**2 * (1.0 | units.AU)**3 /
                  (constants.G * sun_and_earth.total_mass())).sqrt()
        convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun,
                                                 1.0 | units.AU)
        huayno = Huayno(convert_nbody)
        huayno.parameters.epsilon_squared = 0.0 | units.AU**2
        huayno.parameters.inttype_parameter = huayno.inttypes.SHARED8

        test_particle = datamodel.Particle(mass=0 | units.MSun,
                                           position=[4, 0, 0] | units.AU,
                                           velocity=[0, 0, 0] | units.kms)
        test_particle.vy = (constants.G * sun_and_earth.total_mass() /
                            (4.0 | units.AU)).sqrt()
        sun_and_earth.add_particle(test_particle)
        huayno.particles.add_particles(sun_and_earth)
        huayno.evolve_model(period)
        self.assertAlmostRelativeEqual(huayno.particles[:2].x,
                                       sun_and_earth[:2].x, 13)
        huayno.evolve_model(1.25 * period)
        self.assertAlmostRelativeEqual(huayno.particles[1].y,
                                       sun_and_earth[1].x, 13)
        huayno.evolve_model(8.0 * period)
        self.assertAlmostRelativeEqual(huayno.particles.x, sun_and_earth.x, 8)
        huayno.stop()
Beispiel #27
0
 def test1(self):
     convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 149.5e6 | units.km)
 
     huayno = Huayno(convert_nbody)
     huayno.initialize_code()
     huayno.parameters.epsilon_squared = 0.0 | units.AU**2
     
     stars = self.new_system_of_sun_and_earth()
     earth = stars[1]
     
     huayno.particles.add_particles(stars)
     
     huayno.evolve_model(365.0 | units.day)
     huayno.particles.copy_values_of_all_attributes_to(stars)
     
     position_at_start = earth.position.value_in(units.AU)[0]
     position_after_full_rotation = earth.position.value_in(units.AU)[0]
     self.assertAlmostEqual(position_at_start, position_after_full_rotation, 6)
     
     huayno.evolve_model(365.0 + (365.0 / 2) | units.day)
     
     huayno.particles.copy_values_of_all_attributes_to(stars)
     position_after_half_a_rotation = earth.position.value_in(units.AU)[0]
     self.assertAlmostEqual(-position_at_start, position_after_half_a_rotation, 2)
             
     huayno.evolve_model(365.0 + (365.0 / 2) + (365.0 / 4)  | units.day)
     
     huayno.particles.copy_values_of_all_attributes_to(stars)
     position_after_half_a_rotation = earth.position.value_in(units.AU)[1]
     self.assertAlmostEqual(-position_at_start, position_after_half_a_rotation, 3)
     
     huayno.cleanup_code()
     
     huayno.stop()
Beispiel #28
0
    def test2(self):
        convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun,
                                                 149.5e6 | units.km)

        instance = Huayno(convert_nbody)
        instance.initialize_code()
        instance.parameters.epsilon_squared = 0.0 | units.AU**2

        stars = self.new_system_of_sun_and_earth()
        earth = stars[1]
        instance.particles.add_particles(stars)

        for x in range(1, 2000, 10):
            instance.evolve_model(x | units.day)
            instance.particles.copy_values_of_all_attributes_to(stars)
            stars.savepoint()

        if HAS_MATPLOTLIB:
            figure = pyplot.figure()
            plot = figure.add_subplot(1, 1, 1)

            x_points = earth.get_timeline_of_attribute("x")
            y_points = earth.get_timeline_of_attribute("y")

            x_points_in_AU = [t_x[1].value_in(units.AU) for t_x in x_points]
            y_points_in_AU = [t_x1[1].value_in(units.AU) for t_x1 in y_points]

            plot.scatter(x_points_in_AU, y_points_in_AU, color="b", marker='o')

            plot.set_xlim(-1.5, 1.5)
            plot.set_ylim(-1.5, 1.5)

            test_results_path = self.get_path_to_results()
            output_file = os.path.join(test_results_path,
                                       "huayno-earth-sun2.svg")
            figure.savefig(output_file)

        instance.cleanup_code()
        del instance
Beispiel #29
0
 def test2(self):
     convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 149.5e6 | units.km)
 
     instance = Huayno(convert_nbody)
     instance.initialize_code()
     instance.parameters.epsilon_squared = 0.0 | units.AU**2
     
     stars = self.new_system_of_sun_and_earth()
     earth = stars[1]
     instance.particles.add_particles(stars)
 
     for x in range(1,2000,10):
         instance.evolve_model(x | units.day)
         instance.particles.copy_values_of_all_attributes_to(stars)
         stars.savepoint()
     
     if HAS_MATPLOTLIB:
         figure = pyplot.figure()
         plot = figure.add_subplot(1,1,1)
         
         x_points = earth.get_timeline_of_attribute("x")
         y_points = earth.get_timeline_of_attribute("y")
         
         x_points_in_AU = map(lambda (t,x) : x.value_in(units.AU), x_points)
         y_points_in_AU = map(lambda (t,x) : x.value_in(units.AU), y_points)
         
         plot.scatter(x_points_in_AU,y_points_in_AU, color = "b", marker = 'o')
         
         plot.set_xlim(-1.5, 1.5)
         plot.set_ylim(-1.5, 1.5)
            
         
         test_results_path = self.get_path_to_results()
         output_file = os.path.join(test_results_path, "huayno-earth-sun2.svg")
         figure.savefig(output_file)
           
     instance.cleanup_code()
     del instance
Beispiel #30
0
 def test15(self):
     particles = plummer.new_plummer_model(512)
     expected_positions = None
     for mode in ["cpu", "openmp", "opencl"]:
         try:
             instance = Huayno(mode=mode, number_of_workers=1)#, debugger="xterm")
         except:
             print "Running huayno with mode=", mode, " was unsuccessful."
             continue
         else:
             print "Running huayno with mode=", mode, "... "
             
         instance.initialize_code()
         instance.parameters.epsilon_squared = 0.01 | nbody_system.length ** 2
         instance.particles.add_particles(particles)
         
         instance.evolve_model(0.2 | nbody_system.time)
         instance.synchronize_model()
         if expected_positions is None:
             expected_positions = instance.particles.position
         else:
             self.assertAlmostRelativeEquals(expected_positions, instance.particles.position, 8)
         instance.stop()
Beispiel #31
0
    def test27(self):
        particles = plummer.new_plummer_model(31)

        tend = 0.25 | nbody_system.time

        instance = Huayno()
        instance.particles.add_particles(particles)
        instance.evolve_model(tend)
        expected_positions = instance.particles.position
        self.assertEqual(instance.model_time, tend)
        instance.stop()

        particles2 = particles.copy()
        particles2.velocity *= -1

        instance = Huayno()
        instance.particles.add_particles(particles2)
        instance.evolve_model(-tend)
        positions = instance.particles.position
        self.assertEqual(instance.model_time, -tend)
        instance.stop()

        self.assertAlmostEqual(positions, expected_positions)
Beispiel #32
0
    def test27(self):
        particles = plummer.new_plummer_model(31)

        tend=0.25| nbody_system.time

        instance = Huayno()
        instance.particles.add_particles(particles)        
        instance.evolve_model(tend)
        expected_positions = instance.particles.position
        self.assertEqual(instance.model_time, tend)
        instance.stop()
        
        particles2=particles.copy()
        particles2.velocity*=-1

        instance = Huayno()
        instance.particles.add_particles(particles2)        
        instance.evolve_model(-tend)
        positions = instance.particles.position
        self.assertEqual(instance.model_time, -tend)
        instance.stop()

        self.assertAlmostEqual(positions,expected_positions)
Beispiel #33
0
    def test25(self):
        print "test massless particles/ kepler integrator, smoothed"
        N=10        
        tend=20.| units.yr
        numpy.random.seed(12345)
        conv=nbody_system.nbody_to_si(4.| units.MSun, 5.|units.AU)
        orbiters=plummer.new_plummer_model(N,conv)
        sun=datamodel.Particle(mass=1.|units.MSun)
        sun.position=[0,0,0]|units.AU
        sun.velocity=[0,0,0]|units.kms
        orbiters.mass*=0.
        eps=(5. | units.AU)

        e0=energy(sun.mass,eps,orbiters)
        l0=angular_momentum(orbiters)
        
        pos=dict()
        for inttype in [20,14]:
          code=Huayno(conv)
          code.parameters.inttype_parameter=inttype
          code.parameters.timestep_parameter=0.1
          code.parameters.epsilon_squared=eps**2
          code.particles.add_particle(sun)
          orbiters2=code.particles.add_particles(orbiters)
          code.evolve_model(tend)

          e1=energy(sun.mass,eps,orbiters2)
          l1=angular_momentum(orbiters2)
          de,dl=abs((e1-e0)/e0).max(),abs((l1-l0)/l1).max()
          self.assertTrue( numpy.all(de< 1.e-8))
          self.assertTrue( numpy.all(dl< 1.e-8))

          pos[inttype]=[orbiters2.x.value_in(units.AU),orbiters2.y.value_in(units.AU),orbiters2.z.value_in(units.AU)]
        self.assertAlmostRelativeEqual(pos[20][0],pos[14][0],4) # still not clear why 4
        self.assertAlmostRelativeEqual(pos[20][1],pos[14][1],4)
        self.assertAlmostRelativeEqual(pos[20][2],pos[14][2],4)
Beispiel #34
0
    def test7(self):
        print "Test7: Testing effect of Huayno parameter epsilon_squared"
        convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.AU)
        
        particles = datamodel.Particles(2)
        sun = particles[0]
        sun.mass = 1.0 | units.MSun
        sun.position = [0.0, 0.0, 0.0] | units.AU
        sun.velocity = [0.0, 0.0, 0.0] | units.AU / units.yr
        sun.radius = 1.0 | units.RSun

        earth = particles[1]
        earth.mass = 5.9736e24 | units.kg
        earth.radius = 6371.0 | units.km
        earth.position = [0.0, 1.0, 0.0] | units.AU
        earth.velocity = [2.0*numpy.pi, -0.0001, 0.0] | units.AU / units.yr
        
        initial_direction = math.atan((earth.velocity[0]/earth.velocity[1]))
        final_direction = []
        for log_eps2 in range(-9,10,2):
            instance = Huayno(convert_nbody)
            instance.initialize_code()
            instance.parameters.epsilon_squared = 10.0**log_eps2 | units.AU ** 2
            instance.particles.add_particles(particles)
            instance.commit_particles()
            instance.evolve_model(0.25 | units.yr)
            final_direction.append(math.atan((instance.particles[1].velocity[0]/
                instance.particles[1].velocity[1])))
            instance.stop()
        # Small values of epsilon_squared should result in normal earth-sun dynamics: rotation of 90 degrees
        self.assertAlmostEquals(abs(final_direction[0]), abs(initial_direction+math.pi/2.0), 2)
        # Large values of epsilon_squared should result in ~ no interaction
        self.assertAlmostEquals(final_direction[-1], initial_direction, 2)
        # Outcome is most sensitive to epsilon_squared when epsilon_squared = d(earth, sun)^2
        delta = [abs(final_direction[i+1]-final_direction[i]) for i in range(len(final_direction)-1)]
        self.assertEquals(delta[len(final_direction)/2 -1], max(delta))
Beispiel #35
0
 def test22(self):
     print "Testing zero-mass test particles in Huayno, can be used for removing particles when inside recursive evolve loop"
     sun_and_earth = self.new_system_of_sun_and_earth()
     period = (4.0 * math.pi**2 * (1.0 | units.AU)**3 / (constants.G * sun_and_earth.total_mass())).sqrt()
     convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.AU)
     huayno = Huayno(convert_nbody)
     huayno.parameters.epsilon_squared = 0.0 | units.AU**2
     huayno.parameters.inttype_parameter = huayno.inttypes.SHARED8
     
     test_particle = datamodel.Particle(mass=0|units.MSun, position=[4,0,0]|units.AU, velocity=[0,0,0]|units.kms)
     test_particle.vy = (constants.G * sun_and_earth.total_mass() / (4.0 | units.AU)).sqrt()
     sun_and_earth.add_particle(test_particle)
     huayno.particles.add_particles(sun_and_earth)
     huayno.evolve_model(period)
     self.assertAlmostRelativeEqual(huayno.particles[:2].x, sun_and_earth[:2].x, 13)
     huayno.evolve_model(1.25 * period)
     self.assertAlmostRelativeEqual(huayno.particles[1].y, sun_and_earth[1].x, 13)
     huayno.evolve_model(8.0 * period)
     self.assertAlmostRelativeEqual(huayno.particles.x, sun_and_earth.x, 8)
     huayno.stop()
Beispiel #36
0
def main_function(number_of_stars=1000,
                  end_time=4.0e4 | units.yr,
                  steps=100,
                  number_of_workers=6,
                  animate=True,
                  save_animation=False,
                  escape=False,
                  Q=0.5,
                  D=2.6,
                  filename="default.mp4",
                  use_huayno=False,
                  use_tree=False):
    """
    Simulates a cluster of stars with varying masses. 
    Input: 
    :param number_of_stars: Number of stars to simulate, default: 1000
    :param end_time:        Total time at which to stop in nbody_system.time units (I think), 
                            default 10 | nbody_system.time
    :param steps:           Total number of steps to save, default: 1000
    :param number_of_workers: Number of cores/threads to use, does nothing when using Huayno, default: 5
    :param animate:         Makes an animation of the stars at each step (size depends on star mass), default: True
    :param save_animation:  Saves the animation as mp4 file, default: True
    :param Q:               Kinectic to potential energy fraction (I think) default: 0.5
    :param D:               Measure of fragmentedness, must be between 1.5 and 3, default 2.6
    :param filename:        Determines the name of the mp4 file, default: "default.mp4"
    :param use_huayno:      Use alternative Huayno gravity evolver, default: False
    :return: (array of position arrays at each time step, array of time at each time step) 
    """

    start_time = clock_time()

    particles = new_cluster(number_of_stars=number_of_stars, Q=Q, D=D)
    total_mass = particles.mass.sum()
    convert_nbody = nbody_system.nbody_to_si(total_mass, 1.0 | units.parsec)

    # Initialize gravity can use others for tests, but hermite is used
    if use_huayno:
        gravity = Huayno(convert_nbody,
                         number_of_workers=number_of_workers / 2)
    elif use_tree:
        gravity = BHTree(convert_nbody,
                         number_of_workers=1,
                         epsilon_squared=0.05 | nbody_system.length**2)
    else:
        gravity = Hermite(convert_nbody,
                          number_of_workers=number_of_workers / 2)

    gravity.parameters.epsilon_squared = 0.05 | nbody_system.length**2
    # gravity.parameters.epsilon_squared = 0.15 | nbody_system.length ** 2 # Used to be this
    gravity.particles.add_particles(particles)
    from_gravity_to_model = gravity.particles.new_channel_to(particles)

    # particles.scale_to_standard() Cannot scale to standard if not using nbody_system units

    # Initialize the Evolution
    if not use_tree:
        stellar_evolution = SSE(number_of_workers=number_of_workers / 2)
    else:
        stellar_evolution = SSE(number_of_workers=number_of_workers - 1)
    stellar_evolution.particles.add_particles(particles)
    from_stellar_evolution_to_model = stellar_evolution.particles.new_channel_to(
        particles)
    from_stellar_evolution_to_model.copy_attributes(
        ["mass", "luminosity", "temperature"])

    # Initial time (note * end_time for correct units)
    time = 0.0 * end_time

    # Save initial conditions and make arrays (lists) for each step
    total_energy_at_t0 = gravity.kinetic_energy + gravity.potential_energy
    save_positions = [particles.position]
    save_velocities = [particles.velocity]
    save_masses = [particles.mass]
    save_luminosities = [particles.luminosity]
    save_temperatures = [particles.temperature]
    times = [time]

    while time < end_time:
        time += end_time / steps

        # Evolve gravity
        gravity.evolve_model(time)
        from_gravity_to_model.copy()

        # Evolve stars
        stellar_evolution.evolve_model(time)
        from_gravity_to_model.copy()
        from_stellar_evolution_to_model.copy_attributes(
            ["mass", "luminosity", "temperature"])

        # Save data
        save_positions.append(particles.position)
        save_velocities.append(particles.velocity)
        save_masses.append(particles.mass)
        save_luminosities.append(particles.luminosity)
        save_temperatures.append(particles.temperature)
        times.append(time)

        total_energy = gravity.kinetic_energy + gravity.potential_energy
        if np.abs(
            (total_energy - total_energy_at_t0) / total_energy_at_t0) > 0.001:
            print(
                "Warning! Total energy of the system is changing too significantly!"
            )

        print "Time: %.4g" % time.number
        total_mass = particles.mass.sum()
        print total_mass

    if escape:
        escaped_stars_3d, escaped_stars_2d = find_escapees(particles)

    gravity.stop()
    stellar_evolution.stop()
    print "It took %.3g seconds clock time" % (clock_time() - start_time)

    if animate:
        make_animation(save_positions,
                       save_luminosities,
                       save_temperatures,
                       times,
                       save_animation=save_animation,
                       filename=filename)
    if escape:
        return save_positions[-1], save_velocities[-1], save_masses[
            -1], escaped_stars_3d, escaped_stars_2d
    else:
        return save_positions, save_velocities
Beispiel #37
0
def test_run():        
    three=binary_with_planet(
      m1=0.6897 | units.MSun,m2=0.20255 | units.MSun,m_planet=0.333 | units.MJupiter,
      r1=0.6489 | units.RSun,r2=0.22623 | units.RSun,r_planet=0.754 | units.RJupiter,
      ecc_binary=0.15944,P_binary=41.08| units.day,ecc_planet=0.00685,a_planet=.7048 | units.AU,
      pangle_planet=0.) 

    convert=nbody_system.nbody_to_si(1|units.MSun,1|units.AU)
    code=Huayno(convert)
    
    code.parameters.inttype_parameter=code.inttypes.SHARED4
    code.parameters.timestep_parameter=0.1
    
#    tend=100. | units.yr
    tend=100. | units.day
    snapfreq=1
    
    dt=10. | units.day
#    dt=convert.to_si( 1. | nbody_system.time).in_(units.day)
    
    code.particles.add_particles(three)

    x = AdaptingVectorQuantity()
    y = AdaptingVectorQuantity()
    z = AdaptingVectorQuantity()
    vx = AdaptingVectorQuantity()
    vy = AdaptingVectorQuantity()
    vz = AdaptingVectorQuantity()
    x.append(code.particles.x)
    y.append(code.particles.y)
    z.append(code.particles.z)
    vx.append(code.particles.vx)
    vy.append(code.particles.vy)
    vz.append(code.particles.vz)
    ts=[0.]
    E0=code.potential_energy+code.kinetic_energy    
    dE=[1.e-14]
    t=0. | units.day
    i=0
    while(t < tend-dt/2):
        i+=1
        t=t+dt
        if i%snapfreq==0:
          print t
          ts.append(t.value_in(units.day))
          code.evolve_model(t)
          x.append(code.particles.x)
          y.append(code.particles.y)
          z.append(code.particles.z)
          vx.append(code.particles.vx)
          vy.append(code.particles.vy)
          vz.append(code.particles.vz)
          E=code.potential_energy+code.kinetic_energy    
          dE.append(abs(((E-E0)/E0)))
    code.stop()

    a,eps,pangle=elements(three.total_mass(),
    x[:,2],
    y[:,2],
    z[:,2],
    vx[:,2],
    vy[:,2],
    vz[:,2])

    x=x.value_in(units.AU)
    y=y.value_in(units.AU)
    
    a=a.value_in(units.AU)
    eps=eps
    
    print a[-1],eps[-1],pangle[-1]

    f=pyplot.figure(figsize=(8,8))
    pyplot.plot(x[:,0],y[:,0],'r.')
    pyplot.plot(x[:,1],y[:,1],'g.')
    pyplot.plot(x[:,2],y[:,2],'b.')
    pyplot.xlim(-3,3)
    pyplot.ylim(-3,3)
    pyplot.xlabel('AU')
    pyplot.savefig('three_16b.eps')

    f=pyplot.figure(figsize=(8,8))
    pyplot.semilogy(ts,dE,'g.')
    pyplot.xlabel('time (day)')
    pyplot.ylabel('dE/E0')
    pyplot.savefig('three_16b_eerr.eps')

    f=pyplot.figure(figsize=(8,8))
    pyplot.plot(ts,a,'g.')
    pyplot.xlabel('time (day)')
    pyplot.ylabel('a (AU)')
    pyplot.savefig('three_16b_a.eps')

    f=pyplot.figure(figsize=(8,8))
    pyplot.plot(ts,eps,'g.')
    pyplot.xlabel('time (day)')
    pyplot.ylabel('eccentricity')
    pyplot.savefig('three_16b_ecc.eps')

    f=pyplot.figure(figsize=(8,8))
    pyplot.plot(ts,pangle,'g.')
    pyplot.xlabel('time (day)')
    pyplot.ylabel('long. of periapsis')
    pyplot.savefig('three_16b_pangle.eps')
def binary_with_planet_run(m1=1. | units.MSun,
                           m2=1. | units.MSun,
                           m_planet=1 | units.MJupiter,
                           r1=None,
                           r2=None,
                           r_planet=None,
                           ecc_binary=0,
                           P_binary=20 | units.day,
                           ecc_planet=0.,
                           P_planet=1. | units.yr,
                           pangle_planet=0.,
                           a_planet=None,
                           tend=100. | units.yr,
                           hostname=''):

    dEcrit = 1.e-6

    three = binary_with_planet(m1=m1,
                               m2=m2,
                               m_planet=m_planet,
                               r1=r1,
                               r2=r2,
                               r_planet=r_planet,
                               ecc_binary=ecc_binary,
                               P_binary=P_binary,
                               ecc_planet=ecc_planet,
                               a_planet=a_planet,
                               pangle_planet=pangle_planet)

    convert = nbody_system.nbody_to_si(1 | units.MSun, 1 | units.AU)
    code = Huayno(convert, hostname=hostname)

    code.parameters.inttype_parameter = code.inttypes.SHARED10
    code.parameters.timestep_parameter = .2
    code.parameters.timestep = 100. | units.day

    dt = 10000. | units.day

    code.particles.add_particles(three)

    E0 = code.potential_energy + code.kinetic_energy
    a0, eps0, pangle0 = elements(three.total_mass(), code.particles.x[2],
                                 code.particles.y[2], code.particles.z[2],
                                 code.particles.vx[2], code.particles.vy[2],
                                 code.particles.vz[2])

    t = 0. | units.day
    result = "stable"
    while (t < tend - dt / 2):
        t = t + dt
        code.evolve_model(t)
        E = code.potential_energy + code.kinetic_energy
        dE = abs(((E - E0) / E0))
        a, eps, pangle = elements(three.total_mass(), code.particles.x[2],
                                  code.particles.y[2], code.particles.z[2],
                                  code.particles.vx[2], code.particles.vy[2],
                                  code.particles.vz[2])
        if dE > dEcrit or a < 0.5 * a0 or a > 2. * a0:
            result = "unstable"
            if dE > dEcrit:
                result = "failed"
            break
    code.stop()
    return result, t, dE, a.in_(units.AU), eps, pangle
def test_run():
    three = binary_with_planet(m1=0.6897 | units.MSun,
                               m2=0.20255 | units.MSun,
                               m_planet=0.333 | units.MJupiter,
                               r1=0.6489 | units.RSun,
                               r2=0.22623 | units.RSun,
                               r_planet=0.754 | units.RJupiter,
                               ecc_binary=0.15944,
                               P_binary=41.08 | units.day,
                               ecc_planet=0.00685,
                               a_planet=.7048 | units.AU,
                               pangle_planet=0.)

    convert = nbody_system.nbody_to_si(1 | units.MSun, 1 | units.AU)
    code = Huayno(convert)

    code.parameters.inttype_parameter = code.inttypes.SHARED4
    code.parameters.timestep_parameter = 0.1

    #    tend=100. | units.yr
    tend = 100. | units.day
    snapfreq = 1

    dt = 10. | units.day
    #    dt=convert.to_si( 1. | nbody_system.time).in_(units.day)

    code.particles.add_particles(three)

    x = AdaptingVectorQuantity()
    y = AdaptingVectorQuantity()
    z = AdaptingVectorQuantity()
    vx = AdaptingVectorQuantity()
    vy = AdaptingVectorQuantity()
    vz = AdaptingVectorQuantity()
    x.append(code.particles.x)
    y.append(code.particles.y)
    z.append(code.particles.z)
    vx.append(code.particles.vx)
    vy.append(code.particles.vy)
    vz.append(code.particles.vz)
    ts = [0.]
    E0 = code.potential_energy + code.kinetic_energy
    dE = [1.e-14]
    t = 0. | units.day
    i = 0
    while (t < tend - dt / 2):
        i += 1
        t = t + dt
        if i % snapfreq == 0:
            print t
            ts.append(t.value_in(units.day))
            code.evolve_model(t)
            x.append(code.particles.x)
            y.append(code.particles.y)
            z.append(code.particles.z)
            vx.append(code.particles.vx)
            vy.append(code.particles.vy)
            vz.append(code.particles.vz)
            E = code.potential_energy + code.kinetic_energy
            dE.append(abs(((E - E0) / E0)))
    code.stop()

    a, eps, pangle = elements(three.total_mass(), x[:, 2], y[:, 2], z[:, 2],
                              vx[:, 2], vy[:, 2], vz[:, 2])

    x = x.value_in(units.AU)
    y = y.value_in(units.AU)

    a = a.value_in(units.AU)
    eps = eps

    print a[-1], eps[-1], pangle[-1]

    f = pyplot.figure(figsize=(8, 8))
    pyplot.plot(x[:, 0], y[:, 0], 'r.')
    pyplot.plot(x[:, 1], y[:, 1], 'g.')
    pyplot.plot(x[:, 2], y[:, 2], 'b.')
    pyplot.xlim(-3, 3)
    pyplot.ylim(-3, 3)
    pyplot.xlabel('AU')
    pyplot.savefig('three_16b.eps')

    f = pyplot.figure(figsize=(8, 8))
    pyplot.semilogy(ts, dE, 'g.')
    pyplot.xlabel('time (day)')
    pyplot.ylabel('dE/E0')
    pyplot.savefig('three_16b_eerr.eps')

    f = pyplot.figure(figsize=(8, 8))
    pyplot.plot(ts, a, 'g.')
    pyplot.xlabel('time (day)')
    pyplot.ylabel('a (AU)')
    pyplot.savefig('three_16b_a.eps')

    f = pyplot.figure(figsize=(8, 8))
    pyplot.plot(ts, eps, 'g.')
    pyplot.xlabel('time (day)')
    pyplot.ylabel('eccentricity')
    pyplot.savefig('three_16b_ecc.eps')

    f = pyplot.figure(figsize=(8, 8))
    pyplot.plot(ts, pangle, 'g.')
    pyplot.xlabel('time (day)')
    pyplot.ylabel('long. of periapsis')
    pyplot.savefig('three_16b_pangle.eps')