def plot_plummer_model(N, M, R):
    sph_particles = plummer_model(N, M, R)
    x_label = "x [pc]"
    y_label = "y [pc]"
    figure, ax = figure_frame(x_label, y_label, xsize=12, ysize=12)
    sph_particles_plot(sph_particles, min_size = 500, max_size = 500, alpha=0.01, view=(-50, 50, -50, 50)|units.parsec)
    ax.set_axis_bgcolor('white')
    pyplot.xlabel(x_label)
    pyplot.ylabel(y_label)
    native_plot.savefig("plummer_projected")
def plot_stellar_model(N, M, t):
    sph_particles = stellar_model(N, M, t)
    x_label = "x [R$_\odot$]"
    y_label = "y [R$_\odot$]"
    figure, ax = figure_frame(x_label, y_label, xsize=12, ysize=12)
    sph_particles_plot(sph_particles, min_size = 500, max_size = 500, alpha=0.01, view=(-5, 5, -5, 5)|units.RSun)
#    sph_particles_plot(sph_particles, min_size = 500, max_size = 500, alpha=0.01, view=(-2, 2, -2, 2)|units.RSun)
    ax.set_axis_bgcolor('white')
    pyplot.xlabel(x_label)
    pyplot.ylabel(y_label)
    native_plot.savefig("stellar_2MSun_projected")
def plot_GMC_model(N, M, R):
    sph_particles = GMC_model(N, M, R)
    x_label = "x [pc]"
    y_label = "y [pc]"
    figure, ax = figure_frame(x_label, y_label, xsize=12, ysize=12)
    sph_particles_plot(sph_particles, min_size = 500,
                       max_size = 500, alpha=0.01,
                       view=(-20, 20, -20, 20)|units.parsec)
    ax.set_facecolor('white')

    file = 'molecular_cloud_projected.png'
    pyplot.savefig(file)
    print 'Saved figure in file', file
def plot_plummer_model(N, M, R):
    sph_particles = plummer_model(N, M, R)
    x_label = "x [pc]"
    y_label = "y [pc]"
    figure, ax = figure_frame(x_label, y_label, xsize=12, ysize=12)
    sph_particles_plot(sph_particles,
                       min_size=500,
                       max_size=500,
                       alpha=0.01,
                       view=(-50, 50, -50, 50) | units.parsec)
    ax.set_axis_bgcolor('white')
    pyplot.xlabel(x_label)
    pyplot.ylabel(y_label)
    native_plot.savefig("plummer_projected")
def plot_ZAMS_stellar_model(N, M):
    sph_particles = stellar_model(N, M)
    x_label = "x [R$_\odot$]"
    y_label = "y [R$_\odot$]"
    figure, ax = figure_frame(x_label, y_label, xsize=12, ysize=12)
    sph_particles_plot(sph_particles, min_size = 500,
                       max_size = 500, alpha=0.01,
                       view=(-2, 2, -2, 2)|units.RSun)
    ax.set_facecolor('white')
    
    save_file = 'stellar_2MSunZAMS_projected.png'
    pyplot.savefig(save_file)
    print 'Saved figure in file', save_file, '\n'
    pyplot.show()
def plot_GMC_model(N, M, R):
    sph_particles = GMC_model(N, M, R)
    x_label = "x [pc]"
    y_label = "y [pc]"
    figure, ax = figure_frame(x_label, y_label, xsize=12, ysize=12)
    lim = 20
    sph_particles_plot(sph_particles, min_size = 500,
                       max_size = 500, alpha=0.01,
                       view=(-lim, lim, -lim, lim)|units.parsec)
    ax.set_facecolor('white')

    save_file = 'molecular_cloud_projected.png'
    pyplot.savefig(save_file)
    print('Saved figure in file', save_file)
