Lesson 10: Traffic Simulation
Concepts: | Design of object and implementation. Simulation. Multiple interacting classes. |
Estimated time needed: | 10 hours |
Examination: | Mandatory examination of the assignments in accordance with the course page. |
Simulations
A large area of use for computers is simulation, i.e. when you create a computer model of some process (in a broad sense) that you want to study. It can be a model for the weather or the climate, for how snow drifts are formed around different buildings, for the flow of traffic in a street network or for a world with turtles that are born, eat, live and die.
The purpose of the model is to be able to make predictions about what happens if you change different parameters (i.e. raising carbon dioxide emissions, changing the shape of a building, adding a roundabout or giving turtles more food...).
It is usually significantly cheaper to experiment with a computer model than to do it in reality (build one or more roundabouts) or to do it with physical models (build model houses and blow potato flour on them in a wind tunnel).
When building models, you usually have to simplify and ignore many details that you think have no or at least only a small effect.
One way to do simulations is to divide the time into a number of discrete time steps. You start from a starting state and then step forward in time and note what happens in each time step:
Sometimes you know exactly what happens in every step, but most often you only have approximations. Apart from that, there might be some degree of chance involved, which is approximated with some probability. For example, it is seldom known exactly at what times a vehicle arrives at a roundabout, but you may have measured their frequency/traffic density, so that you have a probability that a vehicle will arrive at a certain time step.
Problem Description
The program will simulate the flow of traffic in different types of traffic systems. A traffic system consists, in our case, of lanes, traffic signals and queues (traffic jams). Roads consist of multiple lanes, but we will not use any road objects.
Example 1
A road with a traffic light
Example 2
A road with turning lane and two traffic lights
Example 3
A crossroads
The crossing is controlled by four traffic lights s1, s2, s3 and s4.
A problem in such types of crossings is that vehicles that come from E
and
want to turn left, towards S
may be blocked by vehicles coming from W
,
which will in their turn block vehicles that want to drive straight.
Example 4
To solve the problem, one can build turning lanes for vehicles coming from E
and W
and want to turn left in the crossing. Like this:

This crossing has turning lanes controlled by signals at s2 and s5. A typical question here is how long should the turning lanes be, to avoid queues that would extend to other lanes.
Computer Model
A traffic system must be made up of two general components: traffic lights
(the Light
class) and lanes (the Lane
class). It also
contains a varying number of vehicle objects (the Vehicle
class).
We will also need queues, but they will be simply represented with lists.
Furthermore, the Destinations
class is used to simulate arrivals
of vehicles to the system. You will complete this last class in the
exercise.
Vehicle
Class
The Vehicle
class is very simple. Its task is only to keep track of when the vehicle was created and where it is going. For this, two instance variables are sufficient: named destination and time of creation.
A vehicle does not need to know where it is, or to check traffic lights, or see other vehicles. The vehicles can be seen as small pawns moved by "someone else".
Thus, only the constructor is needed, that receives the destination and time of creation. If you want, you can add a __str__()
method.
Destinations
class
This class is used to simulate the arrival of new vehicles to the traffic system. Each call to its step method returns either None, indicating that no vehicle came this step, or a destination ('W'
or 'S'
).
The class could be based on measured or estimated traffic densities at different times of the day, but in our case it returns a predetermined sequence. This makes it easier to predict the result and thus also check that the program is correct.
The class is completely given and does not need to be changed. It can be downloaded here.
Light
class
This class is used to represent traffic signals.
See the discussion and specification of the class.
Lane
class
A lane is a structure that contains a number of vehicles and a number of empty spaces. The vehicles can only enter at the beginning and leave at the end of the lane i.e. the lane is like a "tube":

TrafficSystem
class
This class defines a specific traffic system. It keeps track of which lanes and which signals are included and how the vehicles are to be moved through the system. This class makes use of all three class described above. When you complete the TrafficSystem
class, make sure to import these classes from the file trafficComponents.py
given below.
To represent the system in Example 1, two lanes and a signal are needed:


See the description of the class!
Tasks: the first system
You will simulate the system in example 1:
That is, a system with two lanes and one traffic signal.
Instructions
-
Copy the Python file trafficComponents.py.
It contains structures for the
Vehicle
,Lane
andLight
classes. In addition, it contains functions that demonstrate these classes (the same example code as in the descriptions of the classes). - Implement the
Vehicle
,Lane
andLight
classes. Run their methods and make sure you get the right output! -
Copy the Python file destinations.py (if you have not done so already).
It contains only the
Destinations
class. You do not need to make any changes to this class. -
Copy the Python file trafficSystem0.py.
This file contains a code structure for the
TrafficSystem
class as well as a pre-written main function. -
Complete the class
TrafficSystem
. Whenever possible, make sure to use the methods from theLane
,Vehicle
andLight
classes, and avoid modifying their attributes directly.-
Fill in the constructor so that it creates two lanes, one traffic light and one
Destination
object. -
Complete
snapshot()
method. It should be based on the__str()__
methods from the various components. -
Write the
step
method as follows:- Remove the first vehicle from the first (left) lane in the figure.
-
Step the first lane with its
step
method. - If the signal is green, move the first vehicle from the second (right) lane to the first lane.
-
Step the traffic signal with its
step
method. - Step the second lane.
-
Call the
step
method in theDestinations
object - if this returns a destination (i.e. something other thanNone
) then create a vehicle and put it last on the second lane.
-
Fill in the constructor so that it creates two lanes, one traffic light and one
- Try it out! Now you should see how the vehicles glide through the system and how the signal changes color.
-
There is one problem: If there is already a vehicle in the last place on the second lane, it will be lost when we put a new one there. To avoid this, organize a queue for vehicles waiting to enter the lane. Add another instance variable of list type for this. The queue should now also be printed by the
snapshot
method.Tip: Your code will be simpler if you always place additional vehicles in the queue before picking up the first one from the queue.
Make sure you do not store
None
in the queue!
The second system
Now you will implement the system in example 2:
The traffic system will consist of three lanes (lane
, lane_west
, and lane_south
) and two traffic lights: light_west
and light_south
(previously we called them s1 and s2).

It can be nice to have short lanes after (to the left of) the traffic lights so that you can see how the vehicles pass.
At point E
there is a queue (not drawn).
At a time step, one or more of the following things may happen, in this order:
-
A vehicle from
lane_west
and/orlane_south
passes its signal (if it is green). -
The
lane_west
andlane_south
files are stepped. -
A vehicle immediately to the right of
X
is moved tolane_west
orlane_south
depending on its destination (W
orS
). If the destination lane is not free, the vehicle remains where it is and the split point is counted as blocked. -
The vehicles on
lane
are stepped. -
A vehicle arrives to the system at point
E
and is queued. -
If the last place in
lane
is vacant and there are vehicles in the queue, the first from the queue is taken and put to the last place inlane
. - The light signals are stepped.
A simulation thus consists of a time stepping scheme where the above things
happen. It is appropriate that the steps, just as in reality, are performed in
the order in which they appear above. It can be practical to let your
step
method in turn call different methods that you introduce yourself
to take care of different parts. It can reduce the amount of repetitive code in
steps
and make it clearer.
Note that the Lane
and Light
classes should not need to be changed - only the TrafficSystem
needs to be redone!
Input data for a simulation
The program is controlled by the following input:
-
the rate at which vehicles arrive at
E
, -
the proportion of vehicles that want to turn, i.e. have
S
as destination, - the lengths of the lanes and
- characteristics of the light signals (total period and green period).
The first two values usually vary with time. This is handled by the Destination
class. In real simulations, the class would produce vehicles according to measured intensities, but, in order for you to get controllable results, this version gives the same sequence every time.
The values in the last two points, i.e. the lengths of the lanes and the characteristics of the light signals, you have to decide for yourself. However, try the parameter settings below and compare with the statistics shown in the next paragraph.
Result of a run
Should consist of:-
Statistics containing:
- Average, minimum and maximum times (number of time steps) for vehicles to pass the respective light signal (west / south).
-
Percentage of time steps that the division point
X
has been blocked. By “blocked” it is meant that it is not possible to move a vehicle from the lanelane
because the last location in its destination lane is occupied. -
Proportion of time steps in which there were vehicles in the queue at the starting point (
E
).
Collect the times of vehicles leaving the system in two list objects, one for each output, and use these to produce the statistics. Use either a separate module with statistics methods or the standard module
statistics
.The statistics must be printed using the
print_statistics
method inTrafficSystem
. It must be possible to call the method at any time during the simulation. Example of printing:Statistics after 100 timesteps: Created vehicles: 48 In system : 8 At exit West South Vehicles out: 21 19 Minimal time: 20 21 Maximal time: 38 53 Mean time : 27.6 39.3 Median time : 27.0 43.0 Blocked : 18.0% Queue : 14.0% -
Snapshots of the system, with the help of
snapshot
method.Example of a snapshot sequence:
(G) [.....W..] [SWWSWSSSWSW] [] (R) [SSSSS.SS] (R) [....W...] [WWSWSSSWSWW] [] (R) [SSSSSSSS] (R) [...W...W] [WSWSSSWSWWS] [] (R) [SSSSSSSS] (R) [..W...WW] [SWSSSWSWWSW] [] (R) [SSSSSSSS] (R) [.W...WW.]*[SWSSSWSWWSW] ['W'] (R) [SSSSSSSS] (R) [W...WW..]*[SWSSSWSWWSW] ['W'] (R) [SSSSSSSS] (R) [W..WW...]*[SWSSSWSWWSW] ['W', 'S'] (R) [SSSSSSSS]In the three last steps, the splitting point is blocked (indicated by the*
-sign), and in addition there is first one, and in the end two cars, waiting in the queue.
Before the examination
- Make sure your code follows the coding rules!
- Check that all required statistics are produced and that the results are correct!
- Make sure the program prints out everything it should, according to the above example.
Dölj style3dev.css för att bli av med annoteringarna!