Beispiel #1
0
def create_giant_molecular_cloud(Ngas, Mgas, Rgas):
    converter = nbody_system.nbody_to_si(Mgas, Rgas)
    particles = molecular_cloud(targetN=Ngas, convert_nbody=converter).result
    particles.u = 1. | units.ms**2
    particles.velocity *= 0.6
    particles.move_to_center()
    return particles, converter
def create_giant_molecular_cloud(Ngas, Mgas, Rgas):
    converter = nbody_system.nbody_to_si(Mgas, Rgas)
    particles = molecular_cloud(targetN=Ngas, convert_nbody=converter).result
    particles.u = 1. | units.ms**2
    particles.velocity *= 0.6
    particles.move_to_center()
    return particles, converter
def run_molecular_cloud(N=100, Mcloud=100. | units.MSun, Rcloud=1. | units.parsec):

    conv = nbody_system.nbody_to_si(Mcloud,Rcloud)

    rho_cloud = 3.*Mcloud/(4.*numpy.pi*Rcloud**3)
    print rho_cloud
    tff = 0.5427/numpy.sqrt(constants.G*rho_cloud)
    print "t_ff=", tff.value_in(units.Myr), 'Myr'

    dt = 0.05 | units.Myr
    tend=1.0 | units.Myr

    parts=molecular_cloud(targetN=N,convert_nbody=conv,
            base_grid=body_centered_grid_unit_cube, seed=100).result
    
    sph = Hydro(Fi, parts)
    #sph = Hydro(Gadget2, parts)
    eps = 0.1 | units.parsec

    expected_dt = 0.2*numpy.pi*numpy.power(eps, 1.5)/numpy.sqrt(constants.G*Mcloud/N)

    print "dt_exp=", expected_dt.value_in(units.Myr)
    print "dt=", dt
    print "eps=", sph.parameters.gas_epsilon.in_(units.parsec)

    i=0
    L=6
    E0 = 0.0
    ttarget = 0.0 | units.Myr

    plot_hydro(ttarget, sph, i, L)

    while ttarget < tend:
        ttarget=float(i)*dt
        print "Evolve to time=", ttarget.in_(units.Myr)
#        print "N=", len(sph.gas_particles), len(sph.dm_particles)
#        print "Masses of dm particles:", sph.dm_particles.mass.in_(units.MSun)

        sph.evolve_model(ttarget)
        E = sph.gas_particles.kinetic_energy()+sph.gas_particles.potential_energy() + sph.gas_particles.thermal_energy()
        E_th = sph.gas_particles.thermal_energy()
        if i==0:
            E0 = E
        Eerr = (E-E0)/E0
        print 'energy=', E, 'energy_error=', Eerr, 'e_th=', E_th
        print "maximal_density:",parts.rho.max().in_(units.MSun/units.parsec**3)

        """
        filename = 'm400k_r10pc_e01_'+ str(i).zfill(2) + '.dat'
        print filename
        parts_sorted = parts.sorted_by_attribute('rho')
        write_output(filename, parts_sorted, conv)        
        """

        plot_hydro(ttarget, sph, i, L)
        i=i+1

    sph.stop()
    return parts
def cloud_init(N=100, M=100. | units.MSun, R=1. | units.parsec):
    '''Initialises the cloud'''
    converter = nbody_system.nbody_to_si(M, R)
    cloud = molecular_cloud(targetN=N, convert_nbody=converter,\
                            base_grid=body_centered_grid_unit_cube,\
                            ).result
    #cloud = new_plummer_model(N, convert_nbody=converter)
    return cloud, converter
Beispiel #5
0
 def test3(self):
     mc=molecular_cloud(targetN=1000,ekep_ratio=2.,base_grid=sobol_unit_cube).result
     self.assertEqual(len(mc),995)
     ek=mc.kinetic_energy()
     ep=mc.potential_energy(G=nbody_system.G)
     eth=mc.thermal_energy()
     self.assertAlmostRelativeEqual(eth/ep, -0.01,2)
     self.assertAlmostRelativeEqual(ek/ep, -2.,2)
Beispiel #6
0
 def test1(self):
     mc = molecular_cloud(targetN=1000, base_grid=sobol_unit_cube).result
     self.assertEqual(len(mc), 995)
     ek = mc.kinetic_energy()
     ep = mc.potential_energy(G=nbody_system.G)
     eth = mc.thermal_energy()
     self.assertAlmostRelativeEqual(eth / ep, -0.01, 2)
     self.assertAlmostRelativeEqual(ek / ep, -1., 2)
Beispiel #7
0
def main():
    "Test class with a molecular cloud"
    from amuse.ext.molecular_cloud import molecular_cloud
    converter = nbody_system.nbody_to_si(
        100000 | units.MSun,
        10.0 | units.parsec,
    )
    numpy.random.seed(11)
    temperature = 30 | units.K
    from plotting_class import temperature_to_u
    u = temperature_to_u(temperature)
    gas = molecular_cloud(targetN=200000, convert_nbody=converter).result
    gas.u = u
    print("We have %i gas particles" % (len(gas)))

    # gastwo = molecular_cloud(targetN=100000, convert_nbody=converter).result
    # gastwo.u = u

    # gastwo.x += 12 | units.parsec
    # gastwo.y += 3 | units.parsec
    # gastwo.z -= 1 | units.parsec
    # gastwo.vx -= ((5 | units.parsec) / (1 | units.Myr))

    # gas.add_particles(gastwo)
    print("Number of gas particles: %i" % (len(gas)))

    model = GasCode(converter=converter, )
    model.gas_particles.add_particles(gas)
    print(model.parameters)
    # print(model.gas_code.gas_particles[0])
    # exit()
    timestep = 0.01 | units.Myr  # model.gas_code.parameters.timestep

    times = [] | units.Myr
    # kinetic_energies = [] | units.J
    # potential_energies = [] | units.J
    # thermal_energies = [] | units.J
    time = 0 | units.Myr
    step = 0
    while time < 0.3 | units.Myr:
        time += timestep
        print("Starting at %s, evolving to %s" % (
            model.model_time.in_(units.Myr),
            time.in_(units.Myr),
        ))
        model.evolve_model(time)
        print("Evolved to %s" % model.model_time.in_(units.Myr))
        print("Maximum density / stopping density = %s" %
              (model.gas_particles.density.max() /
               model.parameters.stopping_condition_maximum_density, ))
        if not model.sink_particles.is_empty():
            print("Largest sink mass: %s" %
                  (model.sink_particles.mass.max().in_(units.MSun)))

        times.append(time)
        step += 1
def create_giant_molecular_clouds(Ngas, Mgas, Rgas, Nclouds):
    converter = nbody_system.nbody_to_si(Mgas, Rgas)
    clouds = []
    for i in xrange(Nclouds):
        particles = molecular_cloud(targetN=Ngas, convert_nbody=converter).result
        particles.u = 1. | units.ms**2
        particles.velocity *= 0.6
        particles.move_to_center()
        clouds.append(particles)
    return clouds, converter
def GMC_model(N, M, R):
    converter = nbody_system.nbody_to_si(M, R)
    parts=molecular_cloud(targetN=N, convert_nbody=converter, seed=100).result
    sph=Fi(converter)
    sph.gas_particles.add_particle(parts)
    sph.evolve_model(1|units.day)
    ch = sph.gas_particles.new_channel_to(parts)
    ch.copy()
    sph.stop()
    return parts
Beispiel #10
0
def GMC_model(N, M, R):
    converter = nbody_system.nbody_to_si(M, R)
    sph_particles = molecular_cloud(targetN=N, convert_nbody=converter).result
    sph = Fi(converter)
    sph.gas_particles.add_particle(sph_particles)
    sph.evolve_model(1 | units.day)
    ch = sph.gas_particles.new_channel_to(sph_particles)
    ch.copy()
    sph.stop()
    return sph_particles
