Algorithm Search⌘K

Algorithmadvanced

Reciprocal velocity obstacles

Also called RVO.

Each robot takes half of the avoidance by choosing velocities outside a velocity obstacle whose apex sits at the average of both velocities, which removes the oscillation of plain velocity obstacles.

Time
O(s k) per_robot_stepO(r s k) per_team_step
Space
O(s + k) extra
Where
k = the number of sensed neighbors per robot; r = the number of robots; s = the number of candidate velocities per robot
Properties
deterministiconlinenot randomized
Origin
Jur van den Berg, Ming C. Lin, Dinesh Manocha, 2008

Reciprocal velocity obstacles (RVO) let many robots avoid each other with no messages and no central planner. A velocity obstacle is the set of velocities that lead to a collision if the other robot keeps its velocity; when both robots use it, both dodge fully, then both see the way clear and return, and they oscillate. RVO moves the apex of the obstacle to the average of the two velocities, so each robot takes half of the avoidance and a mirrored choice is stable. Unlike optimal reciprocal collision avoidance, which gives each pair a half-plane and a linear program, RVO picks a velocity by a sampled penalty and has no collision guarantee for three or more robots.

In plain words

Two people walk toward each other in a corridor. If each one steps fully aside, expecting the other to walk straight, both step aside, then both see the path is clear and step back, and they dance. RVO tells each walker: assume the other person will do half of the work, and do only your half. If both do this and both pick the same side, they pass each other cleanly, and no one wants to step back.

Each robot looks at the robots near it and their speeds. It tries many possible new velocities, and for each one it asks how soon it would hit someone if the others also did their half. It picks the velocity that is close to where it wants to go and keeps a collision far away.

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 maximum speed and a preferred velocity, which points to its goal. The robots are holonomic: they can take any velocity in their speed disc at once. Each robot senses the positions and velocities of the robots within a sensing range, and the robots send no messages; the sensing graph is the disc graph of this range. Time runs in synchronous steps of length Δt\Delta t seconds: every robot picks its new velocity from the same snapshot, then all robots move.

Input. For one robot AA: its own state and its preferred velocity vAprefv^{pref}_A, and the states of the sensed robots.

Output. A new velocity vA′v'_A for the next step.

How it differs from close pages. The velocity obstacle assumes the other robot does not react, and is right for passive obstacles. RVO assumes the other robot runs the same rule. Optimal reciprocal collision avoidance keeps the idea of shared effort but replaces the cone by a half-plane per pair and the sampling by a linear program, and it proves collision avoidance when the program is feasible. The dynamic window approach samples velocities under acceleration limits for one robot among static obstacles. The potential field method works on positions and has no notion of time to collision.

The algorithm

For robots AA and BB with p=pB−pAp = p_B - p_A and R=rA+rBR = r_A + r_B, the collision cone CC is the set of relative velocities ww for which the ray twt w, t>0t > 0, enters the open disc of radius RR around pp. The velocity obstacle is VOA∣B(vB)=vB+CVO_{A|B}(v_B) = v_B + C. The reciprocal velocity obstacle is

RVOA∣B(vA,vB)={v′:2v′−vA∈VOA∣B(vB)},RVO_{A|B}(v_A, v_B) = \{ v' : 2 v' - v_A \in VO_{A|B}(v_B) \},