def plot_stellar_model(N, M, t):
    sph_particles = stellar_model(N, M, t)
    x_label = "x [R$_\odot$]"
    y_label = "y [R$_\odot$]"
    figure, ax = figure_frame(x_label, y_label, xsize=12, ysize=12)
    sph_particles_plot(sph_particles,
                       min_size=500,
                       max_size=500,
                       alpha=0.01,
                       view=(-5, 5, -5, 5) | units.RSun)
    #    sph_particles_plot(sph_particles, min_size = 500, max_size = 500, alpha=0.01, view=(-2, 2, -2, 2)|units.RSun)
    ax.set_axis_bgcolor('white')
    pyplot.xlabel(x_label)
    pyplot.ylabel(y_label)
    native_plot.savefig("stellar_2MSun_projected")
def plot_GMC_model(N, M, R):
    sph_particles = GMC_model(N, M, R)

    x_label = "x [pc]"
    y_label = "y [pc]"
    figure, ax = figure_frame(x_label, y_label, xsize=12, ysize=12)
    lim = 20
    sph_particles_plot(sph_particles,
                       min_size=500,
                       max_size=500,
                       alpha=0.01,
                       view=(-lim, lim, -lim, lim) | units.parsec)
    ax.set_axis_bgcolor('white')
    #native_plot.savefig("molecular_cloud_projected")
    pyplot.savefig("molecular_cloud_projected")
Exemple #9
0
def plot_ZAMS_stellar_model(N, M):
    sph_particles = stellar_model(N, M)
    x_label = "x [R$_\odot$]"
    y_label = "y [R$_\odot$]"
    figure, ax = figure_frame(x_label, y_label, xsize=12, ysize=12)
    sph_particles_plot(sph_particles,
                       min_size=500,
                       max_size=500,
                       alpha=0.01,
                       view=(-2, 2, -2, 2) | units.RSun)
    ax.set_facecolor('white')

    save_file = 'stellar_2MSunZAMS_projected.png'
    pyplot.savefig(save_file)
    print 'Saved figure in file', save_file, '\n'
    pyplot.show()
def plot_ZAMS_stellar_model(N, M):
    sph_particles = stellar_model(N, M)
    figure = pyplot.figure(figsize=(12, 12))
    plot = figure.add_subplot(1, 1, 1)
    pyplot.rcParams.update({'font.size': 30})
    ax = pyplot.gca()
    ax.minorticks_on()  # switch on the minor ticks
    ax.locator_params(nbins=3)
    ax.get_yaxis().get_major_formatter().set_useOffset(False)
    ax.minorticks_on()  # switch on the minor ticks
    lim = 2
    sph_particles_plot(sph_particles,
                       min_size=500,
                       max_size=500,
                       alpha=0.01,
                       view=(-lim, lim, -lim, lim) | units.RSun)
    ax.set_axis_bgcolor('white')
    pyplot.xlabel("x [R$_\odot$]")
    pyplot.ylabel("y [R$_\odot$]")
    #native_plot.savefig("stellar_2MSunZAMS_projected")
    pyplot.savefig("stellar_2MSunZAMS_projected")
def plot_ZAMS_stellar_model(N, M):
    sph_particles = stellar_model(N, M)
    figure = pyplot.figure(figsize=(12, 12))
    plot = figure.add_subplot(1,1,1)
    pyplot.rcParams.update({'font.size': 30})
    ax = pyplot.gca()
    ax.minorticks_on()
    ax.locator_params(nbins=3)
    ax.get_yaxis().get_major_formatter().set_useOffset(False)
    ax.minorticks_on()
    lim = 2
    sph_particles_plot(sph_particles, min_size = 500,
                       max_size = 500, alpha=0.01,
                       view=(-lim, lim, -lim, lim)|units.RSun)
    ax.set_facecolor('white')
    pyplot.xlabel("x [R$_\odot$]")
    pyplot.ylabel("y [R$_\odot$]")

    file = 'stellar_2MSunZAMS_projected.png'
    pyplot.savefig(file)
    print('Saved figure in file', file, '\n')
