예제 #1
0
 def slowtest1(self):
     stellar_evolution = self.new_instance(MESA)
     stellar_evolution.particles.add_particles(Particles(2, mass=[1.0, 5.0]|units.MSun))
     stellar_evolution.evolve_model(10.0 | units.Myr)
     initial_separation = stellar_evolution.particles.radius.sum()
     
     sph_particles_1 = convert_stellar_model_to_SPH(
         stellar_evolution.particles[0], 
         200, 
         seed=12345
     ).gas_particles
     sph_particles_2 = convert_stellar_model_to_SPH(
         stellar_evolution.particles[1], 
         1000, 
         seed=12345
     ).gas_particles
     stellar_evolution.stop()
     
     initial_speed = 10.0 | units.km / units.s
     sph_particles_2.x  += initial_separation
     sph_particles_1.vx += initial_speed
     all_sph_particles = ParticlesSuperset([sph_particles_1, sph_particles_2])
     all_sph_particles.move_to_center()
     
     t_end = 4.0e3 | units.s
     print "Evolving to:", t_end
     n_steps = 4
     
     unit_system_converter = ConvertBetweenGenericAndSiUnits(1.0 | units.RSun, 1.0 | units.MSun, t_end)
     hydro_code = Gadget2(unit_system_converter)
     hydro_code.gas_particles.add_particles(all_sph_particles)
     
     pyplot.ion()
     for time in [i*t_end/n_steps for i in range(1, n_steps+1)]:
         hydro_code.evolve_model(time)
         pyplot.close('all')
         pyplot.figure()
         pynbody_column_density_plot(hydro_code.gas_particles, width=10|units.RSun)
         pyplot.draw()
         pyplot.figure()
         loglog(hydro_code.gas_particles.position.lengths_squared(), hydro_code.gas_particles.pressure, 'bo')
         pyplot.draw()
     
     hydro_code.stop()
     sleep(3)
     pyplot.ioff()
예제 #2
0
def convert_star_to_hydro_model(M, t_end):
    stellar_evolution = EVtwin()
    star = stellar_evolution.particles.add_particle(Particle(mass=M))
    stellar_evolution.evolve_model(t_end)
    Ngas = 10000
    sph_particles = convert_stellar_model_to_SPH(star, Ngas).gas_particles
    stellar_evolution.stop()
    return sph_particles
예제 #3
0
    def slowtest1(self):
        stellar_evolution = self.new_instance(MESA)
        stellar_evolution.particles.add_particles(
            Particles(2, mass=[1.0, 5.0] | units.MSun))
        stellar_evolution.evolve_model(10.0 | units.Myr)
        initial_separation = stellar_evolution.particles.radius.sum()

        sph_particles_1 = convert_stellar_model_to_SPH(
            stellar_evolution.particles[0], 200, seed=12345).gas_particles
        sph_particles_2 = convert_stellar_model_to_SPH(
            stellar_evolution.particles[1], 1000, seed=12345).gas_particles
        stellar_evolution.stop()

        initial_speed = 10.0 | units.km / units.s
        sph_particles_2.x += initial_separation
        sph_particles_1.vx += initial_speed
        all_sph_particles = ParticlesSuperset(
            [sph_particles_1, sph_particles_2])
        all_sph_particles.move_to_center()

        t_end = 4.0e3 | units.s
        print "Evolving to:", t_end
        n_steps = 4

        unit_system_converter = ConvertBetweenGenericAndSiUnits(
            1.0 | units.RSun, 1.0 | units.MSun, t_end)
        hydro_code = Gadget2(unit_system_converter)
        hydro_code.gas_particles.add_particles(all_sph_particles)

        pyplot.ion()
        for time in [i * t_end / n_steps for i in range(1, n_steps + 1)]:
            hydro_code.evolve_model(time)
            pyplot.close('all')
            pyplot.figure()
            pynbody_column_density_plot(hydro_code.gas_particles,
                                        width=10 | units.RSun)
            pyplot.draw()
            pyplot.figure()
            loglog(hydro_code.gas_particles.position.lengths_squared(),
                   hydro_code.gas_particles.pressure, 'bo')
            pyplot.draw()

        hydro_code.stop()
        sleep(3)
        pyplot.ioff()
