> ## Documentation Index
> Fetch the complete documentation index at: https://aegean.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Dynamic optimal transport

> How mass moves in time, and why constant speed costs least.

[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/pantelis/eng-ai-agents/blob/main/notebooks/optimal-transport/dynamic-transport/index.ipynb)

```python theme={null}
import numpy as np
import matplotlib.pyplot as plt
from scipy import sparse, stats
from scipy.optimize import linprog
from scipy.special import logsumexp
from scipy.stats import norm
```

```python theme={null}
# Source p_0 is the standard normal N(0, 1). Target p_1 is this Gaussian mixture.
PI = np.array([0.3, 0.5, 0.2])
MU = np.array([-2.0, 1.0, 3.5])
SIGMA = np.array([0.4, 0.6, 0.3])
U_CLIP = 1e-12  # quantile levels are clipped to [U_CLIP, 1 - U_CLIP]


def mixture_pdf(x, pi=PI, mu=MU, sigma=SIGMA):
    x = np.asarray(x, dtype=float)[..., None]
    return np.sum(pi * norm.pdf(x, mu, sigma), axis=-1)


def mixture_cdf(x, pi=PI, mu=MU, sigma=SIGMA):
    x = np.asarray(x, dtype=float)[..., None]
    return np.sum(pi * norm.cdf(x, mu, sigma), axis=-1)


def mixture_ppf(u, pi=PI, mu=MU, sigma=SIGMA, iters=64):
    """Quantile function F_1^{-1}(u) by vectorized bisection on the mixture CDF.

    The root lies between the smallest and the largest component quantile at level u.
    """
    u = np.clip(np.asarray(u, dtype=float), U_CLIP, 1 - U_CLIP)
    q = mu + sigma * norm.ppf(u)[..., None]
    lo, hi = q.min(axis=-1), q.max(axis=-1)
    for _ in range(iters):
        mid = 0.5 * (lo + hi)
        below = mixture_cdf(mid, pi, mu, sigma) < u
        lo = np.where(below, mid, lo)
        hi = np.where(below, hi, mid)
    return 0.5 * (lo + hi)


def monge_map(x0, pi=PI, mu=MU, sigma=SIGMA):
    """Increasing map T = F_1^{-1} o F_0 from N(0, 1) to the mixture."""
    return mixture_ppf(norm.cdf(x0), pi, mu, sigma)


def w2_squared(n_quad=20000, pi=PI, mu=MU, sigma=SIGMA):
    """W_2^2(p_0, p_1) as the integral of (F_0^{-1} - F_1^{-1})^2 over (0, 1), midpoint rule."""
    u = (np.arange(n_quad) + 0.5) / n_quad
    return np.mean((norm.ppf(u) - mixture_ppf(u, pi, mu, sigma)) ** 2)


def fm_path_density(t, x, pi=PI, mu=MU, sigma=SIGMA):
    """Density of x_t = (1 - t) x_0 + t x_1 with x_0 ~ N(0, 1) and x_1 ~ p_1 independent."""
    s = np.sqrt((1 - t) ** 2 + t**2 * sigma**2)
    return mixture_pdf(x, pi, t * mu, s)


def plot_transport(ax, t_grid, x_grid, density, trajectories=None, title="",
                   action=None, edge=0.22):
    """Standard figure: heatmap of p_t(x) with time on the horizontal axis.

    density has shape (len(x_grid), len(t_grid)). The source and target columns are
    drawn as profiles outside the left and right edges. trajectories, if given, has
    shape (len(t_grid), n_particles). action, if given, is reported in the title.
    """
    vmax = np.quantile(density, 0.995)
    ax.pcolormesh(t_grid, x_grid, density, shading="auto", cmap="magma", vmin=0, vmax=vmax)
    for col, side, color in ((0, -1, "tab:blue"), (-1, 1, "tab:orange")):
        profile = density[:, col] / density[:, col].max()
        t_edge = t_grid[col]
        ax.fill_betweenx(x_grid, t_edge, t_edge + side * edge * profile,
                         color=color, alpha=0.7, lw=0)
    if trajectories is not None:
        ax.plot(t_grid, trajectories, color="white", lw=0.6, alpha=0.7)
    ax.set_xlim(t_grid[0] - 1.05 * edge, t_grid[-1] + 1.05 * edge)
    ax.set_ylim(x_grid[0], x_grid[-1])
    ax.set_xticks(np.linspace(t_grid[0], t_grid[-1], 5))
    ax.set_xlabel("t")
    ax.set_ylabel("x")
    if action is not None:
        title = f"{title} (kinetic action {action:.3f})" if title else f"kinetic action {action:.3f}"
    ax.set_title(title)
```