Beispiel #11
0
def create_giant_molecular_clouds(Ngas, Mgas, Rgas, Nclouds):
    converter = nbody_system.nbody_to_si(Mgas, Rgas)
    clouds = []
    for i in xrange(Nclouds):
        particles = molecular_cloud(targetN=Ngas,
                                    convert_nbody=converter).result
        particles.u = 1. | units.ms**2
        particles.velocity *= 0.6
        particles.move_to_center()
        clouds.append(particles)
    return clouds, converter
def cloud_init(Ngas, Mgas, Rgas, use_plummer=True, seed=1):
    '''Initialises the cloud'''

    np.random.seed(seed)

    converter = nbody_system.nbody_to_si(Mgas, Rgas)
    if use_plummer == True:
        cloud = new_plummer_gas_model(Ngas, convert_nbody=converter)
    else:
        cloud = molecular_cloud(targetN=Ngas, convert_nbody=converter,\
                                base_grid=body_centered_grid_unit_cube).result

    return cloud, converter
Beispiel #13
0
def create_molecular_cloud(N, Mcloud, Rcloud, t_end):

    converter = nbody_system.nbody_to_si(Mcloud,Rcloud)
    parts=molecular_cloud(targetN=N,convert_nbody=converter,
            base_grid=body_centered_grid_unit_cube, seed=100).result
#    parts = new_plummer_gas_model(N, convert_nbody=converter)

    sph=Fi(converter)
    sph.gas_particles.add_particle(parts)

    sph.evolve_model(t_end)
    ch = sph.gas_particles.new_channel_to(parts)
    ch.copy()
    sph.stop()
    return parts
Beispiel #14
0
def create_molecular_cloud(N, Mcloud, Rcloud, t_end):

    converter = nbody_system.nbody_to_si(Mcloud,Rcloud)
    parts=molecular_cloud(targetN=N,convert_nbody=converter,
            base_grid=body_centered_grid_unit_cube, seed=100).result
#    parts = new_plummer_gas_model(N, convert_nbody=converter)

    sph=Fi(converter)
    sph.gas_particles.add_particle(parts)

    sph.evolve_model(t_end)
    ch = sph.gas_particles.new_channel_to(parts)
    ch.copy()
    sph.stop()
    return parts
def run_molecular_cloud(N=100, Mcloud=100. | units.MSun, Rcloud=1. | units.parsec):

    conv = nbody_system.nbody_to_si(Mcloud,Rcloud)
    gas=molecular_cloud(targetN=N,convert_nbody=conv,
            base_grid=body_centered_grid_unit_cube, seed=100).result
    gas.name = "gas"
    
    hydro = Hydro(Fi, gas)

    rho_cloud = 3.*Mcloud/(4.*numpy.pi*Rcloud**3)
    print rho_cloud
    tff = 0.5427/numpy.sqrt(constants.G*rho_cloud)
    print "Freefall timescale=", tff.in_(units.Myr)

    dt = 0.1*tff
    tend=4.0*tff

    i=0
    L=6
    E0 = 0.0
    time = 0.0 | units.Myr

    while time < tend:
        time += dt
        print "Evolve to time=", time.in_(units.Myr)
#        print "N=", len(sph.gas_particles), len(sph.dm_particles)
#        print "Masses of dm particles:", sph.dm_particles.mass.in_(units.MSun)

        hydro.evolve_model(time)
        E = hydro.gas_particles.kinetic_energy()+hydro.gas_particles.potential_energy() + hydro.gas_particles.thermal_energy()
        E_th = hydro.gas_particles.thermal_energy()
        if i==0:
            E0 = E
        Eerr = (E-E0)/E0
        print 'energy=', E, 'energy_error=', Eerr, 'e_th=', E_th
        print "maximal_density:",gas.rho.max().in_(units.MSun/units.parsec**3)

        hydro.write_set_to_file(i)

        i=i+1

    hydro.stop()
    return gas
Beispiel #16
0
def new_molecular_cloud(
    nf=32,
    power=-3.,
    targetN=10000,
    ethep_ratio=0.01,
    convert_nbody=None,
    ekep_ratio=1.,
    seed=None,
    base_grid=None,
):
    return molecular_cloud(
        nf=nf,
        power=power,
        targetN=targetN,
        ethep_ratio=ethep_ratio,
        convert_nbody=convert_nbody,
        ekep_ratio=ekep_ratio,
        seed=seed,
        base_grid=base_grid,
    ).result
def run_mc(N=5000, Mcloud=10000. | units.MSun, Rcloud=1. | units.parsec):
    timestep = 0.005 | units.Myr
    end_time = 0.12 | units.Myr

    conv = nbody_system.nbody_to_si(Mcloud, Rcloud)
    parts = molecular_cloud(targetN=N, convert_nbody=conv,
                            ethep_ratio=0.05, ekep_ratio=0.5).result

    rho_cloud = Mcloud/(4/3.*numpy.pi*Rcloud**3)

    tff = 1/(4*numpy.pi*constants.G*rho_cloud)**0.5
    parts.density = rho_cloud

    update_chem(parts, parts)

    print("Tcloud:", parts.temperature.max().in_(units.K))
    print("cloud n_H:", parts.number_density.max().in_(units.cm**-3))
    print("freefall time:", tff.in_(units.Myr))

    sph = Fi(conv)
    chem = Krome(redirection="none")

    sph.parameters.self_gravity_flag = True
    sph.parameters.use_hydro_flag = True
    sph.parameters.isothermal_flag = True
    sph.parameters.integrate_entropy_flag = False
    sph.parameters.gamma = 1
    sph.parameters.verbosity = 0

    sph.parameters.timestep = timestep/2

    sph.gas_particles.add_particles(parts)
    chem.particles.add_particles(parts)

    tnow = sph.model_time

    f = pyplot.figure()
    pyplot.ion()
    pyplot.show()

    i = 0
    while i < (end_time/timestep+0.5):
        evolve_sph_with_chemistry(sph, chem, i*timestep)
        tnow = sph.model_time
        print("done with step:", i, tnow.in_(units.Myr))
        i += 1

        n = (sph.particles.density/meanmwt).value_in(units.cm**-3)
        fh2 = chem.particles.abundances[:, chem.species["H2"]]
        co = chem.particles.abundances[:, chem.species["CO"]]

        f.clear()
        pyplot.loglog(n, fh2, 'r.')
        pyplot.loglog(n, co, 'g.')
        pyplot.xlim(1.e3, 1.e6)
        pyplot.ylim(1.e-6, 1)
        pyplot.xlabel("density (cm**-3)")
        pyplot.ylabel("H_2,CO abundance")
        pyplot.draw()

    print("done. press key to exit")
    raw_input()