def plot_ZAMS_stellar_model(N, M):
    sph_particles = stellar_model(N, M)
    figure = pyplot.figure(figsize=(12, 12))
    plot = figure.add_subplot(1,1,1)
    pyplot.rcParams.update({'font.size': 30})
    ax = pyplot.gca()
    ax.minorticks_on()
    ax.locator_params(nbins=3)
    ax.get_yaxis().get_major_formatter().set_useOffset(False)
    ax.minorticks_on()
    lim = 2
    sph_particles_plot(sph_particles, min_size = 500,
                       max_size = 500, alpha=0.01,
                       view=(-lim, lim, -lim, lim)|units.RSun)
    ax.set_facecolor('white')
    pyplot.xlabel("x [R$_\odot$]")
    pyplot.ylabel("y [R$_\odot$]")

    file = 'stellar_2MSunZAMS_projected.png'
    pyplot.savefig(file)
    print 'Saved figure in file', file, '\n'
Exemple #13
0
from amuse.units import units
from amuse.community.evtwin.interface import EVtwin
from amuse.ext.star_to_sph import convert_stellar_model_to_SPH
from amuse.datamodel import Particle

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

if __name__ in ("__main__", "__plot__"):
    from amuse.plot import sph_particles_plot, native_plot
    sph_particles = convert_star_to_hydro_model(2.0|units.MSun, 110|units.Myr)
    native_plot.figure(figsize = (10, 10), dpi = 50)
    sph_particles_plot(sph_particles)
    native_plot.show()
def collide_two_stars(t_end, distance, offset, v_vesc, nsteps):
    filename = "Hydro_AM06MSun.h5"
    try:
        pstar = read_set_from_file(filename, format='hdf5')
    except:
        from local_star_to_sph import evolve_star_and_convert_to_sph
        mass = 0.6|units.MSun
        age = 8 | units.Gyr
        omega = 0|units.s**-1
        Nsph = 1000
        pstar, pcore = evolve_star_and_convert_to_sph(mass, age, omega, Nsph)

    print pstar
    pmass = pstar.mass.sum()
    print pmass.in_(units.MSun)

    filename = "Hydro_BM06MSun.h5"
    try:
        sstar = read_set_from_file(filename, format='hdf5')
    except:
        from local_star_to_sph import evolve_star_and_convert_to_sph
        mass = 0.6|units.MSun
        age = 8 | units.Gyr
        omega = 0|units.s**-1
        Nsph = 1000
        sstar, score = evolve_star_and_convert_to_sph(mass, age, omega, Nsph)
    print sstar
    smass = sstar.mass.sum()
    print smass.in_(units.MSun)

    import numpy
    v_esc = numpy.sqrt(2*constants.G*pmass/distance)
    velocity = v_vesc*v_esc
    
    sstar.x += distance
    sstar.y += offset
    sstar.vx -= velocity

    sph_particles = Particles(0)
    sph_particles.add_particles(pstar)
    sph_particles.add_particles(sstar)
    sph_particles.move_to_center()
    converter=nbody_system.nbody_to_si(pmass, distance)

    hydro = Fi(converter)

    dt = t_end/float(nsteps)

    hydro.gas_particles.add_particles(pstar)
    hydro.gas_particles.add_particles(sstar)
    Etot_init = hydro.kinetic_energy + hydro.potential_energy + hydro.thermal_energy
    to_framework = hydro.gas_particles.new_channel_to(sph_particles)

    output_file = "1987ApJ...323..614B.h5"
    write_set_to_file(sph_particles.savepoint(0.0 | t_end.unit), output_file, "hdf5", append_to_file=False)

    time = 0.0 | t_end.unit
    while time < t_end:
        time += dt
        print time
        hydro.evolve_model(time)
        to_framework.copy()

        """
        from amuse.plot import sph_particles_plot
        sph_particles_plot(hydro.particles)
        from matplotlib import pyplot
        pyplot.show()
        """

        write_set_to_file(sph_particles.savepoint(time), output_file, "hdf5")

        """
        Ekin = hydro.kinetic_energy 
        Epot = hydro.potential_energy
        Eth = hydro.thermal_energy
        Etot = Ekin + Epot + Eth
        print "T=", hydro.get_time(), "M=", hydro.gas_particles.mass.sum(), 
        print "E= ", Etot, "Q= ", (Ekin+Eth)/Epot, "dE=", (Etot_init-Etot)/Etot
        """

    from amuse.plot import sph_particles_plot
    sph_particles_plot(hydro.particles)
    from matplotlib import pyplot
    pyplot.show()

    hydro.stop()