## Paths with the same endpoints

The [transport maps and couplings section](https://aegean.ai/aiml-common/lectures/optimal-transport/maps-and-couplings/index.md) found the cheapest way to pair source points with target points. For the squared distance on the line it is the increasing map $T = F_1^{-1} \circ F_0$, and its cost is $W_2^2(p_0, p_1)$. This section asks the next question: how should the mass move through time?

A map gives the endpoint $x_1 = T(x_0)$ of each point and says nothing about the times in between. Every path of the form

$$
x_t = x_0 + h(t)\,\bigl(T(x_0) - x_0\bigr), \qquad h(0) = 0, \quad h(1) = 1,
$$

starts at $x_0$ and ends at $T(x_0)$. The function $h$ is a schedule. With $h(t) = t$ every point moves at constant speed. With $h(t) = t^2$ every point starts slowly and speeds up. For increasing $h$, all these paths move each point along the same segment, but at different times, so their intermediate densities $p_t$ differ.

The code below sets up the grids used in the rest of this section: 201 times in $[0, 1]$ and 2001 positions in $[-6, 7]$.

```python theme={null}
from scipy.integrate import quad
from scipy.interpolate import CubicSpline

T_GRID = np.linspace(0, 1, 201)
X_GRID = np.linspace(-6, 7, 2001)

# Fine grid of source points for pushing densities forward. Beyond |x_0| = 6.5 the
# quantile level Phi(x_0) approaches U_CLIP and T(x_0) stops being accurate.
X0_FINE = np.linspace(-6.5, 6.5, 20001)
T_FINE = monge_map(X0_FINE)
T_PRIME_FINE = norm.pdf(X0_FINE) / mixture_pdf(T_FINE)   # T'(x_0) = p_0(x_0) / p_1(T(x_0))
LEVELS = np.linspace(0.02, 0.98, 25)                     # quantile levels of plotted particles
```

## The fluid picture

Think of $p_t$ as the density of a fluid on the line and of $v_t(x)$ as the velocity of the fluid at position $x$ and time $t$. This is the picture of the storm in the [velocity fields section](https://aegean.ai/aiml-common/lectures/velocity-fields/index.md), where the wind carries raindrops. Here the field carries probability mass. A particle at $x$ at time $t$ moves with velocity $v_t(x)$, so its trajectory solves $\dot x_t = v_t(x_t)$.

Probability mass is conserved: it is neither created nor destroyed. The total stays equal to 1, and mass that leaves one place must arrive somewhere next to it. The wind in the storm example did not have to conserve anything it carried.

## The continuity equation

Conservation of mass becomes an equation once you count the mass in a fixed interval $[a, b]$,

$$
M(t) = \int_a^b p_t(x)\,dx .
$$

Mass enters or leaves the interval only through its two ends. The rate at which mass crosses a point $x$ from left to right is the flux $p_t(x)\,v_t(x)$, the density times the velocity. Mass flows in at $a$ and out at $b$, so

$$
\begin{aligned}
M'(t) &= p_t(a)\,v_t(a) - p_t(b)\,v_t(b) \\
&= -\int_a^b \partial_x\bigl(p_t(x)\,v_t(x)\bigr)\,dx .
\end{aligned}
$$

The second line is the fundamental theorem of calculus. Differentiating under the integral sign also gives $M'(t) = \int_a^b \partial_t p_t(x)\,dx$. The two integrals agree for every interval, so their integrands agree at every point:

$$
\partial_t p_t + \partial_x (p_t\, v_t) = 0 .
$$

This is the continuity equation (Santambrogio, 2015). It links a path to a field: the field $v_t$ moves the path $p_t$ when the pair satisfies it. The diffusion sections later in the book add a second flux term, for mass that spreads by random motion.

## Speed and kinetic energy

On the paths above, a particle moves with velocity $\dot x_t = h'(t)\,\bigl(T(x_0) - x_0\bigr)$. The kinetic action of a path is the average squared speed of its particles, integrated over time. For these paths it factors:

$$
\begin{aligned}
A &= \int_0^1 \mathbb{E}\bigl[\dot X_t^2\bigr]\,dt \\
&= \mathbb{E}\bigl[(T(X_0) - X_0)^2\bigr] \int_0^1 h'(t)^2\,dt \\
&= W_2^2(p_0, p_1) \int_0^1 h'(t)^2\,dt .
\end{aligned}
$$

The last step uses the result of the maps and couplings section: the cost of the increasing map is $W_2^2$. By the Cauchy-Schwarz inequality,

$$
1 = \Bigl(\int_0^1 h'(t)\,dt\Bigr)^2 \le \int_0^1 h'(t)^2\,dt ,
$$

with equality only when $h'$ is constant, that is, when $h(t) = t$. For $h(t) = t^2$ the integral is $\int_0^1 4t^2\,dt = 4/3$, so this schedule costs a third more than constant speed. Of all the ways of following the map $T$, constant speed has the smallest kinetic action, and that action is $W_2^2$.

The code below evaluates both actions.

```python theme={null}
w2 = w2_squared()
schedules = {"h(t) = t": (lambda t: t, lambda t: 1.0),
             "h(t) = t^2": (lambda t: t**2, lambda t: 2 * t)}
actions = {name: w2 * quad(lambda t: dh(t) ** 2, 0, 1)[0] for name, (h, dh) in schedules.items()}
for name, a in actions.items():
    print(f"kinetic action, {name}: {a:.4f}  (ratio to W_2^2: {a / w2:.4f})")
```

```output theme={null}
kinetic action, h(t) = t: 1.5149  (ratio to W_2^2: 1.0000)
kinetic action, h(t) = t^2: 2.0198  (ratio to W_2^2: 1.3333)
```

```python theme={null}
h_ratio = quad(lambda t: (2*t)**2, 0, 1)[0]
assert abs(h_ratio - 4/3) < 1e-9
A_h = w2_squared() * h_ratio                     # action of h(t) = t^2
assert A_h > w2_squared()
assert abs(actions["h(t) = t"] - w2_squared()) < 1e-12 and abs(actions["h(t) = t^2"] - A_h) < 1e-9
```

![Two panels of 25 particle trajectories plotted against time. On the left, with h(t) = t, every trajectory is a straight line from its start at t = 0 to its end at t = 1, and the lines spread into three groups. On the right, with h(t) = t squared, the trajectories have the same endpoints but stay nearly flat at first and bend toward their targets near t = 1. The titles report kinetic actions 1.515 and 2.020.](https://mintcdn.com/aegeanaiinc/TxnGZcYFzPhEZiXx/aiml-common/lectures/optimal-transport/dynamic-transport/images/cell_6_output_1.png?fit=max\&auto=format\&n=TxnGZcYFzPhEZiXx\&q=85\&s=9863a388f623f65bb1b3099b9e90da1d)

*Trajectories of 25 source points at evenly spaced quantile levels under the same map $T$. Both schedules move each point along the same segment. With $h(t) = t^2$ the points move little before $t = 0.5$ and fast near $t = 1$.*

## Displacement interpolation

The constant-speed paths define a probability path. The geodesic $p_t$ is the density of

$$
x_t = (1 - t)\,x_0 + t\,T(x_0), \qquad x_0 \sim p_0 .
$$

This path is called displacement interpolation (Santambrogio, 2015). Each particle moves from its own position to its target. The path is never a weighted average of $p_0$ and $p_1$. The last part of this section computes the cost of such an average.

The map $x_0 \mapsto x_t$ is increasing, so the change of variables formula gives the density,

$$
\begin{aligned}
p_t(x_t) &= \frac{p_0(x_0)}{1 - t + t\,T'(x_0)}, \\
T'(x_0) &= \frac{p_0(x_0)}{p_1(T(x_0))} .
\end{aligned}
$$

The formula for $T'$ comes from differentiating $F_1(T(x)) = F_0(x)$. Because the map keeps the order of points, the CDF follows too: $F_t(x_t) = F_0(x_0)$. Each particle also moves at the constant velocity $T(x_0) - x_0$, so the field at $x$ is that velocity for the source point $x_0$ that reaches $x$ at time $t$. The code below computes all three by pushing a fine grid of source points forward.

```python theme={null}
def _source_point(t, x):
    """The source point x_0 whose straight path reaches x at time t (x is clipped to the range)."""
    x_t = (1 - t) * X0_FINE + t * T_FINE
    return CubicSpline(x_t, X0_FINE)(np.clip(x, x_t[0], x_t[-1]))


def geodesic_density(t, x):
    """Density of x_t = (1 - t) x_0 + t T(x_0), pushed forward from the fine source grid."""
    x_t = (1 - t) * X0_FINE + t * T_FINE
    p = norm.pdf(X0_FINE) / (1 - t + t * T_PRIME_FINE)
    # Cubic, not linear, interpolation: where the map stretches the grid, linear
    # interpolation errs by about 0.1% and the 1D field formula divides by p_t.
    inside = (x >= x_t[0]) & (x <= x_t[-1])
    return np.where(inside, CubicSpline(x_t, p)(np.clip(x, x_t[0], x_t[-1])), 0.0)


def geodesic_cdf(t, x):
    """F_t(x) = F_0(x_0) for the source point x_0 that reaches x at time t."""
    return norm.cdf(_source_point(t, x))


def geodesic_field(t_grid, x_grid):
    """v_t(x) = T(x_0) - x_0 at the source point of x, shape (len(x_grid), len(t_grid))."""
    v = np.empty((len(x_grid), len(t_grid)))
    for j, t in enumerate(t_grid):
        x0 = _source_point(t, x_grid)
        v[:, j] = monge_map(x0) - x0
    return v


def kinetic_action(density_fn, field, t_grid, x_grid):
    """Integral of p_t v_t^2 over x and t by the trapezoid rule, skipping nan cells of field."""
    p = np.stack([density_fn(t, x_grid) for t in t_grid], axis=1)
    integrand = np.where(np.isfinite(field), p * np.nan_to_num(field) ** 2, 0.0)
    return np.trapezoid(np.trapezoid(integrand, x_grid, axis=0), t_grid)
```

```python theme={null}
mass = [np.trapezoid(geodesic_density(t, X_GRID), X_GRID) for t in T_GRID]
v_lagr = geodesic_field(T_GRID, X_GRID)
action_geo = kinetic_action(geodesic_density, v_lagr, T_GRID, X_GRID)
print(f"total mass of p_t over the grid: between {min(mass):.5f} and {max(mass):.5f}")
print(f"kinetic action of the geodesic: {action_geo:.4f} ; W_2^2: {w2:.4f}")
```

```output theme={null}
total mass of p_t over the grid: between 1.00000 and 1.00001
kinetic action of the geodesic: 1.5149 ; W_2^2: 1.5149
```

```python theme={null}
mass = [np.trapezoid(geodesic_density(t, X_GRID), X_GRID) for t in T_GRID]
assert np.allclose(mass, 1, atol=1e-3)
v_lagr = geodesic_field(T_GRID, X_GRID)          # T(x0) - x0 at the preimage of x
assert abs(kinetic_action(geodesic_density, v_lagr, T_GRID, X_GRID) / w2_squared() - 1) < 5e-3
```

![Heatmap of the geodesic path with time on the horizontal axis and x on the vertical axis. The standard normal source profile is on the left edge and the three-component target profile on the right edge. Straight white particle lines fan out from the source and form three bright bands that end at the three target components. The title reports kinetic action 1.515.](https://mintcdn.com/aegeanaiinc/TxnGZcYFzPhEZiXx/aiml-common/lectures/optimal-transport/dynamic-transport/images/cell_10_output_1.png?fit=max\&auto=format\&n=TxnGZcYFzPhEZiXx\&q=85\&s=d4d25db90513bfc942676ffa0dd79e5d)

*Displacement interpolation from $p_0$ to $p_1$. Each white line is one particle moving at constant velocity. The single bump of $p_0$ splits into three bands right away, and each band moves straight to one component of $p_1$. The independent-pair path of the maps and couplings section narrowed before it split; this one does not.*

## A density path fixes its field

In 1D the continuity equation can be solved for the field. Integrate it over $(-\infty, x]$. The first term gives $\partial_t F_t(x)$, the time derivative of the CDF. The second gives $p_t(x)\,v_t(x)$, provided the flux vanishes at $-\infty$. So $\partial_t F_t + p_t\, v_t = 0$, and

$$
v_t(x) = -\frac{\partial_t F_t(x)}{p_t(x)} .
$$

The path alone determines the field. The code below computes the geodesic field in two ways: from this formula, with a finite difference in $t$, and from the particle velocities $T(x_0) - x_0$. The formula divides by $p_t$, so the comparison uses only the grid points where $p_t(x) > 10^{-3}$. Farther out in the tails the field moves almost no mass, and dividing by a tiny density amplifies small numerical errors.

```python theme={null}
def field_from_cdf(cdf_fn, density_fn, t_grid, x_grid, dt=1e-4):
    """v_t(x) = -dF_t(x)/dt / p_t(x) on the grid, nan where p_t(x) <= 1e-3.

    Central differences in t inside (0, 1); second-order one-sided differences at t = 0
    and t = 1, so the path is never evaluated outside [0, 1].
    """
    v = np.empty((len(x_grid), len(t_grid)))
    for j, t in enumerate(t_grid):
        F = lambda s: cdf_fn(s, x_grid)
        if t - dt < 0:
            dF = (-3 * F(t) + 4 * F(t + dt) - F(t + 2 * dt)) / (2 * dt)
        elif t + dt > 1:
            dF = (3 * F(t) - 4 * F(t - dt) + F(t - 2 * dt)) / (2 * dt)
        else:
            dF = (F(t + dt) - F(t - dt)) / (2 * dt)
        p = density_fn(t, x_grid)
        v[:, j] = np.where(p > 1e-3, -dF / np.maximum(p, 1e-3), np.nan)
    return v
```

```python theme={null}
v_cdf = field_from_cdf(geodesic_cdf, geodesic_density, T_GRID, X_GRID)
mask = np.isfinite(v_cdf)
print(f"largest |v from the CDF - v from the particles| where p_t > 1e-3: "
      f"{np.max(np.abs(v_cdf[mask] - v_lagr[mask])):.1e}")
```

```output theme={null}
largest |v from the CDF - v from the particles| where p_t > 1e-3: 3.8e-05
```

```python theme={null}
v_cdf = field_from_cdf(geodesic_cdf, geodesic_density, T_GRID, X_GRID)
mask = np.isfinite(v_cdf)
assert np.max(np.abs(v_cdf[mask] - v_lagr[mask])) < 1e-3
assert np.max(np.abs(v_cdf[mask] - v_lagr[mask])) < 1e-4   # the two computations agree to 1e-4
```

![Three line plots of the geodesic field against x at times 0, 0.5 and 1. In each, a thin red curve from the CDF formula lies on top of a thick gray curve from the particle velocities. At time 0 the field rises steeply near x = -0.5 and x = 0.8. At times 0.5 and 1 the curves are smooth, ranging from about -1 to about 2.3.](https://mintcdn.com/aegeanaiinc/TxnGZcYFzPhEZiXx/aiml-common/lectures/optimal-transport/dynamic-transport/images/cell_14_output_1.png?fit=max\&auto=format\&n=TxnGZcYFzPhEZiXx\&q=85\&s=98e4c854a536248ef2d76b97c712d419)

*The geodesic field at three times, from the CDF formula (red) and from the particle velocities (gray), drawn where $p_t > 10^{-3}$.*

The largest difference between the two computations, printed above, is below $10^{-4}$. At $t = 0$ the field rises steeply near $x = -0.5$ and $x = 0.8$. Source points on either side of those positions head for different components of the mixture. As $t$ grows the three groups move apart and the field becomes smooth.

This uniqueness is special to 1D. In two or more dimensions the continuity equation reads $\partial_t p_t + \nabla \cdot (p_t v_t) = 0$. You can add to $v_t$ any field $w_t$ with $\nabla \cdot (p_t w_t) = 0$ without changing the path. A rotation about the center of a radially symmetric density is an example: it moves every particle except the one at the center, but leaves the density as it was. Many fields then move the same path, and choosing among them is part of the problem.

## The Benamou-Brenier formula

Benamou and Brenier recast the static problem of the maps and couplings section as a problem about motion (Benamou & Brenier, 2000; Peyré & Cuturi, 2018). Consider every pair $(p_t, v_t)$ that satisfies the continuity equation, with $p_t$ equal to $p_0$ at $t = 0$ and to $p_1$ at $t = 1$. The smallest kinetic energy among them is $W_2^2$:

$$
\begin{aligned}
W_2^2(p_0, p_1) &= \min_{(p_t,\, v_t)} \int_0^1 \!\! \int p_t(x)\, v_t(x)^2 \,dx\,dt, \\
&\text{subject to } \partial_t p_t + \partial_x (p_t\, v_t) = 0 .
\end{aligned}
$$

The inner integral is the average squared speed of the mass at time $t$, the same quantity as $\mathbb{E}[\dot X_t^2]$ in the kinetic action. The minimizer is the geodesic. Its computed energy above matches $W_2^2$, and the schedules showed that following the same map at uneven speed costs more.

As a second check, take a path of a different kind. The mixture path blends the two densities,

$$
p_t = (1 - t)\,p_0 + t\,p_1, \qquad F_t = (1 - t)\,F_0 + t\,F_1 .
$$

Its field comes from the 1D formula. Its particles follow from the same formula: along a trajectory, $\frac{d}{dt} F_t(x_t) = \partial_t F_t + p_t v_t = 0$, so a particle keeps its quantile level and $x_t = F_t^{-1}\bigl(F_0(x_0)\bigr)$. The code below computes the field, the particles and the kinetic energy of the mixture path.

```python theme={null}
def mix_path_density(t, x):
    return (1 - t) * norm.pdf(x) + t * mixture_pdf(x)


def mix_path_cdf(t, x):
    return (1 - t) * norm.cdf(x) + t * mixture_cdf(x)


def path_quantile(cdf_fn, t, u, lo=-8.0, hi=9.0, iters=60):
    """F_t^{-1}(u) by vectorized bisection on the path CDF."""
    lo, hi = np.full_like(u, lo), np.full_like(u, hi)
    for _ in range(iters):
        mid = 0.5 * (lo + hi)
        below = cdf_fn(t, mid) < u
        lo, hi = np.where(below, mid, lo), np.where(below, hi, mid)
    return 0.5 * (lo + hi)
```

```python theme={null}
v_mix = field_from_cdf(mix_path_cdf, mix_path_density, T_GRID, X_GRID)
action_mix = kinetic_action(mix_path_density, v_mix, T_GRID, X_GRID)
print(f"kinetic energy of the mixture path where p_t > 1e-3: {action_mix:.4f}"
      f"  ({action_mix / w2:.2f} times W_2^2)")
```

```output theme={null}
kinetic energy of the mixture path where p_t > 1e-3: 3.3156  (2.19 times W_2^2)
```

```python theme={null}
v_mix = field_from_cdf(mix_path_cdf, mix_path_density, T_GRID, X_GRID)
assert kinetic_action(mix_path_density, v_mix, T_GRID, X_GRID) > 1.01 * w2_squared()
assert kinetic_action(mix_path_density, v_mix, T_GRID, X_GRID) > 2 * w2_squared()   # more than twice W_2^2
mix_traj = np.stack([path_quantile(mix_path_cdf, t, LEVELS) for t in T_GRID])
assert np.allclose(mix_traj[0], norm.ppf(LEVELS), atol=1e-9)
assert np.allclose(mix_traj[-1], mixture_ppf(LEVELS), atol=1e-9)
```

![Two standard transport heatmaps side by side. The geodesic on the left shows straight particle lines fanning into three bands, with kinetic action 1.515. The mixture path on the right shows the source bump fading while the three target bumps brighten in place. Its particle lines stay nearly flat, then jump quickly across dark gaps into the upper and lower components. Its title reports kinetic action 3.316.](https://mintcdn.com/aegeanaiinc/TxnGZcYFzPhEZiXx/aiml-common/lectures/optimal-transport/dynamic-transport/images/cell_18_output_1.png?fit=max\&auto=format\&n=TxnGZcYFzPhEZiXx\&q=85\&s=c4c0a71eaa713546a0d10ddbc391c8fe)

*Left, the geodesic. Right, the mixture path $(1 - t)\,p_0 + t\,p_1$, with particles that keep their quantile levels. Both paths join the same endpoints.*

The computed energy of the mixture path is more than twice $W_2^2$. The sum leaves out the grid cells where $p_t \le 10^{-3}$, so the true energy is larger still. The energy is high because this path never moves the source bump. It fades the bump out where it is and fades the target components in where they are. Particles must keep their quantile levels, so a particle bound for the upper or lower component waits and then crosses a nearly empty gap in a short time. A short crossing means a high speed, and the energy grows with the square of the speed.

## From the geodesic to flow matching

Flow matching works with the same objects: a probability path, the field that moves it, and the continuity equation that links them. It picks a path that is easy to sample and to learn from samples, and that path is not in general the geodesic. The [flow matching section](https://aegean.ai/aiml-common/lectures/flow-matching/index.md) states the method in general, and the [1D mixture section](https://aegean.ai/aiml-common/lectures/flow-matching/mog-1d/index.md) runs it on this mixture and measures its kinetic action against $W_2^2$.

Key references: (Benamou & Brenier, 2000; Santambrogio, 2015; Peyré & Cuturi, 2018)

## References

* Benamou, J., Brenier, Y. (2000). *A computational fluid mechanics solution to the Monge-Kantorovich mass transfer problem*. Numer. Math. (Heidelb.). [DOI](https://doi.org/10.1007/s002110050002)
* Peyré, G., Cuturi, M. (2018). *Computational Optimal Transport*. arXiv \[stat.ML]. [DOI](https://doi.org/10.48550/arXiv.1803.00567)
* Santambrogio, F. (2015). *Optimal transport for applied mathematicians – calculus of variations, PDEs and modeling*.

***

Found an error on this page? [Report an issue](https://github.com/aegean-ai/eaia-feedback/issues/new?template=page-issue.yml\&page=/aiml-common/lectures/optimal-transport/dynamic-transport).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.