Example #1
0
    def test22(self):
        particles = new_plummer_model(200)
        particles.scale_to_standard()
        try:
            instance = ph4(mode="gpu")
        except:
            self.skip("gpu mode is not available")

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

        x = numpy.arange(-1, 1, 0.1) | nbody_system.length
        zero = numpy.zeros(len(x)) | nbody_system.length
        gpu_potential = instance.get_potential_at_point(zero, x, zero, zero)
        instance.stop()

        instance = ph4()
        instance.initialize_code()
        instance.parameters.epsilon_squared = 0.00000 | nbody_system.length ** 2
        instance.particles.add_particles(particles)
        nogpu_potential = instance.get_potential_at_point(zero, x, zero, zero)

        self.assertAlmostRelativeEquals(nogpu_potential, gpu_potential, 5)
        instance.stop()
Example #2
0
    def test16(self):
        print "Testing ph4 states"
        stars = new_plummer_model(100)
        black_hole = datamodel.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 = ph4()
        self.assertEquals(instance.get_name_of_current_state(), 'UNINITIALIZED')
        instance.initialize_code()
        self.assertEquals(instance.get_name_of_current_state(), 'INITIALIZED')
        instance.parameters.epsilon_squared = 0.0 | nbody_system.length**2
        instance.parameters.timestep_parameter = 0.01
        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 = ph4()
        self.assertEquals(instance.get_name_of_current_state(), 'UNINITIALIZED')
        instance.parameters.epsilon_squared = 0.0 | nbody_system.length**2
        instance.parameters.timestep_parameter = 0.01
        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')
