Skip to content

Velocity obstacles

cuplan.VelocityObstacleSim — decentralized collision avoidance with velocity obstacles (Fiorini and Shiller 1998, Motion planning in dynamic environments using velocity obstacles, IJRR 17(7)), mirroring pymapf.decentralized.velocity_obstacle.

Semantics

Each timestep, each agent:

  1. computes a desired velocity — full speed toward its goal, zero once within radius / 5 of it;
  2. builds, for every other agent and moving obstacle, a collision cone widened to 2.2 x radius and translated by that obstacle's velocity, expressed as two half-planes;
  3. samples candidate velocities on a polar grid (20 angles x 5 speeds by default, as in pymapf), discards samples inside any cone, and takes the feasible sample closest to the desired velocity — or stops when nothing is feasible.

One deliberate difference from pymapf

Updates are synchronous: all agents choose against the same snapshot of the world, then move together. pymapf updates agents in registration order within a timestep — earlier agents do not see later ones at all. The synchronous rule is order-independent, which is what makes it parallel, and is the standard formulation of the decentralized problem. Because the two simulators integrate different dynamics, the benchmark reports cuplan CPU vs CUDA only for this family rather than a misleading cross-library wall-clock number.

Parallelization

Every (agent, sample) pair is independent — the step is one embarrassingly parallel evaluation:

  • CPU reference — one broadcast expression over (agents, others, samples).
  • CUDA — one thread per (agent, sample), looping over the others; the per-agent argmin is a device-side reduction.

CPU and CUDA trajectories agree to floating-point tolerance (tested).

Decentralized collision avoidance with velocity obstacles.

Mirrors pymapf.decentralized.velocity_obstacle (Fiorini and Shiller 1998): each agent samples candidate velocities on a polar grid, discards those inside any neighbour's collision cone — widened to 2.2 x radius and translated by the neighbour's velocity, expressed as a pair of half-planes — and takes the feasible sample closest to its desired velocity toward the goal.

Every (agent, sample) pair is independent: the whole step is one embarrassingly parallel evaluation, n_agents x n_samples threads on the CUDA backend, one broadcast expression on the NumPy one.

One deliberate difference from pymapf: updates are synchronous. All agents choose their velocity against the same snapshot of the world, then move together. pymapf updates agents in registration order inside a timestep, so earlier agents ignore later ones; the synchronous rule is order-independent, which is what makes it parallel — and is also the standard formulation of the decentralized problem.

VOResult dataclass

Trajectories and summary metrics of a velocity-obstacle run.

Source code in cuplan/velocity_obstacles.py
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
@dataclass
class VOResult:
    """Trajectories and summary metrics of a velocity-obstacle run."""

    positions: np.ndarray  # (T+1, n_agents, 2)
    velocities: np.ndarray  # (T, n_agents, 2)
    runtime: float
    backend: str
    extra: dict = field(default_factory=dict)

    def goals_reached(self, goals: np.ndarray, tolerance: float) -> int:
        """Number of agents ending within ``tolerance`` of their goal."""
        final = self.positions[-1]
        return int(
            (np.linalg.norm(final - goals, axis=1) <= tolerance).sum()
        )

    def min_separation(self) -> float:
        """Smallest pairwise agent distance over the whole run."""
        n = self.positions.shape[1]
        if n < 2:
            return float("inf")
        best = np.inf
        for frame in self.positions:
            diff = frame[:, None, :] - frame[None, :, :]
            dist = np.linalg.norm(diff, axis=-1)
            dist[np.arange(n), np.arange(n)] = np.inf
            best = min(best, float(dist.min()))
        return best

goals_reached

goals_reached(goals, tolerance)

Number of agents ending within tolerance of their goal.

Source code in cuplan/velocity_obstacles.py
44
45
46
47
48
49
def goals_reached(self, goals: np.ndarray, tolerance: float) -> int:
    """Number of agents ending within ``tolerance`` of their goal."""
    final = self.positions[-1]
    return int(
        (np.linalg.norm(final - goals, axis=1) <= tolerance).sum()
    )

