Example #1
0
 def test_orbitplot(self):
     import matplotlib
     matplotlib.use("pdf")
     import numpy as np
     t = np.array(1.)
     plot = rebound.OrbitPlot(self.sim, periastron=True)
     self.assertIsInstance(plot, matplotlib.figure.Figure)
     plot = rebound.OrbitPlot(self.sim,
                              periastron=True,
                              color=True,
                              trails=True,
                              unitlabel="AU")
     self.assertIsInstance(plot, matplotlib.figure.Figure)
Example #2
0
 def test_orbitplot(self):
     with warnings.catch_warnings(record=True) as w:
         warnings.simplefilter("always")
         import matplotlib
         matplotlib.use("pdf")
         import numpy as np
         t = np.array(1.)
         plot, ax_main = rebound.OrbitPlot(self.sim, periastron=True)
         self.assertIsInstance(plot, matplotlib.figure.Figure)
         plot, ax_main = rebound.OrbitPlot(self.sim,
                                           periastron=True,
                                           color=True,
                                           unitlabel="AU")
         self.assertIsInstance(plot, matplotlib.figure.Figure)
Example #3
0
 def plot_simulation(self,
                     simulation_input_df,
                     save_dir,
                     scenario_name,
                     xlim=None,
                     ylim=None):
     eccs = simulation_input_df["eccentricities"].split(",")
     eccs = [float(i) for i in eccs]
     incs = simulation_input_df["inclinations"].split(",")
     incs = [float(i) - 90 for i in incs]
     omegas = simulation_input_df["arg_periastron"].split(",")
     omegas = [float(i) for i in omegas]
     periods = simulation_input_df["periods"].split(",")
     periods = [float(i) for i in periods]
     masses = simulation_input_df["masses"].split(",")
     masses = [float(i) for i in masses]
     star_mass = simulation_input_df["star_mass"]
     sim = self.init_rebound_simulation(
         SimulationInput(star_mass, masses, periods, eccs, incs, omegas, 1))
     filenames = []
     for i in range(1):
         sim.integrate(sim.t + i / 100 * 2 * np.pi)
         fig, ax = rebound.OrbitPlot(sim,
                                     color=True,
                                     unitlabel="[AU]",
                                     xlim=xlim,
                                     ylim=ylim)
         filename = save_dir + "scenario_" + scenario_name + "_" + str(
             i) + ".png"
         plt.savefig(filename)
         filenames.append(filename)
         plt.close(fig)
Example #4
0
def simulate_fly_by(sim, intruder, visualize=False):
    """
    Simulates what happens when a star flies by a planetary system.
    """
    intruder.hash = "intruder"

    sim.add(intruder)

    intruder_distance = np.linalg.norm(sim.particles["intruder"].xyz)
    sim.exit_max_distance = intruder_distance*1.01

    while True:
        try:
            sim.integrate(sim.t+5)

            if visualize:
                fig = rebound.OrbitPlot(sim,color=True,unitlabel="[AU]")
                display(fig)
                plt.close(fig)
                clear_output(wait=True)

        except rebound.Escape as error:
            # print(error)
            for i, particle in enumerate(sim.particles):
                distance = np.linalg.norm(particle.xyz)
                if distance > sim.exit_max_distance:
                    # print("Removed", i, str(particle.hash))
                    sim.remove(hash=particle.hash)
                    sim.move_to_com()

            return sim
Example #5
0
 def test_orbitplot_slices(self):
     with warnings.catch_warnings(record=True) as w:
         warnings.simplefilter("always")
         import matplotlib
         matplotlib.use("pdf")
         import numpy as np
         t = np.array(1.)
         plot, ax_main, ax_top, ax_right = rebound.OrbitPlot(
             self.sim, periastron=True, slices=True)
         self.assertIsInstance(plot, matplotlib.figure.Figure)
         plot, ax_main, ax_top, ax_right = rebound.OrbitPlot(
             self.sim,
             periastron=True,
             color=True,
             orbit_type="solid",
             unitlabel="AU",
             slices=0.4,
             xlim=[-1., 1])
         self.assertIsInstance(plot, matplotlib.figure.Figure)