Example #3
0
 def test27(self):
     print "Testing get timestep of particles"
     with_softening = True
     
     particles = datamodel.Particles(7)
     particles.mass = 0.1 | nbody_system.mass
     particles.radius = 0.01 | nbody_system.length
     particles.x = [-101.0, -100.0, -2.0, 2.0, 98.0, 102.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 + [[-5, 0, 0]] | nbody_system.speed
     total_energy = particles.potential_energy(G=nbody_system.G) + particles.kinetic_energy()
     
     instance = ph4()
     instance.initialize_code()
     instance.parameters.set_defaults()
     
     if with_softening:
         print "small amount of softening will prevent timesteps far below 1e-6 and huge energy errors..."
         instance.parameters.epsilon_squared = 1.0e-10 | nbody_system.length**2
     instance.particles.add_particles(particles)
     
     for target_time, min_dt, n_digits in zip([0, 0.23, 0.24, 0.26, 0.27]|nbody_system.time, 
             [0.5**10, 0.5**11, 0.5**20, 0.5**10, 0.5**10]|nbody_system.time,
             [10, 7, 4, 5, 5]):
         instance.evolve_model(target_time)
         if with_softening:
             self.assertEquals(instance.particles.timestep.amin(), min_dt)
             self.assertAlmostRelativeEquals(instance.potential_energy + instance.kinetic_energy, total_energy, n_digits)
         else:
             print "\ntarget_time:", target_time
             print "minimum timestep:", instance.particles.timestep.amin()
             print "energy error:", (instance.potential_energy + instance.kinetic_energy - total_energy) / total_energy
         total_energy = instance.potential_energy + instance.kinetic_energy
     instance.stop()
Example #4
0
    def test3(self):
        convert_nbody = nbody_system.nbody_to_si(5.0 | units.kg, 10.0 | units.m)

        instance = ph4(convert_nbody)

        instance.initialize_code()

        particles = datamodel.Particles(2)
        self.assertEquals(len(instance.particles), 0)

        particles.mass = [15.0, 30.0] | units.kg
        particles.radius = [10.0, 20.0] | units.m
        particles.position = [[10.0, 20.0, 30.0], [20.0, 40.0, 60.0]] | units.m
        particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | units.m / units.s

        instance.particles.add_particles(particles)
        self.assertEquals(len(instance.particles), 2)
        instance.commit_particles()

        instance.particles.mass = [17.0, 33.0] | units.kg

        self.assertEquals(instance.get_mass(1), 17.0 | units.kg)
        self.assertEquals(instance.get_mass(2), 33.0 | units.kg)

        instance.cleanup_code()
        instance.stop()
Example #5
0
    def xtest12(self):
        particles = datamodel.Particles(2)
        particles.x = [
            0.0,
            1.0,
            # 5,7,
            # 10,12,
            # 15,17,
            # 20,22
        ] | nbody_system.length
        particles.y = 0 | nbody_system.length
        particles.z = 0 | nbody_system.length
        particles.radius = 0.75 | nbody_system.length
        particles.vx = 0 | nbody_system.speed
        particles.vy = 0 | nbody_system.speed
        particles.vz = 0 | nbody_system.speed
        particles.mass = 1.0 | nbody_system.mass

        instance = ph4()
        instance.initialize_code()
        instance.parameters.epsilon_squared = (0.01 | nbody_system.length) ** 2
        instance.particles.add_particles(particles)
        instance.stopping_conditions.pair_detection.enable()
        instance.evolve_model(1.5 | nbody_system.time)
        self.assertTrue(instance.stopping_conditions.pair_detection.is_set())
        self.assertEquals(len(instance.stopping_conditions.pair_detection.particles(0)), 2)
        p0 = instance.stopping_conditions.pair_detection.particles(0)[0]
        p1 = instance.stopping_conditions.pair_detection.particles(1)[0]
        self.assertNotEquals(p0, p1)
        self.assertTrue(p1.x - p0.x < 1.5 | nbody_system.length)
        instance.stop()
Example #6
0
    def xtest14(self):
        particles = datamodel.Particles(2)
        particles.x = [0.0, 10.0] | nbody_system.length
        particles.y = 0 | nbody_system.length
        particles.z = 0 | nbody_system.length
        particles.radius = 0.005 | nbody_system.length
        particles.vx = 0 | nbody_system.speed
        particles.vy = 0 | nbody_system.speed
        particles.vz = 0 | nbody_system.speed
        particles.mass = 1.0 | nbody_system.mass

        very_short_time_to_evolve = 1 | units.s
        very_long_time_to_evolve = 1e9 | nbody_system.time

        instance = ph4()
        instance.initialize_code()
        instance.parameters.stopping_conditions_timeout = very_short_time_to_evolve
        self.assertEquals(instance.parameters.stopping_conditions_timeout, very_short_time_to_evolve)
        instance.parameters.epsilon_squared = (0.01 | nbody_system.length) ** 2
        instance.particles.add_particles(particles)
        instance.stopping_conditions.timeout_detection.enable()
        start = time.time()
        instance.evolve_model(very_long_time_to_evolve)
        end = time.time()
        self.assertTrue(instance.stopping_conditions.timeout_detection.is_set())
        self.assertTrue(
            (end - start) < very_short_time_to_evolve.value_in(units.s) + 2
        )  # 2 = some overhead compensation

        instance.stop()
Example #7
0
    def xtest8(self):
        particles = datamodel.Particles(6)
        particles.mass = nbody_system.mass.new_quantity(range(1, 7))
        particles.radius = 0.00001 | nbody_system.length
        particles.position = [
            [-1.0, 0.0, 0.0],
            [1.0, 0.0, 0.0],
            [0.0, -1.0, 0.0],
            [0.0, 1.0, 0.0],
            [0.0, 0.0, -1.0],
            [0.0, 0.0, 1.0],
        ] | nbody_system.length
        particles.velocity = [
            [0.0, 0.0, 0.0],
            [0.0, 0.0, 0.0],
            [0.0, 0.0, 0.0],
            [0.0, 0.0, 0.0],
            [0.0, 0.0, 0.0],
            [0.0, 0.0, 0.0],
        ] | nbody_system.speed

        for current_mode in ["gpu"]:
            try:
                instance = ph4(mode=current_mode)
            except:
                print "Running PhiGRAPE with mode=", current_mode, " was unsuccessful."
            else:
                print "Running PhiGRAPE with mode=", current_mode, "... ",
                instance.initialize_code()
                instance.particles.add_particles(particles)
                instance.initialize_particles(0.0)
                instance.evolve_model(0.1 | nbody_system.time)
                instance.cleanup_code()
                instance.stop()
                print "ok"
Example #8
0
    def xtest7(self):
        instance = ph4()
        instance.initialize_code()
        instance.parameters.epsilon_squared = 0.0 | nbody_system.length ** 2
        instance.set_eta(0.01, 0.02)

        particles = datamodel.Particles(2)
        particles.mass = [1.0, 1.0] | nbody_system.mass
        particles.radius = [0.0001, 0.0001] | nbody_system.length
        particles.position = [[0.0, 0.0, 0.0], [2.0, 0.0, 0.0]] | nbody_system.length
        particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | nbody_system.speed
        instance.particles.add_particles(particles)

        instance.initialize_particles(0.0)

        zero = [0.0, 0.0, 0.0] | nbody_system.length
        fx, fy, fz = instance.get_gravity_at_point(zero, [0.5, 1.0, 1.5] | nbody_system.length, zero, zero)
        self.assertAlmostRelativeEqual(fx[0], -3.55555555556 | nbody_system.acceleration, 5)
        self.assertAlmostRelativeEqual(fy[0], 0.0 | nbody_system.acceleration, 3)
        self.assertAlmostRelativeEqual(fz[0], 0.0 | nbody_system.acceleration, 3)
        self.assertAlmostRelativeEqual(fx[1], 0.0 | nbody_system.acceleration, 3)
        self.assertAlmostRelativeEqual(fy[1], 0.0 | nbody_system.acceleration, 3)
        self.assertAlmostRelativeEqual(fz[1], 0.0 | nbody_system.acceleration, 3)
        self.assertAlmostRelativeEqual(fx[2], 3.55555555556 | nbody_system.acceleration, 5)
        self.assertAlmostRelativeEqual(fy[2], 0.0 | nbody_system.acceleration, 3)
        self.assertAlmostRelativeEqual(fz[2], 0.0 | nbody_system.acceleration, 3)

        n = 512
        x = nbody_system.length.new_quantity(numpy.linspace(0.1, 1.9, n))
        zero = nbody_system.length.new_quantity(numpy.zeros(n))
        fx, fy, fz = instance.get_gravity_at_point(zero, x, zero, zero)
        for i in range(n / 2):
            self.assertAlmostRelativeEqual(fx[i], -fx[n - 1 - i], 5)

        instance.stop()
Example #9
0
    def test18(self):
        print "Testing effect of ph4 parameter epsilon_squared"
        converter = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.AU)
        particles = datamodel.Particles(2)
        particles.mass = [1.0, 3.0037e-6] | units.MSun
        particles.radius = 1.0 | units.RSun
        particles.position = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]] | units.AU
        particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | units.km / units.s
        particles[1].vy = (constants.G * particles.total_mass() / (1.0 | units.AU)).sqrt()
        particles.rotate(0.0, 0.0, math.pi / 4)
        particles.move_to_center()

        tan_initial_direction = particles[1].vy / particles[1].vx
        self.assertAlmostEquals(tan_initial_direction, math.tan(-math.pi / 4))
        tan_final_direction = []
        for log_eps2 in range(-5, 6, 2):
            instance = ph4(converter)
            instance.initialize_code()
            instance.parameters.epsilon_squared = 10.0 ** log_eps2 | units.AU ** 2
            instance.parameters.timestep_parameter = 0.001
            instance.commit_parameters()
            instance.particles.add_particles(particles)
            instance.commit_particles()
            instance.evolve_model(0.25 | units.yr)
            tan_final_direction.append(instance.particles[1].velocity[1] / instance.particles[1].velocity[0])
            instance.cleanup_code()
            instance.stop()
        # Small values of epsilon_squared should result in normal earth-sun dynamics: rotation of 90 degrees
        self.assertAlmostEquals(tan_final_direction[0], math.tan(math.pi / 4.0), 2)
        # Large values of epsilon_squared should result in ~ no interaction
        self.assertAlmostEquals(tan_final_direction[-1], tan_initial_direction, 2)
        # Outcome is most sensitive to epsilon_squared when epsilon_squared = d(earth, sun)^2
        delta = [abs(tan_final_direction[i + 1] - tan_final_direction[i]) for i in range(len(tan_final_direction) - 1)]
        self.assertEquals(delta[len(tan_final_direction) // 2 - 1], max(delta))
Example #10
0
    def test19(self):
        print "Testing ph4 properties"
        particles = new_plummer_model(1000, do_scale=True)
        particles.position += [1, 2, 3] | nbody_system.length
        cluster_velocity = [4, 5, 6] | nbody_system.speed
        particles.velocity += cluster_velocity
        external_kinetic_energy = (0.5 | nbody_system.mass) * cluster_velocity.length_squared()

        instance = ph4()
        instance.particles.add_particles(particles)

        kinetic_energy = instance.kinetic_energy - external_kinetic_energy
        potential_energy = instance.potential_energy
        self.assertAlmostRelativeEqual(kinetic_energy, 0.25 | nbody_system.energy, 10)
        self.assertAlmostRelativeEqual(potential_energy, -0.5 | nbody_system.energy, 10)
        self.assertAlmostRelativeEqual(instance.total_mass, 1.0 | nbody_system.mass, 10)
        self.assertAlmostRelativeEqual(instance.center_of_mass_position, [1, 2, 3] | nbody_system.length, 10)
        self.assertAlmostRelativeEqual(instance.center_of_mass_velocity, [4, 5, 6] | nbody_system.speed, 10)
        initial_total_energy = kinetic_energy + potential_energy

        instance.evolve_model(0.1 | nbody_system.time)
        self.assertAlmostRelativeEqual(instance.model_time, 0.1 | nbody_system.time, 3)
        kinetic_energy = instance.kinetic_energy - external_kinetic_energy
        potential_energy = instance.potential_energy
        self.assertAlmostRelativeEqual(kinetic_energy + potential_energy, -0.25 | nbody_system.energy, 3)
        self.assertAlmostRelativeEqual(instance.total_mass, 1.0 | nbody_system.mass, 3)
        self.assertAlmostRelativeEqual(instance.center_of_mass_position, [1.4, 2.5, 3.6] | nbody_system.length, 3)
        self.assertAlmostRelativeEqual(instance.center_of_mass_velocity, [4, 5, 6] | nbody_system.speed, 3)

        instance.cleanup_code()
        instance.stop()
Example #11
0
    def test26(self):

        particles = datamodel.Particles(
            mass=[1, 2] | nbody_system.mass,
            x=[-1, 1] | nbody_system.length,
            y=[0, 0] | nbody_system.length,
            z=[0, 0] | nbody_system.length,
            vx=[-1, 1] | nbody_system.speed,
            vy=[-1, 1] | nbody_system.speed,
            vz=[-1, 1] | nbody_system.speed,
            id=[3, 4],
        )

        instance = ph4()

        instance.particles.add_particles(particles)
        self.assertEquals(instance.particles.index_in_code, [3, 4])
        instance.commit_particles()
        print instance.particles[0].potential_in_code
        self.assertEquals(
            instance.particles[0].potential(G=nbody_system.G),
            -(nbody_system.G * (2 | nbody_system.mass)) / (2 | nbody_system.length),
        )
        self.assertEquals(
            instance.particles[0].potential_in_code,
            -(nbody_system.G * (2 | nbody_system.mass)) / (2 | nbody_system.length),
        )
Example #12
0
    def test23(self):

        particles = datamodel.Particles(
            mass=[1, 2] | nbody_system.mass,
            x=[-1, 1] | nbody_system.length,
            y=[-1, 1] | nbody_system.length,
            z=[-1, 1] | nbody_system.length,
            vx=[-1, 1] | nbody_system.speed,
            vy=[-1, 1] | nbody_system.speed,
            vz=[-1, 1] | nbody_system.speed,
        )

        instance = ph4()

        overlay = datamodel.ParticlesOverlay(instance.particles)

        overlay.add_particles(particles)
        all_attributes = overlay.get_values_in_store(
            overlay.get_all_indices_in_store(), ["mass", "x", "y", "z", "vx", "vy", "vz"]
        )

        self.assertEquals(all_attributes[0], [1, 2] | nbody_system.mass)
        self.assertEquals(instance.particles.mass, [1, 2] | nbody_system.mass)
        self.assertEquals(overlay.mass, [1, 2] | nbody_system.mass)
        self.assertEquals(overlay.position, [[-1.0, -1.0, -1.0], [1.0, 1.0, 1.0]] | nbody_system.length)
Example #13
0
    def test10(self):
        instance = ph4()
        instance.initialize_code()

        instance.parameters.epsilon_squared = 0.0 | nbody_system.length ** 2
        instance.parameters.timestep_parameter = 0.01

        stars = new_plummer_model(100)

        instance.particles.add_particles(stars)
        channel = stars.new_channel_to(instance.particles)

        instance.evolve_model(0.001 | nbody_system.time)

        e0 = instance.kinetic_energy + instance.potential_energy

        stars.mass *= 0.9
        channel.copy()

        instance.synchronize_model()

        e1 = instance.kinetic_energy + instance.potential_energy

        instance.cleanup_code()
        instance.stop()

        delta_e = e1 - e0

        self.assertTrue(e1 != e0)
Example #14
0
    def test4(self):
        instance = ph4()
        instance.initialize_code()

        particles = datamodel.Particles(6)
        particles.mass = nbody_system.mass.new_quantity(range(1, 7))
        particles.radius = 0.00001 | nbody_system.length
        particles.position = [
            [-1.0, 0.0, 0.0],
            [1.0, 0.0, 0.0],
            [0.0, -1.0, 0.0],
            [0.0, 1.0, 0.0],
            [0.0, 0.0, -1.0],
            [0.0, 0.0, 1.0],
        ] | nbody_system.length
        particles.velocity = [
            [0.0, 0.0, 0.0],
            [0.0, 0.0, 0.0],
            [0.0, 0.0, 0.0],
            [0.0, 0.0, 0.0],
            [0.0, 0.0, 0.0],
            [0.0, 0.0, 0.0],
        ] | nbody_system.speed
        instance.particles.add_particles(particles)

        instance.commit_particles()
        copyof = instance.particles.copy()

        instance.cleanup_code()
        instance.stop()

        self.assertEquals(2 | nbody_system.mass, copyof[1].mass)
Example #15
0
    def test11(self):
        print "Testing PH4 collision_detection"
        particles = datamodel.Particles(7)
        particles.mass = 0.000001 | 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 = ph4()
        instance.initialize_code()
        instance.parameters.set_defaults()
        instance.parameters.epsilon_squared = 0 | nbody_system.length ** 2
        instance.particles.add_particles(particles)
        collisions = instance.stopping_conditions.collision_detection
        collisions.enable()

        for i in range(3):  # PH4 can handle only one collision (=closest) at a time
            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)), 1)
            self.assertEquals(len(collisions.particles(0)), 1)
            self.assertEquals(len(instance.particles - collisions.particles(0) - collisions.particles(1)), 5 - i)
            self.assertEquals(
                abs(collisions.particles(0).x - collisions.particles(1).x)
                < (collisions.particles(0).radius + collisions.particles(1).radius),
                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()
Example #16
0
def integrate_system(N, t_end, seed=None):

    gravity = ph4()
    gravity.initialize_code()
    gravity.parameters.set_defaults()
    
    if seed is not None: numpy.random.seed(seed)
    stars = new_plummer_model(N)
    stars.mass = 1./N | nbody_system.mass
    stars.scale_to_standard(smoothing_length_squared
                             = gravity.parameters.epsilon_squared)

    id = numpy.arange(N)
    stars.id = id+1

    # Set dynamical radii for encounters.

    stars.radius = 0.5*stars.mass.number | nbody_system.length

    gravity.particles.add_particles(stars)

    stopping_condition = gravity.stopping_conditions.collision_detection
    stopping_condition.enable()

    init_smalln()
    kep = Kepler(unit_converter=None)
    kep.initialize_code()
    multiples_code = multiples.Multiples(gravity, new_smalln, kep)
    multiples_code.neighbor_perturbation_limit = 0.05

    multiples_code.global_debug = 1

    #	global_debug = 0: no output from multiples
    #	               1: minimal output
    #	               2: debugging output
    #	               3: even more output

    print ''
    print 'multiples_code.neighbor_veto =', \
        multiples_code.neighbor_veto
    print 'multiples_code.neighbor_perturbation_limit =', \
        multiples_code.neighbor_perturbation_limit
    print 'multiples_code.retain_binary_apocenter =', \
        multiples_code.retain_binary_apocenter
    print 'multiples_code.wide_perturbation_limit =', \
        multiples_code.wide_perturbation_limit

    # Advance the system.

    E0 = print_diagnostics(multiples_code)
    multiples_code.evolve_model(t_end)
    print_diagnostics(multiples_code, E0)

    gravity.stop()
    kep.stop()
    stop_smalln()
Example #17
0
def evolve_cluster_in_galaxy(N, W0, Rinit, tend, timestep, M, R):

    R_galaxy=0.1 | units.kpc
    M_galaxy=1.6e10 | units.MSun
    converter=nbody_system.nbody_to_si(M_galaxy, R_galaxy)
    galaxy=new_plummer_model(10000,convert_nbody=converter)

    print "com:", galaxy.center_of_mass().in_(units.kpc)
    print "comv:", galaxy.center_of_mass_velocity().in_(units.kms)
   
    print len(galaxy)
    galaxy_code = BHTree(converter, number_of_workers=2)
    galaxy_code.parameters.epsilon_squared = (0.01 | units.kpc)**2
    channe_to_galaxy = galaxy_code.particles.new_channel_to(galaxy)
    channe_to_galaxy.copy()
    galaxy_code.particles.add_particles(galaxy)
    inner_stars = galaxy.select(lambda r: r.length()<Rinit,["position"])
    Minner = inner_stars.mass.sum()
    print "Minner=", Minner.in_(units.MSun)
    print "Ninner=", len(inner_stars)
    vc_inner = (constants.G*Minner/Rinit).sqrt()

    converter=nbody_system.nbody_to_si(Mcluster,Rcluster)
    stars=new_king_model(N,W0,convert_nbody=converter)
    masses = new_powerlaw_mass_distribution(N, 0.1|units.MSun, 100|units.MSun, -2.35)
    stars.mass = masses
    stars.scale_to_standard(converter)
    
    stars.x += Rinit
    stars.vy += 0.8*vc_inner
    cluster_code=ph4(converter, number_of_workers=2)
    cluster_code.particles.add_particles(stars)
    channel_to_stars=cluster_code.particles.new_channel_to(stars)

    system=bridge(verbose=False)
    system.add_system(cluster_code, (galaxy_code,))
    system.add_system(galaxy_code, (cluster_code,))
    system.timestep = 0.1*timestep

    times = quantities.arange(0|units.Myr, tend, timestep)
    for i,t in enumerate(times):
        print "Time=", t.in_(units.Myr)
        channe_to_galaxy.copy()
        channel_to_stars.copy()

        inner_stars =  galaxy.select(lambda r: r.length()<Rinit,["position"])
        print "Minner=", inner_stars.mass.sum().in_(units.MSun)

        system.evolve_model(t,timestep=timestep)
    plot_galaxy_and_stars(galaxy, stars)
    galaxy_code.stop()
    cluster_code.stop()
Example #18
0
    def test21(self):
        particles = new_plummer_model(200)
        particles.scale_to_standard()
        instance = ph4()
        instance.initialize_code()
        instance.parameters.epsilon_squared = 0.00000 | nbody_system.length ** 2
        instance.particles.add_particles(particles)

        x = numpy.arange(-1, 1, 0.1) | nbody_system.length
        zero = numpy.zeros(len(x)) | nbody_system.length
        potential0 = instance.get_potential_at_point(zero, x, zero, zero)
        instance.stop()
        for n in (2, 3, 4):

            instance = ph4(number_of_workers=n)
            instance.initialize_code()
            instance.parameters.epsilon_squared = 0.00000 | nbody_system.length ** 2
            instance.particles.add_particles(particles)
            potential = instance.get_potential_at_point(zero, x, zero, zero)

            self.assertAlmostRelativeEquals(potential0, potential, 8)
            instance.stop()
def run_pyth(te=100):

    dt = 0.01 | nbody_system.time
    t_end = te | nbody_system.time

    code = ph4()

    code.parameters.timestep_parameter = dt.value_in(nbody_system.time)
    code.particles.add_particles(new_particles())

    x = AdaptingVectorQuantity()
    y = AdaptingVectorQuantity()

    t = 0. | nbody_system.time

    eccents_12 = []
    eccents_23 = []
    eccents_31 = []

    semmajaxs_12 = []
    semmajaxs_23 = []
    semmajaxs_31 = []

    times = []

    while(t < t_end-dt/2):

        t=t+dt

        code.evolve_model(t)

        x.append(code.particles.x)
        y.append(code.particles.y)

        mass1, mass2, semimajor_axis_12, eccentricity_12, true_anomaly, inclination, long_asc_node, arg_per = orbital_elements_from_binary([code.particles[0], code.particles[1]])
        mass2, mass3, semimajor_axis_23, eccentricity_23, true_anomaly, inclination, long_asc_node, arg_per = orbital_elements_from_binary([code.particles[1], code.particles[2]])
        mass3, mass1, semimajor_axis_31, eccentricity_31, true_anomaly, inclination, long_asc_node, arg_per = orbital_elements_from_binary([code.particles[2], code.particles[0]])

        eccents_12.append(eccentricity_12)
        eccents_23.append(eccentricity_23)
        eccents_31.append(eccentricity_31)

        semmajaxs_12.append(semimajor_axis_12.value_in(nbody_system.length))
        semmajaxs_23.append(semimajor_axis_23.value_in(nbody_system.length))
        semmajaxs_31.append(semimajor_axis_31.value_in(nbody_system.length))

        times.append(t.value_in(nbody_system.time))

    code.stop()

    return x,y,times,semmajaxs_12,semmajaxs_23,semmajaxs_31,eccents_12,eccents_23,eccents_31
Example #20
0
    def test5(self):
        instance = ph4()
        instance.initialize_code()
        instance.parameters.manage_encounters = 2
        instance.parameters.epsilon_squared = 0.0 | nbody_system.length ** 2
        particles = datamodel.Particles(6)
        particles.mass = [0.01, 0.1, 0.1, 0.1, 0.1, 0.1] | nbody_system.mass
        particles.radius = 0.1 | nbody_system.length
        particles.position = [
            [-1.0, 0.0, 0.0],  # first two close together
            [-1.2, 0.0, 0.0],
            [0.0, 4.0, 0.0],  # rest far away
            [0.0, 5.0, 0.0],
            [0.0, 6.0, 0.0],
            [0.0, 7.0, 0.0],
        ] | nbody_system.length
        particles.velocity = [
            [0.0, 0.0, 0.0],
            [0.0, 0.0, 0.0],
            [0.0, 0.0, 0.0],
            [0.0, 0.0, 0.0],
            [0.0, 0.0, 0.0],
            [0.0, 0.0, 0.0],
        ] | nbody_system.speed

        instance.particles.add_particles(particles)

        instance.commit_particles()
        instance.evolve_model(0.1 | nbody_system.time)

        instance.update_particle_set()

        self.assertEquals(len(instance.particles), 5)
        self.assertEquals(instance.particles.index_in_code, [3, 4, 5, 6, 10])
        self.assertEquals(instance.particles.mass, [0.1, 0.1, 0.1, 0.1, 0.11] | nbody_system.mass)

        self.assertEquals(len(particles), 6)
        instance.particles.synchronize_to(particles)
        self.assertEquals(len(particles), 5)
        self.assertEquals(particles.mass, [0.1, 0.1, 0.1, 0.1, 0.11] | nbody_system.mass)

        binary_energy1, error = instance.legacy_interface.get_binary_energy()
        self.assertEquals(error, 0)
        self.assertTrue(binary_energy1 < 0)

        binary_energy2 = instance.get_binary_energy()

        instance.cleanup_code()
        instance.stop()

        self.assertEquals(binary_energy2.value_in(nbody_system.energy), binary_energy1)
Example #21
0
    def test15(self):
        instance = ph4()
        instance.initialize_code()

        particles = datamodel.Particles(2)
        particles.mass = [1.0, 1.0] | nbody_system.mass
        particles.radius = [0.0001, 0.0001] | nbody_system.length
        particles.position = [[0.0, 0.0, 0.0], [2.0, 0.0, 0.0]] | nbody_system.length
        particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | nbody_system.speed
        instance.particles.add_particles(particles)

        mass = instance.particles[0].mass

        instance.cleanup_code()
        instance.stop()

        self.assertEquals(mass, 1.0 | nbody_system.mass)
Example #22
0
    def test17(self):
        print "Testing parameter defaults"

        instance = ph4()
        instance.parameters.epsilon_squared = 0.5 | nbody_system.length * nbody_system.length

        particles = datamodel.Particles(2)
        particles.mass = [1.0, 1.0] | nbody_system.mass
        particles.radius = [0.0001, 0.0001] | nbody_system.length
        particles.position = [[0.0, 0.0, 0.0], [2.0, 0.0, 0.0]] | nbody_system.length
        particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | nbody_system.speed
        instance.particles.add_particles(particles)

        self.assertAlmostRelativeEquals(
            instance.parameters.epsilon_squared, 0.5 | nbody_system.length * nbody_system.length
        )
        self.assertAlmostRelativeEquals(instance.parameters.timestep_parameter, 0.14)
        self.assertAlmostRelativeEquals(instance.parameters.use_gpu, 0)
        self.assertAlmostRelativeEquals(instance.parameters.manage_encounters, 4)
Example #23
0
    def test28(self):

        particles = datamodel.Particles(
            mass=[1, 2] | nbody_system.mass,
            x=[-2, 2] | nbody_system.length,
            y=[0, 0] | nbody_system.length,
            z=[0, 0] | nbody_system.length,
            vx=[-1, 1] | nbody_system.speed,
            vy=[-1, 1] | nbody_system.speed,
            vz=[-1, 1] | nbody_system.speed,
        )

        instance = ph4()

        instance.particles.add_particles(particles)
        instance.evolve_model(0.1 | nbody_system.time)
        self.assertEquals(len(instance.particles), 2)
        instance.particles.remove_particle(particles[0])
        instance.evolve_model(0.2 | nbody_system.time)
        self.assertEquals(len(instance.particles), 1)
Example #24
0
    def test2(self):
        convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 149.5e6 | units.km)
        instance = ph4(convert_nbody)

        instance.initialize_code()
        instance.parameters.epsilon_squared = 0.0 | units.AU ** 2
        instance.parameters.timestep_parameter = 0.01
        instance.dt_dia = 5000

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

        for x in range(1, 365, 30):
            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, "ph4-earth-sun2.svg")
            figure.savefig(output_file)

        instance.cleanup_code()
        instance.stop()
