Ejemplo n.º 1
0
def slowtest_evrard_gadget():
    assert is_mpd_running()
    run_evrard([new_code("gadget")],
               10000,
               random_seed=12345,
               name_of_the_figure=os.path.join(get_path_to_results(),
                                               "evrard_test_gadget_10000.png"))
Ejemplo n.º 2
0
 def test18(self):
     print "SSE validation"
     sse_src_path = os.path.join(os.path.dirname(sys.modules[SSE.__module__].__file__), 'src')
     if not os.path.exists(os.path.join(sse_src_path, "evolve.in")):
         self.skip("Not in a source release")
     instance = SSE()
     instance.particles.add_particle(Particle(mass = 1.416 | units.MSun))
     instance.particles[0].evolve_for(7000.0 | units.Myr)
     evolved_star = instance.particles.copy()[0]
     evolved_star.temperature = instance.particles[0].temperature
     instance.stop()
    
     testpath = get_path_to_results()
     shutil.copy(os.path.join(sse_src_path, "evolve.in"), os.path.join(testpath, "evolve.in"))
     
     call([os.path.join(sse_src_path, "sse")], cwd=testpath)
     
     with open(os.path.join(testpath, "evolve.dat"), "r") as sse_output:
         lines = sse_output.readlines()
         sse_final_result = lines[-2].split()
     
     self.assertAlmostEqual(evolved_star.age, float(sse_final_result[0]) | units.Myr, 3)
     self.assertAlmostEqual(evolved_star.stellar_type, float(sse_final_result[1]) | units.stellar_type, 3)
     self.assertAlmostEqual(evolved_star.initial_mass, float(sse_final_result[2]) | units.MSun, 3)
     self.assertAlmostEqual(evolved_star.mass, float(sse_final_result[3]) | units.MSun, 3)
     self.assertAlmostEqual(evolved_star.luminosity, 10**float(sse_final_result[4]) | units.LSun, 3)
     self.assertAlmostEqual(evolved_star.radius, 10**float(sse_final_result[5]) | units.RSun, 3)
     self.assertAlmostRelativeEqual(evolved_star.temperature, 10**float(sse_final_result[6]) | units.K, 2)
     self.assertAlmostEqual(evolved_star.core_mass, float(sse_final_result[7]) | units.MSun, 3)
     self.assertAlmostEqual(evolved_star.convective_envelope_mass, float(sse_final_result[8]) | units.MSun, 3)
     self.assertAlmostEqual(evolved_star.epoch, float(sse_final_result[9]) | units.Myr, 3)
     self.assertAlmostEqual(evolved_star.spin, float(sse_final_result[10]) | units.yr**-1, 3)
Ejemplo n.º 3
0
def setup_stellar_evolution_model():
    out_pickle_file = os.path.join(
        get_path_to_results(), "super_giant_stellar_structure.pkl")
    if os.path.exists(out_pickle_file):
        return out_pickle_file

    stellar_evolution = MESA(redirection="none")
    stars = Particles(1)
    stars.mass = 10.0 | units.MSun
    stellar_evolution.initialize_module_with_default_parameters()
    stellar_evolution.particles.add_particles(stars)
    stellar_evolution.commit_particles()

    print(
            "Evolving a MESA star with mass:",
            stellar_evolution.particles[0].mass
            )
    try:
        while True:
            stellar_evolution.evolve_model()
    except AmuseException as ex:
        print "Evolved star to", stellar_evolution.particles[0].age
        print "Radius:", stellar_evolution.particles[0].radius

    pickle_stellar_model(stellar_evolution.particles[0], out_pickle_file)
    stellar_evolution.stop()
    return out_pickle_file
Ejemplo n.º 4
0
 def test18(self):
     print("MOSSE validation")
     mosse_src_path = os.path.join(os.path.dirname(sys.modules[MOSSE.__module__].__file__), 'src')
     if not os.path.exists(os.path.join(mosse_src_path, "evolve.in")):
         self.skip("Not in a source release")
     instance = MOSSE()
     instance.particles.add_particle(Particle(mass = 1.416 | units.MSun))
     instance.particles[0].evolve_for(7000.0 | units.Myr)
     evolved_star = instance.particles.copy()[0]
     evolved_star.temperature = instance.particles[0].temperature
     instance.stop()
    
     testpath = get_path_to_results()
     shutil.copy(os.path.join(sse_src_path, "evolve.in"), os.path.join(testpath, "evolve.in"))
     
     call([os.path.join(sse_src_path, "mosse")], cwd=testpath)
     
     with open(os.path.join(testpath, "evolve.dat"), "r") as sse_output:
         lines = sse_output.readlines()
         sse_final_result = lines[-2].split()
     
     self.assertAlmostEqual(evolved_star.age, float(sse_final_result[0]) | units.Myr, 3)
     self.assertAlmostEqual(evolved_star.stellar_type, float(sse_final_result[1]) | units.stellar_type, 3)
     self.assertAlmostEqual(evolved_star.initial_mass, float(sse_final_result[2]) | units.MSun, 3)
     self.assertAlmostEqual(evolved_star.mass, float(sse_final_result[3]) | units.MSun, 3)
     self.assertAlmostEqual(evolved_star.luminosity, 10**float(sse_final_result[4]) | units.LSun, 3)
     self.assertAlmostEqual(evolved_star.radius, 10**float(sse_final_result[5]) | units.RSun, 3)
     self.assertAlmostRelativeEqual(evolved_star.temperature, 10**float(sse_final_result[6]) | units.K, 2)
     self.assertAlmostEqual(evolved_star.core_mass, float(sse_final_result[7]) | units.MSun, 3)
     self.assertAlmostEqual(evolved_star.convective_envelope_mass, float(sse_final_result[8]) | units.MSun, 3)
     self.assertAlmostEqual(evolved_star.epoch, float(sse_final_result[9]) | units.Myr, 3)
     self.assertAlmostEqual(evolved_star.spin, float(sse_final_result[10]) | units.yr**-1, 3)
Ejemplo n.º 5
0
def setup_stellar_evolution_model():
    out_pickle_file = os.path.join(get_path_to_results(), "super_giant_stellar_structure.pkl")
    if os.path.exists(out_pickle_file):
        return out_pickle_file

    stellar_evolution = MESA(redirection="none")
    stars = Particles(1)
    stars.mass = 10.0 | units.MSun
    stellar_evolution.particles.add_particles(stars)

    """
    print "Evolving a MESA star with mass:", stellar_evolution.particles[0].mass
    try:
        while True:
            stellar_evolution.evolve_model()
    except AmuseException as ex:
        print "Evolved star to t=", stellar_evolution.particles[0].age,
        print "Mass:", stellar_evolution.particles[0].mass
        print "Radius:", stellar_evolution.particles[0].radius
        print "core-mass:", stellar_evolution.particles[0].core_mass
    """
    while stellar_evolution.particles[0].stellar_type <= 12 | units.stellar_type:
        stellar_evolution.evolve_model()

    pickle_stellar_model(stellar_evolution.particles[0], out_pickle_file)
    stellar_evolution.stop()
    return out_pickle_file
Ejemplo n.º 6
0
    def build_worker(self):
        
        path = os.path.abspath(get_path_to_results())
        codefile = os.path.join(path,"code.o")
        interfacefile = os.path.join(path,"interface.o")
        self.exefile = os.path.join(path,"c_worker")
        
        self.c_compile(codefile, codestring)
        
        uc = create_c.GenerateACHeaderStringFromASpecificationClass()
        uc.specification_class = TestCode
        uc.make_extern_c = False
        header =  uc.result
        
        
        uc = create_c.GenerateACSourcecodeStringFromASpecificationClass()
        uc.specification_class = TestCode
	uc.needs_mpi=False
        code =  uc.result
        
        string = '\n\n'.join([header, code])
        
        #print string
        
        self.cxx_compile(interfacefile, string)
        self.c_build(self.exefile, [interfacefile, codefile] )