예제 #4
0
파일: XiTau.py 프로젝트: sarasally/amuse
def convert_giant_to_sph(view_on_se_giant, number_of_sph_particles):
    giant_in_sph = convert_stellar_model_to_SPH(
        view_on_se_giant,
        number_of_sph_particles,
        with_core_particle = True,
        target_core_mass  = 1.4 | units.MSun,
        do_store_composition = False
    )
    return giant_in_sph
예제 #5
0
파일: XiTau.py 프로젝트: amusecode/amuse
def convert_giant_to_sph(view_on_se_giant, number_of_sph_particles):
    giant_in_sph = convert_stellar_model_to_SPH(
        view_on_se_giant,
        number_of_sph_particles,
        with_core_particle = True,
        target_core_mass  = 1.4 | units.MSun,
        do_store_composition = False
    )
    return giant_in_sph
예제 #6
0
 def convert_stars(self, particles, stellar_evolution_code):
     n_particles = self.divide_number_of_particles(particles)
     se_colliders = particles.get_intersecting_subset_in(stellar_evolution_code.particles)
     if self.verbose:
         print("Converting stars of {0} to SPH models of {1} particles, respectively.".format(particles.mass, n_particles))
     sph_models = (
         self.relax(convert_stellar_model_to_SPH(se_colliders[0], n_particles[0], **self.star_to_sph_arguments)),
         self.relax(convert_stellar_model_to_SPH(se_colliders[1], n_particles[1], **self.star_to_sph_arguments))
     )
     gas_particles = Particles()
     for particle, sph_model in zip(particles, sph_models):
         sph_model.position += particle.position
         sph_model.velocity += particle.velocity
         gas_particles.add_particles(sph_model)
     if self.verbose:
         print("Converting stars to SPH particles done")
     if self.debug:
         print(gas_particles)
     return gas_particles
예제 #7
0
 def convert_stars(self, particles, stellar_evolution_code):
     n_particles = self.divide_number_of_particles(particles)
     se_colliders = particles.get_intersecting_subset_in(stellar_evolution_code.particles)
     if self.verbose:
         print "Converting stars of {0} to SPH models of {1} particles, respectively.".format(particles.mass, n_particles)
     sph_models = (
         self.relax(convert_stellar_model_to_SPH(se_colliders[0], n_particles[0], **self.star_to_sph_arguments)),
         self.relax(convert_stellar_model_to_SPH(se_colliders[1], n_particles[1], **self.star_to_sph_arguments))
     )
     gas_particles = Particles()
     for particle, sph_model in zip(particles, sph_models):
         sph_model.position += particle.position
         sph_model.velocity += particle.velocity
         gas_particles.add_particles(sph_model)
     if self.verbose:
         print "Converting stars to SPH particles done"
     if self.debug:
         print gas_particles
     return gas_particles
예제 #8
0
def star_to_sph(star, number_of_sph_particles):
    stellar_evolution = stellar_evolution_code()
    se_star = stellar_evolution.particles.add_particle(star)
    stellar_evolution.evolve_model(22.7 | units.Myr)
    model = convert_stellar_model_to_SPH(se_star,
                                         number_of_sph_particles,
                                         do_store_composition=False,
                                         base_grid_options=dict(type="fcc"))
    stellar_evolution.stop()
    sph_star = model.gas_particles
    sph_star.position += star.position
    sph_star.velocity += star.velocity
    return sph_star
예제 #9
0
def create_particles():
    star = Particle()
    star.mass = 3.0 | units.MSun

    stellar_evolution = EVtwin()
    se_star = stellar_evolution.particles.add_particle(star)

    print("Evolving", star.mass, "star with",
          stellar_evolution.__class__.__name__, "up to", 100 | units.Myr)
    stellar_evolution.evolve_model(100 | units.Myr)

    print("Creating SPH particles from the (1D) stellar evolution model")
    sph_particles = convert_stellar_model_to_SPH(se_star, 1000).gas_particles
    stellar_evolution.stop()
    return sph_particles