Beispiel #18
0
def run_cloud(x):
    cloud = molecular_cloud(32, -4., x, base_grid=regular_grid_unit_cube)
    mass, x, y, z, vx, vy, vz, u = cloud.new_model()
    smooth = numpy.zeros_like(mass)

    nb = interface.FiInterface(redirection="none")
    nb.initialize_code()

    nb.set_stepout(99999)
    nb.set_steplog(99999)
    nb.set_use_hydro(1)
    nb.set_radiate(0)
    nb.set_dtime(0.05)
    nb.set_gdgop(1)
    nb.set_uentropy(0)
    nb.set_isotherm(1)
    nb.set_gamma(1.0)
    nb.set_verbosity(0)
    nb.set_unitl_in_kpc(0.01)
    nb.set_unitm_in_msun(10000.)

    ids, error = nb.new_sph_particle(mass, x, y, z, vx, vy, vz, u, smooth)
    if filter(lambda x: x != 0, error) != []: raise Exception

    nb.commit_particles()

    if hasattr(nb, "viewer"):
        nb.viewer()

    dt = 0.05
    tnow = 0.
    nb.synchronize_model()
    time, Ek, Ep, Eth = [], [], [], []
    time.append(tnow)
    e, ret = nb.get_kinetic_energy()
    Ek.append(e)
    e, ret = nb.get_potential_energy()
    Ep.append(e)
    e, ret = nb.get_thermal_energy()
    Eth.append(e)

    while tnow < .8:
        tnow = tnow + dt
        nb.evolve_model(tnow)
        nb.synchronize_model()
        tnow, err = nb.get_time()
        time.append(tnow)
        e, ret = nb.get_kinetic_energy()
        Ek.append(e)
        e, ret = nb.get_potential_energy()
        Ep.append(e)
        e, ret = nb.get_thermal_energy()
        Eth.append(e)

    nb.stop()

    time = numpy.array(time)
    Ek = numpy.array(Ek)
    Ep = numpy.array(Ep)
    Eth = numpy.array(Eth)
    energy_plot(time, Ek, Ep, Eth)
