plafosim.simulator module

class plafosim.simulator.CF_Model(value)[source]

Bases: Enum

Car Following models that vehicles can use for their mobility.

ACC = 1
CACC = 2
HUMAN = 0
class plafosim.simulator.EmissionClass(value)[source]

Bases: Enum

Emission class for combustion engines using the HBEFA3 model.

Website: https://www.hbefa.net/

PC_G_EU4 = 0
property emission_factors: dict

Return the emission factors of the emission class.

Returns:

dict

Return type:

The emission factors of the emission class

property is_diesel: bool

Return whether the emission class is for a diesel engine.

Returns:

bool

Return type:

Whether the emission class is for a diesel engine

class plafosim.simulator.Infrastructure(simulator: Simulator, iid: int, position: int, formation_algorithm: str, execution_interval: int, **kw_args)[source]

Bases: object

A class representing road side infrastructure / road side units.

The infrastructure can execute formation algorithms.

__init__(simulator: Simulator, iid: int, position: int, formation_algorithm: str, execution_interval: int, **kw_args)[source]

Initialize an Infrastructure instance.

Parameters:
  • simulator (Simulator) – The global simulator object

  • iid (int) – The id of the infrastructure

  • position (int) – The position (x) of the infrastructure

  • formation_algorithm (str) – The platoon formation (i.e., assignment calculation) algorithm to run

  • execution_interval (int) – The execution interval for the formation algorithm

_action(step: int)[source]

Triggers concrete actions of an infrastructure.

Parameters:

step (int) – The current simulation step

_get_neighbors()[source]
action(step: int)[source]

Triggers actions of an infrastructure.

Parameters:

step (int) – The current simulation step

finish()[source]

Clean up the instance of the infrastructure.

property iid: int

Return the id of an infrastructure.

property position: int

Return the position of an infrastructure.

class plafosim.simulator.PlatoonRole(value)[source]

Bases: Enum

A collection of available platoon roles.

FOLLOWER = 2
JOINER = 3
LEADER = 1
LEAVER = 4
NONE = 0
class plafosim.simulator.PlatooningVehicle(simulator: Simulator, vid: int, vehicle_type: VehicleType, depart_position: int, arrival_position: int, desired_speed: float, depart_lane: int, depart_speed: float, depart_time: float, depart_delay: float = 0, communication_range: int = 1000, acc_headway_time: float = 1.0, cacc_spacing: float = 5.0, formation_algorithm: str = None, execution_interval: int = 1, pre_filled: bool = False, **kw_args)[source]

Bases: Vehicle

A vehicle that has platooning functionality.

__init__(simulator: Simulator, vid: int, vehicle_type: VehicleType, depart_position: int, arrival_position: int, desired_speed: float, depart_lane: int, depart_speed: float, depart_time: float, depart_delay: float = 0, communication_range: int = 1000, acc_headway_time: float = 1.0, cacc_spacing: float = 5.0, formation_algorithm: str = None, execution_interval: int = 1, pre_filled: bool = False, **kw_args)[source]

Initialize a platooning vehicle instance.

Parameters:
  • simulator (Simulator) – The global simulator object

  • vid (int) – The id of the vehicle

  • vehicle_type (VehicleType) – The vehicle type of the vehicle

  • depart_position (int) – The departure position of the vehicle

  • arrival_position (int) – The arrival position of the vehicle

  • desired_speed (float) – The desired driving speed of the vehicle

  • depart_lane (int) – The departure lane of the vehicle

  • depart_speed (float) – The departure speed of the vehicle

  • depart_time (float) – The actual departure time of the vehicle

  • depart_delay (float) – The time the vehicle had to wait before starting its trip

  • communication_range (int) – The maximum communication range of the vehicle

  • acc_headway_time (float) – The headway time for the ACC

  • cacc_spacing (float) – The constant spacing for the CACC

  • formation_algorithm (str) – The platoon formation algorithm to use

  • execution_interval (int) – The interval for executing the formation algorithm

  • pre_filled (bool) – Whether this vehicle was pre-filled

_action(step: float)[source]

Triggers specific actions of a PlatooningVehicle.

Parameters:

step (float) – The current simulation step

_calculate_emission(a: float, v: float, f: list, scale: float) float[source]

Calculate the emitted pollutant amount using the given speed and acceleration.

Parameters:
  • a (float) – The current acceleration

  • v (float) – The current speed

  • f (list) – The emission factors to use for current emission variable to be calculated

  • scale (float) – The scale to normalize the calculated value

Returns:

float

Return type:

The calculcated emission in ml/mg per s

_calculate_emissions()

Calculate the emitted pollutant amount using the given speed and acceleration based on the HBEFA3 model.

As the functions are defining emissions in g/hour, the function’s result is normed by 3.6 (seconds in an hour/1000) yielding mg/s. For fuel ml/s is returned. Negative acceleration results directly in zero emission.

The amount emitted by the given emission class when moving with the given velocity and acceleration [mg/s or ml/s]

_get_available_platoons() list[source]

Return the available platoon candidates of the vehicle.

This imitates neighbor maintenance by using a neighbor table.

Returns:

list(PlatooninVehicle)

Return type:

The list of available platoons

_join(platoon_id: int, leader_id: int)[source]

Lets a vehicle join a platoon.

Communication and fine-grained maneuver control is out-of-scope and thus omitted.

Parameters:
  • platoon_id (int) – The id of the target platoon

  • leader_id (int) – The id of the leader of the target platoon

_join_teleport(leader: PlatooningVehicle, last: PlatooningVehicle, new_position: float)[source]

Perform the actual teleporting of the join maneuver.

Parameters:
  • leader (PlatooningVehicle) – The leader of the target platoon

  • last (PlatooningVehicle) – The last vehicle of the target platoon

  • new_position (float) – The new position for joining the target platoon

_leave()[source]

Lets a vehicle leave a platoon.

Communication and fine-grained maneuver control is out-of-scope and thus omitted.

_left_lane_blocked() bool[source]

Check whether a vehicle can move to the left lane in order to leave its current platoon.

Returns:

bool

Return type:

Whether the left lane is blocked

_start()

Start this Vehicle.

_statistics()[source]

Write continuous statistics.

_teleport(new_position: float, new_lane: int, new_speed: float)[source]

Teleport a vehicle to a given position.

Parameters:
  • new_position (float) – The new position

  • new_lane (int) – The new lane

  • new_speed (float) – The new speed

action(step: int)

Triggers actions of a vehicle.

Parameters:

step (int) – The current simulation step

calculate_approaching_time(target_position: float, target_speed: float) float[source]

Calculate approximate time to approach the target position at target speed.

Parameters:
  • target_position (float) – The target position to approach

  • target_speed (float) – The target speed after approaching

Returns:

float

Return type:

The calculated approaching time

finish()[source]

Clean up the instance of the PlatooningVehicle.

This includes leaving the platoon and mostly statistics recording.

get_front_gap() float[source]

Return the gap to the vehicle in the front.

This imitates a measurement of the front radar sensor.