예제 #10
0
def set_up_sph_giant(giant, stellar_structure_file, number_of_sph_particles):
    model = convert_stellar_model_to_SPH(None,
                                         number_of_sph_particles,
                                         pickle_file=stellar_structure_file,
                                         with_core_particle=True,
                                         target_core_mass=2.0 | units.MSun,
                                         do_store_composition=False,
                                         base_grid_options=dict(type="fcc"))
    sph_giant = model.gas_particles
    core = model.core_particle
    sph_giant.position += giant.position
    sph_giant.velocity += giant.velocity
    core.position += giant.position
    core.velocity += giant.velocity
    print "Core radius:", model.core_radius.as_string_in(units.RSun)
    return sph_giant, core, model.core_radius
예제 #11
0
파일: hydro_star.py 프로젝트: Ingwar/amuse
def create_particles():
    star =  Particle()
    star.mass = 3.0 | units.MSun
    
    stellar_evolution = EVtwin()
    se_star = stellar_evolution.particles.add_particle(star)
    
    print("Evolving", star.mass, "star with", stellar_evolution.__class__.__name__, "up to", 100 | units.Myr)
    stellar_evolution.evolve_model(100 | units.Myr)
    
    print("Creating SPH particles from the (1D) stellar evolution model")
    sph_particles = convert_stellar_model_to_SPH(
        se_star, 
        1000
    ).gas_particles
    stellar_evolution.stop()
    return sph_particles
예제 #12
0
def star_to_sph(mass, age, omega, Nsph):
    stellar = evolve_star(mass, age)
    new_age = stellar.model_time
    star = stellar.particles[0]
    if star.core_mass>zero:
        with_core_particle = True
        target_core_mass  = coremass
    else:
        with_core_particle = False
        target_core_mass  = 0|units.MSun

    m_sph = (star.mass-target_core_mass)/float(Nsph)
    print "N_sph=", Nsph, m_sph.in_(units.MSun)
    print "Target core mass:", target_core_mass
    model = convert_stellar_model_to_SPH(
        star, 
        Nsph,
        with_core_particle = with_core_particle,
        target_core_mass  = target_core_mass,
        do_store_composition = False,
        base_grid_options=dict(type="fcc")
    )
    print "Final star:", star
    age = stellar.model_time
    M_scale = star.mass
    R_scale = star.radius
    stellar.stop()

    core = model.core_particle
    print "core", core
    if core is None:
        print "Make zero mass core"
        core = Particle(mass=0|units.MSun, radius=1|units.RSun)
        core.position = (0,0,0) | units.AU
        core.velocity = (0,0,0) | units.kms
    sph_star = model.gas_particles
    print "Add Spin to star:", omega
    sph_star.add_spin(omega)

    relaxed_sph_star, core_particles = relax_sph_realization(sph_star, core)
    return relaxed_sph_star, core_particles, age
예제 #13
0
def star_to_sph(stellar, omega, Nsph):
    new_age = stellar.model_time
    star = stellar.particles[0]
    if star.core_mass>zero:
        with_core_particle = True
        target_core_mass  = coremass
    else:
        with_core_particle = False
        target_core_mass  = 0|units.MSun

    m_sph = (star.mass-target_core_mass)/float(Nsph)
    print "N_sph=", Nsph, m_sph.in_(units.MSun)
    print "Target core mass:", target_core_mass
    model = convert_stellar_model_to_SPH(
        star, 
        Nsph,
        with_core_particle = with_core_particle,
        target_core_mass  = target_core_mass,
        do_store_composition = False,
        base_grid_options=dict(type="fcc")
    )
    print "Final star:", star
    age = stellar.model_time
    M_scale = star.mass
    R_scale = star.radius
    stellar.stop()

    core = model.core_particle
    print "core", core
    if core is None:
        print "Make zero mass core"
        core = Particle(mass=0|units.MSun, radius=1|units.RSun)
        core.position = (0,0,0) | units.AU
        core.velocity = (0,0,0) | units.kms
    sph_star = model.gas_particles
    print "Add Spin to star:", omega
    sph_star.add_spin(omega)

    relaxed_sph_star, core_particles = relax_sph_realization(sph_star, core)
    return relaxed_sph_star, core_particles, age
