17
27/11/14 Department of Mechanical Engineering, UOB 1 Robert Tanner 1217762 Han Zhang 1235042 Road Traffic Dynamics Modelling 1. Summary The object of this project is to model the flow of streams of cars of equal length along a perfectly straight and flat motorway, with each lane of the motorway containing an equal number of cars, and graphically demonstrate the behaviour of the traffic over a set period of time known as the final time. A sample result and an image of the data input control panel of the program are displayed to demonstrate the program’s operation. The program indicates that the velocity and separation of the cars tend towards constant values over time, and the traffic flow density plot indicates that the cars become closer over time, and spread out when they become very close to avoid a collision. Further work can be done on allowing greater realism, greater choice for the user and better visualisation of results. 2. Introduction The flow of traffic along a motorway over a set period of time is modelled by two arrays representing the instantaneous velocity and separation from the car in front of each car in each lane. The velocity and separation change over time as each driver attempts to reach the target speed and separation, which is modelled by a “while” loop. Each step in the “while” loop represents a single time increment. Each car attempts to reach an ideal or “target” velocity and separation from the car in front of it. The program calculates the acceleration of each car at each increment and then stores these values for a set number of increments, to model the delay between thought and action caused by the driver’s reaction time. The input to the program are the number of cars per lane, the number of lanes in the motorway, the final time of the simulation, the duration of each time increment and the length of the reaction time, for the purpose of the simulation it is assumed that each driver has the same reaction time. The outputs are the mean velocity, mean separation and traffic flow density of the first lane at each time increment. The main objective of this project is to demonstrate the behaviour of the cars within the first lane of the motorway, and therefore demonstrate how changing the parameters of the traffic flow and the length of time the traffic is modelled over changes the behaviour of the traffic flow. The sample results show below represent a situation where ten cars are driving down a one-lane motorway over a period of one thousand seconds, where each time increment is one-tenth of a second, and the reaction time of each driver is one second.

Robert_Tanner_&_Han_Zhang_Road_Traffic_Dynamics_Report

Embed Size (px)

Citation preview

Page 1: Robert_Tanner_&_Han_Zhang_Road_Traffic_Dynamics_Report

27/11/14 Department of Mechanical Engineering, UOB

1 Robert Tanner 1217762 Han Zhang 1235042

Road Traffic Dynamics Modelling

1. Summary

The object of this project is to model the flow of streams of cars of equal length along a perfectly

straight and flat motorway, with each lane of the motorway containing an equal number of cars,

and graphically demonstrate the behaviour of the traffic over a set period of time known as the

final time. A sample result and an image of the data input control panel of the program are

displayed to demonstrate the program’s operation. The program indicates that the velocity and

separation of the cars tend towards constant values over time, and the traffic flow density plot

indicates that the cars become closer over time, and spread out when they become very close to

avoid a collision. Further work can be done on allowing greater realism, greater choice for the

user and better visualisation of results.

2. Introduction

The flow of traffic along a motorway over a set period of time is modelled by two arrays

representing the instantaneous velocity and separation from the car in front of each car in each

lane. The velocity and separation change over time as each driver attempts to reach the target

speed and separation, which is modelled by a “while” loop. Each step in the “while” loop

represents a single time increment. Each car attempts to reach an ideal or “target” velocity and

separation from the car in front of it. The program calculates the acceleration of each car at

each increment and then stores these values for a set number of increments, to model the delay

between thought and action caused by the driver’s reaction time. The input to the program are

the number of cars per lane, the number of lanes in the motorway, the final time of the

simulation, the duration of each time increment and the length of the reaction time, for the

purpose of the simulation it is assumed that each driver has the same reaction time. The outputs

are the mean velocity, mean separation and traffic flow density of the first lane at each time

increment. The main objective of this project is to demonstrate the behaviour of the cars within

the first lane of the motorway, and therefore demonstrate how changing the parameters of the

traffic flow and the length of time the traffic is modelled over changes the behaviour of the

traffic flow.

The sample results show below represent a situation where ten cars are driving down a one-lane

motorway over a period of one thousand seconds, where each time increment is one-tenth of a

second, and the reaction time of each driver is one second.

Page 2: Robert_Tanner_&_Han_Zhang_Road_Traffic_Dynamics_Report

27/11/14 Department of Mechanical Engineering, UOB

2 Robert Tanner 1217762 Han Zhang 1235042

Page 3: Robert_Tanner_&_Han_Zhang_Road_Traffic_Dynamics_Report