Beispiel #19
0
def main():
    numpy.random.seed(42)
    evo_headstart = 0.0 | units.Myr
    dt_base = 0.001 | units.Myr
    dt = dt_base
    time = 0 | units.Myr
    time_end = 8 | units.Myr
    Tmin = 22 | units.K

    gas_density = 5e3 | units.amu * units.cm**-3

    increase_vol = 2

    Ngas = increase_vol**3 * 10000
    Mgas = increase_vol**3 * 1000 | units.MSun  # Mgas = Ngas | units.MSun
    volume = Mgas / gas_density  # 4/3 * pi * r**3
    radius = (volume / (pi * 4/3))**(1/3)
    radius = increase_vol * radius  # 15 | units.parsec

    gasconverter = nbody_system.nbody_to_si(Mgas, radius)
    # gasconverter = nbody_system.nbody_to_si(1 | units.pc, 1 | units.MSun)
    # gasconverter = nbody_system.nbody_to_si(1e10 | units.cm, 1e10 | units.g)

    # NOTE: make stars first - so that it remains the same random
    # initialisation even when we change the number of gas particles
    if len(sys.argv) > 1:
        gas = read_set_from_file(sys.argv[1], "amuse")
        stars = read_set_from_file(sys.argv[2], "amuse")
        stars.position = stars.position * 3
    else:
        # stars = new_star_cluster(
        #     stellar_mass=1000 | units.MSun, effective_radius=3 | units.parsec
        # )
        # stars.velocity = stars.velocity * 2.0
        from amuse.datamodel import Particles
        Nstars = 100
        stars = Particles(Nstars)
        stars.position = [0, 0, 0] | units.pc
        stars.velocity = [0, 0, 0] | units.kms
        stars.mass = new_kroupa_mass_distribution(Nstars, mass_min=1 | units.MSun).reshape(Nstars)
        #  25 | units.MSun
        gas = molecular_cloud(targetN=Ngas, convert_nbody=gasconverter).result
        # gas.velocity = gas.velocity * 0.5
        gas.u = temperature_to_u(100 | units.K)
    # gas.x = gas.x
    # gas.y = gas.y
    # gas.z = gas.z
    # gas.h_smooth = (gas.mass / gas_density / (4/3) / pi)**(1/3)
    # print(gas.h_smooth.mean())
    # gas = read_set_from_file("gas_initial.hdf5", "amuse")
    # gas.density = gas_density
    # print(gas.h_smooth.mean())
    # exit()
    u_now = gas.u
    #print(gasconverter.to_nbody(gas[0].u))
    #print(constants.kB.value_in(units.erg * units.K**-1))
    #print((constants.kB * 6.02215076e23).value_in(units.erg * units.K**-1))

    #print(gasconverter.to_nbody(temperature_to_u(10 | units.K)))
    #tempiso = 2.d0/3.d0*ui/(Rg/gmwvar/uergg)
    # print(nbody_system.length**2 / nbody_system.time**2)
    # print(gasconverter.to_si(1 | nbody_system.length**2 / nbody_system.time**2).value_in(units.kms**2))
    # print(gasconverter.to_nbody(temperature_to_u(Tmin)))
    # Rg = (constants.kB * 6.02214076e23).value_in(units.erg * units.K**-1)
    # gmwvar = 1.2727272727
    # uergg = nbody_system.length**2 * nbody_system.time**-2
    # uergg = 6.6720409999999996E-8
    # print(Rg)
    # print(
    #     2.0/3.0*gasconverter.to_nbody(temperature_to_u(Tmin))/(Rg/gmwvar/uergg)
    # )
    # #tempiso, ui, Rg, gmwvar, uergg, udist, utime   1.7552962911187030E-018   2.5778500859241771E-003   83140000.000000000        1.2727272727272725        6.6720409999999996E-008   1.0000000000000000        3871.4231866737564
    # u = 3./2. * Tmin.value_in(units.K) * (Rg/gmwvar/uergg)
    # print(u)
    # print(
    #     2.0/3.0*u/(Rg/gmwvar/uergg)
    # )
    # print(u, Rg, gmwvar, uergg)
    # print(temperature_to_u(10 | units.K).value_in(units.kms**2))
    u = temperature_to_u(20 | units.K)
    #print(gasconverter.to_nbody(u))
    #print(u_to_temperature(u).value_in(units.K))
    # exit()
    # gas.u = u | units.kms**2
    # exit()
    
    # print(gasconverter.to_nbody(gas.u.mean()))
    # print(gasconverter.to_si(gas.u.mean()).value_in(units.kms**2))
    # exit()
    gas.du_dt = (u_now - u_now) / dt  # zero, but in the correct units

    # stars = read_set_from_file("stars.amuse", "amuse")
    # write_set_to_file(stars, 'stars.amuse', 'amuse', append_to_file=False)
    # stars.velocity *= 3
    # stars.vx += 0 | units.kms
    # stars.vy += 0 | units.kms

    M = stars.total_mass() + Mgas
    R = stars.position.lengths().mean()
    converter = nbody_system.nbody_to_si(M, R)
    # exit()
    # gas = new_plummer_gas_model(Ngas, gasconverter)
    # gas = molecular_cloud(targetN=Ngas, convert_nbody=gasconverter).result
    # gas.u = temperature_to_u(Tmin)
    # gas = read_set_from_file("gas.amuse", "amuse")
    # print(stars.mass == stars.mass.max())
    print(len(stars.mass))
    print(len(stars.mass == stars.mass.max()))
    print(stars[0])
    print(stars[stars.mass == stars.mass.max()])
    mms = stars[stars.mass == stars.mass.max()]
    print("Most massive star: %s" % mms.mass)
    print("Gas particle mass: %s" % gas[0].mass)

    evo = SeBa()
    # sph = Fi(converter, mode="openmp")
    phantomconverter = nbody_system.nbody_to_si(
        default_settings.gas_rscale,
        default_settings.gas_mscale,
    )
    sph = Phantom(phantomconverter, redirection="none")
    sph.parameters.ieos = 2
    sph.parameters.icooling = 1
    sph.parameters.alpha = 0.1
    sph.parameters.gamma = 5/3
    sph.parameters.rho_crit = 1e17 | units.amu * units.cm**-3
    sph.parameters.h_soft_sinkgas = 0.1 | units.parsec
    sph.parameters.h_soft_sinksink = 0.1 | units.parsec
    sph.parameters.h_acc = 0.1 | units.parsec
    # print(sph.parameters)

    stars_in_evo = evo.particles.add_particles(stars)
    channel_stars_evo_from_code = stars_in_evo.new_channel_to(
        stars,
        attributes=[
            "age", "radius", "mass", "luminosity", "temperature",
            "stellar_type",
        ],
    )
    channel_stars_evo_from_code.copy()

    # try:
    #     sph.parameters.timestep = dt
    # except:
    #     print("SPH code doesn't support setting the timestep")
    sph.parameters.stopping_condition_maximum_density = \
        5e-16 | units.g * units.cm**-3
    # sph.parameters.beta = 1.
    # sph.parameters.C_cour = sph.parameters.C_cour / 4
    # sph.parameters.C_force = sph.parameters.C_force / 4
    print(sph.parameters)
    stars_in_sph = stars.copy()  # sph.sink_particles.add_particles(stars)
    # stars_in_sph = sph.sink_particles.add_particles(stars)
    channel_stars_grav_to_code = stars.new_channel_to(
        # sph.sink_particles,
        # sph.dm_particles,
        stars_in_sph,
        attributes=["mass"]
    )
    channel_stars_grav_from_code = stars_in_sph.new_channel_to(
        stars,
        attributes=["x", "y", "z", "vx", "vy", "vz"],
    )
    # We don't want to accrete gas onto the stars/sinks
    stars_in_sph.radius = 0 | units.RSun
    # stars_in_sph = sph.dm_particles.add_particles(stars)
    # try:
    #     sph.parameters.isothermal_flag = True
    #     sph.parameters.integrate_entropy_flag = False
    #     sph.parameters.gamma = 1
    # except:
    #     print("SPH code doesn't support setting isothermal flag")
    gas_in_code = sph.gas_particles.add_particles(gas)
    # print(gasconverter.to_nbody(gas_in_code[0].u).value_in(nbody_system.specific_energy))
    # ui = temperature_to_u(10 | units.K)
    # Rg = constants.kB * 6.02214179e+23
    # gmwvar = (1.4/1.1) | units.g
    # uergg = 1.# | nbody_system.specific_energy
    # print("gmwvar = %s"%gasconverter.to_si(gmwvar))
    # print("Rg = %s"% gasconverter.to_si(Rg))
    # print("ui = %s"% gasconverter.to_si(ui))
    # #print("uergg = %s"% gasconverter.to_nbody(uergg))
    # print("uergg = %s" % gasconverter.to_si(1 | nbody_system.specific_energy).in_(units.cm**2 * units.s**-2))
    # print("****** %s" % ((2.0/3.0)*ui/(Rg/gmwvar/uergg)) + "*****")
    # print(gasconverter.to_nbody(Rg))
    # print((ui).in_(units.cm**2*units.s**-2))
    # #exit()
    
    # sph.evolve_model(1 | units.day)
    # write_set_to_file(sph.gas_particles, "gas_initial.hdf5", "amuse")
    # exit()

    channel_gas_to_code = gas.new_channel_to(
        gas_in_code,
        attributes=[
            "x", "y", "z", "vx", "vy", "vz", "u",
        ]
    )
    # mass is never updated, and if sph is in isothermal mode u is not reliable
    channel_gas_from_code = gas_in_code.new_channel_to(
        gas,
        attributes=[
            "x", "y", "z", "vx", "vy", "vz", "density", "pressure", "rho",
            "u", "h_smooth",
        ],
    )
    channel_gas_from_code.copy()  # Initialise values for density etc

    sph_particle_mass = gas[0].mass  # 0.1 | units.MSun
    r_max = 0.1 | units.parsec

    wind = stellar_wind.new_stellar_wind(
        sph_particle_mass,
        mode="heating",
        r_max=r_max,
        derive_from_evolution=True,
        tag_gas_source=True,
        # target_gas=gas,
        # timestep=dt,
    )
    stars_in_wind = wind.particles.add_particles(stars)
    channel_stars_wind_to_code = stars.new_channel_to(
        stars_in_wind,
        attributes=[
            "x", "y", "z", "vx", "vy", "vz", "age", "radius", "mass",
            "luminosity", "temperature", "stellar_type",
        ],
    )
    channel_stars_wind_to_code.copy()


    # reference_mu = 2.2 | units.amu
    gasvolume = (4./3.) * numpy.pi * (
        gas.position - gas.center_of_mass()
    ).lengths().mean()**3
    rho0 = gas.total_mass() / gasvolume
    print(rho0.value_in(units.g * units.cm**-3))
    # exit()
    # cooling_flag = "thermal_model"
    # cooling = Cooling(
    cooling = SimplifiedThermalModelEvolver(
        # gas_in_code,
        gas,
        Tmin=Tmin,
        # T0=30 | units.K,
        # n0=rho0/reference_mu
    )
    cooling.model_time = sph.model_time
    # cooling_to_code = cooling.particles.new_channel_to(gas

    start_mass = (
        stars.mass.sum()
        + (gas.mass.sum() if not gas.is_empty() else 0 | units.MSun)
    )
    step = 0
    plotnr = 0
    com = stars_in_sph.center_of_mass()
    plot_hydro_and_stars(
        time,
        sph,
        stars=stars,
        sinks=None,
        L=20,
        # N=100,
        filename="phantom-coolthermalwindtestplot-%04i.png" % step,
        title="time = %06.2f %s" % (time.value_in(units.Myr), units.Myr),
        gasproperties=["density", "temperature"],
        # colorbar=True,
        starscale=1,
        offset_x=com[0].value_in(units.parsec),
        offset_y=com[1].value_in(units.parsec),
        thickness=5 | units.parsec,
    )

    dt = dt_base
    sph.parameters.time_step = dt
    delta_t = phantomconverter.to_si(2**(-16) | nbody_system.time)
    print("delta_t: %s" % delta_t.in_(units.day))
    # small_step = True
    small_step = False
    plot_every = 100
    subplot_factor = 10
    subplot_enabled = False
    subplot = 0
    while time < time_end:
        time += dt
        print("Gas mean u: %s" % (gas.u.mean().in_(units.erg/units.MSun)))
        print("Evolving to t=%s (%s)" % (time, gasconverter.to_nbody(time)))
        step += 1
        evo.evolve_model(evo_headstart+time)

        print(evo.particles.stellar_type.max())
        channel_stars_evo_from_code.copy()
        channel_stars_grav_to_code.copy()

        if COOLING:
            channel_gas_from_code.copy()
            cooling.evolve_for(dt/2)
            channel_gas_to_code.copy()
        print(
            "min/max temp in gas: %s %s" % (
                u_to_temperature(gas_in_code.u.min()).in_(units.K),
                u_to_temperature(gas_in_code.u.max()).in_(units.K),
            )
        )
        if small_step:
            # Take small steps until a full timestep is done.
            # Each substep is 2* as long as the last until dt is reached
            print("Doing small steps")
            # print(u_to_temperature(sph.gas_particles[0].u))
            # print(sph.gas_particles[0].u)
            old_dt = dt_base
            substeps = 2**8
            dt = old_dt / substeps
            dt_done = 0 * old_dt
            sph.parameters.time_step = dt
            print("adjusted dt to %s, base dt is %s" % (
                dt.in_(units.Myr),
                dt_base.in_(units.Myr),
                )
            )
            sph.evolve_model(sph.model_time + dt)
            dt_done += dt
            while dt_done < old_dt:
                sph.parameters.time_step = dt
                print("adjusted dt to %s, base dt is %s" % (
                    dt.in_(units.Myr),
                    dt_base.in_(units.Myr),
                    )
                )
                sph.evolve_model(sph.model_time + dt)
                dt_done += dt
                dt = min(2*dt, old_dt-dt_done)
                dt = max(dt, old_dt/substeps)
            dt = dt_base
            sph.parameters.time_step = dt
            print(
                "adjusted dt to %s" % sph.parameters.time_step.in_(units.Myr)
            )
            small_step = False
            print("Finished small steps")
            # print(u_to_temperature(sph.gas_particles[0].u))
            # print(sph.gas_particles[0].u)
            # exit()
        else:
            sph.evolve_model(time)
        channel_gas_from_code.copy()
        channel_stars_grav_from_code.copy()
        u_previous = u_now
        u_now = gas.u
        gas.du_dt = (u_now - u_previous) / dt

        channel_stars_wind_to_code.copy()
        wind.evolve_model(time)
        # channel_stars_wind_from_code.copy()
        if COOLING:
            channel_gas_from_code.copy()
            cooling.evolve_for(dt/2)
            channel_gas_to_code.copy()

        if wind.has_new_wind_particles():
            subplot_enabled = True
            wind_p = wind.create_wind_particles()
            # nearest = gas.find_closest_particle_to(wind_p.x, wind_p.y, wind_p.z)
            # wind_p.h_smooth = nearest.h_smooth
            wind_p.h_smooth = 100 | units.au
            print("u: %s / T: %s" % (wind_p.u.mean(), u_to_temperature(wind_p.u.mean())))
            # max_e = (1e44 | units.erg) / wind_p[0].mass
            # max_e = 10 * gas.u.mean()
            # max_e = (1.e48 | units.erg) / wind_p[0].mass
            # wind_p[wind_p.u > max_e].u = max_e
            # wind_p[wind_p.u > max_e].h_smooth = 0.1 | units.parsec
            # print(wind_p.position)
            print(
                "time: %s, wind energy: %s"
                % (time, (wind_p.u * wind_p.mass).sum())
            )
            print(
                "wind temperature: %s"
                % (u_to_temperature(wind_p.u))
            )
            print(
                "gas particles: %i (total mass %s)"
                % (len(wind_p), wind_p.total_mass())
            )
            # for windje in wind_p:
            #     # print(windje)
            #     source = stars[stars.key == windje.source][0]
            #     windje.position += source.position
            #     windje.velocity += source.velocity
            #     # print(source)
            #     # print(windje)
            # # exit()
            gas.add_particles(wind_p)
            gas_in_code.add_particles(wind_p)
            # for wp in wind_p:
            #     print(wp)
            print("Wind particles added")
            if True:  # wind_p.u.max() > gas_in_code.u.max():
                print("Setting dt to very short")
                small_step = True  # dt = 0.1 | units.yr
                h_min = gas.h_smooth.min()
                # delta_t = determine_short_timestep(sph, wind_p, h_min=h_min)
                # print("delta_t is set to %s" % delta_t.in_(units.yr))
        # else:
        #     small_step = True
        print(
            "time: %s sph: %s dM: %s" % (
                time.in_(units.Myr),
                sph.model_time.in_(units.Myr),
                (
                    stars.total_mass()
                    + (
                        gas.total_mass()
                        if not gas.is_empty()
                        else (0 | units.MSun)
                    )
                    - start_mass
                )
            )
        )
        # com = sph.sink_particles.center_of_mass()
        # com = sph.dm_particles.center_of_mass()
        com = stars.center_of_mass()
        print("STEP: %i step%%plot_every: %i" % (step, step % plot_every))
        if step % plot_every == 0:
            plotnr = plotnr + 1
            plot_hydro_and_stars(
                time,
                sph,
                # stars=sph.sink_particles,
                # stars=sph.dm_particles,
                stars=stars,
                sinks=None,
                L=20,
                # N=100,
                # image_size_scale=10,
                filename="phantom-coolthermalwindtestplot-%04i.png" % plotnr,  # int(step/plot_every),
                title="time = %06.2f %s" % (time.value_in(units.Myr), units.Myr),
                gasproperties=["density", "temperature"],
                # colorbar=True,
                starscale=1,
                offset_x=com[0].value_in(units.parsec),
                offset_y=com[1].value_in(units.parsec),
                thickness=5 | units.parsec,
            )
            # write_set_to_file(gas, "gas.amuse", "amuse", append_to_file=False)
            # write_set_to_file(stars, "stars.amuse", "amuse", append_to_file=False)
        elif (
                subplot_enabled
                and ((step % (plot_every/subplot_factor)) == 0)
        ):
            plotnr = plotnr + 1
            subplot += 1
            plot_hydro_and_stars(
                time,
                sph,
                # stars=sph.sink_particles,
                # stars=sph.dm_particles,
                stars=stars,
                sinks=None,
                L=20,
                # N=100,
                # image_size_scale=10,
                filename="phantom-coolthermalwindtestplot-%04i.png" % plotnr,  # int(step/plot_every),
                title="time = %06.2f %s" % (time.value_in(units.Myr), units.Myr),
                gasproperties=["density", "temperature"],
                # colorbar=True,
                starscale=1,
                offset_x=com[0].value_in(units.parsec),
                offset_y=com[1].value_in(units.parsec),
                thickness=5 | units.parsec,
            )
            if subplot % subplot_factor == 0:
                subplot_enabled = False
        print(
            "Average temperature of gas: %s" % (
                u_to_temperature(gas.u).mean().in_(units.K)
            )
        )
    return