Ejemplo n.º 7
0
def setup_stellar_evolution_model():
    out_pickle_file = os.path.join(get_path_to_results(), "super_giant_stellar_structure.pkl")
    if os.path.exists(out_pickle_file):
        return out_pickle_file
    
    stellar_evolution = MESA(redirection = "none")
    stars =  Particles(1)
    stars.mass = 10.0 | units.MSun
    stellar_evolution.particles.add_particles(stars)

    """
    print "Evolving a MESA star with mass:", stellar_evolution.particles[0].mass
    try:
        while True:
            stellar_evolution.evolve_model()
    except AmuseException as ex:
        print "Evolved star to t=", stellar_evolution.particles[0].age,
        print "Mass:", stellar_evolution.particles[0].mass
        print "Radius:", stellar_evolution.particles[0].radius
        print "core-mass:", stellar_evolution.particles[0].core_mass
    """
    while stellar_evolution.particles[0].stellar_type <= 12|units.stellar_type:
        stellar_evolution.evolve_model()
#    while stellar_evolution.particles[0].stellar_type <= 3|units.stellar_type:
#        stellar_evolution.evolve_model()
    
    pickle_stellar_model(stellar_evolution.particles[0], out_pickle_file)
    stellar_evolution.stop()
    return out_pickle_file
Ejemplo n.º 8
0
    def build_worker(self):

        path = os.path.abspath(get_path_to_results())
        codefile = os.path.join(path, "code.o")
        interfacefile = os.path.join(path, "interface.o")
        self.exefile = os.path.join(path, "c_worker")

        self.c_compile(codefile, codestring)

        uc = create_c.GenerateACHeaderStringFromASpecificationClass()
        uc.specification_class = TestCode
        uc.make_extern_c = False
        header = uc.result

        uc = create_c.GenerateACSourcecodeStringFromASpecificationClass()
        uc.specification_class = TestCode
        uc.needs_mpi = False
        code = uc.result

        string = '\n\n'.join([header, code])

        #print string

        self.cxx_compile(interfacefile, string)
        self.c_build(self.exefile, [interfacefile, codefile])
Ejemplo n.º 9
0
    def slowtest4(self):
        print "Generate a model for a disk galaxy (10k disk, no bulge, 20k halo) - SI units"
        halo_number_of_particles = 20000
        converter = generic_unit_converter.ConvertBetweenGenericAndSiUnits(
            constants.G, 1.0e12 | units.MSun, 50.0 | units.kpc)
        particles = new_galactics_model(halo_number_of_particles,
                                        disk_number_of_particles=10000,
                                        generate_bulge_flag=False,
                                        do_scale=True,
                                        unit_system_converter=converter)

        self.assertEquals(len(particles), 30000)
        self.assertAlmostRelativeEquals(particles.total_mass(),
                                        1.0e12 | units.MSun, 10)
        self.assertAlmostRelativeEquals(
            particles.kinetic_energy(),
            converter.to_si(0.25 | nbody_system.energy), 10)

        disk = particles[:10000]
        self.assertAlmostRelativeEquals(disk.total_mass(),
                                        2.156e10 | units.MSun, 3)
        self.assertAlmostRelativeEquals(
            disk.position.lengths_squared().amax().sqrt().in_(units.kpc),
            15.584 | units.kpc, 3)

        self.assertAlmostRelativeEquals(
            disk.position.std(axis=0).in_(units.kpc),
            [3.5934, 3.6768, 0.17078] | units.kpc, 3)

        write_set_to_file(
            particles,
            os.path.join(get_path_to_results(), 'disk_galactICs.amuse'),
            'amuse')
Ejemplo n.º 10
0
def setup_stellar_evolution_model():
    out_pickle_file = os.path.join(get_path_to_results(),
                                   "super_giant_stellar_structure.pkl")
    if os.path.exists(out_pickle_file):
        return out_pickle_file

    stellar_evolution = MESA(redirection="none")
    stars = Particles(1)
    stars.mass = 10.0 | units.MSun
    stellar_evolution.initialize_module_with_default_parameters()
    stellar_evolution.particles.add_particles(stars)
    stellar_evolution.commit_particles()

    print "Evolving a MESA star with mass:", stellar_evolution.particles[
        0].mass
    try:
        while True:
            stellar_evolution.evolve_model()
    except AmuseException as ex:
        print "Evolved star to", stellar_evolution.particles[0].age
        print "Radius:", stellar_evolution.particles[0].radius

    pickle_stellar_model(stellar_evolution.particles[0], out_pickle_file)
    stellar_evolution.stop()
    return out_pickle_file
Ejemplo n.º 11
0
def slowtest_evrard_gadget():
    assert is_mpd_running()
    run_evrard(
        [new_code("gadget")],
        10000,
        random_seed = 12345, 
        name_of_the_figure = os.path.join(get_path_to_results(), "evrard_test_gadget_10000.png")
    )
Ejemplo n.º 12
0
def run_supernova():
    use_hydro_code = Gadget2
    hydro_code_options = dict(number_of_workers=3)
    number_of_sph_particles = 3000
    t_end = 1.0e4 | units.s
    
    pickle_file = setup_stellar_evolution_model()
    model = convert_stellar_model_to_SPH(None, 
                                         number_of_sph_particles, 
                                         seed = 12345,
                                         pickle_file = pickle_file,
                                         with_core_particle = True,
                                         target_core_mass = 1.4|units.MSun)
    print "model=", model.core_particle
    core, gas_without_core, core_radius \
        = model.core_particle, model.gas_particles, model.core_radius
    
    inject_supernova_energy(gas_without_core)
    
    print "\nEvolving (SPH) to:", t_end
    n_steps = 100
    
    unit_converter = ConvertBetweenGenericAndSiUnits(1.0 | units.RSun,
                                                     constants.G, t_end)
    hydro_code = use_hydro_code(unit_converter, **hydro_code_options)
    
    try:
        hydro_code.parameters.timestep = t_end / n_steps
    except Exception as exc:
        if not "parameter is read-only" in str(exc): raise
    
    hydro_code.parameters.epsilon_squared = core_radius**2
    hydro_code.parameters.n_smooth_tol = 0.01
    hydro_code.gas_particles.add_particles(gas_without_core)
    hydro_code.dm_particles.add_particle(core)
    
    times = [] | units.s
    potential_energies = [] | units.J
    kinetic_energies =   [] | units.J
    thermal_energies =   [] | units.J
    for time, i_step in [(i*t_end/n_steps, i) for i in range(0, n_steps+1)]:
        hydro_code.evolve_model(time)
        times.append(time)
        potential_energies.append(hydro_code.potential_energy)
        kinetic_energies.append(  hydro_code.kinetic_energy)
        thermal_energies.append(  hydro_code.thermal_energy)
        hydro_plot([-1.0, 1.0, -1.0, 1.0] * (350 | units.RSun),
                   hydro_code,
                   (100, 100),
                   time,
                   os.path.join(get_path_to_results(),
                            "supernova_hydro_image{0:=03}.png".format(i_step))
        )
    
    energy_plot(times, kinetic_energies, potential_energies, thermal_energies, 
                "supernova_energy_evolution.pdf")

    hydro_code.stop()
Ejemplo n.º 13
0
def slowtest_evrard_compare():
    assert is_mpd_running()
    global labels
    labels = fi_gadget_labels
    run_evrard([new_code("fi"), new_code("gadget")],
               10000,
               random_seed=12345,
               name_of_the_figure=os.path.join(
                   get_path_to_results(), "evrard_test_compare_10000.png"))
