All articles

Dirac concentration and discrete Wasserstein flows

When does an attractive interaction concentrate all the mass at a single vertex? The decisive role of mobilities that vanish at the boundary of the simplex.

Go to the experiment · View the code

Mass moving on a graph

The model lives on the discrete torus \(X=(\mathbb Z/N\mathbb Z)^2\). At each vertex, \(\rho_t(x)\) is a mass, with \(\sum_x\rho_t(x)=1\). The two horizontal axes run through the actual \(N\times N\) graph, whose vertices and edges are shown; the height gives \(\rho_t\). The surface between vertices is a piecewise-linear visual interpolation, not an additional continuous density model. Opposite edges are adjacent. The square is therefore a chart of the discrete torus, rather than a domain with boundary conditions.

The kernel is that of the full model, with \(\beta>0\):

\[ k_\beta(z)=\exp\!\left[\beta\left(\cos\frac{2\pi z_1}{N}+\cos\frac{2\pi z_2}{N}\right)\right], \qquad U_\rho=k_\beta*\rho. \]

Attraction favours increasing the energy \(E_\beta(\rho)=\sum_x\rho(x)U_\rho(x)\). Mass is transported only along graph edges. The integrated vector field is exactly the one in the article, using the mass convention and \(a(x,y)=1/4\):

\[ \dot\rho(x)=\frac12\sum_{y\sim x}\Theta(\rho(x),\rho(y))\bigl(U_\rho(x)-U_\rho(y)\bigr), \qquad \Theta(s,t)=\frac{s-t}{\log s-\log t}. \]

On the diagonal, \(\Theta(s,s)=s\). As soon as either argument vanishes, the mobility vanishes. This is the delicate feature of the model: exterior mass may lose the paths connecting it to the vertex at which concentration is expected. The energy increases, but that alone does not force a Dirac mass. The visualisation therefore makes no assumption that every initial condition eventually forms a single peak.

What is computed

Each experiment starts from a random mixture of periodic bumps, with a strictly positive background. The result is normalised to have total mass one. The seed is displayed: a new experiment changes it, and the exported results allow the initial condition to be reproduced exactly. Changing a parameter and choosing “Recompute” retains the seed, making comparisons possible.

The periodic convolution is computed by FFT. Fluxes are constructed on each unoriented edge and added with opposite signs at its endpoints. This formulation conserves mass up to roundoff. An adaptive Heun scheme controls the local error, positivity and energy increase. The setting \(\Delta t_{\max}\) is an upper bound; the steps actually taken may be smaller, especially near the boundary of the simplex.

A decreasing coordinate below \(10^{-10}\) is set to zero and remains zero. The mass removed in this way is recorded in the results. This approximates the continuation with non-increasing support studied in the text. The threshold is not an extinction theorem: a careful study near the boundary requires lowering it and refining the time step. The program does not explore other continuations that the continuous vector field might admit at the boundary.

Long horizons and the time axis

The requested horizon can extend to \(T=10^6\). Increasing \(T\) does not change the equation or accelerate its physical clock. The maximum step remains the value entered, with a permitted range up to \(10^4\). For a long calculation, a ceiling such as \(100\) or \(1000\) allows larger steps in slowly varying portions of the trajectory; error, positivity and energy checks still reduce the steps wherever needed. Raising this ceiling is not the same as imposing a large fixed step.

Saved times are equally spaced for \(T\leq160\). Beyond that, the default uses the coordinate \(\log(1+t)\), keeping more detail near the start while covering a much longer interval:

\[ t_j=\exp\!\left(\frac{j}{m-1}\log(1+T)\right)-1,\qquad j=0,\ldots,m-1. \]

The labels and time entry always give the physical model time \(t\). The logarithmic scale changes navigation and the saved observation times; it does not rescale the evolution. A large gap between saved times may contain many adaptive steps. The Python option --time-sampling can select linear or logarithmic explicitly.

A constant continuation is used only once the computed vector field is exactly zero. Its starting time is saved and reported. This can happen with several isolated occupied vertices, because the logarithmic mobility vanishes across every intervening zero. It is a stationary state of the numerical continuation; the extinction threshold remains part of that approximation.