Example #25
0
    def test20(self):
        instance = ph4()
        instance.initialize_code()
        instance.parameters.epsilon_squared = 0.00001 | nbody_system.length ** 2

        particles = datamodel.Particles(2)
        particles.mass = [1.0, 1.0] | nbody_system.mass
        particles.radius = [0.0001, 0.0001] | nbody_system.length
        particles.position = [[0.0, 0.0, 0.0], [2.0, 0.0, 0.0]] | nbody_system.length
        particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | nbody_system.speed
        instance.particles.add_particles(particles)

        zero = 0.0 | nbody_system.length
        fx, fy, fz = instance.get_gravity_at_point(zero, 1.0 | nbody_system.length, zero, zero)
        self.assertAlmostEqual(fx, 0.0 | nbody_system.acceleration, 6)
        self.assertAlmostEqual(fy, 0.0 | nbody_system.acceleration, 6)
        self.assertAlmostEqual(fz, 0.0 | nbody_system.acceleration, 6)
        potentials = [-4.57110767688, -2.66662518639, -2.13331892165] | nbody_system.length ** 2 / (
            nbody_system.time ** 2
        )
        for x, pot in zip((0.25, 0.5, 0.75), potentials):
            x0 = x | nbody_system.length
            x1 = (2.0 - x) | nbody_system.length
            potential0 = instance.get_potential_at_point(zero, x0, zero, zero)
            potential1 = instance.get_potential_at_point(zero, x1, zero, zero)
            fx0, fy0, fz0 = instance.get_gravity_at_point(zero, x0, zero, zero)
            fx1, fy1, fz1 = instance.get_gravity_at_point(zero, x1, zero, zero)

            self.assertAlmostRelativeEquals(fy0, 0.0 | nbody_system.acceleration, 6)
            self.assertAlmostRelativeEquals(fz0, 0.0 | nbody_system.acceleration, 6)
            self.assertAlmostRelativeEquals(fy1, 0.0 | nbody_system.acceleration, 6)
            self.assertAlmostRelativeEquals(fz1, 0.0 | nbody_system.acceleration, 6)

            self.assertAlmostRelativeEquals(fx0, -1.0 * fx1, 5)
            fx = (-1.0 / (x0 ** 2) + 1.0 / (x1 ** 2)) * (1.0 | nbody_system.length ** 3 / nbody_system.time ** 2)
            print fx, fx0
            self.assertAlmostRelativeEquals(fx, fx0, 2)
            self.assertAlmostRelativeEquals(potential0, potential1, 5)
            self.assertAlmostRelativeEquals(potential0, pot, 5)
        instance.stop()