Ejemplo n.º 14
0
def run_supernova():
    use_hydro_code = Gadget2
    hydro_code_options = dict(number_of_workers=3)
    number_of_sph_particles = 3000
    t_end = 1.0e4 | units.s

    pickle_file = setup_stellar_evolution_model()
    model = convert_stellar_model_to_SPH(None,
                                         number_of_sph_particles,
                                         seed=12345,
                                         pickle_file=pickle_file,
                                         with_core_particle=True,
                                         target_core_mass=1.4 | units.MSun)
    print("model=", model.core_particle)
    core, gas_without_core, core_radius \
        = model.core_particle, model.gas_particles, model.core_radius

    inject_supernova_energy(gas_without_core)

    print("\nEvolving (SPH) to:", t_end)
    n_steps = 100

    unit_converter = ConvertBetweenGenericAndSiUnits(1.0 | units.RSun,
                                                     constants.G, t_end)
    hydro_code = use_hydro_code(unit_converter, **hydro_code_options)

    try:
        hydro_code.parameters.timestep = t_end / n_steps
    except Exception as exc:
        if not "parameter is read-only" in str(exc): raise

    hydro_code.parameters.epsilon_squared = core_radius**2
    hydro_code.parameters.n_smooth_tol = 0.01
    hydro_code.gas_particles.add_particles(gas_without_core)
    hydro_code.dm_particles.add_particle(core)

    times = [] | units.s
    potential_energies = [] | units.J
    kinetic_energies = [] | units.J
    thermal_energies = [] | units.J
    for time, i_step in [(i * t_end / n_steps, i)
                         for i in range(0, n_steps + 1)]:
        hydro_code.evolve_model(time)
        times.append(time)
        potential_energies.append(hydro_code.potential_energy)
        kinetic_energies.append(hydro_code.kinetic_energy)
        thermal_energies.append(hydro_code.thermal_energy)
        hydro_plot([-1.0, 1.0, -1.0, 1.0] * (350 | units.RSun), hydro_code,
                   (100, 100), time,
                   os.path.join(
                       get_path_to_results(),
                       "supernova_hydro_image{0:=03}.png".format(i_step)))

    energy_plot(times, kinetic_energies, potential_energies, thermal_energies,
                "supernova_energy_evolution.pdf")

    hydro_code.stop()
Ejemplo n.º 15
0
def test_simulate_small_cluster():
    """test_simulate_small_cluster
    This method is found by the testing framework and automatically
    run with all other tests. This method simulates
    a too small cluster, this is done to limit the testing time.
    """
    assert is_mpd_running()
    test_results_path = get_path_to_results()
    output_file = os.path.join(test_results_path, "test-2.svg")
    simulate_small_cluster(4, 4 | units.Myr, name_of_the_figure=output_file)
Ejemplo n.º 16
0
def test_simulate_one_star():
    assert is_mpd_running()
    code = new_code("sse", 1)
    test_results_path = get_path_to_results()
    output_file = os.path.join(test_results_path, "HR_evolution_tracks.png")
    simulate_evolution_tracks(
        code,
        [20.0] | units.MSun,
        name_of_the_figure=output_file,
    )
Ejemplo n.º 17
0
def slowtest_evrard_compare():
    assert is_mpd_running()
    global labels
    labels = fi_gadget_labels
    run_evrard(
        [new_code("fi"), new_code("gadget")],
        10000,
        random_seed = 12345, 
        name_of_the_figure = os.path.join(get_path_to_results(), "evrard_test_compare_10000.png")
    )
Ejemplo n.º 18
0
def test_simulate_one_star():
    assert is_mpd_running()
    code = new_code("sse", 1)
    test_results_path = get_path_to_results()
    output_file = os.path.join(test_results_path, "HR_evolution_tracks.png")
    simulate_evolution_tracks(
        code,
        [20.0] | units.MSun,
        name_of_the_figure=output_file, 
    )
Ejemplo n.º 19
0
def test_simulate_short():
    assert is_mpd_running()
    code = new_code("sse", 100)

    test_results_path = get_path_to_results()
    output_file = os.path.join(test_results_path, "cluster_HR_diagram.png")

    simulate_stellar_evolution(code,
                               number_of_stars=100,
                               end_time=2.0 | units.Myr,
                               name_of_the_figure=output_file)
Ejemplo n.º 20
0
 def slowtest3(self):
     print "Generate a model for M31, using defaults (100k disk, 50k bulge, 200k halo) - Nbody units"
     halo_number_of_particles = 20000
     particles = new_galactics_model(halo_number_of_particles, do_scale = True, 
       bulge_number_of_particles=5000, disk_number_of_particles=10000)
     
     self.assertEquals(len(particles), 35000)
     self.assertAlmostEquals(particles.total_mass(), 1.0 | nbody_system.mass)
     self.assertAlmostEquals(particles.kinetic_energy(), 0.25 | nbody_system.energy)
     
     write_set_to_file(particles, os.path.join(get_path_to_results(), 'M31_galactICs.amuse'), 'amuse')
Ejemplo n.º 21
0
 def slowtest3(self):
     print "Generate a model for M31, using defaults (100k disk, 50k bulge, 200k halo) - Nbody units"
     halo_number_of_particles = 20000
     particles = new_galactics_model(halo_number_of_particles, do_scale = True, 
       bulge_number_of_particles=5000, disk_number_of_particles=10000)
     
     self.assertEquals(len(particles), 35000)
     self.assertAlmostEquals(particles.total_mass(), 1.0 | nbody_system.mass)
     self.assertAlmostEquals(particles.kinetic_energy(), 0.25 | nbody_system.energy)
     
     write_set_to_file(particles, os.path.join(get_path_to_results(), 'M31_galactICs.amuse'), 'amuse')
Ejemplo n.º 22
0
def test_simulate_small_cluster():
    """test_simulate_small_cluster
    This method is found by the testing framework and automatically
    run with all other tests. This method simulates
    a too small cluster, this is done to limit the testing time.
    """
    assert is_mpd_running()
    test_results_path = get_path_to_results()
    output_file = os.path.join(test_results_path, "test-2.svg")
    simulate_small_cluster(4, 4 | units.Myr,
                           name_of_the_figure=output_file)
Ejemplo n.º 23
0
def energy_plot(time, ek, ep, eth):
    if not HAS_MATPLOTLIB:
        return

    pyplot.figure(figsize=(5, 5))
    pyplot.xlabel(r'time')
    pyplot.ylabel(r'energy')
    pyplot.plot(time, ek)
    pyplot.plot(time, ep)
    pyplot.plot(time, eth)
    pyplot.plot(time, ek + ep + eth)
    test_results_path = get_path_to_results()
    pyplot.savefig(os.path.join(test_results_path, "test.png"))
Ejemplo n.º 24
0
def test_simulate_short():
    assert is_mpd_running()
    code = new_code("sse", 100)

    test_results_path = get_path_to_results()
    output_file = os.path.join(test_results_path, "cluster_HR_diagram.png")

    simulate_stellar_evolution(
        code,
        number_of_stars=100,
        end_time=2.0 | units.Myr,
        name_of_the_figure=output_file
    )
Ejemplo n.º 25
0
def energy_plot(time,ek,ep,eth):
    if not HAS_MATPLOTLIB:
        return
      
    pyplot.figure(figsize = (5, 5))
    pyplot.xlabel(r'time')
    pyplot.ylabel(r'energy')
    pyplot.plot(time,ek)
    pyplot.plot(time,ep)
    pyplot.plot(time,eth)
    pyplot.plot(time,ek+ep+eth)
    test_results_path = get_path_to_results()
    pyplot.savefig(os.path.join(test_results_path, "evrard_test.png"))
Ejemplo n.º 26
0
 def test5(self):
     print "Testing ParallelStellarEvolution individual options"
     base_name = os.path.join(get_path_to_results(), "parallel_stellar_evolution_out_")
     for filename in [base_name+str(i) for i in range(3)]:
         if os.path.exists(filename):
             os.remove(filename)
     
     parallel = ParallelStellarEvolution(self.code_factory, number_of_workers=3, 
         individual_options=[dict(redirect_file=base_name+str(i)) for i in range(3)], redirection="file", **default_options)
     
     for filename in [base_name+str(i) for i in range(3)]:
         self.assertTrue(os.path.exists(filename))
     
     parallel.stop()
Ejemplo n.º 27
0
 def test9(self):
     print "Test for saving and loading the stellar structure model"
     filenames = ["test1.dump", "test2.dump"]
     filenames = [os.path.join(get_path_to_results(), name) for name in filenames]
     instance = EVtwin(redirection="none")
     instance.parameters.verbosity = True
     instance.particles.add_particles(Particles(mass=[0.5, 0.8] | units.MSun))
     instance.evolve_model()
     instance.particles.write_star_to_file(filenames)
     copies = Particles(2)
     copies.filename = filenames
     instance.particles.add_particles(copies)
     instance.evolve_model()
     print instance.particles
     self.assertAlmostRelativeEquals(instance.particles.temperature, [3644, 4783, 3644, 4783] | units.K, 3)
     instance.stop()
