Skip to content

Charbonneau traffic

Charbonneau's traffic system.

  • Class: CharbonneauTrafficSystem
  • Import: from skcomplex.systems.engineering.traffic import CharbonneauTrafficSystem
  • Field: engineering/traffic
  • Topics: traffic, jams, agents, avalanches, stochastic
  • References:
    • Charbonneau 2017

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 CharbonneauTrafficSystem

trajectory = CharbonneauTrafficSystem().prepare().simulate()

Parameters

The model parameters take these defaults, and set_params changes them.

Parameter Default
n_cars 100
probability 0.1
safe_distance 5.0
speed_limit 10.0
random_state 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 none
Laws update
Randomness deterministic
Domains integer, real
Structure variable membership

Class

The source of the class shows how it builds its components from its model parameters.

class CharbonneauTrafficSystem(BaseSystem):
    """Charbonneau's traffic system.

    Random braking of single drivers sets off traffic jams. Cars on a one-way road start at rest with random spacings
    between 3 and 17. Every step, each driver brakes by 3 when the car ahead is closer than the safe distance and
    accelerates by 1 otherwise, within the speed limit. A random driver brakes with a probability every step, and then
    every car moves by its speed. The system has the group `cars` of positions `x`, speeds `v`, and ranks `rank`.

    Args:
        n_cars:
            The number of cars.

        probability:
            The probability that a random driver brakes in a step.

        safe_distance:
            The distance to the car ahead below which drivers brake.

        speed_limit:
            The largest speed.

        random_state:
            The seed or generator of the initial spacings.

        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 CharbonneauTrafficSystem
        >>> CharbonneauTrafficSystem(5).prepare().system_.elements[0].size
        5
    """

    field = 'engineering/traffic'
    topics = ('traffic', 'jams', 'agents', 'avalanches', 'stochastic')
    references = ('Charbonneau 2017',)
    until = 100

    def __init__(
        self,
        n_cars: int = 100,
        *,
        probability: float = 0.1,
        safe_distance: float = 5.0,
        speed_limit: float = 10.0,
        random_state: int | np.random.Generator | None = 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.probability = probability
        self.safe_distance = safe_distance
        self.speed_limit = speed_limit
        self.random_state = random_state

    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)
        rng = np.random.default_rng(self.random_state)
        positions = np.cumsum(rng.uniform(3.0, 17.0, self.n_cars))
        cars = MotoristElement(
            'cars',
            x=positions,
            v=np.zeros(self.n_cars),
            rank=np.arange(self.n_cars, dtype=float),
            safe_distance=self.safe_distance,
            speed_limit=self.speed_limit,
            size=self.n_cars,
        )
        self.system_ = System(
            self.label,
            elements=[cars],
            interactions=[
                SafeDistanceInteraction('adjust', target='cars'),
                CarelessBrakingInteraction('braking', cars='cars', probability=self.probability),
            ],
        )

Components

The system uses these element and interaction classes, each with its nearest class of the core.

Elements:

Interactions:

  • SafeDistanceInteraction, from Interaction
  • CarelessBrakingInteraction, from Interaction
class MotoristElement(Element):
    """Car of Charbonneau's traffic system.

    It brakes when it is closer than a safe distance to the car ahead, by the rule of `SafeDistanceInteraction`.

    Args:
        label:
            The label of the agent or group.

        x:
            The position along the road.

        v:
            The speed.

        rank:
            The order of the car along the road, 0 for the last car.

        safe_distance:
            The distance to the car ahead below which the driver brakes.

        braking:
            The speed lost when braking.

        acceleration:
            The speed gained when accelerating.

        speed_limit:
            The largest speed.

        size:
            The number of cars, or `None` for one.

    Examples:
        >>> from skcomplex.systems.engineering.traffic import MotoristElement
        >>> MotoristElement('cars', x=[0.0, 10.0, 20.0], size=3).size
        3
    """

    visual = VisualSpec('agents', {'position': 'x', 'color_by': 'v'})

    def __init__(
        self,
        label: str,
        *,
        x: object = 0.0,
        v: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
        rank: Annotated[object, NN] = 0.0,
        safe_distance: Annotated[float, RealSet.open(0, oo)] = 5.0,
        braking: Annotated[float, RealSet.closed_open(0, oo)] = 3.0,
        acceleration: Annotated[float, RealSet.closed_open(0, oo)] = 1.0,
        speed_limit: Annotated[float, RealSet.open(0, oo)] = 10.0,
        size: int | None = None,
    ) -> None:
        super().__init__(label, size=size)
        self.x = x
        self.v = v
        self.rank = rank
        self.safe_distance = safe_distance
        self.braking = braking
        self.acceleration = acceleration
        self.speed_limit = speed_limit

