You are on page 1of 188

Duluth Entertainment Convention Center (DECC) Special Events Traffic Flow Study

A THESIS SUBMITTED TO THE FACULTY OF THE GRADUATE SCHOOL OF


THE UNIVERSITY OF MINNESOTA
BY

Nan Zhang

IN PARTIAL FULFILLMENT OF THE REQUIREMENTS FOR THE DEGREE OF


MASTER OF SCIENCE IN COMPUTER SCIENCE

JULY 2004

UNIVERSITY OF MINNESOTA

This is to certify that I have examined this copy of a masters thesis by

Nan Zhang

and have found that it is complete and satisfactory in all respects,


and that any and all revisions required by the final
examining committee have been made.

Advisers:

Dr. Jiann-Shiou Yang

Dr. Douglas Dunham

________________________
Signature

_______________________
Signature

Dr. Hudson Turner


_______________________
Signature

_______________________
Date

GRADUATE SCHOOL

Table of Contents
ABSTRACT...................................................................................................................... III
ACKNOWLEDGEMENTS............................................................................................... V
ACRONYM GLOSSARY ................................................................................................ VI
LIST OF FIGURES .........................................................................................................VII
LIST OF TABLES............................................................................................................ IX
CHAPTER 1 ....................................................................................................................... 1
1. INTRODUCTION ....................................................................................................... 1
PART I: SPECIAL EVENTS SIGNAL TIMING OPTIMIZATION................................. 4
CHAPTER 2 ....................................................................................................................... 6
2. DATA COLLECTION ................................................................................................ 6
2.1 Data Collection Tools ........................................................................................... 6
2.2 Identify the Project Study Area............................................................................. 7
2.3 Traffic Data........................................................................................................... 8
CHAPTER 3 ..................................................................................................................... 10
3. THE SPSA ALGORITHM ........................................................................................ 10
3.1 The SPSA Algorithm .......................................................................................... 10
3.2 Implementation ................................................................................................... 12
3.3 Measure-of-Effectiveness (MOE)....................................................................... 15
3.4 Program Implementation .................................................................................... 16
3.4.1 Traffic Control Module............................................................................ 16
3.4.2 Simulation Module................................................................................... 17
3.4.3 MOE Module ........................................................................................... 18
CHAPTER 4 ..................................................................................................................... 19
4. SIGNAL TIMING RESULTS AND DISCUSSIONS............................................... 19
4.1 Background ......................................................................................................... 19
4.2 Signal Timing...................................................................................................... 22
4.3 Performance Evaluations .................................................................................... 28
PART II TRAVEL TIME PREDICTION ..................................................................... 31
CHAPTER 5 ..................................................................................................................... 33
5. TRAVEL TIME DATA COLLECTION................................................................... 33
5.1 GPS Test Vehicle Technique .............................................................................. 34
5.2 The Telemetry Platform...................................................................................... 36

5.3 Sample Data ........................................................................................................ 40


CHAPTER 6 ..................................................................................................................... 42
6. KALMAN FILTERING ............................................................................................ 42
6.1 Background ......................................................................................................... 42
6.2 Filtering Process.................................................................................................. 43
6.3 Implementation ................................................................................................... 45
6.4 The Computer Program....................................................................................... 47
CHAPTER 7 ..................................................................................................................... 49
7. RESULTS OF TRAVEL TIME PREDICTION........................................................ 49
7.1 Travel Time Data ................................................................................................ 49
7.2 Sample Prediction Results .................................................................................. 51
7.3 Error Comparison of the Road Sections ............................................................. 53
7.4 The Effect of Sample Time Interval on Prediction Error ................................... 55
7.5 Data Interpolation ............................................................................................... 55
7.6 The Effect of the Usage of Historic Data............................................................ 58
7.7 The Effect of Variance on Prediction Error........................................................ 60
CHAPTER 8 ..................................................................................................................... 61
8. CONCLUSION.......................................................................................................... 61
REFERENCES ................................................................................................................. 63
APPENDICES .................................................................................................................. 66
APPENDIX I Program List .............................................................................................. 66

II

ABSTRACT
Following special events (e.g., conventions, concerts, graduation ceremonies) at
the Duluth Entertainment and Convention Center (DECC), high volumes of existing traffic
create substantial congestion at adjacent intersections. This research focuses on DECC
special events traffic flow study. The first part of this study is to develop an effective traffic
signal timing control for the high volume traffic movements so that progression through
the downtown Duluth and I-35 is as efficient as possible.
A practical approach for signal timing optimization that eliminates the need of
using a traffic dynamic model is used. This approach is based on Neural Networks (NNs)
with the weight estimation via the Simultaneous Perturbation Stochastic Approximation
(SPSA) algorithm. The NN weights are adjusted by the SPSA algorithm that minimizes the
measure-of-effectiveness (MOE) criterion at the selected intersections. The results derived
from the optimization algorithm are compared with those generated using a traffic control
software called Synchro.
The second part of this research focuses on the critical issue of the mobility
monitoring and performance measure. A performance measure in terms of the travel time
parameter is used as an index to measure the after events service quality of the arterials
near the DECC. The Global Positioning System (GPS) test vehicle technique is used to
collect after events travel time data. The data received are immediately processed by a
Kalman filter via the filtering and estimation techniques. Based on the current data

III

received and traffic flow exiting the main intersections near the DECC, the travel time in
the following time interval can then be estimated. The entire process is recursively
performed in discrete time and the travel time information can be updated continuously to
reflect the traffic fluctuation in real-time so that the service quality of the routes can be
gauged. The short-term signal timing developed in this study should help to move the
traffic exiting the DECC area more efficiently. In addition, the results from this study can
apply to arterials such as the Miller Hill corridor to provide an index to gauge the traffic
performance in the area of interest, and the information produced here can also be utilized
and adopted by an Advanced Traveler Information System (ATIS).

IV

ACKNOWLEDGEMENTS
First of all, I would like to give my sincere thanks to my advisor, Professor
Jiann-Shiou Yang, who has been offering me a great deal of precious guidance and
support to my research project and my thesis. I also want to sincerely thank Professor
Douglas Dunham and Professor Hudson Turner for not only teaching me a lot in my
graduate study but also reviewing my thesis and being my final examination committee
members.
Additionally, I want to thank my group mates Feng Qian and Nan Yang. Besides
helping in data collection, Feng Qian made much effort in choosing and testing the data
collection hardware and Nan Yang set up and maintained our project website.
Also, I want to thank the Electrical and Computer Engineering Department of the
University of Minnesota Duluth and the Northland Advanced Transportation Systems
Research Laboratory (NATSRL) for providing me this opportunity to work in this
research through which I have learned a lot that will be so beneficial to my future career.
And, I want to give my thank to Dr. Daniel C. Chin for giving me useful advices
on the implementation of the SPSA method and Mr. Mars Cyr, traffic signal engineer
from the City of Duluth Traffic Service Center, for providing us the traffic data and
signal timing information.
Last but not least, I want to thank my friends Yanpeng Zhang and Xiaoyue Niu
for giving me advices from their fields and supporting me throughout.

ACRONYM GLOSSARY

ATIS

Advanced Traveler Information System

CMS

Changeable Message Signs

DGPS

Differential Global Positioning System

DOD

Department of Defense

GPS

Global Positioning System

ITS

Intelligent Transportation System

MARE

Mean Absolute Relative Error (MARE)

Mn/DOT

Minnesota Department of Transportation

MOE

Measure of Effectiveness

NATSRL

Northland Advanced Transportation Systems Research Laboratory

NN

Neural Networks

SPSA

Simultaneous Perturbation Stochastic Approximation

SWARM

Synchronized Wide Area Remote Modules

VI

LIST OF FIGURES

Figure 2.1 Traffic data counters TT2 and TT4 ............................................................... 6


Figure 2.2 Data counter and road tube used on Superior Street. .................................... 7
Figure 2.3 Area map showing the project study area...................................................... 8
Figure 2.4 Averaged traffic volume data for the UMD Mens hockey games ............... 9
Figure 3.1 Overall relationships between the traffic system, NN controller, and SPSA
algorithm. .............................................................................................................. 13
Figure 3.2 The structure of the implemented NN controller. ....................................... 17
Figure 3.3 Flowchart for implementation of the SPSA algorithm................................ 18
Figure 4.1 Pre-timed signal operation........................................................................... 20
Figure 4.2 Dual ring concept (east/west main street) ................................................... 21
Figure 4.3 Typical phase numbering schemes.............................................................. 22
Figure 5.1 GPS test vehicle travel time data collection. ............................................... 33
Figure 5.2 Typical equipment setup for GPS test vehicle technique............................ 36
Figure 5.3 A snapshot of GPS-TEAM.......................................................................... 39
Figure 5.4 The sections of the network under study..................................................... 40
Figure 5.5 Sample travel time data. .............................................................................. 41
Figure 6.1 The Kalman filter loop. ............................................................................... 45
Figure 6.2 The flowchart of the implemented computer program................................ 48

VII

Figure 7.1 Observed travel times over different road sections. .................................... 50
Figure 7.2 Comparison of the predicted and observed travel times. ............................ 51
Figure 7.3 Prediction results for the three sections....................................................... 54
Figure 7.4 Prediction results with interpolated data points........................................... 57
Figure 7.5 Effect of the usage of historic data .............................................................. 59

VIII

LIST OF TABLES

Table 4.1 Signal timing.................................................................................................. 27


Table 4.2 Comparison of the performance on 5th Avenue W ........................................ 28
Table 4.3 Comparison of the performance on Railroad Street and Lake Avenue N ..... 29
Table 4.4 Performance comparison of the entire network............................................. 29
Table 7.1 Prediction result for the UMD graduation ceremony. ................................... 52
Table 7.2 Error performance comparison of three road sections................................... 53
Table 7.3 Error performance comparison of 3 min and 5 min interval ......................... 55
Table 7.4 Error performance comparison with interpolated data points ....................... 56
Table 7.5 Error performance comparison with historic data and interpolated points.... 59
Table 7.6 MARE using different measure error variance and noise sequence variance 60

IX

CHAPTER 1
1. INTRODUCTION
The study of traffic flow and efficient traffic management on roads and freeways
is one of the most challenging problems in transportation engineering. Traffic signal
timing optimization of existing systems, signal coordination, and advanced traffic
management and control all have been proposed as important components of Intelligent
Transportation System (ITS) measures. Improving the timing of traffic signals at
intersections in a network is generally the most cost-effective means to reduce
congestion. Following special events (e.g., hockey games, concerts, graduation
ceremonies, etc.) at the Duluth Entertainment Convention Center (DECC), high volumes
of traffic exiting the DECC create substantial congestion at adjacent intersections. This
thesis addresses the congestion issue by developing a coordinated signal timing plan to
improve the traffic flow in that area. Based on the signal timing results developed, the
second part of this study focuses on the critical issue of mobility monitoring and
performance measure.

A performance measure, in terms of travel time, is used to gauge

the service quality of the routes (e.g., Railroad Street, 5th Avenue West) exiting the
DECC area. Travel time is an important measure of the performance of transportation
systems. It is important for a variety of real-time and off-line transportation applications
such as traffic system performance monitoring, control, and planning. In addition,
short-term travel time information through changeable message signs (CMS) is also

useful for motorists to make their route choice decisions, to select different transportation
modes, and to determine their departure time. This thesis studies the after events traffic
flow data over a 30-minute time period at key intersections near the DECC. The first part
will present a coordinated signal timing plan developed by the Simultaneous Perturbation
Stochastic Approximation (SPSA) method, while the second part will focus on the travel
time prediction using the well known Kalman filtering and estimation technique.
By developing the proposed signal timing plans and predicting travel time, this
research should help Minnesota Department of Transportation (Mn/DOT) District 1 and
the City of Duluth Traffic Service Center manage the traffic flow following special
events at the DECC more efficiently. The results can also provide a valuable assessment
tool and guidelines to modify the existing signal timing based on current traffic
situations, and establish an efficient coordinated and prioritized timing control strategy
following DECC events, which is essential to reduce intersection delay and congestion.
This thesis consists of two parts and is organized as follows. The first part (i.e.,
Chapters 2 to 4) presents the development of an improved coordinated signal timing plan
using the SPSA algorithm. The timing optimization is based on a neural network (NN)
serving as a controller with the weight adjustments occurring in closed-loop mode via the
SPSA algorithm. The algorithm requires only loss function measurements and no
gradients of the loss function are required. The second part, which includes Chapter 5
through Chapter 7, presents the prediction of travel time using the Kalman filter. It
focuses on using the travel time parameter in the performance monitoring and mobility

measure of the arterials exiting the DECC following special events. Both the historic and
real-time data are fed into the Kalman filter, which can efficiently predict travel time via
the estimation techniques. In each part of this thesis, the data collection strategy is
introduced, the method/technique is explained, and the results and performance
evaluations are then followed. Finally, the conclusion is given together with the
appendix.

PART I: SPECIAL EVENTS SIGNAL TIMING


OPTIMIZATION
The first part of this thesis analyzes after events traffic flow data over a 30-minute
time period at key intersections near the DECC, and then develops a coordinated signal
timing control to improve traffic flow and reduce intersection delay. During this study,
the signalized intersections having the most impact on the traffic flow exiting the DECC
area are first identified and then the after events traffic data are collected. Based on the
data collected, a practical approach for signal timing control that eliminates the need of
using a traffic dynamic model, usually a set of equations representing the traffic system,
is developed to optimize the intersection signal time following special events. This
approach is based on NN with the weight estimation via the SPSA algorithm. The NN
weights were adjusted by the SPSA parallel estimation algorithm that minimizes the
measure-of-effectiveness (MOE) at the intersections. The results developed using the
SPSA algorithm are compared with those generated using the Synchro. After consultation
with the City of Duluth traffic signal engineer, the suggested coordinated signal timing
plan at the six intersections near the DECC is then developed. The performances
evaluation using the existing signal timing plan and those generated by the SPSA and
Synchro was also studied. Our evaluations are mainly based on two MOE criteria; one is
the tolerance index and the other is the total delay per vehicle. The short-term signal
timing developed in this study should help to move traffic exiting the area more

efficiently and the results can also be easily modified and applied to other coordinated
intersection signal networks.

CHAPTER 2
2. DATA COLLECTION
2.1 Data Collection Tools
For optimizing the signal timing plan in the study area, the data related to the
current traffic is a prerequisite. Combined with manual counting, two types of data
counters from Diamond Traffic Products Corporation are used for traffic data collection.
They are Traffic Tally 2 (TT2) and Traffic Tally 4 (TT4) shown in Figure 2.1. These two
pictures come from the website http://www.diamondtraffic.com/. Figure 2.2 shows a
vehicle counter and road tube on Superior Street. In addition, six video cameras are used
to collect data (images) for two special events (i.e., graduation ceremonies). The traffic
volume data obtained from these videotapes through monitors are used to verify those
data collected by the TT2 and TT4 counters.

Figure 2.1 Traffic data counters TT2 and TT4

Figure 2.2 Data counter and road tube used on Superior Street.

2.2 Identify the Project Study Area


The area map showing our project study area is given in Fig. 2.3. Since the two
main arterials exiting the DECC are 5th Avenue W and Railroad Street, the key
intersections to be studied are: I-35N/5th AvenueWest, I-35S/5th AvenueWest, Superior
St/5th AvenueWest, Railroad St/Lake Avenue South, Railroad St/Canal Park Drive, and
I-35/ Lake Avenue North. The first three intersections are defined as the network 1 and
the other three as the network 2.

Figure 2.3 Area map showing the project study area

2.3 Traffic Data


The special events traffic volume data were collected over the period October 25,
2002 to May 17, 2003. Of the total 21 times, 12 were for UMD Mens hockey games, 4
for graduation commencements, and 5 for concerts. Traffic volumes within 15 minutes
immediately after these events were collected. Similar events data was further averaged

and converted to hourly traffic volume. The traffic volume data were separately recorded
for left turn, right turn and through traffic volumes in all of the four possible directions.
Additional data were also provided by Mr. Mars Cyr, traffic signal engineer from the City
of Duluth Traffic Service Center. Figure 2.4 shows the averaged traffic volume data for
UMD Mens hockey games.

Figure 2.4 Averaged traffic volume data for the UMD Mens hockey games

CHAPTER 3
3. THE SPSA ALGORITHM
Multivariate stochastic optimization is important in analyzing and controlling
many engineering systems. In nearly all real-world optimization problems, it is necessary
to apply a mathematical algorithm that iteratively finds out the solution because an
analytical (closed-form) solution is rarely available. For this reason, the SPSA method for
difficult multivariate optimization problems has been developed [1]. Since its appearance,
the SPSA algorithm has drawn considerable attention in areas such as statistical
parameter estimation, feedback control, simulation-based optimization, signal and image
processing, and experimental design. The essential feature of SPSA, which accounts for
its power and relative ease of implementation, is the underlying gradient approximation
that requires only two measurements of the objective (or loss) function regardless of the
dimension of the optimization problem. This feature greatly decreases the cost of
optimization, especially in problems with a large number of variables to be optimized.

3.1 The SPSA Algorithm


In 1994, Spall and Chin presented an approach for optimal signal light timing,
which is an application of SPSA algorithm [4]. The approach is based on a neural
network (NN) serving as the basis for the control law with the weight estimation
occurring in closed-loop mode via the SPSA algorithm. Since the SPSA algorithm
requires only loss function measurements (no gradients of the loss function), the need for

10

a complex open-loop model of the traffic dynamics as a component of the control


strategy is eliminated.
Given a set of neural network weights , let k denote the estimate of at
the k th iteration of the SPSA algorithm. The SPSA algorithm for estimating has the
general stochastic approximation form

k +1 = k a k g k (k )

(3.1)

where ak is a scalar gain coefficient and g k (k ) represents the gradient estimate at

= k.
Given a loss function L( ) , the optimization problem can be translated into

finding such that L / = 0 . This is the classical formulation of (local) optimization


for differentiable loss functions. Then the critical step in implementing the SPSA
algorithm in Eq. (3.1) is to determine the gradient estimate g k ( ) of any value of .
Assume that the parameter vector is p-dimensional, then the gradient estimate at any

has the form


[ L ( + c k k ) L ( c k k )] / 2c k k1

.........................................................
g k ( ) = .........................................................

.........................................................

[ L( + c k k ) L ( c k k )] / 2c k kp

Eq. (3.2)

where L () denotes an observed value of L() , k = ( k 1 , k 2 ,..., kp ) T is a vector of


random variables (the superscript T means the transpose) that satisfy the regularity
conditions, whose essence is that ak and ck both go to 0 at rates neither too fast nor too

11

slow, that L( ) is sufficiently smooth (several times differentiable) near converged ,


and that the { ki } are independent and symmetrically distributed about 0 with finite
inverse moments (i.e., E(| ki |-1) for all k, i), and c k is a small positive number [1, 4].

3.2 Implementation

The implementation of this approach is based on the combination of the SPSA


algorithm and NN. The NN serves to approximate the true (but unknown) mathematical
function representing the optimal signal controller. This controller takes information from
the traffic data and produces the signal timing to optimize the MOE.
SPSA fulfills a role analogous to back-propagation in providing values for the
NN weights, but at the considerable advantage of not requiring a traffic model. The SPSA
algorithm for weight estimation is based on observing simulated traffic patterns when
slight changes are made to current light timing settings; these slight changes are done
in a special way that is at the heart of the algorithm and that maximizes the amount of
information available for optimization while minimizing disruptions to the traffic system.
The fundamental control strategy here is to develop a mathematical function,
u () , which takes current information on the state of the traffic conditions and produces a
set of signal timings that optimizes the performance of the traffic flow. This control
function is represented by a NN, which is used for approximating complex nonlinear
functions such as the optimal control for traffic timings. Figure 3.1 illustrates the overall
relationship between the traffic system, the NN controller and the SPSA training

12

algorithm. Note that essentials to the performance of the NN controller are the values of
the connection weights in its structure.

Figure 3.1 Overall relationships between the traffic system, NN controller, and SPSA algorithm.

The following steps summarize how the SPSA algorithm would be conceptually
implemented to achieve optimal traffic timing control:
1.

Initialize all the NN weights using the corresponding fixed timing schedule

(e.g. the ratio of time duration between the green and red phases).
2.

Given the current NN weight vector estimate, change all values according to

Eq. (3.2).
3.

Simulate the traffic system throughout the pre-specified time period (i.e. 30

minutes) and form the sample loss function (sum of observed MOEs) based on the system
behavior.

13

4.

During the following pre-specified time period, repeat Steps 2 and 3 with a

complementary slight change in the NN weight vector estimate.


5.

With information from Steps 3 and 4 on separately calculated loss functions,

form the gradient estimate, and then take one iteration of the SPSA algorithm to update
the values of the elements of the weight vector.
6.

Repeat Steps 2-5 with the new weight values until the traffic signal timing is

optimized.

Based on the above approach, the step-by-step implementation of the SPSA


algorithm for updating k to k +1 (k = 0,1,2,...) can be presented as follows:
1.

Given the current estimate k , change all values of k to k + c k k

where c k and k satisfy the regularity conditions in Spall and Cristion (1992, 1994)
[1, 4].
2.

Throughout the given time sector, use a NN control u ( ,) with weights

= k + c k k . Inputs to u ( ,) at any time within the sector include current state


information.
3.

Form loss function L (k + c k k ) based on simulated system behavior.

4.

During the following time sector, repeat Steps 1 to 3 with k c k k

replacing k + c k k . Form L (k c k k ) .

14

5.

With information from Steps 3 and 4 on L (k + c k k ) and L (k c k k ) ,

form the simultaneous perturbation gradient estimate in Eq. (3.2) and then take one
iteration of the SPSA algorithm in Eq. (3.1) to update the value of k to k +1 .
6.

Repeat Steps 1 to 5 with the new value k +1 replacing k until the MOE

is optimized.

3.3 Measure-of-Effectiveness (MOE)

According to Chin, Spall, and Smith [2], the heart of problem for any automated
traffic control algorithm is to determine an adequate MOE calculation that will achieve
the specified goal. The system performance depends on the selected MOE.
The MOE used in our signal timing control is the tolerance index. The value of
tolerance index is calculated from the total sum of the differences between the nominal
throughput during the green phase and the actual averaged traffic counts under saturated
situation (i.e., the number of vehicles, recorded by road tubes, crossing the signal light
over the time period t g ). In other words, it actually represents how much deviation from
the nominal throughput. The smaller the index is, the more satisfied the drivers will be.
This further implies the lower possibility for vehicles to wait for the red signal. Although
tolerance index is not as easy to understand as some other MOEs such as travel time, it is
an integrated reflection of the quality of the traffic signal timing.
Within a unit time at a traffic signal, let v be departure frequency (in vehicles
per second) on the road sector facing the signal, t g be the time of the green phase, l be

15

the averaged traffic volume, and T be the tolerance index for that signal. Then the loss
function is defined as T = (vt g l ) / l , where is either 1 or 0 as it is either included or

excluded from the computations.


Averaged traffic volume and the corresponding signal timings are used to
compute the traffic tolerance index. The two road networks are considered separately and
the tolerance index of each network is the summation of the tolerance index at the three
intersections in that network.

3.4 Program Implementation

Our program implementing signal timing control consists of three separate


modules: the traffic control module, the traffic flow simulation module, and the MOE
evaluation module, coded in C++. These modules are briefly described below.

3.4.1 Traffic Control Module

For the controller, a two-hidden-layer, feed-forward NN with 20 input nodes and


6 output nodes is used. The two hidden layers have 6 and 4 nodes, respectively. The 6
output nodes represent the green/red splits of the associated six intersections. The 20 NN
input nodes are:
1.

The 14 averaged traffic volume (vehicles per hour divided by cycles per

hour) from external nodes to the networks.


2.

The 6 outputs (vectors of timing splits) from the previous control solution.

16

The following figure shows the structure of the NN controller.

Figure 3.2 The structure of the implemented NN controller.

3.4.2 Simulation Module

The simulation module takes the output timings from the NN controller to change
the signal phases and counts the number of vehicles at the sensor locations.
The input of the simulation module consists of the actual number of arriving
vehicles from the roads heading to the simulation area and the values of the control
variables output from the control module. The NN output contains only some of the
elements of the total traffic signal timing plan, and the other elements in the timing plan
are the same as the original plan.

17

3.4.3 MOE Module

This module computes the measure of effectiveness. It uses the averaged traffic
volume and the corresponding signal timings to compute the traffic tolerance index. The
traffic tolerance index defined here is the total sum of the differences between the
nominal throughput during the green phase and the averaged traffic volume. The SPSA
algorithm is used to minimize the tolerance index that is obtained from applying two sets
of perturbed NN weights.
The flowchart for implementation of Fig. 3.1 is shown in Fig 3.3.

Figure 3.3 Flowchart for implementation of the SPSA algorithm.

18

CHAPTER 4
4. SIGNAL TIMING RESULTS AND DISCUSSIONS
The special events signal timing plan using the SPSA optimization algorithm in
Chapter 3 is presented in this chapter. The results include the optimized split times at all
six intersections near the DECC. The performance evaluations are then given in the
second part of this chapter.

4.1 Background

A traffic signal controls traffic by assigning right-of-way to one traffic movement


or several non-conflicting traffic movements at a time. Right-of-way is assigned by
turning on a green signal for a certain length of time or an interval. Right-of-way is ended
by a yellow change interval during which a yellow signal is displayed, followed by the
display of a red signal. The device that times these intervals and switches the signal
lamps is called a controller unit [10].

