Skip to content

bikeped.scenarios

The scenario registry and generators. Scenarios explains the format and the suites.

cli

Command line interface: python -m bikeped.scenarios COMMAND.

Run from the repository root so that decision_testbench is importable.

build_parser

build_parser() -> argparse.ArgumentParser

Argument parser for all subcommands.

Source code in bikeped/scenarios/cli.py
def build_parser() -> argparse.ArgumentParser:
    """Argument parser for all subcommands."""
    from .generators import FAMILIES

    p = argparse.ArgumentParser(
        prog='python -m bikeped.scenarios',
        description='List, check, evaluate, generate and export bike-pedestrian scenarios. '
                    'Suites: ' + ', '.join(list_suites()) + '.')
    sub = p.add_subparsers(dest='command', required=True, metavar='COMMAND')

    sp = sub.add_parser('list', help='list scenarios with suite, family, agents and duration')
    sp.add_argument('--suite', help='only this suite')
    sp.add_argument('--family', help='only this family')
    sp.add_argument('--json', action='store_true', help='print metadata as JSON')
    sp.set_defaults(func=_cmd_list)

    sp = sub.add_parser('show', help='print one scenario as JSON')
    sp.add_argument('id', metavar='ID',
                    help="slug, exact name, or suite:index with a zero-based index "
                         "(e.g. conformance:7)")
    sp.set_defaults(func=_cmd_show)

    sp = sub.add_parser('validate', help='check format, speeds and unique ids; exit 1 on problems')
    sp.add_argument('--suite', help='only this suite (ids are checked for uniqueness within it)')
    sp.set_defaults(func=_cmd_validate)

    sp = sub.add_parser(
        'evaluate', help='run the decision pipeline with ideal perception and summarise',
        description='Simulate each scenario with decision_testbench.simulate_scenario and print '
                    'ground-truth danger time, alert time, false-alert time, the lead of the '
                    'alert over each danger interval (negative means late) and the dominant '
                    'state against the expected one.')
    sp.add_argument('--suite', help='only this suite (default: all registered suites)')
    sp.add_argument('--config', default='default',
                    help='key of decision_testbench.PIPELINE_CONFIGS (default: default)')
    sp.add_argument('--json', action='store_true', help='print rows as JSON')
    sp.set_defaults(func=_cmd_evaluate)

    sp = sub.add_parser('generate', help='write a seeded parametric suite as JSON',
                        description='Families: ' + '; '.join(f'{k}: {v}'
                                                             for k, v in FAMILIES.items()))
    sp.add_argument('--family', required=True, choices=list(FAMILIES))
    sp.add_argument('--n', type=int, default=20, help='number of scenarios (default 20)')
    sp.add_argument('--seed', type=int, default=0, help='random seed (default 0)')
    sp.add_argument('--out', default='-', help='output JSON file, - for stdout (default)')
    sp.set_defaults(func=_cmd_generate)

    sp = sub.add_parser('export', help='write catalog.json and one SVG thumbnail per scenario')
    sp.add_argument('--out', required=True, help='output directory')
    sp.add_argument('--simulator', metavar='DIR',
                    help='also write DIR/scenarios.extended.js for the browser simulator')
    sp.set_defaults(func=_cmd_export)
    return p

main

main(argv: list[str] | None = None) -> int

Parse argv and run the chosen command; returns the exit status.

Source code in bikeped/scenarios/cli.py
def main(argv: list[str] | None = None) -> int:
    """Parse ``argv`` and run the chosen command; returns the exit status."""
    args = build_parser().parse_args(argv)
    return int(args.func(args))

builders

Path builders that emit the testbench waypoint format.

Every builder works in the scenario frame used by decision_testbench: metres, x along the road (bikes ride along it), y across the road (pedestrians cross along it), crosswalk centre at (5, 0). Times are seconds from the start of the scenario and speeds are metres per second.

The testbench interpolates paths linearly in time, so curved or speed-varying motion is sampled densely (every step seconds, 0.25 s by default). Headings are in degrees, counter-clockwise from +x: 0 rides towards +x, 180 towards -x (the direction of the conformance bikes), 90 walks towards +y.

The fluent :class:Path keeps scenario definitions short::

bike = (Path.start(34, 1.5, heading=180).ride(14, 6.0)
        .arc(radius=6, angle=90).ride(8).build())

Path

Path(
    x: float,
    y: float,
    t: float = 0.0,
    heading: float = 0.0,
    speed: float = 0.0,
    step: float = 0.25,
)

Fluent builder for one agent path.

The builder tracks the current position (x, y) in metres, time t in seconds, heading in degrees and speed in m/s. Each motion primitive appends waypoints sampled every step seconds and leaves the state at its end, so primitives chain. :meth:build returns the waypoint list with strictly increasing times.

Source code in bikeped/scenarios/builders.py
def __init__(self, x: float, y: float, t: float = 0.0, heading: float = 0.0,
             speed: float = 0.0, step: float = 0.25) -> None:
    self.x, self.y, self.t = float(x), float(y), float(t)
    self.heading = float(heading)
    self.speed = float(speed)
    self.step = float(step)
    self._points: list[tuple[float, float, float]] = [(self.x, self.y, self.t)]

start classmethod

start(
    x: float,
    y: float,
    t: float = 0.0,
    heading: float = 0.0,
    speed: float = 0.0,
    step: float = 0.25,
) -> Path

Start a path at (x, y) at time t (s), facing heading (deg).

Source code in bikeped/scenarios/builders.py
@classmethod
def start(cls, x: float, y: float, t: float = 0.0, heading: float = 0.0,
          speed: float = 0.0, step: float = 0.25) -> Path:
    """Start a path at ``(x, y)`` at time ``t`` (s), facing ``heading`` (deg)."""
    return cls(x, y, t, heading, speed, step)

ride

ride(distance: float, speed: float | None = None) -> Path

Move distance metres along the current heading at constant speed (m/s).

Source code in bikeped/scenarios/builders.py
def ride(self, distance: float, speed: float | None = None) -> Path:
    """Move ``distance`` metres along the current heading at constant ``speed`` (m/s)."""
    if speed is not None:
        self.speed = float(speed)
    if self.speed <= 0:
        raise ValueError('ride() needs a positive speed')
    ux, uy = self._unit()
    x0, y0, t0 = self.x, self.y, self.t
    dur = distance / self.speed
    n = max(1, math.ceil(dur / self.step))
    for i in range(1, n + 1):
        f = i / n
        self._emit(x0 + ux * distance * f, y0 + uy * distance * f, t0 + dur * f)
    return self

to

to(x: float, y: float, speed: float | None = None) -> Path

Move in a straight line to (x, y) at constant speed; the heading follows.

Source code in bikeped/scenarios/builders.py
def to(self, x: float, y: float, speed: float | None = None) -> Path:
    """Move in a straight line to ``(x, y)`` at constant ``speed``; the heading follows."""
    dx, dy = x - self.x, y - self.y
    dist = math.hypot(dx, dy)
    if dist < 1e-9:
        return self
    self.heading = math.degrees(math.atan2(dy, dx))
    return self.ride(dist, speed)

face

face(heading: float) -> Path

Set the heading (deg) without moving.

Source code in bikeped/scenarios/builders.py
def face(self, heading: float) -> Path:
    """Set the heading (deg) without moving."""
    self.heading = float(heading)
    return self

wait

wait(duration: float) -> Path

Stand still for duration seconds; the speed becomes zero.

Source code in bikeped/scenarios/builders.py
def wait(self, duration: float) -> Path:
    """Stand still for ``duration`` seconds; the speed becomes zero."""
    self.speed = 0.0
    self._emit(self.x, self.y, self.t + duration)
    return self

appear

appear(t: float) -> Path

Shift the whole path so that it begins at time t.

Use it for late emergence: the agent is absent (not detected) until t, as if hidden behind a parked van or a crowd. Call it before any motion primitive.

Source code in bikeped/scenarios/builders.py
def appear(self, t: float) -> Path:
    """Shift the whole path so that it begins at time ``t``.

    Use it for late emergence: the agent is absent (not detected) until ``t``, as if hidden
    behind a parked van or a crowd. Call it before any motion primitive.
    """
    if len(self._points) != 1:
        raise ValueError('appear() must be called before the first motion')
    self.t = float(t)
    self._points = [(self.x, self.y, self.t)]
    return self