Example #26
0
    def test6(self):
        instance = ph4()
        instance.initialize_code()
        instance.parameters.epsilon_squared = 0.0 | nbody_system.length**2

        
        particles = datamodel.Particles(2)
        particles.mass = [1.0, 1.0] | nbody_system.mass
        particles.radius =  [0.0001, 0.0001] | nbody_system.length
        particles.position = [[0.0,0.0,0.0], [2.0,0.0,0.0]] | nbody_system.length
        particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | nbody_system.speed
        instance.particles.add_particles(particles)
        
        instance.commit_particles()
        
        zero = 0.0 | nbody_system.length
        fx, fy, fz = instance.get_gravity_at_point(zero, 1.0| nbody_system.length, zero, zero)
        self.assertAlmostEqual(fx, 0.0 | nbody_system.acceleration, 3)
        self.assertAlmostEqual(fy, 0.0 | nbody_system.acceleration, 3)
        self.assertAlmostEqual(fz, 0.0 | nbody_system.acceleration, 3)
        for x in (0.25, 0.5, 0.75):
            x0 = x| nbody_system.length
            x1 = (2.0 - x) | nbody_system.length
            potential0 = instance.get_potential_at_point(zero, x0, zero, zero)
            potential1 = instance.get_potential_at_point(zero, x1, zero, zero)
            fx0, fy0, fz0 = instance.get_gravity_at_point(zero, x0, zero, zero)
            fx1, fy1, fz1 = instance.get_gravity_at_point(zero, x1, zero, zero)
            
            self.assertAlmostEqual(fy0, 0.0 | nbody_system.acceleration, 3)
            self.assertAlmostEqual(fz0, 0.0 | nbody_system.acceleration, 3)
            self.assertAlmostEqual(fy1, 0.0 | nbody_system.acceleration, 3)
            self.assertAlmostEqual(fz1, 0.0 | nbody_system.acceleration, 3)
            
            self.assertAlmostEqual(fx0, -1.0 * fx1, 5)
            fx = (-1.0 / (x0**2) + 1.0 / (x1**2)) * (1.0 | nbody_system.length ** 3 / nbody_system.time ** 2)
            self.assertAlmostEqual(fx, fx0, 2)
            self.assertAlmostEqual(potential0, potential1, 5)
      
        instance.stop()
