Algorithm Search⌘K

Algorithmadvanced

Optimal reciprocal collision avoidance

Also called ORCA.

Each robot turns every neighbor into one half-plane of allowed velocities, takes half of the needed change, and solves a small linear program for the velocity closest to its goal.

Time
O(k) expected_with_random_orderO(k^2) per_robot_stepO(r k^2) per_team_step
Space
O(k) extra
Where
k = the number of sensed neighbors per robot; r = the number of robots
Properties
deterministiconlinenot randomized
Origin
Jur van den Berg, Stephen J. Guy, Ming C. Lin, Dinesh Manocha, 2011

Optimal reciprocal collision avoidance (ORCA) gives each robot a set of safe velocities that is an intersection of half-planes, one for each neighbor, and picks the safe velocity closest to the one it wants. Each half-plane asks the robot to make half of the smallest velocity change that avoids a collision within a time horizon τ\tau, trusting the neighbor to make the other half. Unlike reciprocal velocity obstacles, which score sampled velocities against cones and have no guarantee, ORCA solves a 2D linear program and proves that no two robots collide when every program is feasible. Unlike the plain velocity obstacle, it assumes the other robots react.

In plain words

Two robots are about to bump into each other. Each robot works out the smallest change in speed and direction that would make the pair miss, and then makes just half of it, because it knows the other robot will make the other half. This gives each robot a straight line in the space of velocities: on one side the velocities are safe, on the other they are not.

A robot with many neighbors gets one such line per neighbor. It then looks for the velocity on the safe side of all lines that is closest to the velocity it wants. If the lines leave no room, it picks the velocity that breaks the lines the least. No messages are needed, because each robot sees the others and both robots of a pair compute the same line.

The problem

The model. There are rr robots in the plane. Each robot is a disc with a radius in meters, a position, a velocity in meters per second, a top speed and a preferred velocity toward its goal. The robots are holonomic and reach a new velocity at once. Each robot senses the positions and velocities of the robots within a sensing range, and sends no messages; the sensing graph is the disc graph of that range. Time runs in synchronous steps of Δt\Delta t seconds: every robot computes its new velocity from the same snapshot, then all robots move. The horizon τ\tau, in seconds, says how far ahead collisions count.

Input. For one robot AA: its state, its preferred velocity, the states of its sensed neighbors, τ\tau and Δt\Delta t.

Output. A new velocity for AA, and a flag that tells whether the linear program was feasible.

How it differs from close pages. The velocity obstacle treats the other robot as passive, so two robots that both use it oscillate. Reciprocal velocity obstacles share the avoidance, but keep the non-convex cone, so they need sampling and can fail when two robots pick opposite sides. ORCA keeps only one half-plane per pair; the half-planes of the two robots fit together by construction, which removes the side problem and turns the choice into a linear program solved by Seidel's method. The dynamic window approach handles one robot with acceleration limits among static obstacles.

The algorithm

For robots AA and BB, with p=pB−pAp = p_B - p_A and R=rA+rBR = r_A + r_B, the truncated velocity obstacle VOA∣BτVO^\tau_{A|B} is the set of relative velocities ww for which the discs overlap at some time in (0,τ](0, \tau]. It is a cone with its tip cut off by a circle of center p/τp / \tau and radius R/τR / \tau, and it is open and convex. Let uu be the vector from the relative velocity vA−vBv_A - v_B to the nearest point of the boundary of VOA∣BτVO^\tau_{A|B}, and let nn be the outward normal there.

  1. ORCA-STEP(robots, tau, dt)
  2. 1for each robot A, in parallel on the same snapshot, do
  3. 2N ← the robots that A senses
  4. 3for each B in N do build the half-plane ORCA_A|B:
  5. 4u ← the nearest boundary point of VO^tau_A|B minus (v_A − v_B); n ← the outward normal there
  6. 5ORCA_A|B ← { v : (v − (v_A + u / 2)) · n ≥ 0 }
  7. 6v_new ← the v closest to v_pref with |v| ≤ v_max inside every ORCA_A|B, by an incremental 2D LP:
  8. 7for each half-plane, in order: if the current optimum is outside it then
  9. 8solve the 1D problem on its boundary line, cut by the speed disc and the earlier half-planes
  10. 9if some 1D problem is empty then
  11. 10v_new ← the v with |v| ≤ v_max that minimizes the largest distance to a violated half-plane (a 3D LP)
  12. 11return v_new and whether the LP was feasible
  13. 12every robot sets its new velocity and moves p ← p + v dt

Line L4 tests whether the nearest boundary point lies on the cut-off circle or on one of the two legs, and projects onto that part. Line L5 puts the boundary through vA+12uv_A + \frac12 u: robot AA makes half of the change uu, and robot BB computes the mirror half-plane with −u-u and −n-n. If two robots already overlap, the code uses Δt\Delta t in place of τ\tau, so that they push apart within one step. Lines L6 to L8 are the incremental method of the linear programming page: when a new half-plane cuts off the current optimum, the new optimum lies on its boundary line, where the problem is one interval. Line L10 is the fallback for crowded scenes.

The code follows the structure of the RVO2 library of the authors. It takes the current velocity as the reference velocity voptv^{opt} of the paper, which is the common choice.

Example