change_speed

change_speed(v_end: float, accel: float) -> Path

Accelerate or brake along the heading to v_end m/s at |accel| m/s^2.

The distance covered follows from constant acceleration; the path ends with speed == v_end. Braking to zero leaves the agent stopped at the end point.

Source code in bikeped/scenarios/builders.py
def change_speed(self, v_end: float, accel: float) -> Path:
    """Accelerate or brake along the heading to ``v_end`` m/s at ``|accel|`` m/s^2.

    The distance covered follows from constant acceleration; the path ends with
    ``speed == v_end``. Braking to zero leaves the agent stopped at the end point.
    """
    a = abs(float(accel))
    v0 = self.speed
    if a <= 0 or abs(v_end - v0) < 1e-9:
        return self
    sign = 1.0 if v_end > v0 else -1.0
    dur = abs(v_end - v0) / a
    ux, uy = self._unit()
    x0, y0, t0 = self.x, self.y, self.t
    n = max(1, math.ceil(dur / self.step))
    for i in range(1, n + 1):
        tt = dur * i / n
        s = v0 * tt + 0.5 * sign * a * tt * tt
        self._emit(x0 + ux * s, y0 + uy * s, t0 + tt)
    self.speed = float(v_end)
    return self

accelerate

accelerate(v_end: float, accel: float = 1.5) -> Path

Speed up to v_end m/s at accel m/s^2 along the heading.

Source code in bikeped/scenarios/builders.py
def accelerate(self, v_end: float, accel: float = 1.5) -> Path:
    """Speed up to ``v_end`` m/s at ``accel`` m/s^2 along the heading."""
    return self.change_speed(v_end, accel)

brake

brake(v_end: float = 0.0, decel: float = 2.0) -> Path

Slow down to v_end m/s (default a full stop) at decel m/s^2.

Source code in bikeped/scenarios/builders.py
def brake(self, v_end: float = 0.0, decel: float = 2.0) -> Path:
    """Slow down to ``v_end`` m/s (default a full stop) at ``decel`` m/s^2."""
    return self.change_speed(v_end, decel)

brake_to

brake_to(x: float | None = None, y: float | None = None, v_end: float = 0.0) -> Path

Brake at constant deceleration so the agent reaches v_end at a given coordinate.

Give x (for agents moving along the road) or y (for agents moving across it). The deceleration is whatever stops the agent exactly there.

Source code in bikeped/scenarios/builders.py
def brake_to(self, x: float | None = None, y: float | None = None,
             v_end: float = 0.0) -> Path:
    """Brake at constant deceleration so the agent reaches ``v_end`` at a given coordinate.

    Give ``x`` (for agents moving along the road) or ``y`` (for agents moving across it). The
    deceleration is whatever stops the agent exactly there.
    """
    ux, uy = self._unit()
    if x is not None:
        dist = (x - self.x) / ux if abs(ux) > 1e-6 else math.nan
    elif y is not None:
        dist = (y - self.y) / uy if abs(uy) > 1e-6 else math.nan
    else:
        raise ValueError('brake_to() needs x or y')
    if not dist > 0:
        raise ValueError('brake_to() target lies behind the agent')
    decel = (self.speed ** 2 - v_end ** 2) / (2.0 * dist)
    if decel <= 0:
        raise ValueError('brake_to() needs v_end below the current speed')
    return self.change_speed(v_end, decel)

arc

arc(radius: float, angle: float, speed: float | None = None) -> Path

Turn on a circular arc of radius metres through angle degrees.

Positive angles turn left (counter-clockwise seen from above, +y up), negative angles turn right. Speed is constant along the arc.

Source code in bikeped/scenarios/builders.py
def arc(self, radius: float, angle: float, speed: float | None = None) -> Path:
    """Turn on a circular arc of ``radius`` metres through ``angle`` degrees.

    Positive angles turn left (counter-clockwise seen from above, ``+y`` up), negative angles
    turn right. Speed is constant along the arc.
    """
    if speed is not None:
        self.speed = float(speed)
    if self.speed <= 0:
        raise ValueError('arc() needs a positive speed')
    sgn = 1.0 if angle >= 0 else -1.0
    h0 = math.radians(self.heading)
    cx = self.x - sgn * radius * math.sin(h0)
    cy = self.y + sgn * radius * math.cos(h0)
    length = radius * math.radians(abs(angle))
    dur = length / self.speed
    n = max(2, math.ceil(dur / self.step))
    t0 = self.t
    for i in range(1, n + 1):
        phi = h0 + sgn * math.radians(abs(angle)) * i / n
        self._emit(cx + sgn * radius * math.sin(phi), cy - sgn * radius * math.cos(phi),
                   t0 + dur * i / n)
    self.heading += angle
    return self

lane_change

lane_change(lateral: float, length: float, speed: float | None = None) -> Path

Shift sideways by lateral metres (positive to the left) over length metres.

The lateral offset follows a half-cosine, which gives a smooth swerve or lane change; the heading is unchanged at the end.

Source code in bikeped/scenarios/builders.py
def lane_change(self, lateral: float, length: float, speed: float | None = None) -> Path:
    """Shift sideways by ``lateral`` metres (positive to the left) over ``length`` metres.

    The lateral offset follows a half-cosine, which gives a smooth swerve or lane change; the
    heading is unchanged at the end.
    """
    if speed is not None:
        self.speed = float(speed)
    ux, uy = self._unit()
    lx, ly = -uy, ux
    x0, y0, t0 = self.x, self.y, self.t
    dur = math.hypot(length, lateral) / self.speed
    n = max(4, math.ceil(dur / self.step))
    for i in range(1, n + 1):
        f = i / n
        off = lateral * 0.5 * (1.0 - math.cos(math.pi * f))
        self._emit(x0 + ux * length * f + lx * off, y0 + uy * length * f + ly * off,
                   t0 + dur * f)
    return self

zigzag

zigzag(
    distance: float, amplitude: float, wavelength: float, speed: float | None = None
) -> Path

Weave about the current heading: sinusoidal lateral offset of amplitude metres.

The agent covers distance metres along the heading; one full weave takes wavelength metres. Speed is the speed along the heading.

Source code in bikeped/scenarios/builders.py
def zigzag(self, distance: float, amplitude: float, wavelength: float,
           speed: float | None = None) -> Path:
    """Weave about the current heading: sinusoidal lateral offset of ``amplitude`` metres.

    The agent covers ``distance`` metres along the heading; one full weave takes
    ``wavelength`` metres. Speed is the speed along the heading.
    """
    if speed is not None:
        self.speed = float(speed)
    ux, uy = self._unit()
    lx, ly = -uy, ux
    x0, y0, t0 = self.x, self.y, self.t
    dur = distance / self.speed
    n = max(4, math.ceil(dur / self.step))
    for i in range(1, n + 1):
        s = distance * i / n
        off = amplitude * math.sin(2.0 * math.pi * s / wavelength)
        self._emit(x0 + ux * s + lx * off, y0 + uy * s + ly * off, t0 + dur * i / n)
    return self

through

through(points: Sequence[tuple[float, float]], speed: float | None = None) -> Path

Follow a Catmull-Rom spline from the current position through points at speed.

The spline passes through every control point. Arc length is resampled so the speed is constant; the heading at the end follows the last segment.

Source code in bikeped/scenarios/builders.py
def through(self, points: Sequence[tuple[float, float]], speed: float | None = None) -> Path:
    """Follow a Catmull-Rom spline from the current position through ``points`` at ``speed``.

    The spline passes through every control point. Arc length is resampled so the speed is
    constant; the heading at the end follows the last segment.
    """
    if speed is not None:
        self.speed = float(speed)
    xy = catmull_rom([(self.x, self.y), *points], samples_per_segment=24)
    seg = np.hypot(np.diff(xy[:, 0]), np.diff(xy[:, 1]))
    s = np.concatenate([[0.0], np.cumsum(seg)])
    total = float(s[-1])
    dur = total / self.speed
    n = max(2, math.ceil(dur / self.step))
    t0 = self.t
    for i in range(1, n + 1):
        si = total * i / n
        self._emit(float(np.interp(si, s, xy[:, 0])), float(np.interp(si, s, xy[:, 1])),
                   t0 + dur * i / n)
    dx, dy = xy[-1] - xy[-2]
    self.heading = math.degrees(math.atan2(dy, dx))
    return self