예제 #14
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
예제 #15
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
def merge_two_stars_sph_and_evolve(Mprim, Msec, tcoll, tend):
    stars = Particles(2)
    stars[0].mass = Mprim
    stars[1].mass = Msec
    stellar = EVtwin()
    stellar.particles.add_particle(stars[0])
    stellar.particles.add_particle(stars[1])
    
    time = [] | units.Myr
    mass = [] | units.MSun
    radius = [] | units.RSun
    temperature = [] | units.K
    luminosity = [] | units.LSun
    while stellar.model_time < tcoll:
        stellar.evolve_model()
        time.append(stellar.model_time)
        mass.append(stellar.particles[0].mass)
        radius.append(stellar.particles[0].radius)
        temperature.append(stellar.particles[0].temperature)
        luminosity.append(stellar.particles[0].luminosity)
        print "Time=", time[-1], mass[-1], radius[-1], \
              temperature[-1].in_(units.K), luminosity[-1].in_(units.LSun)
    n_normal = len(time)

    print stars
    Nprim = int(100*stellar.particles[0].mass.value_in(units.MSun))
    mgas = stellar.particles[0].mass/Nprim
    Nsec = int(stellar.particles[1].mass/mgas)
    print "N gas=", Nprim, Nsec
    sph_primary = convert_stellar_model_to_SPH(
        stellar.particles[0],
        Nprim, 
        seed=12345
    ).gas_particles
    sph_secondary = convert_stellar_model_to_SPH(
        stellar.particles[0], 
        Nsec, 
        seed=12345
    ).gas_particles
    stellar.stop()

    distance = 1 | units.RSun
    sph_secondary.x += distance
    sph_secondary.vx -= 1.7*numpy.sqrt(2*constants.G*stars.mass.sum()/distance)

    sph_particles = Particles()
    sph_particles.add_particles(sph_primary)
    #sph_particles.add_particles(sph_secondary)
    sph_particles.move_to_center()

    converter = nbody_system.nbody_to_si(1|units.hour, 1|units.RSun)

    hydrodynamics = Gadget2(converter)
    hydrodynamics.gas_particles.add_particles(sph_particles)
    hydrodynamics.evolve_model(10.0|units.hour)
    hydrodynamics.gas_particles.copy_values_of_attributes_to(["density", "u",
                                                              "pressure"],
                                                             sph_particles)
    hydrodynamics.stop()

    print "N all=", len(sph_particles)
    clumps = find_clumps(sph_particles, converter)
    #sph_particles = clumps[0]
    print "N blob=", len(sph_particles)
    #plot_clumps(clumps)
    #sph_merger = sph_particles[0]

    print "convert SPH to stellar model"
    merged_star = convert_SPH_to_stellar_model(sph_particles)

    print "initiate stellar evolution model"
    #stellar_evolution = MESA()
    stellar_evolution = EVtwin(redirect="none")    
    stellar_evolution.new_particle_from_model(merged_star, 0.0|units.Myr)
    print "star:", stellar_evolution.particles
    print "evolve star"
    #stellar_evolution.evolve_model(tend)
    while stellar_evolution.model_time<(tend-tcoll):
        stellar_evolution.evolve_model()
        time.append(stellar_evolution.model_time)
        mass.append(stellar_evolution.particles[0].mass)
        radius.append(stellar_evolution.particles[0].radius)
        temperature.append(stellar_evolution.particles[0].temperature)
        luminosity.append(stellar_evolution.particles[0].luminosity)
        print "Time=", time[-1], mass[-1], radius[-1], \
              temperature[-1].in_(units.K), luminosity[-1].in_(units.LSun)

    print stellar_evolution.particles
    stellar_evolution.stop()
    
    return time, mass, radius, temperature, luminosity, n_normal