def pltKep(rad_moon, sma, i, ecc):
    #rad_moon is the bodily radius of the moon
    #i is the inclination of the moon's orbital plane
    #sma is the semi-major axis of the moon's orbit
    #ecc is the eccentricity of the moon's orbit
    m_moon = 4. * math.pi * dens * (rad_moon**3) / 3.
    sim = rebound.Simulation()  #start simulation
    sim.units = ('Hr', 'M', 'Kg')  #use SI units
    sim.add(m=Mass_syn)  #add central body
    sim.add(m=m_moon, a=sma, inc=i, e=ecc)
    fig, ax_main, ax_sub1, ax_sub2 = rebound.OrbitPlot(
        sim,
        slices=1,
        xlim=[-120000000, 60000000],
        ylim=[-60000000, 60000000],
        unitlabel='(m)',
        color=True)
Example #7
0
def pltAM(delmass, inclin, ecc):
    mass = (delmass + 1e24) / M_sun
    mass_Earth = 1e24 / M_sun
    sim = rebound.Simulation()
    sim.units = ('yr', 'AU', 'Msun')  #use astronomical units
    sma = (AM**2) / (sim.G * M_sun * (mass**2))  #calculate semi-major axis
    sma_Earth = (AM**2) / (sim.G * M_sun *
                           (mass_Earth**2))  #calculate semi-major axis
    sim.add(m=1)  #solar mass as central body
    sim.add(m=mass_Earth, a=sma_Earth, e=ecc, inc=inclin)  #add Earth
    sim.add(m=mass, a=sma, e=ecc, inc=inclin)  #add planet
    sim.move_to_com()
    fig, ax, ax2, ax3 = rebound.OrbitPlot(sim,
                                          color=True,
                                          unitlabel="[au]",
                                          slices=1)
    if sma < sma_Earth:
        limit = 2. * sma_Earth
    else:
        limit = 2. * sma
    ax.set_xlim([-limit, limit])
    ax.set_ylim([-limit, limit])
    ax2.set_xlim([-limit, limit])
    ax2.set_ylim([-limit, limit])
    ax3.set_xlim([-limit, limit])
    ax3.set_ylim([-limit, limit])
    ps = sim.particles
    print('The orbit of an Earth-mass planet is shown in red.')
    if delmass > 0:
        print(
            'The enlarged-mass planet (cyan) has an orbital period of {0:.2f} years.'
            .format(ps[2].P))
    else:
        print(
            'The reduced-mass planet (cyan) has an orbital period of {0:.2f} years.'
            .format(ps[2].P))
Example #8
0
                                      0))  #integration
                            # a_e = sim.calculate_orbits()[0]                         #calculating orbital elements after the integration
                            # res[(m, x, v, inc, o)] = (a_e.a, a_e.e)
                            '''determine the color of HZ orbits in omega-inc plot'''
                            # if (a_e.a*(1+a_e.e))<1.2 and (a_e.a*(1-a_e.e))>0.8:
                            #     Color = 'g'
                            #     counter += 1
                            # else:
                            #     Color = 'y'

                            # plt.plot(o,inc,color=Color,marker='.',ms=2)

                            fig = rebound.OrbitPlot(sim,
                                                    trails=True,
                                                    slices=True,
                                                    color=True,
                                                    periastron=True,
                                                    unitlabel="[AU]",
                                                    lim=5.,
                                                    limz=5)
                            # plt.title('X={x} m={m} vz={vz} inc={inc} Omega={Omega}'.format(x=round(x,1), m=m, vz=v, inc=inc, Omega=o))
                            plt.savefig(
                                '/Users/atefeh-behzad/Exoplanet_Simulations/Earth_Omega&inc_Var_Animation/new/X{x}m{m}v{v}inc{inc}Omega{o}t{t}.png'
                                .format(x=round(x, 1),
                                        m=m,
                                        v=v,
                                        inc=round(inc, 2),
                                        o=round(o, 2),
                                        t=(tt + 25)),
                                dpi=100)
                            plt.close()