Beispiel #20
0
def run_molecular_cloud(N=100,
                        Mcloud=100. | units.MSun,
                        Rcloud=1. | units.parsec):

    conv = nbody_system.nbody_to_si(Mcloud, Rcloud)

    rho_cloud = 3. * Mcloud / (4. * numpy.pi * Rcloud**3)
    print rho_cloud
    tff = 0.5427 / numpy.sqrt(constants.G * rho_cloud)
    print "t_ff=", tff.value_in(units.Myr), 'Myr'

    dt = 5.e-2 | units.Myr
    tend = 1.0 | units.Myr
    #    tend=2.0 | units.Myr

    parts = molecular_cloud(targetN=N,
                            convert_nbody=conv,
                            base_grid=body_centered_grid_unit_cube,
                            seed=100).result

    sph = Fi(conv, number_of_workers=3)
    sph.parameters.use_hydro_flag = True
    sph.parameters.radiation_flag = False
    sph.parameters.gamma = 1
    sph.parameters.isothermal_flag = True
    sph.parameters.integrate_entropy_flag = False
    sph.parameters.timestep = dt
    sph.parameters.verbosity = 0
    sph.parameters.eps_is_h_flag = False  # h_smooth is constant
    eps = 0.1 | units.parsec
    sph.parameters.gas_epsilon = eps
    sph.parameters.sph_h_const = eps
    parts.h_smooth = eps

    print 'eps-h flag', sph.get_eps_is_h(), sph.get_consthsm()

    expected_dt = 0.2 * numpy.pi * numpy.power(eps, 1.5) / numpy.sqrt(
        constants.G * Mcloud / N)

    print "dt_exp=", expected_dt.value_in(units.Myr)
    print "dt=", dt
    print "eps=", sph.parameters.gas_epsilon.in_(units.parsec)

    sph.gas_particles.add_particles(parts)

    #grav=copycat(Fi, sph, conv)
    #sys=bridge(verbose=False)
    #sys.add_system(sph,(grav,),False)
    channel_from_sph_to_parts = sph.gas_particles.new_channel_to(parts)
    channel_from_parts_to_sph = parts.new_channel_to(sph.gas_particles)

    i = 0
    L = 6
    E0 = 0.0
    ttarget = 0.0 | units.Myr

    plot_hydro(ttarget, sph, i, L)

    while ttarget < tend:
        ttarget = float(i) * dt
        print ttarget
        sph.evolve_model(ttarget, timestep=dt)
        E = sph.gas_particles.kinetic_energy(
        ) + sph.gas_particles.potential_energy(
        ) + sph.gas_particles.thermal_energy()
        E_th = sph.gas_particles.thermal_energy()
        if i == 0:
            E0 = E
        Eerr = (E - E0) / E0
        print 'energy=', E, 'energy_error=', Eerr, 'e_th=', E_th
        channel_from_sph_to_parts.copy()
        """
        filename = 'm400k_r10pc_e01_'+ str(i).zfill(2) + '.dat'
        print filename
        parts_sorted = parts.sorted_by_attribute('rho')
        write_output(filename, parts_sorted, conv)        
        """
        plot_hydro(ttarget, sph, i, L)
        i = i + 1

    plot_hydro_and_stars(ttarget, sph, L)

    sph.stop()
    return parts