There are basically two types of signal controller units in use today: the pre-timed
and the traffic actuated. The timing plan we developed is for pre-timed signal controller,
that is, the signal assigns right-of-way at an intersection according to a predetermined
schedule. The sequence of right-of-ways (phases or splits) and the length of the time
interval for each signal indication in the cycle is fixed, based on historic traffic patterns.

19

The major elements of pre-timed control are (1) fixed cycle length, (2) fixed phase length,
and (3) number and sequence of phases.

Figure 4.1 shows the timing operation for a basic two-phase or two-traffic
movement pre-timed controller unit.

Figure 4.1 Pre-timed signal operation

The cycle length is the total time to complete one sequence of signalization
around an intersection. A traffic signal phase, or split, is the part of the cycle given to an
individual movement, or combination of non-conflicting movements during one or more
intervals. An interval is a portion of the cycle during which the signal indications do not
change.

20

A ring is a term that is used to describe a series of conflicting phases that occur in
an established order. A ring may be a single ring, dual ring, or multi-ring. The dual ring
concept with the major route in the east/west direction is illustrated in Figure 4.2. A
barrier (compatibility line) is a reference point in the preferred sequence of a multi-ring
controller unit at which all rings are interlocked. Barriers assure there will be no
concurrent selection and timing of conflicting phases for traffic movements in different
rings. All rings cross the barrier simultaneously to select and time phases on the other
side.

Figure 4.2 Dual ring concept (east/west main street)

The dual-ring controller uses a maximum of eight phase modules, each of which
controls a single traffic movement with red, yellow and green display. The eight phases
are required to accommodate the eight movements (four through and four left turns) at
the intersection. Phases 1 through 4 are included in ring A, and phases 5 through 8 are

21

included in ring B. The two rings operate independently, except that their control must
cross the barrier (see definition of barrier above) at the same time.

Phase numbers are the labels assigned to the individual movements around the
intersection. For an eight phase dual ring controller, it is common to assign the main
street through movements as phases 2 and 6. Also, it is common to use odd numbers for
left turn signals and the even numbers for through signals. Figure 4.3 illustrates a typical
phase numbering scheme for an east/west arterial and a north/south arterial.

Figure 4.3 Typical phase numbering schemes

4.2 Signal Timing

The optimized signal timing plan produced by the SPSA algorithm is listed and
also compared with the one generated by the Synchro software. The three intersections at
5th Avenue West use North/South arterial while the three intersections at Railroad Street
use East/West arterial. The timings at the six intersections are given in Table 4.1. Each
table shows the original split times used by the City (if the coordinated mode is

22

available), the optimized split times generated by both the SPSA and Synchro programs,
and the suggested times after re-adjustments. In other words, the column labeled
Original (%) represents the split times (in percentage of the cycle length) currently
used by the city, the third and fourth columns represent the total split times generated by
Synchro and SPSA, respectively; and the column labeled Suggested (%) represents the
split times we suggested after our consultation with the traffic engineer.

(1) 5th Avenue West and I-35 N

Ring 1: 1-4/Ring 2: none


1 NBT & NBR
2 - SBT & SBL
4 - EBT & EBR & EBL

Phase

Original
(%)

Synchro
(%)

SPSA
(%)

Suggested
(%)

----

60

54

55

2
4

-------

10
30

16
30

15
30

----- means signal timing only operates in free mode not in coordinated mode

23

(2) 5th Avenue West and I-35 S

Ring 1: 3/Ring 2: 5, 6
3 WBT & WBR & WBL
5 - NBT & NBL
6 - SBT & SBR
Phase

Original
(%)

Synchro
(%)

SPSA
(%)

Suggested
(%)

----

33.75

26

25

5
6

-------

18.75
47.5

49
25

50
25

(3) 5th Avenue West and Superior Street

Ring 1: 1, 2, 4/Ring 2: 5, 6
1 EBL; 2 - WBT & WBR; 5 WBL; 6 - EBT & EBR
4 - NBT & NBR & NBL (yield on green) plus
SBT & SBR & SBL (yield on green)

24

Phase

Original
(%)

Synchro
(%)

SPSA
(%)

Suggested
(%)

15

35

23

15

2
4
5

45
40
15

35
30
35

64
13
23

50
35
15

45

35

64

50

(4) Railroad Street and Lake Avenue S

Ring 1: 2, 4/Ring 2: 5, 6, 8
2 - WBT & WBR & WBL;
4 - SBT & SBR & SBL (yield on green)
5 NBR; 6 - EBT & EBR & EBL (yield on green)
8 - NBT & NBL (yield on green)

Phase

Original
(%)

Synchro
(%)

SPSA
(%)

Suggested
(%)

----

61.25

62

60

4
5

-------

28.75
10

19
19

20
20

6
8

---------

61.25
28.75

62
19

60
20

25

(5) Railroad Street and Canal Park Drive

Ring 1: 1-4/Ring 2: 5, 6
1 NBL; 2 - SBT & WBR; 3 - EBT & EBR & EBL
4 - WBT & WBR & WBL; 5 SBL; 6 NBT & NBR

Phase

Original
(%)

Synchro
(%)

15

10

16

15

2
3

32
33

25
45

22
43

20
45

4
5

20
15

20
10

19
16

20
15

32

25

22

20

SPSA
(%)

Suggested
(%)

(6) Lake Avenue and I-35 N

Ring 1: 1-3/Ring 2: 5-7


1 NBL; 2 - SBT & SBR; 3 EBT & EBR & EBL; 5 - SBL
6 - NBT & EBR; 7 WBT & WBR & WBL

26

Phase

Original
(%)

Synchro
(%)

SPSA
(%)

Suggested
(%)

20

55.625

26

35

2
3

50
30

18.75
25.625

55
19

45
20

5
6

20
50

55.625
18.75

26
55

35
45

30

25.625

19

20

Table 4.1 Signal timing.

Note that the current signal timing at the intersections of 5th Avenue W & I35 N
and 5th Avenue W & I35 S is operating in free mode. That is, once the loop detector,
located about 300 feet from the intersection, detects a vehicle passing by or standing, it
triggers the signal timing control to automatically extend the green time to 60 seconds.
For the intersection at Railroad Street & Lake Avenue S, the current timing splits also run
in free mode and each time a queue is detected by the loop detector, the green split in
that direction will be again extended for 3 to 4.5 seconds until it reaches the maximum
split preset by the City of Duluth Traffic Service Center.
The original splits listed in the table above for the intersections with free mode
signal are their coordinated timing splits, and their performance index is calculated with
these data. For the three intersections that operate in free mode (i.e., 5th Avenue W &
I35N, 5th Avenue W & I35S and Railroad Street & Lake Avenue S), the performance
index is calculated with maximum splits in main directions while minimum splits in
others directions.

27

As expected, the output timing plan generated by the SPSA algorithm prolongs
the green time for the main traffic exiting the DECC. The traffic from DECC is so heavy
comparing with other traffic that the split of timing for many other directions become less
than the minimum split they can have set by Traffic Service Center. In this case we set
the split to be the minimum split and extend the green time in other directions.

4.3 Performance Evaluations

Traffic flow performance study using the signal timing plans generated by the
SPSA-based optimization technique is conducted and compared with the results of using
the timing plan currently used by the City of Duluth Traffic Service Center. The results
are shown in Table 4.2 to 4.4.

MOE
(vtg - l)/l

Original
(%)
23.7

Synchro
(%)
38.62

Delay/veh (s)

47.1

48.4

53.7

43.7

Total Delay
(hr)
Stops/veh

4.8

4.8

5.4

4.4

1.22

1.40

1.39

1.20

Total Stops

444

504

505

435

Avg Speed
(mph)

17

17

16

18

SPSA
(%)
23.23

Suggested
(%)
23.24

Table 4.2 Comparison of the performance on 5th Avenue W

28

MOE
(vtg - l)/l

Original
(%)
26.54

Synchro
(%)
22.55

Delay/veh

56.0

35.5

40.3

41.9

Total Delay
(hr)
Stops/veh

7.6

4.9

5.6

5.8

1.63

1.04

1.16

1.18

Total Stops

801

518

579

590

11

10

10

Avg
Speed(mph)

SPSA
(%)
25.28

Suggested
(%)
25.31

Table 4.3 Comparison of the performance on Railroad Street and Lake Avenue N

MOE
(vtg l)/l

Original
(%)
50.24

Synchro
(%)
61.17

Delay/veh

103.1

83.9

94.0

85.6

Total Delay
(hr)
Stops/veh

12.4

9.7

11

10.2

2.85

2.44

2.55

2.38

Total Stops

1245

1022

1084

1025

25

28

26

28

Avg
Speed(mph)

SPSA
(%)
48.51

Suggested
(%)
48.55

Table 4.4 Performance comparison of the entire network.

Note:
1.

Except the tolerance index, all the values of the other performance index are

given by Synchro.
2.

Total Performance Index is calculated as the sum of both networks.

29

Since the tolerance index is used as MOE in this research, obviously, the SPSA
algorithm generates the best results (i.e., the lowest value) in terms of that index measure.
This is true for the network on 5th Avenue, but not for the network on Lake Avenue,
where Synchro shows a better result. This is because Synchro does not have a minimum
green time limit so that the green duration time for some directions with lower traffic
volume are set even shorter than the minimum green time used by the Traffic Service
Center. However, we found that Synchro produced an even worse result than the one
currently used by the City for both the network on 5th Avenue W. and the entire
networks.
For the integrated tolerance index of both networks, with the MOE defined in the
implementation, the SPSA method gives the best results while the suggested one is
slightly worse than that generated by the SPSA algorithm. With the MOEs other than the
tolerance index such as the total delay per vehicle used by Synchro, the outcome of
Synchro seems the best. However, even with the MOE used by Synchro, the outcome of
the SPSA approach is still better than that of the original one.
The performance measure was also conducted based on other criteria. Overall, the
SPSA algorithm gives the best results for the tolerance index being optimized. However,
the performance based on other criteria seems to be close to, but no better than, that
generated by the Synchro software. This is true for this case study (i.e., a small-scale
network in downtown area). A further investigation of large-scale networks needs to be
conducted.

30

PART II TRAVEL TIME PREDICTION


Travel time is an important measure of the performance and service quality of
transportation systems. Travel time is selected as a performance measure to study
because it has the following main advantages.
z

Travel time is the most common way that users measure the quality of their
trip.

It is a variable that can be directly measured.

Travel time is a simple measure to use for traffic monitoring.


The second part of this thesis focuses on the critical issue of mobility study and

travel time prediction. The questions to be addressed here are: how easy is it to exit the
DECC area? How much does that "ease of movement" vary after the DECC special
events? It is important to have some kind of measure about the traffic flow performance
on Railroad Street and 5th Avenue West due to sudden traffic surge exiting the DECC
after special events. The ability to monitor and gauge the service quality of the routes
before and after special events is, therefore, necessary. Travel time data are important for
a variety of real-time and off-line transportation applications including traffic system
performance monitoring, control, and planning. In addition, short-term travel time
information through changeable message signs (CMS) is also useful for motorists to
make their route choice decisions, to select different transportation modes, and to
determine their departure time. Travel times and distribution have always been of interest

31

to traveler information researchers, planners, and public agencies and they are used as a
key measure in performance evaluation of traffic systems.

In the second part of this thesis, travel time data collection will first be introduced.
Real-time data are collected using the Global Positioning System (GPS) test vehicle
techniques which will be briefly discussed before a sample of data stream for a special
event is presented. A recursive, discrete-time Kalman filter will then be introduced. Both
historic and real-time data are fed into the model, which can then efficiently predict travel
time via the Kalman filtering and estimation techniques. An assessment of the
performance and its effectiveness at the test site are investigated. Prediction results using
a 5-minute and a 3-minute interval are compared, and the methods of using the rate of
change of historic data and the interpolation technique are also used to improve the
prediction accuracy. The travel time prediction from this study can be easily applied to
other arterials to provide an index to monitor and gauge the traffic system performance in
the area of interest. The information produced can also be utilized and adopted by an
Advanced Traveler Information System (ATIS).

32

CHAPTER 5
5. TRAVEL TIME DATA COLLECTION
The GPS test vehicle technique is used in our travel time data collection. In every
second, the GPS receiver/STXe transmitter module on each test vehicle sends the data
stream back to the RX 2 base station. The base station, housing a very sensitive RX
receiver unit with a high gain dipole antenna, is USB connected to a laptop computer.
The computer is equipped with appropriate software to process the data and then feed the
data to the prediction model for real-time travel time prediction. The data and
communication links between the test vehicles and base station are shown in Fig. 5.1.
In this chapter, the GPS test vehicle technique is briefly introduced and then
followed by the equipment and travel time data.

Figure 5.1 GPS test vehicle travel time data collection.

33

5.1 GPS Test Vehicle Technique

The test vehicle technique has been used for travel time data collection since the
late 1920s. Traditionally, this technique has involved the use of a data collection vehicle
within which an observer records cumulative travel time at predefined checkpoints along
a travel route. This information is then converted to travel time, speed, and delay for each
segment along the survey route. There are several different methods for performing this
type of data collection, depending upon the instrumentation used in the vehicle and the
driving instructions given to the driver. Since these vehicles are instrumented and then
sent into the field for travel time data collection, they are sometimes referred to as
active test vehicles. Conversely, passive ITS probe vehicles are vehicles that are
already in the traffic stream for purposes other than data collection. Two levels of
instrumentation to measure travel time with a test vehicle are used in this project, that is,
Manual - manually recording elapsed time at predefined checkpoints
Global Positioning System (GPS) - determines test vehicle position and speed
by using signals from the Department of Defense (DOD) system of
earth-orbiting satellites.
Historically, the manual method has been the most commonly used travel time
data collection technique. This method requires a driver and a passenger to be in the test
vehicle. The driver operates the test vehicle while the passenger records time information
at predefined checkpoints.
GPS has become the most recent technology to be used for travel time data

34

collection. A GPS receiver is connected to a portable computer and collects the latitude
and longitude information that enables tracking of the test vehicle.
The GPS was originally developed by the Department of Defense for the tracking
of military ships, aircraft, and ground vehicles. Signals are sent from the 24 satellites
orbiting the earth at 20,120 km (12,500 mi). These signals can be utilized to monitor
location, direction, and speed anywhere in the world. A consumer market has quickly
developed for many civil, commercial, and research applications of GPS technology
including recreational (e.g., backpacking, boating), maritime shipping, international air
traffic management, and vehicle navigation. The location and navigation advantages of
GPS have found many uses in the transportation profession.
Figure 5.2 illustrates the equipment needs for GPS travel time data collection. The
test vehicle is shown at the top of the figure with the GPS and Differetial GPS (DGPS)
antennas resting on the roof of the vehicle. The DGPS antenna is connected to the
differential correction receiver, and the GPS antenna is connected to the GPS receiver.
The differential correction data is then transferred to the GPS receiver. The GPS receiver
uses the differential correction data to correct incoming signals, and then the corrected
information is output to the in-vehicle laptop. The laptop stores the data at predefined
time intervals as the vehicle travels down the roadway. When the travel time run is
completed, the laptop information is downloaded to a data storage computer.

35

Figure 5.2 Typical equipment setup for GPS test vehicle technique.

5.2 The Telemetry Platform

Equipment from GPSFlight Corporation is used to realize the GPS test vehicle
technique. The telemetry platform consists of:
z

The TracID Hardware Platform

The GPS-integrated telemetry units is low-cost, micro-sized with an onboard


telemetry TracID CPU and receiver base stations are used to pick up the signals and
display the results on a PC in plug-and play fashion.

36

The transmitter used is the STXe module with TracID, which is built around
patent-pending proprietary firmware algorithms which enable multiple devices to submit
information across a wide-spread, dispersed network without collision, and keep very
accurate synchronization among all units.
z

SWARM and TracID

A network of units communicating in this fashion is known as a Synchronized


Wide Area Remote Modules (SWARM) Network. The SWARM protocol enables
compressed packed data transmissions including GPS and other data, and allows
individual identification by TracID. The SWARM can support more than 46,000 units
with a maximum of 10 units per second reporting per network.
A total of seven independent networks are possible per geographic area. Each of
these seven networks operate independent from each other,

so up to 7 different

networks can operate in the same location without interfering with each other as well.
z

GPSFlight Radio Link

GPSFlight radio link supports 900 MHz Spread Spectrum communication at


speeds of 9600b. With the compression on the data stream through TracID, the
throughput is typically about 8 times that of standard NMEA-type telemetry, or 76.8 kb.
From a range perspective, the 900 MHz products have demonstrated real-time links of
over 30 miles line of sight using 2dB omni directional antennas. For non line of sight,
the range is 1200 to 2000 ft.
To improve the accuracy of the data, we upgraded the antenna for each transmitter
module from its built-in 1 dB antenna to a MMCX connected 2dB gain 6

37

half-wavelength antenna and the antenna for the receiver from 2 dB RPSMA antenna to

HyperGain HG903MGU 3 dB Magnetic Vehicle Mount Omni Antenna. As a result,


the average reception rate was improved from 85% to 95%.
z

GPSFlight GPS Engines

The GPS platform utilizes 12-channel L1 signals and WAAS for positioning
accurate to 1-5 meters typically. The update frequency for GPS position is 1 second.
The GPS output is standard 9600 b NMEA (a standard protocol used by GPS receivers to
transmit data) data, which is communicated to the TracID computer, and simultaneously
to the serial port onboard the transmitter. The TracID compresses the NMEA data into
the binary TracID data stream.
The GPS antenna is a 28 dB gain patch antenna with a 4 lead.
z

The GPS-TEAM Software

Built to compliment the GPSFlight advanced telemetry units, the GPS-TEAM


software platform provides detailed tracking and device configuration. GPS-TEAM is an
advanced, multi-tracking GPS-telemetry application. The software decodes the SWARM
data stream and creates a list of all reporting TracID units. Some of the important features
of the GPS-TEAM software are:

Programming the GPS, radio, and TracID CPU

Display of all reporting TracID units in a network

Map library which enables any bit-mapped map to be used for plotting in

real-time

38

TracID statistics table which lists continually updating speed, position,

heading information as well as maximums attained.

Events window which lists the time, location, and altitude of any event,

similar to a waypoint.

Altitude plot which shows all TracIDs in an altitude window at the same

Setting of Ground Zero for horizontal and vertical starting position.

time.

A snapshot of the GPS-TEAM showing the data steam received and the traveling
path of the test vehicles is given in Fig. 5.3.

Figure 5.3 A snapshot of GPS-TEAM.

39

5.3 Sample Data

The network 2 to be studied is divided into three sections. The first section is the
road segment from the exit of the DECC to the intersection of Railroad Street and Lake
Avenue S. The second section is from the intersection of Railroad Street and Lake
Avenue S to the intersection of Railroad Street and Canal Park Drive. The third section is
from the intersection of Railroad Street and Canal Park Drive to the intersection of I-35
and Lake Avenue N.

Figure 5.4 The sections of the network under study.

The total and section travel times were collected for the DECC special events
over a 7-month time period. These special events includes the UMD Mens and Womens
hockey games, concerts, and graduation ceremonies. Sample data collected for the UMD
graduation ceremony is shown in Figure 5.5.

40

Figure 5.5 Sample travel time data.

As can be seen from Figure 5.5, most of the travel time elapses in section 1. This
is because the distance of section 1 is much longer than the other two. The travel time
fluctuations of sections 2 and 3 are relatively smaller because they are more likely to be
affected by the traffic signal timing while the travel time of section 1 is more likely to be
affected by the flow rate of the traffic.

41

CHAPTER 6
6. KALMAN FILTERING
6.1 Background

In 1960, R.E. Kalman published his famous paper describing a recursive solution
to the discrete-data linear filtering problem [29]. This solution made up previous
solutions in optimal estimate by providing an alternative way of formulating the least
squares filtering problem using state-space methods. Since that time, due to large part to
advances in digital computing, the Kalman filter has been the subject of extensive
research and applications, particularly in the area of autonomous and assisted navigation.
The Kalman filter is a set of mathematical equations that provides an efficient
computational (recursive) means to estimate the state of a process, in a way that
minimizes the mean of the squared error. The filter is very powerful in several aspects: it
supports estimations of past, present, and even future states, and it can do so even when
the precise nature of the modeled system is unknown.
The Kalman filter tells how the past values of the input should be weighted in
order to determine the present value of the output, that is, the optimal estimate. By
providing a way of formulating the least squares filtering problem using state-space
methods, the Kalman filter can solve many discrete-time, multi-input multi-output
problems. The two main features of the Kalman formulation and solution of the problem
are (1) vector modeling of the random processes under consideration, and (2) recursive
processing of the noisy measurement (input) data.

42

6.2 Filtering Process

According to [13], assume that the random process to be estimated can be


modeled in the form
x k +1 = k x k + wk

Eq. (6.1)

where
x k = (n 1) process state vector at time tk.

k = (n n) state transition matrix relating xk to xk+1 without a forcing function.


wk = (n 1) vector representing white noise sequence.
The observation (measurement) of the process is assumed to be
z k = H k xk + vk

Eq. (6.2)

where
z k = (m 1) measurement vector at time tk.
H k = (m n) matrix giving the connection between the measurement and the
state vector at time tk under noise-free condition.
v k = (m 1) measurement error.
We assume that vk is a white sequence with known covariance and it is
uncorrelated with wk. It is also assumed that we have an initial estimate of the process at
time tk, and that this estimate is based on what is known about the process prior to tk. This
prior estimate will be denoted as x k where ^ denotes estimate, and the - is a
reminder that this is the best estimate prior to assimilating the measurement at tk.
Let the estimation error be

43

ek = x k x k

Eq. (6.3)

and the error covariance matrix is


T

Pk = E[ek ek ] = E[( x k x k )( x k x k ) T ]

Eq. (6.4)

where the superscript T means the transpose.


A linear blending of measurement and the prior estimate is expressed as
x k = x k + K k ( z k H k x k )

Eq. (6.5)

where x k = updated estimate and


K k = Pk H kT ( H k Pk H kT + Rk ) 1

Eq. (6.6)

is called the Kalman gain, then the relationship between Pk and Pk can be expressed as
Pk = ( I K k H k ) Pk

Eq. (6.7)

x k+1 = k x k

Eq. (6.8)

Since

we can write the expression for Pk+1 as


Pk+1 = k Pk kT + Qk

Eq. (6.9)

With the results mentioned above, the Kalman filter loop can be expressed as Fig 6.1.

44

Figure 6.1 The Kalman filter loop.

6.3 Implementation

The Kalman filtering algorithm is applied in this study to predict travel time
exiting the DECC following special events.
Assume that the prediction process can be modeled as
x k +1 = k x k + wk
where the state variable xk is the travel time to be predicted at time k, k is the state
transition parameter relating xk to xk+1, and wk is a zero mean Gaussian noise sequence
with covariance Qk. That is, E[ wi wTj ] = Qi (i j ) , where the superscript T means the
transpose, the symbol E[] represents the expected value, and (i j ) is the function

45

which equals to 1 for i = j and 0 for ij. Note that, in general, xk and wk are in vector form
with the same dimension. In this application, xk and wk are scalar and historic data are
used to obtain k , which describes the time dependent relationship between the travel
times in any two consecutive time intervals.
Since no traffic parameter other than travel time is involved, the
measurement/observation equation associated with the state variable xk is given by
z k = H k xk + vk
where zk represents the observation, i.e., the average of the travel times reported by the
test vehicles at time k. The parameter Hk correlates the functional connection between xk
and zk (in our case, Hk =1), and vk, the measurement noise, is a Gaussian sequence with
zero mean and covariance Rk. Assume that {wk} and {vk} are uncorrelated (i.e.,
E[ wi v Tj ] = 0 for all i and j). Furthermore, let the prediction error ek = x k x k and Pk

be the error covariance at time k. Then, our travel time prediction, based on the
minimization of Pk (i.e., minimum mean-square error), can be summarized as follows:
Step 1: Initialization
Set k = 0 and let E[ x0 ] = x 0 and E[e02 ] = P0
Step 2: Extrapolation
State estimate extrapolation: x k+1 = k x k
Error covariance extrapolation: Pk+1 = k Pk kT + Qk
Step 3: Kalman gain calculation

46

K k = Pk H kT ( H k Pk H kT + Rk ) 1 (Hk =1)
Step 4: Update
State estimate update: x k = x k + K k ( z k H k x k )
Error covariance update: Pk = ( I K k H k ) Pk
Step 5: Let k = k + 1 and go to Step 2 until the preset time period ends.

6.4 The Computer Program

A computer program has been developed for recognizing TracID binary data
stream and implementing Kalman filtering online. The input of the program is historic
(average) travel time and TracID binary data stream sent by GPS-TEAM in real-time.
The output generated by the program is the synchronously predicted travel time.
The TracID binary data stream is sent from the STXe transmitters installed in test
vehicles to GPS-TEAM every second. The computer program transfers these data stream
into recognized position and time information. When the test vehicles pass the
pre-defined start and end points, the time is recorded and travel time is computed. With
historic data, these travel time data are fed into Kalman filter to get the predicted travel
time in the next time interval. The program runs recursively until the traffic congestion is
over.

47

Figure 6.2 The flowchart of the implemented computer program

48

CHAPTER 7
7. RESULTS OF TRAVEL TIME PREDICTION
In this chapter, the prediction results using the Kalman filter are discussed. First,
the sample travel time data and prediction results are introduced, and the prediction
results on the three sections are then compared. Furthermore, the methods using the rate
of change of historic data (i.e. slope) and the data interpolation technique will be applied
to improve the accuracy of our travel time prediction. The main criteria used for the error
analysis is Mean Absolute Relative Error (MARE). A lower MARE indicates a better
result.

7.1 Travel Time Data

Sample travel time data for the UMD Graduation Ceremony on May 15, 2004 is
graphed in Fig. 7.1.

