def main():
    filename = "SunAndEarthAndMoon.hdf"
    ss = new_system_of_sun_and_earth()
    star = ss[0]
    planet = ss[1]
    moon = ss[2]
    converter = nbody_system.nbody_to_si(star.mass, planet.position.length())
    star_gravity = ph4(converter)
    star_gravity.particles.add_particle(star)

    planet_gravity = ph4(converter)
    planet_gravity.particles.add_particle(planet)

    moon_gravity = ph4(converter)
    moon_gravity.particles.add_particle(moon)

    channel_from_star_to_framework = star_gravity.particles.new_channel_to(ss)
    channel_from_planet_to_framework = planet_gravity.particles.new_channel_to(
        ss)
    channel_from_moon_to_framework = moon_gravity.particles.new_channel_to(ss)

    write_set_to_file(ss, filename, 'hdf5')

    sp_gravity = bridge.Bridge()
    sp_gravity.add_system(moon_gravity, (planet_gravity, ))
    sp_gravity.add_system(planet_gravity, (moon_gravity, ))

    gravity = bridge.Bridge()
    gravity.add_system(sp_gravity, (star_gravity, ))
    gravity.add_system(star_gravity, (sp_gravity, ))

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

    sp_gravity.timestep = 1 | units.day
    gravity.timestep = 10 | units.day
    time = zero
    dt = 3 | units.day
    t_end = 1 | units.yr
    while time < t_end:
        time += dt
        gravity.evolve_model(time)

        Etot_prev_se = gravity.kinetic_energy + gravity.potential_energy

        channel_from_star_to_framework.copy()
        channel_from_planet_to_framework.copy()
        channel_from_moon_to_framework.copy()
        write_set_to_file(ss, filename, 'hdf5')

        Ekin = gravity.kinetic_energy
        Epot = gravity.potential_energy
        Etot = Ekin + Epot
        print "T=", time,
        print "E= ", Etot, "Q= ", Ekin / Epot,
        print "dE=", (Etot_init - Etot) / Etot, "ddE=", (Etot_prev -
                                                         Etot) / Etot
        Etot_prev = Etot
    gravity.stop()
Beispiel #2
0
    def test3(self):
        print "Bridge potential energy with radius as softening length"
        convert = nbody_system.nbody_to_si(1.e5 | units.MSun,
                                           1.0 | units.parsec)
        epsilon = 0.1 | units.parsec
        test_class = ExampleGravityCodeInterface

        numpy.random.seed(12345)
        stars = new_plummer_model(100, convert_nbody=convert)
        stars.radius = epsilon

        cluster = test_class()
        cluster.parameters.epsilon_squared = epsilon**2
        cluster.particles.add_particles(stars)

        first_half = stars.select_array(lambda x: (x > 0 | units.m), ['x'])
        second_half = stars - first_half
        cluster1 = system_from_particles(test_class, dict(), first_half,
                                         epsilon)
        cluster2 = system_from_particles(test_class, dict(), second_half,
                                         epsilon)
        bridgesys = bridge.Bridge()
        bridgesys.add_system(cluster1, (cluster2, ), radius_is_eps=True)
        bridgesys.add_system(cluster2, (cluster1, ))

        self.assertAlmostRelativeEqual(cluster.potential_energy,
                                       bridgesys.potential_energy)
        self.assertAlmostRelativeEqual(cluster.kinetic_energy,
                                       bridgesys.kinetic_energy)
Beispiel #3
0
def gravity_code_setup(code_name, orbiter_name, Mgalaxy, Rgalaxy, galaxy_code,
                       sepBinary, rvals, phivals, zvals, vrvals, vphivals,
                       vzvals, masses, radii, Norbiters):
    '''
    will need to ask SPZ if he meant for field, orbiter to be separate in non
    Nemesis gravity solvers?
    '''

    gravity = bridge.Bridge(use_threading=False)

    converter_parent = nbody_system.nbody_to_si(Mgalaxy, Rgalaxy)
    converter_sub = nbody_system.nbody_to_si(
        np.median(masses) | units.MSun,
        np.median(radii) | units.parsec)  #masses list is in solar mass units

    channel = stars.new_channel_to(orbiter_code.particles)
    channel.copy_attributes(['mass', 'x', 'y', 'z', 'vx', 'vy', 'vz'])

    stellar = SeBa()
    stellar.particles.add_particles(cluster_code.particles)

    #bridges each cluster with the bulge, not the other way around though
    gravity.add_system(cluster_code, other_things)

    return gravity.particles, gravity, orbiter_bodies_list, cluster_colors, stellar
Beispiel #4
0
def integrate_amuse(orb,pot,tmax,vo,ro):
    """Integrate a snapshot in infile until tmax in Gyr, save to outfile"""

    time=0.0 | tmax.unit
    dt = tmax/10001.

    orbit = Particles(1)

    orbit.mass= 1. | units.MSun
    orbit.radius = 1. |units.RSun

    orbit.position=[orb.x(),orb.y(),orb.z()] | units.kpc
    orbit.velocity=[orb.vx(),orb.vy(),orb.vz()] | units.kms
    galaxy_code = to_amuse(pot,ro=ro,vo=vo)
    
    orbit_gravity=drift_without_gravity(orbit)
    orbit_gravity.particles.add_particles(orbit)
    channel_from_gravity_to_orbit= orbit_gravity.particles.new_channel_to(orbit)

    gravity = bridge.Bridge(use_threading=False)
    gravity.add_system(orbit_gravity, (galaxy_code,))
    gravity.add_system(galaxy_code,)
    gravity.timestep = dt

    while time <= tmax:
        time += dt
        gravity.evolve_model(time)

    channel_from_gravity_to_orbit.copy()
    gravity.stop()

    return orbit.x[0].value_in(units.kpc),orbit.y[0].value_in(units.kpc),orbit.z[0].value_in(units.kpc),orbit.vx[0].value_in(units.kms),orbit.vy[0].value_in(units.kms),orbit.vz[0].value_in(units.kms)
def main():
    filename = "SunAndEarthAndMoon_TBB.h5"
    ss = new_system_of_sun_and_earth()
    star = ss[0]
    planet = ss[1]
    moon = ss[2]

    print moon
    converter=nbody_system.nbody_to_si(star.mass, 1|units.AU)
    star_gravity = ph4(converter)
    star_gravity.particles.add_particle(star)

    planet_gravity = ph4(converter)
    planet_gravity.particles.add_particle(planet)

    moon_gravity = ph4(converter)
    moon_gravity.particles.add_particle(moon)

    channel_from_star_to_framework = star_gravity.particles.new_channel_to(ss)
    channel_from_planet_to_framework = planet_gravity.particles.new_channel_to(ss)
    channel_from_moon_to_framework = moon_gravity.particles.new_channel_to(ss)

    write_set_to_file(ss.savepoint(0.0|units.Myr), filename, 'hdf5', append_to_file=False, version='2')
    
    gravity = bridge.Bridge(use_threading=False, method=SPLIT_4TH_S_M4)
####gravity = bridge.Bridge(use_threading=False, method=SPLIT_6TH_SS_M13)
    gravity.add_system(star_gravity, (planet_gravity,moon_gravity) )
    gravity.add_system(planet_gravity, (star_gravity,moon_gravity) )
    gravity.add_system(moon_gravity, (star_gravity,planet_gravity) )

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

    gravity.timestep = 1|units.day
    time = zero
    dt = 30|units.day
    t_end = 100 | units.yr
    while time < t_end:
        time += dt
        gravity.evolve_model(time)

        Etot_prev_se = gravity.kinetic_energy + gravity.potential_energy

        channel_from_star_to_framework.copy()
        channel_from_planet_to_framework.copy()
        channel_from_moon_to_framework.copy()
        write_set_to_file(ss.savepoint(time), filename, 'hdf5', version='2')

        Ekin = gravity.kinetic_energy 
        Epot = gravity.potential_energy
        Etot = Ekin + Epot
        DDE = (Etot_prev-Etot)/Etot
        DDE_max = max(abs(DDE_max), abs(DDE))
        print "T=", time, 
        print "E= ", Etot, "Q= ", Ekin/Epot,
        print "dE=", (Etot_init-Etot)/Etot, "ddE=", DDE, "dde_min=", DDE_max
        Etot_prev = Etot
    gravity.stop()