get_front_speed() float[source]

Return the speed to the vehicle in the front.

This imitates a measurement of the front radar sensor.

info() str[source]

Return information about the PlatooningVehicle.

is_in_platoon() bool[source]

Return whether the vehicle currently is in a platoon.

This is based on the current PlatoonRole. A joining or leaving vehicle is either not yet or still part of a platoon, thus the returned value should be true.

property acc_headway_time: float

Return the ACC headway time of the vehicle.

property arrival_position: int

Return the arrival position of the vehicle.

property blocked_front: bool

Return whether the vehicle is currently blocked by a slow vehicle in the front.

property cf_model: CF_Model

Return the currently activated car following model of the vehicle.

property color: tuple

Return the current color of the vehicle.

property depart_lane: int

Return the departure lane of the vehicle.

property depart_position: int

Return the departure position of the vehicle.

property depart_speed: float

Return the departure speed of the vehicle.

property depart_time: float

Return the departure time of the vehicle.

property desired_gap: float

Return the desired gap of the vehicle.

This is based on the currently active car following model.

property desired_headway_time: float

Return the desired headway time of the vehicle.

This is based on the currently active car following model.

property desired_speed: float

Return the desired driving speed of the vehicle.

If the vehicle is in a platoon, it returns the desired driving speed of the entire platoon.

property distance_in_platoon: float

Return the travelled distance within platoons.

property headway_time: float

Return the human headway time of the vehicle.

This is based on the vehicle type.

property in_maneuver: bool

Return whether the vehicle is currently in a maneuver.

property lane: int

Return the current lane of the vehicle.

property length: int

Return the length of the vehicle.

This is based on the vehicle type.

property max_acceleration: float

Return the maximum acceleration of the vehicle.

This is based on the vehicle type.

property max_deceleration: float

Return the maximum deceleration of the vehicle.

This is based on the vehicle type.

property max_speed: float

Return the maximum speed of the vehicle.

This is based on the vehicle type.

property min_gap: float

Return the minimum safety gap to the vehicle in front of the vehicle.

This is based on the vehicle type.

property platoon: Platoon

Return the platoon of the vehicle.

property platoon_role: PlatoonRole

Return the current platoon role of the vehicle.

property position: float

Return the current position of the vehicle.

property rear_position: int

Return the current rear position of the vehicle.

property speed: float

Return the current driving speed of the vehicle.

property time_in_platoon: int

Return the travelled time within platoons.

property travel_distance: float

Return the current traveled distance of the vehicle.

property travel_time: float

Return the current traveled time of the vehicle.

property vehicle_type: VehicleType

Return the VehicleType of the vehicle.

property vid: int

Return the id of the vehicle.

class plafosim.simulator.Simulator(*, road_length: int = 100000, number_of_lanes: int = 3, ramp_interval: int = 5000, pre_fill: bool = False, number_of_vehicles: int = 100, vehicle_density: float = -1, max_speed: float = 55, acc_headway_time: float = 1.0, cacc_spacing: float = 5.0, penetration_rate: float = 1.0, random_depart_position: bool = False, depart_all_lanes: bool = True, desired_speed: float = 33.0, random_desired_speed: bool = True, speed_variation: float = 0.1, min_desired_speed: float = 22.0, max_desired_speed: float = 44.0, random_depart_speed: bool = False, depart_desired: bool = False, depart_flow: bool = False, depart_method: str = 'interval', depart_interval: float = 2.0, depart_probability: float = 1.0, depart_rate: int = 3600, random_arrival_position: bool = False, minimum_trip_length: int = 0, maximum_trip_length: int = -1000, communication_range: int = 500, distributed_platoon_knowledge: bool = True, distributed_maneuver_knowledge: bool = False, start_as_platoon: bool = False, reduced_air_drag: bool = True, maximum_teleport_distance: int = 2000, maximum_approach_time: int = 60, delay_teleports: bool = True, update_desired_speed: bool = True, formation_algorithm: str | None = None, formation_strategy: str = 'distributed', execution_interval: int = 10, number_of_infrastructures: int = 0, step_length: float = 1.0, max_step: int = 3600, actions: bool = True, collisions: bool = True, random_seed: int = -1, log_level: int = 30, progress: bool = True, gui: bool = False, gui_delay: int = 0, gui_track_vehicle: int = -1, sumo_config: str = 'sumocfg/freeway.sumo.cfg', gui_play: int = True, gui_start: int = 0, draw_ramps: bool = True, draw_ramp_labels: bool = False, draw_road_end: bool = True, draw_road_end_label: bool = True, draw_infrastructures: bool = True, draw_infrastructure_labels: bool = True, screenshot_filename: str | None = None, result_base_filename: str = 'results', record_simulation_trace: bool = False, record_end_trace: bool = True, record_vehicle_trips: bool = False, record_vehicle_emissions: bool = False, record_vehicle_traces: bool = False, record_vehicle_changes: bool = False, record_emission_traces: bool = False, record_platoon_trips: bool = False, record_platoon_maneuvers: bool = False, record_platoon_formation: bool = False, record_platoon_traces: bool = False, record_vehicle_platoon_traces: bool = False, record_platoon_changes: bool = False, record_infrastructure_assignments: bool = False, record_vehicle_teleports: bool = False, record_prefilled: bool = False, **kwargs: dict)[source]

Bases: object

A collection of parameters and information of the simulator.

__init__(*, road_length: int = 100000, number_of_lanes: int = 3, ramp_interval: int = 5000, pre_fill: bool = False, number_of_vehicles: int = 100, vehicle_density: float = -1, max_speed: float = 55, acc_headway_time: float = 1.0, cacc_spacing: float = 5.0, penetration_rate: float = 1.0, random_depart_position: bool = False, depart_all_lanes: bool = True, desired_speed: float = 33.0, random_desired_speed: bool = True, speed_variation: float = 0.1, min_desired_speed: float = 22.0, max_desired_speed: float = 44.0, random_depart_speed: bool = False, depart_desired: bool = False, depart_flow: bool = False, depart_method: str = 'interval', depart_interval: float = 2.0, depart_probability: float = 1.0, depart_rate: int = 3600, random_arrival_position: bool = False, minimum_trip_length: int = 0, maximum_trip_length: int = -1000, communication_range: int = 500, distributed_platoon_knowledge: bool = True, distributed_maneuver_knowledge: bool = False, start_as_platoon: bool = False, reduced_air_drag: bool = True, maximum_teleport_distance: int = 2000, maximum_approach_time: int = 60, delay_teleports: bool = True, update_desired_speed: bool = True, formation_algorithm: str | None = None, formation_strategy: str = 'distributed', execution_interval: int = 10, number_of_infrastructures: int = 0, step_length: float = 1.0, max_step: int = 3600, actions: bool = True, collisions: bool = True, random_seed: int = -1, log_level: int = 30, progress: bool = True, gui: bool = False, gui_delay: int = 0, gui_track_vehicle: int = -1, sumo_config: str = 'sumocfg/freeway.sumo.cfg', gui_play: int = True, gui_start: int = 0, draw_ramps: bool = True, draw_ramp_labels: bool = False, draw_road_end: bool = True, draw_road_end_label: bool = True, draw_infrastructures: bool = True, draw_infrastructure_labels: bool = True, screenshot_filename: str | None = None, result_base_filename: str = 'results', record_simulation_trace: bool = False, record_end_trace: bool = True, record_vehicle_trips: bool = False, record_vehicle_emissions: bool = False, record_vehicle_traces: bool = False, record_vehicle_changes: bool = False, record_emission_traces: bool = False, record_platoon_trips: bool = False, record_platoon_maneuvers: bool = False, record_platoon_formation: bool = False, record_platoon_traces: bool = False, record_vehicle_platoon_traces: bool = False, record_platoon_changes: bool = False, record_infrastructure_assignments: bool = False, record_vehicle_teleports: bool = False, record_prefilled: bool = False, **kwargs: dict)[source]