49

Figure 7.1 Observed travel times over different road sections.

In Fig. 7.1, the Total curve shows the total travel time from exiting the DECC
till leaving the intersection at I-35 and Lake Avenue N. The travel time associated with
the road section 1, 2 and 3 are expressed in section 1, section 2 and section 3
respectively. Note that the travel time includes waiting time in addition to actual traveling
time.
As can be seen from the figure, during the peak of the traffic congestion, most of
the travel time elapses in section 1. This is because the distance of section 1 is much
longer than that of the other two. And the test vehicles have to wait at intersection 1 for
several signal cycles instead of only one cycle at intersection 2 and 3.

50

Sections 2 and 3 are so short that the length of waiting queue is limited by the
distance of sections no matter how heavy the traffic is. So the travel time of sections 2
and 3 is relatively constant and less likely to be affected by the traffic flow but more
likely to be affected by the signal timing at intersections 2 and 3. If the traffic signal
coordinates well enough, the vehicles can pass intersections 2 and 3 after they pass
intersection 1 without too much delay.

7.2 Sample Prediction Results

Based on Fig. 7.1, the comparison of the predicted and observed travel time is
shown in Fig. 7.2. The predicted travel time at each time instant is compared with the
corresponding observed travel time.

Figure 7.2 Comparison of the predicted and observed travel times.

51

Roughly speaking, the predicted travel time follows the observed travel time. The
predicted travel time at current time instant is basically determined by the observed and
predicted travel times at the past time instants. When there is a sudden increase or
decrease of actual travel time, the predicted one at that time instant will still keep the
previous trend and thus, causes larger prediction error. We found that the average error
will be smaller if the duration of time of congestion lasts longer.
The error, expressed in MARE, is given in Table 7.1. In this table, the prediction
time interval is 3 minutes, that is, the test vehicles depart from the start point every 3
minutes and the computer program predict the travel time every 3 minutes. There are 15
iterations over the time period we studied.

Date and Special


Events

May 15
UMD
Commencement

Prediction
Time Interval
(min.)

Number
of Intervals

3.0

15

MARE
(%)

17.61

Table 7.1 Prediction result for the UMD graduation ceremony.

Note:

xi = true value; xi = predicted value.


n

i =1

Mean Absolute Relative Error (MARE) =

xi xi
xi
n

100%

52

7.3 Error Comparison of the Road Sections

Error performance comparison of three road sections is shown in Table 7.2. Of


the three road sections, section 3 generates a relatively smaller MARE. This is due to the
smaller variance of travel time we observed in section 3. As discussed above, a more
sudden change in travel time incurs a larger prediction error. Overall speaking, the
MARE of all sections is roughly within the same range. The prediction results of the
UMD Graduation Ceremony for the three sections are shown in Figure 7.3.

Date and Special


Events
Section 1
Section 2
Section 3

Prediction Time
Interval (min.)
3.0
3.0
3.0

Number of
Intervals
15
15
15

MARE (%)

24.98
25.17
21.25

Table 7.2 Error performance comparison of three road sections

53

Figure 7.3 Prediction results for the three sections

54

7.4 The Effect of Sample Time Interval on Prediction Error

The time interval is a time step within which data will be collected for predicting
travel time in the next time step. The duration of a time interval for a prediction process
depends on the level of traffic congestion and the number of test vehicles over time. Both
3-minute and 5-minute intervals are used to evaluate the predicted travel time.
As shown in Table 7.3, generally, the prediction results using a 3-minute interval
seem better than those using a 5-minute interval. But this is not always true. Since the
duration time of congestion after special events are similar, the shorter the interval time
is, the more intervals there are. Therefore, the shorter time interval is used, the better the
prediction result will be.

Date and Special


Events
April 25
Concert
May 22
Concert

Prediction Time
Interval (min.)

Number of
Intervals

MARE (%)

5.0

33.44

3.0

21.20

Table 7.3 Error performance comparison of 3 min and 5 min interval

7.5 Data Interpolation

To increase the number of prediction intervals, a data interpolation method is


used. That is, we create a data point between any two consecutive data points by
averaging. After interpolation we found that the prediction error drops dramatically. With
the increased number of data points, the prediction is less likely to be affected by the
sudden increase or decrease of travel time.

55

The values of interpolated data points are calculated by averaging the values of
consecutive data points between which data points are interpolated. The results by
interpolating two and three data points are compared in Table 7.4 and shown in Fig. 7.4.
Obviously, the more data points are used, the better the error performance is.

Date Interpolation

Original
1- point
interpolated
2-point
interpolated

Prediction Time
Interval (min.)

Number of
Intervals

MARE (%)

3.0

15

17.61

1.5

29

7.68

1.0

43

4.40

Table 7.4 Error performance comparison with interpolated data points

56

Figure 7.4 Prediction results with interpolated data points

57

7.6 The Effect of the Usage of Historic Data

The travel time data are categorized into three types: UMD Mens hockey games,
graduate ceremonies, and concerts (including all other special events such as concert,
symphony and circus). Historic data are averaged and used to adjust the result of
prediction.
Since the prediction error is mostly caused by sudden increase and decrease of
travel time, the predicted travel time given by the Kalman filter and the one with the
same slope as historic data are averaged and used as the real predicted travel time. Let xn
be the predicted travel time generated by the Kalman filter at time point n, hn the historic
travel time at time point n, and yn the predicted travel time adjusted using historic data,
then y n = [ x n + ( y n 1 + hn hn 1 )] / 2 . This method is tested on several cases, but it is
only good for the condition that the travel time is typical such as the historic travel time.
In addition, a combined method of using both the interpolation and historic data is
used to improve our prediction results. A case study of the special event on April 25
(Circus Show) is given in Table 7.5 and shown in Figure 7.5.

58

Figure 7.5 Effect of the usage of historic data

Methods

Prediction Time
Interval (min.)

Number of
Intervals

MARE (%)

Original
Slope
Adjusted
Slope Adjusted
+ 1-point Interpolation
Slope Adjusted
+ 2-point Interpolation

5.0

33.44

5.0

27.57

2.5

11

24.08

1.67

16

17.11

Table 7.5 Error performance comparison with historic data and interpolated points

59

7.7 The Effect of Variance on Prediction Error

The effect of varying the parameters Q (i.e., the variance of the process noise) and
R (i.e., the variance of the measurement noise) on the prediction error is also studied.
Different values of Q and R are used to compare the MARE index, and the results for the
UMD Graduate Ceremony are list in Table 7.6.

R\Q

25

50

100

1,000

10,000

100,000

0.232

0.120

0.061

0.006

0.001

0.000

10

1.661

0.971

0.537

0.061

0.006

0.001

100

5.488

4.281

3.031

0.537

0.061

0.006

1,000

8.257

7.610

6.835

3.031

0.537

0.061

10,000

9.337

9.198

8.900

6.835

3.031

0.537

21,394

9.390

9.343

9.219

7.675

4.404

1.025

100,000

9.485

9.447

9.405

8.900

6.835

3.031

Table 7.6 MARE using different measure error variance and noise sequence variance

Generally, MARE drops when the measurement error variance R decreases and
the process noise variance Q increases. In our study, the measurement error variance used
is the averaged variance of the historic travel time, which is 21,394 and the noise
sequence variance Q we choose is 10,000.

60

CHAPTER 8
8. CONCLUSION
A practical approach for signal timing adjustments that eliminates the need of
using traffic dynamic models is developed to optimize the signal timing control following
special events at the DECC. The approach we used is based on neural networks with the
weight estimation (i.e., the training process) via the SPSA algorithm. The NN weights
are determined by use of the SPSA parallel estimation algorithm. Convergence is
obtained when the MOE criterion in terms of the tolerance index has been optimized.
The optimal split times, in percentage of the cycle length, at each intersection are
determined and compared with those generated using the Synchro software. The
suggested timing plan should help to move traffic exiting the DECC area more
efficiently. With some modifications the results from this study can also be used to
manage traffic flow for other scenarios (e.g., Grandmas Marathon, I-35 incident, etc.).
Furthermore, the mobility monitoring and performance measure after DECC
special events are also studied. The travel time parameter, collected via the GPS test
vehicle technique, is used to measure the performance. Using both historic and real-time
data, a recursive, discrete-time Kalman filter is implemented to predict the travel times on
the arterials exiting the DECC.
An assessment of the performance and its effectiveness at the test site are
investigated. The accuracy of our prediction error is improved by use of the rate of

61

change of historic data and the data interpolation technique. The effects of changing the
noise parameters Q and R on the prediction error are also studied. The travel time
prediction from this study can be easily applied to other arterials (e.g., Central
Entrance/Highway 194 corridor) to gauge the performance and service quality of the
arterials in the area of interest.

62

REFERENCES

Spall, J.C., Multivariate Stochastic Approximation Using a Simultaneous


1.
Perturbation Gradient Approximation, IEEE Transactions on Automatic Control, vol.
37, No. 3, pp. 332-341, March 1992.
Chin, D.C., Spall, J.C. and Smith, R.H., Evaluation of System-Wide Traffic
2.
Signal Control Using Stochastic Optimization and Neural Networks, Proceedings of the
American Control Conference, San Diego, California, June 1999.
Spall, J.C. and Chin, D.C., Traffic-responsive Signal Timing for System-wide
3.
Traffic Control, Proceedings of the American Control Conference, Albuquerque, New
Mexico, June 1997.
Spall, J.C. and Chin, D.C., A Model-Free Approach to Optimal Signal Light
4.
Timing for System-wide Traffic Control, Proceedings of the 33rd Conference on
Decision and Control, Lake Buena Vista, FL., December 1994.
Rowe, E., The Los Angeles Automated Traffic Surveillance and Control
5.
(ATSAC) System, IEEE Transactions on Vehicular Technology, vol. 40, No. 1, pp.
16-20, February 1991.
6. Spall, J.C. An Overview of the Simultaneous Perturbation Method for Efficient
Optimization, Johns Hopkins APL Technical Digest, vol. 19, No 4, pp. 482-492, 1998
Yu, X. and Stubberud, A.R., Optimization of Network Signal Timing,
7.
Proceedings of the American Control Conference, Philadelphia, Pennsylvania, June
1998.
Nguyen, D.H. and Widrow, B., Neural Network for Self-learning Control
8.
Systems, IEEE Control Systems Magazine, April 1990.
Husch, D. and Albeck, J., Trafficware Synchro 5.0 User Guide for Windows,
9.
Trafficware, Albany, CA.
Sorenson, H. W., Kalman Filtering: Theory and Application, IEEE Press, New
10.
York, 1985.

63

11.
Roess, R. P., McShane, W. R. and Prassas, E. S., Traffic Engineering, 2nd edition,
Prentice Hall, New Jersey, 1998.
Welch, G and Bishop, G, An Introduction to the Kalman Filter, UNC-Chapel
12.
Hill, TR 95-041, April 5, 2004.
Brown, R.G. and Hwang, Y.C., Introduction to Random Signals and Applied
13.
Kalman Filtering, 3rd Edition, John Wiley & Sons, New York, 1997.
Chien, I. J. and Kuchipudi, M., Dynamic Travel Time Prediction with Real-time
14.
and Historical Data, Transportation Research Board the 81st Annual Meeting,
Washington D.C., January 2002.
Kuchipudi, M. and Chien, I. J., Development of a Hybrid Model for Dynamic
15.
Travel Time Prediction, Transportation Research Board the 82nd Annual Meeting,
Washington D.C., January 2002.
Chen, M. and Chien S. I., Dynamic Freeway Traffic Time Prediction Using
16.
Probe Vehicle Data: Link-based vs. Path-based, Transportation Research Board 80th
Annual Meeting, Washington, D.C., January 2001.
Chien, S.I., Liu, X. and Ozbay, K., Predicting Travel Times for the South Jersey
17.
Real-time Motorist Information System, The Journal of Transportation Research Board,
October 2002.
Gallagher, J., Travel Time Data Collection Using GPS, National Traffic Data
18.
Acquisition Conference, Albuquerque, New Mexico, May 1996.
Laird, D., Emerging Issues in the Use of GPS for Travel Time Data Collection,
19.
National Traffic Data Acquisition Conference, Albuquerque, New Mexico, May 1996.
Febbraro, A. D. and Giglio, D., Timed Petri Net-based Optimization of Traffic
20.
Signal Phases in Urban Areas.
Bullock, D., et al., Data Collection and Reporting for Congestion Management
21.
Systems, National Traffic Data Acquisition Conferences, Albuquerque, New Mexico,
May 1996.
Suzuki, H., Nakatsuji, T., Tanaboriboon, Y. and Takahashi, K., A
22.
Neural-Kalman Filter for Dynamic Estimation of Origin-Destination (O-D) Travel Time

64

and Flow on a Long Freeway Corridor, Transportation Research Board 79th Annual
Meeting, Washington, D. C., January, 2000.
GPSFlight, GPS-Team Product Manual, Advanced Telemetry Tracking,
23.
GPSFlight, Inc. 2003.
Gantz, D. T. and Mekemson, J. R., Flow Profile Comparison of a Microscopic
24.
Car-following Model and a Macroscopic Platoon Dispersion Model for Traffic
Simulation, Proceedings of the 1990 Winter Simulation Conference.
Yu, X. and Stubberud, A.R., Markovian Decision Control for Traffic Signal
25.
Systems, Proceedings of the 36th conference on Decision & Control, San Diego,
California. December 1997.
Kwon. J., Coifman, B. and Bickel, P., Day-to-Day Travel Time Trends and Time
26.
Prediction from Loop Detector Data.
Huisken, G. and van Berkum, E. C., A Comparative Analysis of Short-Range
27.
Travel Time Prediction Methods, 82nd Transportation Research Board Conference.
Sun, C., Arr, G. and Ramachandran, R. P., An Investigation in the Use of
28.
Vehicle Reidentification for Deriving Travel Time and Travel Time Distributions,
Transportation Research Board 2003 Annual Meeting.
Kalman, R. E. 1960. A New Approach to Linear Filtering and Prediction
29.
Problems, Transaction of the ASMEJournal of Basic Engineering, pp. 35-45 March
1960.

65

APPENDICES
APPENDIX I Program List
List of programs:
ChildFrm.h
ChildFrm.cpp
GetArrivalRates.cpp
InputDlg.h
InputDlg.cpp
Intersection.h
Intersections.h
Intersections.cpp
MainFrm.h
MainFrm.cpp
NN.h
NN.cpp
resource.h
RoadNet.h
RoadNet.cpp
RoadSector.h
RoadSectors.h
RoadSectors.cpp
StdAfx.h
StdAfx.cpp
TrafDef.h
TrafDef.cpp
TrafDefDoc.h
TrafDefDoc.cpp
TrafDefView.h
TrafDefView.cpp
trafeval.h
kalman.c

**************************************************************************************
*

ChildFrm.h

**************************************************************************************
// ChildFrm.h : interface of the CChildFrame class

66

//
/////////////////////////////////////////////////////////////////////////////
#if !defined(AFX_CHILDFRM_H__6D3D061B_C6EE_11D4_8AA4_0050DACD1682__INCLUDED_)
#define AFX_CHILDFRM_H__6D3D061B_C6EE_11D4_8AA4_0050DACD1682__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

class CChildFrame : public CMDIChildWnd


{
DECLARE_DYNCREATE(CChildFrame)
public:
CChildFrame();
// Attributes
public:
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CChildFrame)
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CChildFrame();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
// Generated message map functions
protected:
//{{AFX_MSG(CChildFrame)
// NOTE - the ClassWizard will add and remove member functions here.

67

//

DO NOT EDIT what you see in these blocks of generated code!

//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif //
!defined(AFX_CHILDFRM_H__6D3D061B_C6EE_11D4_8AA4_0050DACD1682__INCLUDED_)

**************************************************************************************
*

ChildFrm.cpp

**************************************************************************************
// ChildFrm.cpp : implementation of the CChildFrame class
//
#include "stdafx.h"
#include "TrafDef.h"
#include "ChildFrm.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CChildFrame
IMPLEMENT_DYNCREATE(CChildFrame, CMDIChildWnd)
BEGIN_MESSAGE_MAP(CChildFrame, CMDIChildWnd)
//{{AFX_MSG_MAP(CChildFrame)
// NOTE - the ClassWizard will add and remove mapping macros here.

68

//

DO NOT EDIT what you see in these blocks of generated code !

//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CChildFrame construction/destruction
CChildFrame::CChildFrame()
{
// TODO: add member initialization code here
}
CChildFrame::~CChildFrame()
{
}
BOOL CChildFrame::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: Modify the Window class or styles here by modifying
//

the CREATESTRUCT cs

if( !CMDIChildWnd::PreCreateWindow(cs) )
return FALSE;
return TRUE;
}