Example #9
0
sim.units=('AU','days','Msun')
labels=["Sun","Pseudo-Jupiter","Companion"]
sim.add(m=1.)
sim.add(m=0.009547919152112404,a=5.,e=0.,inc=0.)
sim.add(m=0.5,a=500.,e=0.,inc=np.pi/2)
sim.move_to_com()
sim.integrator = "whfast"
energy_initial=sim.calculate_energy()
orbits=sim.calculate_orbits() #it does not calculate the orbit of the Sun

sim.dt=0.1*orbits[0].P
tmax=130000000*365.25
Nout=700
sim.status()
print(orbits[0].P)
fig=rebound.OrbitPlot(sim, slices=True, unitlabel="[AU]", color=True, periastron=True)
fig.savefig("Companion_initialorbits.png")

######################################
##Iterate and store interesting values
######################################
Nobjects=len(labels)-1
ecc=np.zeros((Nobjects,Nout))
inc=np.zeros((Nobjects,Nout))
Lz=np.zeros((Nobjects,Nout))
empty_list=np.zeros((Nobjects,Nout))

times = np.linspace(0.,tmax,Nout)
particles=sim.particles
for i,time in enumerate(times):
    sim.integrate(time, exact_finish_time=0)
Example #10
0
sim.add(m=0.9, a=11)  #Alpha Centauri B

semimajor = np.random.uniform(0.0, 20.0, n)
incl = np.random.uniform(0.0, np.pi / 2, n)
ecc = np.random.random(n)
for i in range(n):
    sim.add(m=1e-9, a=semimajor[i], e=ecc[i], T=i, inc=incl[i])
sim.status()

# In[2]:

#Static Orbit Plot
sim.move_to_com()
rebound.OrbitPlot(sim,
                  lim=25,
                  figsize=(10, 10),
                  trails=True,
                  lw=0.3,
                  slices=True)

# In[3]:

# Animated Orbit
w = sim.getWidget(size=(500, 500))
w

# In[4]:

#Scatter Plot
plt.clf()
a = np.zeros(n - 1)  #semimajor axis x-axis [0,0,0,0,0...] len=102
e = np.zeros(n - 1)  #eccentricty y-axis
Example #11
0
for particles in plannet:
    if particles == 'Jupiter':
        sim.add(m=1.898580250761156e29,
                a=778480939.193071,
                e=0.048650024931482155)
    else:
        sim.add(particle=particles)
sim.status()
sim.move_to_com()

year = arange(1, 1000, 1)
j = 0
for t in year:
    j += 1
    sim.integrate(t)
    fig, ax_main = rebound.OrbitPlot(sim,
                                     xlim=(-7 * 10**9, 7 * 10**9),
                                     ylim=(-7 * 10**9, 7 * 10**9),
                                     unitlabel='km',
                                     color=[
                                         'grey', 'pink', "blue", "red",
                                         'orange', 'yellow', 'white', 'green',
                                         'cyan'
                                     ],
                                     orbit_type='solid',
                                     fancy='true')
    title('year={0}'.format(round(t, 1)))
    fig.savefig('Solar System{0}.png'.format(j))
    print(t)
fig.show()
Example #12
0
    for i in range(1,active):
        orbit = sim.particles[i].calculate_orbit(sim.particles[0])
        mass = sim.particles[i].m
        print "Lunar embryo "+str(i)+" has a mass of "+str(mass)+" solar masses."
        print(orbit)
