Ring-road driver agents
Drivers on a circular highway.
- Class:
RingRoadDriversSystem - Import:
from skcomplex.systems.engineering.traffic import RingRoadDriversSystem - Field:
engineering/traffic - Topics:
traffic,jams,agents,stochastic - References:
- Downey 2018
- Resnick 1994
Use this system
The block imports the class and simulates the system with its default parameters and its tuned run settings.
from skcomplex.systems.engineering.traffic import RingRoadDriversSystem
trajectory = RingRoadDriversSystem().prepare().simulate()
Parameters
The model parameters take these defaults, and set_params changes them.
| Parameter | Default |
|---|---|
n_cars |
30 |
length |
1000.0 |
eps |
0.02 |
speed_limit |
40.0 |
solver |
'auto' |
backend |
'auto' |
Tags
The system with its default parameters has these capability tags, which solvers and analyses check.
| Tag | Values |
|---|---|
| Time | discrete |
| Space | continuous |
| Laws | update |
| Randomness | stochastic |
| Domains | integer, real |
| Structure | variable membership |
Class
The source of the class shows how it builds its components from its model parameters.
class RingRoadDriversSystem(BaseSystem):
"""Drivers on a circular highway.
Small random errors of speed set off traffic jams. The cars start at rest, equally spaced. Every driver accelerates
by 1 per step up to the speed limit, the speed takes a random relative error of up to `eps`, and a speed that would
reach the car ahead becomes 0. The system has the group `drivers` of speeds `speed` on a ring road of length
`length`.
Args:
n_cars:
The number of cars.
length:
The length of the ring road.
eps:
The relative amplitude of the random error of speed.
speed_limit:
The largest speed.
label:
The label of the system, which names it when it is nested in another one.
solver:
The solver of the problem, or `'auto'` for the one the system chooses.
backend:
The backend that evaluates the compiled functions, or `'auto'` for the one the system chooses.
Examples:
>>> from skcomplex.systems.engineering.traffic import RingRoadDriversSystem
>>> RingRoadDriversSystem(10).prepare().system_.space.prepare().extent_[0]
1000.0
"""
field = 'engineering/traffic'
topics = ('traffic', 'jams', 'agents', 'stochastic')
references = ('Downey 2018', 'Resnick 1994')
until = 100
def __init__(
self,
n_cars: int = 30,
length: float = 1000.0,
*,
eps: float = 0.02,
speed_limit: float = 40.0,
label: str = 'system',
solver: BaseSolver | str = 'auto',
backend: BaseBackend | str = 'auto',
) -> None:
super().__init__(label, solver=solver, backend=backend)
self.n_cars = n_cars
self.length = length
self.eps = eps
self.speed_limit = speed_limit
def _prepare(self, context: Sequence[Observable] | None = None) -> None:
"""Set `system_` to the components of the system built from its model parameters."""
super()._prepare(context)
positions = np.linspace(0.0, self.length, self.n_cars, endpoint=False)
road = ContinuousSpace(extent=(self.length, ROAD_WIDTH), boundary='periodic')
drivers = DriverElement(
'drivers',
rank=np.arange(self.n_cars, dtype=float),
speed_limit=self.speed_limit,
eps=self.eps,
values={'x': positions, 'y': ROAD_WIDTH / 2},
size=self.n_cars,
space=road,
)
self.system_ = System(
self.label,
elements=[drivers],
interactions=[RingRoadDrivingInteraction('drive', target='drivers')],
space=road,
)
Components
The system uses these element and interaction classes, each with its nearest class of the core.
Elements:
DriverElement, fromElement
Interactions:
RingRoadDrivingInteraction, fromInteraction
class DriverElement(Element):
"""Driver on a ring road who accelerates as much as allowed.
The driver stops when the speed would cause a collision, by the rule of `RingRoadDrivingInteraction`.
Args:
label:
The label of the agent or group.
speed:
The speed.
rank:
The order of the car along the ring.
acceleration:
The acceleration every driver chooses.
min_acc:
The largest braking, as a negative acceleration.
max_acc:
The largest acceleration.
speed_limit:
The largest speed.
eps:
The relative amplitude of the random error of speed.
values:
Further values by name, such as the position `x` and `y` of every driver on the road.
size:
The number of drivers, or `None` for one.
space:
The road, a continuous space whose axes `x` and `y` place the drivers, or `None` for none.
Examples:
>>> from skcomplex.systems.engineering.traffic import DriverElement
>>> DriverElement('drivers', values={'x': [0.0, 10.0], 'y': 0.5}, size=2).size
2
"""
visual = VisualSpec('agents', {'color_by': 'speed'})
def __init__(
self,
label: str,
*,
speed: Annotated[float, RealSet.closed_open(0, oo)] = 0.0,
rank: Annotated[object, NN] = 0.0,
acceleration: float = 1.0,
min_acc: float = -10.0,
max_acc: float = 1.0,
speed_limit: Annotated[float, RealSet.open(0, oo)] = 40.0,
eps: Annotated[float, RealSet.closed_open(0, oo)] = 0.02,
values: Mapping[str, object] | None = None,
size: int | None = None,
space: BaseSpace | None = None,
) -> None:
super().__init__(label, values=values, size=size, space=space)
self.speed = speed
self.rank = rank
self.acceleration = acceleration
self.min_acc = min_acc
self.max_acc = max_acc
self.speed_limit = speed_limit
self.eps = eps
class RingRoadDrivingInteraction(Interaction):
"""Driving rule of the drivers on a ring road.
The speed of a driver changes by its acceleration, bounded by `min_acc` and `max_acc`, is multiplied by a random
factor between `1 - eps` and `1 + eps`, and stays between 0 and the speed limit. A speed larger than the distance to
the car ahead becomes 0. The car then moves along the ring by its speed, and the ring is as long as the width of
the space.
Args:
label:
The label of the interaction.
target:
The path of the group of drivers.
Examples:
>>> from skcomplex.systems.engineering.traffic import RingRoadDrivingInteraction
>>> RingRoadDrivingInteraction('drive', target='drivers').target
'drivers'
"""
draws = True
law_classes = (UpdateLaw,)
def __init__(self, label: str, *, target: Role) -> None:
super().__init__(label)
self.target = target
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the driving rule of every driver.
Args:
context:
The namespace of the elements a binding of the roles names.
"""
super()._prepare(context)
self.laws_: list[BaseLaw] = [UpdateLaw(context.target, self.drive)]
def drive(self, agent: DriverView, system: SystemView) -> None:
"""Choose the speed from the distance to the car ahead and move along the ring.
Args:
agent:
The driver.
system:
The system.
"""
cars = cast(list[DriverView], system.get_agents(self.target))
if system.dimensions is None:
error_msg = 'Drivers move along a ring road, a continuous space with an extent.'
raise SimulationError(error_msg)
length = system.dimensions[0]
ahead = self._get_car_ahead(agent, system, len(cars))
x, y = RingRoadDrivingInteraction._get_position(agent)
distance = (RingRoadDrivingInteraction._get_position(ahead)[0] - x) % length if ahead is not None else length
acceleration = min(max(agent.acceleration, agent.min_acc), agent.max_acc)
speed = (agent.speed + acceleration) * system.rng.uniform(1 - agent.eps, 1 + agent.eps)
speed = min(max(speed, 0.0), agent.speed_limit)
agent.speed = 0.0 if speed > distance else speed
agent.move_to(((x + agent.speed) % length, y))
@staticmethod
def _get_position(agent: AgentViewProtocol) -> tuple[float, float]:
"""Return the position of an agent in a continuous space."""
x, y = np.asarray(agent.location, dtype=float)
return float(x), float(y)
def _get_car_ahead(self, agent: DriverView, system: SystemView, n_cars: int) -> DriverView | None:
"""Return the car whose rank follows the agent's rank on a road of `n_cars` cars.
It is `None` for the last car.
"""
rank = (int(agent.rank) + 1) % n_cars if n_cars else 0
return next(
(
car
for car in cast(list[DriverView], system.get_agents(self.target))
if int(car.rank) == rank and car != agent
),
None,
)