/////////////////////////////////////////////////////////////////////////////
// CChildFrame diagnostics
#ifdef _DEBUG
void CChildFrame::AssertValid() const
{
CMDIChildWnd::AssertValid();
}
void CChildFrame::Dump(CDumpContext& dc) const
{

69

CMDIChildWnd::Dump(dc);
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CChildFrame message handlers

**************************************************************************************
*

GetArrivalRates.cpp

**************************************************************************************
void GetArrivalRates(int cycle, float car_arrival_rates[])
{
int loop_count[25][20]=
{128, 42, 8, 88, 30,

44, 124, 55, 30, 0,

6,

6, 2, 14, 40, 15, 6,


24,

5,

64, 15, 7,

30, 6,

184, 56, 8, 98, 30,

40, 128, 55, 30, 0,

6,

6, 3,

128, 78, 8, 92, 30,

56, 128, 55, 30, 0,

6,

6, 3, 14, 72, 15, 7,

5,

40, 8,

206, 66, 8, 80, 30,

42, 142, 60, 30, 0,

6,

6, 4, 20, 76, 15, 7,

5,

40, 8,

178, 94, 8, 102, 30,

68, 136, 60, 30, 0,

6,

6, 8, 26, 90, 17, 8,

5,

40, 8,

214, 72, 8, 116, 35,

52, 170, 65, 35, 0,

6,

6, 8,

162, 86, 8, 92, 35,

70, 156, 65, 35, 3,

6,

6, 8, 18,100,

206, 80, 8, 120, 35,

66, 134, 65, 35, 0,

6,

6, 8,

158, 94, 8, 122, 35,

78, 174, 65, 35, 2,

232, 70, 8, 128, 35,

32, 92, 17, 8,

5,

5,

30, 6,

62, 8,

17, 8,

5,

58, 8,

22,102, 17, 8,

5,

60, 8,

6,

6, 8, 30, 98, 20, 8,

5,

49, 8,

54, 214, 70, 35, 3,

6,

6,10, 32,104,

20, 8,

5,

54, 10,

190, 102, 8, 134, 35,

86, 190, 70, 35, 8,

6,

6,10, 30,118,

20, 8,

5,

67, 10,

242, 94, 8, 128, 40,

66, 184, 70, 40, 10, 8,

8,10, 38,104,

20, 8,

5,

68, 10,

154, 110, 8, 124, 40,

78, 188, 75, 40, 10, 8,

8,10, 30,102,

20, 8,

5,

66, 10,

260, 74, 8, 128, 40,

64, 144, 75, 40, 15, 8,

8,12, 28,108,

20, 8,

5,

72, 10,

196, 130, 8, 125, 40,

88, 140, 80, 40, 10, 8,

8,12, 34,102,

20, 8,

5,

69, 10,

272, 98, 8, 132, 40,

60, 176, 80, 40, 5,

8,

8,12, 32,122,

20, 8,

5,

64, 10,

198, 116, 8, 115, 40,

82, 190, 80, 40, 4,

8,

8,14, 28,106,

25, 8,

5,

55, 12,

266, 124, 8, 118, 45,

62, 178, 85, 45, 4,

8,

8,14, 42,102,

25, 8,

5,

84, 12,

208, 132, 8, 125, 45,

76, 162, 85, 45, 0,

8,

8,14, 30,124,

25, 8,

5,

48, 12,

270, 100, 8, 122, 45,

56, 158, 90, 45, 2,

8,

8,14, 42,124,

25, 8,

5,

61, 12,

184, 122, 8, 120, 45,

94, 146, 90, 45, 0,

8,

8,16, 42,100,

25, 8,

5,

88, 12,

252, 104, 8, 118, 45,

46, 158, 95, 45, 0,

8,

8,16, 40,128,

25, 8,

5,

76, 12,

196, 110, 8, 135, 45,

70, 150, 97, 45, 0,

8,

8,16, 34,128,

20, 8,

5,

84, 12,

278, 122, 8, 148, 45,

44, 150, 95, 45, 0,

8,

8,16, 34,128,

20, 8,

5,

65, 12

70

};
cycle/=2;

// for each cycle only has half of data

for (int i=0; i<20; i++)car_arrival_rates[i]= float(loop_count[cycle][i])*.05f;


car_arrival_rates[3] *= 1.3f;
car_arrival_rates[7] *= 1.3f;
// car_arrival_rates[0]*=1.3f; // adjust for left turn volumes at NB L40
// car_arrival_rates[3]*=1.25f;// adjust for right turn volumes at NB L150
}

**************************************************************************************
*

InputDlg.h

**************************************************************************************
#if !defined(AFX_INPUTDLG_H__6D3D0627_C6EE_11D4_8AA4_0050DACD1682__INCLUDED_)
#define AFX_INPUTDLG_H__6D3D0627_C6EE_11D4_8AA4_0050DACD1682__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// InputDlg.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CInputDlg dialog
class CInputDlg : public CDialog
{
// Construction
public:
double *x;
CInputDlg(CWnd* pParent = NULL);

// standard constructor

// Dialog Data
//{{AFX_DATA(CInputDlg)
enum { IDD = IDD_SPSA_CONSTANTS };
double

m_alpha;

int

m_b;

71

double

m_a;

double

m_c;

double

m_gamma;

int

m_seed;

int

m_hid1;

int

m_hid2;

BOOL

m_b1;

BOOL

m_b2;

BOOL

m_bo;

CString

m_intersection_ID;

int

m_sig_split_offset;

//}}AFX_DATA

// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CInputDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX);

// DDX/DDV support

//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CInputDlg)
virtual BOOL OnInitDialog();
afx_msg void OnDeltaposIdSpin(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnDeltaposTimingSpin(NMHDR* pNMHDR, LRESULT* pResult);
virtual void OnOK();
afx_msg void OnChangeBaseIn();
afx_msg void OnChangeGainAIn();
afx_msg void OnChangeAlphaIn();
virtual void OnCancel();
afx_msg void OnChangeNnHid1();
afx_msg void OnInput();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
private:
int t_index;
};

72

//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif //
!defined(AFX_INPUTDLG_H__6D3D0627_C6EE_11D4_8AA4_0050DACD1682__INCLUDED_)

**************************************************************************************
*

InputDlg.cpp

**************************************************************************************
// InputDlg.cpp : implementation file
//
#include "stdafx.h"
#include "TrafDef.h"
#include "InputDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CInputDlg dialog

CInputDlg::CInputDlg(CWnd* pParent /*=NULL*/)


: CDialog(CInputDlg::IDD, pParent)
{
t_index=0;
//{{AFX_DATA_INIT(CInputDlg)
m_alpha = 0.602;
m_b = 30;
m_a = 0.1;
m_c = 0.1;
m_gamma = 0.102;
m_seed = 4293;
m_hid1 = 6;

73

m_hid2 = 4;
m_b1 = TRUE;
m_b2 = TRUE;
m_bo = TRUE;
m_intersection_ID = _T("");
m_sig_split_offset = 0;
//}}AFX_DATA_INIT
}

void CInputDlg::DoDataExchange(CDataExchange* pDX)


{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CInputDlg)
DDX_Text(pDX, IDC_ALPHA_IN, m_alpha);
DDV_MinMaxDouble(pDX, m_alpha, 0., 1.);
DDX_Text(pDX, IDC_BASE_IN, m_b);
DDX_Text(pDX, IDC_GAIN_A_IN, m_a);
DDX_Text(pDX, IDC_GAIN_C_IN, m_c);
DDX_Text(pDX, IDC_GAMMA_IN, m_gamma);
DDV_MinMaxDouble(pDX, m_gamma, 0., 1.);
DDX_Text(pDX, IDC_SEED_IN, m_seed);
DDX_Text(pDX, IDC_NN_HID1, m_hid1);
DDV_MinMaxInt(pDX, m_hid1, 1, 100);
DDX_Text(pDX, IDC_NN_HID2, m_hid2);
DDV_MinMaxInt(pDX, m_hid2, 0, 100);
DDX_Check(pDX, IDC_NN_BIAS_L1, m_b1);
DDX_Check(pDX, IDC_NN_L2_BIAS, m_b2);
DDX_Check(pDX, IDC_OUTPUT_BIASE, m_bo);
DDX_Text(pDX, IDC_INTERSEC_ID, m_intersection_ID);
DDX_Text(pDX, IDC_SIGNAL_T, m_sig_split_offset);
DDV_MinMaxInt(pDX, m_sig_split_offset, 0, 100);
//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CInputDlg, CDialog)
//{{AFX_MSG_MAP(CInputDlg)
ON_NOTIFY(UDN_DELTAPOS, IDC_ID_SPIN, OnDeltaposIdSpin)
ON_NOTIFY(UDN_DELTAPOS, IDC_TIMING_SPIN, OnDeltaposTimingSpin)

74

ON_EN_CHANGE(IDC_BASE_IN, OnChangeBaseIn)
ON_EN_CHANGE(IDC_GAIN_A_IN, OnChangeGainAIn)
ON_EN_CHANGE(IDC_ALPHA_IN, OnChangeAlphaIn)
ON_EN_CHANGE(IDC_NN_HID1, OnChangeNnHid1)
ON_BN_CLICKED(IDC_INPUT, OnInput)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CInputDlg message handlers
BOOL CInputDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// TODO: Add extra initialization here
m_sig_split_offset = (int) x[t_index];
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void CInputDlg::OnDeltaposIdSpin(NMHDR* pNMHDR, LRESULT* pResult)
{
CString ID[]={"L40","L36","L108","L150","L39","L38","L37",
"L35","L494","L111","L112"};
NM_UPDOWN* pNMUpDown = (NM_UPDOWN*)pNMHDR;
// TODO: Add your control notification handler code here
t_index += pNMUpDown->iDelta;
if(t_index<0) t_index =0;
if(t_index>11) t_index =10;
UpdateData(TRUE);
m_sig_split_offset = (int) x[t_index];
m_intersection_ID = ID[t_index];
Invalidate(TRUE);
*pResult = 0;
}
void CInputDlg::OnDeltaposTimingSpin(NMHDR* pNMHDR, LRESULT* pResult)
{
NM_UPDOWN* pNMUpDown = (NM_UPDOWN*)pNMHDR;
// TODO: Add your control notification handler code here

75

x[t_index]=m_sig_split_offset;
*pResult = 0;
}
void CInputDlg::OnOK()
{
// TODO: Add extra validation here
CDialog::OnOK();
}
void CInputDlg::OnChangeBaseIn()
{
// TODO: If this is a RICHEDIT control, the control will not
// send this notification unless you override the CDialog::OnInitDialog()
// function and call CRichEditCtrl().SetEventMask()
// with the ENM_CHANGE flag ORed into the mask.
// TODO: Add your control notification handler code here
}
void CInputDlg::OnChangeGainAIn()
{
// TODO: If this is a RICHEDIT control, the control will not
// send this notification unless you override the CDialog::OnInitDialog()
// function and call CRichEditCtrl().SetEventMask()
// with the ENM_CHANGE flag ORed into the mask.
// TODO: Add your control notification handler code here
}
void CInputDlg::OnChangeAlphaIn()
{
// TODO: If this is a RICHEDIT control, the control will not
// send this notification unless you override the CDialog::OnInitDialog()
// function and call CRichEditCtrl().SetEventMask()
// with the ENM_CHANGE flag ORed into the mask.
// TODO: Add your control notification handler code here

76

}
void CInputDlg::OnCancel()
{
// TODO: Add extra cleanup here
CDialog::OnCancel();
}
void CInputDlg::OnChangeNnHid1()
{
// TODO: If this is a RICHEDIT control, the control will not
// send this notification unless you override the CDialog::OnInitDialog()
// function and call CRichEditCtrl().SetEventMask()
// with the ENM_CHANGE flag ORed into the mask.
// TODO: Add your control notification handler code here
}
void CInputDlg::OnInput()
{
// TODO: Add your control notification handler code here
}

**************************************************************************************
*

Intersection.h

**************************************************************************************
#include "RoadSector.h"
//

this struct contains the items as follows

//

int i_phase;

//

char phase, 1-north, 2-south, 3-east, 4-west,

//

turn,

1-left turn, 0-no_turn, 2-left turn with caution

//

int min_green;

//

int walk;

//

int ped_clear;

//

int veh_extend;

77

//

int max_green;

//

int yellow;

//

int red;

//

int red_revolt;

//

int mode;

Timings LST1[] =
{

The descriptions are in MC Traffic Timing Sheet

// 5Ave - I35N

{1, NB,TH, 14, 7, 10, 4.5f, 60, 3.5f, 2.5f, 0},


{2, SB,LT, 7, 0, 15, 3.0f, 45, 3.5f, 2.5f, 0},
{4, EB,TH, 15, 0, 15, 4.0f, 60, 4.0f, 5.0f, 0}};

Timings LST2[] = // 5Ave - I35S


{

{3, WB,TH, 15, 7, 10, 4.0f, 50, 3.5f, 2.5f, 0},


{5, NB,LT, 7, 0, 0, 3.0f, 45, 3.5f, 2.5f, 0},
{6, SB,TH, 14, 0, 15, 4.5f, 60, 3.5f, 2.5f, 0}};

Timings LST3[] =
{

// 5Ave - Superior St

{1, EB,LT, 5, 0, 7, 3.0f, 12, 3.0f, 1.0f, 2},


{2, WB,TH, 10,10, 15, 0.0f, 25, 3.5f, 1.5f, 2},
{4, NB,TH, 5,10, 13, 0.0f, 24, 3.5f, 1.5f, 2},
{5, WB,LT, 5, 0, 7, 3.0f, 12, 3.0f, 1.0f, 2},
{6, EB,TH, 10,10, 15, 0.0f, 25, 3.5f, 1.5f, 2}};

Timings LST4[] =
{

// Lake Ave - Railroad St

{2, WB,TH, 10, 7, 12, 3.5f, 60, 4.0f, 1.5f, 2},


{4, SB,TH, 10, 7, 19, 3.0f, 25, 4.0f, 1.5f, 2},
{5, NB,RT, 10, 0, 0, 3.0f, 30, 4.0f, 0.0f, 2},
{6, EB,TH, 10, 7, 14, 3.5f, 60, 4.0f, 1.5f, 2},
{8, NB,TH, 10, 7, 19, 3.0f, 75, 4.0f, 1.5f, 2}};

Timings LST5[] = // Canal Park Drive - Railroad St


{

{1, NB,LT, 8, 0, 0, 3.0f, 25, 3.5f, 1.5f, 2},


{2, SB,TH, 12, 8, 11, 4.5f, 45, 4.0f, 1.5f, 2},
{3, EB,TH, 12, 8, 12, 3.5f, 60, 4.0f, 1.5f, 2},
{4, WB,TH, 10, 8, 12, 3.5f, 30, 4.0f, 1.5f, 2},
{5, SB,LT, 8, 0, 0, 3.0f, 25, 3.5f, 1.5f, 2},
{6, NB,TH, 12, 8, 10, 4.5f, 45, 4.0f, 1.5f, 2}};

Timings LST6[] = //Canal Park Drive - Railroad St


{

{1, NB,LT, 3, 0, 7, 3.0f, 30, 3.5f, 1.5f, 2},

78

{2, SB,TH, 10, 8, 13, 4.0f, 60, 3.5f, 1.5f, 2},


{3, EB,LT, 10, 0, 7, 4.0f, 40, 3.5f, 1.5f, 2},
{5, SB,LT, 3, 0, 7, 3.0f, 30, 3.5f, 1.5f, 2},
{6, NB,TH, 10, 8, 13, 4.0f, 60, 3.5f, 1.5f, 2},
{7, WB,LT, 10, 0, 7, 3.0f, 40, 3.5f, 1.5f, 2}};

//

this struct contains items as follows

//

int id;

//

int n_phase; number of phase sequence defined for this itersection

identification of the intersection

//

struct Timings *ts[8];

//

road_section nb;

south bound road

//

road_section sb;

north bound road

//

road_section wb;

east bound road

//

road_section eb;

west bound road

timing struct define above

//

int

//

int phases[6][2]

phases sequence

//

double pro_rate

prograsive rates

//

double phase_split[5]

//

double even_times[5]

Intersection L1

number of active phases

= {1,1,
{&LST1[0],&LST1[1], NULL, &LST1[2], NULL, NULL, NULL, NULL},
{&NB_5Ave_I35N, NULL, &SB_5Ave_I35N,&EB_5Ave_I35N},
{&NB_5Ave_I35S, NULL, NULL, NULL},
3,1,0,2,0,4,0,0,0,0,0,0,0};

Intersection L2

= {2,1,
{NULL, NULL, &LST2[0], NULL, &LST2[1], &LST2[2], NULL, NULL},
{&NB_5Ave_I35S, &WB_5Ave_I35S, &SB_5Ave_I35S, NULL},
{&NB_5Ave_Superior, NULL, &SB_5Ave_I35N, NULL},
3,3,0,5,0,6,0,0,0,0,0,0,0};

Intersection L3

= {3,1,
{&LST3[0], &LST3[1], NULL, &LST3[2], &LST3[3], &LST3[4], NULL, NULL},

{&NB_5Ave_Superior,&WB_5Ave_Superior,&SB_5Ave_Superior,&EB_5Ave_Superior},
{NULL, NULL, &SB_5Ave_I35S, NULL},
3,1,5,2,6,4,0,0,0,0,0,0,0};
Intersection L4

= {4,1,

79

{NULL, &LST4[0], NULL, &LST4[1], &LST4[2], &LST4[3], NULL,&LST4[4]},


{&NB_Lake_Railroad,&WB_Lake_Railroad,&SB_Lake_Railroad,&EB_Lake_Railroad},
{NULL, NULL, NULL, &EB_Canal_Railroad},
3,2,6,4,8,5,2,0,0,0,0,0,0};
Intersection L5

= {5,1,
{&LST5[0], &LST5[1], &LST5[2], &LST5[3], &LST5[4], &LST5[5], NULL, NULL},

{&NB_Canal_Railroad,&WB_Canal_Railroad,&SB_Canal_Railroad,&EB_Canal_Railroad},
{&NB_Canal_I35, &WB_Lake_Railroad, NULL, NULL},
4,1,5,2,6,3,0,4,0,0,0,0,0};
Intersection L6

= {6,1,
{&LST6[0], &LST6[1], &LST6[2], NULL, &LST6[3], &LST6[4], &LST6[5], NULL},
{&NB_Canal_I35,&WB_Canal_I35,&SB_Canal_I35,&EB_Canal_I35},
{NULL, NULL, &SB_Canal_Railroad, NULL},
3,1,5,2,6,3,7,0,0,0,0,0,0};

**************************************************************************************
*

Intersections.h

**************************************************************************************
#if
!defined(AFX_INTERSECTIONS_H__4DF2F2E0_DB76_11D4_8AB7_0050DACD1682__INCLUDED_
)
#define AFX_INTERSECTIONS_H__4DF2F2E0_DB76_11D4_8AB7_0050DACD1682__INCLUDED_
#include "RoadSectors.h"
#include "StdAfx.h" // Added by ClassView
//#include "StdAfx.h"

// Added by ClassView

#if _MSC_VER > 1000


#pragma once
#endif // _MSC_VER > 1000
// Intersections.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CIntersections document
class CIntersections : public CDocument

80

{
protected:
CIntersections();

// protected constructor used by dynamic creation

DECLARE_DYNCREATE(CIntersections)
// Attributes
public:
CIntersections(Intersection *I_loc);
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CIntersections)
public:
virtual void Serialize(CArchive& ar);

// overridden for document i/o

//}}AFX_VIRTUAL
// Implementation
public:
int phase1;
int phase2;
void TurnLeftPhaseon(CRoadSectors *R);
void TurnPhaseon(CRoadSectors *R);
void Locate(RoadSector *Out_B[]);
void SetTimeToChange();
Intersection *I;
void SetSignalPhase();
CRoadSectors *out_B[4];
CRoadSectors *in_B[4];
int current_seq;
void SimulateTraffic(double t, CFile *Lcount);
SignalTiming st;
virtual ~CIntersections();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
// Generated message map functions
protected:

81

//{{AFX_MSG(CIntersections)
// NOTE - the ClassWizard will add and remove member functions here.
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
private:
TrafficDir dir2;
TrafficDir dir1;
double clock;
double time_to_change;
BOOL offset_cycle_time;
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif //
!defined(AFX_INTERSECTIONS_H__4DF2F2E0_DB76_11D4_8AB7_0050DACD1682__INCLUDED_
)

**************************************************************************************
*

Intersections.cpp

**************************************************************************************
// Intersections.cpp : implementation file
//
#include "stdafx.h"
#include "TrafDef.h"
#include "Intersections.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
int ndir, ndir1, ndir2, nr_dir, nl_dir, nop_dir;
/////////////////////////////////////////////////////////////////////////////
// CIntersections

82

IMPLEMENT_DYNCREATE(CIntersections, CDocument)
CIntersections::CIntersections()
{
// initial the simulation clock for this intersection
clock = 0.;
dir1=NB;
dir2=EB;
}
CIntersections::CIntersections(Intersection *I_loc)
{
I = I_loc;
for (int i=0;i<4;i++)
{
in_B[i] = new CRoadSectors(I->IN_B[i]);
if(I->IN_B[i] != NULL)I->IN_B[i]->CR = POSITION(in_B[i]);
}
offset_cycle_time = !((I->ID = 1) | (I->ID = 2) | (I->ID = 3) |(I->ID = 4) |(I->ID = 5) | (I->ID = 6));
clock = 0.;
}
CIntersections::~CIntersections()
{
for (int i=0; i<4; i++)
{
if (in_B[i] != NULL)delete in_B[i];
}
}

BEGIN_MESSAGE_MAP(CIntersections, CDocument)
//{{AFX_MSG_MAP(CIntersections)
// NOTE - the ClassWizard will add and remove mapping macros here.
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CIntersections diagnostics
#ifdef _DEBUG

83

void CIntersections::AssertValid() const


{
CDocument::AssertValid();
}
void CIntersections::Dump(CDumpContext& dc) const
{
CDocument::Dump(dc);
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CIntersections serialization
void CIntersections::Serialize(CArchive& ar)
{
if (ar.IsStoring())
{
// TODO: add storing code here
}
else
{
// TODO: add loading code here
}
}
/////////////////////////////////////////////////////////////////////////////
// CIntersections commands
void CIntersections::SimulateTraffic(double t,CFile *Lcount)
{
double simulation_time,time_remain;
char dir, r_dir;
time_remain=t-clock;
// Figuring the phases and time of the phase for giving time period
// then move traffic according the red/yellow/green phase of the intersection
while (time_remain>0.)
{

// setup time for moving traffic


simulation_time =
st.split[current_seq] - time_to_change;

84

simulation_time = (time_remain < simulation_time)


? time_remain: simulation_time;
if(simulation_time>.0)
{
phase1=I->PHASE[current_seq][0]-1;
phase2=I->PHASE[current_seq][1]-1;
dir = I->MG_preset[phase1]->bound;
if (dir == NB) ndir = 0;
if (dir == WB) ndir = 1;
if (dir == SB) ndir = 2;
if (dir == EB) ndir = 3;
nop_dir = (ndir+2)%4;
nl_dir = (ndir+1)%4;
if(dir == NB) r_dir = EB;
else nr_dir = ndir -1;
//
/*

move current phase traffic first

if (l_dir == NB) nl_dir = 0;


if (l_dir == WB) nl_dir = 1;
if (l_dir == SB) nl_dir = 2;
if (l_dir == EB) nl_dir = 3;
if (r_dir == NB) nr_dir = 0;
if (r_dir == WB) nr_dir = 1;
if (r_dir == SB) nr_dir = 2;
if (r_dir == EB) nr_dir = 3;

*/
in_B[ndir]->MoveTrafficOnGreen(
*out_B[ndir], *out_B[nr_dir], *out_B[nl_dir],simulation_time);
if (phase2 >= 0)
{
if (I->MG_preset[phase2]->bound != dir && in_B[nop_dir] != NULL)
{
// move opposit phase traffic
if (in_B[nop_dir]->IsGreenLight())in_B[nop_dir]->MoveTrafficOnGreen(
*out_B[nop_dir], *out_B[nl_dir], *out_B[nr_dir],simulation_time);
else in_B[nop_dir]->MoveTrafficOnRed(*out_B[nl_dir], *out_B[nr_dir],
simulation_time);
}

85

}
else
{
if (in_B[nop_dir] !=NULL)
in_B[nop_dir]->MoveTrafficOnRed(*out_B[nl_dir], *out_B[nr_dir],
simulation_time);
}

//

move west bound traffic

if(in_B[nr_dir] != NULL)in_B[nr_dir]->
MoveTrafficOnRed(*out_B[nop_dir],*out_B[ndir],simulation_time);
//

move east bound traffic (east bound road sector maybe void

if(in_B[nl_dir] != NULL)in_B[nl_dir]->
MoveTrafficOnRed(*out_B[ndir],*out_B[nop_dir],simulation_time);
}
time_remain-=simulation_time;
if (time_remain >0.)
{
current_seq++;
current_seq %= I->SEQ;
SetSignalPhase();
time_to_change = .0;
}
else time_to_change += simulation_time;
};
// set this intersection clock to match the simulation time
clock = t;
}
void CIntersections::SetSignalPhase()
{
LightPhase old_phase[4];
for (int i=0; i<4; i++)
{
if (in_B[i] !=NULL)
{
old_phase[i] = in_B[i]->light;
in_B[i]->light=red;

86

in_B[i]->LTLight=red;
}
}
if (dir1 == NB) ndir1 = 0;
if (dir1 == WB) ndir1 = 1;
if (dir1 == SB) ndir1 = 2;
if (dir1 == EB) ndir1 = 3;
if (dir2 == NB) ndir2 = 0;
if (dir2 == WB) ndir2 = 1;
if (dir2 == SB) ndir2 = 2;
if (dir2 == EB) ndir2 = 3;
if( phase2>=0)
{
if (I->MG_preset[phase1]->turns==LT)
{
in_B[ndir1]->light=red;
in_B[ndir1]->LTLight=green;
in_B[ndir2]->light=red;
in_B[ndir2]->LTLight=green;
}
else
{
in_B[ndir1]->light=green;
in_B[ndir1]->LTLight=flash;
in_B[ndir2]->light=green;
in_B[ndir2]->LTLight=flash;
}
}
else
{
in_B[ndir1]->light=green;
in_B[ndir1]->LTLight=green;
}
//

reset queue length when light switch from green to allow repositioning vehicle

//

in queue
for (i=0; i<4; i++)
{
if (in_B[i] !=NULL)

87

{
if(old_phase[i] == green && in_B[i]->light== green)
in_B[i]->ReSetRoomOnRoadSector();
}
}
}
void CIntersections::SetTimeToChange()
{
if(offset_cycle_time)
{
int k=st.prog_ratio;
for (int j=0;j<current_seq+1; j++) k+=st.split[j];
time_to_change = double (k - st.split[current_seq]);
}
else time_to_change = 0.;
}
void CIntersections::Locate(RoadSector *Out_B[])
{
out_B[0]=NULL;
out_B[1]=NULL;
out_B[2]=NULL;
out_B[3]=NULL;
if(Out_B[0] != NULL) out_B[0] = (CRoadSectors*) Out_B[0]->CR;
if(Out_B[1] != NULL) out_B[1] = (CRoadSectors*) Out_B[1]->CR;
if(Out_B[2] != NULL) out_B[2] = (CRoadSectors*) Out_B[2]->CR;
if(Out_B[3] != NULL) out_B[3] = (CRoadSectors*) Out_B[3]->CR;
}

void CIntersections::TurnPhaseon(CRoadSectors *R)


{
if(R == NULL) return;
switch (R->light)
{
case red:
R->light = green;

88

R->ResetDepletionTime();
break;
case green:
R->light = yellow;
break;
case yellow:
R->light = red;
break;
}
}
void CIntersections::TurnLeftPhaseon(CRoadSectors *R)
{
if(R==NULL) return;
switch (R->LTLight)
{
case red:
R->LTLight=green;
break;
case green:
R->LTLight = yellow;
break;
case yellow:
R->LTLight = red;
}
}

**************************************************************************************
*

MainFrm.h

**************************************************************************************
// MainFrm.h : interface of the CMainFrame class
//
/////////////////////////////////////////////////////////////////////////////
#if !defined(AFX_MAINFRM_H__6D3D0619_C6EE_11D4_8AA4_0050DACD1682__INCLUDED_)
#define AFX_MAINFRM_H__6D3D0619_C6EE_11D4_8AA4_0050DACD1682__INCLUDED_
#if _MSC_VER > 1000
#pragma once

89

#endif // _MSC_VER > 1000


class CMainFrame : public CMDIFrameWnd
{
DECLARE_DYNAMIC(CMainFrame)
public:
CMainFrame();
// Attributes
public:
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CMainFrame)
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CMainFrame();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected: // control bar embedded members
CStatusBar m_wndStatusBar;
CToolBar

m_wndToolBar;

// Generated message map functions


protected:
//{{AFX_MSG(CMainFrame)
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////

90

//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif //
!defined(AFX_MAINFRM_H__6D3D0619_C6EE_11D4_8AA4_0050DACD1682__INCLUDED_)

**************************************************************************************
*

MainFrm.cpp

**************************************************************************************
// MainFrm.cpp : implementation of the CMainFrame class
//
#include "stdafx.h"
#include "TrafDef.h"
#include "MainFrm.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CMainFrame
IMPLEMENT_DYNAMIC(CMainFrame, CMDIFrameWnd)
BEGIN_MESSAGE_MAP(CMainFrame, CMDIFrameWnd)
//{{AFX_MSG_MAP(CMainFrame)
ON_WM_CREATE()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
static UINT indicators[] =
{
ID_SEPARATOR,

// status line indicator

91

ID_INDICATOR_CAPS,
ID_INDICATOR_NUM,
ID_INDICATOR_SCRL,
};
/////////////////////////////////////////////////////////////////////////////
// CMainFrame construction/destruction
CMainFrame::CMainFrame()
{
// TODO: add member initialization code here
}
CMainFrame::~CMainFrame()
{
}
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CMDIFrameWnd::OnCreate(lpCreateStruct) == -1)
return -1;
if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP
| CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) ||
!m_wndToolBar.LoadToolBar(IDR_MAINFRAME))
{
TRACE0("Failed to create toolbar\n");
return -1;

// fail to create

}
if (!m_wndStatusBar.Create(this) ||
!m_wndStatusBar.SetIndicators(indicators,
sizeof(indicators)/sizeof(UINT)))
{
TRACE0("Failed to create status bar\n");
return -1;

// fail to create

}
// TODO: Delete these three lines if you don't want the toolbar to
//

be dockable

92

m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY);
EnableDocking(CBRS_ALIGN_ANY);
DockControlBar(&m_wndToolBar);
return 0;
}
BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
if( !CMDIFrameWnd::PreCreateWindow(cs) )
return FALSE;
// TODO: Modify the Window class or styles here by modifying
//

the CREATESTRUCT cs

return TRUE;
}
/////////////////////////////////////////////////////////////////////////////
// CMainFrame diagnostics
#ifdef _DEBUG
void CMainFrame::AssertValid() const
{
CMDIFrameWnd::AssertValid();
}
void CMainFrame::Dump(CDumpContext& dc) const
{
CMDIFrameWnd::Dump(dc);
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CMainFrame message handlers

93

**************************************************************************************
*

NN.h

**************************************************************************************
#if !defined(AFX_NN_H__6F47A681_C78C_11D4_8AA5_0050DACD1682__INCLUDED_)
#define AFX_NN_H__6F47A681_C78C_11D4_8AA5_0050DACD1682__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// NN.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CNN document
struct NN {int in; int out; int lv1; int lv2;BOOL b1; BOOL b2; BOOL bo;};
class CNN : public CDocument
{
public:
CNN();

// protected constructor used by dynamic creation

CNN(NN &nn);
DECLARE_DYNCREATE(CNN)
// Attributes
public:
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CNN)
public:
virtual void Serialize(CArchive& ar);

// overridden for document i/o

protected:
virtual BOOL OnNewDocument();
//}}AFX_VIRTUAL
// Implementation
public:
void Interp();
int n_In;

94

int n_Out;
void load(CNN & net_d);
void PerturbP(CNN &net, CNN & net_d);
void PerturbN(CNN &net, CNN & net_d);
double half_RAND_MAX ;
void rnbl(double * A, int n, double c);
void BlDelta(double c);
inline double SQUASH(double);
void mamb(double* c, double* a, double* b, int l, int m, int n);
void mapb(double* c, double* a, double* b, int p);
void Mapping(double *In, double *Out);
virtual ~CNN();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
// Generated message map functions
protected:
//{{AFX_MSG(CNN)
// NOTE - the ClassWizard will add and remove member functions here.
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
private:
BOOL b1;
BOOL b2;
BOOL bo;
int n_h1;
int n_h2;
int n_w1;
int n_w2;
int n_w3;
double *wb1;

/* First Hidden Layer Bias Weights */

double *wb2;

/* Second Hidden Layer Bias Weights */

double *wb3;
double *w1;

/* Input-First Hidden Layer Weights */

double *w2;

/* First-Second Hidden Layer Weights */

double *w3; /* Second Hidden Layer-Output Weights */

95

};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_NN_H__6F47A681_C78C_11D4_8AA5_0050DACD1682__INCLUDED_)

**************************************************************************************
*

NN.cpp

**************************************************************************************
// NN.cpp : implementation file
//
#include "stdafx.h"
#include "TrafDef.h"
#include "NN.h"
#include "math.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CNN
IMPLEMENT_DYNCREATE(CNN, CDocument)
CNN::CNN()
{
half_RAND_MAX = double (RAND_MAX) /2.0f +1.0f;
}
CNN::CNN(NN& nn)
{
register i;
half_RAND_MAX = double (RAND_MAX) /2.0f +1.0f;
b1 = nn.b1;

96

b2 = nn.b2;
bo = nn.bo;
n_In = nn.in;
n_Out = nn.out;
n_h1 = nn.lv1;
n_h2 = nn.lv2;
n_w1 = n_In * n_h1;
n_w2 = n_h1 * n_h2;
n_w3 = n_h2 * n_Out;
w1 = new double[n_w1];
w2 = new double[n_w2];
w3 = new double[n_w3];
wb1 = new double[n_h1];
wb2 = new double[n_h2];
wb3 = new double[n_Out];
for (i=0;i < n_h1; i++) wb1[i] = 0.;
for (i=0;i < n_h2; i++) wb2[i] = 0.;
for (i=0;i < n_Out; i++) wb3[i]=0.;
for (i=0;i<n_w1; i++) w1[i] = 0.;
for (i=0;i<n_w2; i++) w2[i] = 0.;
for (i=0;i<n_w3; i++) w3[i] =0;
}
BOOL CNN::OnNewDocument()
{
if (!CDocument::OnNewDocument())
return FALSE;
return TRUE;
}
CNN::~CNN()
{
delete w1;
delete w2;
delete w3;
delete wb1;
delete wb2;
delete wb3;
}

