Algorithm Search⌘K

Algorithmadvanced

Continuum crowds

Also called continuum crowd simulation.

Steer large crowds by a dynamic potential field on a grid, solved by fast marching from the goals with a cost that depends on density and speed.

Time
O(g log g) fast_marchO(k g log g + n^2) step
Space
O(g + n) extra
Where
g = the number of grid cells; k = the number of groups; n = the number of people
Properties
deterministicnot exactonlineiterative
Origin
Adrien Treuille, Seth Cooper, Zoran Popović, 2006

Continuum crowds moves a large crowd by a field over the whole space instead of by rules for each person. The people form groups, and all people of a group share a goal. At each time step, the method spreads the people onto a grid as a density and a mean velocity. From these it gets, for every cell and direction, the speed at which a person can walk there: the free walking speed where the crowd is thin, the speed of the crowd where it is dense. A unit cost per distance combines the path length, the time and a discomfort field. Each group then gets a potential ϕ\phi with ϕ=0\phi = 0 in its goal and ∣∇ϕ∣=C|\nabla \phi| = C elsewhere, an eikonal equation solved by the fast marching method. Every person walks down the gradient of the potential of its group, at the local speed. Adrien Treuille, Seth Cooper and Zoran Popović presented the method in 2006.

In plain words

Think of a crowd in a station, where everybody of one group wants to reach the same exit. For each spot on the floor, you write down how long it takes to reach the exit from there, if you walk the best way. Where many people stand, or where the crowd moves the other way, walking is slow, so that spot counts as far away. Then each person simply steps toward the neighboring spot with the smaller number. Because you write the numbers again at every moment, people walk around a jam as soon as it forms. And people who walk against a flow find it cheaper to follow others in the same direction, so lanes appear by themselves.

The problem

The input is a 2D grid of gg square cells of size Δx\Delta x, groups of people with positions and velocities, a goal set of cells for each group, a discomfort field hh (high where people do not want to walk, infinite at obstacles), and the weights α\alpha, β\beta, γ\gamma of the cost. A person who walks along a path from xx to the goal pays

α∫ds+β∫dt+γ∫h dt,\alpha \int ds + \beta \int dt + \gamma \int h\, dt ,

the path length, the time and the discomfort along the way. With dt=ds/fdt = ds / f for the speed ff, the cost per unit length in the direction θ\theta is

C(x,θ)=αf(x,θ)+β+γ h(x)f(x,θ).C(x, \theta) = \frac{\alpha f(x, \theta) + \beta + \gamma\, h(x)}{f(x, \theta)} .

The potential ϕ\phi is the cheapest cost to the goal. It satisfies ϕ=0\phi = 0 in the goal and the eikonal equation ∣∇ϕ∣=C|\nabla \phi| = C elsewhere, and a person moves with the velocity x˙=−f(x,θ) ∇ϕ/∣∇ϕ∣\dot x = -f(x, \theta)\, \nabla \phi / |\nabla \phi|, where θ\theta is the direction of −∇ϕ-\nabla \phi.

The speed comes from Section 3.2 of the paper. The density ρ\rho and the mean velocity vˉ\bar v come from a splat of the people (Eq. 7). The terrain speed fTf_T falls from fmax⁡f_{\max} with the slope (Eq. 8), and the flow speed is fv=max⁡(0,vˉ(x+rnθ)⋅nθ)f_v = \max(0, \bar v(x + r n_\theta) \cdot n_\theta), the crowd velocity a short distance rr ahead in the direction nθn_\theta (Eq. 9). The speed is fTf_T below a density ρmin⁡\rho_{\min}, fvf_v above ρmax⁡\rho_{\max}, and the linear blend fT+ρ−ρmin⁡ρmax⁡−ρmin⁡(fv−fT)f_T + \frac{\rho - \rho_{\min}}{\rho_{\max} - \rho_{\min}} (f_v - f_T) between them (Eq. 10). The paper calls this blend ad hoc, so it is a heuristic, and α\alpha, β\beta, γ\gamma, ρmin⁡\rho_{\min}, ρmax⁡\rho_{\max} and fmax⁡f_{\max} are tuning.

The algorithm

One time step does, as in Section 4 of the paper:

  1. Splat. Every person adds to the four cells around it the weights min⁡(1−Δx,1−Δy)λ\min(1 - \Delta_x, 1 - \Delta_y)^\lambda, min⁡(Δx,1−Δy)λ\min(\Delta_x, 1 - \Delta_y)^\lambda, min⁡(Δx,Δy)λ\min(\Delta_x, \Delta_y)^\lambda and min⁡(1−Δx,Δy)λ\min(1 - \Delta_x, \Delta_y)^\lambda, where (Δx,Δy)(\Delta_x, \Delta_y) is its offset from the center of the lower left cell in cell units (Section 4.1). This gives ρ\rho, and the same weights on the velocities give vˉ\bar v.
  2. Speed and cost. For each group, for each cell MM and each of the four directions, compute ff and CC at the neighbor cell in that direction, the cell one moves into (Section 4.2).
  3. Potential. Solve the discrete eikonal equation for each group by fast marching (Section 4.3), below.
  4. Advection. Move every person by Δt x˙\Delta t\, \dot x, with x˙\dot x from upwind differences of ϕ\phi (Section 4.4).
  5. Minimum distance. Push apart every pair of people closer than dmin⁡d_{\min}, half each way (Section 4.5).