Two robots of radius 0.5 m and top speed 1 m/s meet head on: AA at (0,0)(0, 0) m with velocity (1,0)(1, 0) m/s, and BB at (4,0)(4, 0) m with velocity (−1,0)(-1, 0) m/s. They would touch at t=1.5t = 1.5 s.

Horizon τ=2\tau = 2 s. The relative velocity (2,0)(2, 0) is inside VOA∣B2VO^2_{A|B}. The tip of the truncated cone is at p/τ=(2,0)p / \tau = (2, 0), so the relative velocity sits on it, and the nearest boundary point is on the right leg. The half-plane of AA passes through (15/16,−15/16)≈(0.9375,−0.2421)(15/16, -\sqrt{15}/16) \approx (0.9375, -0.2421) m/s with direction (−15/4,1/4)(-\sqrt{15}/4, 1/4). The closest permitted velocity to (1,0)(1, 0) is that point itself, so AA takes vA′≈(0.9375,−0.2421)v'_A \approx (0.9375, -0.2421) m/s and BB takes −vA′-v'_A. The change is u/2u / 2 with ∥u∥=0.5\lVert u \rVert = 0.5 m/s. With the new velocities the centers come exactly 1.0 m apart, the contact distance, and do not overlap.

Horizon τ=1\tau = 1 s. The collision at 1.5 s is beyond the horizon. The half-plane passes through (1.5,0)(1.5, 0) and allows vx≤1.5v_x \le 1.5 m/s, so AA keeps (1,0)(1, 0). The robots will react in a later step, when the collision is closer.

A crowd. Eight robots of radius 0.4 m on a circle of radius 6 m swap to the opposite points with τ=2\tau = 2 s and Δt=0.1\Delta t = 0.1 s. With a small random change of at most 0.01 m/s on each preferred velocity, every linear program was feasible, no discs overlapped, and all robots arrived (measurement: 513 to 1369 steps over four seeds, closest distance 0.8 m, the contact distance). Without the random change, the exactly symmetric circle stopped in a deadlock with the robots about 1.31 m from the center.

Correctness

The proof shows that VOA∣BτVO^\tau_{A|B} is open and convex, and that the half-planes of AA and BB are mirror images with the same uu. The main theorem: if vA′∈ORCAA∣Bτv'_A \in ORCA^\tau_{A|B} and vB′∈ORCAB∣Aτv'_B \in ORCA^\tau_{B|A}, then vA′−vB′v'_A - v'_B lies in a closed half-plane that misses the obstacle, by the supporting hyperplane theorem, so the robots do not overlap within τ\tau. So when every robot's program is feasible and every robot senses the robots it could meet within τ\tau, no two robots collide in the next τ\tau seconds. It also proves that the incremental solver returns the closest permitted velocity, and that the fallback minimizes the largest violation. When the fallback runs, there is no guarantee, and there is no liveness theorem: symmetric scenes can deadlock.

Proof: When every ORCA linear program is feasible, no two robots collide within the time horizon, and the incremental solver finds the closest permitted velocityfull

There are rr robots in the plane. Robot AA is a disc with center pAp_A, radius rAr_A, current velocity vAv_A, preferred velocity vAprefv^{pref}_A and largest speed vAmaxv^{max}_A. Robots are holonomic: each one can take any velocity in the disc D(0,vAmax)D(0, v^{max}_A). Time is synchronous: in one step of length Δt\Delta t every robot computes a new velocity from the same snapshot of positions and velocities, then all robots move. τ>0\tau > 0 is the time horizon. Lines L1 to L12 refer to the pseudocode on the ORCA page. Every robot uses its current velocity as the optimization velocity vAopt=vAv^{opt}_A = v_A, as in the code.

For a pair A,BA, B write p=pB−pAp = p_B - p_A and R=rA+rBR = r_A + r_B, and assume ∥p∥>R\lVert p \rVert > R (the discs do not overlap). The truncated velocity obstacle is

VOA∣Bτ={w:∃t∈(0,τ] with ∥tw−p∥<R}.VO^\tau_{A|B} = \{ w : \exists t \in (0, \tau] \text{ with } \lVert t w - p \rVert < R \}.

If the relative velocity vA′−vB′v'_A - v'_B stays constant and is not in VOA∣BτVO^\tau_{A|B}, the discs do not overlap at any time in [0,τ][0, \tau], because t(vA′−vB′)−pt (v'_A - v'_B) - p is the vector between the centers at time tt, up to sign. Note that VOB∣Aτ=−VOA∣BτVO^\tau_{B|A} = -VO^\tau_{A|B}.

Lemma 1 (the obstacle is open and convex). VOA∣BτVO^\tau_{A|B} is an open convex set that does not contain 00.

Proof. Substitute s=1/ts = 1/t. Then w∈VOA∣Bτw \in VO^\tau_{A|B} if and only if there is s≥1/τs \ge 1/\tau with ∥w−sp∥<sR\lVert w - s p \rVert < s R. The set K={(w,s):s≥1/τ,∥w−sp∥<sR}K = \{ (w, s) : s \ge 1/\tau, \lVert w - s p \rVert < s R \} is convex, because ∥w−sp∥−sR\lVert w - s p \rVert - s R is a convex function of (w,s)(w, s) and s≥1/τs \ge 1/\tau is a half-space. VOA∣BτVO^\tau_{A|B} is the image of KK under the linear map (w,s)↦w(w, s) \mapsto w, so it is convex. It is a union of open discs D(sp,sR)D(s p, s R), so it is open. 00 is not in it, because ∥0−sp∥=s∥p∥>sR\lVert 0 - s p \rVert = s \lVert p \rVert > s R. □\square