97

BEGIN_MESSAGE_MAP(CNN, CDocument)
//{{AFX_MSG_MAP(CNN)
// NOTE - the ClassWizard will add and remove mapping macros here.
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CNN diagnostics
#ifdef _DEBUG
void CNN::AssertValid() const
{
CDocument::AssertValid();
}
void CNN::Dump(CDumpContext& dc) const
{
CDocument::Dump(dc);
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CNN serialization
void CNN::Serialize(CArchive& ar)
{
if (ar.IsStoring())
{
// TODO: add storing code here
}
else
{
// TODO: add loading code here
}
}
/////////////////////////////////////////////////////////////////////////////
// CNN commands

98

void CNN::Mapping(double *In, double *Out)


{
int ii, one = 1;
double *layer1 = new double[n_h1];
double *layer2 = new double[n_h2];
/* compute input to hidden layer */
mamb (layer1, In, w1, 1, n_In, n_h1);
/* compute output of hidden layer */
mapb (layer1,layer1, wb1, n_h1);
for( ii=0; ii< n_h1; ii++ ) layer1[ii] = SQUASH( layer1[ii] );
/* compute hidden to 2nd hidden layer */
mamb (layer2, layer1, w2, 1, n_h1, n_h2);

/* compute output of 2nd hidden layer */

mapb (layer2, layer2, wb2, n_h2);


for( ii=0; ii< n_h2; ii++ ) layer2[ii] = SQUASH( layer2[ii] );
/* compute input to output layer */
mamb (Out, layer2, w3, one, n_h2, n_Out);
/* compute output of output layer */
for( ii=0; ii<n_Out; ii++ ) Out[ii] = SQUASH( Out[ii] )-.5f;
mapb (Out, Out, wb3, n_Out);
for (ii=0; ii<n_Out; ii++)
{
if(Out[ii]<0.0f) Out[ii]+=1.0f;
if(Out[ii]>1.0f) Out[ii]-=1.0f;
}
delete layer1;
delete layer2;
}

99

void CNN::mamb(double *c, double *a, double* b, int l, int m, int n)


{
int i, j, k, i_j, i_a, i_a_1, j_b;
double sum;
i_j=0;
for (i=0, i_a=0; i < l; i++)
{
i_a_1 = i_a;
for (j = 0; j<n; j++)
{
i_a = i_a_1;
j_b = j;
sum = 0.f;
for (k=0; k<m; k++)
{
sum += a[i_a++] * b[j_b];
j_b += n;
}
c[i_j++] = sum;
}
}
}

void CNN::mapb(double* c, double* a, double* b, int p)


{
for (int i=0; i < p; i++) c[i] = a[i] + b[i];
}
inline double CNN::SQUASH(double arg)
{
return(1./(1.+exp(-arg)));
}
void CNN::BlDelta(double c)
{
rnbl(wb1,n_h1,c);
rnbl(wb2,n_h2,c);
rnbl(wb3,n_Out,c);

100

rnbl(w1, n_w1, c);


rnbl(w2, n_w2, c);
rnbl(w3, n_w3, c);
}
void CNN::rnbl(double *A, int p, double c)
{
for (int i=0; i < p; i++)
A[i]= rand()<half_RAND_MAX ? -c: c;
}
void CNN::PerturbN(CNN & net,CNN &net_d)
{
register i;
if(b1) for (i=0; i<n_h1; i++) wb1[i] = net.wb1[i] - net_d.wb1[i];
if(b2) for (i=0; i<n_h2; i++) wb2[i] = net.wb2[i] - net_d.wb2[i];
if(bo) for (i=0; i<n_Out;i++) wb3[i] = net.wb3[i] - net_d.wb3[i];
for (i=0; i<n_w1; i++) w1[i] = net.w1[i] - net_d.w1[i];
for (i=0; i<n_w2; i++) w2[i] = net.w2[i] - net_d.w2[i];
for (i=0; i<n_w3; i++) w3[i] = net.w3[i] - net_d.w3[i];
}
void CNN::PerturbP(CNN &net,CNN &net_d)
{
register i;
if(b1) for (i=0; i<n_h1; i++) wb1[i] = net.wb1[i] + net_d.wb1[i];
if(b2) for (i=0; i<n_h2; i++) wb2[i] = net.wb2[i] + net_d.wb2[i];
if(bo) for (i=0; i<n_Out;i++) wb3[i] = net.wb3[i] + net_d.wb3[i];
for (i=0; i<n_w1; i++) w1[i] = net.w1[i]+ net_d.w1[i];
for (i=0; i<n_w2; i++) w2[i] = net.w2[i]+ net_d.w2[i];
for (i=0; i<n_w3; i++) w3[i] = net.w3[i]+ net_d.w3[i];
}
void CNN::load(CNN& net_d)
{
register i;
if(b1) for (i=0; i<n_h1;i++) wb1[i] = net_d.wb1[i];
if(b2) for (i=0; i<n_h2;i++) wb2[i] = net_d.wb2[i];
if(bo) for (i=0; i<n_Out;

i++) wb3[i] = net_d.wb3[i];

for (i=0; i<n_w1; i++) w1[i] = net_d.w1[i];

101

for (i=0; i<n_w2; i++) w2[i] = net_d.w2[i];


for (i=0; i<n_w3; i++) w3[i] = net_d.w3[i];
}
void CNN::Interp()
{
}

**************************************************************************************
*

resource.h

**************************************************************************************
//{{NO_DEPENDENCIES}}
// Microsoft Developer Studio generated include file.
// Used by TrafDef.rc
//
#define IDD_ABOUTBOX

100

#define IDD_TRAFDEF_FORM

101

#define IDR_MAINFRAME

128

#define IDR_TRAFDETYPE

129

#define IDD_SPSA_CONSTANTS
#define IDC_FINAL_RESULTS

130
1000

#define IDC_GAIN_A

1001

#define IDC_ALPHA

1002

#define IDC_GAIN_C

1003

#define IDC_GAMMA
#define IDC_SEED

1004
1005

#define IDC_GAIN_BASE

1006

#define IDC_GAIN_A_IN

1008

#define IDC_ALPHA_IN

1009

#define IDC_GAIN_C_IN

1010

#define IDC_GAMMA_IN

1011

#define IDC_BASE_IN

1012

#define IDC_SEED_IN

1013

#define IDC_HIDEN_L1

1014

#define IDC_HIDEN_L2

1015

#define IDC_NN_HID1

1020

102

#define IDC_NN_HID2

1021

#define IDC_NN_BIAS_L1

1025

#define IDC_NN_L2_BIAS

1026

#define IDC_OUTPUT_BIASE

1027

#define IDC_NN_L1_BIAS

1031

#define IDC_INPUT

1032

#define IDC_OUTPUT

1033

#define IDC_ITERATION

1034

#define IDC_SIGNAL_T

1036

#define IDC_TIMING_SPIN

1037

#define IDC_INTERSEC_ID

1038

#define IDC_ID_SPIN

1039

#define ID_RUN_EXEC

32772

#define ID_RUN_DAILY

32773

// Next default values for new objects


//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_3D_CONTROLS
#define _APS_NEXT_RESOURCE_VALUE
#define _APS_NEXT_COMMAND_VALUE

1
131
32774

#define _APS_NEXT_CONTROL_VALUE

1040

#define _APS_NEXT_SYMED_VALUE

101

#endif
#endif

**************************************************************************************
*

RoadNet.h

**************************************************************************************
#if !defined(AFX_ROADNET_H__D7907E91_CB8D_11D4_8AA8_0050DACD1682__INCLUDED_)
#define AFX_ROADNET_H__D7907E91_CB8D_11D4_8AA8_0050DACD1682__INCLUDED_
#include "Intersections.h" // Added by ClassView
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// RoadNet.h : header file
//
#include <fstream.h>

103

#include "RoadSectors.h"
#include "NN.h"

// Added by ClassView

/////////////////////////////////////////////////////////////////////////////
// CRoadNet document
class CRoadNet : public CObject
{
struct NNInput
{
double in[14];
// neural network input which are
//

2 loop counts (a minate apart) at each sensor (number of sensors is

//

different at each inter-section, a total of 28 sensors are used)

double out[6];
// previousely estimated light setting from the output of neural-net
//

timing splits

//

1 - 3 north_south and east_west split at int.

//

4 - 10 prograsive factors at all other intersections

double time_of_day; //

40, 108, and 150

time in hour relative from control starting time

} in;
double cycle_time_in_hour;
public:
CRoadNet();

// protected constructor used by dynamic creation

virtual ~CRoadNet();
// Attributes
int DATA_RATE;
int n_intersections;
CNN *RoadNN;
int m_seq[6];
CIntersections *sI[6];
CRoadSectors *Sysin[15];
public:
// Operations

// Implementation

104

public:
void TrafFlow();
void InitPhaseTime();
void SetupNNInput(double *In);
void Interp(double *Timings);
void CycleTraf(CFile *Lcount);
void AddSystemInput();
void PlaceCars(RoadSector*);
void SetPriority(int* seq_green);
void SetupPhases();
private:
CFile *Lcount;
int cycle;
double GetArrivalRate(int iroad);
};
//int babala;struct Date
#endif //
!defined(AFX_ROADNET_H__D7907E91_CB8D_11D4_8AA8_0050DACD1682__INCLUDED_)

**************************************************************************************
*

RoadNet.cpp

**************************************************************************************
// RoadNet.cpp : implementation file
//
#include <fstream.h>
#include "stdafx.h"
#include <iostream.h>
#include "TrafDef.h"
#include "RoadNet.h"
#include "intersection.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;

105

#endif
/////////////////////////////////////////////////////////////////////////////
// CRoadNet
CRoadNet::CRoadNet()
{
DATA_RATE = 4;
n_intersections = 6;
Intersection *DECC[]={&L1, &L2, &L3, &L4, &L5, &L6, NULL};
for (int i=0; i<n_intersections; i++)
{
sI[i] = new CIntersections(DECC[i]);
}
sI[6]=NULL;
for (i=0; i<n_intersections; i++)
{
sI[i]->Locate(DECC[i]->OUT_B);
}
// Setup array of section roads for system input
// L1
Sysin[0] = sI[0]->in_B[NB];
Sysin[1] = sI[0]->in_B[EB];
// L2
Sysin[2] = sI[1]->in_B[WB];
// L3
Sysin[3] = sI[2]->in_B[WB];
Sysin[4] = sI[2]->in_B[SB];
Sysin[5] = sI[2]->in_B[EB];
// L4
Sysin[6] = sI[3]->in_B[NB];
Sysin[7] = sI[3]->in_B[SB];
Sysin[8] = sI[3]->in_B[EB];
// L5
Sysin[9] = sI[4]->in_B[NB];
Sysin[10] = sI[4]->in_B[WB];

106

// L6
Sysin[11] = sI[5]->in_B[WB];
Sysin[12] = sI[5]->in_B[SB];
Sysin[13] = sI[5]->in_B[EB];
Sysin[14] = NULL;
cycle_time_in_hour = 1/45;
}
CRoadNet::~CRoadNet()
{
for(int i=0; i<6; i++) delete sI[i];
}

/////////////////////////////////////////////////////////////////////////////
// CRoadNet diagnostics

/////////////////////////////////////////////////////////////////////////////
// CRoadNet serialization

/////////////////////////////////////////////////////////////////////////////
// CRoadNet commands
void CRoadNet::AddSystemInput()
{
int i;
i=0;
while (Sysin[i] != NULL)
{ // cars are introduced from entering the system from input node
// defined in SysIn
//

SysIn[i]->cars_on_road = Poisson(arrival_rates[i]);
Sysin[i]->AddCarArrival(Poisson(GetArrivalRate(i)));
i++;

};
}
/////////////////////////////////////////////////////////////////////////
void CRoadNet::SetupPhases()

107

{
// set up time-of-change at each signal
// signal phases are switched to green at major input nodes and red at everywhere else
// at begining of cycle. The progasive ratio is defined as percentage of cycle-time
// starting at the major intersections
// Starting from 2nd intersection
int i=1;
while (sI[i] != NULL)
{
//skip intersection 4, 6, and 8, which for estimating split only
// no change on 7 all the time
sI[i++]->SetTimeToChange();
};
}
void CRoadNet::SetPriority(int *seq_green)
{
// move Rockville Pike intersections traffic before Old Geogetown intersections
//

on green phase or revers order for red phase

int *seq_red;
seq_red = seq_green+5;
// set sequence for Rockville Pike intersections
for (int i=2; i>=0; i--)
{
if (sI[i]->in_B[NB]->IsGreenLight()) *(seq_green++)=i;
else *(seq_red--)=i;
}
// set sequence for Old Georgetown intersections
for (i=3; i<6; i++)
{
if (sI[i]->in_B[NB]->IsGreenLight()) *(seq_green++)=i;
else *(seq_red--)=i;
}
}
void CRoadNet::TrafFlow()
{

108

// starting simulation one cycle before control for developping traffic pattern
InitPhaseTime();
for (cycle=0; cycle < 48; cycle++)
{
CycleTraf(Lcount);
in.time_of_day += cycle_time_in_hour;
SetupNNInput(in.in);
// computes next set of timing splits
RoadNN->Mapping(in.in,in.out);
//

reset timing for next cycle


Interp(in.out);

}
}
//////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
void CRoadNet::CycleTraf(CFile *Lcount)
{
int i,m_s;
double time_in_cycle = 0.;
SetupPhases();
for (i=0; i<10;i++)

// simulate traffic at 1 tenth of cycle

{
// reset sequence for car-movements
SetPriority(m_seq);
for (int j=0; j<n_intersections;j++)
{
m_s = m_seq[j];
sI[m_s]->SimulateTraffic(time_in_cycle,Lcount);
}
// number of car arrived during the time period
AddSystemInput();
//

PlaceArrivedCars();
time_in_cycle+=CYL;
// output loop counts at specification frequency

109

}
}
void CRoadNet::Interp(double *Timings)
{
int fraction_of_ns,fraction_of_ew;
int diff;
float ratio;
//

L1 NS-EW split

fraction_of_ns =int(Timings[0]*100.0f+.4);
fraction_of_ew=100 - fraction_of_ns;
sI[0]->st.split[0] = (int)(double(fraction_of_ns)*.67);
sI[0]->st.split[1] = fraction_of_ns-sI[0]->st.split[0];
sI[0]->st.split[2] = fraction_of_ew;
//

ofstream tfile( "output.dat" , ios::binary );

//

tfile.write( (int *) &sI[0]->st.split[0], sizeof sI[0]->st.split[0] );

//

char a='10';

//

ofstream tfile( "output.dat", ios::binary

//

tfile.write( (char *)&a, sizeof a );

//

tfile.write( (char *)&a, sizeof a );

/*

ofstream ofile();

);

ofile.open( "output.dat", ios::in );


// Do some output
cout.put << sI[0]->st.split[0];
ofile.close(); // FILE1 closed*/
if (sI[0]->st.split[2] < 30)
{
diff = 30 - sI[0]->st.split[2];
ratio = sI[0]->st.split[0] / ( sI[0]->st.split[0] + sI[0]->st.split[1] );
sI[0]->st.split[2] = 30;
sI[0]->st.split[0] -= diff * ratio;
sI[0]->st.split[1] -= diff * ( 1 - ratio );
if (sI[0]->st.split[1] < 16)
{
sI[0]->st.split[0] -= 16 - sI[0]->st.split[1];
sI[0]->st.split[1] = 16;
}

110

}
// L2 NS-EW split
fraction_of_ns =int(Timings[1]*100.0f+.4);
fraction_of_ew=100 - fraction_of_ns;
sI[1]->st.split[0] = fraction_of_ew;
sI[1]->st.split[1] = (int)(double(fraction_of_ns)*0.67);
sI[1]->st.split[2] = fraction_of_ns-sI[1]->st.split[1];
if (sI[1]->st.split[0] < 26)
{
diff = 26 - sI[1]->st.split[0];
ratio = sI[1]->st.split[1] / ( sI[1]->st.split[1] + sI[1]->st.split[2] );
sI[1]->st.split[0] = 26;
sI[1]->st.split[1] -= diff * ratio;
sI[1]->st.split[2] -= diff * ( 1 - ratio );
if (sI[1]->st.split[2] < 25)
{
sI[1]->st.split[1] -= 25 - sI[1]->st.split[2];
sI[1]->st.split[2] = 25;
}
}
//

L3 NS-EW split

fraction_of_ns = int(Timings[2]*100.0f+.4);
fraction_of_ew=100 - fraction_of_ns;
sI[2]->st.split[0] =(int) (double(fraction_of_ew)*.25);
sI[2]->st.split[1] = (int) (double(fraction_of_ew)*.75);
sI[2]->st.split[2] =fraction_of_ns;
if (sI[2]->st.split[2] < 13)
{
diff = 13 - sI[2]->st.split[2];
ratio = sI[2]->st.split[0] / ( sI[2]->st.split[0] + sI[2]->st.split[1] );
sI[2]->st.split[2] = 13;
sI[2]->st.split[0] -= diff * ratio;
sI[2]->st.split[1] -= diff * ( 1 - ratio );
}
/*

sI[2]->st.split[3] = sI[2]->st.split[0];
sI[2]->st.split[4] = sI[2]->st.split[1];

111

if (sI[2]->st.split[2] < 13)


{
diff = 100 - 13 - sI[2]->st.split[0] - sI[2]->st.split[1];
ratio = sI[2]->st.split[0] * 1000000 / ( sI[2]->st.split[0] + sI[2]->st.split[1] );
sI[2]->st.split[0] += diff * ratio / 1000000;
sI[2]->st.split[0] = sI[2]->st.split[0] * 87 / (sI[2]->st.split[0] + sI[2]->st.split[1]);
ratio = sI[2]->st.split[1] * 1000000 / ( sI[2]->st.split[0] + sI[2]->st.split[1] );
sI[2]->st.split[1] += diff * ratio / 1000000;
sI[2]->st.split[1] = sI[2]->st.split[1] * 87 / (sI[2]->st.split[0] + sI[2]->st.split[1]);
ratio = sI[2]->st.split[3] * 1000000 / ( sI[2]->st.split[3] + sI[2]->st.split[4] );
sI[2]->st.split[3] += diff * ratio / 1000000;
sI[2]->st.split[3] = sI[2]->st.split[3] * 87 / (sI[2]->st.split[3] + sI[2]->st.split[4]);
ratio = sI[2]->st.split[4] * 1000000 / ( sI[2]->st.split[3] + sI[2]->st.split[4] );
sI[2]->st.split[4] += diff * ratio / 1000000;
sI[2]->st.split[4] = sI[2]->st.split[4] * 87 / (sI[2]->st.split[3] + sI[2]->st.split[4]);
sI[2]->st.split[2] = 13;
}*/
//

L4 NS-EW split

fraction_of_ns = int(Timings[3]*100.0f+.4);
fraction_of_ew=100 - fraction_of_ns;
sI[3]->st.split[0] =(int) (double(fraction_of_ew)*.83);
sI[3]->st.split[1] = fraction_of_ns;
sI[3]->st.split[2] = fraction_of_ew - sI[3]->st.split[0];
if ((sI[3]->st.split[1] < 19) && (sI[3]->st.split[2] < 19))
{
diff = 38 - sI[3]->st.split[1] - sI[3]->st.split[2] - sI[3]->st.split[3];
sI[3]->st.split[1] = 19;
sI[3]->st.split[2] = 19;
sI[3]->st.split[0] -= diff;
}
//

L5 NS-EW split

fraction_of_ns = int(Timings[4]*100.0f+.4);
fraction_of_ew=100 - fraction_of_ns;
sI[4]->st.split[0]=(int)(double(fraction_of_ns)*.32);
sI[4]->st.split[1]=fraction_of_ns - sI[4]->st.split[0];
sI[4]->st.split[2]=(int)(double(fraction_of_ew)*.62);
sI[4]->st.split[3]=fraction_of_ew - sI[4]->st.split[2];

112

if ((sI[4]->st.split[0] < 16) && (sI[4]->st.split[1] < 22) )


{
diff = 38 - sI[4]->st.split[0] - sI[4]->st.split[1];
ratio = sI[4]->st.split[2] / ( sI[4]->st.split[2] + sI[4]->st.split[3] );
sI[4]->st.split[0] = 16;
sI[4]->st.split[1] = 22;
sI[4]->st.split[2] -= diff * ratio;
sI[4]->st.split[3] -= diff * ( 1 - ratio );
//

sI[4]->st.split[2] = 100 - sI[4]->st.split[0] - sI[4]->st.split[1] - sI[4]->st.split[3];


if (sI[4]->st.split[3] < 19)
{
sI[4]->st.split[3] = 19;
sI[4]->st.split[2] = 100 - sI[4]->st.split[0] - sI[4]->st.split[1] - sI[4]->st.split[3];
}
}
//

L6 NS-EW split

fraction_of_ns = int(Timings[5]*100.0f+.4);
fraction_of_ew=100 - fraction_of_ns;
sI[5]->st.split[0] =(int) (double(fraction_of_ns)*.28);
sI[5]->st.split[1] = (int) (double(fraction_of_ns)*.72);
sI[5]->st.split[2] = fraction_of_ew;
if (sI[5]->st.split[2] < 19)
{
diff = 19 - sI[5]->st.split[2];
ratio = sI[5]->st.split[0] / ( sI[5]->st.split[0] + sI[5]->st.split[1] );
sI[5]->st.split[2] = 19;
sI[5]->st.split[0] -= diff * ratio;
sI[5]->st.split[1] -= diff * ( 1 - ratio );
}
ofstream os("output.dat");
os.put('5');
os.put('t');
os.put('h');
os.put('A');
os.put('v');
os.put('e');
os.put(' ');

113

os.put('&');
os.put(' ');
os.put('I');
os.put('3');
os.put('5');
os.put('N');
os.put(':');
os.put(' ');
os.put(' ');
os.put(' ');
os.put(' ');
os.put(' ');
os.put((char)('0' + (sI[0]->st.split[0] - sI[0]->st.split[0] % 10)/10));
os.put((char)('0' + sI[0]->st.split[0] % 10));
os.put(' ');
os.put((char)('0' + (sI[0]->st.split[1] - sI[0]->st.split[1] % 10)/10));
os.put((char)('0' + sI[0]->st.split[1] % 10));
os.put(' ');
os.put((char)('0' + (sI[0]->st.split[2] - sI[0]->st.split[2] % 10)/10));
os.put((char)('0' + sI[0]->st.split[2] % 10));
os.put('\n');
os.put('5');
os.put('t');
os.put('h');
os.put('A');
os.put('v');
os.put('e');
os.put(' ');
os.put('&');
os.put(' ');
os.put('I');
os.put('3');
os.put('5');
os.put('S');
os.put(':');
os.put(' ');
os.put(' ');
os.put(' ');

114

os.put(' ');
os.put(' ');
os.put((char)('0' + (sI[1]->st.split[0] - sI[1]->st.split[0] % 10)/10));
os.put((char)('0' + sI[1]->st.split[0] % 10));
os.put(' ');
os.put((char)('0' + (sI[1]->st.split[1] - sI[1]->st.split[1] % 10)/10));
os.put((char)('0' + sI[1]->st.split[1] % 10));
os.put(' ');
os.put((char)('0' + (sI[1]->st.split[2] - sI[1]->st.split[2] % 10)/10));
os.put((char)('0' + sI[1]->st.split[2] % 10));
os.put('\n');
os.put('5');
os.put('t');
os.put('h');
os.put('A');
os.put('v');
os.put('e');
os.put(' ');
os.put('&');
os.put(' ');
os.put('S');
os.put('u');
os.put('p');
os.put('e');
os.put('r');
os.put('i');
os.put('o');
os.put('r');
os.put(':');
os.put(' ');
os.put((char)('0' + (sI[2]->st.split[0] - sI[2]->st.split[0] % 10)/10));
os.put((char)('0' + sI[2]->st.split[0] % 10));
os.put(' ');
os.put((char)('0' + (sI[2]->st.split[1] - sI[2]->st.split[1] % 10)/10));
os.put((char)('0' + sI[2]->st.split[1] % 10));
os.put(' ');

115

os.put((char)('0' + (sI[2]->st.split[2] - sI[2]->st.split[2] % 10)/10));


os.put((char)('0' + sI[2]->st.split[2] % 10));
os.put('\n');
os.put('\n');
os.put('R');
os.put('a');
os.put('i');
os.put('l');
os.put('r');
os.put('o');
os.put('a');
os.put('d');
os.put(' ');
os.put('&');
os.put(' ');
os.put('L');
os.put('a');
os.put('k');
os.put('e');
os.put(':');
os.put(' ');
os.put(' ');
os.put(' ');
os.put((char)('0' + (sI[3]->st.split[0] - sI[3]->st.split[0] % 10)/10));
os.put((char)('0' + sI[3]->st.split[0] % 10));
os.put(' ');
os.put((char)('0' + (sI[3]->st.split[1] - sI[3]->st.split[1] % 10)/10));
os.put((char)('0' + sI[3]->st.split[1] % 10));
os.put(' ');
os.put((char)('0' + (sI[3]->st.split[2] - sI[3]->st.split[2] % 10)/10));
os.put((char)('0' + sI[3]->st.split[2] % 10));
os.put('\n');
os.put('R');
os.put('a');
os.put('i');
os.put('l');
os.put('r');

116

os.put('o');
os.put('a');
os.put('d');
os.put(' ');
os.put('&');
os.put(' ');
os.put('C');
os.put('a');
os.put('n');
os.put('a');
os.put('l');
os.put(':');
os.put(' ');
os.put(' ');
os.put((char)('0' + (sI[4]->st.split[0] - sI[4]->st.split[0] % 10)/10));
os.put((char)('0' + sI[4]->st.split[0] % 10));
os.put(' ');
os.put((char)('0' + (sI[4]->st.split[1] - sI[4]->st.split[1] % 10)/10));
os.put((char)('0' + sI[4]->st.split[1] % 10));
os.put(' ');
os.put((char)('0' + (sI[4]->st.split[2] - sI[4]->st.split[2] % 10)/10));
os.put((char)('0' + sI[4]->st.split[2] % 10));
os.put(' ');
os.put((char)('0' + (sI[4]->st.split[3] - sI[4]->st.split[3] % 10)/10));
os.put((char)('0' + sI[4]->st.split[3] % 10));
/*

int temp;
if (sI[4]->st.split[4] > 0)
temp = sI[4]->st.split[4];
else
temp = 0 - sI[4]->st.split[4];
os.put((char)('0' + (temp - temp % 10)/10));
os.put((char)('0' + temp % 10));*/
os.put('\n');
os.put('I');
os.put('3');
os.put('5');

117

os.put(' ');
os.put('&');
os.put(' ');
os.put('C');
os.put('a');
os.put('n');
os.put('a');
os.put('l');
os.put(':');
os.put(' ');
os.put(' ');
os.put(' ');
os.put(' ');
os.put(' ');
os.put(' ');
os.put(' ');
os.put((char)('0' + (sI[5]->st.split[0] - sI[5]->st.split[0] % 10)/10));
os.put((char)('0' + sI[5]->st.split[0] % 10));
os.put(' ');
os.put((char)('0' + (sI[5]->st.split[1] - sI[5]->st.split[1] % 10)/10));
os.put((char)('0' + sI[5]->st.split[1] % 10));
os.put(' ');
os.put((char)('0' + (sI[5]->st.split[2] - sI[5]->st.split[2] % 10)/10));
os.put((char)('0' + sI[5]->st.split[2] % 10));
os.put('\n');
os.close();
/*

//

the following Timings are for offsets at secondary intersections

sI[1]->st.prog_ratio = (int)(Timings[4]*100.0); // L39


sI[2]->st.prog_ratio = (int)(Timings[5]*100.0); // L38
sI[3]->st.prog_ratio = (int)(Timings[6]*100.0); // L37
sI[5]->st.prog_ratio = (int)(Timings[7]*100.0); // L35
sI[9]->st.prog_ratio = (int)(Timings[8]*100.0); // L494
sI[10]->st.prog_ratio = (int)(Timings[9]*100.0); // L111
sI[11]->st.prog_ratio= (int)(Timings[10]*100.0); // L112
*/

118

}
void CRoadNet::SetupNNInput(double *In)
{
int k=0;
for (int i=0; i<6; i++)
{
in.in[k++]=sI[i]->in_B[NB]->cycle_count;
/*if(i==4 || i==7)
in.in[k++]=sI[i]->in_B[WB]->cycle_count;*/
in.in[k++]=sI[i]->in_B[SB]->cycle_count;
if(i==0 || i==2 || i==3 || i==5)
in.in[k++]=sI[i]->in_B[EB]->cycle_count;
}
// set loop count to 0's at sensors
for (i=0; i<6; i++)
for (int j=0; j<4; j++)
{
sI[i]->in_B[j]->ReSet();
}
}
void CRoadNet::InitPhaseTime()
{
int i,j,k;
int initial_volumes[6][4] =
{
1549, 0,

48, 215, // L1

980,

190, 86, 0,

274,

199, 42, 143, // L3

313,

196, 8,

505,

30,

1655, 97,

// L2

1342, // L4

340, 1356, // L5
493, 125,

// L6

};
SignalTiming st[6] =
{
{0, 50, 25, 25, 0, 0}, {0, 25, 50, 25, 0, 0},
{0, 15, 45, 40, 0, 0}, {0, 50, 40, 10, 0, 0},
{0, 15, 32, 33, 20, 0}, {0, 20, 50, 30, 0, 0},
};

119

char seq;
//

data_i=0; // initial data output count, one count is 15 sec.


//

initial timings as current Montgomery traffic signal timings

for (i=0; i<6; i++)


{
sI[i]->st.prog_ratio=st[i].prog_ratio;
for (j=0; j<5;j++) sI[i]->st.split[j] = st[i].split[j];
}
i=0;
sI[6] = NULL;
while (sI[i] != NULL)
{
seq=-1;
k=sI[i]->st.prog_ratio;
while (k<100 && seq<5)
{
seq++;
k+=sI[i]->st.split[seq];
};
sI[i]->current_seq = seq;
sI[i]->SetTimeToChange();
// set all phases to red
for (j=0; j<4; j++)
{
if (sI[i]->in_B[j]!=NULL)
if(sI[i]->in_B[j]->Rd != NULL)
sI[i]->in_B[j]->InitialRoad(initial_volumes[i][j]);
}
sI[i]->phase1=sI[i]->I->PHASE[seq][0]-1;
sI[i]->phase2=sI[i]->I->PHASE[seq][1]-1;
sI[i]->SetSignalPhase();
i++;
};
for ( i=0; i<14; i++) in.in[i]=.0f;
in.time_of_day=0.;

// in seconds

120

}
double CRoadNet::GetArrivalRate(int irec)
{
double car_arrival_rates;
int loop_count[25][14]=
{1549, 215, 190, 199, 42, 143, 313, 8, 1342, 505,

30, 97, 493,

125,

1549, 215, 190, 199, 42, 143, 313, 8, 1342, 505,

30, 97, 493,

125,

1549, 215, 190, 199, 42, 143, 313, 8, 1342, 505,

30, 97, 493,

125,

1549, 215, 190, 199, 42, 143, 313, 8, 1342, 505,

30, 97, 493,

125,

1549, 215, 190, 199, 42, 143, 313, 8, 1342, 505,

30, 97, 493,

125,

1549, 215, 190, 199, 42, 143, 313, 8, 1342, 505,

30, 97, 493,

125,

1549, 215, 190, 199, 42, 143, 313, 8, 1342, 505,

30, 97, 493,

125,

1549, 215, 190, 199, 42, 143, 313, 8, 1342, 505,

30, 97, 493,

125,

1549, 215, 190, 199, 42, 143, 313, 8, 1342, 505,

30, 97, 493,

125,

1549, 215, 190, 199, 42, 143, 313, 8, 1342, 505,

30, 97, 493,

125,

1549, 215, 190, 199, 42, 143, 313, 8, 1342, 505,

30, 97, 493,

125,

1549, 215, 190, 199, 42, 143, 313, 8, 1342, 505,

30, 97, 493,

125,

1549, 215, 190, 199, 42, 143, 313, 8, 1342, 505,

30, 97, 493,

125,

1549, 215, 190, 199, 42, 143, 313, 8, 1342, 505,

30, 97, 493,

125,

1549, 215, 190, 199, 42, 143, 313, 8, 1342, 505,

30, 97, 493,

125,

1549, 215, 190, 199, 42, 143, 313, 8, 1342, 505,

30, 97, 493,

125,

1549, 215, 190, 199, 42, 143, 313, 8, 1342, 505,

30, 97, 493,

125,

1549, 215, 190, 199, 42, 143, 313, 8, 1342, 505,

30, 97, 493,

125,

1549, 215, 190, 199, 42, 143, 313, 8, 1342, 505,

30, 97, 493,

125,

1549, 215, 190, 199, 42, 143, 313, 8, 1342, 505,

30, 97, 493,

125,

1549, 215, 190, 199, 42, 143, 313, 8, 1342, 505,

30, 97, 493,

125,

1549, 215, 190, 199, 42, 143, 313, 8, 1342, 505,

30, 97, 493,

125,

1549, 215, 190, 199, 42, 143, 313, 8, 1342, 505,

30, 97, 493,

125,

1549, 215, 190, 199, 42, 143, 313, 8, 1342, 505,

30, 97, 493,

125,

1549, 215, 190, 199, 42, 143, 313, 8, 1342, 505,

30, 97, 493,

125,

};
car_arrival_rates = float(loop_count[cycle/2][irec])*.05;
//if(irec == 3) car_arrival_rates *= 1.3;// adjust for left turn volumes at NB L40
//if(irec == 7) car_arrival_rates *= 1.3;// adjust for right turn volumes at NB L150
return car_arrival_rates;
}

121

**************************************************************************************
*

RoadSector.h

**************************************************************************************
// the following struct contains the information as follows
//
//

int exit_inter_sec;

//

int lanes;

//

int left_lanes;

//

int right_lanes;

//

float speed_limites; // in number of cars

//

float left_turn_rate;

//
//
//

float right_turn_rate;
float length;

// in number of cars

float queue_length; // in number of cars

//

int loop_count;

//

int cars_in_queue; // queue face north or east

//

int cars_on_road;

// north or east bound traffic

//

light_phase light;

//

light_phase LeftLight;

static RoadSector
// 5Ave & I35N
NB_5Ave_I35N

= { 1, NB,2, 0, 0, 1.76f, 20.0f, .0f,.26f},

SB_5Ave_I35N

= { 1, SB,2, 0, 0, 1.76f, 10.0f,.83f, .0f},

EB_5Ave_I35N

= { 1, EB,2, 0, 0, 1.76f,100.0f,.07f,.06f},

// 5Ave & I35S


NB_5Ave_I35S

= { 2, NB,2, 0, 0, 1.76f, 10.0f,.55f, .0f},

SB_5Ave_I35S

= { 2, SB,2, 0, 0, 1.76f, 20.0f, .0f,.23f},

WB_5Ave_I35S

= { 2, WB,2, 0, 0, 1.76f,100.0f,.09f,.04f},

//5Ave & Superior St


NB_5Ave_Superior

= { 3, NB,2, 1, 0, 1.76f, 10.0f,.18f,.31f},

SB_5Ave_Superior

= { 3, SB,1, 0, 0, 1.76f, 20.0f,.21f,.24f},

EB_5Ave_Superior

= { 3, EB,2, 1, 0, 1.76f, 40.0f,.07f,.07f},

WB_5Ave_Superior

= { 3, WB,2, 1, 0, 1.76f, 40.0f,.09f,.04f},

// Lake Ave & Railroad St


NB_Lake_Railroad

= { 4, NB,2, 0, 1, 1.76f, 40.0f,.11f,.89f},

SB_Lake_Railroad

= { 4, SB,2, 0, 0, 1.76f, 10.0f,.25f, .0f},

122

EB_Lake_Railroad

= { 4, EB,2, 0, 0, 1.76f, 60.0f, .0f,.07f},

WB_Lake_Railroad

= { 4, WB,2, 0, 0, 1.76f, 20.0f,.58f,.01f},

// Canal Park Drive & Railroad St


NB_Canal_Railroad = { 5, NB,3, 1, 0, 1.76f, 40.0f,.02f,.01f},
SB_Canal_Railroad = { 5, SB,4, 1, 1, 1.76f, 60.0f,.03f,.51f},
EB_Canal_Railroad = { 5, EB,2, 1, 0, 1.76f, 20.0f,.99f,.01f},
WB_Canal_Railroad = { 5, WB,1, 0, 0, 1.76f, 10.0f,.17f,.77f},
// Canal Park Drive & I35
NB_Canal_I35

= { 6, NB,4, 1, 1, 1.76f, 40.0f,.20f,.41f},

SB_Canal_I35

= { 6, SB,4, 1, 1, 1.76f, 30.0f,.05f,.32f},

EB_Canal_I35

= { 6, EB,2, 1, 1, 1.76f,100.0f,.60f,.40f},

WB_Canal_I35

= { 6, WB,2, 1, 1, 1.76f,100.0f,.86f,.14f};

**************************************************************************************
*

RoadSectors.h

**************************************************************************************
#if
!defined(AFX_ROADSECTORS_H__32031F20_DB44_11D4_8AB7_0050DACD1682__INCLUDED_)
#define AFX_ROADSECTORS_H__32031F20_DB44_11D4_8AB7_0050DACD1682__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// RoadSectors.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CRoadSectors document
class CRoadSectors : public CDocument
{
private:
CRoadSectors();

// protected constructor used by dynamic creation

DECLARE_DYNCREATE(CRoadSectors)
// Attributes

123

public:
CRoadSectors(RoadSector *R);
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CRoadSectors)
public:
virtual void Serialize(CArchive& ar);

// overridden for document i/o

//}}AFX_VIRTUAL
// Implementation
public:
int cycle_count;
LightPhase LTLight;
LightPhase light;
int rooms_on_road_sector;
void ResetDepletionTime();
int LoadCycleCount();
BOOL IsGreenLight();
void AddCarArrival(int cars);
void ReSet();
int GetLoopcount();
void InitialRoad(int vol0);
void ReSetRoomOnRoadSector();
inline int DevoteCars(int & cars_arrival,int& cars_moving, int& cars_ready);
int ExpectedArrivals(int car_pool, double t);
void MoveTrafficOnRed(CRoadSectors &R, CRoadSectors &L, double time);
void MoveTrafficOnGreen(CRoadSectors &T, CRoadSectors &R, CRoadSectors &L, double time);
RoadSector *Rd;
virtual ~CRoadSectors();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
// Generated message map functions
protected:

124

//{{AFX_MSG(CRoadSectors)
// NOTE - the ClassWizard will add and remove member functions here.
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
private:
int cars_arrival;
double ave_queue;
double ave_speed;
int cars_made_left_turn;
int cars_made_right_turn;
int loop_count;
int cars_making_right_turn;
int cars_on_left_turn_lane;
double next_layer_dtime;
int cars_in_queue;
int cars_on_road;
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif //
!defined(AFX_ROADSECTORS_H__32031F20_DB44_11D4_8AB7_0050DACD1682__INCLUDED_)

**************************************************************************************
*

RoadSectors.cpp

**************************************************************************************
// RoadSectors.cpp : implementation file
//
#include "stdafx.h"
#include "TrafDef.h"
#include "RoadSectors.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;

125

#endif
/////////////////////////////////////////////////////////////////////////////
// CRoadSectors
IMPLEMENT_DYNCREATE(CRoadSectors, CDocument)
CRoadSectors::CRoadSectors()
{
Rd = NULL;
}
CRoadSectors::CRoadSectors(RoadSector *R)
{
ave_queue=0;
ave_speed=0;
cars_arrival=0;
cars_in_queue = 0;
cars_made_left_turn =0;
cars_made_right_turn = 0;
cars_making_right_turn =0;
cars_on_left_turn_lane =0;
cars_on_road =0;
// cumulated data
cycle_count =0;
loop_count = 0;
rooms_on_road_sector = 0;
// 3.13 in cycle time unit is equal to 4.7 seconds for car depleting
next_layer_dtime =3.13;
// assign road sector;
Rd = R;
// signal setting
LTLight = red;
light = red;
}
CRoadSectors::~CRoadSectors()
{
}

BEGIN_MESSAGE_MAP(CRoadSectors, CDocument)

126

//{{AFX_MSG_MAP(CRoadSectors)
// NOTE - the ClassWizard will add and remove mapping macros here.
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CRoadSectors diagnostics
#ifdef _DEBUG
void CRoadSectors::AssertValid() const
{
CDocument::AssertValid();
}
void CRoadSectors::Dump(CDumpContext& dc) const
{
CDocument::Dump(dc);
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CRoadSectors serialization
void CRoadSectors::Serialize(CArchive& ar)
{
if (ar.IsStoring())
{
// TODO: add storing code here
}
else
{
// TODO: add loading code here
}
}
/////////////////////////////////////////////////////////////////////////////
// CRoadSectors commands
void CRoadSectors::MoveTrafficOnGreen(CRoadSectors &T, CRoadSectors &R, CRoadSectors &L,
double time)
{

127

int

cars_to_be_dplted = 0;

int

cars_moving_out = 0;

int

cars_to_left_queue = 0;

int

cars_to_right_queue = 0;

int cars_ready=0;

// The potential number of vehicle

double time_1 = 0.; // The time for the last depletion


double time_of_depleting = 0;
double time_remain = 0;
int cars_add_to_queue = 0;
int

cars_in_sector_moving = cars_on_road;

// compute number of car will arrive to the intersection for depleting


//

skip the computation if there are no cars in queue

while ( cars_in_queue>0 && time_of_depleting< time )


{
// moving cars layer by layer (the first layer cars need 2.1 second the subsequence layers
//

need only 0.5 second)

time_of_depleting += next_layer_dtime;
if(time_of_depleting < time)
{
next_layer_dtime = 1.4; // 1.4 in cycle time is equivalent to 2.1 sec.
//

each time only one layer of vehicles can move that will be equal to

//

number of lanes on the road sector

cars_ready = (cars_in_queue < Rd->lanes) ? cars_in_queue : Rd->lanes;


// The depletion also will be limited by the down stream capacity
if (&T != NULL)
if(T.rooms_on_road_sector<=0) cars_ready=0;
else
{
if( T.rooms_on_road_sector < cars_to_be_dplted + cars_ready)
cars_ready = T.rooms_on_road_sector - cars_to_be_dplted;
}
cars_to_be_dplted += cars_ready;
cars_in_queue -= cars_ready;
}
else
{
// There is not enough time to deplete the remaining cars in queue
next_layer_dtime = time_of_depleting - time;
time_of_depleting = time;

128

}
//

add vehicles to the queue from the incoming traffic at end of queue
if(cars_in_queue>Rd->lanes && cars_in_sector_moving > 0)
{
cars_ready = ExpectedArrivals(cars_in_sector_moving,time_of_depleting-time_1);
time_1=time_of_depleting;
cars_in_queue += cars_ready;
cars_in_sector_moving-= cars_ready;
if (rooms_on_road_sector>cars_ready)

rooms_on_road_sector -= cars_ready;

else rooms_on_road_sector = 0;
}
}
if (time_of_depleting < time)
{
// queue has been emptied

the vehicle could move freely to the down stream

time_remain = time - time_of_depleting;


// Probability for car arrival is
cars_ready = ExpectedArrivals(cars_in_sector_moving, time_remain);
next_layer_dtime = 0.;
}
else
{
// The queue is too long to be depleted within this time period
next_layer_dtime = time_of_depleting-time;
time_remain =.0;
cars_ready = 0;
}
cars_on_road = cars_in_sector_moving - cars_ready;
//

cars are spliting to left and right truning lanes if they are exits

cars_moving_out = cars_to_be_dplted+cars_ready;
// if there is no right or left turning lanes cars_moving_out contains the cars
//

making left and right turns

if (Rd->left_lanes > 0)

cars_to_left_queue = Poisson(cars_moving_out * Rd->left_turn_rate);

else cars_to_left_queue =0;


if (Rd->right_lanes== 0) cars_to_right_queue = Poisson(double(cars_moving_out) *
Rd->right_turn_rate);
else cars_to_right_queue =0;
while (cars_to_left_queue+cars_to_right_queue > cars_moving_out)

129

{
if (cars_to_left_queue > 0) cars_to_left_queue--;
if (cars_to_right_queue > 0) cars_to_right_queue--;
};
cars_on_left_turn_lane+=cars_to_left_queue;
cars_making_right_turn+=cars_to_right_queue;
cars_moving_out -= cars_to_left_queue + cars_to_right_queue;
if (cars_moving_out > 0)
{
cars_ready=cars_moving_out;
if (&T != NULL)
{
T.cars_arrival+=DevoteCars(T.rooms_on_road_sector, cars_moving_out, cars_ready);
T.ReSetRoomOnRoadSector();
}
loop_count += cars_ready;
cycle_count += cars_ready;
if (cars_ready < cars_moving_out)
{
cars_in_queue = cars_moving_out - cars_ready;
ReSetRoomOnRoadSector();
}
}
if (LTLight == green || LTLight == flash)
{
if (&L != NULL)
{
L.cars_arrival+=DevoteCars(L.rooms_on_road_sector, cars_on_left_turn_lane,
cars_ready);
L.ReSetRoomOnRoadSector();
cars_made_left_turn += cars_ready;
cars_on_left_turn_lane -= cars_ready;
}
else
{
cars_made_left_turn += cars_on_left_turn_lane;
cars_on_left_turn_lane =0;
}
}

130

if (cars_making_right_turn > 0)
{
if(&R != NULL)
{
R.cars_arrival+=DevoteCars(R.rooms_on_road_sector,cars_making_right_turn,cars_ready);
R.ReSetRoomOnRoadSector();
cars_made_right_turn += cars_ready;
cars_making_right_turn -= cars_ready;
}
else
{
cars_made_right_turn += cars_making_right_turn;
cars_making_right_turn=0;
}
}
}
void CRoadSectors::MoveTrafficOnRed(CRoadSectors &R, CRoadSectors &L, double time)
{
int

cars_ready;

cars_ready=ExpectedArrivals(cars_on_road, time);
cars_on_road -= cars_ready;
if(cars_ready > 0)
{
cars_in_queue += cars_ready;
ReSetRoomOnRoadSector();
}
if (LTLight == green)
{
if (&L != NULL)
{
L.cars_arrival += DevoteCars(L.rooms_on_road_sector, cars_on_left_turn_lane,
cars_ready);
L.ReSetRoomOnRoadSector();
cars_made_left_turn += cars_ready;
cars_on_left_turn_lane -= cars_ready;
}
else

131

{
cars_made_left_turn += cars_on_left_turn_lane;
cars_on_left_turn_lane =0;
}
}
if(Rd!=NULL)
if (Rd->right_lanes > 0)
if(cars_making_right_turn > 0)
{
if(&R != NULL)
{
R.cars_arrival+=DevoteCars(R.rooms_on_road_sector,cars_making_right_turn,cars_ready);
R.ReSetRoomOnRoadSector();
cars_made_right_turn += cars_ready;
cars_making_right_turn -= cars_ready;
}
else
{
cars_made_right_turn += cars_making_right_turn;
cars_making_right_turn=0;
}
}
}
int CRoadSectors::ExpectedArrivals(int car_pool, double t)
{
double arrival_rate;
int cars;
if (car_pool > 0)
{
// computing number of cars in queue for departing
if (rooms_on_road_sector>Rd->lanes)
{
// compute from the ratio of the distance of a car can trival under
//

the speed limit in the given time to the road space available

arrival_rate = double(car_pool) * t *1.5f * Rd->speed_limit


* double(Rd->lanes)/rooms_on_road_sector;
cars = Poisson(arrival_rate);
cars = ( cars < car_pool ) ? cars: car_pool;
}
else cars = car_pool;

132

}
else cars = 0;
return(cars);
}
inline int CRoadSectors::DevoteCars(int& rooms_on_road_sector, int& cars_out, int& cars_moved)
{
// cars can be devoted when the down stream road has room to accept them
return( (rooms_on_road_sector >cars_out) ? cars_out : rooms_on_road_sector);
}
void CRoadSectors::ReSetRoomOnRoadSector()
{
// reset road cap when cars on the road moved away
rooms_on_road_sector = int(Rd->length*double(Rd->lanes))
- cars_in_queue - cars_on_road - cars_arrival;
if (rooms_on_road_sector < 0)rooms_on_road_sector=0;
}
void CRoadSectors::InitialRoad(int vol0)
{
// initial road with the 5 min. loop count
light=red;
cars_in_queue = 0;
ave_speed = Rd->speed_limit;
cars_on_road =
int ((double(vol0)/300.0) * 15.0 // volume in time cycle for 5 min data
* (Rd->length/(Rd->speed_limit*15.0)) // ratio of total cars : number of cars in a cycle
);

// for a lane

rooms_on_road_sector = int(Rd->length*double(Rd->lanes))-cars_on_road;
}
int CRoadSectors::GetLoopcount()
{
return loop_count;
}
void CRoadSectors::ReSet()
{
loop_count=0;

133

cars_made_left_turn =0;
cars_made_right_turn =0;
}
void CRoadSectors::AddCarArrival(int cars)
{
cars_arrival += cars;
}
BOOL CRoadSectors::IsGreenLight()
{
if(light == green) return TRUE;
else return FALSE;
}
int CRoadSectors::LoadCycleCount()
{
return(cycle_count);
}
void CRoadSectors::ResetDepletionTime()
{
// the time needed for the first car to deplet (4.7 seconds).
//

Here the unit is in cycle-time

next_layer_dtime =3.13;
}

**************************************************************************************
*

StdAfx.h

**************************************************************************************
// stdafx.h : include file for standard system include files,
//
//

or project specific include files that are used frequently, but


are changed infrequently

//
#if !defined(AFX_STDAFX_H__6D3D0617_C6EE_11D4_8AA4_0050DACD1682__INCLUDED_)
#define AFX_STDAFX_H__6D3D0617_C6EE_11D4_8AA4_0050DACD1682__INCLUDED_

134

#if _MSC_VER > 1000


#pragma once
#endif // _MSC_VER > 1000
#define VC_EXTRALEAN

// Exclude rarely-used stuff from Windows headers

#define MAXRANG 20000


#define CYL 10
#include <afxwin.h>

// MFC core and standard components

#include <afxext.h>

// MFC extensions

#include <afxdisp.h>

// MFC Automation classes

#include <afxdtctl.h>

// MFC support for Internet Explorer 4 Common Controls

#ifndef _AFX_NO_AFXCMN_SUPPORT
#include <afxcmn.h>

// MFC support for Windows Common Controls

#endif // _AFX_NO_AFXCMN_SUPPORT
#include <math.h>
enum TrafficDir {NB, WB, SB, EB};//, PD
enum TurningDir {TH, LT, RT};//, SP
enum LightPhase{red,green,yellow,flash,NL};
inline int Poisson( double mean );
struct RoadSector
{
int intersection_ID;
TrafficDir dir;
int lanes;
int left_lanes;
int right_lanes;
double speed_limit;
double length;
double left_turn_rate;
double right_turn_rate;
POSITION CR;
};
struct Timings
{
int i_phase;
TrafficDir bound;
TurningDir turns;

135

int min_green;
int walk;
int ped_clear;
double veh_extend;
int max_green;
double yellow;
double red;
int red_revolt;
};
//////////////////////////////////////////////////////
struct Intersection
{
int ID;
int GRP;
//

maximum of 8 settings scheduled by Montgomery County

Timings *MG_preset[8];
RoadSector *IN_B[4];
RoadSector *OUT_B[4];
char SEQ;
char PHASE[6][2];
};
//////////////////////////////////////////
struct SignalTiming
{
int prog_ratio;
int

split[5];

};
struct LPCT {double tg[4][3];
int Nc[3];
int Wc[3];
int Sc[3];
int Ec[3];};
#include "RoadSector.h"
inline int Poisson( double mean )
{
double bound, product = 1.0;
int i;
double const1,const2=RAND_MAX;
bound = exp( -mean );
for( i=0; i<MAXRANG; ++i)

136

{
const1 = double(rand());
product *= const1 / const2;
if( product <= bound )

return ( i );

}
return ( MAXRANG );
}
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_STDAFX_H__6D3D0617_C6EE_11D4_8AA4_0050DACD1682__INCLUDED_)

**************************************************************************************
*

StdAfx.cpp

**************************************************************************************
// stdafx.cpp : source file that includes just the standard includes
//

TrafDef.pch will be the pre-compiled header

//

stdafx.obj will contain the pre-compiled type information

#include "stdafx.h"

**************************************************************************************
*

TrafDef.h

**************************************************************************************
// TrafDef.h : main header file for the TRAFDEF application
//
#if !defined(AFX_TRAFDEF_H__6D3D0615_C6EE_11D4_8AA4_0050DACD1682__INCLUDED_)
#define AFX_TRAFDEF_H__6D3D0615_C6EE_11D4_8AA4_0050DACD1682__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

137

#ifndef __AFXWIN_H__
#error include 'stdafx.h' before including this file for PCH
#endif
#include "resource.h"

// main symbols

/////////////////////////////////////////////////////////////////////////////
// CTrafDefApp:
// See TrafDef.cpp for the implementation of this class
//
class CTrafDefApp : public CWinApp
{
public:
CTrafDefApp();
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CTrafDefApp)
public:
virtual BOOL InitInstance();
//}}AFX_VIRTUAL
// Implementation
//{{AFX_MSG(CTrafDefApp)
afx_msg void OnAppAbout();
// NOTE - the ClassWizard will add and remove member functions here.
//

DO NOT EDIT what you see in these blocks of generated code !

//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};

/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif //
!defined(AFX_TRAFDEF_H__6D3D0615_C6EE_11D4_8AA4_0050DACD1682__INCLUDED_)

138

**************************************************************************************
*

TrafDef.cpp

**************************************************************************************
// TrafDef.cpp : Defines the class behaviors for the application.
//
#include "stdafx.h"
#include "TrafDef.h"
#include "MainFrm.h"
#include "ChildFrm.h"
#include "TrafDefDoc.h"
#include "TrafDefView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CTrafDefApp
BEGIN_MESSAGE_MAP(CTrafDefApp, CWinApp)
//{{AFX_MSG_MAP(CTrafDefApp)
ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
// NOTE - the ClassWizard will add and remove mapping macros here.
//

DO NOT EDIT what you see in these blocks of generated code!

//}}AFX_MSG_MAP
// Standard file based document commands
ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew)
ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen)
// Standard print setup command
ON_COMMAND(ID_FILE_PRINT_SETUP, CWinApp::OnFilePrintSetup)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CTrafDefApp construction
CTrafDefApp::CTrafDefApp()
{

139

// TODO: add construction code here,


// Place all significant initialization in InitInstance
}
/////////////////////////////////////////////////////////////////////////////
// The one and only CTrafDefApp object
CTrafDefApp theApp;
/////////////////////////////////////////////////////////////////////////////
// CTrafDefApp initialization
BOOL CTrafDefApp::InitInstance()
{
AfxEnableControlContainer();
// Standard initialization
// If you are not using these features and wish to reduce the size
//

of your final executable, you should remove from the following

//

the specific initialization routines you do not need.

#ifdef _AFXDLL
Enable3dControls();

// Call this when using MFC in a shared DLL

#else
Enable3dControlsStatic(); // Call this when linking to MFC statically
#endif
// Change the registry key under which our settings are stored.
// TODO: You should modify this string to be something appropriate
// such as the name of your company or organization.
SetRegistryKey(_T("Local AppWizard-Generated Applications"));
LoadStdProfileSettings(); // Load standard INI file options (including MRU)
// Register the application's document templates. Document templates
//

serve as the connection between documents, frame windows and views.

CMultiDocTemplate* pDocTemplate;
pDocTemplate = new CMultiDocTemplate(
IDR_TRAFDETYPE,
RUNTIME_CLASS(CTrafDefDoc),

140

RUNTIME_CLASS(CChildFrame), // custom MDI child frame


RUNTIME_CLASS(CTrafDefView));
AddDocTemplate(pDocTemplate);
// create main MDI Frame window
CMainFrame* pMainFrame = new CMainFrame;
if (!pMainFrame->LoadFrame(IDR_MAINFRAME))
return FALSE;
m_pMainWnd = pMainFrame;
// Parse command line for standard shell commands, DDE, file open
CCommandLineInfo cmdInfo;
ParseCommandLine(cmdInfo);
// Dispatch commands specified on the command line
if (!ProcessShellCommand(cmdInfo))
return FALSE;
// The main window has been initialized, so show and update it.
pMainFrame->ShowWindow(m_nCmdShow);
pMainFrame->UpdateWindow();
return TRUE;
}

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
//{{AFX_DATA(CAboutDlg)
enum { IDD = IDD_ABOUTBOX };
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CAboutDlg)