build

build() -> list[Waypoint]

Return the path as testbench waypoints [{'x', 'y', 't'}, ...] (rounded to mm, ms).

Source code in bikeped/scenarios/builders.py
def build(self) -> list[Waypoint]:
    """Return the path as testbench waypoints ``[{'x', 'y', 't'}, ...]`` (rounded to mm, ms)."""
    out: list[Waypoint] = []
    for x, y, t in self._points:
        p = {'x': _round(x), 'y': _round(y), 't': _round(t)}
        if out and p['t'] <= out[-1]['t']:
            continue
        out.append(p)
    if len(out) < 2:
        raise ValueError('a path needs at least two waypoints with increasing time')
    return out

catmull_rom

catmull_rom(
    points: Sequence[tuple[float, float]], samples_per_segment: int = 16
) -> np.ndarray

Sample a centripetal-free (uniform) Catmull-Rom spline through points.

Returns an (N, 2) array in the same units as the input. End points are duplicated so the curve starts and ends exactly at the first and last control points.

Source code in bikeped/scenarios/builders.py
def catmull_rom(points: Sequence[tuple[float, float]], samples_per_segment: int = 16) -> np.ndarray:
    """Sample a centripetal-free (uniform) Catmull-Rom spline through ``points``.

    Returns an ``(N, 2)`` array in the same units as the input. End points are duplicated so the
    curve starts and ends exactly at the first and last control points.
    """
    p = np.asarray(points, dtype=float)
    if len(p) < 2:
        raise ValueError('catmull_rom() needs at least two points')
    ext = np.vstack([p[0], p, p[-1]])
    out = [p[0]]
    for i in range(1, len(ext) - 2):
        p0, p1, p2, p3 = ext[i - 1], ext[i], ext[i + 1], ext[i + 2]
        for k in range(1, samples_per_segment + 1):
            u = k / samples_per_segment
            u2, u3 = u * u, u * u * u
            out.append(0.5 * ((2 * p1) + (-p0 + p2) * u + (2 * p0 - 5 * p1 + 4 * p2 - p3) * u2
                              + (-p0 + 3 * p1 - 3 * p2 + p3) * u3))
    return np.asarray(out)

straight

straight(
    x0: float, y0: float, x1: float, y1: float, speed: float, t0: float = 0.0
) -> list[Waypoint]

Constant-speed straight leg from (x0, y0) to (x1, y1) starting at t0.

Source code in bikeped/scenarios/builders.py
def straight(x0: float, y0: float, x1: float, y1: float, speed: float,
             t0: float = 0.0) -> list[Waypoint]:
    """Constant-speed straight leg from ``(x0, y0)`` to ``(x1, y1)`` starting at ``t0``."""
    return Path.start(x0, y0, t0).to(x1, y1, speed).build()

crossing

crossing(
    x: float = 5.0,
    y0: float = -6.0,
    y1: float = 6.0,
    speed: float = 1.35,
    t0: float = 0.0,
) -> list[Waypoint]

Pedestrian crossing along y at road position x at constant speed.

Source code in bikeped/scenarios/builders.py
def crossing(x: float = 5.0, y0: float = -6.0, y1: float = 6.0, speed: float = 1.35,
             t0: float = 0.0) -> list[Waypoint]:
    """Pedestrian crossing along ``y`` at road position ``x`` at constant ``speed``."""
    return straight(x, y0, x, y1, speed, t0)

shift

shift(
    path: Sequence[Waypoint], dx: float = 0.0, dy: float = 0.0, dt: float = 0.0
) -> list[Waypoint]

Return a copy of path translated by (dx, dy) metres and dt seconds.

Source code in bikeped/scenarios/builders.py
def shift(path: Sequence[Waypoint], dx: float = 0.0, dy: float = 0.0,
          dt: float = 0.0) -> list[Waypoint]:
    """Return a copy of ``path`` translated by ``(dx, dy)`` metres and ``dt`` seconds."""
    return [{'x': _round(p['x'] + dx), 'y': _round(p['y'] + dy), 't': _round(p['t'] + dt)}
            for p in path]

group

group(
    path: Sequence[Waypoint], offsets: Sequence[tuple[float, float, float]]
) -> list[list[Waypoint]]

Copies of path for a group that moves together, one per (dx, dy, dt) offset.

Source code in bikeped/scenarios/builders.py
def group(path: Sequence[Waypoint], offsets: Sequence[tuple[float, float, float]]
          ) -> list[list[Waypoint]]:
    """Copies of ``path`` for a group that moves together, one per ``(dx, dy, dt)`` offset."""
    return [shift(path, dx, dy, dt) for dx, dy, dt in offsets]

platoon

platoon(
    path: Sequence[Waypoint],
    n: int,
    headway_s: float = 1.0,
    lateral: float = 0.0,
    jitter_m: float = 0.0,
    jitter_s: float = 0.0,
    seed: int = 0,
    lateral_axis: str = "y",
) -> list[list[Waypoint]]

n riders on the same line, each headway_s seconds behind the previous one.

lateral staggers alternate riders sideways (metres along lateral_axis); jitter_m and jitter_s add seeded uniform noise to each rider's lateral position and start time so the group does not look cloned. The result is deterministic for a given seed.

Source code in bikeped/scenarios/builders.py
def platoon(path: Sequence[Waypoint], n: int, headway_s: float = 1.0, lateral: float = 0.0,
            jitter_m: float = 0.0, jitter_s: float = 0.0, seed: int = 0,
            lateral_axis: str = 'y') -> list[list[Waypoint]]:
    """``n`` riders on the same line, each ``headway_s`` seconds behind the previous one.

    ``lateral`` staggers alternate riders sideways (metres along ``lateral_axis``); ``jitter_m``
    and ``jitter_s`` add seeded uniform noise to each rider's lateral position and start time so
    the group does not look cloned. The result is deterministic for a given ``seed``.
    """
    rng = np.random.default_rng(seed)
    out = []
    for i in range(n):
        side = lateral * (1 if i % 2 else 0)
        off = side + (rng.uniform(-jitter_m, jitter_m) if jitter_m else 0.0)
        dt = i * headway_s + (rng.uniform(0, jitter_s) if jitter_s and i else 0.0)
        if lateral_axis == 'y':
            out.append(shift(path, dy=off, dt=dt))
        else:
            out.append(shift(path, dx=off, dt=dt))
    return out

path_speeds

path_speeds(path: Sequence[Waypoint]) -> np.ndarray

Segment speeds (m/s) of a waypoint path, one per segment.

Source code in bikeped/scenarios/builders.py
def path_speeds(path: Sequence[Waypoint]) -> np.ndarray:
    """Segment speeds (m/s) of a waypoint path, one per segment."""
    xs = np.array([p['x'] for p in path], dtype=float)
    ys = np.array([p['y'] for p in path], dtype=float)
    ts = np.array([p['t'] for p in path], dtype=float)
    return np.hypot(np.diff(xs), np.diff(ys)) / np.diff(ts)

path_accelerations

path_accelerations(path: Sequence[Waypoint]) -> np.ndarray

Magnitude of the velocity change (m/s^2) at each interior waypoint.

The velocity change between consecutive segments is divided by the time between segment midpoints, so turns contribute their centripetal acceleration.

Source code in bikeped/scenarios/builders.py
def path_accelerations(path: Sequence[Waypoint]) -> np.ndarray:
    """Magnitude of the velocity change (m/s^2) at each interior waypoint.

    The velocity change between consecutive segments is divided by the time between segment
    midpoints, so turns contribute their centripetal acceleration.
    """
    xs = np.array([p['x'] for p in path], dtype=float)
    ys = np.array([p['y'] for p in path], dtype=float)
    ts = np.array([p['t'] for p in path], dtype=float)
    if len(ts) < 3:
        return np.zeros(0)
    dts = np.diff(ts)
    vx, vy = np.diff(xs) / dts, np.diff(ys) / dts
    mid = 0.5 * (dts[:-1] + dts[1:])
    return np.hypot(np.diff(vx), np.diff(vy)) / mid