the velocity obstacle with its apex moved from vBv_B to 12(vA+vB)\tfrac12 (v_A + v_B). Each robot scores a set of candidate velocities with the penalty of the paper, ω/tc(v′)+∥v′−vApref∥\omega / t_c(v') + \lVert v' - v^{pref}_A \rVert, where tct_c is the time to the first collision under the reciprocal assumption and ω\omega is a weight in meters.

  1. RVO-STEP(robots, dt, omega)
  2. 1for each robot A, in parallel on the same snapshot, do
  3. 2for each candidate v' among v_pref, 0 and a polar grid in the speed disc do
  4. 3tc ← ∞
  5. 4for each sensed robot B do
  6. 5w ← 2 v' − v_A − v_B
  7. 6tc ← min(tc, the first time t > 0 with |p_B − p_A − t w| < r_A + r_B)
  8. 7penalty(v') ← omega / tc + |v' − v_pref|
  9. 8v'_A ← the candidate with the smallest penalty (the first one on ties)
  10. 9every robot sets v_A ← v'_A and moves p_A ← p_A + v_A dt

Line L5 is the reciprocal relative velocity: v′∈RVOA∣Bv' \in RVO_{A|B} exactly when ww is in the cone. Line L6 solves a quadratic in tt. A candidate with tc=∞t_c = \infty has only the distance term, so a free preferred velocity is always kept. A candidate with tc=0t_c = 0, an overlap now, gets an infinite penalty.

The paper draws random samples. The code uses a fixed polar grid of rings and spokes whose spokes start at the direction of the preferred velocity. Then two robots in mirror image positions get mirror image candidate lists, and they pick mirror image velocities, which is the case the theorems cover.

Example

Two robots of radius 0.5 m and top speed 1 m/s meet head on: AA at (0,0)(0, 0) m moving at (1,0)(1, 0) m/s, BB at (4,0)(4, 0) m moving at (−1,0)(-1, 0) m/s, with ω=1\omega = 1 m and Δt=0.1\Delta t = 0.1 s. The apex of RVOA∣BRVO_{A|B} is 12(vA+vB)=0\tfrac12 (v_A + v_B) = 0, and v′v' is inside when 2v′2 v' points within the half angle arcsin⁡(1/4)≈14.5°\arcsin(1 / 4) \approx 14.5° of the direction to BB.

The straight velocity (1,0)(1, 0) is inside, so AA turns. The grid with 6 rings and 32 spokes has spokes every 11.25°11.25°; the spoke at 11.25°11.25° is still inside, and the first free candidate at full speed is at 22.5°22.5°: vA′=(cos⁡22.5°,sin⁡22.5°)≈(0.924,0.383)v'_A = (\cos 22.5°, \sin 22.5°) \approx (0.924, 0.383) m/s. Robot BB picks exactly −vA′-v'_A. The relative velocity vA′−vB′=2vA′v'_A - v'_B = 2 v'_A misses the disc, so the time to collision is infinite. In the simulation of 80 steps, both robots turn to their left, turn back toward their goals as they pass, and end with velocities (1,0)(1, 0) and (−1,0)(-1, 0) again. The smallest distance between the centers is about 1.007 m, above the 1 m contact distance, and AA never swings to the other side (measurement).

With plain velocity obstacles and the same penalty, both robots dodge in step 1, both see the straight path free in step 2 and go straight, and the pattern repeats with period 2 for all 10 steps of the test (measurement). This is the oscillation that RVO removes.

Correctness

The proof shows two theorems for two robots, under the assumptions of holonomic discs, synchronous steps and exact sensing. Same side: if each robot picks a velocity outside its own reciprocal velocity obstacle, and both pass on the same side, the robots never collide, because the relative velocity is the average of two vectors in the same closed half-plane outside the cone. No oscillation: if the choice is mirrored, vA′+vB′=vA+vBv'_A + v'_B = v_A + v_B, then in the next step the old velocity is inside the new obstacle and the new velocity stays outside, so neither robot wants to go back. The proof also shows why the code makes mirrored choices in a mirrored scene.

The selection rule itself is a heuristic. It may pick a velocity inside an obstacle if the penalty favors it, and with three or more robots nothing makes every pair choose the same side. So RVO has no collision guarantee for the full method; the tests measure no overlap in a swap of 6 robots of radius 0.4 m on a circle of radius 6 m.

Proof: Two robots that choose velocities outside their reciprocal velocity obstacles on the same side never collide, and a mirrored choice does not oscillatefull

Two robots AA and BB are discs in the plane with centers pA,pBp_A, p_B, radii rA,rBr_A, r_B and current velocities vA,vBv_A, v_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, so the discs do not overlap. Lines L1 to L9 refer to the pseudocode on the reciprocal velocity obstacles page. The horizon is infinite, as in van den Berg, Lin and Manocha (2008): a collision at any future time counts.

The cone. Let C={w≠0:∃t>0 with ∥tw−p∥<R}C = \{ w \ne 0 : \exists t > 0 \text{ with } \lVert t w - p \rVert < R \}. If the relative velocity vA′−vB′v'_A - v'_B stays constant, the discs overlap at some time t>0t > 0 if and only if vA′−vB′∈Cv'_A - v'_B \in C, because pB+tvB′−(pA+tvA′)=p−t(vA′−vB′)p_B + t v'_B - (p_A + t v'_A) = p - t (v'_A - v'_B). The velocity obstacle of AA for BB is VOA∣B(vB)=vB+CVO_{A|B}(v_B) = v_B + C, and the reciprocal velocity obstacle is

RVOA∣B(vA,vB)={v′:2v′−vA∈VOA∣B(vB)}={v′:2v′−vA−vB∈C}.RVO_{A|B}(v_A, v_B) = \{ v' : 2 v' - v_A \in VO_{A|B}(v_B) \} = \{ v' : 2 v' - v_A - v_B \in C \}.

Its apex is 12(vA+vB)\frac12 (v_A + v_B). By symmetry, RVOB∣A(vB,vA)={v′:2v′−vA−vB∈−C}RVO_{B|A}(v_B, v_A) = \{ v' : 2 v' - v_A - v_B \in -C \}.

Lemma 1 (the time to collision). Let a=∥w∥2a = \lVert w \rVert^2, b=p⋅wb = p \cdot w, c=∥p∥2−R2>0c = \lVert p \rVert^2 - R^2 > 0 and Δ=b2−ac\Delta = b^2 - a c. Then w∈Cw \in C if and only if a>0a > 0, b>0b > 0 and Δ>0\Delta > 0, and then the first time of contact is t∗=(b−Δ)/a>0t^* = (b - \sqrt{\Delta}) / a > 0.

Proof. ∥tw−p∥2−R2=at2−2bt+c\lVert t w - p \rVert^2 - R^2 = a t^2 - 2 b t + c. For a=0a = 0 this is c>0c > 0 for all tt. For a>0a > 0 the quadratic is negative for some tt if and only if Δ>0\Delta > 0, and then exactly on the open interval between its roots (b±Δ)/a(b \pm \sqrt\Delta) / a. Their product is c/a>0c / a > 0, so both roots have the sign of bb, and the interval meets t>0t > 0 if and only if b>0b > 0. If Δ=0\Delta = 0 the discs only touch, which is not an overlap. □\square

The function time_to_collision computes t∗t^*, and in_rvo tests 2v′−vA−vB∈C2 v' - v_A - v_B \in C with it. The test compares in_rvo with a second test of the cone, p⋅w>0p \cdot w > 0 and ∣w×p∣/∥w∥<R|w \times p| / \lVert w \rVert < R, which says that the ray meets the disc in front of the apex.

Lemma 2 (the cone is an open wedge). Let α=arcsin⁡(R/∥p∥)<π/2\alpha = \arcsin(R / \lVert p \rVert) < \pi / 2, and let ℓL\ell_L and ℓR\ell_R be the unit vectors of pp turned by +α+\alpha and by −α-\alpha (the left and the right leg). Then CC is the set of w≠0w \ne 0 whose angle to pp is less than α\alpha. Its complement is HL∪HRH_L \cup H_R, with the closed half-planes HL={w:ℓL×w≥0}H_L = \{ w : \ell_L \times w \ge 0 \} and HR={w:ℓR×w≤0}H_R = \{ w : \ell_R \times w \le 0 \}. Here u×w=uxwy−uywxu \times w = u_x w_y - u_y w_x.

Proof. The ray {tw:t>0}\{ t w : t > 0 \} meets the open disc D(p,R)D(p, R) if and only if its distance to pp is less than RR and pp lies ahead, that is, if and only if the angle θ\theta between ww and pp satisfies θ<π/2\theta < \pi / 2 and ∥p∥sin⁡θ<R\lVert p \rVert \sin \theta < R, that is, θ<α\theta < \alpha. This open wedge is the intersection of the two open half-planes {ℓL×w<0}\{ \ell_L \times w < 0 \} and {ℓR×w>0}\{ \ell_R \times w > 0 \}, because α<π/2\alpha < \pi / 2, so its complement is the union of their complements HLH_L and HRH_R. □\square

HLH_L holds the relative velocities that pass BB on the left of AA's line of sight, and HRH_R those that pass on the right.

Theorem 1 (same side, no collision). Let wA=2vA′−vA−vBw_A = 2 v'_A - v_A - v_B and wB=−(2vB′−vA−vB)w_B = -(2 v'_B - v_A - v_B). So vA′∉RVOA∣Bv'_A \notin RVO_{A|B} if and only if wA∉Cw_A \notin C, and vB′∉RVOB∣Av'_B \notin RVO_{B|A} if and only if wB∉Cw_B \notin C. If wAw_A and wBw_B both lie in HLH_L, or both lie in HRH_R, then vA′−vB′∉Cv'_A - v'_B \notin C, so the robots never collide with these velocities.