Ejemplo n.º 28
0
 def test10(self):
     stellar_evolution = MOSSE()
     stellar_evolution.commit_parameters()
     stars = Particles(10)
     stars.mass = 1.0 | units.MSun
     stellar_evolution.particles.add_particles(stars)
     self.assertEqual(stellar_evolution.particles._factory_for_new_collection(), Particles)
     
     filename = os.path.join(get_path_to_results(), "test.h5")
     if os.path.exists(filename):
         os.remove(filename)
         
     io.write_set_to_file(stellar_evolution.particles, filename, 'hdf5')
     stored_stars = io.read_set_from_file(filename, 'hdf5')
     self.assertEqual(len(stars), len(stored_stars))
 
     self.assertAlmostRelativeEquals(stars.mass, stored_stars.mass)
Ejemplo n.º 29
0
 def test10(self):
     stellar_evolution = SSE()
     stellar_evolution.commit_parameters()
     stars = Particles(10)
     stars.mass = 1.0 | units.MSun
     stellar_evolution.particles.add_particles(stars)
     self.assertEquals(stellar_evolution.particles._factory_for_new_collection(), Particles)
     
     filename = os.path.join(get_path_to_results(), "test.h5")
     if os.path.exists(filename):
         os.remove(filename)
         
     io.write_set_to_file(stellar_evolution.particles, filename, 'hdf5')
     stored_stars = io.read_set_from_file(filename, 'hdf5')
     self.assertEquals(len(stars), len(stored_stars))
 
     self.assertAlmostRelativeEquals(stars.mass, stored_stars.mass)
Ejemplo n.º 30
0
def setup_stellar_evolution_model():
    out_pickle_file = os.path.join(get_path_to_results(),
                                   "super_giant_stellar_structure.pkl")
    if os.path.exists(out_pickle_file):
        return out_pickle_file
    print("Creating initial conditions from a MESA stellar evolution model...")

    stellar_evolution = MESA(redirection="none")
    stars = Particles(1)
    stars.mass = 10.0 | units.MSun
    stellar_evolution.particles.add_particles(stars)

    while stellar_evolution.particles[
            0].stellar_type <= 12 | units.stellar_type:
        stellar_evolution.evolve_model()

    pickle_stellar_model(stellar_evolution.particles[0], out_pickle_file)
    stellar_evolution.stop()
    return out_pickle_file
Ejemplo n.º 31
0
 def slowtest4(self):
     print "Generate a model for a disk galaxy (10k disk, no bulge, 20k halo) - SI units"
     halo_number_of_particles = 20000
     converter = generic_unit_converter.ConvertBetweenGenericAndSiUnits(constants.G, 1.0e12 | units.MSun, 50.0 | units.kpc)
     particles = new_galactics_model(halo_number_of_particles, disk_number_of_particles=10000, 
         generate_bulge_flag=False, do_scale=True, unit_system_converter=converter)
     
     self.assertEquals(len(particles), 30000)
     self.assertAlmostRelativeEquals(particles.total_mass(), 1.0e12 | units.MSun, 10)
     self.assertAlmostRelativeEquals(particles.kinetic_energy(), converter.to_si(0.25 | nbody_system.energy), 10)
     
     disk = particles[:10000]
     self.assertAlmostRelativeEquals(disk.total_mass(), 2.156e10 | units.MSun, 3)
     self.assertAlmostRelativeEquals(disk.position.lengths_squared().amax().sqrt().in_(units.kpc),
                                              15.584 | units.kpc, 3)
                           
     self.assertAlmostRelativeEquals(disk.position.std(axis=0).in_(units.kpc), [3.5934, 3.6768, 0.17078] | units.kpc, 3)
     
     write_set_to_file(particles, os.path.join(get_path_to_results(), 'disk_galactICs.amuse'), 'amuse')
Ejemplo n.º 32
0
def setup_stellar_evolution_model():
    out_pickle_file = os.path.join(get_path_to_results(),
                                   "super_giant_stellar_structure.pkl")
    if os.path.exists(out_pickle_file):
        return out_pickle_file

    print "Creating initial conditions from a MESA stellar evolution model..."

    stellar_evolution = MESA(redirection = "none")
    stars =  Particles(1)
    stars.mass = 10.0 | units.MSun
    stellar_evolution.particles.add_particles(stars)

    while stellar_evolution.particles[0].stellar_type <= 12|units.stellar_type:
        stellar_evolution.evolve_model()
    
    pickle_stellar_model(stellar_evolution.particles[0], out_pickle_file)
    stellar_evolution.stop()
    return out_pickle_file
    def test5(self):
        print "Testing ParallelStellarEvolution individual options"
        base_name = os.path.join(get_path_to_results(),
                                 "parallel_stellar_evolution_out_")
        for filename in [base_name + str(i) for i in range(3)]:
            if os.path.exists(filename):
                os.remove(filename)

        parallel = ParallelStellarEvolution(
            self.code_factory,
            number_of_workers=3,
            individual_options=[
                dict(redirect_file=base_name + str(i)) for i in range(3)
            ],
            redirection="file",
            **default_options)

        for filename in [base_name + str(i) for i in range(3)]:
            self.assertTrue(os.path.exists(filename))

        parallel.stop()
Ejemplo n.º 34
0
 def test9(self):
     print "Test for saving and loading the stellar structure model"
     filenames = ["test1.dump", "test2.dump"]
     filenames = [os.path.join(get_path_to_results(), name) for name in filenames]
     instance = EVtwin()#redirection="none")
     instance.parameters.verbosity = True
     instance.particles.add_particles(Particles(mass = [0.5, 0.8] | units.MSun))
     instance.evolve_model()
     instance.particles.write_star_to_file(filenames)
     copies = Particles(2)
     copies.filename = filenames
     instance.particles.add_particles(copies)
     instance.evolve_model()
     print instance.particles
     import warnings
     warnings.warn("this test's precision has been temporarily (2017) decreased")
     # the reason for this is that the deviation is compiler dependend (and does only happen 
     # on some machine/compiler/OS combinations)
     # it may have something to do with initialization of variables in evtwin
     #~ self.assertAlmostRelativeEquals(instance.particles.temperature, [3644, 4783, 3644, 4783] | units.K, 3)
     self.assertAlmostRelativeEquals(instance.particles.temperature, [3644, 4783, 3644, 4783] | units.K, 2)
     instance.stop()
Ejemplo n.º 35
0
 def new_particles(self):
     input_file = os.path.join(get_path_to_results(), "test_sph_to_star_input.hdf5")
     if os.path.exists(input_file):
         return read_set_from_file(input_file, "hdf5")
     
     stellar_evolution = EVtwin()
     stellar_evolution.particles.add_particle(Particle(mass=1.0|units.MSun))
     stellar_evolution.evolve_model(100.0|units.Myr)
     particles = convert_stellar_model_to_SPH(
         stellar_evolution.particles[0], 
         500, 
         seed=12345
     ).gas_particles
     stellar_evolution.stop()
     
     hydrodynamics = Gadget2(ConvertBetweenGenericAndSiUnits(1.0|units.MSun, 1.0|units.RSun, 1.0e3|units.s))
     hydrodynamics.gas_particles.add_particles(particles)
     hydrodynamics.evolve_model(1.0|units.s)
     hydrodynamics.gas_particles.copy_values_of_attributes_to(["density", "u", "pressure"], particles)
     hydrodynamics.stop()
     write_set_to_file(particles, input_file, "hdf5")
     return particles
Ejemplo n.º 36
0
    def new_particles(self):
        input_file = os.path.join(get_path_to_results(),
                                  "test_sph_to_star_input.hdf5")
        if os.path.exists(input_file):
            return read_set_from_file(input_file, "hdf5")

        stellar_evolution = EVtwin()
        stellar_evolution.particles.add_particle(
            Particle(mass=1.0 | units.MSun))
        stellar_evolution.evolve_model(100.0 | units.Myr)
        particles = convert_stellar_model_to_SPH(
            stellar_evolution.particles[0], 500, seed=12345).gas_particles
        stellar_evolution.stop()

        hydrodynamics = Gadget2(
            ConvertBetweenGenericAndSiUnits(1.0 | units.MSun, 1.0 | units.RSun,
                                            1.0e3 | units.s))
        hydrodynamics.gas_particles.add_particles(particles)
        hydrodynamics.evolve_model(1.0 | units.s)
        hydrodynamics.gas_particles.copy_values_of_attributes_to(
            ["density", "u", "pressure"], particles)
        hydrodynamics.stop()
        write_set_to_file(particles, input_file, "hdf5")
        return particles