Let w0=vA−vBw_0 = v_A - v_B, and let w0+uw_0 + u be the point of the boundary of VOA∣BτVO^\tau_{A|B} that is nearest to w0w_0. Let nn be the outward unit normal of VOA∣BτVO^\tau_{A|B} at w0+uw_0 + u. Then n=u/∥u∥n = u / \lVert u \rVert if w0w_0 is inside the obstacle, and n=−u/∥u∥n = -u / \lVert u \rVert if w0w_0 is outside. Line L4 computes uu: the code tests whether the nearest boundary point is on the cut-off circle of center p/τp / \tau and radius R/τR / \tau or on one of the two legs of the cone, and projects w0w_0 onto that part. Line L5 forms

ORCAA∣Bτ={v:(v−(vA+12u))⋅n≥0}.ORCA^\tau_{A|B} = \{ v : (v - (v_A + \tfrac12 u)) \cdot n \ge 0 \}.

Lemma 2 (the two half-planes are mirror images). ORCAB∣Aτ={v:(v−(vB−12u))⋅(−n)≥0}ORCA^\tau_{B|A} = \{ v : (v - (v_B - \tfrac12 u)) \cdot (-n) \ge 0 \}, with the same uu and nn as for AA.

Proof. For BB the roles swap: pp becomes −p-p, w0w_0 becomes −w0-w_0, and the obstacle becomes −VOA∣Bτ-VO^\tau_{A|B}. Point reflection through 00 maps the nearest boundary point w0+uw_0 + u to −w0−u-w_0 - u, so the vector for BB is −u-u, and the outward normal for BB is −n-n. Put these into the formula of line L5. □\square

The code computes both half-planes from the same formulas with the roles swapped. The test test_lines_are_mirror_images checks Lemma 2 on random pairs.

Theorem 1 (reciprocal collision avoidance for one pair). If vA′∈ORCAA∣Bτv'_A \in ORCA^\tau_{A|B} and vB′∈ORCAB∣Aτv'_B \in ORCA^\tau_{B|A}, then vA′−vB′∉VOA∣Bτv'_A - v'_B \notin VO^\tau_{A|B}. So, with constant velocities, AA and BB do not overlap during [0,τ][0, \tau].

Proof. By Lemma 1 and the supporting hyperplane theorem for open convex sets, VOA∣Bτ⊆{w:(w−(w0+u))⋅n<0}VO^\tau_{A|B} \subseteq \{ w : (w - (w_0 + u)) \cdot n < 0 \}, since nn is the outward normal at the boundary point w0+uw_0 + u. Now

vA′−vB′−(w0+u)=(vA′−(vA+12u))−(vB′−(vB−12u)),v'_A - v'_B - (w_0 + u) = \big(v'_A - (v_A + \tfrac12 u)\big) - \big(v'_B - (v_B - \tfrac12 u)\big),

because w0=vA−vBw_0 = v_A - v_B. Take the dot product with nn. The first term gives a value ≥0\ge 0 because vA′∈ORCAA∣Bτv'_A \in ORCA^\tau_{A|B}. The second term gives (vB′−(vB−12u))⋅(−n)≥0(v'_B - (v_B - \frac12 u)) \cdot (-n) \ge 0 by Lemma 2, because vB′∈ORCAB∣Aτv'_B \in ORCA^\tau_{B|A}. So (vA′−vB′−(w0+u))⋅n≥0(v'_A - v'_B - (w_0 + u)) \cdot n \ge 0, and vA′−vB′v'_A - v'_B is not in the open half-plane that contains the obstacle. □\square

Theorem 2 (all robots). Suppose every robot senses every robot that it could meet within τ\tau, and every robot's linear program on line L6 is feasible. Then no two robots overlap during the next τ\tau time units if they keep their new velocities. In particular they do not overlap after the step of line L12 when Δt≤τ\Delta t \le \tau.

Proof. Robot AA's new velocity lies in ORCAA∣BτORCA^\tau_{A|B} for every sensed BB, and BB's new velocity lies in ORCAB∣AτORCA^\tau_{B|A}. Apply Theorem 1 to each pair. A pair that does not sense each other cannot meet within τ\tau by the assumption. □\square

Each robot chooses its velocity alone, from the same snapshot, without messages. The guarantee only needs that both robots of a pair compute the two halves of the same uu, which Lemma 2 gives.

Lemma 3 (the incremental linear program). Let H1,…,HmH_1, \dots, H_m be closed half-planes, let C0=D(0,vmax)C_0 = D(0, v^{max}) and Ci=Ci−1∩HiC_i = C_{i-1} \cap H_i. Let f(v)=∥v−vpref∥2f(v) = \lVert v - v^{pref} \rVert^2. Suppose Ci−1C_{i-1} is not empty and xx is the unique minimizer of ff on Ci−1C_{i-1}. If x∉Hix \notin H_i and CiC_i is not empty, the minimizer yy of ff on CiC_i lies on the boundary line ℓi\ell_i of HiH_i.