예제 #17
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")
예제 #18
0
def merge_two_stars_sph_and_evolve(Mprim, Msec, tcoll, tend):
    stars = Particles(2)
    stars.mass = [Mprim.value_in(units.MSun),
                  Msec.value_in(units.MSun)] | units.MSun
    stellar_evolution = MESA()
    stellar_evolution.particles.add_particles(stars)

    # Evolve the stars to tcoll.
    
    while stellar_evolution.model_time < tcoll:
        stellar_evolution.evolve_model()
        print "Time=", stellar_evolution.model_time, \
              stellar_evolution.particles[0].stellar_type, \
              stellar_evolution.particles[0].mass, \
              stellar_evolution.particles[0].radius, \
              stellar_evolution.particles[0].temperature.in_(units.K), \
              stellar_evolution.particles[0].luminosity.in_(units.LSun)

    print stars

    # Convert to SPH particles (nsph per solar mass).

    nsph = 100
    Nprim = int(nsph*stellar_evolution.particles[0].mass.value_in(units.MSun))
    mgas = stellar_evolution.particles[0].mass/Nprim
    Nsec = int(stellar_evolution.particles[1].mass/mgas)
    print "N gas =", Nprim, Nsec
    sph_primary = convert_stellar_model_to_SPH(
        stellar_evolution.particles[0],
        Nprim, 
        seed=12345
    ).gas_particles
    sph_secondary = convert_stellar_model_to_SPH(
        stellar_evolution.particles[1], 
        Nsec, 
        seed=12345
    ).gas_particles
    stellar_evolution.stop()

    # Merge the stars using SPH.
    
    distance = 2 | units.RSun
    sph_secondary.x += distance
    vx = numpy.sqrt(2*constants.G*stars.mass.sum()/distance)
    sph_secondary.vx -= vx
    print 'distance =', distance, 'vx =', vx.in_(units.kms),
    print 'd/v =', (distance/vx).in_(units.hour)
    
    sph_particles = Particles()
    sph_particles.add_particles(sph_primary)
    sph_particles.add_particles(sph_secondary)
    sph_particles.move_to_center()
    
    converter = nbody_system.nbody_to_si(1|units.hour, 1|units.RSun)
    hydrodynamics = Gadget2(converter)
    hydrodynamics.gas_particles.add_particles(sph_particles)
    tf = 10.|units.hour
    hydrodynamics.evolve_model(tf)
    hydrodynamics.gas_particles.copy_values_of_attributes_to(["x", "y", "z",
                                                              "vx", "vy", "vz",
                                                              "density",
                                                              "u", "pressure"],
                                                             sph_particles)
    hydrodynamics.stop()

    # Convert back to a stellar model.
    
    print "N all =", len(sph_particles)
    sph_particles.move_to_center()
    clumps = find_clumps(sph_particles, converter)
    sph_particles = clumps[0]
    print "N blob =", len(sph_particles)
    #plot_clumps(clumps)
    print "convert SPH to stellar model"
    sph_particles.move_to_center()
    merged_star = convert_SPH_to_stellar_model(sph_particles)

    # Evolve the stellar model.
    
    print "initiate stellar evolution model"
    #stellar_evolution = MESA(redirect="none")    
    stellar_evolution = EVtwin(redirect="none")    
    stellar_evolution.new_particle_from_model(merged_star, 0.0|units.Myr)
    print "star:", stellar_evolution.particles
    print "evolve star"
    time = [] | units.Myr
    mass = [] | units.MSun
    radius = [] | units.RSun
    temperature = [] | units.K
    luminosity = [] | units.LSun
    stellar_type = [] 
    while stellar_evolution.model_time < (tend-tcoll):
        try:
            stellar_evolution.evolve_model()
            time.append(stellar_evolution.model_time)
            mass.append(stellar_evolution.particles[0].mass)
            radius.append(stellar_evolution.particles[0].radius)
            temperature.append(stellar_evolution.particles[0].temperature)
            luminosity.append(stellar_evolution.particles[0].luminosity)
            stellar_type.append(stellar_evolution.particles[0].stellar_type)
            print "Time=", time[-1], stellar_type[-1], mass[-1], radius[-1], \
                temperature[-1].in_(units.K), luminosity[-1].in_(units.LSun)
            if stellar_type[-1] >= 4 | units.stellar_type:
                break
        except:
            print 'Code crashed at time', stellar_evolution.model_time
            break

    stellar_evolution.stop()
    return time, stellar_type, mass, radius, temperature, luminosity
