Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
eclipse
GitHub Repository: eclipse/sumo
Path: blob/main/tools/contributed/sumopy/coremodules/simulation/sumo.py
169689 views
1
# Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo
2
# Copyright (C) 2016-2025 German Aerospace Center (DLR) and others.
3
# SUMOPy module
4
# Copyright (C) 2012-2021 University of Bologna - DICAM
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 sumo.py
16
# @author Joerg Schweizer
17
# @date 2012
18
19
from agilepy.lib_base.processes import Process, CmlMixin, ff, call, P, filepathlist_to_filepathstring, Options
20
from coremodules.scenario.scenario import load_scenario
21
from results import Simresults
22
from coremodules.network.network import SumoIdsConf
23
import agilepy.lib_base.xmlman as xm
24
import agilepy.lib_base.arrayman as am
25
import agilepy.lib_base.classman as cm
26
import numpy as np
27
from coremodules.modules_common import *
28
import os
29
import sys
30
import string
31
import time
32
import shutil # for deleting directory trees
33
from collections import OrderedDict
34
from xml.sax import saxutils, parse, handler
35
if __name__ == '__main__':
36
try:
37
APPDIR = os.path.dirname(os.path.abspath(__file__))
38
except:
39
APPDIR = os.path.dirname(os.path.abspath(sys.argv[0]))
40
SUMOPYDIR = os.path.join(APPDIR, '..', '..')
41
sys.path.append(SUMOPYDIR)
42
try:
43
if 'SUMO_HOME' in os.environ:
44
tools = os.path.join(os.environ['SUMO_HOME'], 'tools')
45
sys.path.append(tools)
46
else:
47
print("please declare environment variable 'SUMO_HOME'")
48
49
import traci
50
import traci.constants as tc
51
52
53
except:
54
print 'WARNING: No module traci in syspath. Please provide SUMO_HOME.'
55
56
traci = None
57
58
#from agilepy.lib_base.misc import get_inversemap
59
#from agilepy.lib_base.geometry import find_area
60
61
62
def write_netconfig(filename_netconfig, filename_net,
63
filename_routes='',
64
filename_poly=None,
65
dirname_output='',
66
starttime=None, stoptime=None,
67
time_step=1.0,
68
time_to_teleport=-1,
69
pedestrian_model='None',
70
width_sublanes=-1.0,
71
filename_ptstops=None,
72
filepath_output_vehroute=None,
73
filepath_output_tripinfo=None,
74
is_tripdata_unfinished=False,
75
filepath_output_edgedata=None,
76
filepath_output_lanedata=None,
77
filepath_output_edgeemissions=None,
78
filepath_output_laneemissions=None,
79
filepath_output_edgenoise=None,
80
filepath_output_lanenoise=None,
81
filepath_output_electricenergy=None,
82
filepath_output_fcd=None,
83
filepath_output_summary=None,
84
freq=60,
85
is_exclude_emptyedges=False,
86
is_exclude_emptylanes=False,
87
is_ignore_route_errors=True,
88
filepath_gui=None,
89
seed=1025,
90
is_openscenegraph=False,
91
width_pedestrian_striping=0.49,
92
slowdownfactor_pedestrian_striping=0.2,
93
jamtime_pedestrian_striping=20,
94
jamtime_pedestrian_crossing_striping=10,
95
is_collission_check_junctions=True,
96
is_ignore_accidents=False,
97
collission_action='teleport',
98
is_ballistic_integrator=False,
99
is_rerouting=False,
100
probability_rerouting=0.0,
101
is_deterministic_rerouting=False,
102
period_rerouting=0,
103
preperiod_rerouting=60,
104
adaptationinterval_rerouting=1,
105
adaptationweight_rerouting=0.0,
106
adaptationsteps_rerouting=180,
107
taxiservice=None,
108
):
109
"""
110
filename_netconfig = output filename of network config file without path
111
filename_net = input filename of network file without path
112
filename_rou = input filename of routes file without path
113
filename_poly = input filename of polygons file without path
114
dirname_output = directory where config, network, route and poly file reside
115
"""
116
# print 'write_netconfig >>%s<<'%filename_netconfig
117
# print ' filename_poly=>>%s<<'%filename_poly
118
if dirname_output:
119
filepath_netconfig = os.path.join(dirname_output, filename_netconfig)
120
else:
121
filepath_netconfig = filename_netconfig
122
123
if (filepath_output_edgedata is not None)\
124
| (filepath_output_lanedata is not None)\
125
| (filepath_output_edgeemissions is not None)\
126
| (filepath_output_laneemissions is not None)\
127
| (filepath_output_edgenoise is not None)\
128
| (filepath_output_lanenoise is not None)\
129
| (filepath_output_electricenergy is not None):
130
# filename of additional files:
131
filename_add = string.join(filename_netconfig.split('.')[:-2]+['outc.xml'], '.')
132
filepath_add = os.path.join(dirname_output, filename_add)
133
# print ' filepath_add',filepath_add
134
else:
135
filename_add = None
136
137
simfile = open(filepath_netconfig, 'w')
138
139
simfile.write(
140
"""<?xml version="1.0"?>
141
<configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://sumo.sf.net/xsd/sumoConfiguration.xsd">
142
<input>\n""")
143
144
simfile.write(' <net-file value="%s"/>\n' % filename_net)
145
146
if filename_routes != "":
147
simfile.write(' <route-files value="%s"/>\n' % filename_routes)
148
149
# print ' filename_add',filename_add
150
# print ' filepath_add',filepath_add
151
simfile.write(' <additional-files value="')
152
153
filenames_add = set([filename_poly, filename_add, filename_ptstops])
154
filenames_add.discard(None)
155
filenames_add = list(filenames_add)
156
157
if len(filenames_add) > 0:
158
for filename in filenames_add[:-1]:
159
simfile.write('%s,' % filename)
160
simfile.write('%s' % filenames_add[-1])
161
162
simfile.write('" />\n')
163
simfile.write('</input>\n')
164
165
if (starttime is not None) & (stoptime is not None):
166
simfile.write(
167
"""
168
<time>
169
<begin value="%s"/>
170
<end value="%s"/>
171
</time>
172
""" % (starttime, stoptime))
173
174
simfile.write('<time-to-teleport value="%s"/>\n' % time_to_teleport)
175
simfile.write('<seed value="%s"/>\n' % seed)
176
simfile.write('<step-length value="%s"/>\n' % time_step)
177
178
simfile.write('<ignore-route-errors value="%s"/>\n' % is_ignore_route_errors)
179
180
if is_ballistic_integrator:
181
simfile.write('<step-method.ballistic value="True"/>\n')
182
183
if width_sublanes > 0:
184
simfile.write('<lateral-resolution value="%s"/>\n' % width_sublanes)
185
# not (yet) recogniced...move to cml
186
if pedestrian_model != 'None':
187
simfile.write('<pedestrian.model value="%s"/>\n' % pedestrian_model)
188
if pedestrian_model == 'striping':
189
simfile.write('<pedestrian.striping.stripe-width value="%s"/>\n' % width_pedestrian_striping)
190
simfile.write('<pedestrian.striping.dawdling value="%s"/>\n' % slowdownfactor_pedestrian_striping)
191
simfile.write('<pedestrian.striping.jamtime value="%s"/>\n' % jamtime_pedestrian_striping)
192
193
# from 1.3.0
194
#simfile.write('<pedestrian.striping.jamtime.crossing value="%s"/>\n'%jamtime_pedestrian_crossing_striping)
195
196
simfile.write('<collision.check-junctions value="%s"/>\n' % is_collission_check_junctions)
197
simfile.write('<collision.action value="%s"/>\n' % collission_action)
198
#simfile.write('<ignore-accidents value="%s"/>\n'%is_ignore_accidents)
199
200
if taxiservice is not None:
201
taxiservice.write_config(simfile, ident=0)
202
203
simfile.write('<output>\n')
204
# <output-file value="quickstart.net.xml"/>
205
206
if filepath_output_vehroute is not None:
207
simfile.write('<vehroute-output value="%s"/>\n' % filepath_output_vehroute)
208
if filepath_output_tripinfo is not None:
209
simfile.write('<tripinfo-output value="%s"/>\n' % filepath_output_tripinfo)
210
211
if filepath_output_fcd is not None:
212
simfile.write("""<fcd-output value="%s"/>
213
<device.fcd.probability value="1"/>\n
214
""" % (filepath_output_fcd,))
215
# <device.fcd.period value="1"/>
216
217
if filepath_output_electricenergy is not None:
218
simfile.write("""<battery-output value="%s"/>
219
<battery-output.precision value="4"/>
220
<device.battery.probability value="1"/>
221
\n
222
""" % (filepath_output_electricenergy,))
223
224
if filepath_output_summary is not None:
225
simfile.write("""<summary-output value="%s"/>""" % filepath_output_summary)
226
227
simfile.write('</output>\n')
228
229
if filepath_gui is not None:
230
simfile.write('<gui-settings-file value="%s"/>\n' % filepath_gui)
231
232
if is_openscenegraph:
233
simfile.write('<osg-view value="true"/>\n')
234
235
if is_tripdata_unfinished:
236
simfile.write('<tripinfo-output.write-unfinished value="true"/>\n')
237
238
if is_rerouting:
239
simfile.write("""<routing>
240
<device.rerouting.probability value="%.2f"/>
241
<device.rerouting.deterministic value="%s"/>
242
<device.rerouting.period value="%d"/>
243
<device.rerouting.pre-period value="%d"/>
244
<device.rerouting.adaptation-interval value = "%d"/>\n
245
""" % (probability_rerouting,
246
is_deterministic_rerouting,
247
period_rerouting,
248
preperiod_rerouting,
249
float(adaptationinterval_rerouting)/time_step,
250
))
251
252
if adaptationweight_rerouting > 0:
253
simfile.write("""<device.rerouting.adaptation-weight value="%.4f"/>\n""" % adaptationweight_rerouting)
254
else:
255
simfile.write("""<device.rerouting.adaptation-steps value="%d"/>\n""" % adaptationsteps_rerouting)
256
257
simfile.write('</routing>\n')
258
259
# <report>
260
# <no-duration-log value="true"/>
261
# <no-step-log value="true"/>
262
# </report>
263
264
simfile.write('</configuration>\n')
265
simfile.close()
266
267
# add path to additional files if necessary
268
if filename_add is not None:
269
addfile = open(filepath_add, 'w')
270
addfile.write('<add>\n')
271
if filepath_output_edgedata is not None:
272
addfile.write(' <edgeData id="output_edgedata_%d" freq="%d" file="%s" excludeEmpty="%s"/>\n' %
273
(freq, freq, filepath_output_edgedata, str(is_exclude_emptyedges).lower()))
274
275
if filepath_output_lanedata is not None:
276
addfile.write(' <laneData id="output_lanedata_%d" freq="%d" file="%s" excludeEmpty="%s"/>\n' %
277
(freq, freq, filepath_output_lanedata, str(is_exclude_emptylanes).lower()))
278
279
if filepath_output_edgeemissions is not None:
280
addfile.write(' <edgeData id="output_edgeemissions_%d" type="emissions" freq="%d" file="%s" excludeEmpty="%s"/>\n' %
281
(freq, freq, filepath_output_edgeemissions, str(is_exclude_emptyedges).lower()))
282
283
if filepath_output_laneemissions is not None:
284
addfile.write(' <laneData id="output_laneemissions_%d" type="emissions" freq="%d" file="%s" excludeEmpty="%s"/>\n' %
285
(freq, freq, filepath_output_laneemissions, str(is_exclude_emptylanes).lower()))
286
287
if filepath_output_edgenoise is not None:
288
addfile.write(' <edgeData id="edgenoise_%d" type="harmonoise" freq="%d" file="%s" excludeEmpty="%s"/>\n' %
289
(freq, freq, filepath_output_edgenoise, str(is_exclude_emptyedges).lower()))
290
291
if filepath_output_lanenoise is not None:
292
addfile.write(' <laneData id="lanenoise_%d" type="harmonoise" freq="%d" file="%s" excludeEmpty="%s"/>\n' %
293
(freq, freq, filepath_output_lanenoise, str(is_exclude_emptylanes).lower()))
294
295
# if filepath_output_electricenergy is not None:
296
# addfile.write(' <laneData id="lanenoise_%d" type="harmonoise" freq="%d" file="%s" excludeEmpty="%s"/>\n'%(freq,freq,filepath_output_lanenoise,str(is_exclude_emptylanes).lower()))
297
298
addfile.write('</add>\n')
299
addfile.close()
300
301
302
class Sumo(CmlMixin, Process):
303
def __init__(self, scenario,
304
results=None,
305
logger=None,
306
guimode='sumopy', # sumo,
307
is_runnow=False,
308
is_run_background=False, is_nohup=False,
309
workdirpath=None,
310
is_export_net=True,
311
is_export_poly=True,
312
is_export_rou=True,
313
is_prompt_filepaths=False,
314
routefilepaths=None,
315
netfilepath=None,
316
ptstopsfilepath=None,
317
polyfilepath=None,
318
logfilepath='',
319
cmlfilepath=None, # write command line into this file instead of executing sumo
320
**kwargs):
321
322
#self.scenario = scenario
323
self._cmlfilepath = cmlfilepath
324
self._init_common('sumo', parent=scenario, name='SUMO',
325
logger=logger,
326
info='SUMO micro simulation of scenario.',
327
)
328
329
# if results is None:
330
# self._results = Simresults(scenario=scenario)
331
# else:
332
self._results = results
333
334
rootname = scenario.get_rootfilename()
335
rootdirpath = scenario.get_workdirpath()
336
self.configfilepath = os.path.join(rootdirpath, rootname+'.netc.xml')
337
338
self.init_cml('xxx', is_run_background=is_run_background, is_nohup=is_nohup) # pass main shell command
339
attrsman = self.get_attrsman()
340
341
self.guimode = attrsman.add(cm.AttrConf('guimode', guimode,
342
groupnames=['options', 'misc'],
343
choices=['sumopy', 'sumopy+map', 'native', 'nogui'], # 'openscene'???
344
name='GUI mode',
345
perm='rw',
346
info='Gui mode: sumopy = sumopy style, sumopy+map = sumopy theme with backround map, native = Native SUMO gui, openscene = Open street graph, nogui = run without gui window'
347
))
348
349
simtime_start_default = scenario.demand.get_time_depart_first()
350
# estimate end of simtime
351
simtime_end_default = scenario.demand.get_time_depart_last()
352
353
self.simtime_start = attrsman.add(cm.AttrConf('simtime_start', kwargs.get('simtime_start', simtime_start_default),
354
groupnames=['options', 'timing'],
355
name='Start time',
356
perm='rw',
357
info='Start time of simulation in seconds after midnight.',
358
unit='s',
359
cml='--begin', # no prefix
360
))
361
362
self.simtime_end = attrsman.add(cm.AttrConf('simtime_end', kwargs.get('simtime_end', simtime_end_default),
363
groupnames=['options', 'timing'],
364
name='End time',
365
perm='rw',
366
info='End time of simulation in seconds after midnight.',
367
unit='s',
368
cml='--end', # no prefix
369
))
370
371
self.is_dynaroute = attrsman.add(cm.AttrConf('is_dynaroute', kwargs.get('is_dynaroute', False),
372
groupnames=['options', 'timing'],
373
name='Dynamic routing',
374
perm='rw',
375
info='Routing is always performed during the simulation on vehicle dearture time, based on current edge travel times. This option corrisponds to the so called one shot assignment.',
376
))
377
378
self.time_to_teleport = attrsman.add(cm.AttrConf('time_to_teleport', kwargs.get('time_to_teleport', -1),
379
groupnames=['options', 'timing'],
380
name='teleport',
381
perm='rw',
382
info='Time to teleport in seconds, which is the time after'
383
+ 'dedlocks get resolved by teleporting\n'
384
+ '-1 means no teleporting takes place',
385
metatype='time',
386
unit='s',
387
cml='--time-to-teleport',
388
))
389
390
self._init_attributes_basic(scenario, **kwargs)
391
392
# print '\nSumo.__init__',kwargs
393
394
#self.scenario = scenario
395
#self.settings = scenario.settings
396
397
self.time_sample = attrsman.add(cm.AttrConf('time_sample', kwargs.get('time_sample', 60),
398
groupnames=['options', 'timing'],
399
name='Output sample time',
400
perm='rw',
401
info='Common sampling time of output data.',
402
metatype='time',
403
unit='s',
404
))
405
406
self.time_warmup = attrsman.add(cm.AttrConf('time_warmup', kwargs.get('time_warmup', 0.0),
407
groupnames=['options', 'timing'],
408
name='Warmup time',
409
perm='rw',
410
info='Start recording results after this time. It currently work with edgeresults, connectionresults and virtualpersonresults',
411
metatype='time',
412
unit='s',
413
))
414
415
self.is_edgedata = attrsman.add(cm.AttrConf('is_edgedata', kwargs.get('is_edgedata', False),
416
groupnames=['options', 'output'],
417
name='Output edge data',
418
perm='rw',
419
info='If set, generate detailed data for all edges.'
420
))
421
422
self.is_routedata = attrsman.add(cm.AttrConf('is_routedata', kwargs.get('is_routedata', False),
423
groupnames=['options', 'output'],
424
name='Output route data',
425
perm='rw',
426
info='If set, generate detailed data for all routes.'
427
))
428
429
self.is_tripdata = attrsman.add(cm.AttrConf('is_tripdata', kwargs.get('is_tripdata', False),
430
groupnames=['options', 'output'],
431
name='Output trip data',
432
perm='rw',
433
info='If set, generate detailed data for all completed trips.'
434
))
435
436
self.is_tripdata_unfinished = attrsman.add(cm.AttrConf('is_tripdata_unfinished', kwargs.get('is_tripdata_unfinished', False),
437
groupnames=['options', 'output'],
438
name='Include unfinished trip data',
439
perm='rw',
440
info='If set, also unfinished trip data is collected.'
441
))
442
443
self.is_edgenoise = attrsman.add(cm.AttrConf('is_edgenoise', kwargs.get('is_edgenoise', False),
444
groupnames=['options', 'output'],
445
name='Output edge noise',
446
perm='rw',
447
info='If set, generate noise information for all edges.'
448
))
449
450
self.is_edgesemissions = attrsman.add(cm.AttrConf('is_edgesemissions', kwargs.get('is_edgesemissions', False),
451
groupnames=['options', 'output'],
452
name='Output edge emissions',
453
perm='rw',
454
info='If set, generate emission information for all edges.'
455
))
456
457
self.is_electricenergy = attrsman.add(cm.AttrConf('is_electricenergy', kwargs.get('is_electricenergy', False),
458
groupnames=['options', 'output'],
459
name='Output electric energy',
460
perm='rw',
461
info='If set, record energy data for vehicles with electric drive.'
462
))
463
464
self.is_fcd = attrsman.add(cm.AttrConf('is_fcd', kwargs.get('is_fcd', False),
465
groupnames=['options', 'output'],
466
name='Output vehicle trajectories',
467
perm='rw',
468
info='If set, record vehicle trajectories and speed for each timestep. This means SUMO FCD output is generated. Attention, this option will eat up a tremendous amount of disk space.'
469
))
470
471
self.is_summary = attrsman.add(cm.AttrConf('is_summary', kwargs.get('is_summary', False),
472
groupnames=['options', 'output'],
473
name='Output summary',
474
perm='rw',
475
info='If set, generate summary data of simulation steps.'
476
))
477
478
outfile_prefix = kwargs.get('outfile_prefix', 'out')
479
self.routesdatapath = attrsman.add(cm.AttrConf('routesdatapath', os.path.join(rootdirpath, rootname+'.'+outfile_prefix+'.roudata.xml'),
480
groupnames=['outputfiles', '_private'],
481
perm='r',
482
name='Route data file',
483
wildcards='Route data XML files (*.roudata.xml)|*.roudata.xml',
484
metatype='filepath',
485
info="""SUMO xml file with route output info.""",
486
#attrnames_data = ['depart','arrival'],
487
#element = 'vehicle',
488
#id_type = 'trip',
489
#reader = 'plain',
490
))
491
492
self.tripdatapath = attrsman.add(cm.AttrConf('tripdatapath', os.path.join(rootdirpath, rootname+'.'+outfile_prefix+'.tripdata.xml'),
493
groupnames=['outputfiles', '_private'],
494
perm='r',
495
name='Edge data file',
496
wildcards='Trip data XML files (*.tripdata.xml)|*.tripdata.xml',
497
metatype='filepath',
498
info="""SUMO xml file with trip output data.""",
499
attrnames_data=['depart', 'arrival', 'duration'],
500
#element = 'tripinfo',
501
#id_type = 'trip',
502
#reader = 'plain',
503
))
504
505
self.edgedatapath = attrsman.add(cm.AttrConf('edgedatapath', os.path.join(rootdirpath, rootname+'.'+outfile_prefix+'.edgedata.xml'),
506
groupnames=['outputfiles', '_private'],
507
perm='r',
508
name='Edge data file',
509
wildcards='Edge data XML files (*.edgedata.xml)|*.edgedata.xml',
510
metatype='filepath',
511
info="""SUMO xml file with edge output data.""",
512
))
513
514
self.edgenoisepath = attrsman.add(cm.AttrConf('edgenoisepath', os.path.join(rootdirpath, rootname+'.'+outfile_prefix+'.edgenoise.xml'),
515
groupnames=['outputfiles', '_private'],
516
perm='r',
517
name='Edge noise file',
518
wildcards='Edge noise XML files (*.edgenoise.xml)|*.edgenoise.xml',
519
metatype='filepath',
520
info="""SUMO xml file with edge noise data.""",
521
#attrnames_averaged = ['noise'],
522
#element = 'edge',
523
#id_type = 'edge',
524
#reader = 'interval',
525
))
526
527
self.edgeemissionspath = attrsman.add(cm.AttrConf('edgeemissionspath', os.path.join(rootdirpath, rootname+'.'+outfile_prefix+'.edgeemissions.xml'),
528
groupnames=['outputfiles', '_private'],
529
perm='r',
530
name='Edge noise file',
531
wildcards='Edge noise XML files (*.edgeemissions.xml)|*.edgeemissions.xml',
532
metatype='filepath',
533
info="""SUMO xml file with edge emission data.""",
534
attrnames_data=['fuel_abs', 'CO_abs',
535
'CO2_abs', 'NOx_abs', 'PMx_abs'],
536
attrnames_averaged=['fuel_normed',
537
'CO_normed', 'CO2_normed', ],
538
element='edge',
539
id_type='edge',
540
reader='interval',
541
))
542
543
self.electricenergypath = attrsman.add(cm.AttrConf('electricenergypath', os.path.join(rootdirpath, rootname+'.'+outfile_prefix+'.electricenergy.xml'),
544
groupnames=['outputfiles', '_private'],
545
perm='r',
546
name='Electrical energy file',
547
wildcards='Electrical energy XML files (*.electricenergy.xml)|*.electricenergy.xml',
548
metatype='filepath',
549
info="""SUMO xml file with edge emission data.""",
550
attrnames_data=['Consum', 'energyCharged',
551
'energyChargedInTransit', 'energyChargedStopped'],
552
attrnames_averaged=['speed', ],
553
element='vehicle',
554
id_type='vehicle',
555
reader='interval',
556
))
557
558
self.filepath_output_fcd = attrsman.add(cm.AttrConf('filepath_output_fcd', os.path.join(rootdirpath, rootname+'.'+outfile_prefix+'.fcd.xml'),
559
groupnames=['outputfiles', '_private'],
560
perm='r',
561
name='Trajectory file',
562
wildcards='Trajectory XML files (*.fcd.xml)|*.fcd.xml',
563
metatype='filepath',
564
info="""SUMO xml file with edge emission data.""",
565
attrnames_data=['x', 'y', 'angle', ],
566
attrnames_averaged=['speed', ],
567
element='vehicle',
568
id_type='vehicle',
569
reader='interval',
570
))
571
572
self.summarypath = attrsman.add(cm.AttrConf('summarypath', os.path.join(rootdirpath, rootname+'.'+outfile_prefix+'.electricenergysum.xml'),
573
groupnames=['_private'],
574
perm='r',
575
name='Simulation summary file',
576
wildcards='Simulation summary XML files (*.xml)|*.xml',
577
metatype='filepath',
578
info="""SUMO xml file with summary data on simulatin steps.""",
579
))
580
581
self.is_rerouting = attrsman.add(cm.AttrConf('is_rerouting', kwargs.get('is_rerouting', False),
582
groupnames=['options', 'rerouting'],
583
name='Rerouting enabled',
584
perm='rw',
585
info='Enable rerouting of vehicles during the simulation.'
586
))
587
588
self.probability_rerouting = attrsman.add(cm.AttrConf('probability_rerouting', kwargs.get('probability_rerouting', 0.25),
589
groupnames=['options', 'rerouting'],
590
name='Rerouting probability',
591
perm='rw',
592
info='The probability for a vehicle to have a routing device.'
593
))
594
595
self.is_deterministic_rerouting = attrsman.add(cm.AttrConf('is_deterministic_rerouting', kwargs.get('is_deterministic_rerouting', False),
596
groupnames=['options', 'rerouting'],
597
name='Deterministic rerouting',
598
perm='rw',
599
info='The devices are set deterministic using a fraction of 1000 (with the defined probability).'
600
))
601
602
self.period_rerouting = attrsman.add(cm.AttrConf('period_rerouting', kwargs.get('period_rerouting', 180),
603
groupnames=['options', 'rerouting'],
604
name='Rerouting period',
605
perm='rw',
606
info='The period with which the vehicle shall be rerouted.',
607
unit='s',
608
))
609
610
self.preperiod_rerouting = attrsman.add(cm.AttrConf('preperiod_rerouting', kwargs.get('preperiod_rerouting', 180),
611
groupnames=['options', 'rerouting'],
612
name='Rerouting pre-period',
613
perm='rw',
614
info='The rerouting period before insertion/depart.',
615
unit='s',
616
))
617
self.adaptationinterval_rerouting = attrsman.add(cm.AttrConf('adaptationinterval_rerouting', kwargs.get('adaptationinterval_rerouting', 180),
618
groupnames=['options', 'rerouting'],
619
name='adaptation interval edge weight',
620
perm='rw',
621
info='The interval for updating the edge weights. Short update times means a large computational burden.',
622
unit='s',
623
))
624
self.adaptationweight_rerouting = attrsman.add(cm.AttrConf('adaptationweight_rerouting', kwargs.get('adaptationweight_rerouting', 0.0),
625
groupnames=['options', 'rerouting'],
626
name='Adaptation weight for rerouting',
627
perm='rw',
628
info='The weight of prior edge weights for exponential averaging from [0, 1]. Disabeled for 0.0.'
629
))
630
631
self.adaptationsteps_rerouting = attrsman.add(cm.AttrConf('adaptationsteps_rerouting', kwargs.get('adaptationsteps_rerouting', 10),
632
groupnames=['options', 'rerouting'],
633
name='Adaptation steps for rerouting',
634
perm='rw',
635
info='The number of adaptation steps for edge weights averaging (enable for values > 0).'
636
))
637
638
self._init_special(**kwargs)
639
640
self.is_include_poly = attrsman.add(cm.AttrConf('is_include_poly', kwargs.get('is_include_poly', True),
641
name='Include buildings?',
642
perm='rw',
643
groupnames=['options', 'misc'],
644
info='Include building polynomials. Only for visualization purposes.',
645
))
646
647
self.is_start = attrsman.add(cm.AttrConf('is_start', kwargs.get('is_start', False),
648
groupnames=['options', 'misc'],
649
perm='rw',
650
name='Start immediately',
651
info='Immediate start of simulation, without waiting to press the start button in GUI mode.',
652
is_enabled=lambda self: self.guimode is not 'nogui',
653
))
654
655
self.is_quit_on_end = attrsman.add(cm.AttrConf('is_quit_on_end', kwargs.get('is_quit_on_end', False),
656
groupnames=['options', 'misc'],
657
perm='rw',
658
name='Quit on end',
659
info='Quits the GUI when the simulation stops.',
660
is_enabled=lambda self: self.guimode is not 'nogui',
661
))
662
663
self.logfilepath = attrsman.add(cm.AttrConf('logfilepath', logfilepath,
664
groupnames=['options', 'misc'],
665
perm='rw',
666
name='Log file',
667
wildcards='Log file (*.txt)|*.txt',
668
metatype='filepath',
669
info="Writes all messages to Log filepath, implies verbous. If blank, no logfile is created",
670
))
671
672
if ptstopsfilepath is None:
673
ptstopsfilepath = scenario.net.ptstops.get_stopfilepath()
674
675
self.is_export_ptstops = attrsman.add(cm.AttrConf('is_export_ptstops', True,
676
groupnames=['input', 'options'],
677
perm='rw',
678
name='Export PT stops?',
679
info='Export PT stops before simulation?',
680
))
681
682
if routefilepaths is None:
683
routefilepaths = scenario.demand.get_routefilepath()
684
685
self.is_export_rou = attrsman.add(cm.AttrConf('is_export_rou', is_export_rou,
686
groupnames=['input', 'options'],
687
perm='rw',
688
name='Export routes?',
689
info='Export current routes before simulation? Needs to be done only once after demand has changed.',
690
))
691
else:
692
self.is_export_rou = False
693
694
if netfilepath is None:
695
netfilepath = scenario.net.get_filepath()
696
697
self.is_export_net = attrsman.add(cm.AttrConf('is_export_net', is_export_net,
698
groupnames=['input', 'options'],
699
perm='rw',
700
name='Export net?',
701
info='Export current network before simulation? Needs to be done only once after network has changed.',
702
))
703
else:
704
self.is_export_net = False
705
706
if polyfilepath is None:
707
polyfilepath = scenario.landuse.get_filepath()
708
self.is_export_poly = attrsman.add(cm.AttrConf('is_export_poly', is_export_poly,
709
groupnames=['input', 'options'],
710
perm='rw',
711
name='Export buildings?',
712
info='Export current buildings before simulation? Needs to be done only once after buildings have changed.',
713
))
714
else:
715
self.is_export_poly = False
716
717
if is_prompt_filepaths:
718
filepathgroupnames = ['input', 'options']
719
else:
720
filepathgroupnames = ['input', '_private']
721
722
self.dirpath_results = attrsman.add(cm.AttrConf('dirpath_results', rootdirpath,
723
groupnames=filepathgroupnames,
724
perm='rw',
725
name='Result directory',
726
metatype='dirpath',
727
info="""Directory where general SUMO simulation result files are placed.""",
728
))
729
730
self.netfilepath = attrsman.add(cm.AttrConf('netfilepath', netfilepath,
731
groupnames=filepathgroupnames,
732
perm='rw',
733
name='Netfile',
734
wildcards='SUMO net XML files (*.net.xml)|*.net.xml',
735
metatype='filepath',
736
info="""SUMO network xml file.""",
737
))
738
739
self.ptstopsfilepath = attrsman.add(cm.AttrConf('ptstopsfilepath', ptstopsfilepath,
740
groupnames=filepathgroupnames,
741
perm='rw',
742
name='Stop file',
743
wildcards='SUMO XML files (*.add.xml)|*.add.xml',
744
metatype='filepath',
745
info="""SUMO additional xml file with info on public transport stops.""",
746
))
747
748
self.routefilepaths = attrsman.add(cm.AttrConf('routefilepaths', routefilepaths,
749
groupnames=filepathgroupnames,
750
perm='rw',
751
name='Route file(s)',
752
wildcards='Typemap XML files (*.rou.xml)|*.rou.xml',
753
metatype='filepaths',
754
info='SUMO route xml file.\n'
755
+ 'If multiple, comma separated files are given'
756
+ ' then make sure the start time of trips'
757
+ ' are in increasing chronological order.',
758
))
759
760
self.polyfilepath = attrsman.add(cm.AttrConf('polyfilepath', polyfilepath,
761
groupnames=filepathgroupnames,
762
perm='rw',
763
name='Poly file',
764
wildcards='Poly XML files (*.poly.xml)|*.poly.xml',
765
metatype='filepath',
766
info='SUMO polynomial xml file',
767
))
768
769
# print ' is_export_poly,is_include_poly, filepath_poly',is_export_poly, self.is_include_poly, self.polyfilepath
770
771
if is_runnow:
772
self.run()
773
774
def _init_attributes_basic(self, scenario, optionprefix='', **kwargs):
775
attrsman = self.get_attrsman()
776
777
if optionprefix == '':
778
optionprefix_nice = ''
779
prefixgroups = []
780
else:
781
optionprefix_nice = optionprefix.title()+': '
782
prefixgroups = [optionprefix]
783
784
self.time_step = attrsman.add(cm.AttrConf('time_step', kwargs.get('time_step', 0.2),
785
groupnames=['options', 'timing']+prefixgroups,
786
name=optionprefix_nice+'Time step',
787
perm='rw',
788
info='Basic simulation time step (1s by default).',
789
metatype='time',
790
unit='s',
791
cml=optionprefix+'--step-length',
792
))
793
794
self.is_ballistic_integrator = attrsman.add(cm.AttrConf('is_ballistic_integrator', kwargs.get('is_ballistic_integrator', False),
795
groupnames=['options', 'timing']+prefixgroups,
796
name=optionprefix_nice+'Ballistic integrator',
797
perm='rw',
798
info='Whether to use ballistic method for the positional update of vehicles (default is a semi-implicit Euler method).',
799
cml=optionprefix+'--step-method.ballistic',
800
))
801
802
# print ' ',scenario.demand.vtypes.lanechangemodel.get_value()
803
if scenario.demand.vtypes.lanechangemodel.get_value() in ['SL2015', ]:
804
width_sublanes_default = 1.0
805
else:
806
width_sublanes_default = -1.0
807
808
self.width_sublanes = attrsman.add(cm.AttrConf('width_sublanes', kwargs.get('width_sublanes', width_sublanes_default),
809
groupnames=['options', 'edges']+prefixgroups,
810
cml=optionprefix+'--lateral-resolution',
811
perm='rw',
812
name=optionprefix_nice+'Sublane width',
813
unit='m',
814
info='Width of sublanes. Should be less than lane width. If negative the sublanes are disabeled.',
815
is_enabled=lambda self: self.width_sublanes > 0,
816
))
817
818
#
819
# --max-depart-delay <TIME> <TIME> may be used to discard vehicles which could not be inserted within <TIME> seconds.
820
821
# self.is_ignore_accidents = attrsman.add(cm.AttrConf( 'is_ignore_accidents', kwargs.get('is_ignore_accidents',False),
822
# name = 'ignore accidents',
823
# perm = 'rw',
824
# groupnames = ['options','misc'],
825
# info = 'Ignore accidents.',
826
# ))
827
828
self.is_collission_check_junctions = attrsman.add(cm.AttrConf('is_collission_check_junctions', kwargs.get('is_collission_check_junctions', True),
829
name=optionprefix_nice+'Collission check junctions',
830
perm='rw',
831
groupnames=['options', 'misc']+prefixgroups,
832
info='Perform collission check at junctions.',
833
cml=optionprefix+'--collision.check-junctions',
834
))
835
836
self.collission_action = attrsman.add(cm.AttrConf('collission_action', kwargs.get('collission_action', 'warn'),
837
name=optionprefix_nice+'Collission action',
838
choices=['none', 'warn', 'teleport', 'remove'],
839
perm='rw',
840
groupnames=['options', 'misc']+prefixgroups,
841
info='Specifioes what to do when a collission occurs.',
842
cml=optionprefix+'--collision.action',
843
))
844
845
# self.factor_collission_mingap = attrsman.add(cm.AttrConf( 'factor_collission_mingap', kwargs.get('factor_collission_mingap',-1),
846
# name = 'factor_collission_mingap',
847
# perm = 'rw',
848
# groupnames = ['options','misc'],
849
# info = 'Sets the fraction of minGap that must be maintained to avoid collision detection. If a negative value is given, the carFollowModel parameter is used.',
850
# cml = optionprefix+'--collision.mingap-factor',
851
# ))
852
853
# self.is_exclude_emptyedges = attrsman.add(cm.AttrConf( 'is_exclude_emptyedges', kwargs.get('is_exclude_emptyedges',True),
854
# name = 'No empty edges',
855
# perm = 'rw',
856
# groupnames = ['options','misc'],
857
# info = 'Excludes empty edges from being sampled.',
858
# #cml = optionprefix+'--end',
859
# ))
860
861
# self.is_exclude_emptylanes = attrsman.add(cm.AttrConf( 'is_exclude_emptylanes',kwargs.get('is_exclude_emptylanes',True),
862
# name = 'No empty lanes',
863
# perm = 'rw',
864
# groupnames = ['options','misc'],
865
# info = 'Excludes empty edges from being sampled.',
866
# cml = optionprefix+'--end',
867
# ))
868
869
self.seed = attrsman.add(cm.AttrConf('seed', kwargs.get('seed', 0),
870
name=optionprefix_nice+'Seed',
871
perm='rw',
872
groupnames=['options', 'misc']+prefixgroups,
873
info='Random seed.',
874
cml=optionprefix+'--seed',
875
))
876
877
def _init_special(self, **kwargs):
878
"""
879
Special initializations. To be overridden.
880
"""
881
pass
882
883
def get_results(self):
884
return self._results
885
886
def is_ready(self):
887
"""
888
Returns True if process is ready to run.
889
890
"""
891
# here we can check existance of files
892
return True
893
894
def do(self):
895
"""
896
Called by run after is_ready verification
897
"""
898
899
print 'do... '
900
901
scenario = self.parent
902
903
# exports, if required
904
delta = np.zeros(3, dtype=np.float32)
905
if self.is_export_net:
906
ptstopsfilepath = scenario.net.ptstops.export_sumoxml(self.ptstopsfilepath)
907
netfilepath, delta = scenario.net.export_netxml(self.netfilepath, is_return_delta=True)
908
else:
909
ptstopsfilepath = self.ptstopsfilepath
910
911
if self.is_export_rou & (self.routefilepaths.count(',') == 0):
912
scenario.demand.export_routes_xml(self.routefilepaths,
913
is_route=not self.is_dynaroute)
914
915
if self.is_export_poly & (self.guimode not in ['sumopy+map']):
916
polyfilepath = scenario.landuse.export_polyxml(self.polyfilepath, delta=delta)
917
else:
918
polyfilepath = self.polyfilepath
919
920
# Output data
921
if self.is_routedata:
922
routesdatapath = self.routesdatapath
923
else:
924
routesdatapath = None
925
926
if self.is_tripdata:
927
tripdatapath = self.tripdatapath
928
else:
929
tripdatapath = None
930
931
if self.is_edgedata:
932
edgedatapath = self.edgedatapath
933
else:
934
edgedatapath = None
935
936
if self.is_edgenoise:
937
edgenoisepath = self.edgenoisepath
938
else:
939
edgenoisepath = None
940
941
if self.is_edgesemissions:
942
edgeemissionspath = self.edgeemissionspath
943
else:
944
edgeemissionspath = None
945
946
if self.is_electricenergy:
947
electricenergypath = self.electricenergypath
948
else:
949
electricenergypath = None
950
951
if self.is_fcd:
952
filepath_output_fcd = self.filepath_output_fcd
953
else:
954
filepath_output_fcd = None
955
956
if self.is_summary:
957
summarypath = self.summarypath
958
else:
959
summarypath = None
960
961
# print ' is_include_poly, filepath_poly', self.is_include_poly, self.polyfilepath
962
if self.is_include_poly & (self.guimode not in ['sumopy+map']):
963
if polyfilepath is None:
964
filename_poly = None
965
elif os.path.isfile(self.polyfilepath):
966
filename_poly = os.path.basename(self.polyfilepath)
967
else:
968
filename_poly = None
969
else:
970
filename_poly = None
971
# print ' guimode',self.guimode,self.guimode == 'sumopy+map',is_maps
972
# ['sumopy','sumopy+map','native','osg','nogui']
973
if self.guimode in ['sumopy', 'sumopy+map']:
974
filepath_gui = os.path.basename(self.parent.net.write_guiconfig(
975
is_maps=self.guimode in ['sumopy+map'], delta=delta))
976
else:
977
filepath_gui = None
978
979
if ptstopsfilepath is None:
980
filename_ptstops = None
981
elif os.path.isfile(ptstopsfilepath) & self.is_export_ptstops:
982
filename_ptstops = os.path.basename(self.ptstopsfilepath)
983
else:
984
filename_ptstops = None
985
# if self.files_input.filepath.get('ptstops')=='':
986
# filepath_ptstops = None
987
# filename_ptstops = None
988
# else:
989
# filepath_ptstops = self.files_input.filepath.get('ptstops')
990
# filename_ptstops = os.path.basename(filepath_ptstops)
991
992
# print ' >>%s<<'%self.configfilepath
993
#filename_netconfig = os.path.basename(self.filepath_netconfig)
994
995
# print ' filepath_poly =',filepath_poly
996
# print ' filename_poly =',filename_poly
997
# write configuration file
998
999
write_netconfig(
1000
self.configfilepath,
1001
self.netfilepath,
1002
self.routefilepaths,
1003
starttime=self.simtime_start,
1004
stoptime=self.simtime_end,
1005
time_step=self.time_step,
1006
filename_ptstops=filename_ptstops,
1007
pedestrian_model=scenario.demand.vtypes.pedestrian_model.get_value(),
1008
width_sublanes=self.width_sublanes,
1009
filename_poly=filename_poly,
1010
dirname_output=self.dirpath_results,
1011
time_to_teleport=self.time_to_teleport,
1012
filepath_output_vehroute=routesdatapath,
1013
filepath_output_tripinfo=tripdatapath,
1014
is_tripdata_unfinished=self.is_tripdata_unfinished,
1015
filepath_output_edgedata=edgedatapath,
1016
#filepath_output_lanedata = self._get_filepath_output('lanedata'),
1017
filepath_output_edgeemissions=edgeemissionspath,
1018
filepath_output_electricenergy=electricenergypath,
1019
filepath_output_fcd=filepath_output_fcd,
1020
filepath_output_summary=summarypath,
1021
#filepath_output_laneemissions = self._get_filepath_output('laneemissions'),
1022
filepath_output_edgenoise=edgenoisepath,
1023
#filepath_output_lanenoise = self._get_filepath_output('lanenoise'),
1024
freq=self.time_sample,
1025
#is_exclude_emptyedges = self.is_exclude_emptyedges,
1026
#is_exclude_emptylanes =self.is_exclude_emptylanes,
1027
seed=self.seed,
1028
filepath_gui=filepath_gui,
1029
is_openscenegraph=self.guimode is 'openscene',
1030
width_pedestrian_striping=scenario.demand.vtypes.width_pedestrian_striping.get_value(),
1031
slowdownfactor_pedestrian_striping=scenario.demand.vtypes.slowdownfactor_pedestrian_striping.get_value(),
1032
jamtime_pedestrian_striping=scenario.demand.vtypes.jamtime_pedestrian_striping.get_value(),
1033
jamtime_pedestrian_crossing_striping=scenario.demand.vtypes.jamtime_pedestrian_crossing_striping.get_value(),
1034
is_collission_check_junctions=self.is_collission_check_junctions,
1035
#is_ignore_accidents = self.is_ignore_accidents,
1036
collission_action=self.collission_action,
1037
is_ballistic_integrator=self.is_ballistic_integrator,
1038
is_rerouting=self.is_rerouting,
1039
probability_rerouting=self.probability_rerouting,
1040
is_deterministic_rerouting=self.is_deterministic_rerouting,
1041
period_rerouting=self.period_rerouting,
1042
preperiod_rerouting=self.preperiod_rerouting,
1043
adaptationinterval_rerouting=self.adaptationinterval_rerouting,
1044
adaptationweight_rerouting=self.adaptationweight_rerouting,
1045
adaptationsteps_rerouting=self.adaptationsteps_rerouting,
1046
taxiservice=self.parent.simulation.taxiservice,
1047
)
1048
1049
if self._cmlfilepath is None:
1050
print ' call run_cml'
1051
return self.run_cml(cml=self.get_cml())
1052
else:
1053
print ' do not simulate but write cml to', self._cmlfilepath
1054
f = open(self._cmlfilepath, "w+")
1055
f.write(self.get_cml()+'\n')
1056
1057
f.close()
1058
return True
1059
# self.import_results()
1060
1061
def get_scenario(self):
1062
return self.parent
1063
1064
def import_results(self, results=None):
1065
"""
1066
Imports simulation resuts into results object.
1067
"""
1068
print 'import_results'
1069
1070
# first a dict is created with available dataname as key
1071
# and filepath as value
1072
1073
# with this dict, the import_xml method of results
1074
# is called, where the files are parsed for specific data
1075
1076
if results is None:
1077
results = self._results
1078
if results is None:
1079
results = self.parent.simulation.results
1080
1081
if results is not None:
1082
1083
resultfilepaths = {}
1084
if self.is_edgedata:
1085
if os.path.isfile(self.edgedatapath):
1086
resultfilepaths['edgedatapath'] = self.edgedatapath
1087
1088
if self.is_edgenoise:
1089
if os.path.isfile(self.edgenoisepath):
1090
resultfilepaths['edgenoisepath'] = self.edgenoisepath
1091
1092
if self.is_edgesemissions:
1093
if os.path.isfile(self.edgeemissionspath):
1094
resultfilepaths['edgeemissionspath'] = self.edgeemissionspath
1095
1096
if self.is_routedata:
1097
if os.path.isfile(self.routesdatapath):
1098
resultfilepaths['routesdatapath'] = self.routesdatapath
1099
1100
if self.is_tripdata:
1101
if os.path.isfile(self.tripdatapath):
1102
resultfilepaths['tripdatapath'] = self.tripdatapath
1103
1104
if self.is_electricenergy:
1105
if os.path.isfile(self.electricenergypath):
1106
resultfilepaths['electricenergypath'] = self.electricenergypath
1107
1108
if self.is_fcd:
1109
if os.path.isfile(self.filepath_output_fcd):
1110
resultfilepaths['trajectorypath'] = self.filepath_output_fcd
1111
1112
if len(resultfilepaths) > 0:
1113
results.import_xml(self, **resultfilepaths)
1114
1115
# no. do some preprocessing during import_results then take
1116
# specific actions on demand objects
1117
# def process_results(self):
1118
# self._results.process(self)
1119
1120
def get_cml(self, is_primed=True):
1121
"""
1122
Overwritten, providing configuration file instead of cml options.
1123
"""
1124
if is_primed:
1125
p = P
1126
else:
1127
p = ''
1128
print 'get_cml p=%s=' % p
1129
# print ' self.configfilepath=%s='%self.configfilepath
1130
# print ' self.logfilepath=%s='%self.logfilepath
1131
if self.guimode is 'nogui':
1132
command = 'sumo'
1133
else:
1134
command = 'sumo-gui'
1135
if self.is_quit_on_end:
1136
command += ' --quit-on-end'
1137
if self.is_start:
1138
command += ' --start'
1139
if self.logfilepath != '':
1140
command += ' --log '+p+self.logfilepath+p
1141
1142
# went into config...
1143
# if self.pedestrian_model=='None':
1144
# pedmodeloptions = ''
1145
# else:
1146
# pedmodeloptions = '--pedestrian.model %s'%self.pedestrian_model
1147
# return command + ' ' +pedmodeloptions+' -c '+P+self.configfilepath+P
1148
return command + ' -c '+p+self.configfilepath+p
1149
1150
1151
class Meso(Sumo):
1152
"""
1153
Mesoscopic simulation process.
1154
The mesoscopic simulation model which uses the same input data as the main SUMO model.
1155
It computes vehicle movements with queues and runs up to 100 times faster than the microscopic model of SUMO. Additionally, due to using a coarser model for intersections and lane-changing it is more tolerant of network modelling errors than SUMO.
1156
1157
The simulation model is based on the work of Eissfeldt, Vehicle-based modelling of traffic.
1158
"""
1159
1160
def _init_special(self, **kwargs):
1161
"""
1162
Special initializations. To be overridden.
1163
"""
1164
attrsman = self.get_attrsman()
1165
1166
self.add_option('edgelength_meso', kwargs.get('edgelength_meso', 100.0),
1167
groupnames=['options', 'meso'],
1168
cml='--meso-edgelength',
1169
name='MESO: Maximum queue length',
1170
unit='m',
1171
info='Maximum queue length.',
1172
)
1173
1174
self.add_option('is_allow_overtaking', kwargs.get('is_allow_overtaking', True),
1175
groupnames=['options', 'meso'],
1176
cml='--meso-overtaking',
1177
name='MESO: Allow overtaking',
1178
info='If True, vehicles may overtake each other (swap their position). This is a randomized process depending on vehicle speeds and density.',
1179
)
1180
1181
self.add_option('enable_junction_control', kwargs.get('enable_junction_control', 'true'),
1182
groupnames=['options', 'meso'],
1183
choices=['true', 'false'],
1184
cml='--meso-junction-control',
1185
name='MESO: enable junction control',
1186
info='If True, junctions are modeled as in the simplified microsim mode (without internal links).',
1187
)
1188
1189
self.add_option('time_panelty_minor', kwargs.get('time_panelty_minor', 0.0),
1190
groupnames=['options', 'meso'],
1191
cml='--meso-minor-penalty',
1192
name='MESO: junction timepenalty',
1193
unit='s',
1194
info='fixed time penalty when passing an unprioritzed link.',
1195
)
1196
1197
self.add_option('penalty_tls', kwargs.get('penalty_tls', 0.0),
1198
groupnames=['options', 'meso'],
1199
cml='--meso-tls-penalty',
1200
name='MESO: TLS penalty',
1201
info='For values >0, a time penalty is applied according to the average delay time (based on red phase duration) and the minimum headway time is increased to model the maximum capacity (according the proportion of green time to cycle time). The panelty is used as a scaling factor that roughly corresponds to coordination (1.0 corresponds to uncoordinated traffic lights, whereas values approaching 0 model near-perfect coordination).',
1202
)
1203
1204
self.add_option('time_to_impatience', kwargs.get('time_to_impatience', 1000.0),
1205
groupnames=['options', 'meso'],
1206
cml='--time-to-impatience',
1207
name='MESO: time to impacience',
1208
unit='s',
1209
info='Time to reach an impatience value of 1. Vehicles that reach an impatience value of 1 (maximum) can pass an intersection regardless of foe traffic with higher priority.',
1210
)
1211
1212
def get_cml(self, is_primed=True):
1213
"""
1214
Overwritten, providing configuration file instead of cml options.
1215
"""
1216
1217
# currently meso options are provided through the command line options
1218
# while SUMO options are written to the configuration file
1219
options = self.get_options()
1220
optionstr = options.get_optionstring()
1221
1222
return Sumo.get_cml(self, is_primed) + ' --mesosim true ' + optionstr
1223
1224
1225
class SumoTraci(Sumo):
1226
"""
1227
SUMO simulation process with interactive control via TRACI.
1228
"""
1229
1230
def _init_special(self, **kwargs):
1231
"""
1232
Special initializations. To be overridden.
1233
"""
1234
pass
1235
# self.is_simpla = self.get_attrsman().add(cm.AttrConf( 'is_simpla', kwargs.get('is_simpla',False),
1236
# groupnames = ['options','misc'],
1237
# name = 'Use simple platooning',
1238
# perm = 'rw',
1239
# info = 'Performs simple platooning operations, as configured in Simpla.',
1240
# ))
1241
1242
def do(self):
1243
"""
1244
Called by run after is_ready verification
1245
"""
1246
1247
Sumo.do(self)
1248
1249
def run_cml(self, cml):
1250
scenario = self.parent
1251
cmllist = cml.split(' ')
1252
print 'SumoTraci.run_cml', cmllist
1253
traci.start(cmllist)
1254
1255
simplaconfig = self.parent.simulation.simplaconfig
1256
if simplaconfig.is_enabled:
1257
simplaconfig.prepare_sim()
1258
1259
self.simtime = self.simtime_start
1260
self.duration = 1.0+self.simtime_end-self.simtime_start
1261
self.get_attrsman().status.set('running')
1262
print ' traci started', self.get_attrsman().status.get()
1263
simobjects = []
1264
1265
for simobj in self.parent.simulation.get_simobjects():
1266
# attention, simpla is not a simulation object, only a demand object
1267
# print ' prepare_sim',simobj.ident
1268
simobjects += simobj.prepare_sim(self)
1269
1270
#simobjects = self._prtservice.prepare_sim(self)
1271
self.simobjects = []
1272
for time_sample, simfunc in simobjects:
1273
self.simobjects.append([self.simtime_start, time_sample, simfunc])
1274
# print ' simobjects=',self.simobjects
1275
return True
1276
1277
def get_cml(self):
1278
"""
1279
Returns commandline with all options.
1280
The only difference from this method of the SUMO class is
1281
that filenames must not be quoted when passed to traci.
1282
"""
1283
return Sumo.get_cml(self, is_primed=False)
1284
1285
def aboard(self):
1286
return self.finish_sim()
1287
1288
def step(self):
1289
# called interactively
1290
# when gui it is called through the timer function
1291
print 79*'='
1292
print "simstep", self.simtime, self.simtime_end, self.simtime >= self.simtime_end
1293
traci.simulationStep()
1294
for i in xrange(len(self.simobjects)):
1295
# for time_last, time_sample, simfunc in self.simobjects:
1296
time_last, time_sample, simfunc = self.simobjects[i]
1297
# print ' simfunc',simfunc,'time_last',time_last,'dt',self.simtime-time_last,'sim?',self.simtime-time_last > time_sample
1298
if self.simtime-time_last > time_sample:
1299
self.simobjects[i][0] = self.simtime
1300
simfunc(self)
1301
1302
#self.get_logger().w(100.0*self.simtime/self.duration, key ='progress')
1303
1304
if self.simtime >= self.simtime_end: # | (not (traci.simulation.getMinExpectedNumber() > 0)):
1305
# if self.simtime >= self.simtime_end:
1306
print ' end of simulation reached at', self.simtime
1307
return self.finish_sim()
1308
1309
self.simtime += self.time_step
1310
1311
def finish_sim(self):
1312
print 'finish_sim'
1313
# for demandobj in self.parent.demand.get_demandobjects():
1314
# print ' finish_sim',demandobj.ident
1315
# #demandobj.finish_sim(self) # why not for sim objects?
1316
traci.close()
1317
print ' traci closed.'
1318
self.get_attrsman().status.set('success')
1319
1320
simplaconfig = self.parent.simulation.simplaconfig
1321
if simplaconfig.is_enabled:
1322
scenario = self.get_scenario()
1323
simplaconfig.finish_sim()
1324
1325
return True
1326
1327
# def process_step(self):
1328
# #print traci.vehicle.getSubscriptionResults(vehID)
1329
# print 'process_step time=',self.simtime
1330
1331
1332
class Duaiterate(CmlMixin, Sumo): # attention, CmlMixin overrides Sumo
1333
def __init__(self, scenario,
1334
routefilepath=None,
1335
netfilepath=None,
1336
ptstopsfilepath=None,
1337
logger=None,
1338
results=None,
1339
**kwargs):
1340
1341
self._init_common('duaiterate', name='Dynamic User Equilibrium traffic assignment',
1342
parent=scenario,
1343
logger=logger,
1344
info='The Dynamic User equilibrium traffic Assignment is an iterative micro-simulation process.',
1345
)
1346
1347
# point to script
1348
self.init_cml(os.path.join(os.environ['SUMO_HOME'], 'tools', 'assign', 'duaIterate.py'),
1349
workdirpath=scenario.get_workdirpath())
1350
1351
self._results = results
1352
self.time_warmup = 0.0 # needed for compatibility with sumo process
1353
attrsman = self.get_attrsman()
1354
1355
simtime_start_default = int(scenario.demand.get_time_depart_first())
1356
# estimate end of simtime
1357
simtime_end_default = int(scenario.demand.get_time_depart_last())
1358
1359
self.add_option('simtime_start', kwargs.get('simtime_start', simtime_start_default),
1360
groupnames=['options', 'timing'],
1361
name='Start time',
1362
perm='rw',
1363
info='Start time of simulation in seconds after midnight.',
1364
unit='s',
1365
cml='--begin', # no prefix
1366
)
1367
1368
self.add_option('simtime_end', kwargs.get('simtime_end', simtime_end_default),
1369
groupnames=['options', 'timing'],
1370
name='End time',
1371
perm='rw',
1372
info='End time of simulation in seconds after midnight.',
1373
unit='s',
1374
cml='--end', # no prefix
1375
)
1376
1377
self.add_option('step_first', kwargs.get('step_first', 0),
1378
groupnames=['options', 'timing'],
1379
name='First step',
1380
perm='rw',
1381
info='First DUA step. Default is zero. By settting the first step, one can continue iterate from a previous process.',
1382
cml='--first-step',
1383
)
1384
1385
self.add_option('step_last', kwargs.get('step_last', 50),
1386
groupnames=['options', 'timing'],
1387
name='Last step',
1388
perm='rw',
1389
info='Last DUA step.',
1390
cml='--last-step',
1391
)
1392
1393
self.add_option('n_convergence_iterations', kwargs.get('n_convergence_iterations', 10),
1394
groupnames=['options', 'processing'],
1395
cml='--convergence-iterations',
1396
name="convergence iterations",
1397
info="Number of iterations to use for convergence calculation.",
1398
)
1399
1400
self.add_option('routesteps', kwargs.get('routesteps', 200),
1401
groupnames=['options', 'processing'],
1402
cml='--route-steps',
1403
name="Route steps",
1404
info="Last DUA iteration step.\n"
1405
+ "This is the maximim number of iterations performed.",
1406
)
1407
1408
self.add_option('time_aggregation', kwargs.get('time_aggregation', 900),
1409
groupnames=['options', 'processing'],
1410
name='Aggregation time',
1411
cml='--aggregation',
1412
info='Set main weights aggregation period.',
1413
unit='s',
1414
)
1415
1416
self.add_option('is_mesosim', kwargs.get('is_mesosim', False),
1417
groupnames=['options', 'processing'],
1418
cml='--mesosim',
1419
name='mesosim',
1420
perm='rw',
1421
info='Whether mesosim shall be used.',
1422
)
1423
1424
self.add_option('is_no_internal_link', kwargs.get('is_no_internal_link', False),
1425
groupnames=['options', 'processing'],
1426
cml='--nointernal-link',
1427
name='Simulate no internal links',
1428
perm='rw',
1429
info='No internal links simulated.',
1430
)
1431
1432
# self.add_option( 'path', kwargs.get('path',''),
1433
# name = 'bin dir',
1434
# perm = 'rw',
1435
# info = 'Directory with SUMO binaries.',
1436
# metatype = 'dirpath',
1437
# )
1438
1439
self.add_option('time_to_teleport', kwargs.get('time_to_teleport', -1),
1440
groupnames=['options', 'timing'],
1441
name='teleport',
1442
perm='rw',
1443
info='Time to teleport in seconds, which is the time after'
1444
+ 'dedlocks get resolved by teleporting\n'
1445
+ '-1 means no teleporting takes place',
1446
metatype='time',
1447
unit='s',
1448
cml='--time-to-teleport',
1449
is_enabled=lambda self: self.time_to_teleport >= 0,
1450
)
1451
1452
self.add_option('is_absrand', kwargs.get('is_absrand', False),
1453
groupnames=['options', 'processing'],
1454
cml='--absrand',
1455
name='time rand',
1456
perm='rw',
1457
info='Use current time to generate random number.',
1458
)
1459
1460
# these are duarouter options, but not duaiterate options
1461
# self.add_option( 'is_remove_loops', kwargs.get('is_remove_loops',False),
1462
# groupnames = ['options','processing'],#
1463
# cml = '--remove-loops',
1464
# name = 'Remove loops',
1465
# perm = 'rw',
1466
# info = 'Remove loops within the route; Remove turnarounds at start and end of the route.',
1467
# )
1468
1469
# self.add_option( 'is_repair_routes', kwargs.get('is_repair_routes',False),
1470
# groupnames = ['options','processing'],#
1471
# cml = '--repair',
1472
# name = 'Repair routes',
1473
# perm = 'rw',
1474
# info = 'Tries to correct a false route.',
1475
# )
1476
# self.add_option('is_ignore_errors',kwargs.get('is_ignore_errors',True),
1477
# name = 'Ignore disconnected',
1478
# info = 'Continue if a route could not be build.',
1479
# cml = '--ignore-errors',
1480
# groupnames = ['options','processing'],#
1481
# perm='rw',
1482
# )
1483
# self.add_option( 'use_no_internallink', kwargs.get('use_no_internallink',False),
1484
# groupnames = ['options','processing'],#
1485
# cml = '--internallink',
1486
# name = 'No internal links',
1487
# perm = 'rw',
1488
# info = 'Not to simulate internal link: true or false.',
1489
# )
1490
1491
self.add_option('is_mesojunctioncontrol', kwargs.get('is_mesojunctioncontrol', False),
1492
groupnames=['options', 'processing'],
1493
cml='--mesojunctioncontrol',
1494
name='meso junction control?',
1495
perm='rw',
1496
info='Enable mesoscopic traffic light and priority junciton handling.',
1497
)
1498
1499
self.add_option('is_mesomultiqueue', kwargs.get('is_mesomultiqueue', False),
1500
groupnames=['options', 'processing'],
1501
cml='--mesomultiqueue',
1502
name='meso mesomulti queue?',
1503
perm='rw',
1504
info='Enable multiple queues at edge ends with mesoscopic simulation.',
1505
)
1506
1507
self.add_option('n_meso_recheck', kwargs.get('n_meso_recheck', 0),
1508
groupnames=['options', 'processing'],
1509
cml='--meso-recheck',
1510
name='meso recheck count',
1511
perm='rw',
1512
info='Delay before checking whether a jam is gone. (higher values can lead to a big speed increase)',
1513
)
1514
1515
self.add_option('is_zip_old_iterations', kwargs.get('is_zip_old_iterations', False),
1516
groupnames=['options', 'processing'],
1517
cml='--7',
1518
name='zip old iterations',
1519
perm='rw',
1520
info='zip old iterations using 7zip.',
1521
)
1522
1523
self.add_option('is_no_warnings', kwargs.get('is_no_warnings', False),
1524
groupnames=['options', 'processing'],
1525
cml='--noWarnings',
1526
name='no warnings',
1527
perm='rw',
1528
info='Disables warnings.',
1529
)
1530
1531
self.add_option('is_weight_memory', kwargs.get('is_weight_memory', False),
1532
groupnames=['options', 'processing'],
1533
cml='--weight-memory',
1534
name='Weight memory',
1535
info='Smooth edge weights across iterations.',
1536
)
1537
1538
self.add_option('is_expand_weights', kwargs.get('is_expand_weights', False),
1539
groupnames=['options', 'processing'],
1540
cml='--weights.expand',
1541
name='Expand edge weights',
1542
info='Expand edge weights at time interval boundaries.',
1543
)
1544
1545
self.add_option('g_alpha', kwargs.get('g_alpha', 0.5),
1546
groupnames=['options', 'processing'],
1547
cml='--gA',
1548
name="g_alpha",
1549
perm='rw',
1550
info="Sets Gawron's Alpha",
1551
)
1552
1553
self.add_option('g_beta', kwargs.get('g_beta', 0.9),
1554
groupnames=['options', 'processing'],
1555
cml='--gBeta',
1556
name="g_beta",
1557
perm='rw',
1558
info="Sets Gawron's Beta",
1559
)
1560
1561
self.add_option('routingalgorithm', kwargs.get('routingalgorithm', 'dijkstra'),
1562
groupnames=['options', 'processing'],
1563
choices=['dijkstra', 'astar', 'CH', 'CHWrapper'],
1564
cml='--routing-algorithm',
1565
name='Routing algorithm',
1566
info='Routing algorithm.',
1567
)
1568
1569
self.add_option('is_no_summary', kwargs.get('is_no_summary', False),
1570
groupnames=['options', 'processing'],
1571
cml='--disable-summary',
1572
name="No summary",
1573
perm='rw',
1574
info="No summaries are written by the simulation after each step, which saves time and disk space.",
1575
)
1576
1577
self.add_option('is_no_tripinfo', kwargs.get('is_no_tripinfo', True),
1578
groupnames=['options', 'processing'],
1579
cml='--disable-tripinfos',
1580
name="No Tripinfo",
1581
perm='rw',
1582
info="No tripinfos are written by the simulation after each step, which saves time and disk space.",
1583
)
1584
1585
self.add_option('inc_base', kwargs.get('inc_base', -1),
1586
groupnames=['options', 'processing'],
1587
cml='--inc-base',
1588
name="inc base",
1589
perm='rw',
1590
info="Give the incrementation base. Negative values disable incremental scaling.",
1591
is_enabled=lambda self: self.inc_base >= 0, # default is disabeled
1592
)
1593
1594
self.add_option('inc_value', kwargs.get('inc_value', 1),
1595
groupnames=['options', 'processing'],
1596
cml='--incrementation',
1597
name="inc value",
1598
perm='rw',
1599
info="Give the incrementation",
1600
)
1601
1602
self.add_option('time_inc', kwargs.get('time_inc', 0),
1603
groupnames=['options', 'processing'],
1604
cml='--time-inc',
1605
name="inc time",
1606
perm='rw',
1607
info="Give the time incrementation.",
1608
unit='s',
1609
)
1610
1611
self.add_option('format_routefile', kwargs.get('format_routefile', 'None'),
1612
groupnames=['options', 'processing'],
1613
cml='--vehroute-file',
1614
name="Route file format",
1615
choices=('None', 'routesonly', 'detailed'),
1616
perm='rw',
1617
info="Choose the format of the route file.",
1618
)
1619
1620
self.add_option('is_output_lastroute', kwargs.get('is_output_lastroute', False),
1621
groupnames=['options', 'processing'],
1622
cml='--output-lastRoute',
1623
name="Output last route",
1624
perm='rw',
1625
info="Output the last routes.",
1626
)
1627
1628
self.add_option('is_keep_all_routes', kwargs.get('is_keep_all_routes', False),
1629
groupnames=['options', 'processing'],
1630
cml='--keep-allroutes',
1631
name="Keep all routes",
1632
perm='rw',
1633
info="Save routes even with near zero probability.",
1634
)
1635
1636
self.add_option('is_clean_alt', kwargs.get('is_clean_alt', True),
1637
groupnames=['options', 'processing'],
1638
cml='--clean-alt',
1639
name="Clean alternative routes",
1640
perm='rw',
1641
info=" Whether old rou.alt.xml files shall be removed. This saves lots of disk space.",
1642
)
1643
1644
self.add_option('is_binary_routes', kwargs.get('is_binary_routes', False),
1645
groupnames=['options', 'processing'],
1646
cml='--binary',
1647
name="Save routes in binary format",
1648
perm='rw',
1649
info="Use binary format for intermediate and resulting route files. This saves disk space",
1650
)
1651
1652
self.add_option('is_skip_first_routing', kwargs.get('is_skip_first_routing', False),
1653
groupnames=['options', 'processing'],
1654
cml='--skip-first-routing',
1655
name="Skip first routing",
1656
perm='r',
1657
info="run simulation with demands before first routing. This means, use present routes for the first simulation step.",
1658
)
1659
1660
self.add_option('is_verbose_router', kwargs.get('is_verbose_router', False),
1661
groupnames=['options', 'processing'],
1662
cml='--router-verbose',
1663
name="Verbose router",
1664
perm='rw',
1665
info="Verbose log of routing in dua.log file.",
1666
)
1667
1668
self.is_clean_files = attrsman.add(cm.AttrConf('is_clean_files', True,
1669
groupnames=['input', 'options'],
1670
perm='rw',
1671
name='Clean up files',
1672
info='Cleans up all temporary files and leaves only the route file of the last iteration (i.g. the final result).',
1673
))
1674
1675
# self.add_option( 'districts', kwargs.get('use_districts',''),
1676
# groupnames = ['options','processing'],#
1677
# name = "Use districts",
1678
# perm = 'rw',
1679
# info = "Use districts as sources and targets.",
1680
# )
1681
1682
# self.add_option( 'additional', kwargs.get('filepath_add',''),
1683
# name = "additional files",
1684
# perm = 'rw',
1685
# info = "Path of additional files.",
1686
# )
1687
1688
# standart sumo options
1689
# add basic sumo options
1690
self._init_attributes_basic(scenario, optionprefix='sumo', **kwargs)
1691
1692
# filepath stuff
1693
if ptstopsfilepath is None:
1694
self.ptstopsfilepath = scenario.net.ptstops.get_stopfilepath()
1695
1696
self.is_export_ptstops = attrsman.add(cm.AttrConf('is_export_ptstops', kwargs.get('is_export_ptstops', True),
1697
groupnames=['input', 'options'],
1698
perm='rw',
1699
name='Export PT stops?',
1700
info='Export PT stops before simulation?',
1701
))
1702
else:
1703
self.ptstopsfilepath = ptstopsfilepath
1704
self.is_export_ptstops = False
1705
1706
if routefilepath is None:
1707
self.routefilepath = scenario.demand.get_routefilepath()
1708
self.is_export_routes = attrsman.add(cm.AttrConf('is_export_routes', kwargs.get('is_export_routes', True),
1709
groupnames=['input', 'options'],
1710
perm='rw',
1711
name='Export routes?',
1712
info='Export routes before simulation? ',
1713
))
1714
1715
else:
1716
self.is_export_routes = False
1717
self.routefilepath = routefilepath
1718
1719
if netfilepath is None:
1720
self.netfilepath = scenario.net.get_filepath()
1721
1722
self.is_export_net = attrsman.add(cm.AttrConf('is_export_net', kwargs.get('is_export_net', True),
1723
groupnames=['input', 'options'],
1724
perm='rw',
1725
name='Export net?',
1726
info='Export current network before simulation? Needs to be done only once after network has changed.',
1727
))
1728
else:
1729
self.is_export_net = False
1730
self.netfilepath = netfilepath
1731
1732
# logfilepath not available in duaiterate but as SUMO arg
1733
# self.logfilepath = attrsman.add(cm.AttrConf('logfilepath',kwargs.get('logfilepath',''),
1734
# groupnames = ['options','misc'],
1735
# perm='rw',
1736
# name = 'Log file',
1737
# wildcards = 'Log file (*.txt)|*.txt',
1738
# metatype = 'filepath',
1739
# info = "Writes all messages to Log filepath, implies verbous. If blank, no logfile is created",
1740
# ))
1741
1742
def get_last_step(self):
1743
# very fragile method
1744
#filenames = os.listdir(self.workdir)
1745
# filenames.sort()
1746
#step = int(filenames[-1].split('_')[1])
1747
if 1:
1748
step_max = 0
1749
for filename in os.listdir(self.workdirpath):
1750
try:
1751
step = int(filename)
1752
except:
1753
step = -1
1754
if step > step_max:
1755
step_max = step
1756
1757
if 0: # older sumo version
1758
step_max = 0
1759
for filename in os.listdir(self.workdirpath):
1760
if filename.startswith('dump'):
1761
# print ' ',filename,
1762
step = int(filename.split('_')[1])
1763
if step > step_max:
1764
step_max = step
1765
1766
return min(step_max, self.step_last)
1767
1768
def do(self):
1769
1770
# /usr/local/share/sumo/tools/assign/duaIterate_analysis.py
1771
1772
scenario = self.parent
1773
1774
# exports, if required
1775
if self.is_export_net:
1776
ptstopsfilepath = scenario.net.ptstops.export_sumoxml(self.ptstopsfilepath)
1777
netfilepath = scenario.net.export_netxml(self.netfilepath, is_return_delta=False)
1778
else:
1779
ptstopsfilepath = self.ptstopsfilepath
1780
1781
if self.is_export_routes:
1782
# scenario.demand.export_routes_xml( filepath=self.routefilepath,
1783
# demandobjects = [scenario.demand.trips], is_route = True,
1784
# vtypeattrs_excluded = ['times_boarding','times_loading'],# bug of duaiterate!!
1785
# )
1786
1787
# eport routes of all demand objects
1788
1789
scenario.demand.export_routes_xml(filepath=None, encoding='UTF-8',
1790
is_route=False, # allow True if route export is implemened in virtual population self.is_skip_first_routing,# produce routes only if first dua routing is skipped
1791
vtypeattrs_excluded=['times_boarding',
1792
'times_loading'], # bug of duaiterate!!
1793
is_plain=True, # this will prevent exporting stops and plans
1794
is_exclude_pedestrians=True, # no pedestriann trips, but plans are OK
1795
)
1796
1797
# get command with duaiterate options
1798
cml = self.get_cml()
1799
1800
# do filepath options here
1801
cml += ' --net-file %s' % (ff(self.netfilepath)) +\
1802
' --routes %s' % (ff(self.routefilepath))
1803
1804
additionalpaths = []
1805
if os.path.isfile(self.ptstopsfilepath):
1806
additionalpaths.append(self.ptstopsfilepath)
1807
1808
if len(additionalpaths) > 0:
1809
cml += ' --additional %s' % (filepathlist_to_filepathstring(additionalpaths))
1810
1811
# finally add all sumo command line options
1812
sumooptions = Options()
1813
for attrconfig in self.get_attrsman().get_configs(is_all=True):
1814
if ('sumo' in attrconfig.groupnames) & hasattr(attrconfig, 'cml'):
1815
# print ' sumooption',attrconfig.attrname,attrconfig.groupnames,'is path',attrconfig.get_metatype() in self.pathmetatypes,'has cmlmap',hasattr(attrconfig,'cmlvaluemap')
1816
is_enabled = True
1817
if hasattr(attrconfig, 'is_enabled'):
1818
# print ' is_enabled=',attrconfig.is_enabled(self), attrconfig.get_value()
1819
is_enabled = attrconfig.is_enabled(self)
1820
if is_enabled: # disabeled options are simply not added
1821
if hasattr(attrconfig, 'cmlvaluemap'):
1822
cmlvaluemap = attrconfig.cmlvaluemap
1823
else:
1824
cmlvaluemap = None
1825
is_filepath = attrconfig.get_metatype() in self.pathmetatypes
1826
sumooptions.add_option(attrconfig.attrname, attrconfig.get_value(),
1827
attrconfig.cml, is_filepath=is_filepath, cmlvaluemap=cmlvaluemap)
1828
1829
cml += ' '+sumooptions.get_optionstring()
1830
1831
# if self.logfilepath != '':
1832
# cml += ' --log %s'%(ff(self.logfilepath))
1833
1834
# print '\n Starting command:',cml
1835
if self.run_cml(cml): # call(cml):
1836
step_last = self.get_last_step()
1837
if 0: # old SUMO version
1838
routefilepath_final = '.'.join(self.routefilepath.split(
1839
'.')[:-2]) + "_%03d.rou.xml" % (self.get_last_step(),)
1840
else:
1841
# print ' new since 1.8.0 ?'
1842
# print ' workdirpath',self.workdirpath,'step_last',step_last
1843
resultdir = os.path.join(self.workdirpath, str(step_last))
1844
print ' resultdir', resultdir
1845
filename = self.parent.get_rootfilename() + "_%03d.rou.xml" % (self.get_last_step(),)
1846
print ' filename', filename
1847
#routefilepath_final = os.path.join(self.workdirpath, str(step_last),'.'.join(self.routefilepath.split('.')[:-2]) + "_%03d.rou.xml"%(step_last,))
1848
routefilepath_final = os.path.join(resultdir, filename)
1849
1850
print ' load routes from file ', routefilepath_final
1851
if os.path.isfile(routefilepath_final):
1852
scenario.demand.import_routes_xml(routefilepath_final)
1853
1854
if self.is_clean_files:
1855
if 0: # old version
1856
for filename in os.listdir(self.workdirpath):
1857
if filename.startswith('dump'):
1858
os.remove(os.path.join(self.workdirpath, filename))
1859
1860
elif filename.startswith('dua_dump_'):
1861
os.remove(os.path.join(self.workdirpath, filename))
1862
1863
elif filename.startswith('iteration_'):
1864
os.remove(os.path.join(self.workdirpath, filename))
1865
1866
elif filename.startswith('summary_'):
1867
os.remove(os.path.join(self.workdirpath, filename))
1868
1869
else: # new since 1.8.0 ?'
1870
for step in xrange(self.step_first, step_last):
1871
filepath = os.path.join(self.workdirpath, str(step))
1872
print ' delete dir', filepath
1873
if os.path.isdir(filepath):
1874
# print ' delete now'
1875
try:
1876
shutil.rmtree(filepath)
1877
except OSError as e:
1878
print("Error: %s - %s." % (e.filename, e.strerror))
1879
1880
return True
1881
1882
else:
1883
return False
1884
1885
def import_results(self, results=None):
1886
"""
1887
Imports simulation resuts into results object.
1888
"""
1889
print 'import_results'
1890
1891
# currently nothing is imported in results only routs are
1892
# reimported in trip database
1893
1894
if results is None:
1895
results = self._results
1896
if results is None:
1897
results = self.parent.simulation.results
1898
1899