Ejemplo n.º 37
0
def head_on_stellar_merger(
        masses=[0.3, 3.0] | units.MSun,
        star_age=310.0 | units.Myr,
        initial_separation=4.0 | units.RSun,
        angle=numpy.pi / 3,
        initial_speed=3000.0 | units.km / units.s,
        initial_speed_perpendicular=30.0 | units.km / units.s,
        number_of_sph_particles=50000,
        t_end=1.0e4 | units.s,
        sph_code=Fi,
    ):
    """
    masses: Mass of the two stars
    star_age: Initial age of the stars
    number_of_sph_particles: Total number of particles of both stars, divided
    according to their masses
    t_end: (Physical, not computational) duration of the hydrodynamics
    simulation
    sph_code: Code to use for the hydrodynamics simulation
    """

    # Convert some of the input parameters to string, for use in output file
    # names:
    n_string = "n" + ("%1.0e" % (number_of_sph_particles)
                      ).replace("+0", "").replace("+", "")
    t_end_string = "t" + ("%1.0e" % (t_end.value_in(units.s))
                          ).replace("+0", "").replace("+", "")

    base_output_file_name = os.path.join(
        get_path_to_results(), "stellar_merger_"+n_string+"_"+t_end_string)

    stars = Particles(2)
    stars.mass = masses
    try:
        stellar_evolution = MESA()
        stellar_evolution.initialize_code()
    except:
        print "MESA was not built. Returning."
        return
    stellar_evolution.commit_parameters()
    stellar_evolution.particles.add_particles(stars)
    stellar_evolution.commit_particles()
    print "Evolving stars with MESA..."
    stellar_evolution.evolve_model(star_age)

    number_of_sph_particles_1 = int(
            round(
                number_of_sph_particles
                * (
                    stellar_evolution.particles[0].mass
                    / stellar_evolution.particles.mass.sum()
                    )
                )
            )
    number_of_sph_particles_2 = (
            number_of_sph_particles - number_of_sph_particles_1
            )
    print "Creating initial conditions from a MESA stellar evolution model:"
    print(
            stellar_evolution.particles[0].mass,
            "star consisting of", number_of_sph_particles_1, "particles."
            )
    sph_particles_1 = convert_stellar_model_to_SPH(
        stellar_evolution.particles[0],
        number_of_sph_particles_1,
        seed=12345
    ).gas_particles
    print(
            stellar_evolution.particles[1].mass,
            "star consisting of", number_of_sph_particles_2, "particles."
            )
    sph_particles_2 = convert_stellar_model_to_SPH(
        stellar_evolution.particles[1],
        number_of_sph_particles_2
    ).gas_particles

    initial_separation += stellar_evolution.particles.radius.sum()
    sph_particles_2.x += numpy.cos(angle) * initial_separation
    sph_particles_2.y += numpy.sin(angle) * initial_separation
    sph_particles_1.vx += numpy.cos(angle) * initial_speed - \
        numpy.sin(angle) * initial_speed_perpendicular
    sph_particles_1.vy += numpy.cos(angle) * initial_speed_perpendicular + \
        numpy.sin(angle) * initial_speed
    view = [-0.5, 0.5, -0.5, 0.5] * \
        (initial_separation + stellar_evolution.particles.radius.sum())
    stellar_evolution.stop()

    all_sph_particles = ParticlesSuperset([sph_particles_1, sph_particles_2])
    all_sph_particles.move_to_center()

    unit_converter = ConvertBetweenGenericAndSiUnits(
        1.0 | units.RSun, constants.G, t_end)
    hydro_legacy_code = sph_code(unit_converter)
    n_steps = 100
    hydro_legacy_code.parameters.n_smooth = 96
    try:
        hydro_legacy_code.parameters.timestep = t_end / n_steps
    except Exception as exc:
        if "parameter is read-only" not in str(exc):
            raise
    hydro_legacy_code.gas_particles.add_particles(all_sph_particles)

    print "Evolving to t =", t_end, " (using", sph_code.__name__, "SPH code)."
    for time, i_step in [(i*t_end/n_steps, i) for i in range(1, n_steps+1)]:
        hydro_legacy_code.evolve_model(time)
        if not i_step % 4:
            hydro_plot(
                view,
                hydro_legacy_code,
                (300, 300),
                base_output_file_name +
                "_hydro_image{0:=03}.png".format(i_step)
            )
    hydro_legacy_code.stop()
    print "All done!\n"