Exemple #15
0
def evolve_coupled_system(binary_system, giant_system, t_end, n_steps, 
        do_energy_evolution_plot, previous_data=None):
    directsum = CalculateFieldForParticles(particles=giant_system.particles, gravity_constant=constants.G)
    directsum.smoothing_length_squared = giant_system.parameters.gas_epsilon**2
    coupled_system = Bridge(timestep=(t_end / (2 * n_steps)), verbose=False, use_threading=True)
    coupled_system.add_system(binary_system, (directsum,), False)
    coupled_system.add_system(giant_system, (binary_system,), False)
    
    times = (t_end * list(range(1, n_steps+1)) / n_steps).as_quantity_in(units.day)
    
    if previous_data:
        with open(previous_data, 'rb') as file:
            (all_times, potential_energies, kinetic_energies, thermal_energies, 
                giant_center_of_mass, ms1_position, ms2_position, 
                giant_center_of_mass_velocity, ms1_velocity, ms2_velocity) = pickle.load(file)
        all_times.extend(times + all_times[-1])
    else:
        all_times = times
        if do_energy_evolution_plot:
            potential_energies = coupled_system.particles.potential_energy().as_vector_with_length(1).as_quantity_in(units.erg)
            kinetic_energies = coupled_system.particles.kinetic_energy().as_vector_with_length(1).as_quantity_in(units.erg)
            thermal_energies = coupled_system.gas_particles.thermal_energy().as_vector_with_length(1).as_quantity_in(units.erg)
        else:
            potential_energies = kinetic_energies = thermal_energies = None
        
        giant_center_of_mass = [] | units.RSun
        ms1_position = [] | units.RSun
        ms2_position = [] | units.RSun
        giant_center_of_mass_velocity = [] | units.km / units.s
        ms1_velocity = [] | units.km / units.s
        ms2_velocity = [] | units.km / units.s
    i_offset = len(giant_center_of_mass)
    
    giant_total_mass = giant_system.particles.total_mass()
    ms1_mass = binary_system.particles[0].mass
    ms2_mass = binary_system.particles[1].mass
    
    print("   Evolving for", t_end)
    for i_step, time in enumerate(times):
        coupled_system.evolve_model(time)
        print("   Evolved to:", time, end=' ')
        
        if do_energy_evolution_plot:
            potential_energies.append(coupled_system.particles.potential_energy())
            kinetic_energies.append(coupled_system.particles.kinetic_energy())
            thermal_energies.append(coupled_system.gas_particles.thermal_energy())
        
        giant_center_of_mass.append(giant_system.particles.center_of_mass())
        ms1_position.append(binary_system.particles[0].position)
        ms2_position.append(binary_system.particles[1].position)
        giant_center_of_mass_velocity.append(giant_system.particles.center_of_mass_velocity())
        ms1_velocity.append(binary_system.particles[0].velocity)
        ms2_velocity.append(binary_system.particles[1].velocity)

        a_giant, e_giant = calculate_orbital_elements(ms1_mass, ms2_mass,
                                                      ms1_position, ms2_position,
                                                      ms1_velocity, ms2_velocity,
                                                      giant_total_mass,
                                                      giant_center_of_mass,
                                                      giant_center_of_mass_velocity)
        print("Outer Orbit:", time.in_(units.day),  a_giant[-1].in_(units.AU), e_giant[-1], ms1_mass.in_(units.MSun), ms2_mass.in_(units.MSun), giant_total_mass.in_(units.MSun))
        
        if i_step % 10 == 9:
            snapshotfile = os.path.join("snapshots", "hydro_triple_{0:=04}_gas.amuse".format(i_step + i_offset))
            write_set_to_file(giant_system.gas_particles, snapshotfile, format='amuse')
            snapshotfile = os.path.join("snapshots", "hydro_triple_{0:=04}_core.amuse".format(i_step + i_offset))
            write_set_to_file(giant_system.dm_particles, snapshotfile, format='amuse')
            snapshotfile = os.path.join("snapshots", "hydro_triple_{0:=04}_binary.amuse".format(i_step + i_offset))
            write_set_to_file(binary_system.particles, snapshotfile, format='amuse')
            
            datafile = os.path.join("snapshots", "hydro_triple_{0:=04}_info.amuse".format(i_step + i_offset))
            with open(datafile, 'wb') as outfile:
                pickle.dump((all_times[:len(giant_center_of_mass)], potential_energies, 
                    kinetic_energies, thermal_energies, giant_center_of_mass, 
                    ms1_position, ms2_position, giant_center_of_mass_velocity,
                    ms1_velocity, ms2_velocity), outfile)
       
        figname1 = os.path.join("plots", "hydro_triple_small{0:=04}.png".format(i_step + i_offset))
        figname2 = os.path.join("plots", "hydro_triple_large{0:=04}.png".format(i_step + i_offset))
        print("  -   Hydroplots are saved to: ", figname1, "and", figname2)
        for plot_range, plot_name in [(8|units.AU, figname1), (40|units.AU, figname2)]:
            if HAS_PYNBODY:
                pynbody_column_density_plot(coupled_system.gas_particles, width=plot_range, vmin=26, vmax=32)
                scatter(coupled_system.dm_particles.x, coupled_system.dm_particles.y, c="w")
            else:
                pyplot.figure(figsize = [16, 16])
                sph_particles_plot(coupled_system.gas_particles, gd_particles=coupled_system.dm_particles, 
                    view=plot_range*[-0.5, 0.5, -0.5, 0.5])
            pyplot.savefig(plot_name)
            pyplot.close()
        
    
    coupled_system.stop()
    
    make_movie()
    
    if do_energy_evolution_plot:
        energy_evolution_plot(all_times[:len(kinetic_energies)-1], kinetic_energies, 
            potential_energies, thermal_energies)
    
    print("   Calculating semimajor axis and eccentricity evolution for inner binary")
    # Some temporary variables to calculate semimajor_axis and eccentricity evolution
    total_mass = ms1_mass + ms2_mass
    rel_position = ms1_position - ms2_position
    rel_velocity = ms1_velocity - ms2_velocity
    separation_in = rel_position.lengths()
    speed_squared_in = rel_velocity.lengths_squared()
    
    # Now calculate the important quantities:
    semimajor_axis_binary = (constants.G * total_mass * separation_in / 
        (2 * constants.G * total_mass - separation_in * speed_squared_in)).as_quantity_in(units.AU)
    eccentricity_binary = numpy.sqrt(1.0 - (rel_position.cross(rel_velocity)**2).sum(axis=1) / 
        (constants.G * total_mass * semimajor_axis_binary))

    print("   Calculating semimajor axis and eccentricity evolution of the giant's orbit")
    # Some temporary variables to calculate semimajor_axis and eccentricity evolution
    rel_position = ((ms1_mass * ms1_position + ms2_mass * ms2_position)/total_mass - 
        giant_center_of_mass)
    rel_velocity = ((ms1_mass * ms1_velocity + ms2_mass * ms2_velocity)/total_mass - 
        giant_center_of_mass_velocity)
    total_mass += giant_total_mass
    separation = rel_position.lengths()
    speed_squared = rel_velocity.lengths_squared()
    
    # Now calculate the important quantities:
    semimajor_axis_giant = (constants.G * total_mass * separation / 
        (2 * constants.G * total_mass - separation * speed_squared)).as_quantity_in(units.AU)
    eccentricity_giant = numpy.sqrt(1.0 - (rel_position.cross(rel_velocity)**2).sum(axis=1) / 
        (constants.G * total_mass * semimajor_axis_giant))
    
    orbit_parameters_plot(semimajor_axis_binary, semimajor_axis_giant, all_times[:len(semimajor_axis_binary)])
    orbit_ecc_plot(eccentricity_binary, eccentricity_giant, all_times[:len(eccentricity_binary)])
    
    orbit_parameters_plot(separation_in.as_quantity_in(units.AU), 
        separation.as_quantity_in(units.AU), 
        all_times[:len(eccentricity_binary)], 
        par_symbol="r", par_name="separation")
    orbit_parameters_plot(speed_squared_in.as_quantity_in(units.km**2 / units.s**2), 
        speed_squared.as_quantity_in(units.km**2 / units.s**2), 
        all_times[:len(eccentricity_binary)], 
        par_symbol="v^2", par_name="speed_squared")