#    if sim.N < 21:
#        for i in range(1,sim.N):
#            orbit = sim.particles[i].calculate_orbit(sim.particles[0])
#            mass = sim.particles[i].m
#            print "Particle "+str(i)+" has a mass of "+str(mass)+" solar masses."
#            print(orbit)
#    else:
#        for i in range(1, 21):
#            orbit = sim.particles[i].calculate_orbit(sim.particles[0])
#            mass = sim.particles[i].m
#            print "Particle "+str(i)+" has a mass of "+str(mass)+" solar masses."
#            #f.write('\n' + "Particle "+str(i)+" has a mass of "+str(mass)+" solar masses.")
#            print(orbit)
#            #f.write('\n' + str(orbit) + '\n')

#####################################################

sim.status() 

#Calculates accuracy/energy loss
dE = abs((sim.calculate_energy() - E0)/E0)
print str(dE) + " energy loss"

fig = rebound.OrbitPlot(sim,slices=True,color=True,unitlabel="Semi-Major Axis (AU)",lim=0.0012, limz=0.001, figsize=(9,8), lw=2.0)
fig.savefig("PCb-com-test-2.png")
import rebound
import matplotlib.pyplot as plt

sim = rebound.Simulation()
sim.add([
    "Sun", "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus",
    "Neptune"
],
        date="9999-01-01 06:25")

fig = rebound.OrbitPlot(sim)
fig.savefig("circumbinary_j.png")
plt.show()
Example #14
0
    title('year={0}'.format(round(time / (2 * pi), 2)))
    savefig('{0}.png'.format(j))
    if distance == 0:
        break
#Plotting the orbits
sim = rebound.Simulation()
sim.add(m=1)
sim.add(m=1e-3, a=1)
sim.add(m=5e-3, a=1.25)
sim.move_to_com()
N = 1000
times = linspace(0, 100 * 2 * pi, N)

j = 0

for i, time in enumerate(times):
    if i == 47:
        break
    else:
        j += 1
        sim.integrate(time)
        fig, ax_main = rebound.OrbitPlot(sim,
                                         xlim=(-1.5, 1.5),
                                         ylim=(-1.5, 1.5),
                                         unitlabel='AU',
                                         orbit_type='solid',
                                         fancy='true')
        title('year={0}'.format(round(time / (2 * pi), 2)))
        fig.savefig('System{0}.png'.format(j))
        print(time)
def update_figure(n_planets, stellar_mass, stellar_temp, planet_mass,
                  semi_major_axis, eccentricity):

    string_list = [planet_mass, semi_major_axis, eccentricity]
    planet_mass, semi_major_axis, eccentricity = comma_strings_to_list(
        string_list)
    assert all(
        len(i) == n_planets
        for i in [planet_mass, semi_major_axis, eccentricity]
    ), "The number of planet masses, semi-major axes, and eccentricities must equal the number of planets!"
    assert all(0 <= i < 1
               for i in eccentricity), "Eccentricity values must 0 <= e < 1!"

    # Pretiffy with random arguments of pericenter (not currently using)
    omega = np.random.random(int(n_planets)) * 2 * np.pi

    # Use rebound to create a figure of orbits
    sim = rebound.Simulation()

    # Calculate semi-minor axes, perihelion and aphelion
    r_p = []
    r_a = []
    b = []
    for a, e in zip(semi_major_axis, eccentricity):
        r_p.append((1 - e) * a)
        r_a.append((1 + e) * a)
        b.append(((1 - e**2) * a**2)**(1 / 2))

    r_a_max = np.max(r_a)
    r_p_max = np.max(r_p)
    b_max = np.max(b)
    offset_x = r_a_max * 0.1

    # Add in stellar information
    sim.add(m=stellar_mass)
    for mass, a, e, o in zip(planet_mass, semi_major_axis, eccentricity,
                             omega):
        mass = mass * jup_to_stellar
        sim.add(primary=sim.particles[0], m=mass, a=a, e=e, omega=0)

    particles_x = []
    particles_y = []
    for particle in sim.particles:
        particles_x.append(particle.x)
        particles_y.append(particle.y)

    x_max = np.max(particles_x)
    x_min = np.min(particles_x)
    y_max = np.max(particles_y)
    y_min = np.min(particles_y)

    # Use rebound to plot
    star_color = scale_cmap(stellar_temp)
    color_val = cmap(star_color)
    fig, ax = rebound.OrbitPlot(
        sim,
        color=True,
        xlim=[-(r_a_max + offset_x), r_p_max + offset_x],
        ylim=[-b_max * 1.1, b_max * 1.1],
        lw=3,
        star_color=color_val,
    )
    # Hack in mpl image so that dash can use it
    out_url = fig_to_uri(fig)
    return out_url