27/11/14 Department of Mechanical Engineering, UOB

3 Robert Tanner 1217762 Han Zhang 1235042

Page 4: Robert_Tanner_&_Han_Zhang_Road_Traffic_Dynamics_Report

27/11/14 Department of Mechanical Engineering, UOB

4 Robert Tanner 1217762 Han Zhang 1235042

3. Description of program code

Lines 1-191: Initialising the GUI interface and data entry panel

Lines 192-196: Initialising pushbutton uicontrol which, when pressed, begins the program

Lines 197-208: Extract the values for the input data from the control panel

Lines 209-216: Set values for maximum braking acceleration (abrmax), car length (l) and the

gains used to calculate instantaneous acceleration at each time increment (ktg, ks, kv1, kv2

and ka)

Lines 217-221: Set initial values of zero for t (time), i (a measure of how many time

increments have passed until the reaction time is reached), o (which counts from one to ten

repeatedly) and p (which counts the number of increments overall)

Lines 222-248: Create significant arrays for use in the program

Line 223: Create an array of time periods over which the program takes place

Lines 225-227: Create empty arrays for the target velocity, target separations and

initial accelerations of each car. Each cell in the array represents a single car, the

column number indicates which lane it is in, and the row indicates which car it is in

the stream)

Lines 229-231: Create z, an empty row vector for use in matrix calculations, and CL,

an column vector that allows the program to account for the length of cars when

calculating the exact location of each car along the road

Lines 233-234: Create acc_historic, a matrix to store the older values of

acceleration, and set the initial values for the first car in each lane to two-thirtieths

of a metre per second per second

Lines 236-237: calculate how many lengths of ten metres lie along the stream of

cars

Lines 239-245: Set initial values for velocity and separation, create arrays to store

mean values over time, and set target speed

Lines 247: Create empty matrix to store traffic flow density

Lines 249-472: Iterate acceleration, speed and separation over time

Lines 251-265: Count t, i o and p

Lines 266-268: Calculate j and k, the columns in acc_historic between which the

historic acceleration values are stored for each time increment

Lines 269-323: Change the target velocity and gains used to calculate acceleration

to model changes in driver behaviour

Lines 324-381: Model cars switching lanes in the case of multiple lanes

Page 5: Robert_Tanner_&_Han_Zhang_Road_Traffic_Dynamics_Report

27/11/14 Department of Mechanical Engineering, UOB

5 Robert Tanner 1217762 Han Zhang 1235042

Lines 382-389: Since target separation is not a constant, it is calculated for each

time increment, this code calculates the target separation for each car

Lines 390-397: Calculate the clearing speed, the difference in velocity between each

car and the car in front

Lines 398-408: Calculate instantaneous acceleration and apply lower limit. Since

abrmax is the greatest possible braking acceleration, any values more negative than

abrmax default to abrmax

Lines 409-416: Calculate the maximum possible acceleration for each car, and

default any values greater than the maximum to the maximum

Lines 417-430: In case where cars are within one car length of each other, the

acceleration of the rear car is set to the maximum braking acceleration, and the

acceleration of the front car is set to the maximum in order to prevent collisions

Lines 431-439: Calculate mean velocity and separation in the first lane and store

Lines 440-444: Using historic values of acceleration and clearing speed, calculate

new values of velocity and separation

Lines 445-459: Calculate road traffic density by dividing the motorway into lengths

of ten metres, calculate the number of cars in each block and multiply that number

by one hundred, the equivalent of dividing by one-hundredth of a kilometre

Lines 460-463: Every ten increments, store the density values in the density matrix

Lines 464-471: Restart the loop by inputting the new values of velocity, separation

and acceleration into the start of the loop, and store the acceleration values for the

future

Lines 473-482: Create plot of mean velocity in the first lane against time

Lines 483-491: Create plot of mean separation in the first lane against time

Lines 492-503: Create traffic flow density chart by creating a surface plot of M

4. Discussion

This program performs as intended and carries out the necessary tasks. The control panel built

with Guide is used to input the important data, which is used to calculate the average velocity,

average separation and traffic flow density of the first lane, with the constants used in the

calculations occasionally changing to model changes in driver behaviour since without these

changes the model quickly results in a straight line of evenly spaced cars all travelling at the

same speed, while this often occurs in reality, it rarely happens as quickly as it does in the

program when all gains are constant, approximately one hundred seconds, and the changing