Proof. vA′−vB′=12(wA+wB)v'_A - v'_B = \frac12 (w_A + w_B). A closed half-plane through the origin is a convex cone, so it contains the average of two of its points. By Lemma 2 that half-plane is disjoint from CC. □\square

In words: if each robot takes a velocity outside its own reciprocal velocity obstacle, and both pass on the same side, each robot does half of the avoidance and the halves add up. The test test_same_side_choices_never_collide checks this on random pairs, and it also finds many pairs where each robot is outside its own obstacle but the two choose opposite sides and collide. So the same side condition is needed.

Theorem 2 (a mirrored choice is stable). Suppose the pair was on a collision course, vA−vB∈Cv_A - v_B \in C, and the new velocities are mirrored: vA′+vB′=vA+vBv'_A + v'_B = v_A + v_B. Then in the next step, with the new velocities as the current ones, (a) the old velocity vAv_A is inside RVOA∣B(vA′,vB′)RVO_{A|B}(v'_A, v'_B), and (b) the new velocity vA′v'_A is outside RVOA∣B(vA′,vB′)RVO_{A|B}(v'_A, v'_B) whenever it was outside RVOA∣B(vA,vB)RVO_{A|B}(v_A, v_B).

Proof. Write δ=vA′−vA=−(vB′−vB)\delta = v'_A - v_A = -(v'_B - v_B). (a) 2vA−vA′−vB′=2vA−(vA+vB)=vA−vB∈C2 v_A - v'_A - v'_B = 2 v_A - (v_A + v_B) = v_A - v_B \in C. (b) 2vA′−vA′−vB′=vA′−vB′=vA−vB+2δ2 v'_A - v'_A - v'_B = v'_A - v'_B = v_A - v_B + 2 \delta, and 2vA′−vA−vB=vA−vB+2δ2 v'_A - v_A - v_B = v_A - v_B + 2 \delta is the same vector. □\square