141

protected:
virtual void DoDataExchange(CDataExchange* pDX);

// DDX/DDV support

//}}AFX_VIRTUAL
// Implementation
protected:
//{{AFX_MSG(CAboutDlg)
virtual void OnOK();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
//{{AFX_DATA_INIT(CAboutDlg)
//}}AFX_DATA_INIT
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAboutDlg)
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
// App command to run the dialog
void CTrafDefApp::OnAppAbout()
{
CAboutDlg aboutDlg;
aboutDlg.DoModal();
}
/////////////////////////////////////////////////////////////////////////////
// CTrafDefApp message handlers

142

void CAboutDlg::OnOK()
{
// TODO: Add extra validation here
CDialog::OnOK();
}

**************************************************************************************
*

TrafDefDoc.h

**************************************************************************************
// TrafDefDoc.h : interface of the CTrafDefDoc class
//
/////////////////////////////////////////////////////////////////////////////
#if
!defined(AFX_TRAFDEFDOC_H__6D3D061D_C6EE_11D4_8AA4_0050DACD1682__INCLUDED_)
#define AFX_TRAFDEFDOC_H__6D3D061D_C6EE_11D4_8AA4_0050DACD1682__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "RoadNet.h"
#include "NN.h"
class CTrafDefDoc : public CDocument
{
protected: // create from serialization only
CTrafDefDoc();
DECLARE_DYNCREATE(CTrafDefDoc)
// Attributes
public:
// Operations
public:
struct SA {
double a; double alpha; double c; double gamma; int b; int iter; unsigned seed;
};
CRoadNet *sR;

143

// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CTrafDefDoc)
public:
virtual BOOL OnNewDocument();
virtual void Serialize(CArchive& ar);
//}}AFX_VIRTUAL
// Implementation
public:
double c;
double a;
void RunSPSA(int iter);
CNN *theta;
NN nn;
SA spsa;
virtual ~CTrafDefDoc();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
// Generated message map functions
protected:
//{{AFX_MSG(CTrafDefDoc)
// NOTE - the ClassWizard will add and remove member functions here.
//

DO NOT EDIT what you see in these blocks of generated code !

//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif //
!defined(AFX_TRAFDEFDOC_H__6D3D061D_C6EE_11D4_8AA4_0050DACD1682__INCLUDED_)

144

**************************************************************************************
*

TrafDefDoc.cpp

**************************************************************************************
// TrafDefDoc.cpp : implementation of the CTrafDefDoc class
//
#include "stdafx.h"
#include "TrafDef.h"
#include "InputDlg.h"
#include "TrafDefDoc.h"
#include "NN.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CTrafDefDoc
IMPLEMENT_DYNCREATE(CTrafDefDoc, CDocument)
BEGIN_MESSAGE_MAP(CTrafDefDoc, CDocument)
//{{AFX_MSG_MAP(CTrafDefDoc)
// NOTE - the ClassWizard will add and remove mapping macros here.
//

DO NOT EDIT what you see in these blocks of generated code!

//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CTrafDefDoc construction/destruction
CTrafDefDoc::CTrafDefDoc()
{
// TODO: add one-time construction code here

145

}
CTrafDefDoc::~CTrafDefDoc()
{
if(theta != NULL) delete theta;
if(sR != NULL) delete sR;
}
BOOL CTrafDefDoc::OnNewDocument()
{
double x[]={61., 59., 81.,56., 40., 61., 66., 49., 0.,47.,20.};
CInputDlg Dlg;
if (!CDocument::OnNewDocument())
return FALSE;
Dlg.x = &x[0];
if(Dlg.DoModal() == IDOK)
{
spsa.a=Dlg.m_a;
spsa.alpha = Dlg.m_alpha;
spsa.c=Dlg.m_c;
spsa.gamma = Dlg.m_gamma;
spsa.b=Dlg.m_b;
spsa.seed = Dlg.m_seed;
nn.lv1=Dlg.m_hid1;
nn.lv2=Dlg.m_hid2;
nn.b1 = Dlg.m_b1;
nn.b2 = Dlg.m_b2;
nn.bo = Dlg.m_bo;
}
nn.in=21; // The input dimension is defined by 14 road sectors
//

6 intersections, and time-of-day

// The 11 intersections are the same as out parameters


nn.out=6; // The 11 output paramenters are consisted of 7 timing prograsive rates
// and 4 split ratios for major intersections
theta = new CNN(nn);
sR = new CRoadNet;
sR->RoadNN = theta;
return TRUE;
}

146

/////////////////////////////////////////////////////////////////////////////
// CTrafDefDoc serialization
void CTrafDefDoc::Serialize(CArchive& ar)
{
if (ar.IsStoring())
{
// TODO: add storing code here
}
else
{
// TODO: add loading code here
}
}
/////////////////////////////////////////////////////////////////////////////
// CTrafDefDoc diagnostics
#ifdef _DEBUG
void CTrafDefDoc::AssertValid() const
{
CDocument::AssertValid();
}
void CTrafDefDoc::Dump(CDumpContext& dc) const
{
CDocument::Dump(dc);
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CTrafDefDoc commands
void CTrafDefDoc::RunSPSA(int iter)
{
int i1;
CNN *delta = new CNN(nn);
//

if(iter<spsa.iter) return;
i1=iter+2+spsa.b;
a=spsa.a*pow(double (i1),-spsa.alpha);

147

c=spsa.c*pow(double (i1),-spsa.gamma);
//

mom=MOM*pow(float (i1),rho);
delta->BlDelta(c);
sR->RoadNN->PerturbP(*theta, *delta);
sR->TrafFlow();

//

TrafficDailyControl(net);

//

ep =TrafEvaluate(total_cars_p);

//

Ep[iter]=ep;

//

T_p[iter]=total_cars_p;
sR->RoadNN->PerturbN(*theta, *delta);

//

TrafficDailyControl(net);
//

en = TrafEvaluate(total_cars_n);

//

En[iter]=en;

//

T_n[iter]=total_cars_n;

//

err = a*(ep/total_cars_n - en/total_cars_p)*.5f/c;

//

WeightUpdate(err,net0,net_d,NUM_IN, NUM_OUT);

//

if (eval == 1)

//

//

TrafficDailyControl(net0);

//

err = TrafEvaluate(total_cars_e);

//

Err[iter]=err;

//

T_e[iter]=total_cars_e;

//}
//

printf("\n iter = %d ep = %f, en = %f, err = %f cars %d",iter,ep,en,err,total_cars_e);

/*
if(DUMP==1)
{
FILE *file_out;
file_out = fopen("MCV1_cs50.txt","w");
fprintf(file_out,
"a,%g,alpha,%g,c,%g,gamma,%g,hid1,%u,hid2,%u,in,%u,out,%u,seed,%u,",
A, alpha, C, gamma, HID1, HID2, NUM_IN, NUM_OUT,seed);
fprintf(file_out,"\ncase %d %g %d",n_case,err0,total_cars_e0);
fprintf(file_out,"\nep ");
for (iter=0;iter<n_iter; iter++) fprintf(file_out," %g",Ep[iter]);
fprintf(file_out,"\nen ");
for (iter=0;iter<n_iter; iter++) fprintf(file_out," %g",En[iter]);

148

fprintf(file_out,"\nerr ");
for (iter=0;iter<n_iter; iter++) fprintf(file_out," %g",Err[iter]);
fprintf(file_out,"\nt_p ");
for (iter=0;iter<n_iter; iter++) fprintf(file_out," %d",T_p[iter]);
fprintf(file_out,"\nt_n ");
for (iter=0;iter<n_iter; iter++) fprintf(file_out," %d",T_n[iter]);
fprintf(file_out,"\nt_e ");
for (iter=0;iter<n_iter; iter++) fprintf(file_out," %d",T_e[iter]);
fclose(file_out);
*/
delete delta;
}

**************************************************************************************
*

TrafDefView.h

**************************************************************************************
// TrafDefView.h : interface of the CTrafDefView class
//
/////////////////////////////////////////////////////////////////////////////
#if
!defined(AFX_TRAFDEFVIEW_H__6D3D061F_C6EE_11D4_8AA4_0050DACD1682__INCLUDED_)
#define AFX_TRAFDEFVIEW_H__6D3D061F_C6EE_11D4_8AA4_0050DACD1682__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "RoadNet.h"
#include "Intersections.h"

class CTrafDefView : public CFormView


{
protected: // create from serialization only
CTrafDefView();
DECLARE_DYNCREATE(CTrafDefView)

149

public:
//{{AFX_DATA(CTrafDefView)
enum { IDD = IDD_TRAFDEF_FORM };
CListBox m_result_list;
CString

m_alpha;

CString

m_a;

CString

m_b;

CString

m_c;

CString

m_gamma;

CString

m_seed;

CString

m_hid_1;

CString

m_hid_2;

CString

m_input;

CString

m_output;

BOOL

m_1b;

BOOL

m_2b;

BOOL

m_ob;

CString

m_Iteration;

//}}AFX_DATA
// Attributes
public:
CTrafDefDoc* GetDocument();
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CTrafDefView)
public:
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
protected:
virtual void DoDataExchange(CDataExchange* pDX);

// DDX/DDV support

virtual void OnInitialUpdate(); // called first time after construct


virtual BOOL OnPreparePrinting(CPrintInfo* pInfo);
virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo);
virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo);
virtual void OnPrint(CDC* pDC, CPrintInfo* pInfo);
//}}AFX_VIRTUAL