Otherwise the solver keeps integrating. The default work budget is \(30{,}000\) accepted or rejected trial steps. If it runs out, the result stops at the last time actually reached and the status reports the incomplete interval. A nonzero drift that becomes too small to produce a representable update is also reported as an incomplete calculation, rather than replaced by a stationary tail. The exported values completed, reached_T and termination make the distinction explicit. A larger maximum step may make a long run practical; local runs can also increase the budget with --max-steps.

Reading and comparing trajectories

The time slider below the figure gives access to the saved trajectory, ending at the last computed time if a run is incomplete. During playback, the display interpolates linearly between saved times; the values at those times come from the solver. Interpolation makes the animation smooth and does not perform a new integration. The vertical axis rescales to the current frame, so use its numerical labels and the displayed maximum to compare heights over time. Rescaling changes the drawing, not the masses or the diagnostic curves.

The parameter \(N\) changes the graph itself. This is not merely a mesh refinement for a fixed continuous equation, since the edge weights remain those of the manuscript. The parameter \(\beta\) changes the kernel, its amplitude and its time scale: comparing two values at the same physical time therefore differs from comparing them after rescaling time. No implicit reduction to the \(\beta=0\) model is made.

The energy curve and the mass, maximum and support values help interpret the result. The first-mode quantity is recorded, but its monotonicity is not imposed for the full exponential kernel. Results can be exported with all parameters; the Python script shown below is the file executed by this experiment.

Evolution of the density

Enter a value up to 1,000,000. The slider is logarithmic.
Adaptive error control may choose a smaller step.

Loading the experiment…

Drag · rotate
Scroll · zoom
LowHighOccupied vertex
t = 0

Interpolation between computed states; the tick labels show the current vertical scale.

The lattice shows the actual graph vertices and nearest-neighbour edges. Height and colour represent mass; the vertical axis adjusts to the current density. Contours and the surface between vertices are visual interpolation.

Parameters and computation details

Experiment code

This is the Python file executed by the experiment. It can also be run locally. The window contains the complete source.

wasserstein.pyDownload
"""Attractive Wasserstein--Maas flow on the two-dimensional discrete torus.

The mass convention and factor 1/(2d) are those of the manuscript.
Run: python wasserstein.py --output wasserstein.json --seed 1729
"""

import argparse
import json
import math
import time

import numpy as np


def logarithmic_mean(a, b):
    out = np.zeros_like(a)
    active = (a > 0) & (b > 0)
    small = active & (np.abs(a - b) < 1e-6 * (a + b))
    # The expansion avoids cancellation near the diagonal.
    z = np.zeros_like(a)
    np.divide(a - b, a + b, out=z, where=small)
    out[small] = 0.5 * (a[small] + b[small]) * (1 - z[small] ** 2 / 3)
    far = active & ~small
    out[far] = (a[far] - b[far]) / (np.log(a[far]) - np.log(b[far]))
    return out


def interaction_kernel(n, beta):
    c = np.cos(2 * np.pi * np.arange(n) / n)
    return np.exp(beta * (c[:, None] + c[None, :]))


def vector_field(rho, kernel_fft):
    potential = np.fft.ifft2(np.fft.fft2(rho) * kernel_fft).real
    derivative = np.zeros_like(rho)
    # Each unoriented edge is counted once; 2 a(x,y) = 1/2 in d=2.
    for axis in (0, 1):
        other = np.roll(rho, -1, axis=axis)
        flux = 0.5 * logarithmic_mean(rho, other) * (
            potential - np.roll(potential, -1, axis=axis)
        )
        derivative += flux - np.roll(flux, 1, axis=axis)
    return derivative, potential


def initial_density(n, rng):
    y, x = np.mgrid[:n, :n]
    density = np.full((n, n), rng.uniform(0.03, 0.12))
    for _ in range(int(rng.integers(3, 7))):
        cx, cy = rng.uniform(0, n, 2)
        sx, sy = rng.uniform(0.06, 0.23, 2) * n
        dx = (x - cx + n / 2) % n - n / 2
        dy = (y - cy + n / 2) % n - n / 2
        density += rng.uniform(0.3, 1.2) * np.exp(-0.5 * ((dx / sx) ** 2 + (dy / sy) ** 2))
    density *= rng.uniform(0.94, 1.06, (n, n))
    return density / density.sum()