예제 #19
0
def merge_two_stars_spz_and_evolve(Mprim, Msec, tcoll, tend):

    stellar = EVtwin()
    stars = Particles(2)
    stars[0].mass = Mprim
    stars[1].mass = Msec
    stellar.particles.add_particle(stars[0])
    stellar.particles.add_particle(stars[1])
    time = [] | units.Myr
    mass = [] | units.MSun
    radius = [] | units.RSun
    temperature = [] | units.K
    luminosity = [] | units.LSun
    while stellar.model_time<tcoll:
        stellar.evolve_model()
        time.append(stellar.model_time)
        mass.append(stellar.particles[0].mass)
        radius.append(stellar.particles[0].radius)
        temperature.append(stellar.particles[0].temperature)
        luminosity.append(stellar.particles[0].luminosity)
        print "Time=", time[-1], mass[-1], radius[-1], temperature[-1].in_(units.K), luminosity[-1].in_(units.LSun)
    n_normal = len(time)

    print stars
    Nprim = int(100*stellar.particles[0].mass.value_in(units.MSun))
    mgas = stellar.particles[0].mass/Nprim
    Nsec = int(stellar.particles[1].mass/mgas)
    print "N gas=", Nprim, Nsec
    sph_primary = convert_stellar_model_to_SPH(
        stellar.particles[0], 
        Nprim, 
        seed=12345
    ).gas_particles
    sph_secondary = convert_stellar_model_to_SPH(
        stellar.particles[0], 
        Nsec, 
        seed=12345
    ).gas_particles
    stellar.stop()

    distance = 1 | units.RSun
    sph_secondary.x += distance
    sph_secondary.vx -= 1.7*numpy.sqrt(2*constants.G*stars.mass.sum()/distance)

    sph_particles = Particles()
    sph_particles.add_particles(sph_primary)
    #sph_particles.add_particles(sph_secondary)
    sph_particles.move_to_center()

    converter = nbody_system.nbody_to_si(1|units.hour, 1|units.RSun)

    hydrodynamics = Gadget2(converter)
    hydrodynamics.gas_particles.add_particles(sph_particles)
    hydrodynamics.evolve_model(10.0|units.hour)
    hydrodynamics.gas_particles.copy_values_of_attributes_to(["density", "u", "pressure"],
                                                             sph_particles)
    hydrodynamics.stop()

    print "N all=", len(sph_particles)
    clumps = find_clumps(sph_particles, converter)
    #sph_particles = clumps[0]
    print "N blob=", len(sph_particles)
    #plot_clumps(clumps)
    #sph_merger = sph_particles[0]

    print "convert SPH to stellar model"
    merged_star = convert_SPH_to_stellar_model(sph_particles)

    #stellar_evolution = MESA()
    print "initiate stellar evolution model"
    stellar_evolution = EVtwin(redirect="none")    
    stellar_evolution.new_particle_from_model(merged_star, 0.0|units.Myr)
    print "star:", stellar_evolution.particles
    print "evolve star"
    #stellar_evolution.evolve_model(tend)
    while stellar_evolution.model_time<(tend-tcoll):
        stellar_evolution.evolve_model()
        time.append(stellar_evolution.model_time)
        mass.append(stellar_evolution.particles[0].mass)
        radius.append(stellar_evolution.particles[0].radius)
        temperature.append(stellar_evolution.particles[0].temperature)
        luminosity.append(stellar_evolution.particles[0].luminosity)
        print "Time=", time[-1], mass[-1], radius[-1], temperature[-1].in_(units.K), luminosity[-1].in_(units.LSun)

    print stellar_evolution.particles
    stellar_evolution.stop()
    
    return time, mass, radius, temperature, luminosity, n_normal
예제 #20
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"
    set_printing_strategy(
        "custom",  #nbody_converter = converter, 
        preferred_units=[units.MSun, units.RSun, units.Myr],
        precision=11,
        prefix="",
        separator=" [",
        suffix="]")

    o, arguments = new_option_parser().parse_args()

    print "initialize star"
    stellar_evolution = EVtwin()
    stellar_evolution.particles.add_particle(Particle(mass=o.Mprim))
    stellar_evolution.evolve_model(o.time)
    particles = convert_stellar_model_to_SPH(stellar_evolution.particles[0],
                                             500,
                                             seed=12345).gas_particles
    stellar_evolution.stop()
    from amuse.units.generic_unit_converter import ConvertBetweenGenericAndSiUnits

    print "convert star to SPH"
    converter = nbody_system.nbody_to_si(1 | units.hour, 1 | units.RSun)
    hydrodynamics = Gadget2(converter)
    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()

    print "convert SPH to stellar model"
    model = convert_SPH_to_stellar_model(particles)