Example #16
0
k = 2 * pi / 365.  #modified day per day
year = 2 * pi  #modified day per year
sim = rebound.Simulation()
date = "2017-08-01 00:00"
sim.add("Sun", date=date)
sim.add("399", date=date)
sim.add("Jupiter", date=date)
#sim.add("2008 NU", date = date)
sim.add(m = 0,x= 0.631695419869991, y=-1.03557552813299, z=-0.406141242151842, \
        vx = 0.885336584655336, vy = 0.462313854222598, vz = 0.398919500273978, date=date)
parts = sim.particles
#fig = rebound.OrbitPlot(sim, unitlabel="[AU]", color=True, periastron=True)
#plt.show()
fig = rebound.OrbitPlot(sim,
                        slices=True,
                        color=True,
                        unitlabel="[AU]",
                        lim=10.,
                        limz=1.)
plt.show(fig)
objects = {
    0: [0.3, color.yellow],
    1: [0.1, color.blue],
    2: [0.2, color.orange],
    3: [0.05, color.white]
}

scene = display(title='Simulation of the Sun and Earth',
                width=1200,
                height=700,
                center=(0, 0, 0))
scene.autoscale = 0
Example #17
0
sim.move_to_com()
sim.integrator = "whfast"
#sim.ri_whfast.safe_mode = 0
#sim.ri_whfast.corrector = 11
energy_initial = sim.calculate_energy()
orbits = sim.calculate_orbits()  #it does not calculate the orbit of the Sun
for t in range(0, Nplanets):
    print("P = %6.3f" % (orbits[t].P))
sim.dt = 0.05 * orbits[0].P
tmax = 2000 * 365.25
Nout = 1000

import matplotlib as mpl
mpl.use('tkagg')
import matplotlib.pyplot as plt
fig = rebound.OrbitPlot(sim, trails=True, unitlabel="[AU]", color=True)
fig.savefig("SolarSystem_initialorbits.png")

######################################
##Iterate and store interesting values
######################################
x = np.zeros((Nplanets, Nout))
longitude = np.zeros((Nplanets, Nout))
varpi = np.zeros((Nplanets, Nout))
times = np.linspace(0., tmax, Nout)
particles = sim.particles
for i, time in enumerate(times):
    sim.integrate(time, exact_finish_time=0)
    if time % 100000 == 0: print(time)
    orbits = sim.calculate_orbits()
    for j in range(Nplanets):
Example #18
0
    sim.integrator = "whfast"
    sim.dt = planetD.P / 100.0  # shortest period

    sim.add(m=mStar)
    for planet in [planetC, planetB]:
        sim.add(
            m=planet.mPublished,
            P=planet.P,
            M=planet.MA,
            omega=planet.omega,
            e=planet.e,
            inc=numpy.radians(inc),
        )
    sim.move_to_com()

    fig = rebound.OrbitPlot(sim, trails=True, periastron=True)
    plt.title("inclination = %i degrees"%inc)
    plt.savefig("orbit_%i.png"%inc)
    plt.close(fig)

    radialVx = numpy.zeros(nTimesteps)
    radialVy = numpy.zeros(nTimesteps)
    radialVz = numpy.zeros(nTimesteps)

    for i, t in enumerate(times):
        sim.integrate(t, exact_finish_time=0)
        radialVx[i] = sim.particles[0].vx
        radialVy[i] = sim.particles[0].vy
        radialVz[i] = sim.particles[0].vz
    plt.figure()
    # scale the radial velocity by the inclination angle