catalog

Catalog export: catalog.json, one SVG thumbnail per scenario, simulator data, markdown.

Thumbnails are 320x200 top-down sketches in the scenario frame: the road runs left to right (+x to the right), +y points up, the crosswalk is the striped band at x = 5. The view is the window x in [-12, 36], y in [-15, 15] (metres), widened at the same aspect ratio when a scenario's paths leave it, so most thumbnails share one scale. Pedestrian paths are cyan, cyclist paths amber; dash length grows with the agent's mean speed, a filled dot marks a start in view and a hollow dot an agent that emerges within 15 m of the crosswalk after the start, a ring marks an agent that stands still.

thumbnail_svg

thumbnail_svg(s: dict) -> str

SVG source of the thumbnail for scenario s (320x200 viewBox, no text).

Source code in bikeped/scenarios/catalog.py
def thumbnail_svg(s: dict) -> str:
    """SVG source of the thumbnail for scenario ``s`` (320x200 viewBox, no text)."""
    x0, x1, y0, y1 = _window(s)
    k = W / (x1 - x0)

    def px(x: float) -> float:
        return (x - x0) * k

    def py(y: float) -> float:
        return (y1 - y) * k

    out = ['<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 200" width="320" '
           'height="200">',
           f'<rect width="320" height="200" fill="{BG}"/>',
           f'<rect x="0" y="{_f(py(ROAD_HALF))}" width="320" '
           f'height="{_f(2 * ROAD_HALF * k)}" fill="{ROAD}"/>']
    for yk in (ROAD_HALF, -ROAD_HALF):
        out.append(f'<line x1="0" y1="{_f(py(yk))}" x2="320" y2="{_f(py(yk))}" '
                   f'stroke="{KERB}" stroke-width="1.5"/>')
    out.append(f'<line x1="0" y1="{_f(py(0))}" x2="320" y2="{_f(py(0))}" stroke="{LANE}" '
               f'stroke-width="1" stroke-dasharray="8 8"/>')
    sx0, sx1 = px(CROSSWALK_X[0]), px(CROSSWALK_X[1])
    y = -ROAD_HALF + 0.3
    while y + 0.6 <= ROAD_HALF:
        out.append(f'<rect x="{_f(sx0)}" y="{_f(py(y + 0.6))}" width="{_f(sx1 - sx0)}" '
                   f'height="{_f(0.6 * k)}" fill="{STRIPE}"/>')
        y += 1.2
    # Pedestrians are drawn last so that they stay visible where a bike path crosses them.
    for agent in sorted(s['agents'], key=lambda a: a['type'] == 'person'):
        out.extend(_agent_svg(agent, px, py))
    out.append('</svg>')
    return '\n'.join(out) + '\n'

scenario_record

scenario_record(s: dict) -> dict

JSON-ready metadata and paths of one scenario, as written to catalog.json.

Source code in bikeped/scenarios/catalog.py
def scenario_record(s: dict) -> dict:
    """JSON-ready metadata and paths of one scenario, as written to ``catalog.json``."""
    return {
        'id': s['id'], 'name': s['name'], 'suite': s.get('suite'), 'family': s.get('family'),
        'description': s.get('description', ''), 'tags': list(s.get('tags', [])),
        'expected_dominant': s['expected_dominant'], 'vehicle': s.get('vehicle', 'bicycle'),
        'render': s.get('render', {}), 'duration_s': round(_duration(s), 3),
        'n_agents': len(s['agents']),
        'n_pedestrians': sum(a['type'] == 'person' for a in s['agents']),
        'n_cyclists': sum(a['type'] == 'bike' for a in s['agents']),
        'thumbnail': f"{s['id']}.svg",
        'agents': [{k: a[k] for k in ('type', 'id', 'model', 'label', 'path') if k in a}
                   for a in s['agents']],
    }

export_catalog

export_catalog(out_dir: str | Path, suites: Iterable[str] | None = None) -> dict

Write catalog.json and <id>.svg for every scenario of suites into out_dir.

Returns {'catalog': path, 'thumbnails': n, 'scenarios': n}.

Source code in bikeped/scenarios/catalog.py
def export_catalog(out_dir: str | FsPath, suites: Iterable[str] | None = None) -> dict:
    """Write ``catalog.json`` and ``<id>.svg`` for every scenario of ``suites`` into ``out_dir``.

    Returns ``{'catalog': path, 'thumbnails': n, 'scenarios': n}``.
    """
    out = FsPath(out_dir)
    out.mkdir(parents=True, exist_ok=True)
    names = list(suites) if suites is not None else list_suites()
    records = []
    for name in names:
        for s in get_suite(name):
            (out / f"{s['id']}.svg").write_text(thumbnail_svg(s), encoding='utf-8')
            records.append(scenario_record(s))
    catalog = {
        'frame': 'metres; x along the road, y across it; crosswalk centre at (5, 0)',
        'suites': {n: [r['id'] for r in records if r['suite'] == n] for n in names},
        'families': _family_names(),
        'scenarios': records,
    }
    path = out / 'catalog.json'
    path.write_text(json.dumps(catalog, indent=1) + '\n', encoding='utf-8')
    return {'catalog': str(path), 'thumbnails': len(records), 'scenarios': len(records)}

export_simulator

export_simulator(
    sim_dir: str | Path, suites: Iterable[str] = ("extended", "stress")
) -> str

Write scenarios.extended.js for the browser simulator in sim_dir.

The file defines window.BIKEPED_SUITES = {suite: [scenario, ...]} with the simulator's own scenario keys (name, expected, challenge, agents) plus id, family and vehicle, so the page loads it with a plain <script src> even from file://.

Source code in bikeped/scenarios/catalog.py
def export_simulator(sim_dir: str | FsPath, suites: Iterable[str] = ('extended', 'stress')
                     ) -> str:
    """Write ``scenarios.extended.js`` for the browser simulator in ``sim_dir``.

    The file defines ``window.BIKEPED_SUITES = {suite: [scenario, ...]}`` with the simulator's
    own scenario keys (``name``, ``expected``, ``challenge``, ``agents``) plus ``id``, ``family``
    and ``vehicle``, so the page loads it with a plain ``<script src>`` even from ``file://``.
    """
    data = {}
    for name in suites:
        data[name] = [{
            'id': s['id'], 'name': s['name'], 'expected': s['expected_dominant'],
            'family': s.get('family', ''), 'challenge': s.get('description', ''),
            'vehicle': s.get('vehicle', 'bicycle'),
            'agents': [{'type': a['type'], 'id': a['id'], 'path': a['path']}
                       for a in s['agents']],
        } for s in get_suite(name)]
    path = FsPath(sim_dir) / 'scenarios.extended.js'
    path.write_text('// Extended scenario suites for index.html, written by '
                    '"python -m bikeped.scenarios export --simulator".\n'
                    'window.BIKEPED_SUITES = ' + json.dumps(data, separators=(',', ':')) + ';\n',
                    encoding='utf-8')
    return str(path)

catalog_markdown

catalog_markdown(suite: str, thumb_prefix: str = '../assets/scenarios/') -> str

Markdown table of a suite: thumbnail, name, family, agents, duration, expected state.

Source code in bikeped/scenarios/catalog.py
def catalog_markdown(suite: str, thumb_prefix: str = '../assets/scenarios/') -> str:
    """Markdown table of a suite: thumbnail, name, family, agents, duration, expected state."""
    fam = _family_names()
    rows = ['| | Scenario | Family | Agents | Duration | Expected |',
            '|---|---|---|---|---|---|']
    for s in get_suite(suite):
        rows.append(
            f"| ![{s['name']}]({thumb_prefix}{s['id']}.svg) | "
            f"**{s['name']}**<br>`{s['id']}`<br>{s.get('description', '')} | "
            f"{fam.get(s.get('family', ''), s.get('family', ''))} | {len(s['agents'])} | "
            f"{_duration(s):.1f} s | `{s['expected_dominant']}` |")
    return '\n'.join(rows) + '\n'

conformance

Metadata for the 24 conformance scenarios of the paper.