Step 3 is the core:

  1. FAST-MARCH(C, Γ, Δx) ▷ costs per cell and face, goal cells
  2. 1φ ← ∞ in every cell; φ ← 0 in Γ; push every goal cell into the heap H
  3. 2while H is not empty
  4. 3(p, M) ← pop the smallest entry; skip it if M is known or p > φ_M
  5. 4mark M known
  6. 5for each neighbor N of M that is not known
  7. 6u ← U_N(φ over the known neighbors of N) ▷ the upwind update
  8. 7if u < φ_N then φ_N ← u and push (u, N) into H
  9. 8return φ

The local update. For a cell MM with the face lengths hM→i=Δx CM→ih_{M \to i} = \Delta x\, C_{M \to i} to its neighbors ii, the code solves GM(x)=1G_M(x) = 1 with

GM(x)=∑axis(max⁡i on the axis[x−ϕi]+hM→i)2,G_M(x) = \sum_{\text{axis}} \Big( \max_{i \text{ on the axis}} \frac{[x - \phi_i]^+}{h_{M \to i}} \Big)^2 ,

the upwind (Godunov) form of ∣∇ϕ∣=C|\nabla\phi| = C. It tries every choice of at most one neighbor per axis: ϕi+hi\phi_i + h_i for one neighbor, and the larger root of ∑((x−ϕi)/hi)2=1\sum ((x - \phi_i) / h_i)^2 = 1 for two, kept only if it is at least both ϕi\phi_i; the smallest candidate is UMU_M.

The rule of the paper. The paper picks, on each axis, the neighbor with the smaller ϕi+CM→i\phi_i + C_{M \to i} and solves its Eq. 11 with Δx=1\Delta x = 1. When the two faces of an axis have the same cost, this picks the neighbor with the smaller ϕi\phi_i, which is also the neighbor that attains the maximum in GMG_M, so the two rules agree. With different costs on the two faces they can differ. The code uses the rule of GMG_M, because the proofs below hold for it.

The code steps one group; with several groups, the density is shared, and each group has its own goal, cost and potential.

Example

By hand. Take a constant cost C=2C = 2 on every face, Δx=0.5\Delta x = 0.5, and the goal cell (0,0)(0, 0), so every h=1h = 1. Along an axis, each cell has one useful neighbor and ϕ=1,2,3,…\phi = 1, 2, 3, \dots, which is CC times the distance. The cell (1,1)(1, 1) has the known neighbors (1,0)(1, 0) and (0,1)(0, 1), both with ϕ=1\phi = 1; the two term update gives 2(x−1)2=12 (x - 1)^2 = 1, so ϕ11=1+0.5=1.7071\phi_{11} = 1 + \sqrt{0.5} = 1.7071. The cell (1,2)(1, 2) uses ϕ02=2\phi_{02} = 2 on one axis and ϕ11=1.7071\phi_{11} = 1.7071 on the other, and (x−2)2+(x−1.7071)2=1(x - 2)^2 + (x - 1.7071)^2 = 1 gives ϕ12=2.5453\phi_{12} = 2.5453. The exact cost to the goal center would be 2⋅0.52=1.41422 \cdot 0.5 \sqrt 2 = 1.4142 and 2⋅0.55=2.23612 \cdot 0.5 \sqrt 5 = 2.2361; the first order grid scheme overestimates diagonal distances.

The cost. With α=β=γ=1\alpha = \beta = \gamma = 1, no discomfort, fmax⁡=1.4f_{\max} = 1.4 m/s, ρmin⁡=0.6\rho_{\min} = 0.6 and ρmax⁡=1.6\rho_{\max} = 1.6: a thin crowd gives f=1.4f = 1.4 and C=2.4/1.4=1.71C = 2.4 / 1.4 = 1.71. At ρ=1.1\rho = 1.1 with no flow, f=0.7f = 0.7 and C=1.7/0.7=2.43C = 1.7 / 0.7 = 2.43. In a dense crowd that moves toward the person, fv=0f_v = 0, and the code clamps ff to 10−310^{-3}, so CC is about 1000; walking with a dense flow at 0.3 m/s gives C=1.3/0.3=4.33C = 1.3 / 0.3 = 4.33.

A measured run. The test puts 20 people at random in the left part of a 16×1616 \times 16 grid with Δx=1\Delta x = 1 m (seed 2), with the goal column x∈[15,16)x \in [15, 16), λ=2\lambda = 2, dmin⁡=0.4d_{\min} = 0.4 m and Δt=0.25\Delta t = 0.25 s. After 40 steps (10 s) every person has x≥14.9x \ge 14.9 m, and the closest pair over the run is 0.378 m apart, a little below dmin⁡d_{\min} because one pass of pushes does not fix all pairs. These are measurements of one toy.