So under a mirrored choice neither robot wants to go back to its old velocity, and the new velocity stays permitted. With the plain velocity obstacle, vA′∉VOA∣B(vB)v'_A \notin VO_{A|B}(v_B) means vA′−vB∉Cv'_A - v_B \notin C; when both robots dodge, each sees the other's dodge in the next step, the straight velocity becomes free again, both return to it, and the cycle repeats. This is the oscillation that the reciprocal obstacle removes. The test test_plain_velocity_obstacles_oscillate shows the cycle of period 2 for a head-on pair, and test_head_on_pair_turns_to_the_same_side shows the RVO pair turning once and staying on its side.

Why the code makes mirrored choices in a mirrored scene. Line L2 scores the preferred velocity, the zero velocity and a polar grid whose spokes are measured from the direction of the preferred velocity. If robot BB is the point reflection of robot AA through the midpoint, so pp, vBv_B and vBprefv^{pref}_B are the negatives of the data of AA, then BB's candidate list is the negated list of AA in the same order. Every quantity in lines L5 to L7 changes sign or stays the same under this reflection, and negation is exact in floating point, so the penalties are equal entry by entry and the first minimum has the same index. Then vB′=−vA′v'_B = -v'_A and vB=−vAv_B = -v_A, which is the hypothesis of Theorem 2, and wA=2vA′=wBw_A = 2 v'_A = w_B, which is the hypothesis of Theorem 1.