Example #27
0
    def xtest13(self):
        particles = datamodel.Particles(2)
        particles.x = [0.0, 10.0] | nbody_system.length
        particles.y = 0 | nbody_system.length
        particles.z = 0 | nbody_system.length
        particles.radius = 0.005 | nbody_system.length
        particles.vx = 0 | nbody_system.speed
        particles.vy = 0 | nbody_system.speed
        particles.vz = 0 | nbody_system.speed
        particles.mass = 1.0 | nbody_system.mass

        instance = ph4()
        instance.initialize_code()
        instance.parameters.stopping_conditions_number_of_steps = 2
        self.assertEquals(instance.parameters.stopping_conditions_number_of_steps, 2)
        instance.parameters.epsilon_squared = (0.01 | nbody_system.length) ** 2
        instance.particles.add_particles(particles)
        instance.stopping_conditions.number_of_steps_detection.enable()
        instance.evolve_model(10 | nbody_system.time)
        self.assertTrue(instance.stopping_conditions.number_of_steps_detection.is_set())
        self.assertTrue(instance.model_time < 10 | nbody_system.time)

        instance.stop()
Example #28
0
    def test1(self):
        convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 149.5e6 | units.km)
        instance = ph4(convert_nbody)  # , redirection="none")#, debugger="xterm")
        instance.initialize_code()

        instance.parameters.epsilon_squared = 0.0 | units.AU ** 2
        instance.parameters.timestep_parameter = 0.01

        stars = self.new_system_of_sun_and_earth()
        earth = stars[1]

        instance.particles.add_particles(stars)
        instance.commit_particles()

        instance.evolve_model(365 | units.day)

        instance.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)

        instance.evolve_model(365.0 + (365.0 / 2) | units.day)

        instance.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, 3)

        instance.evolve_model(365.0 + (365.0 / 2) + (365.0 / 4) | units.day)

        instance.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)

        instance.cleanup_code()

        instance.stop()
Example #29
0
    def test24(self):

        particles = datamodel.Particles(
            mass=[1, 2] | nbody_system.mass,
            x=[-1, 1] | nbody_system.length,
            y=[-1, 1] | nbody_system.length,
            z=[-1, 1] | nbody_system.length,
            vx=[-1, 1] | nbody_system.speed,
            vy=[-1, 1] | nbody_system.speed,
            vz=[-1, 1] | nbody_system.speed,
        )

        instance = ph4()

        instance.particles.add_particles(particles)
        self.assertEquals(len(instance.particles), 2)
        self.assertAlmostRelativeEquals(instance.particles.mass, [1, 2] | nbody_system.mass)

        instance.cleanup_code()
        instance.initialize_code()

        instance.particles.add_particles(particles)
        self.assertEquals(len(instance.particles), 2)
        self.assertAlmostRelativeEquals(instance.particles.mass, [1, 2] | nbody_system.mass)