Correctness

The proof file shows, in exact arithmetic, that fast marching solves the discrete equation of the code.

  • The equation GM(x)=1G_M(x) = 1 has exactly one solution UMU_M when MM has a usable neighbor, and line L6 returns it.
  • The update is monotone (smaller neighbors give a smaller value) and causal (a neighbor with ϕi≥UM\phi_i \ge U_M does not change UMU_M).
  • So the cells are accepted at line L4 in nondecreasing order of ϕ\phi, and at the end every reached cell satisfies its equation over all its neighbors, while the cells that are never reached have no finite path to the goal (Theorem 1).
  • The discrete system has only one solution, so fast marching and the brute force iteration of the test give the same field (Theorem 2).

It also follows from the update that every reached cell outside the goal has a neighbor with a smaller ϕ\phi, so the potential has no local minima: a person who walks downhill always reaches the goal.

The tests check the equality with the brute force iteration on random anisotropic grids with obstacles, the order of acceptance, the values of the hand example along the axes and at (1,1)(1, 1), and the two requirements of the splat in Section 4.1: a person adds at least 2−λ2^{-\lambda} to its own cell and at most 2−λ2^{-\lambda} to every other cell, and the density changes continuously with the position.

What is not proved: that the discrete potential is close to the continuous one, that people never overlap, and that the crowd looks right. The speed blend is a heuristic, the constants are tuning, and the lanes and the flows around obstacles are observations in the paper.

Proof: Fast marching returns the unique solution of the discrete upwind eikonal equation of continuum crowdsfull

We use the notation of the page. The arithmetic is exact. The grid has square cells of size Δx\Delta x. For a cell MM and a neighbor ii in direction θ\theta, hM→i=Δx CM→ih_{M \to i} = \Delta x\, C_{M \to i} with 0<CM→i≤∞0 < C_{M \to i} \le \infty; an infinite cost marks an obstacle face, and a neighbor outside the grid does not exist. The goal cells Γ\Gamma have ϕ=0\phi = 0.

The local update

For a cell MM and values ϕ\phi of its neighbors, define for x∈Rx \in \mathbb{R}

GM(x)=∑axis a∈{x,y}(max⁡i∈a[ x−ϕi ]+/hM→i)2,G_M(x) = \sum_{\text{axis } a \in \{x, y\}} \Big( \max_{i \in a} \big[\, x - \phi_i \,\big]^+ / h_{M \to i} \Big)^2,

where [z]+=max⁡(z,0)[z]^+ = \max(z, 0) and the maximum runs over the neighbors of the axis with finite ϕi\phi_i and finite hM→ih_{M \to i} (an empty maximum is 0). The discrete equation at M∉ΓM \notin \Gamma is GM(ϕM)=1G_M(\phi_M) = 1. It is the upwind (Godunov) form of ∣∇ϕ∣=C|\nabla\phi| = C.

Lemma 1. If MM has at least one usable neighbor, GM(x)=1G_M(x) = 1 has exactly one solution UM(ϕ)U_M(\phi). It satisfies UM(ϕ)>ϕiU_M(\phi) > \phi_i for every neighbor whose term is positive at UM(ϕ)U_M(\phi), and UM(ϕ)≥min⁡i(ϕi+hM→i/2)U_M(\phi) \ge \min_i (\phi_i + h_{M \to i}/\sqrt 2) over the usable neighbors.

Proof. GMG_M is continuous and nondecreasing, it is 0 for x≤min⁡iϕix \le \min_i \phi_i, it is strictly increasing where it is positive, and it tends to infinity. So it takes the value 1 exactly once. A term is positive only if x>ϕix > \phi_i. At the solution at most two terms are positive and each is at most 1, so some neighbor has (UM−ϕi)/hM→i≥1/2(U_M - \phi_i)/h_{M \to i} \ge 1/\sqrt 2. □\square

Lemma 2. The function _candidates of line L6 returns UM(ϕ)U_M(\phi).

Proof. The code forms a candidate for every choice of at most one neighbor per axis: ϕi+hi\phi_i + h_i for one neighbor, and for two neighbors the larger root rr of ∑((r−ϕi)/hi)2=1\sum ((r - \phi_i)/h_i)^2 = 1, kept only if r≥max⁡(ϕ1,ϕ2)r \ge \max(\phi_1, \phi_2). Every kept candidate rr satisfies GM(r)≥1G_M(r) \ge 1, because the maximum over an axis is at least the chosen term; so r≥UMr \ge U_M. Conversely, at x=UMx = U_M choose on each axis a neighbor that attains the maximum, if that maximum is positive. If one axis is chosen, UM=ϕi+hiU_M = \phi_i + h_i is a candidate. If two are chosen, UM≥max⁡(ϕ1,ϕ2)U_M \ge \max(\phi_1, \phi_2) solves the quadratic; the quadratic is convex with its smaller root at most the weighted mean of ϕ1\phi_1 and ϕ2\phi_2, which is at most max⁡(ϕ1,ϕ2)\max(\phi_1, \phi_2), so UMU_M is the larger root and a kept candidate. So the minimum over the candidates is UMU_M. □\square