What the theorems do not give. The selection rule of lines L2 to L8 is a heuristic. It may pick a velocity inside a reciprocal velocity obstacle when the penalty ω/tc+∥v′−vpref∥\omega / t_c + \lVert v' - v^{pref} \rVert favors it, and with three or more robots nothing makes every pair pick the same side. So there is no collision guarantee for the full method. The tests measure that no discs overlap in a swap of 6 robots on a circle. The theorems also assume holonomic robots, synchronous steps, and exact velocities of the neighbors. Optimal reciprocal collision avoidance replaces the side choice by one half-plane per pair and gets a guarantee when its linear program is feasible.

Complexity

  • Per robot per step (theorem). ss candidates times kk sensed robots, each a constant-time quadratic, so O(sk)O(s k) in the real RAM model. With 6 rings and 32 spokes, s=194s = 194.
  • Per team step. O(rsk)O(r s k), or O(r2s)O(r^2 s) when every robot senses every other. Finding the neighbors with a spatial grid or a k-d tree keeps kk small.
  • Messages. None: each robot uses only what it senses.
  • Memory. O(s+k)O(s + k) per robot.

Properties

  • Reciprocal. Each robot does half of the avoidance; the apex of its obstacle is the average velocity, not the other robot's velocity.
  • No oscillation for mirrored pairs (theorem). A mirrored choice stays valid in the next step.
  • No collision guarantee in general. The same side condition is needed (theorem), and the penalty does not enforce it; the tests find over 100 pairs, out of 3000 random ones, where each choice is outside its own obstacle but the opposite sides collide.
  • Reactive and local. A robot plans only one velocity ahead, so it can be trapped in local minima such as a dead end.
  • Deterministic with the fixed grid and the tie rule; the paper's random samples make it randomized.

Variants and improvements

  • Optimal reciprocal collision avoidance. ORCA uses one half-plane per neighbor and solves a small linear program, which gives a guarantee and is faster than sampling.
  • Side rules. Later variants mix the plain and the reciprocal obstacle, or add a fixed bias to one side, so that two robots are less likely to pick opposite sides (heuristic).
  • Finite horizon. Counting only collisions within τ\tau seconds makes the obstacle a truncated cone, so far robots do not affect the choice.
  • Static obstacles. A plain velocity obstacle is used for obstacles that do not react.
  • Non-holonomic robots. Extensions restrict the candidates to velocities the robot can reach in one step.

When to use it

Use RVO for crowds of agents in games and crowd simulation, or for many small holonomic robots that sense each other but do not talk. It is simple to write and robust in practice. Use ORCA when a collision guarantee or more speed is needed, and use a planner for multi-agent pathfinding when the robots must get through narrow passages.

Pitfalls

  • Opposite sides. Two robots that choose opposite sides can still collide. Break symmetry the same way for all robots, for example by measuring sample directions from the preferred velocity, or by a small fixed bias to one side.
  • Mixed populations. The reciprocal assumption fails when the other agent does not run RVO, such as a person or a static obstacle. Use the plain velocity obstacle for them.
  • Sensing noise. The obstacle depends on the other robot's velocity, which is estimated. Add a margin to the radii.
  • Time step. The method assumes the new velocity is reached at once. A large Δt\Delta t or slow acceleration leaves a gap between the plan and the motion.
  • Weight. A small ω\omega lets robots come close for a small gain in speed; a large ω\omega makes them shy. Tune it for the density.

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.

reciprocal_velocity_obstacles.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/reciprocal-velocity-obstacles/. The authors are listed in prov/VJAYA8.jsonl.