Beispiel #6
0
def main(Ncl, rcl, W0, Rgal, vgal, t_end, n_steps):

    masses = new_salpeter_mass_distribution(Ncl, 1 | units.MSun,
                                            100 | units.MSun)
    converter = nbody_system.nbody_to_si(masses.sum(), rcl)
    bodies = new_king_model(Ncl, W0, convert_nbody=converter)
    bodies.mass = masses
    bodies.scale_to_standard(convert_nbody=converter)

    stellar = SeBa()
    stellar.particles.add_particles(bodies)
    channel_from_stellar_to_framework = stellar.particles.new_channel_to(
        bodies)
    channel_from_stellar_to_framework.copy()

    bodies.x += Rgal
    bodies.vy += vgal

    CDG = BHTree(converter)
    CDG.particles.add_particles(bodies)
    channel_from_gravity_to_framework = CDG.particles.new_channel_to(bodies)

    gravity = bridge.Bridge()
    gravity.add_system(CDG, (MilkyWay_galaxy(), ))
    dt = t_end / float(n_steps)
    gravity.timestep = dt

    filename = "nbody.hdf5"
    write_set_to_file(bodies.savepoint(0.0 | t_end.unit),
                      filename,
                      "hdf5",
                      append_to_file=False)

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

    time = zero
    dt = t_end / float(n_steps)
    while time < t_end:
        time += dt

        stellar.evolve_model(time)
        channel_from_stellar_to_framework.copy()

        gravity.evolve_model(time)
        channel_from_gravity_to_framework.copy()
        write_set_to_file(bodies.savepoint(time), filename, "hdf5")

        Ekin = gravity.kinetic_energy
        Epot = gravity.potential_energy
        Etot = Ekin + Epot
        print "T=", time, "M=", bodies.mass.sum(),
        print "E= ", Etot, "Q= ", Ekin / Epot,
        print "dE=", (Etot_init - Etot) / Etot, "ddE=", (Etot_prev -
                                                         Etot) / Etot
        Etot_prev = Etot

    gravity.stop()
    def create_bridge(self):
        bridge_code1 = bridge.GravityCodeInField(self.gas_code,
                                                 self.star_to_gas_codes)
        bridge_code2 = bridge.GravityCodeInField(self.star_code,
                                                 self.gas_to_star_codes)

        self.bridge_system = bridge.Bridge(timestep=self.interaction_timestep,
                                           use_threading=False)
        self.bridge_system.add_code(bridge_code2)
        self.bridge_system.add_code(bridge_code1)
Beispiel #8
0
def evolve_cluster_in_galaxy(N, Mcluster, Rcluster, Rinit, Vinit, galaxy_code,
                             dt, dtout, tend, epsilon):

    #Setup cluster
    stars, converter = setup_cluster(N, Mcluster, Rcluster, Rinit, Vinit)
    stars.scale_to_standard(convert_nbody=converter,
                            smoothing_length_squared=epsilon**2)

    cluster_code = BHTree(
        converter, number_of_workers=1
    )  #Change number of workers depending on CPUS available
    cluster_code.parameters.epsilon_squared = epsilon**2
    cluster_code.parameters.opening_angle = 0.6
    cluster_code.parameters.timestep = dt
    cluster_code.particles.add_particles(stars)

    #Setup channels between stars particle dataset and the cluster code
    channel_from_stars_to_cluster_code = stars.new_channel_to(
        cluster_code.particles,
        attributes=["mass", "x", "y", "z", "vx", "vy", "vz"])
    channel_from_cluster_code_to_stars = cluster_code.particles.new_channel_to(
        stars, attributes=["mass", "x", "y", "z", "vx", "vy", "vz"])

    #Setup gravity bridge
    gravity = bridge.Bridge(use_threading=False)
    #stars in cluster_code depend on gravity from galaxy_code
    gravity.add_system(cluster_code, (galaxy_code, ))
    #galaxy_code still needs to be added to system so it evolves with time
    gravity.add_system(galaxy_code, )
    #Set how often to update external potential
    gravity.timestep = cluster_code.parameters.timestep / 2.

    time = 0.0 | tend.unit
    while time < tend:
        print(time.value_in(units.Myr), tend.value_in(units.Myr))
        gravity.evolve_model(time + dt)

        #You need to copy stars from cluster_code to output or analyse:

        #channel_from_cluster_code_to_stars.copy()
        #Output/Analyse

        #If you edited the stars particle set, lets say to remove stars from the array because they have
        #been kicked far from the cluster, you need to copy the array back to cluster_code:

        #channel_from_stars_to_cluster_code.copy()

        time = gravity.model_time

    #Copy back to stars for final dataset
    channel_from_cluster_code_to_stars.copy()
    gravity.stop()

    return stars
Beispiel #9
0
def gravity_hydro_bridge(gravity, hydro, t_end, dt):

    model_time = 0 | units.yr
    filename = "gravhydro.hdf5"
    #write_set_to_file(stars.savepoint(model_time), filename, 'amuse')
    #write_set_to_file(gas, filename, 'amuse')

    gravhydro = bridge.Bridge(use_threading=False)
    gravhydro.add_system(gravity, (hydro, ))
    gravhydro.add_system(hydro, (gravity, ))
    gravhydro.timestep = 2 * hydro.get_timestep()

    a_Jup = list()
    e_Jup = list()
    disk_size = list()

    # start evolotuion
    print 'Start evolving...'
    times = quantities.arange(0. | units.yr, t_end + dt, dt)
    while model_time < t_end:
        stars = gravity.local_particles
        orbit = orbital_elements_from_binary(stars, G=constants.G)
        a = orbit[2].value_in(units.AU)
        e = orbit[3]
        if model_time.value_in(units.yr) % 50 == 0:
            print "Time:", model_time.in_(units.yr), \
                  "ae=", a ,e
        a_Jup.append(a)
        e_Jup.append(e)

        model_time += gravhydro.timestep
        gravhydro.evolve_model(model_time)
        gravity.copy_to_framework()
        hydro.copy_to_framework()

        sink = hydro.local_particles[0]
        _ = hydro_sink_particles([sink], hydro.local_particles[1:])
        Jupiter = gravity.local_particles[1]
        Jupiter.mass += sink.mass
        sink.position = Jupiter.position
        sink.radius = a * (1 - e) * (
            (1.0 | units.MJupiter).value_in(units.MSun) / 3.)**(1. /
                                                                3.) | units.au
        gravity.copy_to_framework()
        hydro.copy_to_framework()
        write_set_to_file(stars.savepoint(model_time), filename, 'amuse')
        write_set_to_file(ism, filename, 'amuse')
        print "P=", model_time.in_(units.yr), gravity.particles.x.in_(units.au)

    gravity.stop()
    hydro.stop()

    return a_Jup, e_Jup, times
def evolve_model(end_time, double_star, stars):
    time = 0 | units.yr
    dt = end_time/100.

    converter = nbody_system.nbody_to_si(double_star.mass,
                                         double_star.semimajor_axis)

    gravity = Hermite(converter)
    gravity.particles.add_particle(stars)
    to_stars = gravity.particles.new_channel_to(stars)
    # from_stars = stars.new_channel_to(gravity.particles)

    massloss_code = CodeWithMassLoss(gravity, ())
    gravml = bridge.Bridge(use_threading=False)
    gravml.timestep = 0.5*dt
    gravml.add_system(gravity,)
    gravml.add_code(massloss_code)

    a = [] | units.au
    e = []
    m = [] | units.MSun
    t = [] | units.yr
    while time < end_time:
        time += dt
        gravml.evolve_model(time)
        to_stars.copy()
        orbital_elements = orbital_elements_from_binary(stars,
                                                        G=constants.G)
        a.append(orbital_elements[2])
        e.append(orbital_elements[3])
        m.append(stars.mass.sum())
        t.append(time)
        print("time=", time.in_(units.yr),
              "a=", a[-1].in_(units.RSun),
              "e=", e[-1],
              "m=", stars.mass.in_(units.MSun))
    gravity.stop()
    from matplotlib import pyplot
    fig, axis = pyplot.subplots(nrows=2, ncols=2, sharex=True)
    axis[0][0].scatter(t.value_in(units.yr), a.value_in(units.RSun))
    axis[0][0].set_ylabel("a [$R_\odot$]")

    axis[0][1].scatter(t.value_in(units.yr), m.value_in(units.MSun))
    axis[0][1].set_ylabel("M [$M_\odot$]")

    axis[1][1].scatter(t.value_in(units.yr), e)
    axis[1][1].set_ylabel("e")

    axis[1][1].set_xlabel("time [yr]")
    axis[1][0].set_xlabel("time [yr]")
    pyplot.savefig("mloss_bridge.png")
    pyplot.show()