min_separation

min_separation()

Smallest pairwise agent distance over the whole run.

Source code in cuplan/velocity_obstacles.py
51
52
53
54
55
56
57
58
59
60
61
62
def min_separation(self) -> float:
    """Smallest pairwise agent distance over the whole run."""
    n = self.positions.shape[1]
    if n < 2:
        return float("inf")
    best = np.inf
    for frame in self.positions:
        diff = frame[:, None, :] - frame[None, :, :]
        dist = np.linalg.norm(diff, axis=-1)
        dist[np.arange(n), np.arange(n)] = np.inf
        best = min(best, float(dist.min()))
    return best

VelocityObstacleSim

Multi-agent velocity-obstacle simulation.

Parameters:

Name Type Description Default
timestep float

integration step in seconds.

0.1
radius float

agent radius; the collision cone uses 2.2 x radius, as in pymapf.

0.5
vmax float

maximum speed; also the desired cruise speed toward the goal.

2.0
n_angles int

angular resolution of the velocity sample grid.

20
n_speeds int

radial resolution of the velocity sample grid.

5
backend Backend

"auto", "cpu" or "cuda".

'auto'

pymapf samples 20 angles x 5 speeds; the defaults match.

Source code in cuplan/velocity_obstacles.py
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
class VelocityObstacleSim:
    """Multi-agent velocity-obstacle simulation.

    Args:
        timestep: integration step in seconds.
        radius: agent radius; the collision cone uses ``2.2 x radius``,
            as in pymapf.
        vmax: maximum speed; also the desired cruise speed toward the
            goal.
        n_angles: angular resolution of the velocity sample grid.
        n_speeds: radial resolution of the velocity sample grid.
        backend: ``"auto"``, ``"cpu"`` or ``"cuda"``.

    pymapf samples 20 angles x 5 speeds; the defaults match.
    """

    def __init__(
        self,
        timestep: float = 0.1,
        radius: float = 0.5,
        vmax: float = 2.0,
        n_angles: int = 20,
        n_speeds: int = 5,
        backend: Backend = "auto",
        profile: bool = False,
    ):
        self.timestep = float(timestep)
        self.radius = float(radius)
        self.vmax = float(vmax)
        self.backend = backend
        #: When True and the backend is CUDA, ``run`` reports per-phase
        #: wall times (``h2d``/``kernel``/``d2h``/``host``, seconds,
        #: summed over steps) in ``VOResult.extra``. Phase boundaries
        #: are device syncs, so profiled totals run slightly slower.
        self.profile = bool(profile)
        self._starts: list[np.ndarray] = []
        self._goals: list[np.ndarray] = []
        self._obstacles: list[tuple[np.ndarray, np.ndarray]] = []
        angles = np.linspace(0.0, 2.0 * np.pi, n_angles)
        speeds = np.linspace(0.0, self.vmax, n_speeds)
        vv, aa = np.meshgrid(speeds, angles)
        self._samples = np.stack(
            [(vv * np.cos(aa)).ravel(), (vv * np.sin(aa)).ravel()], axis=1
        )

    def add_agent(self, start, goal) -> None:
        """Register an agent by start and goal position (2D)."""
        self._starts.append(np.asarray(start, dtype=np.float64))
        self._goals.append(np.asarray(goal, dtype=np.float64))

    def add_obstacle(self, position, velocity) -> None:
        """Register a moving obstacle with constant velocity."""
        self._obstacles.append(
            (
                np.asarray(position, dtype=np.float64),
                np.asarray(velocity, dtype=np.float64),
            )
        )

    @property
    def goals(self) -> np.ndarray:
        """``(n_agents, 2)`` goal positions."""
        return np.stack(self._goals) if self._goals else np.empty((0, 2))

    def run(self, n_steps: int) -> VOResult:
        """Simulate ``n_steps`` timesteps and return the trajectories."""
        if not self._starts:
            raise ValueError("register at least one agent before running")
        started = time.perf_counter()
        which = resolve_backend(self.backend)
        n = len(self._starts)
        pos = np.stack(self._starts)
        vel = np.zeros((n, 2))
        goals = self.goals
        positions = [pos.copy()]
        velocities = []

        timings: dict[str, float] = {}
        if which == "cuda":
            step = self._make_cuda_step(
                timings if self.profile else None
            )
        else:
            step = self._step_cpu

        for k in range(n_steps):
            desired = self._desired_velocity(pos, goals)
            others = self._world_snapshot(pos, vel, k)
            vel = step(pos, vel, desired, others)
            pos = pos + vel * self.timestep
            positions.append(pos.copy())
            velocities.append(vel.copy())

        runtime = time.perf_counter() - started
        extra: dict = {}
        if timings:
            device = sum(timings.values())
            extra = dict(timings, host=max(runtime - device, 0.0))
        return VOResult(
            positions=np.stack(positions),
            velocities=np.stack(velocities),
            runtime=runtime,
            backend=which,
            extra=extra,
        )

    # -- shared pieces ---------------------------------------------------

    def _desired_velocity(self, pos: np.ndarray, goals: np.ndarray) -> np.ndarray:
        """Full speed toward the goal; zero within ``radius / 5`` of it."""
        disp = goals - pos
        norm = np.linalg.norm(disp, axis=1, keepdims=True)
        with np.errstate(invalid="ignore", divide="ignore"):
            unit = np.where(norm > 1e-12, disp / norm, 0.0)
        desired = self.vmax * unit
        desired[norm[:, 0] < self.radius / 5.0] = 0.0
        return desired

    def _world_snapshot(
        self, pos: np.ndarray, vel: np.ndarray, k: int
    ) -> np.ndarray:
        """``(n_agents + n_obstacles, 4)`` states every agent plans against."""
        rows = [np.concatenate([pos, vel], axis=1)]
        for p0, v in self._obstacles:
            rows.append(
                np.concatenate([p0 + v * k * self.timestep, v])[None, :]
            )
        return np.concatenate(rows, axis=0)

    # -- CPU reference ---------------------------------------------------

    def _step_cpu(
        self,
        pos: np.ndarray,
        vel: np.ndarray,
        desired: np.ndarray,
        others: np.ndarray,
    ) -> np.ndarray:
        """Vectorized half-plane feasibility over (agent, other, sample)."""
        n = len(pos)
        samples = self._samples  # (S, 2)
        margin = 2.2 * self.radius

        disp = pos[:, None, :] - others[None, :, :2]  # (n, K, 2)
        dist = np.maximum(np.linalg.norm(disp, axis=-1), margin)
        theta = np.arctan2(disp[..., 1], disp[..., 0])
        half = np.arcsin(np.clip(margin / dist, -1.0, 1.0))
        phi_l = theta + half  # (n, K)
        phi_r = theta - half

        rv = samples[None, :, :] - others[:, None, 2:]  # (K, S, 2)
        left = (
            np.sin(phi_l)[:, :, None] * rv[None, :, :, 0]
            - np.cos(phi_l)[:, :, None] * rv[None, :, :, 1]
        )  # (n, K, S)
        right = (
            np.sin(phi_r)[:, :, None] * rv[None, :, :, 0]
            - np.cos(phi_r)[:, :, None] * rv[None, :, :, 1]
        )
        inside = (left < 0.0) & (right > 0.0)
        inside[np.arange(n), np.arange(n), :] = False  # ignore self
        feasible = ~inside.any(axis=1)  # (n, S)

        objective = np.linalg.norm(
            samples[None, :, :] - desired[:, None, :], axis=-1
        )
        objective[~feasible] = np.inf
        best = np.argmin(objective, axis=1)
        chosen = samples[best]
        chosen[~np.isfinite(objective[np.arange(n), best])] = 0.0
        return chosen

    # -- CUDA backend ----------------------------------------------------

    def _make_cuda_step(self, timings: dict | None = None):
        import cupy

        from .kernels import get_kernel

        kernel = get_kernel("velocity_obstacles", "score_samples")
        samples_d = cupy.asarray(self._samples)
        n_samples = len(self._samples)
        radius = self.radius
        samples_h = self._samples
        sync = cupy.cuda.get_current_stream().synchronize

        def tick(phase, mark):
            sync()
            now = time.perf_counter()
            timings[phase] = timings.get(phase, 0.0) + now - mark
            return now

        def step(pos, vel, desired, others):
            n = len(pos)
            if timings is not None:
                sync()
                mark = time.perf_counter()
            states = cupy.asarray(np.concatenate([pos, vel], axis=1))
            others_d = cupy.asarray(others)
            desired_d = cupy.asarray(desired)
            self_index = cupy.arange(n, dtype=cupy.int32)
            scores = cupy.empty((n, n_samples), dtype=cupy.float64)
            if timings is not None:
                mark = tick("h2d", mark)
            threads = 256
            blocks = min(
                65535, (n * n_samples + threads - 1) // threads
            )
            kernel(
                (blocks,),
                (threads,),
                (
                    states,
                    desired_d,
                    others_d,
                    self_index,
                    samples_d,
                    scores,
                    np.int32(n),
                    np.int32(len(others)),
                    np.int32(n_samples),
                    np.float64(radius),
                ),
            )
            best_d = cupy.argmin(scores, axis=1)
            mins_d = scores.min(axis=1)
            if timings is not None:
                mark = tick("kernel", mark)
            best = cupy.asnumpy(best_d)
            mins = cupy.asnumpy(mins_d)
            if timings is not None:
                tick("d2h", mark)
            chosen = samples_h[best]
            chosen[~np.isfinite(mins)] = 0.0
            return chosen

        return step