The scenario content lives in decision_testbench.SCENARIOS and is not copied here. This module only adds the library metadata (slug, family, description, tags, per-agent model hints) and :func:conformance_suite returns decorated shallow copies, leaving the originals untouched.

slugify

slugify(name: str) -> str

Lower-case slug of a display name: 'High-Speed Near Miss' -> 'high-speed-near-miss'.

Source code in bikeped/scenarios/conformance.py
def slugify(name: str) -> str:
    """Lower-case slug of a display name: ``'High-Speed Near Miss'`` -> ``'high-speed-near-miss'``.
    """
    return re.sub(r'[^a-z0-9]+', '-', name.lower()).strip('-')

conformance_suite

conformance_suite() -> list[dict]

The paper's 24 scenarios in paper order, as decorated shallow copies.

Each copy shares the waypoint lists with decision_testbench.SCENARIOS; the agent dicts are copied so that the model hints do not touch the originals.

Source code in bikeped/scenarios/conformance.py
def conformance_suite() -> list[dict]:
    """The paper's 24 scenarios in paper order, as decorated shallow copies.

    Each copy shares the waypoint lists with ``decision_testbench.SCENARIOS``; the agent dicts are
    copied so that the ``model`` hints do not touch the originals.
    """
    import decision_testbench as tb

    out = []
    for original in tb.SCENARIOS:
        family, description, tags, models = META[original['name']]
        s = dict(original)
        s['agents'] = []
        for agent in original['agents']:
            a = dict(agent)
            if agent['id'] in models:
                a['model'] = models[agent['id']]
            s['agents'].append(a)
        s.update(id=slugify(original['name']), suite='conformance', family=family,
                 description=description, tags=list(tags))
        out.append(s)
    return out

evaluate

Run scenarios through the testbench decision pipeline and summarise the outcome.

Everything is computed by decision_testbench.simulate_scenario with ideal perception (the noise-free path, tracker on, no latency). This module only aggregates its per-frame states and ground-truth dangers into per-scenario figures; the metrics themselves (danger labels, false positives, sensitivity) are the testbench's.

The dominant state of a run is the most severe state (alert > warning > safe > idle) that the pipeline holds for at least :data:MIN_STATE_S seconds in total. The same rule applied to the ground truth gives :func:ground_truth_label: idle without pedestrians, safe without cyclists, alert with at least :data:MIN_STATE_S of danger, else warning.

dominant_state

dominant_state(
    states: Sequence[str], fps: int = FPS, min_s: float = MIN_STATE_S
) -> str

Most severe state held for at least min_s seconds in total (idle if none).

Source code in bikeped/scenarios/evaluate.py
def dominant_state(states: Sequence[str], fps: int = FPS, min_s: float = MIN_STATE_S) -> str:
    """Most severe state held for at least ``min_s`` seconds in total (``idle`` if none)."""
    states = np.asarray(states)
    for state in reversed(SEVERITY):
        if np.sum(states == state) / fps >= min_s:
            return state
    return 'idle'

ground_truth_label

ground_truth_label(
    scenario: dict, dangers: ndarray, fps: int = FPS, min_s: float = MIN_STATE_S
) -> str

State the ground truth calls for: see the module docstring for the rule.

Source code in bikeped/scenarios/evaluate.py
def ground_truth_label(scenario: dict, dangers: np.ndarray, fps: int = FPS,
                       min_s: float = MIN_STATE_S) -> str:
    """State the ground truth calls for: see the module docstring for the rule."""
    types = {a['type'] for a in scenario['agents']}
    if 'person' not in types:
        return 'idle'
    if 'bike' not in types:
        return 'safe'
    return 'alert' if np.sum(dangers) / fps >= min_s else 'warning'

label_scenario

label_scenario(scenario: dict, fps: int = FPS) -> str

:func:ground_truth_label from compute_ground_truth_danger alone (no pipeline run).

The frame times match simulate_scenario: t = k / fps up to the scenario duration.

Source code in bikeped/scenarios/evaluate.py
def label_scenario(scenario: dict, fps: int = FPS) -> str:
    """:func:`ground_truth_label` from ``compute_ground_truth_danger`` alone (no pipeline run).

    The frame times match ``simulate_scenario``: ``t = k / fps`` up to the scenario duration.
    """
    tb = _tb()
    duration = tb.get_scenario_duration(scenario)
    n = int(math.floor(duration * fps + 1e-9)) + 1
    dangers = np.array([tb.compute_ground_truth_danger(scenario, k / fps).is_danger
                        for k in range(n)], dtype=bool)
    return ground_truth_label(scenario, dangers, fps)

evaluate_scenario

evaluate_scenario(scenario: dict, config: str = 'default', fps: int = FPS) -> dict

Simulate one scenario and summarise it.

Returned keys: id, name, suite, family, duration_s, agents, danger_s and actionable_s (ground-truth time), alert_s, false_alert_s (alert on frames the ground truth calls safe), danger_intervals (one dict per interval with start, end, alerted and lead_s: seconds from alert onset to danger onset, negative when the alert came late), sensitivity, specificity, dominant, expected, ground_truth and match.

Source code in bikeped/scenarios/evaluate.py
def evaluate_scenario(scenario: dict, config: str = 'default', fps: int = FPS) -> dict:
    """Simulate one scenario and summarise it.

    Returned keys: ``id``, ``name``, ``suite``, ``family``, ``duration_s``, ``agents``,
    ``danger_s`` and ``actionable_s`` (ground-truth time), ``alert_s``, ``false_alert_s`` (alert
    on frames the ground truth calls safe), ``danger_intervals`` (one dict per interval with
    ``start``, ``end``, ``alerted`` and ``lead_s``: seconds from alert onset to danger onset,
    negative when the alert came late), ``sensitivity``, ``specificity``, ``dominant``,
    ``expected``, ``ground_truth`` and ``match``.
    """
    tb = _tb()
    params = tb.PIPELINE_CONFIGS[config]
    r = tb.simulate_scenario(scenario, params, fps=fps)
    times, states, dangers = r['times'], r['states'], r['dangers']
    dt = 1.0 / fps
    is_alert = states == 'alert'
    actionable = np.array([a.actionable for a in r['assessments']], dtype=bool)
    intervals = []
    for i0, i1 in _runs(dangers):
        lo = max(0, i0 - int(round(LEAD_WINDOW_S * fps)))
        hits = np.flatnonzero(is_alert[lo:i1])
        if len(hits):
            first = lo + int(hits[0])
            while first > 0 and is_alert[first - 1]:
                first -= 1
            lead = float(times[i0] - times[first])
            intervals.append({'start': round(float(times[i0]), 3),
                              'end': round(float(times[i1 - 1]) + dt, 3),
                              'alerted': True, 'lead_s': round(lead, 3)})
        else:
            intervals.append({'start': round(float(times[i0]), 3),
                              'end': round(float(times[i1 - 1]) + dt, 3),
                              'alerted': False, 'lead_s': None})
    dominant = dominant_state(states, fps)
    expected = scenario.get('expected_dominant')
    return {
        'id': scenario.get('id', ''),
        'name': scenario['name'],
        'suite': scenario.get('suite', ''),
        'family': scenario.get('family', ''),
        'duration_s': round(float(tb.get_scenario_duration(scenario)), 3),
        'agents': len(scenario['agents']),
        'danger_s': round(float(np.sum(dangers)) * dt, 3),
        'actionable_s': round(float(np.sum(actionable)) * dt, 3),
        'alert_s': round(float(np.sum(is_alert)) * dt, 3),
        'false_alert_s': round(r['false_pos'] * dt, 3),
        'danger_intervals': intervals,
        'sensitivity': round(float(r['sensitivity']), 4),
        'specificity': round(float(r['specificity']), 4),
        'dominant': dominant,
        'expected': expected,
        'ground_truth': ground_truth_label(scenario, dangers, fps),
        'match': dominant == expected,
        'tags': list(scenario.get('tags', [])),
    }

is_known_hard

is_known_hard(row: dict) -> bool

True when the pipeline's dominant state is wrong or an alert is late or missing.

Late means the alert began more than :data:LATE_ALERT_S seconds after the danger interval.

