Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
eclipse
GitHub Repository: eclipse/sumo
Path: blob/main/tools/assign/cadytsIterate.py
169673 views
1
#!/usr/bin/env python
2
# -*- coding: utf-8 -*-
3
# Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo
4
# Copyright (C) 2010-2025 German Aerospace Center (DLR) and others.
5
# This program and the accompanying materials are made available under the
6
# terms of the Eclipse Public License 2.0 which is available at
7
# https://www.eclipse.org/legal/epl-2.0/
8
# This Source Code may also be made available under the following Secondary
9
# Licenses when the conditions for such availability set forth in the Eclipse
10
# Public License 2.0 are satisfied: GNU General Public License, version 2
11
# or later which is available at
12
# https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
13
# SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
14
15
# @file cadytsIterate.py
16
# @author Jakob Erdmann
17
# @author Yun-Pang Floetteroed
18
# @author Daniel Krajzewicz
19
# @author Michael Behrisch
20
# @author Mirko Barthauer
21
# @date 2010-09-15
22
23
"""
24
- Run Cadyts to calibrate the SUMO simulation with given routes (including alternatives and
25
exit time) for each edge and traffic measurements.
26
- Edges' exit-time information can be obtained by setting the option "exit-times" True when
27
running DUARouter/duaIterate.py
28
- The file format of the route alternatives (together with exit-times info) corresponds to
29
the DUAROUTER assignment result (*.alt.xml)
30
- Respective traffic zones information has to exist in the given route files.
31
"""
32
from __future__ import absolute_import
33
from __future__ import print_function
34
import os
35
import sys
36
import glob
37
from datetime import datetime
38
from duaIterate import call, writeSUMOConf, addGenericOptions, generateEdgedataAddFile
39
40
if 'SUMO_HOME' in os.environ:
41
TOOLS_DIR = os.path.join(os.environ['SUMO_HOME'], 'tools')
42
sys.path.append(TOOLS_DIR)
43
import sumolib # noqa
44
else:
45
sys.exit("please declare environment variable 'SUMO_HOME'")
46
47
48
def initOptions():
49
jars = glob.glob(os.path.join(TOOLS_DIR, "contributed", "calibration", "*", "target", "*.jar")) + \
50
glob.glob(os.path.join(TOOLS_DIR, "..", "bin", "*.jar"))
51
argParser = sumolib.options.ArgumentParser()
52
addGenericOptions(argParser)
53
argParser.add_argument("-r", "--route-alternatives", dest="routes", type=argParser.route_file,
54
help="route alternatives from sumo (comma separated list, mandatory)", metavar="FILE")
55
argParser.add_argument("-d", "--detector-values", dest="detvals", type=argParser.file,
56
help="adapt to the flow on the given edges", metavar="FILE")
57
argParser.add_argument("--classpath", dest="classpath", default=os.pathsep.join(jars), type=str,
58
help="classpath for the calibrator [default: %(default)s]")
59
argParser.add_argument("-l", "--last-calibration-step", dest="calibStep",
60
type=int, default=100, help="last step of the calibration [default: %(default)s]")
61
argParser.add_argument("-S", "--demandscale", dest="demandscale",
62
type=float, default=2., help="scaled demand [default: %(default)s]")
63
argParser.add_argument("-F", "--freezeit", dest="freezeit",
64
type=int, default=85, help="define the number of iterations for stablizing the results " +
65
"in the DTA-calibration")
66
argParser.add_argument("-V", "--varscale", dest="varscale",
67
type=float, default=1., help="define variance of the measured traffic flows for the" +
68
"DTA-calibration")
69
argParser.add_argument("-P", "--PREPITS", type=int, dest="PREPITS",
70
default=5, help="number of preparatory iterations")
71
argParser.add_argument("-W", "--evaluation-prefix", dest="evalprefix",
72
help="prefix of flow evaluation files; only for the calibration with use of detector data")
73
argParser.add_argument("-Y", "--bruteforce", action="store_true", dest="bruteforce",
74
default=False, help="fit the traffic counts as accurate as possible")
75
argParser.add_argument("-Z", "--mincountstddev", type=float, dest="mincountstddev",
76
default=25., help="minimal traffic count standard deviation")
77
argParser.add_argument("-O", "--overridett", action="store_true", dest="overridett",
78
default=False, help="override depart times according to updated link travel times")
79
argParser.add_argument("-E", "--disable-summary", "--disable-emissions", action="store_true", dest="noSummary",
80
default=False, help="No summaries are written by the simulation")
81
argParser.add_argument("-T", "--disable-tripinfos", action="store_true", dest="noTripinfo",
82
default=False, help="No tripinfos are written by the simulation")
83
argParser.add_argument("-M", "--matrix-prefix", dest="fmaprefix", type=str,
84
help="prefix of OD matrix files in visum format")
85
argParser.add_argument("-N", "--clone-postfix", dest="clonepostfix", type=str,
86
default='-CLONE', help="postfix attached to clone ids")
87
argParser.add_argument("-X", "--cntfirstlink", action="store_true", dest="cntfirstlink",
88
default=False, help="if entering vehicles are assumed to cross the upstream sensor of" +
89
"their entry link")
90
argParser.add_argument("-K", "--cntlastlink", action="store_true", dest="cntlastlink",
91
default=False, help="if exiting vehicles are assumed to cross the upstream sensor of" +
92
"their exit link")
93
argParser.add_argument("remaining_args", nargs='*')
94
return argParser
95
96
97
def main():
98
argParser = initOptions()
99
100
options = argParser.parse_args()
101
if not options.net or not options.routes or not options.detvals:
102
argParser.error("--net-file, --routes and --detector-values have to be given!")
103
if "cadyts" not in options.classpath:
104
print("""Warning! No cadyts.jar has been found or given. Please use the --classpath option
105
to point to an existing jar file. You may also download it
106
from https://sumo.dlr.de/daily/cadyts.jar and place it in %s/bin.""" % os.environ['SUMO_HOME'], file=sys.stderr)
107
sumoBinary = sumolib.checkBinary("sumo", options.path)
108
calibrator = ["java", "-cp", options.classpath, "-Xmx1G",
109
"floetteroed.cadyts.interfaces.sumo.SumoController"]
110
log = open("cadySumo-log.txt", "w+")
111
112
# calibration init
113
starttime = datetime.now()
114
evalprefix = None
115
if options.evalprefix:
116
evalprefix = options.evalprefix
117
EDGEDATA_ADD = "edgedata.add.xml"
118
119
# begin the calibration
120
if options.fmaprefix:
121
call(calibrator + ["INIT", "-varscale", options.varscale, "-freezeit", options.freezeit,
122
"-measfile", options.detvals, "-binsize", options.aggregation, "-PREPITS", options.PREPITS,
123
"-bruteforce", options.bruteforce, "-demandscale", options.demandscale,
124
"-mincountstddev", options.mincountstddev, "-overridett", options.overridett,
125
"-clonepostfix", options.clonepostfix, "-fmaprefix", options.fmaprefix,
126
"-cntfirstlink", options.cntfirstlink, "-cntlastlink", options.cntlastlink], log)
127
else:
128
call(calibrator + ["INIT", "-varscale", options.varscale, "-freezeit", options.freezeit,
129
"-measfile", options.detvals, "-binsize", options.aggregation, "-PREPITS", options.PREPITS,
130
"-bruteforce", options.bruteforce, "-demandscale", options.demandscale,
131
"-mincountstddev", options.mincountstddev, "-overridett", options.overridett,
132
"-clonepostfix", options.clonepostfix, "-cntfirstlink", options.cntfirstlink,
133
"-cntlastlink", options.cntlastlink], log)
134
#
135
generateEdgedataAddFile(EDGEDATA_ADD, options)
136
for step in range(options.calibStep):
137
print('calibration step:', step)
138
files = []
139
current_directory = os.getcwd()
140
final_directory = os.path.join(current_directory, "%03i" % step)
141
if not os.path.exists(final_directory):
142
os.makedirs(final_directory)
143
144
# calibration choice
145
firstRoute = options.routes.split(",")[0]
146
routname = os.path.basename(firstRoute)
147
if '_' in routname:
148
output = "%s_%03i.cal.xml" % (routname[:routname.rfind('_')], step)
149
else:
150
output = "%s_%03i.cal.xml" % (routname[:routname.find('.')], step)
151
152
call(calibrator + ["CHOICE", "-choicesetfile",
153
options.routes, "-choicefile", "%s/%s" % (step, output)], log)
154
files.append(output)
155
156
# simulation
157
print(">> Running simulation")
158
btime = datetime.now()
159
print(">>> Begin time: %s" % btime)
160
writeSUMOConf(sumoBinary, step, options, [], ",".join(files))
161
call([sumoBinary, "-c", "%03i/iteration_%03i.sumocfg" % (step, step)], log)
162
etime = datetime.now()
163
print(">>> End time: %s" % etime)
164
print(">>> Duration: %s" % (etime - btime))
165
print("<<")
166
167
# calibration update
168
if evalprefix:
169
call(calibrator + ["UPDATE", "-netfile", "%s/dump_%03i_%s.xml" % (
170
step, step, options.aggregation), "-flowfile", "%s_%03i.txt" % (evalprefix, step)], log)
171
else:
172
call(calibrator + ["UPDATE", "-netfile",
173
"%03i/dump_%03i_%s.xml" % (step, step, options.aggregation)], log)
174
print("< Step %s ended (duration: %s)" %
175
(step, datetime.now() - btime))
176
print("------------------\n")
177
log.flush()
178
179
print("calibration ended (duration: %s)" % (datetime.now() - starttime))
180
log.close()
181
182
183
pyPath = os.path.abspath(os.path.dirname(sys.argv[0]))
184
if __name__ == "__main__":
185
main()
186
187