Beispiel #11
0
def main():
    filename = "SunAndEarth.hdf"
    ss = new_solar_system()
    star = ss[0]
    planet = ss[3]
    converter = nbody_system.nbody_to_si(star.mass, planet.position.length())
    ###BOOKLISTSTART###
    star_gravity = ph4(converter)
    star_gravity.particles.add_particle(star)

    planet_gravity = ph4(converter)
    planet_gravity.particles.add_particle(planet)

    channel_from_star_to_framework = star_gravity.particles.new_channel_to(ss)
    channel_from_planet_to_framework = planet_gravity.particles.new_channel_to(
        ss)

    gravity = bridge.Bridge(use_threading=False)
    gravity.add_system(star_gravity, (planet_gravity, ))
    gravity.add_system(planet_gravity, (star_gravity, ))
    ###BOOKLISTSTOP###

    write_set_to_file(ss, filename, 'hdf5', append_to_file=Fale)

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

    gravity.timestep = 1 | units.day
    time = zero
    dt = 10 | units.day
    t_end = 100 | units.yr
    while time < t_end:
        time += dt
        gravity.evolve_model(time)

        Etot_prev_se = gravity.kinetic_energy + gravity.potential_energy

        channel_from_star_to_framework.copy()
        channel_from_planet_to_framework.copy()
        write_set_to_file(ss, filename, 'hdf5')

        Ekin = gravity.kinetic_energy
        Epot = gravity.potential_energy
        Etot = Ekin + Epot
        print "T=", time,
        print "E= ", Etot, "Q= ", Ekin / Epot,
        print "dE=", (Etot_init - Etot) / Etot, "ddE=", (Etot_prev -
                                                         Etot) / Etot
        Etot_prev = Etot
    gravity.stop()
Beispiel #12
0
    def create_bridge(self):
        self.bridge_system = bridge.Bridge(
            timestep=self.interaction_timestep_in_si,
            use_threading=False
        )

        self.bridge_system.add_system(
            self.gas_code,
            self.star_to_gas_codes
        )
        self.bridge_system.add_system(
            self.star_code,
            self.gas_to_star_codes
        )
Beispiel #13
0
def evolve_binary_in_common_envelope(stars, envelope, t_end):
    R = stars.position.length()
    converter = nbody_system.nbody_to_si(stars.mass.sum(), R)

    gravity = ph4(converter)
    gravity.particles.add_particles(stars)

    channel_from_gravity = gravity.particles.new_channel_to(stars)
    channel_from_to_gravity = stars.new_channel_to(gravity.particles)

    n_steps = 10
    dt = t_end / float(n_steps)

    hydro = Fi(converter, redirection="none")
    tdyn = numpy.sqrt((0.05 * R)**3 / (constants.G * stars.mass.sum()))
    print "tdyn=", tdyn
    hydro.parameters.timestep = tdyn
    hydro.parameters.epsilon_squared = (1 | units.RSun)**2
    hydro.gas_particles.add_particles(envelope)
    hydro.parameters.periodic_box_size = 100 * R

    channel_from_hydro = hydro.gas_particles.new_channel_to(envelope)
    channel_from_to_hydro = envelope.new_channel_to(hydro.gas_particles)

    model_time = 0 | units.Myr
    filename = "XiTau_Hydro.amuse"
    write_set_to_file(stars.savepoint(model_time),
                      filename,
                      'amuse',
                      append_to_file=False)
    write_set_to_file(envelope, filename, 'amuse')

    gravhydro = bridge.Bridge(use_threading=False)
    gravhydro.add_system(gravity, (hydro, ))
    gravhydro.add_system(hydro, (gravity, ))
    gravhydro.timestep = min(dt, 10 * hydro.parameters.timestep)

    while model_time < t_end:
        model_time += dt
        print "Time=", model_time.in_(units.day)
        gravhydro.evolve_model(model_time)

        channel_from_gravity.copy()
        channel_from_hydro.copy()

        write_set_to_file(stars.savepoint(model_time), filename, 'amuse')
        write_set_to_file(envelope, filename, 'amuse')
    gravity.stop()
    hydro.stop()
def integrate_single_particle_in_potential(sun, t_end, dt):
    MWG = MilkyWay_galaxy()
    cluster_gravity = drift_without_gravity(sun)
    channel_from_gravity_to_framework \
        = cluster_gravity.particles.new_channel_to(sun)

    gravity = bridge.Bridge(use_threading=False)
    gravity.add_system(cluster_gravity, (MWG, ))
    t_orb = 2 * numpy.pi * sun.position.length() / sun.velocity.length()
    gravity.timestep = min(dt, 10 | units.Myr)

    x, y = evolve_cluster_in_potential(gravity, t_end, dt,
                                       [channel_from_gravity_to_framework])
    gravity.stop()
    return x, y
Beispiel #15
0
def gravity_hydro_bridge(Mprim, Msec, a, ecc, t_end, n_steps, Rgas, Mgas,
                         Ngas):

    stars = new_binary_from_orbital_elements(Mprim,
                                             Msec,
                                             a,
                                             ecc,
                                             G=constants.G)
    eps = 1 | units.RSun
    gravity = Gravity(ph4, stars, eps)

    converter = nbody_system.nbody_to_si(1.0 | units.MSun, Rgas)
    ism = new_plummer_gas_model(Ngas, convert_nbody=converter)
    ism.move_to_center()
    ism = ism.select(lambda r: r.length() < 2 * a, ["position"])

    hydro = Hydro(Fi, ism, eps)

    model_time = 0 | units.Myr
    filename = "gravhydro.hdf5"
    write_set_to_file(stars.savepoint(model_time), filename, 'amuse')
    write_set_to_file(ism, filename, 'amuse')

    gravhydro = bridge.Bridge(use_threading=False)
    gravhydro.add_system(gravity, (hydro, ))
    gravhydro.add_system(hydro, (gravity, ))
    gravhydro.timestep = 2 * hydro.get_timestep()

    while model_time < t_end:
        orbit = orbital_elements_from_binary(stars, G=constants.G)
        a = orbit[2]
        ecc = orbit[3]

        dE_gravity = gravity.initial_total_energy / gravity.total_energy
        dE_hydro = hydro.initial_total_energy / hydro.total_energy
        print "Time:", model_time.in_(units.yr), "ae=", a.in_(
            units.AU), ecc, "dE=", dE_gravity, dE_hydro

        model_time += 10 * gravhydro.timestep
        gravhydro.evolve_model(model_time)

        gravity.copy_to_framework()
        hydro.copy_to_framework()
        write_set_to_file(stars.savepoint(model_time), filename, 'amuse')
        write_set_to_file(ism, filename, 'amuse')
    gravity.stop()
    hydro.stop()
