Skip to content

Traffic Backends

The vehicles in a scenario come from three places, and only two of them are the scenario's own:

  • the ego, driven by its entity — see External Driver Interface;
  • the authored NPCs a scenario spawns in setup();
  • the ambient traffic that fills the rest of the road network.

A traffic backend owns the third kind outright and answers the manoeuvre intents asked of the second. CARLA's TrafficManager is one such backend and is the default. This page describes the seam, how to select a backend, and how to write one — a microscopic traffic simulator such as SUMO, a replay of recorded traffic, or anything else that can put vehicles on a road.

Architecture

flowchart TB
    subgraph run["Scenario process"]
        SR["ScenarioRunner<br/>owns the world and the tick loop"]
        SC["BaseScenario<br/>ego + authored NPCs"]
        BE["TrafficBackend"]
        SR -->|"prepare / start / tick / close"| BE
        SC -->|"change_lane, turn_at_junction"| BE
        SR --> SC
    end

    subgraph impls["Implementations"]
        TM["TrafficManagerBackend<br/>(default)"]
        NONE["NullTrafficBackend<br/>('none')"]
        SUMO["SumoTrafficBackend<br/>('sumo')"]
        HYB["HybridTrafficBackend<br/>('hybrid')"]
        EXT["your backend<br/>(entry point)"]
    end

    BE --- TM
    BE --- NONE
    BE --- SUMO
    BE --- HYB
    BE --- EXT
    TM --> CTM["CARLA TrafficManager"]
    SUMO --> LS["SUMO (libsumo)"]
    SUMO -.->|"scenario vehicles"| TM
    HYB -->|"near: in CARLA"| CTM
    HYB -->|"far: mesoscopic"| MS["SUMO --mesosim<br/>or the queue model"]
    EXT -.-> SIM["another traffic simulator"]

Two rules hold for every backend:

One authority per vehicle. A vehicle a backend owns is not driven by anything else. ScenarioRunner passes the actors that are under external control — an Autoware ego, a policy-driven ego — to start() as skip_actor_ids, so the rule is data the backend is given rather than a special case it has to know about.

An intent is not a mechanism. change_lane is what the scenario means; tm.force_lane_change and traci.vehicle.changeLane are what two backends do about it. Entities ask for the first and never name the second, which is why actions work unchanged whatever drives the vehicle.

Selecting a backend

The traffic config group chooses one:

# CARLA's TrafficManager (the default — nothing to pass)
uv run scenario scenario=intersection_passing/left_turn

# No traffic model at all: only the ego and the scenario's own cars move
uv run scenario scenario=intersection_passing/left_turn traffic=none
Backend Behaviour
traffic_manager (default) CARLA's TrafficManager drives every vehicle that is not under external control.
none Nothing is driven and no ambient vehicle is created.
sumo SUMO fills the road with its own traffic, co-simulated on the world's road network; see The SUMO backend. Needs the sumo extra.
hybrid CARLA's TrafficManager near the ego, a mesoscopic model far from it: background traffic far from every other vehicle leaves CARLA and comes back as it nears one; see The hybrid backend. For wide maps. Needs the sumo extra.

traffic=none and the default ego

ego.entity=autopilot (the default) means the traffic backend drives the ego, so under traffic=none the ego does not move and the run ends on its timeout. Pair traffic=none with an ego that drives itself — ego.entity=autoware or ego.entity=carla_driver — or with a scenario that steers its vehicles itself. The backend logs how many vehicles it is leaving standing, so the log says why nothing moved.

A backend's own settings live under traffic.options and are passed to it verbatim, so a backend from another package needs no change to this package's config:

traffic:
  backend: traffic_manager
  options:
    port: 8100
# 8101 rather than the default 8100: a second TrafficManager, so two runs
# can share one machine without steering each other's traffic.
uv run scenario traffic.options.port=8101