Source code in bikeped/scenarios/evaluate.py
def is_known_hard(row: dict) -> bool:
    """True when the pipeline's dominant state is wrong or an alert is late or missing.

    Late means the alert began more than :data:`LATE_ALERT_S` seconds after the danger interval.
    """
    if not row['match']:
        return True
    return any(not d['alerted'] or d['lead_s'] < -LATE_ALERT_S for d in row['danger_intervals'])

evaluate_suite

evaluate_suite(
    scenarios: Iterable[dict], config: str = "default", fps: int = FPS
) -> list[dict]

:func:evaluate_scenario for each scenario.

Source code in bikeped/scenarios/evaluate.py
def evaluate_suite(scenarios: Iterable[dict], config: str = 'default',
                   fps: int = FPS) -> list[dict]:
    """:func:`evaluate_scenario` for each scenario."""
    return [evaluate_scenario(s, config, fps) for s in scenarios]

format_table

format_table(rows: Sequence[dict]) -> str

Plain-text table of :func:evaluate_scenario rows with a totals line.

Source code in bikeped/scenarios/evaluate.py
def format_table(rows: Sequence[dict]) -> str:
    """Plain-text table of :func:`evaluate_scenario` rows with a totals line."""
    head = (f"{'scenario':<34} {'dur':>5} {'ag':>3} {'danger':>6} {'alert':>6} {'false':>6} "
            f"{'lead s (per interval)':<22} {'dominant':>8} {'expected':>8}  ok")
    lines = [head, '-' * len(head)]
    for r in rows:
        lines.append(
            f"{r['id'][:34]:<34} {r['duration_s']:>5.1f} {r['agents']:>3} {r['danger_s']:>6.2f} "
            f"{r['alert_s']:>6.2f} {r['false_alert_s']:>6.2f} "
            f"{_fmt_lead(r['danger_intervals'])[:22]:<22} {r['dominant']:>8} "
            f"{str(r['expected']):>8}  {'yes' if r['match'] else 'NO'}")
    n_iv = sum(len(r['danger_intervals']) for r in rows)
    n_ok = sum(1 for r in rows for d in r['danger_intervals']
               if d['alerted'] and d['lead_s'] >= -1.0 / FPS - 1e-9)
    lines.append('-' * len(head))
    lines.append(f"{len(rows)} scenarios, dominant state matches expected in "
                 f"{sum(r['match'] for r in rows)}; {n_ok} of {n_iv} danger intervals alerted "
                 f"no later than one frame after onset; false-alert time "
                 f"{sum(r['false_alert_s'] for r in rows):.2f} s")
    return '\n'.join(lines)

to_json

to_json(rows: Sequence[dict]) -> str

JSON text of evaluation rows (non-finite numbers become null).

Source code in bikeped/scenarios/evaluate.py
def to_json(rows: Sequence[dict]) -> str:
    """JSON text of evaluation rows (non-finite numbers become ``null``)."""
    def clean(v):
        if isinstance(v, float) and not math.isfinite(v):
            return None
        if isinstance(v, dict):
            return {k: clean(x) for k, x in v.items()}
        if isinstance(v, list):
            return [clean(x) for x in v]
        return v

    return json.dumps([clean(r) for r in rows], indent=2)

extended

The extended suite: hand-designed urban conflicts and deliberate negatives.

Same frame as the conformance scenarios: metres, x along the road, y across it, the crosswalk centred on (5, 0) and about 3 m wide, kerbs near y = -6.5 and y = +6.5. Through cyclists ride towards -x (heading 180 degrees) a metre or two either side of the centre line, as in the paper's scenarios.

Speeds follow published ranges: walking 1.2-1.5 m/s, older adults 0.8-1.0, wheelchairs 1.0-1.3, children running 2-3, runners 3-4, commuter cyclists 4-7, fast road cyclists 8-11, e-bikes up to about 11, e-scooters 5-7, cargo bikes 3.5-5.5; comfortable cyclist braking about 2 m/s^2 and hard braking 4-6 m/s^2.

expected_dominant is the label the testbench ground truth implies (:func:bikeped.scenarios.evaluate.ground_truth_label), checked by running each scenario. Scenarios the default pipeline gets wrong carry the known-hard tag: its dominant state differs from expected_dominant (a false alarm or a miss), or its first alert comes more than :data:~bikeped.scenarios.evaluate.LATE_ALERT_S after a danger interval begins.

ped

ped(aid: int, path: list[dict], model: str = 'adult', label: str | None = None) -> dict

Pedestrian agent dict with a model hint.

Source code in bikeped/scenarios/extended.py
def ped(aid: int, path: list[dict], model: str = 'adult', label: str | None = None) -> dict:
    """Pedestrian agent dict with a model hint."""
    a = {'type': 'person', 'id': aid, 'path': path, 'model': model}
    if label:
        a['label'] = label
    return a

bike

bike(
    aid: int, path: list[dict], model: str = "bicycle", label: str | None = None
) -> dict

Cyclist agent dict with a model hint.

Source code in bikeped/scenarios/extended.py
def bike(aid: int, path: list[dict], model: str = 'bicycle', label: str | None = None) -> dict:
    """Cyclist agent dict with a model hint."""
    a = {'type': 'bike', 'id': aid, 'path': path, 'model': model}
    if label:
        a['label'] = label
    return a

across

across(
    speed: float = 1.4,
    t0: float = 0.0,
    x: float = 5.0,
    y0: float = -6.5,
    y1: float = 6.5,
) -> list[dict]

Pedestrian walking straight across the road at x from y0 to y1.

Source code in bikeped/scenarios/extended.py
def across(speed: float = 1.4, t0: float = 0.0, x: float = 5.0, y0: float = -6.5,
           y1: float = 6.5) -> list[dict]:
    """Pedestrian walking straight across the road at ``x`` from ``y0`` to ``y1``."""
    return Path.start(x, y0, t0).to(x, y1, speed).build()

along

along(
    speed: float,
    t_at: float,
    y: float = 1.0,
    x_at: float = 5.0,
    x_end: float = -8.0,
    max_start: float = 34.0,
) -> list[dict]

Cyclist riding towards -x at speed that reaches x_at at time t_at.

It starts at t = 0 far enough back to arrive on time, or later if that would put it more than max_start metres down the road.

Source code in bikeped/scenarios/extended.py
def along(speed: float, t_at: float, y: float = 1.0, x_at: float = 5.0, x_end: float = -8.0,
          max_start: float = 34.0) -> list[dict]:
    """Cyclist riding towards ``-x`` at ``speed`` that reaches ``x_at`` at time ``t_at``.

    It starts at ``t = 0`` far enough back to arrive on time, or later if that would put it more
    than ``max_start`` metres down the road.
    """
    x0 = x_at + speed * t_at
    t0 = 0.0
    if x0 > max_start:
        t0 = t_at - (max_start - x_at) / speed
        x0 = max_start
    return Path.start(x0, y, t0).to(x_end, y, speed).build()

scenario

scenario(
    name: str,
    family: str,
    expected: str,
    description: str,
    agents: list[dict],
    tags: tuple[str, ...] = (),
    vehicle: str | None = None,
    weather: str | None = None,
) -> dict

Assemble one scenario dict with library metadata.

Source code in bikeped/scenarios/extended.py
def scenario(name: str, family: str, expected: str, description: str, agents: list[dict],
             tags: tuple[str, ...] = (), vehicle: str | None = None,
             weather: str | None = None) -> dict:
    """Assemble one scenario dict with library metadata."""
    from .conformance import slugify

    s: dict = {'name': name, 'expected_dominant': expected}
    if vehicle:
        s['vehicle'] = vehicle
    s['agents'] = agents
    s.update(id=slugify(name), suite='extended', family=family, description=description,
             tags=list(tags))
    if weather:
        s['render'] = {'weather': weather}
    return s

extended_suite

extended_suite() -> list[dict]

All extended scenarios, grouped by family.

Source code in bikeped/scenarios/extended.py
def extended_suite() -> list[dict]:
    """All extended scenarios, grouped by family."""
    return [*_turning(), *_occlusion(), *_yielding(), *_counter_flow(), *_shared_space(),
            *_groups(), *_vulnerable(), *_micromobility(), *_pedestrian_behaviour(),
            *_near_miss(), *_signal_platoon(), *_negatives()]