Lemma 3 (monotone and causal). If ϕi≤ψi\phi_i \le \psi_i for every neighbor, then UM(ϕ)≤UM(ψ)U_M(\phi) \le U_M(\psi). Changing the value of a neighbor ii with ϕi≥UM(ϕ)\phi_i \ge U_M(\phi), or adding or removing such a neighbor, does not change UM(ϕ)U_M(\phi).

Proof. Smaller neighbor values make every term larger, so Gϕ≥GψG_\phi \ge G_\psi and the solution is smaller. A neighbor with ϕi≥UM\phi_i \ge U_M contributes [UM−ϕi]+=0[U_M - \phi_i]^+ = 0 at UMU_M, and also 0 for all x≤ϕix \le \phi_i, so GMG_M is unchanged near UMU_M and on (−∞,UM](-\infty, U_M]; the solution is the same. □\square

Fast marching

Lemma 4. The cells are accepted (line L4) in nondecreasing order of their values.

Proof. The heap pops the smallest tentative value (line L3). Suppose cell AA is accepted with value vv, and a neighbor BB then gets the new tentative value u=UBu = U_B over its known neighbors (line L7). If u<vu < v, then by Lemma 3 the term of AA is zero at uu, so uu equals the value of UBU_B over the known neighbors without AA. That set has not changed since the last update of BB, so BB already had the tentative value u<vu < v in the heap when AA was popped, which contradicts the choice of AA. So u≥vu \ge v, and every value pushed after the acceptance of AA is at least vv. □\square

Theorem 1. When the heap is empty, every accepted cell M∉ΓM \notin \Gamma satisfies ϕM=UM(ϕ)\phi_M = U_M(\phi) over all its neighbors, the goal cells have ϕ=0\phi = 0, and every cell that is never accepted has ϕ=∞\phi = \infty and no finite path of usable faces to the goal.

Proof. When MM is accepted, ϕM\phi_M is UMU_M over the neighbors known at that time. Every neighbor accepted later has a value at least ϕM\phi_M by Lemma 4, so by Lemma 3 it does not change UMU_M. A neighbor that is never accepted has ϕ=∞\phi = \infty and is left out of GMG_M. If a cell is next to an accepted cell through a usable face, it gets a finite tentative value and is accepted later; so the accepted cells contain every cell that a chain of usable faces joins to the goal. ■\blacksquare

Theorem 2 (uniqueness). The system ϕ=0\phi = 0 on Γ\Gamma, ϕM=UM(ϕ)\phi_M = U_M(\phi) elsewhere, has at most one solution with values in [0,∞][0, \infty]. So fast marching and the brute force iteration of the test, which stops at a fixed point, return the same field.

Proof. Let ϕ\phi and ψ\psi be two solutions, and suppose ϕM>ψM\phi_M > \psi_M for some cell. Among such cells take one with the smallest ψM\psi_M; it is finite and M∉ΓM \notin \Gamma. By Lemma 3, ψM\psi_M depends only on the neighbors with ψi<ψM\psi_i < \psi_M, and for them ϕi≤ψi\phi_i \le \psi_i by the choice of MM. So at x=ψMx = \psi_M every term of GϕG_\phi is at least the matching term of GψG_\psi, and Gϕ(ψM)≥Gψ(ψM)=1G_\phi(\psi_M) \ge G_\psi(\psi_M) = 1. Since GϕG_\phi is nondecreasing, ϕM=UM(ϕ)≤ψM\phi_M = U_M(\phi) \le \psi_M, a contradiction. By symmetry ϕ=ψ\phi = \psi. ■\blacksquare

Cost

Each cell is accepted once, and each acceptance updates at most four neighbors. Each update tries at most nine candidates, and each push costs O(log⁡g)O(\log g) for gg cells. So fast marching costs O(glog⁡g)O(g \log g) time and O(g)O(g) space, in the worst case.

The paper's rule

The paper picks, on each axis, the neighbor with the smaller ϕi+CM→i\phi_i + C_{M \to i} and then solves its Eq. 11 with Δx=1\Delta x = 1. When the two faces of an axis have the same cost, that neighbor is the one with the smaller ϕi\phi_i, which is also the one that attains the maximum in GMG_M, so the two rules agree. With different costs on the two faces they can differ; the code uses the rule of GMG_M, for which Theorems 1 and 2 hold.

Complexity

Fast marching accepts each of the gg cells once, and each acceptance updates at most four neighbors with at most nine candidates each, plus a heap push of O(log⁡g)O(\log g). So it costs O(glog⁡g)O(g \log g) time and O(g)O(g) space. The splat costs O(n+g)O(n + g), the speed and cost fields O(g)O(g) per group, and the advection O(n)O(n). With kk groups a step costs O(kglog⁡g+n)O(k g \log g + n), plus the minimum distance pass, which is O(n2)O(n^2) in the code over all pairs and O(n)O(n) expected with a uniform grid at bounded density. The planning cost depends on the grid and the number of groups, not on the number of people, which is what makes large crowds cheap.