Ejemplo n.º 38
0
def head_on_stellar_merger(
        masses = [0.3, 3.0] | units.MSun, 
        star_age = 310.0 | units.Myr, 
        maximally_evolved_stars = False,
        initial_separation = 4.0 | units.RSun, 
        angle = numpy.pi / 3,
        initial_speed = 3000.0 | units.km / units.s, 
        initial_speed_perpendicular = 30.0 | units.km / units.s, 
        number_of_sph_particles = 1000, 
        t_end = 1.0e4 | units.s,
        sph_code = Fi,
        steps_per_snapshot = 4,
        snapshot_size = 100,
        use_stored_stellar_models = True
    ):
    """
    masses: Mass of the two stars
    star_age: Initial age of the stars (if maximally_evolved_stars is False)
    maximally_evolved_stars: Evolve stars as far as the Stellar Evolution code can get
    number_of_sph_particles: Total number of particles of both stars, divided according to their masses
    t_end: (Physical, not computational) duration of the hydrodynamics simulation
    sph_code: Code to use for the hydrodynamics simulation
    steps_per_snapshot: A hydroplot snapshot is generated each time after this many steps (0 or None means no snapshots)
    snapshot_size: Size of the snapshot in pixels along one dimension
    use_stored_stellar_models: Flag to use previously stored stellar model files (for speed-up).
    """
    
    # Convert some of the input parameters to string, for use in output file names:    
    n_string = "n" + ("%1.0e"%(number_of_sph_particles)).replace("+0","").replace("+","")
    t_end_string = "t" + ("%1.0e"%(t_end.value_in(units.s))).replace("+0","").replace("+","")
    masses_string = ("m1_" + ("%0.3e"%(masses[0].value_in(units.MSun))).replace("+0","").replace("+","") +
        "_m2_" + ("%0.3e"%(masses[1].value_in(units.MSun))).replace("+0","").replace("+",""))
    if maximally_evolved_stars:
        star_age_string = "a_max"
    else:
        star_age_string = "a" + ("%0.3e"%(star_age.value_in(units.Myr))).replace("+0","").replace("+","")
    
    base_output_file_name = os.path.join(get_path_to_results(), "stellar_merger_"+n_string+"_"+t_end_string)
    pickle_file_1 = os.path.join(get_path_to_results(), "stellar_merger_"+masses_string+"_"+star_age_string+"_1.pkl")
    pickle_file_2 = os.path.join(get_path_to_results(), "stellar_merger_"+masses_string+"_"+star_age_string+"_2.pkl")
    
    if not use_stored_stellar_models or not (os.path.exists(pickle_file_1) and os.path.exists(pickle_file_2)):
        stars =  Particles(2)
        stars.mass = masses
        try:
            stellar_evolution = MESA()
            stellar_evolution.initialize_code()
        except:
            print "MESA was not built. Returning."
            return
        stellar_evolution.commit_parameters() 
        stellar_evolution.particles.add_particles(stars)
        stellar_evolution.commit_particles()
        
        if maximally_evolved_stars:
            try:
                while True:
                    stellar_evolution.evolve_model()
            except AmuseException as exception:
                print exception
        else:
            stellar_evolution.evolve_model(star_age)
        
        if os.path.exists(pickle_file_1):
            print "Could not save stellar model 1: file already exists."
        else:
            pickle_stellar_model(stellar_evolution.particles[0], pickle_file_1)
            print "Stellar model 1 saved at:", pickle_file_1
        if os.path.exists(pickle_file_2):
            print "Could not save stellar model 2: file already exists."
        else:
            pickle_stellar_model(stellar_evolution.particles[1], pickle_file_2)
            print "Stellar model 2 saved at:", pickle_file_2
        
        stellar_evolution.stop()
    
    model_1 = StellarModel2SPH(None, None, pickle_file = pickle_file_1)
    model_2 = StellarModel2SPH(None, None, pickle_file = pickle_file_2)
    model_1.unpickle_stellar_structure()
    model_2.unpickle_stellar_structure()
    composition = model_2.composition_profile
    midpoints = model_2.midpoints_profile[1:-1]
    specific_internal_energy = model_2.specific_internal_energy_profile
    
    number_of_sph_particles_1 = int(round(number_of_sph_particles * 
        (model_1.mass / (model_1.mass + model_2.mass))))
    number_of_sph_particles_2 = number_of_sph_particles - number_of_sph_particles_1
    print "Creating initial conditions from a MESA stellar evolution model:"
    print model_1.mass, "star consisting of", number_of_sph_particles_1, "particles."
    sph_particles_1 = convert_stellar_model_to_SPH(
        None, 
        number_of_sph_particles_1, 
        seed=12345,
        pickle_file = pickle_file_1
    ).gas_particles
    print model_2.mass, "star consisting of", number_of_sph_particles_2, "particles."
    sph_particles_2 = convert_stellar_model_to_SPH(
        None, 
        number_of_sph_particles_2, 
        pickle_file = pickle_file_2
    ).gas_particles
    initial_separation += model_1.radius + model_2.radius
    sph_particles_2.x  += numpy.cos(angle) * initial_separation
    sph_particles_2.y  += numpy.sin(angle) * initial_separation
    sph_particles_1.vx += numpy.cos(angle) * initial_speed - numpy.sin(angle) * initial_speed_perpendicular
    sph_particles_1.vy += numpy.cos(angle) * initial_speed_perpendicular + numpy.sin(angle) * initial_speed
    view = [-0.5, 0.5, -0.5, 0.5] * (initial_separation + model_1.radius + model_2.radius)
    
    all_sph_particles = ParticlesSuperset([sph_particles_1, sph_particles_2])
    all_sph_particles.move_to_center()
    
    unit_converter = ConvertBetweenGenericAndSiUnits(1.0 | units.RSun, constants.G, t_end)
    hydro_legacy_code = sph_code(unit_converter)
    n_steps = 100
    hydro_legacy_code.parameters.n_smooth = 96
    try:
        hydro_legacy_code.parameters.timestep = t_end / n_steps
    except Exception as exc:
        if not "parameter is read-only" in str(exc): raise
    hydro_legacy_code.gas_particles.add_particles(all_sph_particles)
    
    times = [] | units.Myr
    kinetic_energies =   [] | units.J
    potential_energies = [] | units.J
    thermal_energies =   [] | units.J
    
    print "Evolving to:", t_end
    for time, i_step in [(i*t_end/n_steps, i) for i in range(1, n_steps+1)]:
        hydro_legacy_code.evolve_model(time)
        times.append(time)
        kinetic_energies.append(   hydro_legacy_code.kinetic_energy)
        potential_energies.append( hydro_legacy_code.potential_energy)
        thermal_energies.append(   hydro_legacy_code.thermal_energy)
        if steps_per_snapshot and (not i_step % steps_per_snapshot):
            hydro_plot(
                view,
                hydro_legacy_code,
                (snapshot_size, snapshot_size),
                base_output_file_name + "_hydro_image{0:=03}.png".format(i_step)
            )

    
    hydro_legacy_code.gas_particles.new_channel_to(all_sph_particles).copy_attributes(
        ['mass', 'x','y','z', 'vx','vy','vz', 'u'])
    center_of_mass = all_sph_particles.center_of_mass().as_quantity_in(units.RSun)
    center_of_mass_velocity = all_sph_particles.center_of_mass_velocity().as_quantity_in(units.km / units.s)
    print
    print "center_of_mass:", center_of_mass
    print "center_of_mass_velocity:", center_of_mass_velocity
    all_sph_particles.position -= center_of_mass
    sph_midpoints = all_sph_particles.position.lengths()
    
    energy_plot(
        times, 
        kinetic_energies, potential_energies, thermal_energies, 
        base_output_file_name+"_energy_evolution.png"
    )
    thermal_energy_plot(
        times, 
        thermal_energies, 
        base_output_file_name+"_thermal_energy_evolution.png"
    )
    composition_comparison_plot(
        midpoints, composition[0], 
        sph_midpoints, all_sph_particles.h1, 
        base_output_file_name+"_composition_h1.png"
    )
    internal_energy_comparison_plot(
        midpoints, specific_internal_energy, 
        sph_midpoints, all_sph_particles.u, 
        base_output_file_name+"_new_u.png"
    )
    hydro_plot(
        [-2.0, 2.0, -2.0, 2.0] | units.RSun,
        hydro_legacy_code,
        (100, 100),
        base_output_file_name + "_hydro_image.png"
    )
    hydro_legacy_code.stop()
    print "All done!\n"
Ejemplo n.º 39
0
def simulate_small_cluster(number_of_stars,
                           end_time=40 | units.Myr,
                           name_of_the_figure="test-2.svg"):
    # numpy.random.seed(1)

    salpeter_masses = new_salpeter_mass_distribution(number_of_stars)
    total_mass = salpeter_masses.sum()

    convert_nbody = nbody_system.nbody_to_si(total_mass, 1.0 | units.parsec)

    particles = new_plummer_model(number_of_stars, convert_nbody)

    gravity = BHTree(convert_nbody)
    # print gravity.parameters.timestep.as_quantity_in(units.Myr)
    gravity.parameters.timestep = 0.0001 | units.Myr  # tiny!
    gravity.parameters.epsilon_squared \
        = (float(number_of_stars)**(-0.333333) | units.parsec) ** 2

    stellar_evolution = SSE()

    print "setting masses of the stars"
    particles.radius = 0.0 | units.RSun
    particles.mass = salpeter_masses

    print "initializing the particles"
    stellar_evolution.particles.add_particles(particles)
    from_stellar_evolution_to_model \
        = stellar_evolution.particles.new_channel_to(particles)
    from_stellar_evolution_to_model.copy_attributes(["mass"])

    print "centering the particles"
    particles.move_to_center()
    print "scaling particles to viridial equilibrium"
    particles.scale_to_standard(convert_nbody)

    gravity.particles.add_particles(particles)
    from_model_to_gravity = particles.new_channel_to(gravity.particles)
    from_gravity_to_model = gravity.particles.new_channel_to(particles)

    time = 0.0 | units.Myr
    particles.savepoint(time)

    total_energy_at_t0 = gravity.kinetic_energy + gravity.potential_energy

    print "evolving the model until t = " + str(end_time)
    while time < end_time:
        time += 0.25 | units.Myr

        print "gravity evolve step starting"
        gravity.evolve_model(time)
        print "gravity evolve step done"

        print "stellar evolution step starting"
        stellar_evolution.evolve_model(time)
        print "stellar evolution step done"

        from_gravity_to_model.copy()
        from_stellar_evolution_to_model.copy_attributes(["mass", "radius"])

        particles.savepoint(time)

        from_model_to_gravity.copy_attributes(["mass"])

        total_energy_at_this_time \
            = gravity.kinetic_energy + gravity.potential_energy
        print_log(time, gravity, particles, total_energy_at_t0,
                  total_energy_at_this_time)

    test_results_path = get_path_to_results()
    output_file = os.path.join(test_results_path, "small.hdf5")
    if os.path.exists(output_file):
        os.remove(output_file)
    storage = store.StoreHDF(output_file)
    storage.store(particles)

    gravity.stop()
    stellar_evolution.stop()

    plot_particles(particles, name_of_the_figure)