Proof. ff is strictly convex and CiC_i is compact and convex, so yy exists and is unique. Suppose y∉ℓiy \notin \ell_i, so yy is in the open side of HiH_i. The segment from xx to yy lies in Ci−1C_{i-1} and crosses ℓi\ell_i at a point z≠yz \ne y, since xx is outside HiH_i. Then z∈Ciz \in C_i, and by strict convexity f(z)<max⁡(f(x),f(y))=f(y)f(z) < \max(f(x), f(y)) = f(y), since f(x)≤f(y)f(x) \le f(y). This contradicts the choice of yy. □\square

Theorem 3 (lines L6 to L8 return the closest permitted velocity). If the intersection of the ORCA half-planes and the speed disc is not empty, the solver of lines L6 to L8 returns the velocity in it that is closest to vprefv^{pref}. If it is empty, the solver reports this.

Proof. Induction on ii. Before the loop the result is the point of C0C_0 closest to vprefv^{pref}, which is vprefv^{pref} itself or its scaling to length vmaxv^{max}. If the current result satisfies HiH_i, it is still optimal on the smaller set CiC_i. If not, by Lemma 3 the new optimum lies on ℓi\ell_i. On ℓi\ell_i, parametrized as q+tdq + t d with a unit vector dd, the set CiC_i is an interval [tleft,tright][t_{left}, t_{right}]: the disc gives the two roots of ∥q+td∥=vmax\lVert q + t d \rVert = v^{max}, and each earlier half-plane cuts one end, depending on the sign of the cross product of the two directions. A half-plane parallel to ℓi\ell_i either holds on all of ℓi\ell_i or on none of it. f(q+td)f(q + t d) is a convex quadratic in tt with minimum at t∗=d⋅(vpref−q)t^* = d \cdot (v^{pref} - q), so the optimum is t∗t^* clamped to the interval. If the interval is empty, then CiC_i is empty by the contrapositive of Lemma 3, and the solver stops and reports index ii. □\square

The same argument holds when the objective is linear, max⁡ v⋅c\max\, v \cdot c for a direction cc (the flag direction_opt in the code). Then the optimum may not be unique, but some optimum lies on ℓi\ell_i, and on the interval it is the end point in the direction of cc.

Lemma 4 (the fallback program). When the program of line L6 is infeasible, lines L9 and L10 return a velocity in the speed disc that minimizes the largest distance δ(v)=max⁡jdist⁡(v,Hj)\delta(v) = \max_j \operatorname{dist}(v, H_j) by which vv is outside a half-plane.

Proof. This is a linear program in the three variables (v,δ)(v, \delta): minimize δ\delta subject to dist⁡(v,Hj)≤δ\operatorname{dist}(v, H_j) \le \delta for every jj and ∥v∥≤vmax\lVert v \rVert \le v^{max}. The code solves it incrementally in the same way. When the current vv violates HiH_i by more than the current δ\delta, the new optimum makes the violations of some constraint tie with that of HiH_i, by the argument of Lemma 3 one dimension higher. For each earlier jj, the set of vv whose violation of HjH_j is at most its violation of HiH_i is a half-plane bounded by the bisector of ℓi\ell_i and ℓj\ell_j. This bisector passes through ℓi∩ℓj\ell_i \cap \ell_j with direction dj−did_j - d_i, or is the middle line when ℓi\ell_i and ℓj\ell_j are parallel with opposite directions; when they are parallel with the same direction, the constraint is dominated and is skipped. Inside these half-planes and the disc, the violation of HiH_i is the largest violation, and it decreases fastest in the direction of the inner normal of HiH_i. So the 2D program with the bisector half-planes and the linear objective in that direction, solved by Theorem 3, gives the optimum for constraints 1,…,i1, \dots, i. □\square

The test test_lp3_minimizes_the_largest_violation compares the result with a grid search over the disc. When the fallback runs, Theorem 2 does not apply, and robots can overlap; this is a measurement in the tests, not a defect of the code.

What the theorems do not give. There is no liveness theorem. A fully symmetric scene, such as robots on a circle that all aim at the antipodal point, can reach an equilibrium in which every robot stops short of its goal. The tests add a small random change to each preferred velocity, as the RVO2 library does, to break such symmetry. Theorem 2 also needs exact arithmetic, the same snapshot for all robots, and holonomic robots that track the new velocity at once.

Complexity

  • One linear program (theorem). With kk half-planes, the incremental method in the given order costs O(k2)O(k^2) in the worst case; with a random order of the half-planes it costs O(k)O(k) expected, as in Seidel's algorithm. The code keeps the given order, as RVO2 does.
  • Fallback. The 3D program runs one 2D program per violated half-plane, O(k3)O(k^3) in the worst case in the given order. It is rare in sparse scenes.
  • Per team step. O(rk2)O(r k^2) in the real RAM model, plus the neighbor search. A k-d tree or a grid keeps kk bounded by the density.
  • Messages. None.
  • Memory. O(k)O(k) per robot for the half-planes.

Properties

  • Collision-free when feasible (theorem). For holonomic discs, synchronous steps, exact sensing and exact arithmetic.
  • Optimal in the local sense. The velocity is the closest permitted one to the preferred velocity, which is what "optimal" in the name means; it says nothing about the travel time.
  • No liveness (theorem by example). Robots can stop for ever in symmetric scenes.
  • Cheap. One small 2D linear program per robot and step, with no sampling.
  • Deterministic. The same input gives the same output; the random change of the preferred velocity is outside the method.