"""Reciprocal velocity obstacles (RVO) for disc robots in the plane.

This follows van den Berg, Lin and Manocha (2008). The velocity obstacle of
robot A for a robot B is the set of velocities of A that lead to a collision
with B at some time if B keeps its velocity. The reciprocal velocity obstacle
moves the apex of that cone halfway: a new velocity v' of A is inside
RVO_A|B when 2 v' - v_A - v_B is a relative velocity that leads to a collision.

Each robot scores a fixed set of candidate velocities in its speed disc with
the penalty of the paper, weight / (time to collision) + |v' - v_pref|, and
takes the candidate with the smallest penalty. The paper draws random samples;
this file uses a fixed polar grid that is symmetric under v -> -v, so that two
robots in mirror image situations pick mirror image velocities. Vectors are
tuples (x, y). Robots are holonomic discs.
"""

import math
from typing import NamedTuple, Optional, Sequence


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])


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


def time_to_collision(rel_pos, rel_vel, rad) -> float:
    """First t >= 0 with |t * rel_vel - rel_pos| < rad, or inf if the discs never overlap.

    rel_pos is p_B - p_A and rel_vel is the velocity of A relative to B. A
    grazing contact, where the discs only touch, does not count.
    """
    c = dot(rel_pos, rel_pos) - rad * rad
    if c <= 0.0:
        return 0.0
    a = dot(rel_vel, rel_vel)
    b = dot(rel_pos, rel_vel)
    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


def rvo_relative_velocity(a: Agent, b: Agent, v) -> tuple:
    """The relative velocity 2 v - v_A - v_B that RVO_A|B tests."""
    return sub(sub(mul(v, 2.0), a.velocity), b.velocity)


def in_rvo(a: Agent, b: Agent, v) -> bool:
    """True if the candidate velocity v of A lies in RVO_A|B."""
    rel = sub(b.position, a.position)
    return time_to_collision(rel, rvo_relative_velocity(a, b, v), a.radius + b.radius) < math.inf


def candidates(agent: Agent, rings: int = 6, spokes: int = 32) -> list:
    """The preferred velocity (clipped to the speed disc) and a polar grid in the disc.

    The spokes are measured from the direction of the preferred velocity, so a
    robot whose preferred velocity is the negative of another's gets the
    negated list in the same order. Ties then break the same way for both.
    """
    pref = agent.pref
    n = norm(pref)
    if n > agent.vmax:
        pref = mul(pref, agent.vmax / n)
    u = (pref[0] / n, pref[1] / n) if n > 0.0 else (1.0, 0.0)
    out = [pref, (0.0, 0.0)]
    for i in range(1, rings + 1):
        s = agent.vmax * i / rings
        for k in range(spokes):
            th = 2.0 * math.pi * k / spokes
            c, d = math.cos(th), math.sin(th)
            out.append((s * (c * u[0] - d * u[1]), s * (d * u[0] + c * u[1])))
    return out


def penalty(agent: Agent, others: Sequence[Agent], v, weight: float) -> float:
    tc = math.inf  # @line L3
    for b in others:  # @line L4
        w = rvo_relative_velocity(agent, b, v)  # @line L5
        tc = min(tc, time_to_collision(sub(b.position, agent.position), w, agent.radius + b.radius))  # @line L6
    if tc == 0.0:
        return math.inf
    return weight / tc + norm(sub(v, agent.pref))  # @line L7


def new_velocity(agent: Agent, others: Sequence[Agent], weight: float = 1.0, rings: int = 6, spokes: int = 32) -> tuple:
    """The RVO velocity of one robot: the candidate with the smallest penalty.

    Ties go to the earlier candidate in the list.
    """
    best, best_v = math.inf, None
    for v in candidates(agent, rings, spokes):  # @line L2
        pen = penalty(agent, others, v, weight)
        if pen < best:
            best, best_v = pen, v
    if best_v is None:
        best_v = (0.0, 0.0)  # every candidate overlaps already: stop
    return best_v  # @line L8


def step(agents: Sequence[Agent], dt: float, weight: float = 1.0, sensing: Optional[float] = None,
         rings: int = 6, spokes: int = 32) -> list:
    """One synchronous step: every robot picks its velocity from the same snapshot, then all move."""
    new = []
    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)
        ]
        new.append(a._replace(velocity=new_velocity(a, others, weight, rings, spokes)))
    return [a._replace(position=add(a.position, mul(a.velocity, dt))) for a in new]  # @line L9