def run_mc(N=5000, Mcloud=10000. | units.MSun, Rcloud=1. | units.parsec):
    timestep = 0.005 | units.Myr
    end_time = 0.12 | units.Myr

    conv = nbody_system.nbody_to_si(Mcloud, Rcloud)
    parts = molecular_cloud(targetN=N,
                            convert_nbody=conv,
                            ethep_ratio=0.05,
                            ekep_ratio=0.5).result

    rho_cloud = Mcloud / (4 / 3. * numpy.pi * Rcloud**3)

    tff = 1 / (4 * numpy.pi * constants.G * rho_cloud)**0.5
    parts.density = rho_cloud

    update_chem(parts, parts)

    print("Tcloud:", parts.temperature.max().in_(units.K))
    print("cloud n_H:", parts.number_density.max().in_(units.cm**-3))
    print("freefall time:", tff.in_(units.Myr))

    sph = Fi(conv)
    chem = Krome(redirection="none")

    sph.parameters.self_gravity_flag = True
    sph.parameters.use_hydro_flag = True
    sph.parameters.isothermal_flag = True
    sph.parameters.integrate_entropy_flag = False
    sph.parameters.gamma = 1
    sph.parameters.verbosity = 0

    sph.parameters.timestep = timestep / 2

    sph.gas_particles.add_particles(parts)
    chem.particles.add_particles(parts)

    tnow = sph.model_time

    f = pyplot.figure()
    pyplot.ion()
    pyplot.show()

    i = 0
    while i < (end_time / timestep + 0.5):
        evolve_sph_with_chemistry(sph, chem, i * timestep)
        tnow = sph.model_time
        print("done with step:", i, tnow.in_(units.Myr))
        i += 1

        n = (sph.particles.density / meanmwt).value_in(units.cm**-3)
        fh2 = chem.particles.abundances[:, chem.species["H2"]]
        co = chem.particles.abundances[:, chem.species["CO"]]

        f.clear()
        pyplot.loglog(n, fh2, 'r.')
        pyplot.loglog(n, co, 'g.')
        pyplot.xlim(1.e3, 1.e6)
        pyplot.ylim(1.e-6, 1)
        pyplot.xlabel("density (cm**-3)")
        pyplot.ylabel("H_2,CO abundance")
        pyplot.draw()

    print("done. press key to exit")
    raw_input()
Beispiel #22
0
from amuse.ext.evrard_test import body_centered_grid_unit_cube
from amuse.community.simplex.interface import SimpleX

Mcloud = 1000. | units.MSun
Rcloud = 3. | units.pc
Tcloud = 100. | units.K

N = 1000

sigma = 0.01 | units.pc

box_size = 10. | units.pc

converter = nbody_system.nbody_to_si(Mcloud, Rcloud)
gas_particles = molecular_cloud(targetN=N,
                                convert_nbody=converter,
                                base_grid=body_centered_grid_unit_cube).result

gas_particles.x += np.random.normal(size=len(gas_particles)) * sigma
gas_particles.y += np.random.normal(size=len(gas_particles)) * sigma
gas_particles.z += np.random.normal(size=len(gas_particles)) * sigma

gas_particles.flux = 0. | units.s**-1
gas_particles.u = (Tcloud * constants.kB) / (1.008 * constants.u)
gas_particles.rho = Mcloud / (4. / 3. * np.pi * Rcloud**3)

gas_particles.xion = 0.

radiative = SimpleX(redirection='none', number_of_workers=8)

radiative.parameters.blackbody_spectrum_flag = True
def run_molecular_cloud(N=100, Mcloud=100. | units.MSun,
                        Rcloud=1. | units.parsec):

    conv = nbody_system.nbody_to_si(Mcloud,Rcloud)

    rho_cloud = 3.*Mcloud/(4.*numpy.pi*Rcloud**3)
    print rho_cloud
    tff = 0.5427/numpy.sqrt(constants.G*rho_cloud)
    print "t_ff=", tff.value_in(units.Myr), 'Myr'

    dt = 5.e-2 | units.Myr
    t_end = 1.0 | units.Myr

    parts = molecular_cloud(targetN=N,convert_nbody=conv,
                            base_grid=body_centered_grid_unit_cube,
                            seed=100).result

    sph = Fi(conv)
    sph.parameters.use_hydro_flag = True
    sph.parameters.radiation_flag = False
    sph.parameters.gamma = 1
    sph.parameters.isothermal_flag = True
    sph.parameters.integrate_entropy_flag = False
    sph.parameters.timestep = dt  
    sph.parameters.verbosity = 0
    sph.parameters.eps_is_h_flag = False    # h_smooth is constant
    eps = 0.1 | units.parsec
    sph.parameters.gas_epsilon = eps
    sph.parameters.sph_h_const = eps
    parts.h_smooth= eps

    print 'eps-h flag', sph.get_eps_is_h(), sph.get_consthsm()

    expected_dt = 0.2*numpy.pi*numpy.power(eps, 1.5) \
                   / numpy.sqrt(constants.G*Mcloud/N)

    print "dt_exp=", expected_dt.value_in(units.Myr)
    print "dt=", dt
    print "eps=", sph.parameters.gas_epsilon.in_(units.parsec)

    sph.gas_particles.add_particles(parts)

    channel_from_sph_to_parts= sph.gas_particles.new_channel_to(parts)
    channel_from_parts_to_sph= parts.new_channel_to(sph.gas_particles)
    
    i = 0
    L = 6
    E0 = 0.0
    ttarget = 0.0 | units.Myr

    plot_hydro(ttarget, sph, i, L)

    while ttarget < t_end:
        ttarget = float(i)*dt
        print ttarget
        sph.evolve_model(ttarget, timestep=dt)
        E = sph.gas_particles.kinetic_energy() \
             + sph.gas_particles.potential_energy() \
             + sph.gas_particles.thermal_energy()
        E_th = sph.gas_particles.thermal_energy()
        if i == 0:
            E0 = E
        Eerr = (E-E0)/E0
        print 'energy=', E, 'energy_error=', Eerr, 'e_th=', E_th
        channel_from_sph_to_parts.copy()
        plot_hydro(ttarget, sph, i, L)
        i += 1

    sph.stop()
    return parts
