Professional Documents
Culture Documents
Nan Zhang
JULY 2004
UNIVERSITY OF MINNESOTA
Nan Zhang
Advisers:
________________________
Signature
_______________________
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
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
CMS
DGPS
DOD
Department of Defense
GPS
ITS
MARE
Mn/DOT
MOE
Measure of Effectiveness
NATSRL
NN
Neural Networks
SPSA
SWARM
VI
LIST OF FIGURES
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
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.
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.
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.2 Data counter and road tube used on Superior Street.
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.
10
k +1 = k a k g k (k )
(3.1)
= k.
Given a loss function L( ) , the optimization problem can be translated into
.........................................................
g k ( ) = .........................................................
.........................................................
[ L( + c k k ) L ( c k k )] / 2c k kp
Eq. (3.2)
11
3.2 Implementation
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
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.
where c k and k satisfy the regularity conditions in Spall and Cristion (1992, 1994)
[1, 4].
2.
4.
replacing k + c k k . Form L (k c k k ) .
14
5.
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.
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
The 14 averaged traffic volume (vehicles per hour divided by cycles per
The 6 outputs (vectors of timing splits) from the previous control solution.
16
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
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.
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
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.
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.
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.
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.
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
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
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
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
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
(%)
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
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.
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
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
Note:
1.
Except the tolerance index, all the values of the other performance index are
given by Synchro.
2.
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
Travel time is the most common way that users measure the quality of their
trip.
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.
33
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.
Equipment from GPSFlight Corporation is used to realize the GPS test vehicle
technique. The telemetry platform consists of:
z
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
so up to 7 different
networks can operate in the same location without interfering with each other as well.
z
37
half-wavelength antenna and the antenna for the receiver from 2 dB RPSMA antenna to
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
Map library which enables any bit-mapped map to be used for plotting in
real-time
38
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
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.
39
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.
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
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
Eq. (6.1)
where
x k = (n 1) process state vector at time tk.
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)
Pk = E[ek ek ] = E[( x k x k )( x k x k ) T ]
Eq. (6.4)
Eq. (6.5)
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
Eq. (6.9)
With the results mentioned above, the Kalman filter loop can be expressed as Fig 6.1.
44
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.
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
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.
Sample travel time data for the UMD Graduation Ceremony on May 15, 2004 is
graphed in Fig. 7.1.
49
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.
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.
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.
May 15
UMD
Commencement
Prediction
Time Interval
(min.)
Number
of Intervals
3.0
15
MARE
(%)
17.61
Note:
i =1
xi xi
xi
n
100%
52
Prediction Time
Interval (min.)
3.0
3.0
3.0
Number of
Intervals
15
15
15
MARE (%)
24.98
25.17
21.25
53
54
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.
Prediction Time
Interval (min.)
Number of
Intervals
MARE (%)
5.0
33.44
3.0
21.20
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
56
57
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
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
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
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
67
//
//}}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
//
//}}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,
6,
5,
64, 15, 7,
30, 6,
6,
6, 3,
6,
5,
40, 8,
6,
5,
40, 8,
6,
5,
40, 8,
6,
6, 8,
6,
6, 8, 18,100,
6,
6, 8,
5,
5,
30, 6,
62, 8,
17, 8,
5,
58, 8,
22,102, 17, 8,
5,
60, 8,
6,
5,
49, 8,
6,
6,10, 32,104,
20, 8,
5,
54, 10,
6,
6,10, 30,118,
20, 8,
5,
67, 10,
8,10, 38,104,
20, 8,
5,
68, 10,
8,10, 30,102,
20, 8,
5,
66, 10,
8,12, 28,108,
20, 8,
5,
72, 10,
8,12, 34,102,
20, 8,
5,
69, 10,
8,
8,12, 32,122,
20, 8,
5,
64, 10,
8,
8,14, 28,106,
25, 8,
5,
55, 12,
8,
8,14, 42,102,
25, 8,
5,
84, 12,
8,
8,14, 30,124,
25, 8,
5,
48, 12,
8,
8,14, 42,124,
25, 8,
5,
61, 12,
8,
8,16, 42,100,
25, 8,
5,
88, 12,
8,
8,16, 40,128,
25, 8,
5,
76, 12,
8,
8,16, 34,128,
20, 8,
5,
84, 12,
8,
8,16, 34,128,
20, 8,
5,
65, 12
70
};
cycle/=2;
**************************************************************************************
*
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
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
}
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"
//
//
int i_phase;
//
//
turn,
//
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[] =
{
// 5Ave - I35N
Timings LST3[] =
{
// 5Ave - Superior St
Timings LST4[] =
{
78
//
//
int id;
//
//
//
road_section nb;
//
road_section sb;
//
road_section wb;
//
road_section eb;
//
int
//
int phases[6][2]
phases sequence
//
double pro_rate
prograsive rates
//
double phase_split[5]
//
double even_times[5]
Intersection L1
= {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
= {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
80
{
protected:
CIntersections();
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);
//}}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
84
*/
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);
}
//
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;
}
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
m_wndToolBar;
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,
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();
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);
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;
double *wb2;
double *wb3;
double *w1;
double *w2;
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
99
100
101
**************************************************************************************
*
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
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
//
//
double out[6];
// previousely estimated light setting from the output of neural-net
//
timing splits
//
//
double time_of_day; //
} in;
double cycle_time_in_hour;
public:
CRoadNet();
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
//
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);
//
}
}
//////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
void CRoadNet::CycleTraf(CFile *Lcount)
{
int i,m_s;
double time_in_cycle = 0.;
SetupPhases();
for (i=0; i<10;i++)
{
// 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;
//
//
//
char a='10';
//
//
//
/*
ofstream ofile();
);
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
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
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
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();
/*
//
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,
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;
//
// 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,
125,
125,
125,
125,
125,
125,
125,
125,
125,
125,
125,
125,
125,
125,
125,
125,
125,
125,
125,
125,
125,
125,
125,
125,
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 left_turn_rate;
//
//
//
float right_turn_rate;
float length;
// in number of cars
//
int loop_count;
//
//
int cars_on_road;
//
light_phase light;
//
light_phase LeftLight;
static RoadSector
// 5Ave & I35N
NB_5Ave_I35N
SB_5Ave_I35N
EB_5Ave_I35N
= { 1, EB,2, 0, 0, 1.76f,100.0f,.07f,.06f},
SB_5Ave_I35S
WB_5Ave_I35S
= { 2, WB,2, 0, 0, 1.76f,100.0f,.09f,.04f},
SB_5Ave_Superior
EB_5Ave_Superior
WB_5Ave_Superior
SB_Lake_Railroad
122
EB_Lake_Railroad
WB_Lake_Railroad
SB_Canal_I35
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();
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);
//}}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;
cars_in_sector_moving = cars_on_road;
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
//
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
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
//
if (Rd->left_lanes > 0)
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
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).
//
next_layer_dtime =3.13;
}
**************************************************************************************
*
StdAfx.h
**************************************************************************************
// stdafx.h : include file for standard system include files,
//
//
//
#if !defined(AFX_STDAFX_H__6D3D0617_C6EE_11D4_8AA4_0050DACD1682__INCLUDED_)
#define AFX_STDAFX_H__6D3D0617_C6EE_11D4_8AA4_0050DACD1682__INCLUDED_
134
#include <afxext.h>
// MFC extensions
#include <afxdisp.h>
#include <afxdtctl.h>
#ifndef _AFX_NO_AFXCMN_SUPPORT
#include <afxcmn.h>
#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;
//
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
//
//
#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.
//
//}}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.
//
//}}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
//
#ifdef _AFXDLL
Enable3dControls();
#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
//
CMultiDocTemplate* pDocTemplate;
pDocTemplate = new CMultiDocTemplate(
IDR_TRAFDETYPE,
RUNTIME_CLASS(CTrafDefDoc),
140
/////////////////////////////////////////////////////////////////////////////
// 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.
//
//}}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.
//
//}}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
//
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;
//
//
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;
//}
//
/*
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"
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
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
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
/*
}
/////////////////////////////////////////////////////////////////////////////
// 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
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);
//
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);
//
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
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])
{
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
//print latitude
fseek(fr, 4, 1);
fread(lat, 4, 1, fr);
fprintf(fw, "%c%c%c%c
167
fread(speed, 4, 1, fr);
fprintf(fw, "%c%c%c.%c
", 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
speed(knot) dop(%)");
fprintf(fyan, "ID
speed(knot) dop(%)");
fprintf(fzha, "ID
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
");
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
176
177