Initialize a simulator instance.

_add_vehicle(vid: int, vtype: VehicleType, depart_position: float, arrival_position: float, desired_speed: float, depart_lane: int, depart_speed: float, depart_time: float, depart_delay: float = 0, communication_range: int = 500, pre_filled: bool = False) Vehicle[source]

Add a vehicle to the simulation based on the given parameters.

NOTE: Make sure that you set last_vehicle_id correctly.

Parameters:
  • vid (int) – The id of the vehicle

  • vtype (VehicleType) – The vehicle type of the vehicle

  • depart_position (int) – The departure position of the vehicle

  • arrival_position (int) – The arrival position of the vehicle

  • desired_speed (float) – The desired driving speed of the vehicle

  • depart_lane (int) – The departure lane of the vehicle

  • depart_speed (float) – The departure speed of the vehicle

  • depart_time (float) – The actual departure time of the vehicle

  • depart_delay (float, optional) – The time the vehicle had to wait before starting its trip

  • communication_range (int, optional) – The maximum communication range of the vehicle

  • pre_filled (bool, optional) – Whether this vehicle was pre-filled

Returns:

The added vehicle

Return type:

Vehicle

_call_infrastructure_actions()[source]

Triggers actions on all infrastructures in the simulation.

_call_vehicle_actions()[source]

Triggers actions on all vehicles in the simulation.

_finish()[source]

Clean up the simulation.

_generate_infrastructures(number_of_infrastructures: int)[source]

Generate infrastructures for the simulation.

Parameters:

number_of_infrastructures (int) – The number of infrastructures to generate

_generate_vehicles()[source]

Add pre-filled vehicles to the simulation.

_get_predecessor(vehicle: Vehicle, lane: int = -1) Vehicle[source]

Return the preceding (i.e., front) vehicle for a given vehicle on a given lane.

Parameters:
  • vehicle (Vehicle) – The vehicle to consider

  • lane (int, optional) – The lane to consider. A lane of -1 indicates the vehicle’s current lane.

_get_predecessor_rear_position(vehicle: Vehicle, lane: int = -1) float[source]

Return the rear position of the preceding (i.e., front) vehicle for a given vehicle on a given lane.

Parameters:
  • vehicle (Vehicle) – The vehicle to consider

  • lane (int, optional) – The lane to consider. A lane of -1 indicates the vehicle’s current lane.

_get_predecessor_speed(vehicle: Vehicle, lane: int = -1) float[source]

Return the speed of the preceding (i.e., front) vehicle for a given vehicle on a given lane.

Parameters:
  • vehicle (Vehicle) – The vehicle to consider

  • lane (int, optional) – The lane to consider. A lane of -1 indicates the vehicle’s current lane.

_get_successor(vehicle: Vehicle, lane: int = -1) Vehicle[source]

Return the succeeding (i.e., back) vehicle for a given vehicle on a given lane.

Parameters:
  • vehicle (Vehicle) – The vehicle to consider

  • lane (int, optional) – The lane to consider. A lane of -1 indicates the vehicle’s current lane.

_get_vehicles_df() DataFrame[source]

Return a pandas Dataframe from the internal data structure.

Returns:

The Dataframe containing the vehicles as rows index: vid columns: [position, length, lane, ..]

Return type:

pandas.DataFrame

_initialize_gui()[source]

Initialize the GUI.

_initialize_prefilled_platoon()[source]

Initialize all pre-filled vehicles as one platoon.

_initialize_result_recording()[source]

Create output files for all (enabled) statistics and writes the headers.

_record_lane_changes(vdf: DataFrame)[source]

Record lane changes.

Parameters:

vdf (pd.DataFrame) – The Dataframe containing the vehicles as rows index: vid columns: [position, length, lane, ..]

_remove_arrived_vehicles(arrived_vehicles: list)[source]

Remove arrived vehicles from the simulation.

Parameters:

arrived_vehicles (list) – The ids of arrived vehicles

_spawn_vehicles(vdf: DataFrame)[source]

Spawns vehicles within the current step.

  1. Calculate how many vehicles should be spawned according to the departure method

  2. Calculate properties for these vehicles (e.g., desired speed)

  3. Add vehicles to spawn queue

  4. Spawn as many vehicles as possible from the queue (sorted by waiting time)

  5. Update queue

_statistics(vehicles_in_simulator: int, vehicles_in_queue: int, vehicles_spawned: int, vehicles_arrived: int, runtime: float, average_vehicle_speed: float, vehicles_braking_rough: int)[source]

Record some period statistics.

Parameters:
  • vehicles_in_simulator (int) – The number of vehicles in the scenario within this step

  • vehicles_in_queue (int) – The number of vehicles in the spawn queue within this step

  • vehicles_spawned (int) – The number of vehicles that departed within this step

  • vehicles_arrived (int) – The number of vehicles that arrived within this step

  • runtime (float) – The run time of this step

  • average_vehicle_speed (int) – The average driving speed amog all vehicles in the scenario within this step

  • vehicles_braking_rough (int) – The number of vehicles performing rough braking within this step

_update_gui()[source]

Update the GUI.

_vehicles_to_be_scheduled() int[source]

Calculate how many vehicles should be spawned according to the departure method.

Returns:

int

Return type:

The number of vehicles to be spawned within this time step

_write_back_vehicles_df(vdf: DataFrame)[source]

Write back the vehicle updates from a given pandas dataframe to the internal data structure.

Parameters:

vdf (pandas.DataFrame) – The Dataframe containing the vehicles as rows index: vid columns: [position, length, lane, ..]

run()[source]

Run the simulation with the specified parameters until it is stopped.

Main simulation method.

This is based on Krauss’ multi lane traffic: laneChange(); adjust(); move();

stop(msg: str)[source]

Stop the simulation with the given message.

Parameters:

msg (str) – The message to show after stopping the simulation

property number_of_lanes: int

Return the number of lanes.

property road_length: int

Return the road length in m.

property step: int

Return the current simulation step.

property step_length: float

Return the length of a simulation step.