from amuse.units import units
from amuse.community.evtwin.interface import EVtwin
from amuse.ext.star_to_sph import convert_stellar_model_to_SPH
from amuse.datamodel import Particle

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

if __name__ in ("__main__", "__plot__"):
    from amuse.plot import sph_particles_plot, native_plot
    sph_particles = convert_star_to_hydro_model(2.0|units.MSun, 110|units.Myr)
    native_plot.figure(figsize = (10, 10), dpi = 50)
    sph_particles_plot(sph_particles)
    native_plot.show()
Exemple #17
0
def collide_two_stars(t_end, distance, offset, v_vesc, nsteps):
    filename = "Hydro_AM06MSun.h5"
    try:
        pstar = read_set_from_file(filename, format='hdf5')
    except:
        from local_star_to_sph import evolve_star_and_convert_to_sph
        mass = 0.6 | units.MSun
        age = 8 | units.Gyr
        omega = 0 | units.s**-1
        Nsph = 1000
        pstar, pcore = evolve_star_and_convert_to_sph(mass, age, omega, Nsph)

    print pstar
    pmass = pstar.mass.sum()
    print pmass.in_(units.MSun)

    filename = "Hydro_BM06MSun.h5"
    try:
        sstar = read_set_from_file(filename, format='hdf5')
    except:
        from local_star_to_sph import evolve_star_and_convert_to_sph
        mass = 0.6 | units.MSun
        age = 8 | units.Gyr
        omega = 0 | units.s**-1
        Nsph = 1000
        sstar, score = evolve_star_and_convert_to_sph(mass, age, omega, Nsph)
    print sstar
    smass = sstar.mass.sum()
    print smass.in_(units.MSun)

    import numpy
    v_esc = numpy.sqrt(2 * constants.G * pmass / distance)
    velocity = v_vesc * v_esc

    sstar.x += distance
    sstar.y += offset
    sstar.vx -= velocity

    sph_particles = Particles(0)
    sph_particles.add_particles(pstar)
    sph_particles.add_particles(sstar)
    sph_particles.move_to_center()
    converter = nbody_system.nbody_to_si(pmass, distance)

    hydro = Fi(converter)

    dt = t_end / float(nsteps)

    hydro.gas_particles.add_particles(pstar)
    hydro.gas_particles.add_particles(sstar)
    Etot_init = hydro.kinetic_energy + hydro.potential_energy + hydro.thermal_energy
    to_framework = hydro.gas_particles.new_channel_to(sph_particles)

    output_file = "1987ApJ...323..614B.h5"
    write_set_to_file(sph_particles.savepoint(0.0 | t_end.unit),
                      output_file,
                      "hdf5",
                      append_to_file=False)

    time = 0.0 | t_end.unit
    while time < t_end:
        time += dt
        print time
        hydro.evolve_model(time)
        to_framework.copy()
        """
        from amuse.plot import sph_particles_plot
        sph_particles_plot(hydro.particles)
        from matplotlib import pyplot
        pyplot.show()
        """

        write_set_to_file(sph_particles.savepoint(time), output_file, "hdf5")
        """
        Ekin = hydro.kinetic_energy 
        Epot = hydro.potential_energy
        Eth = hydro.thermal_energy
        Etot = Ekin + Epot + Eth
        print "T=", hydro.get_time(), "M=", hydro.gas_particles.mass.sum(), 
        print "E= ", Etot, "Q= ", (Ekin+Eth)/Epot, "dE=", (Etot_init-Etot)/Etot
        """

    from amuse.plot import sph_particles_plot
    sph_particles_plot(hydro.particles)
    from matplotlib import pyplot
    pyplot.show()

    hydro.stop()
