-
Notifications
You must be signed in to change notification settings - Fork 0
/
generateDataFromOD.py
219 lines (194 loc) · 7.38 KB
/
generateDataFromOD.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
import random
import os
import subprocess
import shutil
import pickle
import numpy as np
import xml.etree.ElementTree as ET
from functools import partial
from itertools import repeat
from multiprocessing import Pool, freeze_support
from config import config
cfg = config()
DEBUG = cfg.debug
continuePrevious = cfg.continuePrevious
NsamplesPrior = cfg.NsamplesPrior
dT = cfg.dT # przedział czasu w minutach
N = cfg.N # czas trwania symulacji jako wielokrotność dT
tazPath = cfg.tazPath
os.chdir(r'.\sumo\detectors')
subprocess.call(['python', 'detector.py' ,str(dT*60)], shell=False)
os.chdir(r'..\..')
edges = []
with open(cfg.edgesPath) as file:
lines = file.readlines()
for line in lines:
line = line.split(' ')
if len(line) > 4:
edges.append(line[3])
m = len(edges)
def ToStr(Th, Tmin):
if Tmin < 10:
return str(Th)+'.0'+str(Tmin)
return str(Th)+'.'+str(Tmin)
tazs = ET.parse(tazPath).getroot()
tazslist = tazs.findall('taz')
n = len(tazslist)
OD_base_csv = np.genfromtxt('OD.txt', delimiter=',',dtype=str)
IDlist = list(OD_base_csv[0])
OD_index = {}
for idx,node in enumerate(tazslist):
nodeID = node.get('id')
ID = nodeID.split('_')[-1]
OD_index[idx] = IDlist.index(ID)
OD_base_csv[0][idx+1]
OD_base = np.zeros((n,n))
OD_base_csv = np.genfromtxt('OD.txt', delimiter=',')
for oidx,o in enumerate(tazslist):
for didx,d in enumerate(tazslist):
OD_base[oidx][didx] = OD_base_csv[OD_index[oidx]][OD_index[didx]]
OD_base /= 60*6 / dT
OD_base /= 5
ODfrac, ODfloor = np.modf(OD_base)
DOD_base = np.zeros((n,n,N))
for tn in range(N):
DOD_base[:,:,tn] = OD_base
odFile = open(cfg.ODgenPatternPath, 'wb')
pickle.dump(DOD_base, odFile)
odFile.close()
ODfrac, ODfloor = np.modf(DOD_base)
MIN = None
MAX = None
InputDir = None
SumoDir = None
OutputDir = None
def init(InDir, SumDir, OutDir, MINfrac, MAXfrac):
global InputDir
global OutputDir
global SumoDir
InputDir = InDir
OutputDir = OutDir
SumoDir = SumDir
global ODfrac, ODfloor, MAX, MIN
MIN = MINfrac * ODfloor
MAX = MAXfrac * ODfloor + 1.00
#exit()
netFile = cfg.netFile
od2tripsOptions = cfg.od2tripsOptions
durouterOptions = cfg.durouterOptions
sumoOptions = cfg.sumoOptions
def generateSample(sample):
global OutputDir, InputDir, SumoDir, ODfrac, ODfloor, MIN, MAX, n, N, m
InDir = InputDir+'\\In'+str(sample)
SimDir = SumoDir+'\\SUMO'+str(sample)
os.mkdir(InDir)
os.mkdir(SimDir)
print(sample)
InputSample = np.zeros((n,n,N))
OutputSample = np.zeros((N,m))
shutil.copytree(cfg.sumoDir, SimDir+'\\sumo')
SimDir += '\\'+cfg.sumoDir+'\\'
# Create OD files
T0min = 0 # czas początkowy w minutach
T0h = 0 # czas początkowy w godzinach
T1min = 0 # czas końcowy w minutach
T1h = 0 # czas końcowy w godzinach
files = ''
InputOD = np.random.randint(MIN, MAX) * (ODfloor > 0)
for i in range(N):
T1min += dT
T1h += int(T1min/60)
T1min -= (int(T1min/60)) * 60
files += InDir+'\\OD'+str(i)+'.od,'
file = open(InDir+'\\OD'+str(i)+'.od', 'w')
file.write('$O;D2\n')
file.write('* From-Time\tTo-Time\n')
file.write(ToStr(T0h, T0min)+' '+ToStr(T1h, T1min)+'\n')
file.write('* Factor\n')
file.write('1.00\n')
file.write('*\n')
file.write('* some\n')
file.write('* additional\n')
file.write('* comments\n')
file.write('* \tFROM\tTO\tCOUNT\n')
for oidx,o in enumerate(tazslist):
for didx,d in enumerate(tazslist):
if oidx==didx:
InputSample[oidx][didx][i] = 0
continue
count = InputOD[oidx,didx,i]
InputSample[oidx][didx][i] = count
file.write('\t'+o.get('id')+'\t\t\t\t'+
d.get('id')+'\t\t\t'+str(int(count))+'\n')
file.close()
T0min = T1min
T0h = T1h
# Save dynamic OD to pkl file
inFile = open(InDir+'\\In'+str(sample)+'.pkl', 'wb')
pickle.dump(InputSample, inFile)
inFile.close()
# Generate output trace
subprocess.call(['od2trips','-l', SimDir+'od2tripslog.txt', '-n', tazPath, '-d', files[:-1], '-o', SimDir+'od_file.odtrips.xml']+od2tripsOptions, shell=True)
subprocess.call(['duarouter','-n',SimDir+netFile,'--route-files', SimDir+'od_file.odtrips.xml','-o',SimDir+'od_route_file.odtrips.rou.xml','-l', SimDir+'dualog.txt']+durouterOptions, shell=True)
subprocess.call(['sumo', '-a', SimDir+'detectors\\e1.add.xml','-e',str(N*dT*60),'-n',SimDir+netFile,'-r', SimDir+'od_route_file.odtrips.rou.xml','-l', SimDir+'sumolog.txt']+sumoOptions, shell=True)
# Get link counts and turning movement flows
linkFlow = {}
fcd = ET.parse(SimDir+'detectors\\e1output.xml').getroot()
for link in fcd.findall('interval'):
tn = int(float(link.get('begin'))/(dT*60))
edge = link.get('id')[6:-2]
try:
linkFlow[(tn, edge)] += float(link.get('nVehContrib'))
except KeyError:
linkFlow[(tn, edge)] = float(link.get('nVehContrib'))
for tn in range(N):
for i,edge in enumerate(edges):
OutputSample[tn][i] = linkFlow[(tn, edge)]
print(np.sum(OutputSample))
# Save link flows to pkl file
outFile = open(OutputDir+'\\Out'+str(sample)+'.pkl', 'wb')
pickle.dump(OutputSample, outFile)
outFile.close()
shutil.rmtree(SimDir+'cfg', ignore_errors=True)
os.system('del '+SimDir+'*.xml')
return InputSample, OutputSample
def generateData(InputDir, SumoDir, OutputDir, MINfrac, MAXfrac, Nsamples, cont, processes=None):
init(InputDir, SumoDir, OutputDir, MINfrac, MAXfrac)
begin = 0
if cont==False:
shutil.rmtree(InputDir, ignore_errors=True)
shutil.rmtree(SumoDir, ignore_errors=True)
shutil.rmtree(OutputDir, ignore_errors=True)
os.mkdir(InputDir)
os.mkdir(SumoDir)
os.mkdir(OutputDir)
else:
InputFile0 = open(InputDir+'\\In.pkl', 'rb')
Input0 = pickle.load(InputFile0)
InputFile0.close()
OutputFile0 = open(OutputDir+'\\Out.pkl', 'rb')
Output0 = pickle.load(OutputFile0)
OutputFile0.close()
begin = np.shape(Input0)[0]
with Pool(initializer = init, initargs = (InputDir, SumoDir, OutputDir, MINfrac, MAXfrac), processes=processes) as pool:
M = pool.starmap(generateSample, zip(range(begin,Nsamples+begin)))
Input, Output = zip(*M)
Input = np.array(Input)
Output = np.array(Output)
if cont:
Input = np.concatenate((Input0,Input),axis=0)
Output = np.concatenate((Output0,Output),axis=0)
# Save all OD flows to pkl file
inFile = open(InputDir+'\\In.pkl', 'wb')
pickle.dump(Input, inFile)
inFile.close()
# Save all link counts to pkl file
outFile = open(OutputDir+'\\Out.pkl', 'wb')
pickle.dump(Output, outFile)
outFile.close()
if __name__=="__main__":
freeze_support()
generateData(cfg.InputDirPrior,cfg.SumoDirPrior,cfg.OutputDirPrior,cfg.MINprior,cfg.MAXprior,cfg.NsamplesPrior, continuePrevious, processes=cfg.processes)
if continuePrevious==False:
generateData(cfg.InputDirHist,cfg.SumoDirHist,cfg.OutputDirHist,cfg.MINreal,cfg.MAXreal,cfg.NsamplesHist, False, processes=cfg.processes)
generateData(cfg.InputDirRealTime,cfg.SumoDirRealTime,cfg.OutputDirRealTime, cfg.MINreal, cfg.MAXreal, cfg.NsamplesReal, False, processes=cfg.processes)