Observera att detta är en arbetsversion av sidan!
Dölj style3dev.css för att bli av med annoteringarna!

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:

create variables/model components time = 0 while True: time = time + 1 update all variables show current state (if desired)

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
system1

Example 2

A road with turning lane and two traffic lights
system1

Example 3

A crossroads
korsning0

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:

korsning

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":
lane0
See the discussion and specification of the class

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:

system1Impl
while example 2 requires 3 lanes and 2 signals:
system2Impl

See the description of the class!

Tasks: the first system

You will simulate the system in example 1:
system1

That is, a system with two lanes and one traffic signal.

Instructions

  1. Copy the Python file trafficComponents.py. It contains structures for the Vehicle, Lane and Light classes. In addition, it contains functions that demonstrate these classes (the same example code as in the descriptions of the classes).
  2. Implement the Vehicle, Lane and Light classes. Run their methods and make sure you get the right output!
  3. 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.
  4. Copy the Python file trafficSystem0.py. This file contains a code structure for the TrafficSystem class as well as a pre-written main function.
  5. Complete the class TrafficSystem. Whenever possible, make sure to use the methods from the Lane, Vehicle and Light classes, and avoid modifying their attributes directly.
    1. Fill in the constructor so that it creates two lanes, one traffic light and one Destination object.
    2. Complete snapshot() method. It should be based on the __str()__ methods from the various components.
    3. Write the step method as follows:
      1. Remove the first vehicle from the first (left) lane in the figure.
      2. Step the first lane with its step method.
      3. If the signal is green, move the first vehicle from the second (right) lane to the first lane.
      4. Step the traffic signal with its step method.
      5. Step the second lane.
      6. Call the step method in the Destinations object - if this returns a destination (i.e. something other than None) then create a vehicle and put it last on the second lane.
  6. Try it out! Now you should see how the vehicles glide through the system and how the signal changes color.
  7. 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!

This is what one simulation run might look like:
[.....] (G) [.....] [] [.....] (G) [....S] [] [.....] (G) [...SS] [] [.....] (G) [..SSS] [] [.....] (G) [.SSSS] [] [.....] (G) [SSSSS] [] [....S] (G) [SSSSW] [] [...SS] (G) [SSSWS] [] [..SSS] (R) [SSWSS] [] [.SSS.] (R) [SSWSS] ['S'] [SSS..] (G) [SSWSS] ['S', 'W'] [SS..S] (G) [SWSSS] ['W', 'W'] [S..SS] (G) [WSSSW] ['W', 'S'] [..SSW] (G) [SSSWW] ['S', 'W'] [.SSWS] (G) [SSWWS] ['W', 'S'] [SSWSS] (G) [SWWSW] ['S', 'S'] [SWSSS] (G) [WWSWS] ['S', 'S'] [WSSSW] (G) [WSWSS] ['S', 'W'] [SSSWW] (R) [SWSSS] ['W', 'S'] [SSWW.] (R) [SWSSS] ['W', 'S', 'W'] [SWW..] (G) [SWSSS] ['W', 'S', 'W', 'W'] [WW..S] (G) [WSSSW] ['S', 'W', 'W', 'S'] [W..SW] (G) [SSSWS] ['W', 'W', 'S', 'W'] [..SWS] (G) [SSWSW] ['W', 'S', 'W', 'W'] [.SWSS] (G) [SWSWW] ['S', 'W', 'W'] [SWSSS] (G) [WSWWS] ['W', 'W', 'S'] [WSSSW] (G) [SWWSW] ['W', 'S'] [SSSWS] (G) [WWSWW] ['S'] [SSWSW] (R) [WSWWS] [] [SWSW.] (R) [WSWWS] [] [WSW..] (G) [WSWWS] ['W'] [SW..W] (G) [SWWSW] ['S'] [W..WS] (G) [WWSWS] [] [..WSW] (G) [WSWS.] []
Don't hesitate to show and discuss your solution with a teacher/assistant at this point.

The second system

Now you will implement the system in example 2:
korsning

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).

korsningsimplementation

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 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 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.

lane_length = 11 # Length first (rightmost) lane lanews_length = 8 # Length lanes in front of signals light_period = 14 # Period for the lights west_green = 6 # Green period westbound light south_green = 4 # Green period southbound light

Result of a run

Should consist of:
  1. Statistics containing:
    1. Average, minimum and maximum times (number of time steps) for vehicles to pass the respective light signal (west / south).
    2. 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 lane lane because the last location in its destination lane is occupied.
    3. 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 in TrafficSystem. 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%
  2. 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

  1. Make sure your code follows the coding rules!
  2. Check that all required statistics are produced and that the results are correct!
  3. Make sure the program prints out everything it should, according to the above example.

Tillbaka

Valid CSS!