Repository navigation
Expand file tree
/
Copy pathmmTraCI.py
More file actions
740 lines (635 loc) · 37.5 KB
/
Copy pathmmTraCI.py
File metadata and controls
740 lines (635 loc) · 37.5 KB
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
#!/usr/bin/env python
import csv
import math
import os
import re
import sys
import argparse
import random
from datetime import datetime
from enum import IntEnum
import xml.etree.ElementTree as ET
import simConfig_mm as config
# we need to import some python modules from the $SUMO_HOME/tools directory
if 'SUMO_HOME' in os.environ:
tools = os.path.join(os.environ['SUMO_HOME'], 'tools')
sys.path.append(tools)
else:
sys.exit("please declare environment variable 'SUMO_HOME'")
from sumolib import checkBinary # Checks for the binary in environ vars
import traci
import sumolib
class FloatRange(object):
def __init__(self, start, end):
self.start = start
self.end = end
def __eq__(self, other):
return self.start <= other <= self.end
def __contains__(self, item):
return self.__eq__(item)
def __iter__(self):
yield self
def __repr__(self):
return '[{0},{1}]'.format(self.start, self.end)
def get_options():
"""
Command line options using the argparse library
"""
arg_parser = argparse.ArgumentParser()
micromobility_group = arg_parser.add_argument_group("micromobility options")
loop_group = arg_parser.add_argument_group("loop options")
arg_parser.add_argument("--nogui", action="store_true", default=False, help="run the commandline version of sumo")
arg_parser.add_argument("-v", "--verbosity", dest="verbosity", type=str,
choices=("none", "sparse", "normal", "verbose"),
help="Default = " + str(config.verbosity) + " verbosity of the command line output.")
arg_parser.add_argument("--scenario", dest="scenario", type=str,
choices=config.scenarios.keys(),
help="Default = " + config.scenario + ". Defines the scenario you want to simulate. "
"Choices are: " + str(list(config.scenarios.keys())))
arg_parser.add_argument("--scenario_path", dest="scenario_path", type=str,
help="Alternative to --scenario: defines the path to the .sumoconfigg you want to simulate. "
"Value should be an existing path to a valid .sumoconfigg file.")
arg_parser.add_argument("--time_steps", dest="time_steps", type=int,
help="Default = " + str(
config.seconds_to_simulate) + ". Defines the amount of seconds simulated after which the simulation will terminate. "
"Does not equal real time seconds. A value of 3600 would mean that one hour would get "
"simulated.")
arg_parser.add_argument("--step_length", dest="step_length", type=int,
help="Default = " + str(
config.step_length) + ". Defines the length of each simulated step. "
"Setting this to 1 equals one step per simulated second. 0.25 equals four steps. "
"This setting heavily impacts simulation time and complexity.")
micromobility_group.add_argument("--lateral_resolution", dest="lateral_resolution", type=float,
help="Default = " + str(
config.lateral_resolution) + "Defines the resolution in meters which divides a lane into one or more sublanes."
"For example if three bicycles should be able to ride side by side on a 3m wide lane,"
" the lateral resolution must not be higher than 1.0."
"It is recommended to set the lateral resolution to a value that divides the lane "
"width evenly to avoid artifacts from varying stripe width."
"The smaller this value is, the higher the running time.")
loop_group.add_argument("-l", "--loop", action="store_true", dest="loop",
help="Default = " + str(
config.loop) + ". Run the simulation multiple times in a row, looping through micromobility density.")
loop_group.add_argument("--mm_step_size", dest="mm_step_size", type=float,
choices=FloatRange(0.0, 1.0),
help="default = " + str(
config.mm_step_size) + ". Only useful when the --loop option is set. "
"Defines the step size for the density of micromobility users in the loop."
"Value should be between 0.0 and 1.0 as float. "
"Setting this value to exactly 0.0 disables looping over this variable instead.")
loop_group.add_argument("--mm_start_density", dest="mm_start_density", type=float,
choices=FloatRange(0.0, 1.0),
help="default = " + str(config.mm_start_density) + ". "
"Only useful when combined with the --loop option. Defines the lower bound for the "
"used micromobility density in the loop. "
"Value should be between 0.0 and 1.0 as float.")
loop_group.add_argument("--mm_upper_bound", dest="mm_upper_bound", type=float,
choices=FloatRange(0.0, 1.0),
help="default = " + str(config.mm_start_density) + ". "
"Only useful when combined with the --loop option. Defines the upper bound for the "
"used micromobility density in the loop. "
"Value should be between 0.0 and 1.0 as float.")
args = arg_parser.parse_args()
return args
class Verbosity(IntEnum):
NONE = 0
SPARSE = 1
NORMAL = 2
VERBOSE = 3
# MM
def select_escooter_lane(escooters: set[str], mm_log_writer, mm_log_dict, step):
for escooter in escooters:
current_lane = traci.vehicle.getLaneID(escooter)
current_edge = traci.lane.getEdgeID(current_lane)
lane_count = traci.edge.getLaneNumber(current_edge)
# nothing to do if only one lane exists
if lane_count == 1:
continue
lane_information = {}
bicycle_only_exists = False
for lane_index in range(lane_count):
lane_id = current_edge + '_' + str(lane_index)
allowed_veh_types = traci.lane.getAllowed(lane_id)
# check if bicycles are in allowed vehicles at all
if "scooter" not in allowed_veh_types:
lane_information[lane_index] = {"lane_type": "prohibited",
"occupancy": 1}
continue
# check if lane bicycle only lane
if ("bicycle" in allowed_veh_types) and ("passenger" not in allowed_veh_types) and (
"pedestrian" not in allowed_veh_types):
bicycle_only_exists = True
# change to the bicycle only lane
traci.vehicle.changeLane(escooter, lane_index, config.escooter_lane_change_duration)
try:
entry = [datetime.now(), step, config.scenario, escooter,
round(traci.vehicle.getPosition(escooter)[0]),
round(traci.vehicle.getPosition(escooter)[1]),
"bicycle", round(traci.lane.getLastStepOccupancy(lane_id), 4),
round(traci.lane.getLastStepMeanSpeed(lane_id), 4),
round(traci.lane.getLastStepLength(lane_id), 4),
mm_log_dict[escooter]['routeStartX'],
mm_log_dict[escooter]['routeStartY'],
mm_log_dict[escooter]['routeDestX'],
mm_log_dict[escooter]['routeDestY'],
mm_log_dict[escooter]['originalVehicleId'],
mm_log_dict[escooter]['originalVehicleType'],
config.mm_density,
config.escooter_lane_change_duration, config.escooter_lane_find_frequency,
config.escooter_sidewalk_occupancy_threshold, config.escooter_road_occupancy_threshold,
config.escooter_road_speed_threshold, config.escooter_road_vehicle_length_threshold,
"laneSelection"]
mm_log_writer.writerow(entry)
continue
except:
print("Error: mm_log.csv row not written for escooter lane selection (bicycle).")
# check if lane is a sidewalk
elif ("pedestrian" in allowed_veh_types) and (
"passenger" not in allowed_veh_types) and ("bicycle" not in allowed_veh_types):
gather_lane_information(current_edge, lane_id, lane_index, lane_information, "sidewalk")
else: # neither sidewalk nor bicycle only lane, but allows escooters
gather_lane_information(current_edge, lane_id, lane_index, lane_information, "standard")
if bicycle_only_exists:
# already changed lane to bicycle lane -> nothing to do
continue
else:
best_lane_index = select_preferred_lane(lane_information)
if best_lane_index != -1: # avoid changing to prohibited lanes
try:
traci.vehicle.changeLane(escooter, best_lane_index, config.escooter_lane_change_duration)
print(escooter + " changed lane to index " + str(best_lane_index))
except:
print(escooter + " was unable to changed lane to index " + str(best_lane_index) + ".")
continue
try:
entry = [datetime.now(), step, config.scenario, escooter,
round(traci.vehicle.getPosition(escooter)[0]),
round(traci.vehicle.getPosition(escooter)[1]),
lane_information[best_lane_index]["lane_type"],
round(lane_information[best_lane_index]["occupancy"], 4),
round(lane_information[best_lane_index]["mean_speed"], 4),
round(lane_information[best_lane_index]["mean_length"], 4),
mm_log_dict[escooter]['routeStartX'],
mm_log_dict[escooter]['routeStartY'],
mm_log_dict[escooter]['routeDestX'],
mm_log_dict[escooter]['routeDestY'],
mm_log_dict[escooter]['originalVehicleId'],
mm_log_dict[escooter]['originalVehicleType'],
config.mm_density,
config.escooter_lane_change_duration, config.escooter_lane_find_frequency,
config.escooter_sidewalk_occupancy_threshold, config.escooter_road_occupancy_threshold,
config.escooter_road_speed_threshold, config.escooter_road_vehicle_length_threshold,
"laneSelection"]
mm_log_writer.writerow(entry)
continue
except:
print("Error: mm_log.csv row not written for escooter lane selection.")
# MM
def select_preferred_lane(lane_information: dict) -> int:
highest_lane_rating = 0
best_lane_index = -1
for lane_index in lane_information:
lane_rating = calculate_lane_rating(lane_information[lane_index])
print(str(lane_index) + ": " + str(lane_rating))
if lane_rating > highest_lane_rating:
highest_lane_rating = lane_rating
best_lane_index = lane_index
return best_lane_index
# MM
def calculate_lane_rating(lane_information_entry: dict) -> float:
if lane_information_entry["lane_type"] == "sidewalk":
if lane_information_entry["occupancy"] <= config.escooter_sidewalk_occupancy_threshold:
# low occupancy sidewalk
return 1
else:
# high occupancy sidewalk
return 0.6
elif lane_information_entry["lane_type"] == "standard":
if lane_information_entry["occupancy"] <= config.escooter_road_occupancy_threshold:
# low occupancy road
return 0.9
if lane_information_entry["mean_speed"] <= config.escooter_road_speed_threshold:
if lane_information_entry["mean_length"] <= config.escooter_road_vehicle_length_threshold:
# high occupancy road, slow moving, small vehicles
return 0.8
else:
# high occupancy road, slow moving, large vehicles
return 0.7
else:
if lane_information_entry["mean_length"] <= config.escooter_road_vehicle_length_threshold:
# high occupancy road, fast moving, small vehicles
return 0.5
else:
# high occupancy road, fast moving, large vehicles
return 0.4
else:
# prohibited road or unmarked scenario
return -1.0
# MM
def gather_lane_information(edge_id: str, lane_id: str, lane_index: int, lane_information: dict, lane_type: str):
if lane_type == "sidewalk":
occupancy_rate = len(traci.edge.getLastStepPersonIDs(edge_id)) / traci.lane.getLength(lane_id)
else:
occupancy_rate = traci.lane.getLastStepOccupancy(lane_id)
mean_speed = traci.lane.getLastStepMeanSpeed(lane_id)
mean_length = traci.lane.getLastStepLength(lane_id)
lane_information[lane_index] = {"lane_type": lane_type,
"occupancy": occupancy_rate,
"mean_speed": mean_speed,
"mean_length": mean_length}
# MM
def create_escooters(new_vehicles: set[str], new_pedestrians: set[str], step, mm_log_writer, mm_log_dict) -> set[str]:
new_escooters = set()
for vehicle in new_vehicles: # adjust all newly added vehicles
if (traci.vehicletype.getVehicleClass(traci.vehicle.getTypeID(vehicle)) in config.conversion_vClasses) and (
random.random() <= config.mm_density): # with a chance of <mm_density>
new_id = vehicle + "_escooter"
route = traci.vehicle.getRoute(vehicle) # get route of vehicle. We need 1st and last edge
start_edge = route[0]
if not allowed_on_edge("scooter", start_edge):
start_edge = find_alternative_edge("scooter", start_edge)
if start_edge == "": # no alternative found in config.alternative_edge_radius
if config.verbosity >= Verbosity.SPARSE:
print("Could not find an alternative start edge for " + vehicle + ". Skipping.")
continue
dest_edge = route[-1]
if not allowed_on_edge("scooter", dest_edge):
dest_edge = find_alternative_edge("scooter", dest_edge)
if dest_edge == "": # no alternative found in config.alternative_edge_radius
if config.verbosity >= Verbosity.SPARSE:
print("Could not find an alternative destination edge for " + vehicle + ". Skipping.")
continue
start_coords = traci.junction.getPosition(traci.edge.getFromJunction(start_edge))
dest_coords = traci.junction.getPosition(traci.edge.getFromJunction(dest_edge))
stage = traci.simulation.findRoute(start_edge, dest_edge, "escooter")
if not stage.edges: # no route possible, skip
if config.verbosity >= Verbosity.VERBOSE:
print("Could not find a route from \"" + start_edge + "\" to \"" + dest_edge + "\". Skipping.")
try:
entry = [datetime.now(), step, config.scenario, new_id, "NULL", "NULL", "NULL", "NULL", "NULL",
"NULL",
round(start_coords[0]),
round(start_coords[1]), round(dest_coords[0]), round(dest_coords[1]), vehicle,
traci.vehicle.getTypeID(vehicle),
config.mm_density, config.escooter_lane_change_duration,
config.escooter_lane_find_frequency, config.escooter_sidewalk_occupancy_threshold,
config.escooter_road_occupancy_threshold,
config.escooter_road_speed_threshold, config.escooter_road_vehicle_length_threshold,
"noRoute"]
mm_log_writer.writerow(entry)
continue
except:
print("Error: mm_log.csv row not written at \"Could not find a route\"")
continue
route = stage.edges
route_id = vehicle + "_escooter_route"
traci.route.add(route_id, route)
traci.vehicle.add(new_id, route_id, "escooter")
new_escooters.add(new_id)
mm_log_dict[new_id] = {'routeStartX': round(start_coords[0]),
'routeStartY': round(start_coords[1]),
'routeDestX': round(dest_coords[0]),
'routeDestY': round(dest_coords[1]),
'originalVehicleId': vehicle,
'originalVehicleType': traci.vehicle.getTypeID(vehicle)}
if config.verbosity >= Verbosity.SPARSE:
print("Removed \"" + vehicle + "\" and added \"" + new_id + "\" as a new escooter.\n"
"Traveling from \"" + start_edge + "\" to \"" + dest_edge + "\".")
try:
entry = [datetime.now(), step, config.scenario, new_id, round(traci.vehicle.getPosition(vehicle)[0]),
round(traci.vehicle.getPosition(vehicle)[1]), "NULL", "NULL", "NULL", "NULL",
round(start_coords[0]),
round(start_coords[1]), round(dest_coords[0]), round(dest_coords[1]), vehicle,
traci.vehicle.getTypeID(vehicle), config.mm_density,
config.escooter_lane_change_duration, config.escooter_lane_find_frequency,
config.escooter_sidewalk_occupancy_threshold, config.escooter_road_occupancy_threshold,
config.escooter_road_speed_threshold,
config.escooter_road_vehicle_length_threshold, "new"]
mm_log_writer.writerow(entry)
except:
print("Error: mm_log.csv row not written at \"Creating new escooter\"")
traci.vehicle.remove(vehicle)
return new_escooters
# both
def allowed_on_edge(v_class: str, edge_id: str) -> bool:
lane_count = traci.edge.getLaneNumber(edge_id)
for lane_index in range(lane_count):
lane_id = edge_id + '_' + str(lane_index)
if v_class in traci.lane.getAllowed(lane_id):
return True
return False
# both
def find_alternative_edge(v_class: str, edge_id: str) -> str:
from_junction_coordinates = traci.junction.getPosition(traci.edge.getFromJunction(edge_id))
nearby_edges = net.getNeighboringEdges(from_junction_coordinates[0], from_junction_coordinates[1],
config.alternative_edge_radius, includeJunctions=False)
if len(nearby_edges) > 0:
nearby_edges_sorted = sorted([(dist, edge) for edge, dist in nearby_edges], key=lambda x: x[0])
else:
nearby_edges_sorted = nearby_edges
for nearby_edge in nearby_edges_sorted:
edge_id = nearby_edge[1].getID()
if allowed_on_edge(v_class, edge_id):
return edge_id
return ""
# MM
def log_terminated_escooters(mm_log_writer, step, terminated_escooters: set[str], mm_log_dict):
for terminated_escooter in terminated_escooters:
try:
entry = [datetime.now(), step, config.scenario, terminated_escooter, "NULL", "NULL", "NULL", "NULL", "NULL",
"NULL",
mm_log_dict[terminated_escooter]['routeStartX'], mm_log_dict[terminated_escooter]['routeStartY'],
mm_log_dict[terminated_escooter]['routeDestX'], mm_log_dict[terminated_escooter]['routeDestY'],
mm_log_dict[terminated_escooter]['originalVehicleId'],
mm_log_dict[terminated_escooter]['originalVehicleType'], config.mm_density,
config.escooter_lane_change_duration, config.escooter_lane_find_frequency,
config.escooter_sidewalk_occupancy_threshold, config.escooter_road_occupancy_threshold,
config.escooter_road_speed_threshold, config.escooter_road_vehicle_length_threshold, "terminated"]
mm_log_writer.writerow(entry)
continue
except:
print("Error: mm_log.csv row not written for terminated escooter.")
# MM
def log_close_escooter_ped_encounters(escooters, step, ped_mm_log_writer, mm_log_dict):
for escooter in escooters:
lane_id = traci.vehicle.getLaneID(escooter)
edge_id = traci.lane.getEdgeID(lane_id)
escooter_point = traci.vehicle.getPosition(escooter)
peds = traci.edge.getLastStepPersonIDs(edge_id)
for ped in peds:
if not traci.person.getLaneID(ped) == lane_id: # person not on same lane as escooter
continue
ped_point = traci.person.getPosition(ped)
distance = math.dist(escooter_point, ped_point)
if distance <= config.log_escooter_ped_distance_threshold:
try:
entry = [datetime.now(), step, config.scenario, escooter,
round(escooter_point[0], 4),
round(escooter_point[1], 4),
ped, round(ped_point[0], 4), round(ped_point[1], 4), distance,
round(traci.lane.getLastStepOccupancy(lane_id), 4),
round(traci.lane.getLastStepMeanSpeed(lane_id), 4),
round(traci.lane.getLastStepLength(lane_id), 4),
mm_log_dict[escooter]['routeStartX'],
mm_log_dict[escooter]['routeStartY'],
mm_log_dict[escooter]['routeDestX'],
mm_log_dict[escooter]['routeDestY'],
mm_log_dict[escooter]['originalVehicleId'],
mm_log_dict[escooter]['originalVehicleType'],
config.mm_density,
config.escooter_lane_change_duration, config.escooter_lane_find_frequency,
config.escooter_sidewalk_occupancy_threshold, config.escooter_road_occupancy_threshold,
config.escooter_road_speed_threshold, config.escooter_road_vehicle_length_threshold,
config.log_escooter_ped_distance_threshold]
ped_mm_log_writer.writerow(entry)
continue
except:
print("Error: mm-encounter-log.csv row not written for close escooter and pedestrian encounter.")
# contains TraCI control loop
def run():
parking_area_edges = {}
step = 0
reservation_dict = {}
escooters = set()
last_step_vehicles = set()
last_step_peds = set()
mm_log_dict = {}
mm_log_file_name = "mm-log-{}.csv".format(os.path.basename(results_folder))
mm_log_file_path = os.path.join(results_folder, mm_log_file_name)
mm_log_file = open(mm_log_file_path, 'w', newline='')
mm_log_writer = csv.writer(mm_log_file, delimiter=';')
mm_log_header = ['timestamp', 'step', 'scenario', 'escooterID', 'x', 'y', 'laneType', 'laneOccupancy',
'laneMeanSpeed', 'laneMeanVehicleLength', 'routeStartX', 'routeStartY',
'routeDestX', 'routeDestY', 'originalId', 'originalVType', 'mmDensity',
'lane_change_duration', 'lane_find_frequency', 'sidewalk_occupancy_threshold',
'road_occupancy_threshold', 'road_speed_threshold', 'road_vehicle_length_threshold', 'event']
mm_log_writer.writerow(mm_log_header)
ped_mm_log_file_name = "mm-encounter-log-{}.csv".format(os.path.basename(results_folder))
ped_mm_log_file_path = os.path.join(results_folder, ped_mm_log_file_name)
ped_mm_log_file = open(ped_mm_log_file_path, 'w', newline='')
ped_mm_log_writer = csv.writer(ped_mm_log_file, delimiter=';')
ped_mm_log_header = ['timestamp', 'step', 'scenario', 'escooterID', 'escooter_x', 'escooter_y', 'pedID',
'ped_x', 'ped_y', 'distance', 'laneOccupancy',
'laneMeanSpeed', 'laneMeanVehicleLength', 'routeStartX', 'routeStartY',
'routeDestX', 'routeDestY', 'originalId', 'originalVType', 'mmDensity',
'lane_change_duration', 'lane_find_frequency', 'sidewalk_occupancy_threshold',
'road_occupancy_threshold', 'road_speed_threshold', 'road_vehicle_length_threshold',
'log_escooter_ped_distance_threshold']
ped_mm_log_writer.writerow(ped_mm_log_header)
# start of the main simulation loop
while traci.simulation.getTime() <= config.seconds_to_simulate:
traci.simulationStep()
if config.verbosity >= Verbosity.NORMAL:
print("-----------------------------------------------")
print("Simulation step: " + str(step))
peds = set(traci.person.getIDList())
vehicles = set(traci.vehicle.getIDList())
# determine terminated vehicles and pedestrians
terminated_vehicles = last_step_vehicles - vehicles
terminated_peds = last_step_peds - peds
terminated_escooters = set.intersection(terminated_vehicles, escooters)
log_terminated_escooters(mm_log_writer, step, terminated_escooters, mm_log_dict)
# clean up mm log dict
for terminated_escooter in terminated_escooters:
if terminated_escooter in mm_log_dict:
del mm_log_dict[terminated_escooter]
new_vehicles = vehicles - last_step_vehicles
new_pedestrians = peds - last_step_peds
# remove terminated escooters from list of escooters
escooters = escooters - terminated_vehicles
# every x seconds look for the best lane for each escooter and change to that
if step % config.escooter_lane_find_frequency == 0:
select_escooter_lane(escooters, mm_log_writer, mm_log_dict, step)
if config.escooter_ped_distance_output:
log_close_escooter_ped_encounters(escooters, step, ped_mm_log_writer, mm_log_dict)
# TODO: to support e-scooter added from route.xml (i.e., when using traffic demand generation) --> CHECK
# Loop through each vehicle in new_vehicles
for vehicle in new_vehicles:
# Check if the vehicle type class is 'scooter'
if traci.vehicletype.getVehicleClass(traci.vehicle.getTypeID(vehicle)) == "scooter":
# Add vehicle to the escooter list if it is a scooter
escooters.append(vehicle)
new_escooters = create_escooters(new_vehicles, new_pedestrians, step, mm_log_writer, mm_log_dict)
escooters.update(new_escooters)
last_step_vehicles = set(traci.vehicle.getIDList()) # save current vehicles for the next simulation step
last_step_peds = set(traci.person.getIDList()) # save current vehicles for the next simulation step
step += config.step_length
traci.close()
mm_log_file.close()
ped_mm_log_file.close()
sys.stdout.flush()
# both
def generate_start_config(sumo_binary: str, results_folder) -> list[str]:
"""
Appends all start arguments as defined in simConfig_mm.py and their respective file locations to a list of strings.
This list is then returned and used to start traci with the appropriate start arguments.
:param sumo_binary: string with information about the binary (sumo or sumo-gui)
"""
if options.scenario_path:
start_config = [sumo_binary, "-c", options.scenario_path]
else:
start_config = [sumo_binary, "-c", config.scenarios[config.scenario]]
if config.loop:
start_config.append("--start")
start_config.append("--quit-on-end")
start_config.append("--lateral-resolution")
start_config.append(str(config.lateral_resolution))
start_config.append("--step-length")
start_config.append(str(config.step_length))
start_config.append("--gui-settings-file")
start_config.append(os.path.join("defaultView.xml"))
if config.outputFilesActive:
if config.statsOutput:
start_config.append("--statistic-output")
start_config.append(os.path.join(results_folder, "stats.xml"))
if config.tripinfoOutput:
start_config.append("--tripinfo-output")
start_config.append(os.path.join(results_folder, "tripinfo.xml"))
if config.personsummaryOutput:
start_config.append("--person-summary-output")
start_config.append(os.path.join(results_folder, "personsummary.xml"))
if config.summaryOutput:
start_config.append("--summary")
start_config.append(os.path.join(results_folder, "summary.xml"))
if config.vehroutesOutput:
start_config.append("--vehroute-output")
start_config.append(os.path.join(results_folder, "vehroutes.xml"))
if config.fcdOutput:
start_config.append("--fcd-output")
start_config.append(os.path.join(results_folder, "fcd.xml"))
if config.fullOutput:
start_config.append("--full-output")
start_config.append(os.path.join(results_folder, "full.xml"))
if config.queueOutput:
start_config.append("--queue-output")
start_config.append(os.path.join(results_folder, "queue.xml"))
if config.edgedataOutput:
start_config.append("--edgedata-output")
start_config.append(os.path.join(results_folder, "edgedata.xml"))
if config.lanedataOutput:
start_config.append("--lanedata-output")
start_config.append(os.path.join(results_folder, "lanedata.xml"))
if config.lanechangeOutput:
start_config.append("--lanechange-output")
start_config.append(os.path.join(results_folder, "lanechange.xml"))
if config.amitranOutput:
start_config.append("--amitran-output")
start_config.append(os.path.join(results_folder, "amitran.xml"))
if config.ndumpOutput:
start_config.append("--ndump")
start_config.append(os.path.join(results_folder, "ndump.xml"))
if config.linkOutput:
start_config.append("--link-output")
start_config.append(os.path.join(results_folder, "link.xml"))
if config.personinfoOutput:
start_config.append("--personinfo-output")
start_config.append(os.path.join(results_folder, "personinfo.xml"))
if config.emissionOutput:
start_config.append("--emission-output")
start_config.append(os.path.join(results_folder, "emission.xml"))
return start_config
# both
def generate_base_results_folder(path: str):
hubs_and_name = extract_info(path)
timestamp = datetime.now().strftime("%Y%m%d-%H%M%S")
folder_name = hubs_and_name[0] + "_hubs_" + config.scenario + "_" + str(timestamp)
config.results_folder_path = os.path.join(config.results_folder_path, folder_name)
# creates new folder for results in next simulation
# both
def get_new_results_folder():
data_output_path = os.path.join(config.results_folder_path,
"{}-mm{:.3f}-{}".format(config.scenario,
config.mm_density,
datetime.now().strftime("%Y%m%d-%H%M%S")))
if not os.path.exists(data_output_path):
os.makedirs(data_output_path)
return data_output_path
else:
return ""
# both
def extract_info(filename):
# Remove ".sumocfg" and "scooters_" if present
filename = filename.replace("scooters_", "").replace(".sumocfg", "")
# Extract the number before "_uam_hubs"
uam_hubs_number = re.search(r"(\d+)_uam_hubs", filename)
# Extract remaining part of the filename (after removing "<number>_uam_hubs")
remaining_string = re.sub(r"\d+_uam_hubs", "", filename).strip('_')
return uam_hubs_number.group(1) if uam_hubs_number else "NULL", remaining_string
# both
def process_options():
if options.verbosity is not None:
match options.verbosity:
case "none":
config.verbosity = Verbosity.NONE
case "sparse":
config.verbosity = Verbosity.SPARSE
case "normal":
config.verbosity = Verbosity.NORMAL
case "verbose":
config.verbosity = Verbosity.VERBOSE
if options.time_steps is not None:
config.seconds_to_simulate = options.time_steps
if options.step_length is not None:
config.step_length = options.step_length
if options.loop is not None:
config.loop = options.loop
if options.lateral_resolution is not None:
config.lateral_resolution = options.lateral_resolution
if options.mm_upper_bound is not None:
config.mm_upper_bound = options.mm_upper_bound
if options.mm_step_size is not None:
config.mm_step_size = options.mm_step_size
if options.mm_start_density is not None:
config.mm_density = options.mm_start_density
config.mm_start_density = options.mm_start_density
if options.nogui is not None:
config.no_gui = options.nogui
if options.scenario is not None:
config.scenario = options.scenario
if options.scenario_path is not None:
hubs_and_name = extract_info(os.path.basename(options.scenario_path))
config.scenario = hubs_and_name[1]
# both
if __name__ == '__main__':
options = get_options()
process_options()
if config.scenario not in config.scenarios.keys():
net_path = os.path.join(os.path.dirname(options.scenario_path), ET.parse(options.scenario_path).getroot().find(
".//net-file").get("value").split("/")[0])
scenario_path = options.scenario_path
else:
net_path = os.path.join(os.path.dirname(config.scenarios[config.scenario]),
ET.parse(config.scenarios[config.scenario]).getroot().find(
".//net-file").get("value").split("/")[0])
scenario_path = config.scenarios[config.scenario]
net = sumolib.net.readNet(net_path)
# check binary
if config.no_gui:
sumoBinary = checkBinary('sumo')
config.no_gui = True
else:
sumoBinary = checkBinary('sumo-gui')
config.no_gui = False
generate_base_results_folder(scenario_path)
if not config.loop: # run simulation once
results_folder = get_new_results_folder()
traci_start_config = generate_start_config(sumoBinary, results_folder)
# traci starts sumo as a subprocess and then this script connects and runs
traci.start(traci_start_config)
run()
else: # run multiple simulations in a row, looping through mm density
while config.mm_density <= config.mm_upper_bound:
print("mm_density: " + str(
config.mm_density) + ", mm_upper_bound: " + str(
config.mm_upper_bound) + ", mm_step_size: " + str(
config.mm_step_size))
if config.mm_density > 1.0: # we can't convert over 100% of vehicles to alternatives
break
results_folder = get_new_results_folder()
traci_start_config = generate_start_config(sumoBinary, results_folder)
# traci starts sumo as a subprocess and then this script connects and runs
traci.start(traci_start_config)
run()
if config.mm_step_size == 0.0:
break
config.mm_density += config.mm_step_size