test_reciprocal_velocity_obstacles.py 168 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/reciprocal-velocity-obstacles/. The authors are listed in prov/VJAYA8.jsonl.

import math
import random

from reciprocal_velocity_obstacles import (
    Agent,
    candidates,
    det,
    dot,
    in_rvo,
    new_velocity,
    norm,
    step,
    sub,
    time_to_collision,
)


def in_cone(rel_pos, w, rad):
    """Reference test of the collision cone: the ray t w, t > 0, passes closer than rad to rel_pos."""
    if norm(w) == 0.0:
        return False
    return dot(w, rel_pos) > 0.0 and abs(det(w, rel_pos)) / norm(w) < rad


def legs(rel_pos, rad):
    """Unit directions of the left and right legs of the cone."""
    d = norm(rel_pos)
    alpha = math.asin(rad / d)
    base = math.atan2(rel_pos[1], rel_pos[0])
    return (math.cos(base + alpha), math.sin(base + alpha)), (math.cos(base - alpha), math.sin(base - alpha))


def random_pair(rng):
    a = Agent((0.0, 0.0), (rng.uniform(-1, 1), rng.uniform(-1, 1)), 0.5, 1.0, (1.0, 0.0))
    while True:
        p = (rng.uniform(-5, 5), rng.uniform(-5, 5))
        if norm(p) > 1.2:
            break
    b = Agent(p, (rng.uniform(-1, 1), rng.uniform(-1, 1)), 0.5, 1.0, (-1.0, 0.0))
    return a, b


def test_rvo_is_the_velocity_obstacle_with_its_apex_moved_halfway():
    rng = random.Random(1)
    inside = 0
    for _ in range(3000):
        a, b = random_pair(rng)
        v = (rng.uniform(-1.5, 1.5), rng.uniform(-1.5, 1.5))
        rel = sub(b.position, a.position)
        got = in_rvo(a, b, v)
        # v is in RVO_A|B exactly when 2 v - v_A is in the plain velocity obstacle of B.
        w = (2 * v[0] - a.velocity[0] - b.velocity[0], 2 * v[1] - a.velocity[1] - b.velocity[1])
        assert got == in_cone(rel, w, 1.0)
        inside += got
        # The apex (v_A + v_B) / 2 is never inside.
        apex = ((a.velocity[0] + b.velocity[0]) / 2, (a.velocity[1] + b.velocity[1]) / 2)
        assert not in_rvo(a, b, apex)
    assert 150 < inside < 2850


def test_same_side_choices_never_collide():
    rng = random.Random(2)
    opposite_collisions = 0
    for _ in range(3000):
        a, b = random_pair(rng)
        rel = sub(b.position, a.position)
        left, right = legs(rel, 1.0)

        def on_side(leg, sign):
            # A point in the closed half-plane beyond the leg line: sign det(leg, w) >= 0.
            while True:
                w = (rng.uniform(-3, 3), rng.uniform(-3, 3))
                if sign * det(leg, w) >= 0.0:
                    return w

        side = rng.choice([(left, 1.0), (right, -1.0)])
        wa, wb = on_side(*side), on_side(*side)
        va = ((wa[0] + a.velocity[0] + b.velocity[0]) / 2, (wa[1] + a.velocity[1] + b.velocity[1]) / 2)
        vb = ((a.velocity[0] + b.velocity[0] - wb[0]) / 2, (a.velocity[1] + b.velocity[1] - wb[1]) / 2)
        assert not in_rvo(a, b, va) and not in_rvo(b, a, vb)
        assert time_to_collision(rel, sub(va, vb), 1.0) == math.inf
        # Opposite sides: each choice is outside its own RVO, but the pair can still collide.
        wb2 = on_side(right, -1.0) if side[0] is left else on_side(left, 1.0)
        vb2 = ((a.velocity[0] + b.velocity[0] - wb2[0]) / 2, (a.velocity[1] + b.velocity[1] - wb2[1]) / 2)
        assert not in_rvo(b, a, vb2)
        if time_to_collision(rel, sub(va, vb2), 1.0) < math.inf:
            opposite_collisions += 1
    assert opposite_collisions > 100


