Skip to main content

11  Orbits with orbitr

In Chapter 10 you wrote the loop yourself. That is the right way to learn it and the wrong way to simulate the solar system every time you want one. orbitr is a package I wrote that does the loop for gravity, for any number of bodies. You describe the system with a pipeline, and what comes back is a tibble, so every tool from Chapter 7 and Chapter 8 works on the result.

11.1 Loading orbitr

You installed orbitr in Chapter 1. Load it along with the tidyverse:

library(tidyverse)
library(orbitr)

The package works in SI units throughout: meters, kilograms, seconds. To save you from looking numbers up, it comes with a set of constants.

gravitational_constant
#> [1] 6.6743e-11
mass_earth
#> [1] 5.972e+24
distance_earth_moon
#> [1] 384400000
speed_moon
#> [1] 1022
seconds_per_day
#> [1] 86400

There are masses, orbital distances, and orbital speeds for the Sun, the Moon, and the planets, plus seconds_per_hour and seconds_per_year. They are ordinary numbers, the kind you typed in by hand in Chapter 2:

distance_earth_moon / 1e3   # km
#> [1] 384400

11.2 The Earth and the Moon

A simulation takes four steps: make an empty system, add the Earth, add the Moon, and run it.

moon_sim <- create_system() |>
  add_body("Earth", mass = mass_earth) |>
  add_body("Moon", mass = mass_moon, x = distance_earth_moon, vy = speed_moon) |>
  simulate_system(time_step = seconds_per_hour, duration = seconds_per_day * 28)

add_body() needs a name and a mass. Position (x, y, z) and velocity (vx, vy, vz) default to zero, so the Earth starts at rest at the origin. The Moon starts 384,400 km away on the \(x\) axis, moving at 1022 m/s in the \(+y\) direction. simulate_system() steps the system forward one hour at a time for 28 days.

moon_sim
#> # A tibble: 1,346 × 9
#>    id       mass          x           y     z      vx         vy    vz  time
#>    <chr>   <dbl>      <dbl>       <dbl> <dbl>   <dbl>      <dbl> <dbl> <dbl>
#>  1 Earth 5.97e24         0         0        0   0        0           0     0
#>  2 Moon  7.34e22 384400000         0        0   0        1.02e+3     0     0
#>  3 Earth 5.97e24       215.        0        0   0.119    5.71e-4     0  3600
#>  4 Moon  7.34e22 384382520.  3679200        0  -9.71     1.02e+3     0  3600
#>  5 Earth 5.97e24       860.        4.11     0   0.239    2.29e-3     0  7200
#>  6 Moon  7.34e22 384330083.  7358065.       0 -19.4      1.02e+3     0  7200
#>  7 Earth 5.97e24      1934.       16.5      0   0.358    5.14e-3     0 10800
#>  8 Moon  7.34e22 384242692. 11036262.       0 -29.1      1.02e+3     0 10800
#>  9 Earth 5.97e24      3438.       41.1      0   0.477    9.14e-3     0 14400
#> 10 Moon  7.34e22 384120357. 14713454.       0 -38.8      1.02e+3     0 14400
#> # ℹ 1,336 more rows

One row per body per time step. There are 1346 rows: 2 bodies times 673 instants, the starting state plus \(28 \times 24 = 672\) steps. The columns are the body’s id and mass, its position, its velocity, and the time in seconds since the start.

plot_orbits() draws the path of every body:

plot_orbits(moon_sim)
Figure 11.1: The Moon’s path over 28 days. The Earth is the short mark near the origin.

The result is a ggplot, so you can add labs() or a theme to it with + as in Chapter 8.

11.3 Doing physics with the output

The simulation is a data frame, so questions about it are dplyr questions. Take the distance between the Earth and the Moon over the month.

There is one catch. The Earth does not stay at the origin. The Moon pulls on it just as hard as it pulls on the Moon, so the Earth moves, and the Moon’s distance from the origin is not its distance from the Earth. shift_reference_frame() fixes this by subtracting one body’s position and velocity from every body at every time step:

moon_from_earth <- moon_sim |>
  shift_reference_frame("Earth") |>
  filter(id == "Moon") |>
  mutate(
    time_days   = time / seconds_per_day,
    distance_km = sqrt(x^2 + y^2 + z^2) / 1e3
  )

moon_from_earth |>
  summarise(closest_km = min(distance_km), farthest_km = max(distance_km))
#> # A tibble: 1 × 2
#>   closest_km farthest_km
#>        <dbl>       <dbl>
#> 1    380645.      384400

In the Earth-centered frame the Moon’s distance from the origin is the number we want. It varies by a little under 4000 km. A plot shows how:

ggplot(moon_from_earth, aes(time_days, distance_km)) +
  geom_line() +
  labs(x = "Time (days)", y = "Earth-Moon distance (km)")
Figure 11.2: Earth-Moon distance over the 28-day run.

The Moon starts at its farthest point, falls inward for two weeks, and climbs back out. That is an ellipse. The orbit is not a circle because 1022 m/s is slightly less than the speed a circular orbit needs at that distance, which is \(\sqrt{G(M + m)/r}\):

sqrt(gravitational_constant * (mass_earth + mass_moon) / distance_earth_moon)
#> [1] 1024.529

Nobody told the simulation about ellipses. It only knows Newton’s law of gravitation, the one from Chapter 2, and \(F = ma\).

NoteThe real Moon

The real Moon’s distance varies much more than this, from about 363,000 to 405,000 km. Starting it at its average distance with its average speed gives a rounder orbit than the real one.

11.4 Kepler’s third law