Variants and improvements

  • Static obstacles. Line segments become half-planes too, without the factor 12\frac12, because they do not react; RVO2 handles them first so that they are never violated.
  • Non-holonomic robots. Extensions bound the tracking error of a car-like or differential-drive robot and enlarge the radius by it.
  • Acceleration limits. Extensions add velocity constraints from the acceleration limits.
  • Three dimensions. The same construction in 3D gives half-spaces and a 3D linear program, used for aerial robots.
  • Unequal shares. The proof of the pair theorem works for any shares αu\alpha u and (1−α)u(1 - \alpha) u that add up to uu, so a robot that carries a load can take less of the change.

When to use it

Use ORCA for many holonomic robots or simulated agents that sense each other and must move without collisions in open space: crowd simulation, drone swarms, warehouse robots in open areas. It is fast and has a clear guarantee when feasible. Add a global planner for the route, because ORCA is local and can get stuck behind obstacles. Use a planner for multi-agent pathfinding in narrow corridors, where ORCA tends to deadlock.

Pitfalls

  • Symmetry deadlocks. Exactly symmetric scenes can stop. Add a small random change to the preferred velocities.
  • Horizon choice. A short τ\tau makes robots react late with large changes; a long τ\tau makes them shy and slow in crowds.
  • Non-reacting agents. People and static obstacles do not take their half. Treat them without the factor 12\frac12.
  • Sensing range. The guarantee needs every robot that can be met within τ\tau in the neighbor list. The range must be at least 2vmaxτ2 v_{max} \tau plus the radii.
  • Dynamics. A robot that cannot reach the new velocity at once breaks the assumption. Enlarge the radius or use a dynamics-aware variant.

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.

optimal_reciprocal_collision_avoidance.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/optimal-reciprocal-collision-avoidance/. The authors are listed in prov/D7S5SH.jsonl.

"""Optimal reciprocal collision avoidance (ORCA) for disc robots in the plane.

This follows van den Berg, Guy, Lin and Manocha (2011) and the structure of
their RVO2 library: each robot builds one half-plane of permitted velocities per
neighbor, then solves a 2D linear program for the velocity closest to its
preferred velocity inside all half-planes and inside the disc of maximum speed
(an incremental, Seidel style solver). If the program is infeasible, a second
program finds the velocity that violates the half-planes the least, measured by
the largest distance to a half-plane.

Vectors are tuples (x, y). A half-plane is a Line(point, direction) with a unit
direction; the permitted side is the left side, det(direction, v - point) >= 0.
Agents are holonomic discs: they can take any velocity of length at most vmax.
"""

import math
from typing import NamedTuple, Optional, Sequence

EPS = 1e-9


def add(a, b):
    return (a[0] + b[0], a[1] + b[1])


def sub(a, b):
    return (a[0] - b[0], a[1] - b[1])


def mul(a, k):
    return (a[0] * k, a[1] * k)


def dot(a, b):
    return a[0] * b[0] + a[1] * b[1]


def det(a, b):
    return a[0] * b[1] - a[1] * b[0]


def norm(a):
    return math.hypot(a[0], a[1])


def normalize(a):
    n = norm(a)
    return (a[0] / n, a[1] / n)


class Line(NamedTuple):
    point: tuple
    direction: tuple


class Agent(NamedTuple):
    position: tuple
    velocity: tuple
    radius: float
    vmax: float
    pref: tuple  # preferred velocity


def orca_line(a: Agent, b: Agent, tau: float, dt: float) -> Line:
    """The half-plane ORCA_A|B for agent a, with v_opt equal to the current velocity."""
    rel_pos = sub(b.position, a.position)
    rel_vel = sub(a.velocity, b.velocity)
    dist_sq = dot(rel_pos, rel_pos)
    rad = a.radius + b.radius
    rad_sq = rad * rad
    if dist_sq > rad_sq:
        # No overlap: the boundary of VO is a cut-off circle and two legs.
        w = sub(rel_vel, mul(rel_pos, 1.0 / tau))  # @line L4
        w_len_sq = dot(w, w)
        dot1 = dot(w, rel_pos)
        if dot1 < 0.0 and dot1 * dot1 > rad_sq * w_len_sq:
            w_len = math.sqrt(w_len_sq)  # nearest point is on the cut-off circle
            unit_w = mul(w, 1.0 / w_len)
            direction = (unit_w[1], -unit_w[0])
            u = mul(unit_w, rad / tau - w_len)
        else:
            leg = math.sqrt(dist_sq - rad_sq)  # nearest point is on a leg
            if det(rel_pos, w) > 0.0:
                direction = (
                    (rel_pos[0] * leg - rel_pos[1] * rad) / dist_sq,
                    (rel_pos[0] * rad + rel_pos[1] * leg) / dist_sq,
                )
            else:
                direction = (
                    -(rel_pos[0] * leg + rel_pos[1] * rad) / dist_sq,
                    -(-rel_pos[0] * rad + rel_pos[1] * leg) / dist_sq,
                )
            u = sub(mul(direction, dot(rel_vel, direction)), rel_vel)
    else:
        # Overlap already: push apart within one time step.
        w = sub(rel_vel, mul(rel_pos, 1.0 / dt))
        w_len = norm(w)
        unit_w = mul(w, 1.0 / w_len)
        direction = (unit_w[1], -unit_w[0])
        u = mul(unit_w, rad / dt - w_len)
    return Line(add(a.velocity, mul(u, 0.5)), direction)  # @line L5