Ejemplo n.º 40
0
def simulate_small_cluster(number_of_stars, end_time=40 | units.Myr,
                           name_of_the_figure="test-2.svg"):
    # numpy.random.seed(1)

    salpeter_masses = new_salpeter_mass_distribution(number_of_stars)
    total_mass = salpeter_masses.sum()

    convert_nbody = nbody_system.nbody_to_si(total_mass, 1.0 | units.parsec)

    particles = new_plummer_model(number_of_stars, convert_nbody)

    gravity = BHTree(convert_nbody)
    gravity.initialize_code()
    # gravity.parameters.set_defaults()
    # print gravity.parameters.timestep.as_quantity_in(units.Myr)
    gravity.parameters.timestep = 0.0001 | units.Myr  # tiny!
    gravity.parameters.epsilon_squared \
        = (float(number_of_stars)**(-0.333333) | units.parsec) ** 2

    stellar_evolution = SSE()
    stellar_evolution.initialize_module_with_default_parameters()

    print "setting masses of the stars"
    particles.radius = 0.0 | units.RSun
    particles.mass = salpeter_masses

    print "initializing the particles"
    stellar_evolution.particles.add_particles(particles)
    from_stellar_evolution_to_model \
        = stellar_evolution.particles.new_channel_to(particles)
    from_stellar_evolution_to_model.copy_attributes(["mass"])

    print "centering the particles"
    particles.move_to_center()
    print "scaling particles to viridial equilibrium"
    particles.scale_to_standard(convert_nbody)

    gravity.particles.add_particles(particles)
    from_model_to_gravity = particles.new_channel_to(gravity.particles)
    from_gravity_to_model = gravity.particles.new_channel_to(particles)

    gravity.commit_particles()

    time = 0.0 | units.Myr
    particles.savepoint(time)

    total_energy_at_t0 = gravity.kinetic_energy + gravity.potential_energy

    print "evolving the model until t = " + str(end_time)
    while time < end_time:
        time += 0.25 | units.Myr

        print "Gravity evolve step starting"
        gravity_evolve = gravity.evolve_model.async(time)

        print "Stellar evolution step starting"
        stellar_evolution_evolve = stellar_evolution.evolve_model(time)

        print "Stellar evolution step done."

        gravity_evolve.result()
        print "Gravity evolve step done."

        from_gravity_to_model.copy()
        from_stellar_evolution_to_model.copy_attributes(["mass", "radius"])

        particles.savepoint(time)

        from_model_to_gravity.copy_attributes(["mass"])

        total_energy_at_this_time \
            = gravity.kinetic_energy + gravity.potential_energy
        print_log(time, gravity, particles,
                  total_energy_at_t0, total_energy_at_this_time)

    test_results_path = get_path_to_results()
    output_file = os.path.join(test_results_path, "small.hdf5")
    if os.path.exists(output_file):
        os.remove(output_file)
    storage = store.StoreHDF(output_file)
    storage.store(particles)

    gravity.stop()
    stellar_evolution.stop()

    plot_particles(particles, name_of_the_figure)
Ejemplo n.º 41
0
def run_supernova():
    # options:
    use_hydro_code = Gadget2  # Fi -or- Gadget2
    hydro_code_options = dict(
        number_of_workers=3
    )  # e.g. dict(use_gl = True) or dict(redirection = "none")
    number_of_sph_particles = 30000
    t_end = 1.0e5 | units.s

    pickle_file = setup_stellar_evolution_model()

    print "Creating initial conditions from a MESA stellar evolution model..."
    model = convert_stellar_model_to_SPH(
        None,
        number_of_sph_particles,
        seed=12345,
        pickle_file=pickle_file,
        #        base_grid_options = dict(type = "glass", target_rms = 0.01),
        with_core_particle=True)
    core, gas_without_core, core_radius = model.core_particle, model.gas_particles, model.core_radius
    if len(core):
        print "Created", len(
            gas_without_core), "SPH particles and one 'core-particle':\n", core
        print "Setting gravitational smoothing to:", core_radius
    else:
        print "Warning: Only SPH particles created."

    inject_supernova_energy(gas_without_core)

    print "\nEvolving (SPH) to:", t_end
    n_steps = 100

    unit_converter = ConvertBetweenGenericAndSiUnits(1.0 | units.RSun,
                                                     constants.G, t_end)
    hydro_code = use_hydro_code(unit_converter, **hydro_code_options)

    try:
        hydro_code.parameters.timestep = t_end / n_steps
    except Exception as exc:
        if not "parameter is read-only" in str(exc): raise

    hydro_code.parameters.epsilon_squared = core_radius**2
    hydro_code.parameters.n_smooth_tol = 0.01
    hydro_code.gas_particles.add_particles(gas_without_core)
    hydro_code.dm_particles.add_particles(core)

    times = [] | units.s
    potential_energies = [] | units.J
    kinetic_energies = [] | units.J
    thermal_energies = [] | units.J
    for time, i_step in [(i * t_end / n_steps, i)
                         for i in range(0, n_steps + 1)]:
        hydro_code.evolve_model(time)
        times.append(time)
        potential_energies.append(hydro_code.potential_energy)
        kinetic_energies.append(hydro_code.kinetic_energy)
        thermal_energies.append(hydro_code.thermal_energy)
        hydro_plot([-1.0, 1.0, -1.0, 1.0] * (350 | units.RSun), hydro_code,
                   (100, 100),
                   os.path.join(
                       get_path_to_results(),
                       "supernova_hydro_image{0:=03}.png".format(i_step)))

    energy_plot(
        times, kinetic_energies, potential_energies, thermal_energies,
        os.path.join(get_path_to_results(), "supernova_energy_evolution.png"))

    hydro_code.stop()
    print "All done!\n"