def run_molecular_cloud(N=100, Mcloud=100. | units.MSun,
                        Rcloud=1. | units.parsec):

    conv = nbody_system.nbody_to_si(Mcloud,Rcloud)
    gas=molecular_cloud(targetN=N,convert_nbody=conv,
            base_grid=body_centered_grid_unit_cube).result
    gas.name = "gas"

    rho_cloud = Mcloud/Rcloud**3
    tff = 0.5427/numpy.sqrt(constants.G*rho_cloud)
    print "Freefall timescale=", tff.in_(units.Myr)

    stars = Particles(0)
    hydro = Hydro(Fi, gas, stars)

    rho_cloud = 3.*Mcloud/(4.*numpy.pi*Rcloud**3)
    print rho_cloud

    dt = 0.02 | units.Myr
    tend= 10.0 | units.Myr
    dt_diag = 0.1 | units.Myr
    t_diag = 0 | units.Myr

    i=0
    E0 = 0.0
    time = 0.0 | units.Myr

    while time < tend:
        time += dt
        print "Evolve to time=", time.in_(units.Myr)
        Mtot = 0|units.MSun
        if len(hydro.star_particles) > 0:
            print "Mass conservation: Slocal:", time.in_(units.Myr), \
                  hydro.gas_particles.mass.sum().in_(units.MSun), \
                  hydro.star_particles.mass.sum().in_(units.MSun), \
                  "sum=", (hydro.gas_particles.mass.sum() \
                            + hydro.star_particles.mass.sum()).in_(units.MSun)
            print "Mass conservation: Shydro:", time.in_(units.Myr), \
                  hydro.code.gas_particles.mass.sum().in_(units.MSun), \
                  hydro.code.dm_particles.mass.sum().in_(units.MSun), \
                  "sum=", \
                  (hydro.code.gas_particles.mass.sum() \
                    + hydro.code.dm_particles.mass.sum()).in_(units.MSun), \
                    "S=", hydro.star_particles.mass.sum().in_(units.MSun)
            Mtot = hydro.gas_particles.mass.sum() \
                    + hydro.star_particles.mass.sum()
        else:
            print "Mass conservation: local:", time.in_(units.Myr), \
                  hydro.gas_particles.mass.sum().in_(units.MSun) 
            print "Mass conservation: hydro:", time.in_(units.Myr), \
                  hydro.code.gas_particles.mass.sum().in_(units.MSun)
            Mtot = hydro.gas_particles.mass.sum()

        if Mtot < Mcloud-(1.e-5|units.MSun):
            print "Mass is not conserved:", Mtot.in_(units.MSun), \
                  Mcloud.in_(units.MSun)
            exit(-1)

        hydro.evolve_model(time)
        E = hydro.gas_particles.kinetic_energy() \
             + hydro.gas_particles.potential_energy() \
             + hydro.gas_particles.thermal_energy()
        E_th = hydro.gas_particles.thermal_energy()
        if i==0:
            E0 = E
        Eerr = (E-E0)/E0
        print 'energy=', E, 'energy_error=', Eerr, 'e_th=', E_th
        print "maximal_density:",gas.rho.max().in_(units.MSun/units.parsec**3)

        hydro.print_diagnostics()
        if time>t_diag:
            t_diag += dt_diag
            hydro.write_set_to_file(i)
            i=i+1

    hydro.stop()
    return gas
Beispiel #25
0
def run_molecular_cloud(N=100,
                        Mcloud=100. | units.MSun,
                        Rcloud=1. | units.parsec):

    conv = nbody_system.nbody_to_si(Mcloud, Rcloud)
    gas = molecular_cloud(targetN=N,
                          convert_nbody=conv,
                          base_grid=body_centered_grid_unit_cube).result
    gas.name = "gas"

    rho_cloud = Mcloud / Rcloud**3
    tff = 0.5427 / numpy.sqrt(constants.G * rho_cloud)
    print "Freefall timescale=", tff.in_(units.Myr)
    #omega = 1./tff
    #print "Omega=", omega.in_(units.yr**-1)
    #gas.add_spin(omega)

    stars = Particles(0)

    hydro = Hydro(Fi, gas, stars)

    rho_cloud = 3. * Mcloud / (4. * numpy.pi * Rcloud**3)
    print rho_cloud

    #    dt = 0.1*tff
    #    tend=40.0*tff
    dt = 0.02 | units.Myr
    tend = 10.0 | units.Myr
    dt_diag = 0.1 | units.Myr
    t_diag = 0 | units.Myr

    i = 0
    E0 = 0.0
    time = 0.0 | units.Myr

    while time < tend:
        time += dt
        print "Evolve to time=", time.in_(units.Myr)
        #        print "N=", len(sph.gas_particles), len(sph.dm_particles)
        #        print "Masses of dm particles:", sph.dm_particles.mass.in_(units.MSun)

        hydro.evolve_model(time)
        E = hydro.gas_particles.kinetic_energy(
        ) + hydro.gas_particles.potential_energy(
        ) + hydro.gas_particles.thermal_energy()
        E_th = hydro.gas_particles.thermal_energy()
        if i == 0:
            E0 = E
        Eerr = (E - E0) / E0
        print 'energy=', E, 'energy_error=', Eerr, 'e_th=', E_th
        print "maximal_density:", gas.rho.max().in_(units.MSun /
                                                    units.parsec**3)

        hydro.print_diagnostics()
        if time > t_diag:
            t_diag += dt_diag
            hydro.write_set_to_file(i)
            i = i + 1

    hydro.stop()
    return gas
Beispiel #26
0
def run_mc(N=5000,Mcloud=10000. | units.MSun,Rcloud=1. | units.parsec):

    conv = nbody_system.nbody_to_si(Mcloud,Rcloud)

    interaction_timestep = 0.01 | units.Myr
    time_end=0.36 | units.Myr

    parts=molecular_cloud(targetN=N,convert_nbody=conv,
            base_grid=body_centered_grid_unit_cube).result

    sph=Fi(conv)

    # need to turn off self gravity, the bridge will calculate this
    sph.parameters.self_gravity_flag=False
    
    # some typical Fi flags (just for reference, most are default values)
    sph.parameters.use_hydro_flag=True
    sph.parameters.isothermal_flag=True
    sph.parameters.integrate_entropy_flag=False
    sph.parameters.gamma=1
    sph.parameters.verbosity = 0
    
    # setting the hydro timestep is important
    # the sph code will take 2 timesteps every interaction timestep
    sph.parameters.timestep=interaction_timestep/2  

    sph.gas_particles.add_particles(parts)

    def new_code_to_calculate_gravity_of_gas_particles():
        result = BHTree(conv)
        return result
        
    calculate_gravity_code=bridge.CalculateFieldForCodes(
        new_code_to_calculate_gravity_of_gas_particles,  # the code that calculates the acceleration field
        input_codes = [sph] # the codes to calculate the acceleration field of
    )
    
    bridged_system = bridge.Bridge()
    bridged_system.timestep=interaction_timestep

    bridged_system.add_system(
        sph,                     # the code to move the particles of
        [calculate_gravity_code] # the codes that provide the acceleration field
    )

    fig=pyplot.figure(figsize=(12,12))

    ncolumn=2
    nrow=2
    nplot=ncolumn*nrow

    grid_size = 3 | units.parsec
    extent = (grid_size * (-0.5, 0.5, -0.5, 0.5)).value_in(units.parsec)
    
    if nplot > 1:
        plot_timestep = time_end / (nplot - 1)
    else:
        plot_timestep = time_end
        
    for i in range(nplot):
        ttarget=i*plot_timestep
        print("evolving to time:", ttarget.as_quantity_in(units.Myr))
        bridged_system.evolve_model(ttarget) 
        
        rho=make_map(sph,N=200,grid_size=grid_size)
        subplot=fig.add_subplot(ncolumn,nrow,i+1)
        subplot.imshow(
            numpy.log10(1.e-5+rho.value_in(units.amu/units.cm**3)),
            extent = extent,
            vmin=1,
            vmax=5
        )
        subplot.set_title(ttarget.as_quantity_in(units.Myr))
    
    sph.stop()
    pyplot.show()