def lp1(lines, k, radius, opt, direction_opt):
    """Optimize on line k, inside the disc and the lines 0..k-1. Returns a point or None."""
    ln = lines[k]
    d = dot(ln.point, ln.direction)
    disc = d * d + radius * radius - dot(ln.point, ln.point)
    if disc < 0.0:
        return None
    s = math.sqrt(disc)
    t_left, t_right = -d - s, -d + s
    for i in range(k):
        denom = det(ln.direction, lines[i].direction)
        numer = det(lines[i].direction, sub(ln.point, lines[i].point))
        if abs(denom) <= EPS:
            if numer < 0.0:
                return None
            continue
        t = numer / denom
        if denom >= 0.0:
            t_right = min(t_right, t)
        else:
            t_left = max(t_left, t)
        if t_left > t_right:
            return None
    if direction_opt:
        t = t_right if dot(opt, ln.direction) > 0.0 else t_left
    else:
        t = min(max(dot(ln.direction, sub(opt, ln.point)), t_left), t_right)
    return add(ln.point, mul(ln.direction, t))


def lp2(lines, radius, opt, direction_opt=False):
    """Closest point to opt in the half-planes and the disc (or extreme point in
    direction opt). Returns (number of lines satisfied before a failure, point)."""
    if direction_opt:
        result = mul(opt, radius)
    elif dot(opt, opt) > radius * radius:
        result = mul(normalize(opt), radius)
    else:
        result = opt
    for i in range(len(lines)):  # @line L7
        if det(lines[i].direction, sub(lines[i].point, result)) > 0.0:
            new = lp1(lines, i, radius, opt, direction_opt)  # @line L8
            if new is None:
                return i, result
            result = new
    return len(lines), result


def lp3(lines, begin, radius, result):
    """Minimize the largest violation of the lines, starting from line begin."""
    distance = 0.0
    for i in range(begin, len(lines)):
        if det(lines[i].direction, sub(lines[i].point, result)) > distance:
            proj = []
            for j in range(i):
                denom = det(lines[i].direction, lines[j].direction)
                if abs(denom) <= EPS:
                    if dot(lines[i].direction, lines[j].direction) > 0.0:
                        continue
                    point = mul(add(lines[i].point, lines[j].point), 0.5)
                else:
                    t = det(lines[j].direction, sub(lines[i].point, lines[j].point)) / denom
                    point = add(lines[i].point, mul(lines[i].direction, t))
                proj.append(Line(point, normalize(sub(lines[j].direction, lines[i].direction))))
            temp = result
            opt = (-lines[i].direction[1], lines[i].direction[0])
            count, new = lp2(proj, radius, opt, True)
            result = temp if count < len(proj) else new
            distance = det(lines[i].direction, sub(lines[i].point, result))
    return result


def new_velocity(agent: Agent, others: Sequence[Agent], tau: float, dt: float) -> tuple:
    """The ORCA velocity of one agent, given the agents it sees.

    Returns (velocity, feasible). feasible is False when the linear program has
    no solution and the velocity comes from the fallback program.
    """
    lines = [orca_line(agent, b, tau, dt) for b in others]  # @line L3
    count, v = lp2(lines, agent.vmax, agent.pref)  # @line L6
    if count < len(lines):  # @line L9
        return lp3(lines, count, agent.vmax, v), False  # @line L10
    return v, True  # @line L11


def step(agents: Sequence[Agent], tau: float, dt: float, sensing: Optional[float] = None) -> tuple:
    """One synchronous step: every agent computes its velocity, then all move.

    Returns (new agents, True if every linear program was feasible).
    """
    new = []
    all_feasible = True
    for i, a in enumerate(agents):  # @line L1
        others = [
            b for k, b in enumerate(agents)
            if k != i and (sensing is None or norm(sub(b.position, a.position)) <= sensing)
        ]  # @line L2
        v, ok = new_velocity(a, others, tau, dt)
        all_feasible = all_feasible and ok
        new.append(a._replace(velocity=v))
    moved = [a._replace(position=add(a.position, mul(a.velocity, dt))) for a in new]  # @line L12
    return moved, all_feasible


def time_to_collision(pa, va, pb, vb, rad) -> float:
    """First time t >= 0 at which the discs touch with constant velocities, or inf."""
    p = sub(pb, pa)
    v = sub(va, vb)
    a = dot(v, v)
    b = dot(p, v)
    c = dot(p, p) - rad * rad
    if c <= 0.0:
        return 0.0
    disc = b * b - a * c
    if a <= 0.0 or b <= 0.0 or disc < 0.0:
        return math.inf
    return (b - math.sqrt(disc)) / a
test_optimal_reciprocal_collision_avoidance.py 217 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/optimal-reciprocal-collision-avoidance/. The authors are listed in prov/D7S5SH.jsonl.

import math
import random

