-
Notifications
You must be signed in to change notification settings - Fork 0
/
gamma_crowd_gammaplanner.py
1881 lines (1540 loc) · 73.4 KB
/
gamma_crowd_gammaplanner.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
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
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
import glob
import os
import sys
print('gamma_crowd_slowsim_constantacc')
print(sys.path)
print(os.getcwd())
print(glob.glob(os.path.abspath('%s/../../carla/dist/carla-*%d.%d-%s.egg' % (
os.path.realpath(__file__),
sys.version_info.major,
sys.version_info.minor,
'win-amd64' if os.name == 'nt' else 'linux-x86_64'))))
try:
sys.path.append(glob.glob(os.path.abspath('%s/../../carla/dist/carla-*%d.%d-%s.egg' % (
os.path.realpath(__file__),
sys.version_info.major,
sys.version_info.minor,
'win-amd64' if os.name == 'nt' else 'linux-x86_64')))[0])
except IndexError:
pass
os.environ["PYRO_LOGFILE"] = "pyro.log"
os.environ["PYRO_LOGLEVEL"] = "DEBUG"
from collections import defaultdict
from multiprocessing import Process
from threading import RLock
import Pyro4
import argparse
import carla
import math
import numpy as np
import random
import time
if sys.version_info.major == 2:
from pathlib2 import Path
else:
from pathlib import Path
''' ========== CONSTANTS ========== '''
DATA_PATH = Path(os.path.realpath(__file__)).parent.parent.parent/'Data'
PATH_MIN_POINTS = 20
PATH_INTERVAL = 1.0
# original
ORIGINAL_CONTROL_MAX_RATE = 20
ORIGINAL_GAMMA_MAX_RATE = 40
# original
# SPAWN_DESTROY_MAX_RATE = 15.0
# GAMMA_MAX_RATE = 40 #40
# CONTROL_MAX_RATE = 20 #20
# COLLISION_STATISTICS_MAX_RATE = 5.0
# SPAWN_DESTROY_REPETITIONS = 3
# SUMMIT_TICK_FREQUENCY_RATE = 30
# 3 times slower (CV/CA)
# SPAWN_DESTROY_MAX_RATE = 15.0
# GAMMA_MAX_RATE = 13.333 #40
# CONTROL_MAX_RATE = 6.667 #20
# COLLISION_STATISTICS_MAX_RATE = 5.0
# SPAWN_DESTROY_REPETITIONS = 3
# SUMMIT_TICK_FREQUENCY_RATE = 10
# 6 times slower (CV/CA)
SPAWN_DESTROY_MAX_RATE = 15.0
GAMMA_MAX_RATE = 6.667 #40
CONTROL_MAX_RATE = 3.333 #20
COLLISION_STATISTICS_MAX_RATE = 5.0
SPAWN_DESTROY_REPETITIONS = 3
SUMMIT_TICK_FREQUENCY_RATE = 5.0
# 10 times slower (lanegcn)
# SPAWN_DESTROY_MAX_RATE = 15.0
# GAMMA_MAX_RATE = 4.0 #40
# CONTROL_MAX_RATE = 2.0 #20
# COLLISION_STATISTICS_MAX_RATE = 5.0
# SPAWN_DESTROY_REPETITIONS = 3
# SUMMIT_TICK_FREQUENCY_RATE = 3
# 15 times slower (lanegcn)
# SPAWN_DESTROY_MAX_RATE = 15.0
# GAMMA_MAX_RATE = 2.667 #40
# CONTROL_MAX_RATE = 1.333 #20
# COLLISION_STATISTICS_MAX_RATE = 5.0
# SPAWN_DESTROY_REPETITIONS = 3
# SUMMIT_TICK_FREQUENCY_RATE = 2.0
# 30 times slower (lanegcn)
# SPAWN_DESTROY_MAX_RATE = 15.0
# GAMMA_MAX_RATE = 1.333 #40
# CONTROL_MAX_RATE = 0.667 #20
# COLLISION_STATISTICS_MAX_RATE = 5.0
# SPAWN_DESTROY_REPETITIONS = 3
# SUMMIT_TICK_FREQUENCY_RATE = 1.0
# 40 times slower (same performance ~100-200 node, 8 depths) It suppose to have 60 times slower.
# However when I run moped indepently, it runs faster than cv. thus I change to 40 times slower now.
# SPAWN_DESTROY_MAX_RATE = 15.0
# GAMMA_MAX_RATE = 1.0 #40
# CONTROL_MAX_RATE = 0.5 #20
# COLLISION_STATISTICS_MAX_RATE = 5.0
# SPAWN_DESTROY_REPETITIONS = 3
# SUMMIT_TICK_FREQUENCY_RATE = 0.75
# 60 times slower (same performance ~100-200 node, 8 depths)
# SPAWN_DESTROY_MAX_RATE = 15.0
# GAMMA_MAX_RATE = 0.667 #40
# CONTROL_MAX_RATE = 0.333 #20
# COLLISION_STATISTICS_MAX_RATE = 5.0
# SPAWN_DESTROY_REPETITIONS = 3
# SUMMIT_TICK_FREQUENCY_RATE = 0.5
# 300 times slower (sameHz for all)
# SPAWN_DESTROY_MAX_RATE = 15.0
# GAMMA_MAX_RATE = 0.1333 #40
# CONTROL_MAX_RATE = 0.0667 #20
# COLLISION_STATISTICS_MAX_RATE = 5.0
# SPAWN_DESTROY_REPETITIONS = 3
# SUMMIT_TICK_FREQUENCY_RATE = 0.1
# 600 times slower (sameHz for all)
# SPAWN_DESTROY_MAX_RATE = 15.0
# GAMMA_MAX_RATE = 0.0667 #40
# CONTROL_MAX_RATE = 0.0333 #20
# COLLISION_STATISTICS_MAX_RATE = 5.0
# SPAWN_DESTROY_REPETITIONS = 3
# SUMMIT_TICK_FREQUENCY_RATE = 0.05
# 6000 times slower (same computation for all)
# SPAWN_DESTROY_MAX_RATE = 15.0
# GAMMA_MAX_RATE = 0.00667 #40
# CONTROL_MAX_RATE = 0.00333 #20
# COLLISION_STATISTICS_MAX_RATE = 5.0
# SPAWN_DESTROY_REPETITIONS = 3
# SUMMIT_TICK_FREQUENCY_RATE = 0.005
# Ziegler-Nichols tuning params: K_p, T_u
CAR_SPEED_PID_PROFILES = {
'vehicle.volkswagen.t2': [1.5, 25.0 / 25],
'vehicle.carlamotors.carlacola': [3.0, 25.0 / 25],
'vehicle.jeep.wrangler_rubicon': [1.5, 25.0 / 27],
'vehicle.nissan.patrol': [1.5, 25.0 / 24],
# 'vehicle.tesla.cybertruck': [3.0, 25.0 / 28],
'vehicle.chevrolet.impala': [0.8, 20.0 / 17],
'vehicle.audi.tt': [0.8, 20.0 / 15],
'vehicle.mustang.mustang': [1.0, 20.0 / 15],
'vehicle.citroen.c3': [0.7, 20.0 / 14],
'vehicle.toyota.prius': [1.2, 20.0 / 15],
'vehicle.dodge_charger.police': [1.0, 20.0 /17],
'vehicle.mini.cooperst': [0.8, 20.0 / 14],
'vehicle.audi.a2': [0.8, 20.0 / 18],
'vehicle.nissan.micra': [0.8, 20.0 / 19],
'vehicle.seat.leon': [0.8, 20.0 / 16],
'vehicle.tesla.model3': [1.5, 20.0 / 16],
'vehicle.mercedes-benz.coupe': [0.8, 20.0 / 15],
'vehicle.lincoln.mkz2017': [1.3, 20.0 / 15],
'vehicle.bmw.grandtourer': [1.5, 20.0 / 16],
'default': [1.6, 25.0 / 34]
}
BIKE_SPEED_PID_PROFILES = {
'vehicle.diamondback.century': [1.5, 20.0 / 23.0],
'vehicle.gazelle.omafiets': [1.5, 20.0 / 23.0],
'vehicle.bh.crossbike': [1.5, 20.0 / 23.0],
'default': [0.75, 25.0 / 35.0]
}
CAR_STEER_PID_PROFILES = {
'vehicle.volkswagen.t2': [2.5, 10.0 / 13],
'vehicle.carlamotors.carlacola': [2.5, 10.0 / 15],
'vehicle.jeep.wrangler_rubicon': [2.8, 10.0 / 17],
'vehicle.nissan.patrol': [3.2, 10.0 / 14],
# 'vehicle.tesla.cybertruck': [4.0, 10.0 / 16.0],
'vehicle.audi.etron': [3.0, 10.0 / 15],
'vehicle.chevrolet.impala': [2.5, 10.0 / 19],
'vehicle.audi.tt': [2.3, 10.0 / 20],
'vehicle.mustang.mustang': [2.8, 10.0/ 19],
'vehicle.citroen.c3': [2.0, 10.0 / 17],
'vehicle.toyota.prius': [2.1, 10.0 / 18],
'vehicle.dodge_charger.police': [2.3, 10.0 / 21],
'vehicle.mini.cooperst': [2.0, 10.0 / 16],
'vehicle.audi.a2': [2.0, 10.0 / 18],
'vehicle.nissan.micra': [3.3, 10.0 / 23],
'vehicle.seat.leon': [2.2, 10.0 / 20],
'vehicle.tesla.model3': [2.7, 10.0 / 19],
'vehicle.mercedes-benz.coupe': [2.7, 10.0 / 20],
'vehicle.lincoln.mkz2017': [2.7, 10.0 / 16],
'vehicle.bmw.grandtourer': [2.7, 10.0/ 17],
'default': [2.8, 10.0 / 15]
}
BIKE_STEER_PID_PROFILES = {
'vehicle.diamondback.century': [1.7, 10.0 / 8],
'vehicle.gazelle.omafiets': [1.7, 10.0 / 8],
'vehicle.harley-davidson.low_rider': [1.5, 10.0 / 9],
'vehicle.bh.crossbike': [2.5, 10.0 / 8.0],
'default': [2.0, 10.0 / 9]
}
# Convert (K_p, T_u) -> (K_p, K_i, K_d)
for (k, v) in CAR_SPEED_PID_PROFILES.items():
scale = 1.0
CAR_SPEED_PID_PROFILES[k] = [0.8 * v[0] * scale, 0.0, v[0] * v[1] / 10.0 * scale] # PD
# CAR_SPEED_PID_PROFILES[k] = [v[0] / 5.0, v[0] * 2.0 / 5.0 / v[1], v[0] / 15.0 * v[1]] # no overshoot
for (k, v) in BIKE_SPEED_PID_PROFILES.items():
BIKE_SPEED_PID_PROFILES[k] = [v[0] / 2.0, 0.0, 0.0] # p
for (k, v) in CAR_STEER_PID_PROFILES.items():
scale = 0.9
CAR_STEER_PID_PROFILES[k] = [v[0] / 2.0, 0.0, 0.0]
for (k, v) in BIKE_STEER_PID_PROFILES.items():
scale = 0.9
BIKE_STEER_PID_PROFILES[k] = [0.8 * v[0] * scale, 0.0, v[0] * v[1] / 10.0 * scale ] # PD
def get_car_speed_pid_profile(blueprint_id):
result = CAR_SPEED_PID_PROFILES.get(blueprint_id)
if result is not None:
return result
else:
return CAR_SPEED_PID_PROFILES['default']
def get_bike_speed_pid_profile(blueprint_id):
result = BIKE_SPEED_PID_PROFILES.get(blueprint_id)
if result is not None:
return result
else:
return BIKE_SPEED_PID_PROFILES['default']
def get_car_steer_pid_profile(blueprint_id):
result = CAR_STEER_PID_PROFILES.get(blueprint_id)
if result is not None:
return result
else:
return CAR_STEER_PID_PROFILES['default']
def get_bike_steer_pid_profile(blueprint_id):
result = BIKE_STEER_PID_PROFILES.get(blueprint_id)
if result is not None:
return result
else:
return BIKE_STEER_PID_PROFILES['default']
CAR_STEER_KP = 1.5
BIKE_STEER_KP = 1.0
Pyro4.config.SERIALIZERS_ACCEPTED.add('serpent')
Pyro4.config.SERIALIZER = 'serpent'
Pyro4.util.SerializerBase.register_class_to_dict(
carla.Vector2D,
lambda o: {
'__class__': 'carla.Vector2D',
'x': o.x,
'y': o.y
})
Pyro4.util.SerializerBase.register_dict_to_class(
'carla.Vector2D',
lambda c, o: carla.Vector2D(o['x'], o['y']))
Pyro4.util.SerializerBase.register_class_to_dict(
carla.SumoNetworkRoutePoint,
lambda o: {
'__class__': 'carla.SumoNetworkRoutePoint',
'edge': o.edge,
'lane': o.lane,
'segment': o.segment,
'offset': o.offset
})
def dict_to_sumo_network_route_point(c, o):
r = carla.SumoNetworkRoutePoint()
r.edge = str(o['edge']) # In python2, this is a unicode, so use str() to convert.
r.lane = o['lane']
r.segment = o['segment']
r.offset = o['offset']
return r
Pyro4.util.SerializerBase.register_dict_to_class(
'carla.SumoNetworkRoutePoint', dict_to_sumo_network_route_point)
Pyro4.util.SerializerBase.register_class_to_dict(
carla.SidewalkRoutePoint,
lambda o: {
'__class__': 'carla.SidewalkRoutePoint',
'polygon_id': o.polygon_id,
'segment_id': o.segment_id,
'offset': o.offset
})
def dict_to_sidewalk_route_point(c, o):
r = carla.SidewalkRoutePoint()
r.polygon_id = o['polygon_id']
r.segment_id = o['segment_id']
r.offset = o['offset']
return r
Pyro4.util.SerializerBase.register_dict_to_class(
'carla.SidewalkRoutePoint', dict_to_sidewalk_route_point)
''' ========== MESSAGE PASSING SERVICE ========== '''
@Pyro4.expose
@Pyro4.behavior(instance_mode="single")
class CrowdService():
def __init__(self):
self._simulation_bounds_min = None
self._simulation_bounds_max = None
self._simulation_bounds_lock = RLock()
self._forbidden_bounds_min = None
self._forbidden_bounds_max = None
self._forbidden_bounds_lock = RLock()
self._spawn_car = False
self._new_cars = []
self._new_cars_lock = RLock()
self._spawn_bike = False
self._new_bikes = []
self._new_bikes_lock = RLock()
self._spawn_pedestrian = False
self._new_pedestrians = []
self._new_pedestrians_lock = RLock()
self._control_velocities = []
self._control_velocities_lock = RLock()
self._local_intentions = []
self._local_intentions_lock = RLock()
self._destroy_list = []
self._destroy_list_lock = RLock()
@property
def simulation_bounds(self):
self._simulation_bounds_lock.acquire()
simulation_bounds_min = None if self._simulation_bounds_min is None else \
carla.Vector2D(self._simulation_bounds_min.x, self._simulation_bounds_min.y)
simulation_bounds_max = None if self._simulation_bounds_max is None else \
carla.Vector2D(self._simulation_bounds_max.x, self._simulation_bounds_max.y)
self._simulation_bounds_lock.release()
return (simulation_bounds_min, simulation_bounds_max)
@simulation_bounds.setter
def simulation_bounds(self, bounds):
self._simulation_bounds_lock.acquire()
self._simulation_bounds_min = bounds[0]
self._simulation_bounds_max = bounds[1]
self._simulation_bounds_lock.release()
@property
def forbidden_bounds(self):
self._forbidden_bounds_lock.acquire()
forbidden_bounds_min = None if self._forbidden_bounds_min is None else \
carla.Vector2D(self._forbidden_bounds_min.x, self._forbidden_bounds_min.y)
forbidden_bounds_max = None if self._forbidden_bounds_max is None else \
carla.Vector2D(self._forbidden_bounds_max.x, self._forbidden_bounds_max.y)
self._forbidden_bounds_lock.release()
return (forbidden_bounds_min, forbidden_bounds_max)
@forbidden_bounds.setter
def forbidden_bounds(self, bounds):
self._forbidden_bounds_lock.acquire()
self._forbidden_bounds_min = bounds[0]
self._forbidden_bounds_max = bounds[1]
self._forbidden_bounds_lock.release()
@property
def spawn_car(self):
return self._spawn_car
@spawn_car.setter
def spawn_car(self, value):
self._spawn_car = value
@property
def new_cars(self):
return self._new_cars
@new_cars.setter
def new_cars(self, cars):
self._new_cars = cars
def append_new_cars(self, info):
self._new_cars.append(info)
def acquire_new_cars(self):
self._new_cars_lock.acquire()
def release_new_cars(self):
try:
self._new_cars_lock.release()
except Exception as e:
print(e)
sys.stdout.flush()
@property
def spawn_bike(self):
return self._spawn_bike
@spawn_bike.setter
def spawn_bike(self, value):
self._spawn_bike = value
@property
def new_bikes(self):
return self._new_bikes
@new_bikes.setter
def new_bikes(self, bikes):
self._new_bikes = bikes
def append_new_bikes(self, info):
self._new_bikes.append(info)
def acquire_new_bikes(self):
self._new_bikes_lock.acquire()
def release_new_bikes(self):
try:
self._new_bikes_lock.release()
except Exception as e:
print(e)
sys.stdout.flush()
@property
def spawn_pedestrian(self):
return self._spawn_pedestrian
@spawn_pedestrian.setter
def spawn_pedestrian(self, value):
self._spawn_pedestrian = value
@property
def new_pedestrians(self):
return self._new_pedestrians
@new_pedestrians.setter
def new_pedestrians(self, pedestrians):
self._new_pedestrians = pedestrians
def append_new_pedestrians(self, info):
self._new_pedestrians.append(info)
def acquire_new_pedestrians(self):
self._new_pedestrians_lock.acquire()
def release_new_pedestrians(self):
try:
self._new_pedestrians_lock.release()
except Exception as e:
print(e)
sys.stdout.flush()
@property
def control_velocities(self):
return self._control_velocities
@control_velocities.setter
def control_velocities(self, velocities):
self._control_velocities = velocities
def acquire_control_velocities(self):
self._control_velocities_lock.acquire()
def release_control_velocities(self):
try:
self._control_velocities_lock.release()
except Exception as e:
print(e)
sys.stdout.flush()
@property
def local_intentions(self):
return self._local_intentions
@local_intentions.setter
def local_intentions(self, velocities):
self._local_intentions = velocities
def acquire_local_intentions(self):
self._local_intentions_lock.acquire()
def release_local_intentions(self):
try:
self._local_intentions_lock.release()
except Exception as e:
print(e)
sys.stdout.flush()
@property
def destroy_list(self):
return self._destroy_list
@destroy_list.setter
def destroy_list(self, items):
self._destroy_list = items
def append_destroy_list(self, item):
self._destroy_list.append(item)
def extend_destroy_list(self, items):
self._destroy_list.extend(items)
def acquire_destroy_list(self):
self._destroy_list_lock.acquire()
def release_destroy_list(self):
try:
self._destroy_list_lock.release()
except Exception as e:
print(e)
sys.stdout.flush()
''' ========== UTILITY FUNCTIONS AND CLASSES ========== '''
def get_signed_angle_diff(vector1, vector2):
theta = math.atan2(vector1.y, vector1.x) - math.atan2(vector2.y, vector2.x)
theta = np.rad2deg(theta)
if theta > 180:
theta -= 360
elif theta < -180:
theta += 360
return theta
def get_steer_angle_range(actor):
actor_physics_control = actor.get_physics_control()
return (actor_physics_control.wheels[0].max_steer_angle + actor_physics_control.wheels[1].max_steer_angle) / 2
def get_position(actor):
pos3d = actor.get_location()
return carla.Vector2D(pos3d.x, pos3d.y)
def get_forward_direction(actor):
forward = actor.get_transform().get_forward_vector()
return carla.Vector2D(forward.x, forward.y)
def get_bounding_box(actor):
return actor.bounding_box
def get_position_3d(actor):
return actor.get_location()
def get_aabb(actor):
bbox = actor.bounding_box
loc = carla.Vector2D(bbox.location.x, bbox.location.y) + get_position(actor)
forward_vec = get_forward_direction(actor).make_unit_vector()
sideward_vec = forward_vec.rotate(np.deg2rad(90))
corners = [loc - bbox.extent.x * forward_vec + bbox.extent.y * sideward_vec,
loc + bbox.extent.x * forward_vec + bbox.extent.y * sideward_vec,
loc + bbox.extent.x * forward_vec - bbox.extent.y * sideward_vec,
loc - bbox.extent.x * forward_vec - bbox.extent.y * sideward_vec]
return carla.AABB2D(
carla.Vector2D(
min(v.x for v in corners),
min(v.y for v in corners)),
carla.Vector2D(
max(v.x for v in corners),
max(v.y for v in corners)))
def get_velocity(actor):
v = actor.get_velocity()
return carla.Vector2D(v.x, v.y)
def get_bounding_box_corners(actor):
bbox = actor.bounding_box
loc = carla.Vector2D(bbox.location.x, bbox.location.y) + get_position(actor)
forward_vec = get_forward_direction(actor).make_unit_vector()
sideward_vec = forward_vec.rotate(np.deg2rad(90))
half_y_len = bbox.extent.y
half_x_len = bbox.extent.x
corners = [loc - half_x_len * forward_vec + half_y_len * sideward_vec,
loc + half_x_len * forward_vec + half_y_len * sideward_vec,
loc + half_x_len * forward_vec - half_y_len * sideward_vec,
loc - half_x_len * forward_vec - half_y_len * sideward_vec]
return corners
def get_vehicle_bounding_box_corners(actor):
bbox = actor.bounding_box
loc = carla.Vector2D(bbox.location.x, bbox.location.y) + get_position(actor)
forward_vec = get_forward_direction(actor).make_unit_vector()
sideward_vec = forward_vec.rotate(np.deg2rad(90))
half_y_len = bbox.extent.y + 0.3
half_x_len_forward = bbox.extent.x + 1.0
half_x_len_backward = bbox.extent.x + 0.1
corners = [loc - half_x_len_backward * forward_vec + half_y_len * sideward_vec,
loc + half_x_len_forward * forward_vec + half_y_len * sideward_vec,
loc + half_x_len_forward * forward_vec - half_y_len * sideward_vec,
loc - half_x_len_backward * forward_vec - half_y_len * sideward_vec]
return corners
def get_pedestrian_bounding_box_corners(actor):
bbox = actor.bounding_box
loc = carla.Vector2D(bbox.location.x, bbox.location.y) + get_position(actor)
forward_vec = get_forward_direction(actor).make_unit_vector()
sideward_vec = forward_vec.rotate(np.deg2rad(90))
# Hardcoded values for pedestrians.
half_y_len = 0.25
half_x_len = 0.25
corners = [loc - half_x_len * forward_vec + half_y_len * sideward_vec,
loc + half_x_len * forward_vec + half_y_len * sideward_vec,
loc + half_x_len * forward_vec - half_y_len * sideward_vec,
loc - half_x_len * forward_vec - half_y_len * sideward_vec]
return corners
def get_lane_constraints(sidewalk, position, forward_vec):
left_line_end = position + (1.5 + 2.0 + 0.8) * ((forward_vec.rotate(np.deg2rad(-90))).make_unit_vector())
right_line_end = position + (1.5 + 2.0 + 0.8) * ((forward_vec.rotate(np.deg2rad(90))).make_unit_vector())
left_lane_constrained_by_sidewalk = sidewalk.intersects(carla.Segment2D(position, left_line_end))
right_lane_constrained_by_sidewalk = sidewalk.intersects(carla.Segment2D(position, right_line_end))
return left_lane_constrained_by_sidewalk, right_lane_constrained_by_sidewalk
def is_car(actor):
return isinstance(actor, carla.Vehicle) and int(actor.attributes['number_of_wheels']) > 2
def is_bike(actor):
return isinstance(actor, carla.Vehicle) and int(actor.attributes['number_of_wheels']) == 2
def is_pedestrian(actor):
return isinstance(actor, carla.Walker)
class SumoNetworkAgentPath:
def __init__(self, route_points, min_points, interval):
self.route_points = route_points
self.min_points = min_points
self.interval = interval
@staticmethod
def rand_path(sumo_network, min_points, interval, segment_map, rng=random):
spawn_point = None
route_paths = None
while not spawn_point or len(route_paths) < 1:
spawn_point = segment_map.rand_point()
spawn_point = sumo_network.get_nearest_route_point(spawn_point)
route_paths = sumo_network.get_next_route_paths(spawn_point, min_points - 1, interval)
return SumoNetworkAgentPath(rng.choice(route_paths), min_points, interval)
def resize(self, sumo_network, rng=random):
while len(self.route_points) < self.min_points:
next_points = sumo_network.get_next_route_points(self.route_points[-1], self.interval)
if len(next_points) == 0:
return False
self.route_points.append(rng.choice(next_points))
return True
def get_min_offset(self, sumo_network, position):
min_offset = None
for i in range(int(len(self.route_points) / 2)):
route_point = self.route_points[i]
offset = position - sumo_network.get_route_point_position(route_point)
offset = offset.length()
if min_offset == None or offset < min_offset:
min_offset = offset
return min_offset
def cut(self, sumo_network, position):
cut_index = 0
min_offset = None
min_offset_index = None
for i in range(int(len(self.route_points) / 2)):
route_point = self.route_points[i]
offset = position - sumo_network.get_route_point_position(route_point)
offset = offset.length()
if min_offset == None or offset < min_offset:
min_offset = offset
min_offset_index = i
if offset <= 1.0:
cut_index = i + 1
# Invalid path because too far away.
if min_offset > 1.0:
self.route_points = self.route_points[min_offset_index:]
else:
self.route_points = self.route_points[cut_index:]
def get_position(self, sumo_network, index=0):
return sumo_network.get_route_point_position(self.route_points[index])
def get_yaw(self, sumo_network, index=0):
pos = sumo_network.get_route_point_position(self.route_points[index])
next_pos = sumo_network.get_route_point_position(self.route_points[index + 1])
return np.rad2deg(math.atan2(next_pos.y - pos.y, next_pos.x - pos.x))
class SidewalkAgentPath:
def __init__(self, route_points, route_orientations, min_points, interval):
self.min_points = min_points
self.interval = interval
self.route_points = route_points
self.route_orientations = route_orientations
@staticmethod
def rand_path(sidewalk, min_points, interval, cross_probability, segment_map, rng=None):
if rng is None:
rng = random
spawn_point = sidewalk.get_nearest_route_point(segment_map.rand_point())
path = SidewalkAgentPath([spawn_point], [rng.choice([True, False])], min_points, interval)
path.resize(sidewalk, cross_probability)
return path
def resize(self, sidewalk, cross_probability, rng=None):
if rng is None:
rng = random
while len(self.route_points) < self.min_points:
if rng.random() <= cross_probability:
adjacent_route_point = sidewalk.get_adjacent_route_point(self.route_points[-1], 50.0)
if adjacent_route_point is not None:
self.route_points.append(adjacent_route_point)
self.route_orientations.append(rng.randint(0, 1) == 1)
continue
if self.route_orientations[-1]:
self.route_points.append(
sidewalk.get_next_route_point(self.route_points[-1], self.interval))
self.route_orientations.append(True)
else:
self.route_points.append(
sidewalk.get_previous_route_point(self.route_points[-1], self.interval))
self.route_orientations.append(False)
return True
def cut(self, sidewalk, position):
cut_index = 0
min_offset = None
min_offset_index = None
for i in range(int(len(self.route_points) / 2)):
route_point = self.route_points[i]
offset = position - sidewalk.get_route_point_position(route_point)
offset = offset.length()
if min_offset is None or offset < min_offset:
min_offset = offset
min_offset_index = i
if offset <= 1.0:
cut_index = i + 1
# Invalid path because too far away.
if min_offset > 1.0:
self.route_points = self.route_points[min_offset_index:]
self.route_orientations = self.route_orientations[min_offset_index:]
else:
self.route_points = self.route_points[cut_index:]
self.route_orientations = self.route_orientations[cut_index:]
def get_position(self, sidewalk, index=0):
return sidewalk.get_route_point_position(self.route_points[index])
def get_yaw(self, sidewalk, index=0):
pos = sidewalk.get_route_point_position(self.route_points[index])
next_pos = sidewalk.get_route_point_position(self.route_points[index + 1])
return np.rad2deg(math.atan2(next_pos.y - pos.y, next_pos.x - pos.x))
class Agent(object):
def __init__(self, actor, type_tag, path, preferred_speed, steer_angle_range=0.0, rand=0):
self.actor = actor
self.type_tag = type_tag
self.path = path
self.preferred_speed = preferred_speed
self.stuck_time = None
self.control_velocity = carla.Vector2D(0, 0)
self.steer_angle_range = steer_angle_range
self.behavior_type = self.rand_agent_behavior_type(rand)
def rand_agent_behavior_type(self, prob):
prob_gamma_agent = 1.0
prob_simplified_gamma_agent = 0.0
prob_ttc_agent = 0.0
if prob <= prob_gamma_agent:
return carla.AgentBehaviorType.Gamma
elif prob <= prob_gamma_agent + prob_simplified_gamma_agent:
return carla.AgentBehaviorType.SimplifiedGamma
else:
return -1
class Context(object):
def __init__(self, args):
self.args = args
self.rng = random.Random(args.seed)
with (DATA_PATH/'{}.sim_bounds'.format(args.dataset)).open('r') as f:
self.bounds_min = carla.Vector2D(*[float(v) for v in f.readline().split(',')])
self.bounds_max = carla.Vector2D(*[float(v) for v in f.readline().split(',')])
self.bounds_occupancy = carla.OccupancyMap(self.bounds_min, self.bounds_max)
self.forbidden_bounds_min = None
self.forbidden_bounds_max = None
self.forbidden_bounds_occupancy = None
self.sumo_network = carla.SumoNetwork.load(str(DATA_PATH/'{}.net.xml'.format(args.dataset)))
self.sumo_network_segments = self.sumo_network.create_segment_map()
self.sumo_network_spawn_segments = self.sumo_network_segments.intersection(carla.OccupancyMap(self.bounds_min, self.bounds_max))
self.sumo_network_spawn_segments.seed_rand(self.rng.getrandbits(32))
self.sumo_network_occupancy = carla.OccupancyMap.load(str(DATA_PATH/'{}.network.wkt'.format(args.dataset)))
self.sidewalk = self.sumo_network_occupancy.create_sidewalk(1.5)
self.sidewalk_segments = self.sidewalk.create_segment_map()
self.sidewalk_spawn_segments = self.sidewalk_segments.intersection(carla.OccupancyMap(self.bounds_min, self.bounds_max))
self.sidewalk_spawn_segments.seed_rand(self.rng.getrandbits(32))
self.sidewalk_occupancy = carla.OccupancyMap.load(str(DATA_PATH/'{}.sidewalk.wkt'.format(args.dataset)))
self.client = carla.Client(args.host, args.port)
self.client.set_timeout(10.0)
self.world = self.client.get_world()
self.crowd_service = Pyro4.Proxy('PYRO:crowdservice.warehouse@localhost:{}'.format(args.pyroport))
self.pedestrian_blueprints = self.world.get_blueprint_library().filter('walker.pedestrian.*')
self.vehicle_blueprints = self.world.get_blueprint_library().filter('vehicle.*')
self.car_blueprints = [x for x in self.vehicle_blueprints if int(x.get_attribute('number_of_wheels')) == 4]
self.car_blueprints = [x for x in self.car_blueprints if x.id not in ['vehicle.bmw.isetta', 'vehicle.tesla.cybertruck']] # This dude moves too slow.
self.bike_blueprints = [x for x in self.vehicle_blueprints if int(x.get_attribute('number_of_wheels')) == 2]
class Statistics(object):
def __init__(self, log_file):
self.start_time = None
self.total_num_cars = 0
self.total_num_bikes = 0
self.total_num_pedestrians = 0
self.stuck_num_cars = 0
self.stuck_num_bikes = 0
self.stuck_num_pedestrians = 0
self.avg_speed_cars = 0
self.avg_speed_bikes = 0
self.avg_speed_pedestrians = 0
self.log_file = log_file
def write(self):
self.log_file.write('{} {} {} {} {} {} {} {} {} {}\n'.format(
time.time() - self.start_time,
self.total_num_cars,
self.total_num_bikes,
self.total_num_pedestrians,
self.stuck_num_cars,
self.stuck_num_bikes,
self.stuck_num_pedestrians,
self.avg_speed_cars,
self.avg_speed_bikes,
self.avg_speed_pedestrians))
self.log_file.flush()
os.fsync(self.log_file)
''' ========== MAIN LOGIC FUNCTIONS ========== '''
def do_spawn(c):
c.crowd_service.acquire_new_cars()
spawn_car = c.crowd_service.spawn_car
c.crowd_service.release_new_cars()
c.crowd_service.acquire_new_bikes()
spawn_bike = c.crowd_service.spawn_bike
c.crowd_service.release_new_bikes()
c.crowd_service.acquire_new_pedestrians()
spawn_pedestrian = c.crowd_service.spawn_pedestrian
c.crowd_service.release_new_pedestrians()
if not spawn_car and not spawn_bike and not spawn_pedestrian:
return
# Find car spawn point.
if spawn_car:
aabb_occupancy = carla.OccupancyMap() if c.forbidden_bounds_occupancy is None else c.forbidden_bounds_occupancy
for actor in c.world.get_actors():
if isinstance(actor, carla.Vehicle) or isinstance(actor, carla.Walker):
aabb = get_aabb(actor)
aabb_occupancy = aabb_occupancy.union(carla.OccupancyMap(
carla.Vector2D(aabb.bounds_min.x - c.args.clearance_car, aabb.bounds_min.y - c.args.clearance_car),
carla.Vector2D(aabb.bounds_max.x + c.args.clearance_car, aabb.bounds_max.y + c.args.clearance_car)))
for _ in range(SPAWN_DESTROY_REPETITIONS):
spawn_segments = c.sumo_network_spawn_segments.difference(aabb_occupancy)
if spawn_segments.is_empty:
continue
spawn_segments.seed_rand(c.rng.getrandbits(32))
path = SumoNetworkAgentPath.rand_path(c.sumo_network, PATH_MIN_POINTS, PATH_INTERVAL, spawn_segments, rng=c.rng)
position = path.get_position(c.sumo_network, 0)
trans = carla.Transform()
trans.location.x = position.x
trans.location.y = position.y
trans.location.z = 0.2
trans.rotation.yaw = path.get_yaw(c.sumo_network, 0)
actor = c.world.try_spawn_actor(c.rng.choice(c.car_blueprints), trans)
if actor:
actor.set_collision_enabled(c.args.collision)
try:
c.world.wait_for_tick() # For actor to update pos and bounds, and for collision to apply.
except RuntimeError:
pass
c.crowd_service.acquire_new_cars()
c.crowd_service.append_new_cars((
actor.id,
[p for p in path.route_points], # Convert to python list.
get_steer_angle_range(actor)))
c.crowd_service.release_new_cars()
aabb = get_aabb(actor)
aabb_occupancy = aabb_occupancy.union(carla.OccupancyMap(
carla.Vector2D(aabb.bounds_min.x - c.args.clearance_car, aabb.bounds_min.y - c.args.clearance_car),
carla.Vector2D(aabb.bounds_max.x + c.args.clearance_car, aabb.bounds_max.y + c.args.clearance_car)))
# Find bike spawn point.
if spawn_bike:
aabb_occupancy = carla.OccupancyMap() if c.forbidden_bounds_occupancy is None else c.forbidden_bounds_occupancy
for actor in c.world.get_actors():
if isinstance(actor, carla.Vehicle) or isinstance(actor, carla.Walker):
aabb = get_aabb(actor)
aabb_occupancy = aabb_occupancy.union(carla.OccupancyMap(
carla.Vector2D(aabb.bounds_min.x - c.args.clearance_bike, aabb.bounds_min.y - c.args.clearance_bike),
carla.Vector2D(aabb.bounds_max.x + c.args.clearance_bike, aabb.bounds_max.y + c.args.clearance_bike)))
for _ in range(SPAWN_DESTROY_REPETITIONS):
spawn_segments = c.sumo_network_spawn_segments.difference(aabb_occupancy)
if spawn_segments.is_empty:
continue
spawn_segments.seed_rand(c.rng.getrandbits(32))
path = SumoNetworkAgentPath.rand_path(c.sumo_network, PATH_MIN_POINTS, PATH_INTERVAL, spawn_segments, rng=c.rng)
position = path.get_position(c.sumo_network, 0)
trans = carla.Transform()
trans.location.x = position.x
trans.location.y = position.y
trans.location.z = 0.2
trans.rotation.yaw = path.get_yaw(c.sumo_network, 0)
actor = c.world.try_spawn_actor(c.rng.choice(c.bike_blueprints), trans)
if actor:
actor.set_collision_enabled(c.args.collision)
try:
c.world.wait_for_tick() # For actor to update pos and bounds, and for collision to apply.
except RuntimeError:
pass
c.crowd_service.acquire_new_bikes()
c.crowd_service.append_new_bikes((
actor.id,
[p for p in path.route_points], # Convert to python list.
get_steer_angle_range(actor)))
c.crowd_service.release_new_bikes()
aabb = get_aabb(actor)
aabb_occupancy = aabb_occupancy.union(carla.OccupancyMap(
carla.Vector2D(aabb.bounds_min.x - c.args.clearance_bike, aabb.bounds_min.y - c.args.clearance_bike),
carla.Vector2D(aabb.bounds_max.x + c.args.clearance_bike, aabb.bounds_max.y + c.args.clearance_bike)))
if spawn_pedestrian:
aabb_occupancy = carla.OccupancyMap() if c.forbidden_bounds_occupancy is None else c.forbidden_bounds_occupancy
for actor in c.world.get_actors():
if isinstance(actor, carla.Vehicle) or isinstance(actor, carla.Walker):
aabb = get_aabb(actor)
aabb_occupancy = aabb_occupancy.union(carla.OccupancyMap(
carla.Vector2D(aabb.bounds_min.x - c.args.clearance_pedestrian, aabb.bounds_min.y - c.args.clearance_pedestrian),
carla.Vector2D(aabb.bounds_max.x + c.args.clearance_pedestrian, aabb.bounds_max.y + c.args.clearance_pedestrian)))
for _ in range(SPAWN_DESTROY_REPETITIONS):
spawn_segments = c.sidewalk_spawn_segments.difference(aabb_occupancy)
if spawn_segments.is_empty:
continue
spawn_segments.seed_rand(c.rng.getrandbits(32))
path = SidewalkAgentPath.rand_path(c.sidewalk, PATH_MIN_POINTS, PATH_INTERVAL, c.args.cross_probability, c.sidewalk_spawn_segments, c.rng)
position = path.get_position(c.sidewalk, 0)