def test_head_on_pair_turns_to_the_same_side():
    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))
    assert in_rvo(a, b, (1.0, 0.0))
    va, vb = new_velocity(a, [b]), new_velocity(b, [a])
    c, s = math.cos(math.pi / 8), math.sin(math.pi / 8)
    assert abs(va[0] - c) < 1e-12 and abs(va[1] - s) < 1e-12
    assert abs(vb[0] + c) < 1e-12 and abs(vb[1] + s) < 1e-12
    assert time_to_collision(sub(b.position, a.position), sub(va, vb), 1.0) == math.inf
    agents, closest, ys = [a, b], math.inf, []
    for _ in range(80):
        agents = step(agents, 0.1)
        closest = min(closest, norm(sub(agents[0].position, agents[1].position)))
        ys.append(agents[0].velocity[1])
    assert closest >= 1.0
    assert min(ys) >= 0.0  # A never swings back to the other side
    assert agents[0].velocity == (1.0, 0.0) and agents[1].velocity == (-1.0, 0.0)


def plain_vo_velocity(a, others):
    """The same penalty rule with the plain velocity obstacle (relative velocity v - v_B)."""
    best, best_v = math.inf, None
    for v in candidates(a):
        tc = min(time_to_collision(sub(b.position, a.position), sub(v, b.velocity), a.radius + b.radius) for b in others)
        pen = math.inf if tc == 0.0 else 1.0 / tc + norm(sub(v, a.pref))
        if pen < best:
            best, best_v = pen, v
    return best_v


def test_plain_velocity_obstacles_oscillate():
    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))
    straight = []
    for _ in range(10):
        va, vb = plain_vo_velocity(a, [b]), plain_vo_velocity(b, [a])
        a = a._replace(velocity=va, position=(a.position[0] + 0.1 * va[0], a.position[1] + 0.1 * va[1]))
        b = b._replace(velocity=vb, position=(b.position[0] + 0.1 * vb[0], b.position[1] + 0.1 * vb[1]))
        straight.append(va == (1.0, 0.0))
    assert straight == [False, True] * 5


def test_free_preferred_velocity_is_kept():
    rng = random.Random(6)
    for _ in range(300):
        a, b = random_pair(rng)
        a = a._replace(pref=(rng.uniform(-0.7, 0.7), rng.uniform(-0.7, 0.7)))  # inside the speed disc
        if not in_rvo(a, b, a.pref):
            assert new_velocity(a, [b]) == a.pref


def test_six_robots_swap_without_overlap():
    rng = random.Random(1)
    n, ring, rad = 6, 6.0, 0.4
    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]))
    arrived = False
    for _ in range(600):
        prefs = []
        for a, g in zip(agents, goals):
            d = sub(g, a.position)
            s = max(norm(d), 1.0)
            prefs.append(a._replace(pref=(d[0] / s, d[1] / s)))
        agents = step(prefs, 0.1, rings=4, spokes=16)
        for i in range(n):
            for k in range(i + 1, n):
                assert norm(sub(agents[i].position, agents[k].position)) >= 2 * rad
        if all(norm(sub(a.position, g)) < 0.15 for a, g in zip(agents, goals)):
            arrived = True
            break
    assert arrived

History

Fiorini and Shiller introduced velocity obstacles for a robot among moving obstacles in 1998. Van den Berg, Lin and Manocha presented reciprocal velocity obstacles at ICRA 2008 and showed it on crowd simulations with many agents. In the follow-up paper on reciprocal n-body collision avoidance, published in 2011, van den Berg, Guy, Lin and Manocha replaced the cones by half-planes and named the result ORCA.

References

  1. 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 definition of the reciprocal velocity obstacle, the same side and no oscillation results, and the penalty with sampled velocities)
  2. Jur van den Berg, Stephen J. Guy, Ming C. Lin and Dinesh Manocha, Reciprocal n-body collision avoidance, Robotics Research, Springer Tracts in Advanced Robotics 70, 2011, pages 3 to 19 (the discussion of RVO as the method that ORCA replaces)

Where this leads

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.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