---
author:
- "[Eugeniy E. Mikhailov](http://physics.wm.edu/~evmik/) and [Greg
  Bentsen](https://physics.wm.edu/~gbentsen/)"
title: Ordinary Differential Equations II
---

## Logistics and Agenda

Homework 6 due Monday Nov 16 at 11:59pm

\

Agenda

-   This week:  Ordinary Differential Equations (ODEs)
-   Next week:  Fourier transforms
-   Nov 23: Remote class  *(Nov 25 - 29:  Thanksgiving)*
-   Nov 30 - Dec 4:  Machine learning & review

\

Final exam

-   Dec 9 or Dec 11
-   Same 2-part structure as midterms (take-home, in-class)

## Today

Ordinary differential equations (ODEs) & orbital motion

-   Newton's universal law of gravitation
-   2-body motion & Kepler orbits
-   Energy conservation as a debugging tool
-   3-body motion & chaos

## Predicting the motion of the heavens

ODEs allow us to predict the future!

::: columns
::: {.column width="45%"}
::: {style="text-align: center;"}
![Source: science.nasa.gov](./pics/solar_system.jpg){width="60%"}
:::
:::

::: {.column width="45%"}
::: {style="text-align: center;"}
![Source: www.iflscience.com](./pics/halleys_comet.jpg){width="60%"}
:::
:::
:::

-   Newton's universal law of gravitation predicts the motion of
    planets, moons, comets, and spacecraft.
    -   Example: **Halley's comet** returns once every \~76 years
    -   Understood by English astronomer Edmond Halley using Newton's
        laws in 1705
    -   Predicted return in 1758 and showed that sightings from 1531,
        1607, and 1682 were the same object

Today's motivating question: If we know the masses, positions, and
velocities today, how accurately can we predict the motion
**tomorrow---or in 100 years**?

The answer is: **it depends**

## Newton's law of universal gravitation

::: {style="text-align: center;"}
![Source: Wikipedia](./pics/newton_gravity.png){width="35%"}
:::

$$
\boxed{\mathbf F=-\frac{G m_1 m_2}{r^3}
\mathbf r} \quad \quad \quad \quad \mathbf r = \mathbf x_1 - \mathbf x_2
$$

-   **Two bodies:** regular, analytically solvable orbits.
-   **Three bodies:** the same law can generate chaotic motion.

Both motions are **deterministic**.

However, regular orbits are **predictable**, while chaotic motion is
**not**.

# Two bodies: motion in the 2D plane

::: {style="text-align: center;"}
![Source: Wikipedia](./pics/kepler_orbit.png){width="35%"}
:::

The motion of two bodies is relatively simple: Kepler orbits

Two simplifications:

1.  Only need the relative separation
    $\mathbf r=\mathbf r_1-\mathbf r_2$ (assume the center of mass is
    fixed).
2.  The angular momentum of the system is conserved: reduces motion to
    the 2D plane, with

$$\mathbf{r}(t) = (x(t), y(t))$$

Thus, we only need to solve for $x(t)$ and $y(t)$.

# Equations of motion for two bodies

Newton's second law $\mathbf{F} = m \mathbf{a}$ and the gravitational
force law $\mathbf F=-\frac{G m_1 m_2}{r^3}\mathbf r$ combine to yield:

$$
\boxed{\frac{d^2 \mathbf r}{dt^2} = \ddot{\mathbf r}=-\frac{\mu}{|\mathbf r|^3}\mathbf r}
$$

where $\mu=G(m_1+m_2)$. Or, equivalently (setting $\mu = 1$):

$$
\ddot x=-\frac{x}{(x^2+y^2)^{3/2}},\qquad
\ddot y=-\frac{y}{(x^2+y^2)^{3/2}}.
$$

Thus the motion is described by a pair of 2nd-order ODEs.

## Reducing 2nd-order ODEs to 1st-order ODEs

Pair of 2nd order ODEs:

$$
\ddot x=-\frac{x}{(x^2+y^2)^{3/2}},\qquad
\ddot y=-\frac{y}{(x^2+y^2)^{3/2}}.
$$

The essential trick: use the velocity $v_x = \dot x = dx/dt$ to express
the second derivatives as $\ddot x = \dot v_x$.

So we define the state vector $\mathbf s=(x,y,v_x,v_y)$ to obtain four
1st-order ODEs:

$$
\boxed{\frac{d\mathbf s}{dt}=
\begin{pmatrix}
v_x\\v_y\\-x/r^3\\-y/r^3
\end{pmatrix}=f(t,\mathbf s)},\qquad r=\sqrt{x^2+y^2}.
$$

-   We need **four initial conditions**: $x(0),y(0),v_x(0),v_y(0)$.
-   This first-order representation $f(t, \mathbf s)$ is exactly what
    `solve_ivp` expects.

## Solving the ODEs with SciPy

$$
\frac{d\mathbf s}{dt}=
(
v_x, v_y, -x/r^3, -y/r^3
)=f(t,\mathbf s)
$$

``` {.python .numberLines}
import numpy as np
from scipy.integrate import solve_ivp

def func(t, state):
    x, y, vx, vy = state
    r = np.sqrt(x**2 + y**2)
    return [vx, vy, -x/r**3, -y/r**3]

s0 = [1.0, 0.0, 0.0, 1.0]   # Initial conditions
eval_times = np.linspace(0, 20, 1000)
sol = solve_ivp(fun=func, t_span=(0, 20), y0=s0, 
                         t_eval=eval_times, rtol=1e-9, atol=1e-11)
```

-   `func` gives **derivatives**, not the next discrete time step.
-   `sol.y[0]`, `sol.y[1]` are $x(t)$, $y(t)$; plot **$y$ versus $x$**.
-   `t_eval` sets **output times**; `rtol` and `atol` control solver
    accuracy.

## Code demo I: four kinds of Kepler motion

::: columns
::: {.column width="45%"}
**DEMO:** `kepler_orbits.py`

For $r_0=1$, $\mu=1$, and tangential launch speed $v_0$

Total energy: $E = \frac{1}{2} v_0^2-1/r_0$

  $v_0$      Orbit               Energy
  ---------- ------------------- --------
  $1$        Circular            $-1/2$
  $0.7$      Elliptical          $<0$
  $\sqrt2$   Parabolic escape    $0$
  $1.6$      Hyperbolic escape   $>0$

**Numerical sanity check:** What is the escape speed?
:::

::: {.column width="45%"}
![](./pics/kepler_orbit_gallery.png){width="95%"}
:::
:::

## Validating numerical solutions

::: {style="text-align: center;"}
![](./pics/kepler_numerical_instability.png){width="30%"}
:::

**Question:** When can we trust numerical solutions to ODEs?

-   Elliptical orbits should be stable: (no spiral inward nor outward).
-   Numerical solutions like **Euler's method** can drift badly.
-   We can use **conservation laws** as a nontrivial sanity check to
    validate our simulations.

## Conservation laws: a physicist's debugging tools

An isolated gravitational system conserves **energy**, **momentum**, and
**angular momentum**:

$$
\boxed{E=\sum_i\frac12 m_i |\mathbf v_i|^2
-G\sum_{i<j}\frac{m_i m_j}{|\mathbf r_i-\mathbf r_j|}}
$$

$$
\mathbf P=\sum_i m_i\mathbf v_i,\qquad
$$

$$
\mathbf L=\sum_i m_i\mathbf r_i\times\mathbf v_i
$$

-   These quantities should remain **constant** along the exact
    trajectory.
-   We can use conservation laws to **check our numerical solutions**.

## Code demo 2: Test energy conservation

For $m_1 = m_2 = \mu = 1$ the total energy is $E = \frac{1}{2} v^2-1/r$

``` {.python .numberLines}
x, y, vx, vy = sol.y    # Extract numerical solve_ivp solution
r = np.sqrt(x**2 + y**2)
energy = 0.5 * (vx**2 + vy**2) - 1 / r
energy_error = energy - energy[0]
```

**DEMO:** `kepler_energy.py`

1.  Compare Euler's method against `solve_ivp` from identical initial
    conditions.
2.  Plot the **orbit** and **energy drift** side by side.
3.  Decrease Euler's time step: does the trajectory improve?

**Takeaway:** Physical conservation laws provide numerical sanity
checks---but conserved energy **alone does not prove** an orbit is
accurate.

## The three-body problem

::: columns
::: {.column width="45%"}
-   Real examples: **Sun--Earth--Moon**, triple-star systems, spacecraft
    in multi-body gravitational fields.
    -   Setting for Liu Cixin's *The Three-Body Problem*.
-   The force law hasn't changed---we have added just one interacting
    mass.

\

**Question:** Does a deterministic force law guarantee a simple,
predictable trajectory?
:::

::: {.column width="45%"}
![Source: Wikipedia](./pics/3_body_orbits.png){width="80%"}
:::
:::

## Three bodies = 12 first-order equations in a plane

For each body $i=1,2,3$:

$$
\boxed{\ddot{\mathbf r}_i=
G\sum_{j\ne i}m_j
\frac{\mathbf r_j-\mathbf r_i}{|\mathbf r_j-\mathbf r_i|^3}}.
$$

As before, reduce from 2nd-order ODEs to 1st-order ODEs

Write the state as **six positions followed by six velocities**:

$$
\mathbf s=(x_1,y_1,x_2,y_2,x_3,y_3,
 v_{x1},v_{y1},v_{x2},v_{y2},v_{x3},v_{y3}).
$$

-   Three bodies $\times$ two coordinates $\times$ (position + velocity)
    $=\mathbf{12}$ ODEs.
-   Each acceleration depends on **both other bodies**.
-   `solve_ivp` handles the same kind of first-order system as before.

## Python: just change the right-hand side

For $m_i = G = 1$, we have
$\boxed{\ddot{\mathbf r}_i=\sum_{j\ne i} \frac{\mathbf r_j-\mathbf r_i}{|\mathbf r_j-\mathbf r_i|^3}}.$

``` {.python .numberLines}
def func_3body(t, state):
    x = state[:6].reshape(3, 2)   # positions
    v = state[6:].reshape(3, 2)   # velocities
    a = np.zeros((3, 2))          # accelerations
    for i in range(3):
        for j in range(3):
            if i != j:
                dx = x[j] - x[i]
                r = np.linalg.norm(dx)
                a[i] += dx / r**3
    return np.concatenate([v.reshape(6), a.reshape(6)])
```

-   Same `solve_ivp` interface; now the force is a **sum over pairs**.
-   Close approaches require extra numerical care because gravity is
    singular at collision.
-   Energy, total momentum, and angular momentum are **still
    conserved**.

## Code demo 3: chaos and the butterfly effect

::: columns
::: {.column width="45%"}
**DEMO:** `three_body_chaos.py` (use `--animate` for moving
trajectories)

-   Compare two systems with **almost identical initial positions**.
-   First they appear to agree; later their trajectories differ
    enormously.
-   This is **sensitivity to initial conditions**, i.e. the butterfly
    effect

\

**Key distinction:** **Deterministic** motion does not necessarily mean
that motion is **predictable**.
:::

::: {.column width="45%"}
![](./pics/3_body_chaos.png){width="60%"}
:::
:::

## Recap and takeaways

::: columns
::: {.column width="45%"}
-   Orbital motion obeys Newton's second law + universal law of
    gravitation

$$
\boxed{\mathbf F=m \mathbf a = -\frac{G m M}{r^3}
\mathbf r}
$$

-   Convert $n$ 2nd-order ODEs into $2n$ 1st-order ODEs
    -   Trick: introduce velocity $v = \dot x$ and use
        $\dot v = \ddot x$.
    -   Standard form:

$$
\dot{\mathbf s}=f(t,\mathbf s)
$$

-   Use `solve_ivp` to solve ODEs in standard form. Need to specify
    $f(t,\mathbf s)$
-   Energy conservation is a useful sanity check and debugging tool
-   Ordinary differential equations are **deterministic**, but do not
    always lead to **predictable** results due to chaos and the
    butterfly effect.
:::

::: {.column width="45%"}
![Source: science.nasa.gov](./pics/solar_system.jpg){width="50%"}

![](./pics/3_body_chaos.png){width="45%"}
:::
:::