Ejemplo n.º 42
0
def head_on_stellar_merger(
    masses=[0.3, 3.0] | units.MSun,
    star_age=310.0 | units.Myr,
    maximally_evolved_stars=False,
    initial_separation=4.0 | units.RSun,
    angle=numpy.pi / 3,
    initial_speed=3000.0 | units.km / units.s,
    initial_speed_perpendicular=30.0 | units.km / units.s,
    number_of_sph_particles=1000,
    t_end=1.0e4 | units.s,
    sph_code=Fi,
    steps_per_snapshot=4,
    snapshot_size=100,
    use_stored_stellar_models=True
):
    """
    masses: Mass of the two stars
    star_age: Initial age of the stars (if maximally_evolved_stars is False)
    maximally_evolved_stars: Evolve stars as far as the Stellar Evolution code
    can get
    number_of_sph_particles: Total number of particles of both stars, divided
    according to their masses
    t_end: (Physical, not computational) duration of the hydrodynamics
    simulation
    sph_code: Code to use for the hydrodynamics simulation
    steps_per_snapshot: A hydroplot snapshot is generated each time after this
    many steps (0 or None means no snapshots)
    snapshot_size: Size of the snapshot in pixels along one dimension
    use_stored_stellar_models: Flag to use previously stored stellar model
    files (for speed-up).
    """

    # Convert some of the input parameters to string, for use in output file
    # names:
    n_string = "n" + ("%1.0e" % (number_of_sph_particles)
                      ).replace("+0", "").replace("+", "")
    t_end_string = "t" + ("%1.0e" % (t_end.value_in(units.s))
                          ).replace("+0", "").replace("+", "")
    masses_string = (
            "m1_"
            + (
                "%0.3e" % (masses[0].value_in(units.MSun))
                ).replace("+0", "").replace("+", "")
            + "_m2_"
            + (
                "%0.3e" % (masses[1].value_in(units.MSun))
                ).replace("+0", "").replace("+", "")
            )
    if maximally_evolved_stars:
        star_age_string = "a_max"
    else:
        star_age_string = "a" + \
            ("%0.3e" % (star_age.value_in(units.Myr))).replace(
                "+0", "").replace("+", "")

    base_output_file_name = os.path.join(
        get_path_to_results(), "stellar_merger_"+n_string+"_"+t_end_string)
    pickle_file_1 = os.path.join(get_path_to_results(
    ), "stellar_merger_"+masses_string+"_"+star_age_string+"_1.pkl")
    pickle_file_2 = os.path.join(get_path_to_results(
    ), "stellar_merger_"+masses_string+"_"+star_age_string+"_2.pkl")

    if not use_stored_stellar_models or not (os.path.exists(pickle_file_1) and os.path.exists(pickle_file_2)):
        stars = Particles(2)
        stars.mass = masses
        try:
            stellar_evolution = MESA()
            stellar_evolution.initialize_code()
        except:
            print("MESA was not built. Returning.")
            return
        stellar_evolution.commit_parameters()
        stellar_evolution.particles.add_particles(stars)
        stellar_evolution.commit_particles()

        if maximally_evolved_stars:
            try:
                while True:
                    stellar_evolution.evolve_model()
            except AmuseException as exception:
                print(exception)
        else:
            stellar_evolution.evolve_model(star_age)

        if os.path.exists(pickle_file_1):
            print("Could not save stellar model 1: file already exists.")
        else:
            pickle_stellar_model(stellar_evolution.particles[0], pickle_file_1)
            print("Stellar model 1 saved at:", pickle_file_1)
        if os.path.exists(pickle_file_2):
            print("Could not save stellar model 2: file already exists.")
        else:
            pickle_stellar_model(stellar_evolution.particles[1], pickle_file_2)
            print("Stellar model 2 saved at:", pickle_file_2)
        
        stellar_evolution.stop()

    model_1 = StellarModel2SPH(None, None, pickle_file=pickle_file_1)
    model_2 = StellarModel2SPH(None, None, pickle_file=pickle_file_2)
    model_1.unpickle_stellar_structure()
    model_2.unpickle_stellar_structure()
    composition = model_2.composition_profile
    midpoints = model_2.midpoints_profile[1:-1]
    specific_internal_energy = model_2.specific_internal_energy_profile
    
    number_of_sph_particles_1 = int(
        round(
            number_of_sph_particles
            * (model_1.mass / (model_1.mass + model_2.mass))
        )
    )
    number_of_sph_particles_2 = (
        number_of_sph_particles
        - number_of_sph_particles_1
    )
    print("Creating initial conditions from a MESA stellar evolution model:")
    print(
        model_1.mass,
        "star consisting of",
        number_of_sph_particles_1,
        "particles."
    )
    sph_particles_1 = convert_stellar_model_to_SPH(
        None, 
        number_of_sph_particles_1, 
        seed=12345,
        pickle_file = pickle_file_1
    ).gas_particles
    print(
        model_2.mass,
        "star consisting of",
        number_of_sph_particles_2,
        "particles."
    )
    sph_particles_2 = convert_stellar_model_to_SPH(
            None,
            number_of_sph_particles_2,
            pickle_file=pickle_file_2
            ).gas_particles
    initial_separation += model_1.radius + model_2.radius
    sph_particles_2.x += numpy.cos(angle) * initial_separation
    sph_particles_2.y += numpy.sin(angle) * initial_separation
    sph_particles_1.vx += (
            numpy.cos(angle) * initial_speed
            - numpy.sin(angle) * initial_speed_perpendicular
            )
    sph_particles_1.vy += (
            numpy.cos(angle) * initial_speed_perpendicular
            + numpy.sin(angle) * initial_speed
            )
    view = (
            [-0.5, 0.5, -0.5, 0.5]
            * (initial_separation + model_1.radius + model_2.radius)
            )

    all_sph_particles = ParticlesSuperset([sph_particles_1, sph_particles_2])
    all_sph_particles.move_to_center()

    unit_converter = ConvertBetweenGenericAndSiUnits(
        1.0 | units.RSun, constants.G, t_end)
    hydro_legacy_code = sph_code(unit_converter)
    n_steps = 100
    hydro_legacy_code.parameters.n_smooth = 96
    try:
        hydro_legacy_code.parameters.timestep = t_end / n_steps
    except Exception as exc:
        if "parameter is read-only" not in str(exc):
            raise
    hydro_legacy_code.gas_particles.add_particles(all_sph_particles)

    times = [] | units.Myr
    kinetic_energies = [] | units.J
    potential_energies = [] | units.J
    thermal_energies = [] | units.J

    print("Evolving to:", t_end)
    for time, i_step in [(i*t_end/n_steps, i) for i in range(1, n_steps+1)]:
        hydro_legacy_code.evolve_model(time)
        times.append(time)
        kinetic_energies.append(hydro_legacy_code.kinetic_energy)
        potential_energies.append(hydro_legacy_code.potential_energy)
        thermal_energies.append(hydro_legacy_code.thermal_energy)
        if steps_per_snapshot and (not i_step % steps_per_snapshot):
            hydro_plot(
                view,
                hydro_legacy_code,
                (snapshot_size, snapshot_size),
                base_output_file_name +
                "_hydro_image{0:=03}.png".format(i_step)
            )

    hydro_legacy_code.gas_particles.new_channel_to(
            all_sph_particles
            ).copy_attributes(
                    ['mass', 'x', 'y', 'z', 'vx', 'vy', 'vz', 'u']
                    )
    center_of_mass = all_sph_particles.center_of_mass(
            ).as_quantity_in(units.RSun)
    center_of_mass_velocity = all_sph_particles.center_of_mass_velocity(
            ).as_quantity_in(units.km / units.s)
    print()
    print("center_of_mass:", center_of_mass)
    print("center_of_mass_velocity:", center_of_mass_velocity)
    all_sph_particles.position -= center_of_mass
    sph_midpoints = all_sph_particles.position.lengths()

    energy_plot(
        times,
        kinetic_energies, potential_energies, thermal_energies,
        base_output_file_name+"_energy_evolution.png"
    )
    thermal_energy_plot(
        times,
        thermal_energies,
        base_output_file_name+"_thermal_energy_evolution.png"
    )
    composition_comparison_plot(
        midpoints, composition[0],
        sph_midpoints, all_sph_particles.h1,
        base_output_file_name+"_composition_h1.png"
    )
    internal_energy_comparison_plot(
        midpoints, specific_internal_energy,
        sph_midpoints, all_sph_particles.u,
        base_output_file_name+"_new_u.png"
    )
    hydro_plot(
        [-2.0, 2.0, -2.0, 2.0] | units.RSun,
        hydro_legacy_code,
        (100, 100),
        base_output_file_name + "_hydro_image.png"
    )
    hydro_legacy_code.stop()
    print("All done!\n")
Ejemplo n.º 43
0
def run_supernova():
    # options:
    use_hydro_code = Gadget2  # Fi -or- Gadget2
    # e.g. dict(use_gl = True) or dict(redirection = "none")
    hydro_code_options = dict(number_of_workers=3)
    number_of_sph_particles = 30000
    t_end = 1.0e5 | units.s

    pickle_file = setup_stellar_evolution_model()

    print "Creating initial conditions from a MESA stellar evolution model..."
    model = convert_stellar_model_to_SPH(
        None,
        number_of_sph_particles,
        seed=12345,
        pickle_file=pickle_file,
        #        base_grid_options = dict(type = "glass", target_rms = 0.01),
        with_core_particle=True
    )
    core, gas_without_core, core_radius = \
        model.core_particle, model.gas_particles, model.core_radius
    if len(core):
        print "Created", len(
            gas_without_core), "SPH particles and one 'core-particle':\n", core
        print "Setting gravitational smoothing to:", core_radius
    else:
        print "Warning: Only SPH particles created."

    inject_supernova_energy(gas_without_core)

    print "\nEvolving (SPH) to:", t_end
    n_steps = 100

    unit_converter = ConvertBetweenGenericAndSiUnits(
        1.0 | units.RSun, constants.G, t_end)
    hydro_code = use_hydro_code(unit_converter, **hydro_code_options)

    try:
        hydro_code.parameters.timestep = t_end / n_steps
    except Exception as exc:
        if "parameter is read-only" not in str(exc):
            raise

    hydro_code.parameters.epsilon_squared = core_radius**2
    hydro_code.parameters.n_smooth_tol = 0.01
    hydro_code.gas_particles.add_particles(gas_without_core)
    hydro_code.dm_particles.add_particles(core)

    times = [] | units.s
    potential_energies = [] | units.J
    kinetic_energies = [] | units.J
    thermal_energies = [] | units.J
    for time, i_step in [(i*t_end/n_steps, i) for i in range(0, n_steps+1)]:
        hydro_code.evolve_model(time)
        times.append(time)
        potential_energies.append(hydro_code.potential_energy)
        kinetic_energies.append(hydro_code.kinetic_energy)
        thermal_energies.append(hydro_code.thermal_energy)
        hydro_plot(
            [-1.0, 1.0, -1.0, 1.0] * (350 | units.RSun),
            hydro_code,
            (100, 100),
            os.path.join(get_path_to_results(),
                         "supernova_hydro_image{0:=03}.png".format(i_step))
        )

    energy_plot(
            times, kinetic_energies, potential_energies, thermal_energies,
            os.path.join(
                get_path_to_results(),
                "supernova_energy_evolution.png"
                )
            )

    hydro_code.stop()
    print "All done!\n"