def simulate(params=None):
    p = params or {}
    n = int(p.get("N", 16))
    beta = float(p.get("beta", 0.8))
    horizon = float(p.get("T", 24))
    max_dt = float(p.get("dt", 0.08))
    seed = int(p.get("seed", 1729))
    snapshots = int(p.get("snapshots", 121))
    step_budget = int(p.get("max_steps", 30000))
    time_sampling = p.get("time_sampling", "auto")
    if not 4 <= n <= 40:
        raise ValueError("N must lie between 4 and 40.")
    if not 0.01 <= beta <= 3 or not 0 < horizon <= 1e6:
        raise ValueError("Parameters out of range: 0.01 ≤ β ≤ 3, 0 < T ≤ 1,000,000.")
    if not 0.0005 <= max_dt <= 1e4 or not 2 <= snapshots <= 301:
        raise ValueError("Time step or number of snapshots out of range.")
    if not 1 <= step_budget <= 200000:
        raise ValueError("The trial-step budget must lie between 1 and 200,000.")
    if time_sampling not in ("auto", "linear", "logarithmic"):
        raise ValueError("time_sampling must be auto, linear or logarithmic.")
    if time_sampling == "auto":
        time_sampling = "logarithmic" if horizon > 160 else "linear"

    started = time.perf_counter()
    rng = np.random.default_rng(seed)
    rho = initial_density(n, rng)
    kernel_fft = np.fft.fft2(interaction_kernel(n, beta))
    if time_sampling == "logarithmic":
        target_times = np.expm1(np.linspace(0, math.log1p(horizon), snapshots))
        target_times[-1] = horizon
    else:
        target_times = np.linspace(0, horizon, snapshots)
    times = []
    frames, energy, mass, maxima, support, first_modes = [], [], [], [], [], []
    t = 0.0
    dt = max_dt
    accepted = rejected = 0
    smallest_step, largest_step = math.inf, 0.0
    removed_mass = 0.0
    extinction = 1e-10
    atol, rtol = 2e-8 / (n * n), 4e-4
    stationary_from = None
    termination = None

    def snapshot():
        _, potential = vector_field(rho, kernel_fft)
        modes = np.fft.fft2(rho)
        frames.append(rho.ravel().tolist())
        energy.append(float(np.sum(rho * potential)))
        mass.append(float(rho.sum()))
        maxima.append(float(rho.max()))
        support.append(int(np.count_nonzero(rho)))
        first_modes.append(float(abs(modes[0, 1]) ** 2 + abs(modes[1, 0]) ** 2))
        times.append(float(t))

    snapshot()
    for target in target_times[1:]:
        if stationary_from is not None:
            t = float(target)
            snapshot()
            continue
        while t < target - 1e-12:
            f0, u0 = vector_field(rho, kernel_fft)
            if not np.any(f0):
                stationary_from = float(t)
                if t > times[-1]:
                    snapshot()
                t = float(target)
                break
            if accepted + rejected >= step_budget:
                termination = "step_budget"
                break
            negative = f0 < 0
            positivity_dt = np.min(-rho[negative] / f0[negative]) if negative.any() else np.inf
            h = min(dt, max_dt, target - t, 0.85 * positivity_dt)
            if not np.isfinite(h) or h <= 0 or t + h == t:
                termination = "precision_limit"
                break

            predictor = rho + h * f0
            f1, _ = vector_field(predictor, kernel_fft)
            candidate = rho + 0.5 * h * (f0 + f1)
            if not np.all(np.isfinite(candidate)) or candidate.min() < -1e-15:
                dt = h / 2
                rejected += 1
                continue
            scale = atol + rtol * np.maximum(rho, candidate)
            error = float(np.sqrt(np.mean(((candidate - predictor) / scale) ** 2)))
            _, u1 = vector_field(candidate, kernel_fft)
            e0, e1 = float(np.sum(rho * u0)), float(np.sum(candidate * u1))
            if error > 1.0 or e1 < e0 - 5e-13:
                dt = h * max(0.15, 0.85 / math.sqrt(max(error, 1.01)))
                rejected += 1
                continue

            # A nonzero drift is never replaced by a stationary continuation.
            if np.array_equal(candidate, rho):
                termination = "precision_limit"
                break

            rho = np.maximum(candidate, 0)
            dying = (rho > 0) & (rho < extinction) & (f1 < 0)
            lost = float(rho[dying].sum())
            if lost:
                rho[dying] = 0
                removed_mass += lost
            # Correct only round-off and the explicitly reported extinction mass.
            rho /= rho.sum()
            t += h
            accepted += 1
            smallest_step, largest_step = min(smallest_step, h), max(largest_step, h)
            dt = min(max_dt, h * min(2, max(0.3, 0.9 / math.sqrt(max(error, 1e-12)))))
        if termination is not None:
            if t > times[-1]:
                snapshot()
            break
        t = float(target)
        snapshot()

    completed = termination is None
    if completed:
        termination = "stationary" if stationary_from is not None else "target_reached"
    final_rhs = float(np.max(np.abs(vector_field(rho, kernel_fft)[0])))
    if termination == "stationary":
        status = (f"Reached t = {horizon:g}. The computed vector field became exactly zero "
                  f"at t = {stationary_from:g}; the remaining interval uses its constant continuation.")
    elif termination == "target_reached":
        status = f"Computed the trajectory to t = {t:g}."
    elif termination == "step_budget":
        status = (f"Stopped at t = {t:g} of the requested T = {horizon:g} after "
                  f"{accepted + rejected:,} trial steps. Later times have not been computed. "
                  "A larger maximum step may help; the Python script also accepts a larger step budget.")
    else:
        status = (f"Stopped at t = {t:g} of the requested T = {horizon:g}: a nonzero drift "
                  "could not produce a representable state or time increment. "
                  "No stationary continuation was substituted.")

    return {
        "x": list(range(n)), "y": list(range(n)), "frames": frames,
        "times": times,
        "diagnostics": {"energy": energy, "mass": mass, "maximum": maxima,
                        "support": support, "first_modes": first_modes},
        "meta": {"N": n, "beta": beta, "T": horizon, "dt": max_dt, "seed": seed,
                 "requested_T": horizon, "reached_T": times[-1], "completed": completed,
                 "termination": termination, "status_message": status,
                 "stationary_from": stationary_from, "final_rhs_max": final_rhs,
                 "integrated_until": stationary_from if stationary_from is not None else float(t),
                 "time_sampling": time_sampling, "time_sampling_scale": 1.0,
                 "step_budget": step_budget, "requested_snapshots": snapshots,
                 "saved_snapshots": len(times),
                 "accepted_steps": accepted, "rejected_steps": rejected,
                 "smallest_accepted_dt": smallest_step if accepted else None,
                 "largest_accepted_dt": largest_step if accepted else None,
                 "extinction_threshold": extinction, "removed_mass": removed_mass,
                 "mass_error": max(abs(v - 1) for v in mass),
                 "minimum_energy_increment": float(np.min(np.diff(energy))) if len(energy) > 1 else 0.0,
                 "seconds": time.perf_counter() - started,
                 "method": "Adaptive Heun scheme, conservative fluxes, continuation with nonincreasing support",
                 "time_label": "t", "field_label": "ρₜ(x)",
                 "continuation": "Numerical extinction threshold of 10⁻¹⁰; a single continuation is approximated."}
    }


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output", default="wasserstein.json")
    parser.add_argument("--seed", type=int, default=1729)
    parser.add_argument("--N", type=int, default=16)
    parser.add_argument("--beta", type=float, default=0.8)
    parser.add_argument("--T", type=float, default=24)
    parser.add_argument("--dt", type=float, default=0.08)
    parser.add_argument("--max-steps", dest="max_steps", type=int, default=30000)
    parser.add_argument("--time-sampling", dest="time_sampling", choices=["auto", "linear", "logarithmic"], default="auto")
    args = vars(parser.parse_args())
    output = args.pop("output")
    result = simulate(args)
    with open(output, "w", encoding="utf-8") as stream:
        json.dump(result, stream, separators=(",", ":"), allow_nan=False)
    print(json.dumps(result["meta"], indent=2, ensure_ascii=False))
Back to top