class plafosim.simulator.Vehicle(simulator: Simulator, vid: int, vehicle_type: VehicleType, depart_position: int, arrival_position: int, desired_speed: float, depart_lane: int, depart_speed: float, depart_time: float, depart_delay: float, communication_range: int, pre_filled: bool = False)[source]

Bases: object

A collection of state information for a vehicle in the simulation.

A vehicle can really be anything that can move and can be defined by a vehicle type. It does not necessarily be driven by a computer (i.e., autonomous). However, by default it does have V2X functionality.

__init__(simulator: Simulator, vid: int, vehicle_type: VehicleType, depart_position: int, arrival_position: int, desired_speed: float, depart_lane: int, depart_speed: float, depart_time: float, depart_delay: float, communication_range: int, pre_filled: bool = False)[source]

Initialize a vehicle instance.

Parameters:
  • simulator (Simulator) – The global simulator object

  • vid (int) – The id of the vehicle

  • vehicle_type (VehicleType) – The vehicle type of the vehicle

  • depart_position (int) – The departure position of the vehicle

  • arrival_position (int) – The arrival position of the vehicle

  • desired_speed (float) – The desired driving speed of the vehicle

  • depart_lane (int) – The departure lane of the vehicle

  • depart_speed (float) – The departure speed of the vehicle

  • depart_time (float) – The actual departure time of the vehicle

  • depart_delay (float) – The time the vehicle had to wait before starting its trip

  • communication_range (int) – The maximum communication range of the vehicle

  • pre_filled (bool) – Whether this vehicle was pre-filled

_action(step: float)[source]

Triggers specific actions of a vehicle.

Parameters:

step (float) – The current simulation step

_calculate_emission(a: float, v: float, f: list, scale: float) float[source]

Calculate the actual emission of the vehicle.

Parameters:
  • a (float) – The current acceleration

  • v (float) – The current speed

  • f (list) – The emission factors to use for current emission variable to be calculated

  • scale (float) – The scale to normalize the calculated value

Returns:

float

Return type:

The calculcated emission in ml/mg per s

_calculate_emissions()[source]

Calculate the emitted pollutant amount using the given speed and acceleration based on the HBEFA3 model.

As the functions are defining emissions in g/hour, the function’s result is normed by 3.6 (seconds in an hour/1000) yielding mg/s. For fuel ml/s is returned. Negative acceleration results directly in zero emission.

The amount emitted by the given emission class when moving with the given velocity and acceleration [mg/s or ml/s]

_start()[source]

Start this Vehicle.

_statistics()[source]

Write continuous statistics for the vehicle.

action(step: int)[source]

Triggers actions of a vehicle.

Parameters:

step (int) – The current simulation step

finish()[source]

Clean up the instance of the vehicle.

This includes mostly statistic recording.

info() str[source]

Return information about the vehicle.

property arrival_position: int

Return the arrival position of the vehicle.

property blocked_front: bool

Return whether the vehicle is currently blocked by a slow vehicle in the front.

property cf_model: CF_Model

Return the currently activated car following model of the vehicle.

property color: tuple

Return the current color of the vehicle.

property depart_lane: int

Return the departure lane of the vehicle.

property depart_position: int

Return the departure position of the vehicle.

property depart_speed: float

Return the departure speed of the vehicle.

property depart_time: float

Return the departure time of the vehicle.

property desired_gap: float

Return the desired gap to the vehicle in front of the vehicle.

This is based on the desired headway time and the current driving speed.

property desired_headway_time: float

Return the desired headway time of the vehicle.

property desired_speed: float

Return the desired driving speed of the vehicle.

property headway_time: float

Return the human headway time of the vehicle.

This is based on the vehicle type.

property lane: int

Return the current lane of the vehicle.

property length: int

Return the length of the vehicle.

This is based on the vehicle type.

property max_acceleration: float

Return the maximum acceleration of the vehicle.

This is based on the vehicle type.

property max_deceleration: float

Return the maximum deceleration of the vehicle.

This is based on the vehicle type.

property max_speed: float

Return the maximum speed of the vehicle.

This is based on the vehicle type.

property min_gap: float

Return the minimum safety gap to the vehicle in front of the vehicle.

This is based on the vehicle type.

property position: float

Return the current position of the vehicle.

property rear_position: int

Return the current rear position of the vehicle.

property speed: float

Return the current driving speed of the vehicle.

property travel_distance: float

Return the current traveled distance of the vehicle.

property travel_time: float

Return the current traveled time of the vehicle.

property vehicle_type: VehicleType

Return the VehicleType of the vehicle.

property vid: int

Return the id of the vehicle.

class plafosim.simulator.VehicleType(name: str, length: int, max_speed: float, max_acceleration: float, max_deceleration: float, min_gap: float, headway_time: float, emission_class: str)[source]

Bases: object

A collection of parameters for a concrete vehicle type.

__init__(name: str, length: int, max_speed: float, max_acceleration: float, max_deceleration: float, min_gap: float, headway_time: float, emission_class: str)[source]

Initialize a specific vehicle type.

Parameters:
  • name (str) – The name of the vehicle type

  • length (int) – The length of the vehicle type

  • max_speed (float) – The maximum speed of the vehicle type

  • max_acceleration (float) – The maximum acceleration of the vehicle type

  • max_deceleration (float) – The maximum deceleration of the vehicle type

  • min_gap (float) – The minimum safety gap to the vehicle in front of the vehicle type

  • headway_time (float) – The human headway time of the vehicle type

  • emission_class (EmissionClass) – The emission class of the vehicle type

property emission_class: EmissionClass

Return the emission class of a vehicle type.

property emission_factors: dict

Return the emission factors of a vehicle type.

property headway_time: float

Return the desired human headway time of a vehicle type.

property length: int

Return the length of a vehicle type.

property max_acceleration: float

Return the maximum acceleration of a vehicle type.

property max_deceleration: float

Return the maximum deceleration of a vehicle type.

property max_speed: float

Return the maximum speed of a vehicle type.

property min_gap: float

Return the minimum gap of a vehicle type.

property name: str

Return the name of a vehicle type.

class plafosim.simulator.tqdm(*_, **__)[source]

Bases: Comparable

Decorate an iterable object, returning an iterator which acts exactly like the original iterable, but prints a dynamically updating progressbar every time a value is requested.