Example #30
0
    def test25(self):

        particles = datamodel.Particles(
            mass=[1, 2] | nbody_system.mass,
            x=[-1, 1] | nbody_system.length,
            y=[-1, 1] | nbody_system.length,
            z=[-1, 1] | nbody_system.length,
            vx=[-1, 1] | nbody_system.speed,
            vy=[-1, 1] | nbody_system.speed,
            vz=[-1, 1] | nbody_system.speed,
            id=[3, 4],
        )

        instance = ph4()

        instance.particles.add_particles(particles)
        self.assertEquals(instance.particles.index_in_code, [3, 4])
        instance.commit_particles()
        instance.particles.remove_particle(particles[1])
        instance.recommit_particles()
        self.assertEquals(instance.particles.index_in_code, [3])
        instance.particles.add_particle(particles[1])
        instance.recommit_particles()
        self.assertEquals(instance.particles.index_in_code, [3, 4])
Example #31
0
 def test25(self):
     
     particles = datamodel.Particles(
         mass=[1,2] | nbody_system.mass,
         x=[-1,1] | nbody_system.length,
         y=[-1,1] | nbody_system.length,
         z=[-1,1] | nbody_system.length,
         vx=[-1,1] | nbody_system.speed,
         vy=[-1,1] | nbody_system.speed,
         vz=[-1,1] | nbody_system.speed,
         id=[3,4]
     )
     
     instance=ph4()
     
     instance.particles.add_particles(particles)
     self.assertEqual(instance.particles.index_in_code, [3,4])
     instance.commit_particles()
     instance.particles.remove_particle(particles[1])
     instance.recommit_particles()
     self.assertEqual(instance.particles.index_in_code, [3])
     instance.particles.add_particle(particles[1])
     instance.recommit_particles()
     self.assertEqual(instance.particles.index_in_code, [3,4])
Example #32
0
 def test24(self):
     
     particles = datamodel.Particles(
         mass=[1,2] | nbody_system.mass,
         x=[-1,1] | nbody_system.length,
         y=[-1,1] | nbody_system.length,
         z=[-1,1] | nbody_system.length,
         vx=[-1,1] | nbody_system.speed,
         vy=[-1,1] | nbody_system.speed,
         vz=[-1,1] | nbody_system.speed
     )
     
     instance=ph4()
     
     instance.particles.add_particles(particles)
     self.assertEqual(len(instance.particles), 2)
     self.assertAlmostRelativeEquals(instance.particles.mass, [1,2] | nbody_system.mass)
     
     instance.cleanup_code()
     instance.initialize_code()
     
     instance.particles.add_particles(particles)
     self.assertEqual(len(instance.particles), 2)
     self.assertAlmostRelativeEquals(instance.particles.mass, [1,2] | nbody_system.mass)
Example #33
0
    def xtest7(self):
        instance = ph4()
        instance.initialize_code()
        instance.parameters.epsilon_squared = 0.0 | nbody_system.length**2
        instance.set_eta(0.01,0.02)

        
        particles = datamodel.Particles(2)
        particles.mass = [1.0, 1.0] | nbody_system.mass
        particles.radius =  [0.0001, 0.0001] | nbody_system.length
        particles.position = [[0.0,0.0,0.0], [2.0,0.0,0.0]] | nbody_system.length
        particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | nbody_system.speed
        instance.particles.add_particles(particles)
        
        instance.initialize_particles(0.0 )
        
        zero = [0.0, 0.0, 0.0] | nbody_system.length
        fx, fy, fz = instance.get_gravity_at_point(zero, [0.5, 1.0, 1.5] | nbody_system.length, zero, zero)
        self.assertAlmostRelativeEqual(fx[0], -3.55555555556 | nbody_system.acceleration, 5)
        self.assertAlmostRelativeEqual(fy[0], 0.0 | nbody_system.acceleration, 3)
        self.assertAlmostRelativeEqual(fz[0], 0.0 | nbody_system.acceleration, 3)
        self.assertAlmostRelativeEqual(fx[1], 0.0 | nbody_system.acceleration, 3)
        self.assertAlmostRelativeEqual(fy[1], 0.0 | nbody_system.acceleration, 3)
        self.assertAlmostRelativeEqual(fz[1], 0.0 | nbody_system.acceleration, 3)
        self.assertAlmostRelativeEqual(fx[2], 3.55555555556 | nbody_system.acceleration, 5)
        self.assertAlmostRelativeEqual(fy[2], 0.0 | nbody_system.acceleration, 3)
        self.assertAlmostRelativeEqual(fz[2], 0.0 | nbody_system.acceleration, 3)
        
        n = 512
        x = nbody_system.length.new_quantity(numpy.linspace(0.1, 1.9, n))
        zero = nbody_system.length.new_quantity(numpy.zeros(n))
        fx, fy, fz = instance.get_gravity_at_point(zero, x, zero, zero)
        for i in range(n/2):
            self.assertAlmostRelativeEqual(fx[i], - fx[n - 1 - i], 5)
        
        instance.stop()
Example #34
0
 def test23(self):
     
     particles = datamodel.Particles(
         mass=[1,2] | nbody_system.mass,
         x=[-1,1] | nbody_system.length,
         y=[-1,1] | nbody_system.length,
         z=[-1,1] | nbody_system.length,
         vx=[-1,1] | nbody_system.speed,
         vy=[-1,1] | nbody_system.speed,
         vz=[-1,1] | nbody_system.speed
     )
     
     
     instance=ph4()
     
     overlay = datamodel.ParticlesOverlay(instance.particles)
     
     overlay.add_particles(particles)
     all_attributes = overlay.get_values_in_store(overlay.get_all_indices_in_store(), ['mass', 'x', 'y', 'z', 'vx', 'vy', 'vz'])
     
     self.assertEqual(all_attributes[0], [1,2] | nbody_system.mass )
     self.assertEqual(instance.particles.mass, [1,2] | nbody_system.mass )
     self.assertEqual(overlay.mass, [1,2] | nbody_system.mass )
     self.assertEqual(overlay.position, [[-1., -1., -1.], [ 1.,  1.,  1.]]  | nbody_system.length )
Example #35
0
 def test0(self):
     instance = ph4()
     instance.stop()
Example #36
0
 def new_star_code_ph4(self):
     result = ph4(mode="gpu")
     result.parameters.epsilon_squared = self.star_epsilon**2
     result.particles.add_particles(self.new_particles_cluster())
     result.commit_particles()
     return result
Example #37
0
def new_ph4():
    code = ph4()
    code.initialize_code()
    code.parameters.set_defaults()
    return code