Page 6: Robert_Tanner_&_Han_Zhang_Road_Traffic_Dynamics_Report

27/11/14 Department of Mechanical Engineering, UOB

6 Robert Tanner 1217762 Han Zhang 1235042

gains also ensures that the final separations and velocities of each car are not equal, which add

greater realism to the simulation. The initial separations and velocities are partially or wholly

random, so that each simulation is different from the former. The behaviour of the cars is

demonstrated by the output graphs. By altering the input data, the user can investigate how

different conditions would affect the behaviour of the cars, e.g. by increasing the reaction time

to model tired drivers or changing the duration of the time increment in order to investigate

different sampling rate. As the sample charts show, as time goes on the average separation

decreases and tends towards a constant value, indicating that the cars are becoming closer

together. The average velocity also tends towards constant values, and these constant values

change over time, as the target velocity changes periodically. This indicates that the code is

representing reality fairly well, since over time cars tends to reach a relatively constant speed

and separation on the road, with minor variations between cars and variations in the average

over time.

5. Conclusions

The sample charts indicate that the mean velocity tends towards a constant value, the target

velocity, which is the same for each car and constant over long periods of time. Meanwhile the

target separation is not constant over time or between cars, but it does decrease over time

which allows the cars to become closer, as indicated by the graph’s generally negative direction.

If the final values of velocity and separation for each car are viewed at the end of the program it

is clear that the final values for each car are similar, but not identical which is again a good

indicator of reality. It is important to note that the value the mean velocity tends to changes

over time as the target velocity also changes. Up until approximately 250 seconds into the

simulation the average velocity tends to 55m/s, which is the target velocity between the times of

125s and 250s. Between 250s and approximately 700s the target velocity is 40 m/s, which the

mean velocity tends towards and for the rest of the model the mean velocity tends to 30m/s,

while the target velocity is 32m/s between 730s and 810s. This indicates that the velocity of each

car tends towards the target velocity as it changes. Meanwhile the density plot, while difficult to

interpret, seems to indicate that cars approach one another, increasing local density, and then

spread out again, decreasing it.

This program work in an iterative process with a “while” loop which allows the acceleration to

change in response to simulated external stimuli, which in turn affect the velocity and

separation, which is modelled by performing operators on the matrices representing the velocity

Page 7: Robert_Tanner_&_Han_Zhang_Road_Traffic_Dynamics_Report

27/11/14 Department of Mechanical Engineering, UOB

7 Robert Tanner 1217762 Han Zhang 1235042

and separation. A major problem in this model was that cars would accelerate beyond the peed

of the car in front and, since these cars have no real physical presence, they simply drive through

them, indicated by a negative separation and often acceleration to a velocity on the order of one

million metres per second. It was therefore necessary to first apply an upper limit on the

acceleration, where this is calculated as 𝑎𝑚𝑎𝑥 =2−𝑣2

30, which required further matrix operators

to calculate a value for every car, and default any value of acceleration outside the limits to

either the upper or lower limit. Then it was important to create a string of code that would

ensure that cars on the verge of a collision would apply an acceleration to prevent the collision

from occurring.

6. Further Works

The major challenge in this project was modelling the reaction time of each driver. To do this the

program creates a matrix with rows equal to the number of cars and columns equal to the

product of the reaction time and the number of lanes divided by the time increment, e.g. in the

sample situation, a simple ten-by-ten matrix. For each iteration the values of acceleration for

each car are stored in a block of columns within the historic matrix, using j and k as the column

co-ordinates, to be withdrawn after the reaction time has passed. More importantly however,

the values present in the historic matrix corresponding to these co-ordinates are first used to

calculate the new velocity before being overwritten with the old ones. Meaning the acceleration

applied by each driver is stored for the duration of the reaction time before being used,

modelling the time delay between thought and action in reality.

This program is competently put together and completes the required task, but some further

improvement is possible. For instance, the motorway being modelled is assumed to be perfectly

flat and straight, whereas in reality the majority of motorways are curved and cross several

elevations. To model this, additional code would need to be written to model centripetal

acceleration of cars driving around curves, the difference in length of different lanes along a

curved path and the power required to climb hills which would not be used to propel the car

along the motorway.

To also provide greater realism, another improvement would be the ability to provide random

reaction times to each driver, however, this would provide each car to have an individual historic

matrix, which would be very difficult to program for a general case. It would also aid the

Page 8: Robert_Tanner_&_Han_Zhang_Road_Traffic_Dynamics_Report