Properties

  • Global planning. The potential sees the whole space, so people walk around jams and obstacles far ahead, not only around their neighbors.
  • No local minima. In the discrete field every reached cell has a lower neighbor (proved above).
  • Dynamic. The field is solved again at every step, so it reacts to the moving crowd.
  • Group based. All people of a group follow one field; the cost grows with the number of groups.
  • Not exact. The grid scheme is first order and overestimates diagonal costs, the advection is explicit Euler, and the minimum distance pass leaves small overlaps.
  • Deterministic. The same input gives the same crowd.

Variants and improvements

  • Fast sweeping. Gauss Seidel sweeps in alternating orders solve the same discrete equation in O(g)O(g) per sweep; the paper chose fast marching instead.
  • Dijkstra. Dijkstra's algorithm on the grid graph solves a similar problem in the same time, but its paths move only along the axes, so diagonal distances are too large by up to a factor 2\sqrt 2.
  • Local avoidance. Add reciprocal velocity obstacles or ORCA for the near range, where the grid is too coarse to keep people apart.
  • Incompressible crowds. Later work treats a very dense crowd as a fluid with a limit on the density, solved on the grid, so that the density cannot exceed a maximum.
  • Forces. The social force model moves each person by forces toward a straight line goal; it has no global planning but handles contacts and pushing.

When to use it

Use continuum crowds for large, dense crowds with a few shared goals, such as evacuations, stadiums or streets, where people must route around jams and form lanes. It is a poor fit when every person has its own goal, because each goal needs its own potential, and when close contact or the shape of a single path matters, where agent methods such as boids, ORCA or the social force model are simpler.

Pitfalls

  • The face rule. The paper's argmin rule and the upwind max rule differ when the two faces of an axis have different costs; the proofs above hold for the max rule.
  • Zero speed. In a dense counter flow fv=0f_v = 0, and the cost is infinite; clamp the speed to a small positive value, or the field breaks at such cells.
  • Grid size. Cells much larger than a person blur the density, and cells much smaller give a noisy field; the splat exponent λ\lambda sets how sharp each person is.
  • Overlaps. One pass of pushes does not separate all pairs, as the measured run shows; use more passes or a local avoidance method if overlap matters.
  • Discretization error. The first order scheme overestimates diagonal costs, by about 21 percent at the diagonal neighbor of the goal in the hand example; a finer grid reduces it.
  • Cost per step. A full fast marching per group per step is the main cost; with many goals, group people or update the fields less often.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

continuum_crowds.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/continuum-crowds/. The authors are listed in prov/RXA6V1.jsonl.
"""Continuum crowds (Treuille, Cooper and Popovic 2006) on a small 2D grid.

The grid has nx by ny square cells of size dx. Scalar fields are lists of
rows indexed [i][j], with i the x index and j the y index; cell (i, j) has
its center at ((i + 1/2) dx, (j + 1/2) dx). Anisotropic fields (speed f and
unit cost C) have one value per cell and direction, in the order
E, N, W, S (theta = 0, 90, 180 and 270 degrees).

One time step for one group:
  1. splat the people into the density rho and the mean velocity vbar;
  2. compute the speed f and the unit cost C = (alpha f + beta + gamma g) / f
     for every cell and direction, evaluated at the cell one moves into;
  3. solve the discrete eikonal equation |grad phi| = C with phi = 0 in the
     goal by fast marching;
  4. move every person with x' = -f grad(phi) / |grad(phi)|;
  5. push apart pairs closer than a minimum distance.

The local update of step 3 is the upwind form: for each axis the active
neighbor is the one with the largest (phi_M - phi_i) / (dx C_M->i), and
phi_M solves sum over the active axes of ((phi_M - phi_i) / (dx C_M->i))^2
= 1. When the two faces of an axis have the same cost this is the rule of
the paper (the neighbor with the smaller phi_i + C_M->i). solve_brute
iterates the same update over all cells until no value changes; it is the
reference that the fast marching result must equal.
"""

import heapq
import math

INF = float("inf")
DIRS = ((1, 0), (0, 1), (-1, 0), (0, -1))  # E, N, W, S
OPP = (2, 3, 0, 1)


def grid(nx, ny, value=0.0):
    return [[value] * ny for _ in range(nx)]


def _candidates(xs, ys):
    """xs, ys: lists of (phi_i, h_i) for the two neighbors of each axis, with
    h_i = dx C_M->i. Return the upwind solution phi_M (INF if none)."""
    best = INF
    for a in xs + [None]:
        for b in ys + [None]:
            terms = [t for t in (a, b) if t is not None and t[0] < INF and t[1] < INF]
            if len(terms) == 1:
                p, h = terms[0]
                best = min(best, p + h)
            elif len(terms) == 2:
                (p1, h1), (p2, h2) = terms
                w1, w2 = 1.0 / (h1 * h1), 1.0 / (h2 * h2)
                qa = w1 + w2
                qb = -2.0 * (p1 * w1 + p2 * w2)
                qc = p1 * p1 * w1 + p2 * p2 * w2 - 1.0
                disc = qb * qb - 4.0 * qa * qc
                if disc >= 0.0:
                    r = (-qb + math.sqrt(disc)) / (2.0 * qa)
                    if r >= max(p1, p2):
                        best = min(best, r)
    return best