Kepler’s third law says that the square of a planet’s period \(T\) is proportional to the cube of its semi-major axis \(a\), with the same constant for every planet. Newton later showed that the constant is \(4\pi^2 / GM\), where \(M\) is the mass of the Sun.

For real solar-system bodies you do not type positions and velocities. add_sun() puts the Sun at the origin, and add_planet() places a planet on its real orbit:

inner_sim <- create_system() |>
  add_sun() |>
  add_planet("Mercury", parent = "Sun") |>
  add_planet("Venus", parent = "Sun") |>
  add_planet("Earth", parent = "Sun") |>
  add_planet("Mars", parent = "Sun") |>
  simulate_system(time_step = seconds_per_day, duration = seconds_per_year * 4)

That is four years in one-day steps, long enough for Mars to go around twice.

plot_orbits(inner_sim, three_d = FALSE)
Figure 11.3: The four inner planets over four years.

The real orbits are tilted slightly out of the \(xy\) plane, and by default plot_orbits() responds to any \(z\) motion with an interactive 3D plot. three_d = FALSE asks for the flat view from above.

Now measure \(a\) and \(T\) from the output. The semi-major axis is half the long axis of the ellipse, which is the average of the planet’s smallest and largest distance from the Sun. For the period, time the planet between successive crossings of the \(x\) axis in the upward direction, the way you would time a pendulum through the bottom of its swing. A crossing is a row where y is positive and the row before it was not. lag(y) gives the previous row’s value of y.

kepler <- inner_sim |>
  shift_reference_frame("Sun", keep_center = FALSE) |>
  mutate(
    distance_m = sqrt(x^2 + y^2 + z^2),
    a_m        = (min(distance_m) + max(distance_m)) / 2,
    crossing   = y > 0 & lag(y) <= 0,
    .by = id
  ) |>
  filter(crossing) |>
  summarise(
    a_m      = first(a_m),
    period_s = mean(diff(time)),
    .by = id
  )

keep_center = FALSE drops the Sun’s own rows, which would otherwise sit at the origin doing nothing. .by works in mutate() as it does in summarise(), so min(), max(), and lag() all work one planet at a time. After the filter() only the crossing rows are left, so diff(time) is the gaps between crossings (Chapter 3) and their mean is the period. Converted to friendlier units:

kepler |>
  mutate(
    a_au         = a_m / distance_earth_sun,
    period_years = period_s / seconds_per_year,
    kepler_ratio = period_s^2 / a_m^3
  ) |>
  arrange(a_m)
#> # A tibble: 4 × 6
#>   id                a_m period_s  a_au period_years kepler_ratio
#>   <chr>           <dbl>    <dbl> <dbl>        <dbl>        <dbl>
#> 1 Mercury  58052356536.  7626240 0.388        0.242     2.97e-19
#> 2 Venus   108220625824. 19422720 0.723        0.615     2.98e-19
#> 3 Earth   149609852719. 31564800 1.00         1.00      2.98e-19
#> 4 Mars    227906758050. 59356800 1.52         1.88      2.98e-19

Mercury’s year is about 88 days and Mars’s is 1.88 of ours, as the textbooks say. The last column is \(T^2/a^3\). The periods differ by a factor of nearly eight and the ratio agrees to about one part in a thousand, limited mostly by timing with a one-day step. Newton’s prediction for it is

4 * pi^2 / (gravitational_constant * mass_sun)
#> [1] 2.973851e-19

which is the same number to three figures.

11.5 Checking the simulation

A numerical simulation is an approximation, and you should ask how good it is. The test is the one from Chapter 10: the total energy should not change. get_energy() adds up the kinetic and potential energy of the whole system at every time step:

get_energy(inner_sim)
#> # A tibble: 1,462 × 4
#>      time kinetic potential   energy
#>     <dbl>   <dbl>     <dbl>    <dbl>
#>  1      0 6.57e33  -1.28e34 -6.20e33
#>  2  86400 6.56e33  -1.28e34 -6.20e33
#>  3 172800 6.56e33  -1.28e34 -6.20e33
#>  4 259200 6.56e33  -1.28e34 -6.20e33
#>  5 345600 6.55e33  -1.28e34 -6.20e33
#>  6 432000 6.54e33  -1.27e34 -6.20e33
#>  7 518400 6.53e33  -1.27e34 -6.20e33
#>  8 604800 6.52e33  -1.27e34 -6.20e33
#>  9 691200 6.51e33  -1.27e34 -6.20e33
#> 10 777600 6.50e33  -1.27e34 -6.20e33
#> # ℹ 1,452 more rows

The total is negative, as it must be for bodies that are bound to each other. conserved_quantities() does the same for momentum and angular momentum, and adds columns for how far each has strayed from its starting value. energy_error is the fractional change in energy:

conserved_quantities(inner_sim) |>
  summarise(worst_energy_error = max(abs(energy_error)))
#> # A tibble: 1 × 1
#>   worst_energy_error
#>                <dbl>
#> 1          0.0000899

Less than one part in ten thousand over four years. If that number were large, the first thing to try would be a smaller time step.

11.6 What else is there

animate_system() turns a simulation into an animation. load_solar_system() builds the Sun, all eight planets, the Moon, and Pluto in one call. simulate_system() takes a method argument: the default, "verlet", is the velocity Verlet method, and "euler_cromer" and "euler" are the two methods you wrote by hand in Chapter 10, there for comparison.

TipWhere to read more

The documentation, with a page for every function, is at https://orbit-r.com. For the physics behind all of this, from two-body orbits to chaos, see my other book, Orbital Mechanics with R, free at https://book.orbit-r.com.

Simulating is half of a physicist’s job. The other half is writing up what you found, and Chapter 12 shows how to put code, results, and words in one document.