from optimal_reciprocal_collision_avoidance import (
    Agent,
    Line,
    det,
    dot,
    lp2,
    lp3,
    new_velocity,
    norm,
    orca_line,
    step,
    sub,
)

TOL = 1e-9


def violation(line, v):
    """Distance by which v is on the forbidden (right) side of the line, or <= 0."""
    return det(line.direction, sub(line.point, v))


def min_distance(pa, va, pb, vb, horizon):
    """Smallest distance between two points that move with constant velocities on [0, horizon]."""
    p = sub(pb, pa)
    v = sub(vb, va)
    vv = dot(v, v)
    t = 0.0 if vv == 0.0 else min(max(-dot(p, v) / vv, 0.0), horizon)
    return norm((p[0] + v[0] * t, p[1] + v[1] * t))


def brute_lp(lines, radius, opt):
    """Brute force: the nearest feasible point to opt among all candidate points."""
    cands = [opt]
    for ln in lines:
        t = dot(ln.direction, sub(opt, ln.point))
        cands.append((ln.point[0] + t * ln.direction[0], ln.point[1] + t * ln.direction[1]))
        d = dot(ln.point, ln.direction)
        disc = d * d + radius * radius - dot(ln.point, ln.point)
        if disc >= 0:
            for s in (-1, 1):
                t = -d + s * math.sqrt(disc)
                cands.append((ln.point[0] + t * ln.direction[0], ln.point[1] + t * ln.direction[1]))
    for i in range(len(lines)):
        for k in range(i + 1, len(lines)):
            a, b = lines[i], lines[k]
            den = det(a.direction, b.direction)
            if abs(den) > 1e-12:
                t = det(b.direction, sub(a.point, b.point)) / den
                cands.append((a.point[0] + t * a.direction[0], a.point[1] + t * a.direction[1]))
    n = norm(opt)
    if n > 0:
        cands.append((opt[0] * radius / n, opt[1] * radius / n))
    best = None
    for c in cands:
        if norm(c) <= radius + 1e-9 and all(violation(ln, c) <= 1e-9 for ln in lines):
            d = norm(sub(c, opt))
            if best is None or d < best:
                best = d
    return best


def random_line(rng):
    ang = rng.uniform(0, 2 * math.pi)
    return Line((rng.uniform(-2, 2), rng.uniform(-2, 2)), (math.cos(ang), math.sin(ang)))


def test_head_on_example():
    a = Agent((0.0, 0.0), (1.0, 0.0), 0.5, 1.0, (1.0, 0.0))
    b = Agent((4.0, 0.0), (-1.0, 0.0), 0.5, 1.0, (-1.0, 0.0))
    s15 = math.sqrt(15.0)
    line = orca_line(a, b, 2.0, 0.1)
    assert abs(line.point[0] - 15 / 16) < TOL and abs(line.point[1] + s15 / 16) < TOL
    assert abs(line.direction[0] + s15 / 4) < TOL and abs(line.direction[1] - 0.25) < TOL
    va, ok_a = new_velocity(a, [b], 2.0, 0.1)
    vb, ok_b = new_velocity(b, [a], 2.0, 0.1)
    assert ok_a and ok_b
    assert abs(va[0] - 15 / 16) < TOL and abs(va[1] + s15 / 16) < TOL
    assert abs(vb[0] + 15 / 16) < TOL and abs(vb[1] - s15 / 16) < TOL
    assert min_distance(a.position, va, b.position, vb, 10.0) >= 1.0 - TOL
    # With tau = 1 the collision at t = 1.5 is outside the horizon: no change.
    line1 = orca_line(a, b, 1.0, 0.1)
    assert abs(line1.point[0] - 1.5) < TOL and abs(line1.point[1]) < TOL
    v1, ok = new_velocity(a, [b], 1.0, 0.1)
    assert ok and abs(v1[0] - 1.0) < TOL and abs(v1[1]) < TOL


def test_lines_are_mirror_images():
    rng = random.Random(4)
    for _ in range(200):
        a = Agent((rng.uniform(-3, 3), rng.uniform(-3, 3)), (rng.uniform(-1, 1), rng.uniform(-1, 1)), 0.4, 2.0, (0, 0))
        b = Agent((rng.uniform(-3, 3), rng.uniform(-3, 3)), (rng.uniform(-1, 1), rng.uniform(-1, 1)), 0.3, 2.0, (0, 0))
        if norm(sub(a.position, b.position)) <= 0.7:
            continue
        la = orca_line(a, b, 2.0, 0.1)
        lb = orca_line(b, a, 2.0, 0.1)
        ua = sub(la.point, a.velocity)
        ub = sub(lb.point, b.velocity)
        assert norm((ua[0] + ub[0], ua[1] + ub[1])) < 1e-9
        assert norm((la.direction[0] + lb.direction[0], la.direction[1] + lb.direction[1])) < 1e-9


def test_lp2_against_brute_force():
    rng = random.Random(11)
    feasible = 0
    for _ in range(400):
        lines = [random_line(rng) for _ in range(rng.randint(1, 6))]
        radius = rng.uniform(0.5, 3.0)
        opt = (rng.uniform(-3, 3), rng.uniform(-3, 3))
        count, v = lp2(lines, radius, opt)
        best = brute_lp(lines, radius, opt)
        if count == len(lines):
            feasible += 1
            assert norm(v) <= radius + 1e-9
            assert all(violation(ln, v) <= 1e-9 for ln in lines)
            assert best is not None and abs(norm(sub(v, opt)) - best) < 1e-7
        else:
            assert best is None
    assert feasible > 100