class SafeDistanceInteraction(Interaction):
    """Speed rule of the cars of Charbonneau's traffic system.

    Every step a driver brakes by its braking when the car ahead is closer than its safe distance, and accelerates by
    its acceleration otherwise, within its speed limit.

    Args:
        label:
            The label of the interaction.

        target:
            The path of the group of cars.

    Examples:
        >>> from skcomplex.systems.engineering.traffic import SafeDistanceInteraction
        >>> SafeDistanceInteraction('adjust', target='cars').target
        'cars'
    """

    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 speed rule of every car.

        Args:
            context:
                The namespace of the elements a binding of the roles names.
        """
        super()._prepare(context)
        self.laws_: list[BaseLaw] = [UpdateLaw(context.target, self.adjust)]

    def adjust(self, agent: MotoristView, system: SystemView) -> None:
        """Brake when the car ahead is too close and accelerate otherwise.

        The car brakes when the car ahead is closer than the safe distance. The lead car, which has no car ahead, keeps
        its distance to the car behind it instead.

        Args:
            agent:
                The car.

            system:
                The system.
        """
        cars = cast(list[MotoristView], system.get_agents(self.target))
        ahead = next((car for car in cars if int(car.rank) == int(agent.rank) + 1), None)
        if ahead is None:
            behind = next((car for car in cars if int(car.rank) == int(agent.rank) - 1), None)
            distance = agent.x - behind.x if behind is not None else np.inf
        else:
            distance = ahead.x - agent.x
        change = -agent.braking if distance < agent.safe_distance else agent.acceleration
        agent.v = float(np.clip(agent.v + change, 0.0, agent.speed_limit))

class CarelessBrakingInteraction(Interaction):
    """System rule of Charbonneau's traffic system.

    Every step, with probability `probability`, one random driver brakes by the braking of its group whatever the
    distance to the car ahead. Then every car moves by its speed, but no closer than `gap` to the car ahead.

    Args:
        label:
            The label of the interaction.

        cars:
            The path of the group of cars.

        probability:
            The probability that a random driver brakes in a step.

        gap:
            The smallest distance a car keeps to the car ahead.

    Examples:
        >>> from skcomplex.systems.engineering.traffic import CarelessBrakingInteraction
        >>> CarelessBrakingInteraction('bozo', cars='cars').probability
        0.1
    """

    law_classes = (UpdateLaw,)

    def __init__(
        self,
        label: str,
        *,
        cars: Role,
        probability: Annotated[float, RealSet.closed_open(0, oo)] = 0.1,
        gap: Annotated[float, RealSet.closed_open(0, oo)] = 1.0,
    ) -> None:
        super().__init__(label)
        self.cars = cars
        self.probability = probability
        self.gap = gap

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the rule of random braking and motion of the whole road.

        Args:
            context:
                The namespace of the elements a binding of the roles names.
        """
        super()._prepare(context)
        self.laws_: list[BaseLaw] = [UpdateLaw(context, self.drive)]

    def drive(self, system: SystemView) -> None:
        """Make a random driver brake, then move every car.

        The driver brakes with the interaction's probability.

        Args:
            system:
                The system.
        """
        cars = sorted(cast(list[MotoristView], system.get_agents('cars')), key=lambda car: car.rank)
        if not cars:
            return
        if system.rng.random() < self.probability:
            careless = cars[int(system.rng.integers(len(cars)))]
            careless.v = max(careless.v - careless.braking, 0.0)
        gap = self.gap
        positions = [car.x for car in cars]
        for index, car in enumerate(cars):
            moved = car.x + car.v
            car.x = min(moved, positions[index + 1] - gap) if index + 1 < len(cars) else moved

Equations

The equations are those that symbolic returns for the system with its default parameters.