generators

Seeded parametric scenario families.

generate(family, n, seed) returns n scenarios of one family in the usual frame (metres, x along the road, crosswalk centred on (5, 0)). Sweep families spread their parameter evenly over the range in :data:FAMILIES and use the seed only for small jitter (start times within 0.2 s, speeds within 5 %), so the sweep values themselves stay readable. The same family, n and seed always give identical output.

expected_dominant of each generated scenario is computed from the testbench ground truth with :func:bikeped.scenarios.evaluate.label_scenario.

generate

generate(family: str, n: int = 20, seed: int = 0) -> list[dict]

n scenarios of family (a key of :data:FAMILIES), deterministic for seed.

Source code in bikeped/scenarios/generators.py
def generate(family: str, n: int = 20, seed: int = 0) -> list[dict]:
    """``n`` scenarios of ``family`` (a key of :data:`FAMILIES`), deterministic for ``seed``."""
    if family not in FAMILIES:
        raise KeyError(f'unknown family {family!r}; known: {", ".join(FAMILIES)}')
    if n < 1:
        raise ValueError('n must be at least 1')
    rng = np.random.default_rng(seed)

    def jt() -> float:
        return float(rng.uniform(-0.2, 0.2))

    def js(v: float) -> float:
        return v * float(rng.uniform(0.95, 1.05))

    out: list[dict] = []
    if family == 'crossing-angle':
        for ang in _sweep(30.0, 150.0, n):
            out.append(_base(
                f'Crossing at {ang:.0f} deg',
                f'A pedestrian crosses at {ang:.0f} degrees to the road and reaches the lane '
                f'centre as a {BIKE_SPEED:.0f} m/s cyclist arrives.',
                [ped(1, _cross_through((5.0, 0.0), ang, js(PED_SPEED), T_CONFLICT + jt())),
                 bike(2, _ride(js(BIKE_SPEED), T_CONFLICT + jt()))]))
    elif family == 'cyclist-speed':
        for v in _sweep(3.0, 11.0, n):
            out.append(_base(
                f'Cyclist at {v:.1f} m/s',
                f'A cyclist at {v:.1f} m/s reaches the crosswalk as the pedestrian is mid-lane.',
                [ped(1, _cross_through((5.0, 0.0), 90.0, js(PED_SPEED), T_CONFLICT + jt())),
                 bike(2, _ride(js(v), T_CONFLICT + jt()),
                      model='ebike' if v > 8.5 else 'bicycle')],
                vehicle='ebike' if v > 8.5 else 'bicycle'))
    elif family == 'time-gap':
        for gap in _sweep(-3.0, 3.0, n):
            out.append(_base(
                f'Time gap {gap:+.1f} s',
                f'The cyclist reaches the conflict point {abs(gap):.1f} s '
                f'{"after" if gap >= 0 else "before"} the pedestrian.',
                [ped(1, _cross_through((5.0, 0.0), 90.0, js(PED_SPEED), T_CONFLICT)),
                 bike(2, _ride(js(BIKE_SPEED), T_CONFLICT + gap + 0.5 * jt()))]))
    elif family == 'lateral-offset':
        for off in _sweep(0.0, 5.0, n):
            out.append(_base(
                f'Lateral offset {off:.1f} m',
                f'The cyclist passes {off:.1f} m to the side of the pedestrian at the moment '
                f'of crossing.',
                [ped(1, _cross_through((5.0, 0.0), 90.0, js(PED_SPEED), T_CONFLICT + jt())),
                 bike(2, _ride(js(BIKE_SPEED), T_CONFLICT, y=off))]))
    elif family == 'group-size':
        for k in range(1, n + 1):
            lead = _cross_through((5.0, 0.0), 90.0, PED_SPEED, T_CONFLICT)
            offsets = [(float(rng.uniform(-1.2, 1.2)), -0.8 * (i // 2), 0.15 * i + abs(0.1 * jt()))
                       for i in range(k)]
            out.append(_base(
                f'Group of {k}',
                f'{k} pedestrian{"s" if k > 1 else ""} cross together into the path of one '
                f'cyclist.',
                [*[ped(i + 1, p) for i, p in enumerate(group(lead, offsets))],
                 bike(k + 1, _ride(js(BIKE_SPEED), T_CONFLICT + jt()))]))
    else:
        for _ in range(n):
            n_p, n_b = int(rng.integers(1, 5)), int(rng.integers(1, 4))
            agents = []
            for i in range(n_p):
                agents.append(ped(i + 1, _cross_through(
                    (float(rng.uniform(2, 8)), float(rng.uniform(-2, 2))),
                    float(rng.uniform(55, 125)) + (180.0 if rng.random() < 0.5 else 0.0),
                    float(rng.uniform(1.1, 1.6)), float(rng.uniform(4, 9)))))
            for j in range(n_b):
                agents.append(bike(n_p + j + 1, _ride(float(rng.uniform(4, 8)),
                                                      float(rng.uniform(3, 10)),
                                                      y=float(rng.uniform(-2, 2)))))
            out.append(_base(
                f'Mixed traffic {n_p}P {n_b}B',
                f'{n_p} pedestrian{"s" if n_p > 1 else ""} and {n_b} '
                f'cyclist{"s" if n_b > 1 else ""} at random times, angles and speeds.',
                agents))
    return _finish(out, family, seed)

registry

Scenario registry: named suites and lookup by slug, name or suite:index.

Suites are built lazily on first use and cached. conformance is the paper's 24 scenarios from decision_testbench.SCENARIOS; extended and stress are defined in this package. Callers receive the cached dicts, so treat them as read-only (copy before editing).

list_suites

list_suites() -> list[str]

Names of the registered suites, in display order.

Source code in bikeped/scenarios/registry.py
def list_suites() -> list[str]:
    """Names of the registered suites, in display order."""
    return list(SUITE_ORDER)

get_suite

get_suite(name: str) -> list[dict]

Scenarios of suite name in their defined order (for conformance, paper order).

Source code in bikeped/scenarios/registry.py
def get_suite(name: str) -> list[dict]:
    """Scenarios of suite ``name`` in their defined order (for ``conformance``, paper order)."""
    return list(_suite(name))

all_scenarios

all_scenarios() -> list[dict]

Every scenario of every registered suite.

Source code in bikeped/scenarios/registry.py
def all_scenarios() -> list[dict]:
    """Every scenario of every registered suite."""
    return [s for name in SUITE_ORDER for s in _suite(name)]

get_scenario

get_scenario(key: str) -> dict

Look up one scenario.

key is a slug ('fast-approach'), an exact display name ('Fast Approach') or 'suite:index' with a zero-based index ('conformance:7' is Fast Approach).

Source code in bikeped/scenarios/registry.py
def get_scenario(key: str) -> dict:
    """Look up one scenario.

    ``key`` is a slug (``'fast-approach'``), an exact display name (``'Fast Approach'``) or
    ``'suite:index'`` with a zero-based index (``'conformance:7'`` is Fast Approach).
    """
    if ':' in key:
        suite, _, idx = key.partition(':')
        if idx.lstrip('-').isdigit():
            scenarios = _suite(suite)
            i = int(idx)
            if not 0 <= i < len(scenarios):
                raise KeyError(f'{key!r}: suite {suite!r} has {len(scenarios)} scenarios')
            return scenarios[i]
    for s in all_scenarios():
        if s['id'] == key or s['name'] == key:
            return s
    raise KeyError(f'no scenario with id or name {key!r}')

schema

Validation of scenario dicts.

:func:validate_scenario checks one scenario against the testbench format and the library metadata; :func:validate_suites also checks that ids and names are unique across scenarios. Both return a list of human-readable problems, empty when everything is fine.

Speed and acceleration limits are per agent model and deliberately generous: they catch typos (a pedestrian at 15 m/s, a waypoint with the wrong time) rather than judge realism. Speeds are segment speeds of the piecewise-linear path in m/s; accelerations are velocity changes between consecutive segments in m/s^2, so they include turning.

validate_scenario

validate_scenario(s: dict) -> list[str]

Problems found in one scenario (empty list when valid).

Source code in bikeped/scenarios/schema.py
def validate_scenario(s: dict) -> list[str]:
    """Problems found in one scenario (empty list when valid)."""
    problems: list[str] = []
    label = s.get('id') or s.get('name') or '<unnamed>'

    def bad(msg: str) -> None:
        problems.append(f'{label}: {msg}')

    if not isinstance(s.get('name'), str) or not s.get('name'):
        bad('missing name')
    if s.get('expected_dominant') not in STATES:
        bad(f"expected_dominant {s.get('expected_dominant')!r} not one of {STATES}")
    if 'vehicle' in s and s['vehicle'] not in VEHICLES:
        bad(f"unknown vehicle {s['vehicle']!r}")
    if 'suite' in s and not isinstance(s['suite'], str):
        bad('suite must be a string')
    if 'family' in s and s['family'] not in _known_families():
        bad(f"unknown family {s['family']!r}")
    if 'tags' in s and not all(isinstance(t, str) for t in s['tags']):
        bad('tags must be strings')
    weather = (s.get('render') or {}).get('weather')
    if weather is not None and weather not in WEATHER:
        bad(f'unknown weather preset {weather!r}')
    agents = s.get('agents')
    if not isinstance(agents, list) or not agents:
        bad('needs a non-empty agents list')
        return problems
    coarse = s.get('suite') == 'conformance'
    ids = [a.get('id') for a in agents]
    if len(set(ids)) != len(ids):
        bad(f'duplicate agent ids {ids}')
    for a in agents:
        who = f"agent {a.get('id')}"
        if a.get('type') not in AGENT_TYPES:
            bad(f"{who}: type {a.get('type')!r} not one of {AGENT_TYPES}")
            continue
        model = a.get('model')
        allowed = PERSON_MODELS if a['type'] == 'person' else BIKE_MODELS
        if model is not None and model not in allowed:
            bad(f'{who}: model {model!r} not valid for a {a["type"]}')
            continue
        path = a.get('path')
        if not isinstance(path, list) or len(path) < 2:
            bad(f'{who}: path needs at least two waypoints')
            continue
        if not all(isinstance(p, dict) and all(_finite(p.get(k)) for k in 'xyt') for p in path):
            bad(f'{who}: every waypoint needs finite x, y, t')
            continue
        ts = [p['t'] for p in path]
        if any(t1 <= t0 for t0, t1 in zip(ts, ts[1:])):
            bad(f'{who}: waypoint times must be strictly increasing')
            continue
        if ts[0] < 0:
            bad(f'{who}: negative start time')
        vmax, amax = LIMITS[(a['type'], model)]
        speeds = path_speeds(path)
        if speeds.max() > vmax + 1e-6:
            bad(f'{who}: speed {speeds.max():.2f} m/s exceeds {vmax} m/s for '
                f'{model or a["type"]}')
        acc = path_accelerations(path)
        limit = amax * (COARSE_ACCEL_FACTOR if coarse else 1.0)
        if len(acc) and acc.max() > limit + 1e-6:
            bad(f'{who}: acceleration {acc.max():.2f} m/s^2 exceeds {limit} m/s^2')
    return problems

validate_suites

validate_suites(scenarios: Iterable[dict]) -> list[str]

Validate every scenario and check that ids and names are unique among them.

Source code in bikeped/scenarios/schema.py
def validate_suites(scenarios: Iterable[dict]) -> list[str]:
    """Validate every scenario and check that ids and names are unique among them."""
    problems: list[str] = []
    seen_ids: dict[str, str] = {}
    seen_names: dict[str, str] = {}
    for s in scenarios:
        problems.extend(validate_scenario(s))
        where = f"{s.get('suite', '?')}"
        sid = s.get('id')
        if not sid:
            problems.append(f"{s.get('name')}: missing id")
        elif sid in seen_ids:
            problems.append(f'duplicate id {sid!r} in {seen_ids[sid]} and {where}')
        else:
            seen_ids[sid] = where
        name = s.get('name')
        if name in seen_names:
            problems.append(f'duplicate name {name!r} in {seen_names[name]} and {where}')
        else:
            seen_names[name] = where
    return problems

stress

The stress suite: dense scenes for throughput and tracker-load testing.

Each scene puts many pedestrians and cyclists in view at once (12 to 24 agents) in the usual scenario frame (metres, x along the road, crosswalk centred on (5, 0)). Positions and start times are jittered with fixed seeds, so the suite is identical on every run. expected_dominant is the ground-truth label from :func:bikeped.scenarios.evaluate.ground_truth_label.

stress_suite

stress_suite() -> list[dict]

Eight dense scenes, deterministic.

Source code in bikeped/scenarios/stress.py
def stress_suite() -> list[dict]:
    """Eight dense scenes, deterministic."""
    scenes = []
    rng = np.random.default_rng(101)
    scenes.append(_scene(
        'Rush Hour Crosswalk', 'alert',
        'Twelve pedestrians cross in both directions over 8 s while six cyclists ride through '
        'from both ends.',
        [*_crowd(rng, 12, 1, 8.0), *_riders(rng, 6, 13, 8.0)], ('rush-hour',)))
    rng = np.random.default_rng(102)
    scenes.append(_scene(
        'Stadium Exit', 'alert',
        'Twenty people leave an event and flood the crosswalk in one direction as three '
        'cyclists arrive.',
        [*_crowd(rng, 20, 1, 6.0, x_lo=2.5, x_hi=7.5, both_ways=False),
         *_riders(rng, 3, 21, 6.0, both_ways=False)], ('crowd',)))
    rng = np.random.default_rng(103)
    scenes.append(_scene(
        'Bike Commute Peak', 'alert',
        'Sixteen cyclists in a steady stream at commuter speeds and four pedestrians picking '
        'their way across.',
        [*_crowd(rng, 4, 1, 9.0), *_riders(rng, 16, 5, 9.0)], ('commute', 'multi-cyclist')))
    rng = np.random.default_rng(104)
    scenes.append(_scene(
        'Wet Night Mixed Traffic', 'alert',
        'Ten pedestrians and eight riders on a wet night; some riders go as fast as e-bikes.',
        [*_crowd(rng, 10, 1, 8.0), *_riders(rng, 8, 11, 8.0, speed=(5.0, 10.0))],
        ('night', 'rain', 'ebike', 'known-hard'), weather='wet_night'))
    rng = np.random.default_rng(105)
    tour = [ped(1 + i, Path.start(-6 + 1.5 * i, -7.5 - rng.uniform(0, 0.5), rng.uniform(0, 1))
                .to(26 + 1.5 * i, -7.5, 1.0).build()) for i in range(10)]
    scenes.append(_scene(
        'Sidewalk Tour Group', 'warning',
        'A tour group of ten walks along the sidewalk while six cyclists pass on the road; '
        'nobody crosses.',
        [*tour, *_riders(rng, 6, 11, 8.0, both_ways=False)],
        ('sidewalk', 'negative', 'known-hard')))
    rng = np.random.default_rng(106)
    scenes.append(_scene(
        'Crosswalk Without Cyclists', 'safe',
        'Twenty-four pedestrians cross in both directions and no cyclist appears.',
        _crowd(rng, 24, 1, 10.0), ('no-cyclist', 'negative')))
    rng = np.random.default_rng(107)
    scenes.append(_scene(
        'Group Ride Through Crowd', 'alert',
        'A group ride of ten passes in two lines through a crosswalk with eight pedestrians on '
        'it.',
        [*_crowd(rng, 8, 1, 5.0),
         *[bike(9 + i, Path.start(34 + 3.0 * (i // 2), 0.5 + 1.0 * (i % 2), 0.0, heading=180)
                .ride(60, 6.5).build()) for i in range(10)]], ('group-ride', 'platoon')))
    rng = np.random.default_rng(108)
    scenes.append(_scene(
        'Market Day Shared Street', 'alert',
        'A shared street with fourteen pedestrians wandering across at random angles and six '
        'slow cyclists.',
        [*[ped(1 + i, Path.start(rng.uniform(-6, 16), -7.0, rng.uniform(0, 6))
               .to(rng.uniform(-6, 16), 7.0, rng.uniform(0.9, 1.4)).build())
           for i in range(14)],
         *_riders(rng, 6, 15, 8.0, speed=(3.5, 5.0))], ('shared-space',)))
    return scenes