def run_molecular_cloud(N=100, Mcloud=100. | units.MSun, Rcloud=1. | units.parsec):

    conv = nbody_system.nbody_to_si(Mcloud,Rcloud)

    rho_cloud = 3.*Mcloud/(4.*numpy.pi*Rcloud**3)
    print rho_cloud
    tff = 0.5427/numpy.sqrt(constants.G*rho_cloud)
    print "t_ff=", tff.value_in(units.Myr), 'Myr'

    dt = 5.e-2 | units.Myr
    tend=1.0 | units.Myr

    parts=molecular_cloud(targetN=N,convert_nbody=conv,
            base_grid=body_centered_grid_unit_cube, seed=100).result

    #sph=Fi(conv, number_of_workers=3)
    sph=Fi(conv)
    sph.parameters.use_hydro_flag=True
    sph.parameters.radiation_flag=False
    sph.parameters.gamma=1
    sph.parameters.isothermal_flag=True
    sph.parameters.integrate_entropy_flag=False
    sph.parameters.timestep=dt  
    sph.parameters.verbosity = 0
    sph.parameters.eps_is_h_flag = False# h_smooth is constant
    eps = 0.1 | units.parsec
    sph.parameters.gas_epsilon = eps
    sph.parameters.sph_h_const = eps
    parts.h_smooth= eps

    print 'eps-h flag', sph.get_eps_is_h(), sph.get_consthsm()

    expected_dt = 0.2*numpy.pi*numpy.power(eps, 1.5)/numpy.sqrt(constants.G*Mcloud/N)

    print "dt_exp=", expected_dt.value_in(units.Myr)
    print "dt=", dt
    print "eps=", sph.parameters.gas_epsilon.in_(units.parsec)

    sph.gas_particles.add_particles(parts)

    channel_from_sph_to_parts= sph.gas_particles.new_channel_to(parts)
    channel_from_parts_to_sph= parts.new_channel_to(sph.gas_particles)

    i=0
    L=6
    E0 = 0.0
    ttarget = 0.0 | units.Myr

    plot_hydro(ttarget, sph, i, L)

    while ttarget < tend:
        ttarget=float(i)*dt
        print ttarget
        sph.evolve_model(ttarget, timestep=dt)
        E = sph.gas_particles.kinetic_energy()+sph.gas_particles.potential_energy() + sph.gas_particles.thermal_energy()
        E_th = sph.gas_particles.thermal_energy()
        if i==0:
            E0 = E
        Eerr = (E-E0)/E0
        print 'energy=', E, 'energy_error=', Eerr, 'e_th=', E_th
        channel_from_sph_to_parts.copy()
        """
        filename = 'm400k_r10pc_e01_'+ str(i).zfill(2) + '.dat'
        print filename
        parts_sorted = parts.sorted_by_attribute('rho')
        write_output(filename, parts_sorted, conv)        
        """
        plot_hydro(ttarget, sph, i, L)
        i=i+1

    sph.stop()
    return parts
Beispiel #28
0
def run_cloud(x):
    cloud = molecular_cloud(32, -4., x, base_grid=regular_grid_unit_cube)
    mass, x, y, z, vx, vy, vz, u = cloud.new_model()
    smooth = numpy.zeros_like(mass)

    nb = interface.FiInterface(redirection="none")
    nb.initialize_code()

    nb.set_stepout(99999)
    nb.set_steplog(99999)
    nb.set_use_hydro(1)
    nb.set_radiate(0)
    nb.set_dtime(0.05)
    nb.set_gdgop(1)
    nb.set_uentropy(0)
    nb.set_isotherm(1)
    nb.set_gamma(1.0)
    nb.set_verbosity(0)
    nb.set_unitl_in_kpc(0.01)
    nb.set_unitm_in_msun(10000.)

    ids, error = nb.new_sph_particle(mass, x, y, z, vx, vy, vz, u, smooth)
    if filter(lambda x: x != 0, error) != []: raise Exception

    nb.commit_particles()

    if hasattr(nb, "viewer"):
        nb.viewer()

    dt = 0.05
    tnow = 0.
    nb.synchronize_model()
    time, Ek, Ep, Eth = [], [], [], []
    time.append(tnow)
    e, ret = nb.get_kinetic_energy()
    Ek.append(e)
    e, ret = nb.get_potential_energy()
    Ep.append(e)
    e, ret = nb.get_thermal_energy()
    Eth.append(e)

    while tnow < .8:
        tnow = tnow+dt
        nb.evolve_model(tnow)
        nb.synchronize_model()
        tnow, err = nb.get_time()
        time.append(tnow)
        e, ret = nb.get_kinetic_energy()
        Ek.append(e)
        e, ret = nb.get_potential_energy()
        Ep.append(e)
        e, ret = nb.get_thermal_energy()
        Eth.append(e)

    nb.stop()

    time = numpy.array(time)
    Ek = numpy.array(Ek)
    Ep = numpy.array(Ep)
    Eth = numpy.array(Eth)
    energy_plot(time, Ek, Ep, Eth)
Beispiel #29
0
def run_mc(N=5000, Mcloud=10000. | units.MSun, Rcloud=1. | units.parsec):

    conv = nbody_system.nbody_to_si(Mcloud, Rcloud)

    interaction_timestep = 0.01 | units.Myr
    time_end = 0.36 | units.Myr

    parts = molecular_cloud(targetN=N,
                            convert_nbody=conv,
                            base_grid=body_centered_grid_unit_cube).result

    sph = Fi(conv)

    # need to turn off self gravity, the bridge will calculate this
    sph.parameters.self_gravity_flag = False

    # some typical Fi flags (just for reference, most are default values)
    sph.parameters.use_hydro_flag = True
    sph.parameters.isothermal_flag = True
    sph.parameters.integrate_entropy_flag = False
    sph.parameters.gamma = 1
    sph.parameters.verbosity = 0

    # setting the hydro timestep is important
    # the sph code will take 2 timesteps every interaction timestep
    sph.parameters.timestep = interaction_timestep / 2

    sph.gas_particles.add_particles(parts)

    def new_code_to_calculate_gravity_of_gas_particles():
        result = BHTree(conv)
        return result

    calculate_gravity_code = bridge.CalculateFieldForCodes(
        new_code_to_calculate_gravity_of_gas_particles,  # the code that calculates the acceleration field
        input_codes=[sph]  # the codes to calculate the acceleration field of
    )

    bridged_system = bridge.Bridge()
    bridged_system.timestep = interaction_timestep

    bridged_system.add_system(
        sph,  # the code to move the particles of
        [calculate_gravity_code
         ]  # the codes that provide the acceleration field
    )

    fig = pyplot.figure(figsize=(12, 12))

    ncolumn = 2
    nrow = 2
    nplot = ncolumn * nrow

    grid_size = 3 | units.parsec
    extent = (grid_size * (-0.5, 0.5, -0.5, 0.5)).value_in(units.parsec)

    if nplot > 1:
        plot_timestep = time_end / (nplot - 1)
    else:
        plot_timestep = time_end

    for i in range(nplot):
        ttarget = i * plot_timestep
        print("evolving to time:", ttarget.as_quantity_in(units.Myr))
        bridged_system.evolve_model(ttarget)

        rho = make_map(sph, N=200, grid_size=grid_size)
        subplot = fig.add_subplot(ncolumn, nrow, i + 1)
        subplot.imshow(numpy.log10(1.e-5 +
                                   rho.value_in(units.amu / units.cm**3)),
                       extent=extent,
                       vmin=1,
                       vmax=5)
        subplot.set_title(ttarget.as_quantity_in(units.Myr))

    sph.stop()
    pyplot.show()