def merge_two_stars_sph_and_evolve(Mprim, Msec, tcoll, tend):
    stars = Particles(2)
    stars.mass = [Mprim.value_in(units.MSun),
                  Msec.value_in(units.MSun)] | units.MSun
    stellar_evolution = MESA()
    stellar_evolution.particles.add_particles(stars)

    # Evolve the stars to tcoll.

    while stellar_evolution.model_time < tcoll:
        stellar_evolution.evolve_model()
        print "Time=", stellar_evolution.model_time, \
              stellar_evolution.particles[0].stellar_type, \
              stellar_evolution.particles[0].mass, \
              stellar_evolution.particles[0].radius, \
              stellar_evolution.particles[0].temperature.in_(units.K), \
              stellar_evolution.particles[0].luminosity.in_(units.LSun)

    print stars

    # Convert to SPH particles (nsph per solar mass).

    nsph = 100
    Nprim = int(nsph *
                stellar_evolution.particles[0].mass.value_in(units.MSun))
    mgas = stellar_evolution.particles[0].mass / Nprim
    Nsec = int(stellar_evolution.particles[1].mass / mgas)
    print "N gas =", Nprim, Nsec
    sph_primary = convert_stellar_model_to_SPH(stellar_evolution.particles[0],
                                               Nprim,
                                               seed=12345).gas_particles
    sph_secondary = convert_stellar_model_to_SPH(
        stellar_evolution.particles[1], Nsec, seed=12345).gas_particles
    stellar_evolution.stop()

    # Merge the stars using SPH.

    distance = 2 | units.RSun
    sph_secondary.x += distance
    vx = numpy.sqrt(2 * constants.G * stars.mass.sum() / distance)
    sph_secondary.vx -= vx
    print 'distance =', distance, 'vx =', vx.in_(units.kms),
    print 'd/v =', (distance / vx).in_(units.hour)

    sph_particles = Particles()
    sph_particles.add_particles(sph_primary)
    sph_particles.add_particles(sph_secondary)
    sph_particles.move_to_center()

    converter = nbody_system.nbody_to_si(1 | units.hour, 1 | units.RSun)
    hydrodynamics = Gadget2(converter)
    hydrodynamics.gas_particles.add_particles(sph_particles)
    tf = 10. | units.hour
    hydrodynamics.evolve_model(tf)
    hydrodynamics.gas_particles.copy_values_of_attributes_to(
        ["x", "y", "z", "vx", "vy", "vz", "density", "u", "pressure"],
        sph_particles)
    hydrodynamics.stop()

    # Convert back to a stellar model.

    print "N all =", len(sph_particles)
    sph_particles.move_to_center()
    clumps = find_clumps(sph_particles, converter)
    sph_particles = clumps[0]
    print "N blob =", len(sph_particles)
    #plot_clumps(clumps)
    print "convert SPH to stellar model"
    sph_particles.move_to_center()
    merged_star = convert_SPH_to_stellar_model(sph_particles)

    # Evolve the stellar model.

    print "initiate stellar evolution model"
    #stellar_evolution = MESA(redirect="none")
    stellar_evolution = EVtwin(redirect="none")
    stellar_evolution.new_particle_from_model(merged_star, 0.0 | units.Myr)
    print "star:", stellar_evolution.particles
    print "evolve star"
    time = [] | units.Myr
    mass = [] | units.MSun
    radius = [] | units.RSun
    temperature = [] | units.K
    luminosity = [] | units.LSun
    stellar_type = []
    while stellar_evolution.model_time < (tend - tcoll):
        try:
            stellar_evolution.evolve_model()
            time.append(stellar_evolution.model_time)
            mass.append(stellar_evolution.particles[0].mass)
            radius.append(stellar_evolution.particles[0].radius)
            temperature.append(stellar_evolution.particles[0].temperature)
            luminosity.append(stellar_evolution.particles[0].luminosity)
            stellar_type.append(stellar_evolution.particles[0].stellar_type)
            print "Time=", time[-1], stellar_type[-1], mass[-1], radius[-1], \
                temperature[-1].in_(units.K), luminosity[-1].in_(units.LSun)
            if stellar_type[-1] >= 4 | units.stellar_type:
                break
        except:
            print 'Code crashed at time', stellar_evolution.model_time
            break

    stellar_evolution.stop()
    return time, stellar_type, mass, radius, temperature, luminosity
예제 #23
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"
예제 #24
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"
예제 #25
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"