def test_lp3_minimizes_the_largest_violation():
    rng = random.Random(5)
    checked = 0
    while checked < 40:
        lines = [random_line(rng) for _ in range(rng.randint(2, 5))]
        radius = 1.0
        count, v = lp2(lines, radius, (0.0, 0.0))
        if count == len(lines):
            continue
        checked += 1
        v = lp3(lines, count, radius, v)
        assert norm(v) <= radius + 1e-9
        got = max(violation(ln, v) for ln in lines)
        grid = 1e9
        n = 60
        for i in range(-n, n + 1):
            for k in range(-n, n + 1):
                c = (i / n, k / n)
                if norm(c) <= radius:
                    grid = min(grid, max(violation(ln, c) for ln in lines))
        assert got <= grid + 1e-9
        assert got > 0


def test_pairs_avoid_each_other_for_tau():
    rng = random.Random(3)
    for _ in range(400):
        tau = rng.choice([1.0, 2.0, 5.0])
        a = Agent((0.0, 0.0), (rng.uniform(-0.5, 0.5), rng.uniform(-0.5, 0.5)), 0.5, 1.5, (rng.uniform(-1, 1), rng.uniform(-1, 1)))
        b = Agent((rng.uniform(-4, 4), rng.uniform(-4, 4)), (rng.uniform(-0.5, 0.5), rng.uniform(-0.5, 0.5)), 0.5, 1.5, (rng.uniform(-1, 1), rng.uniform(-1, 1)))
        if norm(b.position) <= 1.0:
            continue
        va, ok_a = new_velocity(a, [b], tau, 0.1)
        vb, ok_b = new_velocity(b, [a], tau, 0.1)
        assert ok_a and ok_b
        assert min_distance(a.position, va, b.position, vb, tau) >= 1.0 - 1e-9


def circle_scenario(n, ring, rad, seed):
    rng = random.Random(seed)
    agents, goals = [], []
    for i in range(n):
        th = 2 * math.pi * i / n + rng.uniform(-0.05, 0.05)
        p = (ring * math.cos(th), ring * math.sin(th))
        agents.append(Agent(p, (0.0, 0.0), rad, 1.0, (0.0, 0.0)))
        goals.append((-p[0], -p[1]))
    return rng, agents, goals


def with_preferences(rng, agents, goals):
    out = []
    for a, g in zip(agents, goals):
        d = sub(g, a.position)
        s = max(norm(d), 1.0)
        ang = rng.uniform(0, 2 * math.pi)
        m = rng.uniform(0, 0.01)  # a small push that breaks symmetric deadlocks
        out.append(a._replace(pref=(d[0] / s + m * math.cos(ang), d[1] / s + m * math.sin(ang))))
    return out


def closest_pair(agents):
    return min(
        norm(sub(agents[i].position, agents[k].position)) - agents[i].radius - agents[k].radius
        for i in range(len(agents))
        for k in range(i + 1, len(agents))
    )


def test_eight_robots_swap_without_overlap():
    rng, agents, goals = circle_scenario(8, 6.0, 0.4, 3)
    for k in range(1500):
        agents, ok = step(with_preferences(rng, agents, goals), 2.0, 0.1)
        assert ok
        assert closest_pair(agents) >= -1e-9
        if all(norm(sub(a.position, g)) < 0.1 for a, g in zip(agents, goals)):
            break
    assert all(norm(sub(a.position, g)) < 0.1 for a, g in zip(agents, goals))


def test_feasible_steps_never_create_overlap():
    rng, agents, goals = circle_scenario(8, 6.0, 0.5, 2)
    fallback = 0
    for k in range(800):
        before = closest_pair(agents)
        agents, ok = step(with_preferences(rng, agents, goals), 2.0, 0.1)
        if not ok:
            fallback += 1
        elif before >= -1e-9:
            assert closest_pair(agents) >= -1e-9
    assert fallback > 0

History

Fiorini and Shiller introduced velocity obstacles in 1998. Van den Berg, Lin and Manocha added reciprocity in 2008. Van den Berg, Guy, Lin and Manocha presented reciprocal n-body collision avoidance at the International Symposium of Robotics Research in 2009, published in 2011, with the half-plane construction, the linear programs and the guarantee. The authors released the RVO2 library, which follows that paper.

References

  1. Jur van den Berg, Stephen J. Guy, Ming C. Lin and Dinesh Manocha, Reciprocal n-body collision avoidance, Robotics Research (ISRR 2009), Springer Tracts in Advanced Robotics 70, 2011, pages 3 to 19 (the truncated velocity obstacle, the ORCA half-plane, the linear programs and the guarantee)
  2. Jur van den Berg, Ming C. Lin and Dinesh Manocha, Reciprocal velocity obstacles for real-time multi-agent navigation, IEEE International Conference on Robotics and Automation, 2008, pages 1928 to 1935 (the reciprocal idea that ORCA builds on)

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.expected_with_random_order
  • a full proof of time.per_robot_step
  • a full proof of time.per_team_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
  • at least three sources
  • a scene preset for the example