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
- Model
- Real RAM
- Properties
- deterministicnot exactonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 with in its goal and 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 square cells of size , groups of people with positions and velocities, a goal set of cells for each group, a discomfort field (high where people do not want to walk, infinite at obstacles), and the weights , , of the cost. A person who walks along a path from to the goal pays
the path length, the time and the discomfort along the way. With for the speed , the cost per unit length in the direction is
The potential is the cheapest cost to the goal. It satisfies in the goal and the eikonal equation elsewhere, and a person moves with the velocity , where is the direction of .
The speed comes from Section 3.2 of the paper. The density and the mean velocity come from a splat of the people (Eq. 7). The terrain speed falls from with the slope (Eq. 8), and the flow speed is , the crowd velocity a short distance ahead in the direction (Eq. 9). The speed is below a density , above , and the linear blend between them (Eq. 10). The paper calls this blend ad hoc, so it is a heuristic, and , , , , and are tuning.
The algorithm
One time step does, as in Section 4 of the paper:
- Splat. Every person adds to the four cells around it the weights , , and , where is its offset from the center of the lower left cell in cell units (Section 4.1). This gives , and the same weights on the velocities give .
- Speed and cost. For each group, for each cell and each of the four directions, compute and at the neighbor cell in that direction, the cell one moves into (Section 4.2).
- Potential. Solve the discrete eikonal equation for each group by fast marching (Section 4.3), below.
- Advection. Move every person by , with from upwind differences of (Section 4.4).
- Minimum distance. Push apart every pair of people closer than , half each way (Section 4.5).
Step 3 is the core:
FAST-MARCH(C, Γ, Δx) ▷ costs per cell and face, goal cells- 1
φ ← ∞ in every cell; φ ← 0 in Γ; push every goal cell into the heap H - 2
while H is not empty - 3
(p, M) ← pop the smallest entry; skip it if M is known or p > φ_M - 4
mark M known - 5
for each neighbor N of M that is not known - 6
u ← U_N(φ over the known neighbors of N) ▷ the upwind update - 7
if u < φ_N then φ_N ← u and push (u, N) into H - 8
return φ
The local update. For a cell with the face lengths to its neighbors , the code solves with
the upwind (Godunov) form of . It tries every choice of at most one neighbor per axis: for one neighbor, and the larger root of for two, kept only if it is at least both ; the smallest candidate is .
The rule of the paper. The paper picks, on each axis, the neighbor with the smaller and solves its Eq. 11 with . When the two faces of an axis have the same cost, this picks the neighbor with the smaller , which is also the neighbor that attains the maximum in , so the two rules agree. With different costs on the two faces they can differ. The code uses the rule of , 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 on every face, , and the goal cell , so every . Along an axis, each cell has one useful neighbor and , which is times the distance. The cell has the known neighbors and , both with ; the two term update gives , so . The cell uses on one axis and on the other, and gives . The exact cost to the goal center would be and ; the first order grid scheme overestimates diagonal distances.
The cost. With , no discomfort, m/s, and : a thin crowd gives and . At with no flow, and . In a dense crowd that moves toward the person, , and the code clamps to , so is about 1000; walking with a dense flow at 0.3 m/s gives .
A measured run. The test puts 20 people at random in the left part of a grid with m (seed 2), with the goal column , , m and s. After 40 steps (10 s) every person has m, and the closest pair over the run is 0.378 m apart, a little below 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 has exactly one solution when has a usable neighbor, and line L6 returns it.
- The update is monotone (smaller neighbors give a smaller value) and causal (a neighbor with does not change ).
- So the cells are accepted at line L4 in nondecreasing order of , 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 , 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 , and the two requirements of the splat in Section 4.1: a person adds at least to its own cell and at most 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 . For a cell and a neighbor in direction , with ; an infinite cost marks an obstacle face, and a neighbor outside the grid does not exist. The goal cells have .
The local update
For a cell and values of its neighbors, define for
where and the maximum runs over the neighbors of the axis with finite and finite (an empty maximum is 0). The discrete equation at is . It is the upwind (Godunov) form of .
Lemma 1. If has at least one usable neighbor, has exactly one solution . It satisfies for every neighbor whose term is positive at , and over the usable neighbors.
Proof. is continuous and nondecreasing, it is 0 for , 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 . At the solution at most two terms are positive and each is at most 1, so some neighbor has .
Lemma 2. The function _candidates of line L6 returns .
Proof. The code forms a candidate for every choice of at most one neighbor per axis: for one neighbor, and for two neighbors the larger root of , kept only if . Every kept candidate satisfies , because the maximum over an axis is at least the chosen term; so . Conversely, at choose on each axis a neighbor that attains the maximum, if that maximum is positive. If one axis is chosen, is a candidate. If two are chosen, solves the quadratic; the quadratic is convex with its smaller root at most the weighted mean of and , which is at most , so is the larger root and a kept candidate. So the minimum over the candidates is .
Lemma 3 (monotone and causal). If for every neighbor, then . Changing the value of a neighbor with , or adding or removing such a neighbor, does not change .
Proof. Smaller neighbor values make every term larger, so and the solution is smaller. A neighbor with contributes at , and also 0 for all , so is unchanged near and on ; the solution is the same.
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 is accepted with value , and a neighbor then gets the new tentative value over its known neighbors (line L7). If , then by Lemma 3 the term of is zero at , so equals the value of over the known neighbors without . That set has not changed since the last update of , so already had the tentative value in the heap when was popped, which contradicts the choice of . So , and every value pushed after the acceptance of is at least .
Theorem 1. When the heap is empty, every accepted cell satisfies over all its neighbors, the goal cells have , and every cell that is never accepted has and no finite path of usable faces to the goal.
Proof. When is accepted, is over the neighbors known at that time. Every neighbor accepted later has a value at least by Lemma 4, so by Lemma 3 it does not change . A neighbor that is never accepted has and is left out of . 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.
Theorem 2 (uniqueness). The system on , elsewhere, has at most one solution with values in . So fast marching and the brute force iteration of the test, which stops at a fixed point, return the same field.
Proof. Let and be two solutions, and suppose for some cell. Among such cells take one with the smallest ; it is finite and . By Lemma 3, depends only on the neighbors with , and for them by the choice of . So at every term of is at least the matching term of , and . Since is nondecreasing, , a contradiction. By symmetry .
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 for cells. So fast marching costs time and space, in the worst case.
The paper's rule
The paper picks, on each axis, the neighbor with the smaller and then solves its Eq. 11 with . When the two faces of an axis have the same cost, that neighbor is the one with the smaller , which is also the one that attains the maximum in , so the two rules agree. With different costs on the two faces they can differ; the code uses the rule of , for which Theorems 1 and 2 hold.
Complexity
Fast marching accepts each of the cells once, and each acceptance updates at most four neighbors with at most nine candidates each, plus a heap push of . So it costs time and space. The splat costs , the speed and cost fields per group, and the advection . With groups a step costs , plus the minimum distance pass, which is in the code over all pairs and 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 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 .
- 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 , 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 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.
# 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
- 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)
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag RXA6V1 Edit this page History Report an error Markdown