27/11/14 Department of Mechanical Engineering, UOB

8 Robert Tanner 1217762 Han Zhang 1235042

visualisation process if an animation of the cars driving along the motorway could be

programmed, or if the user could select which lane they wish to monitor.

The main issue with the output is that the traffic density plot is cluttered and confusing in an

elevated form, and would be much clearer in a flat format, however, when viewed from above

the plot is invisible. If this problem could be understood and fixed, this would be a great

improvement. However, from what we can see of it, the density plot does resemble the density

plot in the project specification. By defining the output axes outside the “while” loop, the

program does not recreate the axes with every iteration, which saves time and allows the final

values to be reached rapidly.

Another potential improvement to the project is to model random events such as adverse

weather conditions. The acceleration gains of the drivers are designed to change to another

value during specified periods of time in order to model changes in behaviour for additional

realism. However, it does not model the results of specific events or provide explanations for

these changes. It would be advantageous if the user could be allowed to choose to apply

external stimuli such rain fall or a strong wind during a specified period of time, possibly through

a drop-down menu. As each event occurred the gains would be altered in a specific manner to

reflect this.

7. Code listing

function varargout = final(varargin) % FINAL MATLAB code for final.fig % FINAL, by itself, creates a new FINAL or raises the existing % singleton*. % % H = FINAL returns the handle to a new FINAL or the handle to % the existing singleton*. % % FINAL('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in FINAL.M with the given input arguments. % % FINAL('Property','Value',...) creates a new FINAL or raises the % existing singleton*. Starting from the left, property value pairs

are % applied to the GUI before final_OpeningFcn gets called. An % unrecognized property name or invalid value makes property

application % stop. All inputs are passed to final_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help final

Page 9: Robert_Tanner_&_Han_Zhang_Road_Traffic_Dynamics_Report

27/11/14 Department of Mechanical Engineering, UOB

9 Robert Tanner 1217762 Han Zhang 1235042

% Last Modified by GUIDE v2.5 25-Nov-2014 13:12:03

% Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @final_OpeningFcn, ... 'gui_OutputFcn', @final_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end

if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT

% --- Executes just before final is made visible. function final_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to final (see VARARGIN)

% Choose default command line output for final handles.output = hObject;

% Update handles structure guidata(hObject, handles);

% UIWAIT makes final wait for user response (see UIRESUME) % uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line. function varargout = final_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure varargout{1} = handles.output;

function n_Callback(hObject, eventdata, handles) % hObject handle to n (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of n as text

Page 10: Robert_Tanner_&_Han_Zhang_Road_Traffic_Dynamics_Report

27/11/14 Department of Mechanical Engineering, UOB

10 Robert Tanner 1217762 Han Zhang 1235042

% str2double(get(hObject,'String')) returns contents of n as a

double

% --- Executes during object creation, after setting all properties. function n_CreateFcn(hObject, eventdata, handles) % hObject handle to n (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'),

get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end

function nl_Callback(hObject, eventdata, handles) % hObject handle to nl (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of nl as text % str2double(get(hObject,'String')) returns contents of nl as a

double

% --- Executes during object creation, after setting all properties. function nl_CreateFcn(hObject, eventdata, handles) % hObject handle to nl (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'),

get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end

function tr_Callback(hObject, eventdata, handles) % hObject handle to tr (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of tr as text % str2double(get(hObject,'String')) returns contents of tr as a

double

% --- Executes during object creation, after setting all properties. function tr_CreateFcn(hObject, eventdata, handles) % hObject handle to tr (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB

Page 11: Robert_Tanner_&_Han_Zhang_Road_Traffic_Dynamics_Report

27/11/14 Department of Mechanical Engineering, UOB

11 Robert Tanner 1217762 Han Zhang 1235042

% handles empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'),

get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end

function dt_Callback(hObject, eventdata, handles) % hObject handle to dt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of dt as text % str2double(get(hObject,'String')) returns contents of dt as a

double

% --- Executes during object creation, after setting all properties. function dt_CreateFcn(hObject, eventdata, handles) % hObject handle to dt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'),

get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end

function tf_Callback(hObject, eventdata, handles) % hObject handle to tf (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of tf as text % str2double(get(hObject,'String')) returns contents of tf as a

double

% --- Executes during object creation, after setting all properties. function tf_CreateFcn(hObject, eventdata, handles) % hObject handle to tf (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'),

get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end

Page 12: Robert_Tanner_&_Han_Zhang_Road_Traffic_Dynamics_Report

27/11/14 Department of Mechanical Engineering, UOB

12 Robert Tanner 1217762 Han Zhang 1235042

% --- Executes on button press in plot. function plot_Callback(hObject, eventdata, handles) % hObject handle to plot (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA)

% Set inital values for calculation numberofcars=get(handles.n,'string'); n=str2double(numberofcars); numberoflanes=get(handles.nl,'string'); nl=str2double(numberoflanes); reactiontime=get(handles.tr,'string'); tr=str2double(reactiontime); finaltime=get(handles.tf,'string'); tf=str2double(finaltime); timeincrement=get(handles.dt,'string'); dt=str2double(timeincrement);

abrmax=-8; ktg=0.6; ks=0.045; kv1=-0.02; kv2=-0.3; ka=0.5; l=6;

t=0; i=0; o=0; p=0;

% Define significant arrays T=[dt:dt:tf];

vtarg=zeros(n,nl); starg=zeros(n,nl); acc_old=zeros(n,nl);

L=l*(ones(n,nl)); z=zeros(1,nl); CL=cumsum(L);

acc_historic=zeros(n,nl*(tr/dt)); acc_historic(1,1:nl*(tr/dt))=2/30;

dy=(60*(n-1)+(n*l)); n100=round(dy);

v_old=10*rand(n,nl); v_old(1,1:nl)=15; V=zeros(1,tf/dt); s_old=((10*L)-(10*rand(n,nl))); s_old(1,1:nl)=0; Sep=zeros(1,tf/dt); vtarg(1:n,1:nl)=40;

M=zeros(tf/dt,n100);

Page 13: Robert_Tanner_&_Han_Zhang_Road_Traffic_Dynamics_Report

27/11/14 Department of Mechanical Engineering, UOB

13 Robert Tanner 1217762 Han Zhang 1235042

% Initialise while loop while t<tf; t=t+dt;

% Set up counters for sotring acceleration, mean speed, etc. i=i+1; if i>tr/dt i=1; end

o=o+1; if o>10 o=1; end

p=p+1;

j=i*nl; k=j+1-nl;

% Change constants in certain circumstances to model changes in driver % behavior if t<810 vtarg(1:n,1:nl)=32; elseif t<730 vtarg(1:n,1:nl)=40; end

if t<200 vtarg(1:n,1:nl)=55; elseif t<125 vtarg(1:n,1:nl)=40; else vtarg(1:n,1:nl)=40; end

if t<621 ktg=rand; elseif 563<t ktg=0.6; else ktg=0.6; end

if t<412 ks=rand/10; elseif 274<t ks=0.045; else ks=0.045; end

if t<627 kv1=-rand/10; elseif 486<t kv1=-0.02; else kv1=-0.02 end

Page 14: Robert_Tanner_&_Han_Zhang_Road_Traffic_Dynamics_Report

27/11/14 Department of Mechanical Engineering, UOB

14 Robert Tanner 1217762 Han Zhang 1235042

if t<333 kv2=-rand; elseif 168<t kv2=-0.3; else kv2=-0.3; end

if t<511; ka=rand; elseif 430<t ka=0.5; else ka=0.5; end

% In the case of multiple lanes, model cars swapping lanes if nl>1; if t==222; aa=v_old(2,1); bb=v_old(2,2); cc=s_old(2,1); dd=s_old(2,2); ee=s_old(3,1)+s_old(2,1); ff=s_old(3,2)+s_old(2,2); v_old(2,1)=bb; v_old(2,2)=aa; s_old(2,1)=dd; s_old(2,2)=cc; if n>2; s_old(3,1)=ee-dd; s_old(3,2)=ff-cc; end end end

if nl>2; if t==543; mm=v_old(2,2); nn=v_old(2,3); oo=s_old(2,2); pp=s_old(2,3); ee=s_old(3,2)+s_old(2,2); ff=s_old(3,3)+s_old(2,3); v_old(2,2)=nn; v_old(2,3)=mm; s_old(2,2)=pp; s_old(2,3)=oo; if n>2; s_old(3,2)=ee-pp; s_old(3,3)=ff-oo; end end end

if n>2 if t==617; gg=v_old(3,1); hh=v_old(3,2);

Page 15: Robert_Tanner_&_Han_Zhang_Road_Traffic_Dynamics_Report

27/11/14 Department of Mechanical Engineering, UOB

15 Robert Tanner 1217762 Han Zhang 1235042

ii=s_old(3,1); jj=s_old(3,2); kk=s_old(4,1)+s_old(3,1)+s_old(2,1); ll=s_old(4,2)+s_old(3,2)+s_old(2,2); v_old(3,1)=hh; v_old(3,2)=gg; s_old(3,1)=jj; s_old(3,2)=ii; if n>2; s_old(4,1)=kk-jj; s_old(4,2)=ll-ii; end end end

% Calculate target separation (starg) starg1=(v_old.^2)./(2*abrmax); starg2=tr*v_old; starg3=starg2-starg1;

starg=(ktg*starg3)+L; starg(1,1:nl)=0;

% Calculate instantaneous acceleration and apply necessary limits v1=[z;v_old]; v2=[v_old;z]; v3=v2-v1; vcl=v3(1:n,1:nl); vcl(vcl<=0)=0; vcl(1,1:nl)=0;

es=s_old-starg; es(es<=-5)=-5;

ev=v_old-vtarg; ev(ev>=10)=10;

acc1=[z;acc_old]; acc2=acc1(1:n,1:nl); acc3=(ks*es)+(kv1*ev)+(kv2*vcl)+(ka*acc2); acc3(acc3<=abrmax)=abrmax;

two=2*ones(n,nl); A0=two-(v_old/30); acc4=(acc3>A0); acc5=(acc3<A0); acc6=acc4.*A0; acc7=acc5.*acc3; acc8=acc6+acc7;

tooclose=(s_old<=l); suddenbrake=(-8).*tooclose; suddenbrake(1,1:nl)=0; approach=[tooclose; z];

beingapproached=approach(2:n+1,1:nl); dontgethit=beingapproached.*A0; emergencyacceleration=suddenbrake+dontgethit; abouttocrash=(emergencyacceleration~=0);

Page 16: Robert_Tanner_&_Han_Zhang_Road_Traffic_Dynamics_Report

27/11/14 Department of Mechanical Engineering, UOB

16 Robert Tanner 1217762 Han Zhang 1235042

perfectlysafe=ones(n,nl)-abouttocrash; wereintrouble=abouttocrash.*emergencyacceleration; everythingsfine=acc8.*perfectlysafe; acc_new=wereintrouble+everythingsfine;

% Calculate mean seperations and speeds and store firstlanev=v_old(1:n,1); firstlanes=s_old(1:n,1); avgspeed=mean(firstlanev); avgsep=mean(firstlanes);

V(1,p)=avgspeed; Sep(1,p)=avgsep;

% Calculate new seperartions and speeds v_new=v_old+(dt*acc_historic(1:n,k:j)); s_new=s_old-(dt*vcl); s_new(1,1:nl)=0;

% Calculate traffic flow density and store every second S=cumsum(s_old(1:n,1))+1; Q=fix(S); D=zeros(1,n100); D(1,Q)=1; D1=vec2mat(D,10); num=size(D1); rows=num(1,1); nine=zeros(rows,9); D2=sum(D1,2); D3=D2./0.01; D4=[D3 nine]; D5=reshape(D4.',1,[]); D6=D5(1,1:n100);

if o==10 M(p,:)=D6; end

% Return new speeds, accelerations and seperations to beginning of loop v_old=v_new; acc_old=acc_new; s_old=s_new;

% Store historical acceleration values acc_historic(1:n,k:j)=acc_new;

end % Output mean speed, mean separation and density arrays and plot

f1=figure plot(T,V) axis([0 tf 0 60]) title('Average speed in the first lane') xlabel 'Time (seconds)' ylabel 'Average Speed (metres per second)' drawnow

f2=figure plot(T,Sep)

Page 17: Robert_Tanner_&_Han_Zhang_Road_Traffic_Dynamics_Report

27/11/14 Department of Mechanical Engineering, UOB

17 Robert Tanner 1217762 Han Zhang 1235042

axis([0 tf 0 60]) title('Average car separation in the first lane') xlabel 'Time (seconds)' ylabel 'Average Separation (metres per second)' drawnow

Z=M; f3=figure axis([0 20000 0 tf]) surf(Z,'EdgeColor','none'),view(-10,10) title('Traffic flow density in the first lane') caxis([0 100]) colorbar shading flat xlabel 'Distance (metres)' ylabel 'Time (seconds)' zlabel 'Density (cars per kilometre)' drawnow