150

// Implementation
public:
int iter;
CIntersections *temp[6];//
Intersection tempnn;//
virtual ~CTrafDefView();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
// Generated message map functions
protected:
//{{AFX_MSG(CTrafDefView)
afx_msg void OnRunDaily();
afx_msg void OnRunExec();
afx_msg void OnChangeIteration();
afx_msg void OnSelchangeFinalResults();
afx_msg void OnNnL1Bias();
afx_msg void OnChangeAlpha();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
#ifndef _DEBUG // debug version in TrafDefView.cpp
inline CTrafDefDoc* CTrafDefView::GetDocument()
{ return (CTrafDefDoc*)m_pDocument; }
#endif
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif //
!defined(AFX_TRAFDEFVIEW_H__6D3D061F_C6EE_11D4_8AA4_0050DACD1682__INCLUDED_)

151

**************************************************************************************
*

TrafDefView.cpp

**************************************************************************************
// TrafDefView.cpp : implementation of the CTrafDefView class
//
#include "stdio.h"
#include "stdafx.h"
#include <iostream.h>
#include "TrafDef.h"
#include "Intersections.h"
#include "RoadNet.h"
#include "RoadSectors.h"
#include "TrafDefDoc.h"
#include "TrafDefView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CTrafDefView
IMPLEMENT_DYNCREATE(CTrafDefView, CFormView)
BEGIN_MESSAGE_MAP(CTrafDefView, CFormView)
//{{AFX_MSG_MAP(CTrafDefView)
ON_COMMAND(ID_RUN_DAILY, OnRunDaily)
ON_COMMAND(ID_RUN_EXEC, OnRunExec)
ON_EN_CHANGE(IDC_ITERATION, OnChangeIteration)
ON_LBN_SELCHANGE(IDC_FINAL_RESULTS, OnSelchangeFinalResults)
ON_BN_CLICKED(IDC_NN_L1_BIAS, OnNnL1Bias)
ON_EN_CHANGE(IDC_ALPHA, OnChangeAlpha)
//}}AFX_MSG_MAP
// Standard printing commands
ON_COMMAND(ID_FILE_PRINT, CFormView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_DIRECT, CFormView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_PREVIEW, CFormView::OnFilePrintPreview)

152

END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CTrafDefView construction/destruction
CTrafDefView::CTrafDefView()
: CFormView(CTrafDefView::IDD)
{
//{{AFX_DATA_INIT(CTrafDefView)
m_alpha = _T("");
m_a = _T("");
m_b = _T("");
m_c = _T("");
m_gamma = _T("");
m_seed = _T("");
m_hid_1 = _T("");
m_hid_2 = _T("");
m_input = _T("");
m_output = _T("");
m_1b = TRUE;
m_2b = TRUE;
m_ob = TRUE;
m_Iteration = _T("");
//}}AFX_DATA_INIT
// TODO: add construction code here
}
CTrafDefView::~CTrafDefView()
{
}
void CTrafDefView::DoDataExchange(CDataExchange* pDX)
{
CFormView::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CTrafDefView)
DDX_Control(pDX, IDC_FINAL_RESULTS, m_result_list);
DDX_Text(pDX, IDC_ALPHA, m_alpha);
DDX_Text(pDX, IDC_GAIN_A, m_a);
DDX_Text(pDX, IDC_GAIN_BASE, m_b);
DDX_Text(pDX, IDC_GAIN_C, m_c);

153

DDX_Text(pDX, IDC_GAMMA, m_gamma);


DDX_Text(pDX, IDC_SEED, m_seed);
DDX_Text(pDX, IDC_HIDEN_L1, m_hid_1);
DDV_MaxChars(pDX, m_hid_1, 3);
DDX_Text(pDX, IDC_HIDEN_L2, m_hid_2);
DDV_MaxChars(pDX, m_hid_2, 3);
DDX_Check(pDX, IDC_NN_L1_BIAS, m_1b);
DDX_Check(pDX, IDC_NN_L2_BIAS, m_2b);
DDX_Check(pDX, IDC_OUTPUT_BIASE, m_ob);
DDX_Text(pDX, IDC_ITERATION, m_Iteration);
DDV_MaxChars(pDX, m_Iteration, 6);
//}}AFX_DATA_MAP
}
BOOL CTrafDefView::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: Modify the Window class or styles here by modifying
//

the CREATESTRUCT cs

return CFormView::PreCreateWindow(cs);
}
void CTrafDefView::OnInitialUpdate()
{
CTrafDefDoc* pDoc = GetDocument();
m_a.Format("%12.3e",pDoc->spsa.a);
m_alpha.Format("%12.3e",pDoc->spsa.alpha);
m_b.Format("%d",pDoc->spsa.b);
m_c.Format("%12.3e",pDoc->spsa.c);
m_gamma.Format("%12.3e",pDoc->spsa.gamma);
m_seed.Format("%12d",pDoc->spsa.seed);
m_input.Format("%d",pDoc->nn.in);
m_output.Format("%d",pDoc->nn.out);
m_hid_1.Format("%d",pDoc->nn.lv1);
m_hid_2.Format("%d",pDoc->nn.lv2);
m_ob = pDoc->nn.bo;
m_1b = pDoc->nn.b1;
m_2b = pDoc->nn.b2;
iter=0;
CFormView::OnInitialUpdate();
ResizeParentToFit();

154

/*

//theta = new CNN(nn);


//sR = new CRoadNet;
//sR->RoadNN = theta;
temp = new CIntersections(tempnn);
tempsR = new CRoadNet;
tempsR->sI = temp;*/

}
/////////////////////////////////////////////////////////////////////////////
// CTrafDefView printing
BOOL CTrafDefView::OnPreparePrinting(CPrintInfo* pInfo)
{
// default preparation
return DoPreparePrinting(pInfo);
}
void CTrafDefView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add extra initialization before printing
}
void CTrafDefView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add cleanup after printing
}
void CTrafDefView::OnPrint(CDC* pDC, CPrintInfo* /*pInfo*/)
{
// TODO: add customized printing code here
}
/////////////////////////////////////////////////////////////////////////////
// CTrafDefView diagnostics
#ifdef _DEBUG
void CTrafDefView::AssertValid() const
{
CFormView::AssertValid();
}

155

void CTrafDefView::Dump(CDumpContext& dc) const


{
CFormView::Dump(dc);
}
CTrafDefDoc* CTrafDefView::GetDocument() // non-debug version is inline
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CTrafDefDoc)));
return (CTrafDefDoc*)m_pDocument;
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CTrafDefView message handlers
void CTrafDefView::OnRunDaily()
{
CString result;
CTrafDefDoc* pDoc = GetDocument();
pDoc->RunSPSA(iter);
iter++;
result.Format("Iteration %d a= %10.4f, c= %10.4f",iter,pDoc->a,//sI[0]->st.split[0]
pDoc->c);
m_Iteration.Format("%d",iter);
m_result_list.AddString(result);
UpdateData(FALSE);
}
void CTrafDefView::OnRunExec()
{
// TODO: Add your command handler code here
int last;
sscanf(m_Iteration,"%d",&last);
if(last<=iter) last =iter+30;
while(iter<last)
{
OnRunDaily();
}
}

156

void CTrafDefView::OnChangeIteration()
{
// TODO: If this is a RICHEDIT control, the control will not
// send this notification unless you override the CFormView::OnInitDialog()
// function and call CRichEditCtrl().SetEventMask()
// with the ENM_CHANGE flag ORed into the mask.
// TODO: Add your control notification handler code here
CWnd* pCtlIterationText = GetDlgItem(IDC_ITERATION);
pCtlIterationText->GetWindowText(m_Iteration);
}
void CTrafDefView::OnSelchangeFinalResults()
{
// TODO: Add your control notification handler code here
}
void CTrafDefView::OnNnL1Bias()
{
// TODO: Add your control notification handler code here
}
void CTrafDefView::OnChangeAlpha()
{
// TODO: If this is a RICHEDIT control, the control will not
// send this notification unless you override the CFormView::OnInitDialog()
// function and call CRichEditCtrl().SetEventMask()
// with the ENM_CHANGE flag ORed into the mask.
// TODO: Add your control notification handler code here
}

157

**************************************************************************************
*

trafeval.h