Beispiel #16
0
    def test4(self):
        print "Bridge evolve_model"
        convert = nbody_system.nbody_to_si(1.e5 | units.MSun,
                                           1.0 | units.parsec)
        epsilon = 1.0e-2 | units.parsec
        test_class = ExampleGravityCodeInterface

        numpy.random.seed(12345)
        stars = new_plummer_model(100, convert_nbody=convert)

        cluster = test_class()
        cluster.initialize_code()
        cluster.parameters.epsilon_squared = epsilon**2
        cluster.particles.add_particles(stars)
        cluster.commit_particles()

        first_half = stars.select_array(lambda x: (x > 0 | units.m), ['x'])
        second_half = stars - first_half
        cluster1 = system_from_particles(test_class, dict(), first_half,
                                         epsilon)
        cluster2 = system_from_particles(test_class, dict(), second_half,
                                         epsilon)
        bridgesys = bridge.Bridge()
        bridgesys.add_system(cluster1, (cluster2, ))
        bridgesys.add_system(cluster2, (cluster1, ))

        self.assertAlmostRelativeEqual(
            cluster1.particles.get_intersecting_subset_in(
                cluster.particles).position, cluster1.particles.position)

        #~        old = cluster1.particles.position
        for i in range(2):
            one_timestep = cluster.next_timestep
            cluster.evolve_model(cluster.model_time + one_timestep)
            bridgesys.evolve_model(bridgesys.model_time + one_timestep,
                                   timestep=one_timestep)

#~        print ((old - cluster1.particles.position)/old).lengths()
        self.assertAlmostRelativeEqual(
            cluster1.particles.get_intersecting_subset_in(
                cluster.particles).position, cluster1.particles.position)

        self.assertAlmostRelativeEqual(cluster.potential_energy,
                                       bridgesys.potential_energy)
        self.assertAlmostRelativeEqual(cluster.kinetic_energy,
                                       bridgesys.kinetic_energy)
def evolve_cluster_in_galaxy(N, Mcluster, Rcluster, Rinit, Vinit, galaxy_code,
                             dt, dtout, tend, epsilon):

    #Setup cluster
    stars, converter = setup_cluster(N, Mcluster, Rcluster, Rinit, Vinit)
    stars.scale_to_standard(convert_nbody=converter,
                            smoothing_length_squared=epsilon**2)

    cluster_code = Nbody6xx(converter, number_of_workers=1)
    cluster_code.initialize_code()
    cluster_code.particles.add_particles(stars)
    cluster_code.commit_particles()

    #Setup channels between stars particle dataset and the cluster code
    channel_from_stars_to_cluster_code = stars.new_channel_to(
        cluster_code.particles,
        attributes=["mass", "x", "y", "z", "vx", "vy", "vz"])
    channel_from_cluster_code_to_stars = cluster_code.particles.new_channel_to(
        stars, attributes=["mass", "x", "y", "z", "vx", "vy", "vz"])

    #Setup gravity bridge
    gravity = bridge.Bridge(use_threading=False)
    #stars in cluster_code depend on gravity from galaxy_code
    gravity.add_system(cluster_code, (galaxy_code, ))
    #galaxy_code still needs to be added to system so it evolves with time
    gravity.add_system(galaxy_code, )
    #Set how often to update external potential
    gravity.timestep = dt / 2.

    time = 0.0 | tend.unit
    gravity.evolve_model(tend)
    time = gravity.model_time

    #Copy back to stars for final dataset
    channel_from_cluster_code_to_stars.copy()
    gravity.stop()

    return stars
Beispiel #18
0
    def __init__(
        self,
        *,
        internal_bridges={},
        timestep=None,
        use_threading=True,
        **systems,
    ):
        """Initialize a Systems instance."""
        super().__init__()
        # save inputs
        self._use_threading = use_threading
        self._init_internal_bridges = internal_bridges
        self._init_timestep = timestep

        self.gravity = bridge.Bridge(use_threading=use_threading)
        self.system_list = set()  # system list set

        for k, v in systems.items():
            self[k] = v

        # now do bridges. needed to create systems first
        self.bridge_internal_systems(bridges=internal_bridges,
                                     timestep=timestep)
def integrate_cluster_and_GMCs_in_potential(sun, GMCs, t_end, dt, filename):
    MWG = MilkyWay_galaxy()
    GMC_gravity = drift_without_gravity(GMCs)
    channels = []
    channels.append(GMC_gravity.particles.new_channel_to(GMCs))

    converter = nbody_system.nbody_to_si(sun.mass.sum(),
                                         sun[0].position.length())
    cluster_gravity = BHTree(converter)
    cluster_gravity.particles.add_particles(sun)
    channels.append(cluster_gravity.particles.new_channel_to(sun))

    gravity = bridge.Bridge(use_threading=False)
    gravity.add_system(cluster_gravity, (MWG, GMC_gravity))
    gravity.add_system(GMC_gravity, (MWG, ))
    gravity.timestep = min(dt, 10 | units.Myr)

    t_orb = 2 * numpy.pi * sun.position.length() / sun.velocity.length()
    gravity.timestep = min(dt, 10 | units.Myr)

    x, y = evolve_cluster_in_potential(gravity, t_end, dt, channels, sun, GMCs,
                                       filename)
    gravity.stop()
    return x, y