traffic_manager.port — where the port lived before this group existed, and what exported scenario packages still set — keeps deciding the port when traffic.options.port is left unset. Under launcher=slurm neither decides: each task's TrafficManager is on its slot's port, which replaces an explicit traffic.options.port (or SUMO's tm_port) with a warning (SLURM, Ports). Either must be a TCP port, an integer within 1-65535: 0, 70000 or true is refused, naming the key, before CARLA is started (a batch's and a sweep's cases before any runs), as the SUMO backend's tm_port is. A null traffic.options.port is the default, as under sumo and hybrid.

Traffic parameters

How the traffic's road users behave is not a backend's own option but three parameter spaces every backend reads: traffic.vehicles (VehicleParameters) for how vehicles drive, traffic.pedestrians (PedestrianParameters) for how pedestrians walk, and traffic.bicycles (BicycleParameters) for how bicycles ride. Every field is null by default, which leaves the backend's own default.

Every numeric parameter is a spread, a mean and a standard deviation ({mean, std}, Spread in Python): each vehicle and each pedestrian draws its own value from a normal distribution of that mean and std, cut to the parameter's bounds (drawn again until it is inside them -- a truncated normal). The traffic is a population of drivers, not one driver copied. Every numeric parameter also takes a plain value instead, in a config and in Python alike: a number (or a std of 0) gives every road user exactly that value. The draws come from the run's seed: the same seed, the same drivers. A value out of its bounds, or a negative std, is refused by its full key and shown as written: traffic.bicycles.min_gap_m.mean must be within [0, inf] (got '-1').

traffic:
  backend: sumo
  vehicles:
    speed_factor: {mean: 0.9, std: 0.1}   # around 10 % under the limit
    min_gap_m: 3.0                        # every vehicle 3 m
    reaction_time_s: {mean: 1.5, std: 0.3}
    follow_visibility: true
  pedestrians:
    walking_speed_mps: {mean: 1.2, std: 0.2}
    red_light_violation_s: {mean: 5.0, std: 5.0}
  bicycles:
    max_speed_mps: {mean: 4.5, std: 0.8}
uv run scenario traffic=sumo traffic.vehicles.reaction_time_s.mean=1.5 \
    traffic.vehicles.reaction_time_s.std=0.3
uv run scenario traffic.vehicles.ignore_lights=0.1
uv run scenario traffic=sumo traffic.pedestrians.walking_speed_mps.mean=1.0

An ODD can draw both the mean and the std of each, per case (Traffic parameters from the ODD).

A numeric field takes a number, never a bool: ignore_lights: true or {mean: true} is an error naming the field (traffic.vehicles.ignore_lights must be a number, not a bool), not a probability of 1. The two bool fields, lane_changes and follow_visibility, take true or false, or one of the spellings 1/true/on/yes and 0/false/off/no (any case, surrounding spaces ignored), which is what Hydra leaves an override such as traffic.vehicles.lane_changes=no as. Each is stored as a real bool, so every backend reads the same value; anything else (enabled, 2, 0.5) is an error naming traffic.vehicles.<field> before the run starts, from the config, a TrafficParametersAction and the scenario editor alike.

uv run scenario traffic.vehicles.lane_changes=no traffic.vehicles.follow_visibility=off

traffic.vehicles:

Field Meaning traffic_manager sumo
speed_factor Desired speed as a multiple of the limit vehicle speed difference each vehicle's speed factor
min_gap_m Gap to the vehicle ahead when standing, m distance to leading vehicle minGap
lane_changes Change lanes of their own accord auto_lane_change lane-change mode (route changes kept)
ignore_lights Probability (0-1) of running a red light ✓ —
ignore_signs Probability (0-1) of ignoring a stop sign ✓ —
ignore_vehicles Probability (0-1) of ignoring vehicles ✓ —
ignore_walkers Probability (0-1) of ignoring pedestrians ✓ —
random_lane_changes Probability (0-1) of a lane change for no reason ✓ —
accel Acceleration, m/s² — accel
decel Braking, m/s² (also the visibility's) — decel
reaction_time_s Reaction time, s (also the visibility's) — tau
imperfection Driver imperfection, 0-1 — sigma
max_lateral_speed_mps Most lateral speed, m/s — maxSpeedLat
max_lateral_accel Most lateral acceleration, m/s² — lcAccelLat (sublane model, the default)
follow_visibility Slow to what the drivers see in the weather ✓ (when true) ✓ (on by default)

traffic.pedestrians (the TrafficManager drives no pedestrians — a scenario's own walk as the scenario steers them — so every field is sumo's):

Field Meaning traffic_manager sumo
walking_speed_mps Walking speed, m/s — maxSpeed
min_gap_m Gap to the person ahead, m — minGap
red_light_violation_s Cross on red if it has been red for less than this, s — jmDriveAfterRedTime

traffic.bicycles (only SUMO simulates bicycles; the TrafficManager drives a bicycle blueprint as it drives a car, so every field is sumo's). The vehicle parameters are a driver's and never reach a bicycle:

Field Meaning traffic_manager sumo Default
max_speed_mps Speed on a free road, m/s — desiredMaxSpeed and maxSpeed 5.56 (20 km/h), with SUMO's spread of 0.1
accel Acceleration, m/s² — accel 1.2
decel Braking, m/s² — decel 3
min_gap_m Gap to the one ahead when standing, m — minGap 0.5
reaction_time_s Reaction time, s — tau 1
imperfection Rider imperfection, 0-1 — sigma 0.5
max_lateral_speed_mps Most lateral speed, m/s — maxSpeedLat 1
red_light_violation_s Ride on through a light red for less than this, s — jmDriveAfterRedTime stop at red

SUMO's default bicycle type (DEFAULT_BIKETYPE) is redefined as a distribution of 100 types, each its own draw of them (<output>/{stem}.sumo/bicycle_type.add.xml, loaded before the demand), which SUMO's own bicycles (traffic.options.bicycles), a route_path demand's of that type and the scenario's bicycles are all of.

Parameter reference

Each parameter, with its type, the values it accepts, and what it becomes in each backend. Unset (null) means the backend's own default, which is given where it is fixed. A numeric one is a spread whose mean must lie in the range given, which is also what each road user's draw is cut to; a mean outside it, or a negative std, is refused when the config is read, before the backend is built. Each vehicle draws once, when it is first put on autopilot (TrafficManager) or departs (SUMO), and keeps its draws.

traffic.vehicles

Shared by traffic_manager and sumo

  • speed_factor — spread, mean >= 0.05

    • The speed drivers aim for, as a multiple of the speed limit: 1.0 drives at the limit, 0.8 20 % under it, 1.1 10 % over it.
    • traffic_manager: vehicle_percentage_speed_difference(vehicle, (1 - draw) * 100). Unset, the TrafficManager's own default, which the backend sets as it prepares the TrafficManager (global_percentage_speed_difference(0), LibCarla's own): the limit. The TrafficManager keeps a percentage or a speed for a vehicle, not both, the one given last: a speed set on it (a background vehicle's spawn speed, a SetSpeedAction) drops its percentage, and a new draw (TrafficParametersAction) drops its speed.
    • sumo: the vehicle's speed factor (setSpeedFactor). Unset, SUMO's own draw around 1.0 (spread 0.1).
  • min_gap_m — spread, metres, mean >= 0

    • The gap a driver leaves to the vehicle ahead when standing in a queue.
    • traffic_manager: distance_to_leading_vehicle(vehicle, draw).
    • sumo: minGap of each vehicle (SUMO's default 2.5 m).
  • lane_changes — bool

    • Whether drivers change lanes of their own accord: to overtake, to keep right, to make room.
    • traffic_manager: auto_lane_change(vehicle, lane_changes) on each vehicle as it goes on autopilot (default true).
    • sumo: false sets each vehicle's lane-change mode to 1537 — the changes its route needs only, still respecting other drivers' gaps — instead of SUMO's 1621; true leaves SUMO's default. A lane change a scenario asks for (LaneChangeAction) still happens.

traffic_manager only

Each is a probability, a spread with its mean in [0, 1] and each draw cut to it, set per vehicle as it goes on autopilot as the TrafficManager's percentage (× 100): with a std, some drivers run red lights more often than others. Unset, 0: drivers obey everything and never change lanes at random.

  • ignore_lights

    • Chance of driving through a red light (ignore_lights_percentage).
  • ignore_signs

    • Chance of ignoring a stop sign (ignore_signs_percentage).
  • ignore_vehicles

    • Chance of ignoring the vehicles in the way, i.e. of colliding with them (ignore_vehicles_percentage).
  • ignore_walkers

    • Chance of ignoring pedestrians (ignore_walkers_percentage).
  • random_lane_changes

    • Chance of a lane change for no reason, to either side (random_left_lanechange_percentage and random_right_lanechange_percentage, both set to it).

sumo only

Set on each vehicle SUMO drives as it departs (traci.vehicle.set*), the scenario's vehicles SUMO drives (scenario_vehicles=sumo) included; a vehicle CARLA's side drives (the ego, and the scenario's vehicles under scenario_vehicles=traffic_manager) is only placed in SUMO and keeps SUMO's defaults.

  • accel — spread, m/s², mean >= 0.05

    • The acceleration drivers use (setAccel; SUMO's default 2.6).
  • decel — spread, m/s², mean >= 0.05

    • The braking drivers use (setDecel; SUMO's default 4.5). Also the braking follow_visibility works the sight speed out from.
  • reaction_time_s — spread, seconds, mean >= 0

    • Drivers' reaction time, SUMO's tau (setTau; default 1.0), which also sets the time headway they keep. Also the reaction time follow_visibility works the sight speed out from.
  • imperfection — spread, mean in [0, 1]

    • Driver imperfection, SUMO's sigma (setImperfection; default 0.5): how much a driver dawdles below the speed it could drive. 0 is a perfect driver.
  • max_lateral_speed_mps — spread, m/s, mean >= 0.05

    • The fastest a vehicle moves sideways, SUMO's maxSpeedLat (setMaxSpeedLat; default 1.0). A lane change takes at least the lane's width over it: a 3.5 m lane at 0.5 here takes about 7 s.
  • max_lateral_accel — spread, m/s², mean >= 0.05

    • The hardest a vehicle accelerates sideways, SUMO's lcAccelLat (set as the laneChangeModel.lcAccelLat parameter; default 1.0). Only SUMO's sublane model, the backend's default, has one: with traffic.options.lateral_resolution_m: null it is an error before the run.
  • follow_visibility — bool

    • Hold the backend's own traffic to the speed its drivers keep in what they see in the run's weather -- the weather rules' sight_speed, which reads the visibility, at each driver's own quantile, never above the speed it stops from within it (v * tau + v² / (2 * decel) = the visibility) -- and give each its own speed back when the weather lifts.
    • sumo: SUMO's own traffic (ambient and background vehicles), with each vehicle's own tau and decel. Unset, true; false ignores the visibility. See Visibility under The SUMO backend.
    • traffic_manager: every vehicle it drives, with SUMO's default car's reaction (1 s) and braking (4.5 m/s²), the TrafficManager having neither, held as a percentage under its road's speed limit (never faster than its own speed_factor), worked out again every second. Off unless true, so a scenario's vehicles drive as they always did. See Weather and the TrafficManager.

traffic.pedestrians (sumo only)

SUMO's default pedestrian type is redefined as a distribution of 100 types, each its own draw of them (vTypeDistribution, in <output>/{stem}.sumo/pedestrian_type.add.xml loaded before the demand); SUMO gives each person one of them as it is added, so each walks as its own draw says. They apply to SUMO's own pedestrians (traffic.options.pedestrians) and to a route_path demand's that names no type of its own. On types, not on each person: SUMO reads jmDriveAfterRedTime off the type only, and TraCI cannot set it on a person. traffic.options.pedestrians says how many SUMO generates; traffic.pedestrians how they walk.

  • walking_speed_mps — spread, m/s, mean > 0
    • The speed a person walks at (SUMO's maxSpeed, with SUMO's own spread speedDev set to 0 so the draw is the speed). Unset, SUMO's 1.39 m/s with its spread of 0.1.
  • min_gap_m — spread, metres, mean >= 0
    • The gap kept to the person ahead (SUMO's minGap; default 0.25).
  • red_light_violation_s — spread, seconds, mean >= 0
    • A pedestrian walks onto a crossing whose light has been red for less than this (SUMO's junction model jmDriveAfterRedTime) when the way is free; a large value has people cross on red whenever they can. Unset, they wait for green. Measured on a signalled crossroads held red for 120 s: unset, 1,347 person-steps on a crossing (crossings whose own signal SUMO keeps green); 1000, 29,386.

The TrafficManager drives no pedestrians, so it refuses every field here.

The same in Python, where every field is a keyword of VehicleParameters or PedestrianParameters, and a numeric one takes a Spread (a distribution) or a plain number (a value):

from autoware_carla_scenario import PedestrianParameters, Spread, VehicleParameters

VehicleParameters(
    speed_factor=Spread(0.9, 0.1),  # a distribution: each vehicle draws its own
    min_gap_m=3.0,                  # a value: every vehicle 3 m
    reaction_time_s=Spread(1.5, 0.3),
)
PedestrianParameters(walking_speed_mps=1.2)

A field set for a backend that cannot honour it fails the run before anything is spawned, naming the backends it can be used with — a run that asked for drivers who react in 1.5 s and silently got the TrafficManager's, which has no reaction time, would test something other than what it says:

TrafficParameterError: The 'traffic_manager' traffic backend does not support
traffic.vehicles.reaction_time_s can only be used with the 'sumo' backend.
Leave the field unset (null) or select a backend that supports it.

The TrafficManager sets each vehicle's draws as the vehicle is first put on autopilot, the scenario's own included (a speed set on one vehicle, a background vehicle's or a SetSpeedAction's, wins over its speed). SUMO sets them on each vehicle it drives as it departs, and hands the shared ones to the TrafficManager driving the scenario's vehicles under scenario_vehicles=traffic_manager. The visibility is one of them: see Visibility under The SUMO backend.

A backend from another package supports none of them until it says so:

class MySimulatorBackend(TrafficBackend):
    def supported_vehicle_parameters(self) -> set[str]:
        return {"speed_factor", "min_gap_m"}

    def supported_pedestrian_parameters(self) -> set[str]:
        return {"walking_speed_mps"}

and reads them from self.vehicle_parameters and self.pedestrian_parameters in prepare().

Changing the parameters during a run

TrafficParametersAction changes the parameters from the tick it fires on, like any action, on a condition:

from autoware_carla_scenario import (
    BicycleParameters,
    ElapsedTimeCondition,
    PedestrianParameters,
    Spread,
    TrafficParametersAction,
    VehicleParameters,
)

# From 20 s on, drivers slow down and keep their distance.
scenario.register_post_tick(
    TrafficParametersAction(
        vehicles=VehicleParameters(
            speed_factor=Spread(0.8, 0.05), min_gap_m=Spread(4.0, 1.0)
        ),
        condition=ElapsedTimeCondition(20.0, label="after_20s"),
    )
)

# The NPC ahead turns reckless (traffic_manager): values, not distributions.
scenario.register_post_tick(
    TrafficParametersAction(
        vehicles=VehicleParameters(speed_factor=1.3, ignore_lights=1.0),
        entity_name="npc1",
    )
)

# Pedestrians hurry (sumo).
scenario.register_post_tick(
    TrafficParametersAction(
        pedestrians=PedestrianParameters(walking_speed_mps=Spread(1.8, 0.2))
    )
)

# Riders brake harder and keep closer (sumo).
scenario.register_post_tick(
    TrafficParametersAction(
        bicycles=BicycleParameters(decel=Spread(4.0, 0.5), min_gap_m=0.3)
    )
)
  • Field by field. The fields the action sets replace the run's; the ones it leaves unset keep their values, whether they came from the config or from the ODD.
  • Everyone draws again. Without entity_name, every vehicle (or pedestrian) already in the run draws its value of the changed fields again from the new spread, and every one that joins later draws from the merged parameters. The ODD's probes read the merged parameters from then on.
  • One vehicle. With entity_name (a role_name), only that vehicle draws the changed fields again; the run's parameters stay as they were. An entity is a vehicle, so pedestrians and bicycles cannot be given with it. Under the TrafficManager, a vehicle not yet on autopilot (one the scenario drives first) keeps the override for its first draw, which takes it over the run's parameters; several such actions layer in order. That first draw keeps what the vehicle was told before it: a speed it was given (a SetSpeed, a background vehicle's spawn speed) wins over its speed_factor, and a route it follows keeps its own lane changes off whatever lane_changes says, unless an override of that field, with or without entity_name, came after them: the one given last wins.
  • The last one wins. An action without entity_name fired after one with it replaces that vehicle's override on the fields both set, as it does for a vehicle that drew already: every vehicle draws those fields from the new spread.
  • Refused before the run. A field the backend cannot change during a run is refused when the action is registered on the scenario, with a TrafficParameterError:
    • the TrafficManager can change every vehicle parameter it supports, and no pedestrian one;
    • SUMO can change every vehicle parameter it supports, and a pedestrian's walking_speed_mps and min_gap_m. It cannot change red_light_violation_s, which SUMO reads off the pedestrian types it is started with: set it in traffic.pedestrians instead. Of the bicycle parameters it can change every one but max_speed_mps and red_light_violation_s, which it reads off the bicycle types: set those in traffic.bicycles.
  • Under SUMO, a scenario vehicle the TrafficManager drives (scenario_vehicles=traffic_manager) gets the shared fields, with a warning naming the others. A visibility already held is held anew, from the new draws.
  • One run only. The change lasts until the run ends: the next run of a queue starts from its own config.
  • In the scenario editor it is two cards: Traffic Parameters on the environment track (the whole run's traffic) and Vehicle Parameters on an NPC's track (that vehicle alone), with a mean and a std field per parameter; an empty field keeps the run's value.

The lifecycle

ScenarioRunner calls these at fixed points of a run, beside the ego entity's own hooks:

Method When
prepare(context) Before setup(), nothing spawned yet. Put a simulator in step, seed it, or refuse the run.
adopt(entity) As the ego and each authored NPC join the run. The vehicle stays the scenario's.
start(world, skip_actor_ids=…) After warm-up and the init phase, immediately before the scenario clock starts.
tick(world, elapsed) Once per world.tick(). A backend driving a second simulator steps it exactly once here.
release(entity, world) When an action takes a vehicle over (a RoutingAction in follow or position mode). Stop driving it; may come before or after start.
resume(entity, world) When an action that took a vehicle over hands it back (an adversarial manoeuvre is over). Drive it again from where it is; undoes release, may come before or after start.
close() During teardown, while the world is still alive. Called even when the run failed.

One backend serves a whole queue: ScenarioQueue builds one runner, so over a batch the real sequence is prepare … close, prepare … close, with a different scenario — and possibly a different map — each time. close() is the end of a run, not the end of the object: forget every vehicle created and every entity adopted, and be ready to prepare() again.

TrafficContext, handed to prepare(), carries the CARLA client and world, the map name, the OpenDRIVE the run installed, the simulation step, the scenario's random seed and the run's output directory — everything a second simulator needs to line itself up with the CARLA one.

Two promises matter:

  • prepare() is the place to fail loudly. Raise TrafficBackendUnavailable when the simulator behind the backend is not installed, naming the extra that installs it; nothing has been spawned yet, so the run costs nothing.
  • tick() and the manoeuvres must never raise. A traffic model that cannot do something logs a warning; an exception there would end a scenario that is otherwise perfectly valid. The base class's defaults already behave this way.

Writing a backend

Subclass TrafficBackend, override what you actually do, and register a factory under a name:

from typing import Any, Collection, Mapping

from autoware_carla_scenario import TrafficBackend, TrafficContext, register_backend


class MySimulatorBackend(TrafficBackend):
    name = "my_simulator"

    def __init__(self, options: Mapping[str, Any]) -> None:
        self._address = options.get("address", "localhost:9999")

    def prepare(self, context: TrafficContext) -> None:
        # Match the simulation step so the two clocks cannot drift, and derive
        # the road network from the OpenDRIVE the CARLA world is running.
        # The map of the run: `xodr_path` is the OpenDRIVE CARLA is running, and Phase B
        # adds `lanelet2_path` for a backend whose own network is built from Lanelet2.
        self._connect(context.fixed_delta_seconds, context.xodr_path, context.random_seed)

    def start(self, world: Any, *, skip_actor_ids: Collection[int] = ()) -> None:
        self._externally_driven = set(skip_actor_ids)

    def tick(self, world: Any, elapsed: float) -> None:
        self._publish_carla_vehicles(world)   # so my traffic reacts to the ego
        self._step_once()                      # exactly one step per world tick
        self._mirror_into_carla(world)

    def close(self) -> None:
        self._disconnect()


def register() -> None:
    register_backend("my_simulator", MySimulatorBackend)

From your own package, advertise it so traffic.backend=my_simulator resolves without an import anywhere in this repository:

[project.entry-points."autoware_carla_scenario.traffic_backends"]
my_simulator = "my_package:register"

A backend that drives through a CARLA TrafficManager names the option of its own its port is read from, so a run reports the port it uses and a SLURM task points it at its slot's port (SLURM, Ports), as the built-in traffic_manager and hybrid (port) and sumo (tm_port) do:

register_backend("my_simulator", MySimulatorBackend, tm_port_option="tm_port")

A run drops every option left null before it hands the options to your factory: the shipped groups declare their keys as null placeholders so that traffic.options.x=y overrides work under Hydra's struct mode, and an interpolation such as ${oc.select:traffic_manager.port,null} resolves to null when nothing sets it, so a null means "not set" and your factory sees the key absent and applies its own default. A backend that reads a null itself -- as a value of its own for some option, as the built-in sumo backend's lateral_resolution_m does -- registers with takes_null_options=True, as the built-in sumo, hybrid and traffic_manager backends do, and is then handed the nulls as they are; it must then read a null as the default of every option that does not take one (utils.config.null_as_default does that for a dataclass):

register_backend("my_simulator", MySimulatorBackend, takes_null_options=True)

build_backend() passes the options it is given on verbatim either way: the flag is for the run, which composes them from the config. A package that overrides a built-in name without the flag is handed no nulls, as any other backend registered without it.

Registering a name that is already taken replaces it, which is how a package overrides a built-in backend (traffic_manager, sumo, ...). It is still reported: load_traffic_backend_plugins() logs a warning naming the entry point and the backend it overrides. Two installed packages that register the same name are reported as well, with a warning naming both entry points; the one loaded last wins. Entry points load sorted by distribution name (normalised, so my-package and my_package sort together) and then entry-point name, so which one that is does not depend on the environment.

Answering manoeuvre intents

A backend that can steer the vehicles it drives overrides the intent methods. They receive the entity, so a backend can read the actor and record its own bookkeeping on the vehicle rather than in a table of its own:

    def change_lane(self, entity, world, direction) -> None: ...
    def lane_change_finished(self, entity, world) -> bool: ...
    def turn_at_junction(self, entity, world, direction, **kwargs) -> None: ...
    def follow_route(self, entity, world, stops) -> None: ...
    def end_route(self, entity, world) -> None: ...

direction is LaneChangeDirection or TurnDirection — intents, not CARLA values. stops is the whole way a vehicle is to drive, as Lanelet2 poses: where it is, its waypoints, its goal -- what a vehicle given a goal is handed (BackendDriven.route_to), where turn_at_junction decides one junction. Each backend lays the route out in its own terms. The TrafficManager backend plans the lanelets between the stops, samples their centrelines every 5 m from the point after the vehicle's own, and leaves out the points in a junction and next to one: the TrafficManager takes a junction's way out by the road of the next point, and there a point lies on several ways through. A backend that has no answer for one simply does not override it: the base class logs that the intent is unavailable and the vehicle keeps doing what it was doing, which is also what LaneChangeAction sees when it asks whether the manoeuvre finished.

end_route is called when a route a RoutingAction watched is over: the vehicle arrived, or the action was stopped, overridden or closed first. It gives back what the route changed in how the vehicle drives, and does nothing by default. The TrafficManager backend turns its own lane changes, which follow_route turned off, back to the run's lane_changes (and the vehicle's overrides); unset, the TrafficManager's default, on. A route handed over untimed ends its action at once, with nothing left to watch it: the TrafficManager backend gives the lane changes back itself once the vehicle has come along its path to within a path point's spacing (5 m) of its last point, where the TrafficManager has used the path up and drives on as it likes. Along: the backend follows each kept vehicle's progress, point by point, coming within 5 m of one of the next eight points (released ones too, so a resumed vehicle goes on from where it was driven), so a route that ends near where it starts (a loop, a U-turn, a route through a via point and back) is not used up at its start. A vehicle lost from its path, 40 m from every point about where it had come to (driven off it while released, or round something for longer than those points span), is looked for along all the rest of it instead, so it picks its path up where it comes back to it.

Handing a vehicle back

release(entity, world) is the one-authority-per-vehicle rule of skip_actor_ids, applied during the run: an action that drives a vehicle itself -- a RoutingAction in position mode places it on a trajectory every tick -- asks the backend to stop driving it first. The TrafficManager takes it off autopilot (and never puts it on, if start has not run yet); SUMO keeps it in its own simulation but publishes it from CARLA, as it does the ego. The base class does nothing, which is right for a backend that never drives the scenario's vehicles.

resume(entity, world) undoes it, for an action that hands the vehicle back when it is done (entity.resume_traffic(world); a RoutingAction leaves its vehicle where the trajectory ends and does not): the TrafficManager puts it back on autopilot, keeping the desired speed and lane-change settings it had, and gives it the rest of its route again from where it was driven to (taken off autopilot, the TrafficManager dropped the points it had planned), with the lane changes along it it has not yet been told of or driven past (#1154). A route given before the vehicle is on autopilot (a RoutingAction at init, or while released) is handed over the same as one given after: the vehicle is told to change lanes where its path crosses to the lane beside, and one starting in a junction's mouth is driven out of the junction first. SUMO drives it again from the pose it was published at, with the speed and lane-change modes and the desired speed it had before. A vehicle never released, or driven elsewhere from the start (an ego: ExternallyDrivenEgo refuses resume_traffic, and both backends ignore it), is left as it is, and saying it twice is harmless.

Simulating far traffic mesoscopically

A backend may simulate the vehicles far from anything that matters at a coarser level than the ones near it: nobody sees the difference there, and the run is cheaper for it. The seam names two levels, SimulationFidelity:

Level What is simulated In CARLA
MICROSCOPIC each vehicle on its lane: car-following, lane changes an actor
MESOSCOPIC a place in a queue on a road: when it gets to the end, not where it is on the way nothing

Every vehicle entity carries its level as entity.simulation_fidelity (MICROSCOPIC by default, and always under a backend with one level), so a scenario or a condition can tell a vehicle that is far away and out of the world from one that is gone. Three rules keep the flag honest:

  • Only the backend writes it, through TrafficBackend._mark_fidelity, and only once a change is complete: an entity reading MESOSCOPIC has no actor (entity.actor is None), one reading MICROSCOPIC has one.
  • An entity leaves the world only if it agrees to. The backend asks entity._replace_actor(None), and later hands it the actor it spawned where its model has the vehicle with entity._replace_actor(actor). A VehicleEntity agrees; an ego, and anything that owns its actor in a way a backend cannot see, does not, and stays microscopic.
  • Whatever needs the actor asks for it: entity.require_microscopic(world) (backend.require_microscopic(entity, world)) brings the vehicle back at once and keeps it for the rest of the run. A backend's release() does it too, since whatever takes a vehicle over drives it in CARLA.

backend.fidelity_census() counts the vehicles a backend simulates at each level. A run's result (<output>/<scenario>_result.json) records it under traffic.fidelity, read when the run ends, beside the backend's describe() (for SUMO, how many vehicles changed level during the run). A condition that looks an entity up by role name while it is mesoscopic finds no actor, and the log says why, once each time the entity becomes mesoscopic. The parts that are the same for every backend are reusable:

  • traffic.fidelity.MesoscopicConfig is the policy: the radii around the focus points (the ego and every vehicle CARLA drives) inside which traffic is microscopic, with hysteresis between them, how far ahead to look (horizon_s), how many may be microscopic at once (max_microscopic), how often to decide, and whether the scenario's own vehicles may leave the world. plan_fidelity(config, candidates, focus, focus_velocities) returns which vehicles change level, the ones that matter most first.
  • traffic.mesoscopic.MesoscopicTraffic is a queue model -- SUMO's own mesoscopic model, cut down: a road lets a vehicle out once it has driven the road's length, first in first out, one per headway per lane, when the road ahead has room and the junction (an optional gate, a red light) lets it through. It knows no simulator: a backend builds it from its own roads (MesoLink), moves a vehicle in when it becomes mesoscopic and reads where it is to decide when to bring it back.
  • traffic.sumo.mesosim.SumoMesoscopicTraffic has the same interface over SUMO's own mesoscopic simulation: a second SUMO, started with --mesosim on the same network, whose vehicles are the ones taken out of the microscopic one. It is what the sumo backend's far traffic runs in by default (mesoscopic.engine: sumo, below).

Two backends simulate far traffic mesoscopically: sumo, with traffic.options.mesoscopic.enabled=true (below), and hybrid, which is the TrafficManager with a mesoscopic model behind it (below). Under traffic_manager every vehicle is microscopic, an actor in CARLA wherever it is on the map, and traffic.options.mesoscopic is an unknown option there (an error, like any other): the TrafficManager exposes neither the route it plans for a vehicle nor a road graph, so hybrid takes both from SUMO's network of the map, and moves only the traffic it owns, its background vehicles. The measurements on Town10HD_Opt (below) show what the sumo backend's saves; on a map that small little is far from the ego, so either pays off on a wide one.

Using a backend from Python

A scenario run built in code takes the backend the same way it takes the ego:

from autoware_carla_scenario import NullTrafficBackend, ScenarioQueue

queue = ScenarioQueue(map_name="Town10HD_Opt", traffic_backend=NullTrafficBackend())

and its parameters in the backend's constructor, or by name through the registry:

from autoware_carla_scenario import (
    PedestrianParameters,
    TrafficManagerBackend,
    VehicleParameters,
)
from autoware_carla_scenario.traffic import build_backend

backend = TrafficManagerBackend(vehicles=VehicleParameters(speed_factor=0.8))
backend = build_backend(
    "sumo",
    {},
    vehicles=VehicleParameters(reaction_time_s=1.5),
    pedestrians=PedestrianParameters(walking_speed_mps=1.2),
)

ScenarioQueue passes it to the ScenarioRunner it builds, and one backend serves every scenario in the queue — the same way one CARLA server does.

Background traffic

Vehicles no scenario entity stands for are created and removed by two actions modelled on OpenSCENARIO's TrafficSourceAction and TrafficSinkAction. Where OpenSCENARIO gives a source or sink a position and a radius, these take lanelet constraints -- the vocabulary a sweep picks its cases with -- so the same action means "every lane outside a junction" on any map:

from autoware_carla_scenario import ElapsedTimeCondition, TrafficSinkAction, TrafficSourceAction

not_in_junction = [{"type": "not", "constraint": {"type": "is_junction"}}]

# Placed during initialization, then no more: register_init runs once.
self.register_init(TrafficSourceAction(not_in_junction, initial_vehicles=20))

# Six a minute during the first 30 s of the run, at most 30 on the road.
self.register_pre_tick(
    TrafficSourceAction(
        not_in_junction,
        vehicles_per_minute=6.0,
        max_vehicles=30,
        until=ElapsedTimeCondition(30.0, label="first_30s"),
    )
)

# Removed at the ends of the map's roads for the whole run.
self.register_pre_tick(
    TrafficSinkAction(
        [{"type": "not", "constraint": {"type": "previous_of",
          "constraints": [{"type": "lanelet_length", "value": 0.0}]}}]
    )
)
  • Where they act is the lanelets vehicles drive on that the constraints match. A crosswalk, walkway, stairs, road shoulder, bicycle lane or parking lot is never part of a source or sink, whatever its constraints say (the test vehicle routes use, MapFeatures.is_road): such a lanelet has no vehicle successor, so "no successor" alone would remove a vehicle as it drives over a crosswalk, and a source would place vehicles across the road. The constraints are a list, or a single constraint mapping (a list of one), and are parsed when the action is built, so one the sweeper does not know is refused then, not when the first vehicle is due; the run's background_traffic.source.constraints and .sink.constraints are parsed by its up-front check, where null builds no source or sink and false or '' is refused, naming the key (#2191); so is a source or sink block that is false, '' or 0 rather than a mapping or null.
  • When they act is the trigger (condition) and the end condition (until), as for every action. With no until a source or sink runs until the scenario ends, as OpenSCENARIO's do; with one, it stops on the first tick until fires. Registered with register_init, a source places its initial_vehicles once, during initialization, and never again.
  • Who drives them is the backend: spawn_background, background_vehicles and remove_background on TrafficBackend; background_vehicles gives each one's CARLA (x, y, z), so a sink or a construction zone tells a road from the overpass above it (on_lanelet reads the height); z is None for a vehicle SUMO's mesoscopic model holds (on a lane's 2D shape), which is then placed in plan view alone. A vehicle SUMO has not inserted yet -- it waits while its spot is taken, often by a SUMO vehicle CARLA does not mirror -- is given at the spot spawn_background was asked for, as it will be on the road once the spot clears. Under traffic=sumo they are SUMO vehicles that wander the network (a random way out at each junction) and are mirrored into CARLA like the rest of SUMO's traffic; ones placed during initialization have SUMO's warm-up to spread out. Under traffic=traffic_manager they are CARLA vehicles on autopilot. none creates none, with a warning.
  • Where they go is a driving lane. Both backends put a vehicle on the lane nearest the spot asked for, facing along it (the TrafficManager would turn one put askew onto its lane at once). Under traffic_manager, where that lane runs against the spot's heading (near a two-way road's centre line) the lane beside it running the spot's way is taken instead, or the spot is refused. Both refuse a spot more than 5 m (BACKGROUND_MAX_OFFSET_M in traffic/base.py) from any driving lane -- a crosswalk, a footway -- with an info message; the source tries elsewhere.
  • speed_kmh is the speed they drive at, at most: both backends cap a vehicle at exactly this and let it enter at no more. It must be finite and at least 1 km/h; 0, a negative speed, NaN or infinity is refused by TrafficSourceAction, by background_traffic.source.speed_kmh and by the editor's validator, because a vehicle that never moves is no traffic (a parked car is an entity). max_vehicles counts every background vehicle on the road, whichever source made it, and every one still waiting to enter it (under sumo, those SUMO has not inserted yet), so a source that keeps asking for a taken spot does not let more than max_vehicles in at once when it clears.
  • vehicles_per_minute and min_gap_m (the least distance from a new vehicle to any other, a waiting one included) must be finite and not negative; NaN or infinity is refused by TrafficSourceAction and by background_traffic.source.*, naming the key, rather than crashing the run or being dropped without a word.
  • background_traffic.source.speed_kmh, .min_gap_m and .vehicles_per_minute left null are their defaults (30 km/h, 15 m and none a minute), as they are when absent; a value that is no number (fast) is refused, naming the key.
  • background_traffic.source.stop_after_seconds and background_traffic.sink.stop_after_seconds end the source's adding and the sink's removing after that many seconds of the run; null (the default) never does. Anything else must be a positive, finite number of seconds (abc, 0, false or '' is refused, naming the key), even when there is no source rate or sink to end.
  • initial_vehicles, max_vehicles and background_traffic.seed are whole numbers, not negative (20 or 20.0; max_vehicles and seed may be null), seed at most 2147483647 (2**31 - 1, what SUMO's --seed takes): 2.9, true, -5 or 2147483648 is refused, naming the key, rather than run as 2, 1 or a negative seed. The run refuses all of these before anything starts, whenever background_traffic.enabled is true (true or false, or a spelling of either such as "false"; anything else is refused: The switches). TrafficSourceAction applies the same rule to its initial_vehicles, max_vehicles and seed (the last two when given), naming the parameter, so a count of 2.5 or NaN is refused when the action is built rather than mid-run.

The examples take all of this from the config, for any scenario:

uv run scenario scenario=intersection_passing/left_turn map=town10hd_opt \
  traffic=sumo background_traffic.enabled=true
# Only what initialization places:
uv run scenario ... background_traffic.enabled=true background_traffic.source.vehicles_per_minute=0
# Keep adding for the first 20 s only:
uv run scenario ... background_traffic.enabled=true background_traffic.source.stop_after_seconds=20

background_traffic (in examples/conf/config.yaml) is off by default, and so are the SUMO backend's own ambient randomTrips demand, its pedestrians and its bicycles (SumoBackendConfig's defaults, and conf/traffic/sumo.yaml's), so a run has no traffic but its own and its traffic sources' unless asked.

Weather and the TrafficManager

CARLA's TrafficManager drives in the weather as on a clear day: its vehicles know where every actor is whatever the fog. With traffic.vehicles.follow_visibility: true each vehicle it drives is held to the speed its driver keeps in what it sees: the weather rules' sight_speed (Weather rules) at the driver's own quantile, for SUMO's default car's reaction (1 s) and braking (4.5 m/s²) -- about 46-62 km/h in 50 m of fog, never more than the 62 km/h it stops from within it. A vehicle is never held faster than it drives anyway. One given a speed of its own (set_desired_speed, a SetSpeedAction, a background vehicle's spawn speed) is given the lesser of that and the sight speed (set_desired_speed), so a stop stays a stop, and a speed the scenario sets while it is held is held too. Any other is given the percentage under its road's limit that holds it there (vehicle_percentage_speed_difference), never less than its own speed_factor's (or the TrafficManager's default, 0 %), worked out again every second and whenever the visibility changes. Each is given its own the same way: the TrafficManager keeps a percentage or a speed for a vehicle, not both, and either drops the other (LibCarla's Parameters.cpp). When the weather lifts, or the field is turned off during the run (TrafficParametersAction), each gets its own back: its speed, or its percentage. Off by default, so a scenario's vehicles drive as they always did; unset, the backend logs the speed it would hold traffic to.

The road's grip is CARLA's vehicle physics alone (EnvironmentAction's tire friction scales every vehicle's wheels, the TrafficManager's as well); the sight speed above does not read it.

uv run scenario ... environment.fog_visibility_range_m=100 \
    environment.rainfall_rate_mm_h=8 traffic.vehicles.follow_visibility=true

The visibility comes from the ODD's conditions: the rainfall rate, the fog visibility and the time of day (The weather and the sun) give what drivers see, worked out before the run, or its visibility knob names it, and the backend -- this one or sumo -- follows.

Vehicles the TrafficManager must not destroy

CARLA's TrafficManager destroys a vehicle it drives in two cases, with no per-vehicle switch but a role_name of hero:

  • Standing: one that has stood (under 0.8 m/s) for 90 s — 180 s at a red light — is destroyed (BLOCKED_TIME_THRESHOLD, ALSM.cpp).
  • A dead end: one whose planned path (4 s of driving ahead, at least 15 m) meets a lane with no successor is destroyed (marked_for_removal, LocalizationStage.cpp; with OSM mode on, the default).

Only background vehicles (spawn_background) are left to that. Every other vehicle the traffic_manager backend has on autopilot — the ego, each NPC the scenario authored — is kept from it in tick(); under traffic=sumo with scenario_vehicles=traffic_manager the same, since SUMO hands those to it. A background vehicle the TrafficManager destroyed is forgotten: no longer counted, listed or chosen by an adversity. It is told by is_alive, not by an error -- another handle to an actor destroyed elsewhere raises nothing and reads at the origin -- except on the frame it was spawned on, before the world has ticked, when a client reads every new actor that way; it is given at its spawn point then.

  • Standing: once a kept vehicle has stood 60 s (90 s less a 30 s margin) it is taken off autopilot and put straight back on. Unregistering a vehicle erases its idle time (ALSM::RemoveActor) and registering it starts a new one, so the TrafficManager's count starts again. Its per-vehicle settings (desired speed, speed difference, gap, lane-change and ignore rules) are the TrafficManager's parameters, which survive the switch. Its planned waypoints do not, and the points of a path already planned are gone from the path the TrafficManager holds (LocalizationStage::ImportPath), so the part of the path it was last given (follow_route, turn_at_junction) still ahead of it is given again: from the point after the one nearest it among the last it has come to along the path that are still within 5 m of it (else from the next one it has not come to), so a path that comes back near itself is not cut at its far part, and the vehicle is not sent back to a point it has passed. It drives on as before; it is logged once.
  • A dead end: every 0.5 s the road ahead of a kept vehicle is walked down every branch (the TrafficManager picks one at random) a little past the TrafficManager's horizon, on the run's cached map. Where some branch ends, the vehicle is taken off autopilot and held braking where it is, logged once, until it is given a new route or an action takes it over. On a path it was given the walk waits until the path's end is near: the TrafficManager follows the path, which goes on, to there. Then, since the TrafficManager plans past a path's end into the dead end beyond it, the vehicle is not held short of its goal but taken off autopilot and drives the rest of its path itself, with the controller a RoutingAction in follow mode drives with (traffic.final_approach.FinalApproach, at 4 m/s, slowing onto the end), and is stopped and held braking on the path's last point, logged once. Off autopilot, the TrafficManager cannot destroy it; a new route puts it back on.

Each kept vehicle is looked at every 0.5 s, the first looks spread over that period: a velocity read and, unless it is where the last walk found the road going on, a waypoint lookup and a walk of a few dozen waypoints. Nothing is done per background vehicle, and no map is built.

Why this exists

CARLA's TrafficManager is a good default for a handful of scripted NPCs and the wrong tool for dense, demand-driven flow. Microscopic traffic simulators model car-following, gap acceptance and route choice in ways it does not, and "does the stack merge into a saturated flow at this intersection?" is a question about traffic rather than about three scripted cars. The seam is what makes answering it possible without a second scenario framework: the same map, the same scenario document, the same conditions and the same result format, with the traffic model swapped.

The hybrid backend

traffic=hybrid keeps CARLA's TrafficManager for every vehicle in CARLA -- the ego, the scenario's vehicles, the background traffic near them -- and moves the background traffic far from all of them into a mesoscopic model of the map's roads, out of CARLA, bringing each back, on autopilot, as it nears one. It is the TrafficManager's way of driving on a map too wide to fill with actors: what is out of CARLA costs CARLA nothing, and the TrafficManager drives only the vehicles someone can see.

# The TrafficManager, with background traffic beyond 200 m (250 m back out)
# simulated by SUMO's mesoscopic model.
uv run scenario scenario=... traffic=hybrid

# Nearer, looking 6 s ahead, never more than 60 background vehicles in CARLA.
uv run scenario scenario=... traffic=hybrid \
    traffic.options.mesoscopic.micro_radius_m=120 \
    traffic.options.mesoscopic.horizon_s=6 \
    traffic.options.mesoscopic.max_microscopic=60

# The in-process queue model instead of a second SUMO.
uv run scenario scenario=... traffic=hybrid traffic.options.mesoscopic.engine=queue

It is the traffic_manager backend in everything else -- the same manoeuvres, the same vehicle parameters (traffic.vehicles, those traffic_manager supports), the same background traffic (below) -- and with mesoscopic.enabled=false it is that backend exactly.

Which vehicles change level. Only background traffic (spawn_background, the background traffic actions): the TrafficManager backend keeps a scenario vehicle's route, lane changes and parameters by its actor, and a condition may read that actor at any time, so the scenario's own vehicles stay in CARLA (mesoscopic.scenario_vehicles: true is refused). The focus points are the ego and every other vehicle in CARLA that is not background traffic; a run with none of those changes nobody's level. Each decision (update_interval_s) is plan_fidelity's, with every option of MesoscopicConfig as the sumo backend reads it: the radii, horizon_s, max_microscopic -- which here bounds the background vehicles in CARLA.

How a vehicle leaves CARLA. The backend finds the road of SUMO's network the vehicle is on, by its position and heading (within 3.5 m of a lane of the road, and within 60 degrees of its direction: not in a junction, which waits for the next decision), puts it there in the mesoscopic model, capped at the speed it was spawned with, and destroys its actor. The TrafficManager tells nobody where it was going, so the model gives it a route on from there, a road chosen at random at each junction -- as the TrafficManager chooses its own -- six roads ahead, and six more as it nears their end; a vehicle that reaches a dead end leaves the run, as the TrafficManager's would. The routes are drawn from the run's seed.

How it comes back. On the nearest driving lane to where the model has it (the model has no lanes: its rightmost lane a car may use), facing along it, as the same blueprint with the same role_name (its handle), at the model's speed, on autopilot again and capped at its speed as before. The model has its bounding box's centre, as SUMO places a vehicle; it is spawned at the origin that puts its box there, by the box offset it had when it left (about a metre behind the centre for a car), so it does not come back a metre ahead each time it changes level. The lane is looked up at the height of SUMO's lane there -- a network converted from OpenDRIVE keeps the roads' elevation -- so a stacked or elevated road gives the right level. A spot CARLA refuses (taken) leaves it out until the next decision. background_vehicles() reports every background vehicle wherever it is, by its origin, as the TrafficManager's are -- one out of CARLA where the model has it, at its lane's height where SUMO's network has one and with no height otherwise -- and background_actors() only those in CARLA; remove_background() takes one out of either.

traffic.options Default Meaning
port traffic_manager.port, else 8100 The TrafficManager's port, as traffic_manager's.
mesoscopic enabled: true MesoscopicConfig, as the sumo backend's (below), on by default here; scenario_vehicles is refused.
net_path null A SUMO network of the map to use as it is, instead of converting the world's OpenDRIVE. Non-empty text or null: '' is refused.
cache_dir null Where converted networks are cached (the sumo backend's cache). Non-empty text or null: '' is refused.

The engines. mesoscopic.engine: sumo (the default) is SUMO's own mesoscopic simulation, a second SUMO (--mesosim, segment_length_m), written to <output_dir>/<stem>.sumo/sumo_meso.log; its junctions run SUMO's own signal programs, since CARLA's lights are matched to SUMO's only by the sumo backend. engine: queue is the in-process queue model (headway_s, jam_spacing_m), which holds nobody at a junction here, having no signals to read; it needs sumolib and SUMO's network of the map (net_path, or the world's OpenDRIVE converted with roadgen and netconvert), but not the sumo binary, which only engine: sumo looks up. Either binary is the one in $SUMO_HOME or the eclipse-sumo package, else the one on PATH.

describe() adds mesoscopic -- the engine, the radii and the changes of level so far -- and fidelity_census() counts the vehicles the TrafficManager drives as microscopic and the model's as mesoscopic.

The SUMO backend

traffic=sumo co-simulates SUMO with the CARLA world. It needs the sumo extra (autoware-carla-scenario[sumo]: SUMO, libsumo and roadgen, all wheels); without it the run is refused in prepare(), before anything is spawned.

uv run scenario scenario=lane_change/left map=town10hd_opt traffic=sumo
uv run scenario ... traffic=sumo traffic.options.ambient.vehicles_per_hour=1800
uv run scenario ... traffic=sumo traffic.options.scenario_vehicles=sumo
uv run scenario ... traffic=sumo traffic.options.scenario_pedestrians=sumo
uv run scenario ... traffic=sumo traffic.options.fcd_output=true   # <output>/{stem}.sumo/fcd.xml
uv run scenario ... traffic=sumo traffic.options.use_libsumo=false traffic.options.binary=sumo-gui

To watch a run, run SUMO as a TraCI process (use_libsumo: false) with binary: sumo-gui. Its window stays open after the run, for a look at how it ended, until it is closed (or --quit-on-end in sumo_args closes it at once). A headless sumo is ended with the run: it is given 5 s to exit once its connection closes, then killed, and a failed start kills it and quotes what it wrote to its standard error.

Its switches -- publish_walkers, pedestrian_crossings, cycle_on_sidewalks, use_libsumo, fcd_output, ambient.enabled, ambient.use_safe_weights, pedestrians.enabled, bicycles.enabled and mesoscopic.enabled, mesoscopic.scenario_vehicles and mesoscopic.junction_control under traffic.options -- are each true or false, or a spelling of either ("false", "no", "off", "0", 0, and "true", "yes", "on", "1", 1), read as the run's own switches are (The switches): so a quoted traffic.options.fcd_output='false' is false. Anything else (maybe, 2, null) is refused before the run, naming the option by its full key as traffic.options.ambient.enabled must be true or false, got 'maybe'. So does every other option's error, and it shows the value as written (traffic.options.warmup_s must be finite and not negative (got -1)).

Its sections -- ambient, pedestrians, bicycles and mesoscopic under traffic.options -- are mappings. An absent or null one is the default; false, 0, "" or a list is refused before the run, naming it (traffic.options.ambient must be a mapping, got False), rather than failing once the backend reads it. Its text options -- net_path, route_path, cache_dir, blueprint, binary and pedestrians.blueprint -- are non-empty strings: '', false or 0 is refused, naming the option, rather than read as the default. A null option is its default, as an absent one is -- blueprint: null is vehicle.lincoln.mkz, tm_port: null the TrafficManager's port -- under traffic.options and in each of its sections, for the hybrid backend's options (a null mesoscopic.enabled is true there) and the traffic_manager backend's port too. So a null bicycles.blueprints is the default list; [] is none, which keeps every SUMO bicycle out of CARLA. The exception is an option that takes null as a value of its own, whose null is that value and not its default: lateral_resolution_m: null is SUMO's lane-based model (below), curve_lateral_acceleration: null the map converted as it is, bicycles.max_distance_m: null no limit. A run hands these backends' options over nulls included, so traffic.options.lateral_resolution_m=null on the command line does what it says (#2178); a backend an installed package registers is handed none (Writing a backend).

Its outputs are the run's own: everything the backend writes -- SUMO's log (sumo.log), the demand it generates (ambient.rou.xml, pedestrians.rou.xml, bicycles.rou.xml), the type files below and, with fcd_output, the floating car data (fcd.xml) and the SUMO time of each CARLA tick (clock.csv) -- goes in <output>/{stem}.sumo/, named by the run's file stem like its _result.json (CutInScenario.sumo/, then CutInScenario-1.sumo/ ...). A batch shares one output directory, so each run keeps its own; the directory counts as one of the run's outputs, so a later run never takes its stem and a retried run clears it first (run_outputs.RUN_DIR_SUFFIXES).

When SUMO keeps failing -- 20 steps in a row raise -- the backend stops stepping it for the rest of the run, and leaves nothing it drove moving on its own: the mirrors of SUMO's vehicles, bicycles and pedestrians are destroyed, every scenario vehicle SUMO drove (scenario_vehicles=sumo), or had yet to put on its road after a spawn brought it up, loses its constant velocity (vehicle_control=teleport) or its last control (physics) and brakes to a stop, and every scenario pedestrian it walked stands still. Vehicles it does not drive (the ego, the TrafficManager's, those an action took over) are left alone; one an action hands back afterwards brakes to a stop too, and a SUMO vehicle's mirror an action hands back is destroyed. It logs an error, and the run goes on without traffic rather than failing: the result records when it gave up (traffic.gave_up_at_s, simulated seconds; null in a run where it did not), so a batch can tell such runs apart.

The network is the world's own road network. The backend takes the OpenDRIVE the world runs (the file the run installed, or world.get_map().to_opendrive()), converts it with roadgen into netconvert's plain-XML input and builds it with netconvert. The result is cached under ~/.cache/autoware_carla_scenario/sumo/, keyed by the OpenDRIVE and the tool versions, so a map is converted once. roadgen writes the network without offset normalisation, so SUMO's x/y are OpenDRIVE's and CARLA's are the same with y mirrored. traffic.options.net_path runs on an existing .net.xml instead.

Note

CARLA's maps bend the OpenDRIVE schema in a few places roadgen's strict parser refuses (<userData> without code, <roadMark> without color, objects of type -1, <cornerLocal> without height); the backend strips or fills those before converting. An OpenDRIVE whose junctions name connections to roads they do not list (the Nishishinjuku map's) is refused by roadgen's validation.

Ownership follows the seam's rule: the scenario owns what it authored.

Vehicle Driven by In SUMO
Ego (autoware, carla_driver) its entity published: moved to its CARLA pose every tick
Scenario NPCs, autopilot ego the TrafficManager (scenario_vehicles=traffic_manager, default), or SUMO (scenario_vehicles=sumo) published, or driven
Ambient traffic (randomTrips.py, ambient.enabled, off by default) SUMO native; mirrored into CARLA
Scenario pedestrians (PedestrianEntity, e.g. WalkStraightAction) CARLA (scenario_pedestrians=traffic_manager, default), or SUMO (scenario_pedestrians=sumo) published, or walked
Other CARLA pedestrians (walker.pedestrian.*) CARLA published as SUMO persons (publish_walkers, on by default)
SUMO's pedestrians (randomTrips.py --pedestrians, pedestrians.enabled) SUMO native; mirrored into CARLA as walkers near the ego
Scenario bicycles (a vehicle whose blueprint's base_type is bicycle) as the scenario's other vehicles published or driven, as a SUMO bicycle
SUMO's bicycles (randomTrips.py --vclass bicycle, bicycles.enabled) SUMO native; mirrored into CARLA as bicycles near the ego
Scenario motorcycles (MotorcycleEntity, or any vehicle whose blueprint's base_type is motorcycle) as the scenario's other vehicles published or driven, as a SUMO motorcycle
Scenario emergency vehicles (EmergencyVehicleEntity, or any vehicle whose blueprint's special_type is emergency) as the scenario's other vehicles published or driven, as a SUMO emergency vehicle with a bluelight device

A published vehicle has SUMO's speed and lane-change control switched off, so SUMO traffic sees it where CARLA has it and reacts to it. With the default the scenario's NPCs behave exactly as under the traffic_manager backend, while SUMO fills the rest of the road.

How much of SUMO's traffic reaches CARLA: an ambient vehicle is mirrored into CARLA while it is within spawn_radius_m of the ego, at most max_vehicles of them, the nearest first; the rest drive in SUMO only, where its traffic still sees them. null (the default) is no radius and no limit, and a limit of 0 mirrors none. A limit must be a whole number from 0, a radius positive and finite. Until there is an ego to measure from, the first max_vehicles SUMO lists are mirrored. SUMO's own pedestrians and bicycles have limits of their own (pedestrians.max_persons, bicycles.max_bicycles), read the same way.

A published pedestrian is a SUMO person moved to its CARLA pose every tick with moveToXY and keepRoute 6: placed exactly there, on whichever lane is there, footway or road. A SUMO vehicle brakes for a person on its lane, on a crossing or anywhere else, or changes lanes round it. A person has to be added on an edge with a footway -- SUMO aborts the whole simulation when one is moved off an edge without -- so a pedestrian with no footway within 50 m (or on a network with none) is left out, with a warning.

The scenario's pedestrians walked by SUMO (scenario_pedestrians=sumo): each PedestrianEntity the scenario registers is a SUMO person from the start of the run, and its CARLA walker follows that person, as a mirrored walker follows one of SUMO's own. Standing, the person is put where its walker stands every tick. A WalkStraightAction walks the person straight on, the way its walker faces, through TraCI: each step it is moved on along the line at the action's speed (moveToXY, keepRoute 6, so off the kerb it is on the road lanes, where SUMO's traffic brakes for it), until a second action stops it (speed_ms: 0). This is TraCI's walk, not SUMO's pedestrian model, which walks footways and crossings to a destination and so has no way to step off the kerb where a pedestrian stands. An action that moves the walker itself (a RoutingAction in follow/position mode, an adversity) takes it back from SUMO, which publishes it from then on. A pedestrian with no footway within 50 m stays CARLA's, as a published one would.

SUMO's own pedestrians (pedestrians, off by default) walk the network's footways (randomTrips.py --pedestrians, unweighted, up to max_distance_m each) and are mirrored into CARLA as walkers (blueprint, with the role name sumo:<id>) while they are near the ego or a vehicle CARLA drives: within radius_m, kept until 1.25 times as far, at most max_persons of them, the nearest first (null: no limit; 0: none). With radius_m: null the radii are mesoscopic's when that is enabled; otherwise every one is mirrored. The rest walk on in SUMO only, where SUMO's traffic still sees them. A walker is put where its person was at the start of the step and walked at its speed (WalkerControl), so CARLA animates it; it is never published back into SUMO as one of CARLA's pedestrians. How they walk is traffic.pedestrians (Traffic parameters).

Pedestrian crossings (pedestrian_crossings, on by default): the network is built with a crossing across each road at a junction where footways meet it, and walking areas joining footways and crossings (netconvert's --crossings.guess), so pedestrians cross roads on crossings — where SUMO's vehicles yield to them — instead of jumping between footways. At a signalised junction netconvert appends the crossings' links after the vehicle links, so the vehicle links keep the indices CARLA's lights are matched to. With traffic_light_authority=carla a crossing is green while every vehicle link into or out of a road it crosses is red, gives way (o) while they are red or switched off and some are off (a dark junction), and is red otherwise; with sumo, SUMO's own program (which netconvert gives a pedestrian phase) drives it. A network given as net_path is used as it is.

uv run scenario ... traffic=sumo traffic.options.pedestrians.enabled=true \
    traffic.options.pedestrians.radius_m=80

Bicycles on sidewalks (cycle_on_sidewalks, off by default): the network is built with roadgen's export_sumo(cycle_on_sidewalks=True) (roadgen 0.41.1 or later, which the sumo extra requires), so bicycles may ride every sidewalk, both ways, as well as the carriageway. Each sidewalk gets a bicycle edge each way along it (<edge>.bike<index> and <edge>.bike<index>.rev), open to bicycles and pedestrians; the sidewalk lane itself stays the pedestrians'. A bicycle may change between sidewalk and road at every junction and every 50 m at most between, ride across the road wherever a crossing is, and turn back at a dead end. At a junction without a light a bicycle coming off the sidewalk gives way to the traffic it meets. At a signalised one roadgen's program gives such a bicycle a green of its own ahead of the traffic; with traffic_light_authority=carla, where CARLA's lights switch the traffic, a bicycle coming onto the road goes with the traffic of the road beside its sidewalk (and gives way), one getting off the road goes with the traffic it leaves, and one riding across a road goes while every vehicle link SUMO's own program never lets go with it is red. Where those links are switched off, the bicycle gives way (o), as the traffic does. Off, sidewalks are the pedestrians' and bicycles keep to the carriageway and the cycle lanes. The network is cached apart from one built without, and a network given as net_path is used as it is.

SUMO's own bicycles (bicycles, off by default) ride from and to edges a bicycle may use (randomTrips.py --vclass bicycle, unweighted, each at least min_distance_m and under max_distance_m long, so min_distance_m must be less than max_distance_m) and are mirrored into CARLA as bicycles, each one of blueprints (those the world lacks are left out; with none left, or with blueprints: [], bicycles ride in SUMO only, where its traffic still sees them; a null blueprints is CARLA's bicycles), with the role name sumo:<id>. They count against limits of their own: radius_m (the vehicles' spawn_radius_m when null) and max_bicycles (null: no limit; 0: none), apart from max_vehicles. A mirror follows its bicycle as bicycles.vehicle_control says, teleport by default: a bicycle changing between sidewalk and road crosses the kerb, which CARLA's vehicle physics would trip on. Bicycles stay in SUMO when mesoscopic is enabled: the queue model's roads are the carriageways.

How they ride is not traffic.vehicles -- a driver's parameters, which never reach a bicycle -- but traffic.bicycles (BicycleParameters, Traffic parameters).

The scenario's own bicycles ride by it too: a vehicle whose blueprint's base_type is bicycle (CARLA's bicycles') joins SUMO as a bicycle, on the nearest lane a bicycle may use -- a sidewalk's, on a network that has them -- published or driven like the scenario's other vehicles, and SUMO routes one it drives (scenario_vehicles=sumo) only where bicycles may go.

uv run scenario ... traffic=sumo traffic.options.cycle_on_sidewalks=true \
    traffic.options.bicycles.enabled=true traffic.options.bicycles.max_bicycles=20 \
    traffic.bicycles.max_speed_mps.mean=4.0 traffic.bicycles.max_speed_mps.std=0.8

Motorcycles: a scenario's motorcycle -- a MotorcycleEntity, or any vehicle whose blueprint's base_type is motorcycle -- joins SUMO as a vehicle of the class motorcycle, of the type acs_motorcycle that every run declares (SUMO has no default one; it has SUMO's defaults for the class), with its CARLA bounding box as its length and width. It rides the carriageway, is published or driven like the scenario's other vehicles, takes the drivers' parameters (traffic.vehicles) as a car does, and may leave for the mesoscopic model like them. Under the TrafficManager backend a motorcycle is a vehicle like any other: put on autopilot at the start of the run and given its manoeuvres (speed, lane changes, turns, routes) as every NPC is.

from autoware_carla_scenario import (
    MotorcycleEntity,
    MotorcycleEntityConfig,
    SpawnPointIndex,
)

# Whichever motorcycle the CARLA server has (`vehicle_type` names none) ...
rider = MotorcycleEntity(MotorcycleEntityConfig("rider", SpawnPointIndex(6)))
# ... or one by name, refused at spawn if it is not a motorcycle's blueprint.
named = MotorcycleEntity(
    MotorcycleEntityConfig("rider2", SpawnPointIndex(7), vehicle_type="vehicle.yamaha.yzf")
)
rider.spawn(world)
self.register_entity(rider)

Emergency vehicles: a scenario's emergency vehicle -- an EmergencyVehicleEntity, or any vehicle whose blueprint's special_type is emergency (CARLA's police cars, ambulances and fire engines) -- joins SUMO as a vehicle of the class emergency, of the type acs_emergency that every run declares, with SUMO's bluelight device (has.bluelight.device). It joins off duty: the device silent (reactiondist 0) and SUMO's own speed mode (31), not the 7 the device gives it, so it stops at red lights as any car does. EmergencyVehicleEntity.set_emergency(True) puts it on a call:

TrafficManager SUMO
Siren lights (VehicleLightState.Special1) on on
Red lights, stop signs runs them (ignore_lights_percentage / ignore_signs_percentage 100) one SUMO drives runs red lights (speed mode 15: no red-light braking, still giving way at the junction)
Other traffic does not make way SUMO's vehicles within reactiondist (25 m) make way: a rescue lane

set_emergency(False) puts it off duty again: lights off, and under the TrafficManager back to its own draw of traffic.vehicles.ignore_lights / ignore_signs (else 0). A call before the run starts (the config's emergency=True, or set_emergency in setup()) holds: the vehicle joins the run on it. A backend that has no notion of an emergency vehicle (none) warns and drives it as before; the lights are switched all the same.

from autoware_carla_scenario import (
    EmergencyVehicleEntity,
    EmergencyVehicleEntityConfig,
    SpawnPointIndex,
)

# Whichever emergency vehicle the CARLA server has, off duty ...
ambulance = EmergencyVehicleEntity(
    EmergencyVehicleEntityConfig("ambulance", SpawnPointIndex(8))
)
# ... or one by name, on a call from its spawn.
police = EmergencyVehicleEntity(
    EmergencyVehicleEntityConfig(
        "police", SpawnPointIndex(9), vehicle_type="vehicle.dodge.charger_police",
        emergency=True,
    )
)
ambulance.spawn(world)
self.register_entity(ambulance)

# Later, when the scenario's emergency begins (on_tick, ...):
ambulance.set_emergency(True)

EmergencyAction does the same from a trigger, and is what the scenario editor offers (Vehicle / Lights > Emergency):

from autoware_carla_scenario import EmergencyAction, ElapsedTimeCondition

# On a call 3 s in, off duty again 20 s in.
self.register_pre_tick(
    EmergencyAction("ambulance", True, ElapsedTimeCondition(3.0, label="siren_on"))
)
self.register_pre_tick(
    EmergencyAction("ambulance", False, ElapsedTimeCondition(20.0, label="siren_off"))
)

Stepping: one SUMO step per CARLA tick, with the step length set to the world's fixed_delta_seconds and the seed to the scenario's. CARLA poses are published before SUMO steps; SUMO's result is applied to the actors after it. step_length_s makes SUMO's step shorter: it must divide the tick in whole milliseconds, as SUMO's clock counts them (0.01 or 0.025 for a 0.05 s tick, not 0.0125), and SUMO then makes that many steps per tick, with the CARLA poses it sees held for all of them. A step_length_s that does not is refused when the config is read, before the run starts CARLA. Without step_length_s the tick itself is SUMO's step, so it must be whole milliseconds too. The runner always ticks at 0.05 s; a backend prepared with a tick that is not whole milliseconds (1/30 s, which SUMO would round to 0.033 s and fall 3 s behind CARLA every 300 s) is refused.

Lane changes: SUMO runs its sublane model (lateral_resolution_m, 0.4 m by default, --lateral-resolution): a vehicle's lateral position is continuous, so it never jumps to the new lane in one step but moves across at its own traffic.vehicles.max_lateral_speed_mps and max_lateral_accel. A vehicle SUMO drives does not move sideways while it stands (lcMaxSpeedLatStanding 0): left to SUMO's default, one held behind a pedestrian edges round them a hand's breadth away, which no car under CARLA's physics could do. lateral_resolution_m: null falls back to SUMO's lane-based model, where a lane change still moves across continuously, over lane_change_duration_s (3 s unset, --lanechange.duration) and no faster than max_lateral_speed_mps. SUMO takes one or the other, so lane_change_duration_s with a sublane width is an error.

# Gentler lane changes, five SUMO steps per 0.05 s tick.
uv run scenario ... traffic=sumo traffic.options.step_length_s=0.01 \
    traffic.vehicles.max_lateral_speed_mps.mean=0.8 \
    traffic.vehicles.max_lateral_accel.mean=0.6

How a CARLA vehicle follows its SUMO vehicle is vehicle_control:

  • physics (default) drives it with CARLA's vehicle physics, as TeraSim's ackermann_physics mode does. SUMO plans; each tick the car is steered towards a point 4-10 m ahead on SUMO's lanes (pure pursuit, offset by SUMO's lateral position mid lane change), and a PI throttle/brake controller with SUMO's acceleration as feedforward drives it at SUMO's speed, corrected by how far it is behind or ahead. Two CARLA 0.10 quirks are handled: its Ackermann controller's speed loop oscillates (so speed is controlled here and sent as throttle and brake), and its steering input maps onto the wheels roughly as 51° × steer² rather than linearly (so the steer command inverts that and closes a loop on the car's measured curvature). A car further than resync_distance_m from its SUMO vehicle is put back on it. By default SUMO does not see where physics actually put the car, so gaps SUMO keeps are kept to within the tracking error -- on Town10 p95 1.1 m. feedback_distance_m (off by default) moves a SUMO vehicle to its car when the two are further apart than that, with SUMO's own moveTo, which takes effect at once and leaves SUMO planning the next step (TeraSim patches SUMO for an XY variant of it); inside junctions nothing is corrected. On Town10 it did not reduce contacts: a SUMO vehicle moved back to a lagging car is re-planned from a state its own model would not have reached. SUMO's car-following models read no curvature, so a vehicle takes a bend at the speed limit -- on Town10 up to ~10 m/s² sideways, more than a car under physics can follow. curve_lateral_acceleration (3.0 m/s² by default) has roadgen cut each edge at its bends and give every piece, and every path across a junction, the speed sqrt(a / curvature) its sharpest point allows; SUMO's vehicles then brake for a bend before they reach it. The pieces keep the edge's id on the first and <edge>.p1, <edge>.p2, … after it, and roadgen's trace has every one.
  • teleport places it where its SUMO vehicle was at the start of the step and gives it SUMO's speed as a constant velocity (enable_constant_velocity), which carries it to where SUMO is at the end of it: exact, but the car is not driven by its physics. The poses of a tick go to CARLA in one batch, and a speed only when it is not the one the car already has (a standing car, in a queue at a light say, is given its zero once).

Visibility (traffic.vehicles.follow_visibility, on by default): SUMO's traffic sees only as far as the run's weather lets a driver see. How far drivers see is worked out before the run from the conditions the run names (Visibility follows the conditions); during the run only an EnvironmentAction given visibility_m changes it (one that sets the fog, the rain or the sun alone leaves the visibility as it was, so a mid-run fog change does not slow the traffic without one), and the backend holds each of SUMO's own vehicles (ambient and background) to the speed its driver keeps in that distance: the weather rules' sight_speed (Weather rules), which reads the visibility, at the driver's own quantile (visibility.driver_quantile, from the vehicle's id), scaled to the vehicle's own tau (reaction time) and decel (braking; traffic.vehicles.reaction_time_s and decel when set), and never above the speed it stops from within the visibility, v * tau + v² / (2 * decel) -- a default car in 50 m of fog drives at about 46-62 km/h, at night under a dipped beam (50 m) the same. A vehicle that departs later is held as it departs, and when the weather lifts each gets its own maximum speed back. A vehicle that leaves SUMO for the mesoscopic model (Far traffic below) while held keeps the held speed there, follows the visibility as it changes, and gets its own back when the weather lifts or it returns to SUMO, where it is held anew as it departs if the weather has not lifted; one that went into the mesoscopic model before the weather closed in has no reaction time or braking there to be held by, and is held only once it returns. The scenario's own vehicles, driven by SUMO or not, are left to the scenario. traffic.vehicles.follow_visibility=false ignores the visibility. It used to be traffic.options.follow_visibility, which is now an error pointing here.

The road's grip (EnvironmentAction's tire friction, Tire friction follows the weather) is CARLA's vehicle physics alone: SUMO's models are not told it, and plan their vehicles' braking as on a dry road. A car under vehicle_control: physics follows that plan on the grip CARLA gives its wheels.

Traffic lights (traffic_light_authority): carla (default) gives SUMO's signals the states of CARLA's lights every step, so a scenario that sets the lights sets them for SUMO's traffic too; sumo drives CARLA's lights from SUMO's programs; none leaves each alone. CARLA's lights are applied while SUMO warms up too, so the queues it starts with are the ones they would build. Under carla, Red, Yellow and Green set SUMO's r, y and G (g where SUMO's own program has a permissive green), and a light switched Off -- a dark junction, as a signal controller's off phase or TrafficSignalAction(state=Off) makes one -- sets o, SUMO's "off, blinking": its vehicles give way by the junction's right-of-way rules, as drivers do at a dark signal. Not O, "off, no signal", which gives a link the right of way and, on every link of a junction, would let crossing streams drive as if each had priority. Unknown says nothing of what a light shows, so its links keep the state they have. Under sumo, SUMO's red-yellow (u) and its green right-turn arrow that a driver must stop at first (s, a right turn on red) show as CARLA's Red, and a signal switched off (o blinking, O dark) as Off. A CARLA light switching several links shows the state of the last one with a regular state (r u y g G); an s, o or O link decides only for a light with no other.

Which SUMO signal links a CARLA light switches is read off roadgen's traces, written beside the network when it is built: the light is the OpenDRIVE signal of its get_opendrive_id(), roadgen records which map element that signal became when it reads the OpenDRIVE (map.xodr.trace.json), and which SUMO links of the junction's program that element became when it writes the network (network.sumo.trace.json). A light whose signal reached no link is named in a warning, and SUMO keeps its own program there. That holds link by link: setting a junction's state switches SUMO to a fixed program of its own, so the links of a junction where CARLA's lights switch others -- and that no bicycle ride or pedestrian crossing follows -- are given the state SUMO's original program shows each step, read before the first state is set and stepped through phase by phase at each phase's duration (an actuated program at its phases' default ones). The start log names them; a junction whose program cannot be read is named in a warning, and those links then hold the state they had. A network given as net_path has no traces, and its links are matched geometrically instead: a light's stop waypoints to the SUMO lane there.

On Town10HD_Opt all 15 lights match, 56 links between them; SUMO's only other signal links are on emergency-only shoulder lanes.

Far traffic (mesoscopic, off by default) leaves SUMO for a mesoscopic model, and CARLA with it, once it is further than meso_radius_m from every vehicle CARLA drives (the ego, and the scenario's vehicles under scenario_vehicles=traffic_manager or an action), and comes back -- into SUMO on the best lane for its route, and into CARLA -- when it is within micro_radius_m of one again. SUMO then steps only the traffic near what CARLA drives, and CARLA holds an actor only for that, so a large demand costs what the traffic around the ego costs. This is a sumo option only: the TrafficManager backend keeps every vehicle in CARLA (why).

uv run scenario ... traffic=sumo traffic.options.mesoscopic.enabled=true \
    traffic.options.mesoscopic.micro_radius_m=150

The mesoscopic model is chosen with engine:

engine The far traffic runs in
sumo (default) SUMO's own mesoscopic simulation: a second SUMO, started with --mesosim on the same network (TraCI, a process of its own, since libsumo runs one simulation per process; its log is <output>/{stem}.sumo/sumo_meso.log). Eissfeldt's queue model as SUMO has it, with SUMO's junction model, and the run's signals copied into it every step.
queue The cut-down queue model of traffic.mesoscopic, in-process: FIFO roads, a capacity of headway_s per lane, spill-back at jam_spacing_m, a red light holding the head of the queue. Cheaper to start, and no process of its own.
# The in-process queue model instead of SUMO's
uv run scenario ... traffic=sumo traffic.options.mesoscopic.enabled=true \
    traffic.options.mesoscopic.engine=queue
Option Default
engine sumo the mesoscopic model, above
micro_radius_m 200 a mesoscopic vehicle this close to a focus point comes back
meso_radius_m 1.25 × micro_radius_m a microscopic one further than this from all of them leaves
update_interval_s 1.0 simulated seconds between two decisions; the mesoscopic model steps every tick
scenario_vehicles false let the scenario's vehicles SUMO drives (scenario_vehicles=sumo) leave CARLA too
horizon_s 0 look this far ahead: a vehicle's distance is the closest it and a focus point come within this time, each at its velocity now (below)
max_microscopic null at most this many of the vehicles that may leave are microscopic at once, the nearest; null: no limit (below)
segment_length_m 20 engine: sumo: the segments SUMO's mesoscopic model cuts a road into (--meso-edgelength)
headway_s, jam_spacing_m 1.5, 7.5 engine: queue: the queue model's capacity per lane, and the road a queued vehicle takes up
junction_control true hold a mesoscopic vehicle at a SUMO signal unless it is green (G, g) or switched off (o, O) on some lane of its move: red, red-yellow, yellow and a right turn on red (s) hold it. Under engine: sumo, SUMO's --meso-junction-control, with the microscopic SUMO's signal states

An option left out, or null, is its default. false, 0 and '' are values like any other: a number refuses false and '' as not numbers and 0 where it must be positive, and a switch reads false and 0 as off and refuses '' (the switches). A value refused is named by its full key and shown as written: micro_radius_m: 0 is traffic.options.mesoscopic.micro_radius_m must be positive and finite (got 0).

When a vehicle changes level is the radii's decision, with two options that refine it:

  • horizon_s looks ahead. The distance the radii are compared with is the closest a vehicle and a focus point come within horizon_s, each going on at its velocity now, rather than how far apart they are. A mesoscopic vehicle heading for the ego -- or one the ego is heading for -- becomes microscopic before it is within micro_radius_m, and has settled on its lane by the time it is; one moving away does not. A microscopic vehicle that is leaving meso_radius_m but will be back within it stays. It is the remedy for the popping measured below, where vehicles appeared within sight: micro_radius_m the sensors' range, and horizon_s what the vehicles cover before they are in it.
  • max_microscopic caps how many vehicles are microscopic at once -- the nearest by the distance above; the rest are mesoscopic however near -- so a dense map costs SUMO and CARLA at most that many. It counts only the vehicles that may leave: the ego, every vehicle CARLA drives, and the scenario's vehicles unless scenario_vehicles is set are microscopic whatever it says.
# Microscopic within 120 m, or within 120 m in the next 6 s; never more than 60.
uv run scenario ... traffic=sumo traffic.options.mesoscopic.enabled=true \
    traffic.options.mesoscopic.micro_radius_m=120 \
    traffic.options.mesoscopic.horizon_s=6 \
    traffic.options.mesoscopic.max_microscopic=60

Under engine: sumo, three things SUMO's mesoscopic model does not do are done around it:

  • Where a vehicle is. SUMO puts a mesoscopic vehicle at the start of the segment it is in; the backend moves it on from there at its speed, up to the segment's end, so it comes back where it would be rather than up to a segment behind.
  • A speed it is told. SUMO takes a new speed only at the next segment, refuses a top speed of 0 and implements neither setSpeed nor resume in its mesoscopic model. A vehicle told a new speed is taken out and put back in where it is, so the speed holds from there; one told to stand is held out of SUMO, where it is, until it may drive again. Those behind it do not queue up behind it meanwhile: a stop that never ends would hold them, but SUMO does not wake the vehicles queued behind one taken out of its mesoscopic model, so they would stand on after it drove off.
  • Its id. Each time a vehicle goes into SUMO's mesoscopic model it does so under an id of its own there (<id>@meso<n>), so one that leaves and comes back in the same step is not refused. The backend, and everything that asks it, knows it by its own.

A vehicle leaves only from a normal edge, never from inside a junction, and comes back with its route, its type, length, width and top speed, and a speed it was told to keep. A scenario's vehicle comes back at the height of its lane in SUMO's network, which keeps the OpenDRIVE's elevation; on a network without any (all its heights 0), at the height of the driving lane CARLA finds nearest to where SUMO has it, so it is not put at z = 0 on a map whose roads are not. A scenario's vehicle that is mesoscopic takes set_desired_speed and turn_at_junction in the mesoscopic model; it cannot change lanes there, and says so. scenario_vehicles is off by default because such a vehicle has no actor while it is far: a scenario that reads it -- a condition on its speed -- should check entity.simulation_fidelity, or call entity.require_microscopic(world) first. SUMO's FCD output records the microscopic vehicles only.

Measured on Town10HD_Opt

The options above were first checked against SUMO and a fake CARLA. These numbers come from a real CARLA 0.10 server with Town10HD_Opt (#449), measured with tools/traffic_benchmark, before engine existed: the mesoscopic rows are the queue model's (engine: queue).

The setup:

  • the ego is driven by the TrafficManager for 120 s;
  • SUMO's ambient demand is 4000 vehicles per hour;
  • the figures cover the ticks after the first 20 s;
  • "tick" means the wall time of world.tick() plus the backend's tick.
Configuration Tick, mean Tick, p95 Vehicles in CARLA In the queue model
every SUMO vehicle mirrored 42.8 ms 55.4 ms 79 --
spawn_radius_m=150 21.0 ms 28.0 ms 42 --
mesoscopic (default radii), physics 40.3 ms 51.7 ms 76 2
mesoscopic (default radii), teleport 18.1 ms 25.2 ms 76 2
mesoscopic, micro_radius_m=80, physics 9.1 ms 13.1 ms 16 49

What the measurements show:

  • Town10HD_Opt is small. Within the default 200 m nearly all of it is near the ego, so the queue model holds little and the mesoscopic mode saves next to nothing. A micro radius that leaves the queue model most of the map (80 m here) cuts the tick to a fifth.
  • Popping. With a small radius, vehicles come and go within sight. At 80 m they appear about 95 m from the ego (median) and leave about 114 m away. Choose the radius from what the scenario's sensors must see, not from the map.
  • Cost of control. teleport costs the backend a quarter of what physics does (7 ms against 28 ms a tick here).

What was observed:

  • Returning vehicles. A vehicle coming back from the queue model appears on its lane, never overlapping another. The closest same-lane neighbours were 5.2 m apart, centre to centre, in a queue at a light; the vehicles 3.5 m away were in the next lane. Queued vehicles come back stopped, where the queue stands.
  • Physics on appearing. Under physics, a vehicle that comes into CARLA drops about 0.5 m onto the road and drives off well below SUMO's speed (#1003). teleport does not.
  • Pedestrians. In 120 s with 2400 persons per hour, 27 persons stepped onto the 16 signalled crossings and none did so on red. Over 1914 ticks of a crossing showing green, the road it crosses was never green too. Every SUMO person near the ego was a CARLA walker, which the ego's sensors see as any walker.
  • A scenario vehicle. With mesoscopic.scenario_vehicles=true and scenario_vehicles=sumo, a scenario vehicle left CARLA once it was far and came back, as a new actor, once it was near. The "has no actor" warning was logged once, when it left.
  • Collision logging. NPC collision logging stopped as vehicles left CARLA (fixed in #999).
  • Walker blueprint. The persons' default blueprint was not in CARLA 0.10 (fixed in #1002).

Manoeuvres of SUMO-driven vehicles become TraCI calls: change_lane → changeLane (SUMO obeys a solid line, and says so), set_desired_speed → setSpeed, turn_at_junction → a route onto the junction's outgoing edge in that direction. With the default, they go to the TrafficManager. follow_route goes to the TrafficManager only: a vehicle SUMO drives keeps its route, since the route's lanelets are not mapped to SUMO edges.

The coupling follows TeraSim's CARLA co-simulation; its adversarial behaviour generation is left to scenarios.