goals property

goals

(n_agents, 2) goal positions.

add_agent

add_agent(start, goal)

Register an agent by start and goal position (2D).

Source code in cuplan/velocity_obstacles.py
110
111
112
113
def add_agent(self, start, goal) -> None:
    """Register an agent by start and goal position (2D)."""
    self._starts.append(np.asarray(start, dtype=np.float64))
    self._goals.append(np.asarray(goal, dtype=np.float64))

add_obstacle

add_obstacle(position, velocity)

Register a moving obstacle with constant velocity.

Source code in cuplan/velocity_obstacles.py
115
116
117
118
119
120
121
122
def add_obstacle(self, position, velocity) -> None:
    """Register a moving obstacle with constant velocity."""
    self._obstacles.append(
        (
            np.asarray(position, dtype=np.float64),
            np.asarray(velocity, dtype=np.float64),
        )
    )

run

run(n_steps)

Simulate n_steps timesteps and return the trajectories.

Source code in cuplan/velocity_obstacles.py
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
def run(self, n_steps: int) -> VOResult:
    """Simulate ``n_steps`` timesteps and return the trajectories."""
    if not self._starts:
        raise ValueError("register at least one agent before running")
    started = time.perf_counter()
    which = resolve_backend(self.backend)
    n = len(self._starts)
    pos = np.stack(self._starts)
    vel = np.zeros((n, 2))
    goals = self.goals
    positions = [pos.copy()]
    velocities = []

    timings: dict[str, float] = {}
    if which == "cuda":
        step = self._make_cuda_step(
            timings if self.profile else None
        )
    else:
        step = self._step_cpu

    for k in range(n_steps):
        desired = self._desired_velocity(pos, goals)
        others = self._world_snapshot(pos, vel, k)
        vel = step(pos, vel, desired, others)
        pos = pos + vel * self.timestep
        positions.append(pos.copy())
        velocities.append(vel.copy())

    runtime = time.perf_counter() - started
    extra: dict = {}
    if timings:
        device = sum(timings.values())
        extra = dict(timings, host=max(runtime - device, 0.0))
    return VOResult(
        positions=np.stack(positions),
        velocities=np.stack(velocities),
        runtime=runtime,
        backend=which,
        extra=extra,
    )