def evolve_cluster(cluster,mCut,dt,tend,mCluster,rCluster):

    print 'Start evolving the cluster with mCut =', mCut
    # timing
    t1 = time()

    converter=nbody_system.nbody_to_si(mCluster,rCluster)

    # split particle according to mass_cut
    low_mass_stars = cluster.select(lambda m: m < mCut,["mass"])
    high_mass_stars = cluster.select(lambda m: m >= mCut,["mass"])
    print 'Number of low-mass stars:', low_mass_stars.__len__()
    print 'Number of high-mass stars:', high_mass_stars.__len__()

    
    # make models and assigning particles    
    code_tree = BHTree(converter)
    code_direct = ph4(converter)
    code_tree.particles.add_particles(low_mass_stars)
    code_direct.particles.add_particles(high_mass_stars)
    channel_from_code_tree = code_tree.particles.new_channel_to(low_mass_stars)
    channel_from_code_direct = code_direct.particles.new_channel_to(high_mass_stars)    
    
    # make bridge
    combined_gravity = bridge()
    combined_gravity.add_system(code_tree,(code_direct,))
    combined_gravity.add_system(code_direct,(code_tree,))
    combined_gravity.timestep = dt

    # the initial total energy
    E0 = combined_gravity.potential_energy + combined_gravity.kinetic_energy
                     
    # evolve the model
    times = quantities.arange(0.|units.Myr, tend+dt, dt)
    n_step = len(times)
    dE = np.empty(n_step)
    Qs = np.empty(n_step)

    for i,t in enumerate(times):
        if t.value_in(units.Myr)%1 == 0:
            print "Time =", t.in_(units.Myr)
        channel_from_code_tree.copy()
        channel_from_code_direct.copy()

        combined_gravity.evolve_model(t, timestep=dt)

        U = cluster.potential_energy()
        T = cluster.kinetic_energy()
        Et = U + T
        dE[i] = np.abs((E0-Et)/E0)
        Qs[i] = -T / U

    code_tree.stop()
    code_direct.stop()

    t2 = time()
    print 'Finished. Time cost: %.2f s'%(t2-t1)
    output_filename = 'ee_q_%.1f.txt'%mCut.value_in(units.MSun)
    with open(output_filename, 'w'):
        np.savetxt(output_filename, np.append(dE,Qs).reshape(2,n_step).transpose())
    print 'Saved the data of energy error and virial ratios in', output_filename

    # plot energy
    plot_energy_error(times.value_in(units.Myr), dE, Qs, mCut)
    return dE[-1], Qs[-1], t2-t1
def evolve_cluster(cluster, mCut, dt, tend, mCluster, rCluster):

    converter = nbody_system.nbody_to_si(mCluster, rCluster)
    # Splitting particle according to mass_cut
    low_mass_stars = cluster.select(lambda m: m < mCut, ["mass"])
    high_mass_stars = cluster.select(lambda m: m >= mCut, ["mass"])

    # Sanity checks
    print('dynamical timescale:',
          cluster.dynamical_timescale().value_in(units.Myr))
    print('Number of low-mass stars:', low_mass_stars.__len__())
    print('Number of high-mass stars:', high_mass_stars.__len__())
    #plot_cluster(low_mass_stars, high_mass_stars)

    # Making models and assigning particles
    code_tree = BHTree(converter)
    code_direct = ph4(converter)
    code_tree.particles.add_particles(low_mass_stars)
    code_direct.particles.add_particles(high_mass_stars)
    channel_from_code_tree = code_tree.particles.new_channel_to(low_mass_stars)
    channel_from_code_direct = code_direct.particles.new_channel_to(
        high_mass_stars)

    # Making bridge
    combined_gravity = bridge()
    combined_gravity.add_system(code_tree, (code_direct, ))
    combined_gravity.add_system(code_direct, (code_tree, ))
    combined_gravity.timestep = dt

    # Evolving the model
    time_series = []
    half_mass_radii = []
    core_radii = []
    times = quantities.arange(0. | units.Myr, tend, dt)
    for i, t in enumerate(times):
        print "Time =", t.in_(units.Myr)
        channel_from_code_tree.copy()
        channel_from_code_direct.copy()
        time_series.append(t.value_in(units.Myr))
        pos, coreradius, coredens = cluster.densitycentre_coreradius_coredens(
            converter)
        lr, mf = cluster.LagrangianRadii(
            converter)  # outputs are radii, mass fractions
        half_mass_radii.append(lr[5].value_in(
            units.parsec))  # 5th argument attributes to half-mass radius
        core_radii.append(coreradius.value_in(units.parsec))
        combined_gravity.evolve_model(t, timestep=dt)

    code_tree.stop()
    code_direct.stop()

    # Plotting results
    #plot_cluster(low_mass_stars, high_mass_stars)

    # Plotting radii
    plot_radii(time_series,
               half_mass_radii,
               x_label='time(Myr)',
               y_label='half-mass radius (pc)')
    plot_radii(time_series,
               core_radii,
               x_label='time(Myr)',
               y_label='core radius (pc)')
Example #40
0
    def test4(self):

        instance = ph4()
        self._run_addition_removal_test(instance)
Example #41
0
    if not read_from_file:
        write.write_initial_state(MasterSet, initial_conditions, cluster_name)

# Define PH4-Related Initial Conditions
    time = 0.0 | units.Myr
    delta_t = 0.002 | units.Myr
    number_of_steps = options.num_steps
    end_time = number_of_steps*delta_t
    num_workers = 1
    eps2 = 1 | units.AU**2
    use_gpu = options.use_gpu
    gpu_ID = options.gpu_ID

# Setting PH4 as the Top-Level Gravity Code
    if use_gpu == 1:
        gravity = ph4(number_of_workers = num_workers, redirection = "none", mode = "gpu", 
                      convert_nbody=LargeScaleConverter)
    else:
        gravity = ph4(number_of_workers = num_workers, redirection = "none",
                      convert_nbody=LargeScaleConverter)

# Initializing PH4 with Initial Conditions
    gravity.initialize_code()
    gravity.parameters.set_defaults()
    gravity.parameters.begin_time = time
    gravity.parameters.epsilon_squared = eps2
    gravity.parameters.timestSep_parameter = options.dt

# Setting up the Code to Run with GPUs Provided by Command Line
    gravity.parameters.use_gpu = use_gpu
    gravity.parameters.gpu_id = gpu_ID
Example #42
0
def get_ph4(converter):
    instance = ph4(converter)
    instance.initialize_code()
    instance.parameters.set_defaults()
    return instance
Example #43
0
    t_end = t_end | nbody_system.time
    dt = t_end / float(nsteps)

    bodies = new_plummer_model(N)
    masses = new_powerlaw_mass_distribution(N,
                                            mass_min=0.1 | units.MSun,
                                            mass_max=10 | units.MSun,
                                            alpha=-2.35)
    masses /= masses.sum()
    bodies.mass = masses | nbody_system.mass

    bodies.radius = 0.001 | nbody_system.length
    Mtot_init = 1 | nbody_system.mass

    gravity = ph4(number_of_workers=4)
    gravity.particles.add_particles(bodies)
    bodies.scale_to_standard(virial_ratio=Qvir)

    channel_from_gd_to_framework = gravity.particles.new_channel_to(bodies)

    stopping_condition = gravity.stopping_conditions.collision_detection
    stopping_condition.enable()

    Etot_init = gravity.kinetic_energy + gravity.potential_energy
    Etot_prev = Etot_init

    time = 0.0 | t_end.unit
    Nenc = 0
    dEk_enc = zero
    dEp_enc = zero
Example #44
0
print MasterSet

time = 0.0 | nbody_system.time
delta_t = 0.05 | nbody_system.time
number_of_steps = 10
end_time = number_of_steps * delta_t
num_workers = 1
eps2 = 0.0 | nbody_system.length**2
use_gpu = 1
gpu_ID = -1

# Setting PH4 as the Top-Level Gravity Code
if use_gpu == 1:
    gravity = ph4(number_of_workers=num_workers,
                  redirection="none",
                  mode="gpu")
#try:
#gravity = ph4(number_of_workers = num_workers, redirection = "none", mode = "gp$
#except Exception as ex:
#    gravity = ph4(number_of_workers = num_workers, redirection = "none")
#    print "*** GPU worker code not found. Reverting to non-GPU code. ***"
else:
    gravity = grav(number_of_workers=num_workers, redirection="none")