__init__(iterable=None, desc=None, total=None, leave=True, file=None, ncols=None, mininterval=0.1, maxinterval=10.0, miniters=None, ascii=None, disable=False, unit='it', unit_scale=False, dynamic_ncols=False, smoothing=0.3, bar_format=None, initial=0, position=None, postfix=None, unit_divisor=1000, write_bytes=None, lock_args=None, nrows=None, colour=None, delay=0, gui=False, **kwargs)[source]
Parameters:
  • iterable (iterable, optional) – Iterable to decorate with a progressbar. Leave blank to manually manage the updates.

  • desc (str, optional) – Prefix for the progressbar.

  • total (int or float, optional) – The number of expected iterations. If unspecified, len(iterable) is used if possible. If float(“inf”) or as a last resort, only basic progress statistics are displayed (no ETA, no progressbar). If gui is True and this parameter needs subsequent updating, specify an initial arbitrary large positive number, e.g. 9e9.

  • leave (bool, optional) – If [default: True], keeps all traces of the progressbar upon termination of iteration. If None, will leave only if position is 0.

  • file (io.TextIOWrapper or io.StringIO, optional) – Specifies where to output the progress messages (default: sys.stderr). Uses file.write(str) and file.flush() methods. For encoding, see write_bytes.

  • ncols (int, optional) – The width of the entire output message. If specified, dynamically resizes the progressbar to stay within this bound. If unspecified, attempts to use environment width. The fallback is a meter width of 10 and no limit for the counter and statistics. If 0, will not print any meter (only stats).

  • mininterval (float, optional) – Minimum progress display update interval [default: 0.1] seconds.

  • maxinterval (float, optional) – Maximum progress display update interval [default: 10] seconds. Automatically adjusts miniters to correspond to mininterval after long display update lag. Only works if dynamic_miniters or monitor thread is enabled.

  • miniters (int or float, optional) – Minimum progress display update interval, in iterations. If 0 and dynamic_miniters, will automatically adjust to equal mininterval (more CPU efficient, good for tight loops). If > 0, will skip display of specified number of iterations. Tweak this and mininterval to get very efficient loops. If your progress is erratic with both fast and slow iterations (network, skipping items, etc) you should set miniters=1.

  • ascii (bool or str, optional) – If unspecified or False, use unicode (smooth blocks) to fill the meter. The fallback is to use ASCII characters ” 123456789#”.

  • disable (bool, optional) – Whether to disable the entire progressbar wrapper [default: False]. If set to None, disable on non-TTY.

  • unit (str, optional) – String that will be used to define the unit of each iteration [default: it].

  • unit_scale (bool or int or float, optional) – If 1 or True, the number of iterations will be reduced/scaled automatically and a metric prefix following the International System of Units standard will be added (kilo, mega, etc.) [default: False]. If any other non-zero number, will scale total and n.

  • dynamic_ncols (bool, optional) – If set, constantly alters ncols and nrows to the environment (allowing for window resizes) [default: False].

  • smoothing (float, optional) – Exponential moving average smoothing factor for speed estimates (ignored in GUI mode). Ranges from 0 (average speed) to 1 (current/instantaneous speed) [default: 0.3].

  • bar_format (str, optional) –

    Specify a custom bar string formatting. May impact performance. [default: ‘{l_bar}{bar}{r_bar}’], where l_bar=’{desc}: {percentage:3.0f}%|’ and r_bar=’| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, ‘

    ’{rate_fmt}{postfix}]’

    Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt,

    percentage, elapsed, elapsed_s, ncols, nrows, desc, unit, rate, rate_fmt, rate_noinv, rate_noinv_fmt, rate_inv, rate_inv_fmt, postfix, unit_divisor, remaining, remaining_s, eta.

    Note that a trailing “: ” is automatically removed after {desc} if the latter is empty.

  • initial (int or float, optional) – The initial counter value. Useful when restarting a progress bar [default: 0]. If using float, consider specifying {n:.3f} or similar in bar_format, or specifying unit_scale.

  • position (int, optional) – Specify the line offset to print this bar (starting from 0) Automatic if unspecified. Useful to manage multiple bars at once (eg, from threads).

  • postfix (dict or *, optional) – Specify additional stats to display at the end of the bar. Calls set_postfix(**postfix) if possible (dict).

  • unit_divisor (float, optional) – [default: 1000], ignored unless unit_scale is True.

  • write_bytes (bool, optional) – If (default: None) and file is unspecified, bytes will be written in Python 2. If True will also write bytes. In all other cases will default to unicode.

  • lock_args (tuple, optional) – Passed to refresh for intermediate output (initialisation, iterating, and updating).

  • nrows (int, optional) – The screen height. If specified, hides nested bars outside this bound. If unspecified, attempts to use environment height. The fallback is 20.

  • colour (str, optional) – Bar colour (e.g. ‘green’, ‘#00ff00’).

  • delay (float, optional) – Don’t display until [default: 0] seconds have elapsed.

  • gui (bool, optional) – WARNING: internal parameter - do not use. Use tqdm.gui.tqdm(…) instead. If set, will attempt to use matplotlib animations for a graphical output [default: False].

Returns:

out

Return type:

decorated iterator.

classmethod _decr_instances(instance)[source]

Remove from list and reposition another unfixed bar to fill the new gap.

This means that by default (where all nested bars are unfixed), order is not maintained but screen flicker/blank space is minimised. (tqdm<=4.44.1 moved ALL subsequent unfixed bars up.)

classmethod _get_free_pos(instance=None)[source]

Skips specified instance.

clear(nolock=False)[source]

Clear current bar display.

close()[source]

Cleanup and (if leave=False) close the progressbar.

display(msg=None, pos=None)[source]

Use self.sp to display msg in the specified pos.

Consider overloading this function when inheriting to use e.g.: self.some_frontend(**self.format_dict) instead of self.sp.

Parameters:
  • msg (str, optional. What to display (default: repr(self)).) –

  • pos (int, optional. Position to moveto) – (default: abs(self.pos)).

classmethod external_write_mode(file=None, nolock=False)[source]

Disable tqdm within context and refresh tqdm when exits. Useful when writing to standard output stream

static format_interval(t)[source]

Formats a number of seconds as a clock time, [H:]MM:SS

Parameters:

t (int) – Number of seconds.

Returns:

out – [H:]MM:SS

Return type:

str

static format_meter(n, total, elapsed, ncols=None, prefix='', ascii=False, unit='it', unit_scale=False, rate=None, bar_format=None, postfix=None, unit_divisor=1000, initial=0, colour=None, **extra_kwargs)[source]

Return a string-based progress bar given some parameters

Parameters:
  • n (int or float) – Number of finished iterations.

  • total (int or float) – The expected total number of iterations. If meaningless (None), only basic progress statistics are displayed (no ETA).

  • elapsed (float) – Number of seconds passed since start.

  • ncols (int, optional) – The width of the entire output message. If specified, dynamically resizes {bar} to stay within this bound [default: None]. If 0, will not print any bar (only stats). The fallback is {bar:10}.

  • prefix (str, optional) – Prefix message (included in total width) [default: ‘’]. Use as {desc} in bar_format string.

  • ascii (bool, optional or str, optional) – If not set, use unicode (smooth blocks) to fill the meter [default: False]. The fallback is to use ASCII characters ” 123456789#”.

  • unit (str, optional) – The iteration unit [default: ‘it’].

  • unit_scale (bool or int or float, optional) – If 1 or True, the number of iterations will be printed with an appropriate SI metric prefix (k = 10^3, M = 10^6, etc.) [default: False]. If any other non-zero number, will scale total and n.

  • rate (float, optional) – Manual override for iteration rate. If [default: None], uses n/elapsed.

  • bar_format (str, optional) –

    Specify a custom bar string formatting. May impact performance. [default: ‘{l_bar}{bar}{r_bar}’], where l_bar=’{desc}: {percentage:3.0f}%|’ and r_bar=’| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, ‘

    ’{rate_fmt}{postfix}]’

    Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt,

    percentage, elapsed, elapsed_s, ncols, nrows, desc, unit, rate, rate_fmt, rate_noinv, rate_noinv_fmt, rate_inv, rate_inv_fmt, postfix, unit_divisor, remaining, remaining_s, eta.

    Note that a trailing “: ” is automatically removed after {desc} if the latter is empty.

  • postfix (*, optional) – Similar to prefix, but placed at the end (e.g. for additional stats). Note: postfix is usually a string (not a dict) for this method, and will if possible be set to postfix = ‘, ‘ + postfix. However other types are supported (#382).

  • unit_divisor (float, optional) – [default: 1000], ignored unless unit_scale is True.

  • initial (int or float, optional) – The initial counter value [default: 0].

  • colour (str, optional) – Bar colour (e.g. ‘green’, ‘#00ff00’).

Returns:

out

Return type:

Formatted meter and stats, ready to display.

static format_num(n)[source]

Intelligent scientific notation (.3g).

Parameters:

n (int or float or Numeric) – A Number.

Returns:

out – Formatted number.

Return type:

str

static format_sizeof(num, suffix='', divisor=1000)[source]

Formats a number (greater than unity) with SI Order of Magnitude prefixes.

Parameters:
  • num (float) – Number ( >= 1) to format.

  • suffix (str, optional) – Post-postfix [default: ‘’].

  • divisor (float, optional) – Divisor between prefixes [default: 1000].

Returns:

out – Number with Order of Magnitude SI unit postfix.

Return type:

str

classmethod get_lock()[source]

Get the global lock. Construct it if it does not exist.

moveto(n)[source]
classmethod pandas(**tqdm_kwargs)[source]
Registers the current tqdm class with

pandas.core. ( frame.DataFrame | series.Series | groupby.(generic.)DataFrameGroupBy | groupby.(generic.)SeriesGroupBy ).progress_apply

A new instance will be create every time progress_apply is called, and each instance will automatically close() upon completion.

Parameters:

tqdm_kwargs (arguments for the tqdm instance) –

Examples

>>> import pandas as pd
>>> import numpy as np
>>> from tqdm import tqdm
>>> from tqdm.gui import tqdm as tqdm_gui
>>>
>>> df = pd.DataFrame(np.random.randint(0, 100, (100000, 6)))
>>> tqdm.pandas(ncols=50)  # can use tqdm_gui, optional kwargs, etc
>>> # Now you can use `progress_apply` instead of `apply`
>>> df.groupby(0).progress_apply(lambda x: x**2)

References

<https://stackoverflow.com/questions/18603270/ progress-indicator-during-pandas-operations-python>

refresh(nolock=False, lock_args=None)[source]

Force refresh the display of this bar.

Parameters:
  • nolock (bool, optional) – If True, does not lock. If [default: False]: calls acquire() on internal lock.

  • lock_args (tuple, optional) – Passed to internal lock’s acquire(). If specified, will only display() if acquire() returns True.

reset(total=None)[source]

Resets to 0 iterations for repeated use.

Consider combining with leave=True.

Parameters:

total (int or float, optional. Total to use for the new bar.) –

set_description(desc=None, refresh=True)[source]

Set/modify description of the progress bar.

Parameters:
  • desc (str, optional) –

  • refresh (bool, optional) – Forces refresh [default: True].

set_description_str(desc=None, refresh=True)[source]

Set/modify description without ‘: ‘ appended.

classmethod set_lock(lock)[source]

Set the global lock.

set_postfix(ordered_dict=None, refresh=True, **kwargs)[source]

Set/modify postfix (additional stats) with automatic formatting based on datatype.

Parameters:
  • ordered_dict (dict or OrderedDict, optional) –

  • refresh (bool, optional) – Forces refresh [default: True].

  • kwargs (dict, optional) –

set_postfix_str(s='', refresh=True)[source]

Postfix without dictionary expansion, similar to prefix handling.

static status_printer(file)[source]

Manage the printing and in-place updating of a line of characters. Note that if the string is longer than a line, then in-place updating may not work (it will print a new line at each refresh).

unpause()[source]

Restart tqdm timer from last print time.

update(n=1)[source]

Manually update the progress bar, useful for streams such as reading files. E.g.: >>> t = tqdm(total=filesize) # Initialise >>> for current_buffer in stream: … … … t.update(len(current_buffer)) >>> t.close() The last line is highly recommended, but possibly not necessary if t.update() will be called in such a way that filesize will be exactly reached and printed.

Parameters:

n (int or float, optional) – Increment to add to the internal counter of iterations [default: 1]. If using float, consider specifying {n:.3f} or similar in bar_format, or specifying unit_scale.

Returns:

out – True if a display() was triggered.

Return type:

bool or None

classmethod wrapattr(stream, method, total=None, bytes=True, **tqdm_kwargs)[source]

stream : file-like object. method : str, “read” or “write”. The result of read() and

the first argument of write() should have a len().

>>> with tqdm.wrapattr(file_obj, "read", total=file_obj.size) as fobj:
...     while True:
...         chunk = fobj.read(chunk_size)
...         if not chunk:
...             break
classmethod write(s, file=None, end='\n', nolock=False)[source]

Print a message via tqdm (without overlap with bars).

property _comparable
_instances = set()
property format_dict

Public API for read-only member access.

monitor = None
monitor_interval = 10
plafosim.simulator.add_gui_vehicle(vid: int, position: float, lane: int, speed: float, color: tuple = (0, 255, 0), track: bool = False)[source]

Add a vehicle to the GUI.

Parameters:
  • vid (int) – The vehicle’s id

  • position (float) – The vehicle’s current position

  • lane (int) – The vehicle’s current lane

  • speed (float) – The vehicle’s current speed

  • color (tuple) – The vehicle’s current color

  • track (bool) – Whether to track this vehicle within the GUI

plafosim.simulator.assert_index_equal(one, two) bool[source]

Ensure the indices of two Sequences/DataFrames are equal.

Parameters:
  • one (pandas.Sequence / pandas.DataFrame) – The first object for the comparison

  • two (pandas.Sequence / pandas.DataFrame) – The second object for the comparsion

Returns:

bool

Return type:

Whether the two indices are equal

plafosim.simulator.check_and_prepare_gui()[source]

Check and prepare GUI environment.

plafosim.simulator.check_collisions(vdf: DataFrame) bool[source]

Do collision checks for all vehicles in the simulation.

Parameters:

vdf (pandas.DataFrame) – The Dataframe containing the vehicles as rows index: vid columns: [position, length, lane, ..]

Returns:

Whether there are collisions between vehicles

Return type:

bool

plafosim.simulator.close_gui()[source]

Close the GUI.

plafosim.simulator.compute_lane_changes(vdf: DataFrame, max_lane: int, step_length: float) DataFrame[source]

Find desired and safe lane changes.

  1. compute all speed gains

  2. “apply” all speed gains

  3. compute all keep rights

  4. “apply” all keep rights

This is based on Krauss’ multi lane traffic: laneChange() congested = (v_safe < v_thresh) and (v^0_safe < v_thresh) favorable(right->left) = (v_safe < v_max) and (not congested) favorable(left->right) = (v_safe >= v_max) and (v^0_safe >= v_max) if ((favorable(i->j) or (rand < p_change)) and safe(i->j)) then change(i->j) for vehicles on the right lane: if (v > v^0_safe) and (not congested) then v <- v^0_safe

Parameters:
  • vdf (pandas.DataFrame) – The Dataframe containing the vehicles as rows index: vid columns: [position, length, lane, ..]

  • max_lane (int) – The largest lane id

  • step_length (float) – The length of a simulation step

Returns:

The Dataframe containing the vehicles as rows index: vid columns: [lane, reason]

Return type:

pandas.DataFrame

plafosim.simulator.compute_new_speeds(vdf: DataFrame, step_length: float) Series[source]

Compute the new speed for all vehicles in the simulation.

Can compute “potential” new speed for different target lanes. Assume vdf already contains predecessor and successor data. Just pass the right predecessor/successor data for different lanes.

Parameters:
  • vdf (pandas.DataFrame) – The Dataframe containing the vehicles as rows index: vid columns: [position, length, lane, ..]

  • step_length (float) – The length of a simulation step

Returns:

The series of new speeds index: vid

Return type:

pandas.Series

plafosim.simulator.compute_vehicle_spawns(vehicles: list, vdf: DataFrame, ramp_positions: list, number_of_lanes: int, current_step: float, rng: Random, random_depart_position: bool, random_arrival_position: bool, depart_all_lanes: bool, step_length: float = 1.0)[source]

Spawn as many vehicles as possible from the queue (sorted by waiting time).

Assumption: list of vehicles is already sorted ascending by departure priority (e.g., waiting time) Assumption: ramp positions is sorted in ascending manner

Parameters:
  • vehicles (list(dict)) – The list of vehicles to add

  • vdf (pandas.DataFrame) – The Dataframe containing the vehicles as rows index: vid columns: [position, length, lane, ..]

  • ramp_positions (list(int)) – The list of available on-ramp positions in m

  • number_of_lanes (int) – The number of available lanes

  • current_step (float) – The current simulation step

  • rng (random.Random) – The random number generator to use

  • random_depart_position (bool) – Whether the vehicles sould depart at a random position

  • random_arrival_position (bool) – Whether the vehicles should arrive at a random position

  • depart_all_lanes (bool) – Whether to use all availale lanes for depature

  • step_length (float, optioal) – The length of a simulation step

plafosim.simulator.draw_infrastructures(infrastructures: list, labels: bool)[source]

Draws infrastructures in the GUI.

Parameters:
  • infrastructures (list) – The list of infrastructure objects to add

  • labels (bool) – Whether to draw infrastructure labels

plafosim.simulator.draw_ramps(road_length: int, interval: int, labels: bool)[source]

Draws on-/off-ramps in the GUI.

Parameters:
  • road_length (int) – The length of the road in m

  • interval (int) – The ramp interval in m

  • labels (bool) – Whether to draw ramp labels

plafosim.simulator.draw_road_end(road_length: int, label: bool)[source]

Draws the end of the road in the GUI.

Parameters:
  • road_length (int) – The length of the road in m

  • label (bool) – Whether to draw a label

plafosim.simulator.get_arrival_position(depart_position: int, road_length: int, ramp_interval: int, min_trip_length: int, max_trip_length: int, rng: Random, random_arrival_position: bool = False, pre_fill: bool = False) int[source]

Return a (random) arrival position for a given departure position.

This considers the ramp interval, road length, and minimum trip length.

Parameters:
  • depart_position (int) – The departure position to consider

  • road_length (int) – The length of the entire road

  • ramp_interval (int) – The distance between two on-/off-ramps

  • min_trip_length (int) – The minimum trip length

  • max_trip_length (int) – The maximum trip length

  • rng (random.Random) – The random number generator to use

  • random_arrival_position (bool) – Whether to use random arrival positions

  • pre_fill (bool, optional) – Whether the trip is for a pre-filled vehicle

Returns:

The arrival position in m

Return type:

int

plafosim.simulator.get_crashed_vehicles(vdf: DataFrame) list[source]

Return the list of crashed vehicles’ ids.

Parameters:

vdf (pandas.DataFrame) – The Dataframe containing the vehicles as rows index: vid columns: [position, length, lane, ..]

Returns:

list(int)

Return type:

the list of vehicles that crashed

plafosim.simulator.get_depart_speed(desired_speed: float, rng: Random, depart_desired: bool = False, random_depart_speed: bool = False) float[source]

Return a (random) departure speed.

Parameters:
  • desired_speed (float) – The desired speed to consider

  • rng (random.Random) – The random number generator to use

  • depart_desired (bool, optional) – Whether to depart with the desired speed

  • random_depart_speed (bool, optional) – Whether to choose a random value from a range

Returns:

The value for the departure speed

Return type:

float

plafosim.simulator.get_desired_speed(desired_speed: float, rng: Random, speed_variation: float, min_desired_speed: float, max_desired_speed: float, random_desired_speed: bool = False) float[source]

Return a (random) desired driving speed.

Parameters:
  • desired_speed (float) – The value to be used as is or as the mean for sampling from a normal distribution

  • rng (random.Random) – The random number generator to use

  • speed_variation (float) – The value to be used as variation for sampling from a normal distribution

  • min_desired_speed (float) – The minimum allowed value for the desired driving speed

  • max_desired_speed (float) – The maximum allowed value for the desired driving speed

  • random_desired_speed (bool, optional) – Whether to choose a random value from a normal distribution

Returns:

The value for the desired driving speed

Return type:

float

plafosim.simulator.get_predecessors(vdf: DataFrame, predecessor_map: DataFrame, target_lane: Series) DataFrame[source]

Return DataFrame of successors to the vehicles on a target lane.

plafosim.simulator.gui_step(target_step: int, screenshot_filename: str | None = None)[source]

Increases the simulation step in the GUI.

Parameters:
  • target_step (int) – The target simulation step

  • screenshot_filename (str, optional) – The name of the screenshot file

plafosim.simulator.has_collision(position1: float, rear_position1: float, lane1: int, position2: float, rear_position2: float, lane2: int) bool[source]

Check for a collision between two vehicles.

Parameters:
  • position1 (float) – The current position of vehicle 1

  • rear_position1 (float) – The current rear position of vehicle 1

  • lane1 (int) – The current lane of vehicle 1

  • position2 (float) – The current position of vehicle 2

  • rear_position2 (float) – The current rear position of vehicle 2

  • lane2 (int) – The current lane of vehicle 2

Returns:

bool

Return type:

Whether there is a collision between two vehicles

plafosim.simulator.initialize_emission_traces(basename: str)[source]
plafosim.simulator.initialize_platoon_changes(basename: str)[source]
plafosim.simulator.initialize_platoon_formation(basename: str)[source]
plafosim.simulator.initialize_platoon_maneuvers(basename: str)[source]
plafosim.simulator.initialize_platoon_traces(basename: str)[source]
plafosim.simulator.initialize_platoon_trips(basename: str)[source]
plafosim.simulator.initialize_simulation_trace(basename: str)[source]
plafosim.simulator.initialize_vehicle_changes(basename: str)[source]
plafosim.simulator.initialize_vehicle_emissions(basename: str)[source]
plafosim.simulator.initialize_vehicle_platoon_changes(basename: str)[source]
plafosim.simulator.initialize_vehicle_platoon_traces(basename: str)[source]
plafosim.simulator.initialize_vehicle_teleports(basename: str)[source]
plafosim.simulator.initialize_vehicle_traces(basename: str)[source]
plafosim.simulator.initialize_vehicle_trips(basename: str)[source]
plafosim.simulator.is_gap_safe(front_position: float, front_speed: float, front_max_deceleration: float, front_length: float, back_position: float, back_speed: float, back_max_acceleration: float, back_min_gap: float, step_length: float) bool[source]

Return whether the gap between the front and back vehicle is safe.

Safe means: - the front vehicle can decelerate as hard as possible for one step - the back vehicle can accelerate as hard as possible for one step - the vehicle will not crash

Assumes euclidean/non-ballistic position updates.

Parameters:
  • front_position (float) – The position of the front vehicle in m

  • front_speed (float) – The speed of the front vehicle in m/s

  • front_max_deceleration (float) – The maximum deceleration of the front vehicle in m/s2

  • front_length (length) – The length of the front vehicle in m

  • back_position (float) – The position of the back vehicle in m

  • back_speed (float) – The speed of the back vehicle in m/s

  • back_max_acceleration (float) – The maximum acceleration of the back vehicle in m/s2

  • back_min_gap (float) – The minimum gap of the back vehicle in m

  • step_length (float) – The length of a simulation step in s

Returns:

bool

Return type:

Whether the gap between the two vehicles is safe

plafosim.simulator.is_insert_safe(depart_position: float, depart_speed: float, vtype: VehicleType, other_vehicle: Vehicle, step_length: float) bool[source]

Checks if a vehicle can be inserted safely at a given position.

Parameters:
  • depart_position (float) – The planned depature position of the vehicle

  • depart_speed (float) – The planned departure speed of the vehicle

  • vtype (VehicleType) – The vehicle type of the vehicle

  • other_vehicle (Vehicle) – The other vehicle to check

  • step_length (float) – The step length

Returns:

bool

Return type:

Whether the insertion of a vehicle is safe

plafosim.simulator.lane_predecessors(vdf: DataFrame, max_lane: int) DataFrame[source]

Find the current (potential) predecessor for each lane and each vehicle.

This means: Which other vehicle would be the predecessor if a vehicle was on lane column. A predecessor id of -1 means there is no predecessor.

Preconditions: - vdf.sorted_values([‘position’, ‘lane’], ascending=False)

Parameters:
  • vdf (pandas.DataFrame) – The Dataframe containing the vehicles as rows index: vid columns: [position, length, lane, ..]

  • max_lane (int) – The largest lane id

plafosim.simulator.move_gui_vehicle(vid: int, position: float, lane: int, speed: float)[source]

Move a vehicle in the GUI.

Parameters:
  • vid (int) – The id of the vehicle to change

  • position (float) – The vehicle’s new position

  • lane (int) – The vehicle’s new lane

  • speed (float) – The vehicle’s new speed

plafosim.simulator.prune_vehicles(keep_vids: list)[source]

Prunes vehicles from the GUI.

Parameters:

keep_vids (list) – The ids of the vehicle that should be kept

plafosim.simulator.record_general_data_begin(basename: str, simulator: Simulator)[source]
plafosim.simulator.record_general_data_end(basename: str, simulator: Simulator)[source]
plafosim.simulator.record_platoon_change(basename: str, step: float, leader: PlatooningVehicle, source_lane: int, target_lane: int, reason: str)[source]
plafosim.simulator.record_simulation_trace(basename: str, step: float, vehicles_in_simulator: int, vehicles_in_queue: int, vehicles_spawned: int, vehicles_arrived: int, runtime: float, average_vehicle_speed: float, vehicles_braking_rough: int)[source]
plafosim.simulator.record_vehicle_change(basename: str, step: float, vid: int, position: float, speed: float, source_lane: int, target_lane: int, reason: str)[source]
plafosim.simulator.record_vehicle_platoon_change(basename: str, step: float, member: PlatooningVehicle, source_lane: int, target_lane: int, reason: str)[source]
plafosim.simulator.record_vehicle_trace(basename: str, step: int, vehicle: Vehicle)[source]
plafosim.simulator.remove_gui_vehicle(vid: int)[source]

Remove a vehicle from the GUI.

Parameters:

vid (int) – The id of the vehicle to remove

plafosim.simulator.report_rough_braking(vdf: DataFrame, new_speed: Series, step_length: float, rough_factor: float = 0.5) int[source]

Report about vehicle preforming rough braking maneuvers.

Rough braking meaning more than rough_factor times max_deceleration.

Return number of rough braking vehicles

Parameters:
  • vdf (pandas.DataFrame) – The Dataframe containing the vehicles as rows index: vid columns: [position, length, lane, ..]

  • new_speed (pandas.Series) – The Series containing the new speeds of the vehicles index: vid

  • step_length (float) – The length of one simulation step in s

  • rough_factor (float, optional) – The factor to apply to the maximum deceleration for setting a rough braking threshold

Returns:

The number of vehicles performing rough braking

Return type:

int

plafosim.simulator.set_gui_window(road_length: int)[source]

Set the window of the GUI according to the road length.

Parameters:

road_length (int) – The length of the road in m

plafosim.simulator.start_gui(config: str, step_length: float, play: bool = True)[source]

Start the GUI.

Parameters:
  • config (str) – The name of the configuration file

  • step_length (float) – The length of one simulation step in s

  • play (bool, optional) – Whether to start the simulation automatically

plafosim.simulator.timer()

perf_counter() -> float

Performance counter for benchmarking.

plafosim.simulator.update_position(vdf: DataFrame, step_length: float) DataFrame[source]

Update the position of vehicles within a pandas Dataframe.

This is based on Krauss’ single lane traffic: adjust position (move) x(t + step_size) = x(t) + v(t)*step_size

Parameters:
  • vdf (pandas.DataFrame) – The Dataframe containing the vehicles as rows index: vid columns: [position, length, lane, ..]

  • step_length (float) – The length of the simulated step

Returns:

The Dataframe containing the vehicles as rows index: vid columns: [position, length, lane, ..]

Return type:

pandas.DataFrame