Beispiel #20
0
def main(t_end, filename):

    bodies = Particles(2)
    Sun = bodies[0]
    Sun.mass = 1 | units.MSun
    Sun.position = (8.4, 0.0, 0.0) | units.kpc
    Sun.velocity = (-10.1, 235.5, 7.5) | units.kms  # SPZ2009

    M67 = bodies[1]
    M67.mass = 50000 | units.MSun
    M67.position = Sun.position + ((0.766, 0.0, 0.49) | units.kpc)
    M67.velocity = Sun.velocity + ((31.92, -21.66, -8.71) | units.kms)

    converter = nbody_system.nbody_to_si(bodies.mass.sum(), Sun.x)
    sunandm67 = Huayno(converter)
    sunandm67.particles.add_particle(bodies)
    channel_from_sunandm67 = sunandm67.particles.new_channel_to(bodies)

    gravity = bridge.Bridge()
    gravity.add_system(sunandm67, (MilkyWay_galaxy(), ))
    dt = 1 | units.Myr
    gravity.timestep = dt

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

    t_end = 4.5 | units.Gyr
    time = 0 * t_end

    if filename:
        write_set_to_file(bodies.savepoint(0.0 | t_end.unit),
                          filename,
                          "hdf5",
                          append_to_file=False)
        pyplot.draw()
    else:
        R = [] | units.kpc
        for bi in bodies:
            R.append(bi.position.length())
        pyplot.ion()
        pyplot.scatter(R.value_in(units.kpc),
                       bodies.z.value_in(units.kpc),
                       c=['k', 'r'],
                       s=10,
                       lw=0)
        pyplot.xlabel("R [kpc]")
        pyplot.ylabel("Z [kpc]")
    while time < t_end:
        time += dt
        gravity.evolve_model(time)
        channel_from_sunandm67.copy()

        Ekin = gravity.kinetic_energy
        Epot = gravity.potential_energy
        Etot = Ekin + Epot
        print "T=", time, "M=", bodies.mass.sum(),
        print "E= ", Etot, "Q= ", Ekin / Epot,
        print "dE=", (Etot_init - Etot) / Etot, "ddE=", (Etot_prev -
                                                         Etot) / Etot
        Etot_prev = Etot
        if filename:
            write_set_to_file(bodies.savepoint(time), filename, "hdf5")
        else:
            R = [] | units.kpc
            for bi in bodies:
                R.append(bi.position.length())
            pyplot.scatter(R.value_in(units.kpc),
                           bodies.z.value_in(units.kpc),
                           c=['k', 'r'],
                           s=10,
                           lw=0)
            pyplot.draw()
    gravity.stop()
                          omega_bar=OB,
                          amplitude=A,
                          m=m,
                          mass_bar=M)

    sun_pos = [-8400.0, 0.0, 17.0] | units.parsec
    MWG = inte.galaxy()
    vc = MWG.get_velcirc(sun_pos[0], sun_pos[1], sun_pos[2])
    sun_vel = [11.352, (12.24 + vc.value_in(units.kms)), 7.41] | units.kms

    star_cluster.position += sun_pos
    star_cluster.velocity += sun_vel

    cluster_gravity, channels = setup_multi_bridge_system(star_cluster)

    gravity = bridge.Bridge(use_threading=False)
    gravity.add_system(cluster_gravity, (MWG, ))
    t_orb = 2 * numpy.pi * sun_pos.length() / sun_vel.length()
    t_end = 100 | units.day
    gravity.timestep = min(0.1 * t_end, 0.01 * t_orb)
    """
    sun_pos = [-8400.0, 0.0, 17.0] | units.parsec
    MWG = MilkyWay_galaxy()
    vc = MWG.vel_circ(sun_pos.length())
    sun_vel = [11.352, (12.24+vc.value_in(units.kms)), 7.41] | units.kms
    
    star_cluster.position += sun_pos
    star_cluster.velocity += sun_vel
    
    cluster_gravity, channels = setup_multi_bridge_system(star_cluster)
Beispiel #22
0
def evolve_disk_flyby(stars,
                      planetesimals,
                      stars_gravity,
                      planetesimals_gravity,
                      t_start,
                      t_end,
                      n_steps,
                      converter,
                      snap_dir,
                      file_out,
                      r_step,
                      bridge_dt,
                      center=0):
    """
  Input Parameters:
  stars --- Star bodies
  planetesimals --- Non-star bodies
  stars_gravity --- 
  planetesimals_gravity --- 
  t_end --- Total Integration Time
  n_steps --- Number of Snapshots
  converter --- 
  snap_dir --- 
  file_out --- 
  r_step --- 
  bridge_dt --- Bridge Timestep
  """

    bodies = ParticlesSuperset([stars, planetesimals])

    channel_from_stars_to_framework = stars_gravity.particles.new_channel_to(
        stars)
    channel_from_planetesimals_to_framework = planetesimals_gravity.particles.new_channel_to(
        planetesimals)

    pl_gravity = planet_gravity_for_disk(Huayno,
                                         stars_gravity.particles,
                                         converter,
                                         center=center)
    gravity = bridge.Bridge(use_threading=False)
    gravity.add_system(planetesimals_gravity,
                       (pl_gravity, ))  # stars work on planetesimals
    gravity.add_system(stars_gravity,
                       ())  # stars are self aware (evolves itself)

    # timestep for BRIDGE relative to the period at r_step (or r_min, if no r_step is given)
    #   BRIDGE_timestep = bridge_dt * P(r_step)
    if r_step is None:
        Porb_min = orbital_period((bodies[2:].position.lengths()).min(),
                                  bodies[0].mass)
        print " ** P_min_disk = ", Porb_min.in_(units.yr)
        gravity.timestep = bridge_dt * Porb_min
    else:
        Porb_min = orbital_period(r_step, bodies[0].mass)
        print " ** P_rin_disk = ", Porb_min.in_(units.yr)
        gravity.timestep = bridge_dt * Porb_min

    time_step = stars_gravity.get_timestep_parameter()
    print ' ** timesteps: \t stars gravity timestep parameter =', time_step
    print '\t\t bridge =', gravity.timestep

    Etot_init = stars_gravity.kinetic_energy + stars_gravity.potential_energy
    Etot = Etot_init

    ps.mkdir(snap_dir)

    duration = t_end - t_start
    dt = duration / float(n_steps)
    time = 0.0 | units.yr

    print "Duration:", duration, "t_start", t_start, "t_end", t_end, "dt:", dt

    print " ** evolving: t_start = ", t_start.value_in(
        1000 * units.yr), "t_end = ", t_end.value_in(1000 *
                                                     units.yr), ", dt = ", dt
    print " \t", "time", "\t\t\t", "E", "\t\t", "dE"

    stdout = (file_out.split('.'))[0]
    stdout += '.txt'
    f = open(snap_dir + "/" + stdout, 'a')

    # Joules
    J = units.m**2 * units.kg * units.s**-2

    while time <= duration:
        gravity.evolve_model(time)
        channel_from_stars_to_framework.copy()
        channel_from_planetesimals_to_framework.copy()

        bodies.collection_attributes.timestamp = time + t_start

        Ekin = stars_gravity.kinetic_energy
        Epot = stars_gravity.potential_energy
        Etot = Ekin + Epot
        dE = Etot_init - Etot

        nb_E = converter.to_nbody(Etot)
        #nb_J = converter.nbody_length ** 2 * units.nbody_mass * units.nbody_time ** -2 # not supposed to work

        # A formatted string would work better than tabs. (Tabs never work)
        line = " \t" + str((time + t_start).value_in(
            units.yr)) + "\t" + str(nb_E) + "\t" + str(dE / Etot_init)
        print line

        f.write(line + "\n")

        # Write coordinates in Center of Mass frame

        # Move Stars to CoM (initially in CoM)
        #### The stars are already in CoM coordinates ####

        # Move planetesimals to CoM (initially w/ respect to star zero)
        planetesimals.velocity += stars[center].velocity
        planetesimals.position += stars[center].position

        write_set_to_file(bodies, snap_dir + "/" + file_out, "hdf5")

        time += dt

    f.close()  # stdout

    gravity.stop()
    stars_gravity.stop()
    planetesimals_gravity.stop()
    pl_gravity.stop()

    # retrieval?
    return stars, planetesimals
Beispiel #23
0
def sim_Sun_and_siblings(N=50,
                         perc=0.01,
                         t_end=4.56 | units.Gyr,
                         dt_save=0.2 | units.Myr,
                         dt=0.01 | units.Myr,
                         pointparticles=True,
                         dirname='None'):
    """
    Simulate Sun and siblings in the Galactic potential.
    """

    if pointparticles:
        """
        Create a set of point partciles to integrate around the galactic center.
        """

        # for the pointparticles
        if dirname == 'None': dirname = './pointparticles/'

        #create outputfolder for this star
        outputfolder = os.path.join(dirname)
        if not os.path.exists(outputfolder):
            os.makedirs(outputfolder)

        # initalize bodies
        bodies = Particles(N + 1)

        # create the Sun
        Sun = bodies[0]
        Sun.mass = 1e-9 | units.kg  # assume Sun is point mass moving in the
        Sun.radius = 0 | units.RSun  # galactic potential
        Sun.velocity = (-1.35, -232.1, -7.41) | units.kms
        Sun.position = (-8400, 0.0, 17.0) | units.parsec

        # create a Gaussian cloud of stars as point particles
        siblings = bodies[1:]
        siblings.mass = 1e-9 | units.kg
        siblings.radius = 0 | units.RSun

        # create a cloud of particles
        siblings.x = np.random.normal(Sun.x.value_in(units.parsec),
                                      abs(Sun.x.value_in(units.parsec)) * perc,
                                      N) | units.parsec
        siblings.y = 0 | units.parsec  # no spread in y-direction since we start at y=0
        siblings.z = np.random.normal(Sun.z.value_in(units.parsec),
                                      abs(Sun.z.value_in(units.parsec)) * perc,
                                      N) | units.parsec

        siblings.vx = np.random.normal(Sun.vx.value_in(units.kms),
                                       abs(Sun.vx.value_in(units.kms)) * perc,
                                       N) | units.kms
        siblings.vy = np.random.normal(Sun.vy.value_in(units.kms),
                                       abs(Sun.vy.value_in(units.kms)) * perc,
                                       N) | units.kms
        siblings.vz = np.random.normal(Sun.vz.value_in(units.kms),
                                       abs(Sun.vz.value_in(units.kms)) * perc,
                                       N) | units.kms

        # Integrator
        converter = nbody_system.nbody_to_si(bodies.mass.sum(), Sun.x)

        bodies.velocity *= -1  # Integrate backwards in time

        # integrator to use
        system = ph4(converter)

    else:
        """
        Create an open star cluster to integrate around the galactic center.
        """

        # if dirname not specified
        if dirname == 'None': dirname = './opencluster/'

        #create outputfolder for this star
        outputfolder = os.path.join(dirname)
        if not os.path.exists(outputfolder):
            os.makedirs(outputfolder)

        # parameters to use
        Rvir = 1.0 | units.parsec
        Qvir = 0.5

        # create masses
        Mmax = 100 | units.MSun
        masses = new_kroupa_mass_distribution(
            N + 1, Mmax)  # cluster with N other stars
        Mtot_init = masses.sum()

        converter = nbody_system.nbody_to_si(Mtot_init, Rvir)

        # assign particles
        bodies = new_plummer_model(N + 1, converter)
        bodies.scale_to_standard(converter, virial_ratio=Qvir)
        bodies.mass = masses
        Sun = bodies[0]
        Sun.mass = 1 | units.MSun  # first body becomes the Sun
        bodies.radius = 0 | units.RSun
        bodies.velocity += (30.6471439995, -200.098514469, 2.52218463835
                            ) | units.kms  # our birthplace of the Sun
        bodies.position += (9499.1059096, 1999.79260586,
                            80.1313697564) | units.parsec

        # integrator with softening length scale
        system = BHTree(converter)
        system.parameters.epsilon_squared = (1 | units.parsec)**2

    system.particles.add_particle(bodies)
    channel_from_system = system.particles.new_channel_to(bodies)

    gravity = bridge.Bridge()
    gravity.add_system(system, (MilkyWay_galaxy(), ))
    gravity.timestep = dt

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

    # duration of simulation
    time = 0 | units.yr
    time_save = 0 | units.yr

    # allocate memory for positions and velocities
    x = []
    y = []
    z = []
    vx = []
    vy = []
    vz = []

    while time < t_end:

        print 'Integrating...', time
        time += dt
        time_save += dt

        gravity.evolve_model(time)
        channel_from_system.copy()

        Ekin = gravity.kinetic_energy
        Epot = gravity.potential_energy
        Etot = Ekin + Epot
        print "T=", time, "M=", bodies.mass.sum(),
        print "E= ", Etot, "Q= ", Ekin / Epot,
        print "dE=", (Etot_init - Etot) / Etot, "ddE=", (Etot_prev -
                                                         Etot) / Etot
        Etot_prev = Etot

        if time_save > dt_save:

            # save the postion and velocities of all objects
            x = np.append(x, bodies.x.value_in(units.parsec))
            y = np.append(y, bodies.y.value_in(units.parsec))
            z = np.append(z, bodies.z.value_in(units.parsec))
            vx = np.append(vx, bodies.vx.value_in(units.kms))
            vy = np.append(vy, bodies.vy.value_in(units.kms))
            vz = np.append(vz, bodies.vz.value_in(units.kms))
            print 'Appended velocities and positions.'

            # reset timer
            time_save = 0 | units.yr

    # explicitly save last position
    x = np.append(x, bodies.x.value_in(units.parsec))
    y = np.append(y, bodies.y.value_in(units.parsec))
    z = np.append(z, bodies.z.value_in(units.parsec))
    vx = np.append(vx, bodies.vx.value_in(units.kms))
    vy = np.append(vy, bodies.vy.value_in(units.kms))
    vz = np.append(vz, bodies.vz.value_in(units.kms))
    print 'Appended final postions.'

    gravity.stop()

    # Correct the inverse velocity
    if pointparticles: bodies.velocity *= -1

    # plot the positions of all particles
    x = x.reshape((N + 1, x.size / (N + 1)))
    y = y.reshape((N + 1, y.size / (N + 1)))
    z = z.reshape((N + 1, z.size / (N + 1)))
    vx = vx.reshape((N + 1, vx.size / (N + 1)))
    vy = vy.reshape((N + 1, vy.size / (N + 1)))
    vz = vz.reshape((N + 1, vz.size / (N + 1)))

    # save positions seperately
    np.save(os.path.join(dirname, 'x.npy'), x)
    np.save(os.path.join(dirname, 'y.npy'), y)
    np.save(os.path.join(dirname, 'z.npy'), z)
    np.save(os.path.join(dirname, 'vx.npy'), vx)
    np.save(os.path.join(dirname, 'vy.npy'), vy)
    np.save(os.path.join(dirname, 'vz.npy'), vz)
    print 'Saved velocities and positions.'
def gravity_hydro_bridge(gravity,
                         hydro,
                         sink,
                         local_particles,
                         Rmin,
                         t_end=1000. | units.yr,
                         dt=10. | units.yr):

    # Set the local particles in each system
    gravity_particles, disk_star, disk_gas = local_particles
    Sun = disk_star[0]
    Jupiter = gravity_particles[0]
    PassStar = gravity_particles[1]
    Mstar = Sun.mass.in_(units.MSun)
    Sun_and_Jupiter = Particles()
    Sun_and_Jupiter.add_particle(Sun)
    Sun_and_Jupiter.add_particle(Jupiter)

    print 'Bridging...'
    # Build up the bridge between gravity and hydrodynamics
    grav_hydro = bridge.Bridge(use_threading=False)
    grav_hydro.add_system(gravity, (hydro, ))
    grav_hydro.add_system(hydro, (gravity, ))
    grav_hydro.timestep = dt

    # Set up channels for updating the particles
    channel_to_grav = gravity.particles.new_channel_to(gravity_particles)
    channel_from_grav = gravity_particles.new_channel_to(gravity.particles)
    channel_to_hydro_gas = hydro.gas_particles.new_channel_to(disk_gas)
    channel_from_hydro_gas = disk_gas.new_channel_to(hydro.gas_particles)
    channel_to_hydro_star = hydro.dm_particles.new_channel_to(disk_star)
    chennel_from_hydro_star = disk_star.new_channel_to(hydro.dm_particles)

    # Sanity checks:
    print('Sanity checks:')
    print('Sun coordinates (AU)', Sun.x.value_in(units.AU),
          Sun.y.value_in(units.AU), Sun.z.value_in(units.AU))
    print('Jupiter coordinates (AU)', Jupiter.x.value_in(units.AU),
          Jupiter.y.value_in(units.AU), Jupiter.z.value_in(units.AU))
    print('Disk particle map saved to: initial_check_disk.png')
    plot_map(hydro, [Sun, Jupiter, PassStar], N=400, L=400,\
             title='initial_check_disk.png', show=True)

    times = list(
        np.arange(0.0,
                  t_end.value_in(units.yr) + dt.value_in(units.yr),
                  dt.value_in(units.yr)))
    a_Jup = list()
    e_Jup = list()
    disk_size = list()
    accreted_mass = list()

    # start evolotuion
    print 'Start evolving...'
    model_time = 0.0 | units.yr
    while model_time <= t_end:

        # Save the data for plots
        orbit = orbital_elements_from_binary(Sun_and_Jupiter, G=constants.G)
        a = orbit[2].value_in(units.AU)
        e = orbit[3]
        lr9 = return_L9_radius(disk_gas, Mstar, Rmin)
        a_Jup.append(a)
        e_Jup.append(e)
        disk_size.append(lr9)
        accreted_mass.append((sink.mass).value_in(units.MJupiter)[0])

        #if model_time.value_in(units.yr) % 50 == 0:
        print 'Time = %.1f yr:'%model_time.value_in(units.yr), \
              'a = %.2f au, e = %.3f,'%(a, e), \
              'disk size = %.2f au'%lr9, \
              'accreted mass = %.2f M_Jupiter'%sink.mass.value_in(units.MJupiter)
        plot_map(hydro, [Sun, Jupiter, PassStar], N=400, L=400,\
                 title='test_plots/%d.png'%model_time.value_in(units.yr), show=False)

        # Evolve the bridge system for one step
        model_time += dt
        grav_hydro.evolve_model(model_time)
        channel_to_grav.copy()
        channel_to_hydro_gas.copy()
        channel_to_hydro_star.copy()

        # Add the 'sinked' mass to Jupiter & keep the sink particle along with Jupiter
        removed_particles = hydro_sink_particles(sink, disk_gas)

        Jupiter.mass += sink.mass
        sink.position = Jupiter.position
        sink.radius = a * (1 - e) * (
            (1.0 | units.MJupiter).value_in(units.MSun) / 3.)**(1. /
                                                                3.) | units.au
        channel_from_grav.copy()

    gravity.stop()
    hydro.stop()

    return times, a_Jup, e_Jup, disk_size, accreted_mass
Beispiel #25
0
def gravity_hydro_bridge(gravity,
                         hydro,
                         local_particles,
                         Rmin,
                         t_end=1000. | units.yr,
                         dt=10. | units.yr):

    Sun_and_Jupiter, disk_gas = local_particles
    Mstar = gravity.particles[1].mass.in_(units.MSun)

    print 'Bridging...'
    # build up the bridge between gravity and hydrodynamics
    grav_hydro = bridge.Bridge(use_threading=False)
    grav_hydro.add_system(gravity, (hydro, ))
    grav_hydro.add_system(hydro, (gravity, ))
    #grav_hydro.timestep = dt

    # set up channels for updating the particles
    channel_from_grav = gravity.particles.new_channel_to(Sun_and_Jupiter)
    channel_from_hydro = hydro.gas_particles.new_channel_to(disk_gas)

    a_Jup = list()
    e_Jup = list()
    disk_size = list()

    # start evolotuion
    print 'Start evolving...'
    times = quantities.arange(0. | units.yr, t_end + 1 * dt, 2 * dt)
    model_time = 0.0 | units.yr
    while model_time <= t_end:
        # save the data for plots
        orbit = orbital_elements_from_binary(Sun_and_Jupiter, G=constants.G)
        a = orbit[2].value_in(units.AU)
        e = orbit[3]
        lr9 = return_L9_radius(disk_gas, Mstar, Rmin | units.AU)
        a_Jup.append(a)
        e_Jup.append(e)
        disk_size.append(lr9)

        if model_time.value_in(units.yr) % 50 == 0:
            print 'Time = %.1f yr:'%model_time.value_in(units.yr), \
                  'a = %.2f au, e = %.2f,'%(a, e), \
                  'disk size = %.2f au'%lr9
        # evolve the bridge system for one step
        model_time += dt
        grav_hydro.evolve_model(model_time, timestep=2 * dt)
        channel_from_grav.copy()
        channel_from_hydro.copy()

        # add the 'sinked' mass to Jupiter & keep the sink particle along with Jupiter
        sink = hydro.particles[0]
        _ = hydro_sink_particles([sink], disk_gas)
        Jupiter = gravity.particles[1]
        Jupiter.mass += sink.mass
        sink.position = Jupiter.position
        sink.radius = a * (1 - e) * (
            (1.0 | units.MJupiter).value_in(units.MSun) / 3.)**(1. /
                                                                3.) | units.au
        channel_from_grav.copy()
        channel_from_hydro.copy()

    gravity.stop()
    hydro.stop()

    return a_Jup, e_Jup, disk_size, times
Beispiel #26
0
# In[11]:


gravity1 = ph4(converter)
gravity1.particles.add_particles(galaxies)
channel = {"from_galaxies": galaxies.new_channel_to(gravity1.particles),
"to_galaxies": gravity1.particles.new_channel_to(galaxies)}

channel.update({"from_gas": sph_code.gas_particles.new_channel_to(sph_code.particles)})
channel.update({"to_gas": sph_code.particles.new_channel_to(sph_code.gas_particles)})

galaxies.add_particles(sph_code.gas_particles)

from amuse.couple import bridge
from amuse.ext.composition_methods import *
gravhydro = bridge.Bridge(use_threading=False) #, method=SPLIT_4TH_S_M4)
gravhydro.add_system(gravity1, (sph_code,))
gravhydro.add_system(sph_code, (gravity1,))
gravhydro.timestep = 5.0 | units.Myr


# In[ ]:


def gravity_hydro_bridge(gravity, hydro, gravhydro, galaxies,
                         t_end):

    model_time = 0 | units.Myr
    dt = 10|units.Myr  #1.0*Pinner
    while model_time < t_end:
def gravity_hydro_bridge(gravity,
                         hydro,
                         sink,
                         local_particles,
                         Rmin,
                         t_end=1000. | units.yr,
                         dt=10. | units.yr):

    Sun_and_Jupiter, disk_gas = local_particles
    Mstar = 1.0 | units.MSun

    print 'Bridging...'
    # Build up the bridge between gravity and hydrodynamics
    grav_hydro = bridge.Bridge(use_threading=False)
    grav_hydro.add_system(gravity, (hydro, ))
    grav_hydro.add_system(hydro, (gravity, ))
    grav_hydro.timestep = dt

    # Set up channels for updating the particles
    channel_from_grav = gravity.particles.new_channel_to(Sun_and_Jupiter)
    channel_from_hydro = hydro.gas_particles.new_channel_to(disk_gas)
    channel_to_grav = Sun_and_Jupiter.new_channel_to(gravity.particles)
    channel_to_hydro = disk_gas.new_channel_to(hydro.gas_particles)

    # Preparing lists for data-recording
    a_Jup = []
    e_Jup = []
    disk_size = []
    accreted_mass = []
    accreted_mass.append((sink.mass).value_in(units.MJupiter)[0])
    sink0_mass = 0 | units.MJupiter

    # Start evolution
    print 'Start evolving...'
    times = quantities.arange(0. | units.yr, t_end + 1 * dt, dt)
    model_time = 0.0 | units.yr
    while model_time <= t_end:

        # Save the data for plots
        orbit = orbital_elements_from_binary(Sun_and_Jupiter, G=constants.G)
        a = orbit[2].value_in(units.AU)
        e = orbit[3]
        lr9 = return_L9_radius(disk_gas, Mstar, Rmin | units.AU)
        a_Jup.append(a)
        e_Jup.append(e)
        disk_size.append(lr9)
        am = (sink.mass[0]).value_in(units.MJupiter)
        accreted_mass.append(am)

        # Plotting system
        print 'Time = %.1f yr:'%model_time.value_in(units.yr), \
                  'a = %.2f au, e = %.2f,'%(a, e), \
                  'disk size = %.2f au'%lr9
        plot_map(hydro,
                 Sun_and_Jupiter,
                 '{0}'.format(int(model_time.value_in(units.yr))),
                 show=False)

        # Evolve the bridge system for one step
        model_time += dt
        grav_hydro.evolve_model(model_time)
        channel_from_grav.copy()
        channel_from_hydro.copy()

        # Calculating accreted mass in new position
        Jupiter = gravity.particles[0]
        sink.position = Jupiter.position
        sink.radius = Hill_radius(a, e, Sun_and_Jupiter) | units.AU
        removed_particles = hydro_sink_particles(sink, disk_gas)
        Jupiter.mass += sink.mass - sink0_mass
        sink0_mass = sink.mass.copy()
        channel_to_grav.copy()
        channel_to_hydro.copy()

    gravity.stop()
    hydro.stop()

    return a_Jup, e_Jup, disk_size, times, accreted_mass
Beispiel #28
0
def simulation():

    Hercules = Particles(1)
    Hercules.mass = 6e5 | units.MSun

    RA, DEC = 250.422, 36.460  #degrees
    D = 7.1  #distance from Sun, kpc
    vlos = -244.49  # pm 0.43, line-of-sight velocity in km/s

    mu_RA = -106.6  #pm 1.6, proper motion in km/s
    mu_DEC = -87.2  #pm 1.6, proper motion in km/s

    #will need to fix this
    Hercules.position = (20., 0., 0.) | units.kpc
    Hercules.velocity = (0., 200., 0.) | units.kms

    gravity = bridge.Bridge(use_threading=False)

    gravity_Hercules = Hermite()
    gravity_Hercules.particles.add_particles(Hercules)

    potential = KuzminKutuzovStaeckelPotential
    galaxy_code = to_amuse(potential,
                           t=0.0,
                           tgalpy=0.0,
                           reverse=False,
                           ro=None,
                           vo=None)

    gravity.add_system(gravity_Hercules, galaxy_code)

    channel_from_gravity_to_framework = gravity.particles.new_channel_to(
        Hercules)
    channel_from_framework_to_gravity = Hercules.new_channel_to(
        gravity.particles)

    tend, dt = 1000. | units.Myr, 5. | units.Myr

    sim_times_unitless = np.arange(
        0.,
        tend.value_in(units.Myr) + dt.value_in(units.Myr),
        dt.value_in(units.Myr))
    sim_times = [t | units.Myr for t in sim_times_unitless]

    plt.rc('text', usetex=True)
    plt.rc('font', family='serif')

    rvals, zvals = [], []

    for j, t in enumerate(sim_times):

        x_gal = gravity.particles.position[0].value_in(units.kpc)
        y_gal = gravity.particles.position[0].value_in(units.kpc)
        z_gal = gravity.particles.position[0].value_in(units.kpc)

        r_gal = np.sqrt(x_gal**2 + y_gal**2)

        rvals.append(r_gal)
        zvals.append(z_gal)

        plt.figure()

        plt.plot(rvals, zvals, c='k', label='M13')
        plt.legend(loc='upper right')

        plt.xlim(0., 50.)
        plt.ylim(-20., 20.)
        plt.xlabel('$r_{\mathrm{gal}}$ (kpc)', fontsize=14)
        plt.ylabel('$z_{\mathrm{gal}}$ (kpc)', fontsize=14)

        plt.savefig('m13_trajectory_%s.png' % (str(j).rjust(5, '0')))
        plt.close()

        gravity.evolve_model(t)

    gravity.stop()

    return 0
Beispiel #29
0
def main(Mstar, Ndisk, fmdisk, Rmin, Rmax, t_end, n_steps):

    Mdisk = fmdisk * Mstar
    converter=nbody_system.nbody_to_si(Mstar, Rmax)
    star_and_planets, disk = initialize_star_and_planetary_system(Mstar, Ndisk, Mdisk, Rmin, Rmax)

    hydro=Fi(converter)
#    hydror = Fi(channel_type="ibis", hostname="galgewater")
 
    hydro.parameters.use_hydro_flag=True
    hydro.parameters.radiation_flag=False
    hydro.parameters.self_gravity_flag=True
    hydro.parameters.gamma=1.
    hydro.parameters.isothermal_flag=True
    hydro.parameters.integrate_entropy_flag=False
    hydro.parameters.timestep=0.125 | units.yr  

    hydro.gas_particles.add_particles(disk)

    gravity = Hermite(converter)
    gravity.particles.add_particles(star_and_planets)

    planet_attributes=["x", "y", "z", "vx", "vy", "vz", "mass", "semimajor_axis", "eccentricity"]
    disk_attributes=["x", "y", "z", "vx", "vy", "vz", "mass", "u", "rho", "h_smooth"]
    channel_to_planets = gravity.particles.new_channel_to(star_and_planets)
    channel_from_hydro_to_framework = hydro.particles.new_channel_to(disk,
                                                                     attributes=disk_attributes)
    channel_from_hydro_to_framework.copy()

    moving_bodies = ParticlesSuperset([star_and_planets, disk])
    moving_bodies.move_to_center()

    index = 0
    filename = "planetary_system_i{0:04}.amuse".format(index)
    write_set_to_file(star_and_planets, filename, 'amuse', attribute_names=planet_attributes,
                      append_to_file=False)
    write_set_to_file(disk, filename, 'amuse', attribute_names=disk_attributes)
    
    gravity_hydro = bridge.Bridge(use_threading=False)
    gravity_hydro.add_system(gravity, (hydro,) )
    gravity_hydro.add_system(hydro, (gravity,) )

    Etot_init = gravity_hydro.kinetic_energy + gravity_hydro.potential_energy
    Etot_prev = Etot_init

    time = 0.0 | t_end.unit
    dt = t_end/float(n_steps)
    gravity_hydro.timestep = dt/10.
    while time < t_end:
        time += dt
        gravity_hydro.evolve_model(time)

        Etot_prev_se = gravity_hydro.kinetic_energy + gravity_hydro.potential_energy

        channel_to_planets.copy()
        channel_from_hydro_to_framework.copy()

        for pi in star_and_planets[1:]:
            a, e = calculate_orbital_elements(star_and_planets[0], pi)
            pi.semimajor_axis = a
            pi.eccentricity = e
        
        index += 1
        filename = "planetary_system_i{0:04}.amuse".format(index)
        write_set_to_file(star_and_planets, filename, 'amuse', attribute_names=planet_attributes,
                          append_to_file=False)
        write_set_to_file(disk, filename, 'amuse', attribute_names=disk_attributes)

        Ekin = gravity_hydro.kinetic_energy 
        Epot = gravity_hydro.potential_energy
        Etot = Ekin + Epot
        print "T=", time, 
        print "E= ", Etot, "Q= ", Ekin/Epot,
        print "dE=", (Etot_init-Etot)/Etot, "ddE=", (Etot_prev-Etot)/Etot 
        Etot_prev = Etot

    gravity_hydro.stop()
def evolve_cluster_in_galaxy(N, Rcluster, Rinit, Vinit, galaxy_code, dt, dtout,
                             tend, epsilon):

    #Setup cluster
    masses = new_kroupa_mass_distribution(N)
    Mcluster = masses.sum()

    #Create star cluster with origin at 0,0,0 and no net velocity
    converter = nbody_system.nbody_to_si(Mcluster, Rcluster)
    stars = new_plummer_sphere(N, converter)

    #Place star cluster in Galactocentric position
    stars.x += Rinit[0]
    stars.y += Rinit[1]
    stars.z += Rinit[2]

    stars.vx += Vinit[0]
    stars.vy += Vinit[1]
    stars.vz += Vinit[2]

    stars.mass = masses

    stars.scale_to_standard(convert_nbody=converter,
                            smoothing_length_squared=epsilon**2)

    #Gravity code
    cluster_code = BHTree(
        converter, number_of_workers=1
    )  #Change number of workers depending on CPUS available
    cluster_code.parameters.epsilon_squared = epsilon**2
    cluster_code.parameters.opening_angle = 0.6
    cluster_code.parameters.timestep = dt
    #cluster_code.particles.add_particles(stars)

    #Setup channels between stars particle dataset and the cluster code
    channel_from_stars_to_cluster_code = stars.new_channel_to(
        cluster_code.particles,
        attributes=["mass", "x", "y", "z", "vx", "vy", "vz"])
    channel_from_cluster_code_to_stars = cluster_code.particles.new_channel_to(
        stars, attributes=["mass", "x", "y", "z", "vx", "vy", "vz"])

    #Stellar evolution code
    stellar_evolution = SSE()
    stellar_evolution.particles.add_particle(stars)

    #Setup channels between stars particle dataset and stellar evolution code
    channel_from_stars_to_stellar_evolution = stars.new_channel_to(
        stellar_evolution.particles, attributes=["mass"])
    channel_from_stellar_evolution_to_stars = stellar_evolution.particles.new_channel_to(
        stars, attributes=["mass"])

    #Setup gravity bridge
    gravity = bridge.Bridge(use_threading=False)
    #stars in cluster_code depend on gravity from galaxy_code
    gravity.add_system(cluster_code, (galaxy_code, ))
    #galaxy_code still needs to be added to system so it evolves with time
    gravity.add_system(galaxy_code, )
    #Set how often to update external potential
    gravity.timestep = cluster_code.parameters.timestep / 2.

    time = 0.0 | tend.unit
    first = True
    while time < tend:
        print(time.value_in(units.Myr), tend.value_in(units.Myr),
              stars.mass.sum().value_in(units.MSun))

        stellar_evolution.evolve_model(time + dt / 2.)
        channel_from_stellar_evolution_to_stars.copy_attributes(["mass"])

        if first:
            cluster_code.particles.add_particles(stars)
            first = False
        else:
            channel_from_stars_to_cluster_code.copy_attributes(["mass"])

        gravity.evolve_model(time + dt)
        channel_from_cluster_code_to_stars.copy()

        stellar_evolution.evolve_model(time + dt)
        channel_from_stellar_evolution_to_stars.copy_attributes(["mass"])
        channel_from_stars_to_cluster_code.copy_attributes(["mass"])

        #You need to copy stars from cluster_code to output or analyse:

        #channel_from_cluster_code_to_stars.copy()
        #Output/Analyse

        #If you edited the stars particle set, lets say to remove stars from the array because they have
        #been kicked far from the cluster, you need to copy the array back to cluster_code:

        #channel_from_stars_to_cluster_code.copy()

        time = gravity.model_time

    #Copy back to stars for final dataset
    channel_from_cluster_code_to_stars.copy()
    gravity.stop()

    return stars