# Initializing PH4 with Initial Conditions
gravity.initialize_code()
gravity.parameters.set_defaults()
gravity.parameters.begin_time = time
gravity.parameters.epsilon_squared = eps2
gravity.parameters.timestep_parameter = delta_t.number
Example #45
0
def integrate_system(N, t_end, seed=None):

    total_mass = N | units.MSun
    length = 1 | units.parsec
    converter = nbody_system.nbody_to_si(total_mass, length)
    gravity = ph4(convert_nbody=converter)
    gravity.initialize_code()
    gravity.parameters.set_defaults()
    gravity.parameters.epsilon_squared = (0.0 | units.parsec)**2

    if seed is not None: numpy.random.seed(seed)
    stars = new_plummer_model(N, convert_nbody=converter)
    stars.mass = total_mass / N
    stars.scale_to_standard(
        convert_nbody=converter,
        smoothing_length_squared=gravity.parameters.epsilon_squared)

    id = numpy.arange(N)
    stars.id = id + 1
    stars.radius = 0.5 / N | units.parsec

    gravity.particles.add_particles(stars)

    stopping_condition = gravity.stopping_conditions.collision_detection
    stopping_condition.enable()

    init_smalln(converter)
    kep = Kepler(unit_converter=converter)
    kep.initialize_code()
    multiples_code = multiples.Multiples(gravity, new_smalln, kep, constants.G)
    multiples_code.neighbor_perturbation_limit = 0.05
    multiples_code.global_debug = 1
    ###BOOKLISTSTOP2###

    #	global_debug = 0: no output from multiples
    #	               1: minimal output
    #	               2: debugging output
    #	               3: even more output

    print ''
    print 'multiples_code.neighbor_veto =', \
        multiples_code.neighbor_veto
    print 'multiples_code.neighbor_perturbation_limit =', \
        multiples_code.neighbor_perturbation_limit
    print 'multiples_code.retain_binary_apocenter =', \
        multiples_code.retain_binary_apocenter
    print 'multiples_code.wide_perturbation_limit =', \
        multiples_code.wide_perturbation_limit

    time = numpy.sqrt(length**3 / (constants.G * total_mass))
    print '\ntime unit =', time.in_(units.Myr)
    ###BOOKLISTSTART3###

    E0 = print_diagnostics(multiples_code)
    multiples_code.evolve_model(t_end)
    print_diagnostics(multiples_code, E0)
    ###BOOKLISTSTOP3###

    gravity.stop()
    kep.stop()
    stop_smalln()
Example #46
0
        particles[i].velocity = [
            math.sin(angle) * vel + VelocityMilky[0],
            -math.cos(angle) * vel + VelocityMilky[1], VelocityMilky[2]
        ]
        i += 1
    return particles


Tracker = Nstars()
print(Tracker)

# In[5]:

#This ph4 will be replaced by the Fi later
converter = nbody_system.nbody_to_si(1.0e12 | units.MSun, 100 | units.kpc)
gravity = ph4(converter)
gravity.particles.add_particles(Galaxies)
channel1 = gravity.particles.new_channel_to(Galaxies)
channel2 = Tracker.new_channel_to(Tracker)
DeltaT = 0.1  #This is the timestep we will use in Myr
#If we want to have a non constant DeltaT we would need to change some of the code since leap-frog is not stable
#enough for varying timesteps. Can be done by finishing the leap-frog and starting a new one

gravity.timestep = DeltaT | units.Myr
times = numpy.arange(0., 50, DeltaT) | units.Myr

unity = 1 | units.m**-1 * units.s**2  #We do this to remove the units inside the vector
unity2 = 1 | units.m * units.s**-2  #Here we add the units on the outside
Accelout = [0, 0, 0]
#Now that we have initialised our particle set we have the main gravitational solver with a certain timestep DeltaT
#This is what will later be the main solving part of Fi.
Example #47
0
def integrate_system(N, t_end, seed=None):

    # Initialize an N-body module and load a stellar system.

    mass = N | units.MSun
    length = 1 | units.parsec
    converter = nbody_system.nbody_to_si(mass, length)
    gravity = ph4(convert_nbody=converter)
    gravity.initialize_code()
    gravity.parameters.set_defaults()
    gravity.parameters.epsilon_squared = (0.0 | units.parsec)**2

    if seed is not None: numpy.random.seed(seed)
    stars = new_plummer_model(N, convert_nbody=converter)
    stars.mass = mass / N
    stars.scale_to_standard(
        convert_nbody=converter,
        smoothing_length_squared=gravity.parameters.epsilon_squared)

    # Star IDs are important, as they are used in multiples bookkeeping.
    id = numpy.arange(N)
    stars.id = id + 1

    # Set dynamical radii.

    #stars.radius = 0.5/N | units.parsec
    stars.radius = 2000 | units.AU

    gravity.particles.add_particles(stars)

    # Add Planets
    do_planets = True
    if do_planets:
        systems_SI = create.planetary_systems(stars,
                                              N - 1,
                                              'test_planets',
                                              Jupiter=True)
        gravity.particles.add_particles(systems_SI)

    # Enable collision detection.

    stopping_condition = gravity.stopping_conditions.collision_detection
    stopping_condition.enable()

    SmallScaleConverter = nbody_system.nbody_to_si(2 * mass / N,
                                                   4000 | units.AU)
    # Define the small-N code.

    init_smalln(SmallScaleConverter)

    # Define a Kepler module.

    kep = Kepler(unit_converter=SmallScaleConverter)
    kep.initialize_code()

    # Create the multiples module.
    global multiples_code
    multiples_code = multiples2.Multiples(gravity, new_smalln, kep,
                                          constants.G)
    multiples_code.neighbor_perturbation_limit = 0.05
    multiples_code.neighbor_veto = True

    multiples_code.global_debug = 1  # 0: no output from multiples
    # 1: minimal output
    # 2: debugging output
    # 3: even more output

    # Setting Up the Encounter Handler
    encounters = EncounterHandler()
    multiples_code.callback = encounters.handle_encounter_v3

    # Print selected multiples settings.

    print ''
    print 'multiples_code.neighbor_veto =', \
        multiples_code.neighbor_veto
    print 'multiples_code.neighbor_perturbation_limit =', \
        multiples_code.neighbor_perturbation_limit
    print 'multiples_code.retain_binary_apocenter =', \
        multiples_code.retain_binary_apocenter
    print 'multiples_code.wide_perturbation_limit =', \
        multiples_code.wide_perturbation_limit

    # Advance the system.
    time = numpy.sqrt(length**3 / (constants.G * mass))
    print '\ntime unit =', time.in_(units.Myr)

    E0 = print_diagnostics(multiples_code)
    dt = 0.1 | units.Myr
    t_current = 0.0 | units.Myr
    #gravity.particles[-1].mass += 1 | units.MSun
    while t_current <= t_end:
        t_current += dt
        multiples_code.evolve_model(t_current)
        print gravity.particles.index_in_code  #, gravity.particles[0].x
        #print multiples_code.particles[-1].key, multiples_code.particles[-1].x
        print multiples_code._inmemory_particles.id,  #multiples_code._inmemory_particles[-1].x
        #print stars[0].id
        # Testing the Multiples & Gravity Particle Set Differences
        #test_psystem_id = systems_SI[0].host_star
        #test_psystem_hs_grav = [star.x for star in gravity.particles if star.index_in_code == test_psystem_id]
        #test_psystem_hs_mult = [star.x for star in multiples_code.particles if star.idex_in_code == test_psystem_id]
        #print "-----------------------------"
        #print "X Position in PH4", test_pystem_hs_grav.in_(units.parsec)
        #print "X Position in Multiples", test_psystem_hs_mult.in_(units.parsec)
        #print "Difference in Particle Sets", test_pystem_hs_grav.in_(units.parsec) - test_psystem_hs_mult.in_(units.parsec)
        #print "-----------------------------"
    print_diagnostics(multiples_code, E0)

    gravity.stop()
    kep.stop()
    stop_smalln()