**************************************************************************************
int InputTimings(FILE *SRt,
SignalTiming SRT[])
{
int icycle,lp;
fscanf(SRt,"%d",&icycle);
if(icycle >= 0)
for (lp=0;lp<12;lp++)
{
fscanf(SRt,"%d, %d, %d, %d, %d, %d",
&SRT[lp].prog_ratio,
&SRT[lp].split[0], &SRT[lp].split[1],
&SRT[lp].split[2], &SRT[lp].split[3],
&SRT[lp].split[4]);
}
return(icycle);
}
float caleff(float t_g[],int lcount[], float speed, int lanes)
{
float err, exp_cars;
err=0.f;
for (int i=0; i<3; i++)
{
exp_cars = t_g[i]*speed*float(lanes);
if(exp_cars>0) err += (exp_cars - float(lcount[i]))/exp_cars;
}
return(err);
}
int InitialPhase(int &j,int split[])
{
int i;
i=0;
while (j< 100)
{
j+= split[i];
i++;
}

158

j %= 100;
return(i-1);
}
void InputLpCounts(FILE *Lpcount, LPCT a[],int i_cycle,int& total_cars)
{
int ir;
if (i_cycle%2 == 0) ir=3;
else ir=2;
for (int i=0; i<ir; i++)
{
for (int lp=0;lp<10;lp++)
{
fscanf(Lpcount,"%d,",&a[lp].Nc[i]);
total_cars += a[lp].Nc[i];
if(lp==4 || lp==7)fscanf(Lpcount,"%d,",&a[lp].Wc[i]);
else a[lp].Wc[i]=0; // skip the intersetion w/o sensor
total_cars += a[lp].Wc[i];
fscanf(Lpcount,"%d,",&a[lp].Sc[i]);
total_cars += a[lp].Sc[i];
if(lp==0 || lp==6 || lp==7 || lp==8)
fscanf(Lpcount,"%d,",&a[lp].Ec[i]);
else a[lp].Ec[i]=0; // skip the intersection w/o sensor
total_cars += a[lp].Ec[i];
}
fscanf(Lpcount,"\n");
}
}
float eff(SignalTiming *SRT,
LPCT *lc,
Intersection *sR,
int icycle)
{
int i,ir,tend,tcurrent,tnext,tphase_end,
i_phase,seq1,seq2;
float err;
err=0.0f;
tphase_end = SRT->prog_ratio;
i_phase=InitialPhase(tphase_end,SRT->split);
//

initial time of green to 0

if (icycle%2 ==0)
{

159

ir=0;
tnext=40;
for (i=0; i<4; i++) lc->tg[i][ir]=0.0f;
}
else
{
ir=2;
tnext=20;
}
tcurrent=0;
tend=tcurrent;
while (tnext<=120)
{
while (tend<tnext && tend<100)
{
seq1= sR->phase[i_phase][0]-1;
seq2= sR->phase[i_phase][1]-1;
if (tnext > tphase_end) tend = tphase_end;
else tend = tnext;
if (tnext == 120) tend = 100;
lc->tg[sR->ts[seq1]->bound][ir] +=tend-tcurrent;
if (seq2 >= 0 )
if(sR->ts[seq1]->bound != sR->ts[seq2]->bound && sR->ts[seq2]->bound != PD)
lc->tg[sR->ts[seq2]->bound][ir] +=tend-tcurrent;
tcurrent=tend;
if(tend == tphase_end)
{
i_phase++;
i_phase %= sR->n_seq;
tphase_end +=SRT->split[i_phase];
}
}
if(tnext<100)
{
ir++;
ir%=3;
for (i=0; i<4; i++) lc->tg[i][ir]=0.0f;
}
tnext+=40;

160

}
if (sR->IB[NB] != 0 && sR->id != 106)
err += caleff(lc->tg[NB],lc->Nc, sR->IB[NB]->speed,sR->IB[0]->lanes);
if (sR->IB[SB] != 0 && sR->id != 106)
err += caleff(lc->tg[SB],lc->Sc, sR->IB[SB]->speed,sR->IB[2]->lanes);
if (sR->id == 36 )
err += caleff(lc->tg[WB],lc->Wc, sR->IB[WB]->speed,sR->IB[1]->lanes);
if (sR->id == 40 || sR->id == 108 || sR->id == 150)
err += caleff(lc->tg[EB],lc->Ec, sR->IB[EB]->speed, sR->IB[3]->lanes);
return (err);
}
int InputTimings(FILE *SRt,
SignalTiming SRT[])
{
int icycle,lp;
fscanf(SRt,"%d",&icycle);
if(icycle >= 0)
for (lp=0;lp<12;lp++)
{
fscanf(SRt,"%d, %d, %d, %d, %d, %d",
&SRT[lp].prog_ratio,
&SRT[lp].split[0], &SRT[lp].split[1],
&SRT[lp].split[2], &SRT[lp].split[3],
&SRT[lp].split[4]);
}
return(icycle);
}
float caleff(float t_g[],int lcount[], float speed, int lanes)
{
float err, exp_cars;
err=0.f;
for (int i=0; i<3; i++)
{
exp_cars = t_g[i]*speed*float(lanes);
if(exp_cars>0) err += (exp_cars - float(lcount[i]))/exp_cars;
}
return(err);
}
int InitialPhase(int &j,int split[])

161

{
int i;
i=0;
while (j< 100)
{
j+= split[i];
i++;
}
j %= 100;
return(i-1);
}
void InputLpCounts(FILE *Lpcount, LPCT a[],int i_cycle,int& total_cars)
{
int ir;
if (i_cycle%2 == 0) ir=3;
else ir=2;
for (int i=0; i<ir; i++)
{
for (int lp=0;lp<10;lp++)
{
fscanf(Lpcount,"%d,",&a[lp].Nc[i]);
total_cars += a[lp].Nc[i];
if(lp==4 || lp==7)fscanf(Lpcount,"%d,",&a[lp].Wc[i]);
else a[lp].Wc[i]=0; // skip the intersetion w/o sensor
total_cars += a[lp].Wc[i];
fscanf(Lpcount,"%d,",&a[lp].Sc[i]);
total_cars += a[lp].Sc[i];
if(lp==0 || lp==6 || lp==7 || lp==8)
fscanf(Lpcount,"%d,",&a[lp].Ec[i]);
else a[lp].Ec[i]=0; // skip the intersection w/o sensor
total_cars += a[lp].Ec[i];
}
fscanf(Lpcount,"\n");
}
}
float eff(SignalTiming *SRT,
LPCT *lc,
Intersection *sR,
int icycle)
{
int i,ir,tend,tcurrent,tnext,tphase_end,

162

i_phase,seq1,seq2;
float err;
err=0.0f;
tphase_end = SRT->prog_ratio;
i_phase=InitialPhase(tphase_end,SRT->split);
//

initial time of green to 0

if (icycle%2 ==0)
{
ir=0;
tnext=40;
for (i=0; i<4; i++) lc->tg[i][ir]=0.0f;
}
else
{
ir=2;
tnext=20;
}
tcurrent=0;
tend=tcurrent;
while (tnext<=120)
{
while (tend<tnext && tend<100)
{
seq1= sR->phase[i_phase][0]-1;
seq2= sR->phase[i_phase][1]-1;
if (tnext > tphase_end) tend = tphase_end;
else tend = tnext;
if (tnext == 120) tend = 100;
lc->tg[sR->ts[seq1]->bound][ir] +=tend-tcurrent;
if (seq2 >= 0 )
if(sR->ts[seq1]->bound != sR->ts[seq2]->bound && sR->ts[seq2]->bound != PD)
lc->tg[sR->ts[seq2]->bound][ir] +=tend-tcurrent;
tcurrent=tend;
if(tend == tphase_end)
{
i_phase++;
i_phase %= sR->n_seq;
tphase_end +=SRT->split[i_phase];
}
}

163

if(tnext<100)
{
ir++;
ir%=3;
for (i=0; i<4; i++) lc->tg[i][ir]=0.0f;
}
tnext+=40;
}
if (sR->IB[NB] != 0 && sR->id != 106)
err += caleff(lc->tg[NB],lc->Nc, sR->IB[NB]->speed,sR->IB[0]->lanes);
if (sR->IB[SB] != 0 && sR->id != 106)
err += caleff(lc->tg[SB],lc->Sc, sR->IB[SB]->speed,sR->IB[2]->lanes);
if (sR->id == 36 )
err += caleff(lc->tg[WB],lc->Wc, sR->IB[WB]->speed,sR->IB[1]->lanes);
if (sR->id == 40 || sR->id == 108 || sR->id == 150)
err += caleff(lc->tg[EB],lc->Ec, sR->IB[EB]->speed, sR->IB[3]->lanes);
return (err);
}

*************************************************************************
*

kalman.c

*************************************************************************
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <math.h>
#define LON0 9810;
#define LON3 8093;
#define LAT0 9563;
#define LAT3 1739;
#define CRIT 15000;
FILE *fr, *ffra, *fyan, *fzha, *flog;
int i, longitude=0, latitude=0, travel_time[50], Q=1000, n=43;
char current_time[6];
double H[50], P_X[50], FI[50], V[50], K[50], X[50], P[50], U_P[50], Z[50], error=0;

164

void sleep( time_t delay )


{
time_t t0, t1;
time( &t0 );
do
{
time( &t1 );
}
while (( t1 - t0 ) < delay );
}
// Transfer char a to int b
int trans(char a)
{
int b;
if (a==48) //ASCII code of "0"
b = 0;
if (a==49) //ASCII code of "1"
b = 1;
if (a==50) //ASCII code of "2"
b = 2;
if (a==51) //ASCII code of "3"
b = 3;
if (a==52) //ASCII code of "4"
b = 4;
if (a==53) //ASCII code of "5"
b = 5;
if (a==54) //ASCII code of "6"
b = 6;
if (a==55) //ASCII code of "7"
b = 7;
if (a==56) //ASCII code of "8"
b = 8;
if (a==57) //ASCII code of "9"
b = 9;
if (a==65) //ASCII code of "A"
b = 10;
if (a==66) //ASCII code of "B"
b = 11;
if (a==67) //ASCII code of "C"

165

b = 12;
if (a==68) //ASCII code of "D"
b = 13;
if (a==69) //ASCII code of "E"
b = 14;
if (a==70) //ASCII code of "F"
b = 15;
return(b);
}
void goback(char later_time[6])

// Go back 1 sec to the real start & end time

{
if (later_time[1]!=48)
{
later_time[1]--;
}
else if (later_time[0]!=48)
{
later_time[0]--;
later_time[1]=57;
}
else if (later_time[3]!=48)
{
later_time[3]--;
later_time[0]=53;
later_time[1]=57;
}
else if (later_time[2]!=48)
{
later_time[2]--;
later_time[3]=57;
later_time[1]=57;
later_time[0]=53;
}
else if (later_time[6]!=48)
{
later_time[6]--;
later_time[2]=53;
later_time[3]=57;
later_time[1]=57;
later_time[0]=53;

166

}
else if (later_time[5]!=48)
{
later_time[5]--;
later_time[6]=57;
later_time[2]=53;
later_time[3]=57;
later_time[1]=57;
later_time[0]=53;
}
else
{
later_time[5]=50;
later_time[6]=51;
later_time[2]=53;
later_time[3]=57;
later_time[1]=57;
later_time[0]=53;
}
}
void print(FILE *fw)
{
char lon[4], lat[4], speed[4], dop[4];
int error, tmp[4];
//print current_time
fseek(fr, 5, 1);
fread(current_time, 6, 1, fr);
fprintf(fw, "%c%c:%c%c:%c%c

", current_time[0], current_time[1], current_time[2],

current_time[3], current_time[4], current_time[5]);


//print longitude
fseek(fr, 4, 1);
fread(lon, 4, 1, fr);
fprintf(fw, "%c%c%c%c

", lon[0], lon[1], lon[2], lon[3]);

//print latitude
fseek(fr, 4, 1);
fread(lat, 4, 1, fr);
fprintf(fw, "%c%c%c%c

", lat[0], lat[1], lat[2], lat[3]);

//print horizontal speed


fseek(fr, 6, 1);

167

fread(speed, 4, 1, fr);
fprintf(fw, "%c%c%c.%c

", speed[0], speed[1], speed[2], speed[3]);

//print horizontal dilution of position


fseek(fr, 16, 1);
fread(dop, 2, 1, fr);
error=0;
for (i=0; i<=3; i++)
{
tmp[i]=0;
}
tmp[0] = trans(dop[0]);
tmp[1] = trans(dop[1]);
error += tmp[0] * 10;
error += tmp[1];
fprintf(fw, "%d

", error);

// Find position 0 - 3
for (i=0; i<=3; i++)
{
tmp[i]=0;
}
tmp[0] = trans(lon[0]);
tmp[1] = trans(lon[1]);
tmp[2] = trans(lon[2]);
tmp[3] = trans(lon[3]);
longitude = tmp[2]*4096 + tmp[3]*256 + tmp[0]*16 + tmp[1];
tmp[0] = trans(lat[0]);
tmp[1] = trans(lat[1]);
tmp[2] = trans(lat[2]);
tmp[3] = trans(lat[3]);
latitude = tmp[2]*4096 + tmp[3]*256 + tmp[0]*16 + tmp[1];
fseek(fr, 14, 1);
}
// Predict using Kalman Filtering
void kalman(int x, int k)
{
Z[k] = x;
if (k == 0)
{

168

H[0] = 137;
H[1] = 147;
H[2] = 157;
H[3] = 167;
H[4] = 211;
H[5] = 255;
H[6] = 299;
H[7] = 397;
H[8] = 495;
H[9] = 594;
H[10] = 586;
H[11] = 578;
H[12] = 570;
H[13] = 684;
H[14] = 798;
H[15] = 912;
H[16] = 925;
H[17] = 938;
H[18] = 951;
H[19] = 999;
H[20] = 1047;
H[21] = 1095;
H[22] = 1012;
H[23] = 929;
H[24] = 845;
H[25] = 868;
H[26] = 891;
H[27] = 914;
H[28] = 835;
H[29] = 756;
H[30] = 678;
H[31] = 759;
H[32] = 840;
H[33] = 920;
H[34] = 890;
H[35] = 860;
H[36] = 830;
H[37] = 661;
H[38] = 492;
H[39] = 323;
H[40] = 321;

169

H[41] = 319;
H[42] = 317;
FI[0] = 1;
FI[1] = H[1]/H[0];
FI[2] = H[2]/H[1];
FI[3] = H[3]/H[2];
FI[4] = H[4]/H[3];
FI[5] = H[5]/H[4];
FI[6] = H[6]/H[5];
FI[7] = H[7]/H[6];
FI[8] = H[8]/H[7];
FI[9] = H[9]/H[8];
FI[10] = H[10]/H[9];
FI[11] = H[11]/H[10];
FI[12] = H[12]/H[11];
FI[13] = H[13]/H[12];
FI[14] = H[14]/H[13];
FI[15] = H[15]/H[14];
FI[16] = H[16]/H[15];
FI[17] = H[17]/H[16];
FI[18] = H[18]/H[17];
FI[19] = H[19]/H[18];
FI[20] = H[20]/H[19];
FI[21] = H[21]/H[20];
FI[22] = H[22]/H[21];
FI[23] = H[23]/H[22];
FI[24] = H[24]/H[23];
FI[25] = H[25]/H[24];
FI[26] = H[26]/H[25];
FI[27] = H[27]/H[26];
FI[28] = H[28]/H[27];
FI[29] = H[29]/H[28];
FI[30] = H[30]/H[29];
FI[31] = H[31]/H[30];
FI[32] = H[32]/H[31];
FI[33] = H[33]/H[32];
FI[34] = H[34]/H[33];
FI[35] = H[35]/H[34];
FI[36] = H[36]/H[35];
FI[37] = H[37]/H[36];
FI[38] = H[38]/H[37];

170

FI[39] = H[39]/H[38];
FI[40] = H[40]/H[39];
FI[41] = H[41]/H[40];
FI[42] = H[42]/H[41];
U_P[0] = 0;
P_X[0] = 137;
}
else
{
X[k] = FI[k-1] * P_X[k-1];
P[k] = FI[k-1] * U_P[k-1] * FI[k-1] + Q;
V[k] = 100000;
K[k] = P[k] / (P[k] + V[k]);
P_X[k] = X[k] + K[k] * (Z[k] - X[k]);
U_P[k] = (1 - K[k]) * P[k];
printf("Predicted travel time in next interval is %5.2fsec\n", P_X[k]);
fprintf(flog, "Predicted travel time in next interval is %5.2fsec\n", P_X[k]);
}
error += fabs(P_X[k] - travel_time[k]) / travel_time[k];
}
void main()
{
char id, fra_start_time[6], fra_end_time[6], yan_start_time[6], yan_end_time[6], zha_start_time[6],
zha_end_time[6];
int j=0, fra_diff0, yan_diff0, zha_diff0, fra_prev_diff0=100000, yan_prev_diff0=100000,
zha_prev_diff0=100000, fra_diff3, yan_diff3, zha_diff3, fra_prev_diff3=1000, yan_prev_diff3=1000,
zha_prev_diff3=1000, travel_time[30];
// Initialization
for (i = 0; i <= 5; i++)
{
fra_start_time[i] = 0;
}
for (i = 0; i <= 5; i++)
{
yan_start_time[i] = 0;
}
for (i = 0; i <= 5; i++)
{
zha_start_time[i] = 0;

171

}
// Open data files
if ((fr = fopen("data.txt", "r"))==NULL)
{
printf("cannot open this file\n");
return;
}
if ((ffra = fopen("fra.txt", "w"))==NULL)
{
printf("cannot open this file\n");
return;
}
if ((fyan = fopen("yan.txt", "w"))==NULL)
{
printf("cannot open this file\n");
return;
}
if ((fzha = fopen("zha.txt", "w"))==NULL)
{
printf("cannot open this file\n");
return;
}
if ((flog = fopen("log.txt", "w"))==NULL)
{
printf("cannot open this file\n");
return;
}
// Print head
fprintf(ffra, "ID

Time(ss:mm:hh) Longitude Latitude

speed(knot) dop(%)");

fprintf(fyan, "ID

Time(ss:mm:hh) Longitude Latitude

speed(knot) dop(%)");

fprintf(fzha, "ID

Time(ss:mm:hh) Longitude Latitude

speed(knot) dop(%)");

// Main loop
while(!feof(fr))
{

172

// Print ID
fseek(fr, 4L, 1);
id=fgetc(fr);
//

printf("%c", id);
if (id==53) //ASCII code of "5"
{
fprintf(ffra, "\nFRA

");

print(ffra);
// Find position 0
fra_diff0 = (longitude - 9810)*(longitude - 9810) + (latitude - 9563)*(latitude - 9563);
if ((fra_diff0>fra_prev_diff0)&&(fra_prev_diff0<100000))
{
fprintf(ffra, "POS0");
//printf("*********************FRA--POS0*********************\n");
for (i = 0; i <= 5; i++)
{
fra_start_time[i] = current_time[i];
}
}
fra_prev_diff0 = fra_diff0;
// Find position 3
fra_diff3 = (longitude - 8093)*(longitude - 8093) + (latitude - 1739)*(latitude - 1739);
//if ((fra_diff3>fra_prev_diff3)&&(fra_prev_diff3<100000))
//printf("*********************fra--POS3*********************\n");
if
((fra_diff3>fra_prev_diff3)&&(fra_prev_diff3<100000)&&(!((fra_start_time[0]==0)&&(fra_start_time[1]
==0)&&(fra_start_time[2]==0)&&(fra_start_time[3]==0)&&(fra_start_time[4]==0)&&(fra_start_time[5]=
=0))))
{
fprintf(ffra, "POS3");
for (i = 0; i <= 5; i++)
{
fra_end_time[i] = current_time[i];
}
goback(fra_start_time);
goback(fra_end_time);
printf("\nFRA Start Time: %c%c:%c%c:%c%c\n", fra_start_time[0],
fra_start_time[1], fra_start_time[2], fra_start_time[3], fra_start_time[4], fra_start_time[5]);

173

printf("\nFRA End Time: %c%c:%c%c:%c%c\n", fra_end_time[0], fra_end_time[1],


fra_end_time[2], fra_end_time[3], fra_end_time[4], fra_end_time[5]);
fprintf(flog, "\nFRA Start Time: %c%c:%c%c:%c%c\n", fra_start_time[0],
fra_start_time[1], fra_start_time[2], fra_start_time[3], fra_start_time[4], fra_start_time[5]);
fprintf(flog, "\nFRA End Time: %c%c:%c%c:%c%c\n", fra_end_time[0],
fra_end_time[1], fra_end_time[2], fra_end_time[3], fra_end_time[4], fra_end_time[5]);
travel_time[j] = (fra_end_time[4]-fra_start_time[4])*36000 +
(fra_end_time[5]-fra_start_time[5])*3600 + (fra_end_time[2]-fra_start_time[2])*600 +
(fra_end_time[3]-fra_start_time[3])*60 + (fra_end_time[0]-fra_start_time[0])*10 +
(fra_end_time[1]-fra_start_time[1]);
printf("\nFRA Travel Time: %dsec\n\n", travel_time[j]);
fprintf(flog, "\nFRA Travel Time: %dsec\n\n", travel_time[j]);
kalman(travel_time[j], j++);
for (i = 0; i <= 5; i++)
{
fra_start_time[i] = 0;
}
}
fra_prev_diff3 = fra_diff3;
}
else if (id==55) //ASCII code of "7"
{
fprintf(fyan, "\nYAN

");

print(fyan);
// Find position 0
yan_diff0 = (longitude - 9810)*(longitude - 9810) + (latitude - 9563)*(latitude - 9563);
if ((yan_diff0>yan_prev_diff0)&&(yan_prev_diff0<100000))
{
fprintf(fyan, "POS0");
//printf("*********************YAN--POS0*********************\n");
for (i = 0; i <= 5; i++)
{
yan_start_time[i] = current_time[i];
}
}
yan_prev_diff0 = yan_diff0;
// Find position 3
yan_diff3 = (longitude - 8093)*(longitude - 8093) + (latitude - 1739)*(latitude - 1739);
//if ((yan_diff3>yan_prev_diff3)&&(yan_prev_diff3<100000))

174

//printf("*********************yan--POS3*********************\n");
if
((yan_diff3>yan_prev_diff3)&&(yan_prev_diff3<100000)&&(!((yan_start_time[0]==0)&&(yan_start_tim
e[1]==0)&&(yan_start_time[2]==0)&&(yan_start_time[3]==0)&&(yan_start_time[4]==0)&&(yan_start_ti
me[5]==0))))
{
fprintf(fyan, "POS3");
for (i = 0; i <= 5; i++)
{
yan_end_time[i] = current_time[i];
}
goback(yan_start_time);
goback(yan_end_time);
printf("\nYAN Start Time: %c%c:%c%c:%c%c\n", yan_start_time[0],
yan_start_time[1], yan_start_time[2], yan_start_time[3], yan_start_time[4], yan_start_time[5]);
printf("\nYAN End Time: %c%c:%c%c:%c%c\n", yan_end_time[0],
yan_end_time[1], yan_end_time[2], yan_end_time[3], yan_end_time[4], yan_end_time[5]);
fprintf(flog, "\nYAN Start Time: %c%c:%c%c:%c%c\n", yan_start_time[0],
yan_start_time[1], yan_start_time[2], yan_start_time[3], yan_start_time[4], yan_start_time[5]);
fprintf(flog, "\nYAN End Time: %c%c:%c%c:%c%c\n", yan_end_time[0],
yan_end_time[1], yan_end_time[2], yan_end_time[3], yan_end_time[4], yan_end_time[5]);
travel_time[j] = (yan_end_time[4]-yan_start_time[4])*36000 +
(yan_end_time[5]-yan_start_time[5])*3600 + (yan_end_time[2]-yan_start_time[2])*600 +
(yan_end_time[3]-yan_start_time[3])*60 + (yan_end_time[0]-yan_start_time[0])*10 +
(yan_end_time[1]-yan_start_time[1]);
printf("\nYAN Travel Time: %dsec\n\n", travel_time[j]);
fprintf(flog, "\nYAN Travel Time: %dsec\n\n", travel_time[j]);
kalman(travel_time[j], j++);
for (i = 0; i <= 5; i++)
{
yan_start_time[i] = 0;
}
}
yan_prev_diff3 = yan_diff3;
}
else if (id==67) //ASCII code of "C"
{
fprintf(fzha, "\nZHA

");

print(fzha);
// Find position 0

175

zha_diff0 = (longitude - 9810)*(longitude - 9810) + (latitude - 9563)*(latitude - 9563);


if ((zha_diff0>zha_prev_diff0)&&(zha_prev_diff0<100000))
{
fprintf(fzha, "POS0");
//printf("*********************zha--POS0*********************\n");
for (i = 0; i <= 5; i++)
{
zha_start_time[i] = current_time[i];
}
}
zha_prev_diff0 = zha_diff0;
// Find position 3
zha_diff3 = (longitude - 8093)*(longitude - 8093) + (latitude - 1739)*(latitude - 1739);
//if ((zha_diff3>zha_prev_diff3)&&(zha_prev_diff3<100000))
//printf("*********************zha--POS3*********************\n");
if
((zha_diff3>zha_prev_diff3)&&(zha_prev_diff3<100000)&&(!((zha_start_time[0]==0)&&(zha_start_time
[1]==0)&&(zha_start_time[2]==0)&&(zha_start_time[3]==0)&&(zha_start_time[4]==0)&&(zha_start_tim
e[5]==0))))
{
fprintf(fzha, "POS3");
for (i = 0; i <= 5; i++)
{
zha_end_time[i] = current_time[i];
}
goback(zha_start_time);
goback(zha_end_time);
printf("\nZHA Start Time: %c%c:%c%c:%c%c\n", zha_start_time[0],
zha_start_time[1], zha_start_time[2], zha_start_time[3], zha_start_time[4], zha_start_time[5]);
printf("\nZHA End Time: %c%c:%c%c:%c%c\n", zha_end_time[0], zha_end_time[1],
zha_end_time[2], zha_end_time[3], zha_end_time[4], zha_end_time[5]);
fprintf(flog, "\nZHA Start Time: %c%c:%c%c:%c%c\n", zha_start_time[0],
zha_start_time[1], zha_start_time[2], zha_start_time[3], zha_start_time[4], zha_start_time[5]);
fprintf(flog, "\nZHA End Time: %c%c:%c%c:%c%c\n", zha_end_time[0],
zha_end_time[1], zha_end_time[2], zha_end_time[3], zha_end_time[4], zha_end_time[5]);
travel_time[j] = (zha_end_time[4]-zha_start_time[4])*36000 +
(zha_end_time[5]-zha_start_time[5])*3600 + (zha_end_time[2]-zha_start_time[2])*600 +
(zha_end_time[3]-zha_start_time[3])*60 + (zha_end_time[0]-zha_start_time[0])*10 +
(zha_end_time[1]-zha_start_time[1]);
printf("\nZHA Travel Time: %dsec\n\n", travel_time[j]);

176

fprintf(flog, "\nZHA Travel Time: %dsec\n\n", travel_time[j]);


kalman(travel_time[j], j++);
for (i = 0; i <= 5; i++)
{
zha_start_time[i] = 0;
}
}
zha_prev_diff3 = zha_diff3;
}
}
MARE = error / n;
printf("MARE is %5.5f\n", MARE);
fclose(fr);
fclose(ffra);
fclose(fyan);
fclose(fzha);
fclose(flog);
}

177

You might also like