Exemple #18
0
def evolve_coupled_system(binary_system, giant_system, t_end, n_steps, 
        do_energy_evolution_plot, previous_data=None):
    directsum = CalculateFieldForParticles(particles=giant_system.particles, gravity_constant=constants.G)
    directsum.smoothing_length_squared = giant_system.parameters.gas_epsilon**2
    coupled_system = Bridge(timestep=(t_end / (2 * n_steps)), verbose=False, use_threading=True)
    coupled_system.add_system(binary_system, (directsum,), False)
    coupled_system.add_system(giant_system, (binary_system,), False)
    
    times = (t_end * range(1, n_steps+1) / n_steps).as_quantity_in(units.day)
    
    if previous_data:
        with open(previous_data, 'rb') as file:
            (all_times, potential_energies, kinetic_energies, thermal_energies, 
                giant_center_of_mass, ms1_position, ms2_position, 
                giant_center_of_mass_velocity, ms1_velocity, ms2_velocity) = pickle.load(file)
        all_times.extend(times + all_times[-1])
    else:
        all_times = times
        if do_energy_evolution_plot:
            potential_energies = coupled_system.particles.potential_energy().as_vector_with_length(1).as_quantity_in(units.erg)
            kinetic_energies = coupled_system.particles.kinetic_energy().as_vector_with_length(1).as_quantity_in(units.erg)
            thermal_energies = coupled_system.gas_particles.thermal_energy().as_vector_with_length(1).as_quantity_in(units.erg)
        else:
            potential_energies = kinetic_energies = thermal_energies = None
        
        giant_center_of_mass = [] | units.RSun
        ms1_position = [] | units.RSun
        ms2_position = [] | units.RSun
        giant_center_of_mass_velocity = [] | units.km / units.s
        ms1_velocity = [] | units.km / units.s
        ms2_velocity = [] | units.km / units.s
    i_offset = len(giant_center_of_mass)
    
    giant_total_mass = giant_system.particles.total_mass()
    ms1_mass = binary_system.particles[0].mass
    ms2_mass = binary_system.particles[1].mass
    
    print "   Evolving for", t_end
    for i_step, time in enumerate(times):
        coupled_system.evolve_model(time)
        print "   Evolved to:", time,
        
        if do_energy_evolution_plot:
            potential_energies.append(coupled_system.particles.potential_energy())
            kinetic_energies.append(coupled_system.particles.kinetic_energy())
            thermal_energies.append(coupled_system.gas_particles.thermal_energy())
        
        giant_center_of_mass.append(giant_system.particles.center_of_mass())
        ms1_position.append(binary_system.particles[0].position)
        ms2_position.append(binary_system.particles[1].position)
        giant_center_of_mass_velocity.append(giant_system.particles.center_of_mass_velocity())
        ms1_velocity.append(binary_system.particles[0].velocity)
        ms2_velocity.append(binary_system.particles[1].velocity)

        a_giant, e_giant = calculate_orbital_elements(ms1_mass, ms2_mass,
                                                      ms1_position, ms2_position,
                                                      ms1_velocity, ms2_velocity,
                                                      giant_total_mass,
                                                      giant_center_of_mass,
                                                      giant_center_of_mass_velocity)
        print "Outer Orbit:", time.in_(units.day),  a_giant[-1].in_(units.AU), e_giant[-1], ms1_mass.in_(units.MSun), ms2_mass.in_(units.MSun), giant_total_mass.in_(units.MSun)
        
        if i_step % 10 == 9:
            snapshotfile = os.path.join("snapshots", "hydro_triple_{0:=04}_gas.amuse".format(i_step + i_offset))
            write_set_to_file(giant_system.gas_particles, snapshotfile, format='amuse')
            snapshotfile = os.path.join("snapshots", "hydro_triple_{0:=04}_core.amuse".format(i_step + i_offset))
            write_set_to_file(giant_system.dm_particles, snapshotfile, format='amuse')
            snapshotfile = os.path.join("snapshots", "hydro_triple_{0:=04}_binary.amuse".format(i_step + i_offset))
            write_set_to_file(binary_system.particles, snapshotfile, format='amuse')
            
            datafile = os.path.join("snapshots", "hydro_triple_{0:=04}_info.amuse".format(i_step + i_offset))
            with open(datafile, 'wb') as outfile:
                pickle.dump((all_times[:len(giant_center_of_mass)], potential_energies, 
                    kinetic_energies, thermal_energies, giant_center_of_mass, 
                    ms1_position, ms2_position, giant_center_of_mass_velocity,
                    ms1_velocity, ms2_velocity), outfile)
       
        figname1 = os.path.join("plots", "hydro_triple_small{0:=04}.png".format(i_step + i_offset))
        figname2 = os.path.join("plots", "hydro_triple_large{0:=04}.png".format(i_step + i_offset))
        print "  -   Hydroplots are saved to: ", figname1, "and", figname2
        for plot_range, plot_name in [(8|units.AU, figname1), (40|units.AU, figname2)]:
            if HAS_PYNBODY:
                pynbody_column_density_plot(coupled_system.gas_particles, width=plot_range, vmin=26, vmax=32)
                scatter(coupled_system.dm_particles.x, coupled_system.dm_particles.y, c="w")
            else:
                pyplot.figure(figsize = [16, 16])
                sph_particles_plot(coupled_system.gas_particles, gd_particles=coupled_system.dm_particles, 
                    view=plot_range*[-0.5, 0.5, -0.5, 0.5])
            pyplot.savefig(plot_name)
            pyplot.close()
        
    
    coupled_system.stop()
    
    make_movie()
    
    if do_energy_evolution_plot:
        energy_evolution_plot(all_times[:len(kinetic_energies)-1], kinetic_energies, 
            potential_energies, thermal_energies)
    
    print "   Calculating semimajor axis and eccentricity evolution for inner binary"
    # Some temporary variables to calculate semimajor_axis and eccentricity evolution
    total_mass = ms1_mass + ms2_mass
    rel_position = ms1_position - ms2_position
    rel_velocity = ms1_velocity - ms2_velocity
    separation_in = rel_position.lengths()
    speed_squared_in = rel_velocity.lengths_squared()
    
    # Now calculate the important quantities:
    semimajor_axis_binary = (constants.G * total_mass * separation_in / 
        (2 * constants.G * total_mass - separation_in * speed_squared_in)).as_quantity_in(units.AU)
    eccentricity_binary = numpy.sqrt(1.0 - (rel_position.cross(rel_velocity)**2).sum(axis=1) / 
        (constants.G * total_mass * semimajor_axis_binary))

    print "   Calculating semimajor axis and eccentricity evolution of the giant's orbit"
    # Some temporary variables to calculate semimajor_axis and eccentricity evolution
    rel_position = ((ms1_mass * ms1_position + ms2_mass * ms2_position)/total_mass - 
        giant_center_of_mass)
    rel_velocity = ((ms1_mass * ms1_velocity + ms2_mass * ms2_velocity)/total_mass - 
        giant_center_of_mass_velocity)
    total_mass += giant_total_mass
    separation = rel_position.lengths()
    speed_squared = rel_velocity.lengths_squared()
    
    # Now calculate the important quantities:
    semimajor_axis_giant = (constants.G * total_mass * separation / 
        (2 * constants.G * total_mass - separation * speed_squared)).as_quantity_in(units.AU)
    eccentricity_giant = numpy.sqrt(1.0 - (rel_position.cross(rel_velocity)**2).sum(axis=1) / 
        (constants.G * total_mass * semimajor_axis_giant))
    
    orbit_parameters_plot(semimajor_axis_binary, semimajor_axis_giant, all_times[:len(semimajor_axis_binary)])
    orbit_ecc_plot(eccentricity_binary, eccentricity_giant, all_times[:len(eccentricity_binary)])
    
    orbit_parameters_plot(separation_in.as_quantity_in(units.AU), 
        separation.as_quantity_in(units.AU), 
        all_times[:len(eccentricity_binary)], 
        par_symbol="r", par_name="separation")
    orbit_parameters_plot(speed_squared_in.as_quantity_in(units.km**2 / units.s**2), 
        speed_squared.as_quantity_in(units.km**2 / units.s**2), 
        all_times[:len(eccentricity_binary)], 
        par_symbol="v^2", par_name="speed_squared")