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
- Model
- Real RAM
- Properties
- deterministiconlinenot randomized
- Evidence
- Proof sketchCode in 1 languages
- 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 , 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 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 seconds: every robot computes its new velocity from the same snapshot, then all robots move. The horizon , in seconds, says how far ahead collisions count.
Input. For one robot : its state, its preferred velocity, the states of its sensed neighbors, and .
Output. A new velocity for , 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 and , with and , the truncated velocity obstacle is the set of relative velocities for which the discs overlap at some time in . It is a cone with its tip cut off by a circle of center and radius , and it is open and convex. Let be the vector from the relative velocity to the nearest point of the boundary of , and let be the outward normal there.
ORCA-STEP(robots, tau, dt)- 1
for each robot A, in parallel on the same snapshot, do - 2
N ← the robots that A senses - 3
for each B in N do build the half-plane ORCA_A|B: - 4
u ← the nearest boundary point of VO^tau_A|B minus (v_A − v_B); n ← the outward normal there - 5
ORCA_A|B ← { v : (v − (v_A + u / 2)) · n ≥ 0 } - 6
v_new ← the v closest to v_pref with |v| ≤ v_max inside every ORCA_A|B, by an incremental 2D LP: - 7
for each half-plane, in order: if the current optimum is outside it then - 8
solve the 1D problem on its boundary line, cut by the speed disc and the earlier half-planes - 9
if some 1D problem is empty then - 10
v_new ← the v with |v| ≤ v_max that minimizes the largest distance to a violated half-plane (a 3D LP) - 11
return v_new and whether the LP was feasible - 12
every 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 : robot makes half of the change , and robot computes the mirror half-plane with and . If two robots already overlap, the code uses in place of , 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 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: at m with velocity m/s, and at m with velocity m/s. They would touch at s.
Horizon s. The relative velocity is inside . The tip of the truncated cone is at , so the relative velocity sits on it, and the nearest boundary point is on the right leg. The half-plane of passes through m/s with direction . The closest permitted velocity to is that point itself, so takes m/s and takes . The change is with m/s. With the new velocities the centers come exactly 1.0 m apart, the contact distance, and do not overlap.
Horizon s. The collision at 1.5 s is beyond the horizon. The half-plane passes through and allows m/s, so keeps . 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 s and 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 is open and convex, and that the half-planes of and are mirror images with the same . The main theorem: if and , then lies in a closed half-plane that misses the obstacle, by the supporting hyperplane theorem, so the robots do not overlap within . So when every robot's program is feasible and every robot senses the robots it could meet within , no two robots collide in the next 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 robots in the plane. Robot is a disc with center , radius , current velocity , preferred velocity and largest speed . Robots are holonomic: each one can take any velocity in the disc . Time is synchronous: in one step of length every robot computes a new velocity from the same snapshot of positions and velocities, then all robots move. 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 , as in the code.
For a pair write and , and assume (the discs do not overlap). The truncated velocity obstacle is
If the relative velocity stays constant and is not in , the discs do not overlap at any time in , because is the vector between the centers at time , up to sign. Note that .
Lemma 1 (the obstacle is open and convex). is an open convex set that does not contain .
Proof. Substitute . Then if and only if there is with . The set is convex, because is a convex function of and is a half-space. is the image of under the linear map , so it is convex. It is a union of open discs , so it is open. is not in it, because .
Let , and let be the point of the boundary of that is nearest to . Let be the outward unit normal of at . Then if is inside the obstacle, and if is outside. Line L4 computes : the code tests whether the nearest boundary point is on the cut-off circle of center and radius or on one of the two legs of the cone, and projects onto that part. Line L5 forms
Lemma 2 (the two half-planes are mirror images). , with the same and as for .
Proof. For the roles swap: becomes , becomes , and the obstacle becomes . Point reflection through maps the nearest boundary point to , so the vector for is , and the outward normal for is . Put these into the formula of line L5.
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 and , then . So, with constant velocities, and do not overlap during .
Proof. By Lemma 1 and the supporting hyperplane theorem for open convex sets, , since is the outward normal at the boundary point . Now
because . Take the dot product with . The first term gives a value because . The second term gives by Lemma 2, because . So , and is not in the open half-plane that contains the obstacle.
Theorem 2 (all robots). Suppose every robot senses every robot that it could meet within , and every robot's linear program on line L6 is feasible. Then no two robots overlap during the next time units if they keep their new velocities. In particular they do not overlap after the step of line L12 when .
Proof. Robot 's new velocity lies in for every sensed , and 's new velocity lies in . Apply Theorem 1 to each pair. A pair that does not sense each other cannot meet within by the assumption.
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 , which Lemma 2 gives.
Lemma 3 (the incremental linear program). Let be closed half-planes, let and . Let . Suppose is not empty and is the unique minimizer of on . If and is not empty, the minimizer of on lies on the boundary line of .
Proof. is strictly convex and is compact and convex, so exists and is unique. Suppose , so is in the open side of . The segment from to lies in and crosses at a point , since is outside . Then , and by strict convexity , since . This contradicts the choice of .
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 . If it is empty, the solver reports this.
Proof. Induction on . Before the loop the result is the point of closest to , which is itself or its scaling to length . If the current result satisfies , it is still optimal on the smaller set . If not, by Lemma 3 the new optimum lies on . On , parametrized as with a unit vector , the set is an interval : the disc gives the two roots of , 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 either holds on all of or on none of it. is a convex quadratic in with minimum at , so the optimum is clamped to the interval. If the interval is empty, then is empty by the contrapositive of Lemma 3, and the solver stops and reports index .
The same argument holds when the objective is linear, for a direction (the flag direction_opt in the code). Then the optimum may not be unique, but some optimum lies on , and on the interval it is the end point in the direction of .
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 by which is outside a half-plane.
Proof. This is a linear program in the three variables : minimize subject to for every and . The code solves it incrementally in the same way. When the current violates by more than the current , the new optimum makes the violations of some constraint tie with that of , by the argument of Lemma 3 one dimension higher. For each earlier , the set of whose violation of is at most its violation of is a half-plane bounded by the bisector of and . This bisector passes through with direction , or is the middle line when and 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 is the largest violation, and it decreases fastest in the direction of the inner normal of . 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 .
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 half-planes, the incremental method in the given order costs in the worst case; with a random order of the half-planes it costs 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, in the worst case in the given order. It is rare in sparse scenes.
- Per team step. in the real RAM model, plus the neighbor search. A k-d tree or a grid keeps bounded by the density.
- Messages. None.
- Memory. 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 , 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 and that add up to , 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 makes robots react late with large changes; a long makes them shy and slow in crowds.
- Non-reacting agents. People and static obstacles do not take their half. Treat them without the factor .
- Sensing range. The guarantee needs every robot that can be met within in the neighbor list. The range must be at least 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.
# 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
- 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)
- 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.
| 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 D7S5SH Edit this page History Report an error Markdown