def local_update(phi, cost, i, j, dx, known=None):
    """The upwind update of cell (i, j) from its four neighbors.

    cost[i][j][d] is C_M->neighbor d. Neighbors outside the grid, with an
    infinite cost, or not in `known` (when given) are left out.
    """
    nx, ny = len(phi), len(phi[0])
    axis = ([], [])
    for d, (di, dj) in enumerate(DIRS):
        a, b = i + di, j + dj
        if 0 <= a < nx and 0 <= b < ny and (known is None or known[a][b]):
            h = dx * cost[i][j][d]
            axis[d % 2].append((phi[a][b], h))
    return _candidates(axis[0], axis[1])  # @line L6


def fast_march(cost, goal, dx):
    """Return (phi, order): the potential and the order of acceptance.

    cost[i][j][d] = C_M->d (INF for an obstacle face), goal: list of cells.
    """
    nx, ny = len(cost), len(cost[0])
    phi = grid(nx, ny, INF)
    known = grid(nx, ny, False)
    heap = []
    for (i, j) in goal:
        phi[i][j] = 0.0  # @line L1
        heapq.heappush(heap, (0.0, i, j))
    order = []
    while heap:  # @line L2
        p, i, j = heapq.heappop(heap)  # @line L3
        if known[i][j] or p > phi[i][j]:
            continue
        known[i][j] = True  # @line L4
        order.append((i, j))
        for di, dj in DIRS:  # @line L5
            a, b = i + di, j + dj
            if 0 <= a < nx and 0 <= b < ny and not known[a][b]:
                v = local_update(phi, cost, a, b, dx, known)
                if v < phi[a][b]:
                    phi[a][b] = v  # @line L7
                    heapq.heappush(heap, (v, a, b))
    return phi, order  # @line L8


def solve_brute(cost, goal, dx, max_sweeps=100000):
    """Iterate the local update over all cells (Jacobi) until no change."""
    nx, ny = len(cost), len(cost[0])
    goals = set(goal)
    phi = grid(nx, ny, INF)
    for (i, j) in goal:
        phi[i][j] = 0.0
    for _ in range(max_sweeps):
        new = [row[:] for row in phi]
        changed = False
        for i in range(nx):
            for j in range(ny):
                if (i, j) in goals:
                    continue
                v = local_update(phi, cost, i, j, dx)
                if v != phi[i][j]:
                    new[i][j] = v
                    changed = True
        phi = new
        if not changed:
            return phi
    raise RuntimeError("no convergence")


def splat(people, nx, ny, dx, lam):
    """Density rho and mean velocity vbar (Section 4.1 of the paper).

    people: list of ((x, y), (vx, vy)). Each person adds
    min(1 - Dx, 1 - Dy)^lam, min(Dx, 1 - Dy)^lam, min(Dx, Dy)^lam and
    min(1 - Dx, Dy)^lam to the cells A, B, C and D around it, where
    (Dx, Dy) is its offset from the center of A in cell units.
    """
    rho = grid(nx, ny)
    mvx, mvy = grid(nx, ny), grid(nx, ny)
    for (px, py), (vx, vy) in people:
        u, v = px / dx - 0.5, py / dx - 0.5
        i, j = math.floor(u), math.floor(v)
        ddx, ddy = u - i, v - j
        for (a, b, w) in (
            (i, j, min(1 - ddx, 1 - ddy) ** lam),
            (i + 1, j, min(ddx, 1 - ddy) ** lam),
            (i + 1, j + 1, min(ddx, ddy) ** lam),
            (i, j + 1, min(1 - ddx, ddy) ** lam),
        ):
            if 0 <= a < nx and 0 <= b < ny:
                rho[a][b] += w
                mvx[a][b] += w * vx
                mvy[a][b] += w * vy
    vbar = [[(mvx[i][j] / rho[i][j], mvy[i][j] / rho[i][j]) if rho[i][j] > 0 else (0.0, 0.0)
             for j in range(ny)] for i in range(nx)]
    return rho, vbar


def speed_and_cost(rho, vbar, disc, params):
    """Speed f (Eq. 10, flat terrain so f_T = f_max) and unit cost C (Eq. 4),
    both evaluated at the neighbor cell in each direction."""
    fmax, fmin_flow = params["fmax"], params.get("fmin", 1e-3)
    rmin, rmax = params["rho_min"], params["rho_max"]
    al, be, ga = params["alpha"], params["beta"], params["gamma"]
    nx, ny = len(rho), len(rho[0])
    f = [[[0.0] * 4 for _ in range(ny)] for _ in range(nx)]
    C = [[[INF] * 4 for _ in range(ny)] for _ in range(nx)]
    for i in range(nx):
        for j in range(ny):
            for d, (di, dj) in enumerate(DIRS):
                a, b = i + di, j + dj
                if not (0 <= a < nx and 0 <= b < ny) or disc[a][b] == INF:
                    continue
                ft = fmax
                fv = max(0.0, vbar[a][b][0] * di + vbar[a][b][1] * dj)
                r = rho[a][b]
                if r <= rmin:
                    s = ft
                elif r >= rmax:
                    s = fv
                else:
                    s = ft + (r - rmin) / (rmax - rmin) * (fv - ft)
                s = max(s, fmin_flow)
                f[i][j][d] = s
                C[i][j][d] = (al * s + be + ga * disc[a][b]) / s
    return f, C


def velocity_field(phi, f, dx):
    """v = -f grad(phi) / |grad(phi)| with upwind one sided differences."""
    nx, ny = len(phi), len(phi[0])
    vel = grid(nx, ny, (0.0, 0.0))
    for i in range(nx):
        for j in range(ny):
            if phi[i][j] == INF:
                continue
            comp = []
            for axis in (0, 1):
                best, bd = 0.0, None
                for d in (axis, axis + 2):
                    di, dj = DIRS[d]
                    a, b = i + di, j + dj
                    if 0 <= a < nx and 0 <= b < ny and phi[a][b] < phi[i][j]:
                        drop = phi[i][j] - phi[a][b]
                        if drop > best:
                            best, bd = drop, d
                comp.append((best / dx, bd))
            g = math.hypot(comp[0][0], comp[1][0])
            if g == 0.0:
                continue
            v = [0.0, 0.0]
            for axis in (0, 1):
                mag, d = comp[axis]
                if d is not None:
                    di, dj = DIRS[d]
                    v[axis] = f[i][j][d] * mag / g * (di + dj)
            vel[i][j] = (v[0], v[1])
    return vel


def enforce_min_distance(pos, dmin):
    """Push apart every pair closer than dmin, half each (one pass)."""
    n = len(pos)
    pos = [list(p) for p in pos]
    for a in range(n):
        for b in range(a + 1, n):
            dx_, dy_ = pos[b][0] - pos[a][0], pos[b][1] - pos[a][1]
            d = math.hypot(dx_, dy_)
            if 0.0 < d < dmin:
                push = 0.5 * (dmin - d) / d
                pos[a][0] -= push * dx_
                pos[a][1] -= push * dy_
                pos[b][0] += push * dx_
                pos[b][1] += push * dy_
    return [tuple(p) for p in pos]


def step(people, goal, nx, ny, dx, dt, params, disc=None):
    """One time step for one group. Return (new people, phi)."""
    if disc is None:
        disc = grid(nx, ny)
    rho, vbar = splat(people, nx, ny, dx, params["lam"])
    f, C = speed_and_cost(rho, vbar, disc, params)
    phi, _ = fast_march(C, goal, dx)
    vel = velocity_field(phi, f, dx)
    pos = []
    vels = []
    for (px, py), _ in people:
        i = min(nx - 1, max(0, int(px / dx)))
        j = min(ny - 1, max(0, int(py / dx)))
        vx, vy = vel[i][j]
        pos.append((min(nx * dx - 1e-9, max(1e-9, px + dt * vx)),
                    min(ny * dx - 1e-9, max(1e-9, py + dt * vy))))
        vels.append((vx, vy))
    pos = enforce_min_distance(pos, params["dmin"])
    return list(zip(pos, vels)), phi


def sample(phi, p, dx):
    nx, ny = len(phi), len(phi[0])
    i = min(nx - 1, max(0, int(p[0] / dx)))
    j = min(ny - 1, max(0, int(p[1] / dx)))
    return phi[i][j]
test_continuum_crowds.py 110 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/continuum-crowds/. The authors are listed in prov/RXA6V1.jsonl.
"""Tests of continuum crowds.

The fast marching potential must equal a brute force fixed point iteration
of the same discrete eikonal update on small random anisotropic grids with
obstacles. Constant costs give exact distances along the axes. The density
splat satisfies the two requirements of Section 4.1. The crowd run is a
measurement of the toy: every person reaches the goal and the minimum
distance between people is reported, not guaranteed.
"""

import math
import random

import continuum_crowds as c


def random_costs(rng, nx, ny, holes):
    C = [[[rng.uniform(0.5, 3.0) for _ in range(4)] for _ in range(ny)] for _ in range(nx)]
    for _ in range(holes):
        i, j = rng.randrange(nx), rng.randrange(ny)
        C[i][j] = [c.INF] * 4
    return C


def test_fast_marching_equals_brute_force():
    rng = random.Random(7)
    for trial in range(6):
        nx, ny = rng.randint(4, 12), rng.randint(4, 12)
        C = random_costs(rng, nx, ny, nx * ny // 10)
        goal = [(rng.randrange(nx), rng.randrange(ny)) for _ in range(rng.randint(1, 3))]
        dx = rng.choice([0.25, 1.0])
        phi, _ = c.fast_march(C, goal, dx)
        ref = c.solve_brute(C, goal, dx)
        for i in range(nx):
            for j in range(ny):
                a, b = phi[i][j], ref[i][j]
                if a == c.INF or b == c.INF:
                    assert a == b
                else:
                    assert abs(a - b) <= 1e-9 * max(1.0, b)


def test_fast_marching_is_a_fixed_point_and_in_order():
    rng = random.Random(11)
    C = random_costs(rng, 10, 10, 8)
    goal = [(0, 0)]
    phi, order = c.fast_march(C, goal, 1.0)
    vals = [phi[i][j] for i, j in order]
    assert all(b >= a for a, b in zip(vals, vals[1:]))
    for i in range(10):
        for j in range(10):
            if (i, j) in goal or phi[i][j] == c.INF:
                continue
            assert abs(c.local_update(phi, C, i, j, 1.0) - phi[i][j]) < 1e-12


def test_constant_cost_gives_axis_distance():
    n, dx = 9, 0.5
    C = [[[2.0] * 4 for _ in range(n)] for _ in range(n)]
    phi, _ = c.fast_march(C, [(0, 0)], dx)
    for k in range(n):
        assert abs(phi[k][0] - 2.0 * k * dx) < 1e-12
        assert abs(phi[0][k] - 2.0 * k * dx) < 1e-12
    # the diagonal neighbor of the goal: two terms, each (phi - 1) / 1
    assert abs(phi[1][1] - (1.0 + math.sqrt(0.5))) < 1e-12
    # the potential grows with the distance and is symmetric
    for i in range(n):
        for j in range(n):
            assert abs(phi[i][j] - phi[j][i]) < 1e-12


def test_splat_requirements():
    rng = random.Random(3)
    lam = 2.0
    bar = 0.5 ** lam
    nx = ny = 8
    for _ in range(300):
        x, y = rng.uniform(1.0, 7.0), rng.uniform(1.0, 7.0)
        rho, vbar = c.splat([((x, y), (0.3, -0.2))], nx, ny, 1.0, lam)
        own = (int(x), int(y))
        for i in range(nx):
            for j in range(ny):
                if (i, j) == own:
                    assert rho[i][j] >= bar - 1e-12
                else:
                    assert rho[i][j] <= bar + 1e-12
                if rho[i][j] > 0:
                    assert abs(vbar[i][j][0] - 0.3) < 1e-12
        # continuity: a small move gives a small change
        rho2, _ = c.splat([((x + 1e-7, y), (0.0, 0.0))], nx, ny, 1.0, lam)
        assert max(abs(rho[i][j] - rho2[i][j]) for i in range(nx) for j in range(ny)) < 1e-5


def test_measured_crowd_reaches_goal():
    rng = random.Random(2)
    n, dx = 16, 1.0
    params = dict(fmax=1.4, rho_min=0.6, rho_max=1.6, alpha=1.0, beta=1.0,
                  gamma=1.0, lam=2.0, dmin=0.4)
    people = [((rng.uniform(1, 4), rng.uniform(1, 15)), (0.0, 0.0)) for _ in range(20)]
    goal = [(n - 1, j) for j in range(n)]
    closest = math.inf
    for _ in range(40):
        people, phi = c.step(people, goal, n, n, dx, 0.25, params)
        pos = [p for p, _ in people]
        closest = min(closest, min(math.dist(a, b) for k, a in enumerate(pos) for b in pos[k + 1:]))
    assert all(p[0] >= n - 1 - 0.1 for p in pos)
    # measured on this seed: the closest pair is about 0.38 m with dmin = 0.4 m
    assert 0.3 < closest <= 0.4 + 1e-9

History

Adrien Treuille, Seth Cooper and Zoran Popović presented continuum crowds at SIGGRAPH 2006. They took the idea of a potential field over the space from robot motion planning and from models of pedestrians as a continuum, and solved its eikonal equation with the Dijkstra like method of Tsitsiklis (1995), which Sethian (1996) had made known as fast marching. Earlier crowd methods in graphics were agent based, from boids (1987) to the social force model (1995); continuum crowds showed that one field per group could plan for a whole large crowd at once.

References

  1. Adrien Treuille, Seth Cooper and Zoran Popović, Continuum crowds, ACM Transactions on Graphics 25(3) (SIGGRAPH 2006), 1160-1168, Section 3 (the unit cost and the potential), Section 3.2 (Eq. 7 to Eq. 10, density, terrain speed, flow speed and their blend), Section 4.1 (the density splat), Section 4.2 (the costs at the cell one moves into), Section 4.3 (fast marching and Eq. 11), Section 4.4 (the advection) and Section 4.5 (the minimum distance)
  2. John N. Tsitsiklis, Efficient algorithms for globally optimal trajectories, IEEE Transactions on Automatic Control 40(9), 1528-1538, 1995, the Dijkstra like method for the discrete eikonal equation that the paper follows
  3. James A. Sethian, A fast marching level set method for monotonically advancing fronts, Proceedings of the National Academy of Sciences 93(4), 1591-1595, 1996, the fast marching method with the upwind update and a